trtc-sdk-v5 5.6.3 → 5.7.0-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
@@ -32,7 +32,7 @@ Refer to: ${Fd("en",a)}
32
32
  `)))}else{if(e instanceof Gi)return e;n=new Gi({code:x.UNKNOWN_ERROR,fnName:t,originError:e})}return n}};function Op(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=Gi;var nl={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}}},ol={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}}},Or={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(r,i,e){if(z(r)&&!document.getElementById(r))throw new k({code:x.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:i}})}},al={name:"userId",required:!0,type:"string"},cl={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{values:[et.AUDIO_PROFILE_STANDARD,et.AUDIO_PROFILE_STANDARD_STEREO,et.AUDIO_PROFILE_HIGH,et.AUDIO_PROFILE_HIGH_STEREO]},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function $s(r,i){if(!r)throw new k({code:x.INVALID_OPERATION,extraCode:5101,fnName:i})}function dl(r,i,e){if(!r)throw new k({code:x.INVALID_OPERATION,extraCode:5102,fnName:i,messageParams:{value:e}})}var RC={type:"number",notLessThanZero:!0},Mp={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:x.INVALID_OPERATION,extraCode:5104,fnName:e});if(r.roomId){if(z(r.roomId))throw new k({code:x.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:i}});if(!(/^[1-9]\d*$/.test(String(r.roomId))&&r.roomId<4294967295))throw new k({code:x.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:x.INVALID_PARAMETER,extraCode:5012,fnName:e,messageParams:{key:i}})}else throw new k({code:x.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:Or,mute:{type:["boolean","string"]},publish:{type:"boolean"},option:nl},validate(r){var i;if(!((i=r==null?void 0:r.option)!=null&&i.videoTrack)&&zt())throw new k({code:x.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:P(N({},Or),{required:!1}),publish:{type:"boolean"},mute:{type:["boolean","string"]},option:nl}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:cl},validate(r){var i;if(!((i=r==null?void 0:r.option)!=null&&i.audioTrack)&&zt())throw new k({code:x.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:cl}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:Or,publish:{type:"boolean"},option:ol},validate(r,i,e,t,s){var n;if(!((n=r==null?void 0:r.option)!=null&&n.videoTrack)&&zt())throw new k({code:x.ENV_NOT_SUPPORTED,extraCode:5201});if(!Cs())throw new k({code:x.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:Or,publish:{type:"boolean"},option:ol}},muteRemoteAudio:[al,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[al,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:Or,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){$s(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(r.userId);if(dl(!!t,e,r),t&&(r.streamType==="main"&&!t.muteState.videoAvailable||r.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new k({code:x.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:r}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:P(N({},Or),{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){$s(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(r.userId);if(dl(!!t,e,r),t&&(r.streamType==="main"&&!t.muteState.videoAvailable||r.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new k({code:x.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!=="*"&&g(r.streamType))throw new k({code:x.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(r,i,e){$s(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(!Si)throw new k({code:x.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new k({code:x.INVALID_OPERATION,fnName:e,extraCode:5108});if(r.byteLength>1e3)throw new k({code:x.INVALID_PARAMETER,extraCode:5018,fnName:e});if(r.byteLength===0)throw new k({code:x.INVALID_PARAMETER,extraCode:5017,messageParams:{key:i},fnName:e});if($s(this._room.isJoined,e),!this._room.isMainStreamPublished)throw new k({code:x.INVALID_PARAMETER,fnName:e,extraCode:5109})}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]}}}],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:x.INVALID_PARAMETER,extraCode:5018,fnName:e});if(r.byteLength===0)throw new k({code:x.INVALID_PARAMETER,extraCode:5017,fnName:e,messageParams:{key:i}})}}},validate(r,i,e){if($s(this._room.isJoined,e),this._room.scene==="live"&&this._room.role==="audience")throw new k({code:x.INVALID_OPERATION,extraCode:5107,fnName:e,messageParams:{key:i}})}}},Se={TRTC:Mp};var ve=class extends Error{};function kp(r,i){let e=fr(r);for(let t=0;t<i.length;t++)jt(e[t],i[t]);return e}function Lp(r){this._resolve=Promise.resolve(r)}function xp(r){this._reject=Promise.reject(r)}var Mr=class{constructor(i,e){this.instance=i;this.group=e;this.started=!1;this.ops=[];this.startSame=()=>!0;this.mergeUpdate=kp;let t=Mr.instances.get(i);t?t.set(e,this):Mr.instances.set(i,new Map([[e,this]]))}static get(i,e){let t=Mr.instances.get(i);return t&&t.get(e)||new Mr(i,e)}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},n=a=>{var c,d;throw this.ops.shift(),i===0&&((c=this.currentOp)==null?void 0:c.type)===2&&this.ops.shift().reject(new ve("start failed")),(d=this.currentOp)==null||d.action(),a},o={type:i,action:()=>e(...o.args).then(s,n),args:t,resolve:Lp,reject:xp};try{switch(this.state){case 1:if(i===0)throw new ve("already started");break;case 4:if(i===2)throw new ve("not started");break;default:return this.cacheOp(o)}}catch(a){return Promise.reject(a)}return this.ops.push(o),o.promise=e(...o.args).then(s,n)}cacheOp(i){if(this.ops.length===1)switch(this.state){case 0:case 2:if(i.type===0)throw new ve("already start");break;case 3:switch(i.type){case 2:throw new ve("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new ve("unknown state")}else switch(i.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let t=new ve("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 ve("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new ve("start not allowed after update");case 0:throw new ve("duplicate start");case 3:if(this.startSame(this.currentOp.args,i.args))throw this.ops.pop().reject(new ve("keep start")),new ve("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}},si=Mr;si.instances=new WeakMap;var Ao=new WeakMap,Ro=(r,i)=>{if(i instanceof ve){let{stack:e}=i;i=new k({code:x.OPERATION_ABORT,message:`${r} abort: ${i.message}`,fnName:r}),e&&(i.stack+=e.substr(e.indexOf(`
33
33
  `)))}throw i};function Ri(r,i){return W((e,t)=>function(...s){let n=si.get(this,typeof r=="string"?r:r.call(this,...s));return i&&(n.startSame=i.bind(this)),n.action(0,e.bind(this),s).catch(Ro.bind(null,t))})}function Wi(r,i){let{merge:e,debounce:t}=i||{};return W((s,n)=>function(...o){let a=si.get(this,typeof r=="string"?r:r.call(this,...o));if(e&&(a.mergeUpdate=e.bind(this)),t&&t.isNeedToDebounce.apply(this,o)){let{delay:c,getKey:d}=t;return new Promise((l,h)=>{var R,y;let _=(R=Ao.get(this))==null?void 0:R.get(d(...o));if(_){let{timeoutId:w,resolve:ie}=_;clearTimeout(w),ie()}let f=setTimeout(()=>{if(a.state===3||a.state===4)return l();a.action(2,s.bind(this),o).catch(Ro.bind(null,n)).then(l,h)},c);Ao.has(this)?(y=Ao.get(this))==null||y.set(d(...o),{timeoutId:f,resolve:l}):Ao.set(this,new Map([[d(...o),{timeoutId:f,resolve:l}]]))})}return a.action(2,s.bind(this),o).catch(Ro.bind(null,n))})}function Ci(r){return W((i,e)=>function(...t){return si.get(this,typeof r=="string"?r:r.call(this,...t)).action(3,i.bind(this),t).catch(Ro.bind(null,e))})}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 Hs(r){return r==="sub"?"auxiliary":r==="auxiliary"?"sub":"main"}function Ji(r){return r===et.QOS_PREFERENCE_CLEAR?"detail":r===et.QOS_PREFERENCE_SMOOTH?"motion":""}var Pt=new WeakMap;function wt({settings:r={retries:5,timeout:2e3},onError:i,onRetrying:e,onRetryFailed:t}){return function(s,n,o){let a=Rt({retryFunction:o.value,settings:r,onError({error:c,retry:d,reject:l,retryFuncArgs:h}){var _;i?i.call(this,c,()=>{var f;(f=Pt.get(s))!=null&&f.has(n)?d():l(c)},l,h):(_=Pt.get(s))!=null&&_.has(n)?d():l(c)},onRetrying(c,d){var l;G(e)&&e.call(this,c,d),(l=Pt.get(s))!=null&&l.has(n)&&(Pt.get(s).get(n).stopRetry=d)},onRetryFailed:t});return o.value=function(...c){let d=Pt.get(s);return d?d.set(n,{args:c}):Pt.set(s,new Map([[n,{args:c}]])),a.apply(this,c).finally(()=>{var l;return(l=Pt.get(s))==null?void 0:l.delete(n)})},o}}function Fs({fnName:r,callback:i,validateArgs:e=!0}){return function(t,s,n){let o=n.value;return n.value=function(...a){var c,d;if((c=Pt.get(t))!=null&&c.has(r)){let{stopRetry:l,args:h}=Pt.get(t).get(r),_=!0;if(e){for(let f of h)if(!a.find(R=>R===f)){_=!1;break}}_&&(i&&i.apply(this,a),l&&l(),(d=Pt.get(t))==null||d.delete(r))}return o.apply(this,a)},n}}var Pp=r=>r.startsWith("data:application/octet-stream;base64,"),wp=r=>r.startsWith("file://"),Co=class{constructor(){u(this,"_log");this._log=I.createLogger({id:"fd"})}download(i,e){return p(this,null,function*(){let{type:t="blob"}=e||{};try{let s=L(),n;if(G(fetch)?n=yield this.downloadWithFetch(i,t):n=yield this.downloadWithXHR(i,t),!n||!n.data)throw new Error("data is empty");let o=L()-s;return this._log.info(`downloaded: ${i}, return type: ${t}, cost: ${o}ms`),v.addSuccessEvent({key:522700,cost:L()-s}),n.data}catch(s){throw this._log.error(`failed to download: ${i}, error: ${s}`),v.addFailedEvent({key:522700,error:s}),s}})}downloadWithFetch(i,e){return p(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 n=new XMLHttpRequest;n.open("GET",i,!0),n.responseType=e,n.onload=()=>{n.status===200||n.status===0&&n.response?t({data:n.response}):s(new Error("XHR failed"))},n.onerror=s,n.send(null)})}loadWasm(i,e){return p(this,null,function*(){this._log.info(`loadWasm ${i}, importObject: ${JSON.stringify(e)}`);let t=L(),s=null,n=null;if(G(WebAssembly.instantiateStreaming)&&!Pp(i)&&!wp(i)&&G(fetch))try{let o=fetch(i);s=(yield WebAssembly.instantiateStreaming(o,e)).instance}catch(o){n=o}if(!s)try{let o=yield this.download(i,{type:"arraybuffer"});s=(yield WebAssembly.instantiate(o,e)).instance}catch(o){n=o}if(s){let o=L()-t;return this._log.info(`loadedWasm ${i}, cost: ${o}ms`),v.addSuccessEvent({key:522701,cost:o}),s}throw this._log.error(`failed to loadWasm ${i}, error: ${n}`),v.addFailedEvent({key:522701,error:n}),n})}};b([wt({settings:{timeout:0,retries:3},onRetrying(r){this._log.warn(`download retrying: ${r}`)}})],Co.prototype,"download",1);var hl=new Co;function ml(r,i,e){return{room:r,assetsPath:e,fileDownloader:hl,innerEmitter:T,constants:ha,environment:mr,utils:Le,eventLogger:ee,log:r.getLogger(),errorModule:i,kvStatManager:v,clearStarted(t,s){let n=t.getAlias(),o=si.instances.get(r);if(!!o)if(s){let a=o.get(n+s);if(!a)return;a.started=!1}else o.forEach((a,c)=>{c.startsWith(n)&&(a.started=!1)})}}}var pl=(r,i)=>{let{emit:e}=r;return r.emit=(...t)=>{try{return e.apply(r,t)}catch(s){let n=M({key:O.CATCH_HANDLER_ERROR,data:{name:i,event:t[0]},addDocLink:!1});return I.warn(`${n}
34
34
 
35
- ${s.stack}`),!1}},r};var yo=new WeakMap;function _l(r,i){return W((e,t)=>function(...s){var a,c;let n=(a=yo.get(this))==null?void 0:a.get(i(...s));n&&n>0&&clearTimeout(n);let o=window.setTimeout(()=>{e.apply(this,s)},r);yo.has(this)?(c=yo.get(this))==null||c.set(i(...s),o):yo.set(this,new Map([[i(...s),o]]))})}var fl="5.6.3";function De(...r){return W((i,e)=>function(...t){try{No.call(this,r,t,e,this._name)}catch(s){return Promise.reject(s)}return i.apply(this,t)})}function Qc(...r){return W((i,e)=>function(...t){try{No.call(this,r,t,e,this._name)}catch(s){throw s}return i.apply(this,t)})}function No(r,i,e,t){if(de(r))for(let s=0;s<r.length;s++)bo.call(this,{rule:r[s],value:i[s],key:r[s].name,fnName:e,className:t});else bo.call(this,{rule:r,value:i[0],key:r.name,fnName:e,className:t})}function bo({rule:r,value:i,key:e,fnName:t,className:s}){function n(c){return{code:x.INVALID_PARAMETER,extraCode:c,fnName:t,messageParams:{key:e,rule:r,value:i}}}if(g(i)){if(r.required)throw new k(n(5001));if(g(r.defaultValue)){G(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),G(r.type[d])&&i instanceof r.type[d]&&(c=!0),z(r.type[d])&&he(i)===r.type[d].toLowerCase()&&(c=!0);if(!c)throw new k({code:x.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:r.type.map(d=>gs(d)?Bn(d):z(d)?d:he(d))},value:i}})}else if(!g(r.type)&&he(i)!==r.type)throw new k(n(5002));if(r.allowEmpty===!1){let c=re(i)&&(i===0||Number.isNaN(i)),d=z(i)&&i.trim()==="";if(c||d)throw new k(n(5003))}if(r.notLessThanZero&&re(i)&&i<0)throw new k(n(5006));if(!g(r.min)&&re(i)&&i<r.min)throw new k(n(5007));if(!g(r.max)&&re(i)&&i>r.max)throw new k(n(5008));if(z(r.instanceOf)){if(!i||i._name!==r.instanceOf)throw new k(n(5004))}else if(G(r.instanceOf)&&!(i instanceof r.instanceOf))throw new k(n(5004));if(Array.isArray(r.values)&&!r.values.includes(i))throw new k(n(5005));let{properties:o}=r;$e(o)&&ut(i)&&Object.keys(o).forEach(c=>{bo.call(this,{rule:o[c],value:i&&i[c],key:`${c}`,fnName:t,className:s})});let{arrayItem:a}=r;$e(a)&&de(i)&&i.forEach((c,d)=>{bo.call(this,{rule:a,value:c,key:`${e}[${d}]`,fnName:t,className:s})}),G(r.validate)&&r.validate.call(this,i,e,t,s,this)}function ne(r={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t}=r;return W((s,n)=>function(...o){function a(l,h,_){if(_&&_.includes(l))return"hided";if(e){let f=e(...o);if(o[f.argIndex]===h)return f.value}if(h===o||l in o)return h;try{return h instanceof HTMLElement?`id: ${h.id} type:${he(h)}`:(JSON.stringify(h),h)}catch(f){return`type:${he(h)}`}}let c=this._log||I;o.length>0?c.info(`${n}() ${JSON.stringify(o,(l,h)=>a(l,h,["userSig","privateMapKey"]))}`):c.info(`${n}()`);let d=t?t(...o):Kn[n];try{let l=s.apply(this,o),h=L();return Es(l)?l.then(_=>(c.info(`${n}() success ${i.call(this,...o)}`),v.addSuccessEvent({key:d,cost:L()-h}),_)).catch(_=>{throw _=k.convertFrom.call(this,_,n,o.length===1?o[0]:o),c.error(`${n}() failed ${i.call(this,...o)} ${_} params: ${JSON.stringify(o,a)}`),v.addFailedEvent({key:d,error:_}),_}):(v.addSuccessEvent({key:d}),l)}catch(l){throw l=k.convertFrom.call(this,l,n),c.error(`${n}() failed ${l} params: ${JSON.stringify(o,a)}`),v.addFailedEvent({key:d,error:l}),l}})}var vo=r=>W((i,e)=>function(t,s){return p(this,null,function*(){let n=this._plugins.get(t);if(!n)throw this._log.error(`plugin ${String(t)} is not found`),new k({code:x.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});return No.call(this,n.getValidateRule(r),[s],e,"TRTC"),i.call(this,n,s)})});var Do=0,zc=class{constructor(i,e){u(this,"player");u(this,"publisher");u(this,"mixInput");this.mixInput=new Ar(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||(g(i.volume)||(this.volume=i.volume),g(i.loop)||(this.loop=i.loop),g(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 kr(r,i){if(i&&typeof i!="function")throw new k({code:x.INVALID_PARAMETER,message:`start audioMixer plugin: param ${r} should be a function.`})}var Lr=class{constructor(i){this.core=i;u(this,"log");u(this,"mixedMusicMap",new Map);u(this,"cacheMusicMap",new Map);Do=Do+1,this.log=i.log.createChild({id:`${this.getAlias()}${Do}`}),this.log.info(`[audioMixer] created id=${this.getAlias()}${Do}`),this.core=i}getName(){return Lr.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return Lr.startValidateRule;case"update":return Lr.updateValidateRule;case"stop":return Lr.stopValidateRule}}start(i){return p(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 n=this.cacheMusicMap.get(t);n?i.url?n.reset():(n.mixInput.replaceSource(i.track),n.mixInput.connect()):(n=new zc(i,e.audioManager),this.cacheMusicMap.set(t,n)),n.updateListener(i),n.updateSettings(i),yield n.play(),this.mixedMusicMap.set(t,n),this.log.info(`start mix audio track ${t} success.`),v.addEnum({key:502700,value:3}),this.kvUpload(i)})}update(i){return p(this,null,function*(){let{id:e,operation:t,seekFrom:s,playbackRate:n}=i;this.log.info(`update music source, ${JSON.stringify(i)}`);let o=this.mixedMusicMap.get(e);if(!o){this.log.warn(`update music source failed, music id: ${e} not found.`);return}o.updateSettings(i),o.updateListener(i),g(t)||o.setOperation(t),g(s)||o.seek(s),this.kvUpload(i)})}stop(e){return p(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:n,operation:o,seekFrom:a,onTimeUpdate:c,onDurationChange:d,onEnded:l}=i;e&&v.addCount({key:502711}),t&&v.addCount({key:502703}),s&&v.addCount({key:502704}),n&&v.addCount({key:502705}),o&&v.addCount({key:502706}),a&&v.addCount({key:502707}),typeof c!="function"&&v.addCount({key:502709}),typeof l!="function"&&v.addCount({key:502710}),typeof d!="function"&&v.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()}},yi=Lr;u(yi,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(i,e,t){if(i.url&&i.url!=="*"){let s=i.url.split("?")[0],n=["mp3","ogg","wav","flac"],o=s.split(".").pop(),a=n.indexOf(o)>=0,c=s.startsWith("blob"),d=s.startsWith("data");if(!(a||c||d))throw new k({code:x.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:x.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t});kr("onTimeUpdate",i.onTimeUpdate),kr("onEnded",i.onEnded),kr("onDurationChange",i.onDurationChange)}}),u(yi,"updateValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},loop:{type:"boolean"},volume:{type:"number"},seekFrom:{type:"number"},operation:{type:"string",values:["pause","resume","stop"]}},validate(i,e,t){kr("onTimeUpdate",i.onTimeUpdate),kr("onEnded",i.onEnded),kr("onDurationChange",i.onDurationChange)}}),u(yi,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),u(yi,"Name","AudioMixer");var El=r=>(r=Number(r),r>0&&r<14e8);var Oo=0,xr=class{constructor(i){this.core=i;u(this,"log");u(this,"preloadPromise");u(this,"audioContext",Fe("denoiser"));u(this,"workletNode");Oo=Oo+1,this.log=i.log.createChild({id:`${this.getAlias()}${Oo}`}),this.log.info(`[audioDenoiser] created id=${this.getAlias()}${Oo}`),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,n){if(!i.room.audioManager.hasAudioTrack)throw new k({code:x.INVALID_OPERATION,extraCode:5106,fnName:s})}}}preload(i){return this.preloadPromise||(this.preloadPromise=this.doPreload(i)),this.preloadPromise}doPreload(i){return p(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield wi(this.audioContext,t)}finally{URL.revokeObjectURL(t)}})}getName(){return xr.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(i){switch(i){case"start":return xr.startValidateRule(this.core);case"update":return xr.updateValidateRule;case"stop":return xr.stopValidateRule}}start(i){return p(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:n,status:o,message:a}=yield Bp(P(N({},i),{timestamp:t}));if(!s)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${s}. Message: ${a}`),new k({code:x.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:n,status:o}}),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 p(this,null,function*(){})}stop(){return p(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(){}},ji=xr;u(ji,"updateValidateRule",{type:"object"}),u(ji,"stopValidateRule",{type:"object"}),u(ji,"Name","AIDenoiser");var gl={MAIN:"schedule.cloud-rtc.com",MAIN_OVERSEA:"schedule.rtc.tencentcloud.com"};function Up(r){let i;return El(r)?i=gl.MAIN_OVERSEA:i=gl.MAIN,i}function Bp(s){return p(this,arguments,function*({sdkAppId:r,userId:i,userSig:e,timestamp:t}){let o=`https://${Up(r)}/api/v1/audioAiAuth?sdkAppId=${r}&userId=${i}&userSig=${e}&timestamp=${t}`,a=yield fetch(o),{data:{errCode:c,errMsg:d,sign:l,status:h}}=yield a.json();if(h==="1")return{auth:!0,sign:l,status:h,message:d};let _="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:h,message:d?`${_} Reason: ${d}. ${f}`:`${_}, ${f}`}})}var Tl=Ie(ke(),1);var Kc=class extends Tl.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 p(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){I.info("PressureDetector start 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;(e=this.observer)==null||e.disconnect(),this.observer=null}},$p=new Kc,Yc=$p;var Sl=0,Mo=new Set,Oe=null;Yo(fl);var Hp={RtcError:k,ErrorCode:x,ErrorCodeDictionary:xt},Gs=class extends Al.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${++Sl}`}));u(this,"_plugins",new Map);u(this,"_networkQuality",null);u(this,"_speakerId");this._room=new e(N({logger:this._log,frameWorkType:Gs.frameWorkType},t)),this._log.debug(JSON.stringify(t)),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(yi,t.assetsPath),this._use(ji,t.assetsPath),this._room.on("audio-volume",s=>{!s.find(n=>n.userId==="")&&this._localAudioTrack&&s.push({userId:"",volume:Math.floor(this._localAudioTrack.getAudioLevel()*100)}),this.emit($.AUDIO_VOLUME,{result:s.sort((n,o)=>o.volume-n.volume)})}),this._room.videoManager.on("error",({reason:s,error:n})=>{this._log.error(new k({code:x.OPERATION_FAILED,extraCode:5504,messageParams:{reason:s,error:n}}))}),this._listenEvents(),this._initActiveSpeaker(),pl(this,"trtc")}static create(e){}static _create(e,t){il();let s=new Gs(e,t||{});return Mo.add(s),Yc.start(),s}_listenEvents(){Ve(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=>{Ve(s,s).add("player-state-changed",n=>{let o=P(N({},n),{userId:e.userId});s.kind===m.VIDEO&&(o.streamType=Hs(s.streamType)),this.emit(s.kind===m.AUDIO?$.AUDIO_PLAY_STATE_CHANGED:$.VIDEO_PLAY_STATE_CHANGED,o)}).add("error",n=>{n.getCode()===A.PLAY_NOT_ALLOWED&&this.emit($.AUTOPLAY_FAILED,{userId:s.userId})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(s=>{pe(s)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:t})=>{let{userId:s}=t,n=e.audioAvailable,o=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"}`),n!==a&&(this.emit(a?$.REMOTE_AUDIO_AVAILABLE:$.REMOTE_AUDIO_UNAVAILABLE,{userId:s}),a?this._onAudioAvailable({userId:s}):this._onAudioUnavailable({userId:s,muteState:t})),o!==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("firewall-restriction",()=>{this.emit($.ERROR,new k({code:x.OPERATION_FAILED,extraCode:5501}))}).add("sei-message",e=>{this.emit($.SEI_MESSAGE,P(N({},e),{streamType:Hs(e.streamType)}))}).add("heartbeat-report",e=>{var n,o,a,c,d,l,h;let t={2:"big",3:"small",7:"sub"},s={rtt:e.msg_up_stream_info.msg_network_status.uint32_rtt||((n=e.msg_down_stream_info[0])==null?void 0:n.msg_network_status.uint32_rtt)||((o=this._networkQuality)==null?void 0:o.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:(((h=e.msg_up_stream_info.msg_audio_status)==null?void 0:h.uint32_audio_level)||0)/nt},video:e.msg_up_stream_info.msg_video_status.filter(_=>t[_.uint32_video_stream_type]).map(_=>({bitrate:(_.uint32_video_codec_bitrate||0)/1e3,width:_.uint32_video_width,height:_.uint32_video_height,frameRate:_.uint32_video_enc_fps,videoType:t[_.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(_=>({userId:_.msg_user_info.str_identifier,audio:{bitrate:(_.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(_.msg_audio_status.uint32_audio_level||0)/nt},video:_.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)}),Ve(this,_e).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=>p(this,null,function*(){if(this.emit($.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),Oe&&Oe.deviceId===Zr){let t=(yield $i()).find(s=>s.deviceId===Zr);t&&Oe.groupId!==t.groupId&&(Oe=t,this.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}})).add("audioOutputRemoved",e=>p(this,null,function*(){this.emit($.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield $i())[0];t&&Oe&&(Oe.deviceId===e.deviceId||Oe.deviceId===Zr&&Oe.groupId!==t.groupId)&&(Oe=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 n=new e(ml(this._room,Hp,t));this._plugins.set(e.Name,n)}enterRoom(e){return p(this,null,function*(){var c,d;let{scene:t="rtc",enableAutoPlayDialog:s=!0,autoReceiveAudio:n=!0,autoReceiveVideo:o=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!z(e.proxy)&&e.proxy.turnServer&&((d=(c=this._room).setTurnServer)==null||d.call(c,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=s,this._room.autoReceiveAudio=n,this._room.autoReceiveVideo=o,ue(e.enableHWEncoder)&&(this._room.enableHWEncoder=e.enableHWEncoder);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,Gs.frameWorkType),this._checkTrackToPublish()})}exitRoom(){return p(this,null,function*(){return yield this._exitRoom()})}switchRole(e,t){return p(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(){pe(this),this.removeAllListeners(),this._room.destroy(),Mo.delete(this),Mo.size===0&&Yc.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 p(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:n}=e,o=new Ne(this._room.audioManager),a={},c={muted:!0};n&&(g(n.microphoneId)?g(n.audioTrack)||(a.customSource=n.audioTrack):a.deviceId=n.microphoneId,n&&re(n.captureVolume)&&o.setCaptureVolume(n.captureVolume),g(n.profile)||(z(n.profile)?mn[n.profile]&&o.setProfile(mn[n.profile]):o.setProfile(n.profile)),re(n.earMonitorVolume)&&(c.muted=!(n.earMonitorVolume>0),c.volume=n.earMonitorVolume),g(n.echoCancellation)||(o.profile.echoCancellation=n.echoCancellation),g(n.noiseSuppression)||(o.profile.noiseSuppression=n.noiseSuppression),g(n.autoGainControl)||(o.profile.autoGainControl=n.autoGainControl)),o.on("5",d=>{this.emit($.ERROR,new k({code:x.DEVICE_ERROR,extraCode:5309,messageParams:{error:d}}))}),o.on("2",d=>{this.emit($.DEVICE_CHANGED,{type:"microphone",action:"active",device:d})}),o.on("4",d=>{let l;d.error&&(l=k.convertFrom(d.error)),this.emit($.PUBLISH_STATE_CHANGED,P(N({},d),{error:l}))}),this._listenOutputTrackChanged(o),this._speakerId&&o.setAudioOutput(this._speakerId),yield o.capture(a),g(s)||o.setMute(s),Ve(o,o).add("player-state-changed",d=>{this.emit($.AUDIO_PLAY_STATE_CHANGED,P(N({},d),{userId:""}))}),t&&this._room.isJoined&&this._room.publish(o).catch(()=>{}),this._localAudioTrack=o,this._localAudioConfig=P(N({},e),{publish:t}),yield this._updateAudioPlayOption({playOption:c,track:o})})}updateLocalAudio(e){return p(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:s,option:n}=e,o={};n&&(n.microphoneId?yield this._localAudioTrack.switchDevice(n.microphoneId):g(n.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(n.audioTrack)),g(n.captureVolume)||this._localAudioTrack.setCaptureVolume(n.captureVolume),g(n.earMonitorVolume)||(o.muted=!(n.earMonitorVolume>0),o.volume=n.earMonitorVolume),yield this._localAudioTrack.update3A(n)),this._room.isJoined&&!g(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),g(s)||this._localAudioTrack.setMute(s),yield this._updateAudioPlayOption({playOption:o,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),jt(this._localAudioConfig,e)})}stopLocalAudio(){return p(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),pe(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)})}startLocalVideo(){return p(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:n,option:o}=e,a=new ae(this._room.videoManager),c={},d={};if(o&&(o.cameraId?c.deviceId=o.cameraId:g(o.useFrontCamera)?g(o.videoTrack)||(c.customSource=o.videoTrack):c.facingMode=o.useFrontCamera?m.FACING_MODE_USER:m.FACING_MODE_ENVIRONMENT,g(o.profile)||(z(o.profile)?Qe[o.profile]&&a.setProfile(Qe[o.profile]):a.setProfile(o.profile)),g(o.fillMode)||(d.objectFit=o.fillMode),g(o.mirror)||(d.mirror=o.mirror),g(o.small)||(ys()?z(o.small)?a.small=Qe[o.small]:o.small===!0?a.small=Qe["120p"]:a.small=o.small:this._log.warn("small stream is not supported"))),a.on("5",l=>{this.emit($.ERROR,new k({code:x.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 h;l.error&&(h=k.convertFrom(l.error)),this.emit($.PUBLISH_STATE_CHANGED,P(N({},l),{error:h}))}),this._listenOutputTrackChanged(a),yield a.capture(c),g(n)||(yield a.setMute(n)),a.mediaTrack)if(o!=null&&o.qosPreference){let l=Ji(o.qosPreference);a.mediaTrack.contentHint=l}else o!=null&&o.videoTrack||(a.mediaTrack.contentHint=Ji(et.QOS_PREFERENCE_SMOOTH));Ve(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 p(this,null,function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:s,mute:n,option:o}=e,a={};if(o){if(g(o.profile)||(z(o.profile)?Qe[o.profile]&&this._localVideoTrack.setProfile(Qe[o.profile]):this._localVideoTrack.setProfile(o.profile),(!o.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(o.cameraId))&&g(o.useFrontCamera)&&this._localVideoTrack.applyProfile()),o.cameraId?yield this._localVideoTrack.switchDevice(o.cameraId):g(o.useFrontCamera)?g(o.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(o.videoTrack)):yield this._localVideoTrack.switchDevice(o.useFrontCamera?m.FACING_MODE_USER:m.FACING_MODE_ENVIRONMENT),g(o.fillMode)||(a.objectFit=o.fillMode),g(o.mirror)||(a.mirror=o.mirror),o.qosPreference&&this._localVideoTrack.mediaTrack){let c=Ji(o.qosPreference);this._localVideoTrack.mediaTrack.contentHint=c}if(o.small){let c=!this._localVideoTrack.small;ys()?(o.small===!0?this._localVideoTrack.small=Qe["120p"]:z(o.small)?this._localVideoTrack.small=Qe[o.small]:this._localVideoTrack.small=o.small,this._room.videoManager.update(),c&&this._room.enableSmall(!0)):this._log.warn("small stream is not supported")}else o.small===!1&&this._localVideoTrack.small&&(delete this._localVideoTrack.small,this._room.videoManager.update(),this._room.enableSmall(!1))}this._room.isJoined&&!g(s)&&(s&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._localVideoConfig.publish&&!s&&this._room.unpublish(this._localVideoTrack).catch(()=>{})),g(n)||(yield this._localVideoTrack.setMute(n)),yield this._updateVideoPlayOption({view:t,playOption:a,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),jt(this._localVideoConfig,e)})}stopLocalVideo(){return p(this,null,function*(){!this._localVideoTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),pe(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return p(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:n}=e,o=new Je(this._room.videoManager);o.on("4",h=>{let _;h.error&&(_=k.convertFrom(h.error)),this.emit($.PUBLISH_STATE_CHANGED,P(N({},h),{error:_}))}),this._listenOutputTrackChanged(o);let a=null,c={},d={};n&&(g(n.profile)||(z(n.profile)?pn[n.profile]&&o.setProfile(pn[n.profile]):o.setProfile(n.profile)),n.systemAudio&&(c.systemAudio=!0,c.echoCancellation=n.echoCancellation,c.noiseSuppression=n.noiseSuppression,c.autoGainControl=n.autoGainControl),g(n.fillMode)||(d.objectFit=n.fillMode),n.videoTrack&&(c.videoTrack=n.videoTrack),n.audioTrack&&(c.audioTrack=n.audioTrack),n.captureElement&&(c.captureElement=n.captureElement),n.preferDisplaySurface&&(c.preferDisplaySurface=n.preferDisplaySurface));let l=yield o.capture(c);if(n!=null&&n.qosPreference){let h=Ji(n.qosPreference);o.mediaTrack.contentHint=h}else n!=null&&n.videoTrack||(o.mediaTrack.contentHint=Ji(et.QOS_PREFERENCE_CLEAR));if(o.mediaTrack.addEventListener(m.ENDED,()=>{this._stopScreenShare(),this.emit($.SCREEN_SHARE_STOPPED)}),l.getAudioTracks()[0]&&(a=new kt(this._room.audioManager),a.setInputMediaStreamTrack(l.getAudioTracks()[0]),this._speakerId&&a.setAudioOutput(this._speakerId)),Ve(o,o).add("player-state-changed",h=>{this.emit($.VIDEO_PLAY_STATE_CHANGED,P(N({},h),{userId:"",streamType:"sub"}))}),s&&this._room.isJoined){let h=[o];a&&h.push(a),this._room.publish(...h).catch(()=>{})}this._localScreenTrack=o,this._localScreenAudioTrack=a,this._localScreenConfig=P(N({},e),{view:t,publish:s}),yield this._updateVideoPlayOption({view:t,playOption:d,track:o})})}updateScreenShare(e){return p(this,null,function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:s,option:n}=e,o={};if(n&&(g(n.fillMode)||(o.objectFit=n.fillMode),n.qosPreference)){let a=Ji(n.qosPreference);this._localScreenTrack.mediaTrack.contentHint=a}this._room.isJoined&&!g(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:o,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),jt(this._localScreenConfig,e)})}stopScreenShare(){return p(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return p(this,null,function*(){let{view:t,userId:s,streamType:n,option:o}=e,a=`${s}_${n}`;if(this._remoteVideoConfigMap.has(a)){this._log.warn(`remote video has already started. userId:${s}, streamType:${n}`);return}let c=this._room.remotePublishedUserMap.get(s);if(!c)return;let d={},l=n==="main"?c.remoteVideoTrack:c.remoteAuxiliaryTrack;this._listenOutputTrackChanged(l),o&&(g(o.fillMode)||(d.objectFit=o.fillMode),g(o.mirror)||(d.mirror=o.mirror),n==="main"&&!g(o.small)&&(c.remoteVideoTrack.setMediaType(o.small?8:4),this._room.changeType(o.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}),o&&!g(o.receiveWhenViewVisible)&&this._observeView({remoteTrack:l,view:t,receiveWhenViewVisible:o.receiveWhenViewVisible,viewRoot:o==null?void 0:o.viewRoot})})}updateRemoteVideo(e){return p(this,null,function*(){var w,ie;let{view:t,userId:s,streamType:n,option:o}=e,a=`${s}_${n}`,c=this._remoteVideoConfigMap.get(a);if(!c||!this._room.remotePublishedUserMap.has(s))return;let d={};o&&(g(o.fillMode)||(d.objectFit=o.fillMode),g(o.mirror)||(d.mirror=o.mirror));let l=null,h=this._room.remotePublishedUserMap.get(s);if(n==="main"&&(h==null?void 0:h.muteState.hasVideo)&&(l=h.remoteVideoTrack),n==="sub"&&(h==null?void 0:h.muteState.hasAuxiliary)&&(l=h.remoteAuxiliaryTrack),!l)return;let{config:_}=c;n==="main"&&o&&!g(o.small)&&this._room.changeType(o.small,l.user),yield this._updateVideoPlayOption({view:t,playOption:d,track:l,prevConfig:_}),jt(_,e);let f=g(o==null?void 0:o.receiveWhenViewVisible)?(w=_.option)==null?void 0:w.receiveWhenViewVisible:o.receiveWhenViewVisible,R=g(t)?_.view:t,y=g(o==null?void 0:o.viewRoot)?(ie=_.option)==null?void 0:ie.viewRoot:o.viewRoot;this._observeView({remoteTrack:l,view:R,receiveWhenViewVisible:f,viewRoot:y})})}stopRemoteVideo(e){return p(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,t=!0){return p(this,null,function*(){let s=[],n=this._room.remotePublishedUserMap.get(e.userId);if(n){let{muteState:a,remoteVideoTrack:c,remoteAuxiliaryTrack:d}=n;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 o=this._remoteVideoConfigMap.get(`${e.userId}_${e.streamType}`);o&&o.observer&&o.observer.disconnect(),this._remoteVideoConfigMap.delete(`${e.userId}_${e.streamType}`)})}muteRemoteAudio(e,t){return p(this,null,function*(){if(e==="*")if(t)yield this._stopRemoteAudio({userId:e});else{let s=[...this._room.remotePublishedUserMap.values()];for(let n of s)n.muteState.hasAudio&&!this._remoteAudioConfigMap.has(n.userId)&&(yield this._startRemoteAudio({userId:n.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 n of s)this._updateAudioPlayOption({playOption:{volume:t},track:n.remoteAudioTrack})}else if(e){let s=this._room.remotePublishedUserMap.get(e);s&&this._updateAudioPlayOption({playOption:{volume:t},track:s.remoteAudioTrack})}}startPlugin(e,t){return p(this,null,function*(){return e.start(t)})}updatePlugin(e,t){return p(this,null,function*(){return e.update(t)})}stopPlugin(e,t){return p(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:(super.on(e,t,s),this._eventListened.add(e),this)}off(e,t,s){return e==="*"?(this._eventListened.clear(),this.removeAllListeners()):super.off(e,t,s),this}getAudioTrack(e={userId:"",streamType:"main"}){var n,o;let t,s="main";if(z(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"?((n=this._localScreenAudioTrack)==null?void 0:n.mediaTrack)||null:((o=this._localAudioTrack)==null?void 0:o.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 n=this._room.remotePublishedUserMap.get(t);if(n)return s==="main"?n.remoteVideoTrack.mediaTrack:n.remoteAuxiliaryTrack.mediaTrack}return null}getVideoSnapshot(e={}){let{userId:t,streamType:s="main"}=e;if(t){let n=this._room.remotePublishedUserMap.get(t);if(s==="main"&&(n==null?void 0:n.muteState.hasVideo))return n.remoteVideoTrack.getVideoFrame();if(s==="sub"&&(n==null?void 0:n.muteState.hasAuxiliary))return n.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(n=>n.remoteAudioTrack.setAudioOutput(e))}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return p(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 n=this._room.remotePublishedUserMap.get(t);if(!n)return;let o={};s&&(g(s.volume)||(o.volume=s.volume));let a=n.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:o,track:a})}catch(c){throw this._remoteAudioConfigMap.delete(t),c}this._emitTrackEvent(a)})}_stopRemoteAudio(e,t=!0){return p(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(o){return p(this,arguments,function*({view:e,playOption:t,track:s,prevConfig:n}){if(s.setMirror(t.mirror),g(e)&&n&&n.view&&!ka(t)){let a=Ss(n.view);a.length>0&&(yield s.play(a,t))}if(!g(e)){let a=Ss(e);a.length>0?yield s.play(a,t):s.stop()}})}_updateAudioPlayOption(n){return p(this,arguments,function*({playOption:e={},track:t,prevConfig:s}){if(!t.isPlayCalled)try{yield t.play(null,e)}catch(o){}g(e.muted)||t.setPlayerMute(e.muted),g(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))}_emitTrackEvent(e){let t=e.isRemote?e.userId:"";e.outMediaTrack&&this._mediaTrackMap.get(e.outMediaTrack)!==t&&(this._mediaTrackMap.set(e.outMediaTrack,t),this.emit($.TRACK,{userId:t,streamType:Hs(e.streamType),track:e.outMediaTrack}))}_checkTrackToPublish(){var t,s,n;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),(n=this._localScreenConfig)!=null&&n.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:n}){if(g(t))return;let o=this._remoteVideoConfigMap.get(`${e.userId}_${Hs(e.streamType)}`);if(!o)return;let a=o.observer||void 0;if(t===null||de(t)&&t.length===0||!s){a==null||a.disconnect(),e.isSubscribed||this._room.subscribe(e).catch(()=>{});return}let d=o.visibleViewMap||new Map,l=-1;(!a||a.root!==n)&&(a==null||a.disconnect(),d.clear(),a=new IntersectionObserver(_=>{_.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:n}));let h=new Set(Ss(t));d.forEach((_,f)=>{h.has(f)||(a.unobserve(f),d.delete(f))}),h.forEach(_=>{d.set(_,!0),a.observe(_)}),a.takeRecords().forEach(_=>{d.set(_.target,_.isIntersecting)}),o.visibleViewMap=d,o.observer=a}_exitRoom(){return p(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=>{pe(e.remoteAudioTrack),pe(e.remoteVideoTrack),pe(e.remoteAuxiliaryTrack)})})}_stopScreenShare(){return p(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),pe(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_initActiveSpeaker(){return p(this,null,function*(){if(Oe&&!Rr(Oe))this.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:Oe});else{let e=yield $i();if(e[0]&&!Rr(e[0]))Oe=e[0],this.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]});else{let t=({track:s})=>{s.kind==="audio"&&(!Oe||Rr(Oe))&&(this._initActiveSpeaker(),T.off("102",this._initActiveSpeaker))};T.on("102",t)}}})}_onAudioAvailable({userId:e}){let t=this._remoteAudioMuteMap.has(e)?this._remoteAudioMuteMap.get(e):this._remoteAudioMuteMap.get("*");(t===!1||this._room.autoReceiveAudio&&!t)&&this._doStartRemoteAudio({userId:e}).catch(()=>{})}_onVideoAvailable({userId:e,streamType:t}){if(!this._room.autoReceiveVideo)return;let s=this._room.remotePublishedUserMap.get(e);if(s){let n=t==="main"?s.remoteVideoTrack:s.remoteAuxiliaryTrack;this._room.subscribe(n).then(()=>{this._emitTrackEvent(n)}).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){this._room.sendSEI(e,t||{seiPayloadType:243}),v.addCount({key:5e5,useUV:!0})}sendCustomMessage(e){var t,s;(s=(t=this._room).sendCustomMessage)==null||s.call(t,e),v.addCount({key:500001,useUV:!0})}static setLogLevel(e,t){I.setLogLevel(e),g(t)||(t?I.enableUploadLog():I.disableUploadLog())}static isSupported(){return Wn()}static getCameraList(e=!0){return Ge(e)}static getMicrophoneList(e=!0){return Ue(e)}static getSpeakerList(e=!0){return $i(e)}static setCurrentSpeaker(e){return p(this,null,function*(){(yield $i()).forEach(s=>{s.deviceId===e&&(Mo.forEach(n=>{n.setCurrentSpeaker(e),n.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:s})}),Oe=s)})})}static _addKVStat({type:e,key:t,value:s,base:n,useUV:o,version:a}){switch(a&&(Ui.version=a),e){case"count":Ui.addCount({key:t,useUV:o});break;case"enum":Ui.addEnum({key:t,value:s,useUV:o});break;case"number":Ui.addNumber({key:t,value:s,split:n});break}}},Q=Gs;u(Q,"_loggerManager",I),u(Q,"EVENT",$),u(Q,"ERROR_CODE",x),u(Q,"TYPE",et),u(Q,"frameWorkType",30),b([ne({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),b([De(Se.TRTC.enterRoom),Ri("room",([r],[i])=>(r.roomId||r.strRoomId)===(i.roomId||i.strRoomId)&&r.userId===i.userId&&r.sdkAppId===i.sdkAppId),W(r=>function(i){return this._log.setUserId(i.userId),this._log.setSdkAppId(i.sdkAppId),r.call(this,i)}),ne()],Q.prototype,"enterRoom",1),b([ne()],Q.prototype,"exitRoom",1),b([De(Se.TRTC.switchRole),Wi("room",{merge:(r,i)=>i}),ne()],Q.prototype,"switchRole",1),b([ne()],Q.prototype,"destroy",1),b([De(Se.TRTC.startLocalAudio),Ri("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)}),ne()],Q.prototype,"startLocalAudio",1),b([De(Se.TRTC.updateLocalAudio),Wi("audio",{debounce:{delay:200,getKey:()=>`${Sl}-localAudio`,isNeedToDebounce:r=>{var i;return!g((i=r.option)==null?void 0:i.captureVolume)}}}),ne()],Q.prototype,"updateLocalAudio",1),b([Ci("audio"),ne()],Q.prototype,"stopLocalAudio",1),b([De(Se.TRTC.startLocalVideo),Ri("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)}),ne()],Q.prototype,"startLocalVideo",1),b([De(Se.TRTC.updateLocalVideo),Wi("video"),ne()],Q.prototype,"updateLocalVideo",1),b([Ci("video"),ne()],Q.prototype,"stopLocalVideo",1),b([De(Se.TRTC.startScreenShare),Ri("screen",()=>!0),ne()],Q.prototype,"startScreenShare",1),b([De(Se.TRTC.updateScreenShare),Wi("screen"),ne()],Q.prototype,"updateScreenShare",1),b([ne()],Q.prototype,"stopScreenShare",1),b([De(Se.TRTC.startRemoteVideo),Ri(r=>`v${r.userId}${r.streamType}`,()=>!0),ne({getRemoteId:r=>`${r.userId}_${r.streamType}`})],Q.prototype,"startRemoteVideo",1),b([De(Se.TRTC.updateRemoteVideo),Wi(r=>`v${r.userId}${r.streamType}`),ne({getRemoteId:r=>`${r.userId}_${r.streamType}`})],Q.prototype,"updateRemoteVideo",1),b([De(Se.TRTC.stopRemoteVideo),W(r=>function(i){return p(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)})}),ne({getRemoteId:r=>`${r.userId}_${r.streamType}`})],Q.prototype,"stopRemoteVideo",1),b([Ci(r=>`v${r.userId}${r.streamType}`)],Q.prototype,"_stopRemoteVideo",1),b([De(...Se.TRTC.muteRemoteAudio),ne({getRemoteId:r=>r})],Q.prototype,"muteRemoteAudio",1),b([Qc(...Se.TRTC.setRemoteAudioVolume),_l(200,r=>r),ne({getRemoteId:r=>r})],Q.prototype,"setRemoteAudioVolume",1),b([vo("start"),Ri((r,i)=>r.getAlias()+r.getGroup(i)),ne({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>ec[r.getName()]})],Q.prototype,"startPlugin",1),b([vo("update"),Wi((r,i)=>r.getAlias()+r.getGroup(i)),ne({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>tc[r.getName()]})],Q.prototype,"updatePlugin",1),b([vo("stop"),Ci((r,i)=>r.getAlias()+r.getGroup(i)),ne({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>ic[r.getName()]})],Q.prototype,"stopPlugin",1),b([Qc(...Se.TRTC.enableAudioVolumeEvaluation)],Q.prototype,"enableAudioVolumeEvaluation",1),b([ne()],Q.prototype,"getVideoSnapshot",1),b([ne()],Q.prototype,"setCurrentSpeaker",1),b([Ri(r=>`a${r.userId}`,()=>!0)],Q.prototype,"_startRemoteAudio",1),b([W(r=>function(i){return p(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)})}),Ci(r=>`a${r.userId}`)],Q.prototype,"_stopRemoteAudio",1),b([Ci("room")],Q.prototype,"_exitRoom",1),b([Ci("screen")],Q.prototype,"_stopScreenShare",1),b([De(...Se.TRTC.sendSEIMessage),Xc({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...r)=>r[0].byteLength})],Q.prototype,"sendSEIMessage",1),b([De(Se.TRTC.sendCustomMessage),Xc({timesInSecond:30,maxSizeInSecond:8e3,getSize:r=>r.data.byteLength})],Q.prototype,"sendCustomMessage",1),b([De(Se.TRTC.create)],Q,"_create",1);var Ws=Q;var Zc=class{constructor(){this._set=new Set;T.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 Fp(){return p(this,null,function*(){let r,i;try{let h=yield Ue();r=h&&h.length}catch(h){}try{let h=yield Ge();i=h&&h.length}catch(h){}let e={microphone:r,camera:i},{isH264EncodeSupported:t,isVp8EncodeSupported:s,isH264DecodeSupported:n,isVp8DecodeSupported:o}=this.checkSystemResult.detail,a=Kt.basis(),c={webRTC:a.isWebRTCSupported,getUserMedia:a.isGetUserMediaSupported,webSocket:a.isWebSocketsSupported,screenShare:a.isScreenShareSupported,webAudio:a.isWebAudioSupported,h264Encode:t,h264Decode:n,vp8Encode:s,vp8Decode:o},d={browser:a.browser,os:a.os,trtc:c,devices:e},l={isWebCodecSupported:a.isWebCodecSupported,isMediaSessionSupported:a.isMediaSessionSupported,isWebTransportSupported:a.isWebTransportSupported};ee.uploadEvent({log:`trtcstats-${JSON.stringify(d)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(d)}`),ee.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(l)}`,userId:this.userId})})}function Rl(){return W(r=>{let i=new Zc;return function(e,t,s){return p(this,null,function*(){let n=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 C({code:A.INVALID_OPERATION,message:M({key:O.INVALID_JOIN})});if(this.checkDestroy(),i.isJoined({userId:this.userId,roomId:n,sdkAppId:this.sdkAppId,room:this}))throw new C({code:A.INVALID_OPERATION,message:M({key:O.REPEAT_JOIN,data:this.userId})});i.add({room:this,roomId:n}),this.role=e.role===21?"audience":"anchor",this._log.info(`Join() => joining room: ${n} useStringRoomId: ${this.useStringRoomId} scene: ${this.scene} role: ${this.role}`),T.emit(E.JOIN_START,{room:this,roomId:n,params:e}),this.checkSystemResult=yield Kt.checkSystemRequirementsInternal(),this.checkDestroy();let o=Le.getEnv();o||(o=$t.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(_n.OLD_CLOUD_LADDER)?o=$t.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(_n.WEBRTC)&&(o=$t.WEBRTC))),ee.setConfig({env:o,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:n}),Fp.call(this);let{isH264EncodeSupported:a,isVp8EncodeSupported:c}=this.checkSystemResult.detail;if(!Kt.isWebRTCSupported()||!a&&!c)throw new C({code:A.NOT_SUPPORTED,message:M({key:O.NOT_SUPPORTED_WEBRTC})});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Le.getEnv()&&(yield this.schedule(e,s));let d=yield r.call(this,e,t,s);return this.roomId=n,this._joinedTimestamp=Le.performanceNow(),T.emit(E.JOIN_SUCCESS,{room:this}),ee.uploadEvent({log:`stat-conv-${Number(dt)}-${location.hostname}`,userId:this.userId}),d}catch(d){throw i.delete({room:this,roomId:n}),T.emit(E.JOIN_FAILED,{room:this,error:d}),d}})}})}var Cl=()=>W(r=>function(...i){return p(this,null,function*(){T.emit(E.LEAVE_START,{room:this}),yield r.call(this),T.emit(E.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function yl(){return W(r=>function(...i){let e=r.apply(this,i);return i.forEach(t=>!t.isSubscribed&&t.subscribe(e)),e})}var Nl=Ie(ke(),1);var bl=Symbol("instance"),BN=Symbol("abortCtrl"),ed=Symbol("cacheResult"),qi=class{constructor(i,e,t){this.oldState=i,this.newState=e,this.action=t,this.aborted=!1}abort(i){this.aborted=!0,qs.call(i,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},Js=class extends Error{constructor(i,e,t){super(e),this.state=i,this.message=e,this.cause=t}};function Gp(r){return typeof r=="object"&&r&&"then"in r}var js=new Map;function td(r,i,e={}){return(t,s,n)=>{let o=e.action||s;if(!e.context){let c=js.get(t)||[];js.has(t)||js.set(t,c),c.push({from:r,to:i,action:o})}let a=n.value;n.value=function(...c){let d=this;if(e.context&&(d=te.get(typeof e.context=="function"?e.context.call(this,...c):e.context)),d.state===i)return d[ed];d.state instanceof qi&&d.state.action==e.abortAction&&d.state.abort(d);let l=null;if(Array.isArray(r)?r.length==0?d.state instanceof qi&&d.state.abort(d):(typeof d.state!="string"||!r.includes(d.state))&&(l=new Js(d._state,`${d.name} ${o} to ${i} failed: current state ${d._state} not in from config`)):r!==d.state&&(l=new Js(d._state,`${d.name} ${o} 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 h=d.state,_=new qi(h,i,o);qs.call(d,_);let f=y=>{var w;return d[ed]=y,_.aborted||(qs.call(d,i),(w=e.success)===null||w===void 0||w.call(this,d[ed])),y},R=y=>{let w=y instanceof Error?y.message:String(y);if(qs.call(d,h,y),e.fail)e.fail.call(this,new Js(d._state,`action '${o}' failed :${w}`,y instanceof Error?y:new Error(w)));else{if(e.ignoreError)return y;throw y}};try{let y=a.apply(this,c);return Gp(y)?y.then(f).catch(R):f(y)}catch(y){R(y)}}}}var Wp=(()=>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 qs(r,i){let e=this._state;this._state=r;let t=r.toString();r&&this.emit(t,e),this.emit(te.STATECHANGED,r,e,i),this.updateDevTools({value:r,old:e,err:i instanceof Error?i.message:String(i)})}var te=class extends Nl.default{constructor(i,e,t){super(),this.name=i,this.groupName=e,this._state=te.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[bl];s?this.name=s.name+"-"+s.count++:t[bl]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let i=Object.getPrototypeOf(this),e=js.get(i)||[],t=new Set,s=[],n=[],o=new Set,a=Object.getPrototypeOf(i);js.has(a)&&(a.stateDiagram.forEach(d=>t.add(d)),a.allStates.forEach(d=>o.add(d))),e.forEach(({from:d,to:l,action:h})=>{typeof d=="string"?s.push({from:d,to:l,action:h}):d.length?d.forEach(_=>{s.push({from:_,to:l,action:h})}):n.push({to:l,action:h})}),s.forEach(({from:d,to:l,action:h})=>{o.add(d),o.add(l),o.add(h+"ing"),t.add(`${d} --> ${h}ing : ${h}`),t.add(`${h}ing --> ${l} : ${h} \u{1F7E2}`),t.add(`${h}ing --> ${d} : ${h} \u{1F534}`)}),n.forEach(({to:d,action:l})=>{t.add(`${l}ing --> ${d} : ${l} \u{1F7E2}`),o.forEach(h=>{h!==d&&t.add(`${h} --> ${l}ing : ${l}`)})});let c=[...t];return Object.defineProperties(i,{stateDiagram:{value:c},allStates:{value:o}}),c}static get(i){let e;return typeof i=="string"?(e=te.instances.get(i),e||te.instances.set(i,e=new te(i,void 0,Object.create(te.prototype)))):(e=te.instances2.get(i),e||te.instances2.set(i,e=new te(i.constructor.name,void 0,Object.create(te.prototype)))),e}static getState(i){var e;return(e=te.get(i))===null||e===void 0?void 0:e.state}updateDevTools(i={}){Wp(te.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){qs.call(this,i)}};te.STATECHANGED="stateChanged";te.UPDATEAFSM="updateAFSM";te.INIT="[*]";te.ON="on";te.OFF="off";te.instances=new Map;te.instances2=new WeakMap;var Dl=Ie(ke());var le={SETUP_SUCCESS:"1",SETUP_FAILED:"5",CONNECTION_STATE_CHANGED:"2",CONNECTED:"3",DISCONNECTED:"5",RECONNECT_FAILED:"4"};var _t={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},vl=[_t.UPDATE_REMOTE_MUTE_STAT,_t.UPLINK_NETWORK_STATS,_t.USER_LIST_RES,_t.MUTE_RESULT,_t.SERVER_FIRST_PACKAGE_RECEIVED,_t.RECEIVE_CUSTOM_MSG],V={CLIENT_BANNED:"client-banned",CHANNEL_SETUP_RESULT:"channel-setup-result",CHANNEL_RECONNECT_RESULT:"channel-reconnect-result",JOIN_ROOM_RESULT:"join-room-result",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",UPLINK_NETWORK_STATS:"uplink-network-stats",UPDATE_REMOTE_MUTE_STAT:"update-remote-mute-stat",PUBLISH_RESULT:"publish-result",PUBLISH_STATE_CHANGE_RESULT:"publish-state-change-result",UNPUBLISH_RESULT:"unpublish-result",SUBSCRIBE_RESULT:"subscribe-result",SUBSCRIBE_CHANGE_RESULT:"subscribe-change-result",UNSUBSCRIBE_RESULT:"unsubscribe-result",UPDATE_OFFER_RESULT:"update-offer-result",START_PUBLISH_TENCENT_CDN_RES:"start-publish-tencent-cdn-res",STOP_PUBLISH_TENCENT_CDN_RES:"stop-publish-tencent-cdn-res",START_PUBLISH_GIVEN_CDN_RES:"start-publish-given-cdn-res",STOP_PUBLISH_GIVEN_CDN_RES:"stop-publish-given-cdn-res",START_MIX_TRANSCODE_RES:"start-mix-transcode-res",STOP_MIX_TRANSCODE_RES:"stop-mix-transcode-res",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"},j={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 ko=new Set;function Ol(r){let i=[...ko.values()].find(e=>e.room.userId===r&&!e.room.isJoined);return i||null}var Pr=class extends Dl.default{constructor(e){var s,n;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);this.room=e.room,this.race=g(e.race)?!0:e.race,(((n=(s=this.room.scheduleResult)==null?void 0:s.config)==null?void 0:n.keepAliveClient)||0)-ko.size>0&&this.room.enableSPC&&(this.keepAlive=!0,ko.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.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 p(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=L();let t=[this.connectWS({url:this._urlWithParam,isMain:!0,timeout:e})];this.race&&this._backupUrlWithParam!==this._urlWithParam&&t.push(this.connectWS({url:this._backupUrlWithParam,isMain:!1,timeout:e})),this._socketInUse=yield _s(t),this.unbindAndCloseSocket(this._socketInUse===this._socket?m.BACKUP:m.MAIN),this.emitConnectionStateChanged("CONNECTED")})}connectWS({url:e,timeout:t,isMain:s}){let n=new WebSocket(e);this.bindSocket(n),s?this._socket=n:this._backupSocket=n;let o=-1;return new Promise((a,c)=>{n.onclose=c,n.onerror=c,n.onopen=()=>a(n),t&&(o=setTimeout(()=>{this.unbindAndCloseSocket(s?m.MAIN:m.BACKUP),c(new C({code:A.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))},t))}).finally(()=>{n.onclose=null,n.onerror=null,n.onopen=null,clearTimeout(o)})}bindSocket(e){e.addEventListener("close",this.onclose),e.addEventListener("error",this.onerror),e.addEventListener("message",this.onmessage)}unbindSocket(e){e.removeEventListener("close",this.onclose),e.removeEventListener("error",this.onerror),e.removeEventListener("message",this.onmessage)}unbindAndCloseSocket(e){if(e===m.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(t){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(t){}this._backupSocket=null}}onclose(e){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?m.MAIN:m.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(m.MAIN),this.unbindAndCloseSocket(m.BACKUP),this._socketInUse=null,this.reconnect())}onmessage(e){if(!this.isConnected)return;this._lastMessageTime=Date.now(),this.bytesReceived+=$n(e.data);let t=JSON.parse(e.data),{cmd:s,data:n}=t,o=Object.values(_t),c=Object.keys(_t)[o.indexOf(s)],d=V[c];switch(vl.includes(s)||(this._log.debug(`received ${s} msg: ${e.data}`),d&&this._log.info(`Received event: [ ${d} ]`)),s){case _t.CHANNEL_SETUP_RESULT:{if(t.code===0)this._signalInfo.clientIp=n.clientIp,this._signalInfo.signalIp=n.signalInnerIp,n.svrTime&&kd(n.svrTime),this._log.info("ChannelSetup Success"),v.addSuccessEvent({key:521701,cost:L()-this._connnectStartTime}),this._connnectStartTime=-1,this.emit(le.SETUP_SUCCESS,{signalInfo:this._signalInfo});else{let l=new C({code:A.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:M({key:O.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error(`${t.code}, ${t.message}`),this.close(),v.addFailedEvent({key:521701,error:l}),this.emit(le.SETUP_FAILED,l)}break}case _t.JOIN_ROOM_RESULT:{t.code===0&&(this._signalInfo.relayIp=n.relayOuterIp,this._signalInfo.relayInnerIp=n.relayInnerIp,this._signalInfo.relayPort=n.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(d,{data:t});break}}reGetSignalChannelUrl(){return p(this,null,function*(){try{yt(!0),yield this.room.schedule(this.room.roomId);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(e){}})}reconnect(){return p(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:n,relayPort:o}=this._signalInfo,{data:a}=yield this.sendWaitForResponse({command:j.RECONNECT_WS,data:{roomId:e,useStringRoomId:t,relayInnerIp:n,relayOuterIp:s,relayPort:o},responseCommand:V.CHANNEL_RECONNECT_RESULT});a.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),v.addSuccessEvent({key:521702,cost:L()-this._connnectStartTime}),this._connnectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(v.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},n=JSON.stringify(s);return this._socketInUse.send(n),this.bytesSent+=$n(n),s.seq}}sendWaitForResponse({command:e,data:t,timeout:s=5e3,responseCommand:n,commandDesc:o,enableLog:a=!0}){return new Promise((c,d)=>{let l=setTimeout(()=>{this.off(n,h);let f=new C({code:A.API_CALL_TIMEOUT,message:M({key:O.API_CALL_TIMEOUT,data:{commandDesc:o,command:e}})});a&&this._log.warn(f),d(f)},s),h=f=>{f.data.seq===_&&(clearTimeout(l),this.off(n,h),c(f))};this.on(n,h);let _=this.send(e,t)})}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:s,retries:n=0,retryTimeout:o=0}=e;return Rt({retryFunction:this.sendWaitForResponse,onError:({retry:a})=>{this.isOnline?a():(this._log.warn(`retry ${s} when connected`),this.once(le.CONNECTED,a))},onRetrying:a=>{this._log.warn(`${t||s} timeout observed, retrying [${a}/${n}]`)},settings:{retries:n,timeout:o},context:this})(e)}getCurrentState(){return this._currentState}getSignalInfo(){return this._signalInfo}stopReconnection(){this._isReconnecting=!1,this._stopConnectRetry&&this._stopConnectRetry()}close(){this._log.info("closed"),ko.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(m.MAIN),this.unbindAndCloseSocket(m.BACKUP),this.emitConnectionStateChanged("DISCONNECTED")}destroy(){this.close(),this.destroyed=!0}stopKeepAliveIn(e=3600){if(this.keepAlive){this._log.info(`stopKeepAlive in ${e}s`);let t=setTimeout(()=>{this.keepAlive=!1,this._log.info(`close due to not used ${e}s`),this.close()},e*1e3),s=n=>{n instanceof qi&&n.action==="join"&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(t),this.room.off(te.STATECHANGED,s))};this.room.on(te.STATECHANGED,s)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info(`${this._currentState} -> ${e}`),this.emit(le.CONNECTION_STATE_CHANGED,{prevState:this._currentState,state:e}),this._currentState=e,e==="CONNECTED"?this.emit(le.CONNECTED):e==="DISCONNECTED"&&this.emit(le.DISCONNECTED))}};b([wt({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())}})],Pr.prototype,"connect",1);var Ml=Ie(ke());var id=0,rd=!1,xo=new Set,jp=r=>id>2&&!rd&&xo.size===0&&r,sd=!1,je=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 Ml.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,"_enableSEI");u(this,"_sei");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,this._enableSEI=i.enableSEI}beforeConnect(){this._prevTime<0&&(this._prevTime=L())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,v.addSuccessEvent({key:521705,cost:Math.min(L()-this._prevTime,30*1e3)})):this._isReconnecting&&v.addSuccessEvent({key:521706,cost:L()-this._prevTime}),this._prevTime=-1}catch(i){throw this._isFirstConnection?(this._isFirstConnection=!1,v.addFailedEvent({key:521705,error:i})):this._isReconnecting&&this._reconnectionCount>=3&&v.addFailedEvent({key:521706,error:i}),i}}initialize(){let i={encodedInsertableStreams:this._enableSEI&&Si,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(),this._sei&&(this._sei.destroy(),this._sei=null),xo.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 C({code:A.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return rt;let i=null;if(this._isUplink){if(!Ti()||this._peerConnection.getSenders().length===0)return rt;i=this._peerConnection.getSenders()[0].transport}else{if(!Pi()||this._peerConnection.getReceivers().length===0)return rt;i=this._peerConnection.getReceivers()[0].transport}return i?i.state:rt}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}`,n=new C({message:s,code:A.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",n)}(i.target.connectionState===se.CONNECTED||i.target.connectionState===se.COMPLETED)&&(this.logSelectedCandidate(),ee.logSuccessEvent({userId:this._room.userId,eventType:xe.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(i){return i===this._currentState?!1:(i==="CONNECTED"?(id=0,rd=!1,sd=!0,xo.add(this)):xo.delete(this),T.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 p(this,null,function*(){if(!this._peerConnection)return;let i=yield this._peerConnection.getStats();for(let[,e]of i)if(gi(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(o),n(),i())},s=({room:a})=>{a===this._room&&(clearTimeout(o),n(),e(new C({code:A.API_CALL_ABORTED,message:M({key:O.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{T.off(E.LEAVE_SUCCESS,s,this),this._emitter.off("connection-state-changed",t,this)},o=setTimeout(()=>{n();let a=new C({code:A.API_CALL_TIMEOUT,message:"connection timeout"});id+=1,jp(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),rd=!0,this._emitter.emit("firewall-restriction")),e(a)},Yr);T.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(le.CONNECTED,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=Ht()){this._log.warn(`SDK has tried reconnect for ${this._reconnectionCount} times, but all failed, please check your network`),this.stopReconnection();let i=new C({code:this._isUplink?A.UPLINK_RECONNECTION_FAILED:A.DOWNLINK_RECONNECTION_FAILED,message:M({key:this._isUplink?O.UPLINK_RECONNECTION_FAILED:O.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(le.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 cd=Ie(ad());var ce=function(r){return cd.default.parse(r)},tt=function(r){return cd.default.write(r)},Bl=function(r){let i=ce(r);return i.media.forEach(e=>{e.type===m.AUDIO&&e.fmtp.forEach(t=>{t.config+=";sprop-stereo=1;stereo=1"})}),tt(i)};function $l(r){let i=ce(r);return i.media.forEach(e=>{var t,s;if(e.type===m.VIDEO){let n=new Set;e.rtp.forEach(({payload:a,codec:c})=>c==="H264"&&n.add(a)),e.fmtp.forEach(({payload:a,config:c})=>{let d=c.match(/apt=(\d+)/);d&&d[1]&&n.has(Number(d[1]))&&n.add(a)});let o=({payload:a})=>!n.has(a);e.rtp=e.rtp.filter(o),e.rtcpFb=(t=e.rtcpFb)==null?void 0:t.filter(o),e.fmtp=e.fmtp.filter(o),e.payloads=(s=e.payloads)==null?void 0:s.split(" ").filter(a=>!n.has(Number(a))).join(" ")}}),tt(i)}function Po(r){return Object.keys(r).filter(i=>r[i])}var ud=class extends je{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 ti(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new Lt(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new br(this._room,this)}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 Ei(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,s,n;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(s=this.remoteVideoTrack)==null||s.onFlagChanged(),(n=this.remoteAuxiliaryTrack)==null||n.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===m.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(e){var n,o;let t=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&t!==e&&((n=this.remoteVideoTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e}),(o=this.remoteAuxiliaryTrack)==null||o.emit("connection-state-changed",{prevState:t,state:e})),s}onTrack(e){let t=e.streams[0],{track:s}=e,n=t.id===Kr?m.MAIN:m.AUXILIARY;this._log.debug(`ontrack ${n} ${s.kind}`);let o=m.AUDIO;s.kind===m.VIDEO&&(o=n===m.MAIN?m.VIDEO:m.AUXILIARY);let a=this.remoteAudioTrack;o===m.VIDEO?a=this.remoteVideoTrack:o===m.AUXILIARY&&(a=this.remoteAuxiliaryTrack),a.setInputMediaStreamTrack(s)}addRRTRLine(e){let t=e.split(`\r
35
+ ${s.stack}`),!1}},r};var yo=new WeakMap;function _l(r,i){return W((e,t)=>function(...s){var a,c;let n=(a=yo.get(this))==null?void 0:a.get(i(...s));n&&n>0&&clearTimeout(n);let o=window.setTimeout(()=>{e.apply(this,s)},r);yo.has(this)?(c=yo.get(this))==null||c.set(i(...s),o):yo.set(this,new Map([[i(...s),o]]))})}var fl="5.7.0-beta.2";function De(...r){return W((i,e)=>function(...t){try{No.call(this,r,t,e,this._name)}catch(s){return Promise.reject(s)}return i.apply(this,t)})}function Qc(...r){return W((i,e)=>function(...t){try{No.call(this,r,t,e,this._name)}catch(s){throw s}return i.apply(this,t)})}function No(r,i,e,t){if(de(r))for(let s=0;s<r.length;s++)bo.call(this,{rule:r[s],value:i[s],key:r[s].name,fnName:e,className:t});else bo.call(this,{rule:r,value:i[0],key:r.name,fnName:e,className:t})}function bo({rule:r,value:i,key:e,fnName:t,className:s}){function n(c){return{code:x.INVALID_PARAMETER,extraCode:c,fnName:t,messageParams:{key:e,rule:r,value:i}}}if(g(i)){if(r.required)throw new k(n(5001));if(g(r.defaultValue)){G(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),G(r.type[d])&&i instanceof r.type[d]&&(c=!0),z(r.type[d])&&he(i)===r.type[d].toLowerCase()&&(c=!0);if(!c)throw new k({code:x.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:r.type.map(d=>gs(d)?Bn(d):z(d)?d:he(d))},value:i}})}else if(!g(r.type)&&he(i)!==r.type)throw new k(n(5002));if(r.allowEmpty===!1){let c=re(i)&&(i===0||Number.isNaN(i)),d=z(i)&&i.trim()==="";if(c||d)throw new k(n(5003))}if(r.notLessThanZero&&re(i)&&i<0)throw new k(n(5006));if(!g(r.min)&&re(i)&&i<r.min)throw new k(n(5007));if(!g(r.max)&&re(i)&&i>r.max)throw new k(n(5008));if(z(r.instanceOf)){if(!i||i._name!==r.instanceOf)throw new k(n(5004))}else if(G(r.instanceOf)&&!(i instanceof r.instanceOf))throw new k(n(5004));if(Array.isArray(r.values)&&!r.values.includes(i))throw new k(n(5005));let{properties:o}=r;$e(o)&&ut(i)&&Object.keys(o).forEach(c=>{bo.call(this,{rule:o[c],value:i&&i[c],key:`${c}`,fnName:t,className:s})});let{arrayItem:a}=r;$e(a)&&de(i)&&i.forEach((c,d)=>{bo.call(this,{rule:a,value:c,key:`${e}[${d}]`,fnName:t,className:s})}),G(r.validate)&&r.validate.call(this,i,e,t,s,this)}function ne(r={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t}=r;return W((s,n)=>function(...o){function a(l,h,_){if(_&&_.includes(l))return"hided";if(e){let f=e(...o);if(o[f.argIndex]===h)return f.value}if(h===o||l in o)return h;try{return h instanceof HTMLElement?`id: ${h.id} type:${he(h)}`:(JSON.stringify(h),h)}catch(f){return`type:${he(h)}`}}let c=this._log||I;o.length>0?c.info(`${n}() ${JSON.stringify(o,(l,h)=>a(l,h,["userSig","privateMapKey"]))}`):c.info(`${n}()`);let d=t?t(...o):Kn[n];try{let l=s.apply(this,o),h=L();return Es(l)?l.then(_=>(c.info(`${n}() success ${i.call(this,...o)}`),v.addSuccessEvent({key:d,cost:L()-h}),_)).catch(_=>{throw _=k.convertFrom.call(this,_,n,o.length===1?o[0]:o),c.error(`${n}() failed ${i.call(this,...o)} ${_} params: ${JSON.stringify(o,a)}`),v.addFailedEvent({key:d,error:_}),_}):(v.addSuccessEvent({key:d}),l)}catch(l){throw l=k.convertFrom.call(this,l,n),c.error(`${n}() failed ${l} params: ${JSON.stringify(o,a)}`),v.addFailedEvent({key:d,error:l}),l}})}var vo=r=>W((i,e)=>function(t,s){return p(this,null,function*(){let n=this._plugins.get(t);if(!n)throw this._log.error(`plugin ${String(t)} is not found`),new k({code:x.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});return No.call(this,n.getValidateRule(r),[s],e,"TRTC"),i.call(this,n,s)})});var Do=0,zc=class{constructor(i,e){u(this,"player");u(this,"publisher");u(this,"mixInput");this.mixInput=new Ar(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||(g(i.volume)||(this.volume=i.volume),g(i.loop)||(this.loop=i.loop),g(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 kr(r,i){if(i&&typeof i!="function")throw new k({code:x.INVALID_PARAMETER,message:`start audioMixer plugin: param ${r} should be a function.`})}var Lr=class{constructor(i){this.core=i;u(this,"log");u(this,"mixedMusicMap",new Map);u(this,"cacheMusicMap",new Map);Do=Do+1,this.log=i.log.createChild({id:`${this.getAlias()}${Do}`}),this.log.info(`[audioMixer] created id=${this.getAlias()}${Do}`),this.core=i}getName(){return Lr.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return Lr.startValidateRule;case"update":return Lr.updateValidateRule;case"stop":return Lr.stopValidateRule}}start(i){return p(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 n=this.cacheMusicMap.get(t);n?i.url?n.reset():(n.mixInput.replaceSource(i.track),n.mixInput.connect()):(n=new zc(i,e.audioManager),this.cacheMusicMap.set(t,n)),n.updateListener(i),n.updateSettings(i),yield n.play(),this.mixedMusicMap.set(t,n),this.log.info(`start mix audio track ${t} success.`),v.addEnum({key:502700,value:3}),this.kvUpload(i)})}update(i){return p(this,null,function*(){let{id:e,operation:t,seekFrom:s,playbackRate:n}=i;this.log.info(`update music source, ${JSON.stringify(i)}`);let o=this.mixedMusicMap.get(e);if(!o){this.log.warn(`update music source failed, music id: ${e} not found.`);return}o.updateSettings(i),o.updateListener(i),g(t)||o.setOperation(t),g(s)||o.seek(s),this.kvUpload(i)})}stop(e){return p(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:n,operation:o,seekFrom:a,onTimeUpdate:c,onDurationChange:d,onEnded:l}=i;e&&v.addCount({key:502711}),t&&v.addCount({key:502703}),s&&v.addCount({key:502704}),n&&v.addCount({key:502705}),o&&v.addCount({key:502706}),a&&v.addCount({key:502707}),typeof c!="function"&&v.addCount({key:502709}),typeof l!="function"&&v.addCount({key:502710}),typeof d!="function"&&v.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()}},yi=Lr;u(yi,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(i,e,t){if(i.url&&i.url!=="*"){let s=i.url.split("?")[0],n=["mp3","ogg","wav","flac"],o=s.split(".").pop(),a=n.indexOf(o)>=0,c=s.startsWith("blob"),d=s.startsWith("data");if(!(a||c||d))throw new k({code:x.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:x.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t});kr("onTimeUpdate",i.onTimeUpdate),kr("onEnded",i.onEnded),kr("onDurationChange",i.onDurationChange)}}),u(yi,"updateValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},loop:{type:"boolean"},volume:{type:"number"},seekFrom:{type:"number"},operation:{type:"string",values:["pause","resume","stop"]}},validate(i,e,t){kr("onTimeUpdate",i.onTimeUpdate),kr("onEnded",i.onEnded),kr("onDurationChange",i.onDurationChange)}}),u(yi,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),u(yi,"Name","AudioMixer");var El=r=>(r=Number(r),r>0&&r<14e8);var Oo=0,xr=class{constructor(i){this.core=i;u(this,"log");u(this,"preloadPromise");u(this,"audioContext",Fe("denoiser"));u(this,"workletNode");Oo=Oo+1,this.log=i.log.createChild({id:`${this.getAlias()}${Oo}`}),this.log.info(`[audioDenoiser] created id=${this.getAlias()}${Oo}`),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,n){if(!i.room.audioManager.hasAudioTrack)throw new k({code:x.INVALID_OPERATION,extraCode:5106,fnName:s})}}}preload(i){return this.preloadPromise||(this.preloadPromise=this.doPreload(i)),this.preloadPromise}doPreload(i){return p(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield wi(this.audioContext,t)}finally{URL.revokeObjectURL(t)}})}getName(){return xr.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(i){switch(i){case"start":return xr.startValidateRule(this.core);case"update":return xr.updateValidateRule;case"stop":return xr.stopValidateRule}}start(i){return p(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:n,status:o,message:a}=yield Bp(P(N({},i),{timestamp:t}));if(!s)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${s}. Message: ${a}`),new k({code:x.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:n,status:o}}),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 p(this,null,function*(){})}stop(){return p(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(){}},ji=xr;u(ji,"updateValidateRule",{type:"object"}),u(ji,"stopValidateRule",{type:"object"}),u(ji,"Name","AIDenoiser");var gl={MAIN:"schedule.cloud-rtc.com",MAIN_OVERSEA:"schedule.rtc.tencentcloud.com"};function Up(r){let i;return El(r)?i=gl.MAIN_OVERSEA:i=gl.MAIN,i}function Bp(s){return p(this,arguments,function*({sdkAppId:r,userId:i,userSig:e,timestamp:t}){let o=`https://${Up(r)}/api/v1/audioAiAuth?sdkAppId=${r}&userId=${i}&userSig=${e}&timestamp=${t}`,a=yield fetch(o),{data:{errCode:c,errMsg:d,sign:l,status:h}}=yield a.json();if(h==="1")return{auth:!0,sign:l,status:h,message:d};let _="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:h,message:d?`${_} Reason: ${d}. ${f}`:`${_}, ${f}`}})}var Tl=Ie(ke(),1);var Kc=class extends Tl.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 p(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){I.info("PressureDetector start 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;(e=this.observer)==null||e.disconnect(),this.observer=null}},$p=new Kc,Yc=$p;var Sl=0,Mo=new Set,Oe=null;Yo(fl);var Hp={RtcError:k,ErrorCode:x,ErrorCodeDictionary:xt},Gs=class extends Al.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${++Sl}`}));u(this,"_plugins",new Map);u(this,"_networkQuality",null);u(this,"_speakerId");this._room=new e(N({logger:this._log,frameWorkType:Gs.frameWorkType},t)),this._log.debug(JSON.stringify(t)),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(yi,t.assetsPath),this._use(ji,t.assetsPath),this._room.on("audio-volume",s=>{!s.find(n=>n.userId==="")&&this._localAudioTrack&&s.push({userId:"",volume:Math.floor(this._localAudioTrack.getAudioLevel()*100)}),this.emit($.AUDIO_VOLUME,{result:s.sort((n,o)=>o.volume-n.volume)})}),this._room.videoManager.on("error",({reason:s,error:n})=>{this._log.error(new k({code:x.OPERATION_FAILED,extraCode:5504,messageParams:{reason:s,error:n}}))}),this._listenEvents(),this._initActiveSpeaker(),pl(this,"trtc")}static create(e){}static _create(e,t){il();let s=new Gs(e,t||{});return Mo.add(s),Yc.start(),s}_listenEvents(){Ve(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=>{Ve(s,s).add("player-state-changed",n=>{let o=P(N({},n),{userId:e.userId});s.kind===m.VIDEO&&(o.streamType=Hs(s.streamType)),this.emit(s.kind===m.AUDIO?$.AUDIO_PLAY_STATE_CHANGED:$.VIDEO_PLAY_STATE_CHANGED,o)}).add("error",n=>{n.getCode()===A.PLAY_NOT_ALLOWED&&this.emit($.AUTOPLAY_FAILED,{userId:s.userId})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(s=>{pe(s)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:t})=>{let{userId:s}=t,n=e.audioAvailable,o=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"}`),n!==a&&(this.emit(a?$.REMOTE_AUDIO_AVAILABLE:$.REMOTE_AUDIO_UNAVAILABLE,{userId:s}),a?this._onAudioAvailable({userId:s}):this._onAudioUnavailable({userId:s,muteState:t})),o!==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("firewall-restriction",()=>{this.emit($.ERROR,new k({code:x.OPERATION_FAILED,extraCode:5501}))}).add("sei-message",e=>{this.emit($.SEI_MESSAGE,P(N({},e),{streamType:Hs(e.streamType)}))}).add("heartbeat-report",e=>{var n,o,a,c,d,l,h;let t={2:"big",3:"small",7:"sub"},s={rtt:e.msg_up_stream_info.msg_network_status.uint32_rtt||((n=e.msg_down_stream_info[0])==null?void 0:n.msg_network_status.uint32_rtt)||((o=this._networkQuality)==null?void 0:o.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:(((h=e.msg_up_stream_info.msg_audio_status)==null?void 0:h.uint32_audio_level)||0)/nt},video:e.msg_up_stream_info.msg_video_status.filter(_=>t[_.uint32_video_stream_type]).map(_=>({bitrate:(_.uint32_video_codec_bitrate||0)/1e3,width:_.uint32_video_width,height:_.uint32_video_height,frameRate:_.uint32_video_enc_fps,videoType:t[_.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(_=>({userId:_.msg_user_info.str_identifier,audio:{bitrate:(_.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(_.msg_audio_status.uint32_audio_level||0)/nt},video:_.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)}),Ve(this,_e).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=>p(this,null,function*(){if(this.emit($.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),Oe&&Oe.deviceId===Zr){let t=(yield $i()).find(s=>s.deviceId===Zr);t&&Oe.groupId!==t.groupId&&(Oe=t,this.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}})).add("audioOutputRemoved",e=>p(this,null,function*(){this.emit($.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield $i())[0];t&&Oe&&(Oe.deviceId===e.deviceId||Oe.deviceId===Zr&&Oe.groupId!==t.groupId)&&(Oe=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 n=new e(ml(this._room,Hp,t));this._plugins.set(e.Name,n)}enterRoom(e){return p(this,null,function*(){var c,d;let{scene:t="rtc",enableAutoPlayDialog:s=!0,autoReceiveAudio:n=!0,autoReceiveVideo:o=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!z(e.proxy)&&e.proxy.turnServer&&((d=(c=this._room).setTurnServer)==null||d.call(c,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=s,this._room.autoReceiveAudio=n,this._room.autoReceiveVideo=o,ue(e.enableHWEncoder)&&(this._room.enableHWEncoder=e.enableHWEncoder);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,Gs.frameWorkType),this._checkTrackToPublish()})}exitRoom(){return p(this,null,function*(){return yield this._exitRoom()})}switchRole(e,t){return p(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(){pe(this),this.removeAllListeners(),this._room.destroy(),Mo.delete(this),Mo.size===0&&Yc.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 p(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:n}=e,o=new Ne(this._room.audioManager),a={},c={muted:!0};n&&(g(n.microphoneId)?g(n.audioTrack)||(a.customSource=n.audioTrack):a.deviceId=n.microphoneId,n&&re(n.captureVolume)&&o.setCaptureVolume(n.captureVolume),g(n.profile)||(z(n.profile)?mn[n.profile]&&o.setProfile(mn[n.profile]):o.setProfile(n.profile)),re(n.earMonitorVolume)&&(c.muted=!(n.earMonitorVolume>0),c.volume=n.earMonitorVolume),g(n.echoCancellation)||(o.profile.echoCancellation=n.echoCancellation),g(n.noiseSuppression)||(o.profile.noiseSuppression=n.noiseSuppression),g(n.autoGainControl)||(o.profile.autoGainControl=n.autoGainControl)),o.on("5",d=>{this.emit($.ERROR,new k({code:x.DEVICE_ERROR,extraCode:5309,messageParams:{error:d}}))}),o.on("2",d=>{this.emit($.DEVICE_CHANGED,{type:"microphone",action:"active",device:d})}),o.on("4",d=>{let l;d.error&&(l=k.convertFrom(d.error)),this.emit($.PUBLISH_STATE_CHANGED,P(N({},d),{error:l}))}),this._listenOutputTrackChanged(o),this._speakerId&&o.setAudioOutput(this._speakerId),yield o.capture(a),g(s)||o.setMute(s),Ve(o,o).add("player-state-changed",d=>{this.emit($.AUDIO_PLAY_STATE_CHANGED,P(N({},d),{userId:""}))}),t&&this._room.isJoined&&this._room.publish(o).catch(()=>{}),this._localAudioTrack=o,this._localAudioConfig=P(N({},e),{publish:t}),yield this._updateAudioPlayOption({playOption:c,track:o})})}updateLocalAudio(e){return p(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:s,option:n}=e,o={};n&&(n.microphoneId?yield this._localAudioTrack.switchDevice(n.microphoneId):g(n.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(n.audioTrack)),g(n.captureVolume)||this._localAudioTrack.setCaptureVolume(n.captureVolume),g(n.earMonitorVolume)||(o.muted=!(n.earMonitorVolume>0),o.volume=n.earMonitorVolume),yield this._localAudioTrack.update3A(n)),this._room.isJoined&&!g(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),g(s)||this._localAudioTrack.setMute(s),yield this._updateAudioPlayOption({playOption:o,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),jt(this._localAudioConfig,e)})}stopLocalAudio(){return p(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),pe(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)})}startLocalVideo(){return p(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:n,option:o}=e,a=new ae(this._room.videoManager),c={},d={};if(o&&(o.cameraId?c.deviceId=o.cameraId:g(o.useFrontCamera)?g(o.videoTrack)||(c.customSource=o.videoTrack):c.facingMode=o.useFrontCamera?m.FACING_MODE_USER:m.FACING_MODE_ENVIRONMENT,g(o.profile)||(z(o.profile)?Qe[o.profile]&&a.setProfile(Qe[o.profile]):a.setProfile(o.profile)),g(o.fillMode)||(d.objectFit=o.fillMode),g(o.mirror)||(d.mirror=o.mirror),g(o.small)||(ys()?z(o.small)?a.small=Qe[o.small]:o.small===!0?a.small=Qe["120p"]:a.small=o.small:this._log.warn("small stream is not supported"))),a.on("5",l=>{this.emit($.ERROR,new k({code:x.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 h;l.error&&(h=k.convertFrom(l.error)),this.emit($.PUBLISH_STATE_CHANGED,P(N({},l),{error:h}))}),this._listenOutputTrackChanged(a),yield a.capture(c),g(n)||(yield a.setMute(n)),a.mediaTrack)if(o!=null&&o.qosPreference){let l=Ji(o.qosPreference);a.mediaTrack.contentHint=l}else o!=null&&o.videoTrack||(a.mediaTrack.contentHint=Ji(et.QOS_PREFERENCE_SMOOTH));Ve(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 p(this,null,function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:s,mute:n,option:o}=e,a={};if(o){if(g(o.profile)||(z(o.profile)?Qe[o.profile]&&this._localVideoTrack.setProfile(Qe[o.profile]):this._localVideoTrack.setProfile(o.profile),(!o.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(o.cameraId))&&g(o.useFrontCamera)&&this._localVideoTrack.applyProfile()),o.cameraId?yield this._localVideoTrack.switchDevice(o.cameraId):g(o.useFrontCamera)?g(o.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(o.videoTrack)):yield this._localVideoTrack.switchDevice(o.useFrontCamera?m.FACING_MODE_USER:m.FACING_MODE_ENVIRONMENT),g(o.fillMode)||(a.objectFit=o.fillMode),g(o.mirror)||(a.mirror=o.mirror),o.qosPreference&&this._localVideoTrack.mediaTrack){let c=Ji(o.qosPreference);this._localVideoTrack.mediaTrack.contentHint=c}if(o.small){let c=!this._localVideoTrack.small;ys()?(o.small===!0?this._localVideoTrack.small=Qe["120p"]:z(o.small)?this._localVideoTrack.small=Qe[o.small]:this._localVideoTrack.small=o.small,this._room.videoManager.update(),c&&this._room.enableSmall(!0)):this._log.warn("small stream is not supported")}else o.small===!1&&this._localVideoTrack.small&&(delete this._localVideoTrack.small,this._room.videoManager.update(),this._room.enableSmall(!1))}this._room.isJoined&&!g(s)&&(s&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._localVideoConfig.publish&&!s&&this._room.unpublish(this._localVideoTrack).catch(()=>{})),g(n)||(yield this._localVideoTrack.setMute(n)),yield this._updateVideoPlayOption({view:t,playOption:a,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),jt(this._localVideoConfig,e)})}stopLocalVideo(){return p(this,null,function*(){!this._localVideoTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),pe(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return p(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:n}=e,o=new Je(this._room.videoManager);o.on("4",h=>{let _;h.error&&(_=k.convertFrom(h.error)),this.emit($.PUBLISH_STATE_CHANGED,P(N({},h),{error:_}))}),this._listenOutputTrackChanged(o);let a=null,c={},d={};n&&(g(n.profile)||(z(n.profile)?pn[n.profile]&&o.setProfile(pn[n.profile]):o.setProfile(n.profile)),n.systemAudio&&(c.systemAudio=!0,c.echoCancellation=n.echoCancellation,c.noiseSuppression=n.noiseSuppression,c.autoGainControl=n.autoGainControl),g(n.fillMode)||(d.objectFit=n.fillMode),n.videoTrack&&(c.videoTrack=n.videoTrack),n.audioTrack&&(c.audioTrack=n.audioTrack),n.captureElement&&(c.captureElement=n.captureElement),n.preferDisplaySurface&&(c.preferDisplaySurface=n.preferDisplaySurface));let l=yield o.capture(c);if(n!=null&&n.qosPreference){let h=Ji(n.qosPreference);o.mediaTrack.contentHint=h}else n!=null&&n.videoTrack||(o.mediaTrack.contentHint=Ji(et.QOS_PREFERENCE_CLEAR));if(o.mediaTrack.addEventListener(m.ENDED,()=>{this._stopScreenShare(),this.emit($.SCREEN_SHARE_STOPPED)}),l.getAudioTracks()[0]&&(a=new kt(this._room.audioManager),a.setInputMediaStreamTrack(l.getAudioTracks()[0]),this._speakerId&&a.setAudioOutput(this._speakerId)),Ve(o,o).add("player-state-changed",h=>{this.emit($.VIDEO_PLAY_STATE_CHANGED,P(N({},h),{userId:"",streamType:"sub"}))}),s&&this._room.isJoined){let h=[o];a&&h.push(a),this._room.publish(...h).catch(()=>{})}this._localScreenTrack=o,this._localScreenAudioTrack=a,this._localScreenConfig=P(N({},e),{view:t,publish:s}),yield this._updateVideoPlayOption({view:t,playOption:d,track:o})})}updateScreenShare(e){return p(this,null,function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:s,option:n}=e,o={};if(n&&(g(n.fillMode)||(o.objectFit=n.fillMode),n.qosPreference)){let a=Ji(n.qosPreference);this._localScreenTrack.mediaTrack.contentHint=a}this._room.isJoined&&!g(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:o,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),jt(this._localScreenConfig,e)})}stopScreenShare(){return p(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return p(this,null,function*(){let{view:t,userId:s,streamType:n,option:o}=e,a=`${s}_${n}`;if(this._remoteVideoConfigMap.has(a)){this._log.warn(`remote video has already started. userId:${s}, streamType:${n}`);return}let c=this._room.remotePublishedUserMap.get(s);if(!c)return;let d={},l=n==="main"?c.remoteVideoTrack:c.remoteAuxiliaryTrack;this._listenOutputTrackChanged(l),o&&(g(o.fillMode)||(d.objectFit=o.fillMode),g(o.mirror)||(d.mirror=o.mirror),n==="main"&&!g(o.small)&&(c.remoteVideoTrack.setMediaType(o.small?8:4),this._room.changeType(o.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}),o&&!g(o.receiveWhenViewVisible)&&this._observeView({remoteTrack:l,view:t,receiveWhenViewVisible:o.receiveWhenViewVisible,viewRoot:o==null?void 0:o.viewRoot})})}updateRemoteVideo(e){return p(this,null,function*(){var w,ie;let{view:t,userId:s,streamType:n,option:o}=e,a=`${s}_${n}`,c=this._remoteVideoConfigMap.get(a);if(!c||!this._room.remotePublishedUserMap.has(s))return;let d={};o&&(g(o.fillMode)||(d.objectFit=o.fillMode),g(o.mirror)||(d.mirror=o.mirror));let l=null,h=this._room.remotePublishedUserMap.get(s);if(n==="main"&&(h==null?void 0:h.muteState.hasVideo)&&(l=h.remoteVideoTrack),n==="sub"&&(h==null?void 0:h.muteState.hasAuxiliary)&&(l=h.remoteAuxiliaryTrack),!l)return;let{config:_}=c;n==="main"&&o&&!g(o.small)&&this._room.changeType(o.small,l.user),yield this._updateVideoPlayOption({view:t,playOption:d,track:l,prevConfig:_}),jt(_,e);let f=g(o==null?void 0:o.receiveWhenViewVisible)?(w=_.option)==null?void 0:w.receiveWhenViewVisible:o.receiveWhenViewVisible,R=g(t)?_.view:t,y=g(o==null?void 0:o.viewRoot)?(ie=_.option)==null?void 0:ie.viewRoot:o.viewRoot;this._observeView({remoteTrack:l,view:R,receiveWhenViewVisible:f,viewRoot:y})})}stopRemoteVideo(e){return p(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,t=!0){return p(this,null,function*(){let s=[],n=this._room.remotePublishedUserMap.get(e.userId);if(n){let{muteState:a,remoteVideoTrack:c,remoteAuxiliaryTrack:d}=n;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 o=this._remoteVideoConfigMap.get(`${e.userId}_${e.streamType}`);o&&o.observer&&o.observer.disconnect(),this._remoteVideoConfigMap.delete(`${e.userId}_${e.streamType}`)})}muteRemoteAudio(e,t){return p(this,null,function*(){if(e==="*")if(t)yield this._stopRemoteAudio({userId:e});else{let s=[...this._room.remotePublishedUserMap.values()];for(let n of s)n.muteState.hasAudio&&!this._remoteAudioConfigMap.has(n.userId)&&(yield this._startRemoteAudio({userId:n.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 n of s)this._updateAudioPlayOption({playOption:{volume:t},track:n.remoteAudioTrack})}else if(e){let s=this._room.remotePublishedUserMap.get(e);s&&this._updateAudioPlayOption({playOption:{volume:t},track:s.remoteAudioTrack})}}startPlugin(e,t){return p(this,null,function*(){return e.start(t)})}updatePlugin(e,t){return p(this,null,function*(){return e.update(t)})}stopPlugin(e,t){return p(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 n,o;let t,s="main";if(z(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"?((n=this._localScreenAudioTrack)==null?void 0:n.mediaTrack)||null:((o=this._localAudioTrack)==null?void 0:o.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 n=this._room.remotePublishedUserMap.get(t);if(n)return s==="main"?n.remoteVideoTrack.mediaTrack:n.remoteAuxiliaryTrack.mediaTrack}return null}getVideoSnapshot(e={}){let{userId:t,streamType:s="main"}=e;if(t){let n=this._room.remotePublishedUserMap.get(t);if(s==="main"&&(n==null?void 0:n.muteState.hasVideo))return n.remoteVideoTrack.getVideoFrame();if(s==="sub"&&(n==null?void 0:n.muteState.hasAuxiliary))return n.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(n=>n.remoteAudioTrack.setAudioOutput(e))}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return p(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 n=this._room.remotePublishedUserMap.get(t);if(!n)return;let o={};s&&(g(s.volume)||(o.volume=s.volume));let a=n.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:o,track:a})}catch(c){throw this._remoteAudioConfigMap.delete(t),c}this._emitTrackEvent(a)})}_stopRemoteAudio(e,t=!0){return p(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(o){return p(this,arguments,function*({view:e,playOption:t,track:s,prevConfig:n}){if(s.setMirror(t.mirror),g(e)&&n&&n.view&&!ka(t)){let a=Ss(n.view);a.length>0&&(yield s.play(a,t))}if(!g(e)){let a=Ss(e);a.length>0?yield s.play(a,t):s.stop()}})}_updateAudioPlayOption(n){return p(this,arguments,function*({playOption:e={},track:t,prevConfig:s}){if(!t.isPlayCalled)try{yield t.play(null,e)}catch(o){}g(e.muted)||t.setPlayerMute(e.muted),g(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))}_emitTrackEvent(e){let t=e.isRemote?e.userId:"";e.outMediaTrack&&this._mediaTrackMap.get(e.outMediaTrack)!==t&&(this._mediaTrackMap.set(e.outMediaTrack,t),this.emit($.TRACK,{userId:t,streamType:Hs(e.streamType),track:e.outMediaTrack}))}_checkTrackToPublish(){var t,s,n;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),(n=this._localScreenConfig)!=null&&n.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:n}){if(g(t))return;let o=this._remoteVideoConfigMap.get(`${e.userId}_${Hs(e.streamType)}`);if(!o)return;let a=o.observer||void 0;if(t===null||de(t)&&t.length===0||!s){a==null||a.disconnect(),e.isSubscribed||this._room.subscribe(e).catch(()=>{});return}let d=o.visibleViewMap||new Map,l=-1;(!a||a.root!==n)&&(a==null||a.disconnect(),d.clear(),a=new IntersectionObserver(_=>{_.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:n}));let h=new Set(Ss(t));d.forEach((_,f)=>{h.has(f)||(a.unobserve(f),d.delete(f))}),h.forEach(_=>{d.set(_,!0),a.observe(_)}),a.takeRecords().forEach(_=>{d.set(_.target,_.isIntersecting)}),o.visibleViewMap=d,o.observer=a}_exitRoom(){return p(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=>{pe(e.remoteAudioTrack),pe(e.remoteVideoTrack),pe(e.remoteAuxiliaryTrack)})})}_stopScreenShare(){return p(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),pe(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_initActiveSpeaker(){return p(this,null,function*(){if(Oe&&!Rr(Oe))this.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:Oe});else{let e=yield $i();if(e[0]&&!Rr(e[0]))Oe=e[0],this.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]});else{let t=({track:s})=>{s.kind==="audio"&&(!Oe||Rr(Oe))&&(this._initActiveSpeaker(),T.off("102",this._initActiveSpeaker))};T.on("102",t)}}})}_onAudioAvailable({userId:e}){let t=this._remoteAudioMuteMap.has(e)?this._remoteAudioMuteMap.get(e):this._remoteAudioMuteMap.get("*");(t===!1||this._room.autoReceiveAudio&&!t)&&this._doStartRemoteAudio({userId:e}).catch(()=>{})}_onVideoAvailable({userId:e,streamType:t}){if(!this._room.autoReceiveVideo)return;let s=this._room.remotePublishedUserMap.get(e);if(s){let n=t==="main"?s.remoteVideoTrack:s.remoteAuxiliaryTrack;this._room.subscribe(n).then(()=>{this._emitTrackEvent(n)}).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){this._room.sendSEI(e,t||{seiPayloadType:243}),v.addCount({key:5e5,useUV:!0})}sendCustomMessage(e){var t,s;(s=(t=this._room).sendCustomMessage)==null||s.call(t,e),v.addCount({key:500001,useUV:!0})}static setLogLevel(e,t){I.setLogLevel(e),g(t)||(t?I.enableUploadLog():I.disableUploadLog())}static isSupported(){return Wn()}static getCameraList(e=!0){return Ge(e)}static getMicrophoneList(e=!0){return Ue(e)}static getSpeakerList(e=!0){return $i(e)}static setCurrentSpeaker(e){return p(this,null,function*(){(yield $i()).forEach(s=>{s.deviceId===e&&(Mo.forEach(n=>{n.setCurrentSpeaker(e),n.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:s})}),Oe=s)})})}static _addKVStat({type:e,key:t,value:s,base:n,useUV:o,version:a}){switch(a&&(Ui.version=a),e){case"count":Ui.addCount({key:t,useUV:o});break;case"enum":Ui.addEnum({key:t,value:s,useUV:o});break;case"number":Ui.addNumber({key:t,value:s,split:n});break}}},Q=Gs;u(Q,"_loggerManager",I),u(Q,"EVENT",$),u(Q,"ERROR_CODE",x),u(Q,"TYPE",et),u(Q,"frameWorkType",30),b([ne({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),b([De(Se.TRTC.enterRoom),Ri("room",([r],[i])=>(r.roomId||r.strRoomId)===(i.roomId||i.strRoomId)&&r.userId===i.userId&&r.sdkAppId===i.sdkAppId),W(r=>function(i){return this._log.setUserId(i.userId),this._log.setSdkAppId(i.sdkAppId),r.call(this,i)}),ne()],Q.prototype,"enterRoom",1),b([ne()],Q.prototype,"exitRoom",1),b([De(Se.TRTC.switchRole),Wi("room",{merge:(r,i)=>i}),ne()],Q.prototype,"switchRole",1),b([ne()],Q.prototype,"destroy",1),b([De(Se.TRTC.startLocalAudio),Ri("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)}),ne()],Q.prototype,"startLocalAudio",1),b([De(Se.TRTC.updateLocalAudio),Wi("audio",{debounce:{delay:200,getKey:()=>`${Sl}-localAudio`,isNeedToDebounce:r=>{var i;return!g((i=r.option)==null?void 0:i.captureVolume)}}}),ne()],Q.prototype,"updateLocalAudio",1),b([Ci("audio"),ne()],Q.prototype,"stopLocalAudio",1),b([De(Se.TRTC.startLocalVideo),Ri("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)}),ne()],Q.prototype,"startLocalVideo",1),b([De(Se.TRTC.updateLocalVideo),Wi("video"),ne()],Q.prototype,"updateLocalVideo",1),b([Ci("video"),ne()],Q.prototype,"stopLocalVideo",1),b([De(Se.TRTC.startScreenShare),Ri("screen",()=>!0),ne()],Q.prototype,"startScreenShare",1),b([De(Se.TRTC.updateScreenShare),Wi("screen"),ne()],Q.prototype,"updateScreenShare",1),b([ne()],Q.prototype,"stopScreenShare",1),b([De(Se.TRTC.startRemoteVideo),Ri(r=>`v${r.userId}${r.streamType}`,()=>!0),ne({getRemoteId:r=>`${r.userId}_${r.streamType}`})],Q.prototype,"startRemoteVideo",1),b([De(Se.TRTC.updateRemoteVideo),Wi(r=>`v${r.userId}${r.streamType}`),ne({getRemoteId:r=>`${r.userId}_${r.streamType}`})],Q.prototype,"updateRemoteVideo",1),b([De(Se.TRTC.stopRemoteVideo),W(r=>function(i){return p(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)})}),ne({getRemoteId:r=>`${r.userId}_${r.streamType}`})],Q.prototype,"stopRemoteVideo",1),b([Ci(r=>`v${r.userId}${r.streamType}`)],Q.prototype,"_stopRemoteVideo",1),b([De(...Se.TRTC.muteRemoteAudio),ne({getRemoteId:r=>r})],Q.prototype,"muteRemoteAudio",1),b([Qc(...Se.TRTC.setRemoteAudioVolume),_l(200,r=>r),ne({getRemoteId:r=>r})],Q.prototype,"setRemoteAudioVolume",1),b([vo("start"),Ri((r,i)=>r.getAlias()+r.getGroup(i)),ne({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>ec[r.getName()]})],Q.prototype,"startPlugin",1),b([vo("update"),Wi((r,i)=>r.getAlias()+r.getGroup(i)),ne({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>tc[r.getName()]})],Q.prototype,"updatePlugin",1),b([vo("stop"),Ci((r,i)=>r.getAlias()+r.getGroup(i)),ne({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>ic[r.getName()]})],Q.prototype,"stopPlugin",1),b([Qc(...Se.TRTC.enableAudioVolumeEvaluation)],Q.prototype,"enableAudioVolumeEvaluation",1),b([ne()],Q.prototype,"getVideoSnapshot",1),b([ne()],Q.prototype,"setCurrentSpeaker",1),b([Ri(r=>`a${r.userId}`,()=>!0)],Q.prototype,"_startRemoteAudio",1),b([W(r=>function(i){return p(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)})}),Ci(r=>`a${r.userId}`)],Q.prototype,"_stopRemoteAudio",1),b([Ci("room")],Q.prototype,"_exitRoom",1),b([Ci("screen")],Q.prototype,"_stopScreenShare",1),b([De(...Se.TRTC.sendSEIMessage),Xc({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...r)=>r[0].byteLength})],Q.prototype,"sendSEIMessage",1),b([De(Se.TRTC.sendCustomMessage),Xc({timesInSecond:30,maxSizeInSecond:8e3,getSize:r=>r.data.byteLength})],Q.prototype,"sendCustomMessage",1),b([De(Se.TRTC.create)],Q,"_create",1);var Ws=Q;var Zc=class{constructor(){this._set=new Set;T.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 Fp(){return p(this,null,function*(){let r,i;try{let h=yield Ue();r=h&&h.length}catch(h){}try{let h=yield Ge();i=h&&h.length}catch(h){}let e={microphone:r,camera:i},{isH264EncodeSupported:t,isVp8EncodeSupported:s,isH264DecodeSupported:n,isVp8DecodeSupported:o}=this.checkSystemResult.detail,a=Kt.basis(),c={webRTC:a.isWebRTCSupported,getUserMedia:a.isGetUserMediaSupported,webSocket:a.isWebSocketsSupported,screenShare:a.isScreenShareSupported,webAudio:a.isWebAudioSupported,h264Encode:t,h264Decode:n,vp8Encode:s,vp8Decode:o},d={browser:a.browser,os:a.os,trtc:c,devices:e},l={isWebCodecSupported:a.isWebCodecSupported,isMediaSessionSupported:a.isMediaSessionSupported,isWebTransportSupported:a.isWebTransportSupported};ee.uploadEvent({log:`trtcstats-${JSON.stringify(d)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(d)}`),ee.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(l)}`,userId:this.userId})})}function Rl(){return W(r=>{let i=new Zc;return function(e,t,s){return p(this,null,function*(){let n=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 C({code:A.INVALID_OPERATION,message:M({key:O.INVALID_JOIN})});if(this.checkDestroy(),i.isJoined({userId:this.userId,roomId:n,sdkAppId:this.sdkAppId,room:this}))throw new C({code:A.INVALID_OPERATION,message:M({key:O.REPEAT_JOIN,data:this.userId})});i.add({room:this,roomId:n}),this.role=e.role===21?"audience":"anchor",this._log.info(`Join() => joining room: ${n} useStringRoomId: ${this.useStringRoomId} scene: ${this.scene} role: ${this.role}`),T.emit(E.JOIN_START,{room:this,roomId:n,params:e}),this.checkSystemResult=yield Kt.checkSystemRequirementsInternal(),this.checkDestroy();let o=Le.getEnv();o||(o=$t.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(_n.OLD_CLOUD_LADDER)?o=$t.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(_n.WEBRTC)&&(o=$t.WEBRTC))),ee.setConfig({env:o,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:n}),Fp.call(this);let{isH264EncodeSupported:a,isVp8EncodeSupported:c}=this.checkSystemResult.detail;if(!Kt.isWebRTCSupported()||!a&&!c)throw new C({code:A.NOT_SUPPORTED,message:M({key:O.NOT_SUPPORTED_WEBRTC})});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Le.getEnv()&&(yield this.schedule(e,s));let d=yield r.call(this,e,t,s);return this.roomId=n,this._joinedTimestamp=Le.performanceNow(),T.emit(E.JOIN_SUCCESS,{room:this}),ee.uploadEvent({log:`stat-conv-${Number(dt)}-${location.hostname}`,userId:this.userId}),d}catch(d){throw i.delete({room:this,roomId:n}),T.emit(E.JOIN_FAILED,{room:this,error:d}),d}})}})}var Cl=()=>W(r=>function(...i){return p(this,null,function*(){T.emit(E.LEAVE_START,{room:this}),yield r.call(this),T.emit(E.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function yl(){return W(r=>function(...i){let e=r.apply(this,i);return i.forEach(t=>!t.isSubscribed&&t.subscribe(e)),e})}var Nl=Ie(ke(),1);var bl=Symbol("instance"),BN=Symbol("abortCtrl"),ed=Symbol("cacheResult"),qi=class{constructor(i,e,t){this.oldState=i,this.newState=e,this.action=t,this.aborted=!1}abort(i){this.aborted=!0,qs.call(i,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},Js=class extends Error{constructor(i,e,t){super(e),this.state=i,this.message=e,this.cause=t}};function Gp(r){return typeof r=="object"&&r&&"then"in r}var js=new Map;function td(r,i,e={}){return(t,s,n)=>{let o=e.action||s;if(!e.context){let c=js.get(t)||[];js.has(t)||js.set(t,c),c.push({from:r,to:i,action:o})}let a=n.value;n.value=function(...c){let d=this;if(e.context&&(d=te.get(typeof e.context=="function"?e.context.call(this,...c):e.context)),d.state===i)return d[ed];d.state instanceof qi&&d.state.action==e.abortAction&&d.state.abort(d);let l=null;if(Array.isArray(r)?r.length==0?d.state instanceof qi&&d.state.abort(d):(typeof d.state!="string"||!r.includes(d.state))&&(l=new Js(d._state,`${d.name} ${o} to ${i} failed: current state ${d._state} not in from config`)):r!==d.state&&(l=new Js(d._state,`${d.name} ${o} 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 h=d.state,_=new qi(h,i,o);qs.call(d,_);let f=y=>{var w;return d[ed]=y,_.aborted||(qs.call(d,i),(w=e.success)===null||w===void 0||w.call(this,d[ed])),y},R=y=>{let w=y instanceof Error?y.message:String(y);if(qs.call(d,h,y),e.fail)e.fail.call(this,new Js(d._state,`action '${o}' failed :${w}`,y instanceof Error?y:new Error(w)));else{if(e.ignoreError)return y;throw y}};try{let y=a.apply(this,c);return Gp(y)?y.then(f).catch(R):f(y)}catch(y){R(y)}}}}var Wp=(()=>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 qs(r,i){let e=this._state;this._state=r;let t=r.toString();r&&this.emit(t,e),this.emit(te.STATECHANGED,r,e,i),this.updateDevTools({value:r,old:e,err:i instanceof Error?i.message:String(i)})}var te=class extends Nl.default{constructor(i,e,t){super(),this.name=i,this.groupName=e,this._state=te.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[bl];s?this.name=s.name+"-"+s.count++:t[bl]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let i=Object.getPrototypeOf(this),e=js.get(i)||[],t=new Set,s=[],n=[],o=new Set,a=Object.getPrototypeOf(i);js.has(a)&&(a.stateDiagram.forEach(d=>t.add(d)),a.allStates.forEach(d=>o.add(d))),e.forEach(({from:d,to:l,action:h})=>{typeof d=="string"?s.push({from:d,to:l,action:h}):d.length?d.forEach(_=>{s.push({from:_,to:l,action:h})}):n.push({to:l,action:h})}),s.forEach(({from:d,to:l,action:h})=>{o.add(d),o.add(l),o.add(h+"ing"),t.add(`${d} --> ${h}ing : ${h}`),t.add(`${h}ing --> ${l} : ${h} \u{1F7E2}`),t.add(`${h}ing --> ${d} : ${h} \u{1F534}`)}),n.forEach(({to:d,action:l})=>{t.add(`${l}ing --> ${d} : ${l} \u{1F7E2}`),o.forEach(h=>{h!==d&&t.add(`${h} --> ${l}ing : ${l}`)})});let c=[...t];return Object.defineProperties(i,{stateDiagram:{value:c},allStates:{value:o}}),c}static get(i){let e;return typeof i=="string"?(e=te.instances.get(i),e||te.instances.set(i,e=new te(i,void 0,Object.create(te.prototype)))):(e=te.instances2.get(i),e||te.instances2.set(i,e=new te(i.constructor.name,void 0,Object.create(te.prototype)))),e}static getState(i){var e;return(e=te.get(i))===null||e===void 0?void 0:e.state}updateDevTools(i={}){Wp(te.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){qs.call(this,i)}};te.STATECHANGED="stateChanged";te.UPDATEAFSM="updateAFSM";te.INIT="[*]";te.ON="on";te.OFF="off";te.instances=new Map;te.instances2=new WeakMap;var Dl=Ie(ke());var le={SETUP_SUCCESS:"1",SETUP_FAILED:"5",CONNECTION_STATE_CHANGED:"2",CONNECTED:"3",DISCONNECTED:"5",RECONNECT_FAILED:"4"};var _t={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},vl=[_t.UPDATE_REMOTE_MUTE_STAT,_t.UPLINK_NETWORK_STATS,_t.USER_LIST_RES,_t.MUTE_RESULT,_t.SERVER_FIRST_PACKAGE_RECEIVED,_t.RECEIVE_CUSTOM_MSG],V={CLIENT_BANNED:"client-banned",CHANNEL_SETUP_RESULT:"channel-setup-result",CHANNEL_RECONNECT_RESULT:"channel-reconnect-result",JOIN_ROOM_RESULT:"join-room-result",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",UPLINK_NETWORK_STATS:"uplink-network-stats",UPDATE_REMOTE_MUTE_STAT:"update-remote-mute-stat",PUBLISH_RESULT:"publish-result",PUBLISH_STATE_CHANGE_RESULT:"publish-state-change-result",UNPUBLISH_RESULT:"unpublish-result",SUBSCRIBE_RESULT:"subscribe-result",SUBSCRIBE_CHANGE_RESULT:"subscribe-change-result",UNSUBSCRIBE_RESULT:"unsubscribe-result",UPDATE_OFFER_RESULT:"update-offer-result",START_PUBLISH_TENCENT_CDN_RES:"start-publish-tencent-cdn-res",STOP_PUBLISH_TENCENT_CDN_RES:"stop-publish-tencent-cdn-res",START_PUBLISH_GIVEN_CDN_RES:"start-publish-given-cdn-res",STOP_PUBLISH_GIVEN_CDN_RES:"stop-publish-given-cdn-res",START_MIX_TRANSCODE_RES:"start-mix-transcode-res",STOP_MIX_TRANSCODE_RES:"stop-mix-transcode-res",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"},j={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 ko=new Set;function Ol(r){let i=[...ko.values()].find(e=>e.room.userId===r&&!e.room.isJoined);return i||null}var Pr=class extends Dl.default{constructor(e){var s,n;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);this.room=e.room,this.race=g(e.race)?!0:e.race,(((n=(s=this.room.scheduleResult)==null?void 0:s.config)==null?void 0:n.keepAliveClient)||0)-ko.size>0&&this.room.enableSPC&&(this.keepAlive=!0,ko.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.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 p(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=L();let t=[this.connectWS({url:this._urlWithParam,isMain:!0,timeout:e})];this.race&&this._backupUrlWithParam!==this._urlWithParam&&t.push(this.connectWS({url:this._backupUrlWithParam,isMain:!1,timeout:e})),this._socketInUse=yield _s(t),this.unbindAndCloseSocket(this._socketInUse===this._socket?m.BACKUP:m.MAIN),this.emitConnectionStateChanged("CONNECTED")})}connectWS({url:e,timeout:t,isMain:s}){let n=new WebSocket(e);this.bindSocket(n),s?this._socket=n:this._backupSocket=n;let o=-1;return new Promise((a,c)=>{n.onclose=c,n.onerror=c,n.onopen=()=>a(n),t&&(o=setTimeout(()=>{this.unbindAndCloseSocket(s?m.MAIN:m.BACKUP),c(new C({code:A.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))},t))}).finally(()=>{n.onclose=null,n.onerror=null,n.onopen=null,clearTimeout(o)})}bindSocket(e){e.addEventListener("close",this.onclose),e.addEventListener("error",this.onerror),e.addEventListener("message",this.onmessage)}unbindSocket(e){e.removeEventListener("close",this.onclose),e.removeEventListener("error",this.onerror),e.removeEventListener("message",this.onmessage)}unbindAndCloseSocket(e){if(e===m.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(t){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(t){}this._backupSocket=null}}onclose(e){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?m.MAIN:m.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(m.MAIN),this.unbindAndCloseSocket(m.BACKUP),this._socketInUse=null,this.reconnect())}onmessage(e){if(!this.isConnected)return;this._lastMessageTime=Date.now(),this.bytesReceived+=$n(e.data);let t=JSON.parse(e.data),{cmd:s,data:n}=t,o=Object.values(_t),c=Object.keys(_t)[o.indexOf(s)],d=V[c];switch(vl.includes(s)||(this._log.debug(`received ${s} msg: ${e.data}`),d&&this._log.info(`Received event: [ ${d} ]`)),s){case _t.CHANNEL_SETUP_RESULT:{if(t.code===0)this._signalInfo.clientIp=n.clientIp,this._signalInfo.signalIp=n.signalInnerIp,n.svrTime&&kd(n.svrTime),this._log.info("ChannelSetup Success"),v.addSuccessEvent({key:521701,cost:L()-this._connnectStartTime}),this._connnectStartTime=-1,this.emit(le.SETUP_SUCCESS,{signalInfo:this._signalInfo});else{let l=new C({code:A.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:M({key:O.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error(`${t.code}, ${t.message}`),this.close(),v.addFailedEvent({key:521701,error:l}),this.emit(le.SETUP_FAILED,l)}break}case _t.JOIN_ROOM_RESULT:{t.code===0&&(this._signalInfo.relayIp=n.relayOuterIp,this._signalInfo.relayInnerIp=n.relayInnerIp,this._signalInfo.relayPort=n.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(d,{data:t});break}}reGetSignalChannelUrl(){return p(this,null,function*(){try{yt(!0),yield this.room.schedule(this.room.roomId);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(e){}})}reconnect(){return p(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:n,relayPort:o}=this._signalInfo,{data:a}=yield this.sendWaitForResponse({command:j.RECONNECT_WS,data:{roomId:e,useStringRoomId:t,relayInnerIp:n,relayOuterIp:s,relayPort:o},responseCommand:V.CHANNEL_RECONNECT_RESULT});a.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),v.addSuccessEvent({key:521702,cost:L()-this._connnectStartTime}),this._connnectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(v.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},n=JSON.stringify(s);return this._socketInUse.send(n),this.bytesSent+=$n(n),s.seq}}sendWaitForResponse({command:e,data:t,timeout:s=5e3,responseCommand:n,commandDesc:o,enableLog:a=!0}){return new Promise((c,d)=>{let l=setTimeout(()=>{this.off(n,h);let f=new C({code:A.API_CALL_TIMEOUT,message:M({key:O.API_CALL_TIMEOUT,data:{commandDesc:o,command:e}})});a&&this._log.warn(f),d(f)},s),h=f=>{f.data.seq===_&&(clearTimeout(l),this.off(n,h),c(f))};this.on(n,h);let _=this.send(e,t)})}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:s,retries:n=0,retryTimeout:o=0}=e;return Rt({retryFunction:this.sendWaitForResponse,onError:({retry:a})=>{this.isOnline?a():(this._log.warn(`retry ${s} when connected`),this.once(le.CONNECTED,a))},onRetrying:a=>{this._log.warn(`${t||s} timeout observed, retrying [${a}/${n}]`)},settings:{retries:n,timeout:o},context:this})(e)}getCurrentState(){return this._currentState}getSignalInfo(){return this._signalInfo}stopReconnection(){this._isReconnecting=!1,this._stopConnectRetry&&this._stopConnectRetry()}close(){this._log.info("closed"),ko.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(m.MAIN),this.unbindAndCloseSocket(m.BACKUP),this.emitConnectionStateChanged("DISCONNECTED")}destroy(){this.close(),this.destroyed=!0}stopKeepAliveIn(e=3600){if(this.keepAlive){this._log.info(`stopKeepAlive in ${e}s`);let t=setTimeout(()=>{this.keepAlive=!1,this._log.info(`close due to not used ${e}s`),this.close()},e*1e3),s=n=>{n instanceof qi&&n.action==="join"&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(t),this.room.off(te.STATECHANGED,s))};this.room.on(te.STATECHANGED,s)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info(`${this._currentState} -> ${e}`),this.emit(le.CONNECTION_STATE_CHANGED,{prevState:this._currentState,state:e}),this._currentState=e,e==="CONNECTED"?this.emit(le.CONNECTED):e==="DISCONNECTED"&&this.emit(le.DISCONNECTED))}};b([wt({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())}})],Pr.prototype,"connect",1);var Ml=Ie(ke());var id=0,rd=!1,xo=new Set,jp=r=>id>2&&!rd&&xo.size===0&&r,sd=!1,je=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 Ml.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,"_enableSEI");u(this,"_sei");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,this._enableSEI=i.enableSEI}beforeConnect(){this._prevTime<0&&(this._prevTime=L())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,v.addSuccessEvent({key:521705,cost:Math.min(L()-this._prevTime,30*1e3)})):this._isReconnecting&&v.addSuccessEvent({key:521706,cost:L()-this._prevTime}),this._prevTime=-1}catch(i){throw this._isFirstConnection?(this._isFirstConnection=!1,v.addFailedEvent({key:521705,error:i})):this._isReconnecting&&this._reconnectionCount>=3&&v.addFailedEvent({key:521706,error:i}),i}}initialize(){let i={encodedInsertableStreams:this._enableSEI&&Si,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(),this._sei&&(this._sei.destroy(),this._sei=null),xo.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 C({code:A.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return rt;let i=null;if(this._isUplink){if(!Ti()||this._peerConnection.getSenders().length===0)return rt;i=this._peerConnection.getSenders()[0].transport}else{if(!Pi()||this._peerConnection.getReceivers().length===0)return rt;i=this._peerConnection.getReceivers()[0].transport}return i?i.state:rt}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}`,n=new C({message:s,code:A.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",n)}(i.target.connectionState===se.CONNECTED||i.target.connectionState===se.COMPLETED)&&(this.logSelectedCandidate(),ee.logSuccessEvent({userId:this._room.userId,eventType:xe.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(i){return i===this._currentState?!1:(i==="CONNECTED"?(id=0,rd=!1,sd=!0,xo.add(this)):xo.delete(this),T.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 p(this,null,function*(){if(!this._peerConnection)return;let i=yield this._peerConnection.getStats();for(let[,e]of i)if(gi(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(o),n(),i())},s=({room:a})=>{a===this._room&&(clearTimeout(o),n(),e(new C({code:A.API_CALL_ABORTED,message:M({key:O.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{T.off(E.LEAVE_SUCCESS,s,this),this._emitter.off("connection-state-changed",t,this)},o=setTimeout(()=>{n();let a=new C({code:A.API_CALL_TIMEOUT,message:"connection timeout"});id+=1,jp(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),rd=!0,this._emitter.emit("firewall-restriction")),e(a)},Yr);T.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(le.CONNECTED,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=Ht()){this._log.warn(`SDK has tried reconnect for ${this._reconnectionCount} times, but all failed, please check your network`),this.stopReconnection();let i=new C({code:this._isUplink?A.UPLINK_RECONNECTION_FAILED:A.DOWNLINK_RECONNECTION_FAILED,message:M({key:this._isUplink?O.UPLINK_RECONNECTION_FAILED:O.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(le.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 cd=Ie(ad());var ce=function(r){return cd.default.parse(r)},tt=function(r){return cd.default.write(r)},Bl=function(r){let i=ce(r);return i.media.forEach(e=>{e.type===m.AUDIO&&e.fmtp.forEach(t=>{t.config+=";sprop-stereo=1;stereo=1"})}),tt(i)};function $l(r){let i=ce(r);return i.media.forEach(e=>{var t,s;if(e.type===m.VIDEO){let n=new Set;e.rtp.forEach(({payload:a,codec:c})=>c==="H264"&&n.add(a)),e.fmtp.forEach(({payload:a,config:c})=>{let d=c.match(/apt=(\d+)/);d&&d[1]&&n.has(Number(d[1]))&&n.add(a)});let o=({payload:a})=>!n.has(a);e.rtp=e.rtp.filter(o),e.rtcpFb=(t=e.rtcpFb)==null?void 0:t.filter(o),e.fmtp=e.fmtp.filter(o),e.payloads=(s=e.payloads)==null?void 0:s.split(" ").filter(a=>!n.has(Number(a))).join(" ")}}),tt(i)}function Po(r){return Object.keys(r).filter(i=>r[i])}var ud=class extends je{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 ti(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new Lt(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new br(this._room,this)}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 Ei(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,s,n;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(s=this.remoteVideoTrack)==null||s.onFlagChanged(),(n=this.remoteAuxiliaryTrack)==null||n.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===m.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(e){var n,o;let t=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&t!==e&&((n=this.remoteVideoTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e}),(o=this.remoteAuxiliaryTrack)==null||o.emit("connection-state-changed",{prevState:t,state:e})),s}onTrack(e){let t=e.streams[0],{track:s}=e,n=t.id===Kr?m.MAIN:m.AUXILIARY;this._log.debug(`ontrack ${n} ${s.kind}`);let o=m.AUDIO;s.kind===m.VIDEO&&(o=n===m.MAIN?m.VIDEO:m.AUXILIARY);let a=this.remoteAudioTrack;o===m.VIDEO?a=this.remoteVideoTrack:o===m.AUXILIARY&&(a=this.remoteAuxiliaryTrack),a.setInputMediaStreamTrack(s)}addRRTRLine(e){let t=e.split(`\r
36
36
  `),s=new Map;t.forEach((o,a)=>{/^a=rtcp-fb:/.test(o)&&t[a+1]&&!/^a=rtcp-fb:/.test(t[a+1])&&s.set(a+1,`${o.match(/^a=rtcp-fb:\d+/)[0]} rrtr`)});let n=[...s];for(let o=0;o<n.length;o++){let[a,c]=n[o];t.splice(a+o,0,c)}return t.join(`\r
37
37
  `)}addSPSDescription(e){let t=ce(e);return t.media.forEach(s=>{s.type===m.VIDEO&&s.fmtp.forEach(n=>{n.config+=";sps-pps-idr-in-keyframe=1"})}),tt(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(n=>{!n.ext||(n.ext=n.ext.filter(o=>!t.includes(o.uri)))}),tt(s)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return p(this,null,function*(){var s,n;try{if((((s=this._peerConnection)==null?void 0:s.connectionState)===se.NEW||((n=this._peerConnection)==null?void 0:n.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 o="subscribe_change";Object.values(e).find(a=>a===!0)||(o="unsubscribe"),yield this.sendSubscription(o,e)}else this.initialize(),yield this.connect(e)}catch(o){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(`${o.message} ${JSON.stringify(this.muteState)}`),new C({code:A.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):o}})}unsubscribe(s){return p(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 n=N({},this.subscribeState);e.forEach(a=>{switch(a.mediaType){case 1:n.audio=!1;break;case 4:n.video=!1;break;case 8:n.smallVideo=!1;break;case 2:n.auxiliary=!1;break;default:break}});let o="subscribe_change";Object.values(n).find(a=>a===!0)||(o="unsubscribe"),this._log.info(`${o==="unsubscribe"?o:"subscribe"} ${t} [${Po(n)}]`),yield this.sendSubscription(o,n),o==="unsubscribe"&&(this.closePeerConnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"))})}sendSubscription(e,t=this.subscribeState){let s={srcTinyId:this.tinyId,srcUserId:this.userId},n=j.UNSUBSCRIBE,o=V.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(s={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},n=j.SUBSCRIBE_CHANGE,o=V.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:n,data:s,responseCommand:o,timeout:1e4}).then(({data:a})=>{if(a.code!==0){let c=new C({code:a.code,message:M({key:O.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(c),c}})}connect(){return p(this,arguments,function*(e=this.subscribeState){try{yield this.exchangeSDP(e),yield this.waitForPeerConnectionConnected()}catch(t){throw this.closePeerConnection(!0),t}})}exchangeSDP(e){return p(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,n={type:t,sdp:s,srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo},o=yield this._signalChannel.sendWaitForResponse({command:j.SUBSCRIBE,commandDesc:"exchange sdp",data:n,responseCommand:V.SUBSCRIBE_RESULT,timeout:da});if(!this._peerConnection){let a=new C({code:A.INVALID_OPERATION,message:M({key:O.CONNECTION_CLOSED})});throw this._log.warn(a),a}yield this.onSubscribeResult(o),this._isSDPExchanging=!1}catch(t){throw this._isSDPExchanging=!1,t}})}createOffer(){return p(this,null,function*(){let e={voiceActivityDetection:!1};Ke()&&this._sdpSemantics===li?(this._peerConnection.addTransceiver(m.AUDIO,{direction:q.RECVONLY}),this._peerConnection.addTransceiver(m.VIDEO,{direction:q.RECVONLY}),this._peerConnection.addTransceiver(m.VIDEO,{direction:q.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:s}=yield Gn();s||(this._log.warn("remove h264 desc from sdp"),t.sdp=$l(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=Bl(t.sdp),this._sdpSemantics===li&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this._peerConnection.setLocalDescription(t)})}onSubscribeResult(e){return p(this,null,function*(){let{code:t,message:s=""}=e&&e.data||{},{type:n,sdp:o}=e&&e.data&&e.data.data||{};if(t===Di)throw new C({code:A.NOT_SUPPORTED_H264,message:M({key:O.NOT_SUPPORTED_H264DECODE})});try{if(t!==0)throw new C({code:t,message:M({key:O.EXCHANGE_SDP_FAILED,data:{errMsg:s}})});this._log.debug(`accept remote answer: ${o}`),yield this._peerConnection.setRemoteDescription({type:n,sdp:o}),this._sei&&(this._sei.handleEncodedStreams(),this._sei.onSEIMessage=a=>{this._emitter.emit("sei-message",P(N({},a),{userId:this.userId}))}),this.updateSSRC(o)}catch(a){throw this._log.error(a),a}})}updateSSRC(e){try{ce(e).media.forEach(s=>{if(!!s.ssrcs)if(s.type===m.AUDIO){let n=s.ssrcs.find(o=>{var a;return(a=o.value)==null?void 0:a.includes(Kr)});n&&(this.ssrc.audio=Number(n.id))}else{let n=s.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(Kr)}),o=s.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(sa)});n&&(this.ssrc.video=Number(n.id)),o&&(this.ssrc.auxiliary=Number(o.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 p(this,null,function*(){if(!(Ee(ud.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=bt(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}},Qs=ud;b([W(r=>function(...i){return new Promise((e,t)=>{let s=n=>{this._emitter.off("closed",s),t(new C({code:A.API_CALL_ABORTED,message:M({key:O.CONNECTION_ABORTED,data:n})}))};this._emitter.on("closed",s),r.apply(this,i).then(e,t).finally(()=>{this._emitter.off("closed",s)})})})],Qs.prototype,"subscribe",1),b([yr(je.prototype.afterConnect),no(je.prototype.beforeConnect)],Qs.prototype,"connect",1);var dd=Qs;var Fl={voiceActivityDetection:!1},ld=class extends je{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 isMainStreamPublished(){return!!(this.localMainAudioTrack||this.localMainVideoTrack)}get isAuxStreamPublished(){return!!(this.localAuxVideoTrack||this.localAuxAudioTrack)}get publishState(){var t,s,n,o;let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let a=this._peerConnection.getSenders();a&&(Nt()?(e.audio=!!((t=a[0])!=null&&t.track),e.bigVideo=!!((s=a[1])!=null&&s.track),e.smallVideo=!!((n=a[2])!=null&&n.track),e.auxVideo=!!((o=a[3])!=null&&o.track)):a.forEach(c=>{c.track&&(c.track.kind===m.AUDIO?e.audio=!0:(e.bigVideo=!0,this._room.videoManager.hasSmall&&(e.smallVideo=!0)))}))}return e}initialize(){super.initialize(),this.installEvents()}reset(){this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this.uninstallEvents()}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this._emitter.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this._emitter.on("connection-state-changed",this.handleConnectionStateChange,this)}uninstallEvents(){this._emitter.off("connection-state-changed",this.handleConnectionStateChange,this)}emitConnectionStateChangedEvent(e,t){var o,a,c;let s=this._currentState,n=super.emitConnectionStateChangedEvent(e);return n&&s!==e&&(t?t.emit("connection-state-changed",{prevState:s,state:e}):((o=this.localMainVideoTrack)==null||o.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}))),n}publish(n){return p(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:s}){var a;this._peerConnection||this.initialize(),e&&(this._publishingLocalAudioTrack=e),t&&(this._publishingLocalVideoTrack=t),this._isPublishingAux=s;let o;t&&!s&&t.small&&(o=this._room.videoManager.smallTrack),this.sendMediaSettings(),Ke()?yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:o,isAuxiliary:s}):yield this.publishByAddTrack({localAudioTrack:e,localVideoTrack:t,smallTrack:o}),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)),(a=this._sei)==null||a.handleEncodedStreams(),this.installTrackMuteEvents(e,t),this.sendMutedFlag()})}publishByTransceiver(o){return p(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:s,isAuxiliary:n}){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||m.AUDIO,{direction:q.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(n?m.VIDEO:c||m.VIDEO,{direction:q.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(s||m.VIDEO,{direction:q.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(n?c||m.VIDEO:m.VIDEO,{direction:q.SENDONLY,streams:[a]}),yield this.connect();else{let h=[];if(d&&(l[0].sender.track||h.push(0),yield l[0].sender.replaceTrack(d),yield this.setBandwidth({bandwidth:(e==null?void 0:e.profile.bitrate)||40,type:m.AUDIO})),c){let _=n?3:1;yield l[_].sender.replaceTrack(c),yield this.setBandwidth({bandwidth:t.profile.bitrate,type:m.VIDEO,videoType:n?m.AUXILIARY:m.BIG}),h.push(_),s&&(yield l[2].sender.replaceTrack(s),yield this.setBandwidth({bandwidth:t.small.bitrate,type:m.VIDEO,videoType:m.SMALL}),h.push(2))}yield this.setTransceiverDirection(q.SENDONLY,h),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(n){return p(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:s}){this._log.info("publish by addtrack");let o=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)),o&&(yield this.addTrack(t));return}let c=new MediaStream;if(a&&c.addTrack(a),o&&c.addTrack(o),a&&this._peerConnection.addTrack(a,c),o&&(this._peerConnection.addTrack(o,c),s)){let d=new MediaStream;d.addTrack(s),this._peerConnection.addTrack(s,d)}yield this.connect()})}enableSmall(e){return p(this,null,function*(){let t=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield t[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.setTransceiverDirection(q.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(q.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()})}installTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.on("mute",this.sendMutedFlag,this),t==null||t.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.off("mute",this.sendMutedFlag,this),t==null||t.off("unmute",this.sendMutedFlag,this))})}unpublish(s){return p(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){if(!Nt()){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 n=t&&t===this.localAuxVideoTrack,o=t==null?void 0:t.outMediaTrack,a=this._peerConnection.getSenders(),c=[];e&&(yield a[0].replaceTrack(null),c.push(0),n?this.localAuxAudioTrack=null:this.localMainAudioTrack=null),o&&(n?(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(q.INACTIVE,c),yield this.doPublishChange(!1)):yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),t==null||t.emit("connection-state-changed",{prevState:this._currentState,state:"DISCONNECTED"})})}doPublishChange(e=!0){return p(this,null,function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},s=yield this._signalChannel.sendWaitForResponse({command:j.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:j.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:n,localAuxVideoTrack:o}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?o=this._publishingLocalVideoTrack:n=this._publishingLocalVideoTrack),vt){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(n&&n.outMediaTrack){let a=n.outMediaTrack.getSettings();this._mediaSettings.videoWidth=a.width||0,this._mediaSettings.videoHeight=a.height||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=n.profile.bitrate*1e3,n.small&&(this._mediaSettings.smallVideoWidth=n.small.width,this._mediaSettings.smallVideoHeight=n.small.height,this._mediaSettings.smallVideoFps=n.small.frameRate,this._mediaSettings.smallVideoBps=n.small.bitrate*1e3)}if(o&&o.outMediaTrack){let a=o.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=a.width||0,this._mediaSettings.auxVideoHeight=a.height||0,this._mediaSettings.auxVideoFps=a.frameRate||0,this._mediaSettings.auxVideoBps=o.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),n&&n.outMediaTrack&&(this._mediaSettings.videoWidth=n.profile.width,this._mediaSettings.videoHeight=n.profile.height,this._mediaSettings.videoFps=n.profile.frameRate,this._mediaSettings.videoBps=n.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:j.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 p(this,null,function*(){var s;if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is adding ${e.kind} track to current published local ${t?m.AUXILIARY:m.MAIN} stream`),(s=this._sei)==null||s.handleEncodedStreams(),Ke()?yield this.addTrackByTransceiver(e,t):yield this.addTrackBySender(e)})}addTrackByTransceiver(e,t){return p(this,null,function*(){var n;if(!e.mediaTrack)return;let s=this._peerConnection.getTransceivers();if(e.kind===m.AUDIO)yield s[0].sender.replaceTrack(e.outMediaTrack);else{let o=t?3:1;yield s[o].sender.replaceTrack(e.outMediaTrack),o===1&&((n=this.localMainVideoTrack)==null?void 0:n.small)&&(yield s[2].sender.replaceTrack(this._room.videoManager.smallTrack)),s[o].direction===q.INACTIVE&&(yield this.setTransceiverDirection(q.SENDONLY,[o]))}this.updateMediaSettings(),yield this.doPublishChange()})}addTrackBySender(e){return p(this,null,function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;Nt()&&this._peerConnection.getTransceivers().findIndex(n=>n.direction==="stopped")>=0&&(this._log.warn("transceiver is stopping, negotiate sdp first"),yield this.updateOffer("remove",t));let s=this._peerConnection.getSenders().find(n=>n.track&&n.track.kind===t.kind);if(s&&s.track){this._log.warn("sender already exists, remove sender first");let n=s.track;this.removeSender(s),yield this.updateOffer("remove",n)}if(t&&this._peerConnection.addTrack(t,new MediaStream([t])),t.kind===m.VIDEO&&e instanceof ae&&e.small){let n=new MediaStream,{smallTrack:o}=this._room.videoManager;n.addTrack(o),this._peerConnection.addTrack(o,n)}yield this.updateOffer("add",t)})}isNeedToResetOfferOrder(){if(this._sdpSemantics===er||!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===m.VIDEO)return!0;return!1}removeSender(e){let t=null;Nt()&&(t=this._peerConnection.getTransceivers().find(s=>s.sender&&s.sender.track===e.track)),this._peerConnection.removeTrack(e),t&&G(t.stop)&&(this._log.info("stop transceiver"),t.stop())}removeTrack(e){return p(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is removing ${e.kind} track from current published local ${t?m.AUXILIARY:m.MAIN} stream`),Ke()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e)})}removeTrackByTransceiver(e,t){return p(this,null,function*(){if(!e.outMediaTrack)return;let s=this._peerConnection.getTransceivers();if(e.kind===m.AUDIO)yield s[0].sender.replaceTrack(null);else{let n=t?3:1;yield s[n].sender.replaceTrack(null),n===1&&e.small&&(yield s[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(q.INACTIVE,[n])}this.updateMediaSettings(),yield this.doPublishChange()})}setTransceiverDirection(e,t){return p(this,null,function*(){if(!Y)return;let s=!1,n=!1;this._log.info(`setting transceiver ${t.join(",")} direction to ${e}`);let o=this._peerConnection.getTransceivers();if(t.forEach(d=>{o[d].direction!==e&&(o[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
38
38
  `).map(d=>{if(d.match(new RegExp(`a=(${q.INACTIVE}|${q.RECVONLY}|${q.SENDONLY})`))&&a++,t.includes(a)){if(e===q.INACTIVE&&d.includes(`a=${q.RECVONLY}`))return n=!0,`a=${e}`;if(e===q.SENDONLY&&d.includes(`a=${q.INACTIVE}`))return n=!0,`a=${q.RECVONLY}`}return d}).join(`\r
@@ -40,7 +40,7 @@ ${s.stack}`),!1}},r};var yo=new WeakMap;function _l(r,i){return W((e,t)=>functio
40
40
  `:c)),e}updateAudioBandwidthRestriction(e,t){let s="AS";return Y&&(s="TIAS",t=t*1e3),e=e.replace(/m=audio (.*)\r\nc=IN (.*)\r\n/,`m=audio $1\r
41
41
  c=IN $2\r
42
42
  b=${s}:${t}\r
43
- `),e}removeBandwidthRestriction(e){return e.replace(/b=AS:.*\r\n/,"").replace(/b=TIAS:.*\r\n/,"")}removeVideoOrientation(e){return e.replace(/urn:3gpp:video-orientation/,"")}connect(){return p(this,null,function*(){try{yield this.exchangeSDP(),yield this.waitForPeerConnectionConnected()}catch(e){throw this.closePeerConnection(!0),this.uninstallEvents(),e}})}exchangeSDP(){return p(this,null,function*(){try{yield this.createOffer(),this._log.info("createOffer success, sending offer to remote server"),yield this.doExchangeSDP()}catch(e){throw e}})}createOffer(){return p(this,null,function*(){try{let e=yield this._peerConnection.createOffer(Fl);yield this._peerConnection.setLocalDescription(e),e.sdp&&this.updateSSRC(e.sdp)}catch(e){throw e}})}doExchangeSDP(){let e={command:j.PUBLISH,responseCommand:V.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof Je||this.localAuxVideoTrack instanceof Je,state:this.publishState,constraintConfig:this._mediaSettings},enableLog:!1};return this._log.debug(`sending sdp offer: ${e.data.sdp}`),this._signalChannel.sendWaitForResponse(e).then(t=>{let{code:s,message:n,data:o}=t.data;return s===0?this.acceptAnswer(o):this.checkPublishResultCode(s,n)})}setSDPDirection(e,t,s="all"){let n=ce(e);return n.media.forEach(o=>{(s==="all"||o.type===s)&&(o.direction=t)}),tt(n)}acceptAnswer(e){return p(this,null,function*(){var t,s,n,o,a;try{let c;if(this._publishingLocalAudioTrack||this._publishingLocalVideoTrack||this.isMainStreamPublished){let h=((t=this._publishingLocalVideoTrack)==null?void 0:t.profile.bitrate)||((s=this.localMainVideoTrack)==null?void 0:s.profile.bitrate),_=((n=this._publishingLocalAudioTrack)==null?void 0:n.profile.bitrate)||((o=this.localMainAudioTrack)==null?void 0:o.profile.bitrate);if(h){let f=this._isPublishingAux?m.AUXILIARY:m.BIG;c=yield this.setBandwidth({bandwidth:h,type:m.VIDEO,sdp:c,videoType:f})}_&&(c=yield this.setBandwidth({bandwidth:_,type:m.AUDIO,sdp:c}))}if(c=this.removeVideoOrientation(e.sdp),(a=this._publishingLocalVideoTrack)!=null&&a.small){let{smallStreamConfig:h}=this._room;c=yield this.setBandwidth({bandwidth:this._publishingLocalVideoTrack.small.bitrate||h.bitrate,type:m.VIDEO,videoType:m.SMALL,sdp:c})}let l={type:e.type,sdp:c};yield this._peerConnection.setRemoteDescription(l),this._log.debug(`accepted answer: ${c}`)}catch(c){throw this._log.error(`failed to accept remote answer ${c}`),c}})}sendMutedFlag(e){var n,o,a;if(e===this.localAuxAudioTrack||e===this.localAuxVideoTrack)return;let s={audio:!!((n=this.localMainAudioTrack)!=null&&n.muted),bigVideo:!!((o=this.localMainVideoTrack)!=null&&o.muted),auxVideo:!!((a=this.localAuxVideoTrack)!=null&&a.muted)};this._log.info(`send muted state: ${JSON.stringify(s)}`),this._signalChannel.send(j.UPDATE_MUTE_STAT,s)}getIsReconnecting(){return this._isReconnecting}reconnect(){return p(this,null,function*(){if(!(Ee(ld.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:j.UNPUBLISH,responseCommand:V.UNPUBLISH_RESULT,enableLog:!1}),this.closePeerConnection(),this.initialize(),this.isMainStreamPublished&&(yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0})),this._log.warn("reconnect() uplink reconnect successfully"),this.stopReconnection()}catch(t){let s=bt(this._reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${s/1e3}s`),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},s)}})}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&T.emit(E.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{ce(e).media.forEach((s,n)=>{if(s.type===m.AUDIO){let o=s.ssrcs&&s.ssrcs[0];o&&(this.ssrc.audio=Number(o.id))}else{if(this._sdpSemantics===er&&s.ssrcGroups){s.ssrcGroups.forEach((a,c)=>{let d=Number(a.ssrcs.split(" ")[0]);c===0?this.ssrc.video=d:c===1&&(this.ssrc.small=d)});return}let o=s.ssrcs&&s.ssrcs[0];if(!o)return;switch(n){case 1:this.ssrc.video=Number(o.id);break;case 2:this.ssrc.small=Number(o.id);break;case 3:this.ssrc.auxiliary=Number(o.id);break;default:break}}})}catch(t){}}getVideoTrackId(e=m.VIDEO){if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===m.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===m.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===m.VIDEO){let t=this.localMainVideoTrack.mediaTrack;if(t)return t.id}if(this.localAuxVideoTrack&&e===m.AUXILIARY){let t=this.localAuxVideoTrack.mediaTrack;if(t)return t.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(e!==0)throw e===Di?(this._log.error(ge.NOT_SUPPORTED_H264ENCODE),new C({code:A.NOT_SUPPORTED_H264,message:M({key:O.NOT_SUPPORTED_H264ENCODE})})):new C({code:A.UNKNOWN,message:M({key:O.SIGNAL_RESPONSE_FAILED,data:{signalResponse:V.PUBLISH_RESULT,code:e,message:t}})})}sendSEI(e,t){var s;(s=this._sei)==null||s.push(e,t)}},zs=ld;b([W(r=>function(...i){return new Promise((e,t)=>{let s=n=>{this._emitter.off("closed",s),t(new C({code:A.API_CALL_ABORTED,message:M({key:O.CONNECTION_ABORTED,data:n})}))};this._emitter.on("closed",s),r.apply(this,i).then(e,t).finally(()=>{this._emitter.off("closed",s)})})})],zs.prototype,"publish",1),b([yr(je.prototype.afterConnect),no(je.prototype.beforeConnect)],zs.prototype,"connect",1);var wo=zs;var Ks=class{constructor(i,e){this.room=i;u(this,"_log");u(this,"_prevReportTime");u(this,"_prevReport",{});u(this,"_prevEncoderImplementation");u(this,"_prevQualityLimitationReason");u(this,"_prevAuxQualityLimitationReason");u(this,"_prevDecoderImplementationMap",new Map);u(this,"totalBytesSent",0);u(this,"totalBytesReceived",0);u(this,"_spcStats",null);this._log=e,this._prevReportTime=0,this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevAuxQualityLimitationReason=""}get statInterval(){return this._prevReportTime===0?2:(Date.now()-this._prevReportTime)/1e3}getSenderStats(i){return p(this,null,function*(){let e={audio:{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0},video:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},small:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},auxiliary:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},rtt:0},t=i.getPeerConnection(),s=i.getSSRC();if(t)try{if((this._spcStats||(yield t.getStats())).forEach(o=>{var a;if(o.type==="outbound-rtp")if((o.mediaType||o.kind)===m.VIDEO){let d,l;if(o.ssrc===s.video?(d=m.VIDEO,l=i.localMainVideoTrack):o.ssrc===s.small?d=m.SMALL:o.ssrc===s.auxiliary&&(l=i.localAuxVideoTrack,d=m.AUXILIARY),!d)return;e[d].bytesSent=o.bytesSent,e[d].packetsSent=o.packetsSent,e[d].framesEncoded=o.framesEncoded,g(o.keyFramesEncoded)||(e[d].keyFramesEncoded=o.keyFramesEncoded),g(o.nackCount)||(e[d].nackCount=o.nackCount),g(o.pliCount)||(e[d].pliCount=o.pliCount),g(o.retransmittedPacketsSent)||(e[d].retransmittedPacketsSent=o.retransmittedPacketsSent),g(o.totalEncodeTime)||(e[d].totalEncodeTime=o.totalEncodeTime),g(o.totalPacketSendDelay)||(e[d].totalPacketSendDelay=o.totalPacketSendDelay),o.ssrc===s.video?(!g(o.encoderImplementation)&&this._prevEncoderImplementation!==o.encoderImplementation&&(this._log.info(`encoderImplementation change to ${o.encoderImplementation}`),this._prevEncoderImplementation=o.encoderImplementation),!g(o.qualityLimitationReason)&&o.bytesSent!==0&&this._prevQualityLimitationReason!==o.qualityLimitationReason&&(this._log.info(`qualityLimitationReason change to ${o.qualityLimitationReason}`),this._prevQualityLimitationReason=o.qualityLimitationReason)):o.ssrc===s.auxiliary&&!g(o.qualityLimitationReason)&&o.bytesSent!==0&&this._prevAuxQualityLimitationReason!==o.qualityLimitationReason&&(this._log.info(`aux qualityLimitationReason change to ${o.qualityLimitationReason}`),this._prevAuxQualityLimitationReason=o.qualityLimitationReason)}else e.audio.bytesSent=o.bytesSent,e.audio.packetsSent=o.packetsSent;else o.type==="candidate-pair"?gi(o)&&re(o.currentRoundTripTime)&&(e.rtt=Math.floor(o.currentRoundTripTime*1e3),this.totalBytesSent=o.bytesSent):o.type==="media-source"&&(o.kind===m.AUDIO?(e.audio.audioLevel=o.audioLevel||0,e.audio.totalAudioEnergy=o.totalAudioEnergy||0):o.kind===m.VIDEO&&(o.trackIdentifier===i.getVideoTrackId(m.VIDEO)?e.video.fpsCapture=o.framesPerSecond:o.trackIdentifier===i.getVideoTrackId(m.AUXILIARY)?e.auxiliary.fpsCapture=o.framesPerSecond:e.small.fpsCapture=o.framesPerSecond));if(!g(o.audioLevel)&&((a=i.localMainAudioTrack)==null?void 0:a.mediaTrack)&&o.trackIdentifier===i.localMainAudioTrack.mediaTrack.id&&(e.audio.audioLevel=o.audioLevel||0),!g(o.frameWidth)){let c=m.SMALL;o.trackIdentifier===i.getVideoTrackId(m.VIDEO)||o.ssrc===s.video?c=m.VIDEO:(o.trackIdentifier===i.getVideoTrackId(m.AUXILIARY)||o.ssrc===s.auxiliary)&&(c=m.AUXILIARY),e[c].frameWidth=o.frameWidth,e[c].frameHeight=o.frameHeight,e[c].framesSent=o.framesSent}}),i.localMainAudioTrack){let o=i.localMainAudioTrack.getInternalAudioLevel();e.audio.micAudioLevel=o,e.audio.audioLevel===0&&(e.audio.audioLevel=o)}this.totalBytesSent||(this.totalBytesSent+=e.audio.bytesSent+e.video.bytesSent+e.auxiliary.bytesSent)}catch(n){this._log.warn(`failed to getStats on sender connection ${n}`)}return e})}getReceiverStats(i){return p(this,null,function*(){let e={tinyId:i.tinyId,userId:i.userId,rtt:0,hasAudio:!1,hasVideo:!1,hasAuxiliary:!1,isSmallSubscribed:!1,audio:{bytesReceived:0,packetsReceived:0,packetsLost:0,p2pDelay:0,totalJitter:0,totalJitterCount:0,audioLevel:0,totalAudioEnergy:0,insertedSamplesForDeceleration:0,removedSamplesForAcceleration:0},video:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0},auxiliary:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0}},t=i.getPeerConnection();if(t)try{let{ssrc:s}=i,{muteState:n,subscribeState:o}=i;(this._spcStats||(yield t.getStats())).forEach(c=>{if(c.type==="inbound-rtp")if((c.mediaType||c.kind)===m.AUDIO){if(c.ssrc!==s.audio||!n.hasAudio)return;e.audio.packetsReceived=c.packetsReceived,e.audio.bytesReceived=c.bytesReceived,e.audio.packetsLost=c.packetsLost,c.insertedSamplesForDeceleration&&(e.audio.insertedSamplesForDeceleration=c.insertedSamplesForDeceleration),c.removedSamplesForAcceleration&&(e.audio.removedSamplesForAcceleration=c.removedSamplesForAcceleration);let{remoteAudioTrack:l}=i;l.stat.packetsReceived=c.packetsReceived,l.stat.bytesReceived=c.bytesReceived,l.stat.packetsLost=c.packetsLost,e.audio.p2pDelay=l.stat.end2EndDelay,c.jitterBufferDelay&&(e.audio.totalJitter=c.jitterBufferDelay,e.audio.totalJitterCount=c.jitterBufferEmittedCount),e.hasAudio=!0}else{if(Y&&c.bytesReceived===0)return;let l;c.ssrc===s.video&&n.hasVideo&&(e.video.packetsReceived=c.packetsReceived,e.video.bytesReceived=c.bytesReceived,e.video.packetsLost=c.packetsLost,e.video.framesReceived=c.framesReceived,e.video.framesDecoded=c.framesDecoded,e.video.fpsDecoded=c.framesPerSecond,e.hasVideo=!0,l=i.remoteVideoTrack,n.hasSmall&&o.smallVideo&&(e.isSmallSubscribed=!0),c.decoderImplementation&&(!this._prevDecoderImplementationMap.has(e.userId)||this._prevDecoderImplementationMap.get(e.userId)!==c.decoderImplementation)&&(this._log.info(`${e.userId} decoderImplementation change to ${c.decoderImplementation}`),this._prevDecoderImplementationMap.set(e.userId,c.decoderImplementation))),c.ssrc===s.auxiliary&&n.hasAuxiliary&&(e.auxiliary.packetsReceived=c.packetsReceived,e.auxiliary.bytesReceived=c.bytesReceived,e.auxiliary.packetsLost=c.packetsLost,e.auxiliary.framesReceived=c.framesReceived,e.auxiliary.framesDecoded=c.framesDecoded,e.auxiliary.fpsDecoded=c.framesPerSecond,l=i.remoteAuxiliaryTrack,e.hasAuxiliary=!0),l&&(l.stat.packetsReceived=c.packetsReceived,l.stat.bytesReceived=c.bytesReceived,l.stat.packetsLost=c.packetsLost,l.stat.framesReceived=c.framesReceived,l.stat.framesDecoded=c.framesDecoded,c.jitterBufferDelay&&(l.stat.jitterBufferDelay=Math.floor(c.jitterBufferDelay/c.jitterBufferEmittedCount*1e3)))}else c.type==="candidate-pair"&&gi(c)&&re(c.currentRoundTripTime)&&(e.rtt=Math.floor(c.currentRoundTripTime*1e3),this.totalBytesReceived=c.bytesReceived);g(c.frameWidth)||((c.trackIdentifier===i.getMainStreamVideoTrackId()||c.ssrc===s.video)&&(e.video.frameWidth=c.frameWidth,e.video.frameHeight=c.frameHeight,i.remoteVideoTrack.stat.frameWidth=c.frameWidth,i.remoteVideoTrack.stat.frameHeight=c.frameHeight),(c.trackIdentifier===i.getAuxStreamVideoTrackId()||c.ssrc===s.auxiliary)&&(e.auxiliary.frameWidth=c.frameWidth,e.auxiliary.frameHeight=c.frameHeight,i.remoteAuxiliaryTrack.stat.frameWidth=c.frameWidth,i.remoteAuxiliaryTrack.stat.frameHeight=c.frameHeight)),!g(c.audioLevel)&&i.muteState.audioAvailable&&i.remoteAudioTrack.mediaTrack&&c.trackIdentifier===i.remoteAudioTrack.mediaTrack.id&&(e.audio.audioLevel=c.audioLevel||0,e.audio.totalAudioEnergy=c.totalAudioEnergy||0)}),e.audio.audioLevel===0&&i.muteState.audioAvailable&&(e.audio.audioLevel=i.remoteAudioTrack.getInternalAudioLevel()||0),this.totalBytesReceived||(this.totalBytesReceived+=e.audio.bytesReceived+e.video.bytesReceived+e.auxiliary.bytesReceived)}catch(s){this._log.warn(`failed to getStats on receiver connection ${s}`)}return e})}getStats(i,e){return p(this,null,function*(){let t={},s=[];if(this.room.singlePC){let n=this.room.singlePC.getPeerConnection();if(!n)return{senderStats:t,receiverStats:s};let o=L(),a=yield n.getStats(),c=L();c-o>2e3&&this._log.warn(`getStats cost ${c-o}ms`);let d=[],l=new Set(["inbound-rtp","outbound-rtp","track","candidate-pair","media-source"]);a.forEach(h=>l.has(h.type)&&d.push(h)),this._spcStats=d}i&&(t=yield this.getSenderStats(i));for(let[n,o]of e){let a=yield this.getReceiverStats(o);s.push(a)}return{senderStats:t,receiverStats:s}})}getDifferenceValue(i,e){if(Ot(i))return e;let t=e-i;return t<0?0:t}prepareReport({stats:i,report:e,freezeMap:t}){if(!Ot(i.senderStats)){let l={uint32_audio_level:i.senderStats.audio.audioLevel*nt,uint32_audio_energy:i.senderStats.audio.totalAudioEnergy*1e6,uint32_audio_codec_bitrate:i.senderStats.audio.bytesSent};i.senderStats.audio.micAudioLevel&&(l.uint32_mic_audio_level=i.senderStats.audio.micAudioLevel*nt);let h=[];if(i.senderStats.video.bytesSent){let f={uint32_video_stream_type:2,uint32_video_codec_fps:i.senderStats.video.framesSent,uint32_video_capture_fps:i.senderStats.video.fpsCapture,uint32_video_width:i.senderStats.video.frameWidth,uint32_video_height:i.senderStats.video.frameHeight,uint32_video_codec_bitrate:i.senderStats.video.bytesSent,uint32_video_enc_fps:i.senderStats.video.framesEncoded,uint32_key_frame_count:i.senderStats.video.keyFramesEncoded,uint32_nack_count:i.senderStats.video.nackCount,uint32_pli_count:i.senderStats.video.pliCount,uint32_encode_cost:(i.senderStats.video.totalEncodeTime||0)*1e3,uint32_send_packet_cost:(i.senderStats.video.totalPacketSendDelay||0)*1e3,uint32_video_arq_packets:i.senderStats.video.retransmittedPacketsSent};h.push(f)}if(i.senderStats.small.bytesSent){let f={uint32_video_stream_type:3,uint32_video_codec_fps:i.senderStats.small.framesSent||0,uint32_video_capture_fps:i.senderStats.small.fpsCapture||0,uint32_video_width:i.senderStats.small.frameWidth||0,uint32_video_height:i.senderStats.small.frameHeight||0,uint32_video_codec_bitrate:i.senderStats.small.bytesSent,uint32_video_enc_fps:i.senderStats.small.framesEncoded||0,uint32_key_frame_count:i.senderStats.small.keyFramesEncoded,uint32_nack_count:i.senderStats.small.nackCount,uint32_pli_count:i.senderStats.small.pliCount,uint32_encode_cost:(i.senderStats.small.totalEncodeTime||0)*1e3,uint32_send_packet_cost:(i.senderStats.small.totalPacketSendDelay||0)*1e3,uint32_video_arq_packets:i.senderStats.small.retransmittedPacketsSent};h.push(f)}if(i.senderStats.auxiliary.bytesSent){let f={uint32_video_stream_type:7,uint32_video_codec_fps:i.senderStats.auxiliary.framesSent||0,uint32_video_capture_fps:i.senderStats.auxiliary.fpsCapture||0,uint32_video_width:i.senderStats.auxiliary.frameWidth||0,uint32_video_height:i.senderStats.auxiliary.frameHeight||0,uint32_video_codec_bitrate:i.senderStats.auxiliary.bytesSent,uint32_video_enc_fps:i.senderStats.auxiliary.framesEncoded||0,uint32_key_frame_count:i.senderStats.auxiliary.keyFramesEncoded,uint32_nack_count:i.senderStats.auxiliary.nackCount,uint32_pli_count:i.senderStats.auxiliary.pliCount,uint32_encode_cost:(i.senderStats.auxiliary.totalEncodeTime||0)*1e3,uint32_send_packet_cost:(i.senderStats.auxiliary.totalPacketSendDelay||0)*1e3,uint32_video_arq_packets:i.senderStats.auxiliary.retransmittedPacketsSent};h.push(f)}let _={uint32_bitrate:0,uint32_lost:0,uint32_rtt:i.senderStats.rtt};e.msg_up_stream_info={msg_audio_status:l,msg_video_status:h,msg_network_status:_}}let{statInterval:s}=this;e.msg_down_stream_info=[],i.receiverStats.forEach(l=>{let h={msg_user_info:{str_identifier:l.userId,uint64_tinyid:l.tinyId},msg_network_status:{uint32_rtt:l.rtt,uint32_bitrate:0,uint32_lost:0},msg_audio_status:{},msg_video_status:[]};if(l.hasAudio){let _={uint32_audio_p2p_delay:l.audio.p2pDelay,uint32_audio_cache_ms:l.audio.totalJitter,uint32_audio_cache_ms_count:l.audio.totalJitterCount,uint32_audio_codec_bitrate:l.audio.bytesReceived,uint32_audio_total_bitrate:l.audio.bytesReceived,uint32_audio_level:l.audio.audioLevel*1e8,uint32_audio_energy:l.audio.totalAudioEnergy*1e6,uint32_audio_receive:l.audio.packetsReceived,uint32_audio_origin_lost:l.audio.packetsLost};h.msg_audio_status=_}if(l.hasVideo){let _=t.get(`${l.userId}_${na}`),f=_?_.duration:0,R={uint32_video_stream_type:l.isSmallSubscribed?3:2,uint32_video_receive_fps:l.video.framesReceived,uint32_video_width:l.video.frameWidth,uint32_video_height:l.video.frameHeight,uint32_video_codec_bitrate:l.video.bytesReceived,uint32_video_receive:l.video.packetsReceived,uint32_video_origin_lost:l.video.packetsLost,uint32_video_block_time:f,uint32_video_dec_fps:l.video.framesDecoded};h.msg_video_status.push(R)}if(l.hasAuxiliary){let _=t.get(`${l.userId}_${oa}`),f=_?_.duration:0,R={uint32_video_stream_type:7,uint32_video_receive_fps:l.auxiliary.framesReceived,uint32_video_width:l.auxiliary.frameWidth,uint32_video_height:l.auxiliary.frameHeight,uint32_video_codec_bitrate:l.auxiliary.bytesReceived,uint32_video_receive:l.auxiliary.packetsReceived+l.auxiliary.packetsLost,uint32_video_origin_lost:l.auxiliary.packetsLost,uint32_video_block_time:f,uint32_video_dec_fps:l.auxiliary.framesDecoded};h.msg_video_status.push(R)}e.msg_down_stream_info.push(h)});let n=this._prevReport;if(this._prevReport=JSON.parse(JSON.stringify(e)),e.msg_up_stream_info.msg_audio_status&&n.msg_up_stream_info.msg_audio_status){let l=n.msg_up_stream_info.msg_audio_status,h=e.msg_up_stream_info.msg_audio_status;if(l.uint32_audio_codec_bitrate===0)h.uint32_audio_codec_bitrate=0;else{let _=this.getDifferenceValue(l.uint32_audio_codec_bitrate,h.uint32_audio_codec_bitrate);h.uint32_audio_codec_bitrate=Math.round(_*8/s),e.msg_up_stream_info.msg_network_status.uint32_bitrate+=h.uint32_audio_codec_bitrate}}let o=n.msg_up_stream_info.msg_video_status;e.msg_up_stream_info.msg_video_status.forEach(l=>{let h=o.find(w=>w.uint32_video_stream_type===l.uint32_video_stream_type);if(!h||h.uint32_video_codec_bitrate===0){l.uint32_video_codec_bitrate=0,l.uint32_video_enc_fps=0,l.uint32_video_codec_fps=0;return}let _=0,f=0,R=0;h&&l.uint32_video_codec_bitrate>=h.uint32_video_codec_bitrate&&(_=h.uint32_video_codec_bitrate,f=h.uint32_video_enc_fps,R=h.uint32_video_codec_fps);let y=this.getDifferenceValue(_,l.uint32_video_codec_bitrate);l.uint32_video_codec_bitrate=Math.round(y*8/s),e.msg_up_stream_info.msg_network_status.uint32_bitrate+=l.uint32_video_codec_bitrate,l.uint32_video_enc_fps=Math.round(this.getDifferenceValue(f,l.uint32_video_enc_fps)/s),l.uint32_video_codec_fps=Math.round(this.getDifferenceValue(R,l.uint32_video_codec_fps)/s),mi&&Gt()===115&&h.uint32_video_width===0&&h.uint32_video_height===0&&h.uint32_video_codec_fps===0&&(l.uint32_video_codec_fps=l.uint32_video_enc_fps),g(h.uint32_key_frame_count)||(l.uint32_key_frame_count=Math.round(this.getDifferenceValue(h.uint32_key_frame_count,l.uint32_key_frame_count))),g(h.uint32_nack_count)||(l.uint32_nack_count=Math.round(this.getDifferenceValue(h.uint32_nack_count,l.uint32_nack_count))),g(h.uint32_pli_count)||(l.uint32_pli_count=Math.round(this.getDifferenceValue(h.uint32_pli_count,l.uint32_pli_count))),g(h.uint32_video_arq_packets)||(l.uint32_video_arq_packets=Math.round(this.getDifferenceValue(h.uint32_video_arq_packets,l.uint32_video_arq_packets))),g(h.uint32_encode_cost)||(l.uint32_encode_cost=Math.round(this.getDifferenceValue(h.uint32_encode_cost,l.uint32_encode_cost)/s)),g(h.uint32_send_packet_cost)||(l.uint32_send_packet_cost=Math.round(this.getDifferenceValue(h.uint32_send_packet_cost,l.uint32_send_packet_cost)/s))});let c=n.msg_down_stream_info;return e.msg_down_stream_info=e.msg_down_stream_info.filter(l=>c.find(h=>h.msg_user_info.uint64_tinyid===l.msg_user_info.uint64_tinyid)),e.msg_down_stream_info.forEach(l=>{let h=c.find(_=>_.msg_user_info.uint64_tinyid===l.msg_user_info.uint64_tinyid);if(!Ot(l.msg_audio_status)&&!Ot(h.msg_audio_status)){let _=l.msg_audio_status,f=h.msg_audio_status,R=this.getDifferenceValue(f.uint32_audio_cache_ms_count,_.uint32_audio_cache_ms_count);delete _.uint32_audio_cache_ms_count,_.uint32_audio_cache_ms=Math.floor(1e3*this.getDifferenceValue(f.uint32_audio_cache_ms,_.uint32_audio_cache_ms)/R)||0;let y=this.room.remotePublishedUserMap.get(l.msg_user_info.str_identifier);y&&(y.remoteAudioTrack.stat.jitterBufferDelay=_.uint32_audio_cache_ms),_.uint32_audio_origin_lost=this.getDifferenceValue(f.uint32_audio_origin_lost,_.uint32_audio_origin_lost),_.uint32_audio_receive=this.getDifferenceValue(f.uint32_audio_receive,_.uint32_audio_receive),_.uint32_audio_receive+=_.uint32_audio_origin_lost;let w=this.getDifferenceValue(f.uint32_audio_codec_bitrate,_.uint32_audio_codec_bitrate);_.uint32_audio_codec_bitrate=Math.round(w*8/s),_.uint32_audio_total_bitrate=Math.round(w*8/s)}else l.msg_audio_status={};if(l.msg_video_status&&h.msg_video_status){let _=h.msg_video_status;l.msg_video_status=l.msg_video_status.filter(R=>_.find(y=>y.uint32_video_stream_type===R.uint32_video_stream_type)),l.msg_video_status.forEach(R=>{let y=_.find(hh=>hh.uint32_video_stream_type===R.uint32_video_stream_type),w=y.uint32_video_receive,ie=y.uint32_video_origin_lost,nn=y.uint32_video_codec_bitrate,on=y.uint32_video_receive_fps,uh=y.uint32_video_dec_fps;R.uint32_video_origin_lost=this.getDifferenceValue(ie,R.uint32_video_origin_lost),R.uint32_video_receive=this.getDifferenceValue(w,R.uint32_video_receive)+R.uint32_video_origin_lost;let H=this.getDifferenceValue(nn,R.uint32_video_codec_bitrate);R.uint32_video_codec_bitrate=Math.round(H*8/s);let lh=this.getDifferenceValue(on,R.uint32_video_receive_fps);R.uint32_video_receive_fps=Math.round(lh/s),R.uint32_video_dec_fps=Math.round(this.getDifferenceValue(uh,R.uint32_video_dec_fps)/s)})}}),e}getStatsReport(s){return p(this,arguments,function*({uplinkConnection:i,downlinkConnections:e,freezeMap:t}){let n={msg_up_stream_info:{msg_audio_status:{uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_level:0,uint32_audio_energy:0},msg_video_status:[],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}},msg_down_stream_info:[{msg_user_info:{str_identifier:"",uint64_tinyid:0},msg_audio_status:{uint32_audio_cache_ms:0,uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_total_bitrate:0,uint32_audio_level:0,uint32_audio_energy:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_final_lost:0},msg_video_status:[{uint32_video_stream_type:0,uint32_video_receive_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_codec_bitrate:0,uint32_video_receive:0,uint32_video_origin_lost:0,uint32_video_block_time:0,uint32_video_dec_fps:0}],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}}]},o=yield this.getStats(i,e);return JSON.stringify(this._prevReport)==="{}"&&(this._prevReport=JSON.parse(JSON.stringify(n))),this.prepareReport({stats:o,report:n,freezeMap:t}),this._prevReportTime=Date.now(),n})}reset(){this._prevReportTime=0,this._prevReport={},this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevDecoderImplementationMap=new Map}};var Gl=Ie(ke());var hd=class extends Gl.default{constructor({signalChannel:e,room:t}){super();u(this,"_room");u(this,"_signalChannel");u(this,"_log");u(this,"_uplinkRTT",0);u(this,"_uplinkLoss",0);u(this,"_downlinkRTT",0);u(this,"_downlinkLoss",0);u(this,"_downlinkPrevStatMap",new Map);u(this,"_downlinkLossAndRTTMap",new Map);u(this,"_interval",-1);u(this,"_uplinkNetworkQuality",0);u(this,"_downlinkNetworkQuality",0);this._room=t,this._signalChannel=e,this._log=I.createLogger({id:"q",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this.initialize()}get uplinkNetworkQuality(){return this._uplinkNetworkQuality}set uplinkNetworkQuality(e){e!==this._uplinkNetworkQuality&&this._log.info(`uplink ${this.uplinkNetworkQuality} -> ${e}, rtt: ${this._uplinkRTT}, loss: ${this._uplinkLoss}`),this._uplinkNetworkQuality=e}get downlinkNetworkQuality(){return this._downlinkNetworkQuality}set downlinkNetworkQuality(e){if(e!==this._downlinkNetworkQuality){let{rtt:t,loss:s}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._log.info(`downlink ${this.downlinkNetworkQuality} -> ${e}, rtt: ${t}, loss: ${s}`)}this._downlinkNetworkQuality=e}initialize(){this._signalChannel.on(V.UPLINK_NETWORK_STATS,e=>{this.handleUplinkNetworkQuality(e)}),this._signalChannel.on(le.CONNECTION_STATE_CHANGED,this.handleSignalConnectionStateChange.bind(this)),this.start()}handleUplinkNetworkQuality(e){var c,d;if(e.data.code!==0)return;let t=e.data.data;if(t.delay&&this.updateDelay(t.delay),!this._room.uplinkConnection){this.uplinkNetworkQuality=0,this._uplinkLoss=0,this._uplinkRTT=0;return}let s=(d=(c=this._room)==null?void 0:c.uplinkConnection)==null?void 0:d.getPeerConnection();if(s&&this.isPeerConnectionDisconnected(s)){this.uplinkNetworkQuality=6,this._uplinkLoss=0,this._uplinkRTT=0;return}let n=t.expectAudPkg+t.expectVidPkg,o=t.recvAudPkg+t.recvVidPkg,a=n-o;n===0&&o===0||(a<=0?this._uplinkLoss=0:this._uplinkLoss=Math.round(a/n*100),this._uplinkRTT=t.rtt,this.uplinkNetworkQuality=this.getNetworkQuality(this._uplinkLoss,this._uplinkRTT))}handleDownlinkNetworkQuality(){return p(this,null,function*(){if(this._room.remotePublishedUserMap.size===0){this.downlinkNetworkQuality=0;return}let e=[...this._room.remotePublishedUserMap.values()],t=e.filter(a=>{var c;return((c=a.getPeerConnection())==null?void 0:c.connectionState)===se.CONNECTED});if(e.filter(a=>this.isPeerConnectionDisconnected(a.getPeerConnection())).length===e.length){this.downlinkNetworkQuality=6;return}for(let a=0;a<t.length;a++){let c=t[a].getPeerConnection();if(!c)return;let{rtt:d,totalPacketsLost:l,totalPacketsReceived:h}=yield this.getStat(c);if(!this._downlinkPrevStatMap.has(c)){this._downlinkPrevStatMap.set(c,{totalPacketsLost:l,totalPacketsReceived:h});continue}let _=0,f=this._downlinkPrevStatMap.get(c),R=l-f.totalPacketsLost,y=h-f.totalPacketsReceived;R<=0||y<0?_=0:_=Math.round(R/(R+y)*100),this._downlinkPrevStatMap.set(c,{totalPacketsLost:l,totalPacketsReceived:h}),this._downlinkLossAndRTTMap.set(c,{rtt:d,loss:_,userId:t[a].getUserId(),audioDelay:t[a].remoteAudioTrack.stat.end2EndDelay,videoDelay:t[a].remoteVideoTrack.stat.end2EndDelay})}if([...this._downlinkPrevStatMap.keys()].forEach(a=>{this.isPeerConnectionDisconnected(a)&&(this._downlinkPrevStatMap.delete(a),this._downlinkLossAndRTTMap.delete(a))}),this._downlinkLossAndRTTMap.size===0)return;let{rtt:n,loss:o}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._downlinkRTT=n,this._downlinkLoss=o,this.downlinkNetworkQuality=this.getNetworkQuality(o,n)})}getStat(e){return p(this,null,function*(){let t={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!Pi())return t;let s=e.getReceivers();try{for(let n=0;n<s.length;n++)(yield s[n].getStats()).forEach(c=>{c.type==="candidate-pair"&&re(c.currentRoundTripTime)&&(t.rtt=Math.round(c.currentRoundTripTime*1e3)),c.type==="inbound-rtp"&&(c.mediaType===m.AUDIO||c.mediaType===m.VIDEO)&&(t.totalPacketsLost+=c.packetsLost,t.totalPacketsReceived+=c.packetsReceived)});return t}catch(n){return t}})}getAverageLossAndRTT(e){let t={rtt:0,loss:0};return Array.isArray(e)&&e.length>0&&(e.forEach(s=>{t.rtt+=s.rtt,t.loss+=s.loss}),Object.keys(t).forEach(s=>{t[s]=Math.round(t[s]/e.length)})),t}getNetworkQuality(e,t){return e>50||t>500?5:e>30||t>350?4:e>20||t>200?3:e>10||t>100?2:e>=0||t>=0?1:0}handleSignalConnectionStateChange(e){e.state==="DISCONNECTED"?(this._uplinkRTT=0,this._uplinkLoss=0,this.uplinkNetworkQuality=6):e.state==="CONNECTED"&&this.uplinkNetworkQuality===6&&(this.uplinkNetworkQuality=5)}handleUplinkConnectionStateChange({state:e}){e==="DISCONNECTED"?(this._uplinkLoss=0,this._uplinkRTT=0,this.uplinkNetworkQuality=6):e==="CONNECTED"&&this.uplinkNetworkQuality===6&&(this.uplinkNetworkQuality=5)}isPeerConnectionDisconnected(e){return!!(e&&(e.connectionState===se.DISCONNECTED||e.connectionState===se.FAILED||e.connectionState===se.CLOSED))}setUplinkConnection(e){this._room.uplinkConnection=e,this._room.uplinkConnection?this._room.uplinkConnection.on("connection-state-changed",this.handleUplinkConnectionStateChange.bind(this)):(this.uplinkNetworkQuality=0,this._uplinkRTT=0,this._uplinkLoss=0)}start(){if(this._interval!==-1){this._log.info("network quality calculating is already started");return}this._log.debug("start network quality calculating"),this._interval=Z.run(gt,()=>{this.handleDownlinkNetworkQuality();let e=[...this._downlinkLossAndRTTMap.values()];T.emit(E.NETWORK_QUALITY,{room:this._room,uplink:{rtt:this._uplinkRTT,loss:this._uplinkLoss},downlinks:e}),this.emit(hd.EVENT_NETWORK_QUALITY,{uplinkNetworkQuality:this.uplinkNetworkQuality,downlinkNetworkQuality:this.downlinkNetworkQuality,uplinkRTT:this._uplinkRTT,uplinkLoss:this._uplinkLoss,downlinkRTT:this._downlinkRTT,downlinkLoss:this._downlinkLoss,downlinkInfo:e})},{delay:2e3})}stop(){this._log.debug("stopped"),this._interval!==-1&&(Z.clearTask(this._interval),this._interval=-1),this._downlinkLossAndRTTMap.clear(),this._downlinkPrevStatMap.clear()}updateDelay(e){let{tinyIdToUserIdMap:t}=this._room;e.forEach(({srcTinyId:s,videoDelay:n,audioDelay:o})=>{let a=t.get(s);if(a){let c=this._room.remotePublishedUserMap.get(a);c==null||c.setDelay({videoDelay:n,audioDelay:o})}})}},Qi=hd;u(Qi,"EVENT_NETWORK_QUALITY","0");function r_({fn:r,context:i}){return function(...e){try{let t=r.apply(i,e);return Es(t)?t.catch(s=>I.error(`${r.name}() error observed ${s}`)):t}catch(t){I.error(`${r.name}() error observed ${t}`)}}}var Vo=class{constructor(i){this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0};this._eventMap=new Map;this._frameWorkType=i.frameWorkType||30,this._component=i.component||0,this.connectionType=i.connectionType||1,this._language=i.language||0,this._room=i.room,this._keyPrefix="key_point",this._log=I.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach(e=>{e.startsWith("handle")&&G(this[e])&&(this[e]=r_({fn:this[e],context:this}))}),this.initData(),this.installEvents(),this._intervalId=Z.run(gt,this.setStorage.bind(this),{delay:2e4})}get _storageKey(){return`${this._keyPrefix}_${this._room.userId}`}initData(){this._firstPublishedUserList=[],this._networkQuality={totalUplinkRTT:0,totalUplinkLoss:0,count:0,totalDownlinkRTTAndLossMap:new Map},this._basicInfo={string_sdk_version:Ae,uint32_os_type:15,string_device_name:"",string_http_user_agent:navigator.userAgent,string_os_version:"",uint32_avg_rtt:0,uint32_avg_up_loss:0,uint32_scene:this._room.scene==="live"?1:0,uint32_joining_duration:0,uint32_networkType:0,uint32_framework:this._frameWorkType,uint32_component:this._component,uint32_connection_type:this.connectionType,uint32_caller_coding_language:this._language,string_domain:location.hostname},this._pathJoinRoom={uint64_start_time:0,uint64_send_request_acc_ip_cmd_start_time:0,uint64_send_request_acc_ip_cmd_end_time:0,uint64_send_request_enter_room_cmd_start_time:0,uint64_send_request_enter_room_cmd_end_time:0,uint64_send_first_video_frame_time:0,uint64_recv_userlist_time:0,uint64_end_time:0,int32_send_request_acc_ip_cmd_ret:0,int32_send_request_enter_room_cmd_ret:0,int32_end_ret:0},this._pathLeaveRoom={uint64_start_time:0,uint64_send_request_exit_room_cmd_start_time:0,uint64_send_request_exit_room_cmd_end_time:0,uint64_end_time:0,int32_send_request_exit_room_cmd_ret:0,int32_end_ret:0},this._localStreamStat={totalVideoBitrate:0,totalVideoFPS:0,totalVideoHeight:0,totalVideoWidth:0,totalAudioLevel:0,videoCount:0,audioLevelCount:0,publishStartTime:0,statsToReport:{uint32_audio_capture_db:0,uint32_video_big_capture_fps:0,uint32_video_big_bitrate:0,uint32_video_big_resolution:0}},this._pathMainVideoMap=new Map,this._pathMainAudioMap=new Map,this._pathAuxiliaryMap=new Map,this._remoteStreamStatMap=new Map,hs().then(i=>{this._basicInfo.string_os_version=ms(),i?this._basicInfo.string_device_name=i.mobile?i.model:this._basicInfo.string_os_version:this._basicInfo.string_device_name=this._basicInfo.string_os_version})}addEvent(i,e){return this._eventMap.set(i,e),T.on(i,e),this}installEvents(){this.handleUnload=this.handleUnload.bind(this),window.addEventListener("unload",this.handleUnload),this._room.once("banned",()=>this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})),this.addEvent(E.JOIN_START,this.handleJoinStart).addEvent(E.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(E.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(E.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(E.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(E.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(E.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(E.JOIN_FAILED,this.handleJoinFailed).addEvent(E.LEAVE_START,this.handleLeaveStart).addEvent(E.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(E.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(E.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(E.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(E.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(E.PUBLISH_START,this.handlePublishStart).addEvent(E.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(E.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(E.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(E.PLAY_TRACK_START,this.handlePlayStart).addEvent(E.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(E.PLAYER_STATE_CHANGED,({track:i,state:e,type:t})=>{!ht(i)||!this.hitTest(i.room)||e==="PLAYING"&&(t===m.AUDIO?this.handleAudioPlaying(i):this.handleVideoPlaying(i))}).addEvent(E.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(E.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(E.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(E.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{if(!this.hitTest(i))return;let s=e.hasAudio||e.hasVideo||e.hasSmall,n=e.hasAuxiliary,o=t.hasAudio||t.hasVideo||t.hasSmall,a=t.hasAuxiliary;!s&&o&&this.handleRemoteStreamAdded(t.userId,"main"),!n&&a&&this.handleRemoteStreamAdded(t.userId,"auxiliary")}).addEvent(E.SINGLE_CONNECTION_STAT,({room:i,stat:e})=>{this.hitTest(i)&&(this._pathJoinRoom.int32_ice_cost=e.ice,this._pathJoinRoom.int32_dtls_cost=e.dtls,this._pathJoinRoom.int32_peer_connection_cost=e.peerConnection)})}uninstallEvents(){window.removeEventListener("unload",this.handleUnload),this._eventMap.forEach((i,e)=>T.off(e,i)),this._eventMap.clear()}destroy(){this.uninstallEvents(),Z.clearTask(this._intervalId)}handleUnload(){this._room.isJoined&&this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})}handleJoinStart(i){this.hitTest(i.room)&&(this._pathJoinRoom.uint64_start_time===0&&(this._pathJoinRoom.uint64_start_time=Date.now(),this.checkStorage()),i.params&&(g(i.params.frameWorkType)||(this._frameWorkType=i.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),g(i.params.component)||(this._component=i.params.component,this._basicInfo.uint32_component=this._component),g(i.params.language)||(this._language=i.params.language,this._basicInfo.uint32_caller_coding_language=this._language)))}handleJoinScheduleSuccess({room:i,detailCost:e}){if(this.hitTest(i)&&e){let{totalCost:t,local:s,dns:n,tcp:o,tls:a,request:c,response:d}=e;this._pathJoinRoom.int32_schedule_cost=t,this._pathJoinRoom.int32_schedule_local=s,this._pathJoinRoom.int32_schedule_dns=n,this._pathJoinRoom.int32_schedule_tcp=o,this._pathJoinRoom.int32_schedule_tls=a,this._pathJoinRoom.int32_schedule_request=c,this._pathJoinRoom.int32_schedule_response=d}}handleSignalConnectionStart({room:i}){this.hitTest(i)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time=Date.now())}handleSignalConnectionEnd({room:i,error:e}){this.hitTest(i)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time=Date.now(),e&&(this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret=e instanceof C?Number(e.getExtraCode()||e.getCode()):A.UNKNOWN,this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret))}handleJoinSendCMD(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=Date.now())}handleJoinReceivedCMDResponce(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=Date.now(),this._pathJoinRoom.int32_send_request_enter_room_cmd_ret=i.code,i.code!==0&&(this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_enter_room_cmd_ret))}handleJoinSuccess(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_end_time===0&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret=0,this._signalInfo=i.room.getSignalInfo())}handleJoinFailed({room:i,error:e}){this.hitTest(i)&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret===0&&(this._pathJoinRoom.int32_end_ret=e.code||this._pathJoinRoom.int32_send_request_enter_room_cmd_ret||this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret),setTimeout(()=>{this.report()}))}handleReceivedPublishUserList(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_recv_userlist_time===0&&(this._pathJoinRoom.uint64_recv_userlist_time=Date.now(),this._firstPublishedUserList=i.publishedUserList||[])}handleSendFirstVideoFrame({room:i}){!this.hitTest(i)||this._pathJoinRoom.uint64_send_first_video_frame_time===0&&this._pathJoinRoom.uint64_start_time!==0&&(this._pathJoinRoom.uint64_send_first_video_frame_time=Date.now())}handleLeaveStart(i){this.hitTest(i.room)&&(this._pathLeaveRoom.uint64_start_time=Date.now())}handleLeaveSuccess(i){this.hitTest(i.room)&&this._pathLeaveRoom.uint64_end_time===0&&(this._pathLeaveRoom.uint64_end_time=Date.now(),this._pathJoinRoom.uint64_end_time!==0?this._basicInfo.uint32_joining_duration=this._pathLeaveRoom.uint64_end_time-this._pathJoinRoom.uint64_end_time:this._log.warn("pathJoinRoom endTime is 0"),this.report())}handleLeaveSendCMD(i){this.hitTest(i.room)&&(this._pathLeaveRoom.uint64_send_request_exit_room_cmd_start_time=Date.now(),this._pathLeaveRoom.uint64_send_request_exit_room_cmd_end_time=Date.now())}handleRemoteStreamAdded(i,e){var s;let t=`${i}_${e}`;if(!this._remoteStreamStatMap.has(t)){let n={userId:i,totalVideoFPS:0,totalVideoBitrate:0,totalAudioLevel:0,totalAudioBitrate:0,totalLoss:0,audioCount:0,audioLevelCount:0,videoCount:0,networkQualityCount:0,streamAddedTime:Date.now(),subscribeStartTime:0,subscribedTime:0,playStreamTime:0,statsToReport:P(N({},s_),{msg_user_info:new Ys({userId:i,tinyId:(s=this._room.remotePublishedUserMap.get(i))==null?void 0:s.tinyId,role:20})})};n.statsToReport.uint32_stream_type=e==="main"?2:7,this._remoteStreamStatMap.set(t,n)}}handleSubscribeStart({room:i,remotePublishedUser:e,streamType:t,subscribeState:s}){if(!this.hitTest(i))return;let{userId:n,tinyId:o,role:a}=e,c=new Ys({userId:n,tinyId:o,role:a==="anchor"?20:21}),d=Date.now(),l=`${n}_${t}`,h=this._remoteStreamStatMap.get(l);h&&h.subscribeStartTime===0&&(h.subscribeStartTime=d),t==="main"?(e.muteState.hasVideo&&(s.video||s.smallVideo)&&!this._pathMainVideoMap.has(l)&&this._pathMainVideoMap.set(l,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:n,sendSubscribeCMDTime:d}),e.muteState.hasAudio&&s.audio&&!this._pathMainAudioMap.has(l)&&this._pathMainAudioMap.set(l,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:n,sendSubscribeCMDTime:d})):e.muteState.hasAuxiliary&&s.auxiliary&&!this._pathAuxiliaryMap.has(l)&&this._pathAuxiliaryMap.set(l,{sendSubscribeCMDTime:d})}handleSubscribed({room:i,remotePublishedUser:e,streamType:t}){if(this.hitTest(i)){let s=`${e.userId}_${t}`,n=this._remoteStreamStatMap.get(s);n&&n.subscribedTime===0&&(n.subscribedTime=Date.now())}}handlePlayStart({track:i}){if(!ht(i)||!this.hitTest(i.room))return;let e=`${i.userId}_${i.streamType}`,t=this._remoteStreamStatMap.get(e);(t==null?void 0:t.playStreamTime)===0&&(t.playStreamTime=Date.now())}handleVideoLoadedData({track:i}){if(!ht(i)||!this.hitTest(i.room))return;let e=`${i.userId}_${i.streamType}`,t=this._pathMainVideoMap.get(e);t&&t.statsToReport.uint64_combine_first_frame_time===0&&(t.statsToReport.uint64_combine_first_frame_time=Date.now())}handleVideoPlaying(i){let e=`${i.userId}_${i.streamType}`,t=Date.now(),s=this._pathMainVideoMap.get(e),n=this._remoteStreamStatMap.get(e);if(s&&(s.statsToReport.uint64_render_first_frame_time===0&&(s.statsToReport.uint64_render_first_frame_time=t),n)){let{statsToReport:a,playStreamTime:c,subscribedTime:d}=n;a.uint32_video_render_first===0&&c-d<=100&&(a.uint32_video_render_first=t-s.sendSubscribeCMDTime)}let o=this._pathAuxiliaryMap.get(e);if(o&&n){let{statsToReport:a,playStreamTime:c,subscribedTime:d}=n;a.uint32_video_render_first===0&&c-d<=100&&(a.uint32_video_render_first=t-o.sendSubscribeCMDTime)}}handleAudioPlaying(i){let e=`${i.userId}_${i.streamType}`,t=this._pathMainAudioMap.get(e);t&&t.statsToReport.uint64_play_first_frame_time===0&&(t.statsToReport.uint64_play_first_frame_time=Date.now())}handleNetworkQuality(i){this.hitTest(i.room)&&(this._networkQuality.totalUplinkLoss+=i.uplink.loss,this._networkQuality.totalUplinkRTT+=i.uplink.rtt,this._networkQuality.count++,i.downlinks.forEach(({rtt:e,loss:t,userId:s,videoDelay:n,audioDelay:o})=>{let a=this._networkQuality.totalDownlinkRTTAndLossMap.get(s);if(a)a.totalRTT+=e,a.totalLoss+=t,n&&(a.totalVideoDelay=(a.totalVideoDelay||0)+n,a.videoDelayCount=(a.videoDelayCount||0)+1),o&&(a.totalAudioDelay=(a.totalAudioDelay||0)+o,a.audioDelayCount=(a.audioDelayCount||0)+1),a.count++;else{let c,d,l,h;n&&(d=n,l=1),o&&(c=o,h=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(s,{totalRTT:e,totalLoss:t,count:1,totalAudioDelay:c,totalVideoDelay:d,audioDelayCount:h,videoDelayCount:l})}}))}handleHeartbeatStats(i){if(this.hitTest(i.room)){let{msg_up_stream_info:e,msg_down_stream_info:t}=i.report;if(e.msg_video_status[0]){let{uint32_video_codec_bitrate:s,uint32_video_enc_fps:n,uint32_video_width:o,uint32_video_height:a}=e.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=s,this._localStreamStat.totalVideoFPS+=n,this._localStreamStat.totalVideoWidth+=o,this._localStreamStat.totalVideoHeight+=a,this._localStreamStat.videoCount++}if(e.msg_audio_status){let{uint32_audio_level:s}=e.msg_audio_status;Math.floor(s/nt*100)>0&&(this._localStreamStat.totalAudioLevel+=s/nt,this._localStreamStat.audioLevelCount++)}t.forEach(s=>{let{msg_user_info:n,msg_audio_status:o,msg_video_status:a}=s,c=n.str_identifier,d=this._room.remotePublishedUserMap.get(c);if(a.forEach(l=>{let h=l.uint32_video_stream_type===2,_=l.uint32_video_stream_type===7,f=`${c}_${h?"main":"auxiliary"}`,R=this._remoteStreamStatMap.get(f);if(!!R&&(h&&(d==null?void 0:d.remoteVideoTrack.isSubscribed)||_&&(d==null?void 0:d.remoteAuxiliaryTrack))){R.totalVideoFPS+=l.uint32_video_receive_fps,R.totalVideoBitrate+=l.uint32_video_codec_bitrate,R.videoCount++,R.statsToReport.uint32_video_width===0&&(R.statsToReport.uint32_video_width=l.uint32_video_width),R.statsToReport.uint32_video_height===0&&(R.statsToReport.uint32_video_height=l.uint32_video_height);let y=h?d.remoteVideoTrack:d.remoteAuxiliaryTrack;y.stat.jitterBufferDelay&&(R.videoJitterBufferDelay=y.stat.jitterBufferDelay),y.stat.framesReceived&&(R.statsToReport.uint32_video_consume_render_rate=Math.floor(y.stat.framesDecoded/y.stat.framesReceived*Gr(10,6)))}}),o){let l=`${c}_${"main"}`,h=this._remoteStreamStatMap.get(l);this._remoteStreamStatMap.has(l)&&h&&(d==null?void 0:d.remoteAudioTrack.isSubscribed)&&(h.totalAudioBitrate+=o.uint32_audio_codec_bitrate,h.audioCount++,d.remoteAudioTrack.stat.jitterBufferDelay&&(h.audioJitterBufferDelay=d.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(o.uint32_audio_level/nt*100)>0&&(h.totalAudioLevel+=o.uint32_audio_level/nt,h.audioLevelCount++))}})}}handlePublishStart({room:i}){this.hitTest(i)&&this._localStreamStat.publishStartTime===0&&(this._localStreamStat.publishStartTime=Date.now())}handleTrackCaptureStart({track:i}){i.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),i.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_start_time&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}handleTrackCaptureSuccess({track:i}){i.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=0,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),i.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=0,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleTrackCaptureFailed({track:i,error:e}){let s={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[e.name]||(e instanceof C?e.getExtraCode()||e.getCode():A.UNKNOWN);i.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=s,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),i.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=s,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}hasVideoFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&di)>=0}hasAudioFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&ui)>=0}hasAuxFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&vi)>=0}hitTest(i){return i===this._room}checkStorage(){return p(this,null,function*(){try{let i=qt.getItem(this._storageKey);i&&(yield this.upload(i),qt.deleteItem(this._storageKey))}catch(i){this._log.warn(i)}})}setStorage(){this.prepareReport();let i=this.getReportData();i.msg_path_enter_room.uint64_start_time!==0&&qt.setItem(this._storageKey,i)}prepareReport(){if(this._networkQuality.count>0&&(this._basicInfo.uint32_avg_rtt=Math.floor(this._networkQuality.totalUplinkRTT/this._networkQuality.count),this._basicInfo.uint32_avg_up_loss=Math.floor(this._networkQuality.totalUplinkLoss/this._networkQuality.count)),this._localStreamStat.videoCount>0){this._localStreamStat.statsToReport.uint32_video_big_capture_fps=Math.floor(this._localStreamStat.totalVideoFPS/this._localStreamStat.videoCount),this._localStreamStat.statsToReport.uint32_video_big_bitrate=Math.floor(this._localStreamStat.totalVideoBitrate/this._localStreamStat.videoCount);let i=Math.floor(this._localStreamStat.totalVideoWidth/this._localStreamStat.videoCount),e=Math.floor(this._localStreamStat.totalVideoHeight/this._localStreamStat.videoCount);this._localStreamStat.statsToReport.uint32_video_big_resolution=i<<16|e}this._localStreamStat.audioLevelCount>0&&(this._localStreamStat.statsToReport.uint32_audio_capture_db=Math.floor(this._localStreamStat.totalAudioLevel/this._localStreamStat.audioLevelCount*100)),this._remoteStreamStatMap.forEach((i,e)=>{let{userId:t}=i,s=this._networkQuality.totalDownlinkRTTAndLossMap.get(t);if(s){let{totalLoss:l,count:h,audioDelayCount:_,videoDelayCount:f,totalAudioDelay:R,totalVideoDelay:y}=s;i.statsToReport.uint32_avg_down_loss=Math.floor(l/h),_&&R&&(i.statsToReport.uint32_audio_network_p2p_delay=Math.floor(R/_),i.audioJitterBufferDelay&&(i.statsToReport.uint32_p2p_delay=Math.floor(i.statsToReport.uint32_audio_network_p2p_delay+i.audioJitterBufferDelay))),f&&y&&(i.statsToReport.uint32_video_network_p2p_delay=Math.floor(y/f))}i.videoCount>0&&(i.statsToReport.uint32_video_avg_fps=Math.floor(i.totalVideoFPS/i.videoCount),i.statsToReport.uint32_video_avg_bitrate=Math.floor(i.totalVideoBitrate/i.videoCount)),i.audioCount>0&&(i.statsToReport.uint32_audio_recv_bitrate=i.statsToReport.uint32_audio_bitrate=Math.floor(i.totalAudioBitrate/i.audioCount)),i.audioLevelCount>0&&(i.statsToReport.uint32_audio_play_db=Math.floor(i.totalAudioLevel/i.audioLevelCount*100));let{callDurationCalculator:n}=this._room;n&&(i.statsToReport.uint32_audio_play_time=n.getDuration(e,m.AUDIO),i.statsToReport.uint32_video_play_time=n.getDuration(e,m.VIDEO)),i.statsToReport.uint32_video_render_first=Math.min(i.statsToReport.uint32_video_render_first,zi);let{badCaseDetector:o}=this._room,{dataFreeze:a,count:c}=o.getDataFreezeDuration(e),{renderFreeze:d}=o.getRenderFreezeDuration(e);i.statsToReport.uint32_video_block_count=c,i.statsToReport.uint32_video_block_time=Math.min(a,i.statsToReport.uint32_video_play_time),i.statsToReport.uint32_video_external_block_time=Math.min(d,i.statsToReport.uint32_video_play_time),o.isBlackStream(e)&&i.statsToReport.uint32_video_avg_fps===0?i.statsToReport.uint32_video_black_screen_subjective=1:i.statsToReport.uint32_video_black_screen_subjective=0,(i.subscribeStartTime===0||i.subscribeStartTime-i.streamAddedTime>100||i.playStreamTime===0)&&(this._pathMainAudioMap.delete(e),this._pathMainVideoMap.delete(e),i.statsToReport.uint32_video_render_first=0)}),this._pathMainAudioMap.forEach((i,e)=>{if(!this.hasAudioFlag(i.userId)){this._pathMainAudioMap.delete(e);return}i.statsToReport.uint64_play_first_frame_time-i.statsToReport.uint64_start_enter_time>zi&&(i.statsToReport.uint64_play_first_frame_time=i.statsToReport.uint64_start_enter_time+zi)}),this._pathMainVideoMap.forEach((i,e)=>{if(!this.hasVideoFlag(i.userId)){this._pathMainVideoMap.delete(e);return}i.statsToReport.uint64_render_first_frame_time-i.statsToReport.uint64_start_enter_time>zi&&(i.statsToReport.uint64_render_first_frame_time=i.statsToReport.uint64_start_enter_time+zi)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>zi&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+zi)}getReportData(){this._basicInfo.uint32_networkType=Er();let i={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new Ys({userId:this._room.userId,tinyId:this._room.tinyId,role:this._room.role==="anchor"?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:Ts(this._signalInfo.relayIp),uint32_client_ip:Ts(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*Gr(2,31)),msg_path_enter_room:this._pathJoinRoom,msg_path_exit_room:this._pathLeaveRoom,msg_path_recv_video:[...this._pathMainVideoMap.values()].map(e=>e.statsToReport),msg_quality_statistics:[...this._remoteStreamStatMap.values()].map(e=>e.statsToReport),str_room_name:String(this._room.roomId||0),msg_path_recv_audio:[...this._pathMainAudioMap.values()].map(e=>e.statsToReport),uint32_info_client_ip:Ts(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport};return Hn(i),i}report(){return p(this,null,function*(){try{this.prepareReport();let i=this.getReportData();yield this.upload(i),qt.deleteItem(this._storageKey),this.initData()}catch(i){this._log.warn(i)}})}upload(i){return p(this,null,function*(){if(dt&&!Sa||i.msg_path_enter_room.uint64_start_time===0||[un,Zo,ea].findIndex(a=>a===location.host)>=0)return;let e=Number(this._room.sdkAppId),t=yield ma(i),s=t instanceof ArrayBuffer,n=`${_i(e,ci.KEY_POINT)}&gzip=${+s}`,o=!1;navigator.sendBeacon&&(o=navigator.sendBeacon(n,t)),o||Ft({url:n,body:t}),this.uploadKVStat(v),this.uploadKVStat(Ui)})}setConnectionType(i){this.connectionType=i,this._basicInfo.uint32_connection_type=i}uploadKVStat(i){return p(this,null,function*(){let e=i.getReportData();if(e.stats_count.length===0&&e.stats_distribution.length===0)return;e.msg_sdk_basic_info=P(N({},e.msg_sdk_basic_info),{bytes_device_name:this._basicInfo.string_device_name||"",bytes_os_version:this._basicInfo.string_os_version||"",uint32_framework:this._frameWorkType,uint32_network_type:this._basicInfo.uint32_networkType||0}),this._log.debug(e);let t=yield ma(e),s=`${_i(+this._room.sdkAppId,ci.KV_STAT)}&gzip=${+(t instanceof ArrayBuffer)}`,n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(s,t)),n||Ft({url:s,body:t})})}};b([wt({settings:{timeout:500,retries:3}})],Vo.prototype,"upload",1);var zi=5e3,s_={msg_user_info:null,uint32_video_avg_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_avg_bitrate:0,uint32_video_block_time:0,uint32_video_play_time:0,uint32_audio_block_time:0,uint32_audio_play_time:0,uint32_audio_play_db:0,uint32_avg_down_loss:0,uint32_stream_type:0,uint32_video_render_first:0,uint32_video_block_count:0,uint32_audio_block_count:0,uint32_audio_bitrate:0,uint32_video_black_screen_subjective:0,uint32_audio_recv_bitrate:0,uint32_video_external_block_time:0,uint32_video_consume_render_rate:0},Ys=class{constructor(i){this.str_identifier=String(i.userId),this.str_tinyid=String(i.tinyId||0),this.uint32_role=i.role}},Wl=Vo;var md=class{constructor(){u(this,"_startTime");u(this,"_endTime");this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=L())}stop(){this._endTime===0&&(this._endTime=L())}getDuration(){return this._endTime===0?L()-this._startTime:this._endTime-this._startTime}get endTime(){return this._endTime}},Vr=md;var pd=class{constructor(i){u(this,"_room",null);u(this,"_durationMap");u(this,"_eventMap",new Map);this._room=i.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(E.SUBSCRIBE_SUCCESS,this.handleSubscribed).set(E.UNSUBSCRIBE_SUCCESS,this.handleStreamStopped).set(E.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{var o;let{userId:s}=t;if(!this.hitTest(i))return;e.hasAudio&&!t.hasAudio&&this.stopDurationItem(`${s}_${"main"}`,m.AUDIO),e.hasVideo&&!t.hasVideo&&this.stopDurationItem(`${s}_${"main"}`,m.VIDEO),e.hasAuxiliary&&!t.hasAuxiliary&&this.stopDurationItem(`${s}_${"auxiliary"}`,m.VIDEO);let n=(o=this._room)==null?void 0:o.remotePublishedUserMap.get(s);!n||(!e.hasAudio&&t.hasAudio&&n.remoteAudioTrack.isSubscribed&&this.addDuractionItem(s,m.AUDIO,"main"),!e.hasVideo&&t.hasVideo&&n.remoteVideoTrack.isSubscribed&&this.addDuractionItem(s,m.VIDEO,"main"),!e.hasAuxiliary&&t.hasAuxiliary&&n.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(s,m.VIDEO,"auxiliary"))}),this._eventMap.forEach((i,e)=>T.on(e,i,this))}uninstallEvents(){this._eventMap.forEach((i,e)=>T.off(e,i,this)),this._eventMap.clear()}handleSubscribed({room:i,streamType:e,remotePublishedUser:t}){if(!this.hitTest(i))return;let{userId:s}=t,n=`${s}_${e}`;if(t.muteState.hasAudio&&e==="main")if(t.remoteAudioTrack.isSubscribed){let o=new Vr,a=this._durationMap.get(n);a?this.isRecording(a.audio)||a.audio.push(o):this._durationMap.set(n,{userId:s,type:e,audio:[o],video:[]})}else this.stopDurationItem(n,m.AUDIO);if(t.muteState.hasVideo||t.muteState.hasAuxiliary)if(t.remoteVideoTrack.isSubscribed||t.remoteAuxiliaryTrack.isSubscribed){let o=new Vr,a=this._durationMap.get(n);a?this.isRecording(a.video)||a.video.push(o):this._durationMap.set(n,{userId:s,type:e,audio:[],video:[o]})}else this.stopDurationItem(n,m.VIDEO)}handleStreamStopped({room:i,streamType:e,remotePublishedUser:t}){if(!this.hitTest(i))return;let{userId:s}=t,n=`${s}_${e}`;this.stopDurationItem(n,m.AUDIO),this.stopDurationItem(n,m.VIDEO)}isRecording(i){return i.findIndex(e=>e.endTime===0)>=0}addDuractionItem(i,e,t){let s=`${i}_${t}`,n=new Vr,o=this._durationMap.get(s);o?this.isRecording(o[e])||o[e].push(n):this._durationMap.set(s,{userId:i,type:t,audio:e===m.AUDIO?[n]:[],video:e===m.AUDIO?[]:[n]})}stopDurationItem(i,e){if(this._durationMap.has(i)){let s=this._durationMap.get(i)[e].find(n=>n.endTime===0);s&&s.stop()}}hitTest(i){return this._room===i}getDuration(i,e){return this._durationMap.has(i)?this._durationMap.get(i)[e].reduce((s,n)=>s+n.getDuration(),0):0}getDurationMap(){return this._durationMap}reset(){this._durationMap.clear()}destroy(){this._room=null,this.uninstallEvents()}},Jl=pd;var _d=class{constructor(i){u(this,"_room");u(this,"_renderFreezeMap",new Map);u(this,"_isVideoPlayingEventFiredMap",new Map);u(this,"_dataFreezeMap",new Map);u(this,"_monitorFreezeData",new Map);u(this,"_eventMap",new Map);this._room=i.room,this.installEvents()}installEvents(){this._eventMap.set(E.LEAVE_SUCCESS,({room:i})=>{this.hitTest(i)&&this.stop()}).set(E.PLAY_TRACK_START,this.onPlayTrackStart).set(E.UNSUBSCRIBE_SUCCESS,({room:i,streamType:e,remotePublishedUser:t})=>{if(!this.hitTest(i))return;let{userId:s}=t,n=`${s}_${e}`;this.stopDataFreeze({key:n,userId:s,type:e})}).set(E.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{if(!this.hitTest(i))return;let{userId:s}=t;if(e.hasVideo&&!t.hasVideo){let n="main",o=`${t.userId}_${n}`;this.stopDataFreeze({key:o,userId:s,type:n})}if(e.hasAuxiliary&&!t.hasAuxiliary){let n="auxiliary",o=`${t.userId}_${n}`;this.stopDataFreeze({key:o,userId:s,type:n})}}).set(E.PLAYER_STATE_CHANGED,({track:i,state:e,reason:t,type:s})=>{if(!(!ht(i)||!this.hitTest(i.room)||s!==m.VIDEO)){if(e==="PLAYING"){let n=`${i.userId}_${i.streamType}`;this._isVideoPlayingEventFiredMap.set(n,!0)}t===m.MUTE?this.onVideoTrackMuted(i):t===m.UNMUTE&&this.onVideoTrackUnmuted(i)}}).set(E.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach((i,e)=>T.on(e,i,this))}uninstallEvents(){this._eventMap.forEach((i,e)=>T.off(e,i,this)),this._eventMap.clear()}stop(){this._renderFreezeMap.clear(),this._dataFreezeMap.clear(),this._isVideoPlayingEventFiredMap.clear()}onVideoTrackMuted(i){if(!i.isSubscribed)return;let{userId:e,streamType:t}=i,s=`${e}_${t}`,n=this._dataFreezeMap.get(s),o=new Vr;n?n.durationItemList.push(o):this._dataFreezeMap.set(s,{userId:e,type:t,durationItemList:[o],isFreezing(){let a=this.durationItemList[this.durationItemList.length-1];return a&&a.endTime===0}})}onVideoTrackUnmuted(i){if(!i.isSubscribed)return;let{userId:e,streamType:t}=i,s=`${e}_${t}`;this.stopDataFreeze({key:s,userId:e,type:t})}onHearBeatReport({room:i,report:e}){!this.hitTest(i)||e.msg_down_stream_info.forEach(t=>{let s=this._room.remotePublishedUserMap.get(t.msg_user_info.str_identifier);if(!s)return;let{userId:n,muteState:o}=s;t.msg_video_status.forEach(a=>{a.uint32_video_stream_type===2&&o.hasVideo&&!o.videoMuted&&s.remoteVideoTrack.isSubscribed&&this.handleRenderFreeze({userId:n,fps:a.uint32_video_dec_fps,type:"main"}),a.uint32_video_stream_type===7&&o.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&this.handleRenderFreeze({userId:n,fps:a.uint32_video_dec_fps,type:"auxiliary"})})})}stopDataFreeze({key:i,userId:e,type:t}){let s=this._dataFreezeMap.get(i);if(!s||!s.isFreezing())return;let n=s.durationItemList[s.durationItemList.length-1];n.stop();let o=n.getDuration();o>gn?this._monitorFreezeData.set(i,{userId:e,type:t,duration:o}):s.durationItemList.pop()}getTotalDuration(i){return i.reduce((e,t)=>{let s=t.getDuration();return e+Math.min(s,5e3)},0)}handleRenderFreeze(s){return p(this,arguments,function*({userId:i,fps:e,type:t}){let n=`${i}_${t}`,o=this._renderFreezeMap.get(n);if(e<=2){let a=L();o&&!o.isFreeze&&(o.freezeTimeline.push({startTime:a,endTime:0}),o.isFreeze=!0),o||this._renderFreezeMap.set(n,{userId:i,type:t,isFreeze:!0,freezeTimeline:[{startTime:a,endTime:0}],renderFreezeTotal:0})}else if(o&&o.isFreeze){o.isFreeze=!1;let a=o.freezeTimeline.pop();if(a){a.endTime=L();let c=a.endTime-a.startTime;o.freezeTimeline.push(a),o.renderFreezeTotal+=Math.min(5e3,c)}}})}onPlayTrackStart({track:i}){if(!ht(i)||!this.hitTest(i.room)||i.kind!==m.VIDEO||i.hasFlag)return;let e=`${i.userId}_${i.streamType}`;this._isVideoPlayingEventFiredMap.has(e)||this._isVideoPlayingEventFiredMap.set(e,!1)}getDataFreezeDuration(i){let e={dataFreeze:0,count:0},t=this._dataFreezeMap.get(i);if(t){if(t.isFreezing()){let s=t.durationItemList[t.durationItemList.length-1];s.stop(),s.getDuration()<gn&&t.durationItemList.pop()}e.dataFreeze=this.getTotalDuration(t.durationItemList),e.count=t.durationItemList.length}return e}getRenderFreezeDuration(i){let e=this._renderFreezeMap.get(i),t=0,s=0;if(e)if(!e.isFreeze)t=e.renderFreezeTotal;else{let n=L(),o=e.freezeTimeline[e.freezeTimeline.length-1],a=n-o.startTime;t=e.renderFreezeTotal+Math.min(a,5e3),s=e.freezeTimeline.length}return{renderFreeze:t,count:s}}getMonitorFreeze(){return this._monitorFreezeData}isBlackStream(i){return this._isVideoPlayingEventFiredMap.has(i)?!this._isVideoPlayingEventFiredMap.get(i):!1}resetMonitor(){this._monitorFreezeData.clear()}hitTest(i){return i===this._room}destroy(){this.uninstallEvents()}},jl=_d;var ql=Ie(ke(),1);var n_=[-1,-1,1,-1,-1,1,1,1],o_=[0,0,1,0,0,1,1,1],qe=class extends U{constructor(e,t){super();this.context=e;u(this,"name");u(this,"input");u(this,"output");u(this,"texture");u(this,"ctx2d",null);u(this,"fbo");u(this,"width",0);u(this,"height",0);u(this,"x",0);u(this,"y",0);u(this,"program");u(this,"vertexShader");u(this,"fragmentShader");u(this,"totalFrames",0);u(this,"dropFrames",0);u(this,"matchInputSize",!0);u(this,"texCoordBuffer");u(this,"positionBuffer");u(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0});u(this,"cost",0);u(this,"_canvas",null);u(this,"_image");if(this.context.on("disconnect",this.close,this),this.name=t.name,this.matchInputSize=t.matchInputSize!==!1,this.width=t.width||e.width,this.height=t.height||e.height,this._image=t.image,e instanceof Xe){if(e.ctx&&t.create2d){let s=document.createElement("canvas"),n=typeof s.transferControlToOffscreen=="function"?s.transferControlToOffscreen():s;n.width=this.width,n.height=this.height,this.ctx2d=n.getContext("2d"),this._image=n,this._canvas=n}return}try{let s=e.ctx;this.texCoordBuffer=this.createBuffer(o_),this.positionBuffer=this.createBuffer(n_),t.createTexture!==!1&&(this.texture=s.createTexture(),this.useTexture(),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),s.pixelStorei(s.PACK_ALIGNMENT,1),s.pixelStorei(s.UNPACK_ALIGNMENT,1)),t.useFbo&&(this.fbo=s.createFramebuffer(),this.useBufferFrame(),this.useTexture(),s.texImage2D(s.TEXTURE_2D,0,s.RGBA,this.width,this.height,0,s.RGBA,s.UNSIGNED_BYTE,null),s.framebufferTexture2D(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0,s.TEXTURE_2D,this.texture,0)),t.useDefaultProgram?this.program=e.defaultProgam:(t.vertexShaderSource||t.fragmentShaderSource)&&(this.vertexShader=t.vertexShaderSource?e.createShader(s.VERTEX_SHADER,t.vertexShaderSource):e.defaultVShader,this.fragmentShader=t.fragmentShaderSource?e.createShader(s.FRAGMENT_SHADER,t.fragmentShaderSource):e.defaultFShader,this.program=e.createProgram(this.vertexShader,this.fragmentShader))}catch(s){this.context.destroy(s)}}get image(){return this._image}set image(e){this._image=e}createFramebuffer(e){let t=this.context.ctx,s=t.createFramebuffer();return t.bindFramebuffer(t.FRAMEBUFFER,s),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0),s}connect(e,...t){return e.addInput(this,...t),this.output=e,e}addInput(e,...t){this.input=e,this.matchInputSize&&e.width&&e.height&&this.resize(e.width,e.height)}requestFrame(e){let t=Date.now();if(this.context instanceof Ce&&this.render(e)||this.context instanceof Xe&&this.render2d(e))this.totalFrames++;else return!1;return this.cost=Date.now()-t,!0}render2d(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?this.draw2d(this.input.image,0,0,this.width,this.height):!1}disconnect(...e){var t;(t=this.output)==null||t.removeInput(this,...e),delete this.output}removeInput(e,...t){delete this.input}close(){var e,t;if(this.context.off("disconnect",this.close,this),(e=this.output)==null||e.removeInput(this),delete this.output,(t=this.input)==null||t.disconnect(),this.context instanceof Ce){let s=this.context.ctx;s.deleteBuffer(this.texCoordBuffer),s.deleteBuffer(this.positionBuffer),this.fbo&&s.deleteFramebuffer(this.fbo),this.texture&&s.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&s.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&s.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&s.deleteProgram(this.program)}this._canvas&&(this._canvas.width=0,this._canvas.height=0,this.ctx2d=null),this.removeAllListeners()}useTexture(){this.useTextures(this.texture)}useInputTexture(){var e;this.useTextures((e=this.input)==null?void 0:e.texture)}useTextures(...e){let t=this.context.ctx;e.forEach((s,n)=>{s&&(t.activeTexture(t.TEXTURE0+n),t.bindTexture(t.TEXTURE_2D,s))})}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){let e=this.context.ctx;e.bindFramebuffer(e.FRAMEBUFFER,this.fbo||null)}createBuffer(e){let t=this.context.ctx,s=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,s),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW),s}setTexBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.texCoordBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}setPosBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}changeBufferData(e,t){let s=this.context.ctx;s.bindBuffer(s.ARRAY_BUFFER,e),s.bufferData(s.ARRAY_BUFFER,new Float32Array(t),s.STATIC_DRAW)}setAttributes(...e){let t=this.context.ctx;e.forEach((s,n)=>{t.enableVertexAttribArray(n),t.bindBuffer(t.ARRAY_BUFFER,s),t.vertexAttribPointer(n,2,t.FLOAT,!1,0,0)})}getVertexPoint(e,t){return[e/this.width*2-1,t/this.height*2-1]}layout2texCoords(e){return[...this.getVertexPoint(e.x,e.y),...this.getVertexPoint(e.x+e.width,e.y),...this.getVertexPoint(e.x,e.y+e.height),...this.getVertexPoint(e.x+e.width,e.y+e.height)]}resize(e,t){if(!(this.width===e&&this.height===t)){if(this.width=e,this.height=t,this._canvas&&(this._canvas.width=e,this._canvas.height=t),this.texture&&this.fbo){this.useTexture();let s=this.context.ctx;s.texImage2D(s.TEXTURE_2D,0,s.RGBA,e,t,0,s.RGBA,s.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(e,t)}}draw(e,t){this.setAttributes(e||this.positionBuffer,t||this.texCoordBuffer);let s=this.context.ctx;s.drawArrays(s.TRIANGLE_STRIP,0,4)}draw2d(e,t,s,n,o){return this.ctx2d&&e?(e instanceof ImageData?this.ctx2d.putImageData(e,t,s):this.ctx2d.drawImage(e,t,s,n,o),!0):!1}getInfo(){var h;let{totalFrames:e,x:t,y:s,width:n,height:o,name:a,cost:c}=this,d=Date.now(),l=(e-this.lastInfo.totalFrames)/((d-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:s,width:n,height:o,timestamp:d,fps:l,name:a,cost:c},N({parent:(h=this.input)==null?void 0:h.getInfo()},this.lastInfo)}createTexture(e){let t=this.context.ctx,s=t.createTexture();return this.useTextures(s),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.pixelStorei(t.PACK_ALIGNMENT,1),t.pixelStorei(t.UNPACK_ALIGNMENT,1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),s}};b([oe(U.INIT,"connected",{sync:!0})],qe.prototype,"connect",1),b([oe("connected",U.INIT,{ignoreError:!0,sync:!0})],qe.prototype,"disconnect",1),b([oe([],"closed",{sync:!0})],qe.prototype,"close",1);var a_=[0,1,1,1,0,0,1,0],Zs=class extends qe{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t));u(this,"_intervalId",0);u(this,"_sequence",0);u(this,"checkGLError",!1);e instanceof Xe?this.ctx2d=e.ctx:e.available&&(t==null?void 0:t.mirrorUpAndDown)&&this.setTexBuffer(a_)}start(e){this._intervalId=Z.run("intervalInWorker",()=>{if(e!==this.context.frameRate&&(Z.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof Ce){let s=this.context.ctx.getError();s&&this.context.destroy(new Error(`${this.name} req ${this._sequence} render ${this.totalFrames} faild ${s}`))}},{fps:this.context.frameRate})}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}addInput(e,...t){super.addInput(e,...t),this.start(this.context.frameRate)}removeInput(e){super.removeInput(e),Z.clearTask(this._intervalId)}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}},Ur=class extends Zs{constructor(e,t){super(e,t);u(this,"_videoTrack");[this._videoTrack]=e._canvas.captureStream(e.frameRate).getVideoTracks();let s=n=>{var c;let o=()=>{var d;return(d=this._videoTrack)==null?void 0:d.removeEventListener(n,a)},a=()=>{o(),this.context.destroy(new Error(`video track ${n}`))};this.once("closed",o),(c=this._videoTrack)==null||c.addEventListener(n,a)};e instanceof Ce&&s("mute"),s("ended")}get videoTrack(){return this._videoTrack}close(){var e;super.close(),(e=this._videoTrack)==null||e.stop(),delete this._videoTrack}},Uo=class extends Ur{render(i){var e;return!!((e=this.input)!=null&&e.requestFrame(i))}};var Bo=class extends Ur{constructor(e,t){super(e,{name:"smallDestination"});this.resolution=t}resize(e,t){let s,n=e*t,o=this.resolution.width*this.resolution.height;I.info(`big res: ${e}*${t} small res: ${this.resolution.width}*${this.resolution.height} `),n>o?s=n/o:(I.warn(`Small stream resolution is not smaller than big stream, which is invalid. big: ${e} * ${t} small: ${this.resolution.width} * ${this.resolution.height}`),s=n/(160*120)),super.resize(e/Math.sqrt(s),t/Math.sqrt(s))}};var en=class extends qe{constructor(e,t){super(e,N({name:"imageSource"},t));u(this,"_lastImage");u(this,"_totalFrames",0);u(this,"_autoResize",!1);this._autoResize=(t==null?void 0:t.autoResize)!==!1}_render(e,t){let{width:s,height:n}=this;if(this.image instanceof HTMLVideoElement){if(G(this.image.getVideoPlaybackQuality)&&!It){let a=this.image.getVideoPlaybackQuality().totalVideoFrames;if(this._totalFrames===a)return!1;this._totalFrames=a,this.dropFrames=this._totalFrames-this.totalFrames}if({videoWidth:s,videoHeight:n}=this.image,!s||!n)return!1;this.image.width=s,this.image.height=n}else if(this.image instanceof HTMLImageElement||this.image instanceof ImageData||this.image instanceof ImageBitmap){if({width:s,height:n}=this.image,this.image!==this._lastImage)this._lastImage=this.image;else if(s===this.width&&n===this.height)return!1}else(this.image instanceof HTMLCanvasElement||this.image instanceof OffscreenCanvas)&&({width:s,height:n}=this.image,this._lastImage=this.image);if(!this._autoResize)return!0;if(this.width===s&&this.height===n&&this.totalFrames){if(t){this.useTexture();let o=this.context.ctx;o.texSubImage2D(o.TEXTURE_2D,0,0,0,o.RGBA,o.UNSIGNED_BYTE,this.image)}}else{if(t){this.useTexture();let o=this.context.ctx;o.texImage2D(o.TEXTURE_2D,0,o.RGBA,o.RGBA,o.UNSIGNED_BYTE,this.image)}this.resize(s,n)}return!0}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},Br=class extends en{constructor(e,t,s){super(e,s);u(this,"_player");this._player=new He({id:s.name,track:t,muted:!0,container:null,objectFit:"contain",log:s.logger}),this.name="videoTrackSource",this._player.play()}get image(){return this._player.element}replaceTrack(e){this._player.setTrack(e)}close(){super.close(),this._player.stop()}};var c_=`
43
+ `),e}removeBandwidthRestriction(e){return e.replace(/b=AS:.*\r\n/,"").replace(/b=TIAS:.*\r\n/,"")}removeVideoOrientation(e){return e.replace(/urn:3gpp:video-orientation/,"")}connect(){return p(this,null,function*(){try{yield this.exchangeSDP(),yield this.waitForPeerConnectionConnected()}catch(e){throw this.closePeerConnection(!0),this.uninstallEvents(),e}})}exchangeSDP(){return p(this,null,function*(){try{yield this.createOffer(),this._log.info("createOffer success, sending offer to remote server"),yield this.doExchangeSDP()}catch(e){throw e}})}createOffer(){return p(this,null,function*(){try{let e=yield this._peerConnection.createOffer(Fl);yield this._peerConnection.setLocalDescription(e),e.sdp&&this.updateSSRC(e.sdp)}catch(e){throw e}})}doExchangeSDP(){let e={command:j.PUBLISH,responseCommand:V.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof Je||this.localAuxVideoTrack instanceof Je,state:this.publishState,constraintConfig:this._mediaSettings},enableLog:!1};return this._log.debug(`sending sdp offer: ${e.data.sdp}`),this._signalChannel.sendWaitForResponse(e).then(t=>{let{code:s,message:n,data:o}=t.data;return s===0?this.acceptAnswer(o):this.checkPublishResultCode(s,n)})}setSDPDirection(e,t,s="all"){let n=ce(e);return n.media.forEach(o=>{(s==="all"||o.type===s)&&(o.direction=t)}),tt(n)}acceptAnswer(e){return p(this,null,function*(){var t,s,n,o,a;try{let c;if(this._publishingLocalAudioTrack||this._publishingLocalVideoTrack||this.isMainStreamPublished){let h=((t=this._publishingLocalVideoTrack)==null?void 0:t.profile.bitrate)||((s=this.localMainVideoTrack)==null?void 0:s.profile.bitrate),_=((n=this._publishingLocalAudioTrack)==null?void 0:n.profile.bitrate)||((o=this.localMainAudioTrack)==null?void 0:o.profile.bitrate);if(h){let f=this._isPublishingAux?m.AUXILIARY:m.BIG;c=yield this.setBandwidth({bandwidth:h,type:m.VIDEO,sdp:c,videoType:f})}_&&(c=yield this.setBandwidth({bandwidth:_,type:m.AUDIO,sdp:c}))}if(c=this.removeVideoOrientation(e.sdp),(a=this._publishingLocalVideoTrack)!=null&&a.small){let{smallStreamConfig:h}=this._room;c=yield this.setBandwidth({bandwidth:this._publishingLocalVideoTrack.small.bitrate||h.bitrate,type:m.VIDEO,videoType:m.SMALL,sdp:c})}let l={type:e.type,sdp:c};yield this._peerConnection.setRemoteDescription(l),this._log.debug(`accepted answer: ${c}`)}catch(c){throw this._log.error(`failed to accept remote answer ${c}`),c}})}sendMutedFlag(e){var n,o,a;if(e===this.localAuxAudioTrack||e===this.localAuxVideoTrack)return;let s={audio:!!((n=this.localMainAudioTrack)!=null&&n.muted),bigVideo:!!((o=this.localMainVideoTrack)!=null&&o.muted),auxVideo:!!((a=this.localAuxVideoTrack)!=null&&a.muted)};this._log.info(`send muted state: ${JSON.stringify(s)}`),this._signalChannel.send(j.UPDATE_MUTE_STAT,s)}getIsReconnecting(){return this._isReconnecting}reconnect(){return p(this,null,function*(){if(!(Ee(ld.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:j.UNPUBLISH,responseCommand:V.UNPUBLISH_RESULT,enableLog:!1}),this.closePeerConnection(),this.initialize(),this.isMainStreamPublished&&(yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0})),this._log.warn("reconnect() uplink reconnect successfully"),this.stopReconnection()}catch(t){let s=bt(this._reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${s/1e3}s`),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},s)}})}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&T.emit(E.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{ce(e).media.forEach((s,n)=>{if(s.type===m.AUDIO){let o=s.ssrcs&&s.ssrcs[0];o&&(this.ssrc.audio=Number(o.id))}else{if(this._sdpSemantics===er&&s.ssrcGroups){s.ssrcGroups.forEach((a,c)=>{let d=Number(a.ssrcs.split(" ")[0]);c===0?this.ssrc.video=d:c===1&&(this.ssrc.small=d)});return}let o=s.ssrcs&&s.ssrcs[0];if(!o)return;switch(n){case 1:this.ssrc.video=Number(o.id);break;case 2:this.ssrc.small=Number(o.id);break;case 3:this.ssrc.auxiliary=Number(o.id);break;default:break}}})}catch(t){}}getVideoTrackId(e=m.VIDEO){if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===m.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===m.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===m.VIDEO){let t=this.localMainVideoTrack.mediaTrack;if(t)return t.id}if(this.localAuxVideoTrack&&e===m.AUXILIARY){let t=this.localAuxVideoTrack.mediaTrack;if(t)return t.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(e!==0)throw e===Di?(this._log.error(ge.NOT_SUPPORTED_H264ENCODE),new C({code:A.NOT_SUPPORTED_H264,message:M({key:O.NOT_SUPPORTED_H264ENCODE})})):new C({code:A.UNKNOWN,message:M({key:O.SIGNAL_RESPONSE_FAILED,data:{signalResponse:V.PUBLISH_RESULT,code:e,message:t}})})}sendSEI(e,t){var s;(s=this._sei)==null||s.push(e,t)}},zs=ld;b([W(r=>function(...i){return new Promise((e,t)=>{let s=n=>{this._emitter.off("closed",s),t(new C({code:A.API_CALL_ABORTED,message:M({key:O.CONNECTION_ABORTED,data:n})}))};this._emitter.on("closed",s),r.apply(this,i).then(e,t).finally(()=>{this._emitter.off("closed",s)})})})],zs.prototype,"publish",1),b([yr(je.prototype.afterConnect),no(je.prototype.beforeConnect)],zs.prototype,"connect",1);var wo=zs;var Ks=class{constructor(i,e){this.room=i;u(this,"_log");u(this,"_prevReportTime");u(this,"_prevReport",{});u(this,"_prevEncoderImplementation");u(this,"_prevQualityLimitationReason");u(this,"_prevAuxQualityLimitationReason");u(this,"_prevDecoderImplementationMap",new Map);u(this,"totalBytesSent",0);u(this,"totalBytesReceived",0);u(this,"_spcStats",null);this._log=e,this._prevReportTime=0,this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevAuxQualityLimitationReason=""}get statInterval(){return this._prevReportTime===0?2:(Date.now()-this._prevReportTime)/1e3}getSenderStats(i){return p(this,null,function*(){let e={audio:{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0},video:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},small:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},auxiliary:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},rtt:0},t=i.getPeerConnection(),s=i.getSSRC();if(t)try{if((this._spcStats||(yield t.getStats())).forEach(o=>{var a;if(o.type==="outbound-rtp")if((o.mediaType||o.kind)===m.VIDEO){let d,l;if(o.ssrc===s.video?(d=m.VIDEO,l=i.localMainVideoTrack):o.ssrc===s.small?d=m.SMALL:o.ssrc===s.auxiliary&&(l=i.localAuxVideoTrack,d=m.AUXILIARY),!d)return;e[d].bytesSent=o.bytesSent,e[d].packetsSent=o.packetsSent,e[d].framesEncoded=o.framesEncoded,g(o.keyFramesEncoded)||(e[d].keyFramesEncoded=o.keyFramesEncoded),g(o.nackCount)||(e[d].nackCount=o.nackCount),g(o.pliCount)||(e[d].pliCount=o.pliCount),g(o.retransmittedPacketsSent)||(e[d].retransmittedPacketsSent=o.retransmittedPacketsSent),g(o.totalEncodeTime)||(e[d].totalEncodeTime=o.totalEncodeTime),g(o.totalPacketSendDelay)||(e[d].totalPacketSendDelay=o.totalPacketSendDelay),o.ssrc===s.video?(!g(o.encoderImplementation)&&this._prevEncoderImplementation!==o.encoderImplementation&&(this._log.info(`encoderImplementation change to ${o.encoderImplementation}`),this._prevEncoderImplementation=o.encoderImplementation),!g(o.qualityLimitationReason)&&o.bytesSent!==0&&this._prevQualityLimitationReason!==o.qualityLimitationReason&&(this._log.info(`qualityLimitationReason change to ${o.qualityLimitationReason}`),this._prevQualityLimitationReason=o.qualityLimitationReason)):o.ssrc===s.auxiliary&&!g(o.qualityLimitationReason)&&o.bytesSent!==0&&this._prevAuxQualityLimitationReason!==o.qualityLimitationReason&&(this._log.info(`aux qualityLimitationReason change to ${o.qualityLimitationReason}`),this._prevAuxQualityLimitationReason=o.qualityLimitationReason)}else e.audio.bytesSent=o.bytesSent,e.audio.packetsSent=o.packetsSent;else o.type==="candidate-pair"?gi(o)&&re(o.currentRoundTripTime)&&(e.rtt=Math.floor(o.currentRoundTripTime*1e3),this.totalBytesSent=o.bytesSent):o.type==="media-source"&&(o.kind===m.AUDIO?(e.audio.audioLevel=o.audioLevel||0,e.audio.totalAudioEnergy=o.totalAudioEnergy||0):o.kind===m.VIDEO&&(o.trackIdentifier===i.getVideoTrackId(m.VIDEO)?e.video.fpsCapture=o.framesPerSecond:o.trackIdentifier===i.getVideoTrackId(m.AUXILIARY)?e.auxiliary.fpsCapture=o.framesPerSecond:e.small.fpsCapture=o.framesPerSecond));if(!g(o.audioLevel)&&((a=i.localMainAudioTrack)==null?void 0:a.mediaTrack)&&o.trackIdentifier===i.localMainAudioTrack.mediaTrack.id&&(e.audio.audioLevel=o.audioLevel||0),!g(o.frameWidth)){let c=m.SMALL;o.trackIdentifier===i.getVideoTrackId(m.VIDEO)||o.ssrc===s.video?c=m.VIDEO:(o.trackIdentifier===i.getVideoTrackId(m.AUXILIARY)||o.ssrc===s.auxiliary)&&(c=m.AUXILIARY),e[c].frameWidth=o.frameWidth,e[c].frameHeight=o.frameHeight,e[c].framesSent=o.framesSent}}),i.localMainAudioTrack){let o=i.localMainAudioTrack.getInternalAudioLevel();e.audio.micAudioLevel=o,e.audio.audioLevel===0&&(e.audio.audioLevel=o)}this.totalBytesSent||(this.totalBytesSent+=e.audio.bytesSent+e.video.bytesSent+e.auxiliary.bytesSent)}catch(n){this._log.warn(`failed to getStats on sender connection ${n}`)}return e})}getReceiverStats(i){return p(this,null,function*(){let e={tinyId:i.tinyId,userId:i.userId,rtt:0,hasAudio:!1,hasVideo:!1,hasAuxiliary:!1,isSmallSubscribed:!1,audio:{bytesReceived:0,packetsReceived:0,packetsLost:0,p2pDelay:0,totalJitter:0,totalJitterCount:0,audioLevel:0,totalAudioEnergy:0,insertedSamplesForDeceleration:0,removedSamplesForAcceleration:0},video:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0},auxiliary:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0}},t=i.getPeerConnection();if(t)try{let{ssrc:s}=i,{muteState:n,subscribeState:o}=i;(this._spcStats||(yield t.getStats())).forEach(c=>{if(c.type==="inbound-rtp")if((c.mediaType||c.kind)===m.AUDIO){if(c.ssrc!==s.audio||!n.hasAudio)return;e.audio.packetsReceived=c.packetsReceived,e.audio.bytesReceived=c.bytesReceived,e.audio.packetsLost=c.packetsLost,c.insertedSamplesForDeceleration&&(e.audio.insertedSamplesForDeceleration=c.insertedSamplesForDeceleration),c.removedSamplesForAcceleration&&(e.audio.removedSamplesForAcceleration=c.removedSamplesForAcceleration);let{remoteAudioTrack:l}=i;l.stat.packetsReceived=c.packetsReceived,l.stat.bytesReceived=c.bytesReceived,l.stat.packetsLost=c.packetsLost,e.audio.p2pDelay=l.stat.end2EndDelay,c.jitterBufferDelay&&(e.audio.totalJitter=c.jitterBufferDelay,e.audio.totalJitterCount=c.jitterBufferEmittedCount),e.hasAudio=!0}else{if(Y&&c.bytesReceived===0)return;let l;c.ssrc===s.video&&n.hasVideo&&(e.video.packetsReceived=c.packetsReceived,e.video.bytesReceived=c.bytesReceived,e.video.packetsLost=c.packetsLost,e.video.framesReceived=c.framesReceived,e.video.framesDecoded=c.framesDecoded,e.video.fpsDecoded=c.framesPerSecond,e.hasVideo=!0,l=i.remoteVideoTrack,n.hasSmall&&o.smallVideo&&(e.isSmallSubscribed=!0),c.decoderImplementation&&(!this._prevDecoderImplementationMap.has(e.userId)||this._prevDecoderImplementationMap.get(e.userId)!==c.decoderImplementation)&&(this._log.info(`${e.userId} decoderImplementation change to ${c.decoderImplementation}`),this._prevDecoderImplementationMap.set(e.userId,c.decoderImplementation))),c.ssrc===s.auxiliary&&n.hasAuxiliary&&(e.auxiliary.packetsReceived=c.packetsReceived,e.auxiliary.bytesReceived=c.bytesReceived,e.auxiliary.packetsLost=c.packetsLost,e.auxiliary.framesReceived=c.framesReceived,e.auxiliary.framesDecoded=c.framesDecoded,e.auxiliary.fpsDecoded=c.framesPerSecond,l=i.remoteAuxiliaryTrack,e.hasAuxiliary=!0),l&&(l.stat.packetsReceived=c.packetsReceived,l.stat.bytesReceived=c.bytesReceived,l.stat.packetsLost=c.packetsLost,l.stat.framesReceived=c.framesReceived,l.stat.framesDecoded=c.framesDecoded,c.jitterBufferDelay&&(l.stat.jitterBufferDelay=Math.floor(c.jitterBufferDelay/c.jitterBufferEmittedCount*1e3)))}else c.type==="candidate-pair"&&gi(c)&&re(c.currentRoundTripTime)&&(e.rtt=Math.floor(c.currentRoundTripTime*1e3),this.totalBytesReceived=c.bytesReceived);g(c.frameWidth)||((c.trackIdentifier===i.getMainStreamVideoTrackId()||c.ssrc===s.video)&&(e.video.frameWidth=c.frameWidth,e.video.frameHeight=c.frameHeight,i.remoteVideoTrack.stat.frameWidth=c.frameWidth,i.remoteVideoTrack.stat.frameHeight=c.frameHeight),(c.trackIdentifier===i.getAuxStreamVideoTrackId()||c.ssrc===s.auxiliary)&&(e.auxiliary.frameWidth=c.frameWidth,e.auxiliary.frameHeight=c.frameHeight,i.remoteAuxiliaryTrack.stat.frameWidth=c.frameWidth,i.remoteAuxiliaryTrack.stat.frameHeight=c.frameHeight)),!g(c.audioLevel)&&i.muteState.audioAvailable&&i.remoteAudioTrack.mediaTrack&&c.trackIdentifier===i.remoteAudioTrack.mediaTrack.id&&(e.audio.audioLevel=c.audioLevel||0,e.audio.totalAudioEnergy=c.totalAudioEnergy||0)}),e.audio.audioLevel===0&&i.muteState.audioAvailable&&(e.audio.audioLevel=i.remoteAudioTrack.getInternalAudioLevel()||0),this.totalBytesReceived||(this.totalBytesReceived+=e.audio.bytesReceived+e.video.bytesReceived+e.auxiliary.bytesReceived)}catch(s){this._log.warn(`failed to getStats on receiver connection ${s}`)}return e})}getStats(i,e){return p(this,null,function*(){let t={},s=[];if(this.room.singlePC){let n=this.room.singlePC.getPeerConnection();if(!n)return{senderStats:t,receiverStats:s};let o=L(),a=yield n.getStats(),c=L();c-o>2e3&&this._log.warn(`getStats cost ${c-o}ms`);let d=[],l=new Set(["inbound-rtp","outbound-rtp","track","candidate-pair","media-source"]);a.forEach(h=>l.has(h.type)&&d.push(h)),this._spcStats=d}i&&(t=yield this.getSenderStats(i));for(let[n,o]of e){let a=yield this.getReceiverStats(o);s.push(a)}return{senderStats:t,receiverStats:s}})}getDifferenceValue(i,e){if(Ot(i))return e;let t=e-i;return t<0?0:t}prepareReport({stats:i,report:e,freezeMap:t}){if(!Ot(i.senderStats)){let l={uint32_audio_level:i.senderStats.audio.audioLevel*nt,uint32_audio_energy:i.senderStats.audio.totalAudioEnergy*1e6,uint32_audio_codec_bitrate:i.senderStats.audio.bytesSent};i.senderStats.audio.micAudioLevel&&(l.uint32_mic_audio_level=i.senderStats.audio.micAudioLevel*nt);let h=[];if(i.senderStats.video.bytesSent){let f={uint32_video_stream_type:2,uint32_video_codec_fps:i.senderStats.video.framesSent,uint32_video_capture_fps:i.senderStats.video.fpsCapture,uint32_video_width:i.senderStats.video.frameWidth,uint32_video_height:i.senderStats.video.frameHeight,uint32_video_codec_bitrate:i.senderStats.video.bytesSent,uint32_video_enc_fps:i.senderStats.video.framesEncoded,uint32_key_frame_count:i.senderStats.video.keyFramesEncoded,uint32_nack_count:i.senderStats.video.nackCount,uint32_pli_count:i.senderStats.video.pliCount,uint32_encode_cost:(i.senderStats.video.totalEncodeTime||0)*1e3,uint32_send_packet_cost:(i.senderStats.video.totalPacketSendDelay||0)*1e3,uint32_video_arq_packets:i.senderStats.video.retransmittedPacketsSent};h.push(f)}if(i.senderStats.small.bytesSent){let f={uint32_video_stream_type:3,uint32_video_codec_fps:i.senderStats.small.framesSent||0,uint32_video_capture_fps:i.senderStats.small.fpsCapture||0,uint32_video_width:i.senderStats.small.frameWidth||0,uint32_video_height:i.senderStats.small.frameHeight||0,uint32_video_codec_bitrate:i.senderStats.small.bytesSent,uint32_video_enc_fps:i.senderStats.small.framesEncoded||0,uint32_key_frame_count:i.senderStats.small.keyFramesEncoded,uint32_nack_count:i.senderStats.small.nackCount,uint32_pli_count:i.senderStats.small.pliCount,uint32_encode_cost:(i.senderStats.small.totalEncodeTime||0)*1e3,uint32_send_packet_cost:(i.senderStats.small.totalPacketSendDelay||0)*1e3,uint32_video_arq_packets:i.senderStats.small.retransmittedPacketsSent};h.push(f)}if(i.senderStats.auxiliary.bytesSent){let f={uint32_video_stream_type:7,uint32_video_codec_fps:i.senderStats.auxiliary.framesSent||0,uint32_video_capture_fps:i.senderStats.auxiliary.fpsCapture||0,uint32_video_width:i.senderStats.auxiliary.frameWidth||0,uint32_video_height:i.senderStats.auxiliary.frameHeight||0,uint32_video_codec_bitrate:i.senderStats.auxiliary.bytesSent,uint32_video_enc_fps:i.senderStats.auxiliary.framesEncoded||0,uint32_key_frame_count:i.senderStats.auxiliary.keyFramesEncoded,uint32_nack_count:i.senderStats.auxiliary.nackCount,uint32_pli_count:i.senderStats.auxiliary.pliCount,uint32_encode_cost:(i.senderStats.auxiliary.totalEncodeTime||0)*1e3,uint32_send_packet_cost:(i.senderStats.auxiliary.totalPacketSendDelay||0)*1e3,uint32_video_arq_packets:i.senderStats.auxiliary.retransmittedPacketsSent};h.push(f)}let _={uint32_bitrate:0,uint32_lost:0,uint32_rtt:i.senderStats.rtt};e.msg_up_stream_info={msg_audio_status:l,msg_video_status:h,msg_network_status:_}}let{statInterval:s}=this;e.msg_down_stream_info=[],i.receiverStats.forEach(l=>{let h={msg_user_info:{str_identifier:l.userId,uint64_tinyid:l.tinyId},msg_network_status:{uint32_rtt:l.rtt,uint32_bitrate:0,uint32_lost:0},msg_audio_status:{},msg_video_status:[]};if(l.hasAudio){let _={uint32_audio_p2p_delay:l.audio.p2pDelay,uint32_audio_cache_ms:l.audio.totalJitter,uint32_audio_cache_ms_count:l.audio.totalJitterCount,uint32_audio_codec_bitrate:l.audio.bytesReceived,uint32_audio_total_bitrate:l.audio.bytesReceived,uint32_audio_level:l.audio.audioLevel*1e8,uint32_audio_energy:l.audio.totalAudioEnergy*1e6,uint32_audio_receive:l.audio.packetsReceived,uint32_audio_origin_lost:l.audio.packetsLost};h.msg_audio_status=_}if(l.hasVideo){let _=t.get(`${l.userId}_${na}`),f=_?_.duration:0,R={uint32_video_stream_type:l.isSmallSubscribed?3:2,uint32_video_receive_fps:l.video.framesReceived,uint32_video_width:l.video.frameWidth,uint32_video_height:l.video.frameHeight,uint32_video_codec_bitrate:l.video.bytesReceived,uint32_video_receive:l.video.packetsReceived,uint32_video_origin_lost:l.video.packetsLost,uint32_video_block_time:f,uint32_video_dec_fps:l.video.framesDecoded};h.msg_video_status.push(R)}if(l.hasAuxiliary){let _=t.get(`${l.userId}_${oa}`),f=_?_.duration:0,R={uint32_video_stream_type:7,uint32_video_receive_fps:l.auxiliary.framesReceived,uint32_video_width:l.auxiliary.frameWidth,uint32_video_height:l.auxiliary.frameHeight,uint32_video_codec_bitrate:l.auxiliary.bytesReceived,uint32_video_receive:l.auxiliary.packetsReceived+l.auxiliary.packetsLost,uint32_video_origin_lost:l.auxiliary.packetsLost,uint32_video_block_time:f,uint32_video_dec_fps:l.auxiliary.framesDecoded};h.msg_video_status.push(R)}e.msg_down_stream_info.push(h)});let n=this._prevReport;if(this._prevReport=JSON.parse(JSON.stringify(e)),e.msg_up_stream_info.msg_audio_status&&n.msg_up_stream_info.msg_audio_status){let l=n.msg_up_stream_info.msg_audio_status,h=e.msg_up_stream_info.msg_audio_status;if(l.uint32_audio_codec_bitrate===0)h.uint32_audio_codec_bitrate=0;else{let _=this.getDifferenceValue(l.uint32_audio_codec_bitrate,h.uint32_audio_codec_bitrate);h.uint32_audio_codec_bitrate=Math.round(_*8/s),e.msg_up_stream_info.msg_network_status.uint32_bitrate+=h.uint32_audio_codec_bitrate}}let o=n.msg_up_stream_info.msg_video_status;e.msg_up_stream_info.msg_video_status.forEach(l=>{let h=o.find(w=>w.uint32_video_stream_type===l.uint32_video_stream_type);if(!h||h.uint32_video_codec_bitrate===0){l.uint32_video_codec_bitrate=0,l.uint32_video_enc_fps=0,l.uint32_video_codec_fps=0;return}let _=0,f=0,R=0;h&&l.uint32_video_codec_bitrate>=h.uint32_video_codec_bitrate&&(_=h.uint32_video_codec_bitrate,f=h.uint32_video_enc_fps,R=h.uint32_video_codec_fps);let y=this.getDifferenceValue(_,l.uint32_video_codec_bitrate);l.uint32_video_codec_bitrate=Math.round(y*8/s),e.msg_up_stream_info.msg_network_status.uint32_bitrate+=l.uint32_video_codec_bitrate,l.uint32_video_enc_fps=Math.round(this.getDifferenceValue(f,l.uint32_video_enc_fps)/s),l.uint32_video_codec_fps=Math.round(this.getDifferenceValue(R,l.uint32_video_codec_fps)/s),mi&&Gt()===115&&h.uint32_video_width===0&&h.uint32_video_height===0&&h.uint32_video_codec_fps===0&&(l.uint32_video_codec_fps=l.uint32_video_enc_fps),g(h.uint32_key_frame_count)||(l.uint32_key_frame_count=Math.round(this.getDifferenceValue(h.uint32_key_frame_count,l.uint32_key_frame_count))),g(h.uint32_nack_count)||(l.uint32_nack_count=Math.round(this.getDifferenceValue(h.uint32_nack_count,l.uint32_nack_count))),g(h.uint32_pli_count)||(l.uint32_pli_count=Math.round(this.getDifferenceValue(h.uint32_pli_count,l.uint32_pli_count))),g(h.uint32_video_arq_packets)||(l.uint32_video_arq_packets=Math.round(this.getDifferenceValue(h.uint32_video_arq_packets,l.uint32_video_arq_packets))),g(h.uint32_encode_cost)||(l.uint32_encode_cost=Math.round(this.getDifferenceValue(h.uint32_encode_cost,l.uint32_encode_cost)/s)),g(h.uint32_send_packet_cost)||(l.uint32_send_packet_cost=Math.round(this.getDifferenceValue(h.uint32_send_packet_cost,l.uint32_send_packet_cost)/s))});let c=n.msg_down_stream_info;return e.msg_down_stream_info=e.msg_down_stream_info.filter(l=>c.find(h=>h.msg_user_info.uint64_tinyid===l.msg_user_info.uint64_tinyid)),e.msg_down_stream_info.forEach(l=>{let h=c.find(_=>_.msg_user_info.uint64_tinyid===l.msg_user_info.uint64_tinyid);if(!Ot(l.msg_audio_status)&&!Ot(h.msg_audio_status)){let _=l.msg_audio_status,f=h.msg_audio_status,R=this.getDifferenceValue(f.uint32_audio_cache_ms_count,_.uint32_audio_cache_ms_count);delete _.uint32_audio_cache_ms_count,_.uint32_audio_cache_ms=Math.floor(1e3*this.getDifferenceValue(f.uint32_audio_cache_ms,_.uint32_audio_cache_ms)/R)||0;let y=this.room.remotePublishedUserMap.get(l.msg_user_info.str_identifier);y&&(y.remoteAudioTrack.stat.jitterBufferDelay=_.uint32_audio_cache_ms),_.uint32_audio_origin_lost=this.getDifferenceValue(f.uint32_audio_origin_lost,_.uint32_audio_origin_lost),_.uint32_audio_receive=this.getDifferenceValue(f.uint32_audio_receive,_.uint32_audio_receive),_.uint32_audio_receive+=_.uint32_audio_origin_lost;let w=this.getDifferenceValue(f.uint32_audio_codec_bitrate,_.uint32_audio_codec_bitrate);_.uint32_audio_codec_bitrate=Math.round(w*8/s),_.uint32_audio_total_bitrate=Math.round(w*8/s)}else l.msg_audio_status={};if(l.msg_video_status&&h.msg_video_status){let _=h.msg_video_status;l.msg_video_status=l.msg_video_status.filter(R=>_.find(y=>y.uint32_video_stream_type===R.uint32_video_stream_type)),l.msg_video_status.forEach(R=>{let y=_.find(hh=>hh.uint32_video_stream_type===R.uint32_video_stream_type),w=y.uint32_video_receive,ie=y.uint32_video_origin_lost,nn=y.uint32_video_codec_bitrate,on=y.uint32_video_receive_fps,uh=y.uint32_video_dec_fps;R.uint32_video_origin_lost=this.getDifferenceValue(ie,R.uint32_video_origin_lost),R.uint32_video_receive=this.getDifferenceValue(w,R.uint32_video_receive)+R.uint32_video_origin_lost;let H=this.getDifferenceValue(nn,R.uint32_video_codec_bitrate);R.uint32_video_codec_bitrate=Math.round(H*8/s);let lh=this.getDifferenceValue(on,R.uint32_video_receive_fps);R.uint32_video_receive_fps=Math.round(lh/s),R.uint32_video_dec_fps=Math.round(this.getDifferenceValue(uh,R.uint32_video_dec_fps)/s)})}}),e}getStatsReport(s){return p(this,arguments,function*({uplinkConnection:i,downlinkConnections:e,freezeMap:t}){let n={msg_up_stream_info:{msg_audio_status:{uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_level:0,uint32_audio_energy:0},msg_video_status:[],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}},msg_down_stream_info:[{msg_user_info:{str_identifier:"",uint64_tinyid:0},msg_audio_status:{uint32_audio_cache_ms:0,uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_total_bitrate:0,uint32_audio_level:0,uint32_audio_energy:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_final_lost:0},msg_video_status:[{uint32_video_stream_type:0,uint32_video_receive_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_codec_bitrate:0,uint32_video_receive:0,uint32_video_origin_lost:0,uint32_video_block_time:0,uint32_video_dec_fps:0}],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}}]},o=yield this.getStats(i,e);return JSON.stringify(this._prevReport)==="{}"&&(this._prevReport=JSON.parse(JSON.stringify(n))),this.prepareReport({stats:o,report:n,freezeMap:t}),this._prevReportTime=Date.now(),n})}reset(){this._prevReportTime=0,this._prevReport={},this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevDecoderImplementationMap=new Map}};var Gl=Ie(ke());var hd=class extends Gl.default{constructor({signalChannel:e,room:t}){super();u(this,"_room");u(this,"_signalChannel");u(this,"_log");u(this,"_uplinkRTT",0);u(this,"_uplinkLoss",0);u(this,"_downlinkRTT",0);u(this,"_downlinkLoss",0);u(this,"_downlinkPrevStatMap",new Map);u(this,"_downlinkLossAndRTTMap",new Map);u(this,"_interval",-1);u(this,"_uplinkNetworkQuality",0);u(this,"_downlinkNetworkQuality",0);this._room=t,this._signalChannel=e,this._log=I.createLogger({id:"q",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this.initialize()}get uplinkNetworkQuality(){return this._uplinkNetworkQuality}set uplinkNetworkQuality(e){e!==this._uplinkNetworkQuality&&this._log.info(`uplink ${this.uplinkNetworkQuality} -> ${e}, rtt: ${this._uplinkRTT}, loss: ${this._uplinkLoss}`),this._uplinkNetworkQuality=e}get downlinkNetworkQuality(){return this._downlinkNetworkQuality}set downlinkNetworkQuality(e){if(e!==this._downlinkNetworkQuality){let{rtt:t,loss:s}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._log.info(`downlink ${this.downlinkNetworkQuality} -> ${e}, rtt: ${t}, loss: ${s}`)}this._downlinkNetworkQuality=e}initialize(){this._signalChannel.on(V.UPLINK_NETWORK_STATS,e=>{this.handleUplinkNetworkQuality(e)}),this._signalChannel.on(le.CONNECTION_STATE_CHANGED,this.handleSignalConnectionStateChange.bind(this)),this.start()}handleUplinkNetworkQuality(e){var c,d;if(e.data.code!==0)return;let t=e.data.data;if(t.delay&&this.updateDelay(t.delay),!this._room.uplinkConnection){this.uplinkNetworkQuality=0,this._uplinkLoss=0,this._uplinkRTT=0;return}let s=(d=(c=this._room)==null?void 0:c.uplinkConnection)==null?void 0:d.getPeerConnection();if(s&&this.isPeerConnectionDisconnected(s)){this.uplinkNetworkQuality=6,this._uplinkLoss=0,this._uplinkRTT=0;return}let n=t.expectAudPkg+t.expectVidPkg,o=t.recvAudPkg+t.recvVidPkg,a=n-o;n===0&&o===0||(a<=0?this._uplinkLoss=0:this._uplinkLoss=Math.round(a/n*100),this._uplinkRTT=t.rtt,this.uplinkNetworkQuality=this.getNetworkQuality(this._uplinkLoss,this._uplinkRTT))}handleDownlinkNetworkQuality(){return p(this,null,function*(){if(this._room.remotePublishedUserMap.size===0){this.downlinkNetworkQuality=0;return}let e=[...this._room.remotePublishedUserMap.values()],t=e.filter(a=>{var c;return((c=a.getPeerConnection())==null?void 0:c.connectionState)===se.CONNECTED});if(e.filter(a=>this.isPeerConnectionDisconnected(a.getPeerConnection())).length===e.length){this.downlinkNetworkQuality=6;return}for(let a=0;a<t.length;a++){let c=t[a].getPeerConnection();if(!c)return;let{rtt:d,totalPacketsLost:l,totalPacketsReceived:h}=yield this.getStat(c);if(!this._downlinkPrevStatMap.has(c)){this._downlinkPrevStatMap.set(c,{totalPacketsLost:l,totalPacketsReceived:h});continue}let _=0,f=this._downlinkPrevStatMap.get(c),R=l-f.totalPacketsLost,y=h-f.totalPacketsReceived;R<=0||y<0?_=0:_=Math.round(R/(R+y)*100),this._downlinkPrevStatMap.set(c,{totalPacketsLost:l,totalPacketsReceived:h}),this._downlinkLossAndRTTMap.set(c,{rtt:d,loss:_,userId:t[a].getUserId(),audioDelay:t[a].remoteAudioTrack.stat.end2EndDelay,videoDelay:t[a].remoteVideoTrack.stat.end2EndDelay})}if([...this._downlinkPrevStatMap.keys()].forEach(a=>{this.isPeerConnectionDisconnected(a)&&(this._downlinkPrevStatMap.delete(a),this._downlinkLossAndRTTMap.delete(a))}),this._downlinkLossAndRTTMap.size===0)return;let{rtt:n,loss:o}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._downlinkRTT=n,this._downlinkLoss=o,this.downlinkNetworkQuality=this.getNetworkQuality(o,n)})}getStat(e){return p(this,null,function*(){let t={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!Pi())return t;let s=e.getReceivers();try{for(let n=0;n<s.length;n++)(yield s[n].getStats()).forEach(c=>{c.type==="candidate-pair"&&re(c.currentRoundTripTime)&&(t.rtt=Math.round(c.currentRoundTripTime*1e3)),c.type==="inbound-rtp"&&(c.mediaType===m.AUDIO||c.mediaType===m.VIDEO)&&(t.totalPacketsLost+=c.packetsLost,t.totalPacketsReceived+=c.packetsReceived)});return t}catch(n){return t}})}getAverageLossAndRTT(e){let t={rtt:0,loss:0};return Array.isArray(e)&&e.length>0&&(e.forEach(s=>{t.rtt+=s.rtt,t.loss+=s.loss}),Object.keys(t).forEach(s=>{t[s]=Math.round(t[s]/e.length)})),t}getNetworkQuality(e,t){return e>50||t>500?5:e>30||t>350?4:e>20||t>200?3:e>10||t>100?2:e>=0||t>=0?1:0}handleSignalConnectionStateChange(e){e.state==="DISCONNECTED"?(this._uplinkRTT=0,this._uplinkLoss=0,this.uplinkNetworkQuality=6):e.state==="CONNECTED"&&this.uplinkNetworkQuality===6&&(this.uplinkNetworkQuality=5)}handleUplinkConnectionStateChange({state:e}){e==="DISCONNECTED"?(this._uplinkLoss=0,this._uplinkRTT=0,this.uplinkNetworkQuality=6):e==="CONNECTED"&&this.uplinkNetworkQuality===6&&(this.uplinkNetworkQuality=5)}isPeerConnectionDisconnected(e){return!!(e&&(e.connectionState===se.DISCONNECTED||e.connectionState===se.FAILED||e.connectionState===se.CLOSED))}setUplinkConnection(e){this._room.uplinkConnection=e,this._room.uplinkConnection?this._room.uplinkConnection.on("connection-state-changed",this.handleUplinkConnectionStateChange.bind(this)):(this.uplinkNetworkQuality=0,this._uplinkRTT=0,this._uplinkLoss=0)}start(){if(this._interval!==-1){this._log.info("network quality calculating is already started");return}this._log.debug("start network quality calculating"),this._interval=Z.run(gt,()=>{this.handleDownlinkNetworkQuality();let e=[...this._downlinkLossAndRTTMap.values()];T.emit(E.NETWORK_QUALITY,{room:this._room,uplink:{rtt:this._uplinkRTT,loss:this._uplinkLoss},downlinks:e}),this.emit(hd.EVENT_NETWORK_QUALITY,{uplinkNetworkQuality:this.uplinkNetworkQuality,downlinkNetworkQuality:this.downlinkNetworkQuality,uplinkRTT:this._uplinkRTT,uplinkLoss:this._uplinkLoss,downlinkRTT:this._downlinkRTT,downlinkLoss:this._downlinkLoss,downlinkInfo:e})},{delay:2e3})}stop(){this._log.debug("stopped"),this._interval!==-1&&(Z.clearTask(this._interval),this._interval=-1),this._downlinkLossAndRTTMap.clear(),this._downlinkPrevStatMap.clear()}updateDelay(e){let{tinyIdToUserIdMap:t}=this._room;e.forEach(({srcTinyId:s,videoDelay:n,audioDelay:o})=>{let a=t.get(s);if(a){let c=this._room.remotePublishedUserMap.get(a);c==null||c.setDelay({videoDelay:n,audioDelay:o})}})}},Qi=hd;u(Qi,"EVENT_NETWORK_QUALITY","0");function r_({fn:r,context:i}){return function(...e){try{let t=r.apply(i,e);return Es(t)?t.catch(s=>I.error(`${r.name}() error observed ${s}`)):t}catch(t){I.error(`${r.name}() error observed ${t}`)}}}var Vo=class{constructor(i){this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0};this._eventMap=new Map;this._frameWorkType=i.frameWorkType||30,this._component=i.component||0,this.connectionType=i.connectionType||1,this._language=i.language||0,this._room=i.room,this._keyPrefix="key_point",this._log=I.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach(e=>{e.startsWith("handle")&&G(this[e])&&(this[e]=r_({fn:this[e],context:this}))}),this.initData(),this.installEvents(),this._intervalId=Z.run(gt,this.setStorage.bind(this),{delay:2e4})}get _storageKey(){return`${this._keyPrefix}_${this._room.userId}`}initData(){this._firstPublishedUserList=[],this._networkQuality={totalUplinkRTT:0,totalUplinkLoss:0,count:0,totalDownlinkRTTAndLossMap:new Map},this._basicInfo={string_sdk_version:Ae,uint32_os_type:15,string_device_name:"",string_http_user_agent:navigator.userAgent,string_os_version:"",uint32_avg_rtt:0,uint32_avg_up_loss:0,uint32_scene:this._room.scene==="live"?1:0,uint32_joining_duration:0,uint32_networkType:0,uint32_framework:this._frameWorkType,uint32_component:this._component,uint32_connection_type:this.connectionType,uint32_caller_coding_language:this._language,string_domain:location.hostname},this._pathJoinRoom={uint64_start_time:0,uint64_send_request_acc_ip_cmd_start_time:0,uint64_send_request_acc_ip_cmd_end_time:0,uint64_send_request_enter_room_cmd_start_time:0,uint64_send_request_enter_room_cmd_end_time:0,uint64_send_first_video_frame_time:0,uint64_recv_userlist_time:0,uint64_end_time:0,int32_send_request_acc_ip_cmd_ret:0,int32_send_request_enter_room_cmd_ret:0,int32_end_ret:0},this._pathLeaveRoom={uint64_start_time:0,uint64_send_request_exit_room_cmd_start_time:0,uint64_send_request_exit_room_cmd_end_time:0,uint64_end_time:0,int32_send_request_exit_room_cmd_ret:0,int32_end_ret:0},this._localStreamStat={totalVideoBitrate:0,totalVideoFPS:0,totalVideoHeight:0,totalVideoWidth:0,totalAudioLevel:0,videoCount:0,audioLevelCount:0,publishStartTime:0,statsToReport:{uint32_audio_capture_db:0,uint32_video_big_capture_fps:0,uint32_video_big_bitrate:0,uint32_video_big_resolution:0}},this._pathMainVideoMap=new Map,this._pathMainAudioMap=new Map,this._pathAuxiliaryMap=new Map,this._remoteStreamStatMap=new Map,hs().then(i=>{this._basicInfo.string_os_version=ms(),i?this._basicInfo.string_device_name=i.mobile?i.model:this._basicInfo.string_os_version:this._basicInfo.string_device_name=this._basicInfo.string_os_version})}addEvent(i,e){return this._eventMap.set(i,e),T.on(i,e),this}installEvents(){this.handleUnload=this.handleUnload.bind(this),window.addEventListener("unload",this.handleUnload),this._room.once("banned",()=>this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})),this.addEvent(E.JOIN_START,this.handleJoinStart).addEvent(E.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(E.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(E.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(E.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(E.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(E.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(E.JOIN_FAILED,this.handleJoinFailed).addEvent(E.LEAVE_START,this.handleLeaveStart).addEvent(E.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(E.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(E.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(E.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(E.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(E.PUBLISH_START,this.handlePublishStart).addEvent(E.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(E.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(E.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(E.PLAY_TRACK_START,this.handlePlayStart).addEvent(E.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(E.PLAYER_STATE_CHANGED,({track:i,state:e,type:t})=>{!ht(i)||!this.hitTest(i.room)||e==="PLAYING"&&(t===m.AUDIO?this.handleAudioPlaying(i):this.handleVideoPlaying(i))}).addEvent(E.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(E.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(E.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(E.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{if(!this.hitTest(i))return;let s=e.hasAudio||e.hasVideo||e.hasSmall,n=e.hasAuxiliary,o=t.hasAudio||t.hasVideo||t.hasSmall,a=t.hasAuxiliary;!s&&o&&this.handleRemoteStreamAdded(t.userId,"main"),!n&&a&&this.handleRemoteStreamAdded(t.userId,"auxiliary")}).addEvent(E.SINGLE_CONNECTION_STAT,({room:i,stat:e})=>{this.hitTest(i)&&(this._pathJoinRoom.int32_ice_cost=e.ice,this._pathJoinRoom.int32_dtls_cost=e.dtls,this._pathJoinRoom.int32_peer_connection_cost=e.peerConnection)})}uninstallEvents(){window.removeEventListener("unload",this.handleUnload),this._eventMap.forEach((i,e)=>T.off(e,i)),this._eventMap.clear()}destroy(){this.uninstallEvents(),Z.clearTask(this._intervalId)}handleUnload(){this._room.isJoined&&this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})}handleJoinStart(i){this.hitTest(i.room)&&(this._pathJoinRoom.uint64_start_time===0&&(this._pathJoinRoom.uint64_start_time=Date.now(),this.checkStorage()),i.params&&(g(i.params.frameWorkType)||(this._frameWorkType=i.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),g(i.params.component)||(this._component=i.params.component,this._basicInfo.uint32_component=this._component),g(i.params.language)||(this._language=i.params.language,this._basicInfo.uint32_caller_coding_language=this._language)))}handleJoinScheduleSuccess({room:i,detailCost:e}){if(this.hitTest(i)&&e){let{totalCost:t,local:s,dns:n,tcp:o,tls:a,request:c,response:d}=e;this._pathJoinRoom.int32_schedule_cost=t,this._pathJoinRoom.int32_schedule_local=s,this._pathJoinRoom.int32_schedule_dns=n,this._pathJoinRoom.int32_schedule_tcp=o,this._pathJoinRoom.int32_schedule_tls=a,this._pathJoinRoom.int32_schedule_request=c,this._pathJoinRoom.int32_schedule_response=d}}handleSignalConnectionStart({room:i}){this.hitTest(i)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time=Date.now())}handleSignalConnectionEnd({room:i,error:e}){this.hitTest(i)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time=Date.now(),e&&(this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret=e instanceof C?Number(e.getExtraCode()||e.getCode()):A.UNKNOWN,this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret))}handleJoinSendCMD(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=Date.now())}handleJoinReceivedCMDResponce(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=Date.now(),this._pathJoinRoom.int32_send_request_enter_room_cmd_ret=i.code,i.code!==0&&(this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_enter_room_cmd_ret))}handleJoinSuccess(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_end_time===0&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret=0,this._signalInfo=i.room.getSignalInfo())}handleJoinFailed({room:i,error:e}){this.hitTest(i)&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret===0&&(this._pathJoinRoom.int32_end_ret=e.code||this._pathJoinRoom.int32_send_request_enter_room_cmd_ret||this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret),setTimeout(()=>{this.report()}))}handleReceivedPublishUserList(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_recv_userlist_time===0&&(this._pathJoinRoom.uint64_recv_userlist_time=Date.now(),this._firstPublishedUserList=i.publishedUserList||[])}handleSendFirstVideoFrame({room:i}){!this.hitTest(i)||this._pathJoinRoom.uint64_send_first_video_frame_time===0&&this._pathJoinRoom.uint64_start_time!==0&&(this._pathJoinRoom.uint64_send_first_video_frame_time=Date.now())}handleLeaveStart(i){this.hitTest(i.room)&&(this._pathLeaveRoom.uint64_start_time=Date.now())}handleLeaveSuccess(i){this.hitTest(i.room)&&this._pathLeaveRoom.uint64_end_time===0&&(this._pathLeaveRoom.uint64_end_time=Date.now(),this._pathJoinRoom.uint64_end_time!==0?this._basicInfo.uint32_joining_duration=this._pathLeaveRoom.uint64_end_time-this._pathJoinRoom.uint64_end_time:this._log.warn("pathJoinRoom endTime is 0"),this.report())}handleLeaveSendCMD(i){this.hitTest(i.room)&&(this._pathLeaveRoom.uint64_send_request_exit_room_cmd_start_time=Date.now(),this._pathLeaveRoom.uint64_send_request_exit_room_cmd_end_time=Date.now())}handleRemoteStreamAdded(i,e){var s;let t=`${i}_${e}`;if(!this._remoteStreamStatMap.has(t)){let n={userId:i,totalVideoFPS:0,totalVideoBitrate:0,totalAudioLevel:0,totalAudioBitrate:0,totalLoss:0,audioCount:0,audioLevelCount:0,videoCount:0,networkQualityCount:0,streamAddedTime:Date.now(),subscribeStartTime:0,subscribedTime:0,playStreamTime:0,statsToReport:P(N({},s_),{msg_user_info:new Ys({userId:i,tinyId:(s=this._room.remotePublishedUserMap.get(i))==null?void 0:s.tinyId,role:20})})};n.statsToReport.uint32_stream_type=e==="main"?2:7,this._remoteStreamStatMap.set(t,n)}}handleSubscribeStart({room:i,remotePublishedUser:e,streamType:t,subscribeState:s}){if(!this.hitTest(i))return;let{userId:n,tinyId:o,role:a}=e,c=new Ys({userId:n,tinyId:o,role:a==="anchor"?20:21}),d=Date.now(),l=`${n}_${t}`,h=this._remoteStreamStatMap.get(l);h&&h.subscribeStartTime===0&&(h.subscribeStartTime=d),t==="main"?(e.muteState.hasVideo&&(s.video||s.smallVideo)&&!this._pathMainVideoMap.has(l)&&this._pathMainVideoMap.set(l,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:n,sendSubscribeCMDTime:d}),e.muteState.hasAudio&&s.audio&&!this._pathMainAudioMap.has(l)&&this._pathMainAudioMap.set(l,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:n,sendSubscribeCMDTime:d})):e.muteState.hasAuxiliary&&s.auxiliary&&!this._pathAuxiliaryMap.has(l)&&this._pathAuxiliaryMap.set(l,{sendSubscribeCMDTime:d})}handleSubscribed({room:i,remotePublishedUser:e,streamType:t}){if(this.hitTest(i)){let s=`${e.userId}_${t}`,n=this._remoteStreamStatMap.get(s);n&&n.subscribedTime===0&&(n.subscribedTime=Date.now())}}handlePlayStart({track:i}){if(!ht(i)||!this.hitTest(i.room))return;let e=`${i.userId}_${i.streamType}`,t=this._remoteStreamStatMap.get(e);(t==null?void 0:t.playStreamTime)===0&&(t.playStreamTime=Date.now())}handleVideoLoadedData({track:i}){if(!ht(i)||!this.hitTest(i.room))return;let e=`${i.userId}_${i.streamType}`,t=this._pathMainVideoMap.get(e);t&&t.statsToReport.uint64_combine_first_frame_time===0&&(t.statsToReport.uint64_combine_first_frame_time=Date.now())}handleVideoPlaying(i){let e=`${i.userId}_${i.streamType}`,t=Date.now(),s=this._pathMainVideoMap.get(e),n=this._remoteStreamStatMap.get(e);if(s&&(s.statsToReport.uint64_render_first_frame_time===0&&(s.statsToReport.uint64_render_first_frame_time=t),n)){let{statsToReport:a,playStreamTime:c,subscribedTime:d}=n;a.uint32_video_render_first===0&&c-d<=100&&(a.uint32_video_render_first=t-s.sendSubscribeCMDTime)}let o=this._pathAuxiliaryMap.get(e);if(o&&n){let{statsToReport:a,playStreamTime:c,subscribedTime:d}=n;a.uint32_video_render_first===0&&c-d<=100&&(a.uint32_video_render_first=t-o.sendSubscribeCMDTime)}}handleAudioPlaying(i){let e=`${i.userId}_${i.streamType}`,t=this._pathMainAudioMap.get(e);t&&t.statsToReport.uint64_play_first_frame_time===0&&(t.statsToReport.uint64_play_first_frame_time=Date.now())}handleNetworkQuality(i){this.hitTest(i.room)&&(this._networkQuality.totalUplinkLoss+=i.uplink.loss,this._networkQuality.totalUplinkRTT+=i.uplink.rtt,this._networkQuality.count++,i.downlinks.forEach(({rtt:e,loss:t,userId:s,videoDelay:n,audioDelay:o})=>{let a=this._networkQuality.totalDownlinkRTTAndLossMap.get(s);if(a)a.totalRTT+=e,a.totalLoss+=t,n&&(a.totalVideoDelay=(a.totalVideoDelay||0)+n,a.videoDelayCount=(a.videoDelayCount||0)+1),o&&(a.totalAudioDelay=(a.totalAudioDelay||0)+o,a.audioDelayCount=(a.audioDelayCount||0)+1),a.count++;else{let c,d,l,h;n&&(d=n,l=1),o&&(c=o,h=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(s,{totalRTT:e,totalLoss:t,count:1,totalAudioDelay:c,totalVideoDelay:d,audioDelayCount:h,videoDelayCount:l})}}))}handleHeartbeatStats(i){if(this.hitTest(i.room)){let{msg_up_stream_info:e,msg_down_stream_info:t}=i.report;if(e.msg_video_status[0]){let{uint32_video_codec_bitrate:s,uint32_video_enc_fps:n,uint32_video_width:o,uint32_video_height:a}=e.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=s,this._localStreamStat.totalVideoFPS+=n,this._localStreamStat.totalVideoWidth+=o,this._localStreamStat.totalVideoHeight+=a,this._localStreamStat.videoCount++}if(e.msg_audio_status){let{uint32_audio_level:s}=e.msg_audio_status;Math.floor(s/nt*100)>0&&(this._localStreamStat.totalAudioLevel+=s/nt,this._localStreamStat.audioLevelCount++)}t.forEach(s=>{let{msg_user_info:n,msg_audio_status:o,msg_video_status:a}=s,c=n.str_identifier,d=this._room.remotePublishedUserMap.get(c);if(a.forEach(l=>{let h=l.uint32_video_stream_type===2,_=l.uint32_video_stream_type===7,f=`${c}_${h?"main":"auxiliary"}`,R=this._remoteStreamStatMap.get(f);if(!!R&&(h&&(d==null?void 0:d.remoteVideoTrack.isSubscribed)||_&&(d==null?void 0:d.remoteAuxiliaryTrack))){R.totalVideoFPS+=l.uint32_video_receive_fps,R.totalVideoBitrate+=l.uint32_video_codec_bitrate,R.videoCount++,R.statsToReport.uint32_video_width===0&&(R.statsToReport.uint32_video_width=l.uint32_video_width),R.statsToReport.uint32_video_height===0&&(R.statsToReport.uint32_video_height=l.uint32_video_height);let y=h?d.remoteVideoTrack:d.remoteAuxiliaryTrack;y.stat.jitterBufferDelay&&(R.videoJitterBufferDelay=y.stat.jitterBufferDelay),y.stat.framesReceived&&(R.statsToReport.uint32_video_consume_render_rate=Math.floor(y.stat.framesDecoded/y.stat.framesReceived*Gr(10,6)))}}),o){let l=`${c}_${"main"}`,h=this._remoteStreamStatMap.get(l);this._remoteStreamStatMap.has(l)&&h&&(d==null?void 0:d.remoteAudioTrack.isSubscribed)&&(h.totalAudioBitrate+=o.uint32_audio_codec_bitrate,h.audioCount++,d.remoteAudioTrack.stat.jitterBufferDelay&&(h.audioJitterBufferDelay=d.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(o.uint32_audio_level/nt*100)>0&&(h.totalAudioLevel+=o.uint32_audio_level/nt,h.audioLevelCount++))}})}}handlePublishStart({room:i}){this.hitTest(i)&&this._localStreamStat.publishStartTime===0&&(this._localStreamStat.publishStartTime=Date.now())}handleTrackCaptureStart({track:i}){i.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),i.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_start_time&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}handleTrackCaptureSuccess({track:i}){i.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=0,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),i.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=0,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleTrackCaptureFailed({track:i,error:e}){let s={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[e.name]||(e instanceof C?e.getExtraCode()||e.getCode():A.UNKNOWN);i.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=s,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),i.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=s,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}hasVideoFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&di)>=0}hasAudioFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&ui)>=0}hasAuxFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&vi)>=0}hitTest(i){return i===this._room}checkStorage(){return p(this,null,function*(){try{let i=qt.getItem(this._storageKey);i&&(yield this.upload(i),qt.deleteItem(this._storageKey))}catch(i){this._log.warn(i)}})}setStorage(){this.prepareReport();let i=this.getReportData();i.msg_path_enter_room.uint64_start_time!==0&&qt.setItem(this._storageKey,i)}prepareReport(){if(this._networkQuality.count>0&&(this._basicInfo.uint32_avg_rtt=Math.floor(this._networkQuality.totalUplinkRTT/this._networkQuality.count),this._basicInfo.uint32_avg_up_loss=Math.floor(this._networkQuality.totalUplinkLoss/this._networkQuality.count)),this._localStreamStat.videoCount>0){this._localStreamStat.statsToReport.uint32_video_big_capture_fps=Math.floor(this._localStreamStat.totalVideoFPS/this._localStreamStat.videoCount),this._localStreamStat.statsToReport.uint32_video_big_bitrate=Math.floor(this._localStreamStat.totalVideoBitrate/this._localStreamStat.videoCount);let i=Math.floor(this._localStreamStat.totalVideoWidth/this._localStreamStat.videoCount),e=Math.floor(this._localStreamStat.totalVideoHeight/this._localStreamStat.videoCount);this._localStreamStat.statsToReport.uint32_video_big_resolution=i<<16|e}this._localStreamStat.audioLevelCount>0&&(this._localStreamStat.statsToReport.uint32_audio_capture_db=Math.floor(this._localStreamStat.totalAudioLevel/this._localStreamStat.audioLevelCount*100)),this._remoteStreamStatMap.forEach((i,e)=>{let{userId:t}=i,s=this._networkQuality.totalDownlinkRTTAndLossMap.get(t);if(s){let{totalLoss:l,count:h,audioDelayCount:_,videoDelayCount:f,totalAudioDelay:R,totalVideoDelay:y}=s;i.statsToReport.uint32_avg_down_loss=Math.floor(l/h),_&&R&&(i.statsToReport.uint32_audio_network_p2p_delay=Math.floor(R/_),i.audioJitterBufferDelay&&(i.statsToReport.uint32_p2p_delay=Math.floor(i.statsToReport.uint32_audio_network_p2p_delay+i.audioJitterBufferDelay))),f&&y&&(i.statsToReport.uint32_video_network_p2p_delay=Math.floor(y/f))}i.videoCount>0&&(i.statsToReport.uint32_video_avg_fps=Math.floor(i.totalVideoFPS/i.videoCount),i.statsToReport.uint32_video_avg_bitrate=Math.floor(i.totalVideoBitrate/i.videoCount)),i.audioCount>0&&(i.statsToReport.uint32_audio_recv_bitrate=i.statsToReport.uint32_audio_bitrate=Math.floor(i.totalAudioBitrate/i.audioCount)),i.audioLevelCount>0&&(i.statsToReport.uint32_audio_play_db=Math.floor(i.totalAudioLevel/i.audioLevelCount*100));let{callDurationCalculator:n}=this._room;n&&(i.statsToReport.uint32_audio_play_time=n.getDuration(e,m.AUDIO),i.statsToReport.uint32_video_play_time=n.getDuration(e,m.VIDEO)),i.statsToReport.uint32_video_render_first=Math.min(i.statsToReport.uint32_video_render_first,zi);let{badCaseDetector:o}=this._room,{dataFreeze:a,count:c}=o.getDataFreezeDuration(e),{renderFreeze:d}=o.getRenderFreezeDuration(e);i.statsToReport.uint32_video_block_count=c,i.statsToReport.uint32_video_block_time=Math.min(a,i.statsToReport.uint32_video_play_time),i.statsToReport.uint32_video_external_block_time=Math.min(d,i.statsToReport.uint32_video_play_time),o.isBlackStream(e)&&i.statsToReport.uint32_video_avg_fps===0?i.statsToReport.uint32_video_black_screen_subjective=1:i.statsToReport.uint32_video_black_screen_subjective=0,(i.subscribeStartTime===0||i.subscribeStartTime-i.streamAddedTime>100||i.playStreamTime===0)&&(this._pathMainAudioMap.delete(e),this._pathMainVideoMap.delete(e),i.statsToReport.uint32_video_render_first=0)}),this._pathMainAudioMap.forEach((i,e)=>{if(!this.hasAudioFlag(i.userId)){this._pathMainAudioMap.delete(e);return}i.statsToReport.uint64_play_first_frame_time-i.statsToReport.uint64_start_enter_time>zi&&(i.statsToReport.uint64_play_first_frame_time=i.statsToReport.uint64_start_enter_time+zi)}),this._pathMainVideoMap.forEach((i,e)=>{if(!this.hasVideoFlag(i.userId)){this._pathMainVideoMap.delete(e);return}i.statsToReport.uint64_render_first_frame_time-i.statsToReport.uint64_start_enter_time>zi&&(i.statsToReport.uint64_render_first_frame_time=i.statsToReport.uint64_start_enter_time+zi)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>zi&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+zi)}getReportData(){this._basicInfo.uint32_networkType=Er();let i={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new Ys({userId:this._room.userId,tinyId:this._room.tinyId,role:this._room.role==="anchor"?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:Ts(this._signalInfo.relayIp),uint32_client_ip:Ts(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*Gr(2,31)),msg_path_enter_room:this._pathJoinRoom,msg_path_exit_room:this._pathLeaveRoom,msg_path_recv_video:[...this._pathMainVideoMap.values()].map(e=>e.statsToReport),msg_quality_statistics:[...this._remoteStreamStatMap.values()].map(e=>e.statsToReport),str_room_name:String(this._room.roomId||0),msg_path_recv_audio:[...this._pathMainAudioMap.values()].map(e=>e.statsToReport),uint32_info_client_ip:Ts(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport};return Hn(i),i}report(){return p(this,null,function*(){try{this.prepareReport();let i=this.getReportData();yield this.upload(i),qt.deleteItem(this._storageKey),this.initData()}catch(i){this._log.warn(i)}})}upload(i){return p(this,null,function*(){if(dt&&!Sa||i.msg_path_enter_room.uint64_start_time===0||[un,Zo,ea].findIndex(a=>a===location.host)>=0)return;let e=Number(this._room.sdkAppId),t=yield ma(i),s=t instanceof ArrayBuffer,n=`${_i(e,ci.KEY_POINT)}&gzip=${+s}`,o=!1;navigator.sendBeacon&&(o=navigator.sendBeacon(n,t)),o||Ft({url:n,body:t}),this.uploadKVStat(v),this.uploadKVStat(Ui)})}setConnectionType(i){this.connectionType=i,this._basicInfo.uint32_connection_type=i}uploadKVStat(i){return p(this,null,function*(){let e=i.getReportData();if(e.stats_count.length===0&&e.stats_distribution.length===0)return;e.msg_sdk_basic_info=P(N({},e.msg_sdk_basic_info),{bytes_device_name:this._basicInfo.string_device_name||"",bytes_os_version:this._basicInfo.string_os_version||"",uint32_framework:this._frameWorkType,uint32_network_type:this._basicInfo.uint32_networkType||0}),this._log.debug(e);let t=yield ma(e),s=`${_i(+this._room.sdkAppId,ci.KV_STAT)}&gzip=${+(t instanceof ArrayBuffer)}`,n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(s,t)),n||Ft({url:s,body:t})})}};b([wt({settings:{timeout:500,retries:3}})],Vo.prototype,"upload",1);var zi=5e3,s_={msg_user_info:null,uint32_video_avg_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_avg_bitrate:0,uint32_video_block_time:0,uint32_video_play_time:0,uint32_audio_block_time:0,uint32_audio_play_time:0,uint32_audio_play_db:0,uint32_avg_down_loss:0,uint32_stream_type:0,uint32_video_render_first:0,uint32_video_block_count:0,uint32_audio_block_count:0,uint32_audio_bitrate:0,uint32_video_black_screen_subjective:0,uint32_audio_recv_bitrate:0,uint32_video_external_block_time:0,uint32_video_consume_render_rate:0},Ys=class{constructor(i){this.str_identifier=String(i.userId),this.str_tinyid=String(i.tinyId||0),this.uint32_role=i.role}},Wl=Vo;var md=class{constructor(){u(this,"_startTime");u(this,"_endTime");this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=L())}stop(){this._endTime===0&&(this._endTime=L())}getDuration(){return this._endTime===0?L()-this._startTime:this._endTime-this._startTime}get endTime(){return this._endTime}},Vr=md;var pd=class{constructor(i){u(this,"_room",null);u(this,"_durationMap");u(this,"_eventMap",new Map);this._room=i.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(E.SUBSCRIBE_SUCCESS,this.handleSubscribed).set(E.UNSUBSCRIBE_SUCCESS,this.handleStreamStopped).set(E.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{var o;let{userId:s}=t;if(!this.hitTest(i))return;e.hasAudio&&!t.hasAudio&&this.stopDurationItem(`${s}_${"main"}`,m.AUDIO),e.hasVideo&&!t.hasVideo&&this.stopDurationItem(`${s}_${"main"}`,m.VIDEO),e.hasAuxiliary&&!t.hasAuxiliary&&this.stopDurationItem(`${s}_${"auxiliary"}`,m.VIDEO);let n=(o=this._room)==null?void 0:o.remotePublishedUserMap.get(s);!n||(!e.hasAudio&&t.hasAudio&&n.remoteAudioTrack.isSubscribed&&this.addDuractionItem(s,m.AUDIO,"main"),!e.hasVideo&&t.hasVideo&&n.remoteVideoTrack.isSubscribed&&this.addDuractionItem(s,m.VIDEO,"main"),!e.hasAuxiliary&&t.hasAuxiliary&&n.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(s,m.VIDEO,"auxiliary"))}),this._eventMap.forEach((i,e)=>T.on(e,i,this))}uninstallEvents(){this._eventMap.forEach((i,e)=>T.off(e,i,this)),this._eventMap.clear()}handleSubscribed({room:i,streamType:e,remotePublishedUser:t}){if(!this.hitTest(i))return;let{userId:s}=t,n=`${s}_${e}`;if(t.muteState.hasAudio&&e==="main")if(t.remoteAudioTrack.isSubscribed){let o=new Vr,a=this._durationMap.get(n);a?this.isRecording(a.audio)||a.audio.push(o):this._durationMap.set(n,{userId:s,type:e,audio:[o],video:[]})}else this.stopDurationItem(n,m.AUDIO);if(t.muteState.hasVideo||t.muteState.hasAuxiliary)if(t.remoteVideoTrack.isSubscribed||t.remoteAuxiliaryTrack.isSubscribed){let o=new Vr,a=this._durationMap.get(n);a?this.isRecording(a.video)||a.video.push(o):this._durationMap.set(n,{userId:s,type:e,audio:[],video:[o]})}else this.stopDurationItem(n,m.VIDEO)}handleStreamStopped({room:i,streamType:e,remotePublishedUser:t}){if(!this.hitTest(i))return;let{userId:s}=t,n=`${s}_${e}`;this.stopDurationItem(n,m.AUDIO),this.stopDurationItem(n,m.VIDEO)}isRecording(i){return i.findIndex(e=>e.endTime===0)>=0}addDuractionItem(i,e,t){let s=`${i}_${t}`,n=new Vr,o=this._durationMap.get(s);o?this.isRecording(o[e])||o[e].push(n):this._durationMap.set(s,{userId:i,type:t,audio:e===m.AUDIO?[n]:[],video:e===m.AUDIO?[]:[n]})}stopDurationItem(i,e){if(this._durationMap.has(i)){let s=this._durationMap.get(i)[e].find(n=>n.endTime===0);s&&s.stop()}}hitTest(i){return this._room===i}getDuration(i,e){return this._durationMap.has(i)?this._durationMap.get(i)[e].reduce((s,n)=>s+n.getDuration(),0):0}getDurationMap(){return this._durationMap}reset(){this._durationMap.clear()}destroy(){this._room=null,this.uninstallEvents()}},Jl=pd;var _d=class{constructor(i){u(this,"_room");u(this,"_renderFreezeMap",new Map);u(this,"_isVideoPlayingEventFiredMap",new Map);u(this,"_dataFreezeMap",new Map);u(this,"_monitorFreezeData",new Map);u(this,"_eventMap",new Map);this._room=i.room,this.installEvents()}installEvents(){this._eventMap.set(E.LEAVE_SUCCESS,({room:i})=>{this.hitTest(i)&&this.stop()}).set(E.PLAY_TRACK_START,this.onPlayTrackStart).set(E.UNSUBSCRIBE_SUCCESS,({room:i,streamType:e,remotePublishedUser:t})=>{if(!this.hitTest(i))return;let{userId:s}=t,n=`${s}_${e}`;this.stopDataFreeze({key:n,userId:s,type:e})}).set(E.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{if(!this.hitTest(i))return;let{userId:s}=t;if(e.hasVideo&&!t.hasVideo){let n="main",o=`${t.userId}_${n}`;this.stopDataFreeze({key:o,userId:s,type:n})}if(e.hasAuxiliary&&!t.hasAuxiliary){let n="auxiliary",o=`${t.userId}_${n}`;this.stopDataFreeze({key:o,userId:s,type:n})}}).set(E.PLAYER_STATE_CHANGED,({track:i,state:e,reason:t,type:s})=>{if(!(!ht(i)||!this.hitTest(i.room)||s!==m.VIDEO)){if(e==="PLAYING"){let n=`${i.userId}_${i.streamType}`;this._isVideoPlayingEventFiredMap.set(n,!0)}t===m.MUTE?this.onVideoTrackMuted(i):t===m.UNMUTE&&this.onVideoTrackUnmuted(i)}}).set(E.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach((i,e)=>T.on(e,i,this))}uninstallEvents(){this._eventMap.forEach((i,e)=>T.off(e,i,this)),this._eventMap.clear()}stop(){this._renderFreezeMap.clear(),this._dataFreezeMap.clear(),this._isVideoPlayingEventFiredMap.clear()}onVideoTrackMuted(i){if(!i.isSubscribed)return;let{userId:e,streamType:t}=i,s=`${e}_${t}`,n=this._dataFreezeMap.get(s),o=new Vr;n?n.durationItemList.push(o):this._dataFreezeMap.set(s,{userId:e,type:t,durationItemList:[o],isFreezing(){let a=this.durationItemList[this.durationItemList.length-1];return a&&a.endTime===0}})}onVideoTrackUnmuted(i){if(!i.isSubscribed)return;let{userId:e,streamType:t}=i,s=`${e}_${t}`;this.stopDataFreeze({key:s,userId:e,type:t})}onHearBeatReport({room:i,report:e}){!this.hitTest(i)||e.msg_down_stream_info.forEach(t=>{let s=this._room.remotePublishedUserMap.get(t.msg_user_info.str_identifier);if(!s)return;let{userId:n,muteState:o}=s;t.msg_video_status.forEach(a=>{a.uint32_video_stream_type===2&&o.hasVideo&&!o.videoMuted&&s.remoteVideoTrack.isSubscribed&&this.handleRenderFreeze({userId:n,fps:a.uint32_video_dec_fps,type:"main"}),a.uint32_video_stream_type===7&&o.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&this.handleRenderFreeze({userId:n,fps:a.uint32_video_dec_fps,type:"auxiliary"})})})}stopDataFreeze({key:i,userId:e,type:t}){let s=this._dataFreezeMap.get(i);if(!s||!s.isFreezing())return;let n=s.durationItemList[s.durationItemList.length-1];n.stop();let o=n.getDuration();o>gn?this._monitorFreezeData.set(i,{userId:e,type:t,duration:o}):s.durationItemList.pop()}getTotalDuration(i){return i.reduce((e,t)=>{let s=t.getDuration();return e+Math.min(s,5e3)},0)}handleRenderFreeze(s){return p(this,arguments,function*({userId:i,fps:e,type:t}){let n=`${i}_${t}`,o=this._renderFreezeMap.get(n);if(e<=2){let a=L();o&&!o.isFreeze&&(o.freezeTimeline.push({startTime:a,endTime:0}),o.isFreeze=!0),o||this._renderFreezeMap.set(n,{userId:i,type:t,isFreeze:!0,freezeTimeline:[{startTime:a,endTime:0}],renderFreezeTotal:0})}else if(o&&o.isFreeze){o.isFreeze=!1;let a=o.freezeTimeline.pop();if(a){a.endTime=L();let c=a.endTime-a.startTime;o.freezeTimeline.push(a),o.renderFreezeTotal+=Math.min(5e3,c)}}})}onPlayTrackStart({track:i}){if(!ht(i)||!this.hitTest(i.room)||i.kind!==m.VIDEO||i.hasFlag)return;let e=`${i.userId}_${i.streamType}`;this._isVideoPlayingEventFiredMap.has(e)||this._isVideoPlayingEventFiredMap.set(e,!1)}getDataFreezeDuration(i){let e={dataFreeze:0,count:0},t=this._dataFreezeMap.get(i);if(t){if(t.isFreezing()){let s=t.durationItemList[t.durationItemList.length-1];s.stop(),s.getDuration()<gn&&t.durationItemList.pop()}e.dataFreeze=this.getTotalDuration(t.durationItemList),e.count=t.durationItemList.length}return e}getRenderFreezeDuration(i){let e=this._renderFreezeMap.get(i),t=0,s=0;if(e)if(!e.isFreeze)t=e.renderFreezeTotal;else{let n=L(),o=e.freezeTimeline[e.freezeTimeline.length-1],a=n-o.startTime;t=e.renderFreezeTotal+Math.min(a,5e3),s=e.freezeTimeline.length}return{renderFreeze:t,count:s}}getMonitorFreeze(){return this._monitorFreezeData}isBlackStream(i){return this._isVideoPlayingEventFiredMap.has(i)?!this._isVideoPlayingEventFiredMap.get(i):!1}resetMonitor(){this._monitorFreezeData.clear()}hitTest(i){return i===this._room}destroy(){this.uninstallEvents()}},jl=_d;var ql=Ie(ke(),1);var n_=[-1,-1,1,-1,-1,1,1,1],o_=[0,0,1,0,0,1,1,1],qe=class extends U{constructor(e,t){super();this.context=e;u(this,"name");u(this,"input");u(this,"output");u(this,"texture");u(this,"ctx2d",null);u(this,"fbo");u(this,"width",0);u(this,"height",0);u(this,"x",0);u(this,"y",0);u(this,"program");u(this,"vertexShader");u(this,"fragmentShader");u(this,"totalFrames",0);u(this,"dropFrames",0);u(this,"matchInputSize",!0);u(this,"texCoordBuffer");u(this,"positionBuffer");u(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0});u(this,"cost",0);u(this,"_canvas",null);u(this,"_image");if(this.context.on("disconnect",this.close,this),this.name=t.name,this.matchInputSize=t.matchInputSize!==!1,this.width=t.width||e.width,this.height=t.height||e.height,this._image=t.image,e instanceof Xe){if(e.ctx&&t.create2d){let s=document.createElement("canvas"),n=typeof s.transferControlToOffscreen=="function"?s.transferControlToOffscreen():s;n.width=this.width,n.height=this.height,this.ctx2d=n.getContext("2d"),this._image=n,this._canvas=n}return}try{let s=e.ctx;this.texCoordBuffer=this.createBuffer(o_),this.positionBuffer=this.createBuffer(n_),t.createTexture!==!1&&(this.texture=s.createTexture(),this.useTexture(),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),s.pixelStorei(s.PACK_ALIGNMENT,1),s.pixelStorei(s.UNPACK_ALIGNMENT,1)),t.useFbo&&(this.fbo=s.createFramebuffer(),this.useBufferFrame(),this.useTexture(),s.texImage2D(s.TEXTURE_2D,0,s.RGBA,this.width,this.height,0,s.RGBA,s.UNSIGNED_BYTE,null),s.framebufferTexture2D(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0,s.TEXTURE_2D,this.texture,0)),t.useDefaultProgram?this.program=e.defaultProgam:(t.vertexShaderSource||t.fragmentShaderSource)&&(this.vertexShader=t.vertexShaderSource?e.createShader(s.VERTEX_SHADER,t.vertexShaderSource):e.defaultVShader,this.fragmentShader=t.fragmentShaderSource?e.createShader(s.FRAGMENT_SHADER,t.fragmentShaderSource):e.defaultFShader,this.program=e.createProgram(this.vertexShader,this.fragmentShader))}catch(s){this.context.destroy(s)}}get image(){return this._image}set image(e){this._image=e}createFramebuffer(e){let t=this.context.ctx,s=t.createFramebuffer();return t.bindFramebuffer(t.FRAMEBUFFER,s),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0),s}connect(e,...t){return e.addInput(this,...t),this.output=e,e}addInput(e,...t){this.input=e,this.matchInputSize&&e.width&&e.height&&this.resize(e.width,e.height)}requestFrame(e){let t=Date.now();if(this.context instanceof Ce&&this.render(e)||this.context instanceof Xe&&this.render2d(e))this.totalFrames++;else return!1;return this.cost=Date.now()-t,!0}render2d(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?this.draw2d(this.input.image,0,0,this.width,this.height):!1}disconnect(...e){var t;(t=this.output)==null||t.removeInput(this,...e),delete this.output}removeInput(e,...t){delete this.input}close(){var e,t;if(this.context.off("disconnect",this.close,this),(e=this.output)==null||e.removeInput(this),delete this.output,(t=this.input)==null||t.disconnect(),this.context instanceof Ce){let s=this.context.ctx;s.deleteBuffer(this.texCoordBuffer),s.deleteBuffer(this.positionBuffer),this.fbo&&s.deleteFramebuffer(this.fbo),this.texture&&s.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&s.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&s.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&s.deleteProgram(this.program)}this._canvas&&(this._canvas.width=0,this._canvas.height=0,this.ctx2d=null),this.removeAllListeners()}useTexture(){this.useTextures(this.texture)}useInputTexture(){var e;this.useTextures((e=this.input)==null?void 0:e.texture)}useTextures(...e){let t=this.context.ctx;e.forEach((s,n)=>{s&&(t.activeTexture(t.TEXTURE0+n),t.bindTexture(t.TEXTURE_2D,s))})}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){let e=this.context.ctx;e.bindFramebuffer(e.FRAMEBUFFER,this.fbo||null)}createBuffer(e){let t=this.context.ctx,s=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,s),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW),s}setTexBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.texCoordBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}setPosBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}changeBufferData(e,t){let s=this.context.ctx;s.bindBuffer(s.ARRAY_BUFFER,e),s.bufferData(s.ARRAY_BUFFER,new Float32Array(t),s.STATIC_DRAW)}setAttributes(...e){let t=this.context.ctx;e.forEach((s,n)=>{t.enableVertexAttribArray(n),t.bindBuffer(t.ARRAY_BUFFER,s),t.vertexAttribPointer(n,2,t.FLOAT,!1,0,0)})}getVertexPoint(e,t){return[e/this.width*2-1,t/this.height*2-1]}layout2texCoords(e){return[...this.getVertexPoint(e.x,e.y),...this.getVertexPoint(e.x+e.width,e.y),...this.getVertexPoint(e.x,e.y+e.height),...this.getVertexPoint(e.x+e.width,e.y+e.height)]}resize(e,t){if(!(this.width===e&&this.height===t)){if(this.width=e,this.height=t,this._canvas&&(this._canvas.width=e,this._canvas.height=t),this.texture&&this.fbo){this.useTexture();let s=this.context.ctx;s.texImage2D(s.TEXTURE_2D,0,s.RGBA,e,t,0,s.RGBA,s.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(e,t)}}draw(e,t){this.setAttributes(e||this.positionBuffer,t||this.texCoordBuffer);let s=this.context.ctx;s.drawArrays(s.TRIANGLE_STRIP,0,4)}draw2d(e,t,s,n,o){return this.ctx2d&&e?(e instanceof ImageData?this.ctx2d.putImageData(e,t,s):this.ctx2d.drawImage(e,t,s,n,o),!0):!1}getInfo(){var h;let{totalFrames:e,x:t,y:s,width:n,height:o,name:a,cost:c}=this,d=Date.now(),l=(e-this.lastInfo.totalFrames)/((d-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:s,width:n,height:o,timestamp:d,fps:l,name:a,cost:c},N({parent:(h=this.input)==null?void 0:h.getInfo()},this.lastInfo)}createTexture(e){let t=this.context.ctx,s=t.createTexture();return this.useTextures(s),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.pixelStorei(t.PACK_ALIGNMENT,1),t.pixelStorei(t.UNPACK_ALIGNMENT,1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),s}};b([oe(U.INIT,"connected",{sync:!0})],qe.prototype,"connect",1),b([oe("connected",U.INIT,{ignoreError:!0,sync:!0})],qe.prototype,"disconnect",1),b([oe([],"closed",{sync:!0})],qe.prototype,"close",1);var a_=[0,1,1,1,0,0,1,0],Zs=class extends qe{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t));u(this,"_intervalId",0);u(this,"_sequence",0);u(this,"checkGLError",!1);e instanceof Xe?this.ctx2d=e.ctx:e.available&&(t==null?void 0:t.mirrorUpAndDown)&&this.setTexBuffer(a_)}start(e){this._intervalId=Z.run("intervalInWorker",()=>{if(e!==this.context.frameRate&&(Z.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof Ce){let s=this.context.ctx.getError();s&&this.context.destroy(new Error(`${this.name} req ${this._sequence} render ${this.totalFrames} faild ${s}`))}},{fps:this.context.frameRate})}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}addInput(e,...t){super.addInput(e,...t),this.start(this.context.frameRate)}removeInput(e){super.removeInput(e),Z.clearTask(this._intervalId)}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}},Ur=class extends Zs{constructor(e,t){super(e,t);u(this,"_videoTrack");[this._videoTrack]=e._canvas.captureStream(e.frameRate).getVideoTracks();let s=n=>{var c;let o=()=>{var d;return(d=this._videoTrack)==null?void 0:d.removeEventListener(n,a)},a=()=>{o(),this.context.destroy(new Error(`video track ${n}`))};this.once("closed",o),(c=this._videoTrack)==null||c.addEventListener(n,a)};e instanceof Ce&&s("mute"),s("ended")}get videoTrack(){return this._videoTrack}close(){var e;super.close(),(e=this._videoTrack)==null||e.stop(),delete this._videoTrack}},Uo=class extends Ur{render(i){var e;return!!((e=this.input)!=null&&e.requestFrame(i))}};var Bo=class extends Ur{constructor(e,t){super(e,{name:"smallDestination"});this.resolution=t}resize(e,t){let s,n=e*t,o=this.resolution.width*this.resolution.height;if(I.info(`big res: ${e}*${t} small res: ${this.resolution.width}*${this.resolution.height} `),n===o){super.resize(e,t);return}n>o?s=n/o:(I.warn(`Small stream resolution is not smaller than big stream, which is invalid. big: ${e} * ${t} small: ${this.resolution.width} * ${this.resolution.height}`),s=n/(160*120)),super.resize(e/Math.sqrt(s),t/Math.sqrt(s))}};var en=class extends qe{constructor(e,t){super(e,N({name:"imageSource"},t));u(this,"_lastImage");u(this,"_totalFrames",0);u(this,"_autoResize",!1);this._autoResize=(t==null?void 0:t.autoResize)!==!1}_render(e,t){let{width:s,height:n}=this;if(this.image instanceof HTMLVideoElement){if(G(this.image.getVideoPlaybackQuality)&&!It){let a=this.image.getVideoPlaybackQuality().totalVideoFrames;if(this._totalFrames===a)return!1;this._totalFrames=a,this.dropFrames=this._totalFrames-this.totalFrames}if({videoWidth:s,videoHeight:n}=this.image,!s||!n)return!1;this.image.width=s,this.image.height=n}else if(this.image instanceof HTMLImageElement||this.image instanceof ImageData||this.image instanceof ImageBitmap){if({width:s,height:n}=this.image,this.image!==this._lastImage)this._lastImage=this.image;else if(s===this.width&&n===this.height)return!1}else(this.image instanceof HTMLCanvasElement||this.image instanceof OffscreenCanvas)&&({width:s,height:n}=this.image,this._lastImage=this.image);if(!this._autoResize)return!0;if(this.width===s&&this.height===n&&this.totalFrames){if(t){this.useTexture();let o=this.context.ctx;o.texSubImage2D(o.TEXTURE_2D,0,0,0,o.RGBA,o.UNSIGNED_BYTE,this.image)}}else{if(t){this.useTexture();let o=this.context.ctx;o.texImage2D(o.TEXTURE_2D,0,o.RGBA,o.RGBA,o.UNSIGNED_BYTE,this.image)}this.resize(s,n)}return!0}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},Br=class extends en{constructor(e,t,s){super(e,s);u(this,"_player");this._player=new He({id:s.name,track:t,muted:!0,container:null,objectFit:"contain",log:s.logger}),this.name="videoTrackSource",this._player.play()}get image(){return this._player.element}replaceTrack(e){this._player.setTrack(e)}close(){super.close(),this._player.stop()}};var c_=`
44
44
  // \u9876\u70B9\u7740\u8272\u5668
45
45
  attribute vec4 a_position;
46
46
  attribute vec2 a_texCoord;