@volcengine/rtc 4.66.34 → 4.66.36

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.
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Copyright (c) 2026 The VolcEngineRTC project authors. All Rights Reserved.
3
3
  * @brief VolcEngine Advance API
4
- * version: 4.66.34
4
+ * version: 4.66.36
5
5
  */
6
- var _a,_b,_c,_d,_e,_f,_g,_h,_i,_j,_k,_l,_m,_n,_o,_p,_q,_r,_s,_t,_u,_v,__defProp=Object.defineProperty,__defNormalProp=(e,t,i)=>t in e?__defProp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,__publicField=(e,t,i)=>(__defNormalProp(e,"symbol"!=typeof t?t+"":t,i),i);function _mergeNamespaces(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(i){if("default"!==i&&!(i in e)){var r=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,r.get?r:{enumerable:!0,get:function(){return t[i]}})}}))})),Object.freeze(e)}var getRandomValues$1,VideoSourceType=(e=>(e[e.VIDEO_SOURCE_TYPE_EXTERNAL=0]="VIDEO_SOURCE_TYPE_EXTERNAL",e[e.VIDEO_SOURCE_TYPE_INTERNAL=1]="VIDEO_SOURCE_TYPE_INTERNAL",e))(VideoSourceType||{}),AudioSourceType=(e=>(e[e.AUDIO_SOURCE_TYPE_EXTERNAL=0]="AUDIO_SOURCE_TYPE_EXTERNAL",e[e.AUDIO_SOURCE_TYPE_INTERNAL=1]="AUDIO_SOURCE_TYPE_INTERNAL",e))(AudioSourceType||{}),UserOfflineReason=(e=>(e[e.QUIT=0]="QUIT",e[e.DROPPED=1]="DROPPED",e[e.SWITCH_TO_INVISIBLE=2]="SWITCH_TO_INVISIBLE",e[e.KICKED_BY_ADMIN=3]="KICKED_BY_ADMIN",e))(UserOfflineReason||{}),UserDisconnectionTag$1=(e=>(e.userLeave="userLeave",e.connectionLost="connectionLost",e.userDuplicateLogin="userDuplicateLogin",e.kickedByAdmin="kickedByAdmin",e.roleChanged="roleChanged",e.onUserTokenDidExpire="onUserTokenDidExpire",e))(UserDisconnectionTag$1||{}),ChannelProfile=(e=>(e[e.CHANNEL_PROFILE_COMMUNICATION=0]="CHANNEL_PROFILE_COMMUNICATION",e[e.CHANNEL_PROFILE_LIVE_BROADCASTING=1]="CHANNEL_PROFILE_LIVE_BROADCASTING",e))(ChannelProfile||{}),SubscribeMode=(e=>(e[e.AUTO_SUBSCRIBE_MODE=0]="AUTO_SUBSCRIBE_MODE",e[e.MANUAL_SUBSCRIBE_MODE=1]="MANUAL_SUBSCRIBE_MODE",e))(SubscribeMode||{}),SubscribeState=(e=>(e[e.SUBSCRIBE_SUCC=0]="SUBSCRIBE_SUCC",e[e.SUBSCRIBE_FAIL=1]="SUBSCRIBE_FAIL",e))(SubscribeState||{}),PublishState=(e=>(e[e.PUBLISH_SUCC=0]="PUBLISH_SUCC",e[e.PUBLISH_FAIL=1]="PUBLISH_FAIL",e))(PublishState||{}),MirrorMode=(e=>(e[e.MIRROR_MODE_OFF=0]="MIRROR_MODE_OFF",e[e.MIRROR_MODE_ON=1]="MIRROR_MODE_ON",e))(MirrorMode||{}),VideoRenderMode=(e=>(e[e.RENDER_MODE_HIDDEN=0]="RENDER_MODE_HIDDEN",e[e.RENDER_MODE_FIT=1]="RENDER_MODE_FIT",e[e.RENDER_MODE_FILL=2]="RENDER_MODE_FILL",e))(VideoRenderMode||{}),StreamIndex$1=(e=>(e[e.STREAM_INDEX_MAIN=0]="STREAM_INDEX_MAIN",e[e.STREAM_INDEX_SCREEN=1]="STREAM_INDEX_SCREEN",e))(StreamIndex$1||{}),MediaType$1=(e=>(e[e.AUDIO=1]="AUDIO",e[e.VIDEO=2]="VIDEO",e[e.AUDIO_AND_VIDEO=3]="AUDIO_AND_VIDEO",e))(MediaType$1||{}),StreamRemoveReason=(e=>(e[e.STREAM_REMOVE_REASON_UNPUBLISH=0]="STREAM_REMOVE_REASON_UNPUBLISH",e[e.STREAM_REMOVE_REASON_PUBLISH_FAILED=1]="STREAM_REMOVE_REASON_PUBLISH_FAILED",e[e.STREAM_REMOVE_REASON_KEEP_LIVE_FAILED=2]="STREAM_REMOVE_REASON_KEEP_LIVE_FAILED",e[e.STREAM_REMOVE_REASON_CLIENT_DISCONNECTED=3]="STREAM_REMOVE_REASON_CLIENT_DISCONNECTED",e[e.STREAM_REMOVE_REASON_REPUBLISH=4]="STREAM_REMOVE_REASON_REPUBLISH",e[e.STREAM_REMOVE_REASON_OTHER=5]="STREAM_REMOVE_REASON_OTHER",e[e.STREAM_REMOVE_REASON_TOKEN_PRIVILEGE_EXPIRED=6]="STREAM_REMOVE_REASON_TOKEN_PRIVILEGE_EXPIRED",e))(StreamRemoveReason||{}),ConnectionState=(e=>(e[e.CONNECTION_START=0]="CONNECTION_START",e[e.CONNECTION_STATE_DISCONNECTED=1]="CONNECTION_STATE_DISCONNECTED",e[e.CONNECTION_STATE_CONNECTING=2]="CONNECTION_STATE_CONNECTING",e[e.CONNECTION_STATE_CONNECTED=3]="CONNECTION_STATE_CONNECTED",e[e.CONNECTION_STATE_RECONNECTING=4]="CONNECTION_STATE_RECONNECTING",e[e.CONNECTION_STATE_RECONNECTED=5]="CONNECTION_STATE_RECONNECTED",e[e.CONNECTION_STATE_LOST=6]="CONNECTION_STATE_LOST",e))(ConnectionState||{}),ReconnectReason=(e=>(e.ICE_FAILED="iceFailed",e.NODE_CHANGE="nodeChange",e.JOIN_TIMEOUT="joinTimeout",e.NOTIFY_RECONNECT="notifyReconnect",e))(ReconnectReason||{}),VideoCodecType=(e=>(e.AUTO="auto",e.H264="h264",e.VP8="vp8",e.ByteVC1="ByteVC1",e))(VideoCodecType||{}),MirrorType=(e=>(e[e.MIRROR_TYPE_NONE=0]="MIRROR_TYPE_NONE",e[e.MIRROR_TYPE_RENDER=1]="MIRROR_TYPE_RENDER",e))(MirrorType||{}),LocalMainReportMode=(e=>(e[e.NORMAL=0]="NORMAL",e[e.DISCONNECT=1]="DISCONNECT",e[e.RESET=2]="RESET",e))(LocalMainReportMode||{}),AudioReportMode=(e=>(e[e.MICROPHONE=0]="MICROPHONE",e[e.AUDIOMIXING=1]="AUDIOMIXING",e))(AudioReportMode||{}),LogChannel=(e=>(e[e.domestic=0]="domestic",e[e.overseas=1]="overseas",e))(LogChannel||{}),USER_ONLINE_STATUS=(e=>(e[e.OFFLINE=0]="OFFLINE",e[e.ONLINE=1]="ONLINE",e[e.UNREACHABLE=2]="UNREACHABLE",e))(USER_ONLINE_STATUS||{}),PublicStreamType=(e=>(e[e.AUDIO_AND_VIDEO=0]="AUDIO_AND_VIDEO",e[e.AUDIO_ONLY=1]="AUDIO_ONLY",e[e.VIDEO_ONLY=2]="VIDEO_ONLY",e))(PublicStreamType||{}),PublicInterpolationMode=(e=>(e[e.PREV_FRAME=0]="PREV_FRAME",e[e.OTHER_FRAME=1]="OTHER_FRAME",e))(PublicInterpolationMode||{}),SubscribeFallbackOption=(e=>(e[e.DISABLE=0]="DISABLE",e[e.VIDEO_STREAM_LOW=1]="VIDEO_STREAM_LOW",e[e.AUDIO_ONLY=2]="AUDIO_ONLY",e))(SubscribeFallbackOption||{}),RemoteUserPriority=(e=>(e[e.LOW=0]="LOW",e[e.MEDIUM=100]="MEDIUM",e[e.HIGH=200]="HIGH",e))(RemoteUserPriority||{}),NetworkQuality=(e=>(e[e.UNKNOWN=0]="UNKNOWN",e[e.EXCELLENT=1]="EXCELLENT",e[e.GOOD=2]="GOOD",e[e.POOR=3]="POOR",e[e.BAD=4]="BAD",e[e.VBAD=5]="VBAD",e[e.DOWN=6]="DOWN",e))(NetworkQuality||{}),FallbackOrRecoverReason=(e=>(e[e.Unknown=-1]="Unknown",e[e.SubscribeFallbackByBandwidth=0]="SubscribeFallbackByBandwidth",e[e.SubscribeRecoverByBandwidth=2]="SubscribeRecoverByBandwidth",e))(FallbackOrRecoverReason||{}),RoomProfileType=(e=>(e[e.communication=0]="communication",e[e.chat=5]="chat",e[e.chatRoom=6]="chatRoom",e[e.coHost=9]="coHost",e[e.meeting=16]="meeting",e[e.classRoom=18]="classRoom",e))(RoomProfileType||{}),AudioProfileType=(e=>(e[e.default=0]="default",e[e.fluent=1]="fluent",e[e.standard=2]="standard",e[e.hd=3]="hd",e[e.standardStereo=4]="standardStereo",e[e.hdMono=5]="hdMono",e))(AudioProfileType||{}),RTCAutoPlayPolicy=(e=>(e[e.AUTO_PLAY=0]="AUTO_PLAY",e[e.VIDEO_ONLY=1]="VIDEO_ONLY",e[e.PLAY_MANUALLY=2]="PLAY_MANUALLY",e))(RTCAutoPlayPolicy||{}),AAC_PROFILE=(e=>(e.LC="LC",e.HEv1="HEv1",e.HEv2="HEv2",e))(AAC_PROFILE||{}),TRANSCODING_VIDEO_CODEC=(e=>(e.H264="H264",e.H265="H265",e))(TRANSCODING_VIDEO_CODEC||{}),SUBTITLE_MODE=(e=>(e[e.ASR_ONLY=0]="ASR_ONLY",e[e.ASR_AND_TRANSLATION=1]="ASR_AND_TRANSLATION",e))(SUBTITLE_MODE||{}),SubtitleEventType=(e=>(e[e.STARTED=0]="STARTED",e[e.STOPPED=1]="STOPPED",e[e.ERROR=2]="ERROR",e[e.UPDATED=3]="UPDATED",e))(SubtitleEventType||{}),ForwardStreamState=(e=>(e[e.FORWARD_STREAM_STATE_SUCCESS=0]="FORWARD_STREAM_STATE_SUCCESS",e[e.FORWARD_STREAM_STATE_FAILURE=1]="FORWARD_STREAM_STATE_FAILURE",e))(ForwardStreamState||{}),ForwardStreamError=(e=>(e[e.FORWARD_STREAM_ERROR_OK=0]="FORWARD_STREAM_ERROR_OK",e[e.FORWARD_STREAM_ERROR_INVALID_TOKEN=1202]="FORWARD_STREAM_ERROR_INVALID_TOKEN",e[e.FORWARD_STREAM_ERROR_RESPONSE=1203]="FORWARD_STREAM_ERROR_RESPONSE",e[e.FORWARD_STREAM_ERROR_REMOTE_KICKED=1204]="FORWARD_STREAM_ERROR_REMOTE_KICKED",e[e.FORWARD_STREAM_ERROR_NOT_SUPPORT=1205]="FORWARD_STREAM_ERROR_NOT_SUPPORT",e))(ForwardStreamError||{}),AudioSelectionPriority=(e=>(e[e.DEFAULT=0]="DEFAULT",e[e.HIGH=1]="HIGH",e))(AudioSelectionPriority||{}),VideoSimulcastMode=(e=>(e[e.VIDEO_ONLY_ONE=0]="VIDEO_ONLY_ONE",e[e.VIDEO_ON_DEMAND=1]="VIDEO_ON_DEMAND",e[e.VIDEO_ALWAYS_SIMULCAST=2]="VIDEO_ALWAYS_SIMULCAST",e))(VideoSimulcastMode||{}),SimulcastStreamType=(e=>(e.VIDEO_STREAM_HIGH="high",e.VIDEO_STREAM_MID="mid",e.VIDEO_STREAM_LOW="low",e))(SimulcastStreamType||{}),EarMonitorPosition=(e=>(e[e.NONE=0]="NONE",e[e.AFTER_CAPTURE=1]="AFTER_CAPTURE",e[e.AFTER_PROCESS=2]="AFTER_PROCESS",e))(EarMonitorPosition||{}),RoomMode=(e=>(e[e.ROOM_MODE_RTC=0]="ROOM_MODE_RTC",e[e.ROOM_MODE_RTS_ONLY=1]="ROOM_MODE_RTS_ONLY",e))(RoomMode||{}),rnds8$1=new Uint8Array(16);function rng$1(){if(!getRandomValues$1&&!(getRandomValues$1="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return getRandomValues$1(rnds8$1)}var REGEX=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function validate(e){return"string"==typeof e&&REGEX.test(e)}for(var byteToHex$1=[],i=0;i<256;++i)byteToHex$1.push((i+256).toString(16).substr(1));function stringify(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=(byteToHex$1[e[t+0]]+byteToHex$1[e[t+1]]+byteToHex$1[e[t+2]]+byteToHex$1[e[t+3]]+"-"+byteToHex$1[e[t+4]]+byteToHex$1[e[t+5]]+"-"+byteToHex$1[e[t+6]]+byteToHex$1[e[t+7]]+"-"+byteToHex$1[e[t+8]]+byteToHex$1[e[t+9]]+"-"+byteToHex$1[e[t+10]]+byteToHex$1[e[t+11]]+byteToHex$1[e[t+12]]+byteToHex$1[e[t+13]]+byteToHex$1[e[t+14]]+byteToHex$1[e[t+15]]).toLowerCase();if(!validate(i))throw TypeError("Stringified UUID is invalid");return i}function v4$1(e,t,i){var r=(e=e||{}).random||(e.rng||rng$1)();if(r[6]=15&r[6]|64,r[8]=63&r[8]|128,t){i=i||0;for(var o=0;o<16;++o)t[i+o]=r[o];return t}return stringify(r)}const isSSR$1=()=>"undefined"==typeof window,genUuid$1=()=>v4$1(),assertValidMsgId=e=>"number"==typeof e,isNativeFunction=e=>Function.prototype.toString.call(e).includes("[native code]");function mediaTrackStringify(e){return null==e?"undefined | null":"string"==typeof e?e:JSON.stringify({contentHint:e.contentHint,enabled:e.enabled,id:e.id,kind:e.kind,label:e.label,muted:e.muted,readyState:e.readyState})}function mediaStreamStringify(e){return null==e?"undefined | null":"string"==typeof e?e:JSON.stringify({id:e.id,active:e.active})}function mediaSenderStringify(e){return null==e?"undefined | null":"string"==typeof e?e:JSON.stringify({track:mediaTrackStringify(e.track)})}function mediaReceiverStringify(e){return null==e?"undefined | null":"string"==typeof e?e:JSON.stringify({track:mediaTrackStringify(e.track)})}function mediaTransceiverStringify(e){return null==e?"undefined | null":"string"==typeof e?e:JSON.stringify({currentDirection:e.currentDirection,direction:e.direction,mid:e.mid,stopped:e.stopped,receiver:mediaReceiverStringify(e.receiver),sender:mediaSenderStringify(e.sender)})}const DB_NAME$1="@byted/ve-rtc",STORE_NAME="@byted/ve-rtc",STORE_CACHED_SIZE_KEY="@byted/ve-rtc-cache-size";class IDB{constructor(){__publicField(this,"storeKey"),__publicField(this,"logLevel"),__publicField(this,"LogfileSize"),__publicField(this,"db"),__publicField(this,"logId"),__publicField(this,"cacheLog"),__publicField(this,"cachedSize"),__publicField(this,"preCacheTime"),__publicField(this,"timer"),__publicField(this,"_getSize",(e=>new Blob(e).size/1048576)),this.storeKey="",this.logId=1,this.cacheLog="",this.logLevel="none",this.LogfileSize=100,this._createStore()}_createStore(){if(isSSR$1()||!window.indexedDB)return;const e=indexedDB.open(DB_NAME$1);e.onupgradeneeded=()=>{e.result.createObjectStore(STORE_NAME);try{localStorage.removeItem(STORE_CACHED_SIZE_KEY)}catch(e){}},e.onerror=e=>{},e.onsuccess=()=>{this.db=e.result,this._getCachedSize()}}_getCachedSize(){try{const e=localStorage.getItem(STORE_CACHED_SIZE_KEY);e?this.cachedSize=Number(e):this.values().then((e=>{this.cachedSize=this._getSize(e),this._setCachedSize()}))}catch(e){}}_setCachedSize(){try{localStorage.setItem(STORE_CACHED_SIZE_KEY,`${this.cachedSize}`)}catch(e){}}_getStore(e){if(this.db)return this.db.transaction(STORE_NAME,e).objectStore(STORE_NAME)}set(e){return new Promise(((t,i)=>{if("none"===this.logLevel)return t();if(e&&this.preCacheTime&&this.preCacheTime-Date.now()<1e3)return this.cacheLog+=`\n\n${this.logId}: ${e}`,this.logId++,this.timer||(this.timer=setTimeout((()=>{this.set("")}),1e3-(this.preCacheTime-Date.now()))),t();clearTimeout(this.timer),this.timer=null;const r=this._getStore("readwrite");if(!r)return i("get store fail");this.cachedSize&&this.cachedSize>this.LogfileSize&&this.keyEarliest().then((e=>{this.get(e).then((t=>{this.del(e).then((()=>{this.cachedSize=this.cachedSize-this._getSize([`${t}`]),this._setCachedSize()}))}))}));const o=r.get(this.storeKey);o.onsuccess=()=>{try{const i=`${o.result||""}${this.cacheLog}`,s=e?`${i?"\n\n":""}${this.logId}: ${e}`:"";r.put(`${i}${s}`,this.storeKey),e&&this.logId++,this.cacheLog="",this.cachedSize=(this.cachedSize||0)+this._getSize([`${this.cacheLog}${s}`]),this._setCachedSize(),this.preCacheTime=Date.now(),t()}catch(t){if(!e)return i(t);this.cacheLog+=`\n\n${this.logId}: ${e}`,this.logId++,i(t)}},o.onerror=t=>{if(!e)return i(t);this.cacheLog+=`\n\n${this.logId}: ${e}`,this.logId++,i(t)}}))}get(e){return new Promise(((t,i)=>{const r=this._getStore("readonly");if(!r)return i();const o=r.get(e);o.onsuccess=()=>{t(o.result)},o.onerror=e=>{i(e)}}))}del(e=this.storeKey){return new Promise(((t,i)=>{const r=this._getStore("readwrite");if(!r)return i();const o=r.delete(e);o.onsuccess=()=>t(o.result),o.onerror=e=>i(e)}))}keyEarliest(){return this.keys().then((e=>{let t,i=Date.now();return e.forEach((e=>{if(!e||!e.length)return;const r=e.split("-")[0];Number(r)<i&&(i=Number(r),t=e)})),t}))}keys(){return new Promise(((e,t)=>{const i=this._getStore("readonly");if(!i)return t();if(i.getAllKeys){const r=i.getAllKeys();return r.onsuccess=()=>{e(r.result)},void(r.onerror=()=>{t()})}const r=[];i.openCursor().onsuccess=function(){this.result&&(r.push(this.result.key),this.result.continue())},i.transaction.oncomplete=()=>e(r)}))}values(){return new Promise(((e,t)=>{const i=this._getStore("readonly");if(!i)return t();if(i.getAll){const r=i.getAll();return r.onsuccess=()=>{e(r.result)},void(r.onerror=()=>{t()})}const r=[];i.openCursor().onsuccess=function(){this.result&&(r.push(this.result.value),this.result.continue())},i.transaction.oncomplete=()=>e(r)}))}download(e){e=e||this.storeKey,this.get(e).then((t=>{const i=document.createElement("a");i.download=`${e}.txt`,i.href=`data:text/paint;utf-8,${t||""}`,i.click()}))}}var iDB=new IDB;let EventEmitter$1=class{constructor(){__publicField(this,"_all",{})}on(e,t){const i=this._all[e];i?i.push(t):this._all[e]=[t]}once(e,t){const i=(...r)=>{t(...r),this.off(e,i)};this.on(e,i)}off(e,t){const i=this._all[e];null==i||i.splice(i.indexOf(t)>>>0,1)}emit(e,...t){const i=this._all[e];null==i||i.slice().forEach((e=>e(...t)))}safeEmit(e,...t){try{return this.emit(e,...t)}catch(e){console.error(e)}}destroy(){this._all={}}};const configNumberKeys=["UPLOAD_CONSOLE_LENGTH_CUT","UPLOAD_REPORT_LIMIT"];function needToNumber(e){return configNumberKeys.includes(e)}let Config$2=class extends EventEmitter$1{constructor(){super(...arguments),__publicField(this,"config",{UPLOAD_CONSOLE_ON:!1,UPLOAD_CONSOLE_LENGTH_CUT:200,UPLOAD_REPORT_LIMIT:45e4,ENABLE_REPORT_IDB_BUFFER:!1})}setParameter(e,t){if(needToNumber(e))try{const i=Number(t);if(Number.isNaN(i))return;this.config[e]=i}catch{return void console.warn(`Cannot convert core lib parameter ${e}:${t} into number`)}else this.config[e]=t;this.emit(e,this.config[e])}getParameter(e){return this.config[e]}getKeys(){return Object.keys(this.config)}};const CoreConfig=new Config$2;var commonjsGlobal="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function getDefaultExportFromCjs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function getAugmentedNamespace(e){if(e.__esModule)return e;var t=e.default;if("function"==typeof t){var i=function e(){if(this instanceof e){var i=[null];return i.push.apply(i,arguments),new(Function.bind.apply(t,i))}return t.apply(this,arguments)};i.prototype=t.prototype}else i={};return Object.defineProperty(i,"__esModule",{value:!0}),Object.keys(e).forEach((function(t){var r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(i,t,r.get?r:{enumerable:!0,get:function(){return e[t]}})})),i}var common={};!function(e){var t="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;function i(e,t){return Object.prototype.hasOwnProperty.call(e,t)}e.assign=function(e){for(var t=Array.prototype.slice.call(arguments,1);t.length;){var r=t.shift();if(r){if("object"!=typeof r)throw new TypeError(r+"must be non-object");for(var o in r)i(r,o)&&(e[o]=r[o])}}return e},e.shrinkBuf=function(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)};var r={arraySet:function(e,t,i,r,o){if(t.subarray&&e.subarray)e.set(t.subarray(i,i+r),o);else for(var s=0;s<r;s++)e[o+s]=t[i+s]},flattenChunks:function(e){var t,i,r,o,s,n;for(r=0,t=0,i=e.length;t<i;t++)r+=e[t].length;for(n=new Uint8Array(r),o=0,t=0,i=e.length;t<i;t++)s=e[t],n.set(s,o),o+=s.length;return n}},o={arraySet:function(e,t,i,r,o){for(var s=0;s<r;s++)e[o+s]=t[i+s]},flattenChunks:function(e){return[].concat.apply([],e)}};e.setTyped=function(t){t?(e.Buf8=Uint8Array,e.Buf16=Uint16Array,e.Buf32=Int32Array,e.assign(e,r)):(e.Buf8=Array,e.Buf16=Array,e.Buf32=Array,e.assign(e,o))},e.setTyped(t)}(common);var deflate$4={},deflate$3={},trees$1={},utils$6=common,Z_FIXED$1=4,Z_BINARY=0,Z_TEXT=1,Z_UNKNOWN$1=2;function zero$1(e){for(var t=e.length;--t>=0;)e[t]=0}var STORED_BLOCK=0,STATIC_TREES=1,DYN_TREES=2,MIN_MATCH$1=3,MAX_MATCH$1=258,LENGTH_CODES$1=29,LITERALS$1=256,L_CODES$1=LITERALS$1+1+LENGTH_CODES$1,D_CODES$1=30,BL_CODES$1=19,HEAP_SIZE$1=2*L_CODES$1+1,MAX_BITS$1=15,Buf_size=16,MAX_BL_BITS=7,END_BLOCK=256,REP_3_6=16,REPZ_3_10=17,REPZ_11_138=18,extra_lbits=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],extra_dbits=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],extra_blbits=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],bl_order=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],DIST_CODE_LEN=512,static_ltree=new Array(2*(L_CODES$1+2));zero$1(static_ltree);var static_dtree=new Array(2*D_CODES$1);zero$1(static_dtree);var _dist_code=new Array(DIST_CODE_LEN);zero$1(_dist_code);var _length_code=new Array(MAX_MATCH$1-MIN_MATCH$1+1);zero$1(_length_code);var base_length=new Array(LENGTH_CODES$1);zero$1(base_length);var static_l_desc,static_d_desc,static_bl_desc,base_dist=new Array(D_CODES$1);function StaticTreeDesc(e,t,i,r,o){this.static_tree=e,this.extra_bits=t,this.extra_base=i,this.elems=r,this.max_length=o,this.has_stree=e&&e.length}function TreeDesc(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}function d_code(e){return e<256?_dist_code[e]:_dist_code[256+(e>>>7)]}function put_short(e,t){e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255}function send_bits(e,t,i){e.bi_valid>Buf_size-i?(e.bi_buf|=t<<e.bi_valid&65535,put_short(e,e.bi_buf),e.bi_buf=t>>Buf_size-e.bi_valid,e.bi_valid+=i-Buf_size):(e.bi_buf|=t<<e.bi_valid&65535,e.bi_valid+=i)}function send_code(e,t,i){send_bits(e,i[2*t],i[2*t+1])}function bi_reverse(e,t){var i=0;do{i|=1&e,e>>>=1,i<<=1}while(--t>0);return i>>>1}function bi_flush(e){16===e.bi_valid?(put_short(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)}function gen_bitlen(e,t){var i,r,o,s,n,a,d=t.dyn_tree,c=t.max_code,l=t.stat_desc.static_tree,u=t.stat_desc.has_stree,_=t.stat_desc.extra_bits,h=t.stat_desc.extra_base,p=t.stat_desc.max_length,m=0;for(s=0;s<=MAX_BITS$1;s++)e.bl_count[s]=0;for(d[2*e.heap[e.heap_max]+1]=0,i=e.heap_max+1;i<HEAP_SIZE$1;i++)(s=d[2*d[2*(r=e.heap[i])+1]+1]+1)>p&&(s=p,m++),d[2*r+1]=s,r>c||(e.bl_count[s]++,n=0,r>=h&&(n=_[r-h]),a=d[2*r],e.opt_len+=a*(s+n),u&&(e.static_len+=a*(l[2*r+1]+n)));if(0!==m){do{for(s=p-1;0===e.bl_count[s];)s--;e.bl_count[s]--,e.bl_count[s+1]+=2,e.bl_count[p]--,m-=2}while(m>0);for(s=p;0!==s;s--)for(r=e.bl_count[s];0!==r;)(o=e.heap[--i])>c||(d[2*o+1]!==s&&(e.opt_len+=(s-d[2*o+1])*d[2*o],d[2*o+1]=s),r--)}}function gen_codes(e,t,i){var r,o,s=new Array(MAX_BITS$1+1),n=0;for(r=1;r<=MAX_BITS$1;r++)s[r]=n=n+i[r-1]<<1;for(o=0;o<=t;o++){var a=e[2*o+1];0!==a&&(e[2*o]=bi_reverse(s[a]++,a))}}function tr_static_init(){var e,t,i,r,o,s=new Array(MAX_BITS$1+1);for(i=0,r=0;r<LENGTH_CODES$1-1;r++)for(base_length[r]=i,e=0;e<1<<extra_lbits[r];e++)_length_code[i++]=r;for(_length_code[i-1]=r,o=0,r=0;r<16;r++)for(base_dist[r]=o,e=0;e<1<<extra_dbits[r];e++)_dist_code[o++]=r;for(o>>=7;r<D_CODES$1;r++)for(base_dist[r]=o<<7,e=0;e<1<<extra_dbits[r]-7;e++)_dist_code[256+o++]=r;for(t=0;t<=MAX_BITS$1;t++)s[t]=0;for(e=0;e<=143;)static_ltree[2*e+1]=8,e++,s[8]++;for(;e<=255;)static_ltree[2*e+1]=9,e++,s[9]++;for(;e<=279;)static_ltree[2*e+1]=7,e++,s[7]++;for(;e<=287;)static_ltree[2*e+1]=8,e++,s[8]++;for(gen_codes(static_ltree,L_CODES$1+1,s),e=0;e<D_CODES$1;e++)static_dtree[2*e+1]=5,static_dtree[2*e]=bi_reverse(e,5);static_l_desc=new StaticTreeDesc(static_ltree,extra_lbits,LITERALS$1+1,L_CODES$1,MAX_BITS$1),static_d_desc=new StaticTreeDesc(static_dtree,extra_dbits,0,D_CODES$1,MAX_BITS$1),static_bl_desc=new StaticTreeDesc(new Array(0),extra_blbits,0,BL_CODES$1,MAX_BL_BITS)}function init_block(e){var t;for(t=0;t<L_CODES$1;t++)e.dyn_ltree[2*t]=0;for(t=0;t<D_CODES$1;t++)e.dyn_dtree[2*t]=0;for(t=0;t<BL_CODES$1;t++)e.bl_tree[2*t]=0;e.dyn_ltree[2*END_BLOCK]=1,e.opt_len=e.static_len=0,e.last_lit=e.matches=0}function bi_windup(e){e.bi_valid>8?put_short(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0}function copy_block(e,t,i,r){bi_windup(e),r&&(put_short(e,i),put_short(e,~i)),utils$6.arraySet(e.pending_buf,e.window,t,i,e.pending),e.pending+=i}function smaller(e,t,i,r){var o=2*t,s=2*i;return e[o]<e[s]||e[o]===e[s]&&r[t]<=r[i]}function pqdownheap(e,t,i){for(var r=e.heap[i],o=i<<1;o<=e.heap_len&&(o<e.heap_len&&smaller(t,e.heap[o+1],e.heap[o],e.depth)&&o++,!smaller(t,r,e.heap[o],e.depth));)e.heap[i]=e.heap[o],i=o,o<<=1;e.heap[i]=r}function compress_block(e,t,i){var r,o,s,n,a=0;if(0!==e.last_lit)do{r=e.pending_buf[e.d_buf+2*a]<<8|e.pending_buf[e.d_buf+2*a+1],o=e.pending_buf[e.l_buf+a],a++,0===r?send_code(e,o,t):(send_code(e,(s=_length_code[o])+LITERALS$1+1,t),0!==(n=extra_lbits[s])&&send_bits(e,o-=base_length[s],n),send_code(e,s=d_code(--r),i),0!==(n=extra_dbits[s])&&send_bits(e,r-=base_dist[s],n))}while(a<e.last_lit);send_code(e,END_BLOCK,t)}function build_tree(e,t){var i,r,o,s=t.dyn_tree,n=t.stat_desc.static_tree,a=t.stat_desc.has_stree,d=t.stat_desc.elems,c=-1;for(e.heap_len=0,e.heap_max=HEAP_SIZE$1,i=0;i<d;i++)0!==s[2*i]?(e.heap[++e.heap_len]=c=i,e.depth[i]=0):s[2*i+1]=0;for(;e.heap_len<2;)s[2*(o=e.heap[++e.heap_len]=c<2?++c:0)]=1,e.depth[o]=0,e.opt_len--,a&&(e.static_len-=n[2*o+1]);for(t.max_code=c,i=e.heap_len>>1;i>=1;i--)pqdownheap(e,s,i);o=d;do{i=e.heap[1],e.heap[1]=e.heap[e.heap_len--],pqdownheap(e,s,1),r=e.heap[1],e.heap[--e.heap_max]=i,e.heap[--e.heap_max]=r,s[2*o]=s[2*i]+s[2*r],e.depth[o]=(e.depth[i]>=e.depth[r]?e.depth[i]:e.depth[r])+1,s[2*i+1]=s[2*r+1]=o,e.heap[1]=o++,pqdownheap(e,s,1)}while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],gen_bitlen(e,t),gen_codes(s,c,e.bl_count)}function scan_tree(e,t,i){var r,o,s=-1,n=t[1],a=0,d=7,c=4;for(0===n&&(d=138,c=3),t[2*(i+1)+1]=65535,r=0;r<=i;r++)o=n,n=t[2*(r+1)+1],++a<d&&o===n||(a<c?e.bl_tree[2*o]+=a:0!==o?(o!==s&&e.bl_tree[2*o]++,e.bl_tree[2*REP_3_6]++):a<=10?e.bl_tree[2*REPZ_3_10]++:e.bl_tree[2*REPZ_11_138]++,a=0,s=o,0===n?(d=138,c=3):o===n?(d=6,c=3):(d=7,c=4))}function send_tree(e,t,i){var r,o,s=-1,n=t[1],a=0,d=7,c=4;for(0===n&&(d=138,c=3),r=0;r<=i;r++)if(o=n,n=t[2*(r+1)+1],!(++a<d&&o===n)){if(a<c)do{send_code(e,o,e.bl_tree)}while(0!=--a);else 0!==o?(o!==s&&(send_code(e,o,e.bl_tree),a--),send_code(e,REP_3_6,e.bl_tree),send_bits(e,a-3,2)):a<=10?(send_code(e,REPZ_3_10,e.bl_tree),send_bits(e,a-3,3)):(send_code(e,REPZ_11_138,e.bl_tree),send_bits(e,a-11,7));a=0,s=o,0===n?(d=138,c=3):o===n?(d=6,c=3):(d=7,c=4)}}function build_bl_tree(e){var t;for(scan_tree(e,e.dyn_ltree,e.l_desc.max_code),scan_tree(e,e.dyn_dtree,e.d_desc.max_code),build_tree(e,e.bl_desc),t=BL_CODES$1-1;t>=3&&0===e.bl_tree[2*bl_order[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t}function send_all_trees(e,t,i,r){var o;for(send_bits(e,t-257,5),send_bits(e,i-1,5),send_bits(e,r-4,4),o=0;o<r;o++)send_bits(e,e.bl_tree[2*bl_order[o]+1],3);send_tree(e,e.dyn_ltree,t-1),send_tree(e,e.dyn_dtree,i-1)}function detect_data_type(e){var t,i=4093624447;for(t=0;t<=31;t++,i>>>=1)if(1&i&&0!==e.dyn_ltree[2*t])return Z_BINARY;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return Z_TEXT;for(t=32;t<LITERALS$1;t++)if(0!==e.dyn_ltree[2*t])return Z_TEXT;return Z_BINARY}zero$1(base_dist);var static_init_done=!1;function _tr_init(e){static_init_done||(tr_static_init(),static_init_done=!0),e.l_desc=new TreeDesc(e.dyn_ltree,static_l_desc),e.d_desc=new TreeDesc(e.dyn_dtree,static_d_desc),e.bl_desc=new TreeDesc(e.bl_tree,static_bl_desc),e.bi_buf=0,e.bi_valid=0,init_block(e)}function _tr_stored_block(e,t,i,r){send_bits(e,(STORED_BLOCK<<1)+(r?1:0),3),copy_block(e,t,i,!0)}function _tr_align(e){send_bits(e,STATIC_TREES<<1,3),send_code(e,END_BLOCK,static_ltree),bi_flush(e)}function _tr_flush_block(e,t,i,r){var o,s,n=0;e.level>0?(e.strm.data_type===Z_UNKNOWN$1&&(e.strm.data_type=detect_data_type(e)),build_tree(e,e.l_desc),build_tree(e,e.d_desc),n=build_bl_tree(e),o=e.opt_len+3+7>>>3,(s=e.static_len+3+7>>>3)<=o&&(o=s)):o=s=i+5,i+4<=o&&-1!==t?_tr_stored_block(e,t,i,r):e.strategy===Z_FIXED$1||s===o?(send_bits(e,(STATIC_TREES<<1)+(r?1:0),3),compress_block(e,static_ltree,static_dtree)):(send_bits(e,(DYN_TREES<<1)+(r?1:0),3),send_all_trees(e,e.l_desc.max_code+1,e.d_desc.max_code+1,n+1),compress_block(e,e.dyn_ltree,e.dyn_dtree)),init_block(e),r&&bi_windup(e)}function _tr_tally(e,t,i){return e.pending_buf[e.d_buf+2*e.last_lit]=t>>>8&255,e.pending_buf[e.d_buf+2*e.last_lit+1]=255&t,e.pending_buf[e.l_buf+e.last_lit]=255&i,e.last_lit++,0===t?e.dyn_ltree[2*i]++:(e.matches++,t--,e.dyn_ltree[2*(_length_code[i]+LITERALS$1+1)]++,e.dyn_dtree[2*d_code(t)]++),e.last_lit===e.lit_bufsize-1}function adler32$2(e,t,i,r){for(var o=65535&e,s=e>>>16&65535,n=0;0!==i;){i-=n=i>2e3?2e3:i;do{s=s+(o=o+t[r++]|0)|0}while(--n);o%=65521,s%=65521}return o|s<<16}trees$1._tr_init=_tr_init,trees$1._tr_stored_block=_tr_stored_block,trees$1._tr_flush_block=_tr_flush_block,trees$1._tr_tally=_tr_tally,trees$1._tr_align=_tr_align;var adler32_1=adler32$2;function makeTable(){for(var e,t=[],i=0;i<256;i++){e=i;for(var r=0;r<8;r++)e=1&e?3988292384^e>>>1:e>>>1;t[i]=e}return t}var crcTable=makeTable();function crc32$2(e,t,i,r){var o=crcTable,s=r+i;e^=-1;for(var n=r;n<s;n++)e=e>>>8^o[255&(e^t[n])];return~e}var configuration_table,crc32_1=crc32$2,messages={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},utils$5=common,trees=trees$1,adler32$1=adler32_1,crc32$1=crc32_1,msg$2=messages,Z_NO_FLUSH$1=0,Z_PARTIAL_FLUSH=1,Z_FULL_FLUSH=3,Z_FINISH$2=4,Z_BLOCK$1=5,Z_OK$2=0,Z_STREAM_END$2=1,Z_STREAM_ERROR$1=-2,Z_DATA_ERROR$1=-3,Z_BUF_ERROR$1=-5,Z_DEFAULT_COMPRESSION$1=-1,Z_FILTERED=1,Z_HUFFMAN_ONLY=2,Z_RLE=3,Z_FIXED=4,Z_DEFAULT_STRATEGY$1=0,Z_UNKNOWN=2,Z_DEFLATED$2=8,MAX_MEM_LEVEL=9,MAX_WBITS$1=15,DEF_MEM_LEVEL=8,LENGTH_CODES=29,LITERALS=256,L_CODES=LITERALS+1+LENGTH_CODES,D_CODES=30,BL_CODES=19,HEAP_SIZE=2*L_CODES+1,MAX_BITS=15,MIN_MATCH=3,MAX_MATCH=258,MIN_LOOKAHEAD=MAX_MATCH+MIN_MATCH+1,PRESET_DICT=32,INIT_STATE=42,EXTRA_STATE=69,NAME_STATE=73,COMMENT_STATE=91,HCRC_STATE=103,BUSY_STATE=113,FINISH_STATE=666,BS_NEED_MORE=1,BS_BLOCK_DONE=2,BS_FINISH_STARTED=3,BS_FINISH_DONE=4,OS_CODE=3;function err(e,t){return e.msg=msg$2[t],t}function rank(e){return(e<<1)-(e>4?9:0)}function zero(e){for(var t=e.length;--t>=0;)e[t]=0}function flush_pending(e){var t=e.state,i=t.pending;i>e.avail_out&&(i=e.avail_out),0!==i&&(utils$5.arraySet(e.output,t.pending_buf,t.pending_out,i,e.next_out),e.next_out+=i,t.pending_out+=i,e.total_out+=i,e.avail_out-=i,t.pending-=i,0===t.pending&&(t.pending_out=0))}function flush_block_only(e,t){trees._tr_flush_block(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,flush_pending(e.strm)}function put_byte(e,t){e.pending_buf[e.pending++]=t}function putShortMSB(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t}function read_buf(e,t,i,r){var o=e.avail_in;return o>r&&(o=r),0===o?0:(e.avail_in-=o,utils$5.arraySet(t,e.input,e.next_in,o,i),1===e.state.wrap?e.adler=adler32$1(e.adler,t,o,i):2===e.state.wrap&&(e.adler=crc32$1(e.adler,t,o,i)),e.next_in+=o,e.total_in+=o,o)}function longest_match(e,t){var i,r,o=e.max_chain_length,s=e.strstart,n=e.prev_length,a=e.nice_match,d=e.strstart>e.w_size-MIN_LOOKAHEAD?e.strstart-(e.w_size-MIN_LOOKAHEAD):0,c=e.window,l=e.w_mask,u=e.prev,_=e.strstart+MAX_MATCH,h=c[s+n-1],p=c[s+n];e.prev_length>=e.good_match&&(o>>=2),a>e.lookahead&&(a=e.lookahead);do{if(c[(i=t)+n]===p&&c[i+n-1]===h&&c[i]===c[s]&&c[++i]===c[s+1]){s+=2,i++;do{}while(c[++s]===c[++i]&&c[++s]===c[++i]&&c[++s]===c[++i]&&c[++s]===c[++i]&&c[++s]===c[++i]&&c[++s]===c[++i]&&c[++s]===c[++i]&&c[++s]===c[++i]&&s<_);if(r=MAX_MATCH-(_-s),s=_-MAX_MATCH,r>n){if(e.match_start=t,n=r,r>=a)break;h=c[s+n-1],p=c[s+n]}}}while((t=u[t&l])>d&&0!=--o);return n<=e.lookahead?n:e.lookahead}function fill_window(e){var t,i,r,o,s,n=e.w_size;do{if(o=e.window_size-e.lookahead-e.strstart,e.strstart>=n+(n-MIN_LOOKAHEAD)){utils$5.arraySet(e.window,e.window,n,n,0),e.match_start-=n,e.strstart-=n,e.block_start-=n,t=i=e.hash_size;do{r=e.head[--t],e.head[t]=r>=n?r-n:0}while(--i);t=i=n;do{r=e.prev[--t],e.prev[t]=r>=n?r-n:0}while(--i);o+=n}if(0===e.strm.avail_in)break;if(i=read_buf(e.strm,e.window,e.strstart+e.lookahead,o),e.lookahead+=i,e.lookahead+e.insert>=MIN_MATCH)for(s=e.strstart-e.insert,e.ins_h=e.window[s],e.ins_h=(e.ins_h<<e.hash_shift^e.window[s+1])&e.hash_mask;e.insert&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[s+MIN_MATCH-1])&e.hash_mask,e.prev[s&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=s,s++,e.insert--,!(e.lookahead+e.insert<MIN_MATCH)););}while(e.lookahead<MIN_LOOKAHEAD&&0!==e.strm.avail_in)}function deflate_stored(e,t){var i=65535;for(i>e.pending_buf_size-5&&(i=e.pending_buf_size-5);;){if(e.lookahead<=1){if(fill_window(e),0===e.lookahead&&t===Z_NO_FLUSH$1)return BS_NEED_MORE;if(0===e.lookahead)break}e.strstart+=e.lookahead,e.lookahead=0;var r=e.block_start+i;if((0===e.strstart||e.strstart>=r)&&(e.lookahead=e.strstart-r,e.strstart=r,flush_block_only(e,!1),0===e.strm.avail_out))return BS_NEED_MORE;if(e.strstart-e.block_start>=e.w_size-MIN_LOOKAHEAD&&(flush_block_only(e,!1),0===e.strm.avail_out))return BS_NEED_MORE}return e.insert=0,t===Z_FINISH$2?(flush_block_only(e,!0),0===e.strm.avail_out?BS_FINISH_STARTED:BS_FINISH_DONE):(e.strstart>e.block_start&&(flush_block_only(e,!1),e.strm.avail_out),BS_NEED_MORE)}function deflate_fast(e,t){for(var i,r;;){if(e.lookahead<MIN_LOOKAHEAD){if(fill_window(e),e.lookahead<MIN_LOOKAHEAD&&t===Z_NO_FLUSH$1)return BS_NEED_MORE;if(0===e.lookahead)break}if(i=0,e.lookahead>=MIN_MATCH&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+MIN_MATCH-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),0!==i&&e.strstart-i<=e.w_size-MIN_LOOKAHEAD&&(e.match_length=longest_match(e,i)),e.match_length>=MIN_MATCH)if(r=trees._tr_tally(e,e.strstart-e.match_start,e.match_length-MIN_MATCH),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=MIN_MATCH){e.match_length--;do{e.strstart++,e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+MIN_MATCH-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart}while(0!=--e.match_length);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+1])&e.hash_mask;else r=trees._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(r&&(flush_block_only(e,!1),0===e.strm.avail_out))return BS_NEED_MORE}return e.insert=e.strstart<MIN_MATCH-1?e.strstart:MIN_MATCH-1,t===Z_FINISH$2?(flush_block_only(e,!0),0===e.strm.avail_out?BS_FINISH_STARTED:BS_FINISH_DONE):e.last_lit&&(flush_block_only(e,!1),0===e.strm.avail_out)?BS_NEED_MORE:BS_BLOCK_DONE}function deflate_slow(e,t){for(var i,r,o;;){if(e.lookahead<MIN_LOOKAHEAD){if(fill_window(e),e.lookahead<MIN_LOOKAHEAD&&t===Z_NO_FLUSH$1)return BS_NEED_MORE;if(0===e.lookahead)break}if(i=0,e.lookahead>=MIN_MATCH&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+MIN_MATCH-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=MIN_MATCH-1,0!==i&&e.prev_length<e.max_lazy_match&&e.strstart-i<=e.w_size-MIN_LOOKAHEAD&&(e.match_length=longest_match(e,i),e.match_length<=5&&(e.strategy===Z_FILTERED||e.match_length===MIN_MATCH&&e.strstart-e.match_start>4096)&&(e.match_length=MIN_MATCH-1)),e.prev_length>=MIN_MATCH&&e.match_length<=e.prev_length){o=e.strstart+e.lookahead-MIN_MATCH,r=trees._tr_tally(e,e.strstart-1-e.prev_match,e.prev_length-MIN_MATCH),e.lookahead-=e.prev_length-1,e.prev_length-=2;do{++e.strstart<=o&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+MIN_MATCH-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart)}while(0!=--e.prev_length);if(e.match_available=0,e.match_length=MIN_MATCH-1,e.strstart++,r&&(flush_block_only(e,!1),0===e.strm.avail_out))return BS_NEED_MORE}else if(e.match_available){if((r=trees._tr_tally(e,0,e.window[e.strstart-1]))&&flush_block_only(e,!1),e.strstart++,e.lookahead--,0===e.strm.avail_out)return BS_NEED_MORE}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(r=trees._tr_tally(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<MIN_MATCH-1?e.strstart:MIN_MATCH-1,t===Z_FINISH$2?(flush_block_only(e,!0),0===e.strm.avail_out?BS_FINISH_STARTED:BS_FINISH_DONE):e.last_lit&&(flush_block_only(e,!1),0===e.strm.avail_out)?BS_NEED_MORE:BS_BLOCK_DONE}function deflate_rle(e,t){for(var i,r,o,s,n=e.window;;){if(e.lookahead<=MAX_MATCH){if(fill_window(e),e.lookahead<=MAX_MATCH&&t===Z_NO_FLUSH$1)return BS_NEED_MORE;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=MIN_MATCH&&e.strstart>0&&(r=n[o=e.strstart-1])===n[++o]&&r===n[++o]&&r===n[++o]){s=e.strstart+MAX_MATCH;do{}while(r===n[++o]&&r===n[++o]&&r===n[++o]&&r===n[++o]&&r===n[++o]&&r===n[++o]&&r===n[++o]&&r===n[++o]&&o<s);e.match_length=MAX_MATCH-(s-o),e.match_length>e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=MIN_MATCH?(i=trees._tr_tally(e,1,e.match_length-MIN_MATCH),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(i=trees._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),i&&(flush_block_only(e,!1),0===e.strm.avail_out))return BS_NEED_MORE}return e.insert=0,t===Z_FINISH$2?(flush_block_only(e,!0),0===e.strm.avail_out?BS_FINISH_STARTED:BS_FINISH_DONE):e.last_lit&&(flush_block_only(e,!1),0===e.strm.avail_out)?BS_NEED_MORE:BS_BLOCK_DONE}function deflate_huff(e,t){for(var i;;){if(0===e.lookahead&&(fill_window(e),0===e.lookahead)){if(t===Z_NO_FLUSH$1)return BS_NEED_MORE;break}if(e.match_length=0,i=trees._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,i&&(flush_block_only(e,!1),0===e.strm.avail_out))return BS_NEED_MORE}return e.insert=0,t===Z_FINISH$2?(flush_block_only(e,!0),0===e.strm.avail_out?BS_FINISH_STARTED:BS_FINISH_DONE):e.last_lit&&(flush_block_only(e,!1),0===e.strm.avail_out)?BS_NEED_MORE:BS_BLOCK_DONE}function Config$1(e,t,i,r,o){this.good_length=e,this.max_lazy=t,this.nice_length=i,this.max_chain=r,this.func=o}function lm_init(e){e.window_size=2*e.w_size,zero(e.head),e.max_lazy_match=configuration_table[e.level].max_lazy,e.good_match=configuration_table[e.level].good_length,e.nice_match=configuration_table[e.level].nice_length,e.max_chain_length=configuration_table[e.level].max_chain,e.strstart=0,e.block_start=0,e.lookahead=0,e.insert=0,e.match_length=e.prev_length=MIN_MATCH-1,e.match_available=0,e.ins_h=0}function DeflateState(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Z_DEFLATED$2,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new utils$5.Buf16(2*HEAP_SIZE),this.dyn_dtree=new utils$5.Buf16(2*(2*D_CODES+1)),this.bl_tree=new utils$5.Buf16(2*(2*BL_CODES+1)),zero(this.dyn_ltree),zero(this.dyn_dtree),zero(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new utils$5.Buf16(MAX_BITS+1),this.heap=new utils$5.Buf16(2*L_CODES+1),zero(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new utils$5.Buf16(2*L_CODES+1),zero(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function deflateResetKeep(e){var t;return e&&e.state?(e.total_in=e.total_out=0,e.data_type=Z_UNKNOWN,(t=e.state).pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap?INIT_STATE:BUSY_STATE,e.adler=2===t.wrap?0:1,t.last_flush=Z_NO_FLUSH$1,trees._tr_init(t),Z_OK$2):err(e,Z_STREAM_ERROR$1)}function deflateReset(e){var t=deflateResetKeep(e);return t===Z_OK$2&&lm_init(e.state),t}function deflateSetHeader(e,t){return e&&e.state?2!==e.state.wrap?Z_STREAM_ERROR$1:(e.state.gzhead=t,Z_OK$2):Z_STREAM_ERROR$1}function deflateInit2(e,t,i,r,o,s){if(!e)return Z_STREAM_ERROR$1;var n=1;if(t===Z_DEFAULT_COMPRESSION$1&&(t=6),r<0?(n=0,r=-r):r>15&&(n=2,r-=16),o<1||o>MAX_MEM_LEVEL||i!==Z_DEFLATED$2||r<8||r>15||t<0||t>9||s<0||s>Z_FIXED)return err(e,Z_STREAM_ERROR$1);8===r&&(r=9);var a=new DeflateState;return e.state=a,a.strm=e,a.wrap=n,a.gzhead=null,a.w_bits=r,a.w_size=1<<a.w_bits,a.w_mask=a.w_size-1,a.hash_bits=o+7,a.hash_size=1<<a.hash_bits,a.hash_mask=a.hash_size-1,a.hash_shift=~~((a.hash_bits+MIN_MATCH-1)/MIN_MATCH),a.window=new utils$5.Buf8(2*a.w_size),a.head=new utils$5.Buf16(a.hash_size),a.prev=new utils$5.Buf16(a.w_size),a.lit_bufsize=1<<o+6,a.pending_buf_size=4*a.lit_bufsize,a.pending_buf=new utils$5.Buf8(a.pending_buf_size),a.d_buf=1*a.lit_bufsize,a.l_buf=3*a.lit_bufsize,a.level=t,a.strategy=s,a.method=i,deflateReset(e)}function deflateInit(e,t){return deflateInit2(e,t,Z_DEFLATED$2,MAX_WBITS$1,DEF_MEM_LEVEL,Z_DEFAULT_STRATEGY$1)}function deflate$2(e,t){var i,r,o,s;if(!e||!e.state||t>Z_BLOCK$1||t<0)return e?err(e,Z_STREAM_ERROR$1):Z_STREAM_ERROR$1;if(r=e.state,!e.output||!e.input&&0!==e.avail_in||r.status===FINISH_STATE&&t!==Z_FINISH$2)return err(e,0===e.avail_out?Z_BUF_ERROR$1:Z_STREAM_ERROR$1);if(r.strm=e,i=r.last_flush,r.last_flush=t,r.status===INIT_STATE)if(2===r.wrap)e.adler=0,put_byte(r,31),put_byte(r,139),put_byte(r,8),r.gzhead?(put_byte(r,(r.gzhead.text?1:0)+(r.gzhead.hcrc?2:0)+(r.gzhead.extra?4:0)+(r.gzhead.name?8:0)+(r.gzhead.comment?16:0)),put_byte(r,255&r.gzhead.time),put_byte(r,r.gzhead.time>>8&255),put_byte(r,r.gzhead.time>>16&255),put_byte(r,r.gzhead.time>>24&255),put_byte(r,9===r.level?2:r.strategy>=Z_HUFFMAN_ONLY||r.level<2?4:0),put_byte(r,255&r.gzhead.os),r.gzhead.extra&&r.gzhead.extra.length&&(put_byte(r,255&r.gzhead.extra.length),put_byte(r,r.gzhead.extra.length>>8&255)),r.gzhead.hcrc&&(e.adler=crc32$1(e.adler,r.pending_buf,r.pending,0)),r.gzindex=0,r.status=EXTRA_STATE):(put_byte(r,0),put_byte(r,0),put_byte(r,0),put_byte(r,0),put_byte(r,0),put_byte(r,9===r.level?2:r.strategy>=Z_HUFFMAN_ONLY||r.level<2?4:0),put_byte(r,OS_CODE),r.status=BUSY_STATE);else{var n=Z_DEFLATED$2+(r.w_bits-8<<4)<<8;n|=(r.strategy>=Z_HUFFMAN_ONLY||r.level<2?0:r.level<6?1:6===r.level?2:3)<<6,0!==r.strstart&&(n|=PRESET_DICT),n+=31-n%31,r.status=BUSY_STATE,putShortMSB(r,n),0!==r.strstart&&(putShortMSB(r,e.adler>>>16),putShortMSB(r,65535&e.adler)),e.adler=1}if(r.status===EXTRA_STATE)if(r.gzhead.extra){for(o=r.pending;r.gzindex<(65535&r.gzhead.extra.length)&&(r.pending!==r.pending_buf_size||(r.gzhead.hcrc&&r.pending>o&&(e.adler=crc32$1(e.adler,r.pending_buf,r.pending-o,o)),flush_pending(e),o=r.pending,r.pending!==r.pending_buf_size));)put_byte(r,255&r.gzhead.extra[r.gzindex]),r.gzindex++;r.gzhead.hcrc&&r.pending>o&&(e.adler=crc32$1(e.adler,r.pending_buf,r.pending-o,o)),r.gzindex===r.gzhead.extra.length&&(r.gzindex=0,r.status=NAME_STATE)}else r.status=NAME_STATE;if(r.status===NAME_STATE)if(r.gzhead.name){o=r.pending;do{if(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>o&&(e.adler=crc32$1(e.adler,r.pending_buf,r.pending-o,o)),flush_pending(e),o=r.pending,r.pending===r.pending_buf_size)){s=1;break}s=r.gzindex<r.gzhead.name.length?255&r.gzhead.name.charCodeAt(r.gzindex++):0,put_byte(r,s)}while(0!==s);r.gzhead.hcrc&&r.pending>o&&(e.adler=crc32$1(e.adler,r.pending_buf,r.pending-o,o)),0===s&&(r.gzindex=0,r.status=COMMENT_STATE)}else r.status=COMMENT_STATE;if(r.status===COMMENT_STATE)if(r.gzhead.comment){o=r.pending;do{if(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>o&&(e.adler=crc32$1(e.adler,r.pending_buf,r.pending-o,o)),flush_pending(e),o=r.pending,r.pending===r.pending_buf_size)){s=1;break}s=r.gzindex<r.gzhead.comment.length?255&r.gzhead.comment.charCodeAt(r.gzindex++):0,put_byte(r,s)}while(0!==s);r.gzhead.hcrc&&r.pending>o&&(e.adler=crc32$1(e.adler,r.pending_buf,r.pending-o,o)),0===s&&(r.status=HCRC_STATE)}else r.status=HCRC_STATE;if(r.status===HCRC_STATE&&(r.gzhead.hcrc?(r.pending+2>r.pending_buf_size&&flush_pending(e),r.pending+2<=r.pending_buf_size&&(put_byte(r,255&e.adler),put_byte(r,e.adler>>8&255),e.adler=0,r.status=BUSY_STATE)):r.status=BUSY_STATE),0!==r.pending){if(flush_pending(e),0===e.avail_out)return r.last_flush=-1,Z_OK$2}else if(0===e.avail_in&&rank(t)<=rank(i)&&t!==Z_FINISH$2)return err(e,Z_BUF_ERROR$1);if(r.status===FINISH_STATE&&0!==e.avail_in)return err(e,Z_BUF_ERROR$1);if(0!==e.avail_in||0!==r.lookahead||t!==Z_NO_FLUSH$1&&r.status!==FINISH_STATE){var a=r.strategy===Z_HUFFMAN_ONLY?deflate_huff(r,t):r.strategy===Z_RLE?deflate_rle(r,t):configuration_table[r.level].func(r,t);if(a!==BS_FINISH_STARTED&&a!==BS_FINISH_DONE||(r.status=FINISH_STATE),a===BS_NEED_MORE||a===BS_FINISH_STARTED)return 0===e.avail_out&&(r.last_flush=-1),Z_OK$2;if(a===BS_BLOCK_DONE&&(t===Z_PARTIAL_FLUSH?trees._tr_align(r):t!==Z_BLOCK$1&&(trees._tr_stored_block(r,0,0,!1),t===Z_FULL_FLUSH&&(zero(r.head),0===r.lookahead&&(r.strstart=0,r.block_start=0,r.insert=0))),flush_pending(e),0===e.avail_out))return r.last_flush=-1,Z_OK$2}return t!==Z_FINISH$2?Z_OK$2:r.wrap<=0?Z_STREAM_END$2:(2===r.wrap?(put_byte(r,255&e.adler),put_byte(r,e.adler>>8&255),put_byte(r,e.adler>>16&255),put_byte(r,e.adler>>24&255),put_byte(r,255&e.total_in),put_byte(r,e.total_in>>8&255),put_byte(r,e.total_in>>16&255),put_byte(r,e.total_in>>24&255)):(putShortMSB(r,e.adler>>>16),putShortMSB(r,65535&e.adler)),flush_pending(e),r.wrap>0&&(r.wrap=-r.wrap),0!==r.pending?Z_OK$2:Z_STREAM_END$2)}function deflateEnd(e){var t;return e&&e.state?(t=e.state.status)!==INIT_STATE&&t!==EXTRA_STATE&&t!==NAME_STATE&&t!==COMMENT_STATE&&t!==HCRC_STATE&&t!==BUSY_STATE&&t!==FINISH_STATE?err(e,Z_STREAM_ERROR$1):(e.state=null,t===BUSY_STATE?err(e,Z_DATA_ERROR$1):Z_OK$2):Z_STREAM_ERROR$1}function deflateSetDictionary(e,t){var i,r,o,s,n,a,d,c,l=t.length;if(!e||!e.state)return Z_STREAM_ERROR$1;if(2===(s=(i=e.state).wrap)||1===s&&i.status!==INIT_STATE||i.lookahead)return Z_STREAM_ERROR$1;for(1===s&&(e.adler=adler32$1(e.adler,t,l,0)),i.wrap=0,l>=i.w_size&&(0===s&&(zero(i.head),i.strstart=0,i.block_start=0,i.insert=0),c=new utils$5.Buf8(i.w_size),utils$5.arraySet(c,t,l-i.w_size,i.w_size,0),t=c,l=i.w_size),n=e.avail_in,a=e.next_in,d=e.input,e.avail_in=l,e.next_in=0,e.input=t,fill_window(i);i.lookahead>=MIN_MATCH;){r=i.strstart,o=i.lookahead-(MIN_MATCH-1);do{i.ins_h=(i.ins_h<<i.hash_shift^i.window[r+MIN_MATCH-1])&i.hash_mask,i.prev[r&i.w_mask]=i.head[i.ins_h],i.head[i.ins_h]=r,r++}while(--o);i.strstart=r,i.lookahead=MIN_MATCH-1,fill_window(i)}return i.strstart+=i.lookahead,i.block_start=i.strstart,i.insert=i.lookahead,i.lookahead=0,i.match_length=i.prev_length=MIN_MATCH-1,i.match_available=0,e.next_in=a,e.input=d,e.avail_in=n,i.wrap=s,Z_OK$2}configuration_table=[new Config$1(0,0,0,0,deflate_stored),new Config$1(4,4,8,4,deflate_fast),new Config$1(4,5,16,8,deflate_fast),new Config$1(4,6,32,32,deflate_fast),new Config$1(4,4,16,16,deflate_slow),new Config$1(8,16,32,32,deflate_slow),new Config$1(8,16,128,128,deflate_slow),new Config$1(8,32,128,256,deflate_slow),new Config$1(32,128,258,1024,deflate_slow),new Config$1(32,258,258,4096,deflate_slow)],deflate$3.deflateInit=deflateInit,deflate$3.deflateInit2=deflateInit2,deflate$3.deflateReset=deflateReset,deflate$3.deflateResetKeep=deflateResetKeep,deflate$3.deflateSetHeader=deflateSetHeader,deflate$3.deflate=deflate$2,deflate$3.deflateEnd=deflateEnd,deflate$3.deflateSetDictionary=deflateSetDictionary,deflate$3.deflateInfo="pako deflate (from Nodeca project)";var strings$2={},utils$4=common,STR_APPLY_OK=!0,STR_APPLY_UIA_OK=!0;try{String.fromCharCode.apply(null,[0])}catch(e){STR_APPLY_OK=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){STR_APPLY_UIA_OK=!1}for(var _utf8len=new utils$4.Buf8(256),q=0;q<256;q++)_utf8len[q]=q>=252?6:q>=248?5:q>=240?4:q>=224?3:q>=192?2:1;function buf2binstring(e,t){if(t<65534&&(e.subarray&&STR_APPLY_UIA_OK||!e.subarray&&STR_APPLY_OK))return String.fromCharCode.apply(null,utils$4.shrinkBuf(e,t));for(var i="",r=0;r<t;r++)i+=String.fromCharCode(e[r]);return i}function ZStream$2(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}_utf8len[254]=_utf8len[254]=1,strings$2.string2buf=function(e){var t,i,r,o,s,n=e.length,a=0;for(o=0;o<n;o++)55296==(64512&(i=e.charCodeAt(o)))&&o+1<n&&56320==(64512&(r=e.charCodeAt(o+1)))&&(i=65536+(i-55296<<10)+(r-56320),o++),a+=i<128?1:i<2048?2:i<65536?3:4;for(t=new utils$4.Buf8(a),s=0,o=0;s<a;o++)55296==(64512&(i=e.charCodeAt(o)))&&o+1<n&&56320==(64512&(r=e.charCodeAt(o+1)))&&(i=65536+(i-55296<<10)+(r-56320),o++),i<128?t[s++]=i:i<2048?(t[s++]=192|i>>>6,t[s++]=128|63&i):i<65536?(t[s++]=224|i>>>12,t[s++]=128|i>>>6&63,t[s++]=128|63&i):(t[s++]=240|i>>>18,t[s++]=128|i>>>12&63,t[s++]=128|i>>>6&63,t[s++]=128|63&i);return t},strings$2.buf2binstring=function(e){return buf2binstring(e,e.length)},strings$2.binstring2buf=function(e){for(var t=new utils$4.Buf8(e.length),i=0,r=t.length;i<r;i++)t[i]=e.charCodeAt(i);return t},strings$2.buf2string=function(e,t){var i,r,o,s,n=t||e.length,a=new Array(2*n);for(r=0,i=0;i<n;)if((o=e[i++])<128)a[r++]=o;else if((s=_utf8len[o])>4)a[r++]=65533,i+=s-1;else{for(o&=2===s?31:3===s?15:7;s>1&&i<n;)o=o<<6|63&e[i++],s--;s>1?a[r++]=65533:o<65536?a[r++]=o:(o-=65536,a[r++]=55296|o>>10&1023,a[r++]=56320|1023&o)}return buf2binstring(a,r)},strings$2.utf8border=function(e,t){var i;for((t=t||e.length)>e.length&&(t=e.length),i=t-1;i>=0&&128==(192&e[i]);)i--;return i<0||0===i?t:i+_utf8len[e[i]]>t?i:t};var zstream=ZStream$2,zlib_deflate=deflate$3,utils$3=common,strings$1=strings$2,msg$1=messages,ZStream$1=zstream,toString$1=Object.prototype.toString,Z_NO_FLUSH=0,Z_FINISH$1=4,Z_OK$1=0,Z_STREAM_END$1=1,Z_SYNC_FLUSH=2,Z_DEFAULT_COMPRESSION=-1,Z_DEFAULT_STRATEGY=0,Z_DEFLATED$1=8;function Deflate(e){if(!(this instanceof Deflate))return new Deflate(e);this.options=utils$3.assign({level:Z_DEFAULT_COMPRESSION,method:Z_DEFLATED$1,chunkSize:16384,windowBits:15,memLevel:8,strategy:Z_DEFAULT_STRATEGY,to:""},e||{});var t=this.options;t.raw&&t.windowBits>0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new ZStream$1,this.strm.avail_out=0;var i=zlib_deflate.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(i!==Z_OK$1)throw new Error(msg$1[i]);if(t.header&&zlib_deflate.deflateSetHeader(this.strm,t.header),t.dictionary){var r;if(r="string"==typeof t.dictionary?strings$1.string2buf(t.dictionary):"[object ArrayBuffer]"===toString$1.call(t.dictionary)?new Uint8Array(t.dictionary):t.dictionary,(i=zlib_deflate.deflateSetDictionary(this.strm,r))!==Z_OK$1)throw new Error(msg$1[i]);this._dict_set=!0}}function deflate$1(e,t){var i=new Deflate(t);if(i.push(e,!0),i.err)throw i.msg||msg$1[i.err];return i.result}function deflateRaw(e,t){return(t=t||{}).raw=!0,deflate$1(e,t)}function gzip(e,t){return(t=t||{}).gzip=!0,deflate$1(e,t)}Deflate.prototype.push=function(e,t){var i,r,o=this.strm,s=this.options.chunkSize;if(this.ended)return!1;r=t===~~t?t:!0===t?Z_FINISH$1:Z_NO_FLUSH,"string"==typeof e?o.input=strings$1.string2buf(e):"[object ArrayBuffer]"===toString$1.call(e)?o.input=new Uint8Array(e):o.input=e,o.next_in=0,o.avail_in=o.input.length;do{if(0===o.avail_out&&(o.output=new utils$3.Buf8(s),o.next_out=0,o.avail_out=s),(i=zlib_deflate.deflate(o,r))!==Z_STREAM_END$1&&i!==Z_OK$1)return this.onEnd(i),this.ended=!0,!1;0!==o.avail_out&&(0!==o.avail_in||r!==Z_FINISH$1&&r!==Z_SYNC_FLUSH)||("string"===this.options.to?this.onData(strings$1.buf2binstring(utils$3.shrinkBuf(o.output,o.next_out))):this.onData(utils$3.shrinkBuf(o.output,o.next_out)))}while((o.avail_in>0||0===o.avail_out)&&i!==Z_STREAM_END$1);return r===Z_FINISH$1?(i=zlib_deflate.deflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===Z_OK$1):r!==Z_SYNC_FLUSH||(this.onEnd(Z_OK$1),o.avail_out=0,!0)},Deflate.prototype.onData=function(e){this.chunks.push(e)},Deflate.prototype.onEnd=function(e){e===Z_OK$1&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=utils$3.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},deflate$4.Deflate=Deflate,deflate$4.deflate=deflate$1,deflate$4.deflateRaw=deflateRaw,deflate$4.gzip=gzip;var inflate$4={},inflate$3={},BAD$1=30,TYPE$1=12,inffast=function(e,t){var i,r,o,s,n,a,d,c,l,u,_,h,p,m,S,g,v,f,E,T,R,b,y,I,C;i=e.state,r=e.next_in,I=e.input,o=r+(e.avail_in-5),s=e.next_out,C=e.output,n=s-(t-e.avail_out),a=s+(e.avail_out-257),d=i.dmax,c=i.wsize,l=i.whave,u=i.wnext,_=i.window,h=i.hold,p=i.bits,m=i.lencode,S=i.distcode,g=(1<<i.lenbits)-1,v=(1<<i.distbits)-1;e:do{p<15&&(h+=I[r++]<<p,p+=8,h+=I[r++]<<p,p+=8),f=m[h&g];t:for(;;){if(h>>>=E=f>>>24,p-=E,0===(E=f>>>16&255))C[s++]=65535&f;else{if(!(16&E)){if(64&E){if(32&E){i.mode=TYPE$1;break e}e.msg="invalid literal/length code",i.mode=BAD$1;break e}f=m[(65535&f)+(h&(1<<E)-1)];continue t}for(T=65535&f,(E&=15)&&(p<E&&(h+=I[r++]<<p,p+=8),T+=h&(1<<E)-1,h>>>=E,p-=E),p<15&&(h+=I[r++]<<p,p+=8,h+=I[r++]<<p,p+=8),f=S[h&v];;){if(h>>>=E=f>>>24,p-=E,16&(E=f>>>16&255)){if(R=65535&f,p<(E&=15)&&(h+=I[r++]<<p,(p+=8)<E&&(h+=I[r++]<<p,p+=8)),(R+=h&(1<<E)-1)>d){e.msg="invalid distance too far back",i.mode=BAD$1;break e}if(h>>>=E,p-=E,R>(E=s-n)){if((E=R-E)>l&&i.sane){e.msg="invalid distance too far back",i.mode=BAD$1;break e}if(b=0,y=_,0===u){if(b+=c-E,E<T){T-=E;do{C[s++]=_[b++]}while(--E);b=s-R,y=C}}else if(u<E){if(b+=c+u-E,(E-=u)<T){T-=E;do{C[s++]=_[b++]}while(--E);if(b=0,u<T){T-=E=u;do{C[s++]=_[b++]}while(--E);b=s-R,y=C}}}else if(b+=u-E,E<T){T-=E;do{C[s++]=_[b++]}while(--E);b=s-R,y=C}for(;T>2;)C[s++]=y[b++],C[s++]=y[b++],C[s++]=y[b++],T-=3;T&&(C[s++]=y[b++],T>1&&(C[s++]=y[b++]))}else{b=s-R;do{C[s++]=C[b++],C[s++]=C[b++],C[s++]=C[b++],T-=3}while(T>2);T&&(C[s++]=C[b++],T>1&&(C[s++]=C[b++]))}break}if(64&E){e.msg="invalid distance code",i.mode=BAD$1;break e}f=S[(65535&f)+(h&(1<<E)-1)]}}break}}while(r<o&&s<a);r-=T=p>>3,h&=(1<<(p-=T<<3))-1,e.next_in=r,e.next_out=s,e.avail_in=r<o?o-r+5:5-(r-o),e.avail_out=s<a?a-s+257:257-(s-a),i.hold=h,i.bits=p},utils$2=common,MAXBITS=15,ENOUGH_LENS$1=852,ENOUGH_DISTS$1=592,CODES$1=0,LENS$1=1,DISTS$1=2,lbase=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],lext=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],dbase=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],dext=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64],inftrees=function(e,t,i,r,o,s,n,a){var d,c,l,u,_,h,p,m,S,g=a.bits,v=0,f=0,E=0,T=0,R=0,b=0,y=0,I=0,C=0,A=0,k=null,M=0,N=new utils$2.Buf16(MAXBITS+1),O=new utils$2.Buf16(MAXBITS+1),P=null,D=0;for(v=0;v<=MAXBITS;v++)N[v]=0;for(f=0;f<r;f++)N[t[i+f]]++;for(R=g,T=MAXBITS;T>=1&&0===N[T];T--);if(R>T&&(R=T),0===T)return o[s++]=20971520,o[s++]=20971520,a.bits=1,0;for(E=1;E<T&&0===N[E];E++);for(R<E&&(R=E),I=1,v=1;v<=MAXBITS;v++)if(I<<=1,(I-=N[v])<0)return-1;if(I>0&&(e===CODES$1||1!==T))return-1;for(O[1]=0,v=1;v<MAXBITS;v++)O[v+1]=O[v]+N[v];for(f=0;f<r;f++)0!==t[i+f]&&(n[O[t[i+f]]++]=f);if(e===CODES$1?(k=P=n,h=19):e===LENS$1?(k=lbase,M-=257,P=lext,D-=257,h=256):(k=dbase,P=dext,h=-1),A=0,f=0,v=E,_=s,b=R,y=0,l=-1,u=(C=1<<R)-1,e===LENS$1&&C>ENOUGH_LENS$1||e===DISTS$1&&C>ENOUGH_DISTS$1)return 1;for(;;){p=v-y,n[f]<h?(m=0,S=n[f]):n[f]>h?(m=P[D+n[f]],S=k[M+n[f]]):(m=96,S=0),d=1<<v-y,E=c=1<<b;do{o[_+(A>>y)+(c-=d)]=p<<24|m<<16|S}while(0!==c);for(d=1<<v-1;A&d;)d>>=1;if(0!==d?(A&=d-1,A+=d):A=0,f++,0==--N[v]){if(v===T)break;v=t[i+n[f]]}if(v>R&&(A&u)!==l){for(0===y&&(y=R),_+=E,I=1<<(b=v-y);b+y<T&&!((I-=N[b+y])<=0);)b++,I<<=1;if(C+=1<<b,e===LENS$1&&C>ENOUGH_LENS$1||e===DISTS$1&&C>ENOUGH_DISTS$1)return 1;o[l=A&u]=R<<24|b<<16|_-s}}return 0!==A&&(o[_+A]=v-y<<24|64<<16),a.bits=R,0},utils$1=common,adler32=adler32_1,crc32=crc32_1,inflate_fast2=inffast,inflate_table2=inftrees,CODES=0,LENS=1,DISTS=2,Z_FINISH=4,Z_BLOCK=5,Z_TREES=6,Z_OK=0,Z_STREAM_END=1,Z_NEED_DICT=2,Z_STREAM_ERROR=-2,Z_DATA_ERROR=-3,Z_MEM_ERROR=-4,Z_BUF_ERROR=-5,Z_DEFLATED=8,HEAD=1,FLAGS=2,TIME=3,OS=4,EXLEN=5,EXTRA=6,NAME=7,COMMENT=8,HCRC=9,DICTID=10,DICT=11,TYPE=12,TYPEDO=13,STORED=14,COPY_=15,COPY=16,TABLE=17,LENLENS=18,CODELENS=19,LEN_=20,LEN=21,LENEXT=22,DIST=23,DISTEXT=24,MATCH=25,LIT=26,CHECK=27,LENGTH=28,DONE=29,BAD=30,MEM=31,SYNC=32,ENOUGH_LENS=852,ENOUGH_DISTS=592,MAX_WBITS=15,DEF_WBITS=MAX_WBITS;function zswap32(e){return(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}function InflateState(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new utils$1.Buf16(320),this.work=new utils$1.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function inflateResetKeep(e){var t;return e&&e.state?(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=HEAD,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new utils$1.Buf32(ENOUGH_LENS),t.distcode=t.distdyn=new utils$1.Buf32(ENOUGH_DISTS),t.sane=1,t.back=-1,Z_OK):Z_STREAM_ERROR}function inflateReset(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,inflateResetKeep(e)):Z_STREAM_ERROR}function inflateReset2(e,t){var i,r;return e&&e.state?(r=e.state,t<0?(i=0,t=-t):(i=1+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?Z_STREAM_ERROR:(null!==r.window&&r.wbits!==t&&(r.window=null),r.wrap=i,r.wbits=t,inflateReset(e))):Z_STREAM_ERROR}function inflateInit2(e,t){var i,r;return e?(r=new InflateState,e.state=r,r.window=null,(i=inflateReset2(e,t))!==Z_OK&&(e.state=null),i):Z_STREAM_ERROR}function inflateInit(e){return inflateInit2(e,DEF_WBITS)}var lenfix,distfix,virgin=!0;function fixedtables(e){if(virgin){var t;for(lenfix=new utils$1.Buf32(512),distfix=new utils$1.Buf32(32),t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(inflate_table2(LENS,e.lens,0,288,lenfix,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;inflate_table2(DISTS,e.lens,0,32,distfix,0,e.work,{bits:5}),virgin=!1}e.lencode=lenfix,e.lenbits=9,e.distcode=distfix,e.distbits=5}function updatewindow(e,t,i,r){var o,s=e.state;return null===s.window&&(s.wsize=1<<s.wbits,s.wnext=0,s.whave=0,s.window=new utils$1.Buf8(s.wsize)),r>=s.wsize?(utils$1.arraySet(s.window,t,i-s.wsize,s.wsize,0),s.wnext=0,s.whave=s.wsize):((o=s.wsize-s.wnext)>r&&(o=r),utils$1.arraySet(s.window,t,i-r,o,s.wnext),(r-=o)?(utils$1.arraySet(s.window,t,i-r,r,0),s.wnext=r,s.whave=s.wsize):(s.wnext+=o,s.wnext===s.wsize&&(s.wnext=0),s.whave<s.wsize&&(s.whave+=o))),0}function inflate$2(e,t){var i,r,o,s,n,a,d,c,l,u,_,h,p,m,S,g,v,f,E,T,R,b,y,I,C=0,A=new utils$1.Buf8(4),k=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!e||!e.state||!e.output||!e.input&&0!==e.avail_in)return Z_STREAM_ERROR;(i=e.state).mode===TYPE&&(i.mode=TYPEDO),n=e.next_out,o=e.output,d=e.avail_out,s=e.next_in,r=e.input,a=e.avail_in,c=i.hold,l=i.bits,u=a,_=d,b=Z_OK;e:for(;;)switch(i.mode){case HEAD:if(0===i.wrap){i.mode=TYPEDO;break}for(;l<16;){if(0===a)break e;a--,c+=r[s++]<<l,l+=8}if(2&i.wrap&&35615===c){i.check=0,A[0]=255&c,A[1]=c>>>8&255,i.check=crc32(i.check,A,2,0),c=0,l=0,i.mode=FLAGS;break}if(i.flags=0,i.head&&(i.head.done=!1),!(1&i.wrap)||(((255&c)<<8)+(c>>8))%31){e.msg="incorrect header check",i.mode=BAD;break}if((15&c)!==Z_DEFLATED){e.msg="unknown compression method",i.mode=BAD;break}if(l-=4,R=8+(15&(c>>>=4)),0===i.wbits)i.wbits=R;else if(R>i.wbits){e.msg="invalid window size",i.mode=BAD;break}i.dmax=1<<R,e.adler=i.check=1,i.mode=512&c?DICTID:TYPE,c=0,l=0;break;case FLAGS:for(;l<16;){if(0===a)break e;a--,c+=r[s++]<<l,l+=8}if(i.flags=c,(255&i.flags)!==Z_DEFLATED){e.msg="unknown compression method",i.mode=BAD;break}if(57344&i.flags){e.msg="unknown header flags set",i.mode=BAD;break}i.head&&(i.head.text=c>>8&1),512&i.flags&&(A[0]=255&c,A[1]=c>>>8&255,i.check=crc32(i.check,A,2,0)),c=0,l=0,i.mode=TIME;case TIME:for(;l<32;){if(0===a)break e;a--,c+=r[s++]<<l,l+=8}i.head&&(i.head.time=c),512&i.flags&&(A[0]=255&c,A[1]=c>>>8&255,A[2]=c>>>16&255,A[3]=c>>>24&255,i.check=crc32(i.check,A,4,0)),c=0,l=0,i.mode=OS;case OS:for(;l<16;){if(0===a)break e;a--,c+=r[s++]<<l,l+=8}i.head&&(i.head.xflags=255&c,i.head.os=c>>8),512&i.flags&&(A[0]=255&c,A[1]=c>>>8&255,i.check=crc32(i.check,A,2,0)),c=0,l=0,i.mode=EXLEN;case EXLEN:if(1024&i.flags){for(;l<16;){if(0===a)break e;a--,c+=r[s++]<<l,l+=8}i.length=c,i.head&&(i.head.extra_len=c),512&i.flags&&(A[0]=255&c,A[1]=c>>>8&255,i.check=crc32(i.check,A,2,0)),c=0,l=0}else i.head&&(i.head.extra=null);i.mode=EXTRA;case EXTRA:if(1024&i.flags&&((h=i.length)>a&&(h=a),h&&(i.head&&(R=i.head.extra_len-i.length,i.head.extra||(i.head.extra=new Array(i.head.extra_len)),utils$1.arraySet(i.head.extra,r,s,h,R)),512&i.flags&&(i.check=crc32(i.check,r,h,s)),a-=h,s+=h,i.length-=h),i.length))break e;i.length=0,i.mode=NAME;case NAME:if(2048&i.flags){if(0===a)break e;h=0;do{R=r[s+h++],i.head&&R&&i.length<65536&&(i.head.name+=String.fromCharCode(R))}while(R&&h<a);if(512&i.flags&&(i.check=crc32(i.check,r,h,s)),a-=h,s+=h,R)break e}else i.head&&(i.head.name=null);i.length=0,i.mode=COMMENT;case COMMENT:if(4096&i.flags){if(0===a)break e;h=0;do{R=r[s+h++],i.head&&R&&i.length<65536&&(i.head.comment+=String.fromCharCode(R))}while(R&&h<a);if(512&i.flags&&(i.check=crc32(i.check,r,h,s)),a-=h,s+=h,R)break e}else i.head&&(i.head.comment=null);i.mode=HCRC;case HCRC:if(512&i.flags){for(;l<16;){if(0===a)break e;a--,c+=r[s++]<<l,l+=8}if(c!==(65535&i.check)){e.msg="header crc mismatch",i.mode=BAD;break}c=0,l=0}i.head&&(i.head.hcrc=i.flags>>9&1,i.head.done=!0),e.adler=i.check=0,i.mode=TYPE;break;case DICTID:for(;l<32;){if(0===a)break e;a--,c+=r[s++]<<l,l+=8}e.adler=i.check=zswap32(c),c=0,l=0,i.mode=DICT;case DICT:if(0===i.havedict)return e.next_out=n,e.avail_out=d,e.next_in=s,e.avail_in=a,i.hold=c,i.bits=l,Z_NEED_DICT;e.adler=i.check=1,i.mode=TYPE;case TYPE:if(t===Z_BLOCK||t===Z_TREES)break e;case TYPEDO:if(i.last){c>>>=7&l,l-=7&l,i.mode=CHECK;break}for(;l<3;){if(0===a)break e;a--,c+=r[s++]<<l,l+=8}switch(i.last=1&c,l-=1,3&(c>>>=1)){case 0:i.mode=STORED;break;case 1:if(fixedtables(i),i.mode=LEN_,t===Z_TREES){c>>>=2,l-=2;break e}break;case 2:i.mode=TABLE;break;case 3:e.msg="invalid block type",i.mode=BAD}c>>>=2,l-=2;break;case STORED:for(c>>>=7&l,l-=7&l;l<32;){if(0===a)break e;a--,c+=r[s++]<<l,l+=8}if((65535&c)!=(c>>>16^65535)){e.msg="invalid stored block lengths",i.mode=BAD;break}if(i.length=65535&c,c=0,l=0,i.mode=COPY_,t===Z_TREES)break e;case COPY_:i.mode=COPY;case COPY:if(h=i.length){if(h>a&&(h=a),h>d&&(h=d),0===h)break e;utils$1.arraySet(o,r,s,h,n),a-=h,s+=h,d-=h,n+=h,i.length-=h;break}i.mode=TYPE;break;case TABLE:for(;l<14;){if(0===a)break e;a--,c+=r[s++]<<l,l+=8}if(i.nlen=257+(31&c),c>>>=5,l-=5,i.ndist=1+(31&c),c>>>=5,l-=5,i.ncode=4+(15&c),c>>>=4,l-=4,i.nlen>286||i.ndist>30){e.msg="too many length or distance symbols",i.mode=BAD;break}i.have=0,i.mode=LENLENS;case LENLENS:for(;i.have<i.ncode;){for(;l<3;){if(0===a)break e;a--,c+=r[s++]<<l,l+=8}i.lens[k[i.have++]]=7&c,c>>>=3,l-=3}for(;i.have<19;)i.lens[k[i.have++]]=0;if(i.lencode=i.lendyn,i.lenbits=7,y={bits:i.lenbits},b=inflate_table2(CODES,i.lens,0,19,i.lencode,0,i.work,y),i.lenbits=y.bits,b){e.msg="invalid code lengths set",i.mode=BAD;break}i.have=0,i.mode=CODELENS;case CODELENS:for(;i.have<i.nlen+i.ndist;){for(;g=(C=i.lencode[c&(1<<i.lenbits)-1])>>>16&255,v=65535&C,!((S=C>>>24)<=l);){if(0===a)break e;a--,c+=r[s++]<<l,l+=8}if(v<16)c>>>=S,l-=S,i.lens[i.have++]=v;else{if(16===v){for(I=S+2;l<I;){if(0===a)break e;a--,c+=r[s++]<<l,l+=8}if(c>>>=S,l-=S,0===i.have){e.msg="invalid bit length repeat",i.mode=BAD;break}R=i.lens[i.have-1],h=3+(3&c),c>>>=2,l-=2}else if(17===v){for(I=S+3;l<I;){if(0===a)break e;a--,c+=r[s++]<<l,l+=8}l-=S,R=0,h=3+(7&(c>>>=S)),c>>>=3,l-=3}else{for(I=S+7;l<I;){if(0===a)break e;a--,c+=r[s++]<<l,l+=8}l-=S,R=0,h=11+(127&(c>>>=S)),c>>>=7,l-=7}if(i.have+h>i.nlen+i.ndist){e.msg="invalid bit length repeat",i.mode=BAD;break}for(;h--;)i.lens[i.have++]=R}}if(i.mode===BAD)break;if(0===i.lens[256]){e.msg="invalid code -- missing end-of-block",i.mode=BAD;break}if(i.lenbits=9,y={bits:i.lenbits},b=inflate_table2(LENS,i.lens,0,i.nlen,i.lencode,0,i.work,y),i.lenbits=y.bits,b){e.msg="invalid literal/lengths set",i.mode=BAD;break}if(i.distbits=6,i.distcode=i.distdyn,y={bits:i.distbits},b=inflate_table2(DISTS,i.lens,i.nlen,i.ndist,i.distcode,0,i.work,y),i.distbits=y.bits,b){e.msg="invalid distances set",i.mode=BAD;break}if(i.mode=LEN_,t===Z_TREES)break e;case LEN_:i.mode=LEN;case LEN:if(a>=6&&d>=258){e.next_out=n,e.avail_out=d,e.next_in=s,e.avail_in=a,i.hold=c,i.bits=l,inflate_fast2(e,_),n=e.next_out,o=e.output,d=e.avail_out,s=e.next_in,r=e.input,a=e.avail_in,c=i.hold,l=i.bits,i.mode===TYPE&&(i.back=-1);break}for(i.back=0;g=(C=i.lencode[c&(1<<i.lenbits)-1])>>>16&255,v=65535&C,!((S=C>>>24)<=l);){if(0===a)break e;a--,c+=r[s++]<<l,l+=8}if(g&&!(240&g)){for(f=S,E=g,T=v;g=(C=i.lencode[T+((c&(1<<f+E)-1)>>f)])>>>16&255,v=65535&C,!(f+(S=C>>>24)<=l);){if(0===a)break e;a--,c+=r[s++]<<l,l+=8}c>>>=f,l-=f,i.back+=f}if(c>>>=S,l-=S,i.back+=S,i.length=v,0===g){i.mode=LIT;break}if(32&g){i.back=-1,i.mode=TYPE;break}if(64&g){e.msg="invalid literal/length code",i.mode=BAD;break}i.extra=15&g,i.mode=LENEXT;case LENEXT:if(i.extra){for(I=i.extra;l<I;){if(0===a)break e;a--,c+=r[s++]<<l,l+=8}i.length+=c&(1<<i.extra)-1,c>>>=i.extra,l-=i.extra,i.back+=i.extra}i.was=i.length,i.mode=DIST;case DIST:for(;g=(C=i.distcode[c&(1<<i.distbits)-1])>>>16&255,v=65535&C,!((S=C>>>24)<=l);){if(0===a)break e;a--,c+=r[s++]<<l,l+=8}if(!(240&g)){for(f=S,E=g,T=v;g=(C=i.distcode[T+((c&(1<<f+E)-1)>>f)])>>>16&255,v=65535&C,!(f+(S=C>>>24)<=l);){if(0===a)break e;a--,c+=r[s++]<<l,l+=8}c>>>=f,l-=f,i.back+=f}if(c>>>=S,l-=S,i.back+=S,64&g){e.msg="invalid distance code",i.mode=BAD;break}i.offset=v,i.extra=15&g,i.mode=DISTEXT;case DISTEXT:if(i.extra){for(I=i.extra;l<I;){if(0===a)break e;a--,c+=r[s++]<<l,l+=8}i.offset+=c&(1<<i.extra)-1,c>>>=i.extra,l-=i.extra,i.back+=i.extra}if(i.offset>i.dmax){e.msg="invalid distance too far back",i.mode=BAD;break}i.mode=MATCH;case MATCH:if(0===d)break e;if(h=_-d,i.offset>h){if((h=i.offset-h)>i.whave&&i.sane){e.msg="invalid distance too far back",i.mode=BAD;break}h>i.wnext?(h-=i.wnext,p=i.wsize-h):p=i.wnext-h,h>i.length&&(h=i.length),m=i.window}else m=o,p=n-i.offset,h=i.length;h>d&&(h=d),d-=h,i.length-=h;do{o[n++]=m[p++]}while(--h);0===i.length&&(i.mode=LEN);break;case LIT:if(0===d)break e;o[n++]=i.length,d--,i.mode=LEN;break;case CHECK:if(i.wrap){for(;l<32;){if(0===a)break e;a--,c|=r[s++]<<l,l+=8}if(_-=d,e.total_out+=_,i.total+=_,_&&(e.adler=i.check=i.flags?crc32(i.check,o,_,n-_):adler32(i.check,o,_,n-_)),_=d,(i.flags?c:zswap32(c))!==i.check){e.msg="incorrect data check",i.mode=BAD;break}c=0,l=0}i.mode=LENGTH;case LENGTH:if(i.wrap&&i.flags){for(;l<32;){if(0===a)break e;a--,c+=r[s++]<<l,l+=8}if(c!==(4294967295&i.total)){e.msg="incorrect length check",i.mode=BAD;break}c=0,l=0}i.mode=DONE;case DONE:b=Z_STREAM_END;break e;case BAD:b=Z_DATA_ERROR;break e;case MEM:return Z_MEM_ERROR;default:return Z_STREAM_ERROR}return e.next_out=n,e.avail_out=d,e.next_in=s,e.avail_in=a,i.hold=c,i.bits=l,(i.wsize||_!==e.avail_out&&i.mode<BAD&&(i.mode<CHECK||t!==Z_FINISH))&&updatewindow(e,e.output,e.next_out,_-e.avail_out),u-=e.avail_in,_-=e.avail_out,e.total_in+=u,e.total_out+=_,i.total+=_,i.wrap&&_&&(e.adler=i.check=i.flags?crc32(i.check,o,_,e.next_out-_):adler32(i.check,o,_,e.next_out-_)),e.data_type=i.bits+(i.last?64:0)+(i.mode===TYPE?128:0)+(i.mode===LEN_||i.mode===COPY_?256:0),(0===u&&0===_||t===Z_FINISH)&&b===Z_OK&&(b=Z_BUF_ERROR),b}function inflateEnd(e){if(!e||!e.state)return Z_STREAM_ERROR;var t=e.state;return t.window&&(t.window=null),e.state=null,Z_OK}function inflateGetHeader(e,t){var i;return e&&e.state&&2&(i=e.state).wrap?(i.head=t,t.done=!1,Z_OK):Z_STREAM_ERROR}function inflateSetDictionary(e,t){var i,r=t.length;return e&&e.state?0!==(i=e.state).wrap&&i.mode!==DICT?Z_STREAM_ERROR:i.mode===DICT&&adler32(1,t,r,0)!==i.check?Z_DATA_ERROR:updatewindow(e,t,r,r)?(i.mode=MEM,Z_MEM_ERROR):(i.havedict=1,Z_OK):Z_STREAM_ERROR}inflate$3.inflateReset=inflateReset,inflate$3.inflateReset2=inflateReset2,inflate$3.inflateResetKeep=inflateResetKeep,inflate$3.inflateInit=inflateInit,inflate$3.inflateInit2=inflateInit2,inflate$3.inflate=inflate$2,inflate$3.inflateEnd=inflateEnd,inflate$3.inflateGetHeader=inflateGetHeader,inflate$3.inflateSetDictionary=inflateSetDictionary,inflate$3.inflateInfo="pako inflate (from Nodeca project)";var constants$1={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8};function GZheader$1(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}var gzheader=GZheader$1,zlib_inflate=inflate$3,utils=common,strings=strings$2,c=constants$1,msg=messages,ZStream=zstream,GZheader=gzheader,toString=Object.prototype.toString;function Inflate(e){if(!(this instanceof Inflate))return new Inflate(e);this.options=utils.assign({chunkSize:16384,windowBits:0,to:""},e||{});var t=this.options;t.raw&&t.windowBits>=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(t.windowBits>=0&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&(15&t.windowBits||(t.windowBits|=15)),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new ZStream,this.strm.avail_out=0;var i=zlib_inflate.inflateInit2(this.strm,t.windowBits);if(i!==c.Z_OK)throw new Error(msg[i]);if(this.header=new GZheader,zlib_inflate.inflateGetHeader(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=strings.string2buf(t.dictionary):"[object ArrayBuffer]"===toString.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(i=zlib_inflate.inflateSetDictionary(this.strm,t.dictionary))!==c.Z_OK))throw new Error(msg[i])}function inflate$1(e,t){var i=new Inflate(t);if(i.push(e,!0),i.err)throw i.msg||msg[i.err];return i.result}function inflateRaw(e,t){return(t=t||{}).raw=!0,inflate$1(e,t)}Inflate.prototype.push=function(e,t){var i,r,o,s,n,a=this.strm,d=this.options.chunkSize,l=this.options.dictionary,u=!1;if(this.ended)return!1;r=t===~~t?t:!0===t?c.Z_FINISH:c.Z_NO_FLUSH,"string"==typeof e?a.input=strings.binstring2buf(e):"[object ArrayBuffer]"===toString.call(e)?a.input=new Uint8Array(e):a.input=e,a.next_in=0,a.avail_in=a.input.length;do{if(0===a.avail_out&&(a.output=new utils.Buf8(d),a.next_out=0,a.avail_out=d),(i=zlib_inflate.inflate(a,c.Z_NO_FLUSH))===c.Z_NEED_DICT&&l&&(i=zlib_inflate.inflateSetDictionary(this.strm,l)),i===c.Z_BUF_ERROR&&!0===u&&(i=c.Z_OK,u=!1),i!==c.Z_STREAM_END&&i!==c.Z_OK)return this.onEnd(i),this.ended=!0,!1;a.next_out&&(0!==a.avail_out&&i!==c.Z_STREAM_END&&(0!==a.avail_in||r!==c.Z_FINISH&&r!==c.Z_SYNC_FLUSH)||("string"===this.options.to?(o=strings.utf8border(a.output,a.next_out),s=a.next_out-o,n=strings.buf2string(a.output,o),a.next_out=s,a.avail_out=d-s,s&&utils.arraySet(a.output,a.output,o,s,0),this.onData(n)):this.onData(utils.shrinkBuf(a.output,a.next_out)))),0===a.avail_in&&0===a.avail_out&&(u=!0)}while((a.avail_in>0||0===a.avail_out)&&i!==c.Z_STREAM_END);return i===c.Z_STREAM_END&&(r=c.Z_FINISH),r===c.Z_FINISH?(i=zlib_inflate.inflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===c.Z_OK):r!==c.Z_SYNC_FLUSH||(this.onEnd(c.Z_OK),a.avail_out=0,!0)},Inflate.prototype.onData=function(e){this.chunks.push(e)},Inflate.prototype.onEnd=function(e){e===c.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=utils.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},inflate$4.Inflate=Inflate,inflate$4.inflate=inflate$1,inflate$4.inflateRaw=inflateRaw,inflate$4.ungzip=inflate$1;var assign=common.assign,deflate=deflate$4,inflate=inflate$4,constants=constants$1,pako={};assign(pako,deflate,inflate,constants);var pako_1=pako,pako$1=getDefaultExportFromCjs(pako_1);let lockId$1=1,PromiseLock$1=class{constructor(e){__publicField(this,"lockingPromise",Promise.resolve()),__publicField(this,"locks",0),__publicField(this,"name",""),__publicField(this,"lockId"),this.lockId=lockId$1++,e&&(this.name=e)}get isLocked(){return this.locks>0}lock(){let e;this.locks+=1;const t=new Promise((t=>{e=()=>{this.locks-=1,t()}})),i=this.lockingPromise.then((()=>e));return this.lockingPromise=this.lockingPromise.then((()=>t)),i}};const DB_NAME="VERTC",indexedDB$1=()=>window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB,_IndexedDBInterface=class{constructor(e){__publicField(this,"storeName"),__publicField(this,"pendingList",[]),this.storeName=e,!isSSR$1()&&indexedDB$1()&&this._checkAndCreateStore(e)}async _checkAndCreateStore(e,t){const i=await _IndexedDBInterface._promiseLock.lock();if(indexedDB$1().databases){let e;await new Promise((t=>{const i=()=>indexedDB$1().databases().finally(t);e=setInterval(i,100),i()})).finally((()=>clearInterval(e)))}return new Promise((r=>{_IndexedDBInterface.db&&(_IndexedDBInterface.db.close(),delete _IndexedDBInterface.db);const o=t?indexedDB$1().open(DB_NAME,t):indexedDB$1().open(DB_NAME);o.onupgradeneeded=()=>{o.result.createObjectStore(e)},o.onerror=()=>{console.error("IndexedDBInterface error",o.error)},o.onsuccess=()=>{const t=o.result;_IndexedDBInterface.db=t;try{_IndexedDBInterface.db.transaction(this.storeName,"readonly"),this.pendingList.forEach((async({txMode:e,pendResolve:t,pendReject:i})=>{try{t(await this._getStore(e))}catch(e){i()}})),r()}catch{r(this._checkAndCreateStore(e,t.version+1))}finally{i()}}}))}async _getStore(e){const t=await _IndexedDBInterface._promiseLock.lock();return new Promise(((i,r)=>{if(!_IndexedDBInterface.db)return this.pendingList.push({txMode:e,pendResolve:i,pendReject:r}),void t();try{i(_IndexedDBInterface.db.transaction(this.storeName,e).objectStore(this.storeName))}catch(t){return void this.pendingList.push({txMode:e,pendResolve:i,pendReject:r})}finally{t()}}))}async put2String(e,t){let i;try{i=JSON.stringify(e)}catch{i=e}return await this.put(i,t)}async get4String(e){const t=await this.get(e);let i;try{i=JSON.parse(t)}catch{i=t}return i}async put(e,t){const i=await this._getStore("readwrite");return new Promise(((r,o)=>{const s=i.put(e,t);s.onsuccess=()=>{r()},s.onerror=e=>{o(e)}}))}async get(e){const t=await this._getStore("readonly");return new Promise(((i,r)=>{const o=t.get(e);o.onsuccess=()=>{i(o.result)},o.onerror=e=>{r(e)}}))}async del(e){const t=await this._getStore("readwrite");return new Promise(((i,r)=>{const o=t.delete(e);o.onsuccess=()=>{i()},o.onerror=e=>{r(e)}}))}};let IndexedDBInterface=_IndexedDBInterface;function isOutBufferItem(e){return void 0!==e.report_id}__publicField(IndexedDBInterface,"db"),__publicField(IndexedDBInterface,"state","init"),__publicField(IndexedDBInterface,"_promiseLock",new PromiseLock$1("iDB"));class LongStringReportor{constructor(){__publicField(this,"name","LongStringReportor"),__publicField(this,"inBuffer",[]),__publicField(this,"outBuffer",[])}push(e){e.message&&this.inBuffer.push({...e,message:{id:genUuid$1().slice(0,3),index:0,end:!0,msg:e.message}})}splice(e){const t=[];let i=0;for(;this.outBuffer.length;){const r=JSON.stringify(this.outBuffer[0]).length;if(!(r<e))break;e-=r,i+=r,t.push(this.outBuffer.shift())}for(;this.inBuffer[0]&&e>0;){const{message:r,...o}=this.inBuffer[0],s={...o,message:{...r,msg:""}},n=JSON.stringify(s).length,a=e-n,d={...s};if(a>r.msg.length)d.message.msg=r.msg,this.inBuffer.shift();else{if(!(a>=10))break;{const e=r.msg.slice(0,a);d.message.msg=e,d.message.end=!1,this.inBuffer[0].message.msg=r.msg.slice(a),this.inBuffer[0].message.index++}}const c=JSON.stringify(d.message),l=c.length;e-=l+n,i+=l+n,t.push({...d,message:c})}return{payload:t,payloadSize:i}}unshift(e){this.outBuffer=e.concat(this.outBuffer)}get(){return[...this.outBuffer,...this.inBuffer.map((e=>({...e,message:JSON.stringify(e.message)})))]}set(e){e.forEach((e=>{isOutBufferItem(e)?this.outBuffer.push(e):(e.message||(e.message=""),this.inBuffer.push({...e,message:JSON.parse(e.message)}))})),this.outBuffer=[].concat(this.outBuffer),this.inBuffer=[].concat(this.inBuffer)}isEmpty(){return 0===this.inBuffer.length&&0===this.outBuffer.length}}var longStringReportor=new LongStringReportor;const HARDCODE_UPLOAD_MAX_LIMIT=5e5,HARDCODE_UPLOAD_MIN_LIMIT=5e4,DEFAULT_UPLOAD_LIMIT=5e5,HTTP_REQUEST_TIMEOUT=1e4,REPORT_INTERVAL=2e3,defaultCommonStats={product_line:"rtc",report_version:"5",os:"web",user_agent:isSSR$1()?"":null==navigator?void 0:navigator.userAgent,platform:"web",product:"webrtc",app_state:"active"},REPORT_DB_BUFFER_STORE="LogReportor",DEBUG$1="undefined"!=typeof window&&(window.location.search.includes("_rtc_debug_")||(null==(_a=window.localStorage)?void 0:_a.getItem("_rtc_debug_")));class ReportorDBBuffer{constructor(e){__publicField(this,"_buffer"),this._buffer=new IndexedDBInterface(e)}async set(e,t){await this._buffer.put2String(e,t)}async get(e){let t=[];try{t=await this._buffer.get4String(e)}catch(e){}return t??[]}}class Reportor{constructor(){__publicField(this,"reportCommon",defaultCommonStats),__publicField(this,"reportIds",new Map),__publicField(this,"dataBuffer",[]),__publicField(this,"reportorList",[]),__publicField(this,"dbBuffer"),__publicField(this,"posting",!1),__publicField(this,"sucSendTimer"),__publicField(this,"preSucTime",0),__publicField(this,"errSendTimer"),__publicField(this,"errSendDelay",100),__publicField(this,"_logServerUrl"),__publicField(this,"_retryCount",0),__publicField(this,"_reportLimit",5e5),__publicField(this,"_disableTimeout",!1),isSSR$1()||(window.addEventListener("beforeunload",(()=>{clearTimeout(this.errSendTimer),clearTimeout(this.sucSendTimer),this.send(void 0,!0)})),document.addEventListener("visibilitychange",(()=>{"visible"===document.visibilityState?this.setCommonStats({app_state:"active"}):"hidden"===document.visibilityState&&this.setCommonStats({app_state:"background"})})),DEBUG$1&&(window.__rtc_debug_reportor__=this)),CoreConfig.on("UPLOAD_REPORT_LIMIT",(e=>{this.setReportLimit(e)})),CoreConfig.on("ENABLE_REPORT_IDB_BUFFER",(e=>{e&&this.enableIndexedDBBuffer()})),setTimeout((()=>{this.reportorList.push(consoleReportor),this.reportorList.push(longStringReportor)}))}setUrl(e){this._logServerUrl=e}setCommonStats(e){this.reportCommon=Object.assign(this.reportCommon,e)}getCommonStats(){return this.reportCommon}setReportLimit(e){this._reportLimit=Math.max(e,5e4),this._reportLimit=Math.min(e,5e5)}getReportId(e){e=e??"__global__",this.reportIds.has(e)||this.reportIds.set(e,0);let t=this.reportIds.get(e);return void 0===t&&(reportGlobalError(`no reportId in reportId map with engine-session-id ${e}`,0,{}),t=0),this.reportIds.set(e,t+1),t}push(e,t=!1){if(t)this.send(e);else{const t=e.engine_session_id??"__global__";this.reportIds.has(t)||this.reportIds.set(t,0),this.dataBuffer.push(e),!this.posting&&!this.errSendTimer&&Date.now()-this.preSucTime>2e3&&(clearTimeout(this.sucSendTimer),this.send())}}enableIndexedDBBuffer(){this.dbBuffer||(this.dbBuffer=new ReportorDBBuffer("ReportorDBBuffer"),this.dbBuffer.get("LogReportor").then((e=>{e.forEach((e=>{this.push(e)}))})),this.reportorList.forEach((e=>{var t;null==(t=this.dbBuffer)||t.get(e.name).then((t=>{e.set(t)}))})))}backup(){var e;try{null==(e=this.dbBuffer)||e.set([...this.dataBuffer],"LogReportor"),this.reportorList.forEach((e=>{var t;null==(t=this.dbBuffer)||t.set([...e.get()],e.name)}))}catch(e){reportGlobalError("Error when save log into IDB",-1,e)}}unshift(e){this.dataBuffer=e[0].concat(this.dataBuffer),this.reportorList.forEach(((t,i)=>{t.unshift(e[i+1]??[])}))}_splice(){let e=findSizeIndex$1(this.dataBuffer,this._reportLimit);0===e&&this.dataBuffer.length>0&&(this._reportLimit=JSON.stringify(this.dataBuffer[0]).length+10,e=1,reportGlobalError(`update report limit to ${this._reportLimit}`,0,null));const t=this.dataBuffer.splice(0,e),i=JSON.stringify(t).length,r=[t];let o=this._reportLimit-i;return this.reportorList.forEach((e=>{const{payload:t,payloadSize:i}=e.splice(o);t.forEach((e=>{var t;void 0===e.report_id&&(e.report_id=this.getReportId(e.engine_session_id),!isSSR$1()&&window.__onRTCReport&&(null==(t=window.__onRTCReport)||t.call(window,e.engine_session_id??"global",e,this.getCommonStats())))})),r.push(t),o-=i})),r}async send(e,t){this.backup();const i=this.reportorList.reduce(((e,t)=>e&&t.isEmpty()),!0);if(!e&&!this.dataBuffer.length&&i||!this._logServerUrl)return;e||(this.posting=!0);let r=[];e||(r=this._splice());const o=DEBUG$1,s={data:e||r.flat(),header:{...this.reportCommon,http_retry_count:this._retryCount},from:"web",os:"web",version:"1"},n={method:"POST",body:o?JSON.stringify(s):pako$1.gzip(JSON.stringify(s))};if(!this._disableTimeout)try{const e=new AbortController;n.signal=e.signal,setTimeout((()=>{e.abort()}),1e4)}catch{console.warn("AbortController is not supported"),this._disableTimeout=!0}o||(n.headers={"Content-Encoding":"gzip","Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"});let a,d,c=null;try{a=await fetch(this._logServerUrl,n),200!==a.status&&304!==a.status||(c=JSON.parse(await a.text()))}catch(e){d=e}e||(this.posting=!1),c&&0===c.StatusCode?e||t||this.sucSend():(setTimeout((()=>{reportGlobalError(`reportor post error, resJSON:${null==c?void 0:c.toString()} err:${d}`,(null==a?void 0:a.status)??-1,d)}),0),e?this.send(e):(this.unshift(r),t?this.send():this.errSend()))}_getDataBufferTotalSize(){return this.dataBuffer.reduce(((e,t)=>e+JSON.stringify(t).length),0)}sucSend(){this.errSendDelay=100,this._retryCount=0,this.preSucTime=Date.now();const e=this._getDataBufferTotalSize()>1e6?1e3:2e3;this.sucSendTimer=setTimeout((()=>this.send()),e)}errSend(){this.errSendTimer=setTimeout((()=>{this.send(),delete this.errSendTimer}),this.errSendDelay),this.errSendDelay*=2,this._retryCount++}}function findSizeIndex$1(e,t){let i=0;for(let r=0;r<e.length;r++)if(i+=JSON.stringify(e[r]).length,i>t)return r;return e.length}var commonReportor=new Reportor;class Monitor{constructor(e){__publicField(this,"modifyIds",{pre_connection:!1}),this.id=e}report(e,t,i){var r;const o={event_key:e,rtc_timestamp:Date.now(),...this.modifyIds,...t,report_id:commonReportor.getReportId(this.modifyIds.engine_session_id)};"object"==typeof i&&Object.keys(i).length>0&&(o.common_extra_info=JSON.stringify(i)),Object.keys(o).forEach((e=>{void 0!==o[e]&&""!==o[e]||delete o[e]})),!isSSR$1()&&window.__onRTCReport&&(null==(r=window.__onRTCReport)||r.call(window,this.modifyIds.engine_session_id,o,commonReportor.getCommonStats())),"UT"!=={}.VITE_TEST&&commonReportor.push(o)}reportLog(e){const t={event_key:"rtc_invoke_status",sdk_api_name:"console_log",rtc_timestamp:Date.now(),...this.modifyIds,message:e};consoleReportor.push(t)}reportLongString(e,t){const i={event_key:"rtc_invoke_status",sdk_api_name:`sdk_long_string_${e}`,rtc_timestamp:Date.now(),...this.modifyIds,message:t};longStringReportor.push(i)}set(e){this.modifyIds=Object.assign(this.modifyIds,e)}destroy(){}}const RESET_DURATION=36e5,_MessageReportor=class{constructor(e){__publicField(this,"_preTime",Date.now()),__publicField(this,"_one2oneNum",0),__publicField(this,"_one2manyNum",0),__publicField(this,"_one2oneMsgCache",new Map),__publicField(this,"_one2manyMsgCache",new Map),__publicField(this,"roomId",""),__publicField(this,"userId",""),__publicField(this,"rtsSessionId",""),__publicField(this,"logger"),__publicField(this,"serverUrl","server"),this.id=e,this.logger=new Logger$1("MessageReportor",1)}needReport(e){return!!_MessageReportor.config&&(Date.now()-this._preTime>=36e5&&(this._preTime=Date.now(),this._one2oneNum=0,this._one2manyNum=0),"one2one"===e&&this._one2oneNum<_MessageReportor.config.max_one2one_fpt_per_hour&&Math.random()<=_MessageReportor.config.one2one_fpt_ratio/100||"one2many"===e&&this._one2manyNum<_MessageReportor.config.max_one2many_fpt_per_hour&&Math.random()<=_MessageReportor.config.one2many_fpt_ratio/100)}cacheP2PMsg(e){var t;this._one2oneMsgCache.set(e.msg_id,{config_version:(null==(t=_MessageReportor.config)?void 0:t.version)||"",...e})}updateP2PMsg(e,t){const i=this._one2oneMsgCache.get(e);i&&this._one2oneMsgCache.set(e,{...i,...t})}cacheCustomMsg(e){var t;this._one2manyMsgCache.set(e.msg_id,{config_version:(null==(t=_MessageReportor.config)?void 0:t.version)||"",...e})}updateOne2ManyMsg(e,t){const i=this._one2manyMsgCache.get(e);i&&this._one2manyMsgCache.set(e,{...i,...t})}reportP2PMsg(e){var t;const i=this._one2oneMsgCache.get(e);i&&(this.logger.info("reportP2PMsg",i.type,JSON.stringify(i)),null==(t=getMonitor(this.id))||t.report("rts_message",i))}reportOne2ManyMsg(e){var t;const i=this._one2manyMsgCache.get(e);i&&(this.logger.info("reportOne2ManyMsg",i.type,JSON.stringify(i)),null==(t=getMonitor(this.id))||t.report("rts_message",i))}reportMsgRecv(e){var t,i;e.config_version=(null==(t=_MessageReportor.config)?void 0:t.version)||"",this.logger.info("reportMsgRecv",e.type,JSON.stringify(e)),null==(i=getMonitor(this.id))||i.report("rts_message",e)}destroy(){this._one2manyNum=0,this._one2oneNum=0,this._one2manyMsgCache.clear(),this._one2oneMsgCache.clear(),this._preTime=Date.now(),this.roomId="",this.userId="",this.rtsSessionId=""}};let MessageReportor=_MessageReportor;__publicField(MessageReportor,"config");const _cache=new Map,setConfig=e=>{new Logger$1("MessageReportor",1).info("setConfig",`get config: ${JSON.stringify(e)}`),MessageReportor.config=e},createRTSMsgReportor=e=>{const t=_cache.get(e)||new MessageReportor(e);return _cache.set(e,t),t},destroyRTSMsgReportor=e=>{const t=_cache.get(e);t&&(t.destroy(),_cache.delete(e))},setServerUrl=(e,t)=>{const i=_cache.get(e);i&&(i.serverUrl=t)},setRoomId=(e,t)=>{const i=_cache.get(e);i&&(i.roomId=t||"")},setUserId=(e,t)=>{const i=_cache.get(e);i&&(i.userId=t||"")},setRtsSessionId=(e,t)=>{const i=_cache.get(e);i&&(i.rtsSessionId=t)},samplingP2PMsg=(e,t)=>{const i=_cache.get(e);if(null==i?void 0:i.needReport("one2one")){const e=t.to?"one2one":"one2server";t.enable_report=!0,t.report_msg_id=t.id,i.cacheP2PMsg({rts_session_id:i.rtsSessionId,msg_id:`${t.id}`,node_role:"src_sdk",from:t.from,to:t.to||i.serverUrl,msg_type:e,type:e,rts_room_id:t.room,req_ts:Date.now(),send_ts:Date.now(),ack_ts:Date.now(),msg_size:0,error_code:0,recv_msg_ts:0,fwd_msg_ts:0,reply_ack_ts:0,cur_dst_uid:""})}return t},updateP2PMsgReq=(e,t,i)=>{var r;t.enable_report&&assertValidMsgId(t.report_msg_id)&&(null==(r=_cache.get(e))||r.updateP2PMsg(`${t.report_msg_id}`,{send_ts:Date.now(),msg_size:i}))},updateP2PMsgAck=(e,t,i)=>{if(t.enable_report&&assertValidMsgId(t.report_msg_id)){const r=_cache.get(e);null==r||r.updateP2PMsg(`${t.report_msg_id}`,{ack_ts:Date.now(),error_code:i}),null==r||r.reportP2PMsg(`${t.report_msg_id}`)}},samplingOne2ManyMsg=(e,t,i)=>{const r=_cache.get(e);return(null==r?void 0:r.needReport("one2many"))&&(i.enable_report=!0,i.report_msg_id=t,r.cacheCustomMsg({rts_session_id:r.rtsSessionId,msg_id:`${t}`,node_role:"src_sdk",from:i.clientId,to:r.roomId||i.roomId,msg_type:"one2many",type:"one2many",rts_room_id:r.roomId,req_ts:Date.now(),send_ts:Date.now(),ack_ts:Date.now(),msg_size:0,error_code:0,recv_msg_ts:0,fwd_msg_ts:0,reply_ack_ts:0,cur_dst_uid:""})),i},updateOne2ManyMsgReq=(e,t,i)=>{if(t.enable_report&&assertValidMsgId(t.report_msg_id)){const r=_cache.get(e);r&&r.updateOne2ManyMsg(`${t.report_msg_id}`,{send_ts:Date.now(),msg_size:i})}},updateOne2ManyMsgAck=(e,t,i)=>{if(t.enable_report&&assertValidMsgId(t.report_msg_id)){const r=_cache.get(e);r&&(null==r||r.updateOne2ManyMsg(`${t.report_msg_id}`,{ack_ts:Date.now(),error_code:i}),null==r||r.reportOne2ManyMsg(`${t.report_msg_id}`))}},reportP2PMsgRecv=(e,t,i)=>{if(t.enable_report&&assertValidMsgId(t.report_msg_id)){const r=_cache.get(e),o=t.to?"one2one":"one2many";null==r||r.reportMsgRecv({rts_session_id:r.rtsSessionId,msg_id:`${t.report_msg_id}`,msg_size:i.msg_size,node_role:"dst_sdk",msg_type:o,type:o,rts_room_id:t.room,from:t.from,to:t.to||t.room,error_code:0,recv_msg_ts:i.recv_msg_ts,fwd_msg_ts:i.fwd_msg_ts,reply_ack_ts:Date.now(),cur_dst_uid:t.to?"":r.userId,config_version:"",req_ts:0,send_ts:0,ack_ts:0})}},reportOne2ManyMsgRecv=(e,t,i)=>{if(t.enable_report&&assertValidMsgId(t.report_msg_id)){const r=_cache.get(e);null==r||r.reportMsgRecv({rts_session_id:r.rtsSessionId,msg_id:`${t.report_msg_id}`,msg_size:i.msg_size,node_role:"dst_sdk",msg_type:"one2many",type:"one2many",rts_room_id:t.roomId,from:t.clientId,to:t.roomId,error_code:0,recv_msg_ts:i.recv_msg_ts,fwd_msg_ts:i.fwd_msg_ts,reply_ack_ts:Date.now(),cur_dst_uid:r.userId,config_version:"",req_ts:0,send_ts:0,ack_ts:0})}},RTSMsgReportor={_cache:_cache,setServerUrl:setServerUrl,setConfig:setConfig,setRtsSessionId:setRtsSessionId,createRTSMsgReportor:createRTSMsgReportor,destroyRTSMsgReportor:destroyRTSMsgReportor,setRoomId:setRoomId,setUserId:setUserId,samplingP2PMsg:samplingP2PMsg,updateP2PMsgReq:updateP2PMsgReq,updateP2PMsgAck:updateP2PMsgAck,samplingOne2ManyMsg:samplingOne2ManyMsg,reportP2PMsgRecv:reportP2PMsgRecv,updateOne2ManyMsgAck:updateOne2ManyMsgAck,updateOne2ManyMsgReq:updateOne2ManyMsgReq,reportOne2ManyMsgRecv:reportOne2ManyMsgRecv};class MessageStatisticsObserver{constructor(e){__publicField(this,"_timer"),__publicField(this,"userMessage",{}),__publicField(this,"roomMessage",{}),this.id=e,this._setTimer()}_setTimer(){const e=()=>{this._reportAndgReset(),clearTimeout(this._timer),this._timer=setTimeout(e,1e4)};e()}_reportAndgReset(){(Object.keys(this.userMessage).length||Object.keys(this.roomMessage).length)&&(this._report(),this._reset())}_report(){var e;null==(e=getMonitor(this.id))||e.report("rtc_message_statistics",{dc_user_message:Object.keys(this.userMessage).map((e=>this.userMessage[e])),dc_room_message:Object.keys(this.roomMessage).map((e=>this.roomMessage[e])),media_server_ip:""})}_reset(){this.userMessage={},this.roomMessage={}}_checkInitUserMessage(e,t){this.userMessage[`${t}-${e}`]||(this.userMessage[`${t}-${e}`]={dc_peer_user_id:e,dc_send_total:0,dc_recv_total:0,dc_send_ack:0,dc_send_fail:0,dc_fail_timeout:0,dc_fail_no_receiver:0,dc_fail_no_relay_path:0,dc_cost_time:0,dc_cost_e2s:0,dc_cost_s2s:0,dc_least_time:Number(1/0),dc_most_time:0,dc_cost_peer_s2e:0,dc_send_ack_100:0,dc_send_ack_200:0,dc_send_ack_400:0,dc_send_ack_1s:0,dc_message_type:t,dc_send_binary:0})}_sendUserMessage(e,t,i){this._checkInitUserMessage(e,t),this.userMessage[`${t}-${e}`].dc_send_total++,i&&this.userMessage[`${t}-${e}`].dc_send_binary++}_recvUserMessage(e,t){this._checkInitUserMessage(e,t),this.userMessage[`${t}-${e}`].dc_recv_total++}_sendUserFail(e,t,i){const r=this.userMessage[`${t}-${e}`];r&&(r.dc_send_fail++,this._handleUserFail(r,i))}_handleUserFail(e,t){t&&(t.code||t.err)&&(["TIME_OUT","USER_MESSAGE_TIMEOUT"].includes(t.code)?e.dc_fail_timeout++:3===t.err?e.dc_fail_no_receiver++:4===t.err?e.dc_fail_no_relay_path++:1===t.err&&e.dc_fail_timeout++)}_sendUserAck(e,t,i,r,o){const s=this.userMessage[`${t}-${e}`];s&&(s.dc_send_ack++,s.dc_cost_time+=i,s.dc_cost_s2s+=r||0,s.dc_cost_peer_s2e+=o,s.dc_cost_e2s+=i-(r||0)-o,i/2<=100?(s.dc_send_ack_100++,s.dc_send_ack_200++,s.dc_send_ack_400++,s.dc_send_ack_1s++):i/2<=200?(s.dc_send_ack_200++,s.dc_send_ack_400++,s.dc_send_ack_1s++):i/2<=400?(s.dc_send_ack_400++,s.dc_send_ack_1s++):i/2<=1e3&&s.dc_send_ack_1s++,i<s.dc_least_time&&(s.dc_least_time=i),i>s.dc_most_time&&(s.dc_most_time=i))}sendRoomMessage(e,t){this.roomMessage[e]||(this.roomMessage[e]={dc_room_id:e,dc_send_total:0,dc_send_ack:0,dc_cost_time:0,dc_least_time:Number(1/0),dc_most_time:0,dc_send_fail:0,dc_send_ack_100:0,dc_send_ack_200:0,dc_send_ack_400:0,dc_send_ack_1s:0,dc_send_binary:0}),this.roomMessage[e].dc_send_total++,t&&this.roomMessage[e].dc_send_binary++}sendRoomFail(e){const t=this.roomMessage[e];t&&t.dc_send_fail++}sendRoomAck(e,t){const i=this.roomMessage[e];i&&(i.dc_send_ack++,i.dc_cost_time+=t,t<i.dc_least_time&&(i.dc_least_time=t),t>i.dc_most_time&&(i.dc_most_time=t),t/2<=100?(i.dc_send_ack_100++,i.dc_send_ack_200++,i.dc_send_ack_400++,i.dc_send_ack_1s++):t/2<=200?(i.dc_send_ack_200++,i.dc_send_ack_400++,i.dc_send_ack_1s++):t/2<=400?(i.dc_send_ack_400++,i.dc_send_ack_1s++):t/2<=1e3&&i.dc_send_ack_1s++)}sendP2PMessage(e,t){this._sendUserMessage(e,"p2p",t)}recvP2PMessage(e){this._recvUserMessage(e,"p2p")}sendP2PFail(e,t){this._sendUserFail(e,"p2p",t)}sendP2PAck(e,t,i,r){this._sendUserAck(e,"p2p",t,i,r)}sendP2POutRoomMessage(e,t){this._sendUserMessage(e,"p2p_outside_room",t)}recvP2POutRoomMessage(e){this._recvUserMessage(e,"p2p_outside_room")}sendP2POutRoomFail(e,t){this._sendUserFail(e,"p2p_outside_room",t)}sendP2POutRoomAck(e,t,i,r){this._sendUserAck(e,"p2p_outside_room",t,i,r)}sendP2serverMessage(e){this._sendUserMessage("","p2server",e)}sendP2serverFail(e){this._sendUserFail("","p2server",e)}sendP2serveAck(e,t,i){this._sendUserAck("","p2server",e,t,i)}countP2PMessage(e,t,i,r,o){this.sendP2PMessage(t,i),e?this.sendP2PAck(t,Date.now()-r,o.s2s_time||0,o.s2e_time||0):this.sendP2PFail(t,o)}countRoomMessage(e,t,i,r){this.sendRoomMessage(t,i),e?this.sendRoomAck(t,Date.now()-r):this.sendRoomFail(t)}countUserMessageOutsideRoom(e,t,i,r,o){this.sendP2POutRoomMessage(t,i),e?this.sendP2POutRoomAck(t,Date.now()-r,o.s2s_time,o.s2e_time):this.sendP2POutRoomFail(t,o)}countServerMessage(e,t,i,r){this.sendP2serverMessage(t),e?(r=r||{},this.sendP2serveAck(Date.now()-i,r.s2s_time||0,r.s2e_time||0)):this.sendP2serverFail(r)}destroy(){this._reset(),clearTimeout(this._timer)}}const setGlobalStats=e=>{commonReportor.setCommonStats(e)},setReportUrl=e=>{commonReportor.setUrl(e)},globalMonitor=new Monitor("global"),reportGlobalApiCall=(e,t,i)=>{globalMonitor.report("rtc_sdk_api_call",{sdk_api_name:e,error_code:t,message:i})},reportGlobalCallback=(e,t,i)=>{globalMonitor.report("rtc_sdk_callback",{sdk_callback_name:e,error_code:t,message:i})},reportGlobalError=(e,t,i)=>{globalMonitor.report("rtc_error",{message:e,error_code:t},i)},reportGlobalInvokeStatus=(e,t,i=0,r="",o)=>{globalMonitor.report("rtc_invoke_status",{sdk_api_name:e,message:t,error_code:i,stream_id:r,elapse:0},o)};function reportGlobalLog(e){globalMonitor.reportLog(e)}const monitorMap=new Map,getMonitor=e=>monitorMap.get(e),createMonitor=(e,t)=>{const i=new Monitor(e);return i.set({...t,engine_session_id:genUuid$1()}),i.report("sdk_init_engine",{start:Date.now(),type:"begin"}),monitorMap.set(e,i),i},destroyMonitor=e=>{e.report("sdk_init_engine",{start:Date.now(),type:"end"}),monitorMap.delete(e.id)},apiReportCache=new Map;function reportRtcSdkApi(e=[],t={}){t=Object.assign({debounce:0},t);const{debounce:i,debounceTag:r}=t;function o(e,t,r,o){if(!i)return t(...r);{const s=`${o}_${e}`,n=apiReportCache.get(s);clearTimeout(n);const a=setTimeout((()=>{t(...r)}),i);apiReportCache.set(s,a)}}return function(t,i,s){if("function"==typeof s.value){const t=s.value;s.value=function(...s){var n,a;const d=this.engineId||this.id,c=genUuid$1(),l={};e.forEach(((e,t)=>{l[e]=s[t]})),"joinRoom"===i&&(null==(a=getMonitor(d))||a.set({room_id:s[1],user_id:null==(n=s[2])?void 0:n.userId}));let u,_="";if(r)try{_=r(...s)}catch{}o(i,reportRtcSdkApiCall,[d,i,s,l,{event_session_id:c}],`start_${_}`);try{u=t.apply(this,s)}catch(e){throw o(i,reportRtcSdkCallback,[d,i,e.message,e.code||-1,{event_session_id:c}],`end_${_}`),e}return"function"==typeof(null==u?void 0:u.then)?u.then((e=>(o(i,reportRtcSdkCallback,[d,i,[e??{}],0,{event_session_id:c}],`end_${_}`),e))).catch((e=>{throw o(i,reportRtcSdkCallback,[d,i,e.message,e.code,{event_session_id:c}],`end_${_}`),e})):(o(i,reportRtcSdkCallback,[d,i,[u??{}],0,{event_session_id:c}],`end_${_}`),u)}}}}const reportRtcSdkApiCall=(e,t,i,r,o={})=>{var s;const n={sdk_api_name:t,message:JSON.stringify(reportParamsCheck(i)),error_code:0,...o};null==(s=getMonitor(e))||s.report("rtc_sdk_api_call",n,r)},reportRtcSdkCallback=(e,t,i,r=0,o={})=>{var s;const n={sdk_callback_name:t,error_code:r,message:JSON.stringify(Array.isArray(i)?reportParamsCheck(i):i),...o};null==(s=getMonitor(e))||s.report("rtc_sdk_callback",n)},reportRtcInvokeStatus=(e,t,i,r=0,o="",s)=>{var n;null==(n=getMonitor(e))||n.report("rtc_invoke_status",{sdk_api_name:t,message:i,error_code:r,stream_id:o,elapse:0},s)},maxBinaryLength=10;function reportParamsCheck(e){const t=e=>{if(null==e?void 0:e._reportName)return e._reportName;if(e instanceof HTMLElement)return e.toString();if(e instanceof ArrayBuffer||ArrayBuffer.isView(e)){const t=ArrayBuffer.isView(e)?e.buffer:e,i=t.byteLength;let r=[];if(i>maxBinaryLength){const e=new DataView(t),o=Array.from({length:maxBinaryLength/2}).map(((t,i)=>e.getUint8(i))),s=Array.from({length:maxBinaryLength/2}).map(((e,t)=>i-1-t)).reverse().map((t=>e.getUint8(t)));r=[...o,"...",...s]}else r=Array.from(new Uint8Array(t));return`${e.constructor.name}(${i}) [${r.join(", ")}]`}if(e instanceof ImageData)return"ImageData";if(Array.isArray(e))return e.map(t);if(["[object Object]","[object MediaStreamTrack]"].includes(Object.prototype.toString.call(e))){const i={};for(const r in e)i[r]=t(e[r]);return i}return e instanceof Function?"[User Function]":e};return e.map(t)}const ENABLE_CONSOLE_UPLOAD="undefined"!=typeof window&&window.location.search.includes("_rtc_upload_console_");class ConsoleReportor{constructor(){__publicField(this,"name","ConsoleReportor"),__publicField(this,"_uuid",`${Math.floor(899*Math.random())+100}`),__publicField(this,"_consoleReportId",0),__publicField(this,"_engineReportIdMap",new Map),__publicField(this,"_enabled","NULL"),__publicField(this,"_consoleCutLength",CoreConfig.getParameter("UPLOAD_CONSOLE_LENGTH_CUT")),__publicField(this,"buffer",[]),ENABLE_CONSOLE_UPLOAD&&setTimeout((()=>{this.switchOn()}),0),CoreConfig.on("UPLOAD_CONSOLE_ON",(e=>{e?this.switchOn():this.turnOff()})),CoreConfig.on("UPLOAD_CONSOLE_LENGTH_CUT",(e=>{this._consoleCutLength=e}))}get enabled(){return"OFF"!==this._enabled}switchOn(){"NULL"===this._enabled&&(console.log("[LoggerReportor.constructor] console upload switch ON"),this._enabled="ON")}turnOff(){"NULL"===this._enabled&&(console.log("[LoggerReportor.constructor] console upload switch OFF"),this._enabled="OFF",this.buffer=[])}getEngineConsoleId(e){const t=this._engineReportIdMap.get(e)??0;return this._engineReportIdMap.set(e,t+1),t}report(e,t,i,r,o,s,n,a,d){if("OFF"===this._enabled)return;const c=getMonitor(t),l=this._consoleReportId++,u=this.getEngineConsoleId(t),_=shallowJson(d,this._consoleCutLength),h=[...d],p=`${a}`.replace(/%o|%s/gi,(()=>shallowJson([h.shift()],this._consoleCutLength))),m=`[${this._uuid}-${l}][${t}-${u}]-${i}-${e}[${r}]${o}[${s}.${n}] ${p} ${_}`;c?c.reportLog(m):reportGlobalLog(m)}push(e){"OFF"!==this._enabled&&this.buffer.push(e)}splice(e){if("ON"!==this._enabled)return{payload:[],payloadSize:0};const{index:t,size:i}=findSizeIndex(this.buffer,e);return{payload:this.buffer.splice(0,t),payloadSize:i}}unshift(e){this.buffer=e.concat(this.buffer)}get(){return this.buffer}set(e){this.buffer=e.concat(this.buffer)}isEmpty(){return"OFF"===this._enabled||0===this.buffer.length}}function shallowJson(e,t){return e.map((e=>{let i="";try{if("string"==typeof e)return e;if(void 0===e)return"undefined";if(null===e)return"null";if(e instanceof MediaStreamTrack)return mediaTrackStringify(e);if(e instanceof MediaStream)return mediaStreamStringify(e);if(e instanceof RTCRtpSender)return mediaSenderStringify(e);if(e instanceof RTCRtpReceiver)return mediaReceiverStringify(e);if(e instanceof RTCRtpTransceiver)return mediaTransceiverStringify(e);i=JSON.stringify(e)}catch(t){i=e.toString()}return i&&i.length>=t&&(i=i.slice(0,t)),i})).join(", ")}function findSizeIndex(e,t){let i=0;for(let r=0;r<e.length;r++){const o=JSON.stringify(e[r]).length;if(i+=o,i>t)return{index:r,size:i-o}}return{index:e.length,size:i}}var consoleReportor=new ConsoleReportor;const HEAD_TEXT="[VERTC]",baseColor="#0050b3",colorMap={DEBUG:"rgba(0, 0, 0, 0)"," INFO":"rgba(93, 173, 226, 0)"," WARN":"rgba(255, 119, 0, 0.3)",ERROR:"rgba(255, 0, 0, 0.3)"," SUCC":"rgba(0, 119, 0, 0.3)"},DEBUG="undefined"!=typeof window&&(window.location.search.includes("_rtc_debug_")||(null==(_b=window.localStorage)?void 0:_b.getItem("_rtc_debug_")));class Logger{constructor(e,t,i="global"){__publicField(this,"indent"),__publicField(this,"module"),__publicField(this,"_engineId"),this.module=e,this.indent=t,this._engineId=i}_print(e,t,...i){const r=i.shift();try{const e=[...i],o=`${r}`.replace(/%o/gi,(()=>{const t=e.shift();return JSON.stringify(t)}));iDB.set(`[VERTC][${this.module}.${t}] ${o} ${e.map((e=>JSON.stringify(e))).join(", ")}`)}catch(e){}let o="";for(let e=0;e<this.indent;e++)o+=" ";const s=getTimestamp();consoleReportor.report("[VERTC]",this._engineId,s,e,o,this.module,t,r,i),DEBUG&&console.log(`%c${s}-[VERTC]%c[${e}]%c${o}[${this.module}.${t}] ${r}`,"color:#0050b3;",`background-color:${colorMap[e]};`,"color:#0050b3;",...i)}print(e,...t){this._print(" INFO",e,...t)}debug(e,...t){this._print("DEBUG",e,...t)}info(e,...t){this._print(" INFO",e,...t)}warn(e,...t){this._print(" WARN",e,...t)}error(e,...t){this._print("ERROR",e,...t)}success(e,...t){this._print(" SUCC",e,...t)}}const getTimestamp=()=>{const e=new Date;return`${e.toTimeString().split(" ")[0]}:${e.getMilliseconds().toString().padStart(3,"0")}`};var Logger$1=Logger;const isSSR=()=>"undefined"==typeof window,userAgentString=isSSR()?"":window.navigator.userAgent;function getBrowser(){let e="none";return isSSR()||(null!==userAgentString.match("Firefox")?e="mozilla":null!==userAgentString.match("Chrome")?(e="chrome-stable",null!==userAgentString.match("Electron")&&(e="electron")):(null!==userAgentString.match("Safari")||null!==userAgentString.match("AppleWebKit"))&&(e="safari")),e}const isFirefox="mozilla"===getBrowser(),isSafari="safari"===getBrowser(),isChrome="chrome-stable"===getBrowser(),isCriOS=!isSSR()&&/CriOS/i.test(userAgentString),isEdgeForDesktop=!isSSR()&&/Edg\//i.test(userAgentString),isEdgeForAndroid=!isSSR()&&/EdgA/i.test(userAgentString),isEdgeForIOS=!isSSR()&&/EdgiOS/i.test(userAgentString),isEdge=isEdgeForDesktop||isEdgeForAndroid||isEdgeForIOS,isDingTalk=!isSSR()&&/DingTalk/i.test(navigator.userAgent),isOpera=!isSSR()&&/OPR\//.test(navigator.userAgent),isIPad=!isSSR()&&(!!/(iPad)/i.exec(userAgentString)||/Macintosh/i.test(userAgentString)&&"ontouchend"in document),isMac=!isSSR()&&/Macintosh/i.test(userAgentString),isWeChat=!isSSR()&&/MicroMessenger/i.test(userAgentString),isMobile=!isSSR()&&userAgentString.toLowerCase().includes("mobile"),isIOS=!isSSR()&&!!/(iPhone|iPad|iPod)/i.exec(userAgentString),isAndroid=!isSSR()&&/Android/i.test(userAgentString),isWindows=!isSSR()&&/Windows/i.test(userAgentString),isOpenHarmony=!isSSR()&&/OpenHarmony/i.test(userAgentString);let sv=0,sv2="0";const v=!isSSR()&&(null==(_c=userAgentString.match(/version\/(\d+)/i))?void 0:_c[1]);isSafari&&v&&(sv=Number(v),sv2=null==(_d=navigator.userAgent.match(/version\/(\d+\.\d+)/i))?void 0:_d[1]);const v2=!isSSR()&&(null==(_e=userAgentString.match(/Firefox\/(\d+)/i))?void 0:_e[1]);isFirefox&&v2&&(sv=Number(v2));const safariVersion=sv,firefoxVersion=sv,safariMinorVersion=sv2,iOSVersion=(!isSSR()&&(null==(_g=null==(_f=userAgentString.match(/ ([\d_]+) like Mac OS X/i))?void 0:_f[1])?void 0:_g.split("_").map((e=>parseInt(e)))))??[];let cv=0;const cvs=!isSSR()&&(null==(_h=userAgentString.match(/Chrome\/(\d+)/i))?void 0:_h[1]);cvs&&(cv=Number(cvs));const chromeVersion=cv,PLATFORM_KEY="VolcEngine",RTC_DEVICE_ID="RTC_DEVICE_ID",RTC_ACCESS_NODE="RTC_ACCESS_NODE",RTC_ACCESS_URLS="RTC_ACCESS_URLS",ENGINE_WEB_CONFIG="ENGINE_WEB_CONFIG",SERVER_CONFIG="SERVER_CONFIG";class Cache{get(e){const t=localStorage.getItem(e);if(!t)return null;try{const i=JSON.parse(t);return i.ttl>0&&Date.now()-i.saveTime>i.ttl?(this.delete(e),null):i.message}catch(e){return null}}set(e,t,i=-1){const r={ttl:i,saveTime:Date.now(),message:t};try{return localStorage.setItem(e,JSON.stringify(r)),!0}catch(e){return!1}}getTtl(e){const t=localStorage.getItem(e);if(!t)return null;try{return JSON.parse(t).ttl}catch(e){return null}}delete(e){try{return localStorage.removeItem(e),!0}catch(e){return!1}}}class SDKCache extends Cache{constructor(){super(...arguments),__publicField(this,"_accessVersion","v2")}getDeviceId(){if(isSSR())return"";let e=this.get(RTC_DEVICE_ID);return e&&!/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(e)||(e=randomNum(16)),this.setDeviceId(e),e}setDeviceId(e){return setGlobalStats({device_id:e}),this.set(RTC_DEVICE_ID,e),e}getAccessKey(e){return`${RTC_ACCESS_NODE}_${e}-${PLATFORM_KEY}-${this._accessVersion}`}getAccessNode(e){return this.get(this.getAccessKey(e))}setAccessNode(e,t,i){return this.set(this.getAccessKey(e),t,1e3*i)}deleteAccessNode(e,t){let i=this.getAccessNode(e);const r=this.getTtl(this.getAccessKey(e));Array.isArray(i)&&i.length>0&&(i=i.filter((e=>e.mediaID!==t.mediaID&&e.msgKey!==t.msgKey)),i.length>0?this.setAccessNode(e,i,r||0):this.clearAccessNode(e))}clearAccessNode(e){if(e)this.delete(this.getAccessKey(e));else for(const e in localStorage)e.startsWith(RTC_ACCESS_NODE)&&localStorage.removeItem(e)}getAccessUrls(){return this.get(`${RTC_ACCESS_URLS}-${PLATFORM_KEY}`)}setAccessUrls(e){const t=e.map((({host:e,path:t})=>`https://${e}${t}`));return this.set(`${RTC_ACCESS_URLS}-${PLATFORM_KEY}`,t)}clearAccessUrls(){this.delete(`${RTC_ACCESS_URLS}-${PLATFORM_KEY}`)}getEngineWebConfig(e,t){var i;const r=`${e}_${t}_${this.getDeviceId()}`,o=this.get(ENGINE_WEB_CONFIG),s=(null==(i=null==o?void 0:o.find((e=>e.key===r)))?void 0:i.config)||{};return Object.assign({},getParameter("ENGINE_WEB_CONFIG"),s)}setEngineWebConfig(e,t,i){if(!i)return;const r=`${e}_${t}_${this.getDeviceId()}`;let o=this.get(ENGINE_WEB_CONFIG)||[];return o=o.filter((e=>e.key!==r)),o.push({key:r,config:i}),this.set(ENGINE_WEB_CONFIG,o.slice(-5))}getServerConfig(e){var t;const i=`${e}`,r=this.get(SERVER_CONFIG);return(null==(t=null==r?void 0:r.find((e=>e.key===i)))?void 0:t.config)||{}}setServerConfig(e,t){if(!t)return;const i=`${e}`;let r=this.get(SERVER_CONFIG)||[];return r=r.filter((e=>e.key!==i)),r.push({key:i,config:t}),this.set(SERVER_CONFIG,r.slice(-5))}}var sdkCache=new SDKCache;const logger$b=new Logger$1("JoinRoomConfig",0),_JoinRoomConfig=class{constructor(e){__publicField(this,"_useTcpAfterJoinTimeout",_JoinRoomConfig.DEFAULT_CONF.useTcpAfterJoinTimeout),__publicField(this,"_joinWithTcpOnly",_JoinRoomConfig.DEFAULT_CONF.joinWithTcpOnly),__publicField(this,"_joinWithTcpOnlyDelay",_JoinRoomConfig.DEFAULT_CONF.joinWithTcpOnlyDelay),__publicField(this,"_blackBrowserRegexList",[]),this._engineId=e,location.search.indexOf("__rtc_tcp_only__")>-1&&(this._joinWithTcpOnly=!0,this._joinWithTcpOnlyDelay=0),this._report()}static setDefaulConf({useTcpAfterJoinTimeout:e,joinWithTcpOnly:t,joinWithTcpOnlyDelay:i}){return"boolean"==typeof e&&(_JoinRoomConfig.DEFAULT_CONF.useTcpAfterJoinTimeout=e),"boolean"==typeof t&&(_JoinRoomConfig.DEFAULT_CONF.joinWithTcpOnly=t),"number"==typeof i&&(_JoinRoomConfig.DEFAULT_CONF.joinWithTcpOnlyDelay=Math.max(0,i)),_JoinRoomConfig.DEFAULT_CONF}get useTcpAfterJoinTimeout(){return this._useTcpAfterJoinTimeout}get useTcpJoin(){return this._joinWithTcpOnly}get useTcpJoinDelay(){return this._joinWithTcpOnlyDelay}isBlackBrower(){return this._blackBrowserRegexList.find((e=>new RegExp(e).test(navigator.userAgent)))}setServerConfig(e){var t,i,r;let o=!1;"boolean"==typeof(null==(t=null==e?void 0:e.use_tcp_after_join_timeout)?void 0:t.enable)&&(this._useTcpAfterJoinTimeout=e.use_tcp_after_join_timeout.enable,o=!0),"boolean"==typeof(null==(i=null==e?void 0:e.join_with_tcp_only)?void 0:i.enable)&&(this._joinWithTcpOnly=e.join_with_tcp_only.enable,o=!0),"number"==typeof(null==(r=null==e?void 0:e.join_with_tcp_only)?void 0:r.delay_ms)&&(this._joinWithTcpOnlyDelay=e.join_with_tcp_only.delay_ms,o=!0),e&&Array.isArray(e.black_browser_regex_list)&&(this._blackBrowserRegexList=e.black_browser_regex_list,o=!0),o&&this._report()}toString(){return JSON.stringify({use_tcp_after_join_timeout:this._useTcpAfterJoinTimeout,join_with_tcp_only:this._joinWithTcpOnly,join_with_tcp_only_delay:this._joinWithTcpOnlyDelay,black_browser_regex_list:this._blackBrowserRegexList})}_report(){logger$b.print("_report",this.toString()),reportRtcInvokeStatus(this._engineId,"web_join_room_config",this.toString())}};let JoinRoomConfig=_JoinRoomConfig;__publicField(JoinRoomConfig,"DEFAULT_CONF",{useTcpAfterJoinTimeout:!0,joinWithTcpOnly:!1,joinWithTcpOnlyDelay:5e3});var ErrorCode=(e=>(e.INVALID_ENGINE="INVALID_ENGINE",e.INVALID_PARAMS="INVALID_PARAMS",e.INVOKED_BEFORE_JOIN_ROOM="INVOKED_BEFORE_JOIN_ROOM",e.INVALID_TOKEN="INVALID_TOKEN",e.JOIN_ROOM_FAILED="JOIN_ROOM_FAILED",e.UPDATE_TOKEN_WITH_INVALID_TOKEN="UPDATE_TOKEN_WITH_INVALID_TOKEN",e.UPDATE_TOKEN_BEFORE_JOIN="UPDATE_TOKEN_BEFORE_JOIN",e.REPEAT_JOIN="REPEAT_JOIN",e.REPEAT_PUBLISH="REPEAT_PUBLISH",e.REPEAT_PUSH="REPEAT_PUSH",e.REPEAT_PLAY="REPEAT_PLAY",e.PUBLISH_BEFORE_JOIN="PUBLISH_BEFORE_JOIN",e.UNPUBLISH_BEFORE_JOIN="UNPUBLISH_BEFORE_JOIN",e.SUBSCRIBE_BEFORE_JOIN="SUBSCRIBE_BEFORE_JOIN",e.UNSUBSCRIBE_BEFORE_JOIN="UNSUBSCRIBE_BEFORE_JOIN",e.NO_PUBLISH_PERMISSION="NO_PUBLISH_PERMISSION",e.STREAM_NOT_EXIST="STREAM_NOT_EXIST",e.EMPTY_STREAM="EMPTY_STREAM",e.NOT_CONNECTED_YET="NOT_CONNECTED_YET",e.IM_BEFORE_JOIN="IM_BEFORE_JOIN",e.USER_NOT_EXIST="USER_NOT_EXIST",e.ALREADY_IN_ROOM="ALREADY_IN_ROOM",e.KICKED_OUT="KICKED_OUT",e.ROOM_DISMISS="ROOM_DISMISS",e.TOKEN_EXPIRED="TOKEN_EXPIRED",e.TOKEN_NO_PUBLISH_PERMISSION="TOKEN_NO_PUBLISH_PERMISSION",e.TOKEN_NO_SUBSCRIBE_PERMISSION="TOKEN_NO_SUBSCRIBE_PERMISSION",e.DUPLICATE_LOGIN="DUPLICATE_LOGIN",e.INVOKED_BEFORE_CAPTURE="INVOKED_BEFORE_CAPTURE",e.REPEAT_CAPTURE="REPEAT_CAPTURE",e.GET_VIDEO_TRACK_FAILED="GET_VIDEO_TRACK_FAILED",e.GET_AUDIO_TRACK_FAILED="GET_AUDIO_TRACK_FAILED",e.GET_SCREEN_TRACK_FAILED="GET_SCREEN_TRACK_FAILED",e.STREAM_TYPE_NOT_MATCH="STREAM_TYPE_NOT_MATCH",e.CANT_FIND_DOM="CANT_FIND_DOM",e.INVALID_DEVICE_ID="INVALID_DEVICE_ID",e.NO_PERMISSION="NO_PERMISSION",e.NOT_SUPPORTED="NOT_SUPPORTED",e.INTERRUPT="INTERRUPT",e.ICE_SERVER_WRONG="ICE_SERVER_WRONG",e.ESTABLISH_DATACHANNEL_FAILED="ESTABLISH_DATACHANNEL_FAILED",e.LOAD_RESOURCES_FAILED="LOAD_RESOURCES_FAILED",e.SIGNALING_CHANNEL_NOT_OPEN="SIGNALING_CHANNEL_NOT_OPEN",e.TIME_OUT="TIME_OUT",e.REFUSE_OPERATION_IN_DISCONNECT="REFUSE_OPERATION_IN_DISCONNECT",e.ADD_TRANSCEIVER_FAILED="ADD_TRANSCEIVER_FAILED",e.UPDATE_TRACK_FAILED="UPDATE_TRACK_FAILED",e.PUBLISH_FAILED="PUBLISH_FAILED",e.UNPUBLISH_FAILED="UNPUBLISH_FAILED",e.SUBSCRIBE_FAILED="SUBSCRIBE_FAILED",e.UNSUBSCRIBE_FAILED="UNSUBSCRIBE_FAILED",e.OPERATION_CANCEL="OPERATION_CANCEL",e.START_CLOUD_PROXY_AFTER_JOIN="START_CLOUD_PROXY_AFTER_JOIN",e.STOP_CLOUD_PROXY_BEFORE_LEAVE="STOP_CLOUD_PROXY_BEFORE_LEAVE",e.UNEXPECTED_ERROR="UNEXPECTED_ERROR",e.REPEAT_DEVICE_TEST="REPEAT_DEVICE_TEST",e.AUDIO_DEVICE_TEST_FAILED="AUDIO_DEVICE_RECORD_FAILED",e.ALREADY_LOGIN="ALREADY_LOGIN",e.LOGIN_FAILED="LOGIN_FAILED",e.NOT_LOGIN="NOT_LOGIN",e.RTM_DUPLICATE_LOGIN="RTM_DUPLICATE_LOGIN",e.RTM_TOKEN_ERROR="RTM_TOKEN_ERROR",e.USER_MESSAGE_TIMEOUT="USER_MESSAGE_TIMEOUT",e.USER_MESSAGE_BROKEN="USER_MESSAGE_BROKEN",e.USER_MESSAGE_NO_RECEIVER="USER_MESSAGE_NO_RECEIVER",e.USER_MESSAGE_NO_RELAYPATH="USER_MESSAGE_NO_RELAYPATH",e.USER_MESSAGE_EXCEED_QPS="USER_MESSAGE_EXCEED_QPS",e.USER_MESSAGE_SEND_TO_SERVER_ERROR="USER_MESSAGE_SEND_TO_SERVER_ERROR",e.USER_MESSAGE_SERVER_RESPONSE_ERROR="USER_MESSAGE_SERVER_RESPONSE_ERROR",e.USER_MESSAGE_NOT_JOIN="USER_MESSAGE_NOT_JOIN",e.USER_MESSAGE_INIT="USER_MESSAGE_INIT",e.USER_MESSAGE_NO_CONNECTION="USER_MESSAGE_NO_CONNECTION",e.USER_MESSAGE_NOT_LOGIN="USER_MESSAGE_NOT_LOGIN",e.USER_MESSAGE_SERVER_PARAMS_NOTSET="USER_MESSAGE_SERVER_PARAMS_NOTSET",e.USER_MESSAGE_UNKNOWN="USER_MESSAGE_UNKNOWN",e.START_PUBLIC_STREAM_BEFORE_JOIN="START_PUBLIC_STREAM_BEFORE_JOIN",e.RECONNECT_FAILED="RECONNECT_FAILED",e.SUBTITLE_ALREADY_ON="SUBTITLE_ALREADY_ON",e.SUBTITLE_NOT_TURNED_ON="SUBTITLE_NOT_TURNED_ON",e.SUBTITLE_ERR_POSTPROCESS="SUBTITLE_ERR_POSTPROCESS",e.SUBTITLE_ERR_CONNECTION_ERROR="SUBTITLE_ERR_CONNECTION_ERROR",e.SUBTITLE_ERR_PROCESS_ERROR="SUBTITLE_ERR_PROCESS_ERROR",e.SUBTITLE_ERR_UNKNOWN="SUBTITLE_ERR_UNKNOWN",e.UNEXPECTED_INVOKE_FORWARD_STREAM="UNEXPECTED_INVOKE_FORWARD_STREAM",e.ROOM_FORBIDDEN="ROOM_FORBIDDEN",e.USER_FORBIDDEN="USER_FORBIDDEN",e.ERR_ELECTRON_IS_NULL="ERR_ELECTRON_IS_NULL",e.ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR="ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR",e.SET_SIMULCAST_FAILED="SET_SIMULCAST_FAILED",e.MIXING_OLD_AND_NEW_APIS="MIXING_OLD_AND_NEW_APIS",e.WTN_PUSH_FAILED="WTN_PUSH_FAILED",e.WTN_PLAY_FAILED="WTN_PLAY_FAILED",e.NOT_ALLOWED_IN_RTS_ROOM="NOT_ALLOWED_IN_RTS_ROOM",e.NOT_ALLOWED_IN_RESTRICTED_MODE="NOT_ALLOWED_IN_RESTRICTED_MODE",e))(ErrorCode||{}),AudioMixingError=(e=>(e[e.AUDIO_MIXING_ERROR_OK=0]="AUDIO_MIXING_ERROR_OK",e[e.AUDIO_MIXING_ERROR_PRELOAD_FAILED=1]="AUDIO_MIXING_ERROR_PRELOAD_FAILED",e[e.AUDIO_MIXING_ERROR_START_FAILED=2]="AUDIO_MIXING_ERROR_START_FAILED",e[e.AUDIO_MIXING_ERROR_ID_NOT_FOUND=3]="AUDIO_MIXING_ERROR_ID_NOT_FOUND",e[e.AUDIO_MIXING_ERROR_SET_POSITION_FAILED=4]="AUDIO_MIXING_ERROR_SET_POSITION_FAILED",e[e.AUDIO_MIXING_ERROR_INVALID_VOLUME=5]="AUDIO_MIXING_ERROR_INVALID_VOLUME",e[e.AUDIO_MIXING_ERROR_LOAD_CONFLICT=6]="AUDIO_MIXING_ERROR_LOAD_CONFLICT",e[e.AUDIO_MIXING_ERROR_ID_TYPE_NOT_MATCH=7]="AUDIO_MIXING_ERROR_ID_TYPE_NOT_MATCH",e[e.AUDIO_MIXING_ERROR_ID_TYPE_INVALID_PITCH=8]="AUDIO_MIXING_ERROR_ID_TYPE_INVALID_PITCH",e[e.AUDIO_MIXING_ERROR_INVALID_AUDIO_TRACK=9]="AUDIO_MIXING_ERROR_INVALID_AUDIO_TRACK",e))(AudioMixingError||{});class SDKError extends Error{constructor(e,t,i){super(t),__publicField(this,"code"),__publicField(this,"message"),__publicField(this,"error"),this.code=e,this.message=t,this.error=i,Object.setPrototypeOf(this,SDKError.prototype)}toString(){return`SDKError: ${this.code} ${this.message}`}}var EngineEventsTypes=(e=>(e.onTrackEnded="onTrackEnded",e.onTrackMute="onTrackMute",e.onTrackUnmute="onTrackUnmute",e.onPlayerEvent="onPlayerEvent",e.onAutoplayFailed="onAutoplayFailed",e.onUserJoined="onUserJoined",e.onUserLeave="onUserLeave",e.onConnectionStateChanged="onConnectionStateChanged",e.onUserPublishStream="onUserPublishStream",e.onUserUnpublishStream="onUserUnpublishStream",e.onUserPublishScreen="onUserPublishScreen",e.onUserUnpublishScreen="onUserUnpublishScreen",e.onRoomMessageReceived="onRoomMessageReceived",e.onRoomBinaryMessageReceived="onRoomBinaryMessageReceived",e.onUserMessageReceived="onUserMessageReceived",e.onUserBinaryMessageReceived="onUserBinaryMessageReceived",e.onVideoFirstFrameRendered="onVideoFirstFrameRendered",e.onVideoFirstFrameDecoded="onVideoFirstFrameDecoded",e.onRemoteVideoFirstFrame="onRemoteVideoFirstFrame",e.onAudioFirstFrameDecoded="onAudioFirstFrameDecoded",e.onRemoteAudioFirstFrame="onRemoteAudioFirstFrame",e.onFirstPublicStreamVideoFrameRendered="onFirstPublicStreamVideoFrameRendered",e.onFirstPublicStreamVideoFrameDecoded="onFirstPublicStreamVideoFrameDecoded",e.onFirstPublicStreamAudioFrameDecoded="onFirstPublicStreamAudioFrameDecoded",e.onVideoDeviceStateChanged="onVideoDeviceStateChanged",e.onAudioDeviceStateChanged="onAudioDeviceStateChanged",e.onRemoteStreamStats="onRemoteStreamStats",e.onPublicStreamStats="onPublicStreamStats",e.onLocalStreamStats="onLocalStreamStats",e.onAudioVolumeIndication="onAudioVolumeIndication",e.onLocalAudioPropertiesReport="onLocalAudioPropertiesReport",e.onRemoteAudioPropertiesReport="onRemoteAudioPropertiesReport",e.onActiveSpeaker="onActiveSpeaker",e.onAudioPlaybackDeviceChanged="onAudioPlaybackDeviceChanged",e.onUserStartVideoCapture="onUserStartVideoCapture",e.onUserStopVideoCapture="onUserStopVideoCapture",e.onUserStartAudioCapture="onUserStartAudioCapture",e.onUserStopAudioCapture="onUserStopAudioCapture",e.onAutoPublishResult="onAutoPublishResult",e.onAutoSubscribeResult="onAutoSubscribeResult",e.onLiveTranscodingResult="onLiveTranscodingResult",e.onStreamMixingEvent="onStreamMixingEvent",e.onAudioPlaybackDeviceTestVolume="onAudioPlaybackDeviceTestVolume",e.onSEIMessageReceived="onSEIMessageReceived",e.onError="onError",e.onAudioMixingStateChanged="onAudioMixingStateChanged",e.onUserMessageReceivedOutsideRoom="onUserMessageReceivedOutsideRoom",e.onUserBinaryMessageReceivedOutsideRoom="onUserBinaryMessageReceivedOutsideRoom",e.onTokenWillExpire="onTokenWillExpire",e.onTokenPublishPrivilegeWillExpire="onTokenPublishPrivilegeWillExpire",e.onTokenPublishPrivilegeDidExpired="onTokenPublishPrivilegeDidExpired",e.onTokenSubscribePrivilegeWillExpire="onTokenSubscribePrivilegeWillExpire",e.onTokenSubscribePrivilegeDidExpired="onTokenSubscribePrivilegeDidExpired",e.onCloudProxyConnected="onCloudProxyConnected",e.onPushPublicStreamResult="onPushPublicStreamResult",e.onPublicStreamSEIMessageReceived="onPublicStreamSEIMessageReceived",e.onNetworkQuality="onNetworkQuality",e.onSimulcastSubscribeFallback="onSimulcastSubscribeFallback",e.onRemoteVideoSizeChanged="onRemoteVideoSizeChanged",e.onVideoStreamBanned="onVideoStreamBanned",e.onAudioStreamBanned="onAudioStreamBanned",e.onLocalVideoSizeChanged="onLocalVideoSizeChanged",e.onSubtitleStateChanged="onSubtitleStateChanged",e.onSubtitleMessageReceived="onSubtitleMessageReceived",e.onServerParamsSetResult="onServerParamsSetResult",e.onLocalStreamTrackChangedByExtension="onLocalStreamTrackChangedByExtension",e.onVendorConnectionStateChanged="onVendorConnectionStateChanged",e.onForwardStreamError="onForwardStreamError",e.onRejoinWithTcp="onRejoinWithTcp",e.onIceConnectWithTcp="onIceConnectWithTcp",e.onPublishRetry="onPublishRetry",e.onSubscribeRetry="onSubscribeRetry",e.onPublishResult="onPublishResult",e.onSubscribeResult="onSubscribeResult",e.onSEIStreamUpdate="onSEIStreamUpdate",e))(EngineEventsTypes||{});function checkBoolean(e,t){if("boolean"!=typeof e)throw new SDKError(ErrorCode.INVALID_PARAMS,`Invalid ${t}: The value should be boolean type.`)}const checkVideoFrameCallback=()=>!isSSR$1()&&"function"==typeof HTMLVideoElement.prototype.requestVideoFrameCallback;function checkNumber(e,t,i=1,r=Number.POSITIVE_INFINITY){if(e<i||e>r||"number"!=typeof e){throw new SDKError(ErrorCode.INVALID_PARAMS,`Invalid ${t}: the value range is [${i}, ${r}]. integer only`)}}function checkString(e,t,i=1,r=Number.POSITIVE_INFINITY){if(null==e)throw new SDKError(ErrorCode.INVALID_PARAMS,`${t} cannot be empty`);if(!isValidString(e,i,r))throw new SDKError(ErrorCode.INVALID_PARAMS,`Invalid ${t}: The value should be string type. Length of the string: [${i},${r}]`)}function checkEnum(e,t,i){if(!i.includes(e))throw new SDKError(ErrorCode.INVALID_PARAMS,`Invalid ${t}: The value can only be set as ${JSON.stringify(i)}`)}function checkMediaStreamTrack(e){if(!(e instanceof MediaStreamTrack))throw new SDKError(ErrorCode.INVALID_PARAMS,"Invalid track, The value should be MediaStreamTrack type.")}function checkEmpty(e,t){if(isEmpty(e))throw new SDKError(ErrorCode.INVALID_PARAMS,`Invalid ${t}, should not be empty`)}function checkArray(e,t){if(!Array.isArray(e))throw new SDKError(ErrorCode.INVALID_PARAMS,`Invalid ${t}, should be array`)}function checkArrayBuffer(e,t){if(!(e instanceof ArrayBuffer))throw new SDKError(ErrorCode.INVALID_PARAMS,`Invalid ${t}, should be ArrayBuffer`)}function checkSupportedConstraints(e){try{const t=navigator.mediaDevices.getSupportedConstraints();for(const i of Object.keys(e))t[i]||delete e[i]}catch(e){}}function isValidString(e,t=1,i=Number.POSITIVE_INFINITY){return"string"==typeof e&&e.length<=i&&e.length>=t}function isEmpty(e){return null==e}function checkRoomId(e){if("string"!=typeof e||!/^[a-zA-Z0-9@._-]{1,128}$/.test(e))throw new SDKError(ErrorCode.INVALID_PARAMS,"The RoomId must be within 128 bytes. The supported characters: a-z,A-Z,0-9,@,-,_,.")}function checkUserId(e){if("string"!=typeof e||!/^[a-zA-Z0-9@._-]{1,128}$/.test(e))throw new SDKError(ErrorCode.INVALID_PARAMS,"The userId must be within 128 bytes. The supported characters: a-z,A-Z,0-9,@,-,_,.")}function checkPublicStreamId(e){if("string"!=typeof e||!/^[a-zA-Z0-9@._-]{1,128}$/.test(e))throw new SDKError(ErrorCode.INVALID_PARAMS,"The publicStreamId must be within 128 bytes. The supported characters: a-z,A-Z,0-9,@,-,_,.")}function illegalBusinessId(e){return"string"!=typeof e}function checkUserInfo(e){checkEmpty(e,"userInfo"),checkUserId(e.userId),isEmpty(e.extraInfo)||checkString(e.extraInfo,"userInfo.extraInfo",1,200)}function checkRoomConfig(e){checkEmpty(e,"roomConfig"),checkBoolean(e.isAutoPublish,"roomConfig.isAutoPublish"),checkBoolean(e.isAutoSubscribeAudio,"roomConfig.isAutoSubscribeAudio"),checkBoolean(e.isAutoSubscribeVideo,"roomConfig.isAutoSubscribeVideo"),isEmpty(e.roomProfileType)||checkEnum(e.roomProfileType,"roomConfig",[RoomProfileType.communication,RoomProfileType.chat,RoomProfileType.chatRoom,RoomProfileType.coHost,RoomProfileType.meeting,RoomProfileType.classRoom])}function checkVideoPlayerOption(e){checkEmpty(e,"videoPlayerOption")}function checkBufferSize(e,t=64){if(!e||0===(null==e?void 0:e.byteLength))throw new SDKError(ErrorCode.INVALID_PARAMS,"The message cannot be empty");let i;if(e instanceof ArrayBuffer)i=e;else{if("string"!=typeof e)throw new SDKError(ErrorCode.INVALID_PARAMS,"The message must be string or ArrayBuffer");i=Utils.str2ab(e)}if((null==i?void 0:i.byteLength)>1024*t)throw new SDKError(ErrorCode.INVALID_PARAMS,`The message length must be less than ${t}KB`);return i.byteLength??0}function isReportCallback(e){const t=getParameter("FORCE_ENABLED_REPORT_CALLBACKS");if(null==t?void 0:t.includes(e))return!0;if(e===EngineEventsTypes.onRemoteStreamStats){if(!!getParameter("UPLOAD_REMOTE_STATS"))return!0}return![EngineEventsTypes.onRemoteStreamStats,EngineEventsTypes.onLocalStreamStats,EngineEventsTypes.onAudioVolumeIndication,EngineEventsTypes.onLocalAudioPropertiesReport,EngineEventsTypes.onRemoteAudioPropertiesReport].includes(e)}function checkRemoteConfig(e){if("number"!=typeof(null==e?void 0:e.width)||"number"!=typeof(null==e?void 0:e.height))throw new SDKError(ErrorCode.INVALID_PARAMS,"remoteVideoConfig must contain width, height, frameRate")}function checkConstrainULongg(e,t){if("number"==typeof e&&!Number.isNaN(e)&&e>=1)return;const i=e;if(!((null==i?void 0:i.min)||(null==i?void 0:i.max)||(null==i?void 0:i.exact)||(null==i?void 0:i.ideal)))throw new SDKError(ErrorCode.INVALID_PARAMS,`${t} is not a valid ConstrainULong`)}function checkVideoEncoderConfig(e){checkArray(e,"videoEncoderConfig");for(const t of e)checkEmpty(t,"videoEncoderConfigItem"),checkNumber(null==t?void 0:t.maxKbps,"maxKbps"),checkConstrainULongg(null==t?void 0:t.width,"width"),checkConstrainULongg(null==t?void 0:t.height,"height"),checkConstrainULongg(null==t?void 0:t.frameRate,"frameRate")}function numberRangeGuide(e,t,i=Number.NEGATIVE_INFINITY,r=Number.POSITIVE_INFINITY){return checkNumber(e,t,Number.NEGATIVE_INFINITY,Number.POSITIVE_INFINITY),e=(e=e>i?e:i)<r?e:r}function checkAudioAndVideoDeviceId(e,t){let i;return isEmpty(t)||checkString(t,"videoDeviceId"),isEmpty(e)||("string"==typeof e?(checkString(e,"audioDeviceId"),i=e):(i=null==e?void 0:e.audioDeviceId,t=null==e?void 0:e.videoDeviceId,checkString(i,"audioDeviceId"),checkString(t,"videoDeviceId"))),{audioDeviceId:i,videoDeviceId:t}}var ExtendMediaType=(e=>(e[e.NONE=0]="NONE",e))(ExtendMediaType||{}),VideoCodecName=(e=>(e.H264="H264",e.VP8="VP8",e.ByteVC1="ByteVC1",e))(VideoCodecName||{});const isSupported=async()=>{try{return!(isSSR()||!window.RTCPeerConnection||!window.RTCPeerConnection.prototype.addTransceiver||!window.RTCPeerConnection.prototype.createDataChannel)&&(await isH264DecodeSupported()&&await isH264EncodeSupported())}catch(e){return!1}},internalGetSupportedCodecs=async()=>{const e=[];return await isH265DecodeSupported()&&await isH265EncodeSupported()&&e.push(VideoCodecName.ByteVC1),await isH264DecodeSupported()&&await isH264EncodeSupported()&&e.push(VideoCodecName.H264),await isVP8DecodeSupported()&&await isVP8EncodeSupported()&&e.push(VideoCodecName.VP8),e},getSupportedCodecs=async()=>(await internalGetSupportedCodecs()).map((e=>e===VideoCodecName.ByteVC1?"H265":e.toUpperCase())),hasHardwareEncodeProfile=()=>{let e=!1;if("function"==typeof RTCRtpSender.getCapabilities){const{codecs:t}=RTCRtpSender.getCapabilities("video")||{};t&&t.length>0&&t.forEach((t=>{var i;((null==(i=null==t?void 0:t.sdpFmtpLine)?void 0:i.indexOf("profile-level-id=42001f"))??-1)>-1&&(e=!0)}))}return e},codecsSupportMap={};function supportH264(e){const t=e.split("\n");let i=!1;for(const e of t)if(e.includes("level-asymmetry-allowed=1")&&e.includes("packetization-mode=1")&&e.includes("profile-level-id=42e0")){i=!0;break}if(i){const e=navigator.userAgent.toLowerCase();let t=!1;const i=[/miuibrowser/,/70.*HeyTapBrowser/i];for(const r of i)r.test(e)&&(t=!0);return!t}return!1}const createOfferSdp=async e=>{const t=new RTCPeerConnection;t.addTransceiver("video",{direction:e});const i=await t.createOffer();return t.close(),i.sdp.toLowerCase()},checkCodecsEncodeSupport=async()=>{let e=await createOfferSdp("sendonly");return navigator.userAgent.includes("VivoBrowser")&&(e=await createOfferSdp("sendonly")),codecsSupportMap.h264encode=supportH264(e),codecsSupportMap.vp8encode=e.indexOf("vp8")>-1,codecsSupportMap.h265encode=e.indexOf("h265")>-1,codecsSupportMap},checkCodecsDecodeSupport=async()=>{let e=await createOfferSdp("recvonly");return navigator.userAgent.includes("VivoBrowser")&&(e=await createOfferSdp("recvonly")),codecsSupportMap.h264decode=supportH264(e),codecsSupportMap.vp8decode=e.indexOf("vp8")>-1,codecsSupportMap.h265decode=e.indexOf("h265")>-1,codecsSupportMap},isH264EncodeSupported=async()=>{if(void 0===codecsSupportMap.h264encode)try{await checkCodecsEncodeSupport()}catch{return!1}return codecsSupportMap.h264encode||!1},isH264DecodeSupported=async()=>{if(void 0===codecsSupportMap.h264decode)try{await checkCodecsDecodeSupport()}catch{return!1}return codecsSupportMap.h264decode||!1},isVP8EncodeSupported=async()=>{if(void 0===codecsSupportMap.vp8encode)try{await checkCodecsEncodeSupport()}catch{return!1}return codecsSupportMap.vp8encode||!1},isVP8DecodeSupported=async()=>{if(void 0===codecsSupportMap.vp8decode)try{await checkCodecsDecodeSupport()}catch{return!1}return codecsSupportMap.vp8decode||!1},isH265EncodeSupported=async()=>{if(void 0===codecsSupportMap.h265encode)try{await checkCodecsEncodeSupport()}catch{return!1}return codecsSupportMap.h265encode||!1},isH265DecodeSupported=async()=>{if(void 0===codecsSupportMap.h265decode)try{await checkCodecsDecodeSupport()}catch{return!1}return codecsSupportMap.h265decode||!1},isEncodedTransformSupported=()=>"undefined"!=typeof TransformStream&&"undefined"!=typeof RTCRtpSender&&"undefined"!=typeof RTCRtpReceiver&&"undefined"!=typeof RTCRtpScriptTransform&&"transform"in RTCRtpSender.prototype&&"transform"in RTCRtpReceiver.prototype&&isWorkerSupported()&&isMessageChannelSupported(),isLegacyEncodedTransformSupported=()=>"undefined"!=typeof TransformStream&&"undefined"!=typeof RTCRtpSender&&"undefined"!=typeof RTCRtpReceiver&&void 0!==RTCRtpSender.prototype.createEncodedStreams&&void 0!==RTCRtpReceiver.prototype.createEncodedStreams,isWebAudioSupported=()=>isMac?isChrome&&chromeVersion>=70||isFirefox&&firefoxVersion>=80||isSafari&&safariVersion>=14:isWindows?isChrome&&chromeVersion>=70||isFirefox&&firefoxVersion>=80:isIOS?iOSVersion[0]>=14:!(!isAndroid&&!isOpenHarmony)&&(isChrome&&chromeVersion>=86),isStatsCallbackSupport=isChrome&&chromeVersion<=114,isTransportCCSupport=!isFirefox||firefoxVersion>=96,isRRTRSupported=!(isSafari&&safariVersion<=14),unsupportedSimultaneousCapture=isAndroid&&isChrome||isIOS&&iOSVersion[0]>=16,isSimulcastSupported=()=>!isFirefox&&!isOpera&&14!==(null==iOSVersion?void 0:iOSVersion[0]),isComputePressureSupported="undefined"!=typeof globalThis&&"PressureObserver"in globalThis,isWorkerSupported=()=>"undefined"!=typeof window&&window.Worker,notSupport48k=isSafari&&safariVersion<=14,is48kSupported=!notSupport48k,isMessageChannelSupported=()=>"undefined"!=typeof MessageChannel,notSupportConstraintInGetDisplayMedia=isSafari&&((null==safariMinorVersion?void 0:safariMinorVersion.includes("16.1"))||(null==safariMinorVersion?void 0:safariMinorVersion.includes("16.2"))||(null==safariMinorVersion?void 0:safariMinorVersion.includes("16.3"))),isConstraintInGetDisplayMediaSupported=!notSupportConstraintInGetDisplayMedia,internalAccessDomains="access.rtc.volcvideo.com,access2-hl.rtc.volcvideo.com,rtcg-access.volcvideos.com".split(",");function getFullAccessUrl(e=""){return e?(/^https?:\/\/.+/.test(e)||(e=`https://${e}`),`${e}/dispatch/v1/AccessInfo?Action=GetAccessInfo`):""}function getFullLogServerUrl(e=""){return e?(/^https?:\/\/.+/.test(e)||(e=`https://${e}`),`${e}/video/v1/webrtc_log/`):""}const domesticLogServerUrl="https://web-log-report.rtc.volcvideo.com/video/v1/webrtc_log/",overseasLogServerUrl="https://web-log-report.volcvideos.com/video/v1/webrtc_log/",configDomains="common.rtc.volcvideo.com,rtcg.volcvideos.com".split(","),Config2={VERSION:"4.66.34",ICE_CONFIG_REQUEST_URLS_INTERNAL:internalAccessDomains.map(getFullAccessUrl),ICE_CONFIG_REQUEST_URLS:[],EXPECTED_ADDR:"",LOG_SERVER_URL:domesticLogServerUrl,CONFIG_REQUEST_DOMAINS:configDomains,DEVICE_ID:"",OVERSEA:!1,PLATFORM:"",PRODUCT:"",FORCE_ENABLED_REPORT_CALLBACKS:[],SKIP_WEB_AUDIO_IN_TRACK:!1,ENFORCE_WEB_AUDIO_SUPPORTED:!1,AUDIO_STALL:!0,VIDEO_STALL:!0,VIDEO_STALL_100MS:!1,STATS_SCALLBACK_SUPPORT:!0,JOIN_ROOM_CONFIG:JoinRoomConfig.DEFAULT_CONF,SIGNAL_COMPRESSION:!0,SIGNAL_CROP_JOINROOM:!0,VIDEO_STALL_DATA:500,AUDIO_STALL_DATA:200,IOS_SAFARI_ORIENTATION:!1,BLACK_FRAME_LIFETIME:6e4,FALLBACK_ENCODE_CODEC:"",SEI_TIME_OUT:2e3,SEI_COUNT_FPS:1,PRE_ICE:!1,STATS_LOOP_INTERVAL:1e3,HIDDEN_STATS:!1,UPLOAD_REMOTE_STATS:ExtendMediaType.NONE,SDK_CODEC_NEGOTIATION:!0,AUDIO_CODEC:"OPUS",DISABLE_ENCODED_TRANSFORM:!1,SKIP_SEI_FILTER:!1,AREA_CODE:"",DISABLE_COMPUTE_PRESSURE:!1,SEND_MESSAGE_SYNC:!1,H264_HW_ENCODER:!1,GPU_URL:"",ENABLE_FALLBACK_HANDLER:!1,ENABLE_STANDARD_HANDLER:isStandardModeEnableByDefault(),PC_KILLSWITCH:{},ENABLE_PLAY_AFTER_CLICK:!1,AUTOPLAY_WORKAROUND:!0,ENGINE_WEB_CONFIG:{},DISABLE_IOS_MUTE_WORKAROUND:!1,AUTOPLAY_THROTTLE:0},originalSetRemoteDescription="undefined"==typeof window?()=>Promise.resolve():null==(_i=null==window?void 0:window.RTCPeerConnection)?void 0:_i.prototype.setRemoteDescription;function setParameter(e,t){if(reportGlobalApiCall("setParameter",0,`key: ${e}, value: ${t}`),"VERSION"===e)return;if("H264_HW_ENCODER"===e){if(Config2.H264_HW_ENCODER=!!t,t){hasHardwareEncodeProfile()?(reportGlobalApiCall("setParameter",0,`key: ${e}, value: ${t} is executed as it met 42001f`),RTCPeerConnection.prototype.setRemoteDescription=function(e){var t;return originalSetRemoteDescription.call(this,{type:e.type,sdp:null==(t=e.sdp)?void 0:t.replaceAll("42e01f","42001f")})}):reportGlobalApiCall("setParameter",0,`key: ${e}, value: ${t} fails as sdp contains no 42001f`)}else RTCPeerConnection.prototype.setRemoteDescription=originalSetRemoteDescription;return}if("GPU_URL"===e)return void(Config2.GPU_URL=t);if("JOIN_ROOM_CONFIG"===e)return JoinRoomConfig.setDefaulConf(t);if("ICE_CONFIG_REQUEST_URLS"===e){const e="string"==typeof t?[t]:t;return Config2.ICE_CONFIG_REQUEST_URLS=e.map(getFullAccessUrl),sdkCache.clearAccessUrls(),void sdkCache.clearAccessNode()}if("VIDEO_STALL_DATA"===e)return void(Config2.VIDEO_STALL_DATA=Math.max(500,Number(t)));if("AUDIO_STALL_DATA"===e)return void(Config2.AUDIO_STALL_DATA=Math.max(200,Number(t)));if("VIDEO_STALL_100MS"===e)return void(Config2.VIDEO_STALL_100MS=checkVideoFrameCallback()&&!!t);if("PLATFORM"===e&&"string"==typeof t)return void setGlobalStats({platform:t});if("PRODUCT"===e&&"string"==typeof t)return void setGlobalStats({product:t});if("FORCE_ENABLED_REPORT_CALLBACKS"===e){const e="string"==typeof t?[t]:t;return void(Config2.FORCE_ENABLED_REPORT_CALLBACKS=e)}if("LOG_SERVER_URL"===e){const e=t===LogChannel.overseas?overseasLogServerUrl:t===LogChannel.domestic?domesticLogServerUrl:"string"==typeof t?t:void 0;e&&(Config2.LOG_SERVER_URL=e,setReportUrl(e))}else if("OVERSEA"===e)return setGlobalStats({extra_is_oversea:t?"1":"0"}),void(Config2.OVERSEA=t);if("CONFIG_REQUEST_DOMAINS"===e&&Array.isArray(t)&&t.length>0)return void(Config2.CONFIG_REQUEST_DOMAINS=t);if("SEI_TIME_OUT"===e&&"number"!=typeof t)return;if("SEI_COUNT_FPS"===e&&"number"!=typeof t)return;if("UPLOAD_REMOTE_STATS"===e&&"string"==typeof t){const e=t.split(",").map((e=>e.trim())).reduce(((e,t)=>"video"===t?e|MediaType$1.VIDEO:"audio"===t?e|MediaType$1.AUDIO:e),ExtendMediaType.NONE);return void(Config2.UPLOAD_REMOTE_STATS=e)}if("AINR_URLS"===e&&"string"==typeof t)try{const{gulpUrl:e,wasmUrl:i,type5ModelUrl:r,type6ModelUrl:o}=JSON.parse(t);return void(Config2.AINR_URLS={gulpUrl:e,wasmUrl:i,type5ModelUrl:r,type6ModelUrl:o})}catch(e){console.error(e)}"DEVICE_ID"===e&&sdkCache.setDeviceId(t);CoreConfig.getKeys().includes(e)?CoreConfig.setParameter(e,t):Reflect.set(Config2,e,t)}function getParameter(e){return"DEVICE_ID"===e?sdkCache.getDeviceId():Config2[e]}function getPublicStreamControlMessage(e,t,i){var r,o,s,n,a,d,c,l,u;return{type:"publicstream",action:t,publicStreamID:e,publicStreamMeta:{audio:{},video:{fps:(null==(r=i.video)?void 0:r.fps)||15,bitrate:1e3*((null==(o=i.video)?void 0:o.kBitRate)||40),width:(null==(s=i.video)?void 0:s.width)||640,height:(null==(n=i.video)?void 0:n.height)||360},layout:{layoutMode:2,interpolationMode:(null==(a=i.layout)?void 0:a.interpolationMode)||PublicInterpolationMode.PREV_FRAME,canvas:{bgColor:(null==(d=i.layout)?void 0:d.backgroundColor)||"#000000",bgImage:(null==(c=i.layout)?void 0:c.backgroundImage)||""},regions:(null==(u=null==(l=i.layout)?void 0:l.regions)?void 0:u.map((e=>({roomId:e.roomId,userId:e.userId,alterImage:e.alertImage||"",alpha:!e.alpha||Number(e.alpha)>1||Number(e.alpha)<=0?1:Number(e.alpha),x:!e.x||Number(e.x)>=1||Number(e.x)<0?0:Number(e.x),y:!e.y||Number(e.y)>=1||Number(e.y)<0?0:Number(e.y),w:!e.w||Number(e.w)>1||Number(e.w)<=0?1:Number(e.w),h:!e.h||Number(e.h)>1||Number(e.h)<=0?1:Number(e.h),zorder:!e.zorder||Number(e.zorder)<0||Number(e.zorder)>100?0:Number(e.zorder),renderMode:void 0===e.renderMode?1:e.renderMode,streamType:e.isScreenStream?1:0,mediaType:e.mediaType||0,sourceCrop:e.sourceCrop}))))||[]}}}}let videoEncoderAutoConfigList=[];function getVideoEncoderAutoConfigList(){return videoEncoderAutoConfigList}function setVideoEncoderAutoConfigList(e){videoEncoderAutoConfigList=e}const autoResetVideoEncoderConfig=(e,t)=>{const i=getVideoEncoderAutoConfigList();if(!i.length)return;const r=e[0],o=t.width||constraints2number(r.width),s=t.height||constraints2number(r.height),n=o*s;if(constraints2number(r.width)*constraints2number(r.height)<=n)return;let a,d,c=i[0];i.forEach((e=>{const t=constraints2number(e.width)*constraints2number(e.height);a||(n<t?a=e:c=e)})),d=a&&constraints2number(a.width)*constraints2number(a.height)-n<n-constraints2number(c.width)*constraints2number(c.height)?Object.assign({},a):Object.assign({},c);const l=e.filter((e=>!(d&&constraints2number(e.width)*constraints2number(e.height)>=n)||(d.maxKbps=Math.min(e.maxKbps,d.maxKbps),!1)));return l.unshift({width:o,height:s,frameRate:t.frameRate?Math.round(t.frameRate):l[0].frameRate,maxKbps:d.maxKbps}),l},defaultVideoEncoderConfig={width:640,height:480,frameRate:15,maxKbps:600},defaultScreenEncoderConfig={width:1920,height:1080,frameRate:15,maxKbps:3e3};function isStandardModeEnableByDefault(){return(isChrome||isEdge)&&!isIOS}let getRandomValues;const rnds8=new Uint8Array(16);function rng(){if(!getRandomValues&&(getRandomValues="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!getRandomValues))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return getRandomValues(rnds8)}const byteToHex=[];for(let e=0;e<256;++e)byteToHex.push((e+256).toString(16).slice(1));function unsafeStringify(e,t=0){return byteToHex[e[t+0]]+byteToHex[e[t+1]]+byteToHex[e[t+2]]+byteToHex[e[t+3]]+"-"+byteToHex[e[t+4]]+byteToHex[e[t+5]]+"-"+byteToHex[e[t+6]]+byteToHex[e[t+7]]+"-"+byteToHex[e[t+8]]+byteToHex[e[t+9]]+"-"+byteToHex[e[t+10]]+byteToHex[e[t+11]]+byteToHex[e[t+12]]+byteToHex[e[t+13]]+byteToHex[e[t+14]]+byteToHex[e[t+15]]}const randomUUID="undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);var native={randomUUID:randomUUID};function v4(e,t,i){if(native.randomUUID&&!t&&!e)return native.randomUUID();const r=(e=e||{}).random||(e.rng||rng)();if(r[6]=15&r[6]|64,r[8]=63&r[8]|128,t){i=i||0;for(let e=0;e<16;++e)t[i+e]=r[e];return t}return unsafeStringify(r)}var libTypedarrays={exports:{}};function commonjsRequire(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var hasRequiredCore,core={exports:{}},__viteBrowserExternal=new Proxy({},{get(e,t){throw new Error(`Module "" has been externalized for browser compatibility. Cannot access ".${t}" in client code. See http://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`)}}),__viteBrowserExternal$1=Object.freeze({__proto__:null,default:__viteBrowserExternal}),require$$0=getAugmentedNamespace(__viteBrowserExternal$1);function requireCore(){return hasRequiredCore||(hasRequiredCore=1,core.exports=(e=e||function(e,t){var i;if("undefined"!=typeof window&&window.crypto&&(i=window.crypto),"undefined"!=typeof self&&self.crypto&&(i=self.crypto),"undefined"!=typeof globalThis&&globalThis.crypto&&(i=globalThis.crypto),!i&&"undefined"!=typeof window&&window.msCrypto&&(i=window.msCrypto),!i&&void 0!==commonjsGlobal&&commonjsGlobal.crypto&&(i=commonjsGlobal.crypto),!i&&"function"==typeof commonjsRequire)try{i=require$$0}catch(e){}var r=function(){if(i){if("function"==typeof i.getRandomValues)try{return i.getRandomValues(new Uint32Array(1))[0]}catch(e){}if("function"==typeof i.randomBytes)try{return i.randomBytes(4).readInt32LE()}catch(e){}}throw new Error("Native crypto module could not be used to get secure random number.")},o=Object.create||function(){function e(){}return function(t){var i;return e.prototype=t,i=new e,e.prototype=null,i}}(),s={},n=s.lib={},a=n.Base={extend:function(e){var t=o(this);return e&&t.mixIn(e),t.hasOwnProperty("init")&&this.init!==t.init||(t.init=function(){t.$super.init.apply(this,arguments)}),t.init.prototype=t,t.$super=this,t},create:function(){var e=this.extend();return e.init.apply(e,arguments),e},init:function(){},mixIn:function(e){for(var t in e)e.hasOwnProperty(t)&&(this[t]=e[t]);e.hasOwnProperty("toString")&&(this.toString=e.toString)},clone:function(){return this.init.prototype.extend(this)}},d=n.WordArray=a.extend({init:function(e,i){e=this.words=e||[],this.sigBytes=i!=t?i:4*e.length},toString:function(e){return(e||l).stringify(this)},concat:function(e){var t=this.words,i=e.words,r=this.sigBytes,o=e.sigBytes;if(this.clamp(),r%4)for(var s=0;s<o;s++){var n=i[s>>>2]>>>24-s%4*8&255;t[r+s>>>2]|=n<<24-(r+s)%4*8}else for(var a=0;a<o;a+=4)t[r+a>>>2]=i[a>>>2];return this.sigBytes+=o,this},clamp:function(){var t=this.words,i=this.sigBytes;t[i>>>2]&=4294967295<<32-i%4*8,t.length=e.ceil(i/4)},clone:function(){var e=a.clone.call(this);return e.words=this.words.slice(0),e},random:function(e){for(var t=[],i=0;i<e;i+=4)t.push(r());return new d.init(t,e)}}),c=s.enc={},l=c.Hex={stringify:function(e){for(var t=e.words,i=e.sigBytes,r=[],o=0;o<i;o++){var s=t[o>>>2]>>>24-o%4*8&255;r.push((s>>>4).toString(16)),r.push((15&s).toString(16))}return r.join("")},parse:function(e){for(var t=e.length,i=[],r=0;r<t;r+=2)i[r>>>3]|=parseInt(e.substr(r,2),16)<<24-r%8*4;return new d.init(i,t/2)}},u=c.Latin1={stringify:function(e){for(var t=e.words,i=e.sigBytes,r=[],o=0;o<i;o++){var s=t[o>>>2]>>>24-o%4*8&255;r.push(String.fromCharCode(s))}return r.join("")},parse:function(e){for(var t=e.length,i=[],r=0;r<t;r++)i[r>>>2]|=(255&e.charCodeAt(r))<<24-r%4*8;return new d.init(i,t)}},_=c.Utf8={stringify:function(e){try{return decodeURIComponent(escape(u.stringify(e)))}catch(e){throw new Error("Malformed UTF-8 data")}},parse:function(e){return u.parse(unescape(encodeURIComponent(e)))}},h=n.BufferedBlockAlgorithm=a.extend({reset:function(){this._data=new d.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=_.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var i,r=this._data,o=r.words,s=r.sigBytes,n=this.blockSize,a=s/(4*n),c=(a=t?e.ceil(a):e.max((0|a)-this._minBufferSize,0))*n,l=e.min(4*c,s);if(c){for(var u=0;u<c;u+=n)this._doProcessBlock(o,u);i=o.splice(0,c),r.sigBytes-=l}return new d.init(i,l)},clone:function(){var e=a.clone.call(this);return e._data=this._data.clone(),e},_minBufferSize:0});n.Hasher=h.extend({cfg:a.extend(),init:function(e){this.cfg=this.cfg.extend(e),this.reset()},reset:function(){h.reset.call(this),this._doReset()},update:function(e){return this._append(e),this._process(),this},finalize:function(e){return e&&this._append(e),this._doFinalize()},blockSize:16,_createHelper:function(e){return function(t,i){return new e.init(i).finalize(t)}},_createHmacHelper:function(e){return function(t,i){return new p.HMAC.init(e,i).finalize(t)}}});var p=s.algo={};return s}(Math),e)),core.exports;var e}!function(){var e;libTypedarrays.exports=(e=requireCore(),function(){if("function"==typeof ArrayBuffer){var t=e.lib.WordArray,i=t.init,r=t.init=function(e){if(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),(e instanceof Int8Array||"undefined"!=typeof Uint8ClampedArray&&e instanceof Uint8ClampedArray||e instanceof Int16Array||e instanceof Uint16Array||e instanceof Int32Array||e instanceof Uint32Array||e instanceof Float32Array||e instanceof Float64Array)&&(e=new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),e instanceof Uint8Array){for(var t=e.byteLength,r=[],o=0;o<t;o++)r[o>>>2]|=e[o]<<24-o%4*8;i.call(this,r,t)}else i.apply(this,arguments)};r.prototype=t}}(),e.lib.WordArray)}();var hasRequiredEncBase64,libTypedarraysExports=libTypedarrays.exports,WordArray=getDefaultExportFromCjs(libTypedarraysExports),aes={exports:{}},encBase64={exports:{}};function requireEncBase64(){return hasRequiredEncBase64||(hasRequiredEncBase64=1,encBase64.exports=(e=requireCore(),function(){var t=e,i=t.lib.WordArray;function r(e,t,r){for(var o=[],s=0,n=0;n<t;n++)if(n%4){var a=r[e.charCodeAt(n-1)]<<n%4*2|r[e.charCodeAt(n)]>>>6-n%4*2;o[s>>>2]|=a<<24-s%4*8,s++}return i.create(o,s)}t.enc.Base64={stringify:function(e){var t=e.words,i=e.sigBytes,r=this._map;e.clamp();for(var o=[],s=0;s<i;s+=3)for(var n=(t[s>>>2]>>>24-s%4*8&255)<<16|(t[s+1>>>2]>>>24-(s+1)%4*8&255)<<8|t[s+2>>>2]>>>24-(s+2)%4*8&255,a=0;a<4&&s+.75*a<i;a++)o.push(r.charAt(n>>>6*(3-a)&63));var d=r.charAt(64);if(d)for(;o.length%4;)o.push(d);return o.join("")},parse:function(e){var t=e.length,i=this._map,o=this._reverseMap;if(!o){o=this._reverseMap=[];for(var s=0;s<i.length;s++)o[i.charCodeAt(s)]=s}var n=i.charAt(64);if(n){var a=e.indexOf(n);-1!==a&&(t=a)}return r(e,t,o)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}}(),e.enc.Base64)),encBase64.exports;var e}var hasRequiredMd5,md5={exports:{}};function requireMd5(){return hasRequiredMd5||(hasRequiredMd5=1,md5.exports=(e=requireCore(),function(t){var i=e,r=i.lib,o=r.WordArray,s=r.Hasher,n=i.algo,a=[];!function(){for(var e=0;e<64;e++)a[e]=4294967296*t.abs(t.sin(e+1))|0}();var d=n.MD5=s.extend({_doReset:function(){this._hash=new o.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(e,t){for(var i=0;i<16;i++){var r=t+i,o=e[r];e[r]=16711935&(o<<8|o>>>24)|4278255360&(o<<24|o>>>8)}var s=this._hash.words,n=e[t+0],d=e[t+1],h=e[t+2],p=e[t+3],m=e[t+4],S=e[t+5],g=e[t+6],v=e[t+7],f=e[t+8],E=e[t+9],T=e[t+10],R=e[t+11],b=e[t+12],y=e[t+13],I=e[t+14],C=e[t+15],A=s[0],k=s[1],M=s[2],N=s[3];A=c(A,k,M,N,n,7,a[0]),N=c(N,A,k,M,d,12,a[1]),M=c(M,N,A,k,h,17,a[2]),k=c(k,M,N,A,p,22,a[3]),A=c(A,k,M,N,m,7,a[4]),N=c(N,A,k,M,S,12,a[5]),M=c(M,N,A,k,g,17,a[6]),k=c(k,M,N,A,v,22,a[7]),A=c(A,k,M,N,f,7,a[8]),N=c(N,A,k,M,E,12,a[9]),M=c(M,N,A,k,T,17,a[10]),k=c(k,M,N,A,R,22,a[11]),A=c(A,k,M,N,b,7,a[12]),N=c(N,A,k,M,y,12,a[13]),M=c(M,N,A,k,I,17,a[14]),A=l(A,k=c(k,M,N,A,C,22,a[15]),M,N,d,5,a[16]),N=l(N,A,k,M,g,9,a[17]),M=l(M,N,A,k,R,14,a[18]),k=l(k,M,N,A,n,20,a[19]),A=l(A,k,M,N,S,5,a[20]),N=l(N,A,k,M,T,9,a[21]),M=l(M,N,A,k,C,14,a[22]),k=l(k,M,N,A,m,20,a[23]),A=l(A,k,M,N,E,5,a[24]),N=l(N,A,k,M,I,9,a[25]),M=l(M,N,A,k,p,14,a[26]),k=l(k,M,N,A,f,20,a[27]),A=l(A,k,M,N,y,5,a[28]),N=l(N,A,k,M,h,9,a[29]),M=l(M,N,A,k,v,14,a[30]),A=u(A,k=l(k,M,N,A,b,20,a[31]),M,N,S,4,a[32]),N=u(N,A,k,M,f,11,a[33]),M=u(M,N,A,k,R,16,a[34]),k=u(k,M,N,A,I,23,a[35]),A=u(A,k,M,N,d,4,a[36]),N=u(N,A,k,M,m,11,a[37]),M=u(M,N,A,k,v,16,a[38]),k=u(k,M,N,A,T,23,a[39]),A=u(A,k,M,N,y,4,a[40]),N=u(N,A,k,M,n,11,a[41]),M=u(M,N,A,k,p,16,a[42]),k=u(k,M,N,A,g,23,a[43]),A=u(A,k,M,N,E,4,a[44]),N=u(N,A,k,M,b,11,a[45]),M=u(M,N,A,k,C,16,a[46]),A=_(A,k=u(k,M,N,A,h,23,a[47]),M,N,n,6,a[48]),N=_(N,A,k,M,v,10,a[49]),M=_(M,N,A,k,I,15,a[50]),k=_(k,M,N,A,S,21,a[51]),A=_(A,k,M,N,b,6,a[52]),N=_(N,A,k,M,p,10,a[53]),M=_(M,N,A,k,T,15,a[54]),k=_(k,M,N,A,d,21,a[55]),A=_(A,k,M,N,f,6,a[56]),N=_(N,A,k,M,C,10,a[57]),M=_(M,N,A,k,g,15,a[58]),k=_(k,M,N,A,y,21,a[59]),A=_(A,k,M,N,m,6,a[60]),N=_(N,A,k,M,R,10,a[61]),M=_(M,N,A,k,h,15,a[62]),k=_(k,M,N,A,E,21,a[63]),s[0]=s[0]+A|0,s[1]=s[1]+k|0,s[2]=s[2]+M|0,s[3]=s[3]+N|0},_doFinalize:function(){var e=this._data,i=e.words,r=8*this._nDataBytes,o=8*e.sigBytes;i[o>>>5]|=128<<24-o%32;var s=t.floor(r/4294967296),n=r;i[15+(o+64>>>9<<4)]=16711935&(s<<8|s>>>24)|4278255360&(s<<24|s>>>8),i[14+(o+64>>>9<<4)]=16711935&(n<<8|n>>>24)|4278255360&(n<<24|n>>>8),e.sigBytes=4*(i.length+1),this._process();for(var a=this._hash,d=a.words,c=0;c<4;c++){var l=d[c];d[c]=16711935&(l<<8|l>>>24)|4278255360&(l<<24|l>>>8)}return a},clone:function(){var e=s.clone.call(this);return e._hash=this._hash.clone(),e}});function c(e,t,i,r,o,s,n){var a=e+(t&i|~t&r)+o+n;return(a<<s|a>>>32-s)+t}function l(e,t,i,r,o,s,n){var a=e+(t&r|i&~r)+o+n;return(a<<s|a>>>32-s)+t}function u(e,t,i,r,o,s,n){var a=e+(t^i^r)+o+n;return(a<<s|a>>>32-s)+t}function _(e,t,i,r,o,s,n){var a=e+(i^(t|~r))+o+n;return(a<<s|a>>>32-s)+t}i.MD5=s._createHelper(d),i.HmacMD5=s._createHmacHelper(d)}(Math),e.MD5)),md5.exports;var e}var hasRequiredSha1,evpkdf={exports:{}},sha1={exports:{}};function requireSha1(){return hasRequiredSha1||(hasRequiredSha1=1,sha1.exports=(a=requireCore(),t=(e=a).lib,i=t.WordArray,r=t.Hasher,o=e.algo,s=[],n=o.SHA1=r.extend({_doReset:function(){this._hash=new i.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(e,t){for(var i=this._hash.words,r=i[0],o=i[1],n=i[2],a=i[3],d=i[4],c=0;c<80;c++){if(c<16)s[c]=0|e[t+c];else{var l=s[c-3]^s[c-8]^s[c-14]^s[c-16];s[c]=l<<1|l>>>31}var u=(r<<5|r>>>27)+d+s[c];u+=c<20?1518500249+(o&n|~o&a):c<40?1859775393+(o^n^a):c<60?(o&n|o&a|n&a)-1894007588:(o^n^a)-899497514,d=a,a=n,n=o<<30|o>>>2,o=r,r=u}i[0]=i[0]+r|0,i[1]=i[1]+o|0,i[2]=i[2]+n|0,i[3]=i[3]+a|0,i[4]=i[4]+d|0},_doFinalize:function(){var e=this._data,t=e.words,i=8*this._nDataBytes,r=8*e.sigBytes;return t[r>>>5]|=128<<24-r%32,t[14+(r+64>>>9<<4)]=Math.floor(i/4294967296),t[15+(r+64>>>9<<4)]=i,e.sigBytes=4*t.length,this._process(),this._hash},clone:function(){var e=r.clone.call(this);return e._hash=this._hash.clone(),e}}),e.SHA1=r._createHelper(n),e.HmacSHA1=r._createHmacHelper(n),a.SHA1)),sha1.exports;var e,t,i,r,o,s,n,a}var hasRequiredHmac,hasRequiredEvpkdf,hmac={exports:{}};function requireHmac(){return hasRequiredHmac||(hasRequiredHmac=1,hmac.exports=(e=requireCore(),i=(t=e).lib.Base,r=t.enc.Utf8,void(t.algo.HMAC=i.extend({init:function(e,t){e=this._hasher=new e.init,"string"==typeof t&&(t=r.parse(t));var i=e.blockSize,o=4*i;t.sigBytes>o&&(t=e.finalize(t)),t.clamp();for(var s=this._oKey=t.clone(),n=this._iKey=t.clone(),a=s.words,d=n.words,c=0;c<i;c++)a[c]^=1549556828,d[c]^=909522486;s.sigBytes=n.sigBytes=o,this.reset()},reset:function(){var e=this._hasher;e.reset(),e.update(this._iKey)},update:function(e){return this._hasher.update(e),this},finalize:function(e){var t=this._hasher,i=t.finalize(e);return t.reset(),t.finalize(this._oKey.clone().concat(i))}})))),hmac.exports;var e,t,i,r}function requireEvpkdf(){return hasRequiredEvpkdf||(hasRequiredEvpkdf=1,evpkdf.exports=(a=requireCore(),requireSha1(),requireHmac(),t=(e=a).lib,i=t.Base,r=t.WordArray,o=e.algo,s=o.MD5,n=o.EvpKDF=i.extend({cfg:i.extend({keySize:4,hasher:s,iterations:1}),init:function(e){this.cfg=this.cfg.extend(e)},compute:function(e,t){for(var i,o=this.cfg,s=o.hasher.create(),n=r.create(),a=n.words,d=o.keySize,c=o.iterations;a.length<d;){i&&s.update(i),i=s.update(e).finalize(t),s.reset();for(var l=1;l<c;l++)i=s.finalize(i),s.reset();n.concat(i)}return n.sigBytes=4*d,n}}),e.EvpKDF=function(e,t,i){return n.create(i).compute(e,t)},a.EvpKDF)),evpkdf.exports;var e,t,i,r,o,s,n,a}var hasRequiredCipherCore,cipherCore={exports:{}};function requireCipherCore(){return hasRequiredCipherCore||(hasRequiredCipherCore=1,cipherCore.exports=(e=requireCore(),requireEvpkdf(),void(e.lib.Cipher||function(t){var i=e,r=i.lib,o=r.Base,s=r.WordArray,n=r.BufferedBlockAlgorithm,a=i.enc;a.Utf8;var d=a.Base64,c=i.algo.EvpKDF,l=r.Cipher=n.extend({cfg:o.extend(),createEncryptor:function(e,t){return this.create(this._ENC_XFORM_MODE,e,t)},createDecryptor:function(e,t){return this.create(this._DEC_XFORM_MODE,e,t)},init:function(e,t,i){this.cfg=this.cfg.extend(i),this._xformMode=e,this._key=t,this.reset()},reset:function(){n.reset.call(this),this._doReset()},process:function(e){return this._append(e),this._process()},finalize:function(e){return e&&this._append(e),this._doFinalize()},keySize:4,ivSize:4,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,_createHelper:function(){function e(e){return"string"==typeof e?f:g}return function(t){return{encrypt:function(i,r,o){return e(r).encrypt(t,i,r,o)},decrypt:function(i,r,o){return e(r).decrypt(t,i,r,o)}}}}()});r.StreamCipher=l.extend({_doFinalize:function(){return this._process(!0)},blockSize:1});var u=i.mode={},_=r.BlockCipherMode=o.extend({createEncryptor:function(e,t){return this.Encryptor.create(e,t)},createDecryptor:function(e,t){return this.Decryptor.create(e,t)},init:function(e,t){this._cipher=e,this._iv=t}}),h=u.CBC=function(){var e=_.extend();function i(e,i,r){var o,s=this._iv;s?(o=s,this._iv=t):o=this._prevBlock;for(var n=0;n<r;n++)e[i+n]^=o[n]}return e.Encryptor=e.extend({processBlock:function(e,t){var r=this._cipher,o=r.blockSize;i.call(this,e,t,o),r.encryptBlock(e,t),this._prevBlock=e.slice(t,t+o)}}),e.Decryptor=e.extend({processBlock:function(e,t){var r=this._cipher,o=r.blockSize,s=e.slice(t,t+o);r.decryptBlock(e,t),i.call(this,e,t,o),this._prevBlock=s}}),e}(),p=(i.pad={}).Pkcs7={pad:function(e,t){for(var i=4*t,r=i-e.sigBytes%i,o=r<<24|r<<16|r<<8|r,n=[],a=0;a<r;a+=4)n.push(o);var d=s.create(n,r);e.concat(d)},unpad:function(e){var t=255&e.words[e.sigBytes-1>>>2];e.sigBytes-=t}};r.BlockCipher=l.extend({cfg:l.cfg.extend({mode:h,padding:p}),reset:function(){var e;l.reset.call(this);var t=this.cfg,i=t.iv,r=t.mode;this._xformMode==this._ENC_XFORM_MODE?e=r.createEncryptor:(e=r.createDecryptor,this._minBufferSize=1),this._mode&&this._mode.__creator==e?this._mode.init(this,i&&i.words):(this._mode=e.call(r,this,i&&i.words),this._mode.__creator=e)},_doProcessBlock:function(e,t){this._mode.processBlock(e,t)},_doFinalize:function(){var e,t=this.cfg.padding;return this._xformMode==this._ENC_XFORM_MODE?(t.pad(this._data,this.blockSize),e=this._process(!0)):(e=this._process(!0),t.unpad(e)),e},blockSize:4});var m=r.CipherParams=o.extend({init:function(e){this.mixIn(e)},toString:function(e){return(e||this.formatter).stringify(this)}}),S=(i.format={}).OpenSSL={stringify:function(e){var t=e.ciphertext,i=e.salt;return(i?s.create([1398893684,1701076831]).concat(i).concat(t):t).toString(d)},parse:function(e){var t,i=d.parse(e),r=i.words;return 1398893684==r[0]&&1701076831==r[1]&&(t=s.create(r.slice(2,4)),r.splice(0,4),i.sigBytes-=16),m.create({ciphertext:i,salt:t})}},g=r.SerializableCipher=o.extend({cfg:o.extend({format:S}),encrypt:function(e,t,i,r){r=this.cfg.extend(r);var o=e.createEncryptor(i,r),s=o.finalize(t),n=o.cfg;return m.create({ciphertext:s,key:i,iv:n.iv,algorithm:e,mode:n.mode,padding:n.padding,blockSize:e.blockSize,formatter:r.format})},decrypt:function(e,t,i,r){return r=this.cfg.extend(r),t=this._parse(t,r.format),e.createDecryptor(i,r).finalize(t.ciphertext)},_parse:function(e,t){return"string"==typeof e?t.parse(e,this):e}}),v=(i.kdf={}).OpenSSL={execute:function(e,t,i,r,o){if(r||(r=s.random(8)),o)n=c.create({keySize:t+i,hasher:o}).compute(e,r);else var n=c.create({keySize:t+i}).compute(e,r);var a=s.create(n.words.slice(t),4*i);return n.sigBytes=4*t,m.create({key:n,iv:a,salt:r})}},f=r.PasswordBasedCipher=g.extend({cfg:g.cfg.extend({kdf:v}),encrypt:function(e,t,i,r){var o=(r=this.cfg.extend(r)).kdf.execute(i,e.keySize,e.ivSize,r.salt,r.hasher);r.iv=o.iv;var s=g.encrypt.call(this,e,t,o.key,r);return s.mixIn(o),s},decrypt:function(e,t,i,r){r=this.cfg.extend(r),t=this._parse(t,r.format);var o=r.kdf.execute(i,e.keySize,e.ivSize,t.salt,r.hasher);return r.iv=o.iv,g.decrypt.call(this,e,t,o.key,r)}})}()))),cipherCore.exports;var e}!function(){var e;aes.exports=(e=requireCore(),requireEncBase64(),requireMd5(),requireEvpkdf(),requireCipherCore(),function(){var t=e,i=t.lib.BlockCipher,r=t.algo,o=[],s=[],n=[],a=[],d=[],c=[],l=[],u=[],_=[],h=[];!function(){for(var e=[],t=0;t<256;t++)e[t]=t<128?t<<1:t<<1^283;var i=0,r=0;for(t=0;t<256;t++){var p=r^r<<1^r<<2^r<<3^r<<4;p=p>>>8^255&p^99,o[i]=p,s[p]=i;var m=e[i],S=e[m],g=e[S],v=257*e[p]^16843008*p;n[i]=v<<24|v>>>8,a[i]=v<<16|v>>>16,d[i]=v<<8|v>>>24,c[i]=v,v=16843009*g^65537*S^257*m^16843008*i,l[p]=v<<24|v>>>8,u[p]=v<<16|v>>>16,_[p]=v<<8|v>>>24,h[p]=v,i?(i=m^e[e[e[g^m]]],r^=e[e[r]]):i=r=1}}();var p=[0,1,2,4,8,16,32,64,128,27,54],m=r.AES=i.extend({_doReset:function(){if(!this._nRounds||this._keyPriorReset!==this._key){for(var e=this._keyPriorReset=this._key,t=e.words,i=e.sigBytes/4,r=4*((this._nRounds=i+6)+1),s=this._keySchedule=[],n=0;n<r;n++)n<i?s[n]=t[n]:(c=s[n-1],n%i?i>6&&n%i==4&&(c=o[c>>>24]<<24|o[c>>>16&255]<<16|o[c>>>8&255]<<8|o[255&c]):(c=o[(c=c<<8|c>>>24)>>>24]<<24|o[c>>>16&255]<<16|o[c>>>8&255]<<8|o[255&c],c^=p[n/i|0]<<24),s[n]=s[n-i]^c);for(var a=this._invKeySchedule=[],d=0;d<r;d++){if(n=r-d,d%4)var c=s[n];else c=s[n-4];a[d]=d<4||n<=4?c:l[o[c>>>24]]^u[o[c>>>16&255]]^_[o[c>>>8&255]]^h[o[255&c]]}}},encryptBlock:function(e,t){this._doCryptBlock(e,t,this._keySchedule,n,a,d,c,o)},decryptBlock:function(e,t){var i=e[t+1];e[t+1]=e[t+3],e[t+3]=i,this._doCryptBlock(e,t,this._invKeySchedule,l,u,_,h,s),i=e[t+1],e[t+1]=e[t+3],e[t+3]=i},_doCryptBlock:function(e,t,i,r,o,s,n,a){for(var d=this._nRounds,c=e[t]^i[0],l=e[t+1]^i[1],u=e[t+2]^i[2],_=e[t+3]^i[3],h=4,p=1;p<d;p++){var m=r[c>>>24]^o[l>>>16&255]^s[u>>>8&255]^n[255&_]^i[h++],S=r[l>>>24]^o[u>>>16&255]^s[_>>>8&255]^n[255&c]^i[h++],g=r[u>>>24]^o[_>>>16&255]^s[c>>>8&255]^n[255&l]^i[h++],v=r[_>>>24]^o[c>>>16&255]^s[l>>>8&255]^n[255&u]^i[h++];c=m,l=S,u=g,_=v}m=(a[c>>>24]<<24|a[l>>>16&255]<<16|a[u>>>8&255]<<8|a[255&_])^i[h++],S=(a[l>>>24]<<24|a[u>>>16&255]<<16|a[_>>>8&255]<<8|a[255&c])^i[h++],g=(a[u>>>24]<<24|a[_>>>16&255]<<16|a[c>>>8&255]<<8|a[255&l])^i[h++],v=(a[_>>>24]<<24|a[c>>>16&255]<<16|a[l>>>8&255]<<8|a[255&u])^i[h++],e[t]=m,e[t+1]=S,e[t+2]=g,e[t+3]=v},keySize:8});t.AES=i._createHelper(m)}(),e.AES)}();var aesExports=aes.exports,encHex$1={exports:{}};encHex$1.exports=requireCore().enc.Hex;var encHexExports=encHex$1.exports,encHex=getDefaultExportFromCjs(encHexExports),modeCtr={exports:{}};!function(){var e,t,i;modeCtr.exports=(i=requireCore(),requireCipherCore(),i.mode.CTR=(e=i.lib.BlockCipherMode.extend(),t=e.Encryptor=e.extend({processBlock:function(e,t){var i=this._cipher,r=i.blockSize,o=this._iv,s=this._counter;o&&(s=this._counter=o.slice(0),this._iv=void 0);var n=s.slice(0);i.encryptBlock(n,0),s[r-1]=s[r-1]+1|0;for(var a=0;a<r;a++)e[t+a]^=n[a]}}),e.Decryptor=t,e),i.mode.CTR)}();var modeCtrExports=modeCtr.exports,ModeCTR=getDefaultExportFromCjs(modeCtrExports),padNopadding={exports:{}};!function(){var e;padNopadding.exports=(e=requireCore(),requireCipherCore(),e.pad.NoPadding={pad:function(){},unpad:function(){}},e.pad.NoPadding)}();var padNopaddingExports=padNopadding.exports,PadNoPadding=getDefaultExportFromCjs(padNopaddingExports);const textDecoder=new TextDecoder,textEncoder=new TextEncoder;let gpuInfo;const genUuid=()=>v4(),getServerNow=()=>Date.now();function concatenate(e,...t){let i=0;for(const e of t)i+=e.length;const r=new e(i);let o=0;for(const e of t)r.set(e,o),o+=e.length;return r}class Utils{static token2auth(e,t,i,r){return r?`Bearer ${r}`:`Basic ${Utils.createUnsafeToken(e,t,i)}`}static createUnsafeToken(e,t,i){return window.btoa([e,t,i].filter((e=>null!==e)).join(":"))}static merge(e={},t={}){for(const[i,r]of Object.entries(e))null!==r&&"object"==typeof r?Utils.merge(e[i],t[i]):void 0!==t[i]&&(e[i]=t[i])}static ab2str(e){return textDecoder.decode(e)}static ab2obj(e){try{const t=Utils.ab2str(e);return JSON.parse(t)}catch(e){return{}}}static str2ab(e){return textEncoder.encode(e).buffer}static async ab2b64str(e){if(getParameter("SEND_MESSAGE_SYNC")){const t=String.fromCharCode.apply(null,new Uint8Array(e));return window.btoa(t)}return(await new Promise((t=>{const i=new FileReader;i.onload=()=>t(i.result),i.readAsDataURL(new Blob([e]))}))).split(",",2)[1]}static async b64str2ab(e,t){return fetch(`data:application/octet;base64,${e}`).then((e=>e.arrayBuffer())).catch((i=>{throw t&&t.report("rtc_error",{error_code:2001,message:`${i.message} -> ${e}`}),i}))}}function wait(e){return new Promise((t=>{setTimeout(t,e)}))}function createRandomId(){const e=Number(`${Math.random()}`.slice(-7).padEnd(7,"0")).toString(2).padEnd(28,"1").split(""),t=[];for(;e.length;)t.push(e.splice(0,7));return t.map(((e,i)=>{const r=i===t.length-1?"0":"1";return Number.parseInt(r+e.join(""),2)}))}const genEventSessionId=()=>Math.floor(65535*Math.random());function isByteId(e){return!(128&~e)}function isRttMessage(e){return"string"==typeof e&&e.indexOf("__web__rtc__rtt__")>-1}function randomNum(e){let t="";for(let i=0;i<e;i++)t+=Math.floor(10*Math.random());return t}let defaultSdp;const createDefaultSdp=async(e=!1)=>{if(defaultSdp)return defaultSdp;const t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan"});t.createDataChannel("default"),t.addTransceiver("audio",{direction:"recvonly"}),t.addTransceiver("video",{direction:"recvonly"}),e&&(t.addTransceiver("audio",{direction:"sendonly"}),t.addTransceiver("video",{direction:"sendonly"}));const i=await t.createOffer();return t.close(),defaultSdp=i.sdp,i.sdp},promiseAny=e=>new Promise(((t,i)=>{let r=(e=Array.isArray(e)?e:[]).length;const o=[];0===r?i([]):e.forEach((e=>{e.then((e=>{t(e)}),(e=>{r--,o.push(e),0===r&&i(o)}))}))}));function getNonlinearVolume(e){return Number(Math.max(-127,10*Math.log10(Math.pow(e/255,2))).toFixed(2))}function audioInMediaType(e){return(e&MediaType$1.AUDIO)===MediaType$1.AUDIO}function videoInMediaType(e){return(e&MediaType$1.VIDEO)===MediaType$1.VIDEO}function getPublicStats(e){const t={};return Object.keys(e).forEach((i=>{"object"==typeof e[i]?t[i]=getPublicStats(e[i]):i.startsWith("_")&&!getParameter("HIDDEN_STATS")||(t[i]=e[i])})),t}function splitPublicStreamSei(e){const t=new DataView(e.buffer);if(t.byteLength<=4||65535!==t.getUint16(0))return{seiCount:1,seis:[e]};const i={seiCount:0,seis:[]};let r=!1,o=2;for(;o<t.byteLength;){const s=t.getUint16(o);if(o+=2,t.byteLength-o<s){r=!0;break}const n=new Uint8Array(e.buffer,o,s);if(o+=s,t.byteLength-o>0&&t.byteLength-o<=2){r=!0;break}i.seiCount++,i.seis.push(n)}return r&&(i.seiCount=1,i.seis=[e]),i}function isUndefined(e){return void 0===e}function warnDeprecatedApi(e){return function(t,i,r){const o=r.value;r.value=function(...t){return console.warn(`[RTC WebSDK]: Api: ${i} has been abandoned from version ${e}`),o.apply(this,t)}}}function warnDevelopers(e){console.warn(`[RTC WebSDK]: ${e}`)}function constraints2number(e){return"number"==typeof e?e:"number"==typeof(null==e?void 0:e.exact)?e.exact:"number"==typeof(null==e?void 0:e.ideal)?e.ideal:"number"==typeof(null==e?void 0:e.max)?e.max:"number"==typeof(null==e?void 0:e.min)?e.min:1}function setJoinRoomInfo(e,t,i){if("function"==typeof i.value){const e=i.value;i.value=function(...t){var i;const r=getMonitor(this.id);return null==r||r.set({room_id:t[1],user_id:null==(i=t[2])?void 0:i.userId}),e.apply(this,t)}}}const MAX_MESSAGE_ID=Math.pow(2,15);class MessageId{constructor(){__publicField(this,"_id"),this._id=Math.ceil(Math.random()*MAX_MESSAGE_ID)}getMessageId(){return++this._id>MAX_MESSAGE_ID&&(this._id=0),this._id}}function filterUndefined(e){const t={};return Object.keys(e).forEach((i=>{void 0!==e[i]&&(t[i]=e[i])})),t}const isDebuggerMode="undefined"!=typeof window&&(window.location.search.includes("_rtc_debug_")||!!(null==(_j=window.localStorage)?void 0:_j.getItem("_rtc_debug_")));function base64ToUint8(e){const t=atob(e),i=t.length,r=new Uint8Array(i);for(let e=0;e<i;e++)r[e]=t.charCodeAt(e);return r}function uint8ToBase64(e){let t="";const i=e.byteLength;for(let r=0;r<i;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function aesCtrEncrypt(e,t,i){const r=uint8ArrayToWordArray(e),o=uint8ArrayToWordArray(t),s=uint8ArrayToWordArray(i);return wordArrayToUint8Array(aesExports.encrypt(r,o,{iv:s,mode:ModeCTR,padding:PadNoPadding}).ciphertext)}function wordArrayToUint8Array(e){const t=e.toString(encHex),i=new Uint8Array(t.length/2);for(let e=0;e<t.length;e+=2)i[e/2]=parseInt(t.substr(e,2),16);return i}function uint8ArrayToWordArray(e){const t=[];for(let i=0;i<e.length;i+=4)t.push(e[i]<<24|(e[i+1]||0)<<16|(e[i+2]||0)<<8|(e[i+3]||0));return WordArray.create(t,e.length)}function getGpuInfo(){return gpuInfo||(gpuInfo=_getGpuInfo()),gpuInfo}function _getGpuInfo(){let e=document.createElement("canvas"),t=e.getContext("webgl")||e.getContext("experimental-webgl");if(!t)return{renderer:"unknown(WebGLRenderingContext not existed)",vendor:"unknown(WebGLRenderingContext not existed)"};const i=t.getExtension("WEBGL_debug_renderer_info");if(!i)return{renderer:"unknown(info not existed)",vendor:"unknown(info not existed)"};const r=t.getParameter(i.UNMASKED_RENDERER_WEBGL),o=t.getParameter(i.UNMASKED_VENDOR_WEBGL);return e&&e.parentNode&&e.parentNode.removeChild(e),e=void 0,t=void 0,{renderer:r,vendor:o}}function getErrorString(e){var t,i;return e instanceof Error&&e.code?`${e} | native.name=${null==(t=e.error)?void 0:t.name} native.message=${null==(i=e.error)?void 0:i.message}`:e instanceof Error?`NativeError: ${e.name} ${e.message}`:`UnknownError: ${e}`}const throttle=function(e,t,i={leading:!0,trailing:!0}){let r,o,s,n,a=0;function d(){a=!1===(null==i?void 0:i.leading)?0:Date.now(),r=null,n=e.apply(o,s),r||(o=null,s=null)}return function(...c){const l=Date.now();a||!1!==(null==i?void 0:i.leading)||(a=l);const u=t-(l-a);return o=this,s=c,u<=0||u>t?(r&&(clearTimeout(r),r=null),a=l,n=e.apply(o,s),r||(o=null,s=null)):r||!1===(null==i?void 0:i.trailing)||(r=setTimeout(d,u)),n}},detectorResults={};function getObjectFunctions(e,t){if(!e)return[];return Object.getOwnPropertyNames(e).filter((t=>{if("peerIdentity"===t)return!1;try{return"function"==typeof e[t]||void 0===e[t]}catch{return!1}})).map((i=>({obj:e,prefix:t,attr:i})))}function isNativeCode(e,t){try{return e[t].toString().includes("[native code]")?"native":"non-native"}catch(e){return"untouchable"}}const detectorList=("undefined"!=typeof window?[[null==(_k=window.RTCPeerConnection)?void 0:_k.prototype,"RTCPeerConnection.prototype"],[window.RTCPeerConnection,"RTCPeerConnection"],[null==(_l=window.RTCDataChannel)?void 0:_l.prototype,"RTCDataChannel.prototype"],[window.RTCDataChannel,"RTCDataChannel"],[null==(_m=window.MediaStreamTrack)?void 0:_m.prototype,"MediaStreamTrack.prototype"],[window.MediaStreamTrack,"MediaStreamTrack"],[null==(_n=window.MediaStream)?void 0:_n.prototype,"MediaStream.prototype"],[window.MediaStream,"MediaStream"],[null==(_o=window.HTMLAudioElement)?void 0:_o.prototype,"HTMLAudioElement.prototype"],[null==(_p=window.HTMLVideoElement)?void 0:_p.prototype,"HTMLVideoElement.prototype"],[null==(_q=window.HTMLMediaElement)?void 0:_q.prototype,"HTMLMediaElement.prototype"],[(null==(_r=window.AudioContext)?void 0:_r.prototype)??(null==(_s=window.webkitAudioContext)?void 0:_s.prototype),"AudioContext.prototype"],[null==(_t=window.BaseAudioContext)?void 0:_t.prototype,"BaseAudioContext.prototype"],[null==(_u=window.AudioNode)?void 0:_u.prototype,"AudioNode.prototype"],[window.navigator.mediaDevices,"navigator.mediaDevices"],[window.console,"console"]]:[]).reduce(((e,[t,i])=>e.concat(getObjectFunctions(t,i))),[]);"undefined"!=typeof window&&detectorList.push({obj:window.navigator.mediaDevices,prefix:"navigator.mediaDevices",attr:"getUserMedia"},{obj:window.navigator.mediaDevices,prefix:"navigator.mediaDevices",attr:"getDisplayMedia"},{obj:window.navigator.mediaDevices,prefix:"navigator.mediaDevices",attr:"enumerateDevices"},{obj:window.navigator.mediaDevices,prefix:"navigator.mediaDevices",attr:"getSupportedConstraints"});for(const{obj:e,prefix:t,attr:i}of detectorList){detectorResults[`${t}.${i}`]=isNativeCode(e,i)}isDebuggerMode&&console.log("RTC_AMBULANCE",detectorResults);const filtedResult=Object.entries(detectorResults).filter((([e,t])=>"non-native"===t)).map((([e,t])=>e));Object.keys(filtedResult).length&&console.warn("RTC_AMBULANCE","have non-native code:\n",filtedResult.join("\n"));let logDisabled_=!0,deprecationWarnings_=!0;function extractVersion(e,t,i){const r=e.match(t);return r&&r.length>=i&&parseInt(r[i],10)}function wrapPeerConnectionEvent(e,t,i){if(!e.RTCPeerConnection)return;const r=e.RTCPeerConnection.prototype,o=r.addEventListener;r.addEventListener=function(e,r){if(e!==t)return o.apply(this,arguments);const s=e=>{const t=i(e);t&&(r.handleEvent?r.handleEvent(t):r(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(r,s),o.apply(this,[e,s])};const s=r.removeEventListener;r.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t])return s.apply(this,arguments);if(!this._eventMap[t].has(i))return s.apply(this,arguments);const r=this._eventMap[t].get(i);return this._eventMap[t].delete(i),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,s.apply(this,[e,r])},Object.defineProperty(r,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function disableLog(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(logDisabled_=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function disableWarnings(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(deprecationWarnings_=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function log(){if("object"==typeof window){if(logDisabled_)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function deprecated(e,t){deprecationWarnings_&&console.warn(e+" is deprecated, please use "+t+" instead.")}function detectBrowser(e){const t={browser:null,version:null};if(void 0===e||!e.navigator||!e.navigator.userAgent)return t.browser="Not a browser.",t;const{navigator:i}=e;if(i.mozGetUserMedia)t.browser="firefox",t.version=extractVersion(i.userAgent,/Firefox\/(\d+)\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=extractVersion(i.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else{if(!e.RTCPeerConnection||!i.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=extractVersion(i.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}function isObject(e){return"[object Object]"===Object.prototype.toString.call(e)}function compactObject(e){return isObject(e)?Object.keys(e).reduce((function(t,i){const r=isObject(e[i]),o=r?compactObject(e[i]):e[i],s=r&&!Object.keys(o).length;return void 0===o||s?t:Object.assign(t,{[i]:o})}),{}):e}function walkStats(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach((r=>{r.endsWith("Id")?walkStats(e,e.get(t[r]),i):r.endsWith("Ids")&&t[r].forEach((t=>{walkStats(e,e.get(t),i)}))})))}function filterStats(e,t,i){const r=i?"outbound-rtp":"inbound-rtp",o=new Map;if(null===t)return o;const s=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&s.push(e)})),s.forEach((t=>{e.forEach((i=>{i.type===r&&i.trackId===t.id&&walkStats(e,i,o)}))})),o}const logging=log;function shimGetUserMedia$2(e,t){const i=e&&e.navigator;if(!i.mediaDevices)return;const r=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((i=>{if("require"===i||"advanced"===i||"mediaSource"===i)return;const r="object"==typeof e[i]?e[i]:{ideal:e[i]};void 0!==r.exact&&"number"==typeof r.exact&&(r.min=r.max=r.exact);const o=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==r.ideal){t.optional=t.optional||[];let e={};"number"==typeof r.ideal?(e[o("min",i)]=r.ideal,t.optional.push(e),e={},e[o("max",i)]=r.ideal,t.optional.push(e)):(e[o("",i)]=r.ideal,t.optional.push(e))}void 0!==r.exact&&"number"!=typeof r.exact?(t.mandatory=t.mandatory||{},t.mandatory[o("",i)]=r.exact):["min","max"].forEach((e=>{void 0!==r[e]&&(t.mandatory=t.mandatory||{},t.mandatory[o(e,i)]=r[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},o=function(e,o){if(t.version>=61)return o(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=r(e.audio)}if(e&&"object"==typeof e.video){let s=e.video.facingMode;s=s&&("object"==typeof s?s:{ideal:s});const n=t.version<66;if(s&&("user"===s.exact||"environment"===s.exact||"user"===s.ideal||"environment"===s.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||n)){let t;if(delete e.video.facingMode,"environment"===s.exact||"environment"===s.ideal?t=["back","rear"]:"user"!==s.exact&&"user"!==s.ideal||(t=["front"]),t)return i.mediaDevices.enumerateDevices().then((i=>{let n=(i=i.filter((e=>"videoinput"===e.kind))).find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!n&&i.length&&t.includes("back")&&(n=i[i.length-1]),n&&(e.video.deviceId=s.exact?{exact:n.deviceId}:{ideal:n.deviceId}),e.video=r(e.video),logging("chrome: "+JSON.stringify(e)),o(e)}))}e.video=r(e.video)}return logging("chrome: "+JSON.stringify(e)),o(e)},s=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(i.getUserMedia=function(e,t,r){o(e,(e=>{i.webkitGetUserMedia(e,t,(e=>{r&&r(s(e))}))}))}.bind(i),i.mediaDevices.getUserMedia){const e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(t){return o(t,(t=>e(t).then((e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach((e=>{e.stop()})),new DOMException("","NotFoundError");return e}),(e=>Promise.reject(s(e))))))}}}function shimGetDisplayMedia$1(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&("function"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function(i){return t(i).then((t=>{const r=i.video&&i.video.width,o=i.video&&i.video.height,s=i.video&&i.video.frameRate;return i.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:s||3}},r&&(i.video.mandatory.maxWidth=r),o&&(i.video.mandatory.maxHeight=o),e.navigator.mediaDevices.getUserMedia(i)}))}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}function shimMediaStream(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function shimOnTrack$1(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",(i=>{let r;r=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.track.id)):{track:i.track};const o=new Event("track");o.track=i.track,o.receiver=r,o.transceiver={receiver:r},o.streams=[t.stream],this.dispatchEvent(o)})),t.stream.getTracks().forEach((i=>{let r;r=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.id)):{track:i};const o=new Event("track");o.track=i,o.receiver=r,o.transceiver={receiver:r},o.streams=[t.stream],this.dispatchEvent(o)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else wrapPeerConnectionEvent(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function shimGetSendersWithDtmf(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const i=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,r){let o=i.apply(this,arguments);return o||(o=t(this,e),this._senders.push(o)),o};const r=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){r.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(t(this,e))}))};const r=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],r.apply(this,[e]),e.getTracks().forEach((e=>{const t=this._senders.find((t=>t.track===e));t&&this._senders.splice(this._senders.indexOf(t),1)}))}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function shimGetStats(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,i,r]=arguments;if(arguments.length>0&&"function"==typeof e)return t.apply(this,arguments);if(0===t.length&&(0===arguments.length||"function"!=typeof e))return t.apply(this,[]);const o=function(e){const t={};return e.result().forEach((e=>{const i={id:e.id,timestamp:e.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type};e.names().forEach((t=>{i[t]=e.stat(t)})),t[i.id]=i})),t},s=function(e){return new Map(Object.keys(e).map((t=>[t,e[t]])))};if(arguments.length>=2){const r=function(e){i(s(o(e)))};return t.apply(this,[r,e])}return new Promise(((e,i)=>{t.apply(this,[function(t){e(s(o(t)))},i])})).then(i,r)}}function shimSenderReceiverGetStats(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>filterStats(t,e.track,!0)))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),wrapPeerConnectionEvent(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>filterStats(t,e.track,!1)))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,i,r;return this.getSenders().forEach((i=>{i.track===e&&(t?r=!0:t=i)})),this.getReceivers().forEach((t=>(t.track===e&&(i?r=!0:i=t),t.track===e))),r||t&&i?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():i?i.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function shimAddTrackRemoveTrackWithNative(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((e=>this._shimmedLocalStreams[e][0]))};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){if(!i)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const r=t.apply(this,arguments);return this._shimmedLocalStreams[i.id]?-1===this._shimmedLocalStreams[i.id].indexOf(r)&&this._shimmedLocalStreams[i.id].push(r):this._shimmedLocalStreams[i.id]=[i,r],r};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")}));const t=this.getSenders();i.apply(this,arguments);const r=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(r)};const r=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],r.apply(this,arguments)};const o=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const i=this._shimmedLocalStreams[t].indexOf(e);-1!==i&&this._shimmedLocalStreams[t].splice(i,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),o.apply(this,arguments)}}function shimAddTrackRemoveTrack(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return shimAddTrackRemoveTrackWithNative(e);const i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=i.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){const i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i}r.apply(this,[t])};const o=e.RTCPeerConnection.prototype.removeStream;function s(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const r=e._reverseStreams[t],o=e._streams[r.id];i=i.replace(new RegExp(o.id,"g"),r.id)})),new RTCSessionDescription({type:t.type,sdp:i})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},o.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,i){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const r=[].slice.call(arguments,1);if(1!==r.length||!r[0].getTracks().find((e=>e===t)))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find((e=>e.track===t)))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const o=this._streams[i.id];if(o)o.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const r=new e.MediaStream([t]);this._streams[i.id]=r,this._reverseStreams[r.id]=i,this.addStream(r)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],r={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?i.apply(this,[t=>{const i=s(this,t);e[0].apply(null,[i])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):i.apply(this,arguments).then((e=>s(this,e)))}};e.RTCPeerConnection.prototype[t]=r[t]}));const n=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const r=e._reverseStreams[t],o=e._streams[r.id];i=i.replace(new RegExp(r.id,"g"),o.id)})),new RTCSessionDescription({type:t.type,sdp:i})}(this,arguments[0]),n.apply(this,arguments)):n.apply(this,arguments)};const a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=a.get.apply(this);return""===e.type?e:s(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(e._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach((i=>{this._streams[i].getTracks().find((t=>e.track===t))&&(t=this._streams[i])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function shimPeerConnection$1(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],r={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=r[t]}))}function fixNegotiationNeeded(e,t){wrapPeerConnectionEvent(e,"negotiationneeded",(e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e}))}var chromeShim=Object.freeze({__proto__:null,fixNegotiationNeeded:fixNegotiationNeeded,shimAddTrackRemoveTrack:shimAddTrackRemoveTrack,shimAddTrackRemoveTrackWithNative:shimAddTrackRemoveTrackWithNative,shimGetDisplayMedia:shimGetDisplayMedia$1,shimGetSendersWithDtmf:shimGetSendersWithDtmf,shimGetStats:shimGetStats,shimGetUserMedia:shimGetUserMedia$2,shimMediaStream:shimMediaStream,shimOnTrack:shimOnTrack$1,shimPeerConnection:shimPeerConnection$1,shimSenderReceiverGetStats:shimSenderReceiverGetStats});function shimGetUserMedia$1(e,t){const i=e&&e.navigator,r=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,r){deprecated("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),i.mediaDevices.getUserMedia(e).then(t,r)},!(t.version>55&&"autoGainControl"in i.mediaDevices.getSupportedConstraints())){const e=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])},t=i.mediaDevices.getUserMedia.bind(i.mediaDevices);if(i.mediaDevices.getUserMedia=function(i){return"object"==typeof i&&"object"==typeof i.audio&&(i=JSON.parse(JSON.stringify(i)),e(i.audio,"autoGainControl","mozAutoGainControl"),e(i.audio,"noiseSuppression","mozNoiseSuppression")),t(i)},r&&r.prototype.getSettings){const t=r.prototype.getSettings;r.prototype.getSettings=function(){const i=t.apply(this,arguments);return e(i,"mozAutoGainControl","autoGainControl"),e(i,"mozNoiseSuppression","noiseSuppression"),i}}if(r&&r.prototype.applyConstraints){const t=r.prototype.applyConstraints;r.prototype.applyConstraints=function(i){return"audio"===this.kind&&"object"==typeof i&&(i=JSON.parse(JSON.stringify(i)),e(i,"autoGainControl","mozAutoGainControl"),e(i,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[i])}}}}function shimGetDisplayMedia(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(i){if(!i||!i.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===i.video?i.video={mediaSource:t}:i.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(i)})}function shimOnTrack(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function shimPeerConnection(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],r={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=r[t]}));const i={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},r=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,o,s]=arguments;return r.apply(this,[e||null]).then((e=>{if(t.version<53&&!o)try{e.forEach((e=>{e.type=i[e.type]||e.type}))}catch(t){if("TypeError"!==t.name)throw t;e.forEach(((t,r)=>{e.set(r,Object.assign({},t,{type:i[t.type]||t.type}))}))}return e})).then(o,s)}}function shimSenderGetStats(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function shimReceiverGetStats(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),wrapPeerConnectionEvent(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function shimRemoveStream(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){deprecated("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function shimRTCDataChannel(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function shimAddTransceiver(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const i=e.length>0;i&&e.forEach((e=>{if("rid"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));const r=t.apply(this,arguments);if(i){const{sender:t}=r,i=t.getParameters();(!("encodings"in i)||1===i.encodings.length&&0===Object.keys(i.encodings[0]).length)&&(i.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(i).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return r})}function shimGetParameters(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function shimCreateOffer(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}function shimCreateAnswer(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}var firefoxShim=Object.freeze({__proto__:null,shimAddTransceiver:shimAddTransceiver,shimCreateAnswer:shimCreateAnswer,shimCreateOffer:shimCreateOffer,shimGetDisplayMedia:shimGetDisplayMedia,shimGetParameters:shimGetParameters,shimGetUserMedia:shimGetUserMedia$1,shimOnTrack:shimOnTrack,shimPeerConnection:shimPeerConnection,shimRTCDataChannel:shimRTCDataChannel,shimReceiverGetStats:shimReceiverGetStats,shimRemoveStream:shimRemoveStream,shimSenderGetStats:shimSenderGetStats});function shimLocalStreamsAPI(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach((i=>t.call(this,i,e))),e.getVideoTracks().forEach((i=>t.call(this,i,e)))},e.RTCPeerConnection.prototype.addTrack=function(e,...i){return i&&i.forEach((e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]})),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const i=e.getTracks();this.getSenders().forEach((e=>{i.includes(e.track)&&this.removeTrack(e)}))})}}function shimRemoteStreamsAPI(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach((e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t)}))})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach((t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const i=new Event("addstream");i.stream=t,e.dispatchEvent(i)}))}),t.apply(e,arguments)}}}function shimCallbacksAPI(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,i=t.createOffer,r=t.createAnswer,o=t.setLocalDescription,s=t.setRemoteDescription,n=t.addIceCandidate;t.createOffer=function(e,t){const r=arguments.length>=2?arguments[2]:arguments[0],o=i.apply(this,[r]);return t?(o.then(e,t),Promise.resolve()):o},t.createAnswer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],o=r.apply(this,[i]);return t?(o.then(e,t),Promise.resolve()):o};let a=function(e,t,i){const r=o.apply(this,[e]);return i?(r.then(t,i),Promise.resolve()):r};t.setLocalDescription=a,a=function(e,t,i){const r=s.apply(this,[e]);return i?(r.then(t,i),Promise.resolve()):r},t.setRemoteDescription=a,a=function(e,t,i){const r=n.apply(this,[e]);return i?(r.then(t,i),Promise.resolve()):r},t.addIceCandidate=a}function shimGetUserMedia(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,i=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>i(shimConstraints(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,r){t.mediaDevices.getUserMedia(e).then(i,r)}.bind(t))}function shimConstraints(e){return e&&void 0!==e.video?Object.assign({},e,{video:compactObject(e.video)}):e}function shimRTCIceServerUrls(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,i){if(e&&e.iceServers){const t=[];for(let i=0;i<e.iceServers.length;i++){let r=e.iceServers[i];void 0===r.urls&&r.url?(deprecated("RTCIceServer.url","RTCIceServer.urls"),r=JSON.parse(JSON.stringify(r)),r.urls=r.url,delete r.url,t.push(r)):t.push(e.iceServers[i])}e.iceServers=t}return new t(e,i)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function shimTrackEventTransceiver(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function shimCreateOfferLegacy(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find((e=>"audio"===e.receiver.track.kind));!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const i=this.getTransceivers().find((e=>"video"===e.receiver.track.kind));!1===e.offerToReceiveVideo&&i?"sendrecv"===i.direction?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":"recvonly"===i.direction&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):!0!==e.offerToReceiveVideo||i||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function shimAudioContext(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var safariShim=Object.freeze({__proto__:null,shimAudioContext:shimAudioContext,shimCallbacksAPI:shimCallbacksAPI,shimConstraints:shimConstraints,shimCreateOfferLegacy:shimCreateOfferLegacy,shimGetUserMedia:shimGetUserMedia,shimLocalStreamsAPI:shimLocalStreamsAPI,shimRTCIceServerUrls:shimRTCIceServerUrls,shimRemoteStreamsAPI:shimRemoteStreamsAPI,shimTrackEventTransceiver:shimTrackEventTransceiver}),sdp$1={exports:{}};!function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((e=>e.trim()))},t.splitSections=function(e){return e.split("\nm=").map(((e,t)=>(t>0?"m="+e:e).trim()+"\r\n"))},t.getDescription=function(e){const i=t.splitSections(e);return i&&i[0]},t.getMediaSections=function(e){const i=t.splitSections(e);return i.shift(),i},t.matchPrefix=function(e,i){return t.splitLines(e).filter((e=>0===e.indexOf(i)))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const i={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let e=8;e<t.length;e+=2)switch(t[e]){case"raddr":i.relatedAddress=t[e+1];break;case"rport":i.relatedPort=parseInt(t[e+1],10);break;case"tcptype":i.tcpType=t[e+1];break;case"ufrag":i.ufrag=t[e+1],i.usernameFragment=t[e+1];break;default:void 0===i[t[e]]&&(i[t[e]]=t[e+1])}return i},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const i=e.component;"rtp"===i?t.push(1):"rtcp"===i?t.push(2):t.push(i),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const r=e.type;return t.push("typ"),t.push(r),"host"!==r&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substring(14).split(" ")},t.parseRtpMap=function(e){let t=e.substring(9).split(" ");const i={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),i.name=t[0],i.clockRate=parseInt(t[1],10),i.channels=3===t.length?parseInt(t[2],10):1,i.numChannels=i.channels,i},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const i=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==i?"/"+i:"")+"\r\n"},t.parseExtmap=function(e){const t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let i;const r=e.substring(e.indexOf(" ")+1).split(";");for(let e=0;e<r.length;e++)i=r[e].trim().split("="),t[i[0].trim()]=i[1];return t},t.writeFmtp=function(e){let t="",i=e.payloadType;if(void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const r=[];Object.keys(e.parameters).forEach((t=>{void 0!==e.parameters[t]?r.push(t+"="+e.parameters[t]):r.push(t)})),t+="a=fmtp:"+i+" "+r.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",i=e.payloadType;return void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((e=>{t+="a=rtcp-fb:"+i+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),i={ssrc:parseInt(e.substring(7,t),10)},r=e.indexOf(":",t);return r>-1?(i.attribute=e.substring(t+1,r),i.value=e.substring(r+1)):i.attribute=e.substring(t+1),i},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((e=>parseInt(e,10)))}},t.getMid=function(e){const i=t.matchPrefix(e,"a=mid:")[0];if(i)return i.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,i){return{role:"auto",fingerprints:t.matchPrefix(e+i,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let i="a=setup:"+t+"\r\n";return e.fingerprints.forEach((e=>{i+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),i},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,i){return t.matchPrefix(e+i,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,i){const r=t.matchPrefix(e+i,"a=ice-ufrag:")[0],o=t.matchPrefix(e+i,"a=ice-pwd:")[0];return r&&o?{usernameFragment:r.substring(12),password:o.substring(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},r=t.splitLines(e)[0].split(" ");i.profile=r[2];for(let o=3;o<r.length;o++){const s=r[o],n=t.matchPrefix(e,"a=rtpmap:"+s+" ")[0];if(n){const r=t.parseRtpMap(n),o=t.matchPrefix(e,"a=fmtp:"+s+" ");switch(r.parameters=o.length?t.parseFmtp(o[0]):{},r.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+s+" ").map(t.parseRtcpFb),i.codecs.push(r),r.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(r.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach((e=>{i.headerExtensions.push(t.parseExtmap(e))}));const o=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return i.codecs.forEach((e=>{o.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),i},t.writeRtpDescription=function(e,i){let r="";r+="m="+e+" ",r+=i.codecs.length>0?"9":"0",r+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",r+=i.codecs.map((e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType)).join(" ")+"\r\n",r+="c=IN IP4 0.0.0.0\r\n",r+="a=rtcp:9 IN IP4 0.0.0.0\r\n",i.codecs.forEach((e=>{r+=t.writeRtpMap(e),r+=t.writeFmtp(e),r+=t.writeRtcpFb(e)}));let o=0;return i.codecs.forEach((e=>{e.maxptime>o&&(o=e.maxptime)})),o>0&&(r+="a=maxptime:"+o+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach((e=>{r+=t.writeExtmap(e)})),r},t.parseRtpEncodingParameters=function(e){const i=[],r=t.parseRtpParameters(e),o=-1!==r.fecMechanisms.indexOf("RED"),s=-1!==r.fecMechanisms.indexOf("ULPFEC"),n=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),a=n.length>0&&n[0].ssrc;let d;const c=t.matchPrefix(e,"a=ssrc-group:FID").map((e=>e.substring(17).split(" ").map((e=>parseInt(e,10)))));c.length>0&&c[0].length>1&&c[0][0]===a&&(d=c[0][1]),r.codecs.forEach((e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&d&&(t.rtx={ssrc:d}),i.push(t),o&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:s?"red+ulpfec":"red"},i.push(t))}})),0===i.length&&a&&i.push({ssrc:a});let l=t.matchPrefix(e,"b=");return l.length&&(l=0===l[0].indexOf("b=TIAS:")?parseInt(l[0].substring(7),10):0===l[0].indexOf("b=AS:")?1e3*parseInt(l[0].substring(5),10)*.95-16e3:void 0,i.forEach((e=>{e.maxBitrate=l}))),i},t.parseRtcpParameters=function(e){const i={},r=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];r&&(i.cname=r.value,i.ssrc=r.ssrc);const o=t.matchPrefix(e,"a=rtcp-rsize");i.reducedSize=o.length>0,i.compound=0===o.length;const s=t.matchPrefix(e,"a=rtcp-mux");return i.mux=s.length>0,i},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},t.parseMsid=function(e){let i;const r=t.matchPrefix(e,"a=msid:");if(1===r.length)return i=r[0].substring(7).split(" "),{stream:i[0],track:i[1]};const o=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return o.length>0?(i=o[0].value.split(" "),{stream:i[0],track:i[1]}):void 0},t.parseSctpDescription=function(e){const i=t.parseMLine(e),r=t.matchPrefix(e,"a=max-message-size:");let o;r.length>0&&(o=parseInt(r[0].substring(19),10)),isNaN(o)&&(o=65536);const s=t.matchPrefix(e,"a=sctp-port:");if(s.length>0)return{port:parseInt(s[0].substring(12),10),protocol:i.fmt,maxMessageSize:o};const n=t.matchPrefix(e,"a=sctpmap:");if(n.length>0){const e=n[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:o}}},t.writeSctpDescription=function(e,t){let i=[];return i="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&i.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),i.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,i,r){let o;const s=void 0!==i?i:2;o=e||t.generateSessionId();return"v=0\r\no="+(r||"thisisadapterortc")+" "+o+" "+s+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,i){const r=t.splitLines(e);for(let e=0;e<r.length;e++)switch(r[e]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return r[e].substring(2)}return i?t.getDirection(i):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const i=t.splitLines(e)[0].substring(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},t.parseOLine=function(e){const i=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:i[0],sessionId:i[1],sessionVersion:parseInt(i[2],10),netType:i[3],addressType:i[4],address:i[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const i=t.splitLines(e);for(let e=0;e<i.length;e++)if(i[e].length<2||"="!==i[e].charAt(1))return!1;return!0},e.exports=t}(sdp$1);var sdpExports=sdp$1.exports,SDPUtils=getDefaultExportFromCjs(sdpExports),sdp=_mergeNamespaces({__proto__:null,default:SDPUtils},[sdpExports]);function shimRTCIceCandidate(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substring(2)),e.candidate&&e.candidate.length){const i=new t(e),r=SDPUtils.parseCandidate(e.candidate);for(const e in r)e in i||Object.defineProperty(i,e,{value:r[e]});return i.toJSON=function(){return{candidate:i.candidate,sdpMid:i.sdpMid,sdpMLineIndex:i.sdpMLineIndex,usernameFragment:i.usernameFragment}},i}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,wrapPeerConnectionEvent(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function shimRTCIceCandidateRelayProtocol(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||wrapPeerConnectionEvent(e,"icecandidate",(e=>{if(e.candidate){const t=SDPUtils.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function shimMaxMessageSize(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(function(e){if(!e||!e.sdp)return!1;const t=SDPUtils.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=SDPUtils.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))}(arguments[0])){const e=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const i=parseInt(t[1],10);return i!=i?-1:i}(arguments[0]),i=function(e){let i=65536;return"firefox"===t.browser&&(i=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),i}(e),r=function(e,i){let r=65536;"firefox"===t.browser&&57===t.version&&(r=65535);const o=SDPUtils.matchPrefix(e.sdp,"a=max-message-size:");return o.length>0?r=parseInt(o[0].substring(19),10):"firefox"===t.browser&&-1!==i&&(r=2147483637),r}(arguments[0],e);let o;o=0===i&&0===r?Number.POSITIVE_INFINITY:0===i||0===r?Math.max(i,r):Math.min(i,r);const s={};Object.defineProperty(s,"maxMessageSize",{get:()=>o}),this._sctp=s}return i.apply(this,arguments)}}function shimSendThrowTypeError(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const i=e.send;e.send=function(){return i.apply(e,arguments)}}const i=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=i.apply(this,arguments);return t(e),e},wrapPeerConnectionEvent(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function shimConnectionState(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;const t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach((e=>{const i=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{const t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;const i=new Event("connectionstatechange",e);t.dispatchEvent(i)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}}))}function removeExtmapAllowMixed(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t.version>=605)return;const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const i=t.sdp.split("\n").filter((e=>"a=extmap-allow-mixed"!==e.trim())).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:i}):t.sdp=i}return i.apply(this,arguments)}}function shimAddIceCandidateNullOrEmpty(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.addIceCandidate;i&&0!==i.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():i.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function shimParameterlessSetLocalDescription(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.setLocalDescription;i&&0!==i.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return i.apply(this,arguments);if(e={type:e.type,sdp:e.sdp},!e.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":e.type="offer";break;default:e.type="answer"}if(e.sdp||"offer"!==e.type&&"answer"!==e.type)return i.apply(this,[e]);return("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then((e=>i.apply(this,[e])))})}var commonShim=Object.freeze({__proto__:null,removeExtmapAllowMixed:removeExtmapAllowMixed,shimAddIceCandidateNullOrEmpty:shimAddIceCandidateNullOrEmpty,shimConnectionState:shimConnectionState,shimMaxMessageSize:shimMaxMessageSize,shimParameterlessSetLocalDescription:shimParameterlessSetLocalDescription,shimRTCIceCandidate:shimRTCIceCandidate,shimRTCIceCandidateRelayProtocol:shimRTCIceCandidateRelayProtocol,shimSendThrowTypeError:shimSendThrowTypeError});function adapterFactory({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const i=log,r=detectBrowser(e),o={browserDetails:r,commonShim:commonShim,extractVersion:extractVersion,disableLog:disableLog,disableWarnings:disableWarnings,sdp:sdp};switch(r.browser){case"chrome":if(!chromeShim||!shimPeerConnection$1||!t.shimChrome)return i("Chrome shim is not included in this adapter release."),o;if(null===r.version)return i("Chrome shim can not determine version, not shimming."),o;i("adapter.js shimming chrome."),o.browserShim=chromeShim,shimAddIceCandidateNullOrEmpty(e,r),shimParameterlessSetLocalDescription(e),shimGetUserMedia$2(e,r),shimMediaStream(e),shimPeerConnection$1(e,r),shimOnTrack$1(e),shimAddTrackRemoveTrack(e,r),shimGetSendersWithDtmf(e),shimGetStats(e),shimSenderReceiverGetStats(e),fixNegotiationNeeded(e,r),shimRTCIceCandidate(e),shimRTCIceCandidateRelayProtocol(e),shimConnectionState(e),shimMaxMessageSize(e,r),shimSendThrowTypeError(e),removeExtmapAllowMixed(e,r);break;case"firefox":if(!firefoxShim||!shimPeerConnection||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),o;i("adapter.js shimming firefox."),o.browserShim=firefoxShim,shimAddIceCandidateNullOrEmpty(e,r),shimParameterlessSetLocalDescription(e),shimGetUserMedia$1(e,r),shimPeerConnection(e,r),shimOnTrack(e),shimRemoveStream(e),shimSenderGetStats(e),shimReceiverGetStats(e),shimRTCDataChannel(e),shimAddTransceiver(e),shimGetParameters(e),shimCreateOffer(e),shimCreateAnswer(e),shimRTCIceCandidate(e),shimConnectionState(e),shimMaxMessageSize(e,r),shimSendThrowTypeError(e);break;case"safari":if(!safariShim||!t.shimSafari)return i("Safari shim is not included in this adapter release."),o;i("adapter.js shimming safari."),o.browserShim=safariShim,shimAddIceCandidateNullOrEmpty(e,r),shimParameterlessSetLocalDescription(e),shimRTCIceServerUrls(e),shimCreateOfferLegacy(e),shimCallbacksAPI(e),shimLocalStreamsAPI(e),shimRemoteStreamsAPI(e),shimTrackEventTransceiver(e),shimGetUserMedia(e),shimAudioContext(e),shimRTCIceCandidate(e),shimRTCIceCandidateRelayProtocol(e),shimMaxMessageSize(e,r),shimSendThrowTypeError(e),removeExtmapAllowMixed(e,r);break;default:i("Unsupported browser!")}return o}if(adapterFactory({window:"undefined"==typeof window?void 0:window}),"undefined"!=typeof MediaStreamTrack){const e=MediaStreamTrack.prototype.getSettings;MediaStreamTrack.prototype.getSettings=function(){const t=e.call(this);return t.width&&(t.width=Math.floor(t.width)),t.height&&(t.height=Math.floor(t.height)),t.frameRate&&(t.frameRate=Math.floor(t.frameRate)),t}}var eventemitter3={exports:{}};!function(e){var t=Object.prototype.hasOwnProperty,i="~";function r(){}function o(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function s(e,t,r,s,n){if("function"!=typeof r)throw new TypeError("The listener must be a function");var a=new o(r,s||e,n),d=i?i+t:t;return e._events[d]?e._events[d].fn?e._events[d]=[e._events[d],a]:e._events[d].push(a):(e._events[d]=a,e._eventsCount++),e}function n(e,t){0==--e._eventsCount?e._events=new r:delete e._events[t]}function a(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),(new r).__proto__||(i=!1)),a.prototype.eventNames=function(){var e,r,o=[];if(0===this._eventsCount)return o;for(r in e=this._events)t.call(e,r)&&o.push(i?r.slice(1):r);return Object.getOwnPropertySymbols?o.concat(Object.getOwnPropertySymbols(e)):o},a.prototype.listeners=function(e){var t=i?i+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var o=0,s=r.length,n=new Array(s);o<s;o++)n[o]=r[o].fn;return n},a.prototype.listenerCount=function(e){var t=i?i+e:e,r=this._events[t];return r?r.fn?1:r.length:0},a.prototype.emit=function(e,t,r,o,s,n){var a=i?i+e:e;if(!this._events[a])return!1;var d,c,l=this._events[a],u=arguments.length;if(l.fn){switch(l.once&&this.removeListener(e,l.fn,void 0,!0),u){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,t),!0;case 3:return l.fn.call(l.context,t,r),!0;case 4:return l.fn.call(l.context,t,r,o),!0;case 5:return l.fn.call(l.context,t,r,o,s),!0;case 6:return l.fn.call(l.context,t,r,o,s,n),!0}for(c=1,d=new Array(u-1);c<u;c++)d[c-1]=arguments[c];l.fn.apply(l.context,d)}else{var _,h=l.length;for(c=0;c<h;c++)switch(l[c].once&&this.removeListener(e,l[c].fn,void 0,!0),u){case 1:l[c].fn.call(l[c].context);break;case 2:l[c].fn.call(l[c].context,t);break;case 3:l[c].fn.call(l[c].context,t,r);break;case 4:l[c].fn.call(l[c].context,t,r,o);break;default:if(!d)for(_=1,d=new Array(u-1);_<u;_++)d[_-1]=arguments[_];l[c].fn.apply(l[c].context,d)}}return!0},a.prototype.on=function(e,t,i){return s(this,e,t,i,!1)},a.prototype.once=function(e,t,i){return s(this,e,t,i,!0)},a.prototype.removeListener=function(e,t,r,o){var s=i?i+e:e;if(!this._events[s])return this;if(!t)return n(this,s),this;var a=this._events[s];if(a.fn)a.fn!==t||o&&!a.once||r&&a.context!==r||n(this,s);else{for(var d=0,c=[],l=a.length;d<l;d++)(a[d].fn!==t||o&&!a[d].once||r&&a[d].context!==r)&&c.push(a[d]);c.length?this._events[s]=1===c.length?c[0]:c:n(this,s)}return this},a.prototype.removeAllListeners=function(e){var t;return e?(t=i?i+e:e,this._events[t]&&n(this,t)):(this._events=new r,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=i,a.EventEmitter=a,e.exports=a}(eventemitter3);var eventemitter3Exports=eventemitter3.exports,EventEmitter2=getDefaultExportFromCjs(eventemitter3Exports);const logger$a=new Logger$1("VERTC",0);class EnhancedEventEmitter extends eventemitter3Exports.EventEmitter{safeEmit(e,...t){const i=this.listenerCount(e);try{return super.emit(e,...t)}catch(t){return logger$a.error("safeEmit","safeEmit() | event listener threw an error [event:%s]:%o",e,t),console.error(t),Boolean(i)}}async asyncEmit(e,...t){await Promise.resolve().then((()=>{try{super.emit(e,...t)}catch(t){logger$a.error("safeEmit","safeEmit() | event listener threw an error [event:%s]:%o",e,t),console.error(t)}}))}}var SEIStreamEventType=(e=>(e[e.BLACK=0]="BLACK",e[e.NORMAL=1]="NORMAL",e))(SEIStreamEventType||{}),RemoveStreamMessage=(e=>(e.streamRemovedBySchedule308="stream removed",e.clientRePublish="client republish",e.publishStreamFaied="publish failed",e.clientUnPublish="client unpublished",e.clientDisconnected="client disconnected",e.videoMuted="video muted",e))(RemoveStreamMessage||{}),StreamControlType=(e=>(e.PushLimitWarn="PushLimitWarn",e.OTHER="OTHER",e))(StreamControlType||{}),EngineControlType=(e=>(e.CHANGE_CODEC="changeCodec",e))(EngineControlType||{}),SignalEvent=(e=>(e.ON_ADD_STREAM="onAddStream",e.ON_ADD_STREAM_LIST="onAddStreamList",e.ON_REMOVE_STREAM="onRemoveStream",e.ON_REMOVE_STREAM_LIST="onRemoveStreamList",e.USER_DISCONNECTION="userDisconnection",e.USER_DISCONNECTION_LIST="userDisconnectionList",e.USER_CONNECTION="userConnection",e.USER_CONNECTION_LIST="userConnectionList",e.ON_UPDATE_STREAM_ATTRIBUTES="onUpdateStreamAttributes",e.ON_UPDATE_ROOM_ATTRIBUTES="onUpdateRoomAttributes",e.ON_UPDATE_USER_ATTRIBUTES="onUpdateUserAttributes",e.ON_PUSH_TRACK="onPushTrack",e.ON_REMOVE_TRACK="onRemoveTrack",e.ON_CUSTOM_MESSAGE="onCustomMessage",e.NODE_CHANGE="nodeChange",e.USER_MESSAGE_RECEIVED="userMessageReceived",e.USER_BINARY_MESSAGE_RECEIVED="userBinaryMessageReceived",e.USER_MESSAGE_RECEIVED_OUTSIDE_ROOM="userMessageReceivedOutsideRoom",e.USER_BINARY_MESSAGE_RECEIVED_OUTSIDE_ROOM="userBinaryMessageReceivedOutsideRoom",e.POST_PROCESSING_MESSAGE="postProcessingMessage",e.ON_USER_TOKEN_WILL_EXPIRE="onUserTokenWillExpire",e.ON_TOKEN_PUBLISH_PRIVILEGE_WILL_EXPIRE="onTokenPublishPrivilegeWillExpire",e.ON_TOKEN_PUBLISH_PRIVILEGE_DID_EXPIRED="onTokenPublishPrivilegeDidExpired",e.ON_TOKEN_SUBSCRIBE_PRIVILEGE_WILL_EXPIRE="onTokenSubscribePrivilegeWillExpire",e.ON_TOKEN_SUBSCRIBE_PRIVILEGE_DID_EXPIRED="onTokenSubscribePrivilegeDidExpired",e.STREAM_CONTROL_MESSAGE="streamControlMessage",e.ON_SPEAKER_CHANGE="onSpeakerChange",e.ON_STREAM_FAILED="streamFailed",e.ON_NOTIFY_RECONNECT="notifyReconnect",e.ON_FORWARD_DST_ROOM_USER_KICK="onForwardDstRoomUserKick",e.ENGINE_CONTROL_MESSAGE="engineControlMessage",e.ON_STREAM_PUSHED_BY_OTHER="onStreamPushedByOther",e.ON_STREAM_PULL_STATE_CHANGED="onStreamPullStateChanged",e))(SignalEvent||{}),MediaServerSignalEvent=(e=>(e.RSCP="RSCP",e.RTT="RTT",e.SSC="SSC",e))(MediaServerSignalEvent||{}),StateEvent=(e=>(e.ON_CONNECTION_STATE_CHANGE="onConnectionStateChange",e.ON_VENDOR_CONNECTION_STATE_CHANGE="onVendorConnectionStateChange",e.ABNORMAL_DISCONNECTION="normalConnection",e.ON_RECONNECT_FAILED="onReconnectFailed",e.CONNECT_WITH_TCP="onIceConnectWithTcp",e))(StateEvent||{}),UserDisconnectionTag=(e=>(e.userLeave="userLeave",e.connectionLost="connectionLost",e.userDuplicateLogin="userDuplicateLogin",e.kickedByAdmin="kickedByAdmin",e.roleChanged="roleChanged",e.onUserTokenDidExpire="onUserTokenDidExpire",e))(UserDisconnectionTag||{}),UserDisconnectionCode=(e=>(e[e.roomDismissByAdmin=2]="roomDismissByAdmin",e))(UserDisconnectionCode||{}),RTS_MODE=(e=>(e[e.LIMIT_MODE=1]="LIMIT_MODE",e[e.NORMAL_MODE=2]="NORMAL_MODE",e))(RTS_MODE||{}),VideoType=(e=>(e[e.NORMAL=0]="NORMAL",e[e.BLACK=1]="BLACK",e))(VideoType||{}),SourceType=(e=>(e[e.EXTERNAL=0]="EXTERNAL",e[e.INTERNAL=1]="INTERNAL",e))(SourceType||{}),MediaType=(e=>(e.AUDIO="audio",e.VIDEO="video",e))(MediaType||{}),ExtendStreamIndex=(e=>(e.MAIN="main",e.SCREEN="screen",e.PUBLIC="public",e.VIRTUAL="virtual",e))(ExtendStreamIndex||{});class Track extends EnhancedEventEmitter{constructor(e,t,i){super(),__publicField(this,"trackId",genUuid()),__publicField(this,"_logger"),__publicField(this,"trackInfo"),__publicField(this,"_originTrack"),__publicField(this,"_channelCount"),this._ctx=e,this._logger=new Logger$1("Track",4,e.id),this.trackInfo=i,this._originTrack=t,this._channelCount=t.getSettings().channelCount}get dummy(){return this.trackInfo.isDummy}get virtual(){return"virtual"===this.trackInfo.streamIndex}get isScreen(){return"screen"===this.trackInfo.streamIndex}get isPublic(){return"public"===this.trackInfo.streamIndex}get sourceType(){return this.trackInfo.sourceType}get mediaType(){return this.trackInfo.mediaType}get captureSessionId(){return this.trackInfo.captureSessionId}get streamIndex(){const{streamIndex:e}=this.trackInfo;return"main"===e?StreamIndex$1.STREAM_INDEX_MAIN:"screen"===e?StreamIndex$1.STREAM_INDEX_SCREEN:void 0}get channelCount(){return this._channelCount??0}get originTrack(){return this._originTrack}set originTrack(e){this._originTrack=e,this._channelCount=mediaTrack.getSettings().channelCount}get logger(){return this._logger.module=this.constructor.name,this._logger}destroy(){this._originTrack.stop()}}class LocalTrack extends Track{constructor(e,t,i){super(e,t,i),__publicField(this,"_mediaTrack"),__publicField(this,"_preProcessingTrack"),__publicField(this,"isTrackReady"),__publicField(this,"handleTrackEnded",(()=>{this.emit("track-ended",this),this.destroy()})),__publicField(this,"handleMute",(()=>{this.emit("track-mute",this)})),__publicField(this,"handleUnmute",(()=>{this.emit("track-unmute",this)})),this._initListeners(),this.isTrackReady=this.generatePreProcessingTrack()}get mediaTrack(){return this._mediaTrack??this._originTrack}set mediaTrack(e){this.mediaTrack.id!==e.id&&(this._mediaTrack=e,this.isTrackReady=this.generatePreProcessingTrack())}get preprocessingTrack(){return this._preProcessingTrack??this.mediaTrack}async generatePreProcessingTrack(){var e;const t=null==(e=this._preProcessingTrack)?void 0:e.id;this._preProcessingTrack=void 0;try{const e=await this._ctx.extensionManager.getPreProcessingTrack(this);e instanceof MediaStreamTrack&&(this._preProcessingTrack=e,t!==this._preProcessingTrack.id&&setTimeout((()=>{this.emit("needReplaceTrack")})))}catch(e){console.error(e)}}destroy(){var e,t;this._originTrack.removeEventListener("ended",this.handleTrackEnded),this._originTrack.removeEventListener("mute",this.handleMute),this._originTrack.removeEventListener("unmute",this.handleUnmute),null==(e=this._preProcessingTrack)||e.stop(),null==(t=this._mediaTrack)||t.stop(),super.destroy()}_initListeners(){this._originTrack instanceof MediaStreamTrack&&(this._originTrack.addEventListener("ended",this.handleTrackEnded),this._originTrack.addEventListener("mute",this.handleMute),this._originTrack.addEventListener("unmute",this.handleUnmute))}}class RemoteTrack extends Track{constructor(e,t,i){super(e,t,i),__publicField(this,"_mediaTrack"),this._originTrack=t}get mediaTrack(){return this._mediaTrack??this._originTrack}set mediaTrack(e){this.mediaTrack.id!==e.id&&(this._mediaTrack=e)}get preprocessingTrack(){return this.mediaTrack}}var RTC_SEI_TYPE=(e=>(e[e.internal=0]="internal",e[e.external=1]="external",e[e.bypass=2]="bypass",e))(RTC_SEI_TYPE||{});const EPB=3,MAX_NUMBER_OF_CONSECUTIVE_ZEROS=2,UUID_INTERNAL=new Uint8Array([109,167,53,190,103,90,72,1,170,89,63,164,194,199,19,85]),UUID_EXTERNAL=new Uint8Array([109,167,53,190,103,90,72,1,170,89,63,164,194,199,19,84]),UUID_EXTERNAL_2=new Uint8Array([31,239,3,50,242,120,76,85,169,42,161,91,75,186,22]),rbsp2ebsp=e=>{const t=[];let i=0;for(const r of e)i>=2&&r<=3&&(t.push(3),i=0),0===r?i++:i=0,t.push(r);return new Uint8Array(t)},ebsp2rbsp=e=>{const t=[];for(let i=0;i<e.length;i++)e[i]<=3&&0===e[i-1]&&0===e[i-2]||t.push(e[i]);return new Uint8Array(t)};function serializeData(e){const t=[];for(;e>=255;)e-=255,t.push(255);return t.push(e),new Uint8Array(t)}function deserializeData(e,t=0){let i=0;for(;255===e[t]&&t<e.byteLength;)t++,i+=255;return t<e.byteLength&&(i+=e[t++]),[i,t]}const HEVC_SEI_NALU_HEADER=new Uint8Array([80,1]),_SEIHelper=class{static generateSEI(e,t,i=!1){const r=new Uint8Array([0,0,0,1]),o=t?HEVC_SEI_NALU_HEADER:new Uint8Array([6]),s=new Uint8Array([5]),n=_SEIHelper.__uuid||(i?UUID_INTERNAL:UUID_EXTERNAL),a=serializeData(e.byteLength+n.byteLength),d=rbsp2ebsp(e);return new Uint8Array([...r,...o,...s,...a,...n,...d,128])}static decodeSEIBody(e,t){e=e.slice(0,e.length-1);const i=ebsp2rbsp(e);if(i.byteLength<2)return;let r=0;const o=t?2:1;if(5!==i[o]&&100!==i[o])return;r+=1+o;const[s,n]=deserializeData(i,r);r=n;let a=2;const d=r+s;i.byteLength>=UUID_EXTERNAL.byteLength&&s>=UUID_EXTERNAL.byteLength&&(i.slice(r,r+UUID_EXTERNAL.byteLength).toString()===UUID_EXTERNAL.toString()||i.slice(r,r+UUID_EXTERNAL_2.byteLength).toString()===UUID_EXTERNAL_2.toString())?(r+=UUID_EXTERNAL.byteLength,a=1):i.byteLength>=UUID_EXTERNAL.byteLength&&s>=UUID_EXTERNAL.byteLength&&i.slice(r,r+UUID_INTERNAL.byteLength).toString()===UUID_INTERNAL.toString()&&(r+=UUID_INTERNAL.byteLength,a=0);return{type:a,payload:i.slice(r,d)}}static parseInternalSEI(e){const t=new Map;let i=0;if(0===e.type){for(;e.payload.byteLength-i>=2;){const[r,o]=deserializeData(e.payload,i);i=o;const[s,n]=deserializeData(e.payload,i);if(i=n,t.get(r)||!(s<=e.payload.byteLength-i))break;t.set(r,e.payload.slice(i,i+s)),i+=s}return t}}static makeInternalSei(e){const t=[];for(const[i,r]of e){const e=serializeData(i),o=serializeData(r.byteLength);t.push(e,o,r)}const i=t.reduce(((e,t)=>e+t.byteLength),0),r=new Uint8Array(i);return t.reduce(((e,t)=>(r.set(t,e),e+t.byteLength)),0),r}};let SEIHelper=_SEIHelper;function setPressureObserver(e){const t=PressureObserver.supportedSources;let i="thermal";i=(null==t?void 0:t.includes("thermal"))?"thermal":"cpu";const r=new PressureObserver((t=>{t.forEach((t=>{t.source===i&&e(t.state)}))}));return r.observe(i,{sampleInterval:2e3}),r}__publicField(SEIHelper,"__uuid");class ComputePressureMonitor{constructor(){__publicField(this,"_state"),__publicField(this,"_handler",!1)}init(){if(isComputePressureSupported&&!getParameter("DISABLE_COMPUTE_PRESSURE")&&"UT"!=={}.VITE_TEST)try{if(isWorkerSupported()){const e=new Blob([`(${setPressureObserver.toString()})(self.postMessage)`],{type:"text/javascript"}),t=new Worker(URL.createObjectURL(e));t.onmessage=e=>{this._state=e.data},this._handler=t}else this._handler=setPressureObserver((e=>{this._state=e}))}catch{}}get state(){return isDebuggerMode&&!isSSR$1()&&(window.thermal_status=this._state),this._handler||this.init(),this._state}}var computePressureMonitor=new ComputePressureMonitor;const stasType=["codec","inbound-rtp","outbound-rtp","remote-inbound-rtp","remote-outbound-rtp","media-source","csrc","peer-connection","data-channel","stream","track","transceiver","sender","receiver","transport","sctp-transport","candidate-pair","local-candidate","remote-candidate","certificate","ice-server"],THROTTLE_DURATION=150,STATS_CACHE=new Map;let canIUseGetStatsCallback=!0;const getExtraChromeStatsReport=async e=>new Promise((t=>{var i,r,o,s;const n={all:[],getTrackStats:()=>[]},a=getParameter("STATS_SCALLBACK_SUPPORT");if(canIUseGetStatsCallback&&isChrome&&void 0===window.InstallTrigger&&isStatsCallbackSupport&&a)try{null==(s=null==(o=null==(r=null==(i=e.getStats((e=>{const i=[];e.result().forEach((e=>{if(stasType.includes(e.type))return;const t={};e.names().forEach((function(i){t[i]=e.stat(i)})),i.push({...t,id:e.id,type:e.type,timestamp:e.timestamp})})),t({all:i,getTrackStats:e=>i.filter((t=>"ssrc"!==t.type||t.googTrackId===e))})})))?void 0:i.then)?void 0:r.call(i,(()=>{t(n)})))?void 0:o.catch)||s.call(o,(()=>{canIUseGetStatsCallback=!1,t(n)}))}catch{canIUseGetStatsCallback=!1,t(n)}else t(n)})),getAllStatsReport=async e=>{var t,i,r;const o=await e.getStats(),s={all:[]},n=new Map;o.forEach((e=>{const t=n.get(e.type)||new Map;t.set(e.id,e),n.set(e.type,t),s.all.push(e)}));const a=(e,t)=>{e.forEach((({codecId:e,transportId:i,trackId:r,playoutId:o})=>{var s,a,d,c,l,u,_,h;let p,m;if(null==(s=n.get("codec"))||s.forEach((i=>{i.id===e&&t.add(i)})),null==(a=n.get("transport"))||a.forEach((e=>{e.id===i&&(p=e,t.add(e))})),null==(d=n.get("track"))||d.forEach((e=>{e.id===r&&t.add(e)})),null==(c=n.get("media-playout"))||c.forEach((e=>{e.id===o&&t.add(e)})),p){const{localCertificateId:e,remoteCertificateId:i,selectedCandidatePairId:r}=p;null==(l=n.get("certificate"))||l.forEach((r=>{(r.id===e||r.id===i)&&t.add(r)})),null==(u=n.get("candidate-pair"))||u.forEach((e=>{e.id===r&&(m=e,t.add(e))}))}if(m){const{localCandidateId:e,remoteCandidateId:i}=m;null==(_=n.get("local-candidate"))||_.forEach((i=>{i.id===e&&t.add(i)})),null==(h=n.get("remote-candidate"))||h.forEach((e=>{e.id===i&&t.add(e)}))}}))};return n.get("media-source")?null==(t=n.get("media-source"))||t.forEach((e=>{var t;const i=new Set;i.add(e);const r=[];null==(t=n.get("outbound-rtp"))||t.forEach((t=>{var o;t.mediaSourceId===e.id&&(i.add(t),r.push(t),null==(o=n.get("remote-inbound-rtp"))||o.forEach((e=>{e.localId===t.id&&i.add(e)})))})),a(r,i),s[e.trackIdentifier]=Array.from(i)})):n.get("track")&&(null==(i=n.get("track"))||i.forEach((e=>{var t;const i=new Set;i.add(e);const r=[];null==(t=n.get("outbound-rtp"))||t.forEach((t=>{var o;t.trackId===e.id&&(i.add(t),r.push(t),null==(o=n.get("remote-inbound-rtp"))||o.forEach((e=>{e.localId===t.id&&i.add(e)})))})),a(r,i),s[e.trackIdentifier]=Array.from(i)}))),null==(r=n.get("inbound-rtp"))||r.forEach((e=>{var t,i;const r=new Set;r.add(e),null==(t=n.get("remote-outbound-rtp"))||t.forEach((t=>{t.localId===e.id&&r.add(t)})),a([e],r);let{trackIdentifier:o}=e;o||null==(i=n.get("track"))||i.forEach((t=>{t.id===e.trackId&&(o=t.trackIdentifier)})),s[o]=Array.from(r)})),s},getStats$1=async(e,t,i,r)=>{const o=null==t?void 0:t.id;if(!(e instanceof RTCPeerConnection))return[];if(isFirefox||isSafari){const i=[];try{(r?await r.getStats():await e.getStats(t)).forEach((e=>{i.push(e)}))}catch{}return i}let s=STATS_CACHE.get(e);(!s||Date.now()-s.timestamp>150)&&(s={timestamp:Date.now(),statsPromise:getAllStatsReport(e),extraStatsPromise:getExtraChromeStatsReport(e)},STATS_CACHE.set(e,s));const n=await s.statsPromise;let a=(o?n[o]:n.all)||[];if(!i){const e=await s.extraStatsPromise;a=a.concat((o?e.getTrackStats(o):e.all)||[])}return a},clearPeerCache=e=>{STATS_CACHE.has(e)&&STATS_CACHE.delete(e)};class StatsMonitor extends EnhancedEventEmitter{constructor(){super(...arguments),__publicField(this,"_continuousVideoEncodeFailure",0),__publicField(this,"_remoteStreamDecodeStatus",new Map)}setLocalVideoStats(e,t){this.checkVideoEncodeFailure(e,t)}setRemoteVideoStats(e,t){this.checkVideoDecodeFailure(e,t)}destroy(){this._continuousVideoEncodeFailure=0,this._remoteStreamDecodeStatus=new Map}checkVideoEncodeFailure(e,t){var i;const r=e.frame_rate_input;window.__createEncodeError__&&(e.frame_rate_sent=0,e.frame_rate_encoded=0);const o=e.frame_rate_sent,s=e.frame_rate_encoded,n=void 0!==r&&r>0&&void 0!==s&&0===s&&void 0!==o&&0===o,a=(null==e?void 0:e.is_screen)?10:5;n?(this._continuousVideoEncodeFailure++,this._continuousVideoEncodeFailure>a&&(this.emit("rtc-encode-error",{codec:null==e?void 0:e.codecName,media_type:"video",track_frame_size_width:null==t?void 0:t.getSettings().width,track_frame_size_height:null==t?void 0:t.getSettings().height,track_frame_rate:null==t?void 0:t.getSettings().frameRate,stats_frame_size_width:null==e?void 0:e.frame_size_width,stats_frame_size_height:null==e?void 0:e.frame_size_height,stats_frame_rate_input:null==e?void 0:e.frame_rate_input,stats_frame_rate_sent:null==e?void 0:e.frame_rate_sent,stats_frame_rate_encoded:null==e?void 0:e.frame_rate_encoded,stats_frame_encoder_name:e.encoder_implementation,stats_is_hardware_encoder_enabled:Config2.H264_HW_ENCODER,stats_gpu_url:Config2.GPU_URL||(null==(i=getGpuInfo())?void 0:i.renderer),is_screen:null==e?void 0:e.is_screen}),this._continuousVideoEncodeFailure=0)):this._continuousVideoEncodeFailure=0}checkVideoDecodeFailure(e,t){var i;const r=e.stream_id;if(this._remoteStreamDecodeStatus.has(r)){const o=this._remoteStreamDecodeStatus.get(r),s=0===e.frame_rate_decoded&&e.packetsReceived>o.packets_received&&e.framesDecoded<10;o.packets_received=e.packetsReceived,o.frames_decoded=e.framesDecoded,o.frame_rate_decoded=e.frame_rate_decoded,o.continuous_video_decode_failure=s?o.continuous_video_decode_failure+1:0,o.continuous_video_decode_failure>5&&(this.emit("rtc-decode-error",{codec:e.codecName,media_type:"video",track_frame_size_width:t.getSettings().width,track_frame_size_height:t.getSettings().height,track_frame_rate:t.getSettings().frameRate,stats_frame_size_width:e.frame_size_width,stats_frame_size_height:e.frame_size_height,stats_frame_rate_decode:e.frame_rate_decoded,stats_frame_rate_receive:e.frame_rate_received,stats_frame_decoder_name:e.decoder_name,stats_gpu_url:Config2.GPU_URL||(null==(i=getGpuInfo())?void 0:i.renderer),is_screen:e.is_screen}),o.continuous_video_decode_failure=0)}else this._remoteStreamDecodeStatus.set(r,{packets_received:e.packetsReceived,frames_decoded:e.framesDecoded,frame_rate_decoded:e.frame_rate_decoded,continuous_video_decode_failure:0})}}class Stats extends EnhancedEventEmitter{constructor(e){super(),__publicField(this,"_timer"),__publicField(this,"_reportTimer"),__publicField(this,"handler"),__publicField(this,"_monitor"),__publicField(this,"logger"),__publicField(this,"_destroyed",!1),__publicField(this,"_isReportStarted",!1),this._context=e,this._monitor=getMonitor(e.id),this.logger=new Logger$1("Stats",3,e.id)}setVar(e){this.handler=e}stopReport(e){this._isReportStarted&&(this.logger.info("stopReport","invoke"),this._isReportStarted=!1,clearTimeout(this._reportTimer),delete this._reportTimer,reportRtcInvokeStatus(this._context.id,"del_media_statistics_timer",`reason: ${e}, stack: ${(new Error).stack}`,0,this._stream.streamId||""))}filterIllegal(e){const t={};return Object.keys(e).forEach((i=>{null===e[i]||void 0===e[i]||Number.isNaN(e[i])||(t[i]=e[i])})),t}destroy(){this.logger.info("destroy","invoke"),reportRtcInvokeStatus(this._context.id,"media_statistics_destroy",`${(new Error).stack}`,0,`${this._stream.streamId}`),this.stopReport("destroy"),clearTimeout(this._timer),this._destroyed=!0}}class LocalStatsReport extends Stats{constructor(e,t){super(e),__publicField(this,"_stats",{audioStats:{},videoStats:{}}),__publicField(this,"_preReports",{audio:{},video:{}}),__publicField(this,"statsMonitor"),this._stream=t,this.statsMonitor=new StatsMonitor,this.statsMonitor.on("stats-exception",(e=>{this.emit("stats-exception",e)})),this.statsMonitor.on("rtc-encode-error",(e=>{var t;this.logger.info("rtc_encode_error",JSON.stringify(e)),null==(t=this._monitor)||t.report("rtc_encode_error",e)}));const i=async()=>{this._stats=await this._getLocalStats(this._stream,this._preReports,!1),this._destroyed||(this._timer=setTimeout(i,getParameter("STATS_LOOP_INTERVAL")))};i()}setLocalStreamStatsEvtInterval(e,t){if(this._isReportStarted)return;this.logger.info("setLocalStreamStatsEvtInterval","invoke"),this._isReportStarted=!0,this.setVar(t),this._destroyed=!1;const i={audio:{},video:{}},r=async()=>{const t=await this._getLocalStats(this._stream,i,!0);e(t),this._destroyed||(this._reportTimer=setTimeout(r,2e3))};r()}getLocalStats(){return this._stats}async _getLocalStats(e,t,i){var r,o,s,n,a,d,c;const l=void 0!==(null==(r=e.audioTrack)?void 0:r.mixType)&&e.audioTrack.mixType!==AudioMixingType.PLAYOUT?(null==(o=e.audioTrack)?void 0:o.mixedAudioTrack)??(null==(s=e.audioTrack)?void 0:s.preprocessingTrack):null==(n=e.audioTrack)?void 0:n.preprocessingTrack,u=null==(a=e.videoTrack)?void 0:a.preprocessingTrack;0===Object.keys(t.audio).length&&0===Object.keys(t.video).length&&(await this.getAudioStats(l,t,null==(d=e.audioTrack)?void 0:d.getAudioLevel(),i),await this.getVideoStats(u,t,i),await wait(150));return{audioStats:await this.getAudioStats(l,t,null==(c=e.audioTrack)?void 0:c.getAudioLevel(),i),videoStats:await this.getVideoStats(u,t,i),isScreen:e.isScreen}}async getAudioStats(e,t,i,r){var o,s,n,a;const d={},c={timestamp:Date.now()},{streamId:l,audioMid:u,isScreen:_,pubAttributes:h,pubAudio:p,audioTrack:m}=this._stream,S={media_type:"audio",is_screen:!!_,direction:"up",stream_id:l,vid:u,connection_status:navigator.onLine,track_enabled:null==e?void 0:e.enabled,capture_state:h.localaudio?"capture_state_on":"capture_state_off",mute_state:p?"mute_state_off":"mute_state_on",thermal_status:computePressureMonitor.state,is_public_stream:this._stream.isPublicStream};if(m&&(S.playback_volume=m.getVolume()),!e||!this.handler)return d;const g=await(null==(s=this.handler.peer)?void 0:s.getStatsWithLowFrequency(e,!1,null==(o=this._stream.audioTransceiver)?void 0:o.sender));if(!g.length)return d;if(g.forEach((({type:e,packetsSent:t,packetsLost:i,bytesSent:r,clockRate:o,roundTripTime:s,channels:n,audioLevel:a,mimeType:l,availableIncomingBitrate:u,availableOutgoingBitrate:_,bytesReceived:h,nominated:p,id:m,currentRoundTripTime:g,state:v,writable:f,requestsReceived:E,responsesReceived:T,requestsSent:R,consentRequestsSent:b,responsesSent:y,jitter:I,candidateType:C,ip:A,address:k,networkType:M,port:N,protocol:O,nackCount:P,retransmittedBytesSent:D,retransmittedPacketsSent:w,audioInputLevel:L,ssrc:x,totalAudioEnergy:F,totalSamplesDuration:U,mediaType:V,fractionLost:B})=>{"outbound-rtp"===e?(c.packetsSent=t,c.bytesSent=r,S.bytes=r,S.packetsSent=t,S.nackCount=P,S.ssrc=x,S.retransmitted_bytes_sent=D,S.retransmitted_packets_sent=w,c.retransmittedBytesSent=D,c.retransmittedPacketsSent=w):"remote-inbound-rtp"===e?(c.packetsLost=i,S.packetsLost=i,S.net_jitter=1e3*I,d.rtt=1e3*s,S.rtt=d.rtt,d._fractionLost=B||0):"codec"===e?(d.recordSampleRate=o,d.numChannels=n,S.codecName=l):"media-source"===e&&void 0!==a?(S.audio_level=a?-10*Math.log10(Math.pow(a,2)):a,S.volume=255*a,S.total_audio_energy=F,S.totalInputDuration=U,S.send_level||(S.send_level=a)):"ssrc"===e&&"audio"===V?L&&(S.send_level=L):"candidate-pair"===e?(S.ice_available_incoming_bitrate=u,S.ice_available_outgoing_bitrate=_,S.ice_bytes_received=h,S.ice_bytes_sent=r,S.ice_nominated=Number(p),S.ice_pair_id=m,S.ice_pair_rtt=g,S.ice_pair_state=v,S.ice_pair_writable=f,S.recv_ping_requests=E,S.recv_ping_responses=T,S.sent_ping_requests_before_first_response=R,S.sent_ping_requests_total=R+(b||0),S.sent_ping_responses=y):"local-candidate"===e?(S.local_candidate_type=C,S.local_ip=A||k,S.local_network_type=M,S.local_port=N,S.protocol=O):"remote-candidate"===e&&(S.remote_candidate_type=C,S.remote_ip=A||k,S.remote_port=N)})),S.send_level)S.send_level<1?S._sendVolumeLevel=32767*S.send_level:S._sendVolumeLevel=S.send_level;else{const e=(null==m?void 0:m.getAudioLevel())||0;S._sendVolumeLevel=Math.round(e/255*32767)}void 0===S.volume&&void 0!==i&&(S.volume=i,S.audio_level=i?-10*Math.log10(Math.pow(i/255,2)):i);const{audio:v}=t;return v.timestamp?(void 0!==c.packetsLost&&(d.audioLossRate=Math.max(0,c.packetsLost-v.packetsLost)/(c.packetsSent-v.packetsSent),d.audioLossRate=Number.isNaN(d.audioLossRate)?0:d.audioLossRate,S.fraction_lost=d.audioLossRate),d.statsInterval=c.timestamp-v.timestamp,S.stats_interval=d.statsInterval,d.sendKBitrate=(c.bytesSent-v.bytesSent||0)/d.statsInterval*8,S.mediaBitratebps=Math.round(1e3*d.sendKBitrate),S.bandwidth=Math.round(S.mediaBitratebps/1024),void 0!==c.retransmittedBytesSent&&(S.retransmitBitratebps=(c.retransmittedBytesSent-v.retransmittedBytesSent||0)/d.statsInterval),t.audio=c,S.vendor_mode=this._stream.vendorCode||0,S.pc_session_id=null==(n=this.handler)?void 0:n.peerConnectionId,r&&(null==(a=this._monitor)||a.report("rtc_media_statistics",S)),d._retransmittedRate=(c.retransmittedPacketsSent-v.retransmittedPacketsSent)/(c.packetsSent-v.packetsSent),void 0===d.audioLossRate&&(d.audioLossRate=d._retransmittedRate,S.fraction_lost=d.audioLossRate),d._fractionLost=Math.max(d._fractionLost,d.audioLossRate),d._sendVolumeLevel=S._sendVolumeLevel,this.filterIllegal(d)):(t.audio=c,this.filterIllegal(d))}async getVideoStats(e,t,i){var r,o,s,n,a,d,c,l;const u={},_={timestamp:Date.now(),simulcast:{}},{streamId:h,videoMid:p,isScreen:m,pubAttributes:S,enableSimulcast:g,pubVideo:v}=this._stream,f={media_type:"video",is_screen:!!m,direction:"up",stream_id:h,vid:p,connection_status:navigator.onLine,track_enabled:null==e?void 0:e.enabled,capture_state:S.localvideo?"capture_state_on":"capture_state_off",mute_state:v?"mute_state_off":"mute_state_on",thermal_status:computePressureMonitor.state,is_public_stream:this._stream.isPublicStream};if(!e||!this.handler)return u;f.cap_frame_width=e.getSettings().width,f.cap_frame_height=e.getSettings().height,f.frameRateSent=e.getSettings().frameRate,u.isScreen=m,f.is_intersecting=JSON.stringify(null==(o=null==(r=this._stream)?void 0:r.videoTrack)?void 0:o.intersection());const E=await(null==(n=this.handler.peer)?void 0:n.getStatsWithLowFrequency(e,!1,null==(s=this._stream.videoTransceiver)?void 0:s.sender));if(!E.length)return u;let T=0;E.forEach((e=>{const{type:i,framesEncoded:r,packetsLost:o,bytesSent:s,framesSent:n,retransmittedBytesSent:a,totalPacketSendDelay:d,totalEncodeTime:c,firCount:l,targetBitrate:h,roundTripTime:p,mimeType:m,frameWidth:S,frameHeight:v,packetsSent:E,googActualEncBitrate:R,googAvailableReceiveBandwidth:b,googAvailableSendBandwidth:y,googAvgEncodeMs:I,googBucketDelay:C,googEncodeUsagePercent:A,googFrameRateInput:k,availableIncomingBitrate:M,availableOutgoingBitrate:N,bytesReceived:O,nominated:P,id:D,currentRoundTripTime:w,state:L,writable:x,candidateType:F,ip:U,address:V,networkType:B,port:$,nackCount:G,pliCount:W,protocol:H,qpSum:K,requestsReceived:X,responsesReceived:Z,googRetransmitBitrate:z,requestsSent:Y,consentRequestsSent:j,responsesSent:J,ssrc:Q,googTargetEncBitrate:q,googTransmitBitrate:ee,retransmittedPacketsSent:te,encoderImplementation:ie,jitter:re,rid:oe,fractionLost:se,googAdaptationChanges:ne,qualityLimitationReason:ae,qualityLimitationDurations:de,googFirsReceived:ce,googFrameRateSent:le,keyFramesEncoded:ue,scalabilityMode:_e,framesPerSecond:he,frames:pe}=e;"outbound-rtp"===i?(g&&(oe?_.simulcast[oe]=e:_.simulcast[T]=e,T++),_.framesEncoded=r||_.framesEncoded||0,f.key_frames_encoded=ue||0,_.bytesSent=s||_.bytesSent||0,_.framesSent=n||_.framesSent,f.bytes=s||f.bytes||0,_.packetsSent=E||_.packetsSent||0,f.packetsSent=E||f.packetsSent||0,f.nackCount=G||f.nackCount||0,f.pli_count=W||f.pli_count||0,f.qp_sum=K||f.qp_sum||0,f.ssrc=Q||f.ssrc||0,f.retransmitted_packets_sent=te,_.retransmittedPacketsSent=te,_.retransmittedBytesSent=a,f.encoder_implementation=ie,f.qualityLimitationReason=ae,f.qualityLimitationDurations=de,f.scalabilityMode=_e,void 0!==S&&((!u.encodedFrameWidth||S>u.encodedFrameWidth)&&(u.encodedFrameWidth=S),(!u.encodedFrameHeight||v>u.encodedFrameHeight)&&(u.encodedFrameHeight=v),f.frame_size_height=v,f.frame_size_width=S)):"track"===i?(u.encodedFrameWidth=S,u.encodedFrameHeight=v,f.frame_size_height=v,f.frame_size_width=S):"remote-inbound-rtp"===i?(_.packetsLost=o,u.rtt=1e3*p,f.rtt=u.rtt,f.jitter=1e3*re,f.packetsLost=o,u._fractionLost=se||0):"codec"===i?(u.codecType=m,f.codecName=m):"candidate-pair"===i?(f.ice_available_incoming_bitrate=M,f.ice_available_outgoing_bitrate=N,f.ice_bytes_received=O,f.ice_bytes_sent=s,f.ice_nominated=Number(P),f.ice_pair_id=D,f.ice_pair_rtt=w,f.ice_pair_state=L,f.ice_pair_writable=x,f.recv_ping_requests=X,f.recv_ping_responses=Z,f.sent_ping_requests_before_first_response=Y,f.sent_ping_requests_total=Y+j,f.sent_ping_responses=J):"local-candidate"===i?(f.local_candidate_type=F,f.local_ip=U||V,f.local_network_type=B,f.local_port=$,f.protocol=H):"remote-candidate"===i?(f.remote_candidate_type=F,f.remote_ip=U||V,f.remote_port=$):"VideoBwe"===i?(f.encBitratebps=R,f.available_receive_bandwidth=b,f.available_send_bandwidth=y,f.bucket_delay=C,f.retransmitBitratebps=z,f.targetEncBitratebps=q,f.transmit_bitrate=ee,u._sendBandWidth=Number(y)):"ssrc"===i&&(f.avg_encode_ms=I,f.encodeUsage=A,f.frame_rate_input=k,f.orignal_input_Framerate=Number(k),f.ddaptationChanges=ne,f.firsReceived=ce,f.frameRateSent=le);const me=getParameter("STATS_SCALLBACK_SUPPORT");if(!isStatsCallbackSupport||!me){const{video:e}=t,o=_.timestamp-e.timestamp;if("outbound-rtp"===i){const t=s-e.bytesSent,i=a-e.retransmittedBytesSent;f.encBitratebps=Math.round(8e3*(t-i)/o),f.bucket_delay=d/E,f.retransmitBitratebps=Math.round(8e3*i/o),f.targetEncBitratebps=h,f.transmit_bitrate=Math.round(1e3*(s-e.bytesSent)*8/o),f.avg_encode_ms=1e3*c/r,f.firsReceived=l+W}else"candidate-pair"===i?(f.available_send_bandwidth=N,u._sendBandWidth=N):"media-source"===i&&(f.frame_rate_input=he,f.orignal_input_Framerate=Number(he),f.frame_input=pe)}}));const{video:R}=t;if(!R.timestamp)return t.video=_,this.filterIllegal(u);u.statsInterval=_.timestamp-R.timestamp,f.stats_interval=u.statsInterval;const b=Object.keys(_.simulcast);if(g){f.sim_enc_width=[],f.sim_enc_height=[],f.sim_enc_bps=[],f.sim_enc_framerate=[],f.sim_enc_key_frames=[],f.sim_rids=[],f.sim_enc_bandwidth=[],f.sim_sent_framerate=[],f.sim_fraction_lost=[],f.sim_keyencoded=[],f.active_sim_streams=this._context.videoProfile.activeSimStreams||[],f.sim_retransmittedRate=[];let e=!1;b.sort(((e,t)=>Number(e)-Number(t))).forEach((t=>{const{frameWidth:i,frameHeight:r,bytesSent:o,framesEncoded:s,framesSent:n,packetsLost:a,packetsSent:d,qualityLimitationReason:c,qualityLimitationDurations:l,qualityLimitationResolutionChanges:h,retransmittedPacketsSent:p,pliCount:m,keyFramesEncoded:S}=_.simulcast[t];void 0!==c&&(f.sim_qualityLimitationReason||(f.sim_qualityLimitationReason=[],f.sim_qualityLimitationDurations=[],f.sim_qualityLimitationResolutionChanges=[]),f.sim_qualityLimitationReason.push(c),f.sim_qualityLimitationDurations.push(l),f.sim_qualityLimitationResolutionChanges.push(h));const g=R.simulcast[t];if(f.sim_enc_width.push(i||0),f.sim_enc_height.push(r||0),f.sim_enc_key_frames.push(S||0),g){const r=(o-g.bytesSent||0)/u.statsInterval;f.sim_enc_bps.push(Math.round(8e3*r)),f.sim_enc_bandwidth.push(Math.round(8e3*r/1024));const c=1e3*(s-g.framesEncoded)/u.statsInterval;f.sim_enc_framerate.push(Math.round(c)),f.sim_rids.push(t);const l=void 0!==n?n-g.framesSent:s-g.framesEncoded,_=1e3*l/u.statsInterval;f.sim_sent_framerate.push(Math.round(_));let h=(a-g.packetsLost)/(d-g.packetsSent);u._retransmittedRate=(p-g.retransmittedPacketsSent)/(d-g.packetsSent),h=Number.isNaN(h)?0:h,f.sim_fraction_lost.push(h),f.sim_keyencoded.push(m-g.pliCount>0),f.sim_retransmittedRate.push(u._retransmittedRate),i>0&&!e&&(u.rid=t,u.sentKBitrate=8*r,u.encoderOutputFrameRate=c,u.encodedFrameCount=l,u.sentFrameRate=_,u.videoLossRate=h,e=!0)}})),f.vendor_mode=this._stream.vendorCode||0,f.pc_session_id=null==(a=this.handler)?void 0:a.peerConnectionId,i&&(null==(d=this._monitor)||d.report("rtc_media_statistics",f))}else u.encodedFrameCount=void 0!==_.framesSent?_.framesSent-R.framesSent:_.framesEncoded-R.framesEncoded,u.sentKBitrate=(_.bytesSent-R.bytesSent||0)/u.statsInterval*8,f.bitrate=Math.round(1e3*u.sentKBitrate),f.bandwidth=Math.round(f.bitrate/1024),u.encoderOutputFrameRate=1e3*(_.framesEncoded-R.framesEncoded)/u.statsInterval,f.frame_rate_encoded=Math.round(u.encoderOutputFrameRate),u.sentFrameRate=1e3*u.encodedFrameCount/u.statsInterval,f.frame_rate_sent=Math.round(u.sentFrameRate),u.videoLossRate=Math.max(0,_.packetsLost-R.packetsLost)/(_.packetsSent-R.packetsSent),u.videoLossRate=Number.isNaN(u.videoLossRate)?0:u.videoLossRate,f.fraction_lost=u.videoLossRate,u._retransmittedRate=(_.retransmittedPacketsSent-R.retransmittedPacketsSent)/(_.packetsSent-R.packetsSent),f.vendor_mode=this._stream.vendorCode||0,f.pc_session_id=null==(c=this.handler)?void 0:c.peerConnectionId,f.sentKBitrate=u.sentKBitrate,u.inputFrameRate=f.orignal_input_Framerate,u.encoderName=f.encoder_implementation,i?null==(l=this._monitor)||l.report("rtc_media_statistics",f):this.statsMonitor.setLocalVideoStats(f,e);return t.video=_,u._fractionLost=Math.max(u._fractionLost,u.videoLossRate),u._captureResolutionWidth=f.cap_frame_width,u._captureResolutionHeight=f.cap_frame_height,this.filterIllegal(u)}destroy(){super.destroy(),this.statsMonitor.destroy()}}class RemoteStatsReport extends Stats{constructor(e,t){super(e),__publicField(this,"_stats",{audioStats:{},videoStats:{}}),__publicField(this,"_preReports",{audio:{},video:{}}),__publicField(this,"statsMonitor"),this._stream=t,this.statsMonitor=new StatsMonitor,this.statsMonitor.on("stats-exception",(e=>{this.emit("stats-exception",e)})),this.statsMonitor.on("rtc-decode-error",(e=>{var t;this.logger.info("rtc_decode_error",JSON.stringify(e)),null==(t=this._monitor)||t.report("rtc_decode_error",e)}));const i=async()=>{this._stats=await this._getRemoteStreamStats(this._stream,this._preReports,!1),this._destroyed||(this._timer=setTimeout(i,getParameter("STATS_LOOP_INTERVAL")))};i()}async setRemoteStreamStatsEvtInterval(e,t){if(this._isReportStarted)return;this.logger.info("setRemoteStreamStatsEvtInterval","invoke"),this._isReportStarted=!0,this.setVar(t),this._destroyed=!1;const i={audio:{},video:{}},r=async()=>{const t=await this._getRemoteStreamStats(this._stream,i,!0);e(t),this._destroyed||(this._reportTimer=setTimeout(r,2e3))};r()}getRemoteStreamStats(){return this._stats}async _getRemoteStreamStats(e,t,i){var r,o,s,n;const a=null==(r=e.videoTrack)?void 0:r.originTrack,d=null==(o=e.audioTrack)?void 0:o.originTrack;0===Object.keys(t.audio).length&&0===Object.keys(t.video).length&&(await this.getRemoteAudioStats(d,t,null==(s=this._stream.audioTrack)?void 0:s.getAudioLevel(),i),await this.getRemoteVideoStats(a,t,i),await wait(150));return{audioStats:await this.getRemoteAudioStats(d,t,null==(n=this._stream.audioTrack)?void 0:n.getAudioLevel(),i),videoStats:await this.getRemoteVideoStats(a,t,i),isScreen:e.isScreen,userId:e.userId,streamId:e.streamId}}unsubscribe(){this.logger.info("unsubscribe","invoke"),super.stopReport("unsubscribe"),this._stream.stopAudioStallObserve()}async getRemoteAudioStats(e,t,i,r){var o,s,n,a,d,c;const l={},u={},{streamId:_,userId:h,isScreen:p,audioMid:m,subMediaType:S,_attributes:g,virtual:v,audioTrack:f}=this._stream,E={media_type:"audio",is_screen:!!p,direction:"down",stream_id:_,stream_user_id:h,vid:m,audio_mux:v,connection_status:navigator.onLine,track_enabled:null==e?void 0:e.enabled,mute_state:audioInMediaType(S)?"mute_state_off":"mute_state_on",remote_user_capture_state:g.localaudio?"capture_state_on":"capture_state_off",remote_user_mute_state:g.localaudio&&g.audiostream?"mute_state_off":"mute_state_on",thermal_status:computePressureMonitor.state,is_public_stream:this._stream.isPublicStream};if(f&&(E.playback_volume=f.getVolume()),!e||!this.handler)return l;const T=await(null==(s=this.handler.peer)?void 0:s.getStatsWithLowFrequency(e,!1,null==(o=this._stream.audioTransceiver)?void 0:o.receiver));if(!T.length)return l;T.forEach((({type:e,packetsLost:t,packetsReceived:r,bytesReceived:o,jitterBufferDelay:s,jitterBufferEmittedCount:n,clockRate:a,channels:d,totalSamplesReceived:c,concealedSamples:h,silentConcealedSamples:p,concealmentEvents:m,totalRoundTripTime:S,packetsDiscarded:g,state:v,currentRoundTripTime:f,audioLevel:T,totalAudioEnergy:R,totalSamplesDuration:b,mimeType:y,googDecodingNormal:I,googDecodingMuted:C,availableIncomingBitrate:A,availableOutgoingBitrate:k,bytesSent:M,nominated:N,id:O,writable:P,jitter:D,candidateType:w,ip:L,address:x,networkType:F,port:U,protocol:V,audioOutputLevel:B,requestsReceived:$,responsesReceived:G,requestsSent:W,consentRequestsSent:H,responsesSent:K,ssrc:X,nackCount:Z,lastPacketReceivedTimestamp:z,concealmentevents:Y,fecPacketsReceived:j})=>{var J,Q;"inbound-rtp"===e?(u.packetsLost=t,u.packetsReceived=r,E.packetsLost=t,E.packetsReceived=r,E.packetsDiscarded=g,E.nackCount=Z,E.lastPacketReceivedTimestamp=z,E.concealmentevents=Y,u.bytesReceived=o,void 0!==s&&(l.jitterBufferDelay=s/n*1e3,E.average_jitter_buffer_delay_ms=l.jitterBufferDelay),void 0!==c&&(u.totalSamplesReceived=c,l.concealedSamples=h,u.concealedSamples=h,u.silentConcealedSamples=p,E.concealedSamples=h,l.concealmentEvents=m,E.totalSamplesReceived=c),void 0!==j&&(E.fec_packets_received=j,u.fecPacketsReceived=j),E.jitter=1e3*D,E.ssrc=X,void 0!==T&&0!==T?(E.audio_level=T?-10*Math.log10(Math.pow(T,2)):T,E.volume=255*T):(E.volume=i??255*T,E.audio_level=i?-10*Math.log10(Math.pow(i/255,2)):i),void 0!==R&&(E.total_audio_energy=R),void 0!==b&&(E.totalAudioDuration=b)):"codec"===e?(l.recordSampleRate=a,d&&(l.numChannels=d),E.codecName=y,l.codecType=y):"candidate-pair"===e?(E.ice_available_incoming_bitrate=A,E.ice_available_outgoing_bitrate=k,E.ice_bytes_received=o,E.ice_bytes_sent=M,E.ice_nominated=Number(N),E.ice_pair_id=O,E.ice_pair_rtt=f,E.rtt=1e3*f,E.rtt&&(null==(Q=null==(J=this._context.streamRTT)?void 0:J[_])?void 0:Q.audio)&&(E.total_rtt_ms=Math.round(E.rtt+this._context.streamRTT[_].audio)),E.ice_pair_state=v,E.ice_pair_writable=P,E.recv_ping_requests=$,E.recv_ping_responses=G,E.sent_ping_requests_before_first_response=W,E.sent_ping_requests_total=W+(H||0),E.sent_ping_responses=K,"succeeded"===v&&(l.rtt=1e3*f,l.total_rtt=1e3*S)):"track"===e&&void 0!==T?(0===T&&0!==i?(E.volume=i,E.audio_level=i?-10*Math.log10(Math.pow(i/255,2)):i):(E.audio_level=T?-10*Math.log10(Math.pow(T,2)):T,E.volume=255*T),E.total_audio_energy=R,E.totalAudioDuration=b):"ssrc"===e?(E.decodingNormal=I,E.recvAudioLevel=B,E.decodingMuted=C):"local-candidate"===e?(E.local_candidate_type=w,E.local_ip=L||x,E.local_network_type=F,E.local_port=U,E.protocol=V):"remote-candidate"===e&&(E.remote_candidate_type=w,E.remote_ip=L||x,E.remote_port=U)}));const{audio:R}=t;if(!R.timestamp)return u.timestamp=Date.now(),t.audio=u,this.filterIllegal(l);let b;return void 0!==u.concealedSamples&&(E.interval_concealed_samples=u.concealedSamples-R.concealedSamples,E.interval_samples_received=u.totalSamplesReceived-R.totalSamplesReceived,E.interval_silent_concealed_samples=u.silentConcealedSamples-R.silentConcealedSamples,b=await this._stream.updateAudioStallInfo(E,l,u)),u.timestamp=Date.now(),l.audioLossRate=Math.max(0,u.packetsLost-R.packetsLost)/(u.packetsReceived-R.packetsReceived+(u.packetsLost-R.packetsLost)),l.audioLossRate=Number.isNaN(l.audioLossRate)?0:l.audioLossRate,E.fraction_lost=l.audioLossRate,l.statsInterval=u.timestamp-R.timestamp,E.stats_interval=l.statsInterval,l.receivedKBitrate=(u.bytesReceived-R.bytesReceived||0)/l.statsInterval*8,E.bandwidth=Math.round(1e3*l.receivedKBitrate/1024),void 0!==u.concealedSamples&&(l.receivedSampleRate=1e3*E.interval_samples_received/l.statsInterval),void 0!==u.fecPacketsReceived&&(E.fecBitratebps=(u.fecPacketsReceived-R.fecPacketsReceived||0)/l.statsInterval),E.average_jitter_buffer_delay_ms&&E.total_rtt_ms&&(l.e2eDelay=E.average_jitter_buffer_delay_ms+E.total_rtt_ms),(null==(a=null==(n=this._context.streamRTT)?void 0:n[_])?void 0:a.audio)&&(l.totalRtt=(E.rtt?E.rtt:0)+this._context.streamRTT[_].audio),t.audio=u,E.vendor_mode=this._stream.vendorCode||0,E.pc_session_id=null==(d=this.handler)?void 0:d.peerConnectionId,r&&(null==(c=this._monitor)||c.report("rtc_media_statistics",E,b)),this.filterIllegal(l)}async getRemoteVideoStats(e,t,i){var r,o,s,n,a,d,c;const l={},u={timestamp:Date.now()},{streamId:_,userId:h,isScreen:p,subMediaType:m,_attributes:S}=this._stream,g={media_type:"video",is_screen:!!p,direction:"down",stream_id:_,stream_user_id:h,vid:this._stream.videoMid,connection_status:navigator.onLine,track_enabled:null==e?void 0:e.enabled,mute_state:videoInMediaType(m)?"mute_state_off":"mute_state_on",remote_user_capture_state:S.localvideo?"capture_state_on":"capture_state_off",remote_user_mute_state:S.localvideo&&S.videostream?"mute_state_off":"mute_state_on",is_intersecting:JSON.stringify(null==(r=this._stream.videoTrack)?void 0:r.intersection()),thermal_status:computePressureMonitor.state,is_public_stream:this._stream.isPublicStream,...this._stream.getVideoRenderInfo()};if(!e||!this.handler)return l;l.isScreen=p;const v=await(null==(s=this.handler.peer)?void 0:s.getStatsWithLowFrequency(e,!1,null==(o=this._stream.videoTransceiver)?void 0:o.receiver));if(!v.length)return l;v.forEach((({type:e,frameHeight:t,frameWidth:i,packetsLost:r,packetsReceived:o,bytesReceived:s,framesDecoded:n,jitterBufferDelay:a,jitterBufferEmittedCount:d,mimeType:c,firCount:h,availableIncomingBitrate:p,availableOutgoingBitrate:m,bytesSent:v,nominated:f,id:E,currentRoundTripTime:T,state:R,writable:b,candidateType:y,ip:I,address:C,networkType:A,port:k,nackCount:M,pliCount:N,protocol:O,requestsReceived:P,responsesReceived:D,requestsSent:w,consentRequestsSent:L,responsesSent:x,ssrc:F,jitter:U,framesReceived:V,keyFramesDecoded:B,totalDecodeTime:$,decoderImplementation:G,lastPacketReceivedTimestamp:W,framesDropped:H})=>{var K,X;if("inbound-rtp"===e){if(u.packetsLost=r,g.packetsLost=r,u.packetsReceived=o,g.packetsReceived=o,u.bytesReceived=s,g.bytes=s,u.framesDecoded=n,u.totalDecodeTime=$,void 0!==a&&(u.jitterBufferDelay=a/d*1e3,g.average_jitter_buffer_delay_ms=u.jitterBufferDelay),g.fir_count=h,g.nackCount=M,u.nackCount=M,g.pli_count=N,g.ssrc=F,g.framesDropped=H,g.jitter=1e3*U,g.framesReceived=V,u.framesReceived=V,g.framesDecoded=n,g.key_frames_decoded=B,g.decoder_name=G,l.decoderName=G,g.last_packet_received_timestamp=W,void 0!==i){g.frame_size_width=i,g.frame_size_height=t;const e=null==S?void 0:S.alphaInfo;(null==e?void 0:e.enableAlpha)?(l.width=e.alphaWidth??i,l.height=e.alphaHeight??(t??0)/2):(l.width=i,l.height=t)}}else if("track"===e&&void 0!==i){g.frame_size_width=i,g.frame_size_height=t;const e=null==S?void 0:S.alphaInfo;(null==e?void 0:e.enableAlpha)?(l.width=e.alphaWidth??i,l.height=e.alphaHeight??(t??0)/2):(l.width=i,l.height=t),void 0!==V&&(g.framesReceived=V,u.framesReceived=V)}else"codec"===e?(g.codecName=c,l.codecType=c):"candidate-pair"===e?(g.ice_available_incoming_bitrate=p,g.ice_available_outgoing_bitrate=m,g.ice_bytes_received=s,g.ice_bytes_sent=v,g.ice_nominated=Number(f),g.ice_pair_id=E,g.ice_pair_rtt=T,g.rtt=1e3*T,g.rtt&&(null==(X=null==(K=this._context.streamRTT)?void 0:K[_])?void 0:X.video)&&(g.total_rtt_ms=Math.round(g.rtt+(this._context.streamRTT[_].video||0))),l.rtt=g.rtt,g.ice_pair_state=R,g.ice_pair_writable=b,g.recv_ping_requests=P,g.recv_ping_responses=D,g.sent_ping_requests_before_first_response=w,g.sent_ping_requests_total=w+(L||0),g.sent_ping_responses=x):"local-candidate"===e?(g.local_candidate_type=y,g.local_ip=I||C,g.local_network_type=A,g.local_port=k,g.protocol=O):"remote-candidate"===e&&(g.remote_candidate_type=y,g.remote_ip=I||C,g.remote_port=k)}));const{video:f}=t;if(!f.timestamp)return t.video=u,this.filterIllegal(l);const E=Math.max(0,u.packetsLost-f.packetsLost),T=u.packetsReceived-f.packetsReceived;if(l.videoLossRate=E/(T+E),l._receivePackets=u.packetsReceived,l._receivePacketsLost=u.packetsLost,f.totalDecodeTime&&f.framesDecoded&&u.framesDecoded!==f.framesDecoded){const e=u.totalDecodeTime-f.totalDecodeTime,t=u.framesDecoded-f.framesDecoded;g.decode_elapse_per_frame=Number((e/t*1e3).toFixed(2))}l._retransmittedRate=(u.nackCount-f.nackCount)/(T+E),l.videoLossRate=Number.isNaN(l.videoLossRate)?0:l.videoLossRate,g.fraction_lost=l.videoLossRate,l.statsInterval=u.timestamp-f.timestamp,g.stats_interval=l.statsInterval,l.receivedKBitrate=(u.bytesReceived-f.bytesReceived||0)/l.statsInterval*8,g.bitrate=Math.round(1e3*l.receivedKBitrate),g.bandwidth=Math.round(g.bitrate/1024),l.decoderOutputFrameRate=1e3*(u.framesDecoded-f.framesDecoded)/l.statsInterval,l.receivedFrameRate=1e3*(u.framesReceived-f.framesReceived)/l.statsInterval,g.frame_rate_decoded=Math.round(l.decoderOutputFrameRate),g.frame_rate_received=Math.round(l.receivedFrameRate),g.average_jitter_buffer_delay_ms&&g.total_rtt_ms&&(l.e2eDelay=g.average_jitter_buffer_delay_ms+g.total_rtt_ms),(null==(a=null==(n=this._context.streamRTT)?void 0:n[_])?void 0:a.video)&&(l.totalRtt=(g.rtt?g.rtt:0)+(this._context.streamRTT[_].video||0)),t.video=u,this._stream.updateVideoStallInfo(g,l,i),g.vendor_mode=this._stream.vendorCode||0,g.pc_session_id=null==(d=this.handler)?void 0:d.peerConnectionId;const R=null==S?void 0:S.alphaInfo;return(null==R?void 0:R.enableAlpha)&&void 0!==g.frame_size_width&&void 0!==g.frame_size_height?(l.frameSizeWidth=R.alphaWidth??g.frame_size_width,l.frameSizeHeight=R.alphaHeight??g.frame_size_height/2):(l.frameSizeWidth=g.frame_size_width,l.frameSizeHeight=g.frame_size_height),l.decoderName=g.decoder_name,i?null==(c=this._monitor)||c.report("rtc_media_statistics",g):this.statsMonitor.setRemoteVideoStats(g,e),this.filterIllegal(l)}destroy(){super.destroy(),super.stopReport("destroy"),this._stream.stopAudioStallObserve(),this.statsMonitor.destroy()}}class VideoStallObserver{constructor(e,t){__publicField(this,"_removeHandler"),__publicField(this,"_remotePauseHandler"),__publicField(this,"_prePts"),__publicField(this,"_stallList"),__publicField(this,"_videoInWaiting",!1),__publicField(this,"_videoInWaitingCallback",!1),__publicField(this,"_videoInWaiting100ms",!1),__publicField(this,"_isPaused"),__publicField(this,"_pauseStart",0),__publicField(this,"_pauseDuration",0),__publicField(this,"_requestVideoFrameCallbackTimer"),__publicField(this,"_logger"),__publicField(this,"_player"),__publicField(this,"_recentVideoInfo"),__publicField(this,"_stallTimeThreshold"),__publicField(this,"_openVideoStall100ms",Config2.VIDEO_STALL_100MS);const i=e?1500:isSafari||isFirefox?550:500;this._stallTimeThreshold={report:i,callback:Math.max(Config2.VIDEO_STALL_DATA,i)},this._logger=new Logger$1("VideoStallObserver",1,t)}start(e){if(this._logger.print("start","invoke"),this._player=e,checkVideoFrameCallback())e.domElement&&(this._requestVideoFrameCallbackTimer=e.domElement.requestVideoFrameCallback(this._onVideoRefresh.bind(this)),this._removeHandler=()=>{var t;this._requestVideoFrameCallbackTimer&&(null==(t=e.domElement)||t.cancelVideoFrameCallback(this._requestVideoFrameCallbackTimer))});else{const t=t=>this._onVideoTimeupdate(t,e);e.on("playback_event",t),this._removeHandler=()=>e.off("playback_event",t)}const t=e=>this._onVideoPause(e);e.on("playback_event",t),this._remotePauseHandler=()=>e.off("playback_event",t)}getRecentRenderInfo4Report(){const e={};return this._recentVideoInfo&&Object.keys(this._recentVideoInfo).forEach((t=>{var i;const r=t.replace(/[a-z]{1}[A-Z]{1}/g,(e=>`${e[0]}_${e[1].toLowerCase()}`));e[`video_${r}`]=null==(i=this._recentVideoInfo)?void 0:i[t]})),e}stop(){var e,t;this._logger.print("stop","invoke"),delete this._player,null==(e=this._removeHandler)||e.call(this),delete this._removeHandler,null==(t=this._remotePauseHandler)||t.call(this),delete this._remotePauseHandler,delete this._stallList,delete this._prePts,delete this._recentVideoInfo,this._videoInWaiting=!1,this._videoInWaitingCallback=!1,this._videoInWaiting100ms=!1}destroy(){this.stop()}getStallInfo({interval:e,frameRateReceived:t,frameRateDecoded:i,bitrate:r}){const o={pts:0,report:{stallCount:0,stallDuration:0,list:[]},callback:{stallCount:0,stallDuration:0},pauseDuration:this._getPauseDuration()};if(this._stallList){(isSafari||isFirefox)&&(0===r||(i||1/0)<=1||(t||1/0)<=1)||0===this._stallList.length?(o.report.stallDuration=o.callback.stallDuration=2e3,o.report.stallCount=o.callback.stallCount=this._videoInWaiting?0:1,this._openVideoStall100ms&&(o.stall100ms={count:this._videoInWaiting100ms?0:1,duration:2e3}),this._videoInWaiting=!0,this._videoInWaitingCallback=!0,this._videoInWaiting100ms=!0):this._stallList.forEach(((t,i)=>{let r=t.timeUpdateInterval;0===i&&this._videoInWaiting&&(r=Math.round(t.timeUpdateInterval%e));const s=t.timeUpdateInterval>this._stallTimeThreshold.report;s&&(o.report.list.push(t.timeUpdateInterval),o.report.stallDuration+=r,this._videoInWaiting||o.report.stallCount++),this._videoInWaiting=s,t.timeUpdateInterval>this._stallTimeThreshold.callback?(o.callback.stallDuration+=r,this._videoInWaitingCallback||o.callback.stallCount++,this._videoInWaitingCallback=!0):this._videoInWaitingCallback=!1,this._openVideoStall100ms&&(o.stall100ms||(o.stall100ms={count:0,duration:0}),t.timeUpdateInterval>100?(o.stall100ms.duration+=r,this._videoInWaiting100ms||o.stall100ms.count++,this._videoInWaiting100ms=!0):this._videoInWaiting100ms=!1),o.pts=t.playTime})),this._stallList=[]}return o}_getPauseDuration(){let e=this._pauseDuration;if(this._pauseDuration=0,this._isPaused){const t=getServerNow(),i=t-(this._pauseStart||0);i>500&&(this._pauseStart=t,e+=i)}return e}_onVideoPause(e){if("pause"===e.eventName)this._isPaused=!0,this._pauseStart=getServerNow();else if("play"===e.eventName&&this._isPaused){this._isPaused=!1;const e=getServerNow()-this._pauseStart;e>500&&(this._pauseDuration+=e)}}_onVideoTimeupdate(e,t){if("timeupdate"===e.eventName){const e=t.domElement;if(!e||0===e.currentTime)return;if(void 0===this._prePts)return void(this._prePts=e.currentTime);if(this._stallList||(this._stallList=[]),e.currentTime>this._prePts){const t=e.currentTime-this._prePts;this._stallList.push({playTime:e.currentTime,timeUpdateInterval:Math.round(1e3*t)})}this._prePts=e.currentTime}}_onVideoRefresh(e,t){var i,r;if(this._stallList||(this._stallList=[]),this._prePts){const e=t.presentationTime-this._prePts;this._stallList.push({playTime:t.presentationTime,timeUpdateInterval:Math.round(e)})}this._recentVideoInfo=t,this._prePts=t.presentationTime,null==(r=null==(i=this._player)?void 0:i.domElement)||r.requestVideoFrameCallback(this._onVideoRefresh.bind(this))}}const _AudioStallObserver=class{constructor(e){__publicField(this,"_audioStallTimer"),__publicField(this,"_preSample"),__publicField(this,"_isStallInPreCallbackEnd",!1),__publicField(this,"_isStallInPreReportEnd",!1),__publicField(this,"_stallList",[]),this._stream=e}static setAudioStallConfig(e){_AudioStallObserver.interval=((null==e?void 0:e.audio_stall_interval)||200)/2,_AudioStallObserver.ratio=(null==e?void 0:e.audio_stall_ratio)||.6}start(e,t){this.stop(),Config2.AUDIO_STALL&&_AudioStallObserver.interval>0&&"number"==typeof e&&"number"==typeof t&&(this._preSample={ts:getServerNow(),concealedSamples:e,totalSamplesReceived:t},this._startStallCountInterval())}stop(){this._stallList=[],this._audioStallTimer&&(clearTimeout(this._audioStallTimer),delete this._audioStallTimer)}destroy(){this.stop()}async getAudioStallInfo(){const e={stats_count:this._stallList.filter((e=>!!e.get_stats_cost)).length,stall_list:[...this._stallList]};try{await this._audioStallCount()}catch(e){}const t=computeStallInfo(this._stallList,2,this._isStallInPreReportEnd);this._isStallInPreReportEnd=t.isStallInEnd;const i=Config2.AUDIO_STALL_DATA/_AudioStallObserver.interval,r=computeStallInfo(this._stallList,i,this._isStallInPreCallbackEnd);return this._isStallInPreCallbackEnd=r.isStallInEnd,this.stop(),this._startStallCountInterval(),{report:{stall_count:t.stall_count,stall_duration:t.stall_duration,list:t.list},callback:{stall_count:r.stall_count,stall_duration:r.stall_duration,list:r.list},extra:e}}_startStallCountInterval(){const e=async()=>{clearTimeout(this._audioStallTimer),delete this._audioStallTimer,await this._audioStallCount(),this._audioStallTimer||(this._audioStallTimer=setTimeout(e,_AudioStallObserver.interval))};this._audioStallTimer=setTimeout(e,_AudioStallObserver.interval)}async _audioStallCount(){var e;if(!this._preSample||getServerNow()-this._preSample.ts<.5*_AudioStallObserver.interval)return;const{hasAudio:t,subAudio:i,virtual:r,virtualOccupy:o,removeTrack:s,audioTrack:n}=this._stream;if(s||!n)return clearTimeout(this._audioStallTimer),void delete this._audioStallTimer;const a=t&&i;if(!a||r&&!o)this._preSample.ts=getServerNow(),this._stallList.push({reason:a?`virtual: ${r}, virtualOccupy: ${o}`:`hasAudio: ${t}, subAudio: ${i}`});else{const t=getServerNow();let i,r,o=0;try{const t=await(null==(e=this._stream.audioTransceiver)?void 0:e.receiver.getStats());null==t||t.forEach((e=>{"inbound-rtp"===e.type&&(i=e),o++}))}catch(e){r=e.message||JSON.stringify(e)}const s=getServerNow(),n=getServerNow(),a=n-this._preSample.ts;if(i){const{concealedSamples:e,totalSamplesReceived:r}=i,o=e-this._preSample.concealedSamples,d=r-this._preSample.totalSamplesReceived,c=o>=0&&d>=0&&o>=_AudioStallObserver.ratio*d;this._stallList.push({concealed:o,received:d,diff:a,start:this._preSample.ts,end:n,get_stats_cost:s-t,get_stats_start:t,get_stats_end:s,is_stall:c}),this._preSample.concealedSamples=e,this._preSample.totalSamplesReceived=r,this._preSample.ts=n}else this._stallList.push({diff:a,start:this._preSample.ts,end:n,get_stats_cost:s-t,get_stats_start:t,get_stats_end:s,reason:o?r||"no inbound-rtp":"no report"})}}};let AudioStallObserver=_AudioStallObserver;__publicField(AudioStallObserver,"interval",100),__publicField(AudioStallObserver,"ratio",.6);const computeStallInfo=(e,t,i)=>{var r;const o={stall_count:0,stall_duration:0,isStallInEnd:!1,list:[]};let s=0,n=0;for(let i=0;i<e.length;i++){const r=e[i];r.is_stall&&(s++,n+=r.diff||0);const a=i===e.length-1;if(!r.is_stall||a){let r=s>=t;const d=i+t-s-1;if(!r&&s>2){let o=0;e.slice(i+1,d+1).forEach((e=>{e.is_stall&&(o+=e.diff||0)})),r=n+o>AudioStallObserver.interval*t*AudioStallObserver.ratio,r&&(i=d,n+=o)}r&&(o.stall_count++,o.stall_duration+=n,o.list.push(n)),a&&(o.isStallInEnd=r),s=n=0}}return!0===(null==(r=e[0])?void 0:r.is_stall)&&i&&o.stall_count>0&&o.stall_count--,o};var RTCExtensionType=(e=>(e[e.CAPTURE=0]="CAPTURE",e[e.PRE_PROCESSING=1]="PRE_PROCESSING",e[e.ENCODE=2]="ENCODE",e[e.TRANSFER=3]="TRANSFER",e[e.POST_PROCESSING=4]="POST_PROCESSING",e[e.DECODE=5]="DECODE",e[e.RENDERING=6]="RENDERING",e))(RTCExtensionType||{}),StreamIndex=(e=>(e[e.STREAM_INDEX_MAIN=0]="STREAM_INDEX_MAIN",e[e.STREAM_INDEX_SCREEN=1]="STREAM_INDEX_SCREEN",e))(StreamIndex||{});class ExtensionManager{constructor(e){__publicField(this,"_plugins",new Map),this.id=e}register(e){const t=this._plugins.get(e.type)||[];if(t.findIndex((t=>t.name===e.name))>-1)throw new Error(`Failed to register ${e.name}: name is repeated.`);t.push(e),this._plugins.set(e.type,t)}getPluginsByType(e){return this._plugins.get(e)||[]}getPluginByName(e,t){return(this._plugins.get(e)||[]).find((e=>e.name===t))}async getPreProcessingTrack(e){const t=this._plugins.get(1)||[];let i=e.mediaTrack;for(const r of t)i=await r.effect(e,i);return i}destroy(){this._plugins.forEach((e=>{e.forEach((e=>e.destroy()))})),this._plugins.clear()}}const logger$9=new Logger$1("InternalEventBus",1);var InternalEvent=(e=>(e.ON_IOS_INTERRUPTION_START="ON_IOS_INTERRUPTION_START",e.ON_IOS_INTERRUPTION_END="ON_IOS_INTERRUPTION_END",e.ON_IOS_LOCAL_TRACK_MUTE="ON_IOS_LOCAL_TRACK_MUTE",e.ON_IOS_LOCAL_TRACK_UNMUTE="ON_IOS_LOCAL_TRACK_UNMUTE",e))(InternalEvent||{});class InternalEventBus extends eventemitter3Exports.EventEmitter{emit(e,...t){return logger$9.info(e),super.emit(e,...t)}}const internalEventBus=new InternalEventBus;var dumpAudioDataWorklet="data:application/javascript;base64,Y2xhc3MgRHVtcEF1ZGlvRGF0YSBleHRlbmRzIEF1ZGlvV29ya2xldFByb2Nlc3NvciB7CiAgcHJvY2VzcyhpbnB1dHMpIHsKICAgIHRoaXMucG9ydC5wb3N0TWVzc2FnZSh7CiAgICAgIGRhdGE6IGlucHV0c1swXSwKICAgICAgY2hhbm5lbENvdW50OiBpbnB1dHNbMF0ubGVuZ3RoLAogICAgICBzYW1wbGVSYXRlLAogICAgfSk7CiAgICByZXR1cm4gdHJ1ZTsKICB9Cn0KCnJlZ2lzdGVyUHJvY2Vzc29yKCdkdW1wLWF1ZGlvLWRhdGEnLCBEdW1wQXVkaW9EYXRhKTsK";const logger$8=new Logger$1("AudioContext",1);class WebAudioManager{constructor(){__publicField(this,"isWorkletReady"),__publicField(this,"_audioContextInstance"),__publicField(this,"_previousState",""),__publicField(this,"_currentState",""),__publicField(this,"_contextStuckAt",0);let e=0;isSSR()||setInterval((()=>{if(this._audioContextInstance){const t=this._audioContextInstance.currentTime;this._contextStuckAt?this._contextStuckAt!==t&&(this._contextStuckAt=0,logger$8.info("currentTime resume"),reportGlobalInvokeStatus("currentTime resume","")):t&&e===t&&(this._contextStuckAt=t,logger$8.warn("currentTime stuck",this._contextStuckAt),this._audioContextInstance.suspend(),this._audioContextInstance.resume(),reportGlobalInvokeStatus("AudioContext currentTime stuck",this._contextStuckAt)),e=t}}),3e3)}getAudioContextInstance(){if(!this._audioContextInstance){const e=window.AudioContext||window.webkitAudioContext;this._audioContextInstance=is48kSupported?new e:new e({sampleRate:44100});try{this.isWorkletReady=this._audioContextInstance.audioWorklet.addModule(dumpAudioDataWorklet),this.isWorkletReady.catch((e=>{reportGlobalError("initial AudioWorklet error in promise",-1,`${e.name}-${e.message}`),logger$8.error("isWorkletReady",e),this.isWorkletReady=null}))}catch(e){reportGlobalError("initial AudioWorklet error in catch",-1,`${e.name}-${e.message}`),logger$8.error("isWorkletReady",e),this.isWorkletReady=null}this._audioContextInstance.onstatechange=()=>{var e,t,i;logger$8.warn("state change",null==(e=this._audioContextInstance)?void 0:e.state),this._previousState=this._currentState,this._currentState=(null==(t=this._audioContextInstance)?void 0:t.state)||"","interrupted"===(null==(i=this._audioContextInstance)?void 0:i.state)&&this._audioContextInstance.resume(),(isIOS||isIPad)&&("running"===this._previousState&&"interrupted"===this._currentState&&internalEventBus.emit(InternalEvent.ON_IOS_INTERRUPTION_START),"interrupted"===this._previousState&&"running"===this._currentState&&internalEventBus.emit(InternalEvent.ON_IOS_INTERRUPTION_END))}}return this._audioContextInstance}}class AudioLevelFetcher{constructor(e){__publicField(this,"_ctx"),__publicField(this,"_analyserNode"),__publicField(this,"_audioSource"),__publicField(this,"currentTrackId"),this.currentTrackId=e.id;const t=audioContextManager.getAudioContextInstance();if(e instanceof MediaStreamTrack){const i=new MediaStream;i.addTrack(e),this._audioSource=t.createMediaStreamSource(i)}else this._audioSource=t.createMediaElementSource(e),this._audioSource.connect(t.destination);const i=t.createAnalyser();this._audioSource.connect(i),this._analyserNode=i,this._ctx=t}getAudioLevel(){var e;"suspended"===(null==(e=this._ctx)?void 0:e.state)&&this._ctx.resume();const t=new Uint8Array(2048);this._analyserNode.getByteTimeDomainData(t);let i=0;t.forEach((e=>i=Math.max(i,Math.abs(e-128))));const r=i/128*255;return r>2?r:0}async resume(){var e;await(null==(e=this._ctx)?void 0:e.resume())}destroy(){this._audioSource.disconnect(),this._analyserNode.disconnect()}}class AudioDataFetcher extends eventemitter3Exports.EventEmitter{constructor(e,t,i=audioContextManager.getAudioContextInstance(),r=audioContextManager.isWorkletReady){super(),__publicField(this,"_ctx"),__publicField(this,"_worklet"),__publicField(this,"_source"),__publicField(this,"_buffers",[]),__publicField(this,"_bufferLength",0),__publicField(this,"_sampleRate"),__publicField(this,"_channelCount"),__publicField(this,"_frameSize"),e instanceof MediaStreamTrack?this._channelCount=e.getSettings().channelCount??1:this._channelCount=e.channelCount,this._ctx=i,this._frameSize=t,null==r||r.then((()=>{this._worklet=new AudioWorkletNode(this._ctx,"dump-audio-data"),e instanceof MediaStreamTrack?this._source=this._ctx.createMediaStreamSource(new MediaStream([e])):this._source=e,this._source.connect(this._worklet),this._initWorkletEventListener(this._worklet)})).catch()}_initWorkletEventListener(e){e.port.onmessage=this._handleWorkletMessage.bind(this)}_handleWorkletMessage(e){const{data:t,sampleRate:i}=e.data;if(this._bufferLength>=this._frameSize||this._sampleRate!==i){if(this._sampleRate){const e=1===this._channelCount||1===t.length?1:2;this.emit("data",{channels:[...this._buffers],sampleRate:this._sampleRate,channelCount:e})}this._sampleRate=i,this._buffers=new Array(this._channelCount).fill(0).map((()=>new Float32Array(this._frameSize))),this._bufferLength=0}for(let e=0;e<this._channelCount;e++)this._buffers[e].set(t[e],this._bufferLength);this._bufferLength=this._bufferLength+t[0].length}setFrameSize(e){this._frameSize=e}destroy(){var e,t,i;this.removeAllListeners("data"),this._worklet&&(null==(e=this._source)||e.disconnect(this._worklet)),null==(t=this._worklet)||t.disconnect(),null==(i=this._worklet)||i.port.close(),this._buffers=[],delete this._source,delete this._worklet}}const audioContextManager=new WebAudioManager,createElement=(e,t={})=>{const i=document.createElement(e);return t.id&&(i.id=t.id),t.classList&&t.classList.forEach((e=>{i.classList.add(e)})),t.style&&Object.assign(i.style,t.style),t.attributes&&Object.entries(t.attributes).forEach((([e,t])=>{"muted"===e?i.muted=!0:i.setAttribute(e,t)})),i};class DeviceDetector extends EnhancedEventEmitter{constructor(){var e;super(),__publicField(this,"deviceMap",{audioinput:new Map,audiooutput:new Map,videoinput:new Map}),__publicField(this,"checkDeviceChangeTimer",null),__publicField(this,"isSupportedPermissionsQuery",!1),__publicField(this,"isGrantedMicrophonePermission",!1),__publicField(this,"isGrantedCameraPermission",!1),this.isSupportedPermissionsQuery=!isSSR()&&!!(null==(e=null==navigator?void 0:navigator.permissions)?void 0:e.query),this._handleDeviceChange=this._handleDeviceChange.bind(this),!isSSR()&&this.initListener().then((()=>{this.updateDeviceListInSilent()}))}async refreshDevices(e="audio"){if(!navigator.mediaDevices)return;let t;if(isFirefox)try{t="audio"===e?await navigator.mediaDevices.getUserMedia({audio:!0}):await navigator.mediaDevices.getUserMedia({video:!0})}catch(e){}const i=await navigator.mediaDevices.enumerateDevices();t&&t.getTracks().forEach((e=>e.stop())),i.forEach((e=>{var t;e.deviceId&&(null==(t=this.deviceMap[e.kind])||t.set(e.deviceId,e))}))}async initListener(){var e,t;if(void 0!==(null==(e=navigator.mediaDevices)?void 0:e.ondevicechange)&&"function"==typeof(null==(t=navigator.mediaDevices)?void 0:t.addEventListener)?navigator.mediaDevices.addEventListener("devicechange",(()=>{this._handleDeviceChange(),setTimeout((()=>{this._handleDeviceChange()}),300)})):this.checkDeviceChangeTimer=window.setInterval((()=>{this._handleDeviceChange()}),3e3),this.isSupportedPermissionsQuery){try{const e=await navigator.permissions.query({name:"microphone"});this.isGrantedMicrophonePermission="granted"===e.state,e.addEventListener("change",(()=>{this.isGrantedMicrophonePermission="granted"===e.state}))}catch{}try{const e=await navigator.permissions.query({name:"camera"});this.isGrantedCameraPermission="granted"===e.state,e.addEventListener("change",(()=>{this.isGrantedCameraPermission="granted"===e.state}))}catch{}}}async _handleDeviceChange(){if(!navigator.mediaDevices)return;let e;isFirefox&&(e=await navigator.mediaDevices.getUserMedia({audio:!0}));let t=await navigator.mediaDevices.enumerateDevices();t=t.filter((e=>!!e.deviceId)),e&&e.getTracks().forEach((e=>e.stop()));const i=Array.from([...this.deviceMap.audioinput.values(),...this.deviceMap.videoinput.values(),...this.deviceMap.audiooutput.values()]);(isMobile||isIPad)&&!i.length&&t.length&&t.forEach((e=>{var t;null==(t=this.deviceMap[e.kind])||t.set(e.deviceId,e)})),i.forEach((e=>{t.find((t=>t.deviceId===e.deviceId&&t.kind===e.kind&&t.label===e.label))||(this.deviceMap[e.kind].delete(e.deviceId),e.kind.includes("video")?this.emit(EngineEventsTypes.onVideoDeviceStateChanged,{mediaDeviceInfo:e,deviceState:"inactive"}):e.kind.includes("audio")&&this.emit(EngineEventsTypes.onAudioDeviceStateChanged,{mediaDeviceInfo:e,deviceState:"inactive"}))})),t.forEach((e=>{const t=this.deviceMap[e.kind].get(e.deviceId);this.deviceMap[e.kind].set(e.deviceId,e),t||(e.kind.includes("video")?this.emit(EngineEventsTypes.onVideoDeviceStateChanged,{mediaDeviceInfo:e,deviceState:"active"}):e.kind.includes("audio")&&this.emit(EngineEventsTypes.onAudioDeviceStateChanged,{mediaDeviceInfo:e,deviceState:"active"}))}))}async getUserMedia(e){const t=await navigator.mediaDevices.getUserMedia(e);return(null==e?void 0:e.audio)&&(this.isGrantedMicrophonePermission=!0),(null==e?void 0:e.video)&&(this.isGrantedCameraPermission=!0),(null==e?void 0:e.video)?this.refreshDevices("video"):this.refreshDevices("audio"),t}async checkPermissionsByDevices(){const e={audio:!1,video:!1};if(!navigator.mediaDevices)return e;const t=await navigator.mediaDevices.enumerateDevices();return e.audio=t.filter((e=>"audioinput"===e.kind&&e.label&&e.deviceId)).length>0,e.video=t.filter((e=>"videoinput"===e.kind&&e.label&&e.deviceId)).length>0,e}async getPermissions(e={}){var t,i,r;let{audio:o,video:s}=e;const{force:n}=e;o||s||(o=!0,s=!0);const a={audio:!1,video:!1,reason:void 0};if(!n)if(this.isSupportedPermissionsQuery){if(o&&s){if(this.isGrantedMicrophonePermission&&this.isGrantedCameraPermission)return a.audio=!0,a.video=!0,a}else if(o&&this.isGrantedMicrophonePermission||s&&this.isGrantedCameraPermission)return a.audio=this.isGrantedMicrophonePermission,a.video=this.isGrantedCameraPermission,a}else{const e=await this.checkPermissionsByDevices();if(o&&s){if(e.audio&&e.video)return e}else if(o&&e.audio||s&&e.video)return e}if(null==(t=navigator.mediaDevices)?void 0:t.getUserMedia)try{const e=await navigator.mediaDevices.getUserMedia({audio:o,video:s});e&&(e.getTracks().forEach((e=>e.stop())),o&&(a.audio=!0,this.isGrantedMicrophonePermission=!0),s&&(a.video=!0,this.isGrantedCameraPermission=!0))}catch(e){a.reason=e,this.isSupportedPermissionsQuery&&(o&&(a.audio="granted"===(null==(i=await navigator.permissions.query({name:"microphone"}).catch((()=>{})))?void 0:i.state)),s&&(a.video="granted"===(null==(r=await navigator.permissions.query({name:"camera"}).catch((()=>{})))?void 0:r.state)))}return o?await this.refreshDevices("audio"):await this.refreshDevices("video"),a}async updateDeviceListInSilent(){this.isGrantedCameraPermission&&this.isGrantedMicrophonePermission&&this.refreshDevices("audio")}async enumerateDevices(){return await this.getPermissions(),await this.refreshDevices(),Array.from([...this.deviceMap.audioinput.values(),...this.deviceMap.videoinput.values(),...this.deviceMap.audiooutput.values()])}async enumerateAudioCaptureDevices(){return await this.getPermissions({audio:!0}),await this.refreshDevices(),Array.from(this.deviceMap.audioinput.values())}async enumerateVideoCaptureDevices(){return await this.getPermissions({video:!0}),await this.refreshDevices("video"),Array.from(this.deviceMap.videoinput.values())}async enumerateAudioPlaybackDevices(){return await this.getPermissions({audio:!0}),await this.refreshDevices("audio"),Array.from(this.deviceMap.audiooutput.values())}async getAudioPlaybackDeviceById(e){return(await this.enumerateAudioPlaybackDevices()).find((t=>t.deviceId===e))}}const dd=new DeviceDetector;isDebuggerMode&&(window.__rtc_dd__=dd);var RtcErrorCode=(e=>(e[e.AUTOPLAY_FAILED=-1e3]="AUTOPLAY_FAILED",e[e.TRACK_ERROR=-1001]="TRACK_ERROR",e[e.Fetch_MODIFY=-1002]="Fetch_MODIFY",e[e.BLACK_BROWSER=-1003]="BLACK_BROWSER",e[e.DC_SEND_ERROR=-1004]="DC_SEND_ERROR",e[e.DUPLICATE_DOM=-1005]="DUPLICATE_DOM",e))(RtcErrorCode||{});const logger$7=new Logger$1("VideoSnapshot",1),getPlayingVideoDom=e=>{const t=null==e?void 0:e.domElement;if(t&&!t.paused&&4===t.readyState)return t},takeSnapshot=async(e,t)=>{const i=document.createElement("canvas"),r=i.getContext("2d");if(!r)throw new Error("canvas.getContext error");const o=(e,t,o)=>(t=t||e.width,o=o||e.height,i.width=t,i.height=o,r.setTransform(1,0,0,1,0,0),r.drawImage(e,0,0,t,o),r.getImageData(0,0,t,o)),s=Date.now(),n=getPlayingVideoDom(t);if(n){if(logger$7.info("takeSnapshot","VideoPlayer already set."),null==t?void 0:t.isAlpha){logger$7.info("takeSnapshot","manually process alpha video");const e=n.videoWidth,o=n.videoHeight,a=t.videoHeight;i.width=e,i.height=a,r.drawImage(n,0,o/2,e,o/2,0,0,e,a);const d=r.getImageData(0,0,e,a);return logger$7.info("takeSnapshot",`success (alpha manual), cost ${Date.now()-s}ms`),d}const e=(null==t?void 0:t.videoWidth)||n.videoWidth,a=(null==t?void 0:t.videoHeight)||n.videoHeight,d=await o(n,e,a);return logger$7.info("takeSnapshot",`success, cost ${Date.now()-s}ms`),d}if(window.ImageCapture){const t=new window.ImageCapture(e);if("live"===t.track.readyState&&t.track.enabled&&!t.track.muted){logger$7.info("takeSnapshot","use ImageCapture");const e=await o(await t.grabFrame());return logger$7.info("takeSnapshot",`success, cost ${Date.now()-s}ms`),e}}return logger$7.info("takeSnapshot","use temp video"),new Promise(((t,i)=>{const r=new MediaStream([e]),n=document.createElement("video");n.setAttribute("playsinline",""),n.muted=!0,document.body.appendChild(n),n.onplaying=()=>{const i=o(n,n.videoWidth,n.videoHeight);logger$7.info("takeSnapshot",`success, cost ${Date.now()-s}ms`),t(i),r.removeTrack(e),n.srcObject=null,n.load()},n.onerror=i,n.srcObject=r,n.play()}))},DEFAULT_PLAYER_ID=Symbol("default");var PlayerStallEvent=(e=>(e.START_STALL_OBSERVE="start_stall_observe",e.STOP_STALL_OBSERVE="stop_stall_observe",e))(PlayerStallEvent||{});class LocalVideoTrack extends LocalTrack{constructor(e,t,i){super(e,t,{...i,mediaType:MediaType.VIDEO}),__publicField(this,"resolution"),__publicField(this,"videoPlayers",new Map),this.resolution={width:0,height:0}}intersection(){const e={};return this.videoPlayers.forEach(((t,i)=>{e[i.toString()]=t.isIntersecting})),e}async updateVideoCaptureConfig(e){this.logger.info("updateVideoEncoderConfig","update localVideoTrack: ",e);const t={...e};delete t.contentHint,isFirefox&&this.trackInfo.streamIndex===ExtendStreamIndex.MAIN&&(t.frameRate={ideal:30,max:30}),await this.originTrack.applyConstraints(t);const i=this.originTrack.getSettings();(i.width&&i.width!==this.resolution.width||i.height&&i.height!==this.resolution.height)&&(this.resolution={width:i.width,height:i.height},this.emit("resolution-change",this.resolution))}setContentHint(e){"contentHint"in this.originTrack&&["text","motion","detail"].includes(e)&&(this.originTrack.contentHint=e)}setTrack(e,t){this._originTrack=e,this.trackInfo={...this.trackInfo,...t},this.isTrackReady=this.generatePreProcessingTrack()}setPlayer(e,t,i,r){const o=e.playerId??DEFAULT_PLAYER_ID;let s=this.videoPlayers.get(o);return e.player!==s&&(s=e.player,this.videoPlayers.set(o,s),r(s,this.isPublic,this.streamIndex)),this.mirror(!!t),this.dummy||i===RTCAutoPlayPolicy.PLAY_MANUALLY||this.play(o),s.domElement}setUserId(e){this.trackInfo.streamUserId=e,this.videoPlayers.forEach((t=>{t.userId=e}))}snapshot(){let e;for(const t of this.videoPlayers.values())if(t.played){e=t;break}return takeSnapshot(this.preprocessingTrack,e)}setRenderMode(e,t){var i;return null==(i=this.videoPlayers.get(e))?void 0:i.setRenderMode(t)}mirror(e){this.videoPlayers.forEach((t=>{t.mirror(e)}))}removePlayerTrack(){this.videoPlayers.forEach(((e,t)=>{var i;null==(i=this.videoPlayers.get(t))||i.removeTrack()}))}play(e){const t=this.videoPlayers.get(e);return(null==t?void 0:t.played)?t.manuallyPlay():null==t?void 0:t.playVideo(this)}playAll(){this.videoPlayers.forEach(((e,t)=>{this.play(t)}))}manuallyPlay(e){var t;return null==(t=this.videoPlayers.get(e))?void 0:t.manuallyPlay()}pause(e){var t;null==(t=this.videoPlayers.get(e))||t.manuallyPause()}stop(e){var t;return null==(t=this.videoPlayers.get(e))?void 0:t.stop()}stopAll(){return this.videoPlayers.forEach(((e,t)=>{this.stop(t)}))}removePlayer(e){this.videoPlayers.delete(e)}destroy(){this.videoPlayers.forEach(((e,t)=>{this.stop(t),e.removeAllListeners(),this.videoPlayers.delete(t)})),super.destroy()}}class RemoteVideoTrack extends RemoteTrack{constructor(e,t,i,r){super(e,t,{...r,mediaType:MediaType.VIDEO}),__publicField(this,"videoPlayers",new Map),__publicField(this,"_stream"),__publicField(this,"_observingPlayer"),this._stream=i}get observingPlayerId(){var e;return null==(e=this._observingPlayer)?void 0:e.playerId}getSizeByPlayer(){let e=0,t=0;return this.videoPlayers.forEach((i=>{i.videoWidth&&i.videoHeight&&(e=i.videoWidth,t=i.videoHeight)})),{width:e,height:t}}intersection(){const e={};return this.videoPlayers.forEach(((t,i)=>{e[i.toString()]=t.isIntersecting})),e}setPlayer(e,t,i,r){const o=t.playerId??DEFAULT_PLAYER_ID;let s=this.videoPlayers.get(o);return t.player!==s&&(s=t.player,isUndefined(this.streamIndex)||s.mirror(this._ctx.getRemoteMirrorType(this.trackInfo.streamUserId??"",this.streamIndex)),this.videoPlayers.set(o,s),this._handlePlayerStallEvent(s),r(s,this.isPublic,this.streamIndex)),this.dummy||this.play(o),null==s?void 0:s.domElement}mirror(e){this.videoPlayers.forEach((t=>{t.mirror(e)}))}dangerousGetPlayer(e){return this.videoPlayers.get(e)}snapshot(){let e;for(const t of this.videoPlayers.values())if(t.played){e=t;break}return takeSnapshot(this.preprocessingTrack,e)}stop(e){var t;null==(t=this.videoPlayers.get(e))||t.stop()}stopAll(){this.videoPlayers.forEach(((e,t)=>{this.stop(t)}))}play(e){if(this._ctx.autoPlayPolicy===RTCAutoPlayPolicy.PLAY_MANUALLY)return;const t=this.videoPlayers.get(e);return null==t?void 0:t.playVideo(this)}manuallyPlay(e){const t=this.videoPlayers.get(e);return(null==t?void 0:t.played)?t.manuallyPlay():null==t?void 0:t.playVideo(this)}pause(e){var t;return null==(t=this.videoPlayers.get(e))?void 0:t.manuallyPause()}_handlePlayerStallEvent(e){e.on("start_stall_observe",(()=>{!this._observingPlayer&&e&&(this._observingPlayer=e,this._stream.startVideoStallObserve(this._observingPlayer))})),e.on("stop_stall_observe",(()=>{this._observingPlayer===e&&(this._stream.stopVideoStallObserve(),this._observingPlayer=void 0,this.videoPlayers.forEach((e=>{!this._observingPlayer&&e.played&&(this._observingPlayer=e,this._stream.startVideoStallObserve(e))})))}))}removePlayer(e){this.videoPlayers.delete(e)}setAlphaInfo(e){this.videoPlayers.forEach((t=>{t.setAlphaInfo(e)}))}destroy(){this.videoPlayers.forEach(((e,t)=>{this.stop(t),e.removeAllListeners(),this.videoPlayers.delete(t)})),super.destroy()}}class AlphaVideoRenderer{constructor(){__publicField(this,"canvas"),__publicField(this,"gl",null),__publicField(this,"program",null),__publicField(this,"videoTexture",null),__publicField(this,"animationFrameId",null),__publicField(this,"isRendering",!1),__publicField(this,"positionBuffer",null),__publicField(this,"texCoordBuffer",null),__publicField(this,"positionLocation",-1),__publicField(this,"texCoordLocation",-1),__publicField(this,"textureLocation",null),__publicField(this,"render",(e=>{if(this.isRendering&&this.gl&&this.program){if(e.videoWidth>0&&e.videoHeight>0){const t=e.videoHeight/2;this.canvas.width===e.videoWidth&&this.canvas.height===t||(this.canvas.width=e.videoWidth,this.canvas.height=t,this.gl.viewport(0,0,this.canvas.width,this.canvas.height))}this.gl.clearColor(0,0,0,0),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.enable(this.gl.BLEND),this.gl.blendFunc(this.gl.SRC_ALPHA,this.gl.ONE_MINUS_SRC_ALPHA),this.gl.useProgram(this.program),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.positionBuffer),this.gl.enableVertexAttribArray(this.positionLocation),this.gl.vertexAttribPointer(this.positionLocation,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.texCoordBuffer),this.gl.enableVertexAttribArray(this.texCoordLocation),this.gl.vertexAttribPointer(this.texCoordLocation,2,this.gl.FLOAT,!1,0,0),this.gl.uniform1i(this.textureLocation,0),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4),this.animationFrameId=requestAnimationFrame((()=>this.render(e)))}})),this.canvas=document.createElement("canvas"),this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.objectFit="contain",this.initWebGL()}initWebGL(){try{if(this.gl=this.canvas.getContext("webgl")||this.canvas.getContext("experimental-webgl"),!this.gl)return console.error("WebGL not supported"),!1;const e="\n attribute vec2 a_position;\n attribute vec2 a_texCoord;\n varying vec2 v_texCoord;\n\n void main() {\n gl_Position = vec4(a_position, 0.0, 1.0);\n v_texCoord = a_texCoord;\n }\n ",t="\n precision mediump float;\n varying vec2 v_texCoord;\n uniform sampler2D u_texture;\n\n void main() {\n // 上半部分是 alpha 通道 (0.0 - 0.5)\n // 下半部分是 RGB 通道 (0.5 - 1.0)\n\n // 获取 RGB 值(从下半部分)\n vec2 rgbCoord = vec2(v_texCoord.x, v_texCoord.y * 0.5 + 0.5);\n vec4 rgbColor = texture2D(u_texture, rgbCoord);\n\n // 获取 Alpha 值(从上半部分)\n vec2 alphaCoord = vec2(v_texCoord.x, v_texCoord.y * 0.5);\n vec4 alphaColor = texture2D(u_texture, alphaCoord);\n\n // 使用 alpha 通道的灰度值作为透明度\n float alpha = (alphaColor.r + alphaColor.g + alphaColor.b) / 3.0;\n\n gl_FragColor = vec4(rgbColor.rgb, alpha);\n }\n ",i=this.createShader(this.gl.VERTEX_SHADER,e),r=this.createShader(this.gl.FRAGMENT_SHADER,t);return i&&r?(this.program=this.createProgram(i,r),this.program?(this.positionLocation=this.gl.getAttribLocation(this.program,"a_position"),this.texCoordLocation=this.gl.getAttribLocation(this.program,"a_texCoord"),this.textureLocation=this.gl.getUniformLocation(this.program,"u_texture"),this.setupBuffers(),this.videoTexture=this.gl.createTexture(),!0):(console.error("Failed to create program"),!1)):(console.error("Failed to create shaders"),!1)}catch(e){return console.error("Failed to initialize WebGL:",e),!1}}createShader(e,t){if(!this.gl)return null;const i=this.gl.createShader(e);return i?(this.gl.shaderSource(i,t),this.gl.compileShader(i),this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS)?i:(console.error("Shader compile error:",this.gl.getShaderInfoLog(i)),this.gl.deleteShader(i),null)):null}createProgram(e,t){if(!this.gl)return null;const i=this.gl.createProgram();return i?(this.gl.attachShader(i,e),this.gl.attachShader(i,t),this.gl.linkProgram(i),this.gl.getProgramParameter(i,this.gl.LINK_STATUS)?i:(console.error("Program link error:",this.gl.getProgramInfoLog(i)),this.gl.deleteProgram(i),null)):null}setupBuffers(){if(!this.gl)return;this.positionBuffer=this.gl.createBuffer(),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.positionBuffer);const e=new Float32Array([-1,-1,1,-1,-1,1,1,1]);this.gl.bufferData(this.gl.ARRAY_BUFFER,e,this.gl.STATIC_DRAW),this.texCoordBuffer=this.gl.createBuffer(),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.texCoordBuffer);const t=new Float32Array([0,1,1,1,0,0,1,0]);this.gl.bufferData(this.gl.ARRAY_BUFFER,t,this.gl.STATIC_DRAW)}startRender(e){this.isRendering||(this.isRendering=!0,this.render(e))}stopRender(){this.isRendering=!1,null!==this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null)}getCanvas(){return this.canvas}setObjectFit(e){this.canvas.style.objectFit=e}setMirror(e){this.canvas.style.transform=e?"rotateY(180deg)":""}destroy(){this.stopRender(),this.gl&&(this.videoTexture&&(this.gl.deleteTexture(this.videoTexture),this.videoTexture=null),this.positionBuffer&&(this.gl.deleteBuffer(this.positionBuffer),this.positionBuffer=null),this.texCoordBuffer&&(this.gl.deleteBuffer(this.texCoordBuffer),this.texCoordBuffer=null),this.program&&(this.gl.deleteProgram(this.program),this.program=null),this.gl=null),this.canvas.parentElement&&this.canvas.parentElement.removeChild(this.canvas)}}const MEDIA_EVENTS=["play","playing","pause","ended","error","seeking","seeked","waiting","canplay","canplaythrough","durationchange","volumechange","loadedmetadata","loadeddata","loadstart","timeupdate"],AUDIO_ATTRIBUTES={playsinline:"","webkit-playsinline":""},VIDEO_ATTRIBUTES={playsinline:"","webkit-playsinline":"","x5-playsinline":"","x5-video-player-type":"h5","x-webkit-airplay":"allow",preload:"",muted:""},NO_RENDER_VERSION=15,NO_RENDER_RETRY_INTERVAL=1e3,NO_RENDER_RESET_INTERVAL=500;class VideoPlayer extends eventemitter3Exports.EventEmitter{constructor(e,t,i){var r;super(),__publicField(this,"_containerDom"),__publicField(this,"_videoDom"),__publicField(this,"_alphaRenderer"),__publicField(this,"_canvasDom"),__publicField(this,"userId"),__publicField(this,"renderMode"),__publicField(this,"mirrorType",MirrorType.MIRROR_TYPE_NONE),__publicField(this,"isScreen"),__publicField(this,"isLocal"),__publicField(this,"isAlpha"),__publicField(this,"alphaInfo"),__publicField(this,"played",!1),__publicField(this,"_needLoad",!1),__publicField(this,"_emitPlayFailed",!1),__publicField(this,"_videoContainer"),__publicField(this,"_safari15VideoTimer"),__publicField(this,"_monitor"),__publicField(this,"logger"),__publicField(this,"_onLocalTrackMute"),__publicField(this,"_onInterruptionEnd"),__publicField(this,"_needResume",!1),__publicField(this,"_rotate",0),__publicField(this,"_rotateDom"),__publicField(this,"_resizeObserver"),__publicField(this,"_hasManuallyPaused",!1),__publicField(this,"isIntersecting"),__publicField(this,"intersectionObserver"),__publicField(this,"hasStartPlaying",!1),__publicField(this,"emitVideoEvent",(e=>{var t,i;const r={type:"video",rawEvent:e,readyState:(null==(t=this._videoDom)?void 0:t.readyState)||0,userId:this.userId,eventName:e.type,currentTime:(null==(i=this._videoDom)?void 0:i.currentTime)||0,isScreen:this.isScreen};switch(this.emit("playback_event",r),e.type){case"canplay":this.refreshRenderSize("the video started playing."),this._internalPlay();break;case"loadeddata":this._internalPlay();break;case"playing":this.logger.info("VideoPlayerPlaying",`[userId-${this.userId}] video element playing`);break;case"pause":this.logger.info("VideoPlayerPause",`[userId-${this.userId}] video element pause`),this._needResume?(this.logger.info("VideoPlayerPause",`[userId-${this.userId}] video element resume`),this._internalPlay(),this._needResume=!1):this._hasManuallyPaused||(this.logger.info("VideoPlayerPause",`[userId-${this.userId}] video element resume`),getParameter("AUTOPLAY_THROTTLE")?this._throttledInternalPlay():this._internalPlay())}})),__publicField(this,"_internalPlay",(()=>{var e,t;if(reportRtcInvokeStatus(this.engineId,"video _internalPlay",{paused:null==(e=this._videoDom)?void 0:e.paused,hasManuallyPaused:this._hasManuallyPaused}),this._hasManuallyPaused||!(null==(t=this._videoDom)?void 0:t.paused))return;const i=this._videoDom.play();(null==i?void 0:i.then)&&i.then((()=>{var e;this.isLocal&&isCriOS&&!this._needLoad&&(null==(e=this._videoDom)||e.load(),this._needLoad=!0)})).catch((e=>{var t,i,r,o;this._emitPlayFailed||("AbortError"!==e.name?(this._emitPlayFailed=!0,null==(i=this._monitor)||i.report("rtc_error",{message:`video autoplay failed, userId: ${this.userId}, ${e.name}`,error_code:RtcErrorCode.AUTOPLAY_FAILED}),this.emit("playback_event",{type:"video",rawEvent:e,readyState:(null==(r=this._videoDom)?void 0:r.readyState)||0,userId:this.userId,eventName:"autoplay-error",currentTime:(null==(o=this._videoDom)?void 0:o.currentTime)||0,isScreen:this.isScreen})):null==(t=this._monitor)||t.report("rtc_error",{message:`video autoplay failed, userId: ${this.userId}, ${e.name}`,error_code:RtcErrorCode.AUTOPLAY_FAILED}))}))})),__publicField(this,"_throttledInternalPlay",throttle(this._internalPlay,getParameter("AUTOPLAY_THROTTLE"))),this.engineId=e,this.playerId=t;const o=i.renderDom;this._monitor=getMonitor(e),this.logger=new Logger$1("Player",0,e);const{userId:s}=i,n=i.isScreen?VideoRenderMode.RENDER_MODE_FIT:VideoRenderMode.RENDER_MODE_HIDDEN;this.renderMode=void 0!==i.renderMode?i.renderMode:n,this._rotate=Number(i.rotation||0);const a="string"==typeof o?document.getElementById(o):o;if(!a)throw new SDKError(ErrorCode.CANT_FIND_DOM,"can't find dom");this._videoContainer=document.createElement("div"),this._videoContainer.style.width="100%",this._videoContainer.style.height="100%",this._videoContainer.style.position="relative",this._videoContainer.style.overflow="hidden",this._containerDom=a,this.userId=s,this.isLocal=!!i.isLocal,this.isScreen=!!i.isScreen,this.isAlpha=!!(null==(r=i.alphaInfo)?void 0:r.enableAlpha),this.alphaInfo=i.alphaInfo,this._initVideo(),!this.isLocal||15!==(null==iOSVersion?void 0:iOSVersion[0])&&15!==safariVersion||(this._safari15VideoTimer=setTimeout((()=>{try{this._videoContainer.style.display="block",setTimeout((()=>{this._videoContainer.style.display="flex"}),500)}catch(e){}}),1e3))}_initVideo(){this._videoDom||(this._videoDom=createElement("video",{style:{width:"100%",height:"100%"},attributes:VIDEO_ATTRIBUTES}),this._videoDom.id=`${this.userId}_${genUuid()}`,this.setRenderMode(this.renderMode),this.mirror(this.mirrorType===MirrorType.MIRROR_TYPE_RENDER)),this.isAlpha&&this._initAlphaRenderer(),this._containerDom.appendChild(this._videoContainer),[90,270].indexOf(this._rotate)>-1?(this._rotateDom=this._createRotationDiv(),this.isAlpha&&this._canvasDom?(this._videoDom.style.display="none",this._rotateDom.appendChild(this._videoDom),this._rotateDom.appendChild(this._canvasDom)):this._rotateDom.appendChild(this._videoDom),this._videoContainer.appendChild(this._rotateDom)):(180===this._rotate&&(this._videoContainer.style.transform="rotate(180deg)"),this.isAlpha&&this._canvasDom?(this._videoDom.style.display="none",this._videoContainer.appendChild(this._videoDom),this._videoContainer.appendChild(this._canvasDom)):this._videoContainer.appendChild(this._videoDom)),this._initInterSectionObserver(),this._initListeners(),this._onLocalTrackMute=()=>{this._needResume=!0},this._onInterruptionEnd=()=>{this.logger.warn("resume player after iOS interruption"),this._internalPlay()},internalEventBus.on(InternalEvent.ON_IOS_LOCAL_TRACK_MUTE,this._onLocalTrackMute),internalEventBus.on(InternalEvent.ON_IOS_LOCAL_TRACK_UNMUTE,this._onInterruptionEnd),internalEventBus.on(InternalEvent.ON_IOS_INTERRUPTION_END,this._onInterruptionEnd)}_initAlphaRenderer(){this._alphaRenderer||(this._alphaRenderer=new AlphaVideoRenderer,this._canvasDom=this._alphaRenderer.getCanvas(),this._alphaRenderer.setObjectFit(this._getObjectFitFromRenderMode(this.renderMode)),this._alphaRenderer.setMirror(this.mirrorType===MirrorType.MIRROR_TYPE_RENDER))}_getObjectFitFromRenderMode(e){return e===VideoRenderMode.RENDER_MODE_FIT?"contain":e===VideoRenderMode.RENDER_MODE_FILL?"fill":"cover"}_initInterSectionObserver(){!this.intersectionObserver&&"undefined"!=typeof IntersectionObserver&&this._videoDom&&(this.intersectionObserver=new IntersectionObserver((e=>{e[0]&&(this.isIntersecting=e[0].isIntersecting)}),{}),this.intersectionObserver.observe(this._videoDom))}_closeIntersectionObserver(){this.intersectionObserver&&this._videoDom&&(this.intersectionObserver.disconnect(),this.intersectionObserver.unobserve(this._videoDom),delete this.intersectionObserver)}_createRotationDiv(){const e=document.createElement("div");return e.style.transform=`rotate(${this._rotate}deg)`,180!==this._rotate&&(e.style.position="absolute",this.refreshRenderSize("init"),window.ResizeObserver&&(this._resizeObserver=new ResizeObserver((()=>{this.refreshRenderSize("the container size has changed.")})),this._resizeObserver.observe(this._containerDom))),e}refreshRenderSize(e){var t,i;if(this._rotateDom){this.logger.print("refreshRenderSize",`Because ${e}`);const r=Number(window.getComputedStyle(this._containerDom).width.replace("px","")),o=Number(window.getComputedStyle(this._containerDom).height.replace("px","")),s=null==(t=this._videoDom)?void 0:t.videoWidth,n=null==(i=this._videoDom)?void 0:i.videoHeight;if(r&&o&&n&&s){let e,t;if(this.renderMode===VideoRenderMode.RENDER_MODE_FILL)e=o,t=r;else{const i=this.renderMode===VideoRenderMode.RENDER_MODE_HIDDEN?Math.max(r/n,o/s):Math.min(r/n,o/s);e=s*i,t=n*i}this._rotateDom.style.width=`${e}px`,this._rotateDom.style.height=`${t}px`,this._rotateDom.style.left=(r-e)/2+"px",this._rotateDom.style.top=(o-t)/2+"px"}}}_initListeners(){this._videoDom&&MEDIA_EVENTS.forEach((e=>{var t;null==(t=this._videoDom)||t.addEventListener(e,this.emitVideoEvent)}))}_removeListeners(){this._videoDom&&MEDIA_EVENTS.forEach((e=>{var t;null==(t=this._videoDom)||t.removeEventListener(e,this.emitVideoEvent)}))}setRenderMode(e){this.renderMode=e,this._videoDom&&(this._videoDom.style.objectFit=this._getObjectFitFromRenderMode(e)),this._alphaRenderer&&this._alphaRenderer.setObjectFit(this._getObjectFitFromRenderMode(e))}async playVideo(e){var t;let i=this._videoDom;if(this.logger.info("playVideo",`play video track: ${this.userId}`),i&&i.srcObject instanceof MediaStream&&i.srcObject.getTrackById(null==(t=e.preprocessingTrack)?void 0:t.id)){try{reportRtcInvokeStatus(this.engineId,"playVideo","play video repeatedly",0,this.userId)}catch(e){}return}i||(this._initVideo(),i=this._videoDom),this.logger.info("playVideo",`play video by dom: ${null==i?void 0:i.id}`);const r=new MediaStream;r.addTrack(e.preprocessingTrack),i.srcObject=r,i&&!this._containerDom.contains(this._videoContainer)&&this._containerDom.appendChild(this._videoContainer),i&&!this._videoContainer.contains(i)&&this._videoContainer.appendChild(i),setTimeout((()=>this._internalPlay())),this.isAlpha&&this._alphaRenderer&&i&&this._alphaRenderer.startRender(i),Config2.VIDEO_STALL&&this.emit(PlayerStallEvent.START_STALL_OBSERVE),this.played=!0,this.hasStartPlaying=!1}updateSrcObject(e){const t=e.preprocessingTrack;if(!t||!this._videoDom)return;const i=new MediaStream;i.addTrack(t),this._videoDom.srcObject=i}removeTrack(){var e;const t=null==(e=this._videoDom)?void 0:e.srcObject;if(t){const e=t.getVideoTracks();(null==e?void 0:e.length)&&e.forEach((e=>{t.removeTrack(e)}))}}manuallyPlay(){if(this.logger.info("Invoke VideoPlayer.manuallyPlay",this.userId,this.isScreen),this._emitPlayFailed=!1,this._hasManuallyPaused=!1,!this._videoDom)throw new SDKError(ErrorCode.INVALID_PARAMS,"Player not found");return 0!==this._videoDom.readyState||isWeChat?this._videoDom.play():Promise.resolve()}manuallyPause(){if(this.logger.print("Invoke VideoPlayer.manuallyPause",this.userId,this.isScreen),this.played){if(this._hasManuallyPaused=!0,!this._videoDom)throw new SDKError(ErrorCode.INVALID_PARAMS,"Player not found");return this._videoDom.pause()}}mirror(e){this.logger.info("mirror",`${this.userId} set mirror: ${e}`),this.mirrorType=e?MirrorType.MIRROR_TYPE_RENDER:MirrorType.MIRROR_TYPE_NONE,this._videoDom&&(this._videoDom.style.transform=e?"rotateY(180deg)":"",this._alphaRenderer&&this._alphaRenderer.setMirror(e))}stop(e=!1){var t,i,r;const{_containerDom:o}=this;this.logger.info("stop",`stop video track: ${this.userId} ${this.playerId.toString()}`),this._alphaRenderer&&this._alphaRenderer.stopRender(),this._videoDom&&(e||(this._videoDom.srcObject=null),(null==o?void 0:o.contains(this._videoContainer))&&o.removeChild(this._videoContainer),null==(t=this._videoContainer)||t.childNodes.forEach((e=>{e!==this._videoDom&&e!==this._rotateDom&&e!==this._canvasDom||this._videoContainer.removeChild(e)})),(null==(i=this._rotateDom)?void 0:i.contains(this._videoDom))&&this._rotateDom.removeChild(this._videoDom),this._canvasDom&&(null==(r=this._rotateDom)?void 0:r.contains(this._canvasDom))&&this._rotateDom.removeChild(this._canvasDom)),this._hasManuallyPaused=!1,this.played=!1,this.hasStartPlaying=!1,Config2.VIDEO_STALL&&this.emit(PlayerStallEvent.STOP_STALL_OBSERVE),this._closeIntersectionObserver()}destroy(e=!1){var t;this.logger.info("destroy",`video player: ${this.userId}`),this.stop(e),this._alphaRenderer&&(this._alphaRenderer.destroy(),this._alphaRenderer=void 0,this._canvasDom=void 0),null==(t=this._resizeObserver)||t.disconnect(),super.removeAllListeners(),this._removeListeners(),internalEventBus.off(InternalEvent.ON_IOS_LOCAL_TRACK_MUTE,this._onLocalTrackMute),internalEventBus.off(InternalEvent.ON_IOS_LOCAL_TRACK_UNMUTE,this._onInterruptionEnd),internalEventBus.off(InternalEvent.ON_IOS_INTERRUPTION_END,this._onInterruptionEnd),this._videoDom&&delete this._videoDom,this._safari15VideoTimer&&(window.clearInterval(this._safari15VideoTimer),this._safari15VideoTimer=void 0)}get domElement(){return this._videoDom}get videoWidth(){var e;return this._videoDom?this.isAlpha&&(null==(e=this.alphaInfo)?void 0:e.alphaWidth)?this.alphaInfo.alphaWidth:this._videoDom.videoWidth:0}get videoHeight(){var e;return this._videoDom?this.isAlpha?(null==(e=this.alphaInfo)?void 0:e.alphaHeight)?this.alphaInfo.alphaHeight:this._videoDom.videoHeight/2:this._videoDom.videoHeight:0}setAlphaInfo(e){var t;this.logger.info("setAlphaInfo",`set alpha info for user: ${this.userId}`,e),this.isAlpha=!!e.enableAlpha,this.alphaInfo=e,this.isAlpha?(this._alphaRenderer||this._initAlphaRenderer(),this._canvasDom&&this._alphaRenderer?(this._videoDom&&(this._videoDom.style.display="none"),this._rotateDom?this._rotateDom.contains(this._canvasDom)||this._rotateDom.appendChild(this._canvasDom):this._videoContainer.contains(this._canvasDom)||this._videoContainer.appendChild(this._canvasDom),(null==(t=this._videoDom)?void 0:t.srcObject)&&this._alphaRenderer.startRender(this._videoDom)):this.logger.info("setAlphaInfo","alpha renderer already exists or canvas not created")):this.logger.warn("setAlphaInfo","alphaInfo.enableAlpha is false, skip alpha renderer creation")}}class AudioPlayer extends eventemitter3Exports.EventEmitter{constructor(e,t,{divId:i,muted:r,isScreen:o}={divId:void 0,muted:!1,isScreen:!1}){if(super(),__publicField(this,"_containerDom"),__publicField(this,"_audioDom"),__publicField(this,"_fakeAudioDom"),__publicField(this,"userId"),__publicField(this,"muted",!1),__publicField(this,"_emitPlayFailed",!1),__publicField(this,"played",!1),__publicField(this,"isScreen"),__publicField(this,"_wechatTimer"),__publicField(this,"_edgeTimer"),__publicField(this,"_monitor"),__publicField(this,"logger"),__publicField(this,"_pasued",!0),__publicField(this,"hasStartPlaying",!1),__publicField(this,"emitAudioEvent",(e=>{var t,i,r,o;const s={type:"audio",rawEvent:e,readyState:(null==(t=this._audioDom)?void 0:t.readyState)||0,userId:this.userId,eventName:e.type,currentTime:(null==(i=this._audioDom)?void 0:i.currentTime)||0};"playing"===e.type&&this.logger.info("AudioPlayerPlaying",`[userId-${this.userId}] audio element playing`),"pause"===e.type&&(this.logger.info("AudioPlayerPause",`[userId-${this.userId}] audio element pause`),!this._pasued&&(null==(o=null==(r=this._audioDom)?void 0:r.srcObject)?void 0:o.active)&&(getParameter("AUTOPLAY_THROTTLE")?this._throttledInternalPlay():this._internalPlay())),isAndroid&&isWeChat&&("canplay"===e.type?(clearTimeout(this._wechatTimer),this._wechatTimer=setTimeout((()=>{this._autoPlayError("wechat")}),500)):"playing"===e.type&&clearTimeout(this._wechatTimer)),isMobile&&isEdge&&"error"===e.type&&(clearTimeout(this._edgeTimer),this._edgeTimer=setTimeout((()=>{var e;0===(null==(e=this._audioDom)?void 0:e.currentTime)&&this._autoPlayError("edge")}),500)),this.emit("playback_event",s)})),__publicField(this,"_internalPlay",(()=>{var e,t,i;if(reportRtcInvokeStatus(this.engineId,"audio _internalPlay",{paused:null==(e=this._audioDom)?void 0:e.paused,userId:this.userId,screen:this.isScreen}),null==(t=this._audioDom)?void 0:t.paused)try{let e=this._audioDom.play();const t=audioContextManager.getAudioContextInstance();if("suspended"===t.state){const e=t.resume(),i=setTimeout((()=>{var e;"suspended"===t.state&&(this._autoPlayError("AudioContext cannot resume"),null==(e=this._monitor)||e.report("rtc_error",{message:`audio autoplay failed, userId: ${this.userId}: Cannot resume the AudioContext - timeout`,error_code:RtcErrorCode.AUTOPLAY_FAILED})),clearTimeout(i)}));e.catch((e=>{var t;this._autoPlayError("AudioContext cannot resume"),null==(t=this._monitor)||t.report("rtc_error",{message:`audio autoplay failed, userId: ${this.userId}: Cannot resume the AudioContext - rejected by: [${null==e?void 0:e.name}]${null==e?void 0:e.message}`,error_code:RtcErrorCode.AUTOPLAY_FAILED})})).finally((()=>{clearTimeout(i)}))}(null==e?void 0:e.then)&&(isAndroid&&isMobile&&(e=e.then((()=>new Promise((e=>{setTimeout((async()=>{var t;null==(t=this._audioDom)||t.pause(),this._audioDom.volume=1,await this._audioDom.play(),e()}),500)}))))),e.then((()=>{reportRtcInvokeStatus(this.engineId,"_internalPlay successfully",{userId:this.userId,screen:this.isScreen}),this._pasued=!1})).catch((e=>{var t;this._autoPlayError(e),null==(t=this._monitor)||t.report("rtc_error",{message:`audio autoplay failed, userId: ${this.userId}: ${e.message} ${e.name}`,error_code:RtcErrorCode.AUTOPLAY_FAILED})})))}catch(e){this._autoPlayError(e),null==(i=this._monitor)||i.report("rtc_error",{message:`audio autoplay failed, userId: ${this.userId}: ${e.message} ${e.name}`,error_code:RtcErrorCode.AUTOPLAY_FAILED})}})),__publicField(this,"_throttledInternalPlay",throttle(this._internalPlay,getParameter("AUTOPLAY_THROTTLE"))),this.engineId=e,i){const e=document.getElementById(i);if(!e)throw new SDKError(ErrorCode.CANT_FIND_DOM,"can't find dom");this._containerDom=e}else this._containerDom=document.body;this.userId=t,this.muted=r,this.isScreen=o,this._monitor=getMonitor(e),this.logger=new Logger$1("Player",0,e),this._initAudio()}_initAudio(){this._audioDom||(this._audioDom=createElement("audio",{style:{display:"none"},attributes:AUDIO_ATTRIBUTES}),this._audioDom.volume=this.muted?0:1,this._audioDom.muted=this.muted,this._audioDom.id=`${this.userId}_${genUuid()}`,this._containerDom.appendChild(this._audioDom)),this._initListeners()}_initListeners(){this._audioDom&&MEDIA_EVENTS.forEach((e=>{var t;null==(t=this._audioDom)||t.addEventListener(e,this.emitAudioEvent)}))}_removeListeners(){this._audioDom&&(MEDIA_EVENTS.forEach((e=>{var t;null==(t=this._audioDom)||t.removeEventListener(e,this.emitAudioEvent)})),this._audioDom.removeEventListener("canplay",this._internalPlay),this._audioDom.removeEventListener("loadeddata",this._internalPlay))}async playAudio(e){var t;this.logger.info("playAudio",`play audio track: ${this.userId}`);let i=this._audioDom;if(i&&i.srcObject instanceof MediaStream&&i.srcObject.getTrackById(null==(t=e.preprocessingTrack)?void 0:t.id))return;i||(this._initAudio(),i=this._audioDom);const r=new MediaStream;e instanceof RemoteAudioTrack?(this._fakeAudioDom=new Audio,this._fakeAudioDom.muted=!0,this._fakeAudioDom.srcObject=new MediaStream([e.originTrack]),r.addTrack(e.preprocessingTrack)):r.addTrack(e.preprocessingTrack),isAndroid&&isMobile&&(this._audioDom.volume=0),i.srcObject=r,null==i||i.addEventListener("canplay",this._internalPlay),null==i||i.addEventListener("loadeddata",this._internalPlay),setTimeout((()=>this._internalPlay())),this.played=!0,this.hasStartPlaying=!1}_autoPlayError(e){var t,i;this._emitPlayFailed||(this._emitPlayFailed=!0,this.emit("playback_event",{type:"audio",rawEvent:e,readyState:(null==(t=this._audioDom)?void 0:t.readyState)||0,userId:this.userId,eventName:"autoplay-error",currentTime:(null==(i=this._audioDom)?void 0:i.currentTime)||0}))}pause(){if(!this._audioDom)throw new SDKError(ErrorCode.INVALID_PARAMS,"Player not found");this._pasued=!0,this._audioDom.pause(),this.hasStartPlaying=!1}manuallyPause(){return this.pause()}manuallyPlay(){var e;if(this.logger.info("Invoke AudioPlayer.manuallyPlay"),this._emitPlayFailed=!1,!this._audioDom)throw new SDKError(ErrorCode.INVALID_PARAMS,"Player not found");if(!this.played)return Promise.resolve();this._audioDom.volume=1,this._audioDom.muted=!1,null==(e=this._fakeAudioDom)||e.play();const t=[],i=this._audioDom.play();(null==i?void 0:i.then)&&t.push(i);const r=audioContextManager.getAudioContextInstance();if("suspended"===r.state){const e=r.resume();(null==e?void 0:e.then)&&t.push(e)}const o=t.length>0?Promise.all(t):Promise.resolve(i);return o.then((()=>{this._pasued=!1})),o}async setPlaybackDevice(e){this.logger.info("setPlaybackDevice",`setPlaybackDevice: ${e}`);(await dd.enumerateAudioPlaybackDevices()).map((e=>e.deviceId)).includes(e)&&this._audioDom&&this._audioDom.setSinkId&&await this._audioDom.setSinkId(e)}stop(){const{_containerDom:e}=this;this.logger.info("stopAudio",`stop audio track: ${this.userId}`),this._audioDom&&(this._audioDom.srcObject=null,(null==e?void 0:e.contains(this._audioDom))&&e.removeChild(this._audioDom)),this._fakeAudioDom&&(this._fakeAudioDom.srcObject=null,this._fakeAudioDom=void 0),this.played=!1,this.hasStartPlaying=!1}get domElement(){return this._audioDom}destroy(){this.logger.info("destroy",`audio player: ${this.userId}`),this.stop(),super.removeAllListeners(),this._removeListeners(),this._audioDom&&(this._audioDom.srcObject=null,delete this._audioDom),this._edgeTimer&&clearTimeout(this._edgeTimer)}}class AudioProcessor{constructor(){__publicField(this,"_ac"),__publicField(this,"_sourceNode"),__publicField(this,"_gainNode"),__publicField(this,"_destNode"),this._ac=audioContextManager.getAudioContextInstance(),this._gainNode=this._ac.createGain(),this._destNode=this._ac.createMediaStreamDestination(),this._gainNode.connect(this._destNode)}setVolume(e){this._gainNode.gain.value=e/100}getVolume(){return Math.round(100*this._gainNode.gain.value)}updateInputTrack(e){this._sourceNode&&(this._sourceNode.mediaStream.getTracks().forEach((e=>{e.stop()})),delete this._sourceNode);const t=new MediaStream;t.addTrack(e),this._sourceNode=this._ac.createMediaStreamSource(t),this._sourceNode.connect(this._gainNode)}getOutputTrack(){return this._destNode.stream.getTracks()[0]}destroy(){var e,t;null==(e=this._sourceNode)||e.mediaStream.getTracks().forEach((e=>{e.stop()})),13!==safariVersion&&this._destNode.stream.getTracks().forEach((e=>{e.stop()})),null==(t=this._sourceNode)||t.disconnect(),this._gainNode.disconnect(),delete this._sourceNode}}class LocalAudioTrack extends LocalTrack{constructor(e,t,i){super(e,t,{...i,mediaType:MediaType.AUDIO}),__publicField(this,"audioCaptureConfig"),__publicField(this,"_ap"),__publicField(this,"mixedAudioTrack"),__publicField(this,"mixType",AudioMixingType.PLAYOUT_AND_PUBLISH),__publicField(this,"_audioFetchMap",new Map),__publicField(this,"_audioDataFetcher"),__publicField(this,"_localPlaybackTrack"),__publicField(this,"notSupportedWebAudio",!1)}get withWebAudio(){return!!this._ap}getAudioLevel(e=AudioReportMode.MICROPHONE){const t=e===AudioReportMode.AUDIOMIXING&&this.mixType!==AudioMixingType.PLAYOUT?this.mixedAudioTrack??this.preprocessingTrack:this.preprocessingTrack;let i=this._audioFetchMap.get(e);return i&&i.currentTrackId===t.id||(null==i||i.destroy(),i=new AudioLevelFetcher(t),this._audioFetchMap.set(e,i)),i.getAudioLevel()}async updateAudioCaptureConfig(){this.audioCaptureConfig&&(this.logger.print("updateAudioCaptureConfig","update localAudioTrack: ",this.audioCaptureConfig),await this.originTrack.applyConstraints(this.audioCaptureConfig))}setVolume(e){var t;const i=!getParameter("SKIP_WEB_AUDIO_IN_TRACK")&&(isWebAudioSupported()||getParameter("ENFORCE_WEB_AUDIO_SUPPORTED"));i||(this.notSupportedWebAudio=!0);const r=!this.withWebAudio&&100!==e;try{i&&r&&(this.logger.print("Create AudioProcess"),this._ap=new AudioProcessor,this._ap.updateInputTrack(this.originTrack),this.mediaTrack=this._ap.getOutputTrack())}catch(e){this.logger.warn("WebAudio may not supported, quired return"),this.notSupportedWebAudio=!0}this.notSupportedWebAudio||null==(t=this._ap)||t.setVolume(e),i&&r&&this.emit("needReplaceTrack",this)}getVolume(){return this._ap?this._ap.getVolume():100}setUserId(e){this.trackInfo.streamUserId=e}setDataFetcher(e,t){this.logger.info("setDataFetcher","frameSize %s",e),null!==audioContextManager.isWorkletReady?this._audioDataFetcher?this._audioDataFetcher.setFrameSize(e):(this._audioDataFetcher=new AudioDataFetcher(this.preprocessingTrack,e),this._audioDataFetcher.on("data",t)):this.logger.info("setDataFetcher","audioContextManager.isWorkletReady is null")}stopDataFetcher(){var e,t;null==(e=this._audioDataFetcher)||e.removeAllListeners("data"),null==(t=this._audioDataFetcher)||t.destroy(),this._audioDataFetcher=void 0}play(e){this._localPlaybackTrack&&this.stop();const t=e===EarMonitorPosition.AFTER_CAPTURE?this.originTrack:e===EarMonitorPosition.AFTER_PROCESS?this.preprocessingTrack:void 0;if(!t)return void this.logger.error("play()","no target track for %s",e);this._localPlaybackTrack=new RemoteAudioTrack(this._ctx,t.clone(),{...this.trackInfo});const i=this._ctx.earMonitorSettings[this.streamIndex??StreamIndex$1.STREAM_INDEX_MAIN].volume;this.setPlaybackVolume(i);const r=new AudioPlayer(this._ctx.id,this.trackInfo.streamUserId??"",{isScreen:this.streamIndex===StreamIndex$1.STREAM_INDEX_SCREEN,muted:!1});return r.on("playback_event",(e=>{"autoplay-error"===e.eventName&&this.emit("autoplay-error",{kind:"audio",streamIndex:this.streamIndex??StreamIndex$1.STREAM_INDEX_MAIN,mediaType:MediaType.AUDIO})})),this._localPlaybackTrack.setPlayer(r),this._localPlaybackTrack.play()}stop(){var e;null==(e=this._localPlaybackTrack)||e.destroy(),this._localPlaybackTrack=void 0}setPlaybackVolume(e){var t;return null==(t=this._localPlaybackTrack)?void 0:t.setVolume(e)}destroy(){var e,t;this._audioFetchMap.forEach((e=>e.destroy())),this._audioFetchMap.clear(),null==(e=this._ap)||e.destroy(),null==(t=this._audioDataFetcher)||t.destroy(),this._audioDataFetcher=void 0,this.stop(),super.destroy()}}class RemoteAudioTrack extends RemoteTrack{constructor(e,t,i){super(e,t,{...i,mediaType:MediaType.AUDIO}),__publicField(this,"_ap"),__publicField(this,"_audioPlayer"),__publicField(this,"_audioLevelFetcher"),__publicField(this,"_audioDataFetcher"),__publicField(this,"notSupportedWebAudio",!1),__publicField(this,"_sourceNode")}get withWebAudio(){return!!this._ap}getAudioLevel(){return this._audioLevelFetcher||(this._audioLevelFetcher=new AudioLevelFetcher(this.originTrack)),this._audioLevelFetcher.getAudioLevel()}setVolume(e){var t,i,r;const o=!getParameter("SKIP_WEB_AUDIO_IN_TRACK")&&(isWebAudioSupported()||getParameter("ENFORCE_WEB_AUDIO_SUPPORTED"));o||(this.notSupportedWebAudio=!0);const s=!this.withWebAudio&&100!==e;try{o&&s&&(this.logger.print("Create AudioProcess"),this._ap=new AudioProcessor,this._ap.updateInputTrack(this.originTrack),this.mediaTrack=this._ap.getOutputTrack())}catch(e){this.logger.warn("WebAudio may not supported, quite return"),this.notSupportedWebAudio=!0}if(this.notSupportedWebAudio){const i=null==(t=this._audioPlayer)?void 0:t.domElement;i&&(i.volume=Math.min(e/100,1))}else null==(i=this._ap)||i.setVolume(e);o&&s&&(this.emit("needReplaceTrack",this),null==(r=this._audioPlayer)||r.playAudio(this))}getVolume(){var e,t;return this.notSupportedWebAudio?100*((null==(t=null==(e=this._audioPlayer)?void 0:e.domElement)?void 0:t.volume)??1):this._ap?this._ap.getVolume():100}setPlaybackDevice(e){var t;return null==(t=this._audioPlayer)?void 0:t.setPlaybackDevice(e)}setPlayer(e){this._audioPlayer=e,this._wechatAutoplayWorkaround(e)}havePlayer(){return!!this._audioPlayer}bindPlayerEvent(e){this._audioPlayer&&e(this._audioPlayer,this.isPublic,this.streamIndex??StreamIndex$1.STREAM_INDEX_MAIN)}pause(){var e;return null==(e=this._audioPlayer)?void 0:e.pause()}play(){var e;return null==(e=this._audioPlayer)?void 0:e.playAudio(this)}manuallyPlay(){var e,t,i;return(null==(e=this._audioPlayer)?void 0:e.played)?null==(t=this._audioPlayer)?void 0:t.manuallyPlay():null==(i=this._audioPlayer)?void 0:i.playAudio(this)}manuallyPause(){var e;return null==(e=this._audioPlayer)?void 0:e.manuallyPause()}stop(){var e;return null==(e=this._audioPlayer)?void 0:e.stop()}setDataFetcher(e,t){this.logger.info("setDataFetcher","frameSize %s",e),null!==audioContextManager.isWorkletReady?this._audioDataFetcher?this._audioDataFetcher.setFrameSize(e):(this._audioDataFetcher=new AudioDataFetcher(this.originTrack,e),this._audioDataFetcher.on("data",t)):this.logger.warn("setDataFetcher","audioContextManager.isWorkletReady is null")}stopDataFetcher(){var e;this.logger.info("stopDataFetcher"),null==(e=this._audioDataFetcher)||e.destroy(),this._audioDataFetcher=void 0}destroy(){var e,t,i;null==(e=this._audioLevelFetcher)||e.destroy(),null==(t=this._audioDataFetcher)||t.destroy(),this._audioDataFetcher=void 0,this._ap&&this._ap.destroy(),null==(i=this._audioPlayer)||i.destroy(),this._audioPlayer=void 0,super.destroy()}_wechatAutoplayWorkaround(e){isWeChat&&e.on("playback_event",(e=>{const t=audioContextManager.getAudioContextInstance();"autoplay-error"===e.eventName?t&&"running"===t.state&&(this._sourceNode||(this._sourceNode=t.createMediaStreamSource(new MediaStream([this.originTrack]))),this._sourceNode.connect(t.destination),reportRtcInvokeStatus(this._ctx.id,"wechatAutoplayWorkaround.connect",{userId:this.trackInfo.streamUserId,streamIndex:this.streamIndex,contextState:t.state,trackInfo:this.trackInfo})):"playing"===e.eventName&&this._sourceNode&&(this._sourceNode.disconnect(),this._sourceNode=void 0,reportRtcInvokeStatus(this._ctx.id,"wechatAutoplayWorkaround.disconnect",{userId:this.trackInfo.streamUserId,streamIndex:this.streamIndex,contextState:t.state,trackInfo:this.trackInfo}))}))}}const logger$6=new Logger$1("VERTC",0);let desktopCapturer,electron=null;const inElectron=()=>!!fetchElectronInstance();function fetchElectronInstance(){if(electron)return electron;try{electron=window.require("electron");const{ipcRenderer:e}=electron;return desktopCapturer={getSources:t=>e.invoke("DESKTOP_CAPTURER_GET_SOURCES",t)},electron}catch(e){return null}}async function getElectronScreenStream(e,t,i){let r;return t||(t={width:1920,height:1080,frameRate:15}),r=i?{audio:{mandatory:{chromeMediaSource:"desktop"}},video:{mandatory:{chromeMediaSource:"desktop",maxHeight:t.height,maxWidth:t.width,maxFrameRate:t.frameRate}}}:{audio:!1,video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:e,maxHeight:t.height,maxWidth:t.width,maxFrameRate:t.frameRate}}},logger$6.info("getUserMediaConfig",JSON.stringify(r)),await navigator.mediaDevices.getUserMedia(r)}async function getElectronScreenSources(e){let t=["window","screen"];"window"===e&&(t=["window"]),"screen"===e&&(t=["screen"]);if(!fetchElectronInstance())throw new SDKError(ErrorCode.ERR_ELECTRON_IS_NULL,"Unable to get Electron object");let i=null;try{i=desktopCapturer.getSources({types:t})}catch(e){i=null}i&&i.then||(i=new Promise(((e,i)=>{desktopCapturer.getSources({types:t},((t,r)=>{t?i(t):e(r)}))})));try{return await i}catch(e){throw new SDKError(ErrorCode.ERR_ELECTRON_IS_NULL,e.toString())}}function showElectronSelectSourceWindow(e){return new Promise(((t,i)=>{const r=document.createElement("div");r.innerText="share screen",r.setAttribute("style","text-align: center; height: 25px; line-height: 25px; border-radius: 4px 4px 0 0; background: #D4D2D4; border-bottom: solid 1px #B9B8B9;");const o=document.createElement("div");o.setAttribute("style","width: 100%; height: 500px; padding: 15px 25px ; box-sizing: border-box;");const s=document.createElement("div");s.innerText="Web Screensharing wants to share the contents of your screen. Choose what you'd like to share.",s.setAttribute("style","height: 12%;");const n=document.createElement("div");n.setAttribute("style","width: 100%; height: 80%; background: #FFF; border: solid 1px #CBCBCB; display: flex; flex-wrap: wrap; justify-content: space-around; overflow-y: scroll; padding: 0 15px; box-sizing: border-box;");const a=document.createElement("div");a.setAttribute("style","text-align: right; padding: 16px 0;");const d=document.createElement("button");d.innerHTML="cancel",d.setAttribute("style","width: 85px;"),d.onclick=()=>{document.body.removeChild(c);const e=new Error("NotAllowedError");e.name="NotAllowedError",i(e)},a.appendChild(d),o.appendChild(s),o.appendChild(n),o.appendChild(a);const c=document.createElement("div");c.setAttribute("style","position: fixed; z-index: 99999999; top: 50%; left: 50%; width: 620px; height: 525px; background: #ECECEC; border-radius: 4px; -webkit-transform: translate(-50%,-50%); transform: translate(-50%,-50%);"),c.appendChild(r),c.appendChild(o),document.body.appendChild(c),e.map((e=>{if(e.id){const i=document.createElement("div");i.setAttribute("style","width: 30%; height: 160px; padding: 20px 0; text-align: center;box-sizing: content-box;"),i.innerHTML=`<div style='height: 120px; display: table-cell; vertical-align: middle;'> \n <img style='width: 100%; background: #333333; box-shadow: 1px 1px 1px 1px rgba(0, 0, 0, 0.2);' src=\n ${e.thumbnail.toDataURL()}\n />\n </div>\n <span style='\theight: 40px; line-height: 40px; display: inline-block; width: 70%; word-break: keep-all; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;'>\n ${e.name}\n </span>`,i.onclick=()=>{document.body.removeChild(c),t(e.id)},n.appendChild(i)}}))}))}async function getElectronScreenStreamByUserSelect(e,t){const i=await getElectronScreenSources(),r=await showElectronSelectSourceWindow(i);return await getElectronScreenStream(r,e,t)}async function createDummyVideoLocalTrack(e,t){const i=new LocalVideoTrack(e,t,{streamIndex:ExtendStreamIndex.MAIN,sourceType:SourceType.INTERNAL,isDummy:!0});return await i.isTrackReady,i}async function createDummyScreenVideoLocalTrack(e,t){const i=new LocalVideoTrack(e,t,{isDummy:!0,streamIndex:ExtendStreamIndex.SCREEN,sourceType:SourceType.INTERNAL});return await i.isTrackReady,i}async function createCameraVideoTrack(e,t){var i,r,o,s,n;let a;const d=(null==(i=(t=t||e.videoProfile.getCaptureConfig()).deviceId)?void 0:i.exact)||"default",c=genUuid$1(),l=new Logger$1("TrackFactory",0,e.id);try{l.info("createCameraVideoTrack","constraints:",t),null==(r=e.monitor)||r.report("rtc_video_capture_event",{event_type:"start",media_device_id:d,capture_session_id:c});const i=getServerNow();isFirefox&&(t.frameRate={ideal:30,max:30}),a=await dd.getUserMedia({video:t}),null==(s=e.monitor)||s.report("rtc_video_capture_event",{event_type:"start_capture_result",media_device_id:d,media_device_name:(null==(o=a.getVideoTracks()[0])?void 0:o.label)||"",reason:"success",elapse:getServerNow()-i,capture_session_id:c})}catch(t){throw null==(n=e.monitor)||n.report("rtc_video_capture_event",{event_type:"running_failed",media_device_id:d,error_code:t.code,reason:t.name+t.message,capture_session_id:c}),new SDKError(ErrorCode.GET_VIDEO_TRACK_FAILED,`throw error from getUserMedia. [${t.name||"unknown name"}]: ${t.message||"unknown message"}.`,t)}const u=a.getVideoTracks()[0],_=new LocalVideoTrack(e,u,{streamIndex:ExtendStreamIndex.MAIN,sourceType:SourceType.INTERNAL,captureSessionId:c});return await _.isTrackReady,_}async function createMicrophoneAudioTrack(e,t){var i,r,o,s,n;let a;new Logger$1("TrackFactory",0,e.id).info("createMicrophoneAudioTrack","constraints:",t);const d=(null==(i=t.deviceId)?void 0:i.exact)||"default",c=genUuid$1();try{null==(r=e.monitor)||r.report("rtc_audio_device_event",{device_type:"audio_record",event_type:"start_begin",media_device_id:d,event_session_id:c});const i=getServerNow();e.extensionManager.getPluginByName(RTCExtensionType.PRE_PROCESSING,"RTCAIAnsExtension")&&(t.autoGainControl=!0,t.noiseSuppression=!1),a=await dd.getUserMedia({audio:t}),null==(s=e.monitor)||s.report("rtc_audio_device_event",{device_type:"audio_record",event_type:"start_result",media_device_id:d,media_device_name:(null==(o=a.getAudioTracks()[0])?void 0:o.label)||"",reason:"success",elapse:getServerNow()-i,event_session_id:c})}catch(t){throw null==(n=e.monitor)||n.report("rtc_audio_device_event",{device_type:"audio_record",event_type:"start_end",media_device_id:d,error_code:t.code,reason:t.name+t.message,event_session_id:c}),new SDKError(ErrorCode.GET_AUDIO_TRACK_FAILED,`throw error from getUserMedia. [${t.name||"unknown name"}]: ${t.message||"unknown message"}.`,t)}const l=a.getAudioTracks()[0],u=new LocalAudioTrack(e,l,{streamIndex:ExtendStreamIndex.MAIN,sourceType:SourceType.INTERNAL,captureSessionId:c});return await u.isTrackReady,u}async function createMicrophoneAndCameraTrack(e,t,i){var r,o,s,n,a,d,c,l,u,_;let h;new Logger$1("TrackFactory",0,e.id).print("createCameraAndMicrophoneTrack","audioConstraints:",t,"videoConstraints:",i);const p=(null==(r=t.deviceId)?void 0:r.exact)||"default",m=(null==(o=i.deviceId)?void 0:o.exact)||"default",S=genUuid$1(),g=genUuid$1();try{null==(s=e.monitor)||s.report("rtc_video_capture_event",{event_type:"start",media_device_id:m,capture_session_id:S}),null==(n=e.monitor)||n.report("rtc_audio_device_event",{device_type:"audio_record",event_type:"start_begin",media_device_id:p,event_session_id:g});const r=getServerNow();isFirefox&&(i.frameRate={ideal:30,max:30});e.extensionManager.getPluginByName(RTCExtensionType.PRE_PROCESSING,"RTCAIAnsExtension")&&(t.autoGainControl=!0,t.noiseSuppression=!1),h=await dd.getUserMedia({audio:t,video:i}),null==(d=e.monitor)||d.report("rtc_video_capture_event",{event_type:"start_capture_result",media_device_id:m,media_device_name:(null==(a=h.getVideoTracks()[0])?void 0:a.label)||"",reason:"success",elapse:getServerNow()-r,capture_session_id:S}),null==(l=e.monitor)||l.report("rtc_audio_device_event",{device_type:"audio_record",event_type:"start_result",media_device_id:p,media_device_name:(null==(c=h.getAudioTracks()[0])?void 0:c.label)||"",reason:"success",elapse:getServerNow()-r,event_session_id:g})}catch(t){throw null==(u=e.monitor)||u.report("rtc_video_capture_event",{event_type:"running_failed",media_device_id:m,error_code:t.code,reason:t.name+t.message,capture_session_id:S}),null==(_=e.monitor)||_.report("rtc_audio_device_event",{device_type:"audio_record",event_type:"start_end",media_device_id:p,error_code:t.code,reason:t.name+t.message,event_session_id:g}),new SDKError(ErrorCode.GET_VIDEO_TRACK_FAILED,`throw error from getUserMedia. [${t.name||"unknown name"}]: ${t.message||"unknown message"}.`,t)}const v=h.getVideoTracks()[0],f=new LocalVideoTrack(e,v,{streamIndex:ExtendStreamIndex.MAIN,sourceType:SourceType.INTERNAL,captureSessionId:S}),E=h.getAudioTracks()[0],T=new LocalAudioTrack(e,E,{streamIndex:ExtendStreamIndex.MAIN,sourceType:SourceType.INTERNAL,captureSessionId:g});return await Promise.all([f.isTrackReady,T.isTrackReady]),{videoTrack:f,audioTrack:T}}async function createScreenTracks(e,t){var i,r,o,s,n;const a=new Logger$1("TrackFactory",0,e.id);let d,c=e.videoProfile.getScreenEncodeConfig();a.info("createScreenTracks","screenConfig: %o, constraints: %o",t,c);const l=genUuid$1(),{enableAudio:u=!1,displaySurface:_,systemAudio:h,surfaceSwitching:p,selfBrowserSurface:m,sourceId:S}=t,g={};_&&["monitor","browser","window"].includes(_)&&(c?c.displaySurface=_:c={displaySurface:_}),h&&["include","exclude"].includes(h)&&(g.systemAudio=h),p&&["include","exclude"].includes(p)&&(g.surfaceSwitching=p),m&&["include","exclude"].includes(m)&&(g.selfBrowserSurface=m);try{null==(i=e.monitor)||i.report("rtc_video_capture_event",{event_type:"start",media_device_id:"screen",capture_session_id:l});const t=getServerNow();d=inElectron()?S?await getElectronScreenStream(S,c,u):await getElectronScreenStreamByUserSelect(c,u):await navigator.mediaDevices.getDisplayMedia({video:!(!c||isConstraintInGetDisplayMediaSupported)||c,audio:!!u&&{channelCount:2,noiseSuppression:!1,echoCancellation:!0,autoGainControl:!1},...g}),null==(s=e.monitor)||s.report("rtc_video_capture_event",{event_type:"start_capture_result",media_device_id:"screen",media_device_name:`${(null==(r=d.getVideoTracks()[0])?void 0:r.label)||""}, ${(null==(o=d.getAudioTracks()[0])?void 0:o.label)||""}`,reason:"success",elapse:getServerNow()-t,capture_session_id:l})}catch(t){throw null==(n=e.monitor)||n.report("rtc_video_capture_event",{event_type:"running_failed",media_device_id:"screen",error_code:t.code,reason:t.name+t.message,capture_session_id:l}),new SDKError(ErrorCode.GET_SCREEN_TRACK_FAILED,"throw error from getDisplayMedia",t)}const v=d.getVideoTracks()[0],f=new LocalVideoTrack(e,v,{streamIndex:ExtendStreamIndex.SCREEN,sourceType:SourceType.INTERNAL,captureSessionId:l}),E=d.getAudioTracks()[0];if(d.getAudioTracks().length){const t=new LocalAudioTrack(e,E,{streamIndex:ExtendStreamIndex.SCREEN,sourceType:SourceType.INTERNAL,captureSessionId:l});return await Promise.all([f.isTrackReady,t.isTrackReady]),[f,t]}return await f.isTrackReady,[f,void 0]}function createRemoteVideoTrack(e,t,i,r){return new RemoteVideoTrack(e,t,i,{...r})}function createRemoteAudioTrack(e,t,i){return new RemoteAudioTrack(e,t,{...i})}async function createCustomVideoLocalTrack(e,t){const i=new LocalVideoTrack(e,t,{streamIndex:ExtendStreamIndex.MAIN,sourceType:SourceType.EXTERNAL});return await i.isTrackReady,i}async function createCustomAudioLocalTrack(e,t){const i=new LocalAudioTrack(e,t,{streamIndex:ExtendStreamIndex.MAIN,sourceType:SourceType.EXTERNAL});return await i.isTrackReady,i}async function createCustomScreenVideoLocalTrack(e,t){const i=new LocalVideoTrack(e,t,{sourceType:SourceType.EXTERNAL,streamIndex:ExtendStreamIndex.SCREEN});return await i.isTrackReady,i}async function createCustomScreenAudioLocalTrack(e,t){const i=new LocalAudioTrack(e,t,{sourceType:SourceType.EXTERNAL,streamIndex:ExtendStreamIndex.SCREEN});return await i.isTrackReady,i}const encodedJs$1="dmFyIF9fZGVmUHJvcD1PYmplY3QuZGVmaW5lUHJvcGVydHksX19kZWZOb3JtYWxQcm9wPShlLHQsbik9PnQgaW4gZT9fX2RlZlByb3AoZSx0LHtlbnVtZXJhYmxlOiEwLGNvbmZpZ3VyYWJsZTohMCx3cml0YWJsZTohMCx2YWx1ZTpufSk6ZVt0XT1uLF9fcHVibGljRmllbGQ9KGUsdCxuKT0+KF9fZGVmTm9ybWFsUHJvcChlLCJzeW1ib2wiIT10eXBlb2YgdD90KyIiOnQsbiksbik7IWZ1bmN0aW9uKCl7InVzZSBzdHJpY3QiO2NvbnN0IGU9e2dldE5BTFVuaXRzKHQsbj0hMSl7aWYodC5sZW5ndGgtdC5wb3NpdGlvbjw0KXJldHVybltdO2NvbnN0e3Bvc2l0aW9uOnN9PXQ7cmV0dXJuIDE9PT10LmdldEludDMyKHMpfHwwPT09dC5nZXRJbnQxNihzKSYmMT09PXQuZ2V0SW50OChzKzIpP2UuZ2V0QW5uZXhiTmFscyh0LG4pOmUuZ2V0QXZjY05hbHModCxuKX0sZ2V0QW5uZXhiTmFscyh0LG4pe2NvbnN0IHM9W107bGV0IHI9ZS5nZXRIZWFkZXJQb3NpdGlvbkFubmV4Qih0KSxvPXIucG9zLGk9bztmb3IoO288dC5sZW5ndGgtNDspe2NvbnN0IGE9bmV3IFVpbnQ4QXJyYXkodC5idWZmZXIuc2xpY2UobyxvK3IuaGVhZGVyTGVuZ3RoKSk7ci5wb3M9PT10LnBvc2l0aW9uJiZ0LnNraXAoci5oZWFkZXJMZW5ndGgpLHI9ZS5nZXRIZWFkZXJQb3NpdGlvbkFubmV4Qih0KSxpPXIucG9zO2NvbnN0IGM9e2hlYWRlcjphLGJvZHk6bmV3IFVpbnQ4QXJyYXkodC5idWZmZXIuc2xpY2UobythLmJ5dGVMZW5ndGgsaSkpLHR5cGU6LTF9O24/ZS5hbmFseXNlSDI2NU5hbChjKTplLmFuYWx5c2VOYWwoYyksKGMudHlwZTw9OXx8biYmYy50eXBlPD00MCkmJjAhPT1jLnR5cGUmJnMucHVzaChjKSx0LnNraXAoaS10LnBvc2l0aW9uKSxvPWl9cmV0dXJuIHN9LGdldEF2Y2NOYWxzKHQsbil7Y29uc3Qgcz1bXTtmb3IoO3QucG9zaXRpb248dC5sZW5ndGgtNDspe2NvbnN0IHI9dC5nZXRJbnQzMih0LnBvc2l0aW9uKTtpZighKHQubGVuZ3RoLXQucG9zaXRpb24+PXIpKWJyZWFrO3tjb25zdCBvPW5ldyBVaW50OEFycmF5KHQuYnVmZmVyLnNsaWNlKHQucG9zaXRpb24sdC5wb3NpdGlvbis0KSk7dC5za2lwKDQpO2NvbnN0IGk9bmV3IFVpbnQ4QXJyYXkodC5idWZmZXIuc2xpY2UodC5wb3NpdGlvbix0LnBvc2l0aW9uK3IpKTt0LnNraXAocik7Y29uc3QgYT17aGVhZGVyOm8sYm9keTppLHR5cGU6LTF9O24/ZS5hbmFseXNlSDI2NU5hbChhKTplLmFuYWx5c2VOYWwoYSksYS50eXBlPD05JiYwIT09YS50eXBlJiZzLnB1c2goYSl9fXJldHVybiBzfSxhbmFseXNlTmFsKGUpe2NvbnN0IHQ9MzEmZS5ib2R5WzBdO3N3aXRjaChlLnR5cGU9dCx0KXtjYXNlIDE6ZS5uZHI9ITA7YnJlYWs7Y2FzZSA1OmUuaWRyPSEwO2JyZWFrO2Nhc2UgNjplLnNlaT0hMDticmVhaztjYXNlIDc6ZS5zcHM9ITA7YnJlYWs7Y2FzZSA4OmUucHBzPSEwfX0sYW5hbHlzZUgyNjVOYWwoZSl7Y29uc3QgdD0oMTI2JmUuYm9keVswXSk+PjE7c3dpdGNoKGUudHlwZT10LHQpe2Nhc2UgMzk6Y2FzZSA0MDplLnNlaT0hMH19LGdldEhlYWRlclBvc2l0aW9uQW5uZXhCKGUpe2xldCB0PWUucG9zaXRpb24sbj0wO2NvbnN0IHM9ZS5sZW5ndGg7Zm9yKDszIT09biYmNCE9PW4mJnQ8cy00OykwPT09ZS5nZXRJbnQxNih0KT8xPT09ZS5nZXRJbnQxNih0KzIpP249NDoxPT09ZS5nZXRJbnQ4KHQrMik/bj0zOnQrKzp0Kys7cmV0dXJuIHQ9PT1zLTQmJigwPT09ZS5nZXRJbnQxNih0KT8xPT09ZS5nZXRJbnQxNih0KzIpP249NDp0PXM6KHQrKywwPT09ZS5nZXRJbnQxNih0KSYmMT09PWUuZ2V0SW50OCh0KT9uPTM6dD1zKSkse3Bvczp0LGhlYWRlckxlbmd0aDpufX0saXNIMjY1VmlkZW9GcmFtZShlKXt2YXIgdCxuO3JldHVybigobnVsbD09KG49bnVsbD09KHQ9ZS5nZXRNZXRhZGF0YSk/dm9pZCAwOnQuY2FsbChlKSk/dm9pZCAwOm4ubWltZVR5cGUpfHwiIikudG9Mb3dlckNhc2UoKS5pbmNsdWRlcygiaDI2NSIpfX0sdD1uZXcgVWludDhBcnJheShbMTA5LDE2Nyw1MywxOTAsMTAzLDkwLDcyLDEsMTcwLDg5LDYzLDE2NCwxOTQsMTk5LDE5LDg1XSksbj1uZXcgVWludDhBcnJheShbMTA5LDE2Nyw1MywxOTAsMTAzLDkwLDcyLDEsMTcwLDg5LDYzLDE2NCwxOTQsMTk5LDE5LDg0XSkscz1uZXcgVWludDhBcnJheShbMzEsMjM5LDMsNTAsMjQyLDEyMCw3Niw4NSwxNjksNDIsMTYxLDkxLDc1LDE4NiwyMl0pO2Z1bmN0aW9uIHIoZSl7Y29uc3QgdD1bXTtmb3IoO2U+PTI1NTspZS09MjU1LHQucHVzaCgyNTUpO3JldHVybiB0LnB1c2goZSksbmV3IFVpbnQ4QXJyYXkodCl9ZnVuY3Rpb24gbyhlLHQ9MCl7bGV0IG49MDtmb3IoOzI1NT09PWVbdF0mJnQ8ZS5ieXRlTGVuZ3RoOyl0Kyssbis9MjU1O3JldHVybiB0PGUuYnl0ZUxlbmd0aCYmKG4rPWVbdCsrXSksW24sdF19Y29uc3QgaT1uZXcgVWludDhBcnJheShbODAsMV0pLGE9Y2xhc3N7c3RhdGljIGdlbmVyYXRlU0VJKGUscyxvPSExKXtjb25zdCBjPW5ldyBVaW50OEFycmF5KFswLDAsMCwxXSksbD1zP2k6bmV3IFVpbnQ4QXJyYXkoWzZdKSxwPW5ldyBVaW50OEFycmF5KFs1XSkseT1hLl9fdXVpZHx8KG8/dDpuKSx1PXIoZS5ieXRlTGVuZ3RoK3kuYnl0ZUxlbmd0aCksZz0oZT0+e2NvbnN0IHQ9W107bGV0IG49MDtmb3IoY29uc3QgcyBvZiBlKW4+PTImJnM8PTMmJih0LnB1c2goMyksbj0wKSwwPT09cz9uKys6bj0wLHQucHVzaChzKTtyZXR1cm4gbmV3IFVpbnQ4QXJyYXkodCl9KShlKTtyZXR1cm4gbmV3IFVpbnQ4QXJyYXkoWy4uLmMsLi4ubCwuLi5wLC4uLnUsLi4ueSwuLi5nLDEyOF0pfXN0YXRpYyBkZWNvZGVTRUlCb2R5KGUscil7Y29uc3QgaT0oZT0+e2NvbnN0IHQ9W107Zm9yKGxldCBuPTA7bjxlLmxlbmd0aDtuKyspZVtuXTw9MyYmMD09PWVbbi0xXSYmMD09PWVbbi0yXXx8dC5wdXNoKGVbbl0pO3JldHVybiBuZXcgVWludDhBcnJheSh0KX0pKGU9ZS5zbGljZSgwLGUubGVuZ3RoLTEpKTtpZihpLmJ5dGVMZW5ndGg8MilyZXR1cm47bGV0IGE9MDtjb25zdCBjPXI/MjoxO2lmKDUhPT1pW2NdJiYxMDAhPT1pW2NdKXJldHVybjthKz0xK2M7Y29uc3RbbCxwXT1vKGksYSk7YT1wO2xldCB5PTI7Y29uc3QgdT1hK2w7aS5ieXRlTGVuZ3RoPj1uLmJ5dGVMZW5ndGgmJmw+PW4uYnl0ZUxlbmd0aCYmKGkuc2xpY2UoYSxhK24uYnl0ZUxlbmd0aCkudG9TdHJpbmcoKT09PW4udG9TdHJpbmcoKXx8aS5zbGljZShhLGErcy5ieXRlTGVuZ3RoKS50b1N0cmluZygpPT09cy50b1N0cmluZygpKT8oYSs9bi5ieXRlTGVuZ3RoLHk9MSk6aS5ieXRlTGVuZ3RoPj1uLmJ5dGVMZW5ndGgmJmw+PW4uYnl0ZUxlbmd0aCYmaS5zbGljZShhLGErdC5ieXRlTGVuZ3RoKS50b1N0cmluZygpPT09dC50b1N0cmluZygpJiYoYSs9dC5ieXRlTGVuZ3RoLHk9MCk7cmV0dXJue3R5cGU6eSxwYXlsb2FkOmkuc2xpY2UoYSx1KX19c3RhdGljIHBhcnNlSW50ZXJuYWxTRUkoZSl7Y29uc3QgdD1uZXcgTWFwO2xldCBuPTA7aWYoMD09PWUudHlwZSl7Zm9yKDtlLnBheWxvYWQuYnl0ZUxlbmd0aC1uPj0yOyl7Y29uc3RbcyxyXT1vKGUucGF5bG9hZCxuKTtuPXI7Y29uc3RbaSxhXT1vKGUucGF5bG9hZCxuKTtpZihuPWEsdC5nZXQocyl8fCEoaTw9ZS5wYXlsb2FkLmJ5dGVMZW5ndGgtbikpYnJlYWs7dC5zZXQocyxlLnBheWxvYWQuc2xpY2UobixuK2kpKSxuKz1pfXJldHVybiB0fX1zdGF0aWMgbWFrZUludGVybmFsU2VpKGUpe2NvbnN0IHQ9W107Zm9yKGNvbnN0W28saV1vZiBlKXtjb25zdCBlPXIobyksbj1yKGkuYnl0ZUxlbmd0aCk7dC5wdXNoKGUsbixpKX1jb25zdCBuPXQucmVkdWNlKCgoZSx0KT0+ZSt0LmJ5dGVMZW5ndGgpLDApLHM9bmV3IFVpbnQ4QXJyYXkobik7cmV0dXJuIHQucmVkdWNlKCgoZSx0KT0+KHMuc2V0KHQsZSksZSt0LmJ5dGVMZW5ndGgpKSwwKSxzfX07bGV0IGM9YTtfX3B1YmxpY0ZpZWxkKGMsIl9fdXVpZCIpO2NsYXNzIGx7Y29uc3RydWN0b3IoZSl7X19wdWJsaWNGaWVsZCh0aGlzLCJzZWlMaXN0IixbXSksX19wdWJsaWNGaWVsZCh0aGlzLCJtYXhTRUlDb3VudCIsMSksdGhpcy5tYXhTRUlDb3VudD1lLm1heFNFSUNvdW50fXNlbmRTRUlUcmFuc2Zvcm0odCxuKXtjb25zdHttYXhTRUlDb3VudDpzLHNlaUxpc3Q6cn09dGhpcztpZighdGhpcy5zZWlMaXN0Lmxlbmd0aClyZXR1cm4gdm9pZCBuLmVucXVldWUodCk7Y29uc3Qgbz1bXTtsZXQgaT0wO2Zvcihjb25zdCBwIG9mIHIpe2lmKG8ubGVuZ3RoPj1zKWJyZWFrO2NvbnN0IG49Yy5nZW5lcmF0ZVNFSShwLmNvbnRlbnQsZS5pc0gyNjVWaWRlb0ZyYW1lKHQpKTtpKz1uLmJ5dGVMZW5ndGgscC5yZXBlYXRDb3VudC0tLG8ucHVzaChuKX10aGlzLnNlaUxpc3Q9ci5maWx0ZXIoKGU9PmUucmVwZWF0Q291bnQ+MCkpO2NvbnN0IGE9bmV3IFVpbnQ4QXJyYXkoaSt0LmRhdGEuYnl0ZUxlbmd0aCk7YS5zZXQobmV3IFVpbnQ4QXJyYXkodC5kYXRhKSk7bGV0IGw9dC5kYXRhLmJ5dGVMZW5ndGg7by5mb3JFYWNoKChlPT57YS5zZXQoZSxsKSxsKz1lLmJ5dGVMZW5ndGh9KSksdC5kYXRhPWEuYnVmZmVyLG4uZW5xdWV1ZSh0KX1wdXNoU0VJKGUpe3RoaXMuc2VpTGlzdC5wdXNoKGUpfXJldm9rZVNFSShlKXtjb25zdCB0PXRoaXMuc2VpTGlzdC5maW5kSW5kZXgoKHQ9PnQudXVpZD09PWUpKTtyZXR1cm4tMSE9PXQmJih0aGlzLnNlaUxpc3Quc3BsaWNlKHQsMSksITApfX0idW5kZWZpbmVkIiE9dHlwZW9mIHNlbGYmJiJEZWRpY2F0ZWRXb3JrZXJHbG9iYWxTY29wZSI9PT1zZWxmLmNvbnN0cnVjdG9yLm5hbWUmJnNlbGYuYWRkRXZlbnRMaXN0ZW5lcigicnRjdHJhbnNmb3JtIiwoZT0+e2NvbnN0e3RyYW5zZm9ybWVyOnR9PWUse21heFNFSUNvdW50Om59PXQub3B0aW9ucyxzPW5ldyBsKHttYXhTRUlDb3VudDpufSkscj1uZXcgVHJhbnNmb3JtU3RyZWFtKHt0cmFuc2Zvcm06cy5zZW5kU0VJVHJhbnNmb3JtLmJpbmQocyl9KTtzZWxmLmFkZEV2ZW50TGlzdGVuZXIoIm1lc3NhZ2UiLCgoe2RhdGE6ZX0pPT57Y29uc3R7dHlwZTp0LGNvbnRlbnQ6bn09ZTtpZigicHVzaCI9PT10KXMucHVzaFNFSShuKTtlbHNlIGlmKCJyZXZva2UiPT09dCl7Y29uc3QgZT1zLnJldm9rZVNFSShuKTtyZXR1cm4gc2VsZi5wb3N0TWVzc2FnZSh7dHlwZToicmV2b2tlLWFjayIsY29udGVudDp7dXVpZDpuLGlzTm90U2VuZDplfX0pfX0pKSx0LnJlYWRhYmxlLnBpcGVUaHJvdWdoKHIpLnBpcGVUbyh0LndyaXRhYmxlKX0pKX0oKTsK",blob$1="undefined"!=typeof window&&window.Blob&&new Blob([atob(encodedJs$1)],{type:"text/javascript;charset=utf-8"});function WorkerWrapper$1(){let e;try{if(e=blob$1&&(window.URL||window.webkitURL).createObjectURL(blob$1),!e)throw"";return new Worker(e)}catch(e){return new Worker("data:application/javascript;base64,"+encodedJs$1)}finally{!("undefined"!=typeof window&&navigator.userAgent.indexOf("Trident/")>0)&&e&&(window.URL||window.webkitlRL).revokeObjectURL(e)}}const Nalunit={getNALUnits(e,t=!1){if(e.length-e.position<4)return[];const{position:i}=e;return 1===e.getInt32(i)||0===e.getInt16(i)&&1===e.getInt8(i+2)?Nalunit.getAnnexbNals(e,t):Nalunit.getAvccNals(e,t)},getAnnexbNals(e,t){const i=[];let r=Nalunit.getHeaderPositionAnnexB(e),o=r.pos,s=o;for(;o<e.length-4;){const n=new Uint8Array(e.buffer.slice(o,o+r.headerLength));r.pos===e.position&&e.skip(r.headerLength),r=Nalunit.getHeaderPositionAnnexB(e),s=r.pos;const a={header:n,body:new Uint8Array(e.buffer.slice(o+n.byteLength,s)),type:-1};t?Nalunit.analyseH265Nal(a):Nalunit.analyseNal(a),(a.type<=9||t&&a.type<=40)&&0!==a.type&&i.push(a),e.skip(s-e.position),o=s}return i},getAvccNals(e,t){const i=[];for(;e.position<e.length-4;){const r=e.getInt32(e.position);if(!(e.length-e.position>=r))break;{const o=new Uint8Array(e.buffer.slice(e.position,e.position+4));e.skip(4);const s=new Uint8Array(e.buffer.slice(e.position,e.position+r));e.skip(r);const n={header:o,body:s,type:-1};t?Nalunit.analyseH265Nal(n):Nalunit.analyseNal(n),n.type<=9&&0!==n.type&&i.push(n)}}return i},analyseNal(e){const t=31&e.body[0];switch(e.type=t,t){case 1:e.ndr=!0;break;case 5:e.idr=!0;break;case 6:e.sei=!0;break;case 7:e.sps=!0;break;case 8:e.pps=!0}},analyseH265Nal(e){const t=(126&e.body[0])>>1;switch(e.type=t,t){case 39:case 40:e.sei=!0}},getHeaderPositionAnnexB(e){let t=e.position,i=0;const r=e.length;for(;3!==i&&4!==i&&t<r-4;)0===e.getInt16(t)?1===e.getInt16(t+2)?i=4:1===e.getInt8(t+2)?i=3:t++:t++;return t===r-4&&(0===e.getInt16(t)?1===e.getInt16(t+2)?i=4:t=r:(t++,0===e.getInt16(t)&&1===e.getInt8(t)?i=3:t=r)),{pos:t,headerLength:i}},isH265VideoFrame(e){var t,i;return((null==(i=null==(t=e.getMetadata)?void 0:t.call(e))?void 0:i.mimeType)||"").toLowerCase().includes("h265")}};class RTCDataView{constructor(e){__publicField(this,"_position",0),__publicField(this,"_dataview"),this._dataview=new DataView(e)}get length(){return this.buffer.byteLength}get buffer(){return this._dataview.buffer}set position(e){this._position=e}get position(){return this._position}back(e){this.position-=e}getUint8(e){return this._dataview.getUint8(e)}getInt8(e){return this._dataview.getInt8(e)}getInt16(e){return this._dataview.getInt16(e)}getUint16(e){return this._dataview.getUint16(e)}getUint32(e){return this._dataview.getUint32(e)}getInt32(e){return this._dataview.getInt32(e)}skip(e){const t=Math.floor(e/4),i=e%4;for(let e=0;e<t;e++)RTCDataView.readByte(this,4);i>0&&RTCDataView.readByte(this,i)}static readByte(e,t,i){let r;switch(t){case 1:r=i?e.getInt8(e.position):e.getUint8(e.position);break;case 2:r=i?e.getInt16(e.position):e.getUint16(e.position);break;case 3:if(i)throw new Error("not supported for readByte 3");r=e.getUint8(e.position)<<16,r|=e.getUint8(e.position+1)<<8,r|=e.getUint8(e.position+2);break;case 4:r=i?e.getInt32(e.position):e.getUint32(e.position);break;case 8:if(i)throw new Error("not supported for readBody 8");r=e.getUint32(e.position)<<32,r|=e.getUint32(e.position+4);break;default:r=""}return e.position+=t,r}readUint8(){return RTCDataView.readByte(this,1)}readUint16(){return RTCDataView.readByte(this,2)}readUint24(){return RTCDataView.readByte(this,3)}readUint32(){return RTCDataView.readByte(this,4)}readUint64(){return RTCDataView.readByte(this,8)}readInt8(){return RTCDataView.readByte(this,1,!0)}readInt16(){return RTCDataView.readByte(this,2,!0)}readInt32(){return RTCDataView.readByte(this,4,!0)}writeUint32(e){return new Uint8Array([e>>>24&255,e>>>16&255,e>>>8&255,255&e])}}function receiveSEITransform({postMessage:e,skipFilter:t}){return new TransformStream({transform(i,r){const o=Nalunit.isH265VideoFrame(i);Nalunit.getNALUnits(new RTCDataView(i.data),o).forEach((i=>{if(i.sei){const r=SEIHelper.decodeSEIBody(i.body,o);r&&(t||r.type===RTC_SEI_TYPE.external)&&e(r)}})),r.enqueue(i)}})}"undefined"!=typeof self&&"DedicatedWorkerGlobalScope"===self.constructor.name&&self.addEventListener("rtctransform",(e=>{const{transformer:t}=e,{streamId:i,skipFilter:r}=t.options,o=receiveSEITransform({postMessage:e=>{self.postMessage({streamId:i,msg:e},[e.payload.buffer])},skipFilter:r});t.readable.pipeThrough(o).pipeTo(e.transformer.writable)}));class EncodedTransformer{constructor(e){__publicField(this,"seiList",[]),__publicField(this,"maxSEICount",1),this.maxSEICount=e.maxSEICount}sendSEITransform(e,t){const{maxSEICount:i,seiList:r}=this;if(!this.seiList.length)return void t.enqueue(e);const o=[];let s=0;for(const t of r){if(o.length>=i)break;const r=SEIHelper.generateSEI(t.content,Nalunit.isH265VideoFrame(e));s+=r.byteLength,t.repeatCount--,o.push(r)}this.seiList=r.filter((e=>e.repeatCount>0));const n=new Uint8Array(s+e.data.byteLength);n.set(new Uint8Array(e.data));let a=e.data.byteLength;o.forEach((e=>{n.set(e,a),a+=e.byteLength})),e.data=n.buffer,t.enqueue(e)}pushSEI(e){this.seiList.push(e)}revokeSEI(e){const t=this.seiList.findIndex((t=>t.uuid===e));return-1!==t&&(this.seiList.splice(t,1),!0)}}"undefined"!=typeof self&&"DedicatedWorkerGlobalScope"===self.constructor.name&&self.addEventListener("rtctransform",(e=>{const{transformer:t}=e,{maxSEICount:i}=t.options,r=new EncodedTransformer({maxSEICount:i}),o=new TransformStream({transform:r.sendSEITransform.bind(r)});self.addEventListener("message",(({data:e})=>{const{type:t,content:i}=e;if("push"===t)r.pushSEI(i);else if("revoke"===t){const e=r.revokeSEI(i);return self.postMessage({type:"revoke-ack",content:{uuid:i,isNotSend:e}})}})),t.readable.pipeThrough(o).pipeTo(t.writable)}));class StreamBase extends EnhancedEventEmitter{constructor(e){super(),__publicField(this,"uuid",genUuid$1()),__publicField(this,"isScreen",!1),__publicField(this,"audioMid"),__publicField(this,"videoMid"),__publicField(this,"audioMLine"),__publicField(this,"videoMLine"),__publicField(this,"videoTransceiver"),__publicField(this,"audioTransceiver"),__publicField(this,"vendorHandler"),__publicField(this,"vendorCode",0),__publicField(this,"engineId"),__publicField(this,"logger"),__publicField(this,"__seiHelper",SEIHelper),__publicField(this,"logName","StreamBase"),__publicField(this,"isPublicStream",!1),this._ctx=e,this.engineId=e.id,this.logger=new Logger$1(this.constructor.name,2,e.id)}stopReport(e){this.statsReport.stopReport(e)}destroy(){var e,t;delete this.audioMid,delete this.videoMid,this.statsReport.destroy(),null==(e=this.observer)||e.reset(),delete this.videoTransceiver,delete this.audioTransceiver,null==(t=this.vendorHandler)||t.destroy(),this.vendorCode=0,delete this.vendorHandler}}var StreamState=(e=>(e[e.INIT=0]="INIT",e[e.SUB_ING=1]="SUB_ING",e[e.SUB_ED=2]="SUB_ED",e))(StreamState||{});class LocalStream extends StreamBase{constructor(e,t=StreamIndex.STREAM_INDEX_MAIN){super(e),__publicField(this,"id"),__publicField(this,"stream"),__publicField(this,"streamId"),__publicField(this,"videoTrack"),__publicField(this,"audioTrack"),__publicField(this,"subVideoDescriptions",[]),__publicField(this,"observer"),__publicField(this,"statsReport"),__publicField(this,"pubAudio",!1),__publicField(this,"pubVideo",!1),__publicField(this,"blackFrameRenderInterval"),__publicField(this,"blackFrameLifetimeInterval"),__publicField(this,"pubAttributes"),__publicField(this,"pcSessionId"),__publicField(this,"maxSeiCount",1),__publicField(this,"preReports",{audio:{},video:{}}),__publicField(this,"remoteSdp"),__publicField(this,"currentVideoCodec"),__publicField(this,"_changeCodecs",[]),__publicField(this,"_videoCaps",[]),__publicField(this,"_sendSEIHandler"),__publicField(this,"_trackMatchingTimer"),__publicField(this,"logName","LocalStream"),this.stream=new MediaStream,this.id=genUuid$1(),this.pubAttributes={localaudio:!1,localvideo:!1,videostream:!1,audiostream:!1,extvideo:!1,extaudio:!1,videoDescriptions:[],videoType:VideoType.NORMAL},this.isScreen=t===StreamIndex.STREAM_INDEX_SCREEN,this.statsReport=new LocalStatsReport(e,this);const i=getParameter("SEI_COUNT_FPS");"number"==typeof i&&i<=10&&(this.maxSeiCount=i),this._trackMatchingTimer=setInterval(this._checkTrackMatching.bind(this),5e3)}get enableSimulcast(){return!this.isScreen&&this._ctx.videoProfile.getSimulcastMode()}get videoEncodeConfig(){return this.isScreen?[this._ctx.videoProfile.getScreenEncodeConfig()]:this._ctx.videoProfile.getVideoEncodeConfig()}get audioHasCapture(){return this.pubAttributes.localaudio}get audioHasPublish(){return this.pubAttributes.audiostream}get videoHasCapture(){return this.pubAttributes.localvideo}get videoHasPublish(){return this.pubAttributes.videostream}get isEmptyStream(){return!this.audioTrack&&!this.videoTrack}get initStreamId(){return this.stream.id}async getSelectedCodec(){var e;const t=this._changeCodecs.length>0?this._changeCodecs:this._videoCaps.length>0?this._videoCaps:await internalGetSupportedCodecs(),i=this._ctx.videoProfile.getPreferCodec(this.isScreen),r=this.isScreen?this._ctx.targetScreenCodec:this._ctx.targetCodec;if(i&&i!==VideoCodecType.AUTO){if(i===VideoCodecType.H264&&t.includes(VideoCodecName.H264))return VideoCodecName.H264;if(i===VideoCodecType.VP8&&t.includes(VideoCodecName.VP8))return VideoCodecName.VP8;if(i===VideoCodecType.ByteVC1&&t.includes(VideoCodecName.ByteVC1))return VideoCodecName.ByteVC1}if((null==(e=this._ctx.serverConfig)?void 0:e.videoCodec)&&t.includes(this._ctx.serverConfig.videoCodec))return this._ctx.serverConfig.videoCodec;if(i===VideoCodecType.AUTO&&t.length>0)return t[0];if(r&&t.includes(r))return r;if(t.includes(VideoCodecName.H264))return VideoCodecName.H264;if(t.includes(VideoCodecName.VP8))return VideoCodecName.VP8;throw new Error("no available codec")}startReport(e,t){this.statsReport.setLocalStreamStatsEvtInterval(e,t)}getLocalStreamStats(){return this.statsReport.getLocalStats()}initVideoEncodedTransform(){if(getParameter("DISABLE_ENCODED_TRANSFORM"))return void this.logger.warn("initVideoEncodedTransform","DISABLE_ENCODED_TRANSFORM");if(!this.videoTransceiver||!this.videoTransceiver.sender)return void this.logger.warn("initVideoEncodedTransform","no sender found when trying to bind encodedTransform");const{sender:e}=this.videoTransceiver;if(this._ctx.pcKillSwitch.ctor_encodedinsetablestream_add&&isLegacyEncodedTransformSupported()){const{readable:t,writable:i}=e.createEncodedStreams();if(window.__createDecodeError__)t.pipeThrough(new TransformStream({transform:(e,t)=>{const i=e.data,r=new DataView(i,16);r.setInt16(4,10),r.setInt16(11,20),t.enqueue(e)}})).pipeTo(i);else{const e=new EncodedTransformer({maxSEICount:this.maxSeiCount}),r=new TransformStream({transform:e.sendSEITransform.bind(e)});t.pipeThrough(r).pipeTo(i),this._sendSEIHandler=e}}else if(isEncodedTransformSupported()){const e=new WorkerWrapper$1;this.videoTransceiver.sender.transform=new RTCRtpScriptTransform(e,{maxSEICount:this.maxSeiCount}),this._sendSEIHandler={pushSEI:t=>{e.postMessage({type:"push",content:t},[t.content.buffer])},revokeSEI:async t=>(e.postMessage({type:"revoke",content:t}),new Promise((i=>{e.addEventListener("message",(({data:e})=>{const{type:r,content:o}=e,{uuid:s,isNotSend:n}=o;"revoke-ack"===r&&s===t&&i(n)}))})))}}}initAudioEncodedTransform(){if(getParameter("DISABLE_ENCODED_TRANSFORM"))return void this.logger.warn("initAudioEncodedTransform","DISABLE_ENCODED_TRANSFORM");if(!this.audioTransceiver||!this.audioTransceiver.sender)return void this.logger.warn("initAudioEncodedTransform","no sender found when trying to bind encodedTransform");if(!this._ctx.pcKillSwitch.ctor_encodedinsetablestream_add)return void this.logger.warn("initAudioEncodedTransform","legacy EncodedTransform is not supported");if(!isLegacyEncodedTransformSupported())return void this.logger.warn("initAudioEncodedTransform","legacy EncodedTransform is not supported");const{sender:e}=this.audioTransceiver,{readable:t,writable:i}=e.createEncodedStreams();t.pipeThrough(new TransformStream({transform:(e,t)=>{t.enqueue(e)}})).pipeTo(i)}clean(){reportRtcInvokeStatus(this.engineId,"localstream_clean",`${(new Error).stack}`,0,this.streamId||""),super.destroy(),this.subVideoDescriptions=[],clearTimeout(this.blackFrameLifetimeInterval),clearInterval(this.blackFrameRenderInterval)}switchTrackEnableState(e,t){let i;"audio"===e?i=this.audioTrack:"video"===e&&(i=this.videoTrack);const r=null==i?void 0:i.mediaTrack;return!(!r||(null==r?void 0:r.enabled)===t)&&(r.enabled=t,!0)}resetStream(){this.stream=new MediaStream}genBlackFrame(){var e,t;this.logger.info("genBlackFrame()");const i=(null==(e=this.videoEncodeConfig[0])?void 0:e.frameRate)?constraints2number(null==(t=this.videoEncodeConfig[0])?void 0:t.frameRate):15,r=Math.ceil(1e3/i),o=document.createElement("canvas"),s=o.getContext("2d");o.width=16,o.height=16;const n=e=>{e.fillRect(0,0,16,16)};s&&(s.fillStyle="#000",n(s),this.blackFrameRenderInterval=window.setInterval((()=>{n(s)}),r),this.refreshBlackFrameLifetime());return o.captureStream(i).getVideoTracks()[0]}stopBlackFrame(){this.logger.info("stopBlackFrame()"),clearTimeout(this.blackFrameLifetimeInterval),clearInterval(this.blackFrameRenderInterval),delete this.blackFrameRenderInterval}refreshBlackFrameLifetime(){this.logger.info("refreshBlackFrameLifetime()"),this.blackFrameRenderInterval&&(clearTimeout(this.blackFrameLifetimeInterval),this.blackFrameLifetimeInterval=setTimeout((()=>{clearInterval(this.blackFrameRenderInterval),delete this.blackFrameRenderInterval,this.emit("black-frame-ended")}),Config2.BLACK_FRAME_LIFETIME))}setChangeCodecs(e){this._changeCodecs=e}setVideoCaps(e){if(!e)return;const t=e.split(",").map((e=>{const t=e.trim().toUpperCase();return{H264:VideoCodecName.H264,VP8:VideoCodecName.VP8,BYTEVC1:VideoCodecName.ByteVC1}[t]||null})).filter((e=>null!==e));this._videoCaps=t}sendSEIMessage(e){var t;this.logger.info("sendSEIMessage"),null==(t=this._sendSEIHandler)||t.pushSEI(e)}async revokeSEIMessage(e){var t;return this.logger.info("revokeSEIMessage"),this._sendSEIHandler?null==(t=this._sendSEIHandler)?void 0:t.revokeSEI(e):(this.logger.warn("revokeSEIMessage","no sei handler found"),!1)}destroy(){clearInterval(this._trackMatchingTimer),super.removeAllListeners(),super.destroy()}_checkTrackMatching(){var e,t,i,r,o,s,n,a;const d=null==(e=this.audioTrack)?void 0:e.preprocessingTrack.id,c=null==(t=this.videoTrack)?void 0:t.preprocessingTrack.id,l=null==(r=null==(i=this.audioTransceiver)?void 0:i.sender.track)?void 0:r.id,u=null==(s=null==(o=this.videoTransceiver)?void 0:o.sender.track)?void 0:s.id;this.pubAudio&&d!==l&&(this.logger.error("_checkTrackMatching",`audio track id: ${d} not matching transceiver track id ${l}, streamId: ${this.streamId}`),null==(n=this._ctx.monitor)||n.report("rtc_error",{message:`audio track id: ${d} not matching transceiver track id ${l}`,error_code:-1,stream_id:this.streamId})),this.pubVideo&&c!==u&&(this.logger.error("_checkTrackMatching",`video track id: ${c} not matching transceiver track id ${u}, streamId: ${this.streamId}`),null==(a=this._ctx.monitor)||a.report("rtc_error",{message:`video track id: ${c} not matching transceiver track id ${u}`,error_code:-1,stream_id:this.streamId}))}}class RemoteStream extends StreamBase{constructor(e,t,i,r,o,s){super(e),__publicField(this,"streamId"),__publicField(this,"userId"),__publicField(this,"isPublic"),__publicField(this,"hasVideo"),__publicField(this,"hasAudio"),__publicField(this,"_attributes"),__publicField(this,"streamState"),__publicField(this,"removeTrack",!1),__publicField(this,"observer"),__publicField(this,"statsReport"),__publicField(this,"subVideo"),__publicField(this,"subAudio"),__publicField(this,"subMediaType"),__publicField(this,"subLayer"),__publicField(this,"_sequenceId"),__publicField(this,"stream"),__publicField(this,"videoTrack"),__publicField(this,"audioTrack"),__publicField(this,"recordedVideoFrames"),__publicField(this,"stillExist"),__publicField(this,"originalMediaType"),__publicField(this,"priority"),__publicField(this,"remoteSessionId",""),__publicField(this,"originalStreamIndex",0),__publicField(this,"virtual"),__publicField(this,"pcSessionId"),__publicField(this,"_virtualOccupy"),__publicField(this,"_videoStallObserver"),__publicField(this,"_audioStallObserver"),__publicField(this,"preReports",{audio:{},video:{}}),__publicField(this,"_installInfo"),__publicField(this,"_seiWorkerHandler"),this.virtual=!1,this._virtualOccupy=!1,this.userId=t,this.isScreen=r,this.isPublic=o,this.streamId=i,this.logName=`RemoteStream-${i}`,this.hasAudio=s.audiostream&&s.localaudio,this.hasVideo=s.videostream&&s.localvideo,this._attributes=s,this.vendorCode=(null==s?void 0:s.vendorCode)||0,this.subVideo=!1,this.subAudio=!1,this._sequenceId=0,this.subMediaType=ExtendMediaType.NONE,this.subLayer={spatialLayer:0,spatialSubLayer:-1},this.streamState=0,this.statsReport=new RemoteStatsReport(e,this),this.enableVendorMode&&(this.pcSessionId=genUuid$1())}get vendor(){return this._attributes.vendorCode}get audioHasCapture(){return this._attributes.localaudio}get audioHasPublish(){return this._attributes.audiostream}get videoHasCapture(){return this._attributes.localvideo}get videoHasPublish(){return this._attributes.videostream}get sequenceId(){return this._sequenceId||-1}set sequenceId(e){"number"==typeof e&&(this._sequenceId=e)}get enableVendorMode(){return"number"==typeof this.attributes.vendorCode&&0!==this.attributes.vendorCode}get hasSubscribed(){return 2===this.streamState}get attributes(){var e;return(null==(e=this._attributes.alphaInfo)?void 0:e.enableAlpha)?{...this._attributes,videoDescriptions:this._attributes.videoDescriptions.map((e=>{var t,i;return{...e,height:(null==(t=this._attributes.alphaInfo)?void 0:t.alphaHeight)??e.height/2,width:(null==(i=this._attributes.alphaInfo)?void 0:i.alphaWidth)??e.width}}))}:this._attributes}set attributes(e){this.hasVideo=e.localvideo&&e.videostream,this.hasAudio=e.localaudio&&e.audiostream,this._attributes=e,this.vendorCode=e.vendorCode||0,e.alphaInfo&&this.videoTrack&&this.videoTrack.setAlphaInfo(e.alphaInfo)}get virtualOccupy(){return this._virtualOccupy}set virtualOccupy(e){var t,i;this._virtualOccupy&&!e?null==(t=this.observer)||t.setPushTrack(!1):!this._virtualOccupy&&e&&(null==(i=this.observer)||i.setPushTrack(!0)),this._virtualOccupy=e}startReport(e,t){this.statsReport.setRemoteStreamStatsEvtInterval(e,t)}getRemoteStreamStats(){return this.statsReport.getRemoteStreamStats()}initVideoEncodedTransform(){var e,t;if(getParameter("DISABLE_ENCODED_TRANSFORM"))this.logger.warn("initVideoEncodedTransform","DISABLE_ENCODED_TRANSFORM");else if(this.videoTransceiver&&this.videoTransceiver.receiver){if(this._ctx.pcKillSwitch.ctor_encodedinsetablestream_add&&isLegacyEncodedTransformSupported()){null==(e=this._ctx.monitor)||e.report("rtc_invoke_status",{sdk_api_name:"initVideoEncodedTransform",message:"using legacy EncodedTransform",error_code:0,stream_id:this.streamId,elapse:0});const{receiver:t}=this.videoTransceiver,{readable:i,writable:r}=t.createEncodedStreams();i.pipeThrough(receiveSEITransform({postMessage:e=>{this.safeEmit("onSEIMessage",e.payload)},skipFilter:!!getParameter("SKIP_SEI_FILTER")})).pipeTo(r)}else if(isEncodedTransformSupported()){null==(t=this._ctx.monitor)||t.report("rtc_invoke_status",{sdk_api_name:"initVideoEncodedTransform",message:"using standard EncodedTransform",error_code:0,stream_id:this.streamId,elapse:0});const e=this._ctx.receiveSEIWorker;this.videoTransceiver.receiver.transform=new RTCRtpScriptTransform(e,{streamId:this.streamId,skipFilter:!!getParameter("SKIP_SEI_FILTER")}),this._seiWorkerHandler=e=>{e.data.streamId===this.streamId&&this.safeEmit("onSEIMessage",e.data.msg.payload)},e.addEventListener("message",this._seiWorkerHandler)}}else this.logger.warn("no receiver found when trying to bind encodedTransform")}initAudioEncodedTransform(){if(getParameter("DISABLE_ENCODED_TRANSFORM"))return void this.logger.warn("initVideoEncodedTransform","DISABLE_ENCODED_TRANSFORM");if(!this.audioTransceiver||!this.audioTransceiver.receiver)return void this.logger.warn("no receiver found when trying to bind encodedTransform");if(!this._ctx.pcKillSwitch.ctor_encodedinsetablestream_add)return void this.logger.warn("legacy EncodedTransform is not supported");if(!isLegacyEncodedTransformSupported())return void this.logger.warn("legacy EncodedTransform is not supported");const{receiver:e}=this.audioTransceiver,{readable:t,writable:i}=e.createEncodedStreams();t.pipeThrough(new TransformStream({transform:(e,t)=>{e.data.byteLength<=1e3?t.enqueue(e):this.logger.print("too large audio frame",e.data.byteLength)}})).pipeTo(i)}ontrack(e){var t,i,r,o;try{reportRtcInvokeStatus(this.engineId,"Stream.ontrack",JSON.stringify({uid:this.userId,streamId:this.streamId,streams:e.streams.reduce(((e,t)=>e+mediaStreamStringify(t)),""),transceiver:mediaTransceiverStringify(e.transceiver),track:mediaTrackStringify(e.track)}),0,this.streamId||"")}catch(e){}if(this.enableVendorMode||(null==(r=null==(i=null==(t=e.streams)?void 0:t[0])?void 0:i.id)?void 0:r.includes(this.streamId))){const{track:t}=e;"video"===(null==t?void 0:t.kind)?this._setVideoTrack(t):"audio"===(null==(o=e.track)?void 0:o.kind)&&this._setAudioTrack(t),this._setStream(e.streams[0])}this.safeEmit("ontrack",e)}startVideoStallObserve(e){this.logger.info("startVideoStallObserve","invoke",e.playerId),this._videoStallObserver||(this._videoStallObserver=new VideoStallObserver(this.isScreen,this.engineId)),this._videoStallObserver.start(e)}stopVideoStallObserve(){var e;this.logger.info("stopVideoStallObserve","invoke"),null==(e=this._videoStallObserver)||e.stop()}updateVideoStallInfo(e,t,i){var r,o;let s;if(i?(s=null==(r=this._videoStallObserver)?void 0:r.getStallInfo({interval:e.stats_interval||0,bitrate:e.bitrate,frameRateDecoded:e.frame_rate_decoded,frameRateReceived:e.frame_rate_received}),this._installInfo=s):s=this._installInfo,s){const r=Math.min(s.report.stallDuration,e.stats_interval||0);if(e.play_time=s.pts,e.stall_count=s.report.stallCount,e.is_screen?e.stuck_length=r:e.stall_duration=r,e.pause_duration=Math.min(r,s.pauseDuration),t.stallCount=s.callback.stallCount,t.stallDuration=s.callback.stallDuration,s.stall100ms){const i=Math.min(s.stall100ms.duration,e.stats_interval||0);e.stall_duration_100ms=i,e.stall_count_100ms=s.stall100ms.count,t.stallDuration100MS=i,t.stallCount100MS=s.stall100ms.count}0===s.report.stallCount&&0===s.report.stallDuration||this.logger.print("video_stall_report",this.userId,null==(o=this.videoTrack)?void 0:o.observingPlayerId,JSON.stringify(s.report),i)}}getVideoRenderInfo(){var e;return(null==(e=this._videoStallObserver)?void 0:e.getRecentRenderInfo4Report())||{}}stopAudioStallObserve(){var e;this.logger.info("stopAudioStallObserve","invoke"),null==(e=this._audioStallObserver)||e.stop()}async updateAudioStallInfo(e,t,i){if(this._audioStallObserver){const i=await this._audioStallObserver.getAudioStallInfo();return e.concealedSamples===e.interval_concealed_samples&&e.totalSamplesReceived===e.interval_samples_received?(e.stall_count=0,e.stall_duration=0,t.stallCount=0,t.stallDuration=0):(e.stall_count=i.report.stall_count,e.stall_duration=i.report.stall_duration,t.stallCount=i.callback.stall_count,t.stallDuration=i.callback.stall_duration),0===i.report.stall_count&&0===i.report.stall_duration||this.logger.print("audio_stall_report",this.userId,JSON.stringify({...i.report,callbackList:i.callback.list})),i.extra}this._audioStallObserver=new AudioStallObserver(this),this._audioStallObserver.start(i.concealedSamples,i.totalSamplesReceived),this.logger.print("startAduioObserver","start")}resetStream(){var e,t;null==(e=this.audioTransceiver)||e.stop(),null==(t=this.videoTransceiver)||t.stop(),this.audioTransceiver=void 0,this.videoTransceiver=void 0}clean(){var e,t;this.logger.info("clean",`exec stream.clean ${this.streamId} ${this.userId}`),reportRtcInvokeStatus(this.engineId,"remotestream_clean",`${(new Error).stack}`,0,this.streamId),super.destroy(),this.subAudio=!1,this.subVideo=!1,this.sequenceId=0,null==(e=this.videoTrack)||e.destroy(),this.videoTrack=void 0,null==(t=this.audioTrack)||t.destroy(),this.audioTrack=void 0,this.stream=void 0,this.recordedVideoFrames=void 0,delete this.priority,this._seiWorkerHandler&&this._ctx.receiveSEIWorker.removeEventListener("message",this._seiWorkerHandler)}destroy(){var e,t;this.clean(),null==(e=this._audioStallObserver)||e.destroy(),delete this._audioStallObserver,null==(t=this._videoStallObserver)||t.destroy(),delete this._videoStallObserver,this.attributes={audiostream:!1,localaudio:!1,localvideo:!1,videostream:!1,extvideo:!1,extaudio:!1,videoDescriptions:[]},super.removeAllListeners()}resetHasSubscribed(){this.streamState=0}_setStream(e){this.stream=e,e.onaddtrack=e=>{"video"===e.track.kind?this._setVideoTrack(e.track):"audio"===e.track.kind&&this._setAudioTrack(e.track)}}_setAudioTrack(e){var t,i,r;if((null==(i=null==(t=this.audioTrack)?void 0:t.preprocessingTrack)?void 0:i.id)!==e.id){this.audioTrack=createRemoteAudioTrack(this._ctx,e,{streamIndex:this.isPublic?ExtendStreamIndex.PUBLIC:this.virtual?ExtendStreamIndex.VIRTUAL:this.isScreen?ExtendStreamIndex.SCREEN:ExtendStreamIndex.MAIN,streamUserId:this.userId});const t=this._ctx._remoteAudioTrackDumpConfig[this.isScreen?StreamIndex.STREAM_INDEX_SCREEN:StreamIndex.STREAM_INDEX_MAIN].get(this.userId);(null==t?void 0:t.callback)&&(null==t?void 0:t.frameSize)&&(null==(r=this.audioTrack)||r.setDataFetcher(t.frameSize,(e=>{var i;this.audioHasCapture&&this.audioHasPublish&&(null==(i=t.callback)||i.call(t,e))}))),this.emit("ontrack",this.audioTrack)}}_setVideoTrack(e){var t,i;(null==(i=null==(t=this.videoTrack)?void 0:t.preprocessingTrack)?void 0:i.id)!==e.id&&(this.videoTrack=createRemoteVideoTrack(this._ctx,e,this,{streamIndex:this.isPublic?ExtendStreamIndex.PUBLIC:this.virtual?ExtendStreamIndex.VIRTUAL:this.isScreen?ExtendStreamIndex.SCREEN:ExtendStreamIndex.MAIN,streamUserId:this.userId}),this.emit("ontrack",this.videoTrack))}}var RoomEvent=(e=>(e.RESUBSCRIBE="resubscribe",e.STREAM_FAILED="stream_failed",e.SUBSCRIBE_PUSH_TRACK="subscribe_push_track",e.REMOVE_PUSH_TRACK="remove_push_track",e.VIDEO_FIRST_FRAME="video_first_frame",e.ON_USER_PUBLISH_STATE_CHANGE="on_user_publish_state_change",e.ON_USER_START_AUDIO_CAPTURE="on_user_start_audio_capture",e.ON_USER_STOP_AUDIO_CAPTURE="on_user_stop_audio_capture",e.ON_USER_START_VIDEO_CAPTURE="on_user_start_video_capture",e.ON_USER_STOP_VIDEO_CAPTURE="on_user_stop_video_capture",e.ON_SEI_MESSAGED_RECEIVED="on_sei_messaged_received",e.ON_PUBLISH_RESULT="on_publish_result",e.ON_SUBSCRIBE_RESULT="ON_SUBSCRIBE_RESULT",e.ON_UPDATE_TOKEN_SUCCESS="on_update_token_success",e.ON_REMOTE_STREAM_STATS="ON_REMOTE_STREAM_STATS",e.ON_LOCAL_STREAM_STATS="ON_LOCAL_STREAM_STATS",e.ON_USER_LEAVE="on_user_leave",e.ON_ROOM_ERROR="on_room_error",e.ON_NETWORK_QUALITY="on_network_quality",e.ON_SIMULCAST_SUBSCRIBE_FALLBACK="on_simulcast_subscribe_fallback",e.ON_REMOTE_VIDEO_SIZE_CHANGED="on_remote_video_size_changed",e.ON_SUBTITLE_STATE_CHANGED="ON_SUBTITLE_STATE_CHANGED",e.ON_SUBTITLE_MESSAGE_RECEIVED="ON_SUBTITLE_MESSAGE_RECEIVED",e.ON_VIDEO_STREAM_BANNED="ON_VIDEO_STREAM_BANNED",e.ON_AUDIO_STREAM_BANNED="ON_AUDIO_STREAM_BANNED",e.ON_FORWARD_STREAM_ERROR="ON_FORWARD_STREAM_ERROR",e.ON_REJOIN_WITH_TCP="ON_REJOIN_WITH_TCP",e.PUB_RETRY="PUB_RETRY",e.SUB_RETRY="SUB_RETRY",e.VIDEO_TYPE_CHANGE="VIDEO_TYPE_CHANGE",e.JOIN_SUCCESS="JOIN_SUCCESS",e.UPDATE_PUBLISH="UPDATE_PUBLISH",e))(RoomEvent||{}),StreamMixingEventType=(e=>(e[e.START=1]="START",e[e.START_SUCCESS=2]="START_SUCCESS",e[e.START_FAILED=3]="START_FAILED",e[e.UPDATE=4]="UPDATE",e[e.UPDATE_SUCCESS=5]="UPDATE_SUCCESS",e[e.UPDATE_FAILED=6]="UPDATE_FAILED",e[e.STOP=7]="STOP",e[e.STOP_SUCCESS=8]="STOP_SUCCESS",e[e.STOP_FAILED=9]="STOP_FAILED",e))(StreamMixingEventType||{}),PubState=(e=>(e[e.PUB=0]="PUB",e[e.UNPUB=1]="UNPUB",e))(PubState||{});const reportFirstFrameRecvError=async(e,t,i,r)=>{var o,s,n,a,d,c,l;try{let u="",_=-1;const h="video"===t?null==(o=null==i?void 0:i.videoTrack)?void 0:o.originTrack:null==(s=null==i?void 0:i.audioTrack)?void 0:s.originTrack,p="video"===t?null==(n=null==i?void 0:i.videoTransceiver)?void 0:n.receiver:null==(a=null==i?void 0:i.audioTransceiver)?void 0:a.receiver;try{const i=await(null==(d=e.peerConnection)?void 0:d.getStatsWithLowFrequency(h,!0,p)),r=(i||[]).find((e=>"inbound-rtp"===e.type)),o=await(null==p?void 0:p.getStats()),s=[];let n;null==o||o.forEach((e=>s.push(e.type))),0===(null==i?void 0:i.length)&&0!==s.length&&(n=await(null==(c=e.peerConnection)?void 0:c.getStatsWithLowFrequency(void 0,void 0,p))),u=JSON.stringify({type:t,reports:i.map((e=>e.type)),reports2:s,pc:(null==(l=e.peerConnection)?void 0:l.getOriginRTCPeerConnection())||null,track:(null==h?void 0:h.id)||null,bytes:null==r?void 0:r.bytesReceived,framesReceived:null==r?void 0:r.framesReceived,packetsReceived:null==r?void 0:r.packetsReceived,allReports:n})}catch(e){_=-999,u=e.mseeage||JSON.stringify(e)}null==r||r.report("rtc_invoke_status",{sdk_api_name:"first_frame_recv_timeout",error_code:_,message:u,stream_id:(null==i?void 0:i.streamId)||"",stream_user_id:null==i?void 0:i.userId,elapse:0})}catch(e){}},reportFirstFrameSendError=async(e,t,i,r)=>{var o,s,n,a,d,c,l;try{let u="",_=-1;const h="video"===t?null==(o=null==i?void 0:i.videoTrack)?void 0:o.preprocessingTrack:null==(s=null==i?void 0:i.audioTrack)?void 0:s.preprocessingTrack,p="video"===t?null==(n=null==i?void 0:i.videoTransceiver)?void 0:n.sender:null==(a=null==i?void 0:i.audioTransceiver)?void 0:a.sender;try{const i=await(null==(d=e.peerConnection)?void 0:d.getStatsWithLowFrequency(h,!0,p)),r=(i||[]).find((e=>"outbound-rtp"===e.type)),o=await(null==p?void 0:p.getStats()),s=[];let n;null==o||o.forEach((e=>s.push(e.type))),0===i.length&&0!==s.length&&(n=await(null==(c=e.peerConnection)?void 0:c.getStatsWithLowFrequency(void 0,void 0,p))),u=JSON.stringify({type:t,reports:i.map((e=>e.type)),reports2:s,pc:(null==(l=e.peerConnection)?void 0:l.getOriginRTCPeerConnection())||null,track:(null==h?void 0:h.id)||null,bytes:null==r?void 0:r.bytesSent,framesSent:null==r?void 0:r.framesSent,packetsSent:null==r?void 0:r.packetsSent,allReports:n})}catch(e){_=-999,u=e.mseeage||JSON.stringify(e)}null==r||r.report("rtc_invoke_status",{sdk_api_name:"first_frame_send_timeout",error_code:_,message:u,stream_id:(null==i?void 0:i.streamId)||"",stream_user_id:null==i?void 0:i.userId,elapse:0})}catch(e){}};class RecvFrameObserver extends eventemitter3Exports.EventEmitter{constructor(e,t){super(),__publicField(this,"_audioEventSessionId",genEventSessionId()),__publicField(this,"_videoEventSessionId",genEventSessionId()),__publicField(this,"_stream"),__publicField(this,"_firstAudioFrameTimer"),__publicField(this,"_firstVideoFrameTimer"),__publicField(this,"_transportDelayInterval"),__publicField(this,"_transportDelay"),__publicField(this,"_firstVideoFrameInterval"),__publicField(this,"_firstAudioFrameInterval"),__publicField(this,"_isScreen",!1),__publicField(this,"_audioFirstFrameState",0),__publicField(this,"_videoFirstFrameState",0),__publicField(this,"_timeout",1e4),__publicField(this,"_currentAudioRecv",{startTime:0,eventSessionId:0,type:"login"}),__publicField(this,"_currentVideoRecv",{startTime:0,eventSessionId:0,type:"login"}),__publicField(this,"_login",!1),__publicField(this,"_unMuteAudio",!1),__publicField(this,"_enableAudio",!1),__publicField(this,"_unMuteVideo",!1),__publicField(this,"_enableVideo",!1),__publicField(this,"_remoteUnmuteAudio",!1),__publicField(this,"_remoteUnmuteVideo",!1),__publicField(this,"_audioExternal",!1),__publicField(this,"_pushAudio",!1),__publicField(this,"_videoExternal",!1),__publicField(this,"_pushVideo",!1),__publicField(this,"_autoSubscribeVideo",!1),__publicField(this,"_autoSubscribeAudio",!1),__publicField(this,"_autoSubscribe",!1),__publicField(this,"_publishVideo",!1),__publicField(this,"_publishAudio",!1),__publicField(this,"_subscribeAudio",!1),__publicField(this,"_subscribeVideo",!1),__publicField(this,"_subscribe",!1),__publicField(this,"_pushTrack",!1),__publicField(this,"_multiChatMode",!1),__publicField(this,"_monitor"),__publicField(this,"logger"),this._ctx=e,this._stream=t,this.getTransportDelay(),this._monitor=getMonitor(t.engineId),this.logger=new Logger$1("RecvFrameObserver",0,t.engineId)}async beginRecvFrame(e,t){var i,r,o,s,n,a,d,c,l,u,_,h,p,m,S,g,v,f;await this.getTransportDelay();let E=this._transportDelay,T=!0;if(["login","unmute","subscribe","push_track"].indexOf(t)>=0&&(E=0,T=!1),"audio"===e){T||this._audioEventSessionId++,this._currentAudioRecv={startTime:Date.now(),eventSessionId:this._audioEventSessionId,type:t};const u={media_type:e,event_type:"begin_recv",type:t,is_screen:!!(null==(i=this._stream)?void 0:i.isScreen),start:null==(r=this._currentAudioRecv)?void 0:r.startTime,event_session_id:this._audioEventSessionId,stream_user_id:null==(o=this._stream)?void 0:o.userId,transport_delay:E,vendor_mode:(null==(s=this._stream)?void 0:s.vendorCode)||0,pc_session_id:(null==(n=this._stream)?void 0:n.pcSessionId)||(null==(a=this._ctx.peerConnection)?void 0:a.getConnectionId()),remote_rtc_session_id:null==(d=this._stream)?void 0:d.remoteSessionId,is_public_stream:null==(c=this._stream)?void 0:c.isPublicStream};this._firstAudioFrameTimer&&window.clearTimeout(this._firstAudioFrameTimer),this._firstAudioFrameTimer=setTimeout((()=>{reportFirstFrameRecvError(this._ctx,"audio",this._stream,this._monitor),this.stopRecvFrame("audio","timeout"),this._firstAudioFrameInterval&&window.clearInterval(this._firstAudioFrameInterval)}),this._timeout),this.logger.info("rtcFirstFrameRecv",JSON.stringify(u)),null==(l=this._monitor)||l.report("rtc_first_frame",u),this._watchForFirstAudioFrameRecv(),this._audioFirstFrameState=1,this._login=!0,this._unMuteAudio=!0,this._enableAudio=!0,this._remoteUnmuteAudio=!0}else if("video"===e){T||this._videoEventSessionId++,this._currentVideoRecv={startTime:Date.now(),eventSessionId:this._videoEventSessionId,type:t};const i={media_type:e,event_type:"begin_recv",type:t,is_screen:!!(null==(u=this._stream)?void 0:u.isScreen),start:null==(_=this._currentVideoRecv)?void 0:_.startTime,event_session_id:this._videoEventSessionId,stream_user_id:null==(h=this._stream)?void 0:h.userId,transport_delay:E,vendor_mode:(null==(p=this._stream)?void 0:p.vendorCode)||0,pc_session_id:(null==(m=this._stream)?void 0:m.pcSessionId)||(null==(S=this._ctx.peerConnection)?void 0:S.getConnectionId()),remote_rtc_session_id:null==(g=this._stream)?void 0:g.remoteSessionId,is_public_stream:null==(v=this._stream)?void 0:v.isPublicStream};this._firstVideoFrameTimer&&window.clearTimeout(this._firstVideoFrameTimer),this._firstVideoFrameTimer=setTimeout((()=>{reportFirstFrameRecvError(this._ctx,"video",this._stream,this._monitor),this.stopRecvFrame("video","timeout"),this._firstVideoFrameInterval&&window.clearInterval(this._firstVideoFrameInterval)}),this._timeout),this._watchForFirstVideoFrameRecv(),this.logger.info("rtcFirstFrameRecv",JSON.stringify(i)),null==(f=this._monitor)||f.report("rtc_first_frame",i),this._videoFirstFrameState=1,this._login=!0,this._unMuteVideo=!0,this._enableVideo=!0,this._remoteUnmuteVideo=!0}}stopRecvFrame(e,t){var i,r,o,s,n,a,d,c,l,u,_,h,p,m,S,g,v,f,E,T,R,b,y,I,C,A,k,M,N,O,P,D,w,L,x,F,U,V,B,$,G,W,H,K,X,Z,z,Y;if("audio"===e){if(1!==this._audioFirstFrameState)return;const _={event_type:"recv_end",media_type:e,is_screen:!!(null==(i=this._stream)?void 0:i.isScreen),start:null==(r=this._currentAudioRecv)?void 0:r.startTime,reason:t,result:!1,stream_user_id:null==(o=this._stream)?void 0:o.userId,event_session_id:this._audioEventSessionId,type:null==(s=this._currentAudioRecv)?void 0:s.type,vendor_mode:(null==(n=this._stream)?void 0:n.vendorCode)||0,pc_session_id:(null==(a=this._stream)?void 0:a.pcSessionId)||(null==(d=this._ctx.peerConnection)?void 0:d.getConnectionId()),remote_rtc_session_id:null==(c=this._stream)?void 0:c.remoteSessionId,is_public_stream:null==(l=this._stream)?void 0:l.isPublicStream};this._firstAudioFrameTimer&&window.clearTimeout(this._firstAudioFrameTimer),delete this._currentAudioRecv,this.logger.info("rtcFirstFrameRecv",JSON.stringify(_)),null==(u=this._monitor)||u.report("rtc_first_frame",_),this._audioFirstFrameState=2}else if("video"===e){if(1!==this._videoFirstFrameState)return;const i={event_type:"recv_end",media_type:e,is_screen:!!(null==(_=this._stream)?void 0:_.isScreen),start:null==(h=this._currentVideoRecv)?void 0:h.startTime,reason:t,result:!1,stream_user_id:null==(p=this._stream)?void 0:p.userId,event_session_id:this._videoEventSessionId,type:null==(m=this._currentVideoRecv)?void 0:m.type,vendor_mode:(null==(S=this._stream)?void 0:S.vendorCode)||0,pc_session_id:(null==(g=this._stream)?void 0:g.pcSessionId)||(null==(v=this._ctx.peerConnection)?void 0:v.getConnectionId()),remote_rtc_session_id:null==(f=this._stream)?void 0:f.remoteSessionId,codec:null==(R=null==(T=null==(E=this._stream)?void 0:E.getRemoteStreamStats())?void 0:T.videoStats)?void 0:R.codecType,stats_frame_size_width:null==(I=null==(y=null==(b=this._stream)?void 0:b.getRemoteStreamStats())?void 0:y.videoStats)?void 0:I.frame_size_width,stats_frame_size_height:null==(k=null==(A=null==(C=this._stream)?void 0:C.getRemoteStreamStats())?void 0:A.videoStats)?void 0:k.frame_size_height,stats_frame_rate_decode:null==(O=null==(N=null==(M=this._stream)?void 0:M.getRemoteStreamStats())?void 0:N.videoStats)?void 0:O.decoderOutputFrameRate,stats_frame_rate_receive:null==(w=null==(D=null==(P=this._stream)?void 0:P.getRemoteStreamStats())?void 0:D.videoStats)?void 0:w.receivedFrameRate,stats_frame_decoder_name:null==(F=null==(x=null==(L=this._stream)?void 0:L.getRemoteStreamStats())?void 0:x.videoStats)?void 0:F.decoderName,stats_gpu_url:Config2.GPU_URL||(null==(U=getGpuInfo())?void 0:U.renderer),track_frame_size_width:null==($=null==(B=null==(V=this._stream)?void 0:V.videoTrack)?void 0:B.originTrack.getSettings())?void 0:$.width,track_frame_size_height:null==(H=null==(W=null==(G=this._stream)?void 0:G.videoTrack)?void 0:W.originTrack.getSettings())?void 0:H.height,track_frame_rate:null==(Z=null==(X=null==(K=this._stream)?void 0:K.videoTrack)?void 0:X.originTrack.getSettings())?void 0:Z.frameRate,is_public_stream:null==(z=this._stream)?void 0:z.isPublicStream};this._firstVideoFrameTimer&&window.clearTimeout(this._firstVideoFrameTimer),delete this._currentVideoRecv,this.logger.info("rtcFirstFrameRecv",JSON.stringify(i)),null==(Y=this._monitor)||Y.report("rtc_first_frame",i),this._videoFirstFrameState=2,setTimeout((()=>{var i,r,o,s,n,a,d,c,l,u,_,h,p,m,S,g,v,f,E,T,R,b,y,I,C,A,k,M,N,O,P,D,w,L,x,F,U,V;const B={event_type:"recv_end",media_type:e,is_screen:!!(null==(i=this._stream)?void 0:i.isScreen),start:null==(r=this._currentVideoRecv)?void 0:r.startTime,reason:t,result:!1,stream_user_id:null==(o=this._stream)?void 0:o.userId,event_session_id:this._videoEventSessionId,type:null==(s=this._currentVideoRecv)?void 0:s.type,vendor_mode:(null==(n=this._stream)?void 0:n.vendorCode)||0,pc_session_id:(null==(a=this._stream)?void 0:a.pcSessionId)||(null==(d=this._ctx.peerConnection)?void 0:d.getConnectionId()),remote_rtc_session_id:null==(c=this._stream)?void 0:c.remoteSessionId,codec:null==(_=null==(u=null==(l=this._stream)?void 0:l.getRemoteStreamStats())?void 0:u.videoStats)?void 0:_.codecType,stats_frame_size_width:null==(m=null==(p=null==(h=this._stream)?void 0:h.getRemoteStreamStats())?void 0:p.videoStats)?void 0:m.frame_size_width,stats_frame_size_height:null==(v=null==(g=null==(S=this._stream)?void 0:S.getRemoteStreamStats())?void 0:g.videoStats)?void 0:v.frame_size_height,stats_frame_rate_decode:null==(T=null==(E=null==(f=this._stream)?void 0:f.getRemoteStreamStats())?void 0:E.videoStats)?void 0:T.decoderOutputFrameRate,stats_frame_rate_receive:null==(y=null==(b=null==(R=this._stream)?void 0:R.getRemoteStreamStats())?void 0:b.videoStats)?void 0:y.receivedFrameRate,stats_frame_decoder_name:null==(A=null==(C=null==(I=this._stream)?void 0:I.getRemoteStreamStats())?void 0:C.videoStats)?void 0:A.decoderName,stats_gpu_url:Config2.GPU_URL||(null==(k=getGpuInfo())?void 0:k.renderer),track_frame_size_width:null==(O=null==(N=null==(M=this._stream)?void 0:M.videoTrack)?void 0:N.originTrack.getSettings())?void 0:O.width,track_frame_size_height:null==(w=null==(D=null==(P=this._stream)?void 0:P.videoTrack)?void 0:D.originTrack.getSettings())?void 0:w.height,track_frame_rate:null==(F=null==(x=null==(L=this._stream)?void 0:L.videoTrack)?void 0:x.originTrack.getSettings())?void 0:F.frameRate,is_public_stream:null==(U=this._stream)?void 0:U.isPublicStream};this.logger.info("rtc_first_frame_statistics",JSON.stringify(B)),null==(V=this._monitor)||V.report("rtc_first_frame_statistics",B)}),8e3)}}async recvFrameFinish(e){var t,i,r,o,s,n,a,d,c,l,u,_,h,p,m,S,g,v,f,E,T,R,b,y,I,C,A,k,M,N,O,P,D,w,L,x,F,U,V,B,$,G,W,H;await this.getTransportDelay();let K=this._transportDelay;if("audio"===e){if(1!==this._audioFirstFrameState)return;if(!this._currentAudioRecv)return;const{type:c,startTime:l}=this._currentAudioRecv;["login","unmute","subscribe","push_track"].indexOf(c)>=0&&(K=0);const u={event_type:"recv_end",media_type:e,start:l,result:!0,is_screen:!!(null==(t=this._stream)?void 0:t.isScreen),stream_user_id:null==(i=this._stream)?void 0:i.userId,event_session_id:this._audioEventSessionId,type:c,transport_delay:K,vendor_mode:(null==(r=this._stream)?void 0:r.vendorCode)||0,pc_session_id:(null==(o=this._stream)?void 0:o.pcSessionId)||(null==(s=this._ctx.peerConnection)?void 0:s.getConnectionId()),remote_rtc_session_id:null==(n=this._stream)?void 0:n.remoteSessionId,is_public_stream:null==(a=this._stream)?void 0:a.isPublicStream};delete this._currentAudioRecv,this._firstAudioFrameTimer&&window.clearTimeout(this._firstAudioFrameTimer),this.logger.info("rtcFirstFrameRecv",JSON.stringify(u)),null==(d=this._monitor)||d.report("rtc_first_frame",u),this.emit("recvAudioFirstFrame"),this._audioFirstFrameState=3}else if("video"===e){if(1!==this._videoFirstFrameState)return;if(!this._currentVideoRecv)return;const{type:t,startTime:i}=this._currentVideoRecv;["login","unmute","subscribe","push_track"].indexOf(t)>=0&&(K=0);const r={event_type:"recv_end",media_type:e,is_screen:!!(null==(c=this._stream)?void 0:c.isScreen),start:i,result:!0,stream_user_id:null==(l=this._stream)?void 0:l.userId,event_session_id:this._videoEventSessionId,type:t,transport_delay:K,vendor_mode:(null==(u=this._stream)?void 0:u.vendorCode)||0,pc_session_id:(null==(_=this._stream)?void 0:_.pcSessionId)||(null==(h=this._ctx.peerConnection)?void 0:h.getConnectionId()),remote_rtc_session_id:null==(p=this._stream)?void 0:p.remoteSessionId,codec:null==(g=null==(S=null==(m=this._stream)?void 0:m.getRemoteStreamStats())?void 0:S.videoStats)?void 0:g.codecType,stats_frame_size_width:null==(E=null==(f=null==(v=this._stream)?void 0:v.getRemoteStreamStats())?void 0:f.videoStats)?void 0:E.frameSizeWidth,stats_frame_size_height:null==(b=null==(R=null==(T=this._stream)?void 0:T.getRemoteStreamStats())?void 0:R.videoStats)?void 0:b.frameSizeHeight,stats_frame_rate_decode:null==(C=null==(I=null==(y=this._stream)?void 0:y.getRemoteStreamStats())?void 0:I.videoStats)?void 0:C.decoderOutputFrameRate,stats_frame_rate_receive:null==(M=null==(k=null==(A=this._stream)?void 0:A.getRemoteStreamStats())?void 0:k.videoStats)?void 0:M.receivedFrameRate,stats_frame_decoder_name:null==(P=null==(O=null==(N=this._stream)?void 0:N.getRemoteStreamStats())?void 0:O.videoStats)?void 0:P.decoderName,stats_gpu_url:Config2.GPU_URL||(null==(D=getGpuInfo())?void 0:D.renderer),track_frame_size_width:null==(x=null==(L=null==(w=this._stream)?void 0:w.videoTrack)?void 0:L.originTrack.getSettings())?void 0:x.width,track_frame_size_height:null==(V=null==(U=null==(F=this._stream)?void 0:F.videoTrack)?void 0:U.originTrack.getSettings())?void 0:V.height,track_frame_rate:null==(G=null==($=null==(B=this._stream)?void 0:B.videoTrack)?void 0:$.originTrack.getSettings())?void 0:G.frameRate,is_public_stream:null==(W=this._stream)?void 0:W.isPublicStream};delete this._currentVideoRecv,this._firstVideoFrameTimer&&window.clearTimeout(this._firstVideoFrameTimer),this.logger.info("rtcFirstFrameRecv",JSON.stringify(r)),null==(H=this._monitor)||H.report("rtc_first_frame",r),this.emit("recvVideoFirstFrame"),this._videoFirstFrameState=3,setTimeout((()=>{var r,o,s,n,a,d,c,l,u,_,h,p,m,S,g,v,f,E,T,R,b,y,I,C,A,k,M,N,O,P,D,w,L,x,F,U;const V={event_type:"recv_end",media_type:e,is_screen:!!(null==(r=this._stream)?void 0:r.isScreen),start:i,result:!0,stream_user_id:null==(o=this._stream)?void 0:o.userId,event_session_id:this._videoEventSessionId,type:t,transport_delay:K,vendor_mode:(null==(s=this._stream)?void 0:s.vendorCode)||0,pc_session_id:(null==(n=this._stream)?void 0:n.pcSessionId)||(null==(a=this._ctx.peerConnection)?void 0:a.getConnectionId()),remote_rtc_session_id:null==(d=this._stream)?void 0:d.remoteSessionId,codec:null==(u=null==(l=null==(c=this._stream)?void 0:c.getRemoteStreamStats())?void 0:l.videoStats)?void 0:u.codecType,stats_frame_size_width:null==(p=null==(h=null==(_=this._stream)?void 0:_.getRemoteStreamStats())?void 0:h.videoStats)?void 0:p.frameSizeWidth,stats_frame_size_height:null==(g=null==(S=null==(m=this._stream)?void 0:m.getRemoteStreamStats())?void 0:S.videoStats)?void 0:g.frameSizeHeight,stats_frame_rate_decode:null==(E=null==(f=null==(v=this._stream)?void 0:v.getRemoteStreamStats())?void 0:f.videoStats)?void 0:E.decoderOutputFrameRate,stats_frame_rate_receive:null==(b=null==(R=null==(T=this._stream)?void 0:T.getRemoteStreamStats())?void 0:R.videoStats)?void 0:b.receivedFrameRate,stats_frame_decoder_name:null==(C=null==(I=null==(y=this._stream)?void 0:y.getRemoteStreamStats())?void 0:I.videoStats)?void 0:C.decoderName,stats_gpu_url:Config2.GPU_URL||(null==(A=getGpuInfo())?void 0:A.renderer),track_frame_size_width:null==(N=null==(M=null==(k=this._stream)?void 0:k.videoTrack)?void 0:M.originTrack.getSettings())?void 0:N.width,track_frame_size_height:null==(D=null==(P=null==(O=this._stream)?void 0:O.videoTrack)?void 0:P.originTrack.getSettings())?void 0:D.height,track_frame_rate:null==(x=null==(L=null==(w=this._stream)?void 0:w.videoTrack)?void 0:L.originTrack.getSettings())?void 0:x.frameRate,is_public_stream:null==(F=this._stream)?void 0:F.isPublicStream};this.logger.info("rtc_first_frame_statistics",JSON.stringify(V)),null==(U=this._monitor)||U.report("rtc_first_frame_statistics",V)}),8e3)}}setLogin(e,t={audio:!0,video:!0}){var i,r,o,s;this._login!==e&&(this._login=e,e&&(null==(i=this._stream)?void 0:i.hasAudio)&&t.audio&&this.beginRecvFrame("audio","login"),e&&(null==(r=this._stream)?void 0:r.hasVideo)&&t.video&&this.beginRecvFrame("video","login"),!e&&(null==(o=this._stream)?void 0:o.hasAudio)&&this.stopRecvFrame("audio","leave_room"),!e&&(null==(s=this._stream)?void 0:s.hasVideo)&&this.stopRecvFrame("video","leave_room"))}setUnmuteAudio(e){var t,i,r;if(this._unMuteAudio===e)return;this._unMuteAudio=e;const o=!!(null==(t=this._stream)?void 0:t.hasAudio);(null==(i=this._stream)?void 0:i.audioHasCapture)&&(null==(r=this._stream)?void 0:r.audioHasPublish)&&(this._unMuteAudio&&o?this.beginRecvFrame("audio","unmute"):o&&this.stopRecvFrame("audio","mute"))}setRemoteUnmuteAudio(e){this._remoteUnmuteAudio!==e&&(this._remoteUnmuteAudio=e,this._remoteUnmuteAudio?this.beginRecvFrame("audio","remote_unmute"):this.stopRecvFrame("audio","remote_mute"))}setEnableAudio(e){this._enableAudio!==e&&(this._enableAudio=e,this._enableAudio?this.beginRecvFrame("audio","enable"):this.stopRecvFrame("audio","disable"))}setUnmuteVideo(e){var t,i,r;if(this._unMuteVideo===e)return;this._unMuteVideo=e;const o=!!(null==(t=this._stream)?void 0:t.hasVideo);(null==(i=this._stream)?void 0:i.videoHasCapture)&&(null==(r=this._stream)?void 0:r.videoHasPublish)&&(this._unMuteVideo&&o?this.beginRecvFrame("video","unmute"):o&&this.stopRecvFrame("video","mute"))}setRemoteUnmuteVideo(e){this._remoteUnmuteVideo!==e&&(this._remoteUnmuteVideo=e,this._remoteUnmuteVideo?this.beginRecvFrame("video","remote_unmute"):this.stopRecvFrame("video","remote_mute"))}setEnableVideo(e){this._enableVideo!==e&&(this._enableVideo=e,this._enableVideo?this.beginRecvFrame("video","enable"):this.stopRecvFrame("video","disable"))}setExternalAudioSource(e){this._audioExternal=e}setPushAudio(e){var t;this._audioExternal&&this._pushAudio!==e&&(this._pushAudio=e),this._pushAudio&&this.beginRecvFrame("audio","push"),!e&&(null==(t=this._stream)?void 0:t.hasAudio)&&this.stopRecvFrame("audio","stop_push")}setExternalVideoSource(e){this._videoExternal=e}setPushVideo(e){var t;this._videoExternal&&this._pushVideo!==e&&(this._pushVideo=e),this._pushVideo&&this.beginRecvFrame("video","push"),!e&&(null==(t=this._stream)?void 0:t.hasVideo)&&this.stopRecvFrame("video","stop_push")}setPublishVideo(e){var t;this._publishVideo!==e&&(this._publishVideo=e),this._publishVideo&&this.beginRecvFrame("video","publish"),!e&&(null==(t=this._stream)?void 0:t.hasVideo)&&this.stopRecvFrame("video","unpublish")}setPublishAudio(e){var t;this._publishAudio!==e&&(this._publishAudio=e),this._publishAudio&&this.beginRecvFrame("audio","publish"),!e&&(null==(t=this._stream)?void 0:t.hasAudio)&&this.stopRecvFrame("audio","unpublish")}setAutoSubscribe(e){this._autoSubscribe=e}setAutoSubscribeVideo(e){this._autoSubscribeVideo=e}setAutoSubscribeAudio(e){this._autoSubscribeAudio=e}setSubscribeAudio(e){var t,i;this._autoSubscribeAudio||this._subscribeAudio===e||(this._subscribe=e,e&&(null==(t=this._stream)?void 0:t.hasAudio)&&this.beginRecvFrame("audio","subscribe")),!e&&(null==(i=this._stream)?void 0:i.hasAudio)&&this.stopRecvFrame("audio","unsubscribe")}setSubscribeVideo(e){var t,i;this._autoSubscribeVideo||this._subscribeVideo===e||(this._subscribeVideo=e,e&&(null==(t=this._stream)?void 0:t.hasVideo)&&this.beginRecvFrame("video","subscribe")),!e&&(null==(i=this._stream)?void 0:i.hasVideo)&&this.stopRecvFrame("video","unsubscribe")}setPushTrack(e){var t;this._pushTrack!==e&&(this._pushTrack=e,e&&!this._isScreen&&this.beginRecvFrame("audio","push_track"),!e&&(null==(t=this._stream)?void 0:t.hasAudio)&&this.stopRecvFrame("audio","remove_track"))}setMultiChatMode(e){this._multiChatMode=e}setTimeout(e){this._timeout=e}_watchForFirstVideoFrameRecv(){let e=-1,t=-1;this._firstVideoFrameInterval&&window.clearInterval(this._firstVideoFrameInterval),this._firstVideoFrameInterval=window.setInterval((async()=>{var i,r,o,s,n,a,d;const c=(null==(r=null==(i=this._stream)?void 0:i.vendorHandler)?void 0:r.peer)??this._ctx.peerConnection;if(c&&(null==(s=null==(o=this._stream)?void 0:o.videoTrack)?void 0:s.preprocessingTrack)){const i=null==(n=this._stream.videoTransceiver)?void 0:n.receiver,r=(await c.getStatsWithLowFrequency(null==(d=null==(a=this._stream)?void 0:a.videoTrack)?void 0:d.preprocessingTrack,!0,i)).find((e=>"inbound-rtp"===e.type));if(r&&(r.framesReceived>e||r.packetsReceived>t)){if(-1===e&&-1===t)return e=r.framesReceived,void(t=r.packetsReceived);this.recvFrameFinish("video"),window.clearInterval(this._firstVideoFrameInterval)}}}),200)}_watchForFirstAudioFrameRecv(){let e=-1,t=-1;this._firstAudioFrameInterval&&window.clearInterval(this._firstAudioFrameInterval),this._firstAudioFrameInterval=window.setInterval((async()=>{var i,r,o,s,n,a;const d=(null==(r=null==(i=this._stream)?void 0:i.vendorHandler)?void 0:r.peer)??this._ctx.peerConnection;if(d&&(null==(s=null==(o=this._stream)?void 0:o.audioTrack)?void 0:s.originTrack)){const i=(await d.getStatsWithLowFrequency(null==(a=null==(n=this._stream)?void 0:n.audioTrack)?void 0:a.originTrack)).find((e=>"inbound-rtp"===e.type));if(i&&(i.totalSamplesReceived>e||i.packetsReceived>t)){if(-1===e&&-1===t)return e=i.totalSamplesReceived,void(t=i.packetsReceived);this.recvFrameFinish("audio"),window.clearInterval(this._firstAudioFrameInterval)}}}),200)}async getTransportDelay(){await this.getTransportDelayIntl(),window.clearInterval(this._transportDelayInterval),this._transportDelayInterval=window.setInterval((async()=>{await this.getTransportDelayIntl()}),2e3)}async getTransportDelayIntl(){var e,t;const i=this._ctx.peerConnection;if(i){const r=null==(t=null==(e=this._stream)?void 0:e.videoTransceiver)?void 0:t.receiver,o=await i.getStatsWithLowFrequency(void 0,!0,r),s=o.find((e=>"transport"===e.type&&"connected"===e.dtlsState)),n=o.find((e=>"candidate-pair"===e.type&&"succeeded"===e.state&&e.id===(null==s?void 0:s.selectedCandidatePairId)));n&&(this._transportDelay=Math.round(1e3*n.currentRoundTripTime/2))}}setDisconnect(){this.stopRecvFrame("audio","connection_lost"),this.stopRecvFrame("video","connection_lost"),this.reset()}reset(){this._currentAudioRecv={startTime:0,eventSessionId:0,type:"login"},this._currentVideoRecv={startTime:0,eventSessionId:0,type:"login"},this._login=!1,this._unMuteAudio=!1,this._enableAudio=!1,this._unMuteVideo=!1,this._remoteUnmuteAudio=!1,this._remoteUnmuteVideo=!1,this._enableVideo=!1,this._audioExternal=!1,this._pushAudio=!1,this._videoExternal=!1,this._pushVideo=!1,this._autoSubscribeVideo=!1,this._autoSubscribeAudio=!1,this._autoSubscribe=!1,this._subscribeAudio=!1,this._subscribeVideo=!1,this._subscribe=!1,this._pushTrack=!1,this._multiChatMode=!1,this._firstAudioFrameTimer&&window.clearTimeout(this._firstAudioFrameTimer),this._firstVideoFrameTimer&&window.clearTimeout(this._firstVideoFrameTimer),this._firstAudioFrameInterval&&window.clearInterval(this._firstAudioFrameInterval),this._firstVideoFrameInterval&&window.clearInterval(this._firstVideoFrameInterval),this._transportDelayInterval&&window.clearInterval(this._transportDelayInterval)}get audioFirstFrameReceived(){return 3===this._audioFirstFrameState}get FirstFrameReceived(){return 3===this._audioFirstFrameState}}class SendFrameObserver{constructor(e,t){__publicField(this,"_audioEventSessionId",genEventSessionId()),__publicField(this,"_videoEventSessionId",genEventSessionId()),__publicField(this,"_pcSessionId"),__publicField(this,"_firstAudioFrameTimer"),__publicField(this,"_firstVideoFrameTimer"),__publicField(this,"_stream"),__publicField(this,"_firstVideoFrameInterval"),__publicField(this,"_firstAudioFrameInterval"),__publicField(this,"_currentAudioSend",{startTime:0,eventSessionId:0,type:"login"}),__publicField(this,"_currentVideoSend",{startTime:0,eventSessionId:0,type:"login"}),__publicField(this,"_login",!1),__publicField(this,"_publisher",!1),__publicField(this,"_unMuteAudio",!1),__publicField(this,"_enableAudio",!1),__publicField(this,"_unMuteVideo",!1),__publicField(this,"_enableVideo",!1),__publicField(this,"_audioExternal",!1),__publicField(this,"_pushAudio",!1),__publicField(this,"_videoExternal",!1),__publicField(this,"_pushVideo",!1),__publicField(this,"_autoPublish",!1),__publicField(this,"_publish",!1),__publicField(this,"_timeout",1e4),__publicField(this,"_audioFirstFrameState",0),__publicField(this,"_videoFirstFrameState",0),__publicField(this,"_monitor"),__publicField(this,"logger"),this._ctx=e,this._stream=t,this._monitor=getMonitor(t.engineId),this.logger=new Logger$1("SendFrameObserver",0,t.engineId)}beginSendFrame(e,t){var i,r,o,s,n,a,d,c,l,u,_,h,p,m,S,g;if("audio"===e){this._audioEventSessionId++,this._currentAudioSend={startTime:Date.now(),eventSessionId:this._audioEventSessionId,type:t};const l={event_type:"begin_send",media_type:e,is_screen:!!(null==(i=this._stream)?void 0:i.isScreen),type:t,start:this._currentAudioSend.startTime,event_session_id:this._audioEventSessionId,vendor_mode:(null==(r=this._stream)?void 0:r.vendorCode)||0,pc_session_id:(null==(o=this._stream)?void 0:o.pcSessionId)||(null==(s=this._ctx.peerConnection)?void 0:s.getConnectionId()),capture_session_id:null==(a=null==(n=this._stream)?void 0:n.audioTrack)?void 0:a.captureSessionId,is_public_stream:null==(d=this._stream)?void 0:d.isPublicStream};this._firstAudioFrameTimer&&window.clearTimeout(this._firstAudioFrameTimer),this._firstAudioFrameTimer=setTimeout((()=>{reportFirstFrameSendError(this._ctx,"audio",this._stream,this._monitor),this.stopSendFrame("audio","timeout"),this._firstAudioFrameInterval&&window.clearInterval(this._firstAudioFrameInterval)}),this._timeout),this.logger.info("rtcFirstFrameSend",JSON.stringify(l)),null==(c=this._monitor)||c.report("rtc_first_frame",l),this._watchForFirstAudioFrameSend(),this._audioFirstFrameState=1,this._login=!0,this._publisher=!0,this._publish=!0,this._unMuteAudio=!0,this._pushAudio||(this._enableAudio=!0)}else if("video"===e){this._videoEventSessionId++,this._currentVideoSend={startTime:Date.now(),eventSessionId:this._videoEventSessionId,type:t};const i={event_type:"begin_send",media_type:e,is_screen:!!(null==(l=this._stream)?void 0:l.isScreen),type:t,start:this._currentVideoSend.startTime,event_session_id:this._videoEventSessionId,vendor_mode:(null==(u=this._stream)?void 0:u.vendorCode)||0,pc_session_id:(null==(_=this._stream)?void 0:_.pcSessionId)||(null==(h=this._ctx.peerConnection)?void 0:h.getConnectionId()),capture_session_id:null==(m=null==(p=this._stream)?void 0:p.videoTrack)?void 0:m.captureSessionId,is_public_stream:null==(S=this._stream)?void 0:S.isPublicStream};this._firstVideoFrameTimer&&window.clearTimeout(this._firstVideoFrameTimer),this._firstVideoFrameTimer=setTimeout((()=>{reportFirstFrameSendError(this._ctx,"video",this._stream,this._monitor),this.stopSendFrame("video","timeout"),this._firstVideoFrameInterval&&window.clearInterval(this._firstVideoFrameInterval)}),this._timeout),this._watchForFirstVideoFrameSend(),this.logger.info("rtcFirstFrameSend",JSON.stringify(i)),null==(g=this._monitor)||g.report("rtc_first_frame",i),this._videoFirstFrameState=1,this._login=!0,this._publisher=!0,this._publish=!0,this._unMuteVideo=!0,this._pushVideo||(this._enableVideo=!0)}}stopSendFrame(e,t){var i,r,o,s,n,a,d,c,l,u,_,h,p,m,S,g,v,f,E,T,R,b,y,I,C,A,k,M,N,O,P,D,w,L,x,F,U,V,B,$,G,W,H,K,X,Z,z,Y,j;if("audio"===e){if(1!==this._audioFirstFrameState)return;const _={event_type:"sent_end",media_type:e,is_screen:!!(null==(i=this._stream)?void 0:i.isScreen),start:null==(r=this._currentAudioSend)?void 0:r.startTime,reason:t,result:!1,event_session_id:this._audioEventSessionId,type:null==(o=this._currentAudioSend)?void 0:o.type,vendor_mode:(null==(s=this._stream)?void 0:s.vendorCode)||0,pc_session_id:(null==(n=this._stream)?void 0:n.pcSessionId)||(null==(a=this._ctx.peerConnection)?void 0:a.getConnectionId()),capture_session_id:null==(c=null==(d=this._stream)?void 0:d.audioTrack)?void 0:c.captureSessionId,is_public_stream:null==(l=this._stream)?void 0:l.isPublicStream};this._firstAudioFrameTimer&&window.clearTimeout(this._firstAudioFrameTimer),delete this._currentAudioSend,this.logger.info("rtcFirstFrameSend",JSON.stringify(_)),null==(u=this._monitor)||u.report("rtc_first_frame",_),this._audioFirstFrameState=2}else if("video"===e){if(1!==this._videoFirstFrameState)return;const i={event_type:"sent_end",media_type:e,start:null==(_=this._currentVideoSend)?void 0:_.startTime,is_screen:!!(null==(h=this._stream)?void 0:h.isScreen),reason:t,result:!1,event_session_id:this._videoEventSessionId,type:null==(p=this._currentVideoSend)?void 0:p.type,vendor_mode:(null==(m=this._stream)?void 0:m.vendorCode)||0,pc_session_id:(null==(S=this._stream)?void 0:S.pcSessionId)||(null==(g=this._ctx.peerConnection)?void 0:g.getConnectionId()),capture_session_id:null==(f=null==(v=this._stream)?void 0:v.videoTrack)?void 0:f.captureSessionId,codec:null==(E=this._stream)?void 0:E.currentVideoCodec,track_frame_size_width:null==(b=null==(R=null==(T=this._stream)?void 0:T.videoTrack)?void 0:R.originTrack)?void 0:b.getSettings().width,track_frame_size_height:null==(C=null==(I=null==(y=this._stream)?void 0:y.videoTrack)?void 0:I.originTrack)?void 0:C.getSettings().height,track_frame_rate:null==(M=null==(k=null==(A=this._stream)?void 0:A.videoTrack)?void 0:k.originTrack)?void 0:M.getSettings().frameRate,stats_frame_size_width:null==(P=null==(O=null==(N=this._stream)?void 0:N.getLocalStreamStats())?void 0:O.videoStats)?void 0:P.frame_size_width,stats_frame_size_height:null==(L=null==(w=null==(D=this._stream)?void 0:D.getLocalStreamStats())?void 0:w.videoStats)?void 0:L.frame_size_height,stats_frame_rate_input:null==(U=null==(F=null==(x=this._stream)?void 0:x.getLocalStreamStats())?void 0:F.videoStats)?void 0:U.inputFrameRate,stats_frame_rate_sent:null==($=null==(B=null==(V=this._stream)?void 0:V.getLocalStreamStats())?void 0:B.videoStats)?void 0:$.sentFrameRate,stats_frame_rate_encode:null==(H=null==(W=null==(G=this._stream)?void 0:G.getLocalStreamStats())?void 0:W.videoStats)?void 0:H.encoderOutputFrameRate,stats_frame_encoder_name:null==(Z=null==(X=null==(K=this._stream)?void 0:K.getLocalStreamStats())?void 0:X.videoStats)?void 0:Z.encoderName,stats_is_hardware_encoder_enabled:Config2.H264_HW_ENCODER,stats_gpu_url:Config2.GPU_URL||(null==(z=getGpuInfo())?void 0:z.renderer),is_public_stream:null==(Y=this._stream)?void 0:Y.isPublicStream};this._firstVideoFrameTimer&&window.clearTimeout(this._firstVideoFrameTimer),delete this._currentVideoSend,this.logger.info("rtcFirstFrameSend",JSON.stringify(i)),null==(j=this._monitor)||j.report("rtc_first_frame",i),this._videoFirstFrameState=2,setTimeout((()=>{var i,r,o,s,n,a,d,c,l,u,_,h,p,m,S,g,v,f,E,T,R,b,y,I,C,A,k,M,N,O,P,D,w,L,x,F,U,V,B;const $={event_type:"sent_end",media_type:e,start:null==(i=this._currentVideoSend)?void 0:i.startTime,is_screen:!!(null==(r=this._stream)?void 0:r.isScreen),reason:t,result:!1,event_session_id:this._videoEventSessionId,type:null==(o=this._currentVideoSend)?void 0:o.type,vendor_mode:(null==(s=this._stream)?void 0:s.vendorCode)||0,pc_session_id:(null==(n=this._stream)?void 0:n.pcSessionId)||(null==(a=this._ctx.peerConnection)?void 0:a.getConnectionId()),capture_session_id:null==(c=null==(d=this._stream)?void 0:d.videoTrack)?void 0:c.captureSessionId,codec:null==(l=this._stream)?void 0:l.currentVideoCodec,track_frame_size_width:null==(h=null==(_=null==(u=this._stream)?void 0:u.videoTrack)?void 0:_.originTrack)?void 0:h.getSettings().width,track_frame_size_height:null==(S=null==(m=null==(p=this._stream)?void 0:p.videoTrack)?void 0:m.originTrack)?void 0:S.getSettings().height,track_frame_rate:null==(f=null==(v=null==(g=this._stream)?void 0:g.videoTrack)?void 0:v.originTrack)?void 0:f.getSettings().frameRate,stats_frame_size_width:null==(R=null==(T=null==(E=this._stream)?void 0:E.getLocalStreamStats())?void 0:T.videoStats)?void 0:R.frame_size_width,stats_frame_size_height:null==(I=null==(y=null==(b=this._stream)?void 0:b.getLocalStreamStats())?void 0:y.videoStats)?void 0:I.frame_size_height,stats_frame_rate_input:null==(k=null==(A=null==(C=this._stream)?void 0:C.getLocalStreamStats())?void 0:A.videoStats)?void 0:k.inputFrameRate,stats_frame_rate_sent:null==(O=null==(N=null==(M=this._stream)?void 0:M.getLocalStreamStats())?void 0:N.videoStats)?void 0:O.sentFrameRate,stats_frame_rate_encode:null==(w=null==(D=null==(P=this._stream)?void 0:P.getLocalStreamStats())?void 0:D.videoStats)?void 0:w.encoderOutputFrameRate,stats_frame_encoder_name:null==(F=null==(x=null==(L=this._stream)?void 0:L.getLocalStreamStats())?void 0:x.videoStats)?void 0:F.encoderName,stats_is_hardware_encoder_enabled:Config2.H264_HW_ENCODER,stats_gpu_url:Config2.GPU_URL||(null==(U=getGpuInfo())?void 0:U.renderer),is_public_stream:null==(V=this._stream)?void 0:V.isPublicStream};this.logger.info("rtc_first_frame_statistics",JSON.stringify($)),null==(B=this._monitor)||B.report("rtc_first_frame_statistics",$)}),8e3)}}sendFrameFinish(e){var t,i,r,o,s,n,a,d,c,l,u,_,h,p,m,S,g,v,f,E,T,R,b,y,I,C,A,k,M,N,O,P,D,w,L,x,F,U,V,B,$,G,W,H,K;if("audio"===e){if(1!==this._audioFirstFrameState)return;if(!this._currentAudioSend)return;const{type:c,startTime:l}=this._currentAudioSend,u={event_type:"sent_end",media_type:e,is_screen:!!(null==(t=this._stream)?void 0:t.isScreen),start:l,result:!0,event_session_id:this._audioEventSessionId,type:c,vendor_mode:(null==(i=this._stream)?void 0:i.vendorCode)||0,pc_session_id:(null==(r=this._stream)?void 0:r.pcSessionId)||(null==(o=this._ctx.peerConnection)?void 0:o.getConnectionId()),capture_session_id:null==(n=null==(s=this._stream)?void 0:s.audioTrack)?void 0:n.captureSessionId,is_public_stream:null==(a=this._stream)?void 0:a.isPublicStream};delete this._currentAudioSend,this._firstAudioFrameTimer&&window.clearTimeout(this._firstAudioFrameTimer),this.logger.info("rtcFirstFrameSend",JSON.stringify(u)),null==(d=this._monitor)||d.report("rtc_first_frame",u),this._audioFirstFrameState=3}else if("video"===e){if(1!==this._videoFirstFrameState)return;if(!this._currentVideoSend)return;const{type:t,startTime:i}=this._currentVideoSend,r={event_type:"sent_end",media_type:e,is_screen:!!(null==(c=this._stream)?void 0:c.isScreen),start:i,result:!0,event_session_id:this._videoEventSessionId,type:t,vendor_mode:(null==(l=this._stream)?void 0:l.vendorCode)||0,pc_session_id:(null==(u=this._stream)?void 0:u.pcSessionId)||(null==(_=this._ctx.peerConnection)?void 0:_.getConnectionId()),capture_session_id:null==(p=null==(h=this._stream)?void 0:h.videoTrack)?void 0:p.captureSessionId,codec:null==(m=this._stream)?void 0:m.currentVideoCodec,track_frame_size_width:null==(v=null==(g=null==(S=this._stream)?void 0:S.videoTrack)?void 0:g.originTrack)?void 0:v.getSettings().width,track_frame_size_height:null==(T=null==(E=null==(f=this._stream)?void 0:f.videoTrack)?void 0:E.originTrack)?void 0:T.getSettings().height,track_frame_rate:null==(y=null==(b=null==(R=this._stream)?void 0:R.videoTrack)?void 0:b.originTrack)?void 0:y.getSettings().frameRate,stats_frame_size_width:null==(A=null==(C=null==(I=this._stream)?void 0:I.getLocalStreamStats())?void 0:C.videoStats)?void 0:A._captureResolutionWidth,stats_frame_size_height:null==(N=null==(M=null==(k=this._stream)?void 0:k.getLocalStreamStats())?void 0:M.videoStats)?void 0:N._captureResolutionHeight,stats_frame_rate_input:null==(D=null==(P=null==(O=this._stream)?void 0:O.getLocalStreamStats())?void 0:P.videoStats)?void 0:D.inputFrameRate,stats_frame_rate_sent:null==(x=null==(L=null==(w=this._stream)?void 0:w.getLocalStreamStats())?void 0:L.videoStats)?void 0:x.sentFrameRate,stats_frame_rate_encode:null==(V=null==(U=null==(F=this._stream)?void 0:F.getLocalStreamStats())?void 0:U.videoStats)?void 0:V.encoderOutputFrameRate,stats_frame_encoder_name:null==(G=null==($=null==(B=this._stream)?void 0:B.getLocalStreamStats())?void 0:$.videoStats)?void 0:G.encoderName,stats_is_hardware_encoder_enabled:Config2.H264_HW_ENCODER,stats_gpu_url:Config2.GPU_URL||(null==(W=getGpuInfo())?void 0:W.renderer),is_public_stream:null==(H=this._stream)?void 0:H.isPublicStream};delete this._currentVideoSend,this._firstVideoFrameTimer&&window.clearTimeout(this._firstVideoFrameTimer),this.logger.info("rtcFirstFrameSend",JSON.stringify(r)),null==(K=this._monitor)||K.report("rtc_first_frame",r),this._videoFirstFrameState=3,setTimeout((()=>{var r,o,s,n,a,d,c,l,u,_,h,p,m,S,g,v,f,E,T,R,b,y,I,C,A,k,M,N,O,P,D,w,L,x,F,U,V;const B={event_type:"sent_end",media_type:e,is_screen:!!(null==(r=this._stream)?void 0:r.isScreen),start:i,result:!0,event_session_id:this._videoEventSessionId,type:t,vendor_mode:(null==(o=this._stream)?void 0:o.vendorCode)||0,pc_session_id:(null==(s=this._stream)?void 0:s.pcSessionId)||(null==(n=this._ctx.peerConnection)?void 0:n.getConnectionId()),capture_session_id:null==(d=null==(a=this._stream)?void 0:a.videoTrack)?void 0:d.captureSessionId,codec:null==(c=this._stream)?void 0:c.currentVideoCodec,track_frame_size_width:null==(_=null==(u=null==(l=this._stream)?void 0:l.videoTrack)?void 0:u.originTrack)?void 0:_.getSettings().width,track_frame_size_height:null==(m=null==(p=null==(h=this._stream)?void 0:h.videoTrack)?void 0:p.originTrack)?void 0:m.getSettings().height,track_frame_rate:null==(v=null==(g=null==(S=this._stream)?void 0:S.videoTrack)?void 0:g.originTrack)?void 0:v.getSettings().frameRate,stats_frame_size_width:null==(T=null==(E=null==(f=this._stream)?void 0:f.getLocalStreamStats())?void 0:E.videoStats)?void 0:T._captureResolutionWidth,stats_frame_size_height:null==(y=null==(b=null==(R=this._stream)?void 0:R.getLocalStreamStats())?void 0:b.videoStats)?void 0:y._captureResolutionHeight,stats_frame_rate_input:null==(A=null==(C=null==(I=this._stream)?void 0:I.getLocalStreamStats())?void 0:C.videoStats)?void 0:A.inputFrameRate,stats_frame_rate_sent:null==(N=null==(M=null==(k=this._stream)?void 0:k.getLocalStreamStats())?void 0:M.videoStats)?void 0:N.sentFrameRate,stats_frame_rate_encode:null==(D=null==(P=null==(O=this._stream)?void 0:O.getLocalStreamStats())?void 0:P.videoStats)?void 0:D.encoderOutputFrameRate,stats_frame_encoder_name:null==(x=null==(L=null==(w=this._stream)?void 0:w.getLocalStreamStats())?void 0:L.videoStats)?void 0:x.encoderName,stats_is_hardware_encoder_enabled:Config2.H264_HW_ENCODER,stats_gpu_url:Config2.GPU_URL||(null==(F=getGpuInfo())?void 0:F.renderer),is_public_stream:null==(U=this._stream)?void 0:U.isPublicStream};this.logger.info("rtc_first_frame_statistics",JSON.stringify(B)),null==(V=this._monitor)||V.report("rtc_first_frame_statistics",B)}),8e3)}}setLogin(e){var t,i;this._login!==e&&(this._login=e,e&&((null==(t=this._stream)?void 0:t.videoTrack)&&this._stream.pubVideo&&this.beginSendFrame("video","login"),(null==(i=this._stream)?void 0:i.audioTrack)&&this._stream.pubAudio&&this.beginSendFrame("audio","login")),!e&&this._audioSending&&this.stopSendFrame("audio","leave_room"),!e&&this._videoSending&&this.stopSendFrame("video","leave_room"))}setPublish(e){var t,i;this._publish!==e&&(this._publish=e,e&&((null==(t=this._stream)?void 0:t.videoTrack)&&this._stream.pubVideo&&this.beginSendFrame("video","publish"),(null==(i=this._stream)?void 0:i.audioTrack)&&this._stream.pubAudio&&this.beginSendFrame("audio","publish")),!e&&this._audioSending&&this.stopSendFrame("audio","unpublish"),!e&&this._videoSending&&this.stopSendFrame("video","unpublish"))}setUnmuteAudio(e){var t;this._unMuteAudio!==e&&(this._unMuteAudio=e,(null==(t=this._stream)?void 0:t.audioHasCapture)&&(e&&this.beginSendFrame("audio","unmute"),!e&&this._audioSending&&this.stopSendFrame("audio","mute")))}setEnableAudio(e){var t;this._enableAudio!==e&&(null==(t=this._stream)?void 0:t.pubAudio)&&(this._enableAudio=e,e&&this.beginSendFrame("audio","enable"),!e&&this._audioSending&&this.stopSendFrame("audio","disable"))}setUnmuteVideo(e){var t;this._unMuteVideo!==e&&(this._unMuteVideo=e,(null==(t=this._stream)?void 0:t.videoHasCapture)&&(e&&this.beginSendFrame("video","unmute"),!e&&this._videoSending&&this.stopSendFrame("video","mute")))}setEnableVideo(e){var t;this._enableVideo!==e&&(null==(t=this._stream)?void 0:t.pubVideo)&&(this._enableVideo=e,e&&this.beginSendFrame("video","enable"),!e&&this._videoSending&&this.stopSendFrame("video","disable"))}setPushAudio(e){this._pushAudio!==e&&(this._pushAudio=e,e&&this.beginSendFrame("audio","push"),!e&&this._audioSending&&this.stopSendFrame("audio","stop_push"))}setPushVideo(e){this._pushVideo!==e&&(this._pushVideo=e,e&&this.beginSendFrame("video","push"),!e&&this._videoSending&&this.stopSendFrame("video","stop_push"))}setAutoPublish(e){this._autoPublish=e}setPublisher(e){this._publisher!==e&&(this._publisher=e,!e&&this._audioSending&&this.stopSendFrame("audio","audience"),!e&&this._videoSending&&this.stopSendFrame("video","audience"))}setDisconnect(){this._audioSending&&this.stopSendFrame("audio","connection_lost"),this._videoSending&&this.stopSendFrame("video","connection_lost"),this.reset()}setTimeout(e){this._timeout=e}setPCSessionId(e){this._pcSessionId=e}async _getFirstVideoFrameStats(){var e,t,i,r,o,s;const n=null==(t=null==(e=this._stream)?void 0:e.videoTrack)?void 0:t.preprocessingTrack,a=null==(r=null==(i=this._stream)?void 0:i.videoTransceiver)?void 0:r.sender,d=(null==(s=null==(o=this._stream)?void 0:o.vendorHandler)?void 0:s.peer)??this._ctx.peerConnection;if(d&&n){return(await d.getStatsWithLowFrequency(n,!0,a)).filter((e=>"outbound-rtp"===e.type))}}async _getFirstAudioFrameStats(){var e,t,i,r,o,s;const n=null==(t=null==(e=this._stream)?void 0:e.audioTrack)?void 0:t.preprocessingTrack,a=null==(r=null==(i=this._stream)?void 0:i.audioTransceiver)?void 0:r.sender,d=(null==(s=null==(o=this._stream)?void 0:o.vendorHandler)?void 0:s.peer)??this._ctx.peerConnection;if(d&&n){return(await d.getStatsWithLowFrequency(n,!0,a)).find((e=>"outbound-rtp"===e.type))}}_watchForFirstVideoFrameSend(){let e=-1,t=-1;this._firstVideoFrameInterval&&window.clearInterval(this._firstVideoFrameInterval),this._firstVideoFrameInterval=window.setInterval((async()=>{const i=await this._getFirstVideoFrameStats();let r=0,o=0;if(null==i||i.map((e=>{r+=e.framesSent,o+=e.packetsSent})),i&&i.length>0&&(r>e||o>t)){if(-1===e&&-1===t)return e=r,void(t=o);this.sendFrameFinish("video"),window.clearInterval(this._firstVideoFrameInterval)}}),100)}_watchForFirstAudioFrameSend(){let e=-1;this._firstAudioFrameInterval&&window.clearInterval(this._firstAudioFrameInterval),this._firstAudioFrameInterval=window.setInterval((async()=>{const t=await this._getFirstAudioFrameStats();if(t&&t.packetsSent>e){if(-1===e)return void(e=t.packetsSent);this.sendFrameFinish("audio"),window.clearInterval(this._firstAudioFrameInterval)}}),100)}reset(){this._login=!1,this._publisher=!1,this._unMuteAudio=!1,this._enableAudio=!1,this._unMuteVideo=!1,this._enableVideo=!1,this._audioExternal=!1,this._pushAudio=!1,this._videoExternal=!1,this._pushVideo=!1,this._autoPublish=!1,this._publish=!1,this._audioFirstFrameState=0,this._videoFirstFrameState=0,this._currentAudioSend={startTime:0,eventSessionId:0,type:"login"},this._currentVideoSend={startTime:0,eventSessionId:0,type:"login"},window.clearTimeout(this._firstAudioFrameTimer),window.clearTimeout(this._firstVideoFrameTimer),window.clearInterval(this._firstAudioFrameInterval),window.clearInterval(this._firstVideoFrameInterval)}destroy(){this.reset(),delete this._stream}get _audioSending(){return 1===this._audioFirstFrameState}get _videoSending(){return 1===this._videoFirstFrameState}}const CONFIG={audio:{delay:1200,stallRadio:.3},video:{delay:1200,stallRadio:.6},screen_audio:{delay:1600,stallRadio:.8},screen_video:{delay:1600,stallRadio:.8}};class NetworkQualityManager{constructor(e){__publicField(this,"_preUplinkStats",new Map),__publicField(this,"_preDownlinkStats",new Map),__publicField(this,"_timer"),__publicField(this,"_delayTimer"),__publicField(this,"reportor"),this._ctx=e}updateUplinkStats(e,t){const{audioStats:i,videoStats:r,isScreen:o}=e;if(i.sendKBitrate>0&&i.rtt){const e=o?"screen_audio":"audio",{rtt:t,_fractionLost:r,_retransmittedRate:s}=i,n=this._getQosLevel(t,r||0,s||0),a=this._preUplinkStats.get(e)||[n];this._preUplinkStats.set(e,[...a,n].slice(-2))}if(r.sentKBitrate>0&&r.rtt){const i=o?"screen_video":"video";let{_fractionLost:s}=r;const{rtt:n,_sendBandWidth:a,_retransmittedRate:d}=r;0===a&&(s=Math.max(.65,s));const c=this._getQosLevel(n,s||0,d||0),l=this._getUplinkVideoQoE(e,t),u=this._getVideoUplinkNetworkQuality(c,l),_=this._preUplinkStats.get(i)||[u];this._preUplinkStats.set(i,[..._,u].slice(-2))}this._startNetworkQualityReport()}updateDownlinkStats(e,t){if(!t)return;const{audioActive:i,videoActive:r}=this._getStreamActiveState(t),{audioStats:o,videoStats:s,isScreen:n,userId:a}=e;let d,c,l=!0,u=!0;if(i)if(0===o.receivedKBitrate)l=!1;else{const{rtt:e,audioLossRate:t,stallDuration:i,statsInterval:r,e2eDelay:a}=o,c=i/r,l=n?"screen_audio":"audio",u=this._getQosLevel(e,t||0,s._retransmittedRate||0),_=this._getDownlinkQoE(l,c,a);d=this._getNetworkQuality(u,_)}if(r)if(0===s.receivedKBitrate||0===s.rtt)u=!1;else{const{rtt:e,videoLossRate:t,stallDuration:i,statsInterval:r,e2eDelay:o,_retransmittedRate:a}=s,d=i/r,l=n?"screen_video":"video",u=this._getQosLevel(e,t||0,a||0),_=this._getDownlinkQoE(l,d,o);c=this._getNetworkQuality(u,_)}const _=`${a}${n?"_screen":""}`;if(!l&&!u)return void this._preDownlinkStats.delete(_);const h=d&&c?Math.ceil((d+c)/2):d||c;if(h){const e=this._preDownlinkStats.get(_)||[h];this._preDownlinkStats.set(_,[...e,h].slice(-2)),this._startNetworkQualityReport()}}destroy(){this._timer&&(window.clearInterval(this._timer),delete this._timer),this._delayTimer&&(window.clearTimeout(this._delayTimer),delete this._delayTimer),this._preUplinkStats.clear(),this._preDownlinkStats.clear()}_startNetworkQualityReport(){this._delayTimer||this._timer||(this._preUplinkStats.size>0||this._preDownlinkStats.size>0)&&(this._delayTimer=setTimeout((()=>{delete this._delayTimer,this._reportNetworkQuality(),this._timer=window.setInterval((()=>{this._reportNetworkQuality()}),2e3)}),300))}_reportNetworkQuality(){var e;let t,i;if(["connected","connecting"].includes(null==(e=this._ctx.handler)?void 0:e.getConnectionState())){const e=this._getBetterQualityAndRemoveOldest("audio","up"),r=this._getBetterQualityAndRemoveOldest("video","up");t=e&&r?Math.ceil((e+r)/2):e||r||this._getBetterQualityAndRemoveOldest("screen_video","up")||this._getBetterQualityAndRemoveOldest("screen_audio","up")||NetworkQuality.EXCELLENT;const o=Array.from(this._preDownlinkStats.keys()).map((e=>this._getBetterQualityAndRemoveOldest(e,"down"))).filter((e=>e));i=Math.ceil(o.reduce(((e,t)=>t+e),0)/o.length)||NetworkQuality.UNKNOWN}else t=i=NetworkQuality.DOWN;navigator.onLine||(t=NetworkQuality.DOWN,i=NetworkQuality.DOWN),"function"==typeof this.reportor&&this.reportor(t,i)}_getNetworkQuality(e,t){return 1===t?Math.max(e-2,1):2===t?e:Math.min(e+1,5)}_getVideoUplinkNetworkQuality(e,t){return 1===t||0===t?e:2===t?Math.min(e+1,5):Math.min(e+2,5)}_getQosLevel(e,t,i){let r;return r=(!e||e<=250)&&t<=.15?1:(!e||e<=500)&&t<=.3?2:(!e||e<=750)&&t<=.45?3:(!e||e<=1e3)&&t<=.6?4:5,i>.5?r=Math.max(r,4):i>.35?r=Math.max(r,3):i>.15&&(r=Math.max(r,2)),r}_getUplinkQoE(e,t){let i=0;switch(e){case"audio":case"video":i=t<.05?1:t<.1?2:3;break;case"screen_video":case"screen_audio":i=t<.04?1:t<.08?2:3}return i}_getUplinkVideoQoE(e,t){var i;const r=(null==(i=null==e?void 0:e.videoStats)?void 0:i.rid)||"0";if(!t)return 0;const o=t.pubAttributes.videoDescriptions[r],s=e.videoStats,n=s.encodedFrameWidth*s.encodedFrameHeight/(o.width*o.height),a=s.sentFrameRate/o.framerate;let d=0,c=0;return"number"!=typeof n||Number.isNaN(n)||(d=n>=.9?1:n<.9&&n>=.8?2:3),"number"!=typeof a||Number.isNaN(a)||(c=a>=.8?1:a<.8&&a>=.6?2:3),Math.max(0,d,c)}_getDownlinkQoE(e,t,i){const r=CONFIG[e];return t>r.stallRadio||i>r.delay||t>r.stallRadio/2&&i>r.delay/2?3:(t>r.stallRadio/2||r.delay,2)}_getBetterQualityAndRemoveOldest(e,t){let i=NetworkQuality.UNKNOWN;const r="up"===t?this._preUplinkStats:this._preDownlinkStats,o=r.get(e);if(o){const t=o.filter((e=>e));t.length>0&&(i=Math.min(...t)),o.shift(),0===o.length&&r.delete(e)}return i}_getStreamActiveState({subMediaType:e,_attributes:t,subVideo:i,subAudio:r}){return{audioActive:r&&audioInMediaType(e)&&t.localaudio&&t.audiostream,videoActive:i&&videoInMediaType(e)&&t.localvideo&&t.videostream}}}class VideoSizeObserver{constructor(e){__publicField(this,"_timer"),__publicField(this,"_remoteVideoSizeCache",{}),__publicField(this,"_remoteScreenSizeCache",{}),__publicField(this,"onchange"),this._room=e,this._start()}destroy(){this._timer&&(window.clearInterval(this._timer),delete this._timer),this._remoteVideoSizeCache={},this._remoteScreenSizeCache={}}_start(){this._timer||(this._timer=window.setInterval((()=>{const e={},t={};this._room.remoteStreams.forEach(((i,r)=>{i.forEach((i=>{var o,s,n;const a=null==(o=i.videoTrack)?void 0:o.preprocessingTrack;if(a){const o=i.isScreen?this._remoteScreenSizeCache:this._remoteVideoSizeCache,{width:d=0,height:c=0}=o[r]||{};let l=0,u=0;if(isFirefox)({width:l,height:u}=(null==(s=null==i?void 0:i.videoTrack)?void 0:s.getSizeByPlayer())??{width:0,height:0});else{const e=a.getSettings();l=e.width||0,u=e.height||0;const t=null==(n=i._attributes)?void 0:n.alphaInfo;(null==t?void 0:t.enableAlpha)&&(l=t.alphaWidth??l,u=t.alphaHeight??u/2)}c===u&&d===l||"function"==typeof this.onchange&&this.onchange(r,i.isScreen,l,u),delete o[r],(i.isScreen?t:e)[r]={width:l,height:u}}}))})),Object.keys(this._remoteVideoSizeCache).forEach((e=>{"function"==typeof this.onchange&&this.onchange(e,!1,0,0)})),Object.keys(this._remoteScreenSizeCache).forEach((e=>{"function"==typeof this.onchange&&this.onchange(e,!0,0,0)})),this._remoteVideoSizeCache=e,this._remoteScreenSizeCache=t}),1e3))}}const SUBTITLE_PREFIX=Array.from((new TextEncoder).encode("subt")),ERROR_CODE_MAP={1:ErrorCode.SUBTITLE_ERR_POSTPROCESS,2:ErrorCode.SUBTITLE_ERR_CONNECTION_ERROR,3:ErrorCode.SUBTITLE_ERR_PROCESS_ERROR},logger$5=new Logger$1("SubtitleTool",1),checkSourceLanguage=e=>{var t;if(e.extraInfo)try{const t=JSON.parse(e.extraInfo);t.source_language&&["zh","en","ja"].indexOf(t.source_language)}catch{}else{const i=(null==(t=navigator.language)?void 0:t.substring(0,2))||"";["zh","en","ja"].indexOf(i)>-1&&(e.extraInfo=JSON.stringify({source_language:i}))}},_SubtitleTool=class{constructor(e,t){__publicField(this,"_taskId"),__publicField(this,"_sourceLanguage","zh"),__publicField(this,"_updating",!1),__publicField(this,"onEvent"),__publicField(this,"onMessage"),__publicField(this,"_preConfig"),__publicField(this,"_timer"),this._ctx=e,this._roomConf=t;const{extraInfo:i}=t.userInfo;if(i)try{const e=JSON.parse(i);e.source_language&&(this._sourceLanguage=e.source_language)}catch{}}async start(e){logger$5.info("start","Invoke config: %o",e),checkEnum(e.mode,"mode",[SUBTITLE_MODE.ASR_ONLY,SUBTITLE_MODE.ASR_AND_TRANSLATION]);const t=Array.isArray(e.targetLanguage)?e.targetLanguage:[e.targetLanguage||""];if(e.mode===SUBTITLE_MODE.ASR_AND_TRANSLATION&&t.findIndex((e=>-1===SUPPORT_LANG.indexOf(e)))>-1)throw new SDKError(ErrorCode.INVALID_PARAMS,"Invalid targetLanguage.");if(this._taskId)throw new SDKError(ErrorCode.SUBTITLE_ALREADY_ON,"Already turned on subtitle");this._preConfig={targetLanguage:t,mode:e.mode},this._taskId=(Date.now().toString()+this._roomConf.roomId+this._roomConf.userId).substring(0,20),await this._sendSubtitleSignalingWithRetry(e,this._taskId)}async update(e){if(logger$5.info("update","Invoke config: %o",e),!this._taskId)throw new SDKError(ErrorCode.SUBTITLE_NOT_TURNED_ON,"Start subtitle first.");this._sourceLanguage=e.sourceLanguage,this._updating=!0;try{await this._ctx.signalingManager.sendSignaling("controlMessage",this._genChangeSubtitleLanguageSignaling(e,this._taskId))}catch(e){throw this._updating=!1,e}}stop(){logger$5.info("stop","Invoke"),this._taskId&&this._ctx.signalingManager.sendSignaling("controlMessage",{type:"subtitle",action:"stopped",appId:this._ctx.appId,roomId:this._roomConf.roomId,userId:this._roomConf.userId,taskId:this._taskId}).finally((()=>{var e;delete this._taskId,null==(e=this.onEvent)||e.call(this,{event:SubtitleEventType.STOPPED}),this._clearTimer()}))}async reconnect(){this._taskId&&this._preConfig&&(await this._ctx.signalingManager.sendSignaling("controlMessage",{type:"subtitle",action:"stopped",appId:this._ctx.appId,roomId:this._roomConf.roomId,userId:this._roomConf.userId,taskId:this._taskId}),delete this._taskId,this.start(this._preConfig))}getConfig(){return this._preConfig}destroy(){logger$5.info("destroy","Invoke"),this.stop(),delete this._preConfig,delete this._taskId}onResult(e){var t,i,r;const{error:o,errorMessage:s,eventType:n}=e.body;if(0!==o){const e=new SDKError(ERROR_CODE_MAP[o]||ErrorCode.SUBTITLE_ERR_UNKNOWN,s||"");null==(t=this.onEvent)||t.call(this,{event:SubtitleEventType.ERROR,errorCode:e.code,errorMessage:e.message}),this._clearTimer()}else"SubtitleStarted"===n?(null==(i=this.onEvent)||i.call(this,{event:SubtitleEventType.STARTED}),this._clearTimer()):this._updating&&"LanguageChanged"===n&&(this._updating=!1,null==(r=this.onEvent)||r.call(this,{event:SubtitleEventType.UPDATED}))}onMessageRecv(e,t=!1){var i;if(t||this._taskId&&this._preConfig){const t=parseSubtitleMessage(e);if(!t||0===t.length)return!1;if(this._taskId&&this._preConfig){const{mode:e,targetLanguage:r}=this._preConfig,o=[];t.forEach((t=>{if(e===SUBTITLE_MODE.ASR_ONLY)t.mode===e&&o.push(t);else{const e=r.includes(t.language);(e||t.mode===SUBTITLE_MODE.ASR_ONLY)&&o.push(t),t.mode===SUBTITLE_MODE.ASR_ONLY&&e&&o.push({...t,mode:SUBTITLE_MODE.ASR_AND_TRANSLATION})}})),o.length>0&&(null==(i=this.onMessage)||i.call(this,o))}return!0}return!1}async _sendSubtitleSignalingWithRetry(e,t,i=0){await this._ctx.signalingManager.sendSignaling("controlMessage",this._genSubtitleSignaling(e,t)),this._timer=self.setTimeout((()=>{var r;2===i?(null==(r=this.onEvent)||r.call(this,{event:SubtitleEventType.ERROR,errorCode:ErrorCode.TIME_OUT,errorMessage:"start subtitle timeout."}),delete this._timer,this.stop()):this._sendSubtitleSignalingWithRetry(e,t,i+1)}),_SubtitleTool.retryIntervel)}_genSubtitleSignaling(e,t){return{taskId:t,type:"subtitle",action:"started",roomId:this._roomConf.roomId,appId:this._ctx.appId,userId:this._roomConf.userId,subtitleMeta:{subtitleConfig:{mode:e.mode,usersConfig:[{userId:this._roomConf.userId,targetLanguages:Array.isArray(e.targetLanguage)?e.targetLanguage:[e.targetLanguage||""]}]},vendorConfig:{type:0}}}}_genChangeSubtitleLanguageSignaling(e,t){return{taskId:t,type:"subtitle",action:"subtitleUpdated",roomId:this._roomConf.roomId,appId:this._ctx.appId,userId:this._roomConf.userId,subtitleMeta:{protocol:1,languageConfig:{sourceLanguages:[{userId:this._roomConf.userId,languageCode:[e.sourceLanguage]}]}}}}_clearTimer(){this._timer&&(self.clearTimeout(this._timer),delete this._timer)}};let SubtitleTool=_SubtitleTool;__publicField(SubtitleTool,"retryIntervel",3e4);const parseSubtitleMessage=({message:e})=>{if(e instanceof ArrayBuffer&&e.byteLength>8)try{const t=new DataView(e,0);let i=0;if(SUBTITLE_PREFIX.every((e=>t.getUint8(i++)===e))){const r=t.getUint32(i);if(i+=4,r===t.byteLength-8){const t=Utils.ab2str(e.slice(8)),{data:i,type:r}=JSON.parse(t);if("subtitle"===r)return i}}}catch{}return!1},SUPPORT_LANG=["zh","zh-Hant","tn","vi","iu","it","id","hi","en","ho","he","es","el","uk","ur","tk","tr","ti","ty","tl","to","th","ta","te","sl","sk","ss","eo","sm","sg","st","sv","ja","tw","qu","pt","pa","no","nb","nr","my","bn","mn","mh","mk","ml","mr","ms","lu","ro","lt","lv","lo","kj","hr","kn","ki","cs","ca","nl","ko","ht","gu","ka","kl","km","lg","kg","fi","fj","fr","ru","ng","de","tt","da","ts","cv","fa","bs","pl","bi","nd","ba","bg","az","ar","af","sq","ab","os","ee","et","ay","lzh","am","ckb","cy","gl","ha","hy","ig","kmr","ln","nso","ny","om","sn","so","sr","sw","xh","yo","zu"];function camel2Snake(e){return e.replace(/[A-Z]/g,(e=>`_${e.toLowerCase()}`))}function assignIn(e,t){return{...e,...t}}function cloneDeep(e){const t={};return Object.keys(e).forEach((i=>{const r=e[i];try{Array.isArray(r)?t[i]=r.map((e=>null!==e&&"object"==typeof e?cloneDeep(e):e)):t[i]=null!==r&&"object"==typeof r?cloneDeep(r):r}catch{}})),t}function values(e){return null===e?[]:Object.keys(e).map((t=>e[t]))}const logger$4=new Logger$1("Locker",2);let lockId=1;class PromiseLock2{constructor(e){__publicField(this,"lockingPromise",Promise.resolve()),__publicField(this,"locks",0),__publicField(this,"name",""),__publicField(this,"lockId"),__publicField(this,"closeReason"),this.lockId=lockId++,e&&(this.name=e),logger$4.info(`lock-${this.name}-${this.lockId}`,"is created.")}get isLocked(){return this.locks>0}lock(){let e;this.locks+=1,logger$4.info(`lock-${this.name}-${this.lockId}`,`locked, current queue ${this.locks}.`);const t=new Promise((t=>{e=()=>{this.locks-=1,logger$4.info(`lock-${this.name}-${this.lockId}`,`unlocked, current queue ${this.locks}.`),t()}})),i=this.lockingPromise.then((()=>e));return this.lockingPromise=this.lockingPromise.then((()=>t)),i}}var DC_MESSAGE_DIRECTION=(e=>(e[e.SEND=0]="SEND",e[e.FEEDBACK=1]="FEEDBACK",e))(DC_MESSAGE_DIRECTION||{}),DC_MESSAGE_FUNCTION_TYPE=(e=>(e[e.P2P=0]="P2P",e[e.SIGNAL=1]="SIGNAL",e[e.BROADCAST=2]="BROADCAST",e[e.BUSINESS_SERVER=3]="BUSINESS_SERVER",e))(DC_MESSAGE_FUNCTION_TYPE||{}),USER_MESSAGE_SEND_RESULT=(e=>(e[e.SUCCESS=0]="SUCCESS",e[e.TIMEOUT=1]="TIMEOUT",e[e.BROKEN=2]="BROKEN",e[e.NO_RECEIVER=3]="NO_RECEIVER",e[e.NO_RELAYPATH=4]="NO_RELAYPATH",e[e.EXCEED_QPS=5]="EXCEED_QPS",e[e.SEND_TO_SERVER_ERROR=17]="SEND_TO_SERVER_ERROR",e[e.SERVER_RESPONSE_ERROR=18]="SERVER_RESPONSE_ERROR",e[e.NOT_JOIN=100]="NOT_JOIN",e[e.NOT_LOGIN=105]="NOT_LOGIN",e[e.SERVER_PARAMS_NOTSET=106]="SERVER_PARAMS_NOTSET",e[e.UNKNOWN=1e3]="UNKNOWN",e))(USER_MESSAGE_SEND_RESULT||{});const USER_MESSAGE_SEND_RESULT_EXPLAIN={0:[0,"success"],1:[ErrorCode.USER_MESSAGE_TIMEOUT,"timeout, failed to send."],2:[ErrorCode.USER_MESSAGE_BROKEN,"dataChannel broken, failed to send."],3:[ErrorCode.USER_MESSAGE_NO_RECEIVER,"cannot find the receiver."],4:[ErrorCode.USER_MESSAGE_NO_RECEIVER,"cannot find relay path."],5:[ErrorCode.USER_MESSAGE_EXCEED_QPS,"cannot find relay path."],17:[ErrorCode.USER_MESSAGE_SEND_TO_SERVER_ERROR,"failed to send to business server."],18:[ErrorCode.USER_MESSAGE_SERVER_RESPONSE_ERROR,"business server response error."],100:[ErrorCode.USER_MESSAGE_NOT_JOIN,"not join room"],105:[ErrorCode.USER_MESSAGE_NOT_LOGIN,"not login."],106:[ErrorCode.USER_MESSAGE_SERVER_PARAMS_NOTSET,"server param is not set."],1e3:[ErrorCode.USER_MESSAGE_UNKNOWN,"unknown."]},noPrintSignaling=[],noAckSignaling=[SignalEvent.ENGINE_CONTROL_MESSAGE];var SIGNALING_FUNCTION_TYPE=(e=>(e[e.C2S=0]="C2S",e[e.C2C=1]="C2C",e[e.C2GW=2]="C2GW",e[e.C2CDirect=3]="C2CDirect",e[e.C2RTM=4]="C2RTM",e))(SIGNALING_FUNCTION_TYPE||{});const DATA_CHANNEL_MESSAGE_TIMEOUT=6e4,P2P_MESSAGE_TIMEOUT=12e3;class DataChannelSignaling extends eventemitter3Exports.EventEmitter{constructor(e,t,i){super(),__publicField(this,"_singlingCache",new Map),__publicField(this,"_p2pCache",new Map),__publicField(this,"_rttIds",{}),__publicField(this,"_p2pMessageId",new MessageId),__publicField(this,"_clearDataChannelListener"),__publicField(this,"_monitor"),__publicField(this,"logger"),this.id=e,this._dataChannel=t,this.connectionIds=i,this._clearDataChannelListener=this._handleHandler(),this._monitor=getMonitor(e),this.logger=new Logger$1("DataChannelSignaling",3,e)}destroy(){this._clearDataChannelListener(),delete this._dataChannel,this._singlingCache.forEach(((e,t)=>{e.error(new SDKError(ErrorCode.OPERATION_CANCEL,"disconnect")),this._singlingCache.delete(t)})),this._singlingCache.clear(),this._p2pCache.clear(),this._rttIds={}}sendSignaling(e,t,i,r=6e4){return new Promise(((o,s)=>{var n;const a=this._genHeader(i);a.id=createRandomId();const d=a.id.join("-"),c={error_code:0,message:JSON.stringify(t),signaling_event:`call-${e}`,signaling_type:"Send",stream_id:t.streamId,stream_user_id:t.streamUserId,direction:"up",event_session_id:d,...this.connectionIds};null==(n=this._monitor)||n.report("rtc_signaling",c);const l="customMessage"===e;l&&RTSMsgReportor.samplingOne2ManyMsg(this.id,Number(a.id.join("")),t);const u=setTimeout((()=>{this._singlingCache.delete(d),s(new SDKError(ErrorCode.TIME_OUT,`${e} message time out`)),l&&RTSMsgReportor.updateOne2ManyMsgAck(this.id,t,999)}),r);this._singlingCache.set(d,{start:getServerNow(),signalingType:e,success:e=>{clearTimeout(u),o(e),l&&RTSMsgReportor.updateOne2ManyMsgAck(this.id,t,0)},error:e=>{clearTimeout(u),s(e),l&&RTSMsgReportor.updateOne2ManyMsgAck(this.id,t,e.code)},id:d}),this.logger.info("Signal",`>>>>>> [${e}{${a.functionType}}][${d}]`,t),this._sendMessage(e,a,t)}))}sendPingSignaling(){return this.sendSignaling("CheckConnectivity",{ts:Date.now()},{functionType:2})}async sendP2PMessage({msg:e,...t},i){const r=e instanceof ArrayBuffer;return this._sendP2PMessage(RTSMsgReportor.samplingP2PMsg(this.id,{ver:1,id:this._p2pMessageId.getMessageId(),time:Date.now(),dir:DC_MESSAGE_DIRECTION.SEND,type:DC_MESSAGE_FUNCTION_TYPE.P2P,err:USER_MESSAGE_SEND_RESULT.SUCCESS,...t,binary:r,msg:r?await Utils.ab2b64str(e):e}),i)}_sendP2PMessage(e,t={}){const i=this._genHeader({needAck:!0,functionType:1,...t,id:createRandomId()});return isRttMessage(e.msg)?this._rttIds[e.id]=e.id:e.dir===DC_MESSAGE_DIRECTION.SEND&&this.logger.info(`_sendP2PMessage [DC Signaling p2p{${i.functionType}} >>]`,JSON.stringify(e)),new Promise(((t,r)=>{if(e.dir===DC_MESSAGE_DIRECTION.SEND){const i=setTimeout((()=>{this._p2pCache.delete(e.id),r(new SDKError(ErrorCode.USER_MESSAGE_TIMEOUT,"P2P message timeout")),RTSMsgReportor.updateP2PMsgAck(this.id,e,999)}),12e3);this._p2pCache.set(e.id,{success:(r,o)=>{clearTimeout(i),t(o),RTSMsgReportor.updateP2PMsgAck(this.id,e,0)},error:t=>{clearTimeout(i),RTSMsgReportor.updateP2PMsgAck(this.id,e,t.err);const[o,s]=USER_MESSAGE_SEND_RESULT_EXPLAIN[t.err]||[ErrorCode.USER_MESSAGE_UNKNOWN,`err: ${t.err}, msg: ${t.msg}`];r({err:t.err,code:o,message:t.msg||s})}})}try{this._sendMessage("p2p",i,e)}catch(e){throw e.code===ErrorCode.NOT_CONNECTED_YET&&(e.code=ErrorCode.USER_MESSAGE_BROKEN),e}}))}_sendMessage(e,t,i){var r;if(!this._dataChannel||"open"!==this._dataChannel.readyState)throw new SDKError(ErrorCode.NOT_CONNECTED_YET,"DataChannel not open");const o=getParameter("SIGNAL_COMPRESSION")||t.zip,s=t.version+(Number(o)<<4)+(Number(t.encrypt)<<5),n=Number(t.needAck)+(Number(t.direction)<<1)+(Number(t.functionType)<<2)+(Number(t.binary)<<6),a=Utils.str2ab(JSON.stringify([e,i])),d=concatenate(Uint8Array,[s,n,...t.id||[]],o||t.zip?pako$1.deflate(new Uint8Array(a)):new Uint8Array(a));try{this._dataChannel.send(d.buffer)}catch(e){throw null==(r=this._monitor)||r.report("rtc_error",{message:`datachannel send error: ${e.message}`,error_code:RtcErrorCode.DC_SEND_ERROR}),e}"p2p"===e?RTSMsgReportor.updateP2PMsgReq(this.id,i,d.buffer.byteLength):"customMessage"===e&&RTSMsgReportor.updateOne2ManyMsgReq(this.id,i,d.buffer.byteLength)}_dispartData(e){const t=new Uint8Array(e);let i=0;const r=t[i++],o=t[i++],s={version:15&r,zip:!(16&~r),encrypt:!(32&~r),needAck:!(1&~o),direction:(2&o)>>1,functionType:(60&o)>>2,binary:!(64&~o)};if(s.needAck||1===s.direction){for(;i<=6;i++)if(!isByteId(t[i])){i++;break}s.id=Array.from(t.slice(2,i))}return{header:s,data:t.slice(i)}}_feedbackSignaling(e,t,i){const r=this._genHeader({needAck:!0,direction:1,id:e.split("-").map((e=>Number(e)))});noPrintSignaling.includes(t)||this.logger.info("Signal",`>>>>>> [${t}-res][${e}]`),this._sendMessage(`${t}-res`,r,i)}async _handleMessage(e){var t;const i=Date.now(),{byteLength:r}=e,o=this._dispartData(e);let{data:s}=o;const{header:n}=o;if(n.zip){const e=new pako$1.Inflate;e.push(s,!0),s=e.result}const a=Utils.ab2str(s);let d=[];try{d=JSON.parse(a)}catch(e){return void(e instanceof Error&&(null==(t=this._monitor)||t.report("rtc_signaling_msg_error",{error_code:-1,message:e.message,reason:"message parse failed",...this.connectionIds})))}switch(n.functionType){case 0:case 4:this.C2S(n,d,a,r,i);break;case 1:this.C2C(d,r,i);break;case 2:this.C2GW(n,d,a)}}async C2S(e,t,i,r,o){var s,n;const a=(null==(s=e.id)?void 0:s.join("-"))||"";if(1===e.direction)this._handleAckMessage(a,t[0]||{},i,e.functionType);else if(Array.isArray(t)){const s=t[0];t=t[1],noPrintSignaling.includes(s)||this.logger.info("Signal",`<<<<<< ${s}{${e.functionType}}`,t,a),noAckSignaling.includes(s)||this._feedbackSignaling(a,s,s===SignalEvent.ON_CUSTOM_MESSAGE?{...t,message:""}:""),t.binary&&"string"==typeof t.message&&(t.message=await Utils.b64str2ab(t.message,this._monitor));const d=Date.now();this.emit(s,{...t}),s===SignalEvent.ON_CUSTOM_MESSAGE&&RTSMsgReportor.reportOne2ManyMsgRecv(this.id,t,{msg_size:r,recv_msg_ts:o,fwd_msg_ts:d}),null==(n=this._monitor)||n.report("rtc_signaling",{error_code:0,message:i,signaling_event:`on-${s}`,signaling_type:"Recv",stream_id:t.streamId,stream_user_id:t.clientId,direction:"down",...this.connectionIds})}}async C2C(e,t,i){Array.isArray(e)&&(e=e[1]);const r=null==e?void 0:e.id;switch(this._rttIds[r]||(null==e?void 0:e.dir)===DC_MESSAGE_DIRECTION.FEEDBACK||isRttMessage(null==e?void 0:e.msg)?delete this._rttIds[r]:this.logger.info("Signal","<<<<<< p2p response",e),e.dir){case DC_MESSAGE_DIRECTION.SEND:const r=Date.now();if(!isRttMessage(null==e?void 0:e.msg)){const{binary:t,msg:i,room:r,to:o,from:s}=e,n=""===r?t?SignalEvent.USER_BINARY_MESSAGE_RECEIVED_OUTSIDE_ROOM:SignalEvent.USER_MESSAGE_RECEIVED_OUTSIDE_ROOM:t?SignalEvent.USER_BINARY_MESSAGE_RECEIVED:SignalEvent.USER_MESSAGE_RECEIVED;o?this.emit(n,{...e,msg:t?await Utils.b64str2ab(i,this._monitor):i}):this.emit(SignalEvent.ON_CUSTOM_MESSAGE,{clientId:s,binary:t,message:t?await Utils.b64str2ab(i,this._monitor):i})}this._sendP2PMessage({...e,dir:DC_MESSAGE_DIRECTION.FEEDBACK,msg:""}),RTSMsgReportor.reportP2PMsgRecv(this.id,e,{msg_size:t,recv_msg_ts:i,fwd_msg_ts:r});break;case DC_MESSAGE_DIRECTION.FEEDBACK:this._handleP2PMsgFeedback(e)}}C2GW(e,t,i){var r,o;if(1===e.direction){const o=(null==(r=e.id)?void 0:r.join("-"))||"";this._handleAckMessage(o,t[0]||{},i,e.functionType)}else{const[r,s={}]=t;if("RXMediaMsg"===r){const{type:e,data:t}=s;switch(null==(o=this._monitor)||o.report("rtc_signaling",{error_code:0,message:i,signaling_event:`on-${e}`,signaling_type:"Recv",stream_id:"",stream_user_id:"",direction:"down",...this.connectionIds}),e){case"RSCP":try{const i=JSON.parse(t);Array.isArray(i)&&this.emit(e,i)}catch(e){}break;case"RTT":try{const i=JSON.parse(t);i.length&&this.emit(e,i[0])}catch(e){}break;case"SSC":try{const i=JSON.parse(t);i.length&&(this.logger.info("Signal",`<<<<<< ${e}`,i),this.emit(e,i[0]))}catch(e){}}}else"engineControlMessage"===r&&this.C2S(e,t,i,0,0)}}_handleHandler(){const e=e=>{this.logger.warn("_handleHandler","dataChannel close",e)},t=e=>{this.logger.error("_handleHandler","dataChannel error",e)},i=e=>{this._handleMessage(e.data)};return this._dataChannel.addEventListener("close",e),this._dataChannel.addEventListener("error",t),this._dataChannel.addEventListener("message",i),()=>{const r=this._dataChannel;null==r||r.removeEventListener("close",e),null==r||r.removeEventListener("error",t),null==r||r.removeEventListener("message",i)}}_genHeader(e={}){return{version:2,zip:!1,encrypt:!1,needAck:!0,direction:0,functionType:0,binary:!1,...e}}_handleAckMessage(e,t,i,r){var o;const s=this._singlingCache.get(e);s&&(this._singlingCache.delete(e),200===t.code?s.success(t):s.error(t),this.logger.info("Signal",`<<<<<< [${s.signalingType}{${r}}-ack] ${e}`,t));const n={error_code:0,message:i,signaling_event:null==s?void 0:s.signalingType,signaling_type:"Ack",stream_id:"",stream_user_id:"",direction:"down",elapse:s?getServerNow()-s.start:0,...this.connectionIds};(null==s?void 0:s.id)&&(n.event_session_id=s.id),null==(o=this._monitor)||o.report("rtc_signaling",n)}_handleP2PMsgFeedback(e){const t=this._p2pCache.get(e.id);t&&(this._p2pCache.delete(e.id),e.err===USER_MESSAGE_SEND_RESULT.SUCCESS?t.success(e.id,e):t.error(e))}}class RoomContext{constructor(e,t){__publicField(this,"roomId"),__publicField(this,"userInfo"),__publicField(this,"userId"),__publicField(this,"sessionId",genUuid$1()),__publicField(this,"token"),__publicField(this,"rtcVid"),__publicField(this,"joinPromise"),__publicField(this,"startJoinTimestamp"),__publicField(this,"_liveControlMessage"),__publicField(this,"_userStreamMap",new Map),__publicField(this,"_roomConfig",{isAutoPublish:!0,isAutoSubscribeAudio:!0,isAutoSubscribeVideo:!0,roomProfileType:RoomProfileType.communication}),__publicField(this,"_vendorConfig",{enableMultiVendor:!1,vendorCode:0}),__publicField(this,"_roomAttr",{multiChatMode:!1,bigRoomMode:!1}),__publicField(this,"_tokenPublishPrivilegeExpired",!1),__publicField(this,"_tokenSubscribePrivilegeExpired",!1),__publicField(this,"_streamQueueMap",new Map),__publicField(this,"_monitor"),this._ctx=t,this.roomId=e.roomId,this.userInfo=e.userInfo,this.userId=e.userInfo.userId,this.token=e.token,this._monitor=getMonitor(t.id)}async checkJoinRoom(){await this.joinPromise}get vendorConfig(){return this._vendorConfig}setVendorConfig(e){this._vendorConfig=e}updateRoomAttributes(e){this._roomAttr={...this._roomAttr,...e}}setLiveControlMessage(e){this._liveControlMessage=e}getLiveControlMessage(){return this._liveControlMessage}isMultiChatMode(){return this._roomAttr.multiChatMode}updateRoomConfig(e){return this._roomConfig=assignIn(this._roomConfig,e),this._roomConfig}get isAutoPublish(){return!this.isRTSOnlyRoom()&&this._roomConfig.isAutoPublish}get isAutoSubscribeAudio(){return!this.isRTSOnlyRoom()&&this._roomConfig.isAutoSubscribeAudio}get isAutoSubscribeVideo(){return!this.isRTSOnlyRoom()&&this._roomConfig.isAutoSubscribeVideo}get remoteVideoConfig(){return this._roomConfig.remoteVideoConfig}get roomProfileType(){return this._roomConfig.roomProfileType||RoomProfileType.communication}isRTSOnlyRoom(){return this._roomConfig.roomMode===RoomMode.ROOM_MODE_RTS_ONLY}get rtsOnlySignalHeader(){return this.isRTSOnlyRoom()?{functionType:SIGNALING_FUNCTION_TYPE.C2RTM}:void 0}updateUserPubInfo(e){const t=this._userStreamMap.get(e.clientId)||{};e.screen?(t.screenAudio=e.attributes.audiostream,t.screenVideo=e.attributes.videostream):(t.audio=e.attributes.audiostream,t.video=e.attributes.videostream),this._userStreamMap.set(e.clientId,t)}getUserPubInfo(e){return{audio:!1,video:!1,screenAudio:!1,screenVideo:!1,...this._userStreamMap.get(e)||{}}}resetUserPubInfo(){this._userStreamMap.clear()}get tokenPublishPrivilegeExpired(){return this._tokenPublishPrivilegeExpired}get tokenSubscribePrivilegeExpired(){return this._tokenSubscribePrivilegeExpired}setTokenPublishPrivilegeExpired(e){this._tokenPublishPrivilegeExpired=e}setTokenSubscribePrivilegeExpired(e){this._tokenSubscribePrivilegeExpired=e}getStayRoomDuration(){return this.startJoinTimestamp?getServerNow()-this.startJoinTimestamp:0}getStreamQueueLock(e){let t=this._streamQueueMap.get(e);return t||(t=new PromiseLock2(e),this._streamQueueMap.set(e,t)),t}report(e,t,i){var r;null==(r=this._monitor)||r.report(e,{room_id:this.roomId,user_id:this.userId,rtc_session_id:this.sessionId,rtc_vid:this.rtcVid,...t},i)}}const WAIT_TRACK_TIMEOUT=6e4,logRemoteStream=(e,t,i)=>{i.info(e,"userId: %o, subAudio: %o, subVideo: %o, audioMid: %o, videoMid: %o, sequenceId: %o",t.userId,t.subAudio,t.subVideo,t.audioMid,t.videoMid,t.sequenceId)};function checkRoomState(e,t,i){const r=i.value;return i.value=async function(...e){if(!this._ctx.signalingManager.isConnected())throw new SDKError(ErrorCode.NOT_CONNECTED_YET,`error in ${t}: try again after connect`);try{await(this._roomConf||this.config).checkJoinRoom()}catch(e){throw new SDKError(ErrorCode.JOIN_ROOM_FAILED,`error in ${t}: try again after joined`)}return r.apply(this,e)},i}const enableStreamQueue=!0;function streamQueue(e,t,i){const r=i.value;return i.value=async function(...e){const i=this._roomConf,o=this._logger,s=getStreamIdentification(e[0]);if(!s)return null==r?void 0:r.apply(this,e);o.info("streamQueue","lock stream %o, task %o",s.slice(-5),t);const n=await i.getStreamQueueLock(s).lock();try{return await(null==r?void 0:r.apply(this,e))}finally{o.info("streamQueue","unlock stream %o, task %o",s.slice(-5),t),n()}},i}function getStreamIdentification(e){return e instanceof LocalStream?e.id:null==e?void 0:e.streamId}var __defProp$9=Object.defineProperty,__getOwnPropDesc$9=Object.getOwnPropertyDescriptor,__decorateClass$9=(e,t,i,r)=>{for(var o,s=r>1?void 0:r?__getOwnPropDesc$9(t,i):t,n=e.length-1;n>=0;n--)(o=e[n])&&(s=(r?o(t,i,s):o(s))||s);return r&&s&&__defProp$9(t,i,s),s};class ForwardStreamManager extends EnhancedEventEmitter{constructor(e,t){super(),__publicField(this,"_forwardDstRooms",new Map),__publicField(this,"forwardStreamState","stopped"),this._ctx=e,this._roomConf=t}async startForwardStream2Rooms(e){if("running"===this.forwardStreamState||"paused"===this.forwardStreamState)throw new SDKError(ErrorCode.UNEXPECTED_INVOKE_FORWARD_STREAM,`should not invoke startForwardStreamToRooms in state: ${this.forwardStreamState}`);const t=await this._sendForwardStreamSignaling("start",this._roomConf.roomId,e);this._updateDstRooms(e,t);const i=this._transformForwardStreamResult(t);return this.forwardStreamState="running",i}async updateForwardStream2Rooms(e){if("stopped"===this.forwardStreamState)throw new SDKError(ErrorCode.UNEXPECTED_INVOKE_FORWARD_STREAM,`should not invoke updateForwardStreamToRooms in state: ${this.forwardStreamState}`);let t=this._mockForwardStreamResult(e);"running"===this.forwardStreamState&&(t=await this._sendForwardStreamSignaling("update",this._roomConf.roomId,e)),this._updateDstRooms(e,t);return this._transformForwardStreamResult(t)}async stopForwardStream2Rooms(){if("stopped"===this.forwardStreamState)throw new SDKError(ErrorCode.UNEXPECTED_INVOKE_FORWARD_STREAM,`should not invoke stopForwardStreamToRooms in state: ${this.forwardStreamState}`);let e=this._mockForwardStreamResult([]);if("running"===this.forwardStreamState&&(e=await this._sendForwardStreamSignaling("stop",this._roomConf.roomId)),this._updateDstRooms([],e),[...this._forwardDstRooms.keys()].length>0)throw new SDKError(ErrorCode.UNEXPECTED_ERROR,`stopforwardstream failed: ${JSON.stringify(e)}`);const t=this._transformForwardStreamResult(e);return this.forwardStreamState="stopped",t}async pauseForwardStream2AllRooms(){if("paused"===this.forwardStreamState||"stopped"===this.forwardStreamState)throw new SDKError(ErrorCode.UNEXPECTED_INVOKE_FORWARD_STREAM,`should not invoke pauseForwardStreamToAllRooms in state: ${this.forwardStreamState}`);const e=await this._sendForwardStreamSignaling("stop",this._roomConf.roomId),t=this._transformForwardStreamResult(e);return this.forwardStreamState="paused",t}async resumeForwardStream2AllRooms(e=!1){if(!e&&["running","stopped"].includes(this.forwardStreamState))throw new SDKError(ErrorCode.UNEXPECTED_INVOKE_FORWARD_STREAM,`should not invoke resumeForwardStreamToAllRooms in state: ${this.forwardStreamState}`);const t=this._getDstRooms(),i=await this._sendForwardStreamSignaling("start",this._roomConf.roomId,t);this._updateDstRooms(t,i);const r=this._transformForwardStreamResult(i);return this.forwardStreamState="running",r}resumeFromReconnect(){"running"===this.forwardStreamState&&this.resumeForwardStream2AllRooms(!0).then((e=>{e.forEach((e=>{e.state===ForwardStreamState.FORWARD_STREAM_STATE_FAILURE&&this.safeEmit(RoomEvent.ON_FORWARD_STREAM_ERROR,e)}))}))}onForwardDstRoomUserKick(e){const t=[{dstRoomId:e.dstRoomId,code:200,forwardStreamType:"stop"}];this._updateDstRooms([],t),this.safeEmit(RoomEvent.ON_FORWARD_STREAM_ERROR,{roomId:e.dstRoomId,state:ForwardStreamState.FORWARD_STREAM_STATE_FAILURE,error:ForwardStreamError.FORWARD_STREAM_ERROR_REMOTE_KICKED})}destoy(){super.removeAllListeners(),this._forwardDstRooms.clear(),this.forwardStreamState="stopped"}_mockForwardStreamResult(e){const t=[];return this._forwardDstRooms.forEach(((e,i)=>{t.push({dstRoomId:i,forwardStreamType:"stop",code:200})})),e.forEach((e=>{const i=t.findIndex((t=>t.dstRoomId===e.roomId));-1===i?t.push({dstRoomId:e.roomId,forwardStreamType:"start",code:e.roomId===this._roomConf.roomId?400:200}):t[i].forwardStreamType="update"})),t}_transformForwardStreamResult(e){e||(e=[]);const t=[];for(const{dstRoomId:i,code:r}of e){const e={roomId:i,state:ForwardStreamState.FORWARD_STREAM_STATE_SUCCESS,error:ForwardStreamError.FORWARD_STREAM_ERROR_OK};200===r||(400===r?(e.state=ForwardStreamState.FORWARD_STREAM_STATE_FAILURE,e.error=ForwardStreamError.FORWARD_STREAM_ERROR_REMOTE_KICKED):r>=700&&r<800?(e.state=ForwardStreamState.FORWARD_STREAM_STATE_FAILURE,e.error=ForwardStreamError.FORWARD_STREAM_ERROR_INVALID_TOKEN):(e.state=ForwardStreamState.FORWARD_STREAM_STATE_FAILURE,e.error=ForwardStreamError.FORWARD_STREAM_ERROR_RESPONSE)),t.push(e)}return t}_updateDstRooms(e,t=[]){0===t.length&&this._forwardDstRooms.clear(),t.forEach((({dstRoomId:t,code:i,forwardStreamType:r})=>{if(200===i)if("stop"===r)this._forwardDstRooms.delete(t);else{const i=e.find((e=>e.roomId===t));if(!i&&!this._forwardDstRooms.has(t))throw new SDKError(ErrorCode.UNEXPECTED_ERROR,`unknow roomid ${t} in signaling return`);let r=this._forwardDstRooms.get(t)??{token:void 0};r=Object.assign(r,i),this._forwardDstRooms.set(t,r)}else this._forwardDstRooms.has(t)&&this._forwardDstRooms.delete(t)}))}_getDstRooms(){const e=[];return this._forwardDstRooms.forEach(((t,i)=>{e.push({roomId:i,token:t.token})})),e}async _sendForwardStreamSignaling(e,t,i){var r,o;const s=`${genEventSessionId()}`;if("stop"!==e){const e=i.map((e=>e.roomId));this._roomConf.report("rtc_forward_stream",{type:"begin",dst_rooms:`{ ${e.map((e=>`"${e}"`)).join(",")} }`,event_session_id:s})}const n={forwardStreamType:e,roomId:t};("start"===e||"update"===e)&&(n.dstRoomInfos=null==i?void 0:i.map((e=>({dstRoomId:e.roomId,dstToken:Utils.token2auth(this._ctx.appId,e.roomId,this._roomConf.userId,e.token)}))));const a=await this._ctx.signalingManager.sendSignaling("forwardStream",n),d=[];if(200!==(null==a?void 0:a.code))throw"stop"!==e&&(null==i||i.forEach((e=>{d.push({dst_room_id:e.roomId,result:`server error ${null==a?void 0:a.code}`})})),this._roomConf.report("rtc_forward_stream",{type:"end",dst_rooms:JSON.stringify(d),event_session_id:s})),new SDKError(ErrorCode.UNEXPECTED_ERROR,`server side internal error, error code: ${a}`);return"stop"!==e&&(null==(r=a.forwardStreamResults)||r.forEach((e=>{d.push({dst_room_id:e.dstRoomId,result:"dst room lost"})})),null==(o=a.forwardStreamResults)||o.forEach((e=>{const t=d.find((t=>t.dst_room_id===e.dstRoomId));t&&(200===e.code?"update"===e.forwardStreamType?t.result="update":t.result="success":t.result=`server error ${e.code}`)})),this._roomConf.report("rtc_forward_stream",{type:"end",dst_rooms:JSON.stringify(d),event_session_id:s})),a.forwardStreamResults}}__decorateClass$9([checkRoomState],ForwardStreamManager.prototype,"startForwardStream2Rooms",1),__decorateClass$9([checkRoomState],ForwardStreamManager.prototype,"updateForwardStream2Rooms",1),__decorateClass$9([checkRoomState],ForwardStreamManager.prototype,"stopForwardStream2Rooms",1),__decorateClass$9([checkRoomState],ForwardStreamManager.prototype,"pauseForwardStream2AllRooms",1),__decorateClass$9([checkRoomState],ForwardStreamManager.prototype,"resumeForwardStream2AllRooms",1);const simulcastFormats=[{maxLayers:3,totalPixels:2073600},{maxLayers:3,totalPixels:921600},{maxLayers:3,totalPixels:518400},{maxLayers:2,totalPixels:230400},{maxLayers:2,totalPixels:129600},{maxLayers:1,totalPixels:57600},{maxLayers:1,totalPixels:0}],getSimulcastLayers=(e,t)=>{const i=simulcastFormats.findIndex((i=>e*t>=i.totalPixels)),r=e*t;if(0===i)return simulcastFormats[i].maxLayers;const o=simulcastFormats[i-1].totalPixels;return(o-r)/(o-simulcastFormats[i].totalPixels)<.1?simulcastFormats[i-1].maxLayers:simulcastFormats[i].maxLayers};function calculateKbps(e,t,i){var r;const o=e?null==(r=i.find((t=>t.rid===e)))?void 0:r.maxkbps:i[0].maxkbps;return Math.min(o??Number.POSITIVE_INFINITY,t)}const getSubLayerByVideoConfig=(e,t)=>{var i,r;let o=0,s=-1;const{videoDescriptions:n,subVideoDescriptions:a}=(null==t?void 0:t.attributes)||{},d=Array.isArray(a)?a:n;let c=-1;const l=e.width*e.height;for(let e=0;e<(null==d?void 0:d.length);e++)if(l>=(null==(i=d[e])?void 0:i.width)*(null==(r=d[e])?void 0:r.height)){c=e;break}let u=d[0];if(-1===c)c=d.length-1,u=d[c];else if(0!==c){const e=d[c-1].width*d[c-1].height,t=(e-l)/(e-d[c].width*d[c].height);u=t<.1?d[c-1]:d[c],c=t<.1?c-1:c}return s=(null==u?void 0:u.sub_index)??-1,o=(null==u?void 0:u.video_index)??c,{spatialLayer:o,spatialSubLayer:s}},videoCaptureConf2EncodeConf=e=>({width:constraints2number(e.width),height:constraints2number(e.height),frameRate:constraints2number(e.frameRate),maxKbps:e.maxKbps}),getResolution=({width:e,height:t})=>constraints2number(e)*constraints2number(t),checkVideoConfigQuotient=(e,t)=>{const i=constraints2number(e.width)/constraints2number(t.width)||1,r=constraints2number(e.height)/constraints2number(t.height)||1;Math.floor(i)===i&&Math.floor(r)===r||warnDevelopers("setLocalSimulcastMode: The resolution setting needs to be an integer multiple")};class AudioProfileManager{constructor(e){__publicField(this,"_roomId"),__publicField(this,"_constraints",{}),__publicField(this,"_profile"),__publicField(this,"_customMaxBitrate",0),this._appId=e}setRoomId(e){this._roomId=e}setAudioProfile(e){this._profile=e,this._customMaxBitrate=0}get customMaxBitrate(){return this._customMaxBitrate}setCustomMaxBitrate(e){const{audio_encode:t}=sdkCache.getEngineWebConfig(this._appId,this._roomId||"");this._customMaxBitrate=(null==t?void 0:t.bitrate)?0:1e3*e}getOpusConfigStr(e=""){const{audio_encode:t}=sdkCache.getEngineWebConfig(this._appId,this._roomId||""),{sampleRate:i,channelCount:r}=this.getConstraints(),o="number"==typeof i?i:null==i?void 0:i.exact,s="number"==typeof r?r:null==r?void 0:r.exact,n={};e.split(";").forEach((e=>{const[t,i]=e.split("=");t&&i&&(n[t]=i)}));const a=(null==t?void 0:t.bitrate)||this._customMaxBitrate||this._getConfigByAudioProfile().bitrate;a&&(n.maxaveragebitrate=a);const d=(null==t?void 0:t.enc_sample_rate)||o;d&&(n["sprop-maxcapturerate"]=d);const c=(null==t?void 0:t.playback_rate)||o;return c&&(n.maxplaybackrate=c),(s&&s>1||(null==t?void 0:t.stereo))&&(n["sprop-stereo"]=1,n.stereo=1),(null==t?void 0:t.dtx)&&(n.usedtx=1),Object.keys(n).map((e=>`${e}=${n[e]}`)).join(";")}updateConstraints(e){this._constraints={...this._constraints,...e}}getConstraints(){const e={...this._constraints},{audio_capture:t}=sdkCache.getEngineWebConfig(this._appId,this._roomId||"");isUndefined(null==t?void 0:t.sample_rate)||(e.sampleRate=t.sample_rate),isUndefined(null==t?void 0:t.channel)||(e.channelCount=t.channel),isUndefined(null==t?void 0:t.agc)||(e.autoGainControl=t.agc),isUndefined(null==t?void 0:t.ans)||(e.noiseSuppression=t.ans),isUndefined(null==t?void 0:t.aec)||(e.echoCancellation=t.aec);const{sampleRate:i,channel:r}=this._getConfigByAudioProfile();return isUndefined(e.sampleRate)&&!isUndefined(i)&&(e.sampleRate=i),isUndefined(e.channelCount)&&!isUndefined(r)&&(e.channelCount=r),e}_getConfigByAudioProfile(){const e={};switch(this._profile){case AudioProfileType.fluent:e.sampleRate=16e3,e.bitrate=24e3;break;case AudioProfileType.standard:e.sampleRate=48e3,e.bitrate=48e3;break;case AudioProfileType.hd:e.sampleRate=48e3,e.bitrate=128e3,e.channel=2;break;case AudioProfileType.standardStereo:e.sampleRate=48e3,e.bitrate=8e4,e.channel=2;break;case AudioProfileType.hdMono:e.sampleRate=48e3,e.bitrate=128e3}return e}}const defaultConfig={start_interval:100,multiplier:2,max_interval:3e4};class RetryLimiter{constructor(){__publicField(this,"_times",0),__publicField(this,"_config",defaultConfig),__publicField(this,"initTs",getServerNow())}getRetryDelay(){return Math.min(this._config.max_interval,Math.pow(this._config.multiplier,this._times++)*this._config.start_interval)}setConfig(e){this._config=e}reset(){this._times=0}}class DecisionConfig{constructor(e){__publicField(this,"_logger"),__publicField(this,"_monitor"),this._ctx=e;const t=sdkCache.getServerConfig(this._ctx.appId);this._logger=new Logger$1("DecisionConfig",1,this._ctx.id),this._monitor=getMonitor(this._ctx.id),setTimeout((()=>{this.updateConfig(t,!0)}),0)}updateConfig(e,t){!t&&sdkCache.setServerConfig(this._ctx.appId,e),e.rts_report&&RTSMsgReportor.setConfig(e.rts_report),this._ctx.joinRoomConfig.setServerConfig(e.web_join_room),this._setRtsConfig(e.rts_config),this._setRtsQpsConfig(e.rts_qps),this._preConnect(e),this._getServerConfigExecutor(e,t)}_setRtsConfig(e){(null==e?void 0:e.rts_mode)&&e.rts_mode!==this._ctx.rtsMode&&(this._logger.print("_setRtsConfig","setRtsMode to %o",e.rts_mode),this._ctx.setRTSMode(e.rts_mode===RTS_MODE.NORMAL_MODE?RTS_MODE.NORMAL_MODE:RTS_MODE.LIMIT_MODE))}_setRtsQpsConfig(e){this._logger.print("_setRtsQpsConfig",JSON.stringify(e)),this._ctx.setRtsQpsConf(e),Object.keys(this._ctx.rtsLimiter).length>0&&reportRtcInvokeStatus(this._ctx.id,"setRtsQpsConf",JSON.stringify(e))}_getServerConfigExecutor(e,t){var i,r,o,s,n,a,d,c,l,u,_,h,p;const{upload_console_length_cut:m,upload_report_limit:S}=(null==e?void 0:e.web_rtc_config)||{};if(CoreConfig.setParameter("UPLOAD_CONSOLE_ON",!!(null==(i=null==e?void 0:e.web_rtc_config)?void 0:i.upload_console_on)),m&&CoreConfig.setParameter("UPLOAD_CONSOLE_LENGTH_CUT",m),S&&CoreConfig.setParameter("UPLOAD_REPORT_LIMIT",S),CoreConfig.setParameter("ENABLE_REPORT_IDB_BUFFER",!!(null==(r=null==e?void 0:e.web_rtc_config)?void 0:r.enable_report_idb_buffer)),!1===(null==(o=null==e?void 0:e.web_rtc_config)?void 0:o.sdk_codec_negotiation)&&setParameter("SDK_CODEC_NEGOTIATION",!1),void 0!==(null==(s=null==e?void 0:e.web_rtc_config)?void 0:s.ainr_enable_dump)&&setParameter("AINR_ENABLE_DUMP",e.web_rtc_config.ainr_enable_dump),void 0!==(null==(n=null==e?void 0:e.web_rtc_config)?void 0:n.ainr_overload_threshold)&&setParameter("AINR_OVERLOAD_THRESHOLD",e.web_rtc_config.ainr_overload_threshold),void 0!==(null==(a=null==e?void 0:e.web_rtc_config)?void 0:a.ainr_urls))try{setParameter("AINR_URLS",JSON.parse(e.web_rtc_config.ainr_urls))}catch(e){this._logger.warn("_getServerConfigExecutor","parse AINR_URLS error %o",e)}void 0!==(null==(d=null==e?void 0:e.web_rtc_config)?void 0:d.ainr_cache_time)&&setParameter("AINR_CACHE_TIME",e.web_rtc_config.ainr_cache_time),void 0!==(null==(c=null==e?void 0:e.web_rtc_config)?void 0:c.ainr_dump_time)&&setParameter("AINR_DUMP_TIME",e.web_rtc_config.ainr_dump_time),(null==(l=null==e?void 0:e.web_rtc_config)?void 0:l.web_pc_killswitch)&&(this._logger.print("web_pc_killswitch update: ",JSON.stringify(e.web_rtc_config.web_pc_killswitch)),this._ctx.pcKillSwitch={...this._ctx.pcKillSwitch,...e.web_rtc_config.web_pc_killswitch}),"boolean"==typeof(null==(u=null==e?void 0:e.web_rtc_config)?void 0:u.fallback)&&(!1===(null==e?void 0:e.web_rtc_config.fallback)?this._ctx.enableFallbackHandler=!1:Array.isArray(null==(_=null==e?void 0:e.web_rtc_config)?void 0:_.fallback_ua_reg)?this._ctx.enableFallbackHandler=null==e?void 0:e.web_rtc_config.fallback_ua_reg.every((e=>"string"==typeof e&&new RegExp(e).test(navigator.userAgent))):this._ctx.enableFallbackHandler=!1),"boolean"==typeof(null==(h=null==e?void 0:e.web_rtc_config)?void 0:h.standard)&&(!1===(null==e?void 0:e.web_rtc_config.standard)?this._ctx.enableStandardHandler=!1:Array.isArray(null==(p=null==e?void 0:e.web_rtc_config)?void 0:p.standard_ua_reg)?this._ctx.enableStandardHandler=null==e?void 0:e.web_rtc_config.standard_ua_reg.every((e=>"string"==typeof e&&new RegExp(e).test(navigator.userAgent))):this._ctx.enableStandardHandler=!1)}_preConnect(e){var t,i;let r=getParameter("PRE_ICE");"boolean"==typeof(null==(t=null==e?void 0:e.web_rtc_config)?void 0:t.pre_ice)&&(r=e.web_rtc_config.pre_ice),r&&(this._logger.print("preConnect","start pre ice connection."),this._ctx.signalingManager.connect(),null==(i=this._monitor)||i.set({pre_connection:!0}),this._ctx.isPreConnection=!0)}}class IceConfigRequestManager{constructor(e){__publicField(this,"_reconnectTimer"),__publicField(this,"_retryFunc"),__publicField(this,"_abortControllers",[]),__publicField(this,"_monitor"),__publicField(this,"logger"),__publicField(this,"_groupConfigId",genUuid()),__publicField(this,"_retryLimiter",new RetryLimiter),__publicField(this,"_timer"),__publicField(this,"_destroyed",!1),__publicField(this,"_onlineListener",(()=>{this._reconnectTimer&&this._retryFunc&&(clearTimeout(this._reconnectTimer),this._retryFunc())})),__publicField(this,"_decisionConfig"),this._ctx=e,this._monitor=getMonitor(e.id),this.logger=new Logger$1("ICERequest",4,e.id),this._decisionConfig=new DecisionConfig(e),window.addEventListener("online",this._onlineListener)}async getICENode(e){let t;this.logger.info("getICENode","invoke");try{if(t=await this._getAccessWithRetry(e),0===t.length)throw new Error("server return empty nodes.")}catch(e){throw this._reportRtcInvokeStatus("es.join.getNodeFailed",e),new SDKError(ErrorCode.ICE_SERVER_WRONG,`get ICE config failed: ${e.message}`,e)}return this.logger.success("getICENode","success"),this._reportRtcInvokeStatus("es.join.getNodeSuccess",t),t}_getAccessWithRetry(e,t=0){return 0!==t&&this.logger.info("_getAccessWithRetry()","invoke feedbackInfo: %o, 201count: %o",e,t),new Promise(((i,r)=>{this._getAccessNode(e).then((e=>{this._retryLimiter.reset(),i(e)})).catch((o=>{if(this._destroyed)return;if(Array.isArray(o)&&o.length>0){if(o.findIndex((e=>400<=e.code&&e.code<500))>-1)return this._retryLimiter.reset(),r(new Error("HTTP request failed(4xx)"));if(o.every((e=>{var t;return 201===e.code||201===(null==(t=e.error)?void 0:t.code)}))&&t++,3===t)return this._retryLimiter.reset(),r(new Error("HTTP request failed(201)"))}const s=this._retryLimiter.getRetryDelay();this.logger.warn("_getAccessWithRetry()",`_getAccessWithRetry error, will retry after ${s}ms`,o),this._retryFunc=()=>{this._getAccessWithRetry(e,t).then(i).catch(r)},this._reconnectTimer=self.setTimeout(this._retryFunc,s)}))}))}async _getAccessNode(e){return new Promise(((t,i)=>{const r=sdkCache.getAccessNode(this._ctx.appId);if(r){const i=(Array.isArray(r)?r:[r]).map((e=>(e.cache_status=!0,e)));this.logger.info("getAccessNode","use cache node."),t(i),this._timer=setTimeout((()=>{this._getAccessNodeFromServer(e).catch((()=>{})),this._reportRtcInvokeStatus("es.R.node.cache",r),delete this._timer}),0)}else this._getAccessNodeFromServer(e).then(t).catch(i)}))}async _getAccessNodeFromServer(e){const{urls:t,needFallback:i}=this._getAccessUrls();return this.getICEConfigFromServer(t,e).then((e=>{const{nodes:t,decisionConfig:i}=e;return!this._ctx.useCloudProxy&&(null==t?void 0:t.length)>0&&sdkCache.setAccessNode(this._ctx.appId,t,e.ttl||11200),i&&this._decisionConfig.updateConfig(i,!1),e.dispatchDomains&&!this._ctx.useCloudProxy&&sdkCache.setAccessUrls(e.dispatchDomains),t})).catch((t=>{if(i)return this._reportRtcInvokeStatus("es.R.req.fallback",""),sdkCache.clearAccessUrls(),this._getAccessNodeFromServer(e);throw t}))}_getAccessUrls(){let e=sdkCache.getAccessUrls()||[],t=!0;return 0!==e.length?this._reportRtcInvokeStatus("es.R.req.cache.urls",e):(t=!1,e=Config2.ICE_CONFIG_REQUEST_URLS,0!==e.length?this._reportRtcInvokeStatus("es.R.req.external.urls",e):(e=Config2.ICE_CONFIG_REQUEST_URLS_INTERNAL,this._reportRtcInvokeStatus("es.R.req.internal.urls",e))),{urls:e,needFallback:t}}async getICEConfigFromServer(e,t){var i,r;const o={appID:this._ctx.appId,deviceID:sdkCache.getDeviceId(),os:"web",sdkVersion:Config2.VERSION,isOversea:Config2.OVERSEA,expectedAddr:getParameter("EXPECTED_ADDR"),productPlatform:"VolcEngine",enableCloudProxy:this._ctx.useCloudProxy,expectedIDC:this._ctx.expectedIDC,decisionKeys:["rts_report","web_join_room","web_rtc_config","rts_qps","rts_config"],accessParams:JSON.stringify({requireICEUfragV2:!0}),userAgent:null==navigator?void 0:navigator.userAgent};t&&(o.feedbackInfo=t,"ICE_FAILED"!==(null==(r=null==(i=t[0])?void 0:i.feedbackReason)?void 0:r.type)&&delete o.expectedAddr),"AREA_CODE_US_OPCO"===getParameter("AREA_CODE")&&(o.mediaArea=JSON.stringify([{AreaList:["GEO:US_OPCO"],Attribute:"include"}]),o.accessArea=JSON.stringify([{AreaList:["GEO:US_OPCO"],Attribute:"include"}]));const s=e.map((e=>this._httpRequest(e,o)));return promiseAny(s)}async _httpRequest(e,t){var i,r,o,s;const n=genUuid();t.connectSessionID=n;const a=Date.now();null==(i=this._monitor)||i.report("rtc_get_access",{error_code:0,message:JSON.stringify(t),elapse:0,type:"request",host:e,config_id:n,group_config_id:this._groupConfigId});const d=new AbortController;let c;this._abortControllers.push(d);try{try{c=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},mode:"cors",body:JSON.stringify(t),signal:d.signal})}catch(e){throw isNativeFunction(fetch)||null==(r=this._monitor)||r.report("rtc_error",{error_code:RtcErrorCode.Fetch_MODIFY,message:"get access failed, possibly due to modifying the browser's Fetch API."},{origin_error:e}),e}if(this._abortControllers=this._abortControllers.filter((e=>e!==d)),200!==c.status)throw{message:c.statusText,code:c.status};const i=await c.json();if(200!==i.code)throw i;return null==(o=this._monitor)||o.report("rtc_get_access",{error_code:200,message:JSON.stringify(i),elapse:Date.now()-a,type:"response",host:e,config_id:n,group_config_id:this._groupConfigId}),i}catch(t){throw null==(s=this._monitor)||s.report("rtc_get_access",{error_code:Number((null==t?void 0:t.code)||(null==t?void 0:t.server_code)),message:null==t?void 0:t.message,elapse:Date.now()-a,type:"response",host:e,config_id:n,group_config_id:this._groupConfigId},{error:JSON.stringify(t)}),t}}destroy(){this._destroyed=!0,window.removeEventListener("online",this._onlineListener),this._abortControllers.forEach((e=>e.abort("engine destroy"))),this._reconnectTimer&&(window.clearTimeout(this._reconnectTimer),delete this._reconnectTimer),this._timer&&(window.clearTimeout(this._timer),delete this._timer)}_reportRtcInvokeStatus(e,t){var i;null==(i=this._monitor)||i.report("rtc_invoke_status",{sdk_api_name:e,message:t,error_code:0,stream_id:"",elapse:0,group_config_id:this._groupConfigId})}}var lib={},parser$1={},grammar$3={exports:{}},grammar$2=grammar$3.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return null!=e.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),t+=null!=e["network-id"]?" network-id %d":"%v",t+=null!=e["network-cost"]?" network-cost %d":"%v"}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return null!=e.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",t+=null!=e.rateNumerator?" rate=%s":"",t+=null!=e.rateDenominator?"/%s":""}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(grammar$2).forEach((function(e){grammar$2[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))}));var grammarExports=grammar$3.exports;!function(e){var t=function(e){return String(Number(e))===e?Number(e):e},i=function(e,i,r){var o=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:o&&!i[e.name]&&(i[e.name]={});var s=e.push?{}:o?i[e.name]:i;!function(e,i,r,o){if(o&&!r)i[o]=t(e[1]);else for(var s=0;s<r.length;s+=1)null!=e[s+1]&&(i[r[s]]=t(e[s+1]))}(r.match(e.reg),s,e.names,e.name),e.push&&i[e.push].push(s)},r=grammarExports,o=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},s=[],n=t;return e.split(/(\r\n|\r|\n)/).filter(o).forEach((function(e){var t=e[0],o=e.slice(2);"m"===t&&(s.push({rtp:[],fmtp:[]}),n=s[s.length-1]);for(var a=0;a<(r[t]||[]).length;a+=1){var d=r[t][a];if(d.reg.test(o))return i(d,n,o)}})),t.media=s,t};var s=function(e,i){var r=i.split(/=(.+)/,2);return 2===r.length?e[r[0]]=t(r[1]):1===r.length&&i.length>1&&(e[r[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(s,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var i=[],r=e.split(" ").map(t),o=0;o<r.length;o+=3)i.push({component:r[o],ip:r[o+1],port:r[o+2]});return i},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(s,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var i,r=!1;return"~"!==e[0]?i=t(e):(i=t(e.substring(1,e.length)),r=!0),{scid:i,paused:r}}))}))}}(parser$1);var grammar$1=grammarExports,formatRegExp=/%[sdv%]/g,format=function(e){var t=1,i=arguments,r=i.length;return e.replace(formatRegExp,(function(e){if(t>=r)return e;var o=i[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(o);case"%d":return Number(o);case"%v":return""}}))},makeLine=function(e,t,i){var r=[e+"="+(t.format instanceof Function?t.format(t.push?i:i[t.name]):t.format)];if(t.names)for(var o=0;o<t.names.length;o+=1){var s=t.names[o];t.name?r.push(i[t.name][s]):r.push(i[t.names[o]])}else r.push(i[t.name]);return format.apply(null,r)},defaultOuterOrder=["v","o","s","i","u","e","p","c","b","t","r","z","a"],defaultInnerOrder=["i","c","b","a"],writer$1=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var i=t.outerOrder||defaultOuterOrder,r=t.innerOrder||defaultInnerOrder,o=[];return i.forEach((function(t){grammar$1[t].forEach((function(i){i.name in e&&null!=e[i.name]?o.push(makeLine(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){o.push(makeLine(t,i,e))}))}))})),e.media.forEach((function(e){o.push(makeLine("m",grammar$1.m[0],e)),r.forEach((function(t){grammar$1[t].forEach((function(i){i.name in e&&null!=e[i.name]?o.push(makeLine(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){o.push(makeLine(t,i,e))}))}))}))})),o.join("\r\n")+"\r\n"},parser=parser$1,writer=writer$1,grammar=grammarExports;lib.grammar=grammar,lib.write=writer,lib.parse=parser.parse,lib.parseParams=parser.parseParams,lib.parseFmtpConfig=parser.parseFmtpConfig,lib.parsePayloads=parser.parsePayloads,lib.parseRemoteCandidates=parser.parseRemoteCandidates,lib.parseImageAttributes=parser.parseImageAttributes,lib.parseSimulcastStreamList=parser.parseSimulcastStreamList;const logger$3=new Logger$1("FirefoxHandler",3),SSRC_MAX=Math.pow(2,32),SSRC_MIN=1e4,clientCname="kp34Za0H+aVf862l",serverCname="o/i14u9pJrxRKAsu",generateRandomSsrc=()=>Math.floor(Math.random()*SSRC_MAX+1e4);function generateAllSsrc(e){return e>SSRC_MAX-18?(logger$3.warn("generateAllSsrc","reset start id",e),generateAllSsrc(e=e-SSRC_MAX+1e4+18)):{audio:e,audioFec:e+1,audioRtx:e+2,video:e+3,videoFec:e+4,videoRtx:e+5,next:e+18}}const generateSsrc=(e,t,i,r=serverCname)=>[{id:i,attribute:"cname",value:r},{id:i,attribute:"msid",value:`${e} ${e}-${t}`},{id:i,attribute:"mslabel",value:`${e}`},{id:i,attribute:"label",value:`${e}-${t}`}],generateSsrcs=(e,t,i={})=>{const r=t.video,o=t.videoRtx,s=t.videoFec,n=[r,o],{cname:a,flexfec:d}=i;d&&n.push(s);const c=n.reduce(((t,i)=>t.concat(generateSsrc(e,"video",i,a))),[]),l=[{semantics:"FID",ssrcs:`${r} ${o}`}];return d&&l.push({semantics:"FEC-FR",ssrcs:`${r} ${s}`}),{ssrcs:c,ssrcGroups:l}};function closeMline(e){return e.direction="inactive",e.port=0,delete e.ext,delete e.ssrcs,delete e.ssrcGroups,delete e.simulcast,delete e.simulcast_03,delete e.rids,delete e.extmapAllowMixed,delete e.msid,delete e.bundleOnly,e}const getLocalPartialSdp=(e,t,i,r=!0)=>{const o={...e,media:[]};return r&&(o.invalid=[{value:"realx-exts:rscp"}]),t&&o.media.push(cloneDeep(t)),i&&o.media.push(cloneDeep(i)),delete o.groups,delete o.msidSemantic,H265ToByteVC1(o)};function parseAnswerIceParams(e){const t={},{publicIPs:i,certFingerprint:r,iceParams:o,iceConfig:s}=e;return t.fingerprint={type:"sha-256",hash:r},t.icePwd=o.serverIcePwd,t.iceUfrag=getServerUfrag(o.serverIceUfrag),t.candidates=genCandidates(i,s),t.setup="active",t.iceOptions="renomination",t}function genCandidates(e,t){if(!Array.isArray(e))return[];let i=0;const r=2130706431,o=[];return e.forEach((e=>{const s={component:1,ip:e.ip,type:"host",generation:e.generation};e.udpPorts&&!t.tcpOnly&&e.udpPorts.forEach((e=>{o.push({...s,foundation:i++,transport:"udp",port:e,priority:r})})),e.tcpPorts&&e.tcpPorts.forEach((e=>{o.push({...s,foundation:i++,transport:"tcp",port:e,tcptype:"passive",priority:2130705431})}))})),o}const getServerUfrag=e=>{const t=(new TextEncoder).encode("PREC"),i=base64ToUint8(e),r=new Uint8Array(4);crypto.getRandomValues(r);const o=new Uint8Array(2);o[0]=0,o[1]=1;return uint8ToBase64(concatenate(Uint8Array,t,i,r,o))};var ICEConfigType=(e=>(e[e.kICEConfigTypeSrtpDtlsType=0]="kICEConfigTypeSrtpDtlsType",e[e.kICEConfigTypeRenominationType=1]="kICEConfigTypeRenominationType",e[e.kICEConfigTypeTcpType=2]="kICEConfigTypeTcpType",e[e.kICEConfigTypeMultiSendType=3]="kICEConfigTypeMultiSendType",e[e.kICEConfigTypeKcpType=4]="kICEConfigTypeKcpType",e[e.kICEConfigTypeSrtpSdesType=5]="kICEConfigTypeSrtpSdesType",e))(ICEConfigType||{});function getServerUfragV2({random:e,serverUfrag:t,serverPwd:i,clientPwd:r,options:o}){let s=0;const n=(new TextEncoder).encode("WPRE");s+=4,e||(e=new Uint8Array(4),crypto.getRandomValues(e)),s+=4;const a=base64ToUint8(t);s+=1,s+=a.byteLength;const d=aesCtrEncrypt(base64ToUint8(r),base64ToUint8(i).subarray(0,16),base64ToUint8(t).subarray(0,16));s+=1,s+=d.byteLength;const c=new Uint8Array(Object.keys(o).reduce(((e,t)=>{const i=Number(t);return e.push(i),e.push(o[i]?1:0),e}),[]));s+=c.byteLength;let l=concatenate(Uint8Array,n,e,[a.byteLength],a,[d.byteLength],d,c);l.byteLength%3!=0&&(l=concatenate(Uint8Array,l,new Uint8Array(3-l.byteLength%3).fill(255)));return[uint8ToBase64(l),uint8ToBase64(concatenate(Uint8Array,e,a.subarray(0,20)))]}const setAudioCodecPreferences=(e,t)=>{if(!Array.isArray(e.fmtp)||!Array.isArray(e.rtp))return;for(let i=0;i<e.rtp.length;i++){if(e.rtp[i].codec.toUpperCase()===t.toUpperCase()){e.rtp.unshift(e.rtp.splice(i,1)[0]);break}}const i=[];e.rtp.forEach((e=>i.push(e.payload))),e.payloads=i.join(" ")},setCodecPreferences=(e,t)=>{let i=0;if(!Array.isArray(e.fmtp)||!Array.isArray(e.rtp))return;for(const t of e.fmtp)if(t.config.includes("level-asymmetry-allowed=1")&&t.config.includes("packetization-mode=1")&&t.config.includes("profile-level-id=42e0")){i=t.payload;break}for(let r=0;r<e.rtp.length;r++){const o=e.rtp[r];if("H264"===t){if(o.payload===i){e.rtp.unshift(e.rtp.splice(r,1)[0]);break}}else if(o.codec===t){e.rtp.unshift(e.rtp.splice(r,1)[0]);break}}const r=[];e.rtp.forEach((e=>r.push(e.payload))),e.payloads=r.join(" ")},cropSdpMediaSection=e=>{const t=lib.parse(e);return t.media=t.media.map((e=>{if("audio"===e.type){return cropAudioMediaSection(e,t)}return cropVideoMediaSection(e,["H264","VP8","ByteVC1"],t)})),lib.write(t)},pushRRTR=e=>{e.media.forEach((e=>{"audio"!==e.type&&"video"!==e.type||e.rtp.forEach((t=>{e.rtcpFb||(e.rtcpFb=[]),e.rtcpFb.find((e=>e.payload===t.payload&&"rrtr"===e.type))||e.rtcpFb.push({payload:t.payload,type:"rrtr"})}))}))},cropVideoMediaSection=(e,t,i,r={rrtr:!1})=>{const o={},s={};let n=-1;const a=[];return Array.isArray(e.fmtp)&&e.fmtp.forEach((({payload:e,config:t})=>{if(t.startsWith("apt=")){const i=t.slice(4);o[e]=i}else t.includes("42e0")&&t.includes("packetization-mode=1")&&(n=e)})),Array.isArray(e.rtp)&&(e.rtp=e.rtp.filter((e=>{const i=e.codec,r=e.payload;let d;switch(i){case"H264":return d=!1,t.map((e=>{"H264"===e&&r===n&&(s[r]=r,a.push(r),d=!0)})),d;case"rtx":return!!s[o[r]]&&(s[r]=r,!0);case"red":case"ulpfec":case"flexfec-03":return s[r]=r,!0;default:return d=!1,t.map((e=>{e===i&&(s[r]=r,a.push(r),d=!0)})),d}}))),Array.isArray(e.fmtp)&&(e.fmtp=e.fmtp.filter((e=>s[e.payload]))),Array.isArray(e.rtcpFb)?e.rtcpFb=e.rtcpFb.filter((e=>s[e.payload])):e.rtcpFb=[],r.rrtr&&a.forEach((t=>{var i;null==(i=e.rtcpFb)||i.push({payload:t,type:"rrtr"})})),deleteProperty(e,i),Array.isArray(e.ext)&&(e.ext=e.ext.filter((e=>{if("http://www.webrtc.org/experiments/rtp-hdrext/video-content-type"!==e.uri&&"http://www.webrtc.org/experiments/rtp-hdrext/video-timing"!==e.uri&&"http://www.webrtc.org/experiments/rtp-hdrext/color-space"!==e.uri)return e}))),"string"==typeof e.payloads&&(e.payloads=e.payloads.split(" ").filter((e=>s[e])).join(" ")),e},cropAudioMediaSection=(e,t,i={rrtr:!1})=>{const r={};if(Array.isArray(e.rtp)&&(e.rtp=e.rtp.filter((e=>{const t=e.codec,i=e.payload;return("opus"===t||"red"===t)&&(r[i]=i,!0)}))),Array.isArray(e.rtcpFb)||(e.rtcpFb=[]),i.rrtr&&Object.keys(r).forEach((t=>{var i;null==(i=e.rtcpFb)||i.push({payload:Number(t),type:"rrtr"})})),deleteProperty(e,t),"string"==typeof e.payloads){const t=[];e.payloads.split(" ").forEach((e=>{r[e]&&t.push(e)})),e.payloads=t.join(" ")}return e},deleteProperty=(e,t)=>{e.iceOptions&&delete e.iceOptions,e.icePwd&&(t.icePwd=e.icePwd,delete e.icePwd),e.iceUfrag&&(t.iceUfrag=e.iceUfrag,delete e.iceUfrag),e.fingerprint&&(t.fingerprint=e.fingerprint,delete e.fingerprint)},H265ToByteVC1=e=>vcodecTransform(e,"H265","ByteVC1"),ByteVC1ToH265=e=>vcodecTransform(e,"ByteVC1","H265"),vcodecTransform=(e,t,i)=>{const r="string"==typeof e?lib.parse(e):e;return r.media=r.media.map((e=>("video"===e.type&&(e.rtp=e.rtp.map((e=>(e.codec===t&&(e.codec=i),e)))),e))),lib.write(r)};function DCHECK(e,t,...i){const r=(new Error).stack;reportGlobalError(`[DCHECK FAILED] ${t}`,-1,{stack:r})}const encodedTransformSupported$3=isLegacyEncodedTransformSupported(),peerConnectionConfiguration={iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"};var ConnectFailCode=(e=>(e[e.DC_ERROR=0]="DC_ERROR",e[e.DC_CLOSE=1]="DC_CLOSE",e[e.ICE_FAILED=2]="ICE_FAILED",e[e.DESTROY=3]="DESTROY",e[e.TIMEOUT=4]="TIMEOUT",e))(ConnectFailCode||{});let PeerConnectionGUID=0;class PeerConnection extends EnhancedEventEmitter{constructor(e,t,i=!1){super(),__publicField(this,"uuid",(PeerConnectionGUID++).toString()),__publicField(this,"_peerConnectionId",""),__publicField(this,"audioTrack4ff"),__publicField(this,"_pc"),__publicField(this,"_dc"),__publicField(this,"_iceNode"),__publicField(this,"_initSctpEvents",!1),__publicField(this,"_monitor"),__publicField(this,"_offerIce",{}),__publicField(this,"_answerIce",{}),__publicField(this,"_offerSession"),__publicField(this,"_answerSession"),__publicField(this,"_offerMlines",[]),__publicField(this,"_answerMlines",[]),__publicField(this,"_connectReject"),__publicField(this,"_logger"),__publicField(this,"_destroyed",!1),__publicField(this,"_reportTimer"),__publicField(this,"_onLineCheckerTimer"),__publicField(this,"_clearPeerListeners"),__publicField(this,"_peerConfig"),__publicField(this,"_iceStartTs",0),__publicField(this,"_icePreStepTs",0),this._ctx=e,this._groupConnectionId=t,this._isReconnect=i,this._monitor=getMonitor(e.id),this._logger=new Logger$1(`PeerConnection_${this.uuid}`,4,e.id),this._ctx.enableFallbackHandler&&this._logger.warn("ctor","PeerConnection running in fallback mode"),this._peerConfig=genPeerConfig(e),this._pc=new RTCPeerConnection(this._peerConfig),this._pc.ontrack=e=>{var t,i;const r=null==(i=null==(t=e.streams)?void 0:t[0])?void 0:i.id;this._print("pc.ontrack",`${e.track.kind} ${e.track.id} ${r}`),"ff-stream"===r&&(this.audioTrack4ff=e.track),this.emit("ontrack",e)},this._pc.onconnectionstatechange=()=>{this._print("onconnectionstatechange",`${this._pc.connectionState}. ice -> ${this._pc.iceConnectionState}`),"failed"!==this._pc.iceConnectionState&&"closed"!==this._pc.iceConnectionState&&"failed"!==this._pc.connectionState?"disconnected"!==this._pc.connectionState?"connecting"!==this._pc.connectionState&&"connected"!==this._pc.connectionState||clearInterval(this._onLineCheckerTimer):navigator.onLine?this.emit("disconnect",InternalReconnectReason.ICE_FAILED):this._onLineCheckerTimer=setInterval((()=>{navigator.onLine&&(clearInterval(this._onLineCheckerTimer),this.emit("disconnect",InternalReconnectReason.ICE_FAILED))}),1e3):this.emit("disconnect",InternalReconnectReason.ICE_FAILED)},this._pc.oniceconnectionstatechange=()=>{const e=this._pc.iceConnectionState;this._report("rtc_pre_ice_state",{message:e,ice_state:e.toUpperCase()}),this.emit("ice_state",e)}}static checkSupported(){if(!RTCPeerConnection)throw new SDKError(ErrorCode.NOT_SUPPORTED,"missing RTCPeerConnection API.");["addTransceiver","createDataChannel","createOffer","setLocalDescription","setRemoteDescription"].forEach((e=>{var t;if(!(null==(t=null==RTCPeerConnection?void 0:RTCPeerConnection.prototype)?void 0:t[e]))throw new SDKError(ErrorCode.NOT_SUPPORTED,`missing peer.${e} API.`)}))}getOriginRTCPeerConnection(){return this._pc}getConnectionId(){return this._peerConnectionId}getGroupConnectionId(){return this._groupConnectionId}getIceConnectionState(){return this._pc.iceConnectionState}async createOfferSdp(){let{sdp:e}=await this._pc.createOffer();return e}async startIceConnect(e){var t,i;if(this._ctx.enableStandardHandler&&!this._ctx.enableFallbackHandler)return this.startIceConnectStandard(e);this._print("connect","invoke. %o",e),this._iceNode=e;const r=this._pc.createDataChannel("signaling",{negotiated:!0,id:100});r.binaryType="arraybuffer",this._dc=r;const{offerIce:o,answerIce:s}=this._genIceInfo(e);this._offerIce=o,this._answerIce=s,isFirefox&&firefoxVersion<138&&(this._pc.addTransceiver("audio",{direction:"recvonly"}),this._pc.addTransceiver("video",{direction:"recvonly"}));const n=await this.createOfferSdp();if(!n)throw new SDKError(ErrorCode.NOT_SUPPORTED,"create offer sdp failed.");const a=lib.parse(n);this._peerConnectionId=s.iceUfrag||"";const d=!o.iceUfrag&&!o.icePwd;if(d){const r="renomination"===(null==(t=a.media[0])?void 0:t.iceOptions)||!this._ctx.enableFallbackHandler&&this._ctx.pcKillSwitch.sld_iceoption_renomination;r||(delete o.iceOptions,delete s.iceOptions),delete o.iceUfrag,delete o.icePwd;const[n,d]=getServerUfragV2({serverUfrag:e.iceParams.serverIceUfrag,serverPwd:e.iceParams.serverIcePwd,clientPwd:null==(i=a.media[0])?void 0:i.icePwd,options:{[ICEConfigType.kICEConfigTypeSrtpDtlsType]:!0,[ICEConfigType.kICEConfigTypeRenominationType]:r}});this._peerConnectionId=d,s.iceUfrag=n,this._logger.info("use serverUfrag v2",JSON.stringify({dtls:!0,renomination:r}))}this.reportRtcPreIce("ice_start");const[c]=a.media;if(this._offerIce.fingerprint=a.fingerprint||c.fingerprint,isFirefox||this._ctx.enableFallbackHandler){a.media=a.media.map((e=>{var t,i,r,o;const s={...e,...this._offerIce};return"video"===s.type&&(isTransportCCSupport?(s.ext=null==(t=s.ext)?void 0:t.filter((e=>-1===e.uri.indexOf("abs-send-time"))),s.rtcpFb=null==(i=s.rtcpFb)?void 0:i.filter((e=>"goog-remb"!==e.type))):(s.rtcpFb=null==(r=s.rtcpFb)?void 0:r.filter((e=>"transport-cc"!==e.type)),s.ext=null==(o=s.ext)?void 0:o.filter((e=>-1===e.uri.indexOf("transport"))))),s})),isRRTRSupported&&pushRRTR(a);const e={...a};e.fingerprint=this._answerIce.fingerprint,e.media=e.media.map((e=>(delete(e={...e,...this._answerIce}).bundleOnly,e.port=9,"application"===e.type?e.sctpmap={sctpmapNumber:5e3,app:"webrtc-datachannel",maxMessageSize:262144}:("audio"===e.type&&(e.msid="ff-stream ff-stream-audio"),e.direction="sendonly"),e))),isRRTRSupported&&pushRRTR(e),this._ctx.enableFallbackHandler?await this.setLocalDescription(n):await this.setLocalDescription(lib.write(a)),await this.setRemoteDescription(lib.write(e))}else{delete a.media,this._offerSession={...a},this._answerSession={...a},this._answerSession.fingerprint&&(this._answerSession.fingerprint=this._answerIce.fingerprint);const e=0;d&&(this._offerIce.iceUfrag=c.iceUfrag,this._offerIce.icePwd=c.icePwd),this._offerMlines=[{...c,...this._offerIce,mid:`${e}`}],this._answerMlines=[{...c,...this._answerIce,sctpmap:{sctpmapNumber:5e3,app:"webrtc-datachannel",maxMessageSize:262144},mid:`${e}`}],this.setDescription()}return this._reportTransportStats(),await new Promise(((e,t)=>{this._connectReject=t;const i=setTimeout((()=>{var e;this.reportRtcPreIce("timeout"),null==(e=this._connectReject)||e.call(this,{code:4,message:"connect timeout"}),delete this._connectReject}),8e3),o=()=>{this._print("connect","dataChannel open"),this._reportRtcInvokeStatus("es.dc.open",""),this.reportRtcPreIce("datachannel_opened"),clearTimeout(i),e(""),delete this._connectReject},s=e=>{var t,r,o,s;this._report("rtc_signaling_msg_error",{error_code:null==(t=null==e?void 0:e.error)?void 0:t.sdpLineNumber,message:null==(r=null==e?void 0:e.error)?void 0:r.errorDetail,reason:"invalid data"}),this._reportRtcInvokeStatus("es.dc.error",""),null==(s=this._connectReject)||s.call(this,{message:`dc.onerror, ${null==(o=e.error)?void 0:o.errorDetail}`,code:0}),this.emit("disconnect",InternalReconnectReason.DC_ERROR),delete this._connectReject,clearTimeout(i)},n=()=>{var e;this._reportRtcInvokeStatus("es.dc.close",""),null==(e=this._connectReject)||e.call(this,{message:"dc.onclose",code:1}),this.reportRtcPreIce("datachannel_closed"),this.emit("disconnect",InternalReconnectReason.DC_CLOSE),delete this._connectReject,clearTimeout(i)},a=()=>{"connected"===this._pc.iceConnectionState?this.reportRtcPreIce("ice_connected"):"failed"!==this._pc.iceConnectionState&&"closed"!==this._pc.iceConnectionState||this.reportRtcPreIce("ice_failed")},d=()=>{var e;"failed"!==this._pc.iceConnectionState&&"closed"!==this._pc.iceConnectionState&&"failed"!==this._pc.connectionState||(null==(e=this._connectReject)||e.call(this,{message:`pc.connectionstatechange -> ${this._pc.connectionState}, ice -> ${this._pc.iceConnectionState}`,code:2}),delete this._connectReject,clearTimeout(i))};r.addEventListener("open",o),r.addEventListener("error",s),r.addEventListener("close",n),this._pc.addEventListener("iceconnectionstatechange",a),this._pc.addEventListener("connectionstatechange",d),this._clearPeerListeners=()=>{r.removeEventListener("open",o),r.removeEventListener("error",s),r.removeEventListener("close",n),this._pc.removeEventListener("iceconnectionstatechange",a),this._pc.removeEventListener("connectionstatechange",d)}})),this._print("connect","dataChannel establish success"),r}async startIceConnectStandard(e){this._print("connect","standard invoke. %o",e),this._iceNode=e;const t=this._pc.createDataChannel("signaling",{negotiated:!0,id:100});t.binaryType="arraybuffer",this._dc=t;const{offerIce:i,answerIce:r}=this._genIceInfo(e);this._offerIce=i,this._answerIce=r,isFirefox&&firefoxVersion<138&&(this._pc.addTransceiver("audio",{direction:"recvonly"}),this._pc.addTransceiver("video",{direction:"recvonly"}));const o=await this.createOfferSdp();if(!o)throw new SDKError(ErrorCode.NOT_SUPPORTED,"create offer sdp failed.");const s=lib.parse(o);this._answerSession={...s},this._answerSession.fingerprint&&(this._answerSession.fingerprint=this._answerIce.fingerprint);const n=s.media.find((e=>"application"===e.type));this._peerConnectionId=r.iceUfrag||"";if(!i.iceUfrag&&!i.icePwd){const t=this._ctx.pcKillSwitch.sld_iceoption_renomination||"renomination"===(null==n?void 0:n.iceOptions);t||(delete i.iceOptions,delete r.iceOptions),delete i.iceUfrag,delete i.icePwd;const[o,s]=getServerUfragV2({serverUfrag:e.iceParams.serverIceUfrag,serverPwd:e.iceParams.serverIcePwd,clientPwd:null==n?void 0:n.icePwd,options:{[ICEConfigType.kICEConfigTypeSrtpDtlsType]:!0,[ICEConfigType.kICEConfigTypeRenominationType]:t}});this._peerConnectionId=s,r.iceUfrag=o,this._logger.info("use serverUfrag v2",JSON.stringify({dtls:!0,renomination:t}))}this.reportRtcPreIce("ice_start"),this._offerIce.fingerprint=s.fingerprint||n.fingerprint;const a={...s};return a.fingerprint=this._answerIce.fingerprint,a.media=a.media.map((e=>{var t,i,r,o;return"application"===(e={...e,...this._answerIce}).type&&(e.sctpmap={sctpmapNumber:5e3,app:"webrtc-datachannel",maxMessageSize:262144}),isFirefox&&(delete e.bundleOnly,e.port=9,"audio"===e.type?(e.msid="ff-stream ff-stream-audio",e.direction="sendonly"):"video"===e.type&&(isTransportCCSupport?(e.ext=null==(t=e.ext)?void 0:t.filter((e=>-1===e.uri.indexOf("abs-send-time"))),e.rtcpFb=null==(i=e.rtcpFb)?void 0:i.filter((e=>"goog-remb"!==e.type))):(e.rtcpFb=null==(r=e.rtcpFb)?void 0:r.filter((e=>"transport-cc"!==e.type)),e.ext=null==(o=e.ext)?void 0:o.filter((e=>-1===e.uri.indexOf("transport")))),e.direction="sendonly")),e})),"v1"===this.getIceVersion()||this._ctx.pcKillSwitch.sld_iceoption_renomination?(s.media=s.media.map((e=>e={...e,...this._offerIce})),await this.setLocalDescription(lib.write(s))):await this.setLocalDescription(o),await this.setRemoteDescription(lib.write(a)),this._reportTransportStats(),await new Promise(((e,i)=>{this._connectReject=i;const r=setTimeout((()=>{var e;this.reportRtcPreIce("timeout"),null==(e=this._connectReject)||e.call(this,{code:4,message:"connect timeout"}),delete this._connectReject}),8e3),o=()=>{this._print("connect","dataChannel open"),this._reportRtcInvokeStatus("es.dc.open",""),this.reportRtcPreIce("datachannel_opened"),clearTimeout(r),e(""),delete this._connectReject},s=e=>{var t,i,o,s;this._report("rtc_signaling_msg_error",{error_code:null==(t=null==e?void 0:e.error)?void 0:t.sdpLineNumber,message:null==(i=null==e?void 0:e.error)?void 0:i.errorDetail,reason:"invalid data"}),this._reportRtcInvokeStatus("es.dc.error",""),null==(s=this._connectReject)||s.call(this,{message:`dc.onerror, ${null==(o=e.error)?void 0:o.errorDetail}`,code:0}),this.emit("disconnect",InternalReconnectReason.DC_ERROR),delete this._connectReject,clearTimeout(r)},n=()=>{var e;this._reportRtcInvokeStatus("es.dc.close",""),null==(e=this._connectReject)||e.call(this,{message:"dc.onclose",code:1}),this.reportRtcPreIce("datachannel_closed"),this.emit("disconnect",InternalReconnectReason.DC_CLOSE),delete this._connectReject,clearTimeout(r)},a=()=>{"connected"===this._pc.iceConnectionState?this.reportRtcPreIce("ice_connected"):"failed"!==this._pc.iceConnectionState&&"closed"!==this._pc.iceConnectionState||this.reportRtcPreIce("ice_failed")},d=()=>{var e;"failed"!==this._pc.iceConnectionState&&"closed"!==this._pc.iceConnectionState&&"failed"!==this._pc.connectionState||(null==(e=this._connectReject)||e.call(this,{message:`pc.connectionstatechange -> ${this._pc.connectionState}, ice -> ${this._pc.iceConnectionState}`,code:2}),delete this._connectReject,clearTimeout(r))};t.addEventListener("open",o),t.addEventListener("error",s),t.addEventListener("close",n),this._pc.addEventListener("iceconnectionstatechange",a),this._pc.addEventListener("connectionstatechange",d),this._clearPeerListeners=()=>{t.removeEventListener("open",o),t.removeEventListener("error",s),t.removeEventListener("close",n),this._pc.removeEventListener("iceconnectionstatechange",a),this._pc.removeEventListener("connectionstatechange",d)}})),this._print("connect","dataChannel establish success"),t}async setDescription(e){this._print("setDescription","invoke."),this._offerSession.media=this._offerMlines,this._answerSession.media=this._answerMlines;const t=[];this._offerMlines.forEach((e=>{"inactive"!==e.direction&&e.mid&&t.push(e.mid)})),this._offerSession.groups&&this._answerSession.groups&&(this._offerSession.groups[0].mids=t.join(" "),this._answerSession.groups[0].mids=t.join(" "));const i=getServerNow();e&&this._report("rtc_begin_create_offer",{direction:"local"===e.streamUserId?"up":"down",stream_id:e.streamId,stream_user_id:e.streamUserId,pc_session_id:this._peerConnectionId,vendor_mode:0}),e&&this._report("rtc_create_offer",{error_code:0,direction:"local"===e.streamUserId?"up":"down",stream_id:e.streamId,stream_user_id:e.streamUserId,elapse:getServerNow()-i}),await this.setLocalDescription(lib.write(this._offerSession),e),await this.setRemoteDescription(lib.write(this._answerSession),e)}async setLocalDescription(e,t){var i;const r=getServerNow();try{if(await this._pc.setLocalDescription({type:"offer",sdp:e}),this._report("rtc_set_description",{error_code:0,message:e,is_local:"1",direction:"local"===(null==t?void 0:t.streamUserId)?"up":"down",stream_id:(null==t?void 0:t.streamId)||"",stream_user_id:(null==t?void 0:t.streamUserId)||"",elapse:getServerNow()-r},{type:"offer"}),!this._initSctpEvents){this._initSctpEvents=!0;const e=null==(i=this._pc)?void 0:i.sctp;e&&(e.onstatechange=()=>{this._reportRtcInvokeStatus("sctp",`sctp state change TO: ${e.state}`)},e.transport&&(e.transport.onstatechange=()=>{var t;this._reportRtcInvokeStatus("dtls",`dtls state change TO: ${null==(t=null==e?void 0:e.transport)?void 0:t.state}`)}))}}catch(i){throw console.error("setLocal",i),this._report("rtc_set_description",{error_code:-1,message:i.message+e,is_local:"1",direction:"local"===(null==t?void 0:t.streamUserId)?"up":"down",stream_id:"",stream_user_id:"",elapse:getServerNow()-r},{type:"offer"}),i}}async setRemoteDescription(e,t){const i=getServerNow();try{e=ByteVC1ToH265(e),await this._pc.setRemoteDescription({type:"answer",sdp:e}),this._report("rtc_set_description",{error_code:0,message:e,is_local:"0",direction:"local"===(null==t?void 0:t.streamUserId)?"up":"down",stream_id:(null==t?void 0:t.streamId)||"",stream_user_id:(null==t?void 0:t.streamUserId)||"",elapse:getServerNow()-i},{type:"answer"})}catch(r){throw console.error("setRemote",r),this._report("rtc_set_description",{error_code:-1,message:r.message+e,is_local:"0",direction:"local"===(null==t?void 0:t.streamUserId)?"up":"down",stream_id:(null==t?void 0:t.streamId)||"",stream_user_id:(null==t?void 0:t.streamUserId)||"",elapse:getServerNow()-i},{type:"answer"}),r}}closeIceConnect(){var e,t,i,r;null==(e=this._connectReject)||e.call(this,{code:3,message:"invoke destroy()"}),delete this._connectReject,null==(t=this._pc)||t.close(),null==(i=this._dc)||i.close(),delete this._dc,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,clearPeerCache(this._pc),null==(r=this._clearPeerListeners)||r.call(this),delete this._clearPeerListeners}reportRtcPreIce(e){var t;const i=getServerNow();"ice_start"===e&&(this._iceStartTs=i,this._icePreStepTs=i),this._report("rtc_pre_ice",{connect_event:e,message:e,elapse:i-this._icePreStepTs,total_elapse:i-this._iceStartTs,cache_status:!!(null==(t=this._iceNode)?void 0:t.cache_status),is_reconnect:this._isReconnect}),this._icePreStepTs=i}getStatsWithLowFrequency(e,t,i){return getStats$1(this._pc,e,t,i)}getIceVersion(){var e,t;return(null==(e=this._iceNode)?void 0:e.iceParams.clientIceUfrag)||(null==(t=this._iceNode)?void 0:t.iceParams.clientIcePwd)?"v1":"v2"}createAnswerSdp(e,t){DCHECK(this._answerSession,"_answerSession should be existed");const i={...this._answerSession};i.media=e,i.groups=t;return lib.write(i)}destroy(){this._print("destroy",this._peerConnectionId),super.removeAllListeners(),this.closeIceConnect(),this._destroyed=!0,this._reportTimer&&(clearTimeout(this._reportTimer),delete this._reportTimer),this._onLineCheckerTimer&&(clearInterval(this._onLineCheckerTimer),delete this._onLineCheckerTimer),delete this._pc}_genIceInfo(e){var t,i;return{offerIce:{iceUfrag:null==(t=e.iceParams)?void 0:t.clientIceUfrag,icePwd:null==(i=e.iceParams)?void 0:i.clientIcePwd,iceOptions:"renomination"},answerIce:parseAnswerIceParams(e)}}async _reportTransportStats(){var e;const t=await this.getStatsWithLowFrequency(),i={};if(t.forEach((e=>{"transport"===e.type?(i.dtls_state=e.dtlsState,i.bytes_received=e.bytesReceived,i.bytes_sent=e.bytesSent,i.ice_state=e.iceState,i.packets_received=e.packetsReceived,i.packets_sent=e.packetsSent,i.selected_candidate_pair_changes=e.selectedCandidatePairChanges):"local-candidate"===e.type||"remote-candidate"===e.type?i.candidates_info=[...i.candidates_info||[],{id:e.id,is_remote:e.isRemote,port:e.port,protocol:e.protocol,candidate_type:e.candidateType,priority:e.priority,network_type:e.networkType,candidate_ip:e.ip}]:"candidate-pair"===e.type&&(i.candidatePairsInfo={},i.candidatePairsInfo.candidate_state=e.state,i.candidatePairsInfo.writable_state=e.writable,i.candidatePairsInfo.sent_ping_requests_total=e.requestsSent,i.candidatePairsInfo.recv_ping_requests=e.requestsReceived,i.candidatePairsInfo.sent_ping_responses=e.responsesSent,i.candidatePairsInfo.recv_ping_responses=e.responsesReceived,i.candidatePairsInfo.current_rtt=e.currentRoundTripTime,i.candidatePairsInfo.total_rtt=e.totalRoundTripTime,["localCandidateId","remoteCandidateId","bytesSent","bytesReceived","availableOutgoingBitrate","availableIncomingBitrate","bytesDiscardedOnSend","consentRequestsSent","packetsDiscardedOnSend","lastPacketReceivedTimestamp","lastPacketSentTimestamp"].forEach((t=>{void 0!==e[t]&&(i.candidatePairsInfo[camel2Snake(t)]=e[t])})))})),Object.keys(i).length>0&&(null==(e=this._monitor)||e.report("rtc_transport_statistics",i)),!this._destroyed){const e="connected"===this._pc.iceConnectionState&&"connected"===this._pc.connectionState;this._reportTimer=setTimeout((()=>{this._reportTransportStats()}),e?5e3:1e3)}}_print(e,...t){this._logger.info(`${e}`,...t)}_report(e,t,i){var r,o,s;null==(s=this._monitor)||s.report(e,{...t,connection_id:this._peerConnectionId,group_connection_id:this._groupConnectionId},{...i,tcp_only:null==(r=this._iceNode)?void 0:r.iceConfig.tcpOnly,ms_addr:JSON.stringify((null==(o=this._iceNode)?void 0:o.publicIPs.map((e=>({ip:e.ip,tcp:e.tcpPorts,udp:e.udpPorts}))))||[])})}_reportRtcInvokeStatus(e,t){this._report("rtc_invoke_status",{sdk_api_name:e,message:t,error_code:0,stream_id:"",elapse:0})}}const genPeerConfig=e=>{const t={...peerConnectionConfiguration};return e.pcKillSwitch.ctor_sdpsemantics_add&&(t.sdpSemantics="unified-plan"),e.pcKillSwitch.ctor_encodedinsetablestream_add&&encodedTransformSupported$3&&!getParameter("DISABLE_ENCODED_TRANSFORM")&&(t.encodedInsertableStreams=!0),t};var InternalReconnectReason=(e=>(e.ICE_FAILED="ice failed",e.DC_ERROR="datachannel onerror",e.DC_CLOSE="datachannel onclose",e.NODE_CHANGE="recv nodeChange signaling",e.NOTIFY_RECONNECT="recv notifyReconnect signaling",e.JOIN_TIMEOUT="joinRoom timeout, retry with tcp only",e))(InternalReconnectReason||{});class ConnectionManager extends EnhancedEventEmitter{constructor(e){super(),__publicField(this,"id"),__publicField(this,"_monitor"),__publicField(this,"logger"),__publicField(this,"_getAccessManager"),__publicField(this,"_connectionPool",new Map),__publicField(this,"_curConnection"),__publicField(this,"_hasReportBrowerWarning",!1),__publicField(this,"_reconnectTimer"),__publicField(this,"_connecting",!1),__publicField(this,"_isFirstTimeConnected",!0),__publicField(this,"_feedbackNodes",[]),__publicField(this,"_preIceStartTime",-1),__publicField(this,"_tcpOnlyTimer"),__publicField(this,"_destroyed",!1),this._ctx=e,this.id=e.id,this._monitor=getMonitor(this.id),this.logger=new Logger$1("ConnectionManager",3,this.id),this.logger.info("constructor","invoke"),this._getAccessManager=new IceConfigRequestManager(e)}startup(){this.logger.info("connect","invoke");try{PeerConnection.checkSupported()}catch(e){this.asyncEmit("disconnected",e)}this._connecting||(this._onConnectStart(),Promise.resolve().then((()=>this.emit("__onGetIceConfigHook"))),this._getAccess())}async reconnectByNodeChange(e){var t,i,r,o;this.logger.info("reconnectByNodeChange","invoke %o",e);const{nodes:s,reason:n}=e;null==(t=this._monitor)||t.report("rtc_node_change",{error_code:0,message:JSON.stringify(e),reason:JSON.stringify(n)}),sdkCache.clearAccessNode(this._ctx.appId),null==(i=this._curConnection)||i.pc.reportRtcPreIce("node_change");const a=(null==(o=null==(r=this._curConnection)?void 0:r.node.publicIPs[0])?void 0:o.ip)||"";this._closeCurrentConnection(),this._clearConnectionPool(),this._clearReconnectTimer(),this._onConnectStart("recv nodeChange signaling"),Array.isArray(s)&&s.length>0?this._startIceConnect(s):this._getAccess([{feedbackIP:a,feedbackReason:{type:"NODE_CHANGED",reason:n}}])}async reconnect(e,t=!1){this.logger.info("reconnect","invoke. "+(t?"ICE over TCP":"")),this._closeCurrentConnection(),this._clearConnectionPool(),this._clearReconnectTimer(),this._onConnectStart(e),this._getAccess(void 0,t)}shotdown(){this.logger.info("destroy","invoke"),this._destroyed=!0,this.asyncEmit("disconnected",new SDKError(ErrorCode.OPERATION_CANCEL,"destroy")).then((()=>{super.removeAllListeners()})),this._clearReconnectTimer(),this._clearConnectionPool(),this._getAccessManager.destroy(),this._closeCurrentConnection()}_getAccess(e,t=!1){this._getAccessManager.getICENode(e).then((e=>{this.emit("__onGetIceSuccessHook",e),this._startIceConnect(e,t)})).catch((e=>{this.asyncEmit("disconnected",e)})).finally((()=>{this._feedbackNodes=[]}))}_startIceConnect(e,t=!1){if(this._destroyed)return;this.logger.info("_startIceConnect","invoke");const i=genUuid$1();this._preIceStartTime=getServerNow();const r=this._ctx.joinRoomConfig.useTcpJoin,o=this._ctx.joinRoomConfig.useTcpJoinDelay,s=async r=>{t&&((r=cloneDeep(r)).iceConfig.tcpOnly=!0);const o={node:r};try{const t=new PeerConnection(this._ctx,i,!this._isFirstTimeConnected);o.pc=t,this._connectionPool.set(t.uuid,o);const s=await t.startIceConnect(r),n=new DataChannelSignaling(this.id,s,{connection_id:t.getConnectionId(),group_connection_id:i});o.signaling=n,t.reportRtcPreIce("datachannel_send_ping"),await n.sendPingSignaling(),t.reportRtcPreIce("datachannel_recv_pong"),this._onConnectSuccess({node:r,pc:t,signaling:n,dc:s}),this.safeEmit("__onConnectSuccessHook",e.length)}catch(e){this._onConnectionFailed(o,e)}};this.emit("__onIceConnectStartHook"),e.forEach(s),r&&!t&&(this.logger.info("_startIceConnect",`tcp-only will try after ${o}ms`),this._tcpOnlyTimer=setTimeout((()=>{this.emit("connectWidthTcp"),e.forEach((e=>{(e=cloneDeep(e)).iceConfig.tcpOnly=!0,s(e)})),delete this._tcpOnlyTimer}),o))}_onConnectSuccess(e){var t;this.logger.info("connect","peer_%s connect success.",e.pc.uuid),this.emit("__onIceConnectSuccessHook",e),this._curConnection?(e.pc.destroy(),e.signaling.destroy(),this._connectionPool.delete(e.pc.uuid)):(this._curConnection=e,this._addConnectionHandler(e.pc),null==(t=this._monitor)||t.set({connection_id:e.pc.getConnectionId()}),this._connectionPool.delete(e.pc.uuid),this._feedbackNodes.forEach((e=>this._feedbackBySignaling(e))),this._feedbackNodes=[],this._onConnectEnded(e))}_onConnectionFailed(e,t){var i,r;this.logger.info("connect","peer_%s connect failed. %s",(null==(i=e.pc)?void 0:i.uuid)||"",t.message),this.emit("__onIceConnectFailedHook",e),t.code!==ConnectFailCode.DESTROY&&t.code!==ErrorCode.OPERATION_CANCEL&&(this._curConnection?this._feedbackBySignaling(e.node):this._feedbackNodes.push(e.node),this.logger.info("connect","remove cache node"),sdkCache.deleteAccessNode(this._ctx.appId,e.node),e.pc&&(this._connectionPool.delete(e.pc.uuid),e.pc.destroy()),null==(r=e.signaling)||r.destroy(),0!==this._connectionPool.size||this._curConnection||this._destroyed||(this.logger.error("connect","establish peerConnection failed"),this._checkBrowserUA(),getServerNow()-this._preIceStartTime<1e3?(this._clearReconnectTimer(),this._reconnectTimer=setTimeout((()=>{delete this._reconnectTimer,this._reconnectWithIceFailed(this._feedbackNodes)}),1e3)):this._reconnectWithIceFailed(this._feedbackNodes)))}_feedbackBySignaling(e){var t;null==(t=this._curConnection)||t.signaling.sendSignaling("scheduleMessage",{type:"feedback",body:{feedbackIP:e.publicIPs[0].ip,feedbackReason:{type:"ICE_FAILED",reason:{}}}})}async _reconnectWithIceFailed(e){this._onConnectStart("ice failed"),this.logger.warn("reconnect","because of ice failed"),this._getAccess(e.map((e=>({feedbackIP:e.publicIPs[0].ip,feedbackReason:{type:"ICE_FAILED",reason:{}}}))))}_checkBrowserUA(){var e;!this._hasReportBrowerWarning&&this._ctx.joinRoomConfig.isBlackBrower()&&(this._hasReportBrowerWarning=!0,null==(e=this._monitor)||e.report("rtc_error",{error_code:RtcErrorCode.BLACK_BROWSER,message:"failed to establish data-channel, and the current browser is on the browser blacklist."}))}_onConnectStart(e){var t,i;this.logger.info("_onConnectStart",`invoke, reason: ${e||"init"}`),this._connecting=!0,e?this.asyncEmit("reconnecting",e):this.asyncEmit("connecting");const r=genUuid$1();null==(t=this._monitor)||t.set({connect_session_id:r}),this._isFirstTimeConnected||null==(i=this._monitor)||i.report("rtc_reconnect",{error_code:1002,message:"peerconnection reconnecting",reconnect_id:r,reconnect_type:"peerconnection"},{reason:e})}_onConnectEnded(e){var t;this.logger.info("_onConnectEnded","invoke"),this._connecting=!1,this._isFirstTimeConnected||null==(t=this._monitor)||t.report("rtc_reconnected",{message:"peerconnection reconnected",reconnect_type:"peerconnection"}),this._isFirstTimeConnected=!1,this.asyncEmit("connected",e),e.node.iceConfig.tcpOnly&&(this.logger.info("_onConnectEnded","use tcp only"),reportRtcInvokeStatus(this._ctx.id,"connected_with_tcp_only",JSON.stringify(e.node))),this._tcpOnlyTimer&&(window.clearTimeout(this._tcpOnlyTimer),delete this._tcpOnlyTimer),this._clearConnectionPool()}_addConnectionHandler(e){e.on("disconnect",(e=>{this._closeCurrentConnection(),this._clearReconnectTimer(),navigator.onLine?this.reconnect(e):this._reconnectTimer=setTimeout((()=>this.reconnect(e)),3e3)}))}_closeCurrentConnection(){var e,t;null==(e=this._curConnection)||e.pc.destroy(),null==(t=this._curConnection)||t.signaling.destroy(),delete this._curConnection}_clearConnectionPool(){this._connectionPool.forEach(((e,t)=>{var i,r;null==(i=e.signaling)||i.destroy(),null==(r=e.pc)||r.destroy(),this._connectionPool.delete(t)}))}_clearReconnectTimer(){this._reconnectTimer&&(window.clearTimeout(this._reconnectTimer),delete this._reconnectTimer)}}var AudioMixingDualMonoMode=(e=>(e[e.AUTO=0]="AUTO",e[e.MODE_L=1]="MODE_L",e[e.MODE_R=2]="MODE_R",e[e.MODE_MIX=3]="MODE_MIX",e))(AudioMixingDualMonoMode||{}),AudioMixingType=(e=>(e[e.PLAYOUT=0]="PLAYOUT",e[e.PUBLISH=1]="PUBLISH",e[e.PLAYOUT_AND_PUBLISH=2]="PLAYOUT_AND_PUBLISH",e))(AudioMixingType||{}),AudioMixingState=(e=>(e[e.AUDIO_MIXING_STATE_PRELOADED=0]="AUDIO_MIXING_STATE_PRELOADED",e[e.AUDIO_MIXING_STATE_PLAYING=1]="AUDIO_MIXING_STATE_PLAYING",e[e.AUDIO_MIXING_STATE_PAUSED=2]="AUDIO_MIXING_STATE_PAUSED",e[e.AUDIO_MIXING_STATE_STOPPED=3]="AUDIO_MIXING_STATE_STOPPED",e[e.AUDIO_MIXING_STATE_FAILED=4]="AUDIO_MIXING_STATE_FAILED",e[e.AUDIO_MIXING_STATE_FINISHED=5]="AUDIO_MIXING_STATE_FINISHED",e[e.AUDIO_MIXING_STATE_PCM_ENABLED=6]="AUDIO_MIXING_STATE_PCM_ENABLED",e[e.AUDIO_MIXING_STATE_PCM_DISABLED=7]="AUDIO_MIXING_STATE_PCM_DISABLED",e))(AudioMixingState||{});class BasicHandler extends eventemitter3Exports.EventEmitter{constructor(e,t){super(),__publicField(this,"_context"),__publicField(this,"peerConnectionMode",0),__publicField(this,"id"),__publicField(this,"_monitor"),__publicField(this,"logger"),__publicField(this,"_nextSsrc",generateRandomSsrc()),__publicField(this,"_aSendonlyAnswerTpl"),__publicField(this,"_vSendonlyAnswerTpl"),__publicField(this,"_enableSubFlexfec",!1),__publicField(this,"audioTrack4ff"),__publicField(this,"setLocalDescription"),__publicField(this,"setRemoteDescription"),this.peer=t,this.id=e.id,this._monitor=getMonitor(this.id),this.logger=new Logger$1("BasicHandler",3,e.id),this.setLocalDescription=t.setLocalDescription.bind(t),this.setRemoteDescription=t.setRemoteDescription.bind(t),this._context=e,this.peer.on("ontrack",(e=>{this.emit("ontrack",e)}))}destroy(){this.logger.info("destroy",this.peerConnectionId||""),super.removeAllListeners()}get _peerConnection(){return this.peer.getOriginRTCPeerConnection()}getTransceivers(){return this._peerConnection.getTransceivers()}getConnectionState(){return this._peerConnection.connectionState}internalPublish(e){const{stream:t,videoTrack:i,audioTrack:r,pubAudio:o,pubVideo:s}=e,n={direction:"sendonly",streams:[t]},a={direction:"sendonly",streams:[t]},{sendEncodings:d,videoDescriptions:c,subVideoDescriptions:l,activeSimulcastStreams:u}=this._context.videoProfile.genVideoDescriptions(e);a.sendEncodings=d,this._context.videoProfile.activeSimStreams=u,this.logger.info("publish videoTransceiverInit videoDescriptions","",a,c);let _=null==r?void 0:r.preprocessingTrack;(null==r?void 0:r.mixType)!==AudioMixingType.PLAYOUT&&(null==r?void 0:r.mixedAudioTrack)&&(_=null==r?void 0:r.mixedAudioTrack),_=o&&_?_:"audio";let h=null==i?void 0:i.preprocessingTrack;h=s&&h?h:"video";try{this._reportRtcInvokeStatus("Handler.internalPublish",JSON.stringify({aTrack:mediaTrackStringify(_),vTrack:mediaTrackStringify(h),audioTransceiverInit:n,videoTransceiverInit:a}))}catch(e){}return{semantics:"unified-plan",videoDescriptions:c,subVideoDescriptions:l,audioTransceiverInit:{track:_,init:n},videoTransceiverInit:{track:h,init:a}}}async setCurrentDescription(){}createAVMlineAnswerTpl(e){const t=lib.parse(e);t.media.forEach((e=>{if("audio"===e.type){if("sendonly"===e.direction){const t=null==e?void 0:e.rtp.find((e=>"opus"===e.codec));if(t&&(null==e?void 0:e.fmtp)){const i=null==e?void 0:e.fmtp.find((e=>e.payload===t.payload));i&&this._context&&(i.config+=";stereo=1;sprop-stereo=1")}this._aSendonlyAnswerTpl=e}}else"video"===e.type&&("sendonly"===e.direction&&(this._vSendonlyAnswerTpl=e),Array.isArray(e.rtp)&&e.rtp.forEach((e=>{var t;(null==(t=e.codec)?void 0:t.includes("flexfec"))&&(this._enableSubFlexfec=!0)})))})),isRRTRSupported&&pushRRTR(t)}get peerConnectionId(){return this.peer.getConnectionId()||""}addBitrateLimit(e,t){null==e||e.rtp.forEach((({codec:i,payload:r})=>{if(["vp8","h264"].includes(i.toLocaleLowerCase())){const i=e.fmtp.find((e=>e.payload===r));i?i.config=[...i.config.split(";"),"x-google-min-bitrate=100",`x-google-start-bitrate=${t}`].join(";"):e.fmtp.push({payload:r,config:`x-google-min-bitrate=100;x-google-start-bitrate=${t}`})}}))}_report(e,t,i){var r;null==(r=this._monitor)||r.report(e,{...t,connection_id:this.peer.getConnectionId(),group_connection_id:this.peer.getGroupConnectionId()},i)}_reportRtcInvokeStatus(e,t,i=0,r="",o){this._report("rtc_invoke_status",{sdk_api_name:e,message:t,error_code:i,stream_id:r,elapse:0},o)}}const logger$2=new Logger$1("queue",4);var SdpStrategy=(e=>(e[e.ADD=0]="ADD",e[e.CLOSE=1]="CLOSE",e))(SdpStrategy||{}),SdpAction=(e=>(e.publish="publish",e.unpublish="unpublish",e.subscribe="subscribe",e.unsubscribe="unsubscribe",e.pushtrack="pushtrack",e.removetrack="removetrack",e))(SdpAction||{});const negativedAction={publish:"unpublish",subscribe:"unsubscribe",pushtrack:"removetrack"},aggregationSdpStrategy={publish:0,subscribe:0,pushtrack:0,unpublish:1,unsubscribe:1,removetrack:1};class SdpQueue extends EventEmitter2{constructor(){super(),__publicField(this,"_queue"),this._queue=[]}get queue(){return this._queue}enqueue(e){const t=this._queue.length;let i="";return this._queue=this._queue.filter((t=>t.streamId!==e.streamId||e.action!==negativedAction[t.action]||(i=t.streamId,logger$2.info("offsetStreamId",i),!1))),this._queue.length===t&&this._queue.push(e),this.emit("start"),i}dequeue(){if(!this._queue.length)return null;let e=this._queue.length;isChrome&&chromeVersion>=86&&chromeVersion<=92&&(e=Math.min(this._queue.length,5));const t=aggregationSdpStrategy[this._queue[0].action];for(let i=1;i<e;i++)if(aggregationSdpStrategy[this._queue[i].action]!==t)return{sdpStrategy:t,items:this._queue.splice(0,i)};return{sdpStrategy:t,items:this._queue.splice(0,e)}}destroy(){this._queue=[]}}const encodedTransformSupported$2=isLegacyEncodedTransformSupported()||isEncodedTransformSupported();class ChromeHandler extends BasicHandler{constructor(e,t){var i;super(e,t),__publicField(this,"name","chrome"),__publicField(this,"_queueBusy",!1),__publicField(this,"_sdpQueue"),__publicField(this,"_aSendonlyOfferTpl"),__publicField(this,"_vSendonlyOfferTpl"),__publicField(this,"_aRecvonlyOfferTpl"),__publicField(this,"_vRecvonlyOfferTpl"),__publicField(this,"_mid",10),__publicField(this,"_inactiveMlineIndex",[]),__publicField(this,"setDescription"),this.logger=new Logger$1("ChromeHandler",3,e.id),this.setDescription=t.setDescription.bind(t),this._sdpQueue=new SdpQueue,this._sdpQueue.on("start",(()=>{this._queueBusy||"stable"!==this._peerConnection.signalingState||(this.logger.info("dequeue start"),this.dequeue())})),null==(i=this._context.monitor)||i.set({handler_mode:"chrome"})}destroy(){super.destroy(),this._sdpQueue.destroy()}async publish(e){var t;const{stream:i,enableSimulcast:r}=e,{videoDescriptions:o,subVideoDescriptions:s,audioTransceiverInit:n,videoTransceiverInit:a}=super.internalPublish(e),d=generateAllSsrc(this._nextSsrc);this._nextSsrc=d.next;const c=""+this._mid++,l=""+this._mid++,u={...this._aSendonlyOfferTpl,...this.peer._offerIce,mid:c,msid:`${i.id} ${i.id}-audio`,ssrcs:generateSsrc(i.id,"audio",d.audio,clientCname)},_={...this._vSendonlyOfferTpl,...this.peer._offerIce,mid:l,msid:`${i.id} ${i.id}-video`};if(r){this.logger.info("subVideoDesc","desc: %o ",s),delete _.ssrcGroups,delete _.ssrcs;const e=[];_.rids=o.map((({rid:t})=>(e.unshift(t),{id:t,direction:"send"}))),_.simulcast={dir1:"send",list1:e.join(";")}}else{const{ssrcs:e,ssrcGroups:t}=generateSsrcs(i.id,d,{cname:clientCname});_.ssrcs=e,_.ssrcGroups=t}if((null==(t=this._context.serverConfig)?void 0:t.audioRed)&&Array.isArray(u.rtp)){this.logger.info("audioCodec","use Red");const e=u.rtp.findIndex((e=>"red"===e.codec));if(-1!==e){const[t]=u.rtp.splice(e,1);u.rtp.unshift(t)}const t=[];u.rtp.forEach((e=>t.push(e.payload))),u.payloads=t.join(" ")}Array.isArray(_.ext)&&(getParameter("IOS_SAFARI_ORIENTATION")||!isSafari&&!isIOS||(_.ext=_.ext.filter((e=>{var t;return!(null==(t=null==e?void 0:e.uri)?void 0:t.includes("video-orientation"))}))),_.ext=_.ext.filter((e=>{var t;return!(null==(t=null==e?void 0:e.uri)?void 0:t.includes("framemarking"))})));const h=null==u?void 0:u.rtp.find((e=>"opus"===e.codec));if(h&&u.fmtp){const e=u.fmtp.find((e=>e.payload===h.payload));e&&this._context.audioProfileManager&&(e.config=this._context.audioProfileManager.getOpusConfigStr(e.config))}return r||isSafari||this.addBitrateLimit(_,e.videoEncodeConfig[0].maxKbps),e.audioMLine=u,e.videoMLine=_,{partialSdp:getLocalPartialSdp(this.peer._offerSession,u,_),audioMid:c,videoMid:l,type:"incroffer",semantics:"unified-plan",videoDescriptions:o,subVideoDescriptions:s,audioTransceiverInit:n,videoTransceiverInit:a,peerConnectionMode:this.peerConnectionMode}}async subscribe(e,t){this.logger.info("subscribe");if(!this._aRecvonlyOfferTpl||!this._vRecvonlyOfferTpl){const e=await this._genOfferSdp();await this.createAVMlineOfferTpl(e)}let i,r,o,s,n="",a="",d=!1,c=!1;e.audioMLine=i,e.videoMLine=r,e.virtual?(n=""+this._mid++,d=!0):t.multiChatMode?(n=""+this._mid++,a=""+this._mid++,c=!0):(d=!0,c=!0,n=""+this._mid++,a=""+this._mid++),n&&(i={...cloneDeep(this._aRecvonlyOfferTpl),mid:n}),d&&(e.audioMLine=i,o={track:"audio",init:{direction:"recvonly"}}),a&&(r={...cloneDeep(this._vRecvonlyOfferTpl),mid:a}),c&&(e.videoMLine=r,s={track:"video",init:{direction:"recvonly"}});const l=getLocalPartialSdp(this.peer._offerSession,i,r);let u,_;if(!e.enableVendorMode&&!t.multiChatMode&&!e.virtual&&this._aSendonlyAnswerTpl&&this._vSendonlyAnswerTpl){u=generateAllSsrc(this._nextSsrc),this._nextSsrc=u.next;const t={...this._aSendonlyAnswerTpl,...this.peer._answerIce,mid:n,msid:`${e.streamId}${this._context.avSync?"":"-audio"} ${e.streamId}-audio`,ssrcs:generateSsrc(e.streamId,"audio",u.audio)},i={...this._vSendonlyAnswerTpl,...this.peer._answerIce,mid:a,msid:`${e.streamId}${this._context.avSync?"":"-video"} ${e.streamId}-video`,...generateSsrcs(e.streamId,u,{flexfec:this._enableSubFlexfec})};_={sdp:lib.write({...this.peer._answerSession,media:[t,i]}),sequenceId:e.sequenceId?++e.sequenceId:0},null==u||delete u.next}const h=null==i?void 0:i.rtp.find((e=>"opus"===e.codec));if(h&&(null==i?void 0:i.fmtp)){const e=null==i?void 0:i.fmtp.find((e=>e.payload===h.payload));e&&this._context&&(e.config+=";stereo=1;sprop-stereo=1")}if(e.isPublic&&chromeVersion>=86){const e=null==r?void 0:r.rtp.filter((e=>"H264"===e.codec));(null==e?void 0:e.length)&&(null==r?void 0:r.fmtp)&&(null==r||r.fmtp.forEach((t=>{e.find((e=>e.payload===t.payload))&&(t.config+=";sps-pps-idr-in-keyframe=1")})))}return{partialSdp:l,audioMid:n,videoMid:a,type:"incroffer",semantics:"unified-plan",audioTransceiverInit:o,videoTransceiverInit:s,allSsrc:u,peerConnectionMode:this.peerConnectionMode,signalingAck:_}}async handleAck(e){return this.logger.info("handleAck()","item: %o",e),this._sdpQueue.enqueue(e)}async dequeue(){var e,t;this._queueBusy=!0;const i=this._sdpQueue.dequeue();if(this.logger.info("dequeue()","ret: %o",i),!i)return void(this._queueBusy=!1);const r=[];try{const{items:o,sdpStrategy:s}=i,n=[],a=[],d=[];if(s===SdpStrategy.ADD){delete{...this.peer._answerIce}.candidates;for await(const i of o){const{audioMid:o,videoMid:s,action:c,audioTransceiverInit:l,videoTransceiverInit:u,signalingAck:_,stream:h,videoCodec:p,onSuccess:m,onFail:S}=i,g=h instanceof RemoteStream;if(m&&d.push(m),S&&r.push(S),g&&_.sequenceId<h.sequenceId)break;const v=lib.parse(_.sdp);if(!Array.isArray(v.media))break;v.media.sort(((e,t)=>{var i;return null==(i=null==e?void 0:e.type)?void 0:i.localeCompare(null==t?void 0:t.type)}));const f=v.media.find((e=>"audio"===e.type)),E=v.media.find((e=>"video"===e.type));if(!f||!E)break;const T={...f,...this.peer._answerIce,mid:o},R={...E,...this.peer._answerIce,mid:s},{audioMLine:b,videoMLine:y,audioTransceiver:I,videoTransceiver:C}=h;if(b){let t=this.peer._offerMlines.findIndex((e=>e.mid===o));if(I){if(this._reportRtcInvokeStatus("chromeHandler.updateTrack",JSON.stringify({audioStreamTrack:mediaTrackStringify(null==(e=h.audioTrack)?void 0:e.preprocessingTrack)})),-1===t){this.logger.error("dequeue","audio mid not found when update sdp, %s from %o",o,this.peer._offerMlines);continue}}else l&&b&&(h.audioTransceiver=this._peerConnection.addTransceiver(l.track,l.init),this._reportRtcInvokeStatus("chromeHandler.addTrack",JSON.stringify({audioStreamTrack:mediaTrackStringify(l.track)})),t=this._inactiveMlineIndex.shift(),t||(t=this.peer._offerMlines.length),encodedTransformSupported$2&&h.initAudioEncodedTransform());c===SdpAction.publish&&"OPUS"!==getParameter("AUDIO_CODEC")&&(setAudioCodecPreferences(b,getParameter("AUDIO_CODEC")),setAudioCodecPreferences(T,getParameter("AUDIO_CODEC"))),this.peer._offerMlines[t]={...b},this.peer._answerMlines[t]={...T}}if(y){let e=this.peer._offerMlines.findIndex((e=>e.mid===s));if(C){if(this._reportRtcInvokeStatus("chromeHandler.updateTrack",JSON.stringify({audioStreamTrack:mediaTrackStringify(null==(t=h.videoTrack)?void 0:t.preprocessingTrack)})),-1===e){this.logger.error("dequeue","video mid not found when update sdp, %s from %o",s,this.peer._offerMlines);continue}}else u&&y&&(h.videoTransceiver=this._peerConnection.addTransceiver(u.track,u.init),this._reportRtcInvokeStatus("chromeHandler.addTrack",JSON.stringify({videoStreamTrack:mediaTrackStringify(u.track)})),e=this._inactiveMlineIndex.shift(),e||(e=this.peer._offerMlines.length),encodedTransformSupported$2&&h.initVideoEncodedTransform());this.peer._offerMlines[e]={...y},c===SdpAction.publish&&p&&(setCodecPreferences(y,p),setCodecPreferences(R,p)),this.peer._answerMlines[e]=R}n.push(h.streamId||""),a.push(g?h.userId:"local"),g&&(h.sequenceId=_.sequenceId)}}else{const e={};o.forEach((t=>{const{audioMid:i,videoMid:r,action:o}=t;e[i]=i,o!==SdpAction.removetrack&&(e[r]=r),e[i]=i})),this.peer._offerMlines=this.peer._offerMlines.map(((t,i)=>(t.mid&&e[t.mid]&&(t=closeMline(t),this._inactiveMlineIndex.push(i)),t))),this._inactiveMlineIndex=[...new Set(this._inactiveMlineIndex)],this._inactiveMlineIndex.sort(((e,t)=>e-t)),this.peer._answerMlines=this.peer._answerMlines.map((t=>(t.mid&&e[t.mid]&&(t=closeMline(t)),t)))}try{await this.peer.getOriginRTCPeerConnection().createOffer(),await this.setDescription(n.length?{streamId:n.join(","),streamUserId:a.join(",")}:void 0)}catch(e){throw"have-local-offer"===this._peerConnection.signalingState&&await this._peerConnection.setLocalDescription({type:"rollback"}),e}try{d.forEach((e=>e()))}catch(e){}this.logger.info("dequeue","loop")}catch(e){this.logger.error("dequeue","unknown error: %o",e),r.forEach((t=>t(e)))}finally{this.dequeue()}}async getDefaultSdp(){const e=await this._genOfferSdp();this.createAVMlineOfferTpl(e);const t=lib.parse(e),i=[];return t.media=t.media.filter((e=>"recvonly"===e.direction&&(Array.isArray(e.ext)&&(e.ext=e.ext.filter((e=>"urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id"!==e.uri))),i.push(`${e.mid}`),!0))),t.groups=[{mids:i.join(" "),type:"BUNDLE"}],isRRTRSupported&&pushRRTR(t),{sdp:lib.write(t),semantics:"unified-plan",type:"incroffer"}}async rollback({stream:e}){e instanceof LocalStream||await this.handleAck({action:SdpAction.unsubscribe,streamId:e.streamId,audioMid:e.audioMid,videoMid:e.videoMid,stream:e}),delete e.audioMLine,delete e.videoMLine}createAVMlineOfferTpl(e){const t=lib.parse(e);t.media.forEach((e=>{e.icePwd=this.peer._offerIce.icePwd,e.iceUfrag=this.peer._offerIce.iceUfrag,"audio"===e.type?"sendonly"===e.direction?this._aSendonlyOfferTpl=e:(Array.isArray(e.ext)&&(e.ext=e.ext.filter((e=>"urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id"!==e.uri))),this._aRecvonlyOfferTpl=e):"video"===e.type&&("sendonly"===e.direction?this._vSendonlyOfferTpl=e:(Array.isArray(e.ext)&&(e.ext=e.ext.filter((e=>"urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id"!==e.uri))),this._vRecvonlyOfferTpl=e))})),isRRTRSupported&&pushRRTR(t)}async _genOfferSdp(){let e;try{if(e=await createDefaultSdp(!0),!e)throw"pc.createOffer() return empty."}catch(e){const t="Get offer Error. "+(e.message|e);throw new SDKError(ErrorCode.NOT_SUPPORTED,t)}return e}}class FirefoxHandler extends BasicHandler{constructor(e,t){var i;super(e,t),__publicField(this,"name","firefox"),__publicField(this,"_aRecvonlyOfferTpl"),this.logger=new Logger$1("FirefoxHandler",3,e.id),null==(i=this._context.monitor)||i.set({handler_mode:"firefox"})}async publish(e){var t,i;const{videoDescriptions:r,subVideoDescriptions:o,audioTransceiverInit:s,videoTransceiverInit:n}=super.internalPublish(e);e.audioTransceiver=this._peerConnection.addTransceiver(s.track,s.init),Array.isArray(n.init.sendEncodings)&&1===n.init.sendEncodings.length&&(n.init.sendEncodings=n.init.sendEncodings.map((e=>(delete e.rid,e)))),e.videoTransceiver=this._peerConnection.addTransceiver(n.track,n.init);const a=getServerNow();this._report("rtc_begin_create_offer",{direction:"up",stream_id:"",stream_user_id:"",pc_session_id:this.peerConnectionId,vendor_mode:0});const d=await this.peer.createOfferSdp();this._report("rtc_create_offer",{direction:"up",error_code:0,stream_id:"",stream_user_id:"",elapse:getServerNow()-a});const c=lib.parse(d);c.media=null==(t=c.media)?void 0:t.map((e=>({...e,...this.peer._offerIce}))),pushRRTR(c),await this.setLocalDescription(lib.write(c));const l=e.audioTransceiver.mid,u=e.videoTransceiver.mid;let _=null,h=null;return c.media=null==(i=c.media)?void 0:i.map((e=>{var t;if(`${e.mid}`===l){_=e;const i=null==_?void 0:_.rtp.find((e=>"opus"===e.codec));if(i&&_.fmtp){const e=_.fmtp.find((e=>e.payload===i.payload));e&&(null==(t=this._context)?void 0:t.audioProfileManager)&&(e.config=this._context.audioProfileManager.getOpusConfigStr(e.config))}}else`${e.mid}`===u&&(h=e);return e})),this.addBitrateLimit(h,e.videoEncodeConfig[0].maxKbps),await this.setLocalDescription(lib.write(c)),e.initVideoEncodedTransform(),e.initAudioEncodedTransform(),{partialSdp:getLocalPartialSdp(c,_,h),audioMid:l,videoMid:u,type:"incroffer",semantics:"unified-plan",videoDescriptions:r,subVideoDescriptions:o,audioTransceiverInit:s,videoTransceiverInit:n,peerConnectionMode:this.peerConnectionMode}}async _internalChangePubCodec(){const{localDescription:e}=this._peerConnection;e&&(await this.peer.createOfferSdp(),await this._peerConnection.setLocalDescription(e))}async subscribe(e,t){var i,r,o,s,n,a;this.logger.info("subscribe()");let d,c,l="",u="",_=!1,h=!1;e.virtual?_=!0:(t.multiChatMode||(_=!0),h=!0),_&&(e.audioTransceiver=this._peerConnection.addTransceiver("audio",{direction:"recvonly"})),h&&(e.videoTransceiver=this._peerConnection.addTransceiver("video",{direction:"recvonly"}));const p=getServerNow();this._report("rtc_begin_create_offer",{direction:"up",stream_id:e.streamId,stream_user_id:e.userId,pc_session_id:this.peerConnectionId,vendor_mode:0});const m=await this.peer.createOfferSdp();this._report("rtc_create_offer",{error_code:0,direction:"up",stream_id:e.streamId,stream_user_id:e.userId,elapse:getServerNow()-p});const S=lib.parse(m);let g,v;if(S.media=null==(i=S.media)?void 0:i.map((e=>({...e,...this.peer._offerIce}))),S.media.map((e=>{var t,i,r,o;"video"===e.type&&(isTransportCCSupport?(e.ext=null==(t=e.ext)?void 0:t.filter((e=>-1===e.uri.indexOf("abs-send-time"))),e.rtcpFb=null==(i=e.rtcpFb)?void 0:i.filter((e=>"goog-remb"!==e.type))):(e.rtcpFb=null==(r=e.rtcpFb)?void 0:r.filter((e=>"transport-cc"!==e.type)),e.ext=null==(o=e.ext)?void 0:o.filter((e=>-1===e.uri.indexOf("transport")))))})),isRRTRSupported&&pushRRTR(S),await this.setLocalDescription(lib.write(S),{streamId:e.streamId||"",streamUserId:e.userId}),l=null==(r=e.audioTransceiver)?void 0:r.mid,u=null==(o=e.videoTransceiver)?void 0:o.mid,null==(s=S.media)||s.forEach((e=>{`${e.mid}`===l?d=e:`${e.mid}`===u&&(c=e)})),l&&d||(l=`audio_${u}`,d={...this._aRecvonlyOfferTpl,mid:l}),e.audioMid=l,e.videoMid=u,!t.multiChatMode&&!e.virtual&&this._aSendonlyAnswerTpl&&this._aSendonlyAnswerTpl){g=generateAllSsrc(this._nextSsrc),this._nextSsrc=g.next;const t={...this._aSendonlyAnswerTpl,...this.peer._answerIce,mid:l,msid:`${e.streamId}${(null==(n=this._context)?void 0:n.avSync)?"":"-audio"} ${e.streamId}-audio`,ssrcs:generateSsrc(e.streamId,"audio",g.audio)},i={...this._vSendonlyAnswerTpl,...this.peer._answerIce,mid:u,msid:`${e.streamId}${(null==(a=this._context)?void 0:a.avSync)?"":"-video"} ${e.streamId}-video`,...generateSsrcs(e.streamId,g,{flexfec:this._enableSubFlexfec})};v={sdp:lib.write({...this.peer._answerSession,media:[t,i]}),sequenceId:e.sequenceId?++e.sequenceId:0},null==g||delete g.next}return e.initVideoEncodedTransform(),e.initAudioEncodedTransform(),{partialSdp:getLocalPartialSdp(S,d,c,!1),audioMid:l,videoMid:u,type:"incroffer",semantics:"unified-plan",audioTransceiverInit:e.audioTransceiver?{track:"audio",init:{direction:"recvonly"}}:void 0,videoTransceiverInit:e.videoTransceiver?{track:"video",init:{direction:"recvonly"}}:void 0,allSsrc:g,peerConnectionMode:this.peerConnectionMode,signalingAck:v}}async handleAck(e){const{stream:t,action:i}=e;if(i===SdpAction.removetrack)return"";if(i===SdpAction.unpublish||i===SdpAction.unsubscribe){try{await this.close(t),"function"==typeof e.onSuccess&&e.onSuccess()}catch(t){"function"==typeof e.onFail&&e.onFail(t)}return t.streamId||""}const{signalingAck:r,videoCodec:o}=e,s=lib.parse(r.sdp);try{await this._internalSetRemoteDescription(s.media,t,o),"function"==typeof e.onSuccess&&e.onSuccess()}catch(t){"function"==typeof e.onFail&&e.onFail(t)}return""}async _internalSetRemoteDescription(e,t,i){var r,o;const s={},n=lib.parse(null==(r=this._peerConnection.remoteDescription)?void 0:r.sdp);n.media.forEach((e=>{void 0!==e.mid&&(s[e.mid]=e)})),e.forEach((e=>{if("audio"===(e={...e,...this.peer._answerIce}).type&&(t.audioMid?(e.mid=t.audioMid,s[t.audioMid]=e):s[e.mid]=e),"video"===e.type){if(t instanceof LocalStream&&firefoxVersion<=87){const t={};Array.isArray(e.rtp)&&(e.rtp=e.rtp.filter((e=>"rtx"!==e.codec||(t[e.payload]=e.payload,!1)))),"string"==typeof e.payloads&&(e.payloads=e.payloads.split(" ").filter((e=>!t[e])).join(" ")),Array.isArray(e.fmtp)&&(e.fmtp=e.fmtp.filter((e=>!t[e.payload]))),Array.isArray(e.rtcpFb)&&(e.fmtp=e.fmtp.filter((e=>!t[e.payload])))}i&&setCodecPreferences(e,i),t.videoMid?(e.mid=t.videoMid,s[t.videoMid]=e):s[e.mid]=e}}));const a=lib.parse(null==(o=this._peerConnection.localDescription)?void 0:o.sdp),d=a.media.map((e=>{const t=s[e.mid];return"inactive"===e.direction?e:t}));n.groups=a.groups,n.media=d,n.media.map((e=>{var t,i,r,o,s;"video"===e.type&&(isTransportCCSupport?(e.ext=null==(t=e.ext)?void 0:t.filter((e=>-1===e.uri.indexOf("abs-send-time"))),e.rtcpFb=null==(i=e.rtcpFb)?void 0:i.filter((e=>"goog-remb"!==e.type))):(e.rtcpFb=null==(r=e.rtcpFb)?void 0:r.filter((e=>"transport-cc"!==e.type)),e.ext=null==(o=e.ext)?void 0:o.filter((e=>-1===e.uri.indexOf("transport")))),firefoxVersion>=138&&(e.ext=null==(s=e.ext)?void 0:s.filter((e=>!e.uri.includes("sdes:mid")))))})),isRRTRSupported&&pushRRTR(n),await this.setRemoteDescription(lib.write(n))}async getDefaultSdp(){const e=new RTCPeerConnection;e.addTransceiver("audio",{direction:"recvonly"}),e.addTransceiver("video",{direction:"recvonly"});const t=await e.createOffer(),i=lib.parse(t.sdp);this.createAVMlineOfferTpl(t.sdp);const r=[];return i.media=i.media.filter((e=>{if("recvonly"===e.direction){const t=`template_${e.type}`;return e.mid=t,r.push(t),!0}return!1})),isRRTRSupported&&pushRRTR(i),i.groups=[{mids:r.join(" "),type:"BUNDLE"}],e.close(),{sdp:lib.write(i),semantics:"unified-plan",type:"incroffer"}}async rollback({msid:e,stream:t,audioMid:i,videoMid:r}){return this.logger.warn("rollback()"),this.close(t,i,r)}async close(e,t,i){var r;this.logger.info("close()");const o=e.audioMid||t,s=e.videoMid||i,n={};e.audioTransceiver&&o&&(e.audioTransceiver.stop(),n[o]=o),e.videoTransceiver&&s&&(e.videoTransceiver.stop(),n[s]=s);const a=[],d=await this.peer.createOfferSdp(),c=lib.parse(d);c.media=c.media.map((e=>(n[e.mid]&&(e=closeMline(e)),"inactive"!==e.direction&&a.push(e.mid),{...e,...this.peer._offerIce})));const l=lib.parse(null==(r=this._peerConnection.remoteDescription)?void 0:r.sdp),u={};l.media.forEach((e=>{void 0!==e.mid&&(u[e.mid]=e)})),l.media=c.media.map((e=>"inactive"===e.direction?e:u[e.mid])),c.groups&&l.groups&&(c.groups[0].mids=a.join(" "),l.groups[0].mids=a.join(" ")),await this.setLocalDescription(lib.write(c)),await this.setRemoteDescription(lib.write(l))}async setCurrentDescription(){await this.peer.createOfferSdp(),this._peerConnection.localDescription&&this._peerConnection.remoteDescription&&(await this._peerConnection.setLocalDescription(this._peerConnection.localDescription),await this._peerConnection.setRemoteDescription(this._peerConnection.remoteDescription))}createAVMlineOfferTpl(e){const t=lib.parse(e);t.media.forEach((e=>{"audio"===e.type&&(this._aRecvonlyOfferTpl=e)})),isRRTRSupported&&pushRRTR(t)}}class FallbackHandler extends BasicHandler{constructor(e,t){var i,r;super(e,t),__publicField(this,"name","fallback"),__publicField(this,"_aRecvonlyOfferTpl"),this.logger=new Logger$1("FallbackHandler",3,e.id),this.logger.warn("ctor","using fallback handler"),null==(i=this._context.monitor)||i.report("rtc_error",{message:"using fallback handler",error_code:-1}),null==(r=this._context.monitor)||r.set({handler_mode:"fallback"})}async publish(e){var t;const{videoDescriptions:i,subVideoDescriptions:r,audioTransceiverInit:o,videoTransceiverInit:s}=super.internalPublish(e);e.audioTransceiver=this._peerConnection.addTransceiver(o.track,o.init),Array.isArray(s.init.sendEncodings)&&1===s.init.sendEncodings.length&&(s.init.sendEncodings=s.init.sendEncodings.map((e=>(delete e.rid,e)))),e.videoTransceiver=this._peerConnection.addTransceiver(s.track,s.init);const n=getServerNow();this._report("rtc_begin_create_offer",{direction:"up",stream_id:"",stream_user_id:"",pc_session_id:this.peerConnectionId,vendor_mode:0});const a=await this.peer.createOfferSdp();this._report("rtc_create_offer",{direction:"up",error_code:0,stream_id:"",stream_user_id:"",elapse:getServerNow()-n});const d=lib.parse(a);await this.setLocalDescription(a);const c=e.audioTransceiver.mid,l=e.videoTransceiver.mid;let u=null,_=null;return d.media=null==(t=d.media)?void 0:t.map((e=>(`${e.mid}`===c?u=e:`${e.mid}`===l&&(_=e),e))),e.initVideoEncodedTransform(),e.initAudioEncodedTransform(),{partialSdp:getLocalPartialSdp(d,u,_),audioMid:c,videoMid:l,type:"incroffer",semantics:"unified-plan",videoDescriptions:i,subVideoDescriptions:r,audioTransceiverInit:o,videoTransceiverInit:s,peerConnectionMode:this.peerConnectionMode}}async _internalChangePubCodec(){const{localDescription:e}=this._peerConnection;e&&(await this.peer.createOfferSdp(),await this._peerConnection.setLocalDescription(e))}async subscribe(e,t){var i,r,o,s,n;this.logger.info("subscribe()");let a,d,c="",l="",u=!1,_=!1;e.virtual?u=!0:(t.multiChatMode||(u=!0),_=!0),u&&(e.audioTransceiver=this._peerConnection.addTransceiver("audio",{direction:"recvonly"})),_&&(e.videoTransceiver=this._peerConnection.addTransceiver("video",{direction:"recvonly"}));const h=getServerNow();this._report("rtc_begin_create_offer",{direction:"up",stream_id:e.streamId,stream_user_id:e.userId,pc_session_id:this.peerConnectionId,vendor_mode:0});const p=await this.peer.createOfferSdp();this._report("rtc_create_offer",{error_code:0,direction:"up",stream_id:e.streamId,stream_user_id:e.userId,elapse:getServerNow()-h});const m=lib.parse(p);let S,g;if(await this.setLocalDescription(p,{streamId:e.streamId||"",streamUserId:e.userId}),c=null==(i=e.audioTransceiver)?void 0:i.mid,l=null==(r=e.videoTransceiver)?void 0:r.mid,null==(o=m.media)||o.forEach((e=>{`${e.mid}`===c?a=e:`${e.mid}`===l&&(d=e)})),c&&a||(c=`audio_${l}`,a={...this._aRecvonlyOfferTpl,mid:c}),e.audioMid=c,e.videoMid=l,!t.multiChatMode&&!e.virtual&&this._aSendonlyAnswerTpl&&this._aSendonlyAnswerTpl){S=generateAllSsrc(this._nextSsrc),this._nextSsrc=S.next;const t={...this._aSendonlyAnswerTpl,...this.peer._answerIce,mid:c,msid:`${e.streamId}${(null==(s=this._context)?void 0:s.avSync)?"":"-audio"} ${e.streamId}-audio`,ssrcs:generateSsrc(e.streamId,"audio",S.audio)},i={...this._vSendonlyAnswerTpl,...this.peer._answerIce,mid:l,msid:`${e.streamId}${(null==(n=this._context)?void 0:n.avSync)?"":"-video"} ${e.streamId}-video`,...generateSsrcs(e.streamId,S,{flexfec:this._enableSubFlexfec})};g={sdp:lib.write({...this.peer._answerSession,media:[t,i]}),sequenceId:e.sequenceId?++e.sequenceId:0},null==S||delete S.next}return e.initVideoEncodedTransform(),e.initAudioEncodedTransform(),{partialSdp:getLocalPartialSdp(m,a,d,!1),audioMid:c,videoMid:l,type:"incroffer",semantics:"unified-plan",audioTransceiverInit:e.audioTransceiver?{track:"audio",init:{direction:"recvonly"}}:void 0,videoTransceiverInit:e.videoTransceiver?{track:"video",init:{direction:"recvonly"}}:void 0,allSsrc:S,peerConnectionMode:this.peerConnectionMode,signalingAck:g}}async handleAck(e){const{stream:t,action:i}=e;if(i===SdpAction.removetrack)return"";if(i===SdpAction.unpublish||i===SdpAction.unsubscribe){try{await this.close(t),"function"==typeof e.onSuccess&&e.onSuccess()}catch(t){"function"==typeof e.onFail&&e.onFail(t)}return t.streamId||""}const{signalingAck:r,videoCodec:o}=e,s=lib.parse(r.sdp);try{await this._internalSetRemoteDescription(s.media,t,o),"function"==typeof e.onSuccess&&e.onSuccess()}catch(t){"function"==typeof e.onFail&&e.onFail(t)}return""}async _internalSetRemoteDescription(e,t,i){var r,o;const s={},n=lib.parse(null==(r=this._peerConnection.remoteDescription)?void 0:r.sdp);n.media.forEach((e=>{void 0!==e.mid&&(s[e.mid]=e)})),e.forEach((e=>{"audio"===(e={...e,...this.peer._answerIce}).type&&(t.audioMid?(e.mid=t.audioMid,s[t.audioMid]=e):s[e.mid]=e),"video"===e.type&&(i&&setCodecPreferences(e,i),t.videoMid?(e.mid=t.videoMid,s[t.videoMid]=e):s[e.mid]=e)}));const a=lib.parse(null==(o=this._peerConnection.localDescription)?void 0:o.sdp),d=a.media.map((e=>{const t=s[e.mid];return"inactive"===e.direction?e:t}));n.groups=a.groups,n.media=d,n.media.map((e=>{var t,i,r,o;"video"===e.type&&(isTransportCCSupport?(e.ext=null==(t=e.ext)?void 0:t.filter((e=>-1===e.uri.indexOf("abs-send-time"))),e.rtcpFb=null==(i=e.rtcpFb)?void 0:i.filter((e=>"goog-remb"!==e.type))):(e.rtcpFb=null==(r=e.rtcpFb)?void 0:r.filter((e=>"transport-cc"!==e.type)),e.ext=null==(o=e.ext)?void 0:o.filter((e=>-1===e.uri.indexOf("transport")))))})),await this.setRemoteDescription(lib.write(n))}async getDefaultSdp(){const e=new RTCPeerConnection;e.addTransceiver("audio",{direction:"recvonly"}),e.addTransceiver("video",{direction:"recvonly"});const t=await e.createOffer(),i=lib.parse(t.sdp);this.createAVMlineOfferTpl(t.sdp);const r=[];return i.media=i.media.filter((e=>{if("recvonly"===e.direction){const t=`template_${e.type}`;return e.mid=t,r.push(t),!0}return!1})),i.groups=[{mids:r.join(" "),type:"BUNDLE"}],e.close(),{sdp:lib.write(i),semantics:"unified-plan",type:"incroffer"}}async rollback({msid:e,stream:t,audioMid:i,videoMid:r}){return this.logger.warn("rollback()"),this.close(t,i,r)}async close(e,t,i){var r;this.logger.info("close()");const o=e.audioMid||t,s=e.videoMid||i,n={};e.audioTransceiver&&o&&(e.audioTransceiver.stop(),n[o]=o),e.videoTransceiver&&s&&(e.videoTransceiver.stop(),n[s]=s);const a=[],d=await this.peer.createOfferSdp(),c=lib.parse(d);c.media=c.media.map((e=>(n[e.mid]&&(e=closeMline(e)),"inactive"!==e.direction&&a.push(e.mid),{...e,...this.peer._offerIce})));const l=lib.parse(null==(r=this._peerConnection.remoteDescription)?void 0:r.sdp),u={};l.media.forEach((e=>{void 0!==e.mid&&(u[e.mid]=e)})),l.media=c.media.map((e=>"inactive"===e.direction?e:u[e.mid])),c.groups&&l.groups&&(c.groups[0].mids=a.join(" "),l.groups[0].mids=a.join(" ")),await this.setLocalDescription(d),await this.setRemoteDescription(lib.write(l))}async setCurrentDescription(){await this.peer.createOfferSdp(),this._peerConnection.localDescription&&this._peerConnection.remoteDescription&&(await this._peerConnection.setLocalDescription(this._peerConnection.localDescription),await this._peerConnection.setRemoteDescription(this._peerConnection.remoteDescription))}createAVMlineOfferTpl(e){lib.parse(e).media.forEach((e=>{"audio"===e.type&&(this._aRecvonlyOfferTpl=e)}))}}var __defProp$8=Object.defineProperty,__getOwnPropDesc$8=Object.getOwnPropertyDescriptor,__decorateClass$8=(e,t,i,r)=>{for(var o,s=r>1?void 0:r?__getOwnPropDesc$8(t,i):t,n=e.length-1;n>=0;n--)(o=e[n])&&(s=(r?o(t,i,s):o(s))||s);return r&&s&&__defProp$8(t,i,s),s};class BatchProcessor{constructor(e){__publicField(this,"_queue",[]),__publicField(this,"_runningTask",[]),__publicField(this,"executor"),__publicField(this,"busy",!1),this.executor=e}add(e){const{promise:t,resolve:i,reject:r}=promiseWithResolves();return this._queue.push({item:e,resolve:i,reject:r}),this.busy||this._emit(),t}destroy(){[...this._queue,...this._runningTask].forEach((({reject:e})=>{e(new SDKError(ErrorCode.OPERATION_CANCEL,"queue close"))})),this.busy=!1,this._queue=[]}async _emit(){const e=this._queue;if(this._runningTask=e,this._queue=[],0===e.length)return void(this.busy=!1);const t=e.map((e=>e.item)),i=e.map((e=>e.resolve)),r=e.map((e=>e.reject));try{this.busy=!0;const e=await this.executor(t);i.forEach((t=>t(e)))}catch(e){r.forEach((t=>t(e)))}this._runningTask=[],setTimeout((()=>{this._emit()}))}}function encodedTransformSupported$1(){return isLegacyEncodedTransformSupported()||isEncodedTransformSupported()}class StandardHandler extends BasicHandler{constructor(e,t){var i;super(e,t),__publicField(this,"name","standard"),__publicField(this,"_applyQueue",new BatchProcessor(this.apply.bind(this))),__publicField(this,"_createQueue",new BatchProcessor(this.create.bind(this))),__publicField(this,"_pqueue",new PriorityQueue),__publicField(this,"_midMap",new Map),__publicField(this,"_aRecvonlyOfferTpl"),this.logger=new Logger$1("StandardHandler",3,e.id),this.logger.warn("ctor","using standard handler"),null==(i=this._context.monitor)||i.set({handler_mode:"standard"})}async publish(e){var t;this.logger.info("publish()",`streamId: ${e.streamId}`);const{videoDescriptions:i,subVideoDescriptions:r,audioTransceiverInit:o,videoTransceiverInit:s}=super.internalPublish(e);e.audioTransceiver=this._peerConnection.addTransceiver(o.track,{...o.init,direction:"sendonly"}),Array.isArray(s.init.sendEncodings)&&1===s.init.sendEncodings.length&&(s.init.sendEncodings=s.init.sendEncodings.map((e=>(delete e.rid,e)))),e.videoTransceiver=this._peerConnection.addTransceiver(s.track,{...s.init,direction:"sendonly"});const n=getServerNow();this._report("rtc_begin_create_offer",{direction:"up",stream_id:"",stream_user_id:"",pc_session_id:this.peerConnectionId,vendor_mode:0});const a=await this._createQueue.add();this._report("rtc_create_offer",{direction:"up",error_code:0,stream_id:"",stream_user_id:"",elapse:getServerNow()-n});const d=e.audioTransceiver.mid,c=e.videoTransceiver.mid;DCHECK(d&&c,"Transceiver not return MID after setLocalDescription"),e.audioMid=d,e.videoMid=c;let l=null,u=null;const _=lib.parse(a);return _.media=null==(t=_.media)?void 0:t.map((e=>(`${e.mid}`===d?l=e:`${e.mid}`===c&&(u=e),e))),encodedTransformSupported$1()&&(e.initVideoEncodedTransform(),e.initAudioEncodedTransform()),{partialSdp:getLocalPartialSdp(_,l,u),audioMid:d,videoMid:c,type:"incroffer",semantics:"unified-plan",videoDescriptions:i,subVideoDescriptions:r,audioTransceiverInit:o,videoTransceiverInit:s,peerConnectionMode:this.peerConnectionMode}}async subscribe(e,t){var i,r,o,s,n;this.logger.info("subscribe()",`streamId: ${e.streamId}`);let a,d,c=!1,l=!1;e.virtual?c=!0:(t.multiChatMode||(c=!0),l=!0),c&&(e.audioTransceiver=this._peerConnection.addTransceiver("audio",{direction:"recvonly"})),l&&(e.videoTransceiver=this._peerConnection.addTransceiver("video",{direction:"recvonly"}));const u=getServerNow();this._report("rtc_begin_create_offer",{direction:"up",stream_id:e.streamId,stream_user_id:e.userId,pc_session_id:this.peerConnectionId,vendor_mode:0});const _=await this._createQueue.add();this._report("rtc_create_offer",{error_code:0,direction:"up",stream_id:e.streamId,stream_user_id:e.userId,elapse:getServerNow()-u});let h=(null==(i=e.audioTransceiver)?void 0:i.mid)??void 0;const p=(null==(r=e.videoTransceiver)?void 0:r.mid)??void 0,m=lib.parse(_);let S,g;if(null==(o=m.media)||o.forEach((e=>{`${e.mid}`===h?a=e:`${e.mid}`===p&&(d=e)})),h&&a||(h=`audio_${p}`,a={...this._aRecvonlyOfferTpl,mid:h}),e.audioMid=h,e.videoMid=p,!t.multiChatMode&&!e.virtual&&this._aSendonlyAnswerTpl&&this._aSendonlyAnswerTpl){S=this._generateAllSsrc();const t={...this._aSendonlyAnswerTpl,...this.peer._answerIce,mid:h,msid:`${e.streamId}${(null==(s=this._context)?void 0:s.avSync)?"":"-audio"} ${e.streamId}-audio`,ssrcs:generateSsrc(e.streamId,"audio",S.audio)},i={...this._vSendonlyAnswerTpl,...this.peer._answerIce,mid:p,msid:`${e.streamId}${(null==(n=this._context)?void 0:n.avSync)?"":"-video"} ${e.streamId}-video`,...generateSsrcs(e.streamId,S,{flexfec:this._enableSubFlexfec})};g={sdp:lib.write({...this.peer._answerSession,media:[t,i]}),sequenceId:e.sequenceId?++e.sequenceId:0},null==S||delete S.next}return encodedTransformSupported$1()&&(e.initVideoEncodedTransform(),e.initAudioEncodedTransform()),{partialSdp:getLocalPartialSdp(m,a,d,!1),audioMid:h,videoMid:p||"",type:"incroffer",semantics:"unified-plan",audioTransceiverInit:e.audioTransceiver?{track:"audio",init:{direction:"recvonly"}}:void 0,videoTransceiverInit:e.videoTransceiver?{track:"video",init:{direction:"recvonly"}}:void 0,allSsrc:S,peerConnectionMode:this.peerConnectionMode,signalingAck:g}}async handleAck(e){const{stream:t,action:i}=e;if(i===SdpAction.removetrack)return"";if(i===SdpAction.unpublish||i===SdpAction.unsubscribe){try{await this.close(t),"function"==typeof e.onSuccess&&e.onSuccess()}catch(t){"function"==typeof e.onFail&&e.onFail(t)}return t.streamId||""}const{signalingAck:r,videoCodec:o}=e,s=lib.parse(r.sdp);try{await this._internalSetRemoteDescription(s.media,t,o),"function"==typeof e.onSuccess&&e.onSuccess()}catch(t){"function"==typeof e.onFail&&e.onFail(t)}return""}async _internalSetRemoteDescription(e,t,i){e.forEach((e=>{"audio"===(e={...e,...this.peer._answerIce}).type&&(t.audioMid?(e.mid=t.audioMid,this._midMap.set(t.audioMid,e)):this._midMap.set(e.mid,e)),"video"===e.type&&(i&&setCodecPreferences(e,i),t.videoMid?(e.mid=t.videoMid,this._midMap.set(t.videoMid,e)):this._midMap.set(e.mid,e))}));t instanceof LocalStream?this.handlePublishAction({stream:t,videoCodec:i}):this.handleSubscribeAction({stream:t}),await this._applyQueue.add()}handlePublishAction(e){var t;const{videoCodec:i,stream:r}=e,o=r.audioMid?this._midMap.get(r.audioMid):void 0,s=r.videoMid?this._midMap.get(r.videoMid):void 0;this._context.pcKillSwitch.sld_rtcpfb_rrtr_add&&isRRTRSupported&&(SDPTools.addRRTR(o),SDPTools.addRRTR(s));const n=(null==(t=this._context.serverConfig)?void 0:t.audioRed)?"RED":getParameter("AUDIO_CODEC");"OPUS"!==n&&o&&setAudioCodecPreferences(o,n),this._context.pcKillSwitch.sld_fmtp_opus_add&&SDPTools.decorateOpusConfig(o,this._context.audioProfileManager),isFirefox&&firefoxVersion<=87&&SDPTools.removeRtxInMLine(s),i&&s&&setCodecPreferences(s,i),this._context.pcKillSwitch.sld_ext_sdesmid_remove&&isFirefox&&firefoxVersion>=138&&SDPTools.removeExtSdesMid(s),this._context.pcKillSwitch.sld_fmtp_bitrate_add&&(r.enableSimulcast||isSafari||!s||this.addBitrateLimit(s,r.videoEncodeConfig[0].maxKbps)),isFirefox&&SDPTools.selectCC(s,isTransportCCSupport?"tcc":"remb"),r.audioMid&&o&&this._midMap.set(r.audioMid,o),r.videoMid&&s&&this._midMap.set(r.videoMid,s)}handleSubscribeAction(e){const{stream:t}=e,i=t.audioMid?this._midMap.get(t.audioMid):void 0,r=t.videoMid?this._midMap.get(t.videoMid):void 0;isFirefox||(SDPTools.removeRtpStreamId(i),SDPTools.removeRtpStreamId(r)),this._context.pcKillSwitch.sld_rtcpfb_rrtr_add&&isRRTRSupported&&(SDPTools.addRRTR(i),SDPTools.addRRTR(r)),this._context.pcKillSwitch.sld_fmtp_opus_add&&SDPTools.decorateOpusConfig(i),getParameter("IOS_SAFARI_ORIENTATION")||!isSafari&&!isIOS||SDPTools.removeExtVideoOrientation(r),this._context.pcKillSwitch.sld_fmtp_sps_add&&t.isPublic&&isChrome&&chromeVersion>=86&&SDPTools.decorateSpsPpsIdrInKeyframe(r),t.audioMid&&i&&this._midMap.set(t.audioMid,i),t.videoMid&&r&&this._midMap.set(t.videoMid,r)}async getDefaultSdp(){const e=new RTCPeerConnection;e.addTransceiver("audio",{direction:"recvonly"}),e.addTransceiver("video",{direction:"recvonly"});const t=await e.createOffer(),i=lib.parse(t.sdp);this.createAVMlineOfferTpl(t.sdp);const r=[];return i.media=i.media.filter((e=>{if("recvonly"===e.direction){const t=`template_${e.type}`;return e.mid=t,r.push(t),!0}return!1})),isRRTRSupported&&pushRRTR(i),i.groups=[{mids:r.join(" "),type:"BUNDLE"}],e.close(),{sdp:lib.write(i),semantics:"unified-plan",type:"incroffer"}}async rollback({msid:e,stream:t,audioMid:i,videoMid:r}){return this.logger.warn("rollback()"),this.close(t,i,r)}async close(e,t,i){this.logger.info("close()");const r=e.audioMid||t,o=e.videoMid||i;if(e.audioTransceiver&&r)try{e.audioTransceiver.stop(),delete e.audioTransceiver}catch{}if(e.videoTransceiver&&o)try{e.videoTransceiver.stop(),delete e.videoTransceiver}catch{}const s=r?this._midMap.get(r):void 0,n=o?this._midMap.get(o):void 0;s&&closeMline(s),n&&closeMline(n),r&&s&&this._midMap.set(r,s),o&&n&&this._midMap.set(o,n),await this._applyQueue.add()}async setCurrentDescription(){await this._applyQueue.add()}createAVMlineOfferTpl(e){lib.parse(e).media.forEach((e=>{"audio"===e.type&&(this._aRecvonlyOfferTpl=e)}))}_generateAllSsrc(){const e=generateAllSsrc(this._nextSsrc);return this._nextSsrc=e.next,e}async create(){this.logger.info("RTCPeerConnection create");const e=await this.peer.createOfferSdp();return DCHECK(e,"RTCPeerConnection not return SDP"),await this.peer.setLocalDescription(e),e}async apply(){this.logger.info("RTCPeerConnection apply");let e=await this.peer.createOfferSdp();DCHECK(e,"RTCPeerConnection not return SDP",e);const t=lib.parse(e);e=this.generateOffer(t,e);const i=this.generateAnswer(t);await this.setLocalDescription(e),await this.setRemoteDescription(i)}generateOffer(e,t){let i=!1;return"v1"===this.peer.getIceVersion()&&isFirefox&&(e.media=e.media.map((e=>({...e,...this.peer._offerIce}))),i=!0),this._context.pcKillSwitch.sld_fmtp_opus_add&&(e.media=e.media.map((e=>{if("audio"===e.type){const t="sendonly"===e.direction;SDPTools.decorateOpusConfig(e,t?this._context.audioProfileManager:void 0)}return e})),i=!0),this._context.pcKillSwitch.sld_rtcpfb_rrtr_add&&(e.media=e.media.map((e=>(!isRRTRSupported||"audio"!==e.type&&"video"!==e.type||SDPTools.addRRTR(e),e))),i=!0),i?lib.write(e):t}generateAnswer(e){const t=[];return e.media.forEach((e=>{if("application"===e.type){DCHECK(void 0!==e.mid,"should always have mid in mline",e);let i=this._midMap.get(e.mid);return i||(i=this.generateDCAnswer(e),this._midMap.set(e.mid,i)),void t.push({...i})}const i=`${e.mid}`;DCHECK(i,`No MID in offer m-line: ${e}`);let r=this._midMap.get(i);r||(this.logger.info("generateInactiveAnswerMLine","mid: %o, mLine: %o",e.mid,e),r=this.generateInactiveAnswerMLine(e)),t.push(r)})),this.peer.createAnswerSdp(t,e.groups)}generateInactiveAnswerMLine(e){return{...e,...this.peer._answerIce,direction:"inactive"}}generateDCAnswer(e){const t={...e,...this.peer._answerIce,sctpmap:{sctpmapNumber:5e3,app:"webrtc-datachannel",maxMessageSize:262144}};return isFirefox&&(delete t.bundleOnly,t.port=9),t}destroy(){super.destroy(),this._pqueue.destroy(),this._applyQueue.destroy(),this._createQueue.destroy()}}function highPLock(e,t,i){const r=i.value;return i.value=async function(...e){const i=this.logger;i.info("SDP Lock","pending task %o",t);const o=await this._pqueue.enqueue(0);i.info("SDP Lock","running task %o",t);try{return await(null==r?void 0:r.apply(this,e))}finally{i.info("SDP Lock","unlocking by task %o",t),o()}},i}function lowPLock(e,t,i){const r=i.value;return i.value=async function(...e){const i=this.logger;i.info("SDP Lock","pending task %o",t);const o=await this._pqueue.enqueue(1);i.info("SDP Lock","running task %o",t);try{return await(null==r?void 0:r.apply(this,e))}finally{i.info("SDP Lock","unlocking by task %o",t),o()}},i}__decorateClass$8([highPLock],StandardHandler.prototype,"create",1),__decorateClass$8([lowPLock],StandardHandler.prototype,"apply",1);const SDPTools={decorateOpusConfig(e,t){if(!e)return;const i=null==e?void 0:e.rtp.find((e=>"opus"===e.codec));if(!i||!e.fmtp)return;const r=e.fmtp.find((e=>e.payload===i.payload));r&&(t&&(r.config=t.getOpusConfigStr(r.config)),r.config=addStereo(r.config))},removeRtxInMLine(e){var t;if(!e)return;const i=[];e.rtp=e.rtp.filter((e=>("rtx"===e.codec&&i.push(e.payload),"rtx"!==e.codec))),e.fmtp=e.fmtp.filter((e=>i.includes(e.payload))),e.payloads=null==(t=e.payloads)?void 0:t.split(" ").filter((e=>!i.includes(parseInt(e)))).join(" ")},removeExtSdesMid(e){var t;e&&(e.ext=null==(t=e.ext)?void 0:t.filter((e=>!e.uri.includes("sdes:mid"))))},selectCC(e,t){var i,r,o,s;e&&("tcc"===t?(e.ext=null==(i=e.ext)?void 0:i.filter((e=>-1===e.uri.indexOf("abs-send-time"))),e.rtcpFb=null==(r=e.rtcpFb)?void 0:r.filter((e=>"goog-remb"!==e.type))):"remb"===t&&(e.rtcpFb=null==(o=e.rtcpFb)?void 0:o.filter((e=>"transport-cc"!==e.type)),e.ext=null==(s=e.ext)?void 0:s.filter((e=>-1===e.uri.indexOf("transport")))))},addRRTR(e){e&&e.rtp.forEach((t=>{e.rtcpFb||(e.rtcpFb=[]),e.rtcpFb.find((e=>e.payload===t.payload&&"rrtr"===e.type))||e.rtcpFb.push({payload:t.payload,type:"rrtr"})}))},removeRtpStreamId(e){e&&Array.isArray(e.ext)&&(e.ext=e.ext.filter((e=>"urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id"!==e.uri)))},decorateSpsPpsIdrInKeyframe(e){if(!e)return;const t=e.rtp.filter((e=>"H264"===e.codec));t.length&&e.fmtp&&e.fmtp.forEach((e=>{t.find((t=>t.payload===e.payload))&&(e.config+=";sps-pps-idr-in-keyframe=1")}))},removeExtVideoOrientation(e){e&&Array.isArray(e.ext)&&(e.ext=e.ext.filter((e=>!e.uri.includes("video-orientation"))))},removeExtFramemarking(e){e&&Array.isArray(e.ext)&&(e.ext=e.ext.filter((e=>!e.uri.includes("framemarking"))))}};class PriorityQueue{constructor(){__publicField(this,"queue",[]),__publicField(this,"processing",!1)}async enqueue(e=0){const{promise:t,resolve:i}=promiseWithResolves(),r={priority:e,resolve:i},o=this.queue.findIndex((t=>t.priority>e));return-1===o?this.queue.push(r):this.queue.splice(o,0,r),this.tryProcess(),await t,this.processing=!0,()=>{this.processing=!1,this.tryProcess()}}destroy(){this.queue.forEach((({resolve:e})=>{e()})),this.queue=[],this.processing=!1}tryProcess(){if(this.processing)return;const e=this.queue.shift();e&&e.resolve()}}function promiseWithResolves(){let e,t;const i=new Promise(((i,r)=>{e=i,t=r}));if(!e||!t)throw Error("Broken Implement of Promise");return{promise:i,resolve:e,reject:t}}const addStereo=e=>{const t={};return e.split(";").forEach((e=>{const[i,r]=e.split("=");i&&r&&(t[i]=r)})),t["sprop-stereo"]=1,t.stereo=1,Object.keys(t).map((e=>`${e}=${t[e]}`)).join(";")},createHandler=(e,t)=>e.enableFallbackHandler?new FallbackHandler(e,t):e.enableStandardHandler?new StandardHandler(e,t):isFirefox?new FirefoxHandler(e,t):new ChromeHandler(e,t),ReconnectReasonMap={[InternalReconnectReason.ICE_FAILED]:ReconnectReason.ICE_FAILED,[InternalReconnectReason.DC_ERROR]:ReconnectReason.ICE_FAILED,[InternalReconnectReason.DC_CLOSE]:ReconnectReason.ICE_FAILED,[InternalReconnectReason.NODE_CHANGE]:ReconnectReason.NODE_CHANGE,[InternalReconnectReason.NOTIFY_RECONNECT]:ReconnectReason.NOTIFY_RECONNECT,[InternalReconnectReason.JOIN_TIMEOUT]:ReconnectReason.JOIN_TIMEOUT};class SignalingManager extends EnhancedEventEmitter{constructor(e){super(),__publicField(this,"_connectionManager"),__publicField(this,"_dataChannelSignal"),__publicField(this,"_state"),__publicField(this,"_connectionLostTimer"),__publicField(this,"_isReconnecting",!1),__publicField(this,"logger"),this._ctx=e,this.logger=new Logger$1("SignalingManager",1,e.id),this.logger.info("constructor","invoke"),this._connectionManager=new ConnectionManager(e),this._addConnectorHandler()}connect(){return this.isConnected()?Promise.resolve():new Promise(((e,t)=>{this._connectionManager.once("connected",(()=>e())),this._connectionManager.once("disconnected",t),this._connectionManager.startup()}))}reconnect(e,t){this._connectionManager.reconnect(e,t)}sendSignaling(e,t,i,r){if(!this._dataChannelSignal)throw new SDKError(ErrorCode.NOT_CONNECTED_YET,"signaling channel is not connected");return this._dataChannelSignal.sendSignaling(e,t,i,r)}sendP2PMessage(e,t){if(!this._dataChannelSignal)throw new SDKError(ErrorCode.NOT_CONNECTED_YET,"signaling channel is not connected");return this._dataChannelSignal.sendP2PMessage(e,t)}destroy(){var e,t;this.logger.info("destroy()"),this._clearConnectionLostTimer(),this._connectionManager.shotdown(),null==(e=this._ctx.handler)||e.destroy(),this._ctx.handler=void 0,null==(t=this._dataChannelSignal)||t.destroy(),this._state&&this._setState(ConnectionState.CONNECTION_STATE_DISCONNECTED),this.removeAllListeners()}isConnected(){return this._state===ConnectionState.CONNECTION_STATE_CONNECTED||this._state===ConnectionState.CONNECTION_STATE_RECONNECTED}isReconnecting(){return this._state===ConnectionState.CONNECTION_STATE_CONNECTING||this._state===ConnectionState.CONNECTION_STATE_RECONNECTING}_setState(e,t){if(this._state===e)return;this._state=e;const i={state:e};t&&(i.reason=ReconnectReasonMap[t]||ReconnectReason.ICE_FAILED),this.safeEmit(StateEvent.ON_CONNECTION_STATE_CHANGE,i)}_addConnectorHandler(){this._connectionManager.on("connected",(e=>{var t;this.logger.info("connectStateChange","connected"),this._clearConnectionLostTimer(),null==(t=this._dataChannelSignal)||t.destroy(),this._ctx.peerConnection=e.pc,this._ctx.handler=createHandler(this._ctx,e.pc),this._dataChannelSignal=e.signaling,this._addSignalEventHandler(),this._setState(this._isReconnecting?ConnectionState.CONNECTION_STATE_RECONNECTED:ConnectionState.CONNECTION_STATE_CONNECTED)})),this._connectionManager.on("disconnected",(e=>{this._clearConnectionLostTimer(),this._setState(ConnectionState.CONNECTION_STATE_DISCONNECTED),this.logger.error("connectStateChange","disconnected. %o",e.message),this._isReconnecting&&this.safeEmit(StateEvent.ON_RECONNECT_FAILED)})),this._connectionManager.on("connecting",(()=>{this._isReconnecting=!1,this._ctx.handler=void 0,this._setState(ConnectionState.CONNECTION_STATE_CONNECTING),this.logger.info("connectStateChange","connecting")})),this._connectionManager.on("reconnecting",(e=>{this._setState(ConnectionState.CONNECTION_STATE_DISCONNECTED,e),this._connectionLostTimer||(this._connectionLostTimer=setTimeout((()=>{this.safeEmit(StateEvent.ON_CONNECTION_STATE_CHANGE,{state:ConnectionState.CONNECTION_STATE_LOST})}),1e4)),this._isReconnecting=!0,this._ctx.handler=void 0,this._setState(ConnectionState.CONNECTION_STATE_RECONNECTING,e),this.logger.warn("connectStateChange","reconnecting")})),this._connectionManager.on("connectWidthTcp",(()=>{this.safeEmit(StateEvent.CONNECT_WITH_TCP)})),["__onGetIceConfigHook","__onIceConnectSuccessHook","__onConnectSuccessHook"].forEach((e=>{this._connectionManager.on(e,((...t)=>this.emit(e,...t)))}))}_clearConnectionLostTimer(){this._connectionLostTimer&&(clearTimeout(this._connectionLostTimer),delete this._connectionLostTimer)}_addSignalEventHandler(){var e,t;[SignalEvent.ON_ADD_STREAM,SignalEvent.ON_ADD_STREAM_LIST,SignalEvent.ON_REMOVE_STREAM,SignalEvent.ON_REMOVE_STREAM_LIST,SignalEvent.USER_CONNECTION,SignalEvent.USER_CONNECTION_LIST,SignalEvent.USER_DISCONNECTION,SignalEvent.USER_DISCONNECTION_LIST,SignalEvent.ON_UPDATE_STREAM_ATTRIBUTES,SignalEvent.ON_UPDATE_ROOM_ATTRIBUTES,SignalEvent.ON_PUSH_TRACK,SignalEvent.ON_REMOVE_TRACK,SignalEvent.ON_CUSTOM_MESSAGE,SignalEvent.USER_MESSAGE_RECEIVED_OUTSIDE_ROOM,SignalEvent.USER_BINARY_MESSAGE_RECEIVED_OUTSIDE_ROOM,SignalEvent.USER_MESSAGE_RECEIVED,SignalEvent.USER_BINARY_MESSAGE_RECEIVED,SignalEvent.POST_PROCESSING_MESSAGE,SignalEvent.ON_USER_TOKEN_WILL_EXPIRE,SignalEvent.ON_TOKEN_PUBLISH_PRIVILEGE_WILL_EXPIRE,SignalEvent.ON_TOKEN_PUBLISH_PRIVILEGE_DID_EXPIRED,SignalEvent.ON_TOKEN_SUBSCRIBE_PRIVILEGE_WILL_EXPIRE,SignalEvent.ON_TOKEN_SUBSCRIBE_PRIVILEGE_DID_EXPIRED,SignalEvent.STREAM_CONTROL_MESSAGE,SignalEvent.ENGINE_CONTROL_MESSAGE,SignalEvent.ON_UPDATE_USER_ATTRIBUTES,SignalEvent.ON_SPEAKER_CHANGE,SignalEvent.ON_STREAM_FAILED,SignalEvent.ON_FORWARD_DST_ROOM_USER_KICK,SignalEvent.ON_STREAM_PULL_STATE_CHANGED,SignalEvent.ON_STREAM_PUSHED_BY_OTHER,MediaServerSignalEvent.RSCP,MediaServerSignalEvent.RTT,MediaServerSignalEvent.SSC].forEach((e=>{var t;null==(t=this._dataChannelSignal)||t.on(e,(t=>{this.safeEmit(e,t)}))})),null==(e=this._dataChannelSignal)||e.on(SignalEvent.NODE_CHANGE,(e=>{this._connectionManager.reconnectByNodeChange(e)})),null==(t=this._dataChannelSignal)||t.on(SignalEvent.ON_NOTIFY_RECONNECT,(()=>{this._connectionManager.reconnect(InternalReconnectReason.NOTIFY_RECONNECT)}))}}var UserRole=(e=>(e.NORMAL_USER="normalUser",e.SILENT_USER="silentUser",e))(UserRole||{});class EngineVideoProfile{constructor(e){__publicField(this,"_captureDeviceId"),__publicField(this,"_contentHint"),__publicField(this,"_videoCaptureConf",{...defaultVideoEncoderConfig}),__publicField(this,"_mainPreferCodec"),__publicField(this,"_screenPreferCodec"),__publicField(this,"_remoteVideoConfig",new Map),__publicField(this,"_remoteSimulcastStreamType",new Map),__publicField(this,"_simulcastMode",VideoSimulcastMode.VIDEO_ONLY_ONE),__publicField(this,"_highVideoEncodeConf",videoCaptureConf2EncodeConf(defaultVideoEncoderConfig)),__publicField(this,"_midVideoEncodeConf"),__publicField(this,"_lowVideoEncodeConf"),__publicField(this,"_screenEncodeConfig",defaultScreenEncoderConfig),__publicField(this,"_invalidVideoEncodeConf"),__publicField(this,"activeSimStreams",[]),__publicField(this,"_logger"),__publicField(this,"_apiVersion"),this._ctx=e,this._logger=new Logger$1("EngineVideoProfile",1,e.id)}setCaptureDeviceId(e){this._captureDeviceId=e}setCaptureConfig(e){this._videoCaptureConf={...this._videoCaptureConf,...e}}getCaptureConfig(e){e=e||this._captureDeviceId;const t={...this._videoCaptureConf};return"user"===e||"environment"===e||"left"===e||"right"===e?(delete t.deviceId,t.facingMode=e):e&&(!isDingTalk||isIOS?t.deviceId={exact:e}:delete t.deviceId),t}getContentHint(){return this._contentHint}getPreferCodec(e){return e?this._screenPreferCodec:this._mainPreferCodec}setRemoteUserVideoConfig(e,t){"object"==typeof t?this._remoteVideoConfig.set(e,t):this._remoteSimulcastStreamType.set(e,t)}getSubLayer(e,t){var i,r;const o=this._remoteSimulcastStreamType.get(e.userId),s=this._remoteVideoConfig.get(e.userId);if(o){const{videoDescriptions:t,subVideoDescriptions:s}=e.attributes||{},n=Array.isArray(s)?s:t;let a;return 1===n.length?a=0:2===n.length?a=o===SimulcastStreamType.VIDEO_STREAM_HIGH?0:1:n.length>=3&&(a={[SimulcastStreamType.VIDEO_STREAM_HIGH]:0,[SimulcastStreamType.VIDEO_STREAM_MID]:1,[SimulcastStreamType.VIDEO_STREAM_LOW]:2}[o]),{spatialLayer:(a&&(null==(i=n[a])?void 0:i.video_index))??a??0,spatialSubLayer:(a&&(null==(r=n[a])?void 0:r.sub_index))??a??-1}}return s?getSubLayerByVideoConfig(s,e):t?getSubLayerByVideoConfig(t,e):void 0}getSimulcastMode(){return this._simulcastMode}async setSimulcastMode(e,t){var i,r;if(!isSimulcastSupported())throw new SDKError(ErrorCode.NOT_SUPPORTED,"Simulcast is not supported");if(this._simulcastMode!==e){if(null==t?void 0:t.hasPublished){if((null==(i=t.localStream)?void 0:i.videoHasPublish)||(null==(r=t.localStream)?void 0:r.audioHasPublish))throw new SDKError(ErrorCode.SET_SIMULCAST_FAILED,"Cannot change simulcast mode after publishing the video streams");this._logger.print("setSimulcastMode()","change simulcast mode and unpublish."),await t.unpublish()}this._simulcastMode=e,e!==VideoSimulcastMode.VIDEO_ONLY_ONE&&this._autoGenerateSubVideoEncodeConfig()}}closeSimulcast(){this._simulcastMode=VideoSimulcastMode.VIDEO_ONLY_ONE}async setVideoEncodeConfigPolyfill(e){if(Array.isArray(e)){checkVideoEncoderConfig(e);const[t,...i]=e;this.setVideoEncodeConfig(t),await this.setSubVideoEncodeConfig(i.reverse())}else this.setVideoEncodeConfig(e)}setVideoEncodeConfig(e){checkVideoEncoderConfig([e]);const t=this._midVideoEncodeConf||this._lowVideoEncodeConf;t&&getResolution(t)>=getResolution(e)?(this._logger.warn("setVideoEncodeConfig","smaller then substream"),this._invalidVideoEncodeConf=videoCaptureConf2EncodeConf(e),e=t):delete this._invalidVideoEncodeConf;const{preferCodecName:i,...r}={...e};checkSupportedConstraints(r),this._logger.print("setVideoEncodeConfig","update encode config",e),this._highVideoEncodeConf=videoCaptureConf2EncodeConf(e),this._contentHint=e.contentHint,this._mainPreferCodec=i,this._logger.print("setVideoEncodeConfig","update capture config",r),this._videoCaptureConf=r}async setSubVideoEncodeConfig(e,t,i){var r,o;if(this._logger.print("setSubVideoEncodeConfig","%o, published=%s",e,null==t?void 0:t.hasPublished),e&&e.length>0){checkVideoEncoderConfig(e),e.sort(((e,t)=>getResolution(e)-getResolution(t)));const s=this._invalidVideoEncodeConf||this._highVideoEncodeConf,n=e[e.length-1];if(getResolution(n)>=getResolution(s))throw new SDKError(ErrorCode.SET_SIMULCAST_FAILED,"The resolution cannot exceed the mainstream");if((null==t?void 0:t.hasPublished)&&e.length!==this._getSubLayers().length){if((null==(r=t.localStream)?void 0:r.videoHasPublish)||(null==(o=t.localStream)?void 0:o.audioHasPublish))throw new SDKError(ErrorCode.SET_SIMULCAST_FAILED,"Cannot change the number of substreams after publishing the video streams");await t.unpublish()}e.length>2&&(reportRtcInvokeStatus(this._ctx.id,"simulcast_over_limit","setLocalSimulcastMode: You can set parameters for up to 2 streams"),warnDevelopers("setLocalSimulcastMode: You can set parameters for up to 2 streams"));const[a,d]=e;a&&(checkVideoConfigQuotient(s,a),this._lowVideoEncodeConf=videoCaptureConf2EncodeConf(a)),d&&(checkVideoConfigQuotient(s,d),this._midVideoEncodeConf=videoCaptureConf2EncodeConf(d)),this._invalidVideoEncodeConf&&(this.setVideoEncodeConfig(this._invalidVideoEncodeConf),await(null==i?void 0:i.updateVideoCaptureConfig(this._ctx.videoProfile.getCaptureConfig())))}else this._autoGenerateSubVideoEncodeConfig()}genVideoDescriptions(e){var t;const i=[];let r=[];const o=[],s=[];let{width:n,height:a,frameRate:d,maxKbps:c}=e.videoEncodeConfig[0];n=constraints2number(n),a=constraints2number(a);const l=null==(t=e.videoTrack)?void 0:t.preprocessingTrack,{width:u,height:_,frameRate:h}=(null==l?void 0:l.getSettings())??{};u&&(n=Math.floor(u)),_&&(a=Math.floor(_)),h&&(d=Math.floor(h)),("number"!=typeof d||Number.isNaN(d))&&(d=30),i.push({width:n,height:a,framerate:d,maxkbps:c,rid:"0"}),o.unshift({maxBitrate:1e3*c,rid:"0",maxFramerate:d});const{serverConfig:p}=this._ctx;if(!(e.isScreen||this._simulcastMode===VideoSimulcastMode.VIDEO_ONLY_ONE||isFirefox&&"VP8"!==(null==p?void 0:p.videoCodec))){const e=getSimulcastLayers(n,a);if(e>1){const t=this._getSubVideoEncodeConfig(e,{width:n,height:a});this._logger.info("simulcast() ","simulcastLayers: %o",t),s.push(!0),t.forEach(((e,t)=>{const r={maxBitrate:1e3*e.maxkbps,scaleResolutionDownBy:e.scaleResolutionDownBy,rid:`${t+1}`,maxFramerate:e.frameRate};o.unshift(r),i.push({width:e.width,height:e.height,framerate:e.frameRate,maxkbps:e.maxkbps,rid:`${t+1}`}),s.push(!0)})),(null==p?void 0:p.simulcastOnDemand)&&(r=i.map(((e,t)=>({...e,video_index:t,sub_index:t}))))}}return(null==p?void 0:p.e2eFeedback)&&(r=i.map(((e,t)=>({...e,video_index:t,sub_index:t})))),{videoDescriptions:i,subVideoDescriptions:r,sendEncodings:o,activeSimulcastStreams:s}}getVideoEncodeConfig(){return[this._highVideoEncodeConf,this._midVideoEncodeConf,this._lowVideoEncodeConf].filter((e=>e))}setScreenEncodeConfig(e){this._screenEncodeConfig=e}getScreenEncodeConfig(){return this._screenEncodeConfig}checkSimulcastApiVersion(e){if(this._apiVersion){if(this._apiVersion!==e){const e=`mixing old and new apis, please use ${"new"===this._apiVersion?"setLocalSimulcastMode/setRemoteSimulcastStreamType":"enableSimulcastMode/setRemoteVideoConfig"} instead.`;throw reportRtcInvokeStatus(this._ctx.id,"mixingOldAndNewApis",e),new SDKError(ErrorCode.MIXING_OLD_AND_NEW_APIS,e)}}else this._apiVersion=e}destroy(){this._videoCaptureConf=defaultVideoEncoderConfig,this._highVideoEncodeConf=videoCaptureConf2EncodeConf(defaultVideoEncoderConfig),delete this._invalidVideoEncodeConf,this._remoteVideoConfig.clear(),this._remoteSimulcastStreamType.clear()}_autoGenerateSubVideoEncodeConfig(){this._logger.print("_autoGenerateSubVideoEncodeConfig()","generate low stream.");const e=this._highVideoEncodeConf,t=constraints2number(e.width),i=constraints2number(e.height),r=Math.min(t,i)/90;this._lowVideoEncodeConf={width:Math.floor(t/r),height:Math.floor(i/r),maxKbps:100,frameRate:10}}_getSubLayers(){const e=[];return this._midVideoEncodeConf&&e.push(this._midVideoEncodeConf),this._lowVideoEncodeConf&&e.push(this._lowVideoEncodeConf),e}_getSubVideoEncodeConfig(e,t){return this._getSubLayers().slice(1-e).map((e=>{if(e.width>e.height&&t.width<t.height||e.width<e.height&&t.width>t.height){const t=e.width;e.width=e.height,e.height=t}const i=constraints2number(e.width),r=constraints2number(e.height),o=Math.max(t.width/i,t.height/r);return{width:Math.floor(t.width/o),height:Math.floor(t.height/o),scaleResolutionDownBy:o,frameRate:constraints2number(e.frameRate)||15,maxkbps:e.maxKbps||600}}))}__autoResetVideoEncoderConfig(e){const t=autoResetVideoEncoderConfig(this.getVideoEncodeConfig(),e);t&&(this.setVideoEncodeConfigPolyfill(t),this._logger.print("autoResetVideoEncoderConfig() result",JSON.stringify(t)),reportRtcInvokeStatus(this._ctx.id,"autoResetVideoEncoderConfig",JSON.stringify(t)))}}class RTSMessageLimiter{constructor(e){__publicField(this,"_sendTimes",[]),__publicField(this,"_bufferSizeLimit"),__publicField(this,"_totalSizeLimitPerSecond"),__publicField(this,"_limitModeInterval"),__publicField(this,"_limitModeQPS"),__publicField(this,"_interval"),__publicField(this,"_qps"),this.setLimitMode(e)}setLimitMode(e){e===RTS_MODE.LIMIT_MODE?(this._bufferSizeLimit=1,this._totalSizeLimitPerSecond=30720,this._limitModeInterval=1e3,this._limitModeQPS=60):(this._bufferSizeLimit=64,delete this._totalSizeLimitPerSecond,delete this._limitModeInterval,delete this._limitModeQPS)}setQPS(e,t){this._interval=e,this._qps=t}check(e){const t=Date.now(),i=checkBufferSize(e,this._bufferSizeLimit);if("number"==typeof this._totalSizeLimitPerSecond){if(this._sendTimes.reduce(((e,i)=>t-i.ts<1e3?e+i.size:e),0)+i>this._totalSizeLimitPerSecond)throw new SDKError(ErrorCode.USER_MESSAGE_EXCEED_QPS,`user message exceed total size(${this._totalSizeLimitPerSecond})`)}const r=this._limitModeInterval??this._interval,o=this._limitModeQPS??this._qps;if("number"==typeof r&&"number"==typeof o)if(this._sendTimes.length<o)this._sendTimes.push({ts:t,size:i});else{if(t-this._sendTimes[0].ts<r)throw new SDKError(ErrorCode.USER_MESSAGE_EXCEED_QPS,`user message exceed qps(${o})`);this._sendTimes.splice(0,1),this._sendTimes.push({ts:t,size:i})}}}const encodedJs="dmFyIF9fZGVmUHJvcD1PYmplY3QuZGVmaW5lUHJvcGVydHksX19kZWZOb3JtYWxQcm9wPSh0LGUsbik9PmUgaW4gdD9fX2RlZlByb3AodCxlLHtlbnVtZXJhYmxlOiEwLGNvbmZpZ3VyYWJsZTohMCx3cml0YWJsZTohMCx2YWx1ZTpufSk6dFtlXT1uLF9fcHVibGljRmllbGQ9KHQsZSxuKT0+KF9fZGVmTm9ybWFsUHJvcCh0LCJzeW1ib2wiIT10eXBlb2YgZT9lKyIiOmUsbiksbik7IWZ1bmN0aW9uKCl7InVzZSBzdHJpY3QiO2NvbnN0IHQ9e2dldE5BTFVuaXRzKGUsbj0hMSl7aWYoZS5sZW5ndGgtZS5wb3NpdGlvbjw0KXJldHVybltdO2NvbnN0e3Bvc2l0aW9uOnJ9PWU7cmV0dXJuIDE9PT1lLmdldEludDMyKHIpfHwwPT09ZS5nZXRJbnQxNihyKSYmMT09PWUuZ2V0SW50OChyKzIpP3QuZ2V0QW5uZXhiTmFscyhlLG4pOnQuZ2V0QXZjY05hbHMoZSxuKX0sZ2V0QW5uZXhiTmFscyhlLG4pe2NvbnN0IHI9W107bGV0IGk9dC5nZXRIZWFkZXJQb3NpdGlvbkFubmV4QihlKSxzPWkucG9zLG89cztmb3IoO3M8ZS5sZW5ndGgtNDspe2NvbnN0IGE9bmV3IFVpbnQ4QXJyYXkoZS5idWZmZXIuc2xpY2UocyxzK2kuaGVhZGVyTGVuZ3RoKSk7aS5wb3M9PT1lLnBvc2l0aW9uJiZlLnNraXAoaS5oZWFkZXJMZW5ndGgpLGk9dC5nZXRIZWFkZXJQb3NpdGlvbkFubmV4QihlKSxvPWkucG9zO2NvbnN0IHA9e2hlYWRlcjphLGJvZHk6bmV3IFVpbnQ4QXJyYXkoZS5idWZmZXIuc2xpY2UocythLmJ5dGVMZW5ndGgsbykpLHR5cGU6LTF9O24/dC5hbmFseXNlSDI2NU5hbChwKTp0LmFuYWx5c2VOYWwocCksKHAudHlwZTw9OXx8biYmcC50eXBlPD00MCkmJjAhPT1wLnR5cGUmJnIucHVzaChwKSxlLnNraXAoby1lLnBvc2l0aW9uKSxzPW99cmV0dXJuIHJ9LGdldEF2Y2NOYWxzKGUsbil7Y29uc3Qgcj1bXTtmb3IoO2UucG9zaXRpb248ZS5sZW5ndGgtNDspe2NvbnN0IGk9ZS5nZXRJbnQzMihlLnBvc2l0aW9uKTtpZighKGUubGVuZ3RoLWUucG9zaXRpb24+PWkpKWJyZWFrO3tjb25zdCBzPW5ldyBVaW50OEFycmF5KGUuYnVmZmVyLnNsaWNlKGUucG9zaXRpb24sZS5wb3NpdGlvbis0KSk7ZS5za2lwKDQpO2NvbnN0IG89bmV3IFVpbnQ4QXJyYXkoZS5idWZmZXIuc2xpY2UoZS5wb3NpdGlvbixlLnBvc2l0aW9uK2kpKTtlLnNraXAoaSk7Y29uc3QgYT17aGVhZGVyOnMsYm9keTpvLHR5cGU6LTF9O24/dC5hbmFseXNlSDI2NU5hbChhKTp0LmFuYWx5c2VOYWwoYSksYS50eXBlPD05JiYwIT09YS50eXBlJiZyLnB1c2goYSl9fXJldHVybiByfSxhbmFseXNlTmFsKHQpe2NvbnN0IGU9MzEmdC5ib2R5WzBdO3N3aXRjaCh0LnR5cGU9ZSxlKXtjYXNlIDE6dC5uZHI9ITA7YnJlYWs7Y2FzZSA1OnQuaWRyPSEwO2JyZWFrO2Nhc2UgNjp0LnNlaT0hMDticmVhaztjYXNlIDc6dC5zcHM9ITA7YnJlYWs7Y2FzZSA4OnQucHBzPSEwfX0sYW5hbHlzZUgyNjVOYWwodCl7Y29uc3QgZT0oMTI2JnQuYm9keVswXSk+PjE7c3dpdGNoKHQudHlwZT1lLGUpe2Nhc2UgMzk6Y2FzZSA0MDp0LnNlaT0hMH19LGdldEhlYWRlclBvc2l0aW9uQW5uZXhCKHQpe2xldCBlPXQucG9zaXRpb24sbj0wO2NvbnN0IHI9dC5sZW5ndGg7Zm9yKDszIT09biYmNCE9PW4mJmU8ci00OykwPT09dC5nZXRJbnQxNihlKT8xPT09dC5nZXRJbnQxNihlKzIpP249NDoxPT09dC5nZXRJbnQ4KGUrMik/bj0zOmUrKzplKys7cmV0dXJuIGU9PT1yLTQmJigwPT09dC5nZXRJbnQxNihlKT8xPT09dC5nZXRJbnQxNihlKzIpP249NDplPXI6KGUrKywwPT09dC5nZXRJbnQxNihlKSYmMT09PXQuZ2V0SW50OChlKT9uPTM6ZT1yKSkse3BvczplLGhlYWRlckxlbmd0aDpufX0saXNIMjY1VmlkZW9GcmFtZSh0KXt2YXIgZSxuO3JldHVybigobnVsbD09KG49bnVsbD09KGU9dC5nZXRNZXRhZGF0YSk/dm9pZCAwOmUuY2FsbCh0KSk/dm9pZCAwOm4ubWltZVR5cGUpfHwiIikudG9Mb3dlckNhc2UoKS5pbmNsdWRlcygiaDI2NSIpfX07Y2xhc3MgZXtjb25zdHJ1Y3Rvcih0KXtfX3B1YmxpY0ZpZWxkKHRoaXMsIl9wb3NpdGlvbiIsMCksX19wdWJsaWNGaWVsZCh0aGlzLCJfZGF0YXZpZXciKSx0aGlzLl9kYXRhdmlldz1uZXcgRGF0YVZpZXcodCl9Z2V0IGxlbmd0aCgpe3JldHVybiB0aGlzLmJ1ZmZlci5ieXRlTGVuZ3RofWdldCBidWZmZXIoKXtyZXR1cm4gdGhpcy5fZGF0YXZpZXcuYnVmZmVyfXNldCBwb3NpdGlvbih0KXt0aGlzLl9wb3NpdGlvbj10fWdldCBwb3NpdGlvbigpe3JldHVybiB0aGlzLl9wb3NpdGlvbn1iYWNrKHQpe3RoaXMucG9zaXRpb24tPXR9Z2V0VWludDgodCl7cmV0dXJuIHRoaXMuX2RhdGF2aWV3LmdldFVpbnQ4KHQpfWdldEludDgodCl7cmV0dXJuIHRoaXMuX2RhdGF2aWV3LmdldEludDgodCl9Z2V0SW50MTYodCl7cmV0dXJuIHRoaXMuX2RhdGF2aWV3LmdldEludDE2KHQpfWdldFVpbnQxNih0KXtyZXR1cm4gdGhpcy5fZGF0YXZpZXcuZ2V0VWludDE2KHQpfWdldFVpbnQzMih0KXtyZXR1cm4gdGhpcy5fZGF0YXZpZXcuZ2V0VWludDMyKHQpfWdldEludDMyKHQpe3JldHVybiB0aGlzLl9kYXRhdmlldy5nZXRJbnQzMih0KX1za2lwKHQpe2NvbnN0IG49TWF0aC5mbG9vcih0LzQpLHI9dCU0O2ZvcihsZXQgaT0wO2k8bjtpKyspZS5yZWFkQnl0ZSh0aGlzLDQpO3I+MCYmZS5yZWFkQnl0ZSh0aGlzLHIpfXN0YXRpYyByZWFkQnl0ZSh0LGUsbil7bGV0IHI7c3dpdGNoKGUpe2Nhc2UgMTpyPW4/dC5nZXRJbnQ4KHQucG9zaXRpb24pOnQuZ2V0VWludDgodC5wb3NpdGlvbik7YnJlYWs7Y2FzZSAyOnI9bj90LmdldEludDE2KHQucG9zaXRpb24pOnQuZ2V0VWludDE2KHQucG9zaXRpb24pO2JyZWFrO2Nhc2UgMzppZihuKXRocm93IG5ldyBFcnJvcigibm90IHN1cHBvcnRlZCBmb3IgcmVhZEJ5dGUgMyIpO3I9dC5nZXRVaW50OCh0LnBvc2l0aW9uKTw8MTYscnw9dC5nZXRVaW50OCh0LnBvc2l0aW9uKzEpPDw4LHJ8PXQuZ2V0VWludDgodC5wb3NpdGlvbisyKTticmVhaztjYXNlIDQ6cj1uP3QuZ2V0SW50MzIodC5wb3NpdGlvbik6dC5nZXRVaW50MzIodC5wb3NpdGlvbik7YnJlYWs7Y2FzZSA4OmlmKG4pdGhyb3cgbmV3IEVycm9yKCJub3Qgc3VwcG9ydGVkIGZvciByZWFkQm9keSA4Iik7cj10LmdldFVpbnQzMih0LnBvc2l0aW9uKTw8MzIscnw9dC5nZXRVaW50MzIodC5wb3NpdGlvbis0KTticmVhaztkZWZhdWx0OnI9IiJ9cmV0dXJuIHQucG9zaXRpb24rPWUscn1yZWFkVWludDgoKXtyZXR1cm4gZS5yZWFkQnl0ZSh0aGlzLDEpfXJlYWRVaW50MTYoKXtyZXR1cm4gZS5yZWFkQnl0ZSh0aGlzLDIpfXJlYWRVaW50MjQoKXtyZXR1cm4gZS5yZWFkQnl0ZSh0aGlzLDMpfXJlYWRVaW50MzIoKXtyZXR1cm4gZS5yZWFkQnl0ZSh0aGlzLDQpfXJlYWRVaW50NjQoKXtyZXR1cm4gZS5yZWFkQnl0ZSh0aGlzLDgpfXJlYWRJbnQ4KCl7cmV0dXJuIGUucmVhZEJ5dGUodGhpcywxLCEwKX1yZWFkSW50MTYoKXtyZXR1cm4gZS5yZWFkQnl0ZSh0aGlzLDIsITApfXJlYWRJbnQzMigpe3JldHVybiBlLnJlYWRCeXRlKHRoaXMsNCwhMCl9d3JpdGVVaW50MzIodCl7cmV0dXJuIG5ldyBVaW50OEFycmF5KFt0Pj4+MjQmMjU1LHQ+Pj4xNiYyNTUsdD4+PjgmMjU1LDI1NSZ0XSl9fXZhciBuPSh0PT4odFt0LmludGVybmFsPTBdPSJpbnRlcm5hbCIsdFt0LmV4dGVybmFsPTFdPSJleHRlcm5hbCIsdFt0LmJ5cGFzcz0yXT0iYnlwYXNzIix0KSkobnx8e30pO2NvbnN0IHI9bmV3IFVpbnQ4QXJyYXkoWzEwOSwxNjcsNTMsMTkwLDEwMyw5MCw3MiwxLDE3MCw4OSw2MywxNjQsMTk0LDE5OSwxOSw4NV0pLGk9bmV3IFVpbnQ4QXJyYXkoWzEwOSwxNjcsNTMsMTkwLDEwMyw5MCw3MiwxLDE3MCw4OSw2MywxNjQsMTk0LDE5OSwxOSw4NF0pLHM9bmV3IFVpbnQ4QXJyYXkoWzMxLDIzOSwzLDUwLDI0MiwxMjAsNzYsODUsMTY5LDQyLDE2MSw5MSw3NSwxODYsMjJdKTtmdW5jdGlvbiBvKHQpe2NvbnN0IGU9W107Zm9yKDt0Pj0yNTU7KXQtPTI1NSxlLnB1c2goMjU1KTtyZXR1cm4gZS5wdXNoKHQpLG5ldyBVaW50OEFycmF5KGUpfWZ1bmN0aW9uIGEodCxlPTApe2xldCBuPTA7Zm9yKDsyNTU9PT10W2VdJiZlPHQuYnl0ZUxlbmd0aDspZSsrLG4rPTI1NTtyZXR1cm4gZTx0LmJ5dGVMZW5ndGgmJihuKz10W2UrK10pLFtuLGVdfWNvbnN0IHA9bmV3IFVpbnQ4QXJyYXkoWzgwLDFdKSxjPWNsYXNze3N0YXRpYyBnZW5lcmF0ZVNFSSh0LGUsbj0hMSl7Y29uc3Qgcz1uZXcgVWludDhBcnJheShbMCwwLDAsMV0pLGE9ZT9wOm5ldyBVaW50OEFycmF5KFs2XSksbD1uZXcgVWludDhBcnJheShbNV0pLGc9Yy5fX3V1aWR8fChuP3I6aSkseT1vKHQuYnl0ZUxlbmd0aCtnLmJ5dGVMZW5ndGgpLGQ9KHQ9Pntjb25zdCBlPVtdO2xldCBuPTA7Zm9yKGNvbnN0IHIgb2YgdCluPj0yJiZyPD0zJiYoZS5wdXNoKDMpLG49MCksMD09PXI/bisrOm49MCxlLnB1c2gocik7cmV0dXJuIG5ldyBVaW50OEFycmF5KGUpfSkodCk7cmV0dXJuIG5ldyBVaW50OEFycmF5KFsuLi5zLC4uLmEsLi4ubCwuLi55LC4uLmcsLi4uZCwxMjhdKX1zdGF0aWMgZGVjb2RlU0VJQm9keSh0LGUpe2NvbnN0IG49KHQ9Pntjb25zdCBlPVtdO2ZvcihsZXQgbj0wO248dC5sZW5ndGg7bisrKXRbbl08PTMmJjA9PT10W24tMV0mJjA9PT10W24tMl18fGUucHVzaCh0W25dKTtyZXR1cm4gbmV3IFVpbnQ4QXJyYXkoZSl9KSh0PXQuc2xpY2UoMCx0Lmxlbmd0aC0xKSk7aWYobi5ieXRlTGVuZ3RoPDIpcmV0dXJuO2xldCBvPTA7Y29uc3QgcD1lPzI6MTtpZig1IT09bltwXSYmMTAwIT09bltwXSlyZXR1cm47bys9MStwO2NvbnN0W2MsbF09YShuLG8pO289bDtsZXQgZz0yO2NvbnN0IHk9bytjO24uYnl0ZUxlbmd0aD49aS5ieXRlTGVuZ3RoJiZjPj1pLmJ5dGVMZW5ndGgmJihuLnNsaWNlKG8sbytpLmJ5dGVMZW5ndGgpLnRvU3RyaW5nKCk9PT1pLnRvU3RyaW5nKCl8fG4uc2xpY2UobyxvK3MuYnl0ZUxlbmd0aCkudG9TdHJpbmcoKT09PXMudG9TdHJpbmcoKSk/KG8rPWkuYnl0ZUxlbmd0aCxnPTEpOm4uYnl0ZUxlbmd0aD49aS5ieXRlTGVuZ3RoJiZjPj1pLmJ5dGVMZW5ndGgmJm4uc2xpY2UobyxvK3IuYnl0ZUxlbmd0aCkudG9TdHJpbmcoKT09PXIudG9TdHJpbmcoKSYmKG8rPXIuYnl0ZUxlbmd0aCxnPTApO3JldHVybnt0eXBlOmcscGF5bG9hZDpuLnNsaWNlKG8seSl9fXN0YXRpYyBwYXJzZUludGVybmFsU0VJKHQpe2NvbnN0IGU9bmV3IE1hcDtsZXQgbj0wO2lmKDA9PT10LnR5cGUpe2Zvcig7dC5wYXlsb2FkLmJ5dGVMZW5ndGgtbj49Mjspe2NvbnN0W3IsaV09YSh0LnBheWxvYWQsbik7bj1pO2NvbnN0W3Msb109YSh0LnBheWxvYWQsbik7aWYobj1vLGUuZ2V0KHIpfHwhKHM8PXQucGF5bG9hZC5ieXRlTGVuZ3RoLW4pKWJyZWFrO2Uuc2V0KHIsdC5wYXlsb2FkLnNsaWNlKG4sbitzKSksbis9c31yZXR1cm4gZX19c3RhdGljIG1ha2VJbnRlcm5hbFNlaSh0KXtjb25zdCBlPVtdO2Zvcihjb25zdFtpLHNdb2YgdCl7Y29uc3QgdD1vKGkpLG49byhzLmJ5dGVMZW5ndGgpO2UucHVzaCh0LG4scyl9Y29uc3Qgbj1lLnJlZHVjZSgoKHQsZSk9PnQrZS5ieXRlTGVuZ3RoKSwwKSxyPW5ldyBVaW50OEFycmF5KG4pO3JldHVybiBlLnJlZHVjZSgoKHQsZSk9PihyLnNldChlLHQpLHQrZS5ieXRlTGVuZ3RoKSksMCkscn19O2xldCBsPWM7X19wdWJsaWNGaWVsZChsLCJfX3V1aWQiKSwidW5kZWZpbmVkIiE9dHlwZW9mIHNlbGYmJiJEZWRpY2F0ZWRXb3JrZXJHbG9iYWxTY29wZSI9PT1zZWxmLmNvbnN0cnVjdG9yLm5hbWUmJnNlbGYuYWRkRXZlbnRMaXN0ZW5lcigicnRjdHJhbnNmb3JtIiwocj0+e2NvbnN0e3RyYW5zZm9ybWVyOml9PXIse3N0cmVhbUlkOnMsc2tpcEZpbHRlcjpvfT1pLm9wdGlvbnMsYT1mdW5jdGlvbih7cG9zdE1lc3NhZ2U6cixza2lwRmlsdGVyOml9KXtyZXR1cm4gbmV3IFRyYW5zZm9ybVN0cmVhbSh7dHJhbnNmb3JtKHMsbyl7Y29uc3QgYT10LmlzSDI2NVZpZGVvRnJhbWUocyk7dC5nZXROQUxVbml0cyhuZXcgZShzLmRhdGEpLGEpLmZvckVhY2goKHQ9PntpZih0LnNlaSl7Y29uc3QgZT1sLmRlY29kZVNFSUJvZHkodC5ib2R5LGEpO2UmJihpfHxlLnR5cGU9PT1uLmV4dGVybmFsKSYmcihlKX19KSksby5lbnF1ZXVlKHMpfX0pfSh7cG9zdE1lc3NhZ2U6dD0+e3NlbGYucG9zdE1lc3NhZ2Uoe3N0cmVhbUlkOnMsbXNnOnR9LFt0LnBheWxvYWQuYnVmZmVyXSl9LHNraXBGaWx0ZXI6b30pO2kucmVhZGFibGUucGlwZVRocm91Z2goYSkucGlwZVRvKHIudHJhbnNmb3JtZXIud3JpdGFibGUpfSkpfSgpOwo=",blob="undefined"!=typeof window&&window.Blob&&new Blob([atob(encodedJs)],{type:"text/javascript;charset=utf-8"});function WorkerWrapper(){let e;try{if(e=blob&&(window.URL||window.webkitURL).createObjectURL(blob),!e)throw"";return new Worker(e)}catch(e){return new Worker("data:application/javascript;base64,"+encodedJs)}finally{!("undefined"!=typeof window&&navigator.userAgent.indexOf("Trident/")>0)&&e&&(window.URL||window.webkitlRL).revokeObjectURL(e)}}var ResetPubSubLockReason=(e=>(e.RECONNECT="ice-reconnect",e.LEAVE="leave_room",e))(ResetPubSubLockReason||{});const DEFAULT_RTS_MODE=RTS_MODE.NORMAL_MODE;class RTCContext{constructor(e,t,i){__publicField(this,"engineDestroyed",!1),__publicField(this,"avSync",!0),__publicField(this,"callId"),__publicField(this,"streamRTT",{}),__publicField(this,"useCloudProxy",!1),__publicField(this,"videoProfile"),__publicField(this,"audioProfileManager"),__publicField(this,"extensionManager"),__publicField(this,"userPriority",new Map),__publicField(this,"expectedIDC"),__publicField(this,"autoPlayPolicy"),__publicField(this,"joinRoomConfig"),__publicField(this,"signalingManager"),__publicField(this,"peerConnection"),__publicField(this,"pubSubLock",new PromiseLock2("pubSubLock")),__publicField(this,"pcKillSwitch",{ctor_sdpsemantics_add:!0,ctor_encodedinsetablestream_add:!0,sld_rtcpfb_rrtr_add:!0,sld_ext_sdesmid_remove:!0,sld_fmtp_sps_add:!0,sld_fmtp_bitrate_add:!0,sld_fmtp_opus_add:!0,sld_iceoption_renomination:!0,...getParameter("PC_KILLSWITCH")}),__publicField(this,"visibility",!0),__publicField(this,"rtsLimiter",{e2e:new RTSMessageLimiter(DEFAULT_RTS_MODE),e2s:new RTSMessageLimiter(DEFAULT_RTS_MODE),boradcast:new RTSMessageLimiter(DEFAULT_RTS_MODE),conf:void 0,rtsMode:DEFAULT_RTS_MODE}),__publicField(this,"serverConfig"),__publicField(this,"mediaParams"),__publicField(this,"subscribeFallbackOption"),__publicField(this,"joinRoomParams"),__publicField(this,"isPreConnection",!1),__publicField(this,"_handler"),__publicField(this,"monitor"),__publicField(this,"enableFallbackHandler",!!getParameter("ENABLE_FALLBACK_HANDLER")),__publicField(this,"enableStandardHandler",!!getParameter("ENABLE_STANDARD_HANDLER")),__publicField(this,"_businessId"),__publicField(this,"_userStreamConfig",new Map),__publicField(this,"_localAudioTrackDumpConfig",{[StreamIndex$1.STREAM_INDEX_MAIN]:{callback:void 0,frameSize:void 0},[StreamIndex$1.STREAM_INDEX_SCREEN]:{callback:void 0,frameSize:void 0}}),__publicField(this,"_remoteAudioTrackDumpConfig",{[StreamIndex$1.STREAM_INDEX_MAIN]:new Map,[StreamIndex$1.STREAM_INDEX_SCREEN]:new Map}),__publicField(this,"_targetCodec"),__publicField(this,"_targetScreenCodec"),__publicField(this,"earMonitorSettings",{[StreamIndex$1.STREAM_INDEX_MAIN]:{position:EarMonitorPosition.NONE,volume:100},[StreamIndex$1.STREAM_INDEX_SCREEN]:{position:EarMonitorPosition.NONE,volume:100}}),__publicField(this,"localVideoTrack"),__publicField(this,"localAudioTrack"),__publicField(this,"publicAudioVolume",new Map),__publicField(this,"_receiveSEIWorker"),this.id=e,this.appId=t,this.monitor=getMonitor(e),this.expectedIDC=null==i?void 0:i.expectedIDC,this.autoPlayPolicy=null==i?void 0:i.autoPlayPolicy,this.audioProfileManager=new AudioProfileManager(t),this.extensionManager=new ExtensionManager(e),this.joinRoomConfig=new JoinRoomConfig(e),this.signalingManager=new SignalingManager(this),this.videoProfile=new EngineVideoProfile(this)}set businessId(e){var t;this._businessId=e,null==(t=this.monitor)||t.set({rtc_business_id:e})}get businessId(){return this._businessId}set handler(e){var t;e&&this.resetPubSubLock("ice-reconnect"),null==(t=this._handler)||t.destroy(),this._handler=e}get handler(){return this._handler}get role(){return this.visibility?UserRole.NORMAL_USER:UserRole.SILENT_USER}set targetCodec(e){e&&[VideoCodecName.H264,VideoCodecName.VP8,VideoCodecName.ByteVC1].forEach((t=>{e.toLowerCase()===t.toLowerCase()&&(this._targetCodec=t)}))}set targetScreenCodec(e){e&&[VideoCodecName.H264,VideoCodecName.VP8,VideoCodecName.ByteVC1].forEach((t=>{e.toLowerCase()===t.toLowerCase()&&(this._targetScreenCodec=t)}))}get targetCodec(){return this._targetCodec}get targetScreenCodec(){return this._targetScreenCodec}resetPubSubLock(e){this.pubSubLock.closeReason=e,this.pubSubLock=new PromiseLock2("pubSubLock")}setUserStreamConf(e,t,i){const r=this._userStreamConfig.get(e)||{},o=r[t]||{};r[t]={...o,...i},this._userStreamConfig.set(e,r)}getRemoteMirrorType(e,t){var i,r;return!!(null==(r=null==(i=this._userStreamConfig.get(e))?void 0:i[t])?void 0:r.mirrorType)}get rtsMode(){return this.rtsLimiter.rtsMode}setRTSMode(e){this.rtsLimiter.e2e.setLimitMode(e),this.rtsLimiter.boradcast.setLimitMode(e),this.rtsLimiter.e2s.setLimitMode(e),this.rtsLimiter.rtsMode=e}setRtsQpsConf(e){this.rtsLimiter.e2e.setQPS(null==e?void 0:e.rts_qps_interval,null==e?void 0:e.rts_e2e_qps_value),this.rtsLimiter.boradcast.setQPS(null==e?void 0:e.rts_qps_interval,null==e?void 0:e.rts_broadcast_qps_value),this.rtsLimiter.e2s.setQPS(null==e?void 0:e.rts_qps_interval,null==e?void 0:e.rts_e2s_qps_value),this.rtsLimiter.conf=e}get receiveSEIWorker(){return this._receiveSEIWorker||(this._receiveSEIWorker=new WorkerWrapper),this._receiveSEIWorker}updatePCKillSwitch(e){this.pcKillSwitch={...this.pcKillSwitch,...e}}destroy(){this.engineDestroyed=!0,this.signalingManager.destroy(),this.userPriority.clear(),this.avSync=!0,this._localAudioTrackDumpConfig={[StreamIndex$1.STREAM_INDEX_MAIN]:{callback:void 0,frameSize:void 0},[StreamIndex$1.STREAM_INDEX_SCREEN]:{callback:void 0,frameSize:void 0}},this._remoteAudioTrackDumpConfig[StreamIndex$1.STREAM_INDEX_MAIN].clear(),this._remoteAudioTrackDumpConfig[StreamIndex$1.STREAM_INDEX_SCREEN].clear(),this.extensionManager.destroy(),this.earMonitorSettings={[StreamIndex$1.STREAM_INDEX_MAIN]:{position:EarMonitorPosition.NONE,volume:100},[StreamIndex$1.STREAM_INDEX_SCREEN]:{position:EarMonitorPosition.NONE,volume:100}},this.publicAudioVolume.clear()}}function pubSubLock(e,t,i){const r=i.value;return i.value=async function(...e){var t,i,o,s;const n=await this._ctx.pubSubLock.lock();"chrome"!==(null==(t=this._ctx.handler)?void 0:t.name)&&"standard"!==(null==(i=this._ctx.handler)?void 0:i.name)||n();try{const{closeReason:t}=this._ctx.pubSubLock;if(t)throw new SDKError(ErrorCode.UNEXPECTED_ERROR,t);return await r.apply(this,e)}finally{"chrome"!==(null==(o=this._ctx.handler)?void 0:o.name)&&"standard"!==(null==(s=this._ctx.handler)?void 0:s.name)&&n()}},i}function checkNotInRTSRoom(e,t,i){const r=i.value;return i.value=async function(...e){var i;if(null==(i=this._room)?void 0:i.config.isRTSOnlyRoom())throw new SDKError(ErrorCode.NOT_ALLOWED_IN_RTS_ROOM,`Engine.${t}() is not allowed in RTS room`);return await r.apply(this,e)},i}const encodedTransformSupported=isLegacyEncodedTransformSupported()||isEncodedTransformSupported();class VendorHandler extends BasicHandler{constructor(e,t){super(e,t),__publicField(this,"_peerConnectionId",genUuid()),__publicField(this,"peerConnectionMode",1),__publicField(this,"name","vendor"),__publicField(this,"direction","up"),__publicField(this,"stream"),t.on("ice_state",(e=>{this._report("rtc_ice_state",{pc_session_id:this.peerConnectionId,direction:this.direction,error_code:0,ice_state:e.toUpperCase(),message:"",peer_connection_id:this.peerConnectionId,stream_id:"",stream_user_id:""})})),t.on("disconnect",(()=>{this.emit("disconnect")}))}async publish(e){this._context.videoProfile.closeSimulcast(),this.stream=e;const{videoDescriptions:t,subVideoDescriptions:i,audioTransceiverInit:r,videoTransceiverInit:o}=super.internalPublish(e);e.audioTransceiver=this._peerConnection.addTransceiver(r.track,r.init),e.videoTransceiver=this._peerConnection.addTransceiver(o.track,o.init),encodedTransformSupported&&(e.initAudioEncodedTransform(),e.initVideoEncodedTransform()),this._report("rtc_begin_create_offer",{direction:"up",stream_id:"",stream_user_id:"",pc_session_id:this.peerConnectionId,vendor_mode:(null==e?void 0:e.vendorCode)||0});const s=await this.peer.createOfferSdp(),n=getServerNow(),a=lib.parse(s);Array.isArray(a.media)&&(a.media=a.media.map((e=>{var t;if("video"===e.type)(isSafari||isIOS)&&Array.isArray(e.ext)&&(e.ext=e.ext.filter((e=>{var t;return!(null==(t=null==e?void 0:e.uri)?void 0:t.includes("video-orientation"))}))),isSafari||this.addBitrateLimit(e,this._context.videoProfile.getVideoEncodeConfig()[0].maxKbps);else if("audio"===e.type){const i=null==e?void 0:e.rtp.find((e=>"opus"===e.codec));if(i&&e.fmtp){const r=e.fmtp.find((e=>e.payload===i.payload));r&&(null==(t=this._context)?void 0:t.audioProfileManager)&&(r.config=this._context.audioProfileManager.getOpusConfigStr(r.config))}}return e})));const d={type:"offer",sdp:lib.write(a)};try{await this._peerConnection.setLocalDescription(d),this._report("rtc_set_description",{error_code:0,message:d.sdp||"",is_local:"1",direction:"up",stream_id:"",stream_user_id:"",elapse:getServerNow()-n},{type:"offer"})}catch(e){throw this._report("rtc_set_description",{error_code:-1,message:e.message+d.sdp,is_local:"1",direction:"up",stream_id:"",stream_user_id:"",elapse:getServerNow()-n},{type:"offer"}),e}return{partialSdp:d.sdp||"",audioMid:"0",videoMid:"1",type:"offer",semantics:"unified-plan",videoDescriptions:t,subVideoDescriptions:i,audioTransceiverInit:r,videoTransceiverInit:o,peerConnectionMode:this.peerConnectionMode,peerConnectionId:this.peerConnectionId}}async subscribe(e){this.stream=e,this.direction="down",e.audioTransceiver=this._peerConnection.addTransceiver("audio",{direction:"recvonly"}),e.videoTransceiver=this._peerConnection.addTransceiver("video",{direction:"recvonly"}),encodedTransformSupported&&(e.initAudioEncodedTransform(),e.initVideoEncodedTransform()),this._report("rtc_begin_create_offer",{direction:"down",stream_id:e.streamId,stream_user_id:e.userId,pc_session_id:this.peerConnectionId,vendor_mode:e.vendorCode||0});const t=await this.peer.createOfferSdp(),i=getServerNow(),r=lib.parse(t);Array.isArray(r.media)&&(r.media=r.media.map((e=>{if("audio"===e.type){const t=null==e?void 0:e.rtp.find((e=>"opus"===e.codec));if(t&&(null==e?void 0:e.fmtp)){const i=null==e?void 0:e.fmtp.find((e=>e.payload===t.payload));i&&this._context&&(i.config+=";stereo=1;sprop-stereo=1")}}return e})));const o={type:"offer",sdp:lib.write(r)};try{await this._peerConnection.setLocalDescription(o),this._report("rtc_set_description",{error_code:0,message:o.sdp||"",is_local:"1",direction:"down",stream_id:e.streamId,stream_user_id:e.userId,elapse:getServerNow()-i},{type:"offer"})}catch(t){throw this._report("rtc_set_description",{error_code:-1,message:t.message+o.sdp,is_local:"1",direction:"down",stream_id:e.streamId,stream_user_id:e.userId,elapse:getServerNow()-i},{type:"offer"}),t}return{partialSdp:o.sdp||"",audioMid:"0",videoMid:"1",type:"offer",semantics:"unified-plan",peerConnectionMode:this.peerConnectionMode,peerConnectionId:this.peerConnectionId}}async handleAck(e){var t,i,r,o;if(e.action===SdpAction.publish||e.action===SdpAction.subscribe){const{signalingAck:s,videoMid:n,videoCodec:a}=e,{sdp:d}=s,c=lib.parse(d);c.media=c.media.map((e=>(e.mid===n&&a&&setCodecPreferences(e,a),e)));const l={sdp:lib.write(c),type:"answer"},u=getServerNow();try{await this._peerConnection.setRemoteDescription(l),this._report("rtc_set_description",{error_code:0,message:l.sdp||"",is_local:"1",direction:"down",stream_id:(null==(t=e.stream)?void 0:t.streamId)||"",stream_user_id:null==(i=e.stream)?void 0:i.userId,elapse:getServerNow()-u},{type:"answer"})}catch(t){throw this._report("rtc_set_description",{error_code:-1,message:t.message+l.sdp,is_local:"1",direction:"down",stream_id:(null==(r=e.stream)?void 0:r.streamId)||"",stream_user_id:null==(o=e.stream)?void 0:o.userId,elapse:getServerNow()-u},{type:"offer"}),t}"function"==typeof e.onSuccess&&e.onSuccess()}else e.action!==SdpAction.unpublish&&e.action!==SdpAction.unsubscribe||this.destroy();return""}destroy(){this.peer.destroy(),super.destroy()}async getDefaultSdp(){return{sdp:"",type:"offer",semantics:""}}connect(){throw new Error("Method not implemented.")}async rollback(){try{this._peerConnection.close()}catch(e){}}get peerConnectionId(){return this._peerConnectionId}set peerConnectionId(e){this._peerConnectionId=e}}var __defProp$7=Object.defineProperty,__getOwnPropDesc$7=Object.getOwnPropertyDescriptor,__decorateClass$7=(e,t,i,r)=>{for(var o,s=r>1?void 0:r?__getOwnPropDesc$7(t,i):t,n=e.length-1;n>=0;n--)(o=e[n])&&(s=(r?o(t,i,s):o(s))||s);return r&&s&&__defProp$7(t,i,s),s};class RoomPublisher extends EnhancedEventEmitter{constructor(e,t){super(),__publicField(this,"_logger"),__publicField(this,"_pubBackOff",new Map),this._ctx=e,this._roomConf=t,this._logger=new Logger$1("RoomPublisher",2,e.id)}async hasPublished(e){return!!e.audioMid&&!!e.videoMid}async publish(e){return this._publish(e)}async _publish(e){var t,i,r,o,s,n,a,d,c;this._logger.info("publish()","localStream: %o",e);const{videoTrack:l}=e,{audioTrack:u}=e,_=getServerNow();let h,{handler:p}=this._ctx;this._roomConf.vendorConfig.enableMultiVendor?[p,h]=await this._getVendorPubSdpInfo(e):h=await this._ctx.handler.publish(e),this.emit("_test_pub_sdpInfo_",h);const{audioMid:m,videoMid:S}=h;e.pubAttributes={localaudio:!!u,localvideo:!!l,videostream:e.pubVideo,audiostream:e.pubAudio,extvideo:(null==l?void 0:l.sourceType)===SourceType.EXTERNAL,extaudio:(null==u?void 0:u.sourceType)===SourceType.EXTERNAL,videoDescriptions:h.videoDescriptions,videoType:VideoType.NORMAL};const g={attributes:{...e.pubAttributes},audio:!0,video:!0,screen:e.isScreen,audioMid:m,videoMid:S,sdpInfo:{msid:e.stream.id,type:h.type,sdp:h.partialSdp,semantics:h.semantics},peerConnectionMode:null==h?void 0:h.peerConnectionMode,supportMultiVendor:!0},v=!this._roomConf.vendorConfig.enableMultiVendor&&e.enableSimulcast&&(null==(t=this._ctx.serverConfig)?void 0:t.simulcastOnDemand)&&(null==(i=h.subVideoDescriptions)?void 0:i.length);let f;(v||(null==(r=this._ctx.serverConfig)?void 0:r.e2eFeedback))&&(g.attributes.subVideoDescriptions=h.subVideoDescriptions),(null==h?void 0:h.peerConnectionId)&&(g.peerConnectionId=h.peerConnectionId);try{this.emit("_test_pub_body_",g),f=await this._ctx.signalingManager.sendSignaling("publish",g)}catch(t){if(this._logger.error("_publish",getErrorString(t)),null==(o=this._ctx.monitor)||o.report("rtc_error",{message:`[publisher._publish] ${getErrorString(t)}`,error_code:-1}),t instanceof Error?this._roomConf.report("rtc_publish_stat",{result:"fail",is_screen:"0",start:_,message:`${t.name}: ${t.message}`}):t instanceof SDKError&&this._roomConf.report("rtc_publish_stat",{result:"fail",is_screen:"0",start:_,message:`${t.code}: ${t.message}`}),await(null==p?void 0:p.rollback({msid:e.stream.id,stream:e,audioMid:m,videoMid:S})),t.code>=500&&t.code<600){this.emit("_test_pub_5xx_");const t=this._getPubBackOff(e.id);if(t.retryDuration<6e4)return this._logger.info("pubRetry",e.id,t.retryDuration),await new Promise((e=>setTimeout(e,t.interval))),t.retryDuration+=t.interval,t.interval=t.interval>4e3?8e3:2*t.interval,e.resetStream(),this.emit(RoomEvent.PUB_RETRY,{screen:e.isScreen}),this._publish(e);this._logger.info("pubRetry","end"),this._pubBackOff.delete(e.id)}else if(403===t.code)throw new SDKError(ErrorCode.TOKEN_NO_PUBLISH_PERMISSION,t.message||"token no publish permission");throw t}this._roomConf.report("rtc_recv_answer",{error_code:0,answer_type:null==f?void 0:f.relayMessage.type,sequence_id:(null==(s=null==f?void 0:f.relayMessage)?void 0:s.sequenceId)||0,message:null==(n=null==f?void 0:f.relayMessage)?void 0:n.sdp,direction:"up",stream_id:"",stream_user_id:"",pc_session_id:(null==p?void 0:p.peerConnectionId)||""}),e.isScreen?e.setVideoCaps(null==(a=f.relayMessage.content)?void 0:a.screenCaps):e.setVideoCaps(null==(d=f.relayMessage.content)?void 0:d.videoCaps),e.streamId=f.streamId;const E=await e.getSelectedCodec();e.currentVideoCodec=E;const T=new Promise(((t,i)=>{var r,o;null==p||p.handleAck({action:SdpAction.publish,streamId:f.streamId,audioMid:m,videoMid:S,audioTransceiverInit:null==h?void 0:h.audioTransceiverInit,videoTransceiverInit:null==h?void 0:h.videoTransceiverInit,signalingAck:{sdp:null==(r=null==f?void 0:f.relayMessage)?void 0:r.sdp,sequenceId:null==(o=null==f?void 0:f.relayMessage)?void 0:o.sequenceId},stream:e,videoCodec:E,onSuccess:()=>{this._logger.info("publish()","publish success"),t(0)},onFail:e=>{this._logger.info("publish()","publish fail"),i(e)}})}));!isFirefox&&await T,this.emit("___afterHandleAckInPub"),(v&&this._ctx.videoProfile.getSimulcastMode()===VideoSimulcastMode.VIDEO_ON_DEMAND||(null==(c=this._ctx.serverConfig)?void 0:c.e2eFeedback))&&this.emit(MediaServerSignalEvent.RSCP,[{StreamIds:[e.stream.id],Metadata:{VideoIndex:0}}],!0),e.videoMid=S,e.audioMid=m,e.subVideoDescriptions=h.subVideoDescriptions,e.remoteSdp=f.relayMessage.sdp,this._roomConf.report("rtc_publish_stat",{result:"success",is_screen:"0",start:_,message:"unknown"})}async updatePubTrack(e){var t,i,r,o;this._logger.info("updatePubTrack()","localStream: %o",e);const{videoTrack:s,audioTrack:n,pubAudio:a,pubVideo:d}=e,c=e.vendorHandler||this._ctx.handler;let l=null==n?void 0:n.preprocessingTrack;const u=null==s?void 0:s.preprocessingTrack;if(d&&u?(e.stopBlackFrame(),await(null==(t=e.videoTransceiver)?void 0:t.sender.replaceTrack(u)),this._updateVideoDescriptions(e)):await(null==(i=e.videoTransceiver)?void 0:i.sender.replaceTrack(null)),a&&l){const{mixType:t,mixedAudioTrack:i}=n;i&&t!==AudioMixingType.PLAYOUT&&l.enabled&&(l=i),await(null==(r=e.audioTransceiver)?void 0:r.sender.replaceTrack(l))}else await(null==(o=e.audioTransceiver)?void 0:o.sender.replaceTrack(null)),reportRtcInvokeStatus(this._ctx.id,"MediaClient.updatePubTrack(audio)","null");await this._updatePublishCodec(e),this.emit("___onAfterReplaceTrack");try{reportRtcInvokeStatus(this._ctx.id,"MediaClient.updatePubTrack",JSON.stringify({audioStreamTrack:mediaTrackStringify(l),videoStreamTrack:mediaTrackStringify(u)}))}catch(e){}const _={localaudio:!!n,localvideo:!!s,videostream:d,audiostream:a,extvideo:(null==s?void 0:s.sourceType)===SourceType.EXTERNAL,extaudio:(null==n?void 0:n.sourceType)===SourceType.EXTERNAL,videoType:s?VideoType.NORMAL:e.pubAttributes.videoType},h={};for(const[t,i]of Object.entries(_))i!==Reflect.get(e.pubAttributes,t)&&Reflect.set(h,t,i);if(!Object.keys(h).length)return;if(e.observer){const{observer:t}=e,{audiostream:i,videostream:r,localaudio:o,localvideo:s,extaudio:n,extvideo:a}=h;void 0!==s?void 0!==a?t.setPushVideo(a):t.setEnableVideo(s):void 0!==r&&t.setUnmuteVideo(r),void 0!==o?void 0!==n?t.setPushAudio(n):t.setEnableAudio(o):void 0!==i&&t.setUnmuteAudio(i)}e.pubAttributes={...e.pubAttributes,..._},e.pubAttributes.videostream||e.stopBlackFrame();const p={roomId:this._roomConf.roomId,streamId:e.streamId,attributes:h};await this._ctx.signalingManager.sendSignaling("updateStreamAttributes",p),this.emit("___onAfterUpdateSignaling"),isFirefox&&await(null==c?void 0:c.setCurrentDescription())}async _updatePublishCodec(e){var t;this._logger.info("updatePublishCodec()","localStream: %o",e);const{audioMid:i,videoMid:r,remoteSdp:o,streamId:s,currentVideoCodec:n}=e,a=await e.getSelectedCodec();if(this._logger.info("updatePublishCodec()","selectedCodec: %o",a),a!==n){if(e.currentVideoCodec=a,i&&r&&s&&o)return(this._ctx.handler instanceof FirefoxHandler||this._ctx.handler instanceof FallbackHandler)&&await(null==(t=this._ctx.handler)?void 0:t._internalChangePubCodec()),new Promise(((t,n)=>{var d;null==(d=this._ctx.handler)||d.handleAck({action:SdpAction.publish,streamId:s,audioMid:i,videoMid:r,signalingAck:{sdp:o,sequenceId:-1},videoCodec:a,onSuccess:t,onFail:n,stream:e})}));{const t=["audioMid","videoMid","streamId","remoteSdp"].filter((t=>!Reflect.get(e,t)));this._logger.warn("updatePublishCodec()","fast return, because params: %o",t)}}else this._logger.warn("updatePublishCodec()","selectedCodec is equal to currentVideoCodec")}async unpublish(e){this._logger.info("unpublish()","localStream: %o",e);const t={roomId:this._roomConf.roomId,initStreamId:e.initStreamId,streamId:e.streamId};this._ctx.signalingManager.sendSignaling("unpublish",t).catch((()=>{}));const i=e.vendorHandler||this._ctx.handler;e.stopBlackFrame(),await(null==i?void 0:i.handleAck({action:SdpAction.unpublish,audioMid:e.audioMid,videoMid:e.videoMid,stream:e,streamId:e.streamId}))}async updatePubBlackFrame(e){var t,i;const r=e.genBlackFrame();r&&(null==(i=null==(t=e.videoTransceiver)?void 0:t.sender)||i.replaceTrack(r),e.pubAttributes.videoType=VideoType.BLACK,this._ctx.signalingManager.sendSignaling("updateStreamAttributes",{roomId:this._roomConf.roomId,streamId:e.streamId,attributes:{videoType:VideoType.BLACK}}),e.on("black-frame-ended",(()=>{var t,i;null==(i=null==(t=e.videoTransceiver)?void 0:t.sender)||i.replaceTrack(null),e.pubAttributes.videoType=VideoType.NORMAL,this._ctx.signalingManager.sendSignaling("updateStreamAttributes",{roomId:this._roomConf.roomId,streamId:e.streamId,attributes:{videoType:VideoType.NORMAL}})})))}async cleanStream(e){return this._logger.info("cleanStream()","localStream: %o",e),null==e?void 0:e.clean()}async destroyStream(e){return this._logger.info("destroyStream()","localStream: %o",e),null==e?void 0:e.destroy()}destroy(e){e.forEach((e=>{e&&(this.unpublish(e).catch((()=>{})),this.destroyStream(e).catch((()=>{})))})),this._pubBackOff.clear(),super.removeAllListeners()}async _updateVideoDescriptions(e){var t,i,r,o;const s=this._ctx.videoProfile.genVideoDescriptions(e),n=e.pubAttributes.videoDescriptions;if(n.length!==s.videoDescriptions.length)return;const a={};if(n.find(((e,t)=>{if(e.framerate!==s.videoDescriptions[t].framerate||e.maxkbps!==s.videoDescriptions[t].maxkbps||e.width!==s.videoDescriptions[t].width||e.height!==s.videoDescriptions[t].height)return a.videoDescriptions=s.videoDescriptions,!0})),null==(t=e.subVideoDescriptions)||t.find(((e,t)=>{if(e.framerate!==s.subVideoDescriptions[t].framerate||e.maxkbps!==s.subVideoDescriptions[t].maxkbps||e.width!==s.subVideoDescriptions[t].width||e.height!==s.subVideoDescriptions[t].height)return a.subVideoDescriptions=s.subVideoDescriptions,!0})),Object.keys(a).length>0){this._ctx.signalingManager.sendSignaling("updateStreamAttributes",{roomId:this._roomConf.roomId,streamId:e.streamId,attributes:a});const t=null==(r=null==(i=e.videoTransceiver)?void 0:i.sender)?void 0:r.getParameters();reportRtcInvokeStatus(this._ctx.id,"sender.getParameters",JSON.stringify(t),0,e.streamId),t&&Array.isArray(null==t?void 0:t.encodings)&&(t.encodings=t.encodings.map(((e,i)=>((e.rid??(1===t.encodings.length?"0":void 0))===s.sendEncodings[i].rid&&(e.maxBitrate=s.sendEncodings[i].maxBitrate,e.maxFramerate=s.sendEncodings[i].maxFramerate,e.scaleResolutionDownBy=s.sendEncodings[i].scaleResolutionDownBy),e))),this._logger.info("sender.setParameters()",JSON.stringify(t.encodings)),reportRtcInvokeStatus(this._ctx.id,"sender.setParameters",JSON.stringify(t),0,e.streamId),null==(o=e.videoTransceiver)||o.sender.setParameters(t),reportRtcInvokeStatus(this._ctx.id,"Handler.updateScaleResolutionDownBy",JSON.stringify(t.encodings)))}}async _getVendorPubSdpInfo(e){const t=new PeerConnection(this._ctx,"");e.vendorHandler=new VendorHandler(this._ctx,t),e.pcSessionId&&(e.vendorHandler.peerConnectionId=e.pcSessionId);const i=await e.vendorHandler.publish(e),r=e.vendorHandler;return r.on("ice_state",(e=>{this.emit(StateEvent.ON_VENDOR_CONNECTION_STATE_CHANGE,{state:{checking:ConnectionState.CONNECTION_STATE_CONNECTING,connected:ConnectionState.CONNECTION_STATE_CONNECTED,disconnected:ConnectionState.CONNECTION_STATE_RECONNECTING}[e],userId:this._roomConf.userId})})),r.once("disconnect",(async()=>{var t;r.removeAllListeners(),"connected"===(null==(t=this._ctx.peerConnection)?void 0:t.getIceConnectionState())?(await this.unpublish(e),await this.publish(e),e.vendorHandler&&e.statsReport.setVar(e.vendorHandler)):this._logger.info("vendor ice failed",e.streamId)})),[r,i]}_getPubBackOff(e){return this._pubBackOff.has(e)||this._pubBackOff.set(e,{interval:1e3,retryDuration:0}),this._pubBackOff.get(e)}}__decorateClass$7([streamQueue],RoomPublisher.prototype,"hasPublished",1),__decorateClass$7([streamQueue,pubSubLock,checkRoomState],RoomPublisher.prototype,"publish",1),__decorateClass$7([streamQueue,pubSubLock,checkRoomState],RoomPublisher.prototype,"updatePubTrack",1),__decorateClass$7([streamQueue,pubSubLock,checkRoomState],RoomPublisher.prototype,"unpublish",1),__decorateClass$7([streamQueue,checkRoomState],RoomPublisher.prototype,"updatePubBlackFrame",1),__decorateClass$7([streamQueue],RoomPublisher.prototype,"cleanStream",1),__decorateClass$7([streamQueue],RoomPublisher.prototype,"destroyStream",1),__decorateClass$7([checkRoomState],RoomPublisher.prototype,"_updateVideoDescriptions",1);var __defProp$6=Object.defineProperty,__getOwnPropDesc$6=Object.getOwnPropertyDescriptor,__decorateClass$6=(e,t,i,r)=>{for(var o,s=r>1?void 0:r?__getOwnPropDesc$6(t,i):t,n=e.length-1;n>=0;n--)(o=e[n])&&(s=(r?o(t,i,s):o(s))||s);return r&&s&&__defProp$6(t,i,s),s};class RoomSubscriber extends EnhancedEventEmitter{constructor(e,t){super(),__publicField(this,"_logger"),__publicField(this,"_subBackOff",new Map),__publicField(this,"_subResolves",{}),__publicField(this,"_ontrackCallbackMap",new Map),this._ctx=e,this._roomConf=t,this._logger=new Logger$1("RoomSubscriber",2,e.id)}async hasSubscribed(e){return e.streamState===StreamState.SUB_ED}async subscribe(e,t,i){if(e.streamState!==StreamState.SUB_ED)return this._subscribe(e,t,i);this._logger.warn("subscribe()",`remoteStream ${e.streamId} has been subscribed, silently return`)}async _subscribe(e,t,i){var r,o,s,n,a,d,c;this._logger.info("subscribe()","mediaType: %o",t),logRemoteStream("subscribe()",e,this._logger),e.streamState=StreamState.SUB_ING;let l=!1,u=!1;if(audioInMediaType(t)&&(u=!0),videoInMediaType(t)&&(l=!0),!l&&this._roomConf.isMultiChatMode())return void(e.streamState=StreamState.INIT);const _=getServerNow(),h=e.subVideo,p=[];this._subResolves[e.streamId]||(this._subResolves[e.streamId]=[]),p.push(new Promise(((t,i)=>{this._subResolves[e.streamId].push(t);const r=setTimeout((()=>i(new SDKError(ErrorCode.TIME_OUT,`wait video timeout for userId: ${e.userId}`))),6e4),o=i=>{"video"===i.mediaType&&(this._logger.info(`remoteStream ${e.userId} received video track`),e.off("ontrack",o),clearTimeout(r),t(0))};e.on("ontrack",o)}))),this._roomConf.isMultiChatMode()||p.push(new Promise(((t,i)=>{this._subResolves[e.streamId].push(t);const r=setTimeout((()=>i(new SDKError(ErrorCode.TIME_OUT,`wait audio timeout for userId: ${e.userId}`))),6e4),o=i=>{"audio"===i.mediaType&&(this._logger.info(`remoteStream ${e.userId} received audio track`),e.off("ontrack",o),clearTimeout(r),t(0))};e.on("ontrack",o)})));const m=t=>{e.ontrack(t)};null==(r=this._ctx.handler)||r.on("ontrack",m),this._ontrackCallbackMap.set(e,m);let S,{handler:g}=this._ctx;!(null==(o=this._ctx.serverConfig)?void 0:o.forceUniHandler)&&e.enableVendorMode?[g,S]=await this._getVendorSubSdpInfo(e,m):S=await this._ctx.handler.subscribe(e,{multiChatMode:this._roomConf.isMultiChatMode()});const{audioMid:v,videoMid:f}=S;e.subVideo=l;const E={spatialLayer:(null==i?void 0:i.spatialLayer)||0,temporalLayer:0,spatialSubLayer:(null==i?void 0:i.spatialSubLayer)||-1},T={audio:!this._roomConf.isMultiChatMode(),video:!0,data:!0,screen:e.isScreen,browser:"chrome-stable",videoMid:f,audioMid:v,sdpInfo:{sdp:null==S?void 0:S.partialSdp,semantics:null==S?void 0:S.semantics,type:null==S?void 0:S.type},streamUserId:e.userId,streamId:e.streamId,config:{enableMediaType:{audio:!!this._roomConf.isMultiChatMode()||u,video:l},qualityLayer:E},extra:{enableSendRTT:!0},peerConnectionMode:null==S?void 0:S.peerConnectionMode,supportMultiVendor:!0};(null==S?void 0:S.peerConnectionId)&&(T.peerConnectionId=S.peerConnectionId);const{subscribeFallbackOption:R,userPriority:b}=this._ctx;"number"==typeof R&&(T.config.fallbackOption=R),b.has(e.userId)&&(T.config.priority=b.get(e.userId)),(null==S?void 0:S.allSsrc)&&(T.extra.subscribeSSRC=S.allSsrc),this.emit("_test_before_ack_");const{signalingAck:y,audioTransceiverInit:I,videoTransceiverInit:C}=S;let A;y&&(e.videoMid=f,e.audioMid=v,await new Promise(((t,i)=>{null==g||g.handleAck({action:SdpAction.subscribe,streamId:e.streamId,audioMid:v,videoMid:f,audioTransceiverInit:I,videoTransceiverInit:C,signalingAck:y,stream:e,onSuccess:()=>{this._logger.info("ssrc","success"),t(0)},onFail:e=>{this._logger.info("ssrc","fail",e),i(e)}})})));try{this.emit("_test_sub_body_",T);const e=this._ctx.signalingManager.sendSignaling("subscribe",T);this.emit("_test_during_signaling_",T),A=await e}catch(r){if(null==(s=this._ctx.monitor)||s.report("rtc_error",{message:`[subscriber._subscribe] ${getErrorString(r)}`,error_code:-1}),e.streamState=StreamState.INIT,r instanceof Error&&this._roomConf.report("rtc_subscribe_stat",{result:"fail",start:_,message:r.message,stream_user_id:e.userId}),r.code>=500&&r.code<600){this.emit("_test_sub_5xx_");const r=this._getSubBackOff(e.streamId);if(r.retryDuration<6e4)return this._logger.info("subRetry",e.streamId,r.retryDuration),await new Promise((e=>setTimeout(e,r.interval))),r.retryDuration+=r.interval,r.interval=r.interval>4e3?8e3:2*r.interval,this.emit(RoomEvent.SUB_RETRY,{screen:e.isScreen,userId:e.userId}),await(null==g?void 0:g.handleAck({action:SdpAction.unsubscribe,streamId:e.streamId,audioMid:v,videoMid:f,stream:e})),e.resetStream(),this._subscribe(e,t,i);this._logger.info("subRetry","end",e.streamId),this._subBackOff.delete(e.streamId)}e.subVideo=h,await(null==g?void 0:g.rollback({msid:e.streamId,stream:e}));const o={roomId:this._roomConf.roomId,streamId:e.streamId,userId:e.userId};if(await this._ctx.signalingManager.sendSignaling("unsubscribe",o).catch((()=>{})),e.streamState=StreamState.INIT,403===r.code)throw new SDKError(ErrorCode.TOKEN_NO_SUBSCRIBE_PERMISSION,r.message||"token no subscribe permission");throw r}if(!A.relayMessage)throw this._roomConf.report("rtc_error",{error_code:-1009,message:"relayMessage is null"}),new SDKError(ErrorCode.UNEXPECTED_ERROR,"unable to subscribe");const{audioMid:k,videoMid:M}=(null==A?void 0:A.relayMessage)??{},N={[v]:k,[f]:M};this._logger.info("sub midmap",e.userId,N),e.videoMid=f,e.audioMid=v,e.subMediaType=t,e.streamState=StreamState.SUB_ED,e.subLayer=E,this._roomConf.report("rtc_recv_answer",{error_code:0,answer_type:null==(n=null==A?void 0:A.relayMessage)?void 0:n.type,sequence_id:(null==(a=null==A?void 0:A.relayMessage)?void 0:a.sequenceId)||0,message:null==(d=null==A?void 0:A.relayMessage)?void 0:d.sdp,direction:"down",stream_id:e.streamId,stream_user_id:e.userId,pc_session_id:(null==g?void 0:g.peerConnectionId)||""});try{(null==S?void 0:S.signalingAck)||await new Promise(((t,i)=>{var r,o;null==g||g.handleAck({action:SdpAction.subscribe,streamId:e.streamId,audioMid:v,videoMid:f,audioTransceiverInit:null==S?void 0:S.audioTransceiverInit,videoTransceiverInit:null==S?void 0:S.videoTransceiverInit,signalingAck:{sdp:null==(r=null==A?void 0:A.relayMessage)?void 0:r.sdp,sequenceId:null==(o=null==A?void 0:A.relayMessage)?void 0:o.sequenceId},stream:e,onSuccess:()=>{this._logger.info("sub ack","success"),t(0)},onFail:e=>{this._logger.info("sub ack","fail",e),i(e)}})})),await Promise.all(p)}catch(t){null==(c=this._ctx.monitor)||c.report("rtc_error",{message:`[subscriber._subscribe] ${getErrorString(t)}`,error_code:-1}),t instanceof Error&&this._roomConf.report("rtc_subscribe_stat",{result:"fail",start:_,message:t.message,stream_user_id:e.userId});const i={roomId:this._roomConf.roomId,streamId:e.streamId,userId:e.userId};throw await this._ctx.signalingManager.sendSignaling("unsubscribe",i).catch((()=>{})),await(null==g?void 0:g.handleAck({action:SdpAction.unsubscribe,streamId:e.streamId,audioMid:v,videoMid:f,stream:e})),e.streamState=StreamState.INIT,e.resetStream(),t}this._roomConf.isMultiChatMode()||(e.subAudio=u),this._roomConf.report("rtc_subscribe_stat",{result:"success",start:_,message:"unknown",stream_user_id:e.userId}),e.startReport((e=>this.emit("onRemoteStreamStats",e)),g)}async unsubscribe(e){return this._unsubscribe(e)}async _unsubscribe(e){var t,i;logRemoteStream("unsubscribe()",e,this._logger);const r={roomId:this._roomConf.roomId,streamId:e.streamId,userId:e.userId},o=e.vendorHandler||this._ctx.handler;this._ctx.signalingManager.sendSignaling("unsubscribe",r).catch((()=>{})),e.streamState=StreamState.INIT,e.subVideo=!1,null==(t=e.observer)||t.setSubscribeVideo(!1),!this._roomConf.isMultiChatMode()&&(null==(i=e.observer)||i.setSubscribeAudio(!1));const s=await(null==o?void 0:o.handleAck({action:SdpAction.unsubscribe,streamId:e.streamId,audioMid:e.audioMid,videoMid:e.videoMid,stream:e}));this._subResolves[s]&&this._subResolves[s].forEach((e=>e(0))),this._logger.info("unsubscribe",`clean unsub ${e.userId}`),e.clean(),e.subMediaType=ExtendMediaType.NONE,this._removeOnTrackListener(e),e.statsReport.unsubscribe()}async unsubscribe4removeTrack(e,t,i){var r,o,s,n;if(logRemoteStream("unsubscribe4removeTrack()",e,this._logger),this._logger.info("unsubscribe4removeTrack()","sequenceId: ",t.sequenceId,"trackType: ",i),t.sequenceId<e.sequenceId)return void this._logger.warn("unsubscribe4removeTrack()","sequenceId return");const a=i+1,d=!!(a&MediaType$1.AUDIO),c=!!(a&MediaType$1.VIDEO);await(null==(r=this._ctx.handler)?void 0:r.handleAck({action:SdpAction.removetrack,streamId:e.streamId,audioMid:e.audioMid,videoMid:e.videoMid,stream:e})),null==(o=e.observer)||o.setPushTrack(!1),null==(s=e.observer)||s.setUnmuteAudio(!d),e.subAudio=!d,null==(n=e.observer)||n.setUnmuteVideo(!c),e.subVideo=!c,e.subMediaType=e.subMediaType-(e.subMediaType&a),e.virtual&&(e.clean(),e.resetHasSubscribed(),e.statsReport.unsubscribe())}async handleStreamFailed(e){const t=e.subMediaType,i=e.subLayer;await this._unsubscribe(e),await this._subscribe(e,t,i)}async handleRemoveStream(e){logRemoteStream("handleRemoveStream()",e,this._logger),e.subVideo=!1,e.streamState!==StreamState.INIT&&(await this._unsubscribe(e),await this._cleanStream(e),this._destroyStream(e))}_removeOnTrackListener(e){const t=this._ontrackCallbackMap.get(e);if(t){const i=e.vendorHandler||this._ctx.handler;null==i||i.off("ontrack",t),this._ontrackCallbackMap.delete(e)}}async _getVendorSubSdpInfo(e,t){const i=new PeerConnection(this._ctx,"");e.vendorHandler=new VendorHandler(this._ctx,i),e.pcSessionId&&(e.vendorHandler.peerConnectionId=e.pcSessionId);const r=e.vendorHandler;r.on("ontrack",t);const o=await e.vendorHandler.subscribe(e);return r.on("ice_state",(t=>{this.emit(StateEvent.ON_VENDOR_CONNECTION_STATE_CHANGE,{state:{checking:ConnectionState.CONNECTION_STATE_CONNECTING,connected:ConnectionState.CONNECTION_STATE_CONNECTED,disconnected:ConnectionState.CONNECTION_STATE_RECONNECTING}[t],userId:e.userId})})),r.once("disconnect",(async()=>{var t;if(null==r||r.removeAllListeners(),"connected"!==(null==(t=this._ctx.peerConnection)?void 0:t.getIceConnectionState()))return void this._logger.info("vendor ice failed",e.streamId);const i=e.subMediaType;await this.unsubscribe(e),await this.subscribe(e,i),e.vendorHandler&&e.statsReport.setVar(e.vendorHandler),this.emit(RoomEvent.RESUBSCRIBE,{stream:e})})),[r,o]}async subscribe4pushTrack(e,t){var i,r,o;this._logger.info("subscribe4pushTrack()","streamInfo: %o",t),logRemoteStream("subscribe4pushTrack()",e,this._logger),e.subAudio=!0;const s=await(null==(i=this._ctx.handler)?void 0:i.subscribe(e,{multiChatMode:this._roomConf.isMultiChatMode()}));if(!s)throw new SDKError(ErrorCode.ADD_TRANSCEIVER_FAILED,"add transceiver failed");const{audioMid:n}=s,{videoMid:a}=s,d=[];d.push(new Promise(((t,i)=>{const r=setTimeout((()=>i(new SDKError(ErrorCode.TIME_OUT,`wait audio timeout for userId: ${e.userId}`))),6e4),o=i=>{"audio"===i.mediaType&&(this._logger.success(`remoteStream ${e.userId} received audio track`),e.off("ontrack",o),clearTimeout(r),t(0))};e.on("ontrack",o)})));const c=t=>{e.ontrack(t)};null==(r=this._ctx.handler)||r.on("ontrack",c),this._ontrackCallbackMap.set(e,c),await(null==(o=this._ctx.handler)?void 0:o.handleAck({action:SdpAction.pushtrack,streamId:e.streamId,audioMid:n,videoMid:a,stream:e,audioTransceiverInit:null==s?void 0:s.audioTransceiverInit,videoTransceiverInit:null==s?void 0:s.videoTransceiverInit,signalingAck:null==t?void 0:t.message})),await Promise.all(d),e.videoMid=a,e.audioMid=n,e.startReport((e=>this.emit("onRemoteStreamStats",e)),this._ctx.handler)}async updateUserAttributes(e){this._logger.info("updateUserAttributes()","attributes: %o",e),await this._ctx.signalingManager.sendSignaling("updateUserAttributes",{roomId:this._roomConf.roomId,sessionId:this._roomConf.sessionId,attributes:e})}async updateSubTrackLayer(e,t){if(this._logger.info("updateSubTrack()","subLayer: %o",t),e.subLayer.spatialLayer===t.spatialLayer&&e.subLayer.spatialSubLayer===t.spatialSubLayer)return void this._logger.warn("updateSubTrack()","subLayer no change");const i={roomId:this._roomConf.roomId,streamList:[e.streamId],streamId:e.streamId,streamUserId:e.userId,config:{qualityLayer:t}};return await this._ctx.signalingManager.sendSignaling("updateSubscribe",i),this.emit("___afterUpdateSubscribeSend"),e.subLayer=t,e}async updateSubPriority(e,t){if(this._logger.info("updateSubPriority()","priority: %o",t),e.priority===t)return this._logger.warn("updateSubPriority()","priority no change"),e;const i={roomId:this._roomConf.roomId,streamList:[e.streamId],streamId:e.streamId,streamUserId:e.userId,config:{priority:t}};return await this._ctx.signalingManager.sendSignaling("updateSubscribe",i),e.priority=t,e}async updateSubMediaType(e,t){var i,r;let o=!1,s=!1;audioInMediaType(t)&&(s=!0),videoInMediaType(t)&&(o=!0);const n={roomId:this._roomConf.roomId,streamList:[e.streamId],config:{enableMediaType:{video:o,audio:!!this._roomConf.isMultiChatMode()||s}}};return await this._ctx.signalingManager.sendSignaling("updateSubscribe",n),this._roomConf.isMultiChatMode()||(null==(i=e.observer)||i.setUnmuteAudio(s),e.subAudio=s),null==(r=e.observer)||r.setUnmuteVideo(o),e.subVideo=o,e.subMediaType=t,e}async cleanStream(e){return this._cleanStream(e)}async _cleanStream(e){this._logger.info("cleanStream()","stream: %o",e),null==e||e.clean()}destroyStream(e){return this._destroyStream(e)}_destroyStream(e){this._logger.info("destroyStream()","stream: %o",e),null==e||e.destroy()}destroy(e){var t;this._logger.info("destroy()","remoteStream: %o",e),e.forEach((e=>{this.unsubscribe(e).catch((()=>{})),this.destroyStream(e)})),this._subBackOff.clear(),this._ontrackCallbackMap.forEach(((e,t)=>{this._removeOnTrackListener(t),this._ontrackCallbackMap.delete(t)})),this._subResolves={},null==(t=this._ctx.handler)||t.removeAllListeners("ontrack"),super.removeAllListeners()}_getSubBackOff(e){return this._subBackOff.has(e)||this._subBackOff.set(e,{interval:1e3,retryDuration:0}),this._subBackOff.get(e)}}__decorateClass$6([streamQueue],RoomSubscriber.prototype,"hasSubscribed",1),__decorateClass$6([streamQueue,pubSubLock,checkRoomState],RoomSubscriber.prototype,"subscribe",1),__decorateClass$6([streamQueue,pubSubLock,checkRoomState],RoomSubscriber.prototype,"unsubscribe",1),__decorateClass$6([streamQueue,pubSubLock,checkRoomState],RoomSubscriber.prototype,"unsubscribe4removeTrack",1),__decorateClass$6([streamQueue],RoomSubscriber.prototype,"handleStreamFailed",1),__decorateClass$6([streamQueue,checkRoomState],RoomSubscriber.prototype,"handleRemoveStream",1),__decorateClass$6([streamQueue,pubSubLock,checkRoomState],RoomSubscriber.prototype,"subscribe4pushTrack",1),__decorateClass$6([streamQueue,checkRoomState],RoomSubscriber.prototype,"updateUserAttributes",1),__decorateClass$6([streamQueue,checkRoomState],RoomSubscriber.prototype,"updateSubTrackLayer",1),__decorateClass$6([streamQueue,checkRoomState],RoomSubscriber.prototype,"updateSubPriority",1),__decorateClass$6([streamQueue],RoomSubscriber.prototype,"updateSubMediaType",1),__decorateClass$6([streamQueue],RoomSubscriber.prototype,"cleanStream",1),__decorateClass$6([streamQueue],RoomSubscriber.prototype,"destroyStream",1);const RoomProfileMap={[RoomProfileType.communication]:[0],[RoomProfileType.chat]:[0],[RoomProfileType.chatRoom]:[1,"IES_chatroom"],[RoomProfileType.coHost]:[1,"IES_PK"],[RoomProfileType.meeting]:[16],[RoomProfileType.classRoom]:[0]},_RoomJoin=class extends EnhancedEventEmitter{constructor(e,t){super(),__publicField(this,"_logger"),__publicField(this,"_authorization"),__publicField(this,"_joinRoom5xxTimer"),__publicField(this,"_joinTask"),__publicField(this,"_sdpInfo"),this._ctx=e,this._roomConf=t,this._logger=new Logger$1("RoomJoin",2,e.id),this._logger.info("constructor","invoke")}join(e=!1){let t,i;this._logger.info("join()");const r=new Promise(((r,o)=>{t=r,i=o,this._callJoinRoom(e).catch((e=>{const t=Array.isArray(e)&&e.length>0?e[0]:e;this._joinRoomFailed(t.message)}))}));return this._joinTask&&e?this._joinTask.startTime=getServerNow():(this._joinTask={startTime:getServerNow(),success:t,fail:i},this._roomConf.joinPromise=r),this._reportJoinRoomStart(),r}async updateToken(e){if(this._logger.info("updateToken()","newToken: %o",e),!this._ctx.appId||!this._roomConf.userId||!this._roomConf.roomId)return;const t={roomId:this._roomConf.roomId,userId:this._roomConf.userId,appId:this._ctx.appId,token:`Bearer ${e}`};try{await this._ctx.signalingManager.sendSignaling("updateToken",t)}catch(e){throw new SDKError(ErrorCode.UPDATE_TOKEN_WITH_INVALID_TOKEN,"invoke updateToken with an invalid token")}}async leave(){this._logger.info("leave()"),this._stopJoinRoom5xxRetry(),this._joinRoomFailed("leave_room");const e={Authorization:this._authorization,roomId:this._roomConf.roomId,sessionId:this._roomConf.sessionId};if(await this._ready2join(),!this._ctx.signalingManager.isConnected())return Promise.reject(new SDKError(ErrorCode.NOT_CONNECTED_YET,"server not connected"));await this._ctx.signalingManager.sendSignaling("leaveRoom",e,this._roomConf.rtsOnlySignalHeader)}destroy(){this._logger.info("destroy()"),this._joinRoomFailed("leave_room"),this._authorization=void 0,this._stopJoinRoom5xxRetry(),this.removeAllListeners()}async _ready2join(){var e;return await this._ctx.signalingManager.connect(),this._sdpInfo||(this._sdpInfo=await(null==(e=this._ctx.handler)?void 0:e.getDefaultSdp())),_RoomJoin.supportedCodecs||(_RoomJoin.supportedCodecs=await internalGetSupportedCodecs()),{sdpInfo:this._sdpInfo,supportedCodecs:_RoomJoin.supportedCodecs}}async _callJoinRoom(e){var t,i,r,o,s,n,a,d,c,l,u,_;this._logger.info("_callJoinRoom","invoke"),delete this._sdpInfo;const{appId:h,role:p,businessId:m,useCloudProxy:S,joinRoomParams:g,mediaParams:v}=this._ctx,{sdpInfo:f,supportedCodecs:E}=await this._ready2join(),T={Authorization:Utils.token2auth(h,this._roomConf.roomId,this._roomConf.userId,this._roomConf.token),sessionId:this._roomConf.sessionId,timestamp:Date.now(),controlMessage:this._roomConf.getLiveControlMessage(),userAttributes:{extra_info:this._roomConf.userInfo.extraInfo,role:p},sdpInfo:f,params:{supportedCodecs:E,userAgent:window.navigator.userAgent,sdkVersion:Config2.VERSION,deviceId:sdkCache.getDeviceId(),appId:h,roomId:this._roomConf.roomId,userId:this._roomConf.userId,businessId:m,enableCloudProxy:S,channelProfile:RoomProfileMap[this._roomConf.roomProfileType]?`${RoomProfileMap[this._roomConf.roomProfileType][0]}`:"0",SDKCodecNegotiation:getParameter("SDK_CODEC_NEGOTIATION"),sdkType:"rtc",joinRoomMode:this._roomConf.isRTSOnlyRoom()?2:1,deviceType:"web",platformType:2,rtsMode:this._ctx.rtsMode,mediaProcessingType:Config2.MEDIA_PROCESSING_TYPE??0},options:{supportCheckTokenPrivilege:!0,supportTokenExpireCallBack:!0,enableSceneConfigV2:!0,enableUnBundleMode:!0,enableAudioMux:!0,enableBigRoomMode:!0,needNegotiateSDP:!0,supportMultiVendor:!0},accessParams:JSON.stringify({requireICEUfragV2:!0})};if("AREA_CODE_US_OPCO"===getParameter("AREA_CODE")&&(T.params.mediaArea=JSON.stringify([{AreaList:["GEO:US_OPCO"],Attribute:"include"}])),g)for(const[e,t]of Object.entries(g))T.params[e]=t;v&&(T.mediaParams=v);getParameter("SIGNAL_CROP_JOINROOM")&&(null==(t=T.sdpInfo)?void 0:t.sdp)&&(T.sdpInfo.sdp=cropSdpMediaSection(T.sdpInfo.sdp)),Promise.resolve().then((()=>this.emit("onSendingJoinMessageHook")));try{const t=e?"reconnected":"joinRoom",_=await this._joinRoomWithRetry(t,T);this._logger.success("join","send join message success");const{_abtest_vid:h}=_.config||{};let{engine_WEB:p}=_.config||{};this._authorization=T.Authorization,sdkCache.setEngineWebConfig(this._ctx.appId,this._roomConf.roomId,p),p=Object.assign({},getParameter("ENGINE_WEB_CONFIG"),p),this._ctx.serverConfig={videoCodec:null==p?void 0:p.video_codec,audioRed:!!(null==p?void 0:p.pub_audio_red),muteReplaceUnsub:!!(null==(i=_.config)?void 0:i.mute_replace_unsub),simulcastOnDemand:!(!1===(null==(s=null==(o=null==(r=_.config)?void 0:r.engine_VPM)?void 0:o.ondemand)?void 0:s.enable)),forceUniHandler:1===(null==(a=null==(n=_.config)?void 0:n.vendor_param)?void 0:a.vendor_stream_sub_mode),e2eFeedback:null==p?void 0:p.e2e_feedback},getParameter("SDK_CODEC_NEGOTIATION")&&(this._ctx.targetCodec=null==(d=_.config)?void 0:d.targetCodec,this._ctx.targetScreenCodec=null==(c=_.config)?void 0:c.targetScreenCodec),"boolean"==typeof(null==p?void 0:p.av_sync)&&(this._ctx.avSync=p.av_sync),this._roomConf.rtcVid=h,_.vendorConfig&&this._roomConf.setVendorConfig(_.vendorConfig),AudioStallObserver.setAudioStallConfig(p),(null==(l=_.relayMessage)?void 0:l.sdp)&&(null==(u=this._ctx.handler)||u.createAVMlineAnswerTpl(_.relayMessage.sdp)),this.emit(RoomEvent.JOIN_SUCCESS,{joinRes:_,reconnect:e}),this._joinRoomSuccess(_)}catch(e){null==(_=this._ctx.monitor)||_.report("rtc_error",{message:`[join._callJoinRoom] ${getErrorString(e)}`,error_code:-1});const t={461:ErrorCode.ROOM_FORBIDDEN,462:ErrorCode.USER_FORBIDDEN};(null==e?void 0:e.code)>=700&&(null==e?void 0:e.code)<800?this._joinRoomFailed("token_error",ErrorCode.INVALID_TOKEN):t[null==e?void 0:e.code]?this._joinRoomFailed((null==e?void 0:e.message)||t[null==e?void 0:e.code],t[null==e?void 0:e.code]):(null==e?void 0:e.code)===ErrorCode.TIME_OUT&&this._ctx.joinRoomConfig.useTcpAfterJoinTimeout?(this._logger.error("join",InternalReconnectReason.JOIN_TIMEOUT),this.safeEmit(RoomEvent.ON_REJOIN_WITH_TCP),this._ctx.signalingManager.reconnect(InternalReconnectReason.JOIN_TIMEOUT,!0)):e.code===ErrorCode.OPERATION_CANCEL&&this._ctx.signalingManager.isReconnecting()||this._joinRoomFailed((null==e?void 0:e.message)||"signaling_error")}}_joinRoomWithRetry(e,t,i){return new Promise(((r,o)=>{this._ctx.signalingManager.sendSignaling(e,t,this._roomConf.rtsOnlySignalHeader,1e4).then((e=>{this.emit("onJoinRoomAck",e),r(e)})).catch((s=>{if(i=i||new RetryLimiter,s.code>=500&&s.code<600&&getServerNow()-i.initTs<6e4){const n=i.getRetryDelay();return this._logger.warn("_joinRoomWithRetry",`joinRoom failed(code: ${s.code}), will retry after ${n}ms`),void(this._joinRoom5xxTimer=setTimeout((()=>{delete this._joinRoom5xxTimer,this._joinRoomWithRetry(e,t,i).then(r).catch(o)}),n))}o(s)}))}))}_stopJoinRoom5xxRetry(){this._joinRoom5xxTimer&&(clearTimeout(this._joinRoom5xxTimer),delete this._joinRoom5xxTimer)}_reportJoinRoomStart(){this._joinTask&&(this.emit("__joinRoomStartReport"),this._roomConf.report("join_room",{type:"begin",start:this._joinTask.startTime,result:!1,reason:""},{enable_cloud_proxy:this._ctx.useCloudProxy,expectedIDC:this._ctx.expectedIDC}))}_joinRoomSuccess(e){this._joinTask&&(this._joinTask.success(e),this.emit("__joinRoomSuccessReport"),this._roomConf.report("join_room",{type:"end",start:this._joinTask.startTime,result:!0,reason:""},{enable_cloud_proxy:this._ctx.useCloudProxy,expectedIDC:this._ctx.expectedIDC}),this._roomConf.report("rtc_join_room",{error_code:0,deviceModel:"web",deviceManufacturer:"web",elapse:getServerNow()-this._joinTask.startTime}),delete this._joinTask,delete this._roomConf.joinPromise)}_joinRoomFailed(e,t){this._joinTask&&(this._joinTask.fail(new SDKError(t||ErrorCode.JOIN_ROOM_FAILED,e)),this.emit("__joinRoomFailedReport"),this._roomConf.report("join_room",{type:"end",start:this._joinTask.startTime,result:!1,reason:e},{enable_cloud_proxy:this._ctx.useCloudProxy,expectedIDC:this._ctx.expectedIDC}),delete this._joinTask,delete this._roomConf.joinPromise)}};let RoomJoin=_RoomJoin;__publicField(RoomJoin,"supportedCodecs");var __defProp$5=Object.defineProperty,__getOwnPropDesc$5=Object.getOwnPropertyDescriptor,__decorateClass$5=(e,t,i,r)=>{for(var o,s=r>1?void 0:r?__getOwnPropDesc$5(t,i):t,n=e.length-1;n>=0;n--)(o=e[n])&&(s=(r?o(t,i,s):o(s))||s);return r&&s&&__defProp$5(t,i,s),s};class RoomMessage{constructor(e,t){__publicField(this,"_logger"),this._ctx=e,this._roomConf=t,this._logger=new Logger$1("RoomMessage",2,e.id)}sendUserMessage(e,t){return this._ctx.signalingManager.sendP2PMessage({to:e,from:this._roomConf.userId,room:this._roomConf.roomId,app:this._ctx.appId,msg:t})}async sendRoomMessage(e,t){const i={clientId:this._roomConf.userId,binary:t,message:"",roomId:this._roomConf.roomId};return i.message=t?await Utils.ab2b64str(e):e,this._ctx.signalingManager.sendSignaling("customMessage",i,this._roomConf.rtsOnlySignalHeader)}async controlMessage(e){this._logger.info("controlMessage()","params: %o",e);const t=e;"transcode"===e.type&&(t.roomId=this._roomConf.roomId),await this._ctx.signalingManager.sendSignaling("controlMessage",t)}}__decorateClass$5([checkRoomState],RoomMessage.prototype,"sendUserMessage",1),__decorateClass$5([checkRoomState],RoomMessage.prototype,"sendRoomMessage",1),__decorateClass$5([checkRoomState],RoomMessage.prototype,"controlMessage",1);var __defProp$4=Object.defineProperty,__getOwnPropDesc$4=Object.getOwnPropertyDescriptor,__decorateClass$4=(e,t,i,r)=>{for(var o,s=r>1?void 0:r?__getOwnPropDesc$4(t,i):t,n=e.length-1;n>=0;n--)(o=e[n])&&(s=(r?o(t,i,s):o(s))||s);return r&&s&&__defProp$4(t,i,s),s};const virtualStreamAttributes={audiostream:!0,extaudio:!1,extvideo:!1,localaudio:!0,localvideo:!1,videoDescriptions:[],videostream:!1,publishTime:0};class Room extends EnhancedEventEmitter{constructor(e,t){super(),__publicField(this,"_localStream"),__publicField(this,"_localScreenStream"),__publicField(this,"_remoteUsers",new Map),__publicField(this,"_remoteStreams",new Map),__publicField(this,"_remoteStreamStreamIdUserIdMap",{}),__publicField(this,"_remoteUserMediaBanned",new Map),__publicField(this,"_virtualStreams",[]),__publicField(this,"_serverConfig"),__publicField(this,"_userDuplicateLoginTimerMap",new Map),__publicField(this,"_networkQualityManager"),__publicField(this,"_videoSizeObserver"),__publicField(this,"_hasPublished",!1),__publicField(this,"_subtitleTool"),__publicField(this,"_csrcUserIdMap",{}),__publicField(this,"_publishOnDemandItem"),__publicField(this,"_onceTriggerBySignal",!1),__publicField(this,"_pubTransceiverReady",!1),__publicField(this,"_publishOnDemandBusy",!1),__publicField(this,"logger"),__publicField(this,"_forwardStreamManager"),__publicField(this,"_publisher"),__publicField(this,"_subscriber"),__publicField(this,"_roomJoin"),__publicField(this,"_roomMessage"),__publicField(this,"_clearSignalListeners"),this.config=e,this._ctx=t,this.logger=new Logger$1("Room",1,t.id),this.logger.info("constructor","invoke"),this._publisher=new RoomPublisher(t,e),this._addPublisherListeners(),this._subscriber=new RoomSubscriber(t,e),this._addSubscriberListeners(),this._roomJoin=new RoomJoin(t,e),this._addJoinRoomHandler(),this._forwardStreamManager=new ForwardStreamManager(t,e),this._addForwardStreamListeners(),this._roomMessage=new RoomMessage(t,e),this._networkQualityManager=new NetworkQualityManager(t),this._networkQualityManager.reportor=this._reportNetworkQuality.bind(this),this._videoSizeObserver=new VideoSizeObserver(this),this._videoSizeObserver.onchange=this._emitVideoSizeChange.bind(this),this._addSignalListeners()}get remoteUsers(){return this._remoteUsers}get remoteStreams(){return this._remoteStreams}get localStream(){return this._localStream}get localScreenStream(){return this._localScreenStream}get virtualStreams(){return this._virtualStreams}_addSignalListeners(){const e={[SignalEvent.ON_ADD_STREAM]:this._onAddStream.bind(this),[SignalEvent.ON_ADD_STREAM_LIST]:e=>{e&&Array.isArray(e.streamList)&&e.streamList.forEach((e=>this._onAddStream(e)))},[SignalEvent.ON_REMOVE_STREAM]:this._onRemoveStream.bind(this),[SignalEvent.ON_REMOVE_STREAM_LIST]:e=>{e&&Array.isArray(e.streamList)&&e.streamList.forEach((e=>this._onRemoveStream(e)))},[SignalEvent.USER_CONNECTION]:this._onUserConnection.bind(this),[SignalEvent.USER_CONNECTION_LIST]:e=>{e&&Array.isArray(e.userList)&&e.userList.forEach((e=>this._onUserConnection(e)))},[SignalEvent.USER_DISCONNECTION]:this._onUserDisconnection.bind(this),[SignalEvent.USER_DISCONNECTION_LIST]:e=>{e&&Array.isArray(e.userList)&&e.userList.forEach((e=>this._onUserDisconnection(e)))},[SignalEvent.ON_UPDATE_ROOM_ATTRIBUTES]:this._onUpdateRoomAttributes.bind(this),[SignalEvent.ON_UPDATE_USER_ATTRIBUTES]:this._onUpdateUserAttributes.bind(this),[SignalEvent.ON_UPDATE_STREAM_ATTRIBUTES]:this._onUpdateStreamAttributes.bind(this),[SignalEvent.ON_PUSH_TRACK]:this._onPushTrack.bind(this),[SignalEvent.ON_REMOVE_TRACK]:this._onRemoveTrack.bind(this),[SignalEvent.ON_CUSTOM_MESSAGE]:this._onCustomMessage.bind(this),[SignalEvent.USER_MESSAGE_RECEIVED]:this._onUserMessageReceived.bind(this),[SignalEvent.USER_BINARY_MESSAGE_RECEIVED]:this._onUserBinaryMessageReceived.bind(this),[SignalEvent.POST_PROCESSING_MESSAGE]:this._onPostProcessingMessage.bind(this),[SignalEvent.ON_USER_TOKEN_WILL_EXPIRE]:this._onUserTokenWillExpire.bind(this),[SignalEvent.ON_TOKEN_PUBLISH_PRIVILEGE_WILL_EXPIRE]:this._onUserTokePublishPrivilegeWillExpire.bind(this),[SignalEvent.ON_TOKEN_PUBLISH_PRIVILEGE_DID_EXPIRED]:this._onUserTokenPublishPrivilegeDidExpire.bind(this),[SignalEvent.ON_TOKEN_SUBSCRIBE_PRIVILEGE_WILL_EXPIRE]:this._onUserTokeSubscribePrivilegeWillExpire.bind(this),[SignalEvent.ON_TOKEN_SUBSCRIBE_PRIVILEGE_DID_EXPIRED]:this._onUserTokenSubscribePrivilegeDidExpire.bind(this),[SignalEvent.STREAM_CONTROL_MESSAGE]:this._onStreamControlMessage.bind(this),[SignalEvent.ENGINE_CONTROL_MESSAGE]:this._onEngineControlMessage.bind(this),[SignalEvent.ON_STREAM_FAILED]:this._onStreamFailed.bind(this),[MediaServerSignalEvent.RTT]:this._onRTT.bind(this),[MediaServerSignalEvent.SSC]:this._onSSC.bind(this),[StateEvent.ON_CONNECTION_STATE_CHANGE]:this._onConnectionStateChange.bind(this),[SignalEvent.ON_SPEAKER_CHANGE]:this._onMeetingSpeakerChange.bind(this),[SignalEvent.ON_FORWARD_DST_ROOM_USER_KICK]:this._forwardStreamManager.onForwardDstRoomUserKick.bind(this._forwardStreamManager),[MediaServerSignalEvent.RSCP]:this._onRSCP.bind(this)};Object.keys(e).forEach((t=>{this._ctx.signalingManager.on(t,e[t])})),this._clearSignalListeners=()=>{Object.keys(e).forEach((t=>{this._ctx.signalingManager.off(t,e[t])}))}}_addPublisherListeners(){this._publisher.on(RoomEvent.PUB_RETRY,(e=>{this.emit(RoomEvent.PUB_RETRY,e)})),this._publisher.on(MediaServerSignalEvent.RSCP,this._onRSCP.bind(this)),this._publisher.on(StateEvent.ON_VENDOR_CONNECTION_STATE_CHANGE,(e=>this.emit(StateEvent.ON_VENDOR_CONNECTION_STATE_CHANGE,e)))}_addSubscriberListeners(){this._subscriber.on(StateEvent.ON_VENDOR_CONNECTION_STATE_CHANGE,(e=>this.emit(StateEvent.ON_VENDOR_CONNECTION_STATE_CHANGE,e))),this._subscriber.on("onRemoteStreamStats",(e=>{this._networkQualityManager.updateDownlinkStats(e,this._findRemoteStreamByScreen(e.userId,e.isScreen)),getParameter("HIDDEN_STATS")||(e=getPublicStats(e)),this.emit(RoomEvent.ON_REMOTE_STREAM_STATS,e)})),this._subscriber.on(RoomEvent.RESUBSCRIBE,(e=>{this.emit(RoomEvent.RESUBSCRIBE,e)})),this._subscriber.on(RoomEvent.SUB_RETRY,(e=>{this.emit(RoomEvent.SUB_RETRY,e)}))}_addJoinRoomHandler(){this._roomJoin.on(RoomEvent.JOIN_SUCCESS,this._onJoinSucc.bind(this)),this._roomJoin.on(RoomEvent.ON_REJOIN_WITH_TCP,(()=>{this.emit(RoomEvent.ON_REJOIN_WITH_TCP)}))}_addForwardStreamListeners(){this._forwardStreamManager.on(RoomEvent.ON_FORWARD_STREAM_ERROR,(e=>{this.safeEmit(RoomEvent.ON_FORWARD_STREAM_ERROR,e)}))}_onLocalStreamStats(e){const t=e.isScreen?this._localScreenStream:this.localStream;this._networkQualityManager.updateUplinkStats(e,t),getParameter("HIDDEN_STATS")||(e=getPublicStats(e)),this.emit(RoomEvent.ON_LOCAL_STREAM_STATS,e)}async join(){var e,t;this.logger.info("join()"),this.config.startJoinTimestamp=getServerNow();try{const t=await this._roomJoin.join();return this._ctx.callId=t.callId,(null==(e=t.roomAttributes)?void 0:e.multiChatMode)&&this._handleFFAudioTrack(),this._initSubtitleTool(),{users:t.clients,streams:t.streams}}catch(e){if(null==(t=this._ctx.monitor)||t.report("rtc_error",{message:`[room.join] ${getErrorString(e)}`,error_code:-1}),e.code!==ErrorCode.OPERATION_CANCEL)throw e}}async hasScreenPublished(){return!!this._localScreenStream&&this._publisher.hasPublished(this._localScreenStream)}async hasPublished(){return!!this._localStream&&this._publisher.hasPublished(this._localStream)}async publishScreen(e,t,i,r){var o,s,n,a,d;this.logger.info("publishScreen()"),this._localScreenStream||(this._localScreenStream=new LocalStream(this._ctx,StreamIndex$1.STREAM_INDEX_SCREEN),this.config.vendorConfig.enableMultiVendor&&(this._localScreenStream.pcSessionId=genUuid$1()),this._localScreenStream.isScreen=!0,this._localScreenStream.observer=new SendFrameObserver(this._ctx,this._localScreenStream));let c=!1,l=!1,u=!1,_=!1;!this._localScreenStream.videoTrack&&e?(e.sourceType===SourceType.EXTERNAL&&(l=!0),c=!0):this._localScreenStream.videoTrack&&!e&&(c=!1),!this._localScreenStream.audioTrack&&t?(t.sourceType===SourceType.EXTERNAL&&(_=!0),u=!0):this._localScreenStream.audioTrack&&!t&&(u=!1),this._localScreenStream.videoTrack=e,this._localScreenStream.audioTrack=t,i&&(audioInMediaType(i)&&(this._localScreenStream.pubAudio=r===PubState.PUB),videoInMediaType(i)&&(this._localScreenStream.pubVideo=r===PubState.PUB),this.logger.info("publishScreen mediaType","pubAudio: %o, pubVideo: %o",this._localScreenStream.pubAudio,this._localScreenStream.pubVideo));const h=await this._publisher.hasPublished(this._localScreenStream);if(!this._localScreenStream.pubAudio&&!this._localScreenStream.pubVideo)return h?this.unpublishScreen():void 0;h?(l?null==(s=this._localScreenStream.observer)||s.setPushVideo(c):null==(n=this._localScreenStream.observer)||n.setEnableVideo(c),_?null==(a=this._localScreenStream.observer)||a.setPushAudio(u):null==(d=this._localScreenStream.observer)||d.setEnableAudio(u),await this.updatePubScreenTrack()):(null==(o=this._localScreenStream.observer)||o.setPublish(!0),await this._publisher.publish(this._localScreenStream)),this._localScreenStream.pubAudio||this._localScreenStream.pubVideo?this._ctx.handler&&this._localScreenStream.startReport(this._onLocalStreamStats.bind(this),this._localScreenStream.vendorHandler||this._ctx.handler):this._localScreenStream.stopReport("unpublish screen")}async updatePubScreenTrack(){this.logger.info("updatePubScreenTrack","Invoke updatePubScreenTrack"),this._localScreenStream&&await this._publisher.updatePubTrack(this._localScreenStream)}async unpublishScreen(){var e;this.logger.info("unpublish","Invoke unpublishScreen"),this._localScreenStream&&(null==(e=this._localScreenStream.observer)||e.setPublish(!1),await this._publisher.unpublish(this._localScreenStream),this._localScreenStream.stopReport("unpublish screen"),await this._publisher.cleanStream(this._localScreenStream),this._localScreenStream=void 0)}async liveControlMessage(e){var t;this.logger.info("controlMessage","Invoke controlMessage"),null==(t=e.transcodeMeta)||t.layout.regions.forEach((e=>{e.roomID=this.config.roomId})),this.config.setLiveControlMessage("stopped"===e.action?void 0:e);try{await this._roomMessage.controlMessage(e)}catch(t){if("stopped"!==e.action)throw t}}async publicStreamControlMessage(e){"stopped"===e.action&&delete e.publicStreamMeta,await this._roomMessage.controlMessage(e)}getLocalStreamStats(){var e;return null==(e=this.localStream)?void 0:e.getLocalStreamStats()}async updateUserAttributes(){this.logger.info("updateUserAttributes","Invoke updateUserAttributes"),await this._subscriber.updateUserAttributes({role:this._ctx.role})}async publish(e,t,i,r,o=!1){var s,n,a,d,c,l,u,_,h;this.logger.info("publish","Invoke publish");let p=!1;this._localStream||(this._localStream=new LocalStream(this._ctx),this.config.vendorConfig.enableMultiVendor&&(this._localStream.pcSessionId=genUuid$1()),this._localStream.observer=new SendFrameObserver(this._ctx,this._localStream),p=!0,this._localStream.vendorCode=this.config.vendorConfig.vendorCode||0),this._localStream.videoTrack=e,this._localStream.audioTrack=t;const{pubAudio:m,pubVideo:S}=this._localStream;i&&(audioInMediaType(i)&&(this._localStream.pubAudio=r===PubState.PUB),videoInMediaType(i)&&(this._localStream.pubVideo=r===PubState.PUB),this.logger.info("publish mediaType","pubAudio: %o, pubVideo: %o",this._localStream.pubAudio,this._localStream.pubVideo));if(await this._publisher.hasPublished(this._localStream))try{this.emit("___onMediaServerClientPublish"),await this.updatePubTrack()}catch(e){throw this._localStream.pubAudio=m,this._localStream.pubVideo=S,e}else{if(!this._localStream.pubAudio&&!this._localStream.pubVideo)return;try{if(o)null==(s=this._localStream.observer)||s.setLogin(!0);else if(p){const e=!!this._localStream.videoTrack,t=!!this._localStream.audioTrack,i=(null==(n=this._localStream.videoTrack)?void 0:n.sourceType)===SourceType.EXTERNAL,r=(null==(a=this._localStream.audioTrack)?void 0:a.sourceType)===SourceType.EXTERNAL;this.config.isAutoPublish&&!this._hasPublished?(e&&(i?null==(d=this._localStream.observer)||d.setPushVideo(!0):null==(c=this._localStream.observer)||c.setEnableVideo(!0)),t&&(r?null==(l=this._localStream.observer)||l.setPushAudio(!0):null==(u=this._localStream.observer)||u.setEnableAudio(!0))):null==(_=this._localStream.observer)||_.setPublish(!0)}this.emit("___onMediaServerClientPublish"),await this._publisher.publish(this._localStream),this._hasPublished=!0,this.emit(RoomEvent.ON_PUBLISH_RESULT,{isScreen:!1,state:PublishState.PUBLISH_SUCC})}catch(e){throw null==(h=this._ctx.monitor)||h.report("rtc_error",{message:`[room.publish] ${getErrorString(e)}`,error_code:-1}),this.emit(RoomEvent.ON_PUBLISH_RESULT,{isScreen:!1,state:PublishState.PUBLISH_FAIL,errorCode:e.code}),delete this._localStream,e}}this._localStream.pubAudio||this._localStream.pubVideo?this._ctx.handler&&this._localStream.startReport(this._onLocalStreamStats.bind(this),this._localStream.vendorHandler||this._ctx.handler):this._localStream.stopReport("unpublish")}async updatePubTrack(){var e;if(this.logger.info("updatePubTrack","Invoke updatePubTrack"),this._localStream)try{await this._publisher.updatePubTrack(this._localStream)}catch(t){throw null==(e=this._ctx.monitor)||e.report("rtc_error",{message:`[room.updatePubTrack] ${getErrorString(t)}`,error_code:-1}),t}}async unpublish(){var e;if(this.logger.info("unpublish","Invoke unpublish"),this._localStream)try{await this._publisher.unpublish(this._localStream),this._localStream.stopReport("unpublish"),await this._publisher.cleanStream(this._localStream),this._localStream=void 0}catch(t){throw null==(e=this._ctx.monitor)||e.report("rtc_error",{message:`[room.unpublish] ${getErrorString(t)}`,error_code:-1}),t}}async subscribe(e,t){var i;this.logger.info("subscribe","remoteStream %o",e);if(await this._subscriber.hasSubscribed(e)){const i=e.subMediaType|t;return i!==e.subMediaType?await this._subscriber.updateSubMediaType(e,i):void 0}const r=this._ctx.videoProfile.getSubLayer(e,this.config.remoteVideoConfig);try{await this._subscriber.subscribe(e,t,r)}catch(e){throw null==(i=this._ctx.monitor)||i.report("rtc_error",{message:`[room.subscribe] ${getErrorString(e)}`,error_code:-1}),e}}async updateSubVideoConfig(e){var t,i;const r=this._findRemoteStreamByScreen(e,!1);if(this.logger.info("updateSubVideoConfig","userId %s",e),!r)return;if(!await this._subscriber.hasSubscribed(r)||(null==(i=null==(t=r.attributes)?void 0:t.videoDescriptions)?void 0:i.length)<=1)return;const o=this._ctx.videoProfile.getSubLayer(r);return o?(r.originalStreamIndex=o.spatialLayer,this._subscriber.updateSubTrackLayer(r,o)):void 0}async unsubscribe(e,t){var i,r;this.logger.info("unsubscribe","Invoke unsubscribe");try{if(!await this._subscriber.hasSubscribed(e))return;const r=e.subMediaType-(e.subMediaType&t);if(!(null==(i=this._ctx.serverConfig)?void 0:i.muteReplaceUnsub)&&(r===ExtendMediaType.NONE||this.config.isMultiChatMode()&&r===MediaType$1.AUDIO))return await this._subscriber.unsubscribe(e);await this._subscriber.updateSubMediaType(e,r)}catch(e){throw null==(r=this._ctx.monitor)||r.report("rtc_error",{message:`[room.unsubscribe] ${getErrorString(e)}`,error_code:-1}),e}}async startSubtitle(e){if(!this._subtitleTool)throw new SDKError(ErrorCode.INVOKED_BEFORE_JOIN_ROOM,"join first");await this._subtitleTool.start(e)}async updateSubtitleConfig(e){if(!this._subtitleTool)throw new SDKError(ErrorCode.INVOKED_BEFORE_JOIN_ROOM,"join first");await this._subtitleTool.update(e)}async stopSubtitle(){var e;null==(e=this._subtitleTool)||e.stop()}async startForwardStream2Rooms(e){return this._forwardStreamManager.startForwardStream2Rooms(e)}async updateForwardStream2Rooms(e){return this._forwardStreamManager.updateForwardStream2Rooms(e)}async stopForwardStream2Rooms(){return this._forwardStreamManager.stopForwardStream2Rooms()}async pauseForwardStream2AllRooms(){return this._forwardStreamManager.pauseForwardStream2AllRooms()}async resumeForwardStream2AllRooms(){return this._forwardStreamManager.resumeForwardStream2AllRooms()}async updateMediaParams(e){return this._ctx.signalingManager.sendSignaling("updateMediaParams",{roomId:this.config.roomId,mediaParams:e})}async leave(e=!1){var t,i,r;this.logger.info("leave","Invoke leave"),null==(t=this._subtitleTool)||t.destroy(),delete this._subtitleTool;try{for(const e of this._remoteStreams.values())Array.isArray(e)&&e.forEach((e=>{var t;null==(t=e.observer)||t.setLogin(!1)}));this._localStream&&(null==(i=this._localStream.observer)||i.setLogin(!1)),await this._roomJoin.leave().catch((()=>{})),this.destroy(),this.config.report("rtc_leave_room",{error_code:0,message:"",elapse:this.config.getStayRoomDuration()})}catch(t){if(null==(r=this._ctx.monitor)||r.report("rtc_error",{message:`[room.leave] ${getErrorString(t)}`,error_code:-1}),t instanceof Error&&this.config.report("rtc_leave_room",{error_code:-1,message:t.message,elapse:this.config.getStayRoomDuration()}),e)throw t;this.destroy()}}updateRemoteUserPriority(e){var t;null==(t=this.remoteStreams.get(e))||t.forEach((t=>{const{userPriority:i}=this._ctx;t.hasSubscribed&&i.has(e)&&this._subscriber.updateSubPriority(t,i.get(e))}))}destroy(){var e,t;this.logger.info("destroy","Invoke destroy"),reportRtcInvokeStatus(this._ctx.id,"room_destroy",`${(new Error).stack}`),null==(e=this._subtitleTool)||e.destroy(),delete this._subtitleTool;const i=Array.from(this._remoteStreams.values()).flat();this._subscriber.destroy(i),this._subscriber.destroy(this._virtualStreams),this._publisher.destroy([this.localStream,this.localScreenStream]),this._roomJoin.destroy(),null==(t=this._clearSignalListeners)||t.call(this),this._remoteUsers=new Map,this._remoteStreams=new Map,this._localStream&&(this._localStream=void 0),this._localScreenStream&&(this._localScreenStream=void 0),this._userDuplicateLoginTimerMap.forEach((e=>{clearTimeout(e)})),this._userDuplicateLoginTimerMap.clear(),this._networkQualityManager.destroy(),this._videoSizeObserver.destroy(),this._csrcUserIdMap={},this._virtualStreams=[],this._remoteStreamStreamIdUserIdMap={},this._forwardStreamManager.destoy(),this._remoteUserMediaBanned.clear()}async updateToken(e){if(this.logger.info("updateToken","Invoke updateToken"),this.config.token=e,!this.config.isRTSOnlyRoom())try{await this._roomJoin.updateToken(e)}catch(e){throw this.safeEmit(RoomEvent.ON_ROOM_ERROR,{errorCode:ErrorCode.UPDATE_TOKEN_WITH_INVALID_TOKEN}),e}}sendUserMessage(e,t){return this._ctx.rtsLimiter.e2e.check(t),this._roomMessage.sendUserMessage(e,t)}sendRoomMessage(e,t=!1){return this._ctx.rtsLimiter.boradcast.check(e),this._roomMessage.sendRoomMessage(e,t)}async maybeFillBackFrame2Stream(e){var t;e.refreshBlackFrameLifetime(),(null==(t=e.videoTransceiver)?void 0:t.sender.track)||this._publisher.updatePubBlackFrame(e)}_onJoinSucc({joinRes:e,reconnect:t}){var i,r;this.logger.info("_onJoinSucc()","invoke. "+(t?"[reconnect]":"")),this.emit(RoomEvent.JOIN_SUCCESS,t),this._serverConfig=e.config,this.config.updateRoomAttributes(e.roomAttributes);const o=[],s=[],n=[],a=[],d=[];this.config.isRTSOnlyRoom()&&Array.isArray(e.userInfos)&&(e.clientsDetail=e.userInfos.map((e=>({clientId:e.userId,clientJoinTime:e.userJoinTime})))),null==(i=e.clientsDetail)||i.forEach((t=>{if(this._checkClientBanned(t),t.clientId===e.clientId)return;const i=this._remoteUsers.get(t.clientId);i?i._stillExist=!0:o.push(t)}));for(const e of this._remoteUsers.values())e._stillExist||s.push({clientId:e.userId}),delete e._stillExist;null==(r=e.streams)||r.forEach((e=>{const t=this._findRemoteStreamByScreen(e.clientId,e.screen);this.config.updateUserPubInfo(e),t?(t.stillExist=!0,t.streamId=e.streamId,d.push(e)):a.push(e)}));for(const e of this._remoteStreams.values())Array.isArray(e)&&e.forEach((e=>{e.stillExist?delete e.stillExist:n.push({clientId:e.userId,streamId:e.streamId,message:RemoveStreamMessage.clientDisconnected})}));s.forEach((e=>this._onUserDisconnection(e))),o.forEach((e=>this._onUserConnection(e))),n.forEach((e=>this._onRemoveStream(e))),a.forEach((e=>this._onAddStream(e,{fromSignal:!1}))),d.forEach((e=>this._onUpdateStreamAttributes(e))),this.config.resetUserPubInfo(),t&&this._handleSendOrRecvStreamAfterReconnect(),this.emit("__joinSuccess")}_handleSendOrRecvStreamAfterReconnect(){var e;this._localStream&&(this._publisher.cleanStream(this._localStream).then((()=>{var e;this._localStream&&(this._localStream.vendorCode=this.config.vendorConfig.vendorCode||0,null==(e=this._localStream.observer)||e.setLogin(!0))})),this._publisher.publish(this._localStream).then((()=>{var e;this._ctx.handler&&(null==(e=this._localStream)||e.startReport(this._onLocalStreamStats.bind(this),this._localStream.vendorHandler||this._ctx.handler)),this.emit(RoomEvent.ON_PUBLISH_RESULT,{isScreen:!1,state:PublishState.PUBLISH_SUCC,retry:!0})})).catch((e=>{this.logger.error(`failed repub error:${e}`),this.emit(RoomEvent.ON_PUBLISH_RESULT,{isScreen:!1,state:PublishState.PUBLISH_FAIL,errorCode:e.code,retry:!0})}))),this._localScreenStream&&(this._publisher.cleanStream(this._localScreenStream).then((()=>{var e;this._localScreenStream&&(null==(e=this._localScreenStream.observer)||e.setLogin(!0))})),this._publisher.publish(this._localScreenStream).then((()=>{var e;this._ctx.handler&&(null==(e=this._localScreenStream)||e.startReport(this._onLocalStreamStats.bind(this),this._localScreenStream.vendorHandler||this._ctx.handler)),this.emit(RoomEvent.ON_PUBLISH_RESULT,{isScreen:!0,state:PublishState.PUBLISH_SUCC,retry:!0})})).catch((e=>{this.logger.error(`failed repub screen stream error:${e}`),this.emit(RoomEvent.ON_PUBLISH_RESULT,{isScreen:!0,state:PublishState.PUBLISH_FAIL,errorCode:e.code,retry:!0})})));for(const e of this._remoteStreams.values())Array.isArray(e)&&e.forEach((async e=>{var t,i;if(e.hasSubscribed){e.resetHasSubscribed();try{this.logger.info(`start resubscribe ${e.userId} with ${e.subMediaType}`),videoInMediaType(e.subMediaType)&&(null==(t=e.observer)||t.setSubscribeVideo(!0)),audioInMediaType(e.subMediaType)&&(null==(i=e.observer)||i.setSubscribeAudio(!0)),await this._subscriber.subscribe(e,e.subMediaType),this.logger.info(`success resubscribe ${e.userId} with ${e.subMediaType}`),this.safeEmit(RoomEvent.RESUBSCRIBE,{stream:e}),this.emit(RoomEvent.ON_SUBSCRIBE_RESULT,{state:SubscribeState.SUBSCRIBE_SUCC,userId:e.userId,isScreen:e.isScreen,retry:!0})}catch(t){if(this.emit(RoomEvent.ON_SUBSCRIBE_RESULT,{state:SubscribeState.SUBSCRIBE_FAIL,userId:e.userId,isScreen:e.isScreen,errorCode:t.code,retry:!0}),this.logger.error(`failed resubscribe ${e.userId} with ${e.subMediaType}, error:${t}`),t.code===ErrorCode.NOT_CONNECTED_YET)return void(e.streamState=StreamState.SUB_ED);await this._subscriber.cleanStream(e),e.resetHasSubscribed()}}}));null==(e=this._subtitleTool)||e.reconnect(),this._forwardStreamManager.resumeFromReconnect()}_handleFFAudioTrack(){var e,t;const i=null==(e=this._ctx.handler)?void 0:e.audioTrack4ff,r=null==(t=this._ctx.handler)?void 0:t.getTransceivers();if(i&&Array.isArray(r)){const e=r.find((e=>{var t;return(null==(t=null==e?void 0:e.receiver)?void 0:t.track)===i}));if(e){const t=new RemoteStream(this._ctx,"ff-stream","ff-stream",!1,!1,virtualStreamAttributes);t.virtual=!0,t.audioTransceiver=e,t.audioMid="0",t.audioTrack=createRemoteAudioTrack(this._ctx,i,{streamIndex:ExtendStreamIndex.VIRTUAL}),this._virtualStreams.push(t),this.safeEmit(RoomEvent.SUBSCRIBE_PUSH_TRACK,{stream:t})}}}_findRemoteStream(e,t){const i=this._remoteStreams.get(e);return Array.isArray(i)?i.find((e=>e.streamId===t)):null}_findRemoteStreamByScreen(e,t){const i=this._remoteStreams.get(e);return Array.isArray(i)?i.find((e=>e.isScreen===t)):null}_onAddStream(e,{needEmit:t=!0,fromSignal:i=!0,virtual:r=!1}={}){var o;if(e.clientId===this.config.userId)return;const{isAutoSubscribeAudio:s,isAutoSubscribeVideo:n}=this.config,a=this._findRemoteStreamByScreen(e.clientId,e.screen);if(a&&a.streamId!==e.streamId){const t=null==(o=this._remoteStreams.get(e.clientId))?void 0:o.filter((e=>e.streamId!==a.streamId));this._subscriber.cleanStream(a),this._remoteStreams.set(e.clientId,t||[])}let d=this._findRemoteStream(e.clientId,e.streamId);if(this._remoteStreamStreamIdUserIdMap[e.streamId]=e.clientId,d)d.attributes=e.attributes;else if(d=new RemoteStream(this._ctx,e.clientId,e.streamId,e.screen,!1,e.attributes),d.virtual=r,this._initStreamListeners(d),!r){const t=this._remoteStreams.get(e.clientId);t?t.push(d):this._remoteStreams.set(e.clientId,[d])}if(d.remoteSessionId=e.remoteSessionId||"",d.observer=new RecvFrameObserver(this._ctx,d),!d.isScreen&&n&&!this._getRemoteUserMediaBanned(e.clientId,MediaType$1.VIDEO)&&(i&&d.hasVideo&&(d.attributes.extvideo?(d.observer.setExternalVideoSource(!0),d.observer.setPushVideo(!0)):(d.observer.setExternalVideoSource(!1),d.observer.setPublishVideo(!0))),i&&d.hasAudio&&s&&!this.config.isMultiChatMode()&&!this._getRemoteUserMediaBanned(e.clientId,MediaType$1.AUDIO)&&(d.attributes.extaudio?(d.observer.setExternalAudioSource(!0),d.observer.setPushAudio(!0)):(d.observer.setExternalAudioSource(!1),d.observer.setPublishAudio(!0))),t&&!i)){const{isAutoSubscribeAudio:e,isAutoSubscribeVideo:t}=this.config;d.observer.setLogin(!0,{audio:!!e&&!this.config.isMultiChatMode(),video:!!t})}return t&&this.safeEmit(SignalEvent.ON_ADD_STREAM,{stream:d}),d}_onUserConnection(e){var t;if(e.clientId===this.config.userId)return;const i=this._userDuplicateLoginTimerMap.get(e.clientId);if("number"==typeof i)return this._userDuplicateLoginTimerMap.delete(e.clientId),void self.clearTimeout(i);const r={userId:e.clientId,extraInfo:null==(t=e.attributes)?void 0:t.extra_info};this._remoteUsers.set(e.clientId,{...r}),this.safeEmit(SignalEvent.USER_CONNECTION,{userInfo:r,publishState:this.config.getUserPubInfo(r.userId)}),this._checkClientBanned(e)}_onUserDisconnection({clientId:e,tag:t,code:i,forbiddenTime:r}){if(e)if(e===this.config.userInfo.userId){let e=null;t===UserDisconnectionTag.kickedByAdmin?e=ErrorCode.KICKED_OUT:t===UserDisconnectionTag.onUserTokenDidExpire?e=ErrorCode.TOKEN_EXPIRED:t===UserDisconnectionTag.userDuplicateLogin&&(e=ErrorCode.DUPLICATE_LOGIN),i===UserDisconnectionCode.roomDismissByAdmin&&(e=ErrorCode.ROOM_DISMISS),e&&this.safeEmit(RoomEvent.ON_ROOM_ERROR,{errorCode:e,forbiddenTime:r})}else{let i=UserOfflineReason.DROPPED;t===UserDisconnectionTag.userLeave?i=UserOfflineReason.QUIT:t===UserDisconnectionTag.kickedByAdmin?i=UserOfflineReason.KICKED_BY_ADMIN:t===UserDisconnectionTag.roleChanged&&(i=UserOfflineReason.SWITCH_TO_INVISIBLE);const r=()=>{var r;this._remoteUsers.delete(e);const o=[];null==(r=this._remoteStreams.get(e))||r.forEach((e=>{o.push(this._onRemoveStream({clientId:e.userId,streamId:e.streamId,message:RemoveStreamMessage.clientDisconnected}))})),this._remoteStreams.delete(e),Promise.all(o).finally((()=>{this.safeEmit(RoomEvent.ON_USER_LEAVE,{userInfo:{userId:e},reason:i,tag:t})}))};if(t===UserDisconnectionTag.userDuplicateLogin){const t=this._userDuplicateLoginTimerMap.get(e);t&&self.clearTimeout(t);const i=self.setTimeout(r,5e3);this._userDuplicateLoginTimerMap.set(e,i)}else r()}}async _onRemoveStream(e){var t,i;if(e.clientId===this.config.userId)return;const r=this._remoteStreams.get(e.clientId);if(!r)return;const o=r.find((t=>t.streamId===e.streamId));if(!o)return;o.hasVideo&&(null==(t=o.observer)||t.setPublishVideo(!1)),o.hasAudio&&!this.config.isMultiChatMode()&&(null==(i=o.observer)||i.setPublishAudio(!1));const s=r.filter((t=>t.streamId!==e.streamId));this._remoteStreams.set(e.clientId,s);const n={isScreen:o.isScreen,userId:o.userId,streamId:o.streamId,attributes:{audiostream:o.attributes.audiostream,videostream:o.attributes.videostream}};try{await this._subscriber.handleRemoveStream(o)}catch(e){console.error(e)}this.safeEmit(SignalEvent.ON_REMOVE_STREAM,{stream:n,reason:e.message})}_onUpdateUserAttributes(e){this._checkClientBanned(e)}_onUpdateRoomAttributes(e){var t;e.roomAttributes&&(this.config.updateRoomAttributes(e.roomAttributes),this._ctx&&(this._ctx.callId=e.roomAttributes.callId)),(null==(t=e.roomAttributes)?void 0:t.multiChatMode)&&this._handleFFAudioTrack()}_onUpdateStreamAttributes(e){var t,i,r,o,s,n,a,d,c,l,u,_,h,p,m,S,g,v;const{isAutoSubscribeAudio:f,isAutoSubscribeVideo:E}=this.config,{clientId:T,streamId:R,attributes:b}=e,y=this._findRemoteStream(T,R);if(!y)return;const I=y.attributes,C={...I,...b};let A=!1;const k=C.localaudio!==I.localaudio;let M=!1,N=!1;const O=C.localvideo!==I.localvideo;let P=!1,D=ExtendMediaType.NONE,w=ExtendMediaType.NONE;C.audiostream!==I.audiostream&&(A=C.localaudio,M=!!C.audiostream,C.audiostream?D|=MediaType$1.AUDIO:w|=MediaType$1.AUDIO),C.videostream!==I.videostream&&(N=C.localvideo,P=!!C.videostream,C.videostream?D|=MediaType$1.VIDEO:w|=MediaType$1.VIDEO),D&&this.safeEmit(RoomEvent.ON_USER_PUBLISH_STATE_CHANGE,{userId:T,mediaType:D,isScreen:y.isScreen,pubState:PubState.PUB,remoteStream:y}),w&&this.safeEmit(RoomEvent.ON_USER_PUBLISH_STATE_CHANGE,{userId:T,mediaType:w,isScreen:y.isScreen,pubState:PubState.UNPUB,remoteStream:y}),y.remoteSessionId=e.remoteSessionId||"",y.attributes=C,C.localaudio!==I.localaudio&&(C.localaudio?((f||y.subAudio)&&C.audiostream&&(C.extaudio?(null==(t=y.observer)||t.setExternalAudioSource(!0),null==(i=y.observer)||i.setPushAudio(!0)):(null==(r=y.observer)||r.setExternalAudioSource(!1),null==(o=y.observer)||o.setEnableAudio(!0))),this.safeEmit(RoomEvent.ON_USER_START_AUDIO_CAPTURE,{userId:T},y)):(C.extaudio?(null==(s=y.observer)||s.setExternalAudioSource(!0),null==(n=y.observer)||n.setPushAudio(!1)):(null==(a=y.observer)||a.setExternalAudioSource(!1),null==(d=y.observer)||d.setEnableAudio(!1)),!y.isScreen&&this.safeEmit(RoomEvent.ON_USER_STOP_AUDIO_CAPTURE,{userId:T}))),C.localvideo!==I.localvideo&&(C.localvideo?((E||y.subVideo)&&C.videostream&&(C.extvideo?(null==(c=y.observer)||c.setExternalVideoSource(!0),null==(l=y.observer)||l.setPushVideo(!0)):(null==(u=y.observer)||u.setExternalVideoSource(!1),null==(_=y.observer)||_.setEnableVideo(!0))),this.safeEmit(RoomEvent.ON_USER_START_VIDEO_CAPTURE,{userId:T})):(C.extvideo?(null==(h=y.observer)||h.setExternalVideoSource(!0),null==(p=y.observer)||p.setPushVideo(!1)):(null==(m=y.observer)||m.setExternalVideoSource(!1),null==(S=y.observer)||S.setEnableVideo(!1)),!y.isScreen&&this.safeEmit(RoomEvent.ON_USER_STOP_VIDEO_CAPTURE,{userId:T}))),A&&!k&&f&&(null==(g=y.observer)||g.setRemoteUnmuteAudio(M)),N&&!O&&E&&(null==(v=y.observer)||v.setRemoteUnmuteVideo(P)),"number"==typeof C.videoType&&C.videoType!==I.videoType&&this.safeEmit(RoomEvent.VIDEO_TYPE_CHANGE,{userId:y.userId,isScreen:y.isScreen,type:C.videoType===VideoType.BLACK?SEIStreamEventType.BLACK:SEIStreamEventType.NORMAL})}_onPushTrack(e){var t;if(!(null==(t=e.streamId)?void 0:t.startsWith("audio_mux")))return void this.config.report("rtc_error",{message:`onPushTrack, userId: ${e.clientId}, ${e.streamId}`,error_code:RtcErrorCode.TRACK_ERROR});const i=this._onAddStream({...e,attributes:virtualStreamAttributes},{needEmit:!1,fromSignal:!1,virtual:!0});i&&this._subscriber.subscribe4pushTrack(i,e).then((()=>{this.safeEmit(RoomEvent.SUBSCRIBE_PUSH_TRACK,{stream:i}),this._virtualStreams.push(i)})).catch((e=>{this.logger.error("subscribe","push track failed %o",e)}))}_onRemoveTrack({clientId:e,streamId:t,message:i,trackType:r}){this.logger.info("_onRemoveTrack","remove track: %o",e);const o=this._findRemoteStream(e,t);o&&(o.removeTrack=!0,this._subscriber.unsubscribe4removeTrack(o,i,r),this.emit(RoomEvent.REMOVE_PUSH_TRACK,{stream:o,mediaType:r+1}))}_onMeetingSpeakerChange(e){if(Array.isArray(null==e?void 0:e.speakerCsrcInfo)){const t={};null==e||e.speakerCsrcInfo.forEach((({csrc:e,userId:i,isScreen:r})=>{r||(t[e]=i)})),this._csrcUserIdMap=t}Array.isArray(e.muxStreamInUse)&&this._virtualStreams.forEach((t=>{var i;(null==(i=e.muxStreamInUse)?void 0:i.includes(t.streamId))?t.virtualOccupy=!0:t.virtualOccupy=!1}))}getActiveSpeakerInMultiChatMode(){const e=[];return this._virtualStreams.forEach((t=>{var i;const r=null==(i=t.audioTransceiver)?void 0:i.receiver;if(r){const[t]=r.getContributingSources()||[];if(t){const{audioLevel:i,source:r}=t;this._csrcUserIdMap[r]&&e.push({userId:this._csrcUserIdMap[r],audioLevel:i})}}})),e.length&&e.sort(((e,t)=>e.audioLevel-t.audioLevel)),e}_onReconnecting(){var e,t,i,r;for(const e of this._remoteStreams.values())Array.isArray(e)&&e.forEach((e=>{var t;null==(t=e.observer)||t.setDisconnect(),this._subscriber.cleanStream(e)}));this._virtualStreams.forEach((e=>{var t;this.emit(RoomEvent.REMOVE_PUSH_TRACK,{stream:e,mediaType:MediaType$1.AUDIO}),null==(t=e.observer)||t.setDisconnect(),this._subscriber.cleanStream(e)})),this._virtualStreams=[],null==(t=null==(e=this.localStream)?void 0:e.observer)||t.setDisconnect(),this._publisher.cleanStream(this.localStream),null==(r=null==(i=this.localScreenStream)?void 0:i.observer)||r.setDisconnect(),this._publisher.cleanStream(this.localScreenStream)}_onConnectionStateChange(e){e.state===ConnectionState.CONNECTION_STATE_RECONNECTING?this._onReconnecting():e.state===ConnectionState.CONNECTION_STATE_RECONNECTED&&this._roomJoin.join(!0)}_initStreamListeners(e){e.on("ontrack",(e=>{e.track})),e.on("onSEIMessage",(t=>{this.emit(RoomEvent.ON_SEI_MESSAGED_RECEIVED,{sei:t,remoteStreamKey:{userId:e.userId,roomId:this.config.roomId,streamIndex:e.isScreen?StreamIndex$1.STREAM_INDEX_SCREEN:StreamIndex$1.STREAM_INDEX_MAIN}})}))}_onCustomMessage(e){var t;(null==(t=this._subtitleTool)?void 0:t.onMessageRecv(e))||this.safeEmit(SignalEvent.ON_CUSTOM_MESSAGE,e)}_onUserMessageReceived(e){this.safeEmit(SignalEvent.USER_MESSAGE_RECEIVED,{userId:e.from,message:e.msg})}_onUserBinaryMessageReceived(e){var t;const i={userId:e.from,message:e.msg};(null==(t=this._subtitleTool)?void 0:t.onMessageRecv(i))||this.safeEmit(SignalEvent.USER_BINARY_MESSAGE_RECEIVED,i)}_initSubtitleTool(){this._subtitleTool=new SubtitleTool(this._ctx,this.config),this._subtitleTool.onEvent=e=>{this.emit(RoomEvent.ON_SUBTITLE_STATE_CHANGED,e)},this._subtitleTool.onMessage=e=>{this.emit(RoomEvent.ON_SUBTITLE_MESSAGE_RECEIVED,e)}}_onPostProcessingMessage(e){var t;if(!e.body)return;if("subtitleCallback"===e.type)return void(null==(t=this._subtitleTool)||t.onResult(e));const i=e.body,r=i.error||0;let o=StreamMixingEventType.START;const s=["success","parameter error","subscription timeout","ffmpeg error","cdn error","publish error"];if("2.0"===i.protocol){switch(i.eventType){case"TranscodeStarted":0!==i.error&&(o=StreamMixingEventType.START_FAILED);break;case"TranscodeStateChanged":o=0!==i.error?StreamMixingEventType.START_FAILED:StreamMixingEventType.START_SUCCESS;break;case"TranscodeStopped":o=0!==i.error?StreamMixingEventType.STOP_FAILED:StreamMixingEventType.STOP_SUCCESS;break;case"TranscodeUpdated":o=0!==i.error?StreamMixingEventType.UPDATE_FAILED:StreamMixingEventType.UPDATE_SUCCESS}this.safeEmit(SignalEvent.POST_PROCESSING_MESSAGE,{code:r,protocol:i.protocol,error:i.error,eventType:o,message:s[r]})}this.safeEmit(SignalEvent.POST_PROCESSING_MESSAGE,{code:r,message:s[r],type:e.type})}_onUserTokenWillExpire(){this.safeEmit(SignalEvent.ON_USER_TOKEN_WILL_EXPIRE,null)}_onUserTokePublishPrivilegeWillExpire(){this.safeEmit(SignalEvent.ON_TOKEN_PUBLISH_PRIVILEGE_WILL_EXPIRE,null)}_onUserTokenPublishPrivilegeDidExpire(){this.safeEmit(SignalEvent.ON_TOKEN_PUBLISH_PRIVILEGE_DID_EXPIRED,null)}_onUserTokeSubscribePrivilegeWillExpire(){this.safeEmit(SignalEvent.ON_TOKEN_SUBSCRIBE_PRIVILEGE_WILL_EXPIRE,null)}_onUserTokenSubscribePrivilegeDidExpire(){this.safeEmit(SignalEvent.ON_TOKEN_SUBSCRIBE_PRIVILEGE_DID_EXPIRED,null)}async _onStreamFailed(e){var t,i;if("publish"===e.type){let r;if((null==(t=this.localStream)?void 0:t.streamId)===e.streamId?r=this.localStream:(null==(i=this.localScreenStream)?void 0:i.streamId)===e.streamId&&(r=this.localScreenStream),!r)return;await this._publisher.unpublish(r).catch((()=>{})),await this._publisher.cleanStream(r),await this._publisher.publish(r).catch((()=>{}))}else if("subscribe"===e.type){const t=this._remoteStreamStreamIdUserIdMap[e.streamId],i=this._findRemoteStream(t,e.streamId);i&&(await this._subscriber.handleStreamFailed(i),this.safeEmit(RoomEvent.RESUBSCRIBE,{stream:i}))}}_onStreamControlMessage(e){var t,i;e.type===StreamControlType.PushLimitWarn&&((null==(t=this._localStream)?void 0:t.pubAudio)||(null==(i=this._localStream)?void 0:i.pubVideo)||this.unpublish())}async _onPublishOnDemand(){var e,t,i,r,o;if(this._publishOnDemandItem&&!this._publishOnDemandBusy&&!1!==(null==(i=null==(t=null==(e=this._serverConfig)?void 0:e.engine_VPM)?void 0:t.ondemand)?void 0:i.enable)){if(null==(r=this._localStream)?void 0:r.videoTransceiver){this._publishOnDemandBusy=!0;const e=this._publishOnDemandItem;this._publishOnDemandItem=void 0;const t=[],i=this._localStream.stream.id,{sender:r}=this._localStream.videoTransceiver,o=r.getParameters();if(reportRtcInvokeStatus(this._ctx.id,"sender.getParameters",JSON.stringify(o),0,i),Array.isArray(o.encodings)&&Array.isArray(e)){const r={};this.logger.info("_onPublishOnDemand exec","usedDescriptions: %o",e),e.forEach((e=>{var t,o,s,n;if(null==(t=e.StreamIds)?void 0:t.includes(i)){const t=(null==(o=e.Metadata)?void 0:o.VideoIndex)??0;let i=0;(null==(s=this._ctx.serverConfig)?void 0:s.e2eFeedback)&&(i=Math.max(...Object.keys((null==(n=e.Metadata)?void 0:n.VideoKbpsHist)??{}).map((e=>Number(e))),0)),r[t]={kbps:i}}}));const s=[...this._localStream.pubAttributes.videoDescriptions];o.encodings=o.encodings.map((e=>{var i,o;if(e.rid){if(r[e.rid]){e.active=!0;const t=null==(i=r[e.rid])?void 0:i.kbps;t&&(e.maxBitrate=1e3*calculateKbps(e.rid,t,s))}else e.active=!1;const o=Number(e.rid);t[o]=e.active}else{const t=null==(o=r[0])?void 0:o.kbps;t&&(e.maxBitrate=1e3*calculateKbps(void 0,t,s))}return e})),this.config.report("rtc_invoke_status",{sdk_api_name:"onPublishOnDemand",message:JSON.stringify(o.encodings),error_code:0,stream_id:i,elapse:0}),this._ctx.videoProfile.activeSimStreams=t}this.logger.info("sender.setParameters()",JSON.stringify(o.encodings)),reportRtcInvokeStatus(this._ctx.id,"sender.setParameters",JSON.stringify(o),0,i),await r.setParameters(o),this._publishOnDemandBusy=!1}else if(!(null==(o=this._localStream)?void 0:o.videoTransceiver))return;this._onPublishOnDemand()}}_onRTT(e){const{StreamIds:t,Metadata:i}=e;if((null==t?void 0:t.length)&&i){const e=t[0];this._ctx.streamRTT[e]={audio:i.audio_rtt,video:i.video_rtt}}}_onRSCP(e,t){!!e.find((e=>{var t,i,r;return null==(r=null==e?void 0:e.StreamIds)?void 0:r.includes(null==(i=null==(t=this._localStream)?void 0:t.stream)?void 0:i.id)}))&&(t?this._pubTransceiverReady=!0:this._onceTriggerBySignal=!0,t&&this._onceTriggerBySignal||(this._publishOnDemandItem=e),this._pubTransceiverReady&&this._onPublishOnDemand())}_onSSC(e){const{StreamIds:t,Metadata:i}=e,r=t[0],o=this._remoteStreamStreamIdUserIdMap[r],s=this._findRemoteStream(o,r),n={userId:o,isScreen:!!s&&s.isScreen,beforeVideoIndex:i.ssc_items[0].prev_layer_id,afterVideoIndex:i.ssc_items[0].cur_layer_id,beforeEnable:0!==i.ssc_items[0].prev_video_open,afterEnable:0!==i.ssc_items[0].cur_video_open,reason:i.ssc_items[0].change_reason};this.emit(RoomEvent.ON_SIMULCAST_SUBSCRIBE_FALLBACK,n)}_reportNetworkQuality(e,t){this.emit(RoomEvent.ON_NETWORK_QUALITY,e,t)}_emitVideoSizeChange(e,t,i,r){this.emit(RoomEvent.ON_REMOTE_VIDEO_SIZE_CHANGED,{roomId:this.config.roomId,userId:e,streamIndex:t?StreamIndex$1.STREAM_INDEX_SCREEN:StreamIndex$1.STREAM_INDEX_MAIN},{width:i,height:r})}async setAudioEncodeMaxBitrate(e,t){var i,r;const o=e===StreamIndex$1.STREAM_INDEX_MAIN?this.localStream:this.localScreenStream;if(null==o?void 0:o.pubAudio){const e=null==(i=o.audioTransceiver)?void 0:i.sender.getParameters();reportRtcInvokeStatus(this._ctx.id,"sender.getParameters",JSON.stringify(e),0,o.streamId),(null==e?void 0:e.encodings.length)&&(e.encodings[0].maxBitrate=1e3*t,reportRtcInvokeStatus(this._ctx.id,"sender.setParameters",JSON.stringify(e),0,o.streamId),await(null==(r=o.audioTransceiver)?void 0:r.sender.setParameters(e)))}}_onEngineControlMessage({type:e,body:t}){var i,r;if(e===EngineControlType.CHANGE_CODEC){if(!getParameter("SDK_CODEC_NEGOTIATION"))return void this.logger.info("_onEngineControlMessage","SDK_CODEC_NEGOTIATION is false, ignore");const{codec:e,media:o,streamId:s}=t;if(!o||"audio"===o)return;const n=e.split(",").map((e=>e.trim().toUpperCase()));let a;this.logger.info("_onEngineControlMessage","changeCodec to %s",e),s?((null==(i=this.localStream)?void 0:i.streamId)===s?a=this.localStream:(null==(r=this.localScreenStream)?void 0:r.streamId)===s&&(a=this.localScreenStream),null==a||a.setChangeCodecs(n)):"video"===o?(a=this.localStream,this._ctx.targetCodec=n[0]):"screen"===o&&(a=this.localScreenStream,this._ctx.targetScreenCodec=n[0]),a&&this.emit(RoomEvent.UPDATE_PUBLISH,{streamIndex:a.isScreen?StreamIndex$1.STREAM_INDEX_SCREEN:StreamIndex$1.STREAM_INDEX_MAIN})}}_checkClientBanned({clientId:e,attributes:t}){if(!t||!e)return;const{serverMuteAudio:i,serverMuteVideo:r}=t;if(r){const t=1===r;this.safeEmit(RoomEvent.ON_VIDEO_STREAM_BANNED,{uid:e,banned:t}),this._setRemoteUserMediaBanned(e,MediaType$1.VIDEO,t),this._maybeStartReceiveFirstFrameForServerMute(e,MediaType$1.VIDEO,t)}if(i){const t=1===i;this.safeEmit(RoomEvent.ON_AUDIO_STREAM_BANNED,{uid:e,banned:t}),this._setRemoteUserMediaBanned(e,MediaType$1.AUDIO,t),this._maybeStartReceiveFirstFrameForServerMute(e,MediaType$1.AUDIO,t)}}_setRemoteUserMediaBanned(e,t,i){let r=this._remoteUserMediaBanned.get(e)??0;i?r|=t:r&=~t,this._remoteUserMediaBanned.set(e,r)}_getRemoteUserMediaBanned(e,t){return t&(this._remoteUserMediaBanned.get(e)??0)}_maybeStartReceiveFirstFrameForServerMute(e,t,i){var r,o;if(i)return;const s=this._remoteStreams.get(e)??[];for(const e of s)e.isScreen||e.attributes.localvideo&&e.subVideo&&(null==(r=e.observer)||r.setExternalVideoSource(e.attributes.extvideo),null==(o=e.observer)||o.setUnmuteVideo(!0))}}__decorateClass$4([checkRoomState],Room.prototype,"publishScreen",1),__decorateClass$4([checkRoomState],Room.prototype,"updatePubScreenTrack",1),__decorateClass$4([checkRoomState],Room.prototype,"unpublishScreen",1),__decorateClass$4([checkRoomState],Room.prototype,"liveControlMessage",1),__decorateClass$4([checkRoomState],Room.prototype,"publicStreamControlMessage",1),__decorateClass$4([checkRoomState],Room.prototype,"updateUserAttributes",1),__decorateClass$4([checkRoomState],Room.prototype,"publish",1),__decorateClass$4([checkRoomState],Room.prototype,"updatePubTrack",1),__decorateClass$4([checkRoomState],Room.prototype,"unpublish",1),__decorateClass$4([checkRoomState],Room.prototype,"subscribe",1),__decorateClass$4([checkRoomState],Room.prototype,"updateSubVideoConfig",1),__decorateClass$4([checkRoomState],Room.prototype,"unsubscribe",1),__decorateClass$4([checkRoomState],Room.prototype,"startSubtitle",1),__decorateClass$4([checkRoomState],Room.prototype,"stopSubtitle",1),__decorateClass$4([checkRoomState],Room.prototype,"startForwardStream2Rooms",1),__decorateClass$4([checkRoomState],Room.prototype,"updateForwardStream2Rooms",1),__decorateClass$4([checkRoomState],Room.prototype,"stopForwardStream2Rooms",1),__decorateClass$4([checkRoomState],Room.prototype,"pauseForwardStream2AllRooms",1),__decorateClass$4([checkRoomState],Room.prototype,"resumeForwardStream2AllRooms",1),__decorateClass$4([checkRoomState],Room.prototype,"updateMediaParams",1),__decorateClass$4([checkRoomState],Room.prototype,"updateRemoteUserPriority",1),__decorateClass$4([checkRoomState],Room.prototype,"updateToken",1),__decorateClass$4([checkRoomState],Room.prototype,"sendUserMessage",1),__decorateClass$4([checkRoomState],Room.prototype,"sendRoomMessage",1),__decorateClass$4([checkRoomState],Room.prototype,"maybeFillBackFrame2Stream",1);const isValidAudioFile=async(e,t)=>{const i=new Audio(URL.createObjectURL(new Blob([e],t)));try{return i.muted=!0,await i.play(),i.pause(),!0}catch(e){return!1}};var __defProp$3=Object.defineProperty,__getOwnPropDesc$3=Object.getOwnPropertyDescriptor,__decorateClass$3=(e,t,i,r)=>{for(var o,s=r>1?void 0:r?__getOwnPropDesc$3(t,i):t,n=e.length-1;n>=0;n--)(o=e[n])&&(s=(r?o(t,i,s):o(s))||s);return r&&s&&__defProp$3(t,i,s),s};class AudioMixingManager{constructor(e,t){var i,r;__publicField(this,"_sharedAudioContext",new AudioContext),__publicField(this,"_workletReady"),__publicField(this,"_audioDestination",this._sharedAudioContext.createMediaStreamDestination()),__publicField(this,"_localGainNode",this._sharedAudioContext.createGain()),__publicField(this,"_bufferGainNode",this._sharedAudioContext.createGain()),__publicField(this,"_audioBufferSource"),__publicField(this,"_localSource"),__publicField(this,"_context"),__publicField(this,"_failedAudioList",[]),__publicField(this,"_startingIds",new Map),__publicField(this,"_revokeURLs",new Set),__publicField(this,"_audioFetchMap",new Map),__publicField(this,"_audioFetchConfig",new Map),__publicField(this,"mixingMap",new Map),__publicField(this,"resourcesCache",new Map),__publicField(this,"volumeConfig",new Map),__publicField(this,"cachedBuffer",[]),__publicField(this,"id","AudioMixingManager"),this.engineId=t,this._context=e;try{this._workletReady=null==(r=null==(i=this._sharedAudioContext.audioWorklet)?void 0:i.addModule)?void 0:r.call(i,dumpAudioDataWorklet),this._workletReady.catch((()=>{this._workletReady=null}))}catch{this._workletReady=null}this._localGainNode.gain.value=1}mixMediaStream(e){this._localSource&&this._localSource.disconnect(this._localGainNode),this._localSource=this._sharedAudioContext.createMediaStreamSource(e),this._localSource.connect(this._localGainNode).connect(this._audioDestination)}async startAudioMixing(e,t,i){if(void 0!==this._startingIds.get(e))return void console.warn(`AudioMixing task id: ${e} is starting`);this._startingIds.set(e,e);const{playCount:r,type:o}=i;checkEnum(o,"mixingType",values(AudioMixingType));const s=this._context.getLocalAudioTrack();if(!s)return;const n=s.preprocessingTrack;n&&this.mixMediaStream(new MediaStream([n])),s.once("needReplaceTrack",(()=>{this.mixMediaStream(new MediaStream([s.preprocessingTrack]))}));const a=this.mixingMap.get(e);if(null==a?void 0:a.audioNode){a.audioNode.pause(),this._context.emitMessage({mixId:e,state:AudioMixingState.AUDIO_MIXING_STATE_STOPPED,error:AudioMixingError.AUDIO_MIXING_ERROR_OK});try{a.gainNode.disconnect(this._audioDestination),a.audioSource.disconnect(a.gainNode)}catch(e){}}let d;const c=this.resourcesCache.get(e);if(c&&c.filePath===t)d=c.getAudioNode();else{const i=await fetch(t,{mode:"cors"}).then((t=>{if(t.ok)return t.arrayBuffer();throw this._context.emitMessage({mixId:e,state:AudioMixingState.AUDIO_MIXING_STATE_FAILED,error:AudioMixingError.AUDIO_MIXING_ERROR_START_FAILED}),this._startingIds.delete(e),this.mixingMap.delete(e),new SDKError(ErrorCode.LOAD_RESOURCES_FAILED,t.statusText)}));let r;t.endsWith("mp3")?r={type:"audio/mpeg"}:t.endsWith("aac")&&(r={type:"audio/aac"});if(!await isValidAudioFile(i,r))throw this._context.emitMessage({mixId:e,state:AudioMixingState.AUDIO_MIXING_STATE_FAILED,error:AudioMixingError.AUDIO_MIXING_ERROR_START_FAILED}),this._startingIds.delete(e),this.mixingMap.delete(e),new SDKError(ErrorCode.LOAD_RESOURCES_FAILED,"invalid audio resource");d=new Audio,d.crossOrigin="anonymous",d.src=URL.createObjectURL(new Blob([i],r))}if(r<=0)d.loop=!0;else if(r>0){let t=r;d.onended=()=>{--t>0?d.play():(this.mixingMap.delete(e),this._context.emitMessage({mixId:e,state:AudioMixingState.AUDIO_MIXING_STATE_FINISHED,error:AudioMixingError.AUDIO_MIXING_ERROR_OK}))}}try{await d.play()}catch(e){console.error(e),this._failedAudioList.push(d),this._context.onAutoPlayFailed({userId:this.id,kind:"audio",streamIndex:StreamIndex$1.STREAM_INDEX_MAIN,mediaType:MediaType$1.AUDIO})}this._startingIds.delete(e);const l=this._sharedAudioContext.createMediaElementSource(d),u=this._sharedAudioContext.createGain(),_=this.volumeConfig.get(e);if(u.gain.value=_?_/100:1,l.connect(u).connect(this._audioDestination),this.mixingMap.set(e,{audioSource:l,audioNode:d,gainNode:u,type:"file"}),o===AudioMixingType.PUBLISH)try{u.disconnect(this._sharedAudioContext.destination)}catch(e){}else u.connect(this._sharedAudioContext.destination);this._context.updateLocalAudioTrack(this._audioDestination.stream.getAudioTracks()[0],i.type),this._context.emitMessage({mixId:e,state:AudioMixingState.AUDIO_MIXING_STATE_PLAYING,error:AudioMixingError.AUDIO_MIXING_ERROR_OK}),this.updateFetcher(e)}stopAudioMixing(e){const t=this.mixingMap.get(e);t&&"file"===t.type&&(this.mixingMap.delete(e),t.audioNode.pause(),t.audioSource.disconnect(t.gainNode),t.gainNode.disconnect(this._audioDestination),this.updateFetcher(e),this._context.emitMessage({mixId:e,state:AudioMixingState.AUDIO_MIXING_STATE_STOPPED,error:AudioMixingError.AUDIO_MIXING_ERROR_OK}))}pauseAudioMixing(e){const t=this.mixingMap.get(e);t&&(this._context.emitMessage({mixId:e,state:AudioMixingState.AUDIO_MIXING_STATE_PAUSED,error:AudioMixingError.AUDIO_MIXING_ERROR_OK}),t.audioNode.pause())}resumeAudioMixing(e){const t=this.mixingMap.get(e);t&&(this._context.emitMessage({mixId:e,state:AudioMixingState.AUDIO_MIXING_STATE_PLAYING,error:AudioMixingError.AUDIO_MIXING_ERROR_OK}),t.audioNode.play())}async preloadAudioMixing(e,t){this.stopAudioMixing(e);const i=await fetch(t,{mode:"cors"}).then((e=>{if(e.ok)return e.arrayBuffer();throw new SDKError(ErrorCode.LOAD_RESOURCES_FAILED,e.statusText)})).catch((t=>{if(this._context.emitMessage({mixId:e,state:AudioMixingState.AUDIO_MIXING_STATE_FAILED,error:AudioMixingError.AUDIO_MIXING_ERROR_PRELOAD_FAILED}),t instanceof SDKError)throw t;throw new SDKError(ErrorCode.LOAD_RESOURCES_FAILED,"Load resources failed",t)}));let r;t.endsWith("mp3")?r={type:"audio/mpeg"}:t.endsWith("aac")&&(r={type:"audio/aac"});if(!await isValidAudioFile(i,r))throw this._context.emitMessage({mixId:e,state:AudioMixingState.AUDIO_MIXING_STATE_FAILED,error:AudioMixingError.AUDIO_MIXING_ERROR_PRELOAD_FAILED}),new SDKError(ErrorCode.LOAD_RESOURCES_FAILED,"Load resources failed");this._context.emitMessage({mixId:e,state:AudioMixingState.AUDIO_MIXING_STATE_PRELOADED,error:AudioMixingError.AUDIO_MIXING_ERROR_OK}),this.resourcesCache.set(e,{getAudioNode:()=>{const e=URL.createObjectURL(new Blob([i],r));return this._revokeURLs.add(e),new Audio(e)},filePath:t,duration:0}),await new Promise((t=>{const o=URL.createObjectURL(new Blob([i],r)),s=new Audio(o);s.addEventListener("durationchange",(()=>{const i=this.resourcesCache.get(e);i&&(i.duration=s.duration,this.resourcesCache.set(e,i)),URL.revokeObjectURL(o),t(null)}))}))}unloadAudioMixing(e){this.resourcesCache.has(e)&&this.resourcesCache.delete(e)}getAudioMixingVolume(e){const t=this.mixingMap.get(e);return t?100*t.gainNode.gain.value:0}setAudioMixingVolume(e,t){t<0?t=0:t>400&&(t=400),this.volumeConfig.set(e,t);const i=this.mixingMap.get(e);i&&(i.gainNode.gain.value=Number(t)/100)}getAudioMixingDuration(e){const t=this.mixingMap.get(e),i=this.resourcesCache.get(e);return t||i?t?1e3*t.audioNode.duration:i?1e3*i.duration:0:0}getAudioMixingCurrentPosition(e){const t=this.mixingMap.get(e);return t?1e3*t.audioNode.currentTime:0}setAudioMixingPosition(e,t){const i=this.mixingMap.get(e);i&&(i.audioNode.currentTime=t/1e3,i.audioNode.play())}setAudioFrameCallback(e,t,i=4096){if(checkEnum(i,"frameSize",[256,512,1024,2048,4096,8192,16384]),i=i??4096,null===this._workletReady)throw new SDKError(ErrorCode.NOT_SUPPORTED,"Not support AudioWorklet");t?this._audioFetchConfig.set(e,{callback:t,frameSize:i}):this._audioFetchConfig.delete(e),this.updateFetcher(e)}updateFetcher(e){var t;const{callback:i,frameSize:r}=this._audioFetchConfig.get(e)??{},o=null==(t=this.mixingMap.get(e))?void 0:t.gainNode;if(o&&i&&r){let t=this._audioFetchMap.get(e);t?t.setFrameSize(r):t=new AudioDataFetcher(o,r,this._sharedAudioContext,this._workletReady),t.on("data",i),this._audioFetchMap.set(e,t)}else{const t=this._audioFetchMap.get(e);null==t||t.removeAllListeners("data"),null==t||t.destroy(),this._audioFetchMap.delete(e)}}enableAudioMixingBuffer(e){checkEnum(e,"type",values(AudioMixingType));const t=this._context.getLocalAudioTrack();if(!t)return;const i=t.preprocessingTrack;if(i&&this.mixMediaStream(new MediaStream([i])),e===AudioMixingType.PUBLISH)try{this._bufferGainNode.disconnect(this._sharedAudioContext.destination)}catch(e){}else this._bufferGainNode.connect(this._sharedAudioContext.destination);this._context.updateLocalAudioTrack(this._audioDestination.stream.getAudioTracks()[0],e),this._bufferGainNode.connect(this._audioDestination),this._context.emitMessage({mixId:-1,state:AudioMixingState.AUDIO_MIXING_STATE_PCM_ENABLED,error:AudioMixingError.AUDIO_MIXING_ERROR_OK})}disableAudioMixingBuffer(){if(this.cachedBuffer=[],this._audioBufferSource){try{this._audioBufferSource.onended=null,this._audioBufferSource.disconnect(this._bufferGainNode),this._bufferGainNode.disconnect(this._audioDestination),this._bufferGainNode.disconnect(this._sharedAudioContext.destination)}catch(e){}finally{this._audioBufferSource=void 0}this._context.updateLocalAudioTrack(),this._context.emitMessage({mixId:-1,state:AudioMixingState.AUDIO_MIXING_STATE_PCM_DISABLED,error:AudioMixingError.AUDIO_MIXING_ERROR_OK})}}pushAudioMixingBuffer(e){if(!(this._audioBufferSource&&(this.cachedBuffer.push(e),this.cachedBuffer.length>0))){this._audioBufferSource=this._sharedAudioContext.createBufferSource(),this._audioBufferSource.buffer=e,this._audioBufferSource.connect(this._bufferGainNode);try{this._audioBufferSource.start()}catch(e){this._failedAudioList.push(this._audioBufferSource)}this._audioBufferSource.onended=()=>{var e;if(null==(e=this._audioBufferSource)||e.disconnect(this._bufferGainNode),this._audioBufferSource=void 0,this.cachedBuffer.length){const e=this.cachedBuffer.shift();e&&this.pushAudioMixingBuffer(e)}}}}stopAll(){if(this._localSource)try{this._localSource.disconnect(this._localGainNode),delete this._localSource}catch(e){}this.mixingMap.forEach(((e,t)=>{this.stopAudioMixing(t)}))}get mixTrack(){return this._audioDestination.stream.getAudioTracks()[0]}get sharedAudioContext(){return this._sharedAudioContext}async resumeLocalPlay(){const e=[];for(const t of this._failedAudioList)try{t instanceof HTMLAudioElement?(t.muted=!1,await t.play()):t.start()}catch(i){e.push(t),console.error(i),this._context.onAutoPlayFailed({userId:this.id,kind:"audio",streamIndex:StreamIndex$1.STREAM_INDEX_MAIN,mediaType:MediaType$1.AUDIO});break}this._failedAudioList=e}destroy(){const{_sharedAudioContext:e}=this;"closed"!==e.state&&"function"==typeof e.close&&e.close(),this.cachedBuffer=[],this.mixingMap.clear(),this.resourcesCache.clear(),this.volumeConfig.clear(),this._startingIds=new Map,this._revokeURLs.forEach((e=>{URL.revokeObjectURL(e)}))}}__decorateClass$3([reportRtcSdkApi(["id","filePath","options"])],AudioMixingManager.prototype,"startAudioMixing",1),__decorateClass$3([reportRtcSdkApi(["id"])],AudioMixingManager.prototype,"stopAudioMixing",1),__decorateClass$3([reportRtcSdkApi(["id"])],AudioMixingManager.prototype,"pauseAudioMixing",1),__decorateClass$3([reportRtcSdkApi(["id"])],AudioMixingManager.prototype,"resumeAudioMixing",1),__decorateClass$3([reportRtcSdkApi(["id"])],AudioMixingManager.prototype,"preloadAudioMixing",1),__decorateClass$3([reportRtcSdkApi(["id"])],AudioMixingManager.prototype,"unloadAudioMixing",1),__decorateClass$3([reportRtcSdkApi(["id"])],AudioMixingManager.prototype,"getAudioMixingVolume",1),__decorateClass$3([reportRtcSdkApi(["id","volume"])],AudioMixingManager.prototype,"setAudioMixingVolume",1),__decorateClass$3([reportRtcSdkApi(["id"])],AudioMixingManager.prototype,"getAudioMixingDuration",1),__decorateClass$3([reportRtcSdkApi(["id"])],AudioMixingManager.prototype,"getAudioMixingCurrentPosition",1),__decorateClass$3([reportRtcSdkApi(["id","position"])],AudioMixingManager.prototype,"setAudioMixingPosition",1),__decorateClass$3([reportRtcSdkApi(["id","callback","frameSize"])],AudioMixingManager.prototype,"setAudioFrameCallback",1),__decorateClass$3([reportRtcSdkApi(["type"])],AudioMixingManager.prototype,"enableAudioMixingBuffer",1),__decorateClass$3([reportRtcSdkApi()],AudioMixingManager.prototype,"disableAudioMixingBuffer",1),__decorateClass$3([reportRtcSdkApi(["buffer"])],AudioMixingManager.prototype,"pushAudioMixingBuffer",1);class RTSClient extends eventemitter3Exports.EventEmitter{constructor(e){super(),__publicField(this,"_loginSessionId",null),__publicField(this,"_userId",null),__publicField(this,"_token",null),__publicField(this,"_loginResolveCallback"),__publicField(this,"_loginRejectCallback"),__publicField(this,"_waitLoginToken",!1),__publicField(this,"_serverParamsCache"),__publicField(this,"id"),__publicField(this,"logger"),__publicField(this,"_clearListeners"),this._ctx=e,this.id=e.id,this.logger=new Logger$1("RTSClient",1,e.id)}login(e,t){return new Promise(((i,r)=>{var o;if(this.logger.info("login","invoke login, token: %o, userId: %o",e,t),this._loginSessionId)throw new SDKError(ErrorCode.ALREADY_LOGIN,"Already logined");if(this._loginResolveCallback)throw new SDKError(ErrorCode.LOGIN_FAILED,"Is logging in, please try again later.");this._userId=t,this._token=e,null==(o=getMonitor(this.id))||o.set({rtm_user_id:t}),this._loginResolveCallback=i,this._loginRejectCallback=r,this._ctx.signalingManager.connect().then((()=>{this._addSignalEventHandler(),this._login()}))}))}async logout(){if(!this._loginSessionId||!this._userId)throw new SDKError(ErrorCode.NOT_LOGIN,"login first");this._checkNotInLimitMode("logout"),await this._ctx.signalingManager.sendSignaling("logout",{loginSessionId:this._loginSessionId,userId:this._userId,appId:this._ctx.appId},{functionType:SIGNALING_FUNCTION_TYPE.C2RTM}).catch((()=>{})),this._clearState()}async updateLoginToken(e){return this._checkNotInLimitMode("updateLoginToken"),this._token=e,new Promise(((e,t)=>{this._waitLoginToken?(this._loginResolveCallback=e,this._loginRejectCallback=t,this._login()):e()}))}async getPeerOnlineStatus(e){if(!this._loginSessionId||!this._userId)throw new SDKError(ErrorCode.NOT_LOGIN,"login first");this._checkNotInLimitMode("getPeerOnlineStatus");const t=await this._ctx.signalingManager.sendSignaling("getPeerOnlineStatus",{loginSessionId:this._loginSessionId,userId:this._userId,appId:this._ctx.appId,peerUserId:e},{functionType:SIGNALING_FUNCTION_TYPE.C2RTM});return null==t?void 0:t.status}async sendUserMessageOutsideRoom(e,t){if(!this._loginSessionId||!this._userId)throw new SDKError(ErrorCode.NOT_LOGIN,"login first");return this._checkNotInLimitMode("sendUserMessageOutsideRoom"),this._ctx.rtsLimiter.e2e.check(t),this._ctx.signalingManager.sendP2PMessage({from:this._userId,app:this._ctx.appId,to:e,room:"",msg:t})}async setRTSMessageLimit(e){e&&this._ctx.signalingManager.sendSignaling("RTSMessageLimit",{appId:this._ctx.appId,interval:e.rts_qps_interval,broadcast:e.rts_broadcast_qps_value,one2one:e.rts_e2e_qps_value,e2bs:e.rts_e2s_qps_value},{functionType:SIGNALING_FUNCTION_TYPE.C2RTM}).catch((()=>{}))}async setServerParams(e,t){try{if(checkString(e,"signature"),checkString(t,"url"),!this._loginSessionId||!this._userId)throw new SDKError(ErrorCode.NOT_LOGIN,"login first");await this._ctx.signalingManager.sendSignaling("setServerParams",{loginSessionId:this._loginSessionId,userId:this._userId,appId:this._ctx.appId,signature:e,url:t},{functionType:SIGNALING_FUNCTION_TYPE.C2RTM}).catch((e=>{throw new SDKError(ErrorCode.UNEXPECTED_ERROR,e.msg)})),RTSMsgReportor.setServerUrl(this.id,t),this._serverParamsCache={signature:e,url:t},this.emit("onServerParamsSetResult")}catch(e){throw this.emit("onServerParamsSetResult",e),e}}async sendServerMessage(e){if(!this._loginSessionId||!this._userId)throw new SDKError(ErrorCode.NOT_LOGIN,"login first");return this._checkNotInLimitMode("sendServerMessage"),this._ctx.rtsLimiter.e2s.check(e),this._ctx.signalingManager.sendP2PMessage({from:this._userId,app:this._ctx.appId,to:"",room:"",type:DC_MESSAGE_FUNCTION_TYPE.BUSINESS_SERVER,msg:e})}destroy(){this.logger.info("destroy","invoke."),super.removeAllListeners(),this._loginResolveCallback&&this._loginRejectCallback&&(this._loginRejectCallback(new SDKError(ErrorCode.LOGIN_FAILED,"logout")),delete this._loginResolveCallback,delete this._loginRejectCallback),this._clearState(),delete this._serverParamsCache}_login(){var e;if(!this._userId)return;const t=genUuid();try{this._checkNotInLimitMode("login")}catch(t){null==(e=this._loginRejectCallback)||e.call(this,t)}this._ctx.signalingManager.sendSignaling("login",{Token:Utils.token2auth(this._ctx.appId,null,this._userId,this._token),timestamp:Date.now(),loginSessionId:t,params:{userAgent:window.navigator.userAgent,sdkVersion:Config2.VERSION,deviceId:sdkCache.getDeviceId(),appId:this._ctx.appId,userId:this._userId,deviceType:"web",platformType:2,rtsMode:this._ctx.rtsMode,mediaProcessingType:Config2.MEDIA_PROCESSING_TYPE??0},accessParams:JSON.stringify({requireICEUfragV2:!0})},{functionType:SIGNALING_FUNCTION_TYPE.C2RTM}).then((()=>{"function"==typeof this._loginResolveCallback&&this._loginResolveCallback(),this._loginSessionId=t,RTSMsgReportor.setRtsSessionId(this.id,t),this._waitLoginToken=!1,this._serverParamsCache&&this.setServerParams(this._serverParamsCache.signature,this._serverParamsCache.url)})).catch((e=>{const{code:t,message:i}=e||{};let r,o;this._waitLoginToken=!1,t>=700&&t<800?708===t?(r=ErrorCode.INVALID_PARAMS,o="Invalid userId"):(r=ErrorCode.INVALID_TOKEN,o="Invalid token",this._waitLoginToken=!0,this._loginRejectCallback||this.emit("onRTMTokenError")):(r=ErrorCode.LOGIN_FAILED,o="login failed"),"function"==typeof this._loginRejectCallback&&this._loginRejectCallback(new SDKError(r,i||o))})).finally((()=>{delete this._loginResolveCallback,delete this._loginRejectCallback}))}_addSignalEventHandler(){const e=e=>{e.state===ConnectionState.CONNECTION_STATE_RECONNECTED&&this._login()},t=()=>this._clearState(),i=e=>{this.emit("onUserMessageReceivedOutsideRoom",{userId:e.from,message:e.msg})},r=e=>{this.emit("onUserBinaryMessageReceivedOutsideRoom",{userId:e.from,message:e.msg})},o=e=>{e.clientId!==this._userId||e.roomId||(this.emit("onUserDisconnection"),this._clearState())};this._ctx.signalingManager.on(StateEvent.ON_CONNECTION_STATE_CHANGE,e),this._ctx.signalingManager.on(StateEvent.ON_RECONNECT_FAILED,t),this._ctx.signalingManager.on(SignalEvent.USER_MESSAGE_RECEIVED_OUTSIDE_ROOM,i),this._ctx.signalingManager.on(SignalEvent.USER_BINARY_MESSAGE_RECEIVED_OUTSIDE_ROOM,r),this._ctx.signalingManager.on(SignalEvent.USER_DISCONNECTION,o),this._clearListeners=()=>{this._ctx.signalingManager.off(StateEvent.ON_CONNECTION_STATE_CHANGE,e),this._ctx.signalingManager.off(StateEvent.ON_RECONNECT_FAILED,t),this._ctx.signalingManager.off(SignalEvent.USER_MESSAGE_RECEIVED_OUTSIDE_ROOM,i),this._ctx.signalingManager.off(SignalEvent.USER_BINARY_MESSAGE_RECEIVED_OUTSIDE_ROOM,r),this._ctx.signalingManager.off(SignalEvent.USER_DISCONNECTION,o)}}_clearState(){var e;null==(e=this._clearListeners)||e.call(this),this._userId=null,this._token=null,this._loginSessionId=null,RTSMsgReportor.setRtsSessionId(this.id,"")}_checkNotInLimitMode(e){if(this._ctx.rtsMode===RTS_MODE.LIMIT_MODE)throw new SDKError(ErrorCode.NOT_ALLOWED_IN_RESTRICTED_MODE,`not allow to call ${e} in rts restricted mode`)}}var WTNStreamEventsTypes=(e=>(e.onWTNPushStateChanged="onWTNPushStateChanged",e.onWTNPlayStateChanged="onWTNPlayStateChanged",e.onWTNRemoteAudioStateChanged="onWTNRemoteAudioStateChanged",e.onWTNRemoteVideoStateChanged="onWTNRemoteVideoStateChanged",e.onWTNRemoteVideoStats="onWTNRemoteVideoStats",e.onWTNRemoteAudioStats="onWTNRemoteAudioStats",e.onWTNFirstRemoteVideoFrameDecoded="onWTNFirstRemoteVideoFrameDecoded",e.onWTNSEIMessageReceived="onWTNSEIMessageReceived",e))(WTNStreamEventsTypes||{}),WTNPushState=(e=>(e[e.INIT=0]="INIT",e[e.START=1]="START",e[e.SUCCESS=2]="SUCCESS",e[e.STOP=3]="STOP",e[e.FAIL=4]="FAIL",e))(WTNPushState||{}),WTNPushStateChangedReason=(e=>(e[e.PUSH_SUCCESS=0]="PUSH_SUCCESS",e[e.START_PUSH=1]="START_PUSH",e[e.STOP_PUSH=2]="STOP_PUSH",e[e.IN_RETRY=3]="IN_RETRY",e[e.RETRY_FAIL=4]="RETRY_FAIL",e[e.NO_PUSH_PERMISSION=5]="NO_PUSH_PERMISSION",e[e.STREAM_PUSH_BY_OTHER=6]="STREAM_PUSH_BY_OTHER",e))(WTNPushStateChangedReason||{}),WTNPlayState=(e=>(e[e.INIT=0]="INIT",e[e.START=1]="START",e[e.SUCCESS=2]="SUCCESS",e[e.STOP=3]="STOP",e[e.FAIL=4]="FAIL",e))(WTNPlayState||{}),WTNPlayStateChangedReason=(e=>(e[e.PLAY_SUCCESS=0]="PLAY_SUCCESS",e[e.START_PLAY=1]="START_PLAY",e[e.STOP_PLAY=2]="STOP_PLAY",e[e.REMOTE_STOP=3]="REMOTE_STOP",e[e.REMOTE_FAILURE=4]="REMOTE_FAILURE",e[e.STREAM_BANNED=5]="STREAM_BANNED",e[e.NO_PLAY_PERMISSION=6]="NO_PLAY_PERMISSION",e[e.STREAM_NOT_EXIST=7]="STREAM_NOT_EXIST",e[e.IN_RETRY=8]="IN_RETRY",e[e.RETRY_FAIL=9]="RETRY_FAIL",e[e.INTERNAL=10]="INTERNAL",e[e.OVER_CLIENT_SUBSCRIBE_STREAM_LIMIT=1310]="OVER_CLIENT_SUBSCRIBE_STREAM_LIMIT",e[e.OVER_STREAM_SUBSCRIBE_USER_LIMIT=1311]="OVER_STREAM_SUBSCRIBE_USER_LIMIT",e[e.OVER_STREAM_SUBSCRIBE_REQUES_TLIMIT=1312]="OVER_STREAM_SUBSCRIBE_REQUES_TLIMIT",e))(WTNPlayStateChangedReason||{}),WTNRemoteAudioState=(e=>(e[e.STOPED=0]="STOPED",e[e.STARTING=1]="STARTING",e[e.DECODING=2]="DECODING",e[e.FROZEN=3]="FROZEN",e[e.FAILED=4]="FAILED",e))(WTNRemoteAudioState||{}),WTNRemoteAudioStateChangeReason=(e=>(e[e.INTERNAL=0]="INTERNAL",e[e.NETWORK_CONGESTION=1]="NETWORK_CONGESTION",e[e.NETWORK_RECOVERY=2]="NETWORK_RECOVERY",e[e.UNMUTE=3]="UNMUTE",e[e.MUTE=4]="MUTE",e[e.REMOTE_START=5]="REMOTE_START",e[e.REMOTE_STOP=6]="REMOTE_STOP",e))(WTNRemoteAudioStateChangeReason||{}),WTNRemoteVideoState=(e=>(e[e.STOPED=0]="STOPED",e[e.STARTING=1]="STARTING",e[e.DECODING=2]="DECODING",e[e.FROZEN=3]="FROZEN",e[e.FAILED=4]="FAILED",e))(WTNRemoteVideoState||{}),WTNRemoteVideoStateChangeReason=(e=>(e[e.INTERNAL=0]="INTERNAL",e[e.NETWORK_CONGESTION=1]="NETWORK_CONGESTION",e[e.NETWORK_RECOVERY=2]="NETWORK_RECOVERY",e[e.UNMUTE=3]="UNMUTE",e[e.MUTE=4]="MUTE",e[e.REMOTE_START=5]="REMOTE_START",e[e.REMOTE_STOP=6]="REMOTE_STOP",e))(WTNRemoteVideoStateChangeReason||{});const BACK_OFF_INIT_STATE={interval:1e3,retryDuration:0};class WTNLocalStream extends LocalStream{constructor(e,t,i,r=!1){super(i,StreamIndex.STREAM_INDEX_MAIN),__publicField(this,"_state",WTNPushState.INIT),__publicField(this,"_stateChangeTs",getServerNow()),__publicField(this,"streamId"),__publicField(this,"Authorization"),__publicField(this,"_backOff",BACK_OFF_INIT_STATE),this.token=t,this.streamId=e,this.logName=`WTNLocalStream-${e}`,this.observer=new SendFrameObserver(this._ctx,this),this.Authorization=Utils.token2auth(i.appId,"",e,t),this._state=r?WTNPushState.FAIL:WTNPushState.INIT,this.isPublicStream=!0}setState(e,t){const i=this._state;if(i===e)return;this.logger.print("setState",e,t),this._state=e;const r=getServerNow();this.safeEmit(WTNStreamEventsTypes.onWTNPushStateChanged,{streamId:this.streamId,oldState:i,newState:e,reason:t,elapse:r-this._stateChangeTs}),this._stateChangeTs=r}getPushBackOff(){return this._backOff}updatePushBackOff(){this._backOff.retryDuration+=this._backOff.interval,this._backOff.interval=this._backOff.interval>4e3?8e3:2*this._backOff.interval}resetPushBackOff(){this._backOff=BACK_OFF_INIT_STATE}}class WTNRemoteStream extends RemoteStream{constructor(e,t,i,r=!1){super(i,e,e,!1,!0,{audiostream:!0,localaudio:!0,videostream:!0,localvideo:!0,extaudio:!1,extvideo:!1,videoDescriptions:[]}),__publicField(this,"_state",WTNPlayState.INIT),__publicField(this,"Authorization"),__publicField(this,"_stateChangeTs",getServerNow()),__publicField(this,"streamId"),__publicField(this,"_backOff",BACK_OFF_INIT_STATE),__publicField(this,"_audioState",WTNRemoteAudioState.STOPED),__publicField(this,"_videoState",WTNRemoteVideoState.STOPED),this.token=t,this.streamId=e,this.logName=`WTNRemoteStream-${e}`,this.observer=new RecvFrameObserver(this._ctx,this),this._initObserverEvent(r),this.Authorization=Utils.token2auth(i.appId,"",e,t),this._state=r?WTNPlayState.FAIL:WTNPlayState.INIT,this.isPublicStream=!0}setState(e,t){const i=this._state;if(i===e)return;this.logger.print("setState",e,t),this._state=e;const r=getServerNow();this.safeEmit(WTNStreamEventsTypes.onWTNPlayStateChanged,{streamId:this.streamId,oldState:i,newState:e,reason:t,elapse:r-this._stateChangeTs}),this._stateChangeTs=r}get state(){return this._state}getPushBackOff(){return this._backOff}updatePushBackOff(){this._backOff.retryDuration+=this._backOff.interval,this._backOff.interval=this._backOff.interval>4e3?8e3:2*this._backOff.interval}resetPushBackOff(){this._backOff=BACK_OFF_INIT_STATE}setVideoState(e,t){this._videoState!==e&&(e===WTNRemoteVideoState.DECODING&&this.setVideoState(WTNRemoteVideoState.STARTING,t),this.logger.print("setVideoState",e,t),this._videoState=e,this.safeEmit(WTNStreamEventsTypes.onWTNRemoteVideoStateChanged,{streamId:this.streamId,state:e,reason:t}))}setAudioState(e,t){this._audioState!==e&&(e===WTNRemoteAudioState.DECODING&&this.setAudioState(WTNRemoteAudioState.STARTING,t),this.logger.print("setAudioState",e,t),this._audioState=e,this.safeEmit(WTNStreamEventsTypes.onWTNRemoteAudioStateChanged,{streamId:this.streamId,state:e,reason:t}))}muteToSubMediaType(e,t){let i=!1;const r=audioInMediaType(this.subMediaType),o=videoInMediaType(this.subMediaType);return"boolean"==typeof e&&r===e&&(this.subMediaType+=e?-MediaType$1.AUDIO:MediaType$1.AUDIO,i=!0),"boolean"==typeof t&&o===t&&(this.subMediaType+=t?-MediaType$1.VIDEO:MediaType$1.VIDEO,i=!0),i}getEnableMediaType(){return{audio:audioInMediaType(this.subMediaType),video:videoInMediaType(this.subMediaType)}}_initObserverEvent(e){var t,i;null==(t=this.observer)||t.once("recvAudioFirstFrame",(()=>{this.setAudioState(WTNRemoteAudioState.DECODING,e?WTNRemoteAudioStateChangeReason.NETWORK_RECOVERY:WTNRemoteAudioStateChangeReason.REMOTE_START)})),null==(i=this.observer)||i.once("recvVideoFirstFrame",(()=>{this.setVideoState(WTNRemoteVideoState.DECODING,e?WTNRemoteVideoStateChangeReason.NETWORK_RECOVERY:WTNRemoteVideoStateChangeReason.REMOTE_START)}))}}var __defProp$2=Object.defineProperty,__getOwnPropDesc$2=Object.getOwnPropertyDescriptor,__decorateClass$2=(e,t,i,r)=>{for(var o,s=r>1?void 0:r?__getOwnPropDesc$2(t,i):t,n=e.length-1;n>=0;n--)(o=e[n])&&(s=(r?o(t,i,s):o(s))||s);return r&&s&&__defProp$2(t,i,s),s};class WTNStream extends EnhancedEventEmitter{constructor(e){super(),__publicField(this,"_reportName","WTNStream"),__publicField(this,"_localStreams",new Map),__publicField(this,"_remoteStreams",new Map),__publicField(this,"_logger"),__publicField(this,"_monitor"),__publicField(this,"_ontrackCallbackMap",new Map),__publicField(this,"_wtnPlayLocks",new Map),__publicField(this,"_pushTaskMap",new Map),__publicField(this,"_playTaskMap",new Map),__publicField(this,"engineId"),__publicField(this,"_publicVideoPlayerConfig",new Map),__publicField(this,"__onSEIMessageReceived"),__publicField(this,"__onRemoteStreamStats"),__publicField(this,"__onResubscribe"),__publicField(this,"__onPlayerEvents"),__publicField(this,"_clearSignalListeners"),this._ctx=e,this._monitor=getMonitor(e.id),this._logger=new Logger$1("WTNStream",1,e.id),this.engineId=e.id,this._addSignalListeners()}async startPushWTN(e,t,i,r,o=!1){var s;if(i=!!i,r=!!r,this._logger.print("startPushWTN",e,t,i,r),checkPublicStreamId(t),!isEmpty(e)&&checkString(e,"token"),this._localStreams.get(t))return;const n=new WTNLocalStream(t,e,this._ctx,o);this._addLocalStreamEventHandler(n),n.setState(WTNPushState.START,WTNPushStateChangedReason.START_PUSH),this._localStreams.set(t,n),await this._ctx.signalingManager.connect(),n.videoTrack=this._ctx.localVideoTrack,n.audioTrack=this._ctx.localAudioTrack,n.pubAudio=!r,n.pubVideo=!i,null==(s=n.observer)||s.setLogin(!0),await new Promise(((e,i)=>{o||this._pushTaskMap.set(t,{resolve:()=>{e(),n.startReport((()=>{}),this._ctx.handler)},reject:i}),this._sendStartPushStreamSignal(n).catch((e=>i(e)))}))}async stopPushWTN(e){var t;this._logger.print("stopPushWTN",e);const i=this._localStreams.get(e);i&&(null==(t=i.observer)||t.setLogin(!1),i.setState(WTNPushState.STOP,WTNPushStateChangedReason.STOP_PUSH),this._ctx.signalingManager.sendSignaling("stopPushStream",{appId:this._ctx.appId,streamId:e}).catch((()=>{})),await this._stopLocalStream(i))}async muteWTNLocalAudio(e,t){var i;this._logger.print("muteWTNLocalAudio",e,t);const r=this._localStreams.get(e);if(!r)throw new SDKError(ErrorCode.INVALID_PARAMS,"streamId not found");this._assertNotConnect(),r.pubAudio=!t,null==(i=r.observer)||i.setUnmuteAudio(!t),await this._updatePushStream(r)}async muteWTNLocalVideo(e,t){var i;this._logger.print("muteWTNLocalVideo",e,t);const r=this._localStreams.get(e);if(!r)throw new SDKError(ErrorCode.INVALID_PARAMS,"streamId not found");this._assertNotConnect(),null==(i=r.observer)||i.setUnmuteVideo(!t),r.pubVideo=!t,await this._updatePushStream(r)}sendWTNSEIMessage(e,t,i){this._logger.info("sendWTNSEIMessage()","streamId: %o, sei: %o, repeatCount: %o",e,t,i);const r=this._localStreams.get(e);if(!r||!r.pubVideo&&!r.pubAudio)return;if(!isLegacyEncodedTransformSupported()&&!isEncodedTransformSupported())return warnDevelopers("Your browser does not support sending SEI"),!1;checkNumber(i,"repeatCount",0,30);const o="string"==typeof t?new Uint8Array(Utils.str2ab(t)):t;if(!t.length)return this._logger.warn("sei message must not be empty"),!1;if(o.byteLength>4096)return void this._logger.warn("sei size must not bigger than 4KB");isAndroid||this._maybeFillBackFrame2Stream(r);const s=genUuid();r.sendSEIMessage({content:o,uuid:s,repeatCount:i+1}),setTimeout((async()=>{var e;if(!r)return;await r.revokeSEIMessage(s)&&(console.error("[RTC WebSDK] sei timeout for message: %o",t),null==(e=this._monitor)||e.report("rtc_sdk_callback",{sdk_callback_name:"sendSEIMessage",message:`timeout for message: ${t}`,error_code:400}))}),getParameter("SEI_TIME_OUT"))}async startPlayWTN(e,t,i,r,o=!1){await this._startPlayWTNInternal(e,t,i,r,o)}async _startPlayWTNInternal(e,t,i,r,o=!1){var s;i=!!i,r=!!r,this._logger.print("startPlayWTN",e,t,i,r),checkPublicStreamId(t),!isEmpty(e)&&checkString(e,"token");let n=this._remoteStreams.get(t);if(n){if(n.state===WTNPlayState.START||n.state===WTNPlayState.SUCCESS)throw new SDKError(ErrorCode.REPEAT_PLAY,"repeat play public media stream");await this._stopPlayWTNInternal(t)}n=new WTNRemoteStream(t,e,this._ctx,o),this._addRemoteStreamEventHandler(n),n.setState(WTNPlayState.START,WTNPlayStateChangedReason.START_PLAY),n.muteToSubMediaType(r,i),this._remoteStreams.set(t,n),null==(s=n.observer)||s.setLogin(!0,n.getEnableMediaType());try{await this._ctx.signalingManager.connect(),await new Promise(((e,i)=>{o||this._playTaskMap.set(t,{resolve:e,reject:i}),this._sendStartPullStreamSignal(n).catch((e=>i(e)))}))}catch(e){throw this._remoteStreams.delete(t),e}}async stopPlayWTN(e){await this._stopPlayWTNInternal(e)}async _stopPlayWTNInternal(e){var t,i;this._logger.print("stopPlayWTN",e);const r=this._remoteStreams.get(e);if(r)return r.setState(WTNPlayState.STOP,WTNPlayStateChangedReason.STOP_PLAY),r.setAudioState(WTNRemoteAudioState.STOPED,WTNRemoteAudioStateChangeReason.MUTE),r.setVideoState(WTNRemoteVideoState.STOPED,WTNRemoteVideoStateChangeReason.MUTE),null==(t=r.observer)||t.setLogin(!1),null==(i=null==r?void 0:r.audioTrack)||i.stop(),this._remoteStreams.delete(e),await this._ctx.signalingManager.connect(),this._unsubscribePublicStream(r)}async muteWTNRemoteAudio(e,t){var i;this._logger.print("muteWTNRemoteAudio",e,t),this._assertNotConnect();const r=this._remoteStreams.get(e);if(!r)throw new SDKError(ErrorCode.INVALID_PARAMS,"streamId not found");r.muteToSubMediaType(t,null)&&(null==(i=r.observer)||i.setUnmuteAudio(!t),await this._updatePullStream(e,r),r.setAudioState(t?WTNRemoteAudioState.STOPED:WTNRemoteAudioState.DECODING,t?WTNRemoteAudioStateChangeReason.MUTE:WTNRemoteAudioStateChangeReason.UNMUTE))}async muteWTNRemoteVideo(e,t){var i;this._logger.print("muteWTNRemoteVideo",e,t),this._assertNotConnect();const r=this._remoteStreams.get(e);if(!r)throw new SDKError(ErrorCode.INVALID_PARAMS,"streamId not found");r.muteToSubMediaType(null,t)&&(null==(i=r.observer)||i.setUnmuteVideo(!t),await this._updatePullStream(e,r),r.setVideoState(t?WTNRemoteVideoState.STOPED:WTNRemoteVideoState.DECODING,t?WTNRemoteVideoStateChangeReason.MUTE:WTNRemoteVideoStateChangeReason.UNMUTE))}setWTNRemoteVideoPlayer(e,t){var i,r;if(this._logger.print("setWTNRemoteVideoPlayer()","streamId: %o, videoPlayerOption: %o",e,t),null==(r=null==(i=this._publicVideoPlayerConfig.get(e))?void 0:i.player)||r.destroy(),!t.renderDom)return void this._publicVideoPlayerConfig.delete(e);const o=new VideoPlayer(this._ctx.id,DEFAULT_PLAYER_ID,{...t,isLocal:!1,userId:e}),s={...t,player:o};return this._publicVideoPlayerConfig.set(e,s),this._updateVideoPlayerState(e),o.domElement}setWTNRemoteAudioPlaybackVolume(e,t){var i,r;checkString(e,"publicStreamId"),t=numberRangeGuide(t,"volume",0,400),this._ctx.publicAudioVolume.set(e,t),null==(r=null==(i=this._remoteStreams.get(e))?void 0:i.audioTrack)||r.setVolume(t)}__getRemoteStreams(){return this._remoteStreams}__getPublicStreamTrack(e,t){const i=this._remoteStreams.get(e);if(i)return"video"===t?i.videoTrack:i.audioTrack}async _updatePushTrack(){0!==this._localStreams.size&&(this._logger.info("_updatePushTrack()"),await this._ctx.signalingManager.connect(),this._localStreams.forEach((async e=>{var t;e.videoTrack=this._ctx.localVideoTrack,e.audioTrack=this._ctx.localAudioTrack,null==(t=e.observer)||t.setEnableVideo(!0),await this._updatePushStream(e)})))}destroy(){var e;this._remoteStreams.forEach((e=>{e.destroy()})),this._remoteStreams=new Map,this.removeAllListeners(),this._ontrackCallbackMap.clear(),this._publicVideoPlayerConfig.forEach((e=>{e.player.destroy()})),this._publicVideoPlayerConfig.clear(),null==(e=this._clearSignalListeners)||e.call(this),this._wtnPlayLocks=new Map}async _sendStartPushStreamSignal(e){var t,i,r;this._logger.print("_sendStartPushStreamSignal()","streamId: %s",e.streamId);const{streamId:o,Authorization:s,pubAudio:n,pubVideo:a}=e,{handler:d}=this._ctx;await(null==d?void 0:d.getDefaultSdp());const c=await d.publish(e),l=await internalGetSupportedCodecs(),{appId:u,businessId:_,useCloudProxy:h}=this._ctx,p={appId:u,streamId:o,Authorization:s,sdpInfo:{msid:e.stream.id,type:c.type,sdp:c.partialSdp,semantics:c.semantics},timestamp:Date.now(),params:{appId:u,businessId:_,userAgent:window.navigator.userAgent,sdkVersion:Config2.VERSION,deviceId:sdkCache.getDeviceId(),enableCloudProxy:h,channelProfile:"0",SDKCodecNegotiation:!0,supportedCodecs:l,sdkType:"rtc",joinRoomMode:1,deviceType:"web",platformType:2,rtsMode:this._ctx.rtsMode,mediaProcessingType:Config2.MEDIA_PROCESSING_TYPE??0},options:{supportCheckTokenPrivilege:!0,supportTokenExpireCallBack:!0,enableSceneConfigV2:!0,enableUnBundleMode:!0,enableAudioMux:!0,enableBigRoomMode:!0,needNegotiateSDP:!0,supportMultiVendor:!0,enableStreamStatusCallback:!0},attributes:{localaudio:!!e.audioTrack,localvideo:!!e.videoTrack,videostream:a,audiostream:n,extvideo:(null==(t=e.videoTrack)?void 0:t.sourceType)===SourceType.EXTERNAL,extaudio:(null==(i=e.audioTrack)?void 0:i.sourceType)===SourceType.EXTERNAL,videoDescriptions:c.videoDescriptions.map((({rid:e,...t})=>t)),videoType:VideoType.NORMAL},video:a,audio:n,screen:e.isScreen,accessParams:JSON.stringify({requireICEUfragV2:!0})};let m;try{this.emit("__onSendingPushStreamMessageHook"),m=await this._ctx.signalingManager.sendSignaling("startPushStream",p)}catch(t){if(await(null==d?void 0:d.rollback({msid:e.stream.id,stream:e,audioMid:c.audioMid,videoMid:c.videoMid})),t.code>=500&&t.code<600){const i=e.getPushBackOff();if(i.retryDuration<6e4)return this._logger.info("pushRetry","start msid: %s, retryDuration: %s",e.id,i.retryDuration),await new Promise((e=>setTimeout(e,i.interval))),e.updatePushBackOff(),e.resetStream(),e.setState(WTNPushState.START,WTNPushStateChangedReason.IN_RETRY),this._sendStartPushStreamSignal(e);throw this._logger.info("pushRetry","end"),e.setState(WTNPushState.FAIL,WTNPushStateChangedReason.RETRY_FAIL),await this._stopLocalStream(e),e.resetPushBackOff(),new SDKError(ErrorCode.WTN_PUSH_FAILED,t.message||"server error")}if(401===t.code)throw e.setState(WTNPushState.FAIL,WTNPushStateChangedReason.NO_PUSH_PERMISSION),await this._stopLocalStream(e),new SDKError(ErrorCode.WTN_PUSH_FAILED,t.message||"token error");if(t.code===ErrorCode.OPERATION_CANCEL&&this._ctx.signalingManager.isReconnecting())return;throw new SDKError(ErrorCode.WTN_PUSH_FAILED,t.message||"push error")}e.pubAttributes=p.attributes;const S=await e.getSelectedCodec();e.currentVideoCodec=S;const g=new Promise(((t,i)=>{var r,s;null==d||d.handleAck({action:SdpAction.publish,streamId:o,audioMid:c.audioMid,videoMid:c.videoMid,audioTransceiverInit:null==c?void 0:c.audioTransceiverInit,videoTransceiverInit:null==c?void 0:c.videoTransceiverInit,signalingAck:{sdp:null==(r=null==m?void 0:m.relayMessage)?void 0:r.sdp,sequenceId:null==(s=null==m?void 0:m.relayMessage)?void 0:s.sequenceId},stream:e,videoCodec:S,onSuccess:()=>{this._logger.info("pushStream()","pushStream success"),e.setState(WTNPushState.SUCCESS,WTNPushStateChangedReason.PUSH_SUCCESS),t(0)},onFail:e=>{this._logger.info("pushStream()","pushStream fail"),i(e)}})}));!isFirefox&&await g,null==(r=this._pushTaskMap.get(o))||r.resolve(),this._pushTaskMap.delete(o)}async _stopLocalStream(e){var t;e.stopBlackFrame(),await(null==(t=this._ctx.handler)?void 0:t.handleAck({action:SdpAction.unpublish,audioMid:e.audioMid,videoMid:e.videoMid,stream:e,streamId:e.streamId})),e.destroy(),this._localStreams.delete(e.streamId)}async _updatePushStream(e){var t,i,r,o,s,n,a;const{videoTrack:d,audioTrack:c,pubAudio:l,pubVideo:u}=e;let _=null==(t=e.audioTrack)?void 0:t.preprocessingTrack;const h=null==(i=e.videoTrack)?void 0:i.preprocessingTrack;if(u&&h?(e.stopBlackFrame(),await(null==(r=e.videoTransceiver)?void 0:r.sender.replaceTrack(h))):await(null==(o=e.videoTransceiver)?void 0:o.sender.replaceTrack(null)),l&&_){const{mixType:t,mixedAudioTrack:i}=e.audioTrack;i&&t!==AudioMixingType.PLAYOUT&&_.enabled&&(_=i),await(null==(s=e.audioTransceiver)?void 0:s.sender.replaceTrack(_))}else await(null==(n=e.audioTransceiver)?void 0:n.sender.replaceTrack(null));const p={localaudio:!!c,localvideo:!!d,videostream:u,audiostream:l,extvideo:(null==d?void 0:d.sourceType)===SourceType.EXTERNAL,extaudio:(null==c?void 0:c.sourceType)===SourceType.EXTERNAL,videoType:d?VideoType.NORMAL:e.pubAttributes.videoType},m={};for(const[t,i]of Object.entries(p))i!==Reflect.get(e.pubAttributes,t)&&Reflect.set(m,t,i);Object.keys(m).length&&(e.pubAudio=p.audiostream??e.pubAudio,e.pubVideo=p.videostream??e.pubVideo,e.pubAttributes={...e.pubAttributes,...p},e.pubAttributes.videostream||e.stopBlackFrame(),await this._ctx.signalingManager.sendSignaling("updatePushStream",{appId:this._ctx.appId,streamId:e.streamId,attributes:p}),isFirefox&&await(null==(a=this._ctx.handler)?void 0:a.setCurrentDescription()))}async _sendStartPullStreamSignal(e){var t,i,r,o;this._logger.print("startPullStream()","streamId:",e.streamId);const{streamId:s,Authorization:n}=e,{handler:a}=this._ctx,d=await(null==a?void 0:a.subscribe(e,{multiChatMode:!1}));if(!d)throw new SDKError(ErrorCode.ADD_TRANSCEIVER_FAILED,"add transceiver failed");const c=getServerNow(),{audioMid:l,videoMid:u}=d,{appId:_,businessId:h,useCloudProxy:p}=this._ctx,m=await internalGetSupportedCodecs(),S={appId:_,streamId:s,Authorization:n,audio:!0,video:!0,screen:!1,timestamp:Date.now(),sdpInfo:{sdp:d.partialSdp,semantics:d.semantics,type:d.type},params:{appId:_,businessId:h,userAgent:window.navigator.userAgent,sdkVersion:Config2.VERSION,deviceId:sdkCache.getDeviceId(),enableCloudProxy:p,channelProfile:"0",SDKCodecNegotiation:!0,supportedCodecs:m,sdkType:"rtc",joinRoomMode:1,deviceType:"web",platformType:2,rtsMode:this._ctx.rtsMode,mediaProcessingType:Config2.MEDIA_PROCESSING_TYPE??0},options:{supportCheckTokenPrivilege:!0,supportTokenExpireCallBack:!0,enableSceneConfigV2:!0,enableUnBundleMode:!0,enableAudioMux:!0,enableBigRoomMode:!0,needNegotiateSDP:!0,supportMultiVendor:!0,enableStreamStatusCallback:!0},config:{enableMediaType:e.getEnableMediaType(),qualityLayer:{spatialLayer:0,temporalLayer:0}},accessParams:JSON.stringify({requireICEUfragV2:!0}),extra:{enableSendRTT:!0}};let g;try{this.emit("__onSendingPullStreamMessageHook"),g=await this._ctx.signalingManager.sendSignaling("startPullStream",S)}catch(t){if(await(null==a?void 0:a.rollback({msid:s,stream:e}).catch((()=>{}))),401===t.code)throw e.setState(WTNPlayState.FAIL,WTNPlayStateChangedReason.NO_PLAY_PERMISSION),new SDKError(ErrorCode.WTN_PLAY_FAILED,t.message||"token error");if(433===t.code)throw e.setState(WTNPlayState.FAIL,WTNPlayStateChangedReason.OVER_CLIENT_SUBSCRIBE_STREAM_LIMIT),new SDKError(ErrorCode.WTN_PLAY_FAILED,t.message||"over client subscribe stream limit");if(434===t.code)throw e.setState(WTNPlayState.FAIL,WTNPlayStateChangedReason.OVER_STREAM_SUBSCRIBE_USER_LIMIT),new SDKError(ErrorCode.WTN_PLAY_FAILED,t.message||"over stream subscribe user limit");if(t.code===ErrorCode.OPERATION_CANCEL&&this._ctx.signalingManager.isReconnecting())return;throw e.setState(WTNPlayState.FAIL,WTNPlayStateChangedReason.INTERNAL),new SDKError(ErrorCode.WTN_PLAY_FAILED,t.message||"play wtn error")}const v=[];v.push(new Promise(((t,i)=>{const r=setTimeout((()=>i(new SDKError(ErrorCode.WTN_PLAY_FAILED,`wait video timeout for streamId: ${s}`))),6e4),o=i=>{"video"===i.mediaType&&(this._logger.success(`remoteStream ${e.userId} received video track`),e.off("ontrack",o),clearTimeout(r),t(0))};e.on("ontrack",o)}))),v.push(new Promise(((t,i)=>{const r=setTimeout((()=>i(new SDKError(ErrorCode.WTN_PLAY_FAILED,`wait audio timeout for streamId: ${s}`))),6e4),o=i=>{"audio"===i.mediaType&&(this._logger.success(`remoteStream ${e.userId} received audio track`),e.off("ontrack",o),clearTimeout(r),t(0))};e.on("ontrack",o)})));const f=t=>{e.ontrack(t)};null==(t=this._ctx.handler)||t.on("ontrack",f),this._ontrackCallbackMap.set(e,f);const{sequenceId:E,sdp:T}=g.relayMessage;e.videoMid=u,e.audioMid=l,e.sequenceId=E,e.streamState=StreamState.SUB_ED,await(null==(i=this._ctx.handler)?void 0:i.handleAck({action:SdpAction.subscribe,streamId:s,audioMid:l,videoMid:u,audioTransceiverInit:d.audioTransceiverInit,videoTransceiverInit:d.videoTransceiverInit,signalingAck:{sdp:T,sequenceId:E},stream:e})),await Promise.all(v),null==(r=this._monitor)||r.report("rtc_subscribe_stat",{result:"success",start:c,message:"unknown",stream_user_id:e.userId}),e.startReport((t=>{var i;t.publicStreamId=t.userId,delete t.userId,delete t.isScreen;const r=getPublicStats(t);r.audioStats&&this.safeEmit(WTNStreamEventsTypes.onWTNRemoteAudioStats,{streamId:e.streamId,audioStats:r.audioStats}),r.videoStats&&this.safeEmit(WTNStreamEventsTypes.onWTNRemoteVideoStats,{streamId:e.streamId,videoStats:r.videoStats}),null==(i=this.__onRemoteStreamStats)||i.call(this,r)}),this._ctx.handler),this._updateVideoPlayerState(s),this._initAudioPlayer(s),e.subVideo=e.getEnableMediaType().video,e.subAudio=e.getEnableMediaType().audio,null==(o=this._playTaskMap.get(s))||o.resolve(),this._playTaskMap.delete(s)}async _unsubscribePublicStream(e){var t;logRemoteStream("_unsubscribePublicStream()",e,this._logger);const i={appId:this._ctx.appId,streamId:e.streamId};try{await this._ctx.signalingManager.sendSignaling("stopPullStream",i)}catch(e){}e.streamState=StreamState.INIT,await(null==(t=this._ctx.handler)?void 0:t.handleAck({action:SdpAction.unsubscribe,streamId:e.streamId,audioMid:e.audioMid,videoMid:e.videoMid,stream:e})),e.subMediaType=ExtendMediaType.NONE,this._removeOnTrackListener(e),e.statsReport.unsubscribe(),e.destroy()}async _updatePullStream(e,t){const i=t.getEnableMediaType();await this._ctx.signalingManager.sendSignaling("updatePullStream",{appId:this._ctx.appId,streamId:e,config:{enableMediaType:i}}),t.subVideo=i.video,t.subAudio=i.audio}_removeOnTrackListener(e){const t=this._ontrackCallbackMap.get(e);if(t){const i=e.vendorHandler||this._ctx.handler;null==i||i.off("ontrack",t),this._ontrackCallbackMap.delete(e)}}_addSignalListeners(){const e={[StateEvent.ON_CONNECTION_STATE_CHANGE]:e=>{e.state===ConnectionState.CONNECTION_STATE_RECONNECTED?(Array.from(this._remoteStreams.values()).forEach((e=>{const{streamId:t,token:i}=e,{audio:r,video:o}=e.getEnableMediaType();e.destroy(),this._remoteStreams.delete(t),this._startPlayWTNInternal(i,t,!o,!r,!0).then((()=>{var t;null==(t=this.__onResubscribe)||t.call(this,{stream:e})}))})),Array.from(this._localStreams.values()).forEach((e=>{const{token:t,pubAudio:i,pubVideo:r}=e;e.destroy(),this._localStreams.delete(e.streamId),this.startPushWTN(t,e.streamId,!r,!i,!0)}))):e.state===ConnectionState.CONNECTION_STATE_DISCONNECTED&&(this._remoteStreams.forEach((e=>{e.setState(WTNPlayState.FAIL,WTNPlayStateChangedReason.IN_RETRY),e.setAudioState(WTNRemoteAudioState.FROZEN,WTNRemoteAudioStateChangeReason.NETWORK_CONGESTION),e.setVideoState(WTNRemoteVideoState.FROZEN,WTNRemoteVideoStateChangeReason.NETWORK_CONGESTION)})),this._localStreams.forEach((e=>{e.setState(WTNPushState.FAIL,WTNPushStateChangedReason.IN_RETRY)})))},[SignalEvent.ON_STREAM_PUSHED_BY_OTHER]:e=>{const t=this._localStreams.get(e.streamId);this._logger.print("_addSignalListeners","onStreamPushedByOther",e.streamId),t&&(t.setState(WTNPushState.FAIL,WTNPushStateChangedReason.STREAM_PUSH_BY_OTHER),this._stopLocalStream(t))},[SignalEvent.ON_STREAM_PULL_STATE_CHANGED]:async e=>{var t,i;const r=this._remoteStreams.get(e.streamId);if(this._logger.print("_addSignalListeners","onStreamPullStateChanged",e),r)switch(e.code){case 0:r.setState(WTNPlayState.SUCCESS,WTNPlayStateChangedReason.PLAY_SUCCESS);break;case 1:case 2:case 3:const o={1:WTNPlayStateChangedReason.STREAM_NOT_EXIST,2:WTNPlayStateChangedReason.REMOTE_STOP,3:WTNPlayStateChangedReason.REMOTE_FAILURE}[e.code];r.setAudioState(WTNRemoteAudioState.STOPED,WTNRemoteAudioStateChangeReason.REMOTE_STOP),r.setVideoState(WTNRemoteVideoState.STOPED,WTNRemoteVideoStateChangeReason.REMOTE_STOP),r.setState(WTNPlayState.FAIL,o);break;case 4:const s=r.getPushBackOff();s.retryDuration<6e4?(this._logger.info("subRetry",r.streamId,s.retryDuration),r.setState(WTNPlayState.START,WTNPlayStateChangedReason.IN_RETRY),await new Promise((e=>setTimeout(e,s.interval))),r.updatePushBackOff(),await(null==(i=null==(t=this._ctx)?void 0:t.handler)?void 0:i.handleAck({action:SdpAction.unsubscribe,streamId:r.streamId,audioMid:r.audioMid,videoMid:r.videoMid,stream:r})),r.clean(),await this._sendStartPullStreamSignal(r)):(r.setState(WTNPlayState.FAIL,WTNPlayStateChangedReason.RETRY_FAIL),this._logger.info("subRetry","end",r.streamId),r.resetPushBackOff())}},[MediaServerSignalEvent.RTT]:e=>{const{StreamIds:t,Metadata:i}=e;if((null==t?void 0:t.length)&&i){const e=t[0];this._ctx.streamRTT[e]={audio:i.audio_rtt,video:i.video_rtt}}}};Object.keys(e).forEach((t=>{this._ctx.signalingManager.on(t,e[t])})),this._clearSignalListeners=()=>{Object.keys(e).forEach((t=>{this._ctx.signalingManager.off(t,e[t])}))}}_addLocalStreamEventHandler(e){e.on(WTNStreamEventsTypes.onWTNPushStateChanged,(e=>{this.safeEmit(WTNStreamEventsTypes.onWTNPushStateChanged,e)}))}_addRemoteStreamEventHandler(e){e.on(WTNStreamEventsTypes.onWTNPlayStateChanged,(e=>{this.safeEmit(WTNStreamEventsTypes.onWTNPlayStateChanged,e)})),e.on(WTNStreamEventsTypes.onWTNRemoteAudioStateChanged,(e=>{this.safeEmit(WTNStreamEventsTypes.onWTNRemoteAudioStateChanged,e)})),e.on(WTNStreamEventsTypes.onWTNRemoteVideoStateChanged,(e=>{this.safeEmit(WTNStreamEventsTypes.onWTNRemoteVideoStateChanged,e)})),e.on("onSEIMessage",(t=>{var i;if(t instanceof Uint8Array){const r=splitPublicStreamSei(t);for(let t=0;t<r.seiCount;t++)null==(i=this.__onSEIMessageReceived)||i.call(this,{sei:r.seis[t],publicStreamId:e.streamId}),this.safeEmit(WTNStreamEventsTypes.onWTNSEIMessageReceived,{streamId:e.streamId,sei:r.seis[t]})}}))}_updateVideoPlayerState(e){var t,i;const r=this._remoteStreams.get(e);if(r){const o=this._publicVideoPlayerConfig.get(e);o&&(null==(i=r.videoTrack)||i.setPlayer(this._ctx.id,o,null==(t=this._ctx)?void 0:t.autoPlayPolicy,this._initPlayerEvents.bind(this)))}}_initAudioPlayer(e){var t,i;const r=this._remoteStreams.get(e);if(null==r?void 0:r.audioTrack){const o=new AudioPlayer(this._ctx.id,e,{muted:(null==(t=this._ctx)?void 0:t.autoPlayPolicy)===RTCAutoPlayPolicy.VIDEO_ONLY||(null==(i=this._ctx)?void 0:i.autoPlayPolicy)===RTCAutoPlayPolicy.PLAY_MANUALLY,isScreen:!1});r.audioTrack.setPlayer(o),r.audioTrack.bindPlayerEvent(this._initPlayerEvents.bind(this)),r.audioTrack.play()}}_initPlayerEvents(e,t=!1,i=StreamIndex$1.STREAM_INDEX_MAIN){var r;null==(r=this.__onPlayerEvents)||r.call(this,e,t,i),e.on("playback_event",(t=>{const i=this._remoteStreams.get(e.userId);if("loadeddata"===t.eventName){const e=()=>{i&&"video"===t.type&&this.safeEmit(WTNStreamEventsTypes.onWTNFirstRemoteVideoFrameDecoded,{streamId:i.streamId})};!(null==i?void 0:i.observer)||i.observer.audioFirstFrameReceived?e():i.observer.once("recvVideoFirstFrame",e)}}))}async _maybeFillBackFrame2Stream(e){var t,i,r;if(e.refreshBlackFrameLifetime(),!(null==(t=e.videoTransceiver)?void 0:t.sender.track)){const t=e.genBlackFrame();if(!t)return;null==(r=null==(i=e.videoTransceiver)?void 0:i.sender)||r.replaceTrack(t),e.pubAttributes.videoType=VideoType.BLACK,this._ctx.signalingManager.sendSignaling("updatePushStream",{streamId:e.streamId,appId:this._ctx.appId,attributes:{videoType:VideoType.BLACK}}),e.on("black-frame-ended",(()=>{var t,i;null==(i=null==(t=e.videoTransceiver)?void 0:t.sender)||i.replaceTrack(null),e.pubAttributes.videoType=VideoType.NORMAL,this._ctx.signalingManager.sendSignaling("updatePushStream",{streamId:e.streamId,appId:this._ctx.appId,attributes:{videoType:VideoType.NORMAL}})}))}}safeEmit(e,...t){return reportRtcSdkCallback(this._ctx.id,e,t),super.safeEmit(e,...t)}_assertNotConnect(){if(!this._ctx.signalingManager.isConnected())throw new SDKError(ErrorCode.NOT_CONNECTED_YET,"server not connected")}getWTNPlayLock(e){let t=this._wtnPlayLocks.get(e);return t||(t=new PromiseLock2(`wtn_play_${e}`),this._wtnPlayLocks.set(e,t)),t}}function wtnPlayLock(e,t,i){const r=i.value;return i.value=async function(...e){let i="";"startPlayWTN"===t?i=e[1]:"stopPlayWTN"===t&&(i=e[0]);const o=await this.getWTNPlayLock(i).lock();try{return await r.apply(this,e)}finally{o()}},i}__decorateClass$2([reportRtcSdkApi()],WTNStream.prototype,"startPushWTN",1),__decorateClass$2([reportRtcSdkApi()],WTNStream.prototype,"stopPushWTN",1),__decorateClass$2([reportRtcSdkApi()],WTNStream.prototype,"muteWTNLocalAudio",1),__decorateClass$2([reportRtcSdkApi()],WTNStream.prototype,"muteWTNLocalVideo",1),__decorateClass$2([reportRtcSdkApi()],WTNStream.prototype,"sendWTNSEIMessage",1),__decorateClass$2([reportRtcSdkApi(),wtnPlayLock],WTNStream.prototype,"startPlayWTN",1),__decorateClass$2([reportRtcSdkApi(),wtnPlayLock],WTNStream.prototype,"stopPlayWTN",1),__decorateClass$2([reportRtcSdkApi()],WTNStream.prototype,"muteWTNRemoteAudio",1),__decorateClass$2([reportRtcSdkApi()],WTNStream.prototype,"muteWTNRemoteVideo",1),__decorateClass$2([reportRtcSdkApi()],WTNStream.prototype,"setWTNRemoteVideoPlayer",1),__decorateClass$2([reportRtcSdkApi()],WTNStream.prototype,"setWTNRemoteAudioPlaybackVolume",1),__decorateClass$2([pubSubLock],WTNStream.prototype,"_sendStartPushStreamSignal",1),__decorateClass$2([pubSubLock],WTNStream.prototype,"_stopLocalStream",1),__decorateClass$2([pubSubLock],WTNStream.prototype,"_sendStartPullStreamSignal",1),__decorateClass$2([pubSubLock],WTNStream.prototype,"_unsubscribePublicStream",1);const MAX_RECORDER_DURATION=3e4,logger$1=new Logger$1("AudioDeviceManager",1);class AudioDeviceManager extends eventemitter3Exports.EventEmitter{constructor(e){super(),__publicField(this,"_audioLevelFetcher"),__publicField(this,"_playbackDeviceTestTimer"),__publicField(this,"_audioElement"),__publicField(this,"_audioTrack"),__publicField(this,"_mediaRecorder"),__publicField(this,"_recoderTimer"),__publicField(this,"_isAudioPlaybackDeviceTesting",!1),__publicField(this,"_isAudioDeviceRecordTesting",!1),__publicField(this,"_audioCaptureAndRecoderResolve"),__publicField(this,"_onAutoplayFailed"),__publicField(this,"_audioPlaybackDeviceId"),this._ctx=e}get audioTrack(){return this._audioTrack}async startAudioPlaybackDeviceTest(e,t){if(this._isAudioPlaybackDeviceTesting||this._isAudioDeviceRecordTesting)throw new SDKError(ErrorCode.REPEAT_DEVICE_TEST,"device test cannot be called repeatedly at the same time.");this._isAudioPlaybackDeviceTesting=!0,logger$1.info("startAudioPlaybackDeviceTest()","Invoke");try{await this._playAudioFile(e,{loop:!0})}catch(e){throw logger$1.error("startAudioPlaybackDeviceTest()","error",e),this.stopAudioPlaybackDeviceTest(),e}this._startEmitAudioPlaybackDeviceTestVolume(t)}stopAudioPlaybackDeviceTest(){this._isAudioPlaybackDeviceTesting&&(logger$1.info("stopAudioPlaybackDeviceTest()","Invoke"),this._isAudioPlaybackDeviceTesting=!1,this._stopEmitAudioPlaybackDeviceTestVolume(),this._destroyAudioElement())}async startAudioDeviceRecordTest(e,t,i,r=3e4){if(!window.MediaRecorder)throw new SDKError(ErrorCode.NOT_SUPPORTED,"Your browser does not support MediaRecorder.");if(this._isAudioDeviceRecordTesting||this._isAudioPlaybackDeviceTesting)throw new SDKError(ErrorCode.REPEAT_DEVICE_TEST,"device test cannot be called repeatedly at the same time.");this._isAudioDeviceRecordTesting=!0,logger$1.info("startAudioDeviceRecordTest()","Invoke"),this._recoderTimer=setTimeout((()=>{logger$1.info("startAudioDeviceRecordTest()",`${r}ms automatic call method "stopAudioDeviceRecordAndPlayTest"`),this._stopAudioCaptureAndRecoder()}),r);try{this._onAutoplayFailed=t,await this._startAudioCaptureAndRecoder(e,i??100)}catch(e){throw this._isAudioDeviceRecordTesting=!1,delete this._onAutoplayFailed,e}delete this._audioCaptureAndRecoderResolve}stopAudioDeviceRecordAndPlayTest(){logger$1.info("stopAudioDeviceRecordAndPlayTest()","Invoke"),void 0!==this._recoderTimer&&(clearTimeout(this._recoderTimer),delete this._recoderTimer),this._stopAudioCaptureAndRecoder()}stopAudioDevicePlayTest(){this._isAudioDeviceRecordTesting&&(logger$1.info("stopAudioDevicePlayTest()","Invoke"),this._isAudioDeviceRecordTesting=!1,this._mediaRecorder&&(this._mediaRecorder.ondataavailable=null),this.stopAudioDeviceRecordAndPlayTest(),this._stopEmitAudioPlaybackDeviceTestVolume(),this._destroyAudioElement()),delete this._onAutoplayFailed}getRecordTrack(){return this._audioTrack}async setSinkId(e){if(logger$1.info("setSinkId()","Invoke"),void 0===HTMLAudioElement.prototype.setSinkId)throw new SDKError(ErrorCode.NOT_SUPPORTED,"setSinkId not supported by current browser");const t=await dd.getAudioPlaybackDeviceById(e);if(!t)throw new SDKError(ErrorCode.INVALID_DEVICE_ID,`audio playback device id ${e} is invalid`);return this._audioPlaybackDeviceId=e,this._setAudioCtxSinkId(),t}getSinkId(){return this._audioPlaybackDeviceId}destroy(){logger$1.info("destroy()","Invoke"),super.removeAllListeners(),this.stopAudioPlaybackDeviceTest(),this.stopAudioDevicePlayTest()}async _playAudioFile(e,t){return logger$1.info("_playAudioFile()",`Invoke url=${e}; loop=${t.loop}`),new Promise(((i,r)=>{const o=createElement("audio",{attributes:{src:e,crossOrigin:"anonymous"}});this._audioElement=o,o.loop=t.loop,this._audioLevelFetcher=new AudioLevelFetcher(o),o.onplaying=()=>{o.onplaying=null,logger$1.info("_playAudioFile()","onplaying"),i()},o.onerror=async e=>{var t;logger$1.error("_playAudioFile()","onerror",e);const i=e.message||(null==(t=null==o?void 0:o.error)?void 0:t.message);r(new SDKError(ErrorCode.LOAD_RESOURCES_FAILED,"Failed to play recorded audio"+(i?`, reason: ${i}`:".")))},this._setAudioCtxSinkId().then((()=>{var e,t;return null==(t=null==(e=o.play())?void 0:e.catch)?void 0:t.call(e,(e=>{logger$1.warn("_playAudioFile()","autoplay error",e);const t=`Failed to play recorded audio, ${e.name}: ${e.message}`;"NotAllowedError"===e.name&&this._onAutoplayFailed?this._onAutoplayFailed((()=>{var e;return Promise.all([null==(e=this._audioLevelFetcher)?void 0:e.resume(),o.play()])})):r(new SDKError(ErrorCode.LOAD_RESOURCES_FAILED,t))}))}))}))}_destroyAudioElement(){this._audioElement&&(logger$1.info("_destroyAudioElement()","Invoke"),this._audioElement.onplaying=null,this._audioElement.onerror=null,this._audioElement.src="",delete this._audioElement,"function"==typeof this._audioCaptureAndRecoderResolve&&this._audioCaptureAndRecoderResolve())}_startEmitAudioPlaybackDeviceTestVolume(e){e=Math.max(e,100),this._audioElement&&(logger$1.info("_startEmitAudioPlaybackDeviceTestVolume()",`start timer(${e}ms)`),this._playbackDeviceTestTimer=self.setInterval((()=>{this._audioLevelFetcher&&this.emit("onAudioPlaybackDeviceTestVolume",this._audioLevelFetcher.getAudioLevel())}),e))}_stopEmitAudioPlaybackDeviceTestVolume(){var e;void 0!==this._playbackDeviceTestTimer&&(logger$1.info("_stopEmitAudioPlaybackDeviceTestVolume()","stop timer"),self.clearInterval(this._playbackDeviceTestTimer),delete this._playbackDeviceTestTimer),null==(e=this._audioLevelFetcher)||e.destroy(),delete this._audioLevelFetcher}async _startAudioCaptureAndRecoder(e,t){this._audioTrack=await createMicrophoneAudioTrack(this._ctx,this._ctx.audioProfileManager.getConstraints()),this._audioTrack.setVolume(t+.01);const i=new MediaStream([this._audioTrack.preprocessingTrack]);return logger$1.info("startAudioDeviceRecordTest()","create microphone track success!"),new Promise(((t,r)=>{let o;"function"==typeof MediaRecorder.isTypeSupported&&(o=["audio/webm","audio/mp4"].find((e=>MediaRecorder.isTypeSupported(e))),logger$1.info("startAudioDeviceRecordTest()",`use mimeType: ${o}`)),this._mediaRecorder=new MediaRecorder(i,o?{mimeType:o}:void 0);const s=this._mediaRecorder.mimeType;this._mediaRecorder.ondataavailable=async i=>{var o;if(this._isAudioDeviceRecordTesting){logger$1.info("startAudioDeviceRecordTest()",`get recorded file(mimeType: ${s}).`);const n=new Blob([i.data],{type:s});try{await this._playAudioFile(URL.createObjectURL(n),{loop:!1})}catch(e){return r(e)}this._startEmitAudioPlaybackDeviceTestVolume(e),null==(o=this._audioElement)||o.addEventListener("ended",(()=>{this.stopAudioDevicePlayTest(),t()})),this._audioCaptureAndRecoderResolve=t}else t()},this._mediaRecorder.onerror=e=>{r(new SDKError(ErrorCode.AUDIO_DEVICE_TEST_FAILED,e.message||"mediaRecorder error"))},this._audioCaptureAndRecoderResolve=t,this._mediaRecorder.start()}))}_stopAudioCaptureAndRecoder(){var e;this._mediaRecorder&&("recording"===this._mediaRecorder.state&&this._mediaRecorder.stop(),delete this._mediaRecorder),null==(e=this._audioTrack)||e.destroy(),delete this._audioTrack}async _setAudioCtxSinkId(){var e,t;let i=this._audioPlaybackDeviceId;if(i){"default"===i&&(i="");try{null==(t=null==(e=audioContextManager.getAudioContextInstance())?void 0:e.setSinkId)||t.call(e,i),logger$1.info("setSinkId",`ctx.sinkId=${i}`)}catch(e){logger$1.error("setSinkId",`failed, ${e.name} - ${e.message}`)}}}}const getDefaultValue=()=>({url:"",video:{codec:TRANSCODING_VIDEO_CODEC.H264,width:640,height:360,fps:15,gop:2,kBitRate:getKBitRate(640,360,15)},audio:{codec:"AAC",kBitRate:64,sampleRate:48e3,channels:2,AACProfile:AAC_PROFILE.LC},layout:{regions:[],appData:"",backgroundColor:"#000000"}});function getKBitRate(e,t,i){return e*t<=288e3?i<=15?800:1200:e*t<=864e3?i<=15?1200:1800:e*t<=1152e3?i<=15?1600:2400:e*t<=2592e3?i<=15?2500:3750:i<=15?3300:5e3}function checkRtmpUrl(e){if("string"!=typeof e||!/^rtmps?:\/\//.test(e))throw new SDKError(ErrorCode.INVALID_PARAMS,"Invalid rtmp address")}function checkTranscodeRegions(e=[]){if(!(null==e?void 0:e.length))throw new SDKError(ErrorCode.INVALID_PARAMS,"regions should not be empty.");for(const t of e){if("string"!=typeof t.userId)throw new SDKError(ErrorCode.INVALID_PARAMS,`region.userId(${t.userId}) should be a string.`);if(checkUserId(t.userId),"boolean"!=typeof t.isScreenStream)throw new SDKError(ErrorCode.INVALID_PARAMS,`region.isScreenStream(${t.isScreenStream}) should be a boolean.`)}}function getTranscodeControlMessage(e,t){var i,r,o;const s=(e,i)=>{const r=e.reduce(((e,t)=>null==e?void 0:e[t]),t),o=e.reduce(((e,t)=>null==e?void 0:e[t]),getDefaultValue());return r&&i(r)?r:o},n=e=>e%2==0?e:e+1,a=n(s(["video","width"],(e=>e>=2&&e<=1920))),d=n(s(["video","height"],(e=>e>=2&&e<=1920))),c=s(["video","fps"],(e=>e>=1&&e<=60)),l=(null==(i=t.video)?void 0:i.kBitRate)||0,u=s(["audio","sampleRate"],(e=>!![32e3,44100,48e3].find((t=>t===e||t/1e3===e))));return{type:"transcode",action:e,transcodeMeta:{transcode:{url:t.url},control:{protocol:"2.0"},audio:{codec:s(["audio","codec"],(e=>"AAC"===e)),bitRate:1e3*s(["audio","kBitRate"],(e=>e>=32&&e<=192)),sampleRate:u<100?1e3*u:u,channels:s(["audio","channels"],(e=>[1,2].includes(e))),profile:s(["audio","AACProfile"],(e=>[AAC_PROFILE.LC,AAC_PROFILE.HEv1,AAC_PROFILE.HEv2].includes(e)))},video:{codec:s(["video","codec"],(e=>["H264","H265"].includes(e))),fps:c,gop:s(["video","gop"],(e=>e>=1&&e<=5))*c,bitRate:1e3*(l>=16&&l<=1e4?l:getKBitRate(a,d,c)),width:a,height:d},layout:{canvas:{bgnd:s(["layout","backgroundColor"],(e=>/^#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})$/.test(e)))},regions:(null==(o=null==(r=t.layout)?void 0:r.regions)?void 0:o.map((e=>({alpha:!e.alpha||Number(e.alpha)>1||Number(e.alpha)<=0?1:Number(e.alpha),uid:e.userId,zorder:!e.zorder||Number(e.zorder)<0||Number(e.zorder)>100?0:Number(e.zorder),x:!e.x||Number(e.x)>=1||Number(e.x)<0?0:Number(e.x),y:!e.y||Number(e.y)>=1||Number(e.y)<0?0:Number(e.y),w:!e.w||Number(e.w)>1||Number(e.w)<=0?1:Number(e.w),h:!e.h||Number(e.h)>1||Number(e.h)<=0?1:Number(e.h),renderMode:e.renderMode&&[1,2,3].includes(e.renderMode)?e.renderMode:1,contentControl:e.contentControl&&[0,1,2].includes(e.contentControl)?e.contentControl:0,screen:!!e.isScreenStream}))))||[],app_data:s(["layout","appData"],(e=>"string"==typeof e))}}}}function checkStartParams(e){var t;checkRtmpUrl(e.url),checkTranscodeRegions(null==(t=e.layout)?void 0:t.regions)}function checkUpdateParams(e){var t;e.url&&checkRtmpUrl(e.url),checkTranscodeRegions(null==(t=e.layout)?void 0:t.regions)}function getStartParams(e){return getTranscodeControlMessage("started",e)}function getUpdateParams(e){return getTranscodeControlMessage("layoutChanged",e)}const LiveTranscoding={getDefaultValue:getDefaultValue,checkStartParams:checkStartParams,checkUpdateParams:checkUpdateParams,getStartParams:getStartParams,getUpdateParams:getUpdateParams};let remoteAudioReplayTimer;const replayRemoteAudioWorkaround=e=>{remoteAudioReplayTimer&&clearTimeout(remoteAudioReplayTimer),remoteAudioReplayTimer=setTimeout((()=>{for(const[t,i]of e)(null==t?void 0:t.startsWith("mux"))&&i.forEach((e=>{var t;null==(t=e.audioTrack)||t.pause()}));for(const[t,i]of e)(null==t?void 0:t.startsWith("mux"))&&i.forEach((e=>{var t;null==(t=e.audioTrack)||t.play()}))}),2e3)},MEDIA_STATES=["currentTime","duration","ended","error","muted","networkState","paused","readyState","seekable","sinkId","src","volume"],AUDIOCONTEXT_STATES=["currentTime","sampleRate","state","baseLatency","outputLatency","sinkId"],TRACK_STATES=["contentHint","enabled","id","kind","label","muted","readyState"],TRANSCEIVER_STATES=["currentDirection","direction","mid","stopped"];let ac;async function getStats(e){const t=Date.now();let i=[];e._ctx.handler&&e._ctx.handler._peerConnection&&(i=await e._ctx.handler._peerConnection.getStats());const r=[];return i.forEach((e=>{r.push(e)})),{timestamp:t,stats:r}}function formatSrcObject(e){const t={};if(e instanceof MediaStream){t.id=e.id,t.active=e.active;const i=e.getTracks();t.tracks=i.map((e=>Object.fromEntries(TRACK_STATES.map((t=>[t,e[t]])))))}return t}async function getMediaElementState(e){var t;const i=Date.now(),r=[];e._videoPlayer&&r.push({userId:"__local__",mediaType:"video",isScreen:!1,isPublic:!1,ele:e._videoPlayer._videoDom}),e._screenPlayer&&r.push({userId:"__local__",mediaType:"video",isScreen:!0,isPublic:!1,ele:e._screenPlayer._videoDom}),e._remoteVideoPlayer&&e._remoteVideoPlayer.forEach(((e,t)=>{r.push({userId:t,mediaType:"video",isScreen:!1,isPublic:!1,ele:e?e._videoDom:void 0})})),e._remoteScreenPlayer&&(null==(t=e._remoteScreenPlayer)||t.forEach(((e,t)=>{r.push({userId:t,mediaType:"video",isScreen:!0,isPublic:!1,ele:e?e._videoDom:void 0})}))),e._remoteAudioPlayer&&e._remoteAudioPlayer.forEach(((e,t)=>{r.push({userId:t,mediaType:"audio",isScreen:!1,isPublic:!1,ele:e?e._audioDom:void 0,fakeEle:e?e._fakeAudioDom:void 0})})),e._remoteScreenAudioPlayer&&e._remoteScreenAudioPlayer.forEach(((e,t)=>{r.push({userId:t,mediaType:"audio",isScreen:!0,isPublic:!1,ele:e?e._audioDom:void 0,fakeEle:e?e._fakeAudioDom:void 0})})),e._publicStreamVideoPlayer&&e._publicStreamVideoPlayer.forEach(((e,t)=>{r.push({userId:t,mediaType:"video",isScreen:!1,isPublic:!0,ele:e?e._videoDom:void 0})})),e._publicStreamAudioPlayer&&e._publicStreamAudioPlayer.forEach(((e,t)=>{r.push({userId:t,mediaType:"audio",isScreen:!1,isPublic:!0,ele:e?e._audioDom:void 0,fakeEle:e?e._fakeAudioDom:void 0})})),e._localVideoTrack&&e._localVideoTrack.videoPlayers&&e._localVideoTrack.videoPlayers.forEach(((e,t)=>{r.push({playerId:t.toString(),userId:"__local__",mediaType:"video",isScreen:!1,isPublic:!1,ele:e._videoDom})})),e._localScreenTrack&&e._localScreenTrack.videoPlayers&&e._localScreenTrack.videoPlayers.forEach(((e,t)=>{r.push({playerId:t.toString(),userId:"__local__",mediaType:"video",isScreen:!0,isPublic:!1,ele:e._videoDom})})),e._room&&e._room._remoteStreams&&e._room._remoteStreams.forEach(((e,t)=>{e.forEach((e=>{if(e.audioTrack){const i=e.audioTrack._audioPlayer;r.push({userId:t,mediaType:"audio",isScreen:e.isScreen,isPublic:!1,ele:i?i._audioDom:void 0,fakeEle:i?i._fakeAudioDom:void 0})}e.videoTrack&&e.videoTrack.videoPlayers&&e.videoTrack.videoPlayers.forEach(((i,o)=>{r.push({playerId:o.toString(),userId:t,mediaType:"video",isScreen:e.isScreen,isPublic:!1,ele:i?i._videoDom:void 0})}))}))}));let o=e._publicStreamManager;o||(o=e._outsideRoom),o&&o.remoteStreams&&o.remoteStreams.forEach(((e,t)=>{if(e.audioTrack){const i=e.audioTrack._audioPlayer;r.push({userId:t,mediaType:"audio",isScreen:!1,isPublic:!0,ele:i?i._audioDom:void 0,fakeEle:i?i._fakeAudioDom:void 0})}e.videoTrack&&e.videoTrack.videoPlayers&&e.videoTrack.videoPlayers.forEach(((e,i)=>{r.push({playerId:i.toString(),userId:t,mediaType:"video",isScreen:!1,isPublic:!0,ele:e?e._videoDom:void 0})}))})),e&&e._room&&e._room._virtualStreams&&e._room._virtualStreams.forEach(((e,t)=>{if(e.audioTrack){const i=e.audioTrack._audioPlayer;r.push({userId:`virtualStream-${t}`,mediaType:"audio",isScreen:!1,isPublic:!1,isVirtual:!0,ele:i?i._audioDom:void 0,fakeEle:i?i._fakeAudioDom:void 0})}}));return{timestamp:i,elementStats:r.map((({ele:e,fakeEle:t,...i})=>{const r={ele:{srcObject:e?formatSrcObject(e.srcObject):void 0,...Object.fromEntries(MEDIA_STATES.map((t=>[t,e[t]])))},...i};return t&&(r.fakeEle={srcObject:formatSrcObject(t.srcObject),...Object.fromEntries(MEDIA_STATES.map((e=>[e,t[e]])))}),r}))}}function findAudioContextInEngine(e){const t=[];let i=[];e&&e._room&&e._room._remoteStreams&&(i=e._room._remoteStreams.values());for(const e of i)e.forEach((e=>{e.audioTrack&&t.push(e.audioTrack)}));e._localAudioTrack&&t.push(e._localAudioTrack),e._localScreenAudioTrack&&t.push(e._localScreenAudioTrack);for(const e of t){if(e._audioLevelFetcher&&e._audioLevelFetcher._ctx)return e._audioLevelFetcher._ctx;if(e._ac)return e._ac;if(e._audioFetchMap&&Array.from(e._audioFetchMap.values()).length)return Array.from(e._audioFetchMap.values())[0]._ctx;if(e._ap&&e._ap._ac)return e._ap._ac}return null}async function getAudioContextState(e){const t=Date.now(),i=findAudioContextInEngine(e),r={};return i?(AUDIOCONTEXT_STATES.forEach((e=>{r[e]=i[e]})),{timestamp:t,acState:r}):{timestamp:t,acState:void 0}}function getTrack(e){const t=[];e._localAudioTrack&&t.push({userId:"__local__",mediaType:"audio",isScreen:!1,isPublic:!1,isVirtual:!1,orgTrack:e._localAudioTrack._originTrack,mediaTrack:e._localAudioTrack._mediaTrack,preprocessingTrack:e._localAudioTrack._preProcessingTrack}),e._localScreenAudioTrack&&t.push({userId:"__local__",mediaType:"audio",isScreen:!0,isPublic:!1,isVirtual:!1,orgTrack:e._localScreenAudioTrack._originTrack,mediaTrack:e._localScreenAudioTrack._mediaTrack,preprocessingTrack:e._localScreenAudioTrack._preProcessingTrack}),e._localVideoTrack&&t.push({userId:"__local__",mediaType:"video",isScreen:!1,isPublic:!1,isVirtual:!1,orgTrack:e._localVideoTrack._originTrack,mediaTrack:e._localVideoTrack._mediaTrack,preprocessingTrack:e._localVideoTrack._preProcessingTrack}),e._localScreenVideoTrack&&t.push({userId:"__local__",mediaType:"video",isScreen:!0,isPublic:!1,isVirtual:!1,orgTrack:e._localScreenVideoTrack._originTrack,mediaTrack:e._localScreenVideoTrack._mediaTrack,preprocessingTrack:e._localScreenVideoTrack._preProcessingTrack}),e._room&&e._room._remoteStreams&&e._room._remoteStreams.forEach(((e,i)=>{e.forEach((e=>{e.audioTrack&&t.push({userId:i,mediaType:"audio",isScreen:e.isScreen,isPublic:!1,isVirtual:!1,orgTrack:e.audioTrack._originTrack,mediaTrack:e.audioTrack._mediaTrack}),e.videoTrack&&t.push({userId:i,mediaType:"video",isScreen:e.isScreen,isPublic:!1,isVirtual:!1,orgTrack:e.videoTrack._originTrack,mediaTrack:e.videoTrack._mediaTrack})}))}));let i=e._publicStreamManager;return i||(i=e._outsideRoom),i&&i.remoteStreams&&i.remoteStreams.forEach(((e,i)=>{e.audioTrack&&t.push({userId:i,mediaType:"audio",isScreen:e.isScreen,isPublic:!0,isVirtual:!1,orgTrack:e.audioTrack._originTrack,mediaTrack:e.audioTrack._mediaTrack}),e.videoTrack&&t.push({userId:i,mediaType:"video",isScreen:e.isScreen,isPublic:!0,isVirtual:!1,orgTrack:e.videoTrack._originTrack,mediaTrack:e.videoTrack._mediaTrack})})),e&&e._room&&e._room._virtualStreams&&e._room._virtualStreams.forEach(((e,i)=>{e.audioTrack&&t.push({userId:`virtualStream-${i}`,mediaType:"audio",isScreen:!1,isPublic:!1,isVirtual:!0,orgTrack:e.audioTrack._originTrack,mediaTrack:e.audioTrack._mediaTrack}),e.videoTrack&&t.push({userId:`virtualStream-${i}`,mediaType:"video",isScreen:!1,isPublic:!1,isVirtual:!0,orgTrack:e.videoTrack._originTrack,mediaTrack:e.videoTrack._mediaTrack})})),t}async function getVolumeFromTrack(e,t){if(!e)return;const i=new MediaStream;i.addTrack(e);const r=t.createMediaStreamSource(i),o=t.createAnalyser();r.connect(o),"suspended"===t.state&&(console.warn(t.state),t.resume());const s=new Uint8Array(2048);o.getByteTimeDomainData(s),await new Promise((e=>{setTimeout(e,50)})),o.getByteTimeDomainData(s),await new Promise((e=>{setTimeout(e,50)}));let n=0;s.forEach((e=>n=Math.max(n,Math.abs(e-128))));const a=n/128*256,d=a>2?a:0;return r.disconnect(),o.disconnect(),d}async function getVolume(e){const t=Date.now();if(ac||(ac=new AudioContext),"suspended"===ac.state&&await new Promise((t=>{const i=setTimeout((()=>{console.warn("[RTC_AMBULANCE] AudioContext resume failed, try to find one in RTCEngine"),ac=findAudioContextInEngine(e),ac&&console.warn("[RTC_AMBULANCE] find AudioContext in RTCEngine success"),t()}),1e3);ac.resume().then((()=>{clearTimeout(i),t()}),(()=>{clearTimeout(i),ac=null,t()}))})),!ac)return void console.error("[RTC_AMBULANCE] get volume is not supported");const i=getTrack(e),r=[];return await Promise.all(i.filter((e=>"audio"===e.mediaType)).map((async({orgTrack:e,mediaTrack:t,preprocessingTrack:i,...o})=>{const s={...o};await Promise.all([getVolumeFromTrack(e,ac).then((e=>{s.orgTrackVolume=e})),getVolumeFromTrack(t,ac).then((e=>{s.mediaTrackVolume=e})),getVolumeFromTrack(i,ac).then((e=>{s.preprocessingTrackVolume=e}))]),r.push(s)}))),{timestamp:t,trackVolumes:r}}async function getTrackState(e){return{timestamp:Date.now(),trackStates:getTrack(e).map((({orgTrack:e,mediaTrack:t,preprocessingTrack:i,...r})=>({orgTrack:e?Object.fromEntries(TRACK_STATES.map((t=>[t,e[t]]))):void 0,mediaTrack:t?Object.fromEntries(TRACK_STATES.map((e=>[e,t[e]]))):void 0,preprocessingTrack:i?Object.fromEntries(TRACK_STATES.map((e=>[e,i[e]]))):void 0,...r})))}}function formatSenderOrReceiver(e){if(!e)return;const t={track:e.track?e.track.id:void 0,transport:{state:e.transport?e.transport.state:void 0}};return e.transport&&e.transport.iceTransport&&(t.iceTransport={state:e.transport.iceTransport.state,role:e.transport.iceTransport.role,gatheringState:e.transport.iceTransport.gatheringState,component:e.transport.iceTransport.component}),t}async function getTranceiverState(e){const t=Date.now();let i=[];e._ctx._handler&&e._ctx._handler._peerConnection&&(i=e._ctx._handler._peerConnection.getTransceivers());const r=[];return i.forEach((e=>{const t={sender:formatSenderOrReceiver(e.sender),receiver:formatSenderOrReceiver(e.receiver),...Object.fromEntries(TRANSCEIVER_STATES.map((t=>[t,e[t]])))};r.push(t)})),{timestamp:t,tranceiverStates:r}}async function ambulance(e){const t={stats:[],mediaElementStates:[],audioContextStates:[],volumes:[],trackStates:[],tranceiverStates:[]},i=[];return await new Promise((r=>{let o,s=0;const n=()=>{i.push(getStats(e).then((e=>{t.stats.push(e)})),getMediaElementState(e).then((e=>{t.mediaElementStates.push(e)})),getAudioContextState(e).then((e=>{t.audioContextStates.push(e)})),getVolume(e).then((e=>{t.volumes.push(e)})),getTrackState(e).then((e=>{t.trackStates.push(e)})),getTranceiverState(e).then((e=>{t.tranceiverStates.push(e)}))),s++,s>=10?Promise.all(i).then((()=>{r()})):(clearTimeout(o),o=setTimeout(n,500))};o=setTimeout(n,500)})),console.log("RTC_AMBULANCE",t),t}class ContainerCollisionDetector{constructor(){__publicField(this,"containers",new WeakSet)}getContainerById(e){return document.getElementById(e)}registerContainer(e){return"string"==typeof e&&(e=this.getContainerById(e)??void 0),!(!e||this.containers.has(e))&&(this.containers.add(e),!0)}unregisterContainer(e){return"string"==typeof e&&(e=this.getContainerById(e)??void 0),!!e&&(this.containers.delete(e),!0)}}var __defProp$1=Object.defineProperty,__getOwnPropDesc$1=Object.getOwnPropertyDescriptor,__decorateClass$1=(e,t,i,r)=>{for(var o,s=r>1?void 0:r?__getOwnPropDesc$1(t,i):t,n=e.length-1;n>=0;n--)(o=e[n])&&(s=(r?o(t,i,s):o(s))||s);return r&&s&&__defProp$1(t,i,s),s};const _RTCEngine=(_v=class extends EnhancedEventEmitter{constructor(e,t,i){super(),__publicField(this,"monitor"),__publicField(this,"logger"),__publicField(this,"_room"),__publicField(this,"_wtnStreamManager"),__publicField(this,"_appId"),__publicField(this,"_localImgVideoTrack"),__publicField(this,"_localImgScreenTrack"),__publicField(this,"_localScreenVideoTrack"),__publicField(this,"_localScreenAudioTrack"),__publicField(this,"_tempMixingAudioTrack"),__publicField(this,"_localAudioVolume",100),__publicField(this,"_localScreenAudioVolume",100),__publicField(this,"_remoteAudioVolume",new Map),__publicField(this,"_remoteScreenAudioVolume",new Map),__publicField(this,"_localVideoPlayerConfig",{[StreamIndex$1.STREAM_INDEX_MAIN]:new Map,[StreamIndex$1.STREAM_INDEX_SCREEN]:new Map}),__publicField(this,"_remoteVideoPlayerConfig",{[StreamIndex$1.STREAM_INDEX_MAIN]:new Map,[StreamIndex$1.STREAM_INDEX_SCREEN]:new Map}),__publicField(this,"_publicStreamIds",new Map),__publicField(this,"_dummyMainImage"),__publicField(this,"_dummyScreenImage"),__publicField(this,"_trackSourceType"),__publicField(this,"_liveTranscodeConfig"),__publicField(this,"_startCloudProxyTimestamp"),__publicField(this,"_pauseAllSubscribeState",{audio:void 0,video:void 0,resumeAudioStreamIds:{},resumeVideoStreamIds:{}}),__publicField(this,"_audioVolumeIndicationTimer"),__publicField(this,"_dummyMainTimer"),__publicField(this,"_dummyScreenTimer"),__publicField(this,"_audioPropertiesReportTimer",null),__publicField(this,"_mirrorType",MirrorType.MIRROR_TYPE_RENDER),__publicField(this,"_audioMixingManager"),__publicField(this,"_pubLock"),__publicField(this,"_subLocks"),__publicField(this,"_audioCaptureLock"),__publicField(this,"_videoCaptureLock"),__publicField(this,"_screenCaptureLock"),__publicField(this,"_subScreenLocks"),__publicField(this,"_rtmClient"),__publicField(this,"_messageStatisticsObserver"),__publicField(this,"_waitForNewToken",!1),__publicField(this,"_originIceConfigRequestUrls"),__publicField(this,"_originConfigServerUrls"),__publicField(this,"_originLogServerUrl"),__publicField(this,"_audioDeviceManager"),__publicField(this,"_config"),__publicField(this,"_needClosePreTrack",!1),__publicField(this,"_containerCollisionDetector",new ContainerCollisionDetector),__publicField(this,"_ctx"),__publicField(this,"_removeDeviceEventHandler"),__publicField(this,"_updateMixAudioTrack",(async(e,t=AudioMixingType.PLAYOUT_AND_PUBLISH)=>{var i;if(this.logger.info("_updateMixAudioTrack()"),!this._localAudioTrack)return void(e&&(this._tempMixingAudioTrack={track:e,type:t}));e?(this._localAudioTrack.mixType=t,this._localAudioTrack.mixedAudioTrack=e):(delete this._localAudioTrack.mixType,delete this._localAudioTrack.mixedAudioTrack);await(null==(i=this._room)?void 0:i.hasPublished())&&await this._updatePublish(),this._wtnStreamManager._updatePushTrack()})),__publicField(this,"_onVideoDeviceStateChange",(e=>{this.safeEmit(EngineEventsTypes.onVideoDeviceStateChanged,e)})),__publicField(this,"_onAudioDeviceStateChange",(e=>{this.safeEmit(EngineEventsTypes.onAudioDeviceStateChanged,e)})),__publicField(this,"_onAudioMixingMessage",(e=>{this.safeEmit(EngineEventsTypes.onAudioMixingStateChanged,e)})),__publicField(this,"_onAudioMixingAutoplayFailed",(e=>{this.safeEmit(EngineEventsTypes.onAutoplayFailed,e)})),__publicField(this,"_revokeAutoplayFailedWorkaround"),this.id=t,this._appId=e,this.monitor=getMonitor(t),this._ctx=new RTCContext(t,e,i),this._pubLock=new PromiseLock2("pubLock"),this._subLocks=new Map,this._subScreenLocks=new Map,this._audioCaptureLock=new PromiseLock2("audioCap"),this._videoCaptureLock=new PromiseLock2("videoCap"),this._screenCaptureLock=new PromiseLock2("screenCap"),this._addDeviceEventHandler(),this._audioDeviceManager=new AudioDeviceManager(this._ctx),this._addSignalingEventHandler(),this._wtnStreamManager=new WTNStream(this._ctx),this._addWTNStreamEventHandler(),isDebuggerMode&&(window.__rtc_engine__=this,window[`__rtc_engine__${Math.floor(100*Math.random()+1)}`]=this),this._trackSourceType={video:VideoSourceType.VIDEO_SOURCE_TYPE_INTERNAL,screenVideo:VideoSourceType.VIDEO_SOURCE_TYPE_INTERNAL,audio:AudioSourceType.AUDIO_SOURCE_TYPE_INTERNAL,screenAudio:AudioSourceType.AUDIO_SOURCE_TYPE_INTERNAL},this._config=i,this._rtmClient=new RTSClient(this._ctx),this._handleRTMClient(this._rtmClient),this._handleAudioDeviceManager(),this._messageStatisticsObserver=new MessageStatisticsObserver(t),this.logger=new Logger$1("Engine",0,t),RTSMsgReportor.createRTSMsgReportor(this.id),_RTCEngine.hasReportNativeDetector||(this.monitor.reportLongString("NativeDetector",JSON.stringify(detectorResults)),_RTCEngine.hasReportNativeDetector=!0),this._initAutoplayFailedWorkaround()}get appId(){return this._appId}set appId(e){this._appId=e}async updateToken(e){if(this.logger.info("updateToken()","token: %s",e),checkString(e,"token"),this._room&&this._waitForNewToken)return this._waitForNewToken=!1,this._room.config.token=e,await this._join(this._room);if(!this._room)throw new SDKError(ErrorCode.UPDATE_TOKEN_BEFORE_JOIN,"update token before join room");await this._room.updateToken(e);const t=[];if(this._room.config.tokenPublishPrivilegeExpired&&this._room.config.isAutoPublish&&this._ctx.visibility&&t.push(this._updatePublish({mediaType:MediaType$1.AUDIO_AND_VIDEO})),this._room.config.tokenSubscribePrivilegeExpired){const{isAutoSubscribeAudio:e,isAutoSubscribeVideo:i}=this._room.config,r=(e?MediaType$1.AUDIO:0)|(i?MediaType$1.VIDEO:0);r&&t.push(this._triedResumeAllRemoteStreams(r,!0))}await Promise.allSettled(t)}async setVideoCaptureDevice(e){var t;if(this.logger.info("setVideoCaptureDevice()","deviceId: %s",e),checkString(e,"deviceId"),!this._localVideoTrack)return void this._ctx.videoProfile.setCaptureDeviceId(e);if(isWeChat&&isAndroid){if(this._localVideoTrack.originTrack.getSettings().deviceId===e)return}const i=this._ctx.videoProfile.getCaptureConfig(e);isAndroid&&isChrome&&chromeVersion>=85&&chromeVersion<=91&&(null==(t=this.localVideoTrack)||t.removePlayerTrack()),this._needClosePreTrack=this._needClosePreTrack||unsupportedSimultaneousCapture,this._needClosePreTrack&&(this._removeLocalTrackEvents(this._localVideoTrack),this._localVideoTrack.destroy(),delete this._localVideoTrack),this.logger.info("setVideoCaptureDevice()","start createCameraVideoTrack...");const r=await createCameraVideoTrack(this._ctx,i).catch((e=>{if(this._localVideoTrack&&!this._localVideoTrack.dummy)return this.logger.warn("setVideoCaptureDevice()","createCameraVideoTrack failed, stop pre VideoTrack."),this._removeLocalTrackEvents(this._localVideoTrack),this._localVideoTrack.destroy(),delete this._localVideoTrack,createCameraVideoTrack(this._ctx,i).then((e=>(this._needClosePreTrack=!0,e))).catch((async()=>{this.logger.error("setVideoCaptureDevice()","createCameraVideoTrack failed, rollback.");const t=await createCameraVideoTrack(this._ctx);throw this._switchTrack(t),e}));throw e}));this.logger.success("setVideoCaptureDevice()","createCameraVideoTrack success."),this._ctx.videoProfile.setCaptureDeviceId(e),this._localVideoTrack&&(this._removeLocalTrackEvents(this._localVideoTrack),this._localVideoTrack.destroy());const o=this._ctx.videoProfile.getContentHint();o&&r.setContentHint(o),await this._switchTrack(r)}async setAudioCaptureDevice(e){var t;if(this.logger.info("setAudioCaptureDevice()","deviceId: %s",e),checkString(e,"deviceId"),this._ctx.audioProfileManager.updateConstraints({deviceId:{exact:e}}),!this._localAudioTrack)return;this._localAudioTrack.destroy(),this._removeLocalTrackEvents(this._localAudioTrack);const i=await createMicrophoneAudioTrack(this._ctx,this._ctx.audioProfileManager.getConstraints());this._initLocalTrackEvents(i),this._localAudioTrack=i,this._localAudioTrack.setVolume(this._localAudioVolume),this._wtnStreamManager._updatePushTrack(),this._room&&(null==(t=this._room.localStream)?void 0:t.pubAudio)&&await this._updatePublish()}_addDeviceEventHandler(){dd.on(EngineEventsTypes.onVideoDeviceStateChanged,this._onVideoDeviceStateChange),dd.on(EngineEventsTypes.onAudioDeviceStateChanged,this._onAudioDeviceStateChange),this._removeDeviceEventHandler=()=>{dd.off(EngineEventsTypes.onVideoDeviceStateChanged,this._onVideoDeviceStateChange),dd.off(EngineEventsTypes.onAudioDeviceStateChanged,this._onAudioDeviceStateChange)}}_addSignalingEventHandler(){const e=this._ctx.signalingManager;e.on(StateEvent.ON_CONNECTION_STATE_CHANGE,this._onConnectionStateChange.bind(this)),e.on(StateEvent.ON_RECONNECT_FAILED,(()=>{this.safeEmit(EngineEventsTypes.onError,{errorCode:ErrorCode.RECONNECT_FAILED})})),e.on(StateEvent.CONNECT_WITH_TCP,(()=>{this.safeEmit(EngineEventsTypes.onIceConnectWithTcp)}))}_addWTNStreamEventHandler(){this._wtnStreamManager.__onResubscribe=e=>{const t=e.stream;t&&(t.audioTrack&&this._updateAudioPlayerState(t),t.videoTrack&&this._updateVideoPlayerState(t))},this._wtnStreamManager.__onRemoteStreamStats=e=>{this.safeEmit(EngineEventsTypes.onPublicStreamStats,e)},this._wtnStreamManager.__onSEIMessageReceived=e=>{this.safeEmit(EngineEventsTypes.onPublicStreamSEIMessageReceived,e)},this._wtnStreamManager.__onPlayerEvents=(e,t,i)=>{this._initPlayerEvents(e,t,i)}}_addHandlerEventHandler(){var e,t,i,r,o,s,n,a,d,c,l,u,_,h,p,m,S,g,v,f,E,T,R,b,y,I,C,A,k,M,N,O,P,D,w,L,x,F,U,V,B,$;null==(e=this._room)||e.on(SignalEvent.ON_ADD_STREAM,this._onAddStream.bind(this)),null==(t=this._room)||t.on(SignalEvent.ON_REMOVE_STREAM,this._onRemoveStream.bind(this)),null==(i=this._room)||i.on(SignalEvent.USER_CONNECTION,this._onUserConnection.bind(this)),null==(r=this._room)||r.on(RoomEvent.ON_USER_LEAVE,this._onUserLeave.bind(this)),null==(o=this._room)||o.on(RoomEvent.ON_ROOM_ERROR,this._onRoomError.bind(this)),null==(s=this._room)||s.on(RoomEvent.ON_NETWORK_QUALITY,this._onNetworkQuality.bind(this)),null==(n=this._room)||n.on(SignalEvent.ON_CUSTOM_MESSAGE,this._onCustomMessage.bind(this)),null==(a=this._room)||a.on(SignalEvent.USER_MESSAGE_RECEIVED,this._onUserMessageReceived.bind(this)),null==(d=this._room)||d.on(SignalEvent.USER_BINARY_MESSAGE_RECEIVED,this._onUserBinaryMessageReceived.bind(this)),null==(c=this._room)||c.on(SignalEvent.ON_USER_TOKEN_WILL_EXPIRE,this._onUserTokenWillExpire.bind(this)),null==(l=this._room)||l.on(SignalEvent.ON_TOKEN_PUBLISH_PRIVILEGE_WILL_EXPIRE,this._onUserTokenPublishPrivilegeWillExpire.bind(this)),null==(u=this._room)||u.on(SignalEvent.ON_TOKEN_PUBLISH_PRIVILEGE_DID_EXPIRED,this._onUserTokenPublishPrivilegeDidExpired.bind(this)),null==(_=this._room)||_.on(SignalEvent.ON_TOKEN_SUBSCRIBE_PRIVILEGE_WILL_EXPIRE,this._onUserTokenSubscribePrivilegeWillExpire.bind(this)),null==(h=this._room)||h.on(SignalEvent.ON_TOKEN_SUBSCRIBE_PRIVILEGE_DID_EXPIRED,this._onUserTokenSubscribePrivilegeDidExpired.bind(this)),null==(p=this._room)||p.on(SignalEvent.POST_PROCESSING_MESSAGE,(e=>{var t;"2.0"===(null==(t=e)?void 0:t.protocol)?this._onStreamMixingEvent({error:e.error,event:e.eventType,message:e.message}):"publicStreamCallback"===e.type?this._onPushPublicStreamResult(e):"transcodeStatusCallback"===e.type&&this._onLiveTranscodingResult(e)})),null==(m=this._room)||m.on(StateEvent.ON_VENDOR_CONNECTION_STATE_CHANGE,(e=>this.safeEmit(EngineEventsTypes.onVendorConnectionStateChanged,e))),null==(S=this._room)||S.on(RoomEvent.RESUBSCRIBE,this._onResubscribe.bind(this)),null==(g=this._room)||g.on(RoomEvent.SUBSCRIBE_PUSH_TRACK,this._onSubscribePushTrack.bind(this)),null==(v=this._room)||v.on(RoomEvent.REMOVE_PUSH_TRACK,this._onRemovePushTrack.bind(this)),null==(f=this._room)||f.on(RoomEvent.ON_PUBLISH_RESULT,(e=>{var t,i,r;e.state===PublishState.PUBLISH_SUCC&&(null==(t=this._room)||t.config.setTokenPublishPrivilegeExpired(!1)),e.state===PublishState.PUBLISH_FAIL&&e.errorCode===ErrorCode.TOKEN_NO_PUBLISH_PERMISSION&&(null==(i=this._room)||i.config.setTokenPublishPrivilegeExpired(!0));const o=!(e.retry||!(null==(r=this._room)?void 0:r.config.isAutoPublish));o&&this.safeEmit(EngineEventsTypes.onAutoPublishResult,e),this.safeEmit(EngineEventsTypes.onPublishResult,{isScreen:e.isScreen,isAutoPublish:o,errorCode:e.errorCode})})),null==(E=this._room)||E.on(RoomEvent.ON_SUBSCRIBE_RESULT,(e=>{var t;e.state===SubscribeState.SUBSCRIBE_SUCC&&(null==(t=this._room)||t.config.setTokenSubscribePrivilegeExpired(!1)),e.state===SubscribeState.SUBSCRIBE_FAIL&&e.errorCode===ErrorCode.TOKEN_NO_SUBSCRIBE_PERMISSION&&this._handleLoseSubscribePrivilege(),this.safeEmit(EngineEventsTypes.onSubscribeResult,{userId:e.userId,isScreen:e.isScreen,isAutoSubscribe:!1,errorCode:e.errorCode})})),null==(T=this._room)||T.on(RoomEvent.ON_REMOTE_STREAM_STATS,(e=>{this.safeEmit(EngineEventsTypes.onRemoteStreamStats,e)})),null==(R=this._room)||R.on(RoomEvent.ON_LOCAL_STREAM_STATS,(e=>{this.safeEmit(EngineEventsTypes.onLocalStreamStats,e)})),null==(b=this._room)||b.on(RoomEvent.ON_SUBTITLE_STATE_CHANGED,(e=>{this.safeEmit(EngineEventsTypes.onSubtitleStateChanged,e)})),null==(y=this._room)||y.on(RoomEvent.ON_SUBTITLE_MESSAGE_RECEIVED,(e=>{this.safeEmit(EngineEventsTypes.onSubtitleMessageReceived,e)})),null==(I=this._room)||I.on(RoomEvent.ON_USER_PUBLISH_STATE_CHANGE,this._onUserPublishStateChange.bind(this)),null==(C=this._room)||C.on(RoomEvent.ON_USER_START_AUDIO_CAPTURE,(({userId:e},t)=>{this._updateAudioPlayerState(t),this.safeEmit(EngineEventsTypes.onUserStartAudioCapture,{userId:e})})),null==(A=this._room)||A.on(RoomEvent.ON_USER_STOP_AUDIO_CAPTURE,(({userId:e})=>{this.safeEmit(EngineEventsTypes.onUserStopAudioCapture,{userId:e})})),null==(k=this._room)||k.on(RoomEvent.ON_USER_START_VIDEO_CAPTURE,(({userId:e})=>{this.safeEmit(EngineEventsTypes.onUserStartVideoCapture,{userId:e})})),null==(M=this._room)||M.on(RoomEvent.ON_USER_STOP_VIDEO_CAPTURE,(({userId:e})=>{this.safeEmit(EngineEventsTypes.onUserStopVideoCapture,{userId:e})})),null==(N=this._room)||N.on(RoomEvent.ON_SEI_MESSAGED_RECEIVED,(e=>{this.safeEmit(EngineEventsTypes.onSEIMessageReceived,e)})),null==(O=this._room)||O.on(RoomEvent.ON_REMOTE_VIDEO_SIZE_CHANGED,((e,t)=>{this.safeEmit(EngineEventsTypes.onRemoteVideoSizeChanged,e,t)})),null==(P=this._room)||P.on(RoomEvent.ON_SIMULCAST_SUBSCRIBE_FALLBACK,(e=>this.safeEmit(EngineEventsTypes.onSimulcastSubscribeFallback,e))),null==(D=this._room)||D.on(RoomEvent.ON_VIDEO_STREAM_BANNED,(e=>{this.safeEmit(EngineEventsTypes.onVideoStreamBanned,{uid:e.uid,banned:e.banned})})),null==(w=this._room)||w.on(RoomEvent.ON_AUDIO_STREAM_BANNED,(e=>{this.safeEmit(EngineEventsTypes.onAudioStreamBanned,{uid:e.uid,banned:e.banned})})),null==(L=this._room)||L.on(RoomEvent.ON_FORWARD_STREAM_ERROR,(e=>{this.safeEmit(EngineEventsTypes.onForwardStreamError,e)})),null==(x=this._room)||x.on(RoomEvent.ON_REJOIN_WITH_TCP,(()=>{this.safeEmit(EngineEventsTypes.onRejoinWithTcp)})),null==(F=this._room)||F.on(RoomEvent.PUB_RETRY,(e=>{this.safeEmit(EngineEventsTypes.onPublishRetry,e)})),null==(U=this._room)||U.on(RoomEvent.SUB_RETRY,(e=>{this.safeEmit(EngineEventsTypes.onSubscribeRetry,e)})),null==(V=this._room)||V.on(RoomEvent.VIDEO_TYPE_CHANGE,(e=>{this.safeEmit(EngineEventsTypes.onSEIStreamUpdate,e)})),null==(B=this._room)||B.on(RoomEvent.JOIN_SUCCESS,(e=>{this._ctx.isPreConnection||this.safeEmit(EngineEventsTypes.onConnectionStateChanged,{state:e?ConnectionState.CONNECTION_STATE_RECONNECTED:ConnectionState.CONNECTION_STATE_CONNECTED})})),null==($=this._room)||$.on(RoomEvent.UPDATE_PUBLISH,(({streamIndex:e})=>{e===StreamIndex$1.STREAM_INDEX_MAIN?this._updatePublish():e===StreamIndex$1.STREAM_INDEX_SCREEN&&this._updateScreenPublish()}))}safeEmit(e,...t){if(isReportCallback(e)){if(e===EngineEventsTypes.onRemoteStreamStats){const e=getParameter("UPLOAD_REMOTE_STATS"),i=getParameter("FORCE_ENABLED_REPORT_CALLBACKS").includes("onRemoteStreamStats"),{videoStats:r,audioStats:o,...s}=t[0];t[0]={...s},(e&MediaType$1.VIDEO||i)&&(t[0].videoStats=r),(e&MediaType$1.AUDIO||i)&&(t[0].audioStats=o)}reportRtcSdkCallback(this.id,e,t)}return super.safeEmit(e,...t)}_removeHandlerEventHandler(){var e;null==(e=this._room)||e.removeAllListeners()}async connect(){await this._ctx.signalingManager.connect()}async joinRoom(e,t,i,r){var o,s,n,a,d;if(this.logger.info("joinRoom()","token: %o roomId: %o, userInfo: %o, roomConfig: %o",e,t,i,r),isEmpty(e)||checkString(e,"token"),this._room)throw new SDKError(ErrorCode.REPEAT_JOIN,"Already joined");null==(o=this._ctx.monitor)||o.report("rtc_sdk_api_call",{sdk_api_name:"host",message:location.host,error_code:0}),checkRoomId(t),checkUserInfo(i);const c=new RoomContext({token:e,roomId:t,userInfo:i},this._ctx);return checkRoomConfig(c.updateRoomConfig(r)),c.setLiveControlMessage(this._liveTranscodeConfig&&LiveTranscoding.getStartParams(this._liveTranscodeConfig)),this._room=new Room(c,this._ctx),this.monitor.set({rtc_session_id:this._room.config.sessionId}),this._addHandlerEventHandler(),this._ctx.useCloudProxy&&(this._startCloudProxyTimestamp=Date.now()),null==(s=this._localVideoTrack)||s.setUserId(i.userId),null==(n=this._localScreenVideoTrack)||n.setUserId(i.userId),null==(a=this._localAudioTrack)||a.setUserId(i.userId),null==(d=this._localScreenAudioTrack)||d.setUserId(i.userId),checkSourceLanguage(i),await this._join(this._room)}async _join(e){var t;try{const i=await e.join();return this._waitForNewToken=!1,this._ctx.audioProfileManager.setRoomId(e.config.roomId),(null==(t=this._room)?void 0:t.config.isAutoPublish)&&(this._ctx.visibility?this._updatePublish({invokeByJoinRoom:!0,mediaType:MediaType$1.AUDIO_AND_VIDEO}).catch((e=>{this.logger.error("_join","_updatePublish failed",e)})):(this.safeEmit(EngineEventsTypes.onAutoPublishResult,{isScreen:!1,state:PublishState.PUBLISH_FAIL}),this.safeEmit(EngineEventsTypes.onPublishResult,{isScreen:!1,isAutoPublish:!0,errorCode:ErrorCode.NO_PUBLISH_PERMISSION}))),this.monitor.set({rtc_vid:e.config.rtcVid}),RTSMsgReportor.setRoomId(this.id,e.config.roomId),RTSMsgReportor.setUserId(this.id,e.config.userId),i}catch(t){throw t.code===ErrorCode.INVALID_TOKEN?this._waitForNewToken=!0:(e.destroy(),this._room===e&&delete this._room),t}}async leaveRoom(e=!1){this.logger.info("leaveRoom()");const t=this._room;delete this._room,this._ctx.resetPubSubLock(ResetPubSubLockReason.LEAVE),this._ctx.callId=void 0,e?await(null==t?void 0:t.leave(e)):null==t||t.leave(e).catch(),this._removeHandlerEventHandler(),this._subLocks=new Map,this._subScreenLocks=new Map,this._ctx.audioProfileManager.setRoomId(),this._liveTranscodeConfig&&this.stopLiveTranscoding(),null==t||t.destroy(),this._remoteVideoPlayerConfig[StreamIndex$1.STREAM_INDEX_MAIN].forEach((e=>{e.forEach((e=>{const{player:t,renderDom:i}=e;null==t||t.destroy(),this._containerCollisionDetector.unregisterContainer(i)}))})),this._remoteVideoPlayerConfig[StreamIndex$1.STREAM_INDEX_MAIN].clear(),this._remoteVideoPlayerConfig[StreamIndex$1.STREAM_INDEX_SCREEN].forEach((e=>{e.forEach((e=>{const{player:t,renderDom:i}=e;null==t||t.destroy(),this._containerCollisionDetector.unregisterContainer(i)}))})),this._remoteVideoPlayerConfig[StreamIndex$1.STREAM_INDEX_SCREEN].clear(),this._publicStreamIds=new Map,RTSMsgReportor.setRoomId(this.id,""),RTSMsgReportor.setUserId(this.id,""),this.monitor.set({rtc_session_id:"",rtc_vid:""})}_destroyLocalTrack(){this._localAudioTrack&&(this._removeLocalTrackEvents(this._localAudioTrack),this._localAudioTrack.destroy(),this._localAudioTrack=void 0),this._localVideoTrack&&(this._removeLocalTrackEvents(this._localVideoTrack),this._localVideoTrack.destroy(),this._localVideoTrack=void 0),this._localScreenAudioTrack&&(this._removeLocalTrackEvents(this._localScreenAudioTrack),this._localScreenAudioTrack.destroy(),this._localScreenAudioTrack=void 0),this._localScreenVideoTrack&&(this._removeLocalTrackEvents(this._localScreenVideoTrack),this._localScreenVideoTrack.destroy(),this._localScreenVideoTrack=void 0),this._localImgVideoTrack&&(this._localImgVideoTrack.stop(),this._localImgVideoTrack=void 0),this._localImgScreenTrack&&(this._localImgScreenTrack.stop(),this._localImgScreenTrack=void 0)}destroy(){var e,t,i,r;this.logger.info("destroy()"),this.removeAllListeners(),this._removeHandlerEventHandler(),null==(e=this._removeDeviceEventHandler)||e.call(this),null==(t=this._revokeAutoplayFailedWorkaround)||t.call(this),null==(i=this._room)||i.destroy(),this._room=void 0,this._subLocks=new Map,this._subScreenLocks=new Map,this._audioCaptureLock=new PromiseLock2("audioCap"),this._videoCaptureLock=new PromiseLock2("videoCap"),this._screenCaptureLock=new PromiseLock2("screenCap"),this._pauseAllSubscribeState={audio:void 0,video:void 0,resumeVideoStreamIds:{},resumeAudioStreamIds:{}},this._messageStatisticsObserver.destroy(),this.monitor.destroy(),RTSMsgReportor.destroyRTSMsgReportor(this.id),clearInterval(this._audioVolumeIndicationTimer),clearInterval(this._dummyMainTimer),clearInterval(this._dummyScreenTimer),this._audioVolumeIndicationTimer=void 0,this._stopAudioPropertiesReport(),this._destroyLocalTrack(),null==(r=this._audioMixingManager)||r.destroy(),this._rtmClient.destroy(),this._wtnStreamManager.destroy(),this._publicStreamIds=new Map,this._audioDeviceManager.destroy(),this._ctx.destroy(),this._localAudioVolume=100,this._localScreenAudioVolume=100,this._remoteAudioVolume.clear(),this._remoteScreenAudioVolume.clear(),this._localVideoPlayerConfig[StreamIndex$1.STREAM_INDEX_MAIN].forEach((e=>{e.player.destroy()})),this._localVideoPlayerConfig[StreamIndex$1.STREAM_INDEX_MAIN].clear(),this._localVideoPlayerConfig[StreamIndex$1.STREAM_INDEX_SCREEN].forEach((e=>{e.player.destroy()})),this._localVideoPlayerConfig[StreamIndex$1.STREAM_INDEX_SCREEN].clear(),this._remoteVideoPlayerConfig[StreamIndex$1.STREAM_INDEX_MAIN].forEach((e=>{e.forEach((e=>{e.player.destroy()}))})),this._remoteVideoPlayerConfig[StreamIndex$1.STREAM_INDEX_MAIN].clear(),this._remoteVideoPlayerConfig[StreamIndex$1.STREAM_INDEX_SCREEN].forEach((e=>{e.forEach((e=>{e.player.destroy()}))})),this._remoteVideoPlayerConfig[StreamIndex$1.STREAM_INDEX_SCREEN].clear()}async publishStream(e){this.logger.info("publishStream()","mediaType: %o",e),this._checkMediaType(e),this._assertNotInRoom(),videoInMediaType(e)&&!this._localVideoTrack&&this._localImgVideoTrack&&(this._localVideoTrack=await createDummyVideoLocalTrack(this._ctx,this._localImgVideoTrack)),await this._updatePublish({mediaType:e},!0)}async unpublishStream(e,t){var i;if(this.logger.info("unpublishStream()","mediaType: %o",e),this._checkMediaType(e),this._assertNotInRoom(),t)return null==(i=this._room)?void 0:i.unpublish();await this._updatePublish({mediaType:e,pubState:PubState.UNPUB},!0)}async publishScreen(e){this.logger.info("publishScreen()","mediaType: %o",e),this._checkMediaType(e),this._assertNotInRoom();try{videoInMediaType(e)&&!this._localScreenVideoTrack&&this._localImgScreenTrack&&(this._localScreenVideoTrack=await createDummyScreenVideoLocalTrack(this._ctx,this._localImgScreenTrack)),await this._updateScreenPublish({mediaType:e,pubState:PubState.PUB})}catch(e){throw e instanceof SDKError?e:new SDKError(ErrorCode.UNEXPECTED_ERROR,"unexpected error",e)}}async unpublishScreen(e){this.logger.info("unpublishScreen()","mediaType: %o",e),this._checkMediaType(e),this._assertNotInRoom(),await this._updateScreenPublish({mediaType:e,pubState:PubState.UNPUB})}async subscribeStream(e,t){return this.logger.info("subscribeStream()","userId: %o, mediaType: %o",e,t),this._subscribe(!1,e,t)}async _subscribe(e,t,i){var r,o,s,n,a,d;const c=i;if(i===MediaType$1.AUDIO&&(null==(r=this._room)?void 0:r.config.isMultiChatMode()))return void this.logger.warn("subscribeStream()","due to multiChatMode return");const l=this._room.remoteStreams.get(t),u=null==l?void 0:l.find((t=>t.isScreen===e));if(!u)throw new SDKError(ErrorCode.STREAM_NOT_EXIST,"stream not exist");const _=this._pauseAllSubscribeState.audio,h=this._pauseAllSubscribeState.video;this._pauseAllSubscribeState.audio&&(i-=i&MediaType$1.AUDIO),this._pauseAllSubscribeState.video&&(i-=i&MediaType$1.VIDEO),this.logger.warn("subscribeStream()","due to pauseAll mediaType: %o",i);const{hasSubscribed:p}=u;u.originalMediaType=i;try{await this._room.subscribe(u,i),audioInMediaType(i)&&this._updateAudioPlayerState(u),videoInMediaType(i)&&this._updateVideoPlayerState(u);let r=0,l=0;if(_!==this._pauseAllSubscribeState.audio&&(this._pauseAllSubscribeState.audio?r|=MediaType$1.AUDIO:l|=MediaType$1.AUDIO),h!==this._pauseAllSubscribeState.video&&(this._pauseAllSubscribeState.video?r|=MediaType$1.VIDEO:l|=MediaType$1.VIDEO),r&&this.pauseAllSubscribedStream(r),l&&this.resumeAllSubscribedStream(l),audioInMediaType(c)&&(this._pauseAllSubscribeState.resumeAudioStreamIds[u.streamId]=u.streamId),videoInMediaType(c)&&(this._pauseAllSubscribeState.resumeVideoStreamIds[u.streamId]=u.streamId),u.audioTrack||u.videoTrack){const i=!(e||!(null==(o=this._room)?void 0:o.config.isAutoSubscribeAudio)&&!(null==(s=this._room)?void 0:s.config.isAutoSubscribeVideo)),r={userId:t,isScreen:!1,state:SubscribeState.SUBSCRIBE_SUCC};i&&this.safeEmit(EngineEventsTypes.onAutoSubscribeResult,r),this.safeEmit(EngineEventsTypes.onSubscribeResult,{userId:t,isScreen:e,isAutoSubscribe:i})}!(null==(n=this._room)?void 0:n.config.isMultiChatMode())&&!p&&audioInMediaType(i)&&u.hasAudio&&(null==(a=u.observer)||a.setSubscribeAudio(!0)),!p&&videoInMediaType(i)&&u.hasVideo&&(null==(d=u.observer)||d.setSubscribeVideo(!0))}catch(e){throw e instanceof SDKError&&e.code===ErrorCode.TOKEN_NO_SUBSCRIBE_PERMISSION&&this._handleLoseSubscribePrivilege(),e}}async _handleLoseSubscribePrivilege(){var e;null==(e=this._room)||e.config.setTokenSubscribePrivilegeExpired(!0);try{await this._unSubscribeAllRemoteStreams()}catch(e){}}async unsubscribeStream(e,t){return this.logger.info("unsubscribeStream()","userId: %o, mediaType: %o",e,t),this._unsubscribe(!1,e,t)}async subscribeScreen(e,t){return this.logger.info("subscribeScreen() userId: %o, mediaType: %o",e,t),this._subscribe(!0,e,t)}async unsubscribeScreen(e,t){return this.logger.info("unsubscribeScreen() userId: %o, mediaType: %o",e,t),this._unsubscribe(!0,e,t)}_unsubscribe(e,t,i,r){var o,s;if(i===MediaType$1.AUDIO&&(null==(o=this._room)?void 0:o.config.isMultiChatMode()))return void this.logger.warn("subscribeStream()","due to multiChatMode return");const n=this._room.remoteStreams.get(t),a=null==n?void 0:n.find((t=>t.isScreen===e));if(!a)throw new SDKError(ErrorCode.STREAM_NOT_EXIST,"stream not exist");return isAndroid&&chromeVersion&&chromeVersion>=85&&chromeVersion<=91&&i!==MediaType$1.AUDIO&&(null==(s=a.videoTrack)||s.stopAll()),this._room.unsubscribe(a,i).then((()=>{r||(audioInMediaType(i)&&delete this._pauseAllSubscribeState.resumeAudioStreamIds[a.streamId],videoInMediaType(i)&&delete this._pauseAllSubscribeState.resumeVideoStreamIds[a.streamId])}))}async setRemoteVideoConfig(e,t){var i;return this.logger.info("setRemoteVideoConfig() userId: %o, remoteVideoConfig: %o",e,t),this._ctx.videoProfile.checkSimulcastApiVersion("old"),checkUserId(e),checkRemoteConfig(t),this._ctx.videoProfile.setRemoteUserVideoConfig(e,t),null==(i=this._room)?void 0:i.updateSubVideoConfig(e).then((()=>{}))}async setRemoteSimulcastStreamType(e,t){var i;this.logger.info("setRemoteSimulcastStreamType()","userId: %s, streamType: %s",e,t),this._ctx.videoProfile.checkSimulcastApiVersion("new"),checkUserId(e),checkEnum(t,"SimulcastStreamType",[SimulcastStreamType.VIDEO_STREAM_HIGH,SimulcastStreamType.VIDEO_STREAM_MID,SimulcastStreamType.VIDEO_STREAM_LOW]),this._ctx.videoProfile.setRemoteUserVideoConfig(e,t),await(null==(i=this._room)?void 0:i.updateSubVideoConfig(e))}async startVideoCapture(e){var t,i,r;if(this.logger.info("startVideoCapture()","deviceId: %s",e),isEmpty(e)||checkString(e,"deviceId"),e&&this._ctx.videoProfile.setCaptureDeviceId(e),this._trackSourceType.video===VideoSourceType.VIDEO_SOURCE_TYPE_EXTERNAL)throw new SDKError(ErrorCode.STREAM_TYPE_NOT_MATCH,"setVideoSourceType as internal first");if(this._localVideoTrack&&!this._localVideoTrack.dummy)throw new SDKError(ErrorCode.REPEAT_CAPTURE,"Has already capture");let o={};const s=await createCameraVideoTrack(this._ctx),n=this._ctx.videoProfile.getContentHint();n&&s.setContentHint(n),this._initLocalTrackEvents(s),this._localVideoTrack=s;this._localVideoPlayerConfig[StreamIndex$1.STREAM_INDEX_MAIN].forEach((e=>{var t,i;null==(i=this._localVideoTrack)||i.setPlayer(e,this._mirrorType,null==(t=this._config)?void 0:t.autoPlayPolicy,this._initPlayerEvents.bind(this))}));o=s.originTrack.getSettings();const a={width:o.width,height:o.height};if(this._localVideoTrack.resolution=a,this._ctx.videoProfile.__autoResetVideoEncoderConfig(o),setTimeout((()=>this.safeEmit(EngineEventsTypes.onLocalVideoSizeChanged,{streamIndex:StreamIndex$1.STREAM_INDEX_MAIN,info:a}))),this._ctx.engineDestroyed)return this._destroyLocalTrack(),o;if(this._wtnStreamManager._updatePushTrack(),!this._room)return o;const{isAutoPublish:d}=this._room.config;return((null==(t=this._room.localStream)?void 0:t.pubVideo)||d)&&this._ctx.visibility&&this._updatePublish(),null==(r=null==(i=this._room.localStream)?void 0:i.observer)||r.setEnableVideo(!0),o}async getLocalStreamStats(){var e;return await(null==(e=this._room)?void 0:e.getLocalStreamStats())}async stopVideoCapture(){var e,t,i;if(this.logger.info("stopVideoCapture()"),this._trackSourceType.video===VideoSourceType.VIDEO_SOURCE_TYPE_EXTERNAL)throw new SDKError(ErrorCode.STREAM_TYPE_NOT_MATCH,"setVideoSourceType as internal first");if(this._localVideoTrack&&!this._localVideoTrack.dummy){const e=this._ctx.extensionManager.getPluginByName(RTCExtensionType.PRE_PROCESSING,"RTCBeautyExtension");e&&e.emit("stop"),this._removeLocalTrackEvents(this._localVideoTrack),this._localVideoTrack.destroy(),this._localImgVideoTrack?this._localVideoTrack.setTrack(this._localImgVideoTrack,{isDummy:!0}):this._localVideoTrack=void 0}this._wtnStreamManager._updatePushTrack(),this._room&&((null==(e=this._room.localStream)?void 0:e.pubVideo)&&await this._updatePublish(),null==(i=null==(t=this._room.localStream)?void 0:t.observer)||i.setEnableVideo(!1))}async startAudioCapture(e){var t,i,r;if(this.logger.info("startAudioCapture()","deviceId: $o",e),isEmpty(e)||checkString(e,"deviceId"),e&&this._ctx.audioProfileManager.updateConstraints({deviceId:{exact:e}}),this._trackSourceType.audio===AudioSourceType.AUDIO_SOURCE_TYPE_EXTERNAL)throw new SDKError(ErrorCode.STREAM_TYPE_NOT_MATCH,"setAudioSourceType as internal first");if(this._localAudioTrack)throw new SDKError(ErrorCode.REPEAT_CAPTURE,"Has already capture");let o={};const s=await createMicrophoneAudioTrack(this._ctx,this._ctx.audioProfileManager.getConstraints());o=s.originTrack.getSettings(),this._initLocalTrackEvents(s),this._localAudioTrack=s,this._localAudioTrack.setVolume(this._localAudioVolume);const{frameSize:n,callback:a}=this._ctx._localAudioTrackDumpConfig[StreamIndex$1.STREAM_INDEX_MAIN];n&&a&&this._localAudioTrack.setDataFetcher(n,a);const{position:d,volume:c}=this._ctx.earMonitorSettings[StreamIndex$1.STREAM_INDEX_MAIN];if(d!==EarMonitorPosition.NONE&&(this._localAudioTrack.play(d),this._localAudioTrack.setPlaybackVolume(c)),this._tempMixingAudioTrack&&(this._localAudioTrack.mixType=this._tempMixingAudioTrack.type,this._localAudioTrack.mixedAudioTrack=this._tempMixingAudioTrack.track,delete this._tempMixingAudioTrack),this._ctx.engineDestroyed)return this._destroyLocalTrack(),o;if(this._wtnStreamManager._updatePushTrack(),!this._room)return o;const{isAutoPublish:l}=this._room.config;return((null==(t=this._room.localStream)?void 0:t.pubAudio)||l)&&this._ctx.visibility&&this._updatePublish(),null==(r=null==(i=this._room.localStream)?void 0:i.observer)||r.setEnableAudio(!0),o}async stopAudioCapture(){var e,t,i,r;if(this.logger.info("stopAudioCapture()"),this._trackSourceType.audio===AudioSourceType.AUDIO_SOURCE_TYPE_EXTERNAL)throw new SDKError(ErrorCode.STREAM_TYPE_NOT_MATCH,"setAudioSourceType as internal first");this._localAudioTrack&&(this._removeLocalTrackEvents(this._localAudioTrack),this._localAudioTrack.destroy()),this._localAudioTrack=void 0,null==(e=this._audioMixingManager)||e.stopAll(),this._wtnStreamManager._updatePushTrack(),this._room&&((null==(t=this._room.localStream)?void 0:t.pubAudio)&&await this._updatePublish(),null==(r=null==(i=this._room.localStream)?void 0:i.observer)||r.setEnableAudio(!1))}async startAudioAndVideoCapture(e,t){var i,r,o,s,n,a;this.logger.print("startAudioAndVideoCapture","optionsOrAudioDeviceId: $o",e,"videoDeviceId: $o",t);const{audioDeviceId:d,videoDeviceId:c}=checkAudioAndVideoDeviceId(e,t);if(d&&this._ctx.audioProfileManager.updateConstraints({deviceId:{exact:d}}),this._trackSourceType.video===VideoSourceType.VIDEO_SOURCE_TYPE_EXTERNAL||this._trackSourceType.audio===AudioSourceType.AUDIO_SOURCE_TYPE_EXTERNAL)throw new SDKError(ErrorCode.STREAM_TYPE_NOT_MATCH,this._trackSourceType.video===VideoSourceType.VIDEO_SOURCE_TYPE_EXTERNAL?"setVideoSourceType as internal first":"setAudioSourceType as internal first");if(this._localVideoTrack&&!this._localVideoTrack.dummy)throw new SDKError(ErrorCode.REPEAT_CAPTURE,"video has already capture");if(this._localAudioTrack)throw new SDKError(ErrorCode.REPEAT_CAPTURE,"audio has already capture");const l=this._ctx.videoProfile.getCaptureConfig(c);let u={},_={};const{audioTrack:h,videoTrack:p}=await createMicrophoneAndCameraTrack(this._ctx,this._ctx.audioProfileManager.getConstraints(),l),m=this._ctx.videoProfile.getContentHint();m&&p.setContentHint(m),c&&this._ctx.videoProfile.setCaptureDeviceId(c),this._initLocalTrackEvents(p),this._localVideoTrack=p;this._localVideoPlayerConfig[StreamIndex$1.STREAM_INDEX_MAIN].forEach((e=>{var t,i;null==(i=this._localVideoTrack)||i.setPlayer(e,this._mirrorType,null==(t=this._config)?void 0:t.autoPlayPolicy,this._initPlayerEvents.bind(this))})),this._initLocalTrackEvents(h),this._localAudioTrack=h,this._localAudioTrack.setVolume(this._localAudioVolume);const{frameSize:S,callback:g}=this._ctx._localAudioTrackDumpConfig[StreamIndex$1.STREAM_INDEX_MAIN];S&&g&&this._localAudioTrack.setDataFetcher(S,g),this._tempMixingAudioTrack&&(this._localAudioTrack.mixType=this._tempMixingAudioTrack.type,this._localAudioTrack.mixedAudioTrack=this._tempMixingAudioTrack.track,delete this._tempMixingAudioTrack);let v=p.originTrack;u=v.getSettings();const f={width:u.width||0,height:u.height||0};if(this._localVideoTrack.resolution=f,this._ctx.videoProfile.__autoResetVideoEncoderConfig(u),setTimeout((()=>this.safeEmit(EngineEventsTypes.onLocalVideoSizeChanged,{streamIndex:StreamIndex$1.STREAM_INDEX_MAIN,info:f}))),v=h.originTrack,_=v.getSettings(),this._ctx.engineDestroyed)return this._destroyLocalTrack(),{audioTrackSettings:_,videoTrackSettings:u};if(this._wtnStreamManager._updatePushTrack(),!this._room)return{audioTrackSettings:_,videoTrackSettings:u};const{isAutoPublish:E}=this._room.config;return((null==(i=this._room.localStream)?void 0:i.pubVideo)||(null==(r=this._room.localStream)?void 0:r.pubAudio)||E)&&this._ctx.visibility&&this._updatePublish(),null==(s=null==(o=this._room.localStream)?void 0:o.observer)||s.setEnableVideo(!0),null==(a=null==(n=this._room.localStream)?void 0:n.observer)||a.setEnableAudio(!0),{audioTrackSettings:_,videoTrackSettings:u}}async startVideoAndAudioCapture(e,t){return this.startAudioAndVideoCapture(t,e)}getAudioMixingManager(){return this.logger.info("getAudioMixingManager()","invoke"),this._audioMixingManager||(this._audioMixingManager=new AudioMixingManager({getLocalAudioTrack:()=>this._localAudioTrack,updateLocalAudioTrack:this._updateMixAudioTrack,emitMessage:this._onAudioMixingMessage,onAutoPlayFailed:this._onAudioMixingAutoplayFailed},this.id)),this._audioMixingManager}getWTNStreamManager(){return this._wtnStreamManager}getCallId(){var e;return null==(e=this._ctx)?void 0:e.callId}async startScreenCapture(e={}){var t,i,r,o,s;if(this.logger.info("startScreenCapture()","config: %o",e),this._trackSourceType.screenVideo===VideoSourceType.VIDEO_SOURCE_TYPE_EXTERNAL)throw new SDKError(ErrorCode.STREAM_TYPE_NOT_MATCH,"setVideoSourceType as internal first");if(this._trackSourceType.screenAudio===AudioSourceType.AUDIO_SOURCE_TYPE_EXTERNAL)throw new SDKError(ErrorCode.STREAM_TYPE_NOT_MATCH,"setAudioSourceType as internal first");const[n,a]=await createScreenTracks(this._ctx,e);null==a||a.setVolume(this._localScreenAudioVolume),this._localScreenVideoTrack&&!this._localScreenVideoTrack.dummy&&(this._removeLocalTrackEvents(this._localScreenVideoTrack),this._localScreenVideoTrack.destroy()),null==(t=this._localScreenAudioTrack)||t.destroy(),delete this._localScreenAudioTrack,this._localScreenVideoTrack=n;const{contentHint:d}=this._ctx.videoProfile.getScreenEncodeConfig();d&&n.setContentHint(d);const c=n.originTrack;setTimeout((()=>{const e=c.getSettings(),t={width:e.width,height:e.height};n.resolution=t,this.safeEmit(EngineEventsTypes.onLocalVideoSizeChanged,{streamIndex:StreamIndex$1.STREAM_INDEX_SCREEN,info:{width:e.width,height:e.height}})}),500),a&&(this._localScreenAudioTrack=a,this._initLocalTrackEvents(a));this._localVideoPlayerConfig[StreamIndex$1.STREAM_INDEX_SCREEN].forEach((e=>{var t,i;null==(i=this._localScreenVideoTrack)||i.setPlayer(e,MirrorType.MIRROR_TYPE_NONE,null==(t=this._config)?void 0:t.autoPlayPolicy,this._initPlayerEvents.bind(this))})),this._initLocalTrackEvents(this._localScreenVideoTrack,!0),((null==(r=null==(i=this._room)?void 0:i.localScreenStream)?void 0:r.pubAudio)||(null==(s=null==(o=this._room)?void 0:o.localScreenStream)?void 0:s.pubVideo))&&await this._updateScreenPublish()}async stopScreenCapture(){var e,t,i,r,o,s;this.logger.info("stopScreenCapture()"),null==(e=this._localScreenVideoTrack)||e.stopAll(),this._localScreenVideoTrack&&(this._localScreenVideoTrack.dummy||(this._removeLocalTrackEvents(this._localScreenVideoTrack),this._localScreenVideoTrack.destroy(),this._localImgScreenTrack&&this._localScreenVideoTrack.setTrack(this._localImgScreenTrack,{isDummy:!0}))),this._localScreenAudioTrack&&(this._removeLocalTrackEvents(this._localScreenAudioTrack),this._localScreenAudioTrack.destroy()),this._localScreenAudioTrack=void 0,(null==(t=this._localScreenVideoTrack)?void 0:t.dummy)||(this._localScreenVideoTrack=void 0),((null==(r=null==(i=this._room)?void 0:i.localScreenStream)?void 0:r.pubAudio)||(null==(s=null==(o=this._room)?void 0:o.localScreenStream)?void 0:s.pubVideo))&&await this._updateScreenPublish()}setLocalVideoPlayer(e,t){var i,r,o,s,n;this.logger.info("setLocalVideoPlayer()","streamIndex: %o, videoPlayerOption: %o",e,t),checkEnum(e,"streamIndex",[StreamIndex$1.STREAM_INDEX_MAIN,StreamIndex$1.STREAM_INDEX_SCREEN]);const a=e===StreamIndex$1.STREAM_INDEX_MAIN?this._localVideoTrack:this._localScreenVideoTrack,d=(null==t?void 0:t.playerId)??DEFAULT_PLAYER_ID;if(!(null==t?void 0:t.renderDom)){null==(r=null==(i=this._localVideoPlayerConfig[e].get(d))?void 0:i.player)||r.destroy(),null==a||a.removePlayer(d);const t=null==(o=this._localVideoPlayerConfig[e].get(d))?void 0:o.renderDom;return this._containerCollisionDetector.unregisterContainer(t),void this._localVideoPlayerConfig[e].delete(d)}checkVideoPlayerOption(t);const c=this._localVideoPlayerConfig[e].get(d);if(!c){const{renderDom:i}=t;if(!this._containerCollisionDetector.registerContainer(i))return this.monitor.report("rtc_error",{message:"RenderDom is not empty",error_code:RtcErrorCode.DUPLICATE_DOM}),void warnDevelopers("renderDom is not empty");const r=new VideoPlayer(this._ctx.id,d,{...t,isLocal:!0,isScreen:e===StreamIndex$1.STREAM_INDEX_SCREEN,userId:t.userId??"_local_"}),o={...t,player:r};return this._localVideoPlayerConfig[e].set(d,o),null==a||a.setPlayer(o,e===StreamIndex$1.STREAM_INDEX_MAIN?this._mirrorType:MirrorType.MIRROR_TYPE_NONE,null==(s=this._config)?void 0:s.autoPlayPolicy,this._initPlayerEvents.bind(this)),null==(n=o.player)?void 0:n.domElement}void 0!==t.renderMode&&(null==a||a.setRenderMode(d,t.renderMode),c.renderMode=t.renderMode)}async startLiveTranscoding(e){var t;this.logger.info("startLiveTranscoding()","transcode: %o",e),LiveTranscoding.checkStartParams(e),this._liveTranscodeConfig=e;const i=null==(t=this._room)?void 0:t.config;if(i&&i.roomId.length+i.userId.length>126)throw new SDKError(ErrorCode.INVALID_PARAMS,"The roomId+userId must be within 126 bytes");try{this.safeEmit(EngineEventsTypes.onStreamMixingEvent,{event:StreamMixingEventType.START,error:0,message:""}),this._room&&this._ctx.signalingManager.isConnected()&&await this._room.liveControlMessage(LiveTranscoding.getStartParams(this._liveTranscodeConfig))}catch(e){throw e instanceof SDKError?e:new SDKError(ErrorCode.UNEXPECTED_ERROR,"unexpected error",e)}}async updateLiveTranscoding(e){var t,i,r;if(this.logger.info("updateLiveTranscoding()","transcode: %o",e),!this._liveTranscodeConfig)return;const o=assignIn({},e);delete o.audio,null==(t=o.video)||delete t.codec,null==(i=o.video)||delete i.gop,LiveTranscoding.checkUpdateParams(o),this._liveTranscodeConfig=assignIn(this._liveTranscodeConfig,o);try{this.safeEmit(EngineEventsTypes.onStreamMixingEvent,{event:StreamMixingEventType.UPDATE,error:0,message:""}),await(null==(r=this._room)?void 0:r.liveControlMessage(LiveTranscoding.getUpdateParams(this._liveTranscodeConfig)))}catch(e){throw e instanceof SDKError?e:new SDKError(ErrorCode.UNEXPECTED_ERROR,"unexpected error",e)}}async stopLiveTranscoding(){var e;if(this.logger.info("stopLiveTranscoding()"),this._liveTranscodeConfig){delete this._liveTranscodeConfig;try{this.safeEmit(EngineEventsTypes.onStreamMixingEvent,{event:StreamMixingEventType.STOP,error:0,message:""}),await(null==(e=this._room)?void 0:e.liveControlMessage({action:"stopped",type:"transcode"}))}catch(e){throw e instanceof SDKError?e:new SDKError(ErrorCode.UNEXPECTED_ERROR,"unexpected error",e)}}}async startSubtitle(e){var t;this.logger.info("startSubtitle()","config: %o",e),this._assertNotInRoom(),await(null==(t=this._room)?void 0:t.startSubtitle(e))}async updateSubtitleConfig(e){var t;this.logger.info("updateSubtitleConfig()","config: %o",e),this._assertNotInRoom(),await(null==(t=this._room)?void 0:t.updateSubtitleConfig(e))}stopSubtitle(){var e;this.logger.info("stopSubtitle()","invoke"),null==(e=this._room)||e.stopSubtitle()}setBusinessId(e){return this.logger.info("setBusinessId()","businessId: %s",e),!illegalBusinessId(e)&&!this._room&&(this._ctx.businessId=e,!0)}async setUserVisibility(e){var t,i;if(this.logger.info("setUserVisibility()","enable: %o",e),e=!!e,this._ctx.visibility!==e)if(this._room){if(this._assertNotInRoom(),this._room.localStream&&(null==(t=this._room.localStream.observer)||t.setPublisher(e)),!e){const e=await this._pubLock.lock();try{this._room.unpublish(),this._room.unpublishScreen()}finally{e()}}this._ctx.visibility=e;try{await this._room.updateUserAttributes()}catch(t){throw this._ctx.visibility=!e,t}e&&(null==(i=this._room)?void 0:i.config.isAutoPublish)&&this._updatePublish({mediaType:MediaType$1.AUDIO_AND_VIDEO})}else this._ctx.visibility=e}_initPlayerEvents(e,t=!1,i=StreamIndex$1.STREAM_INDEX_MAIN){const r=i===StreamIndex$1.STREAM_INDEX_SCREEN;e.on("playback_event",(i=>{var o,s,n,a,d,c;switch(i.eventName){case"timeupdate":if(!e.hasStartPlaying&&e instanceof AudioPlayer){e.hasStartPlaying=!0;const t=e.userId.replace("_screen",""),i=null==(s=null==(o=this._room)?void 0:o.remoteStreams.get(t))?void 0:s.find((e=>e.isScreen===r));setTimeout((()=>{var e,t;const o={is_screen:r,media_type:"audio",codec:null==(t=null==(e=null==i?void 0:i.getRemoteStreamStats())?void 0:e.audioStats)?void 0:t.codecType};this.logger.info("remote_audio_playing",JSON.stringify(o)),this.monitor.report("remote_audio_playing",o)}),8e3)}return;case"loadeddata":if("audio"===i.type){const i=e.userId.replace("_screen",""),o=null==(a=null==(n=this._room)?void 0:n.remoteStreams.get(i))?void 0:a.find((e=>e.isScreen===r)),s=()=>{t?this.safeEmit(EngineEventsTypes.onFirstPublicStreamAudioFrameDecoded,{publicStreamId:i}):(this.safeEmit(EngineEventsTypes.onAudioFirstFrameDecoded,{userId:i,isScreen:r}),this.safeEmit(EngineEventsTypes.onRemoteAudioFirstFrame,{userId:i,isScreen:r})),this.monitor.report("first_remote_audio_render",{stream_id:"",stream_user_id:i||""},{isScreen:r})};!(null==o?void 0:o.observer)||o.observer.audioFirstFrameReceived?s():o.observer.once("recvAudioFirstFrame",s)}else{const o={userId:e.userId,height:e.videoHeight||0,width:e.videoWidth||0,isScreen:r,playerId:e.playerId};t?(o.publicStreamId=o.userId,delete o.userId,delete o.isScreen,this.safeEmit(EngineEventsTypes.onFirstPublicStreamVideoFrameRendered,o),this.safeEmit(EngineEventsTypes.onFirstPublicStreamVideoFrameDecoded,o)):e.isLocal||(this.safeEmit(EngineEventsTypes.onVideoFirstFrameRendered,o),this.safeEmit(EngineEventsTypes.onVideoFirstFrameDecoded,o),this.safeEmit(EngineEventsTypes.onRemoteVideoFirstFrame,o)),this.monitor.report("first_remote_video_render",{stream_id:"",stream_user_id:i.userId||""},{isScreen:r})}break;case"autoplay-error":{t&&(i.publicStreamId=i.userId),reportRtcInvokeStatus(this.id,"autoplay-error",e instanceof VideoPlayer?"video":"audio",0,i.userId||"");const r={userId:i.userId,kind:e instanceof VideoPlayer?"video":"audio",mediaType:e instanceof VideoPlayer?MediaType$1.VIDEO:MediaType$1.AUDIO,streamIndex:e.isScreen?StreamIndex$1.STREAM_INDEX_SCREEN:StreamIndex$1.STREAM_INDEX_MAIN};return e instanceof VideoPlayer&&(r.playerId=e.playerId===DEFAULT_PLAYER_ID?void 0:e.playerId),void this.safeEmit(EngineEventsTypes.onAutoplayFailed,r)}case"playing":{const t=e.userId.replace("_screen",""),o=null==(c=null==(d=this._room)?void 0:d.remoteStreams.get(t))?void 0:c.find((e=>e.isScreen===r));"video"===i.type&&setTimeout((()=>{var e,t,i,s,n,a,d,c,l,u,_,h,p,m,S,g,v,f,E;const T={is_screen:r,media_type:"video",codec:null==(t=null==(e=null==o?void 0:o.getRemoteStreamStats())?void 0:e.videoStats)?void 0:t.codecType,stats_frame_size_width:null==(s=null==(i=null==o?void 0:o.getRemoteStreamStats())?void 0:i.videoStats)?void 0:s.frameSizeWidth,stats_frame_size_height:null==(a=null==(n=null==o?void 0:o.getRemoteStreamStats())?void 0:n.videoStats)?void 0:a.frameSizeHeight,stats_frame_rate_decode:null==(c=null==(d=null==o?void 0:o.getRemoteStreamStats())?void 0:d.videoStats)?void 0:c.decoderOutputFrameRate,stats_frame_rate_receive:null==(u=null==(l=null==o?void 0:o.getRemoteStreamStats())?void 0:l.videoStats)?void 0:u.receivedFrameRate,stats_frame_decoder_name:null==(h=null==(_=null==o?void 0:o.getRemoteStreamStats())?void 0:_.videoStats)?void 0:h.decoderName,stats_gpu_url:Config2.GPU_URL||(null==(p=getGpuInfo())?void 0:p.renderer),track_frame_size_width:null==(S=null==(m=null==o?void 0:o.videoTrack)?void 0:m.originTrack)?void 0:S.getSettings().width,track_frame_size_height:null==(v=null==(g=null==o?void 0:o.videoTrack)?void 0:g.originTrack)?void 0:v.getSettings().height,track_frame_rate:null==(E=null==(f=null==o?void 0:o.videoTrack)?void 0:f.originTrack)?void 0:E.getSettings().frameRate};this.logger.info("remote_video_playing",JSON.stringify(T)),this.monitor.report("remote_video_playing",T)}),8e3);break}}e instanceof VideoPlayer&&(i.playerId=e.playerId===DEFAULT_PLAYER_ID?void 0:e.playerId),this.safeEmit(EngineEventsTypes.onPlayerEvent,i)}))}_initLocalTrackEvents(e,t=!1){["track-ended","track-mute","track-unmute"].forEach((t=>{e.on(t,(async e=>{this.monitor.report("rtc_error",{message:`track-${t} mediaType: ${e.originTrack.kind}`,error_code:RtcErrorCode.TRACK_ERROR,capture_session_id:e.captureSessionId,media_type:t,reason:t});let i=!1;e!==this._localScreenAudioTrack&&e!==this._localScreenVideoTrack||(i=!0);const{kind:r}=e.originTrack,o=e.sourceType;this.safeEmit({"track-ended":EngineEventsTypes.onTrackEnded,"track-mute":EngineEventsTypes.onTrackMute,"track-unmute":EngineEventsTypes.onTrackUnmute}[t],{kind:r,isScreen:i}),Config2.DISABLE_IOS_MUTE_WORKAROUND||!isIOS&&!isIPad||("track-mute"===t&&(internalEventBus.emit(InternalEvent.ON_IOS_LOCAL_TRACK_MUTE,r),"audio"===r&&o===SourceType.INTERNAL&&(await this.stopAudioCapture(),this.startAudioCapture())),"track-unmute"===t&&internalEventBus.emit(InternalEvent.ON_IOS_LOCAL_TRACK_UNMUTE,r))}))})),e.on("resolution-change",(e=>{this._ctx.extensionManager.getPluginsByType(RTCExtensionType.PRE_PROCESSING).forEach((i=>{var r;null==(r=null==i?void 0:i.applyConstraints)||r.call(i,t?StreamIndex$1.STREAM_INDEX_SCREEN:StreamIndex$1.STREAM_INDEX_MAIN,e)})),this.safeEmit(EngineEventsTypes.onLocalVideoSizeChanged,{streamIndex:t?StreamIndex$1.STREAM_INDEX_SCREEN:StreamIndex$1.STREAM_INDEX_MAIN,info:e})})),e.on("needReplaceTrack",(()=>{var t,i;if(e instanceof LocalAudioTrack){e.stopDataFetcher();const r=this._ctx._localAudioTrackDumpConfig[e.streamIndex??StreamIndex$1.STREAM_INDEX_MAIN];(null==r?void 0:r.frameSize)&&(null==r?void 0:r.callback)&&e.setDataFetcher(r.frameSize,r.callback);const{position:o,volume:s}=this._ctx.earMonitorSettings[e.streamIndex??StreamIndex$1.STREAM_INDEX_MAIN];if(o!==EarMonitorPosition.NONE&&(e.play(o),e.setPlaybackVolume(s)),this._room){const{streamIndex:r}=e;r===StreamIndex$1.STREAM_INDEX_MAIN?(null==(t=this._room.localStream)?void 0:t.pubAudio)&&this._ctx.visibility&&this._updatePublish():(null==(i=this._room.localStream)?void 0:i.pubAudio)&&this._ctx.visibility&&this._updateScreenPublish()}}})),e.on("autoplay-error",(e=>{this.safeEmit(EngineEventsTypes.onAutoplayFailed,e)}))}_removeLocalTrackEvents(e){e.removeAllListeners("track-ended"),e.removeAllListeners("track-mute"),e.removeAllListeners("track-unmute"),e.removeAllListeners("resolution-change")}setRemoteVideoPlayer(e,t){var i,r,o,s,n,a,d,c;this.logger.info("setRemoteVideoPlayer()","streamIndex: %o, videoPlayerOption: %o",e,t),checkEnum(e,"streamIndex",[StreamIndex$1.STREAM_INDEX_MAIN,StreamIndex$1.STREAM_INDEX_SCREEN]),checkVideoPlayerOption(t);const{userId:l}=t,u=e===StreamIndex$1.STREAM_INDEX_SCREEN,_=null==(r=null==(i=this._room)?void 0:i.remoteStreams.get(l))?void 0:r.find((e=>e.isScreen===u)),h=null==_?void 0:_.videoTrack,p=t.playerId??DEFAULT_PLAYER_ID;null==(s=null==(o=this._getRemoteVideoPlayerConfig(e,l,p))?void 0:o.player)||s.destroy();const m=null==(n=this._getRemoteVideoPlayerConfig(e,l,p))?void 0:n.renderDom;if(this._containerCollisionDetector.unregisterContainer(m),!t.renderDom)return null==(a=this._remoteVideoPlayerConfig[e].get(l))||a.delete(p),void(null==h||h.removePlayer(p));const{renderDom:S}=t;if(!this._containerCollisionDetector.registerContainer(S))return this.monitor.report("rtc_error",{message:"RenderDom is not empty",error_code:RtcErrorCode.DUPLICATE_DOM}),void warnDevelopers("renderDom is not empty");const g=new VideoPlayer(this.id,p,{...t,isLocal:!1,isScreen:u,userId:l,alphaInfo:null==_?void 0:_.attributes.alphaInfo}),v={...t,player:g};return this._setRemoteVideoPlayerConfig(e,l,p,v),null==h||h.setPlayer(this.id,v,null==(d=this._config)?void 0:d.autoPlayPolicy,this._initPlayerEvents.bind(this)),_&&this._updateVideoPlayerState(_),null==(c=v.player)?void 0:c.domElement}setLocalVideoMirrorType(e){var t;this.logger.info("setLocalVideoMirrorType()","mirrorType: %o",e),checkEnum(e,"mirrorType",[MirrorType.MIRROR_TYPE_NONE,MirrorType.MIRROR_TYPE_RENDER]),this._mirrorType=e,null==(t=this.localVideoTrack)||t.mirror(!!e)}setRemoteVideoMirrorType(e,t,i){var r,o,s,n;this.logger.info("setRemoteVideoMirrorType()","userId: %s, streamIndex: %o, mirrorType: %o",e,t,i),checkUserId(e),checkEnum(t,"streamIndex",[StreamIndex$1.STREAM_INDEX_MAIN,StreamIndex$1.STREAM_INDEX_SCREEN]),checkEnum(i,"mirrorType",[MirrorType.MIRROR_TYPE_NONE,MirrorType.MIRROR_TYPE_RENDER]),this._ctx.setUserStreamConf(e,t,{mirrorType:i}),null==(n=null==(s=null==(o=null==(r=this._room)?void 0:r.remoteStreams.get(e))?void 0:o.find((e=>e.isScreen===(t===StreamIndex$1.STREAM_INDEX_SCREEN))))?void 0:s.videoTrack)||n.mirror(!!i)}async setAudioPlaybackDevice(e){var t;this.logger.info("setAudioPlaybackDevice()","deviceId: %s",e),checkString(e,"deviceId");const i=await this._audioDeviceManager.setSinkId(e);null==(t=this._room)||t.remoteStreams.forEach((t=>{t.forEach((t=>{var i;null==(i=t.audioTrack)||i.setPlaybackDevice(e)}))})),this.safeEmit(EngineEventsTypes.onAudioPlaybackDeviceChanged,i),this.monitor.report("rtc_audio_device",{audio_event:"playout_device_switch",message:JSON.stringify(i),error_code:0})}async play(e,t=MediaType$1.AUDIO_AND_VIDEO,i,r){var o,s,n;this.logger.info("play()","userId: %s, mediaType: %s, streamIndex: %s",e,t,i);const a=r??DEFAULT_PLAYER_ID,d=!e||e===this._getUserId()||"local_user"===e,c=void 0===i||i===StreamIndex$1.STREAM_INDEX_MAIN,l=void 0===i||i===StreamIndex$1.STREAM_INDEX_SCREEN,u=t!==MediaType$1.VIDEO,_=t!==MediaType$1.AUDIO,h=[];if(d&&_){if(c&&this._localVideoTrack){this._localVideoTrack.mirror(!!this._mirrorType);const e=this._localVideoTrack.play(a);e&&h.push(e)}if(l&&this._localScreenVideoTrack){(null==(o=this._localScreenVideoTrack)?void 0:o.manuallyPlay(a))&&h.push()}}this._audioMixingManager&&e===this._audioMixingManager.id&&h.push(this._audioMixingManager.resumeLocalPlay());let p=[];return null==(s=this._room)||s.remoteStreams.forEach(((t,i)=>{e&&e!==i||t.forEach((e=>{e.audioTrack&&p.push(e.audioTrack),e.videoTrack&&p.push(e.videoTrack)}))})),this._wtnStreamManager.__getRemoteStreams().forEach(((t,i)=>{e&&e!==i||(t.audioTrack&&p.push(t.audioTrack),t.videoTrack&&p.push(t.videoTrack))})),c||(p=p.filter((e=>!!e.isScreen))),l||(p=p.filter((e=>!e.isScreen))),u||(p=p.filter((e=>"audio"!==e.mediaType))),_||(p=p.filter((e=>"video"!==e.mediaType))),u&&(null==(n=this._room)||n.virtualStreams.forEach((e=>{e.audioTrack&&p.push(e.audioTrack)}))),p.forEach((e=>{const t=e.manuallyPlay(a);t&&h.push(t)})),Promise.all(h).then((()=>{}))}async stop(e,t=MediaType$1.AUDIO_AND_VIDEO,i,r){var o,s;this.logger.info("stop()","userId: %s, mediaType: %s, streamIndex: %s, playerId: %s",e,t,i,r);const n=r??DEFAULT_PLAYER_ID,a=!e||e===this._getUserId()||"local_user"===e,d=void 0===i||i===StreamIndex$1.STREAM_INDEX_MAIN,c=void 0===i||i===StreamIndex$1.STREAM_INDEX_SCREEN,l=t!==MediaType$1.VIDEO,u=t!==MediaType$1.AUDIO;if(a&&u&&(d&&this._localVideoTrack&&this._localVideoTrack.pause(n),c&&this._localScreenVideoTrack&&this._localScreenVideoTrack.pause(n)),e){let t=[];null==(s=null==(o=this._room)?void 0:o.remoteStreams.get(e))||s.forEach((e=>{e.audioTrack&&t.push(e.audioTrack),e.videoTrack&&t.push(e.videoTrack)}));const i=this._wtnStreamManager.__getPublicStreamTrack(e,"audio"),r=this._wtnStreamManager.__getPublicStreamTrack(e,"video");i&&t.push(i),r&&t.push(r),d||(t=t.filter((e=>!!e.isScreen))),c||(t=t.filter((e=>!e.isScreen))),l||(t=t.filter((e=>"audio"!==e.mediaType))),u||(t=t.filter((e=>"video"!==e.mediaType))),t.forEach((e=>{e.pause(n)}))}}getAudioVolume(e,t){var i,r,o;checkEnum(e,"streamIndex",[StreamIndex$1.STREAM_INDEX_MAIN,StreamIndex$1.STREAM_INDEX_SCREEN]);let s=0;if(t){const n=null==(o=null==(r=null==(i=this._room)?void 0:i.remoteStreams.get(t))?void 0:r.find((t=>t.isScreen===(e===StreamIndex$1.STREAM_INDEX_SCREEN))))?void 0:o.audioTrack;n&&(s=n.getAudioLevel())}else{const t=e===StreamIndex$1.STREAM_INDEX_MAIN?this._localAudioTrack:this._localScreenAudioTrack;t&&(s=t.getAudioLevel())}return{linearVolume:s,nonlinearVolume:getNonlinearVolume(s)}}setAudioFrameCallback(e,t,i,r=4096){var o,s,n;if(this.logger.info("setAudioFrameCallback()","streamIndex: %s, userId: %s, callback: %s, frameSize: %s",e,t,i?"true":"false",r),checkEnum(r,"frameSize",[256,512,1024,2048,4096,8192,16384]),void 0===audioContextManager.isWorkletReady&&audioContextManager.getAudioContextInstance(),null===audioContextManager.isWorkletReady)throw this.logger.error("setAudioFrameCallback()","Not support AudioWorklet"),new SDKError(ErrorCode.NOT_SUPPORTED,"Not support AudioWorklet");t?i?this._ctx._remoteAudioTrackDumpConfig[e].set(t,{callback:i,frameSize:r}):this._ctx._remoteAudioTrackDumpConfig[e].delete(t):this._ctx._localAudioTrackDumpConfig[e]={callback:i,frameSize:i?r:void 0};const a=t?null==(n=null==(s=null==(o=this._room)?void 0:o.remoteStreams.get(t))?void 0:s.find((t=>t.isScreen===(e===StreamIndex$1.STREAM_INDEX_SCREEN))))?void 0:n.audioTrack:e===StreamIndex$1.STREAM_INDEX_MAIN?this._localAudioTrack:this._localScreenAudioTrack;a?i?a.setDataFetcher(r,i):a.stopDataFetcher():this.logger.warn("setAudioFrameCallback()","track not found")}async pauseAllSubscribedStream(e){this.logger.info("pauseAllSubscribedStream()","mediaType: %o",e),this._checkMediaType(e);return(()=>{audioInMediaType(e)&&(this._pauseAllSubscribeState.audio=!0),videoInMediaType(e)&&(this._pauseAllSubscribeState.video=!0)})(),this._room?this._pauseAllRemoteStreams(e):Promise.resolve()}async _pauseAllRemoteStreams(e){if(!this._room)return Promise.resolve();const t=[];return this._room.remoteStreams.forEach((i=>{Array.isArray(i)&&i.forEach((i=>{if(i.hasSubscribed){i.attributes.audiostream&&audioInMediaType(e)&&(this._pauseAllSubscribeState.resumeAudioStreamIds[i.streamId]=i.streamId),i.attributes.videostream&&videoInMediaType(e)&&(this._pauseAllSubscribeState.resumeVideoStreamIds[i.streamId]=i.streamId);const r=this._unsubscribe(i.isScreen,i.userId,e,!0);r&&t.push(r)}}))})),Promise.all(t).then((()=>{}))}async resumeAllSubscribedStream(e){this.logger.info("resumeAllSubscribedStream()","mediaType: %o",e),this._checkMediaType(e);if((()=>{audioInMediaType(e)&&(this._pauseAllSubscribeState.audio=!1),videoInMediaType(e)&&(this._pauseAllSubscribeState.video=!1)})(),!this._room)return Promise.resolve();await this._triedResumeAllRemoteStreams(e,!1)}async _triedResumeAllRemoteStreams(e,t){if(!this._room)return Promise.resolve();if(this._pauseAllSubscribeState.audio&&e===MediaType$1.AUDIO)return Promise.resolve();if(this._pauseAllSubscribeState.video&&e===MediaType$1.VIDEO)return Promise.resolve();if(this._pauseAllSubscribeState.video&&this._pauseAllSubscribeState.audio&&e===MediaType$1.AUDIO_AND_VIDEO)return Promise.resolve();const i=[],r=[...Object.keys(this._pauseAllSubscribeState.resumeAudioStreamIds)],o=[...Object.keys(this._pauseAllSubscribeState.resumeVideoStreamIds)];return this._room.remoteStreams.forEach((r=>{Array.isArray(r)&&r.forEach((r=>{if(t&&r.isScreen)return;const o=this._pauseAllSubscribeState.resumeAudioStreamIds[r.streamId],s=this._pauseAllSubscribeState.resumeVideoStreamIds[r.streamId];if(o&&audioInMediaType(e)||s&&videoInMediaType(e)){const t=this._subscribe(r.isScreen,r.userId,e).then((()=>{o&&audioInMediaType(e)&&delete this._pauseAllSubscribeState.resumeAudioStreamIds[r.streamId],s&&videoInMediaType(e)&&delete this._pauseAllSubscribeState.resumeVideoStreamIds[r.streamId]}));t&&i.push(t)}}))})),Promise.all(i).then((()=>{var e;return null==(e=this._room)||e.remoteStreams.forEach((e=>{Array.isArray(e)&&e.forEach((e=>{this._updateAudioPlayerState(e),this._updateVideoPlayerState(e)}))})),Promise.resolve()})).finally((()=>{var e;return(null==(e=this._room)?void 0:e.config.tokenSubscribePrivilegeExpired)&&(r.forEach((e=>{this._pauseAllSubscribeState.resumeAudioStreamIds[e]=e})),o.forEach((e=>{this._pauseAllSubscribeState.resumeVideoStreamIds[e]=e}))),Promise.resolve()}))}async sendUserMessage(e,t){var i,r;checkUserId(e),this._assertNotInRoom();const o=Date.now();return null==(r=null==(i=this._room)?void 0:i.sendUserMessage(e,t))?void 0:r.then((t=>(this._messageStatisticsObserver.countP2PMessage(!0,e,!1,o,t),t.id))).catch((t=>{throw this._messageStatisticsObserver.countP2PMessage(!1,e,!1,o,t),t}))}async sendUserBinaryMessage(e,t){var i,r;checkUserId(e),checkArrayBuffer(t,"message"),this._assertNotInRoom();const o=Date.now();return null==(r=null==(i=this._room)?void 0:i.sendUserMessage(e,t))?void 0:r.then((t=>(this._messageStatisticsObserver.countP2PMessage(!0,e,!0,o,t),t.id))).catch((t=>{throw this._messageStatisticsObserver.countP2PMessage(!1,e,!0,o,t),t}))}async sendRoomMessage(e){var t,i,r;this._assertNotInRoom();const o=null==(t=this._room)?void 0:t.config.roomId,s=Date.now();return null==(r=null==(i=this._room)?void 0:i.sendRoomMessage(e))?void 0:r.then((e=>(this._messageStatisticsObserver.countRoomMessage(!0,o,!1,s),e))).catch((e=>{throw this._messageStatisticsObserver.countRoomMessage(!1,o,!1,s),e}))}async sendRoomBinaryMessage(e){var t,i,r;this._assertNotInRoom();const o=null==(t=this._room)?void 0:t.config.roomId,s=Date.now();return null==(r=null==(i=this._room)?void 0:i.sendRoomMessage(e,!0))?void 0:r.then((e=>(this._messageStatisticsObserver.countRoomMessage(!0,o,!0,s),e))).catch((e=>{throw this._messageStatisticsObserver.countRoomMessage(!1,o,!0,s),e}))}async setAudioCaptureConfig(e={}){this.logger.info("setAudioCaptureConfig()","config: %o",e),delete e.deviceId,checkSupportedConstraints(e);await this._shouldUpdateAudioConf("setAudioCaptureConfig")&&this._ctx.audioProfileManager.updateConstraints(e)}async setVideoCaptureConfig(e={}){return this.logger.info("setVideoCaptureConfig()","config: %o",e),this._setVideoCaptureConfig(e)}async _setVideoCaptureConfig(e={}){var t;delete e.deviceId,checkSupportedConstraints(e);const i={...this._ctx.videoProfile.getCaptureConfig(),...e};return this._localVideoTrack&&await this._localVideoTrack.updateVideoCaptureConfig(i),this._ctx.videoProfile.setCaptureConfig(i),(null==(t=this._localVideoTrack)?void 0:t.originTrack.getSettings())||{}}enableSimulcastMode(e){this.logger.info("enableSimulcastMode()","enabled: %o",e),this._ctx.videoProfile.checkSimulcastApiVersion("old");try{return this._ctx.videoProfile.setSimulcastMode(e?VideoSimulcastMode.VIDEO_ON_DEMAND:VideoSimulcastMode.VIDEO_ONLY_ONE,this._room),!0}catch{return!1}}async setLocalSimulcastMode(e,t){var i;this.logger.info("setLocalSimulcastMode()","mode: %o, config: %o",e,t),this._ctx.videoProfile.checkSimulcastApiVersion("new"),await this._ctx.videoProfile.setSimulcastMode(e,this._room),await this._ctx.videoProfile.setSubVideoEncodeConfig(t,this._room,this._localVideoTrack);await(null==(i=this._room)?void 0:i.hasPublished())&&this._updatePublish()}async setVideoEncoderConfig(e){var t;if(this.logger.info("setVideoEncoderConfig()","descriptions: %o",e),await this._ctx.videoProfile.setVideoEncodeConfigPolyfill(e),this._localVideoTrack){const e=this._ctx.videoProfile.getContentHint();e&&this._localVideoTrack.setContentHint(e),await this._localVideoTrack.updateVideoCaptureConfig(this._ctx.videoProfile.getCaptureConfig())}this._updateDummyCaptureImage(StreamIndex$1.STREAM_INDEX_MAIN);await(null==(t=this._room)?void 0:t.hasPublished())&&this._updatePublish()}setVideoEncoderAutoConfigList(e){if(Array.isArray(e))return e.sort(((e,t)=>e.maxKbps-t.maxKbps)),setVideoEncoderAutoConfigList(e)}async setScreenEncoderConfig(e){var t;this.logger.info("setScreenEncoderConfig()","description: %o",e),this._ctx.videoProfile.setScreenEncodeConfig(e),this._localScreenVideoTrack&&("16.1"!==safariMinorVersion&&await this._localScreenVideoTrack.updateVideoCaptureConfig(e),e.contentHint&&this._localScreenVideoTrack.setContentHint(e.contentHint)),this._updateDummyCaptureImage(StreamIndex$1.STREAM_INDEX_SCREEN);await(null==(t=this._room)?void 0:t.hasScreenPublished())&&this._updateScreenPublish()}sendSEIMessage(e,t,i){var r,o,s,n,a,d,c,l,u;if(this.logger.info("sendSEIMessage()","streamIdex: %o, message: %o, repeatCount: %o",e,t,i),!isLegacyEncodedTransformSupported()&&!isEncodedTransformSupported())return warnDevelopers("Your browser does not support sending SEI"),!1;checkEnum(e,"streamIndex",[StreamIndex$1.STREAM_INDEX_MAIN,StreamIndex$1.STREAM_INDEX_SCREEN]),checkNumber(i,"repeatCount",0,30);const _="string"==typeof t?new Uint8Array(Utils.str2ab(t)):t;if(!t.length)return this.logger.warn("sei message must not be empty"),!1;let h;if(e===StreamIndex$1.STREAM_INDEX_MAIN){if(!(null==(o=null==(r=this._room)?void 0:r.localStream)?void 0:o.pubAudio)&&!(null==(n=null==(s=this._room)?void 0:s.localStream)?void 0:n.pubVideo))return;h=this._room.localStream}else{if(!(null==(d=null==(a=this._room)?void 0:a.localScreenStream)?void 0:d.pubAudio)&&!(null==(l=null==(c=this._room)?void 0:c.localScreenStream)?void 0:l.pubVideo))return;h=this._room.localScreenStream}if(_.byteLength>4096)return void this.logger.warn("sei size must not bigger than 4KB");isAndroid||null==(u=this._room)||u.maybeFillBackFrame2Stream(h);const p=genUuid();return h.sendSEIMessage({content:_,uuid:p,repeatCount:i+1}),setTimeout((async()=>{if(!h)return;if(await h.revokeSEIMessage(p)){const e=`timeout for sei message(id: ${p})`;console.error(`[RTC WebSDK] ${e}`),this.monitor.report("rtc_sdk_callback",{sdk_callback_name:"sendSEIMessageTimeout",message:e,error_code:400})}}),getParameter("SEI_TIME_OUT")),p}setAudioVolumeIndicationInterval(e){this.logger.info("setAudioVolumeIndicationInterval()","interval %o: ",e),("number"!=typeof e||e<200)&&(e=200);let t=[];this._audioVolumeIndicationTimer&&clearInterval(this._audioVolumeIndicationTimer),this._audioVolumeIndicationTimer=setInterval((()=>{var e,i;t=[],null==(e=this._room)||e.remoteStreams.forEach(((e,i)=>{var r;if(0===e.length)return;const o=e.find((e=>!e.isScreen)),s=null==(r=null==o?void 0:o.audioTrack)?void 0:r.getAudioLevel();t.push({userId:i,volume:s||0})}));const r=null==(i=this._localAudioTrack)?void 0:i.getAudioLevel();t.push({userId:this._getUserId(),volume:r||0}),this.safeEmit(EngineEventsTypes.onAudioVolumeIndication,{speakers:t})}),e)}_sendActiveSpeaker(e,t){if(this._room&&this._room.remoteUsers.size>=1){const i=e[0],r=t.reduce(((e,t)=>e&&e.audioPropertiesInfo.nonlinearVolume>t.audioPropertiesInfo.nonlinearVolume?e:t),void 0);let o;if(o=i?r?i.audioPropertiesInfo.nonlinearVolume>r.audioPropertiesInfo.nonlinearVolume?i:r:i:r,o&&o.audioPropertiesInfo.nonlinearVolume>-35){let e;e=o.streamKey?this._room.remoteUsers.get(o.streamKey.userId):this._room.config.userInfo,e&&this.safeEmit(EngineEventsTypes.onActiveSpeaker,{userId:e.userId,extraInfo:e.extraInfo})}}}enableAudioPropertiesReport(e={}){this.logger.info("enableAudioPropertiesReport()","config %o: ",e);const{enableInBackground:t=!0,localMainReportMode:i=LocalMainReportMode.NORMAL,audioReportMode:r=AudioReportMode.MICROPHONE}=e;let{interval:o=100}=e;this._stopAudioPropertiesReport(),o<=0||(o=Math.max(100,o),this._audioPropertiesReportTimer=self.setInterval((()=>{var e,o;if(!t&&"hidden"===document.visibilityState)return;const s=[],n=this._audioDeviceManager.getRecordTrack()||this._localAudioTrack;if(n){const t=null==(o=null==(e=this._room)?void 0:e.localStream)?void 0:o.audioHasPublish,a=!!this._audioDeviceManager.getRecordTrack(),d=n.getAudioLevel(r),c=getNonlinearVolume(d),l={streamIndex:StreamIndex$1.STREAM_INDEX_MAIN,audioPropertiesInfo:{linearVolume:d,nonlinearVolume:c}};if(t||a)s.push(l);else switch(i){case LocalMainReportMode.DISCONNECT:break;case LocalMainReportMode.RESET:l.audioPropertiesInfo.linearVolume=0,l.audioPropertiesInfo.nonlinearVolume=-127,s.push(l);break;case LocalMainReportMode.NORMAL:s.push(l);break;default:throw new SDKError(ErrorCode.INVALID_PARAMS,`invalid localMainReportMode: ${i} in config`)}}if(this._localScreenAudioTrack){const e=this._localScreenAudioTrack.getAudioLevel();s.push({streamIndex:StreamIndex$1.STREAM_INDEX_SCREEN,audioPropertiesInfo:{linearVolume:e,nonlinearVolume:getNonlinearVolume(e)}})}if(this.safeEmit(EngineEventsTypes.onLocalAudioPropertiesReport,s),this._room){const e=[];if(this._room.config.isMultiChatMode()){this._room.getActiveSpeakerInMultiChatMode().forEach((t=>{var i;const r=255*t.audioLevel;e.push({streamKey:{userId:t.userId,streamIndex:StreamIndex$1.STREAM_INDEX_MAIN,roomId:(null==(i=this._room)?void 0:i.config.roomId)??""},audioPropertiesInfo:{linearVolume:r,nonlinearVolume:getNonlinearVolume(r)}})}))}else this._room.remoteStreams.forEach(((t,i)=>{t.forEach((t=>{var r;if(t.audioTrack){const o=t.audioTrack.getAudioLevel();e.push({streamKey:{userId:i,streamIndex:t.isScreen?StreamIndex$1.STREAM_INDEX_SCREEN:StreamIndex$1.STREAM_INDEX_MAIN,roomId:(null==(r=this._room)?void 0:r.config.roomId)??""},audioPropertiesInfo:{linearVolume:o,nonlinearVolume:getNonlinearVolume(o)}})}}))}));this.safeEmit(EngineEventsTypes.onRemoteAudioPropertiesReport,e),this._sendActiveSpeaker(s,e.filter((e=>e.streamKey.streamIndex!==StreamIndex$1.STREAM_INDEX_SCREEN)))}}),o))}async setVideoSourceType(e,t){var i,r,o,s,n,a,d,c,l,u,_,h,p,m,S,g,v,f,E;this.logger.print("setVideoSourceType()","index: %o, videoSourceType: %o",e,t),checkEnum(e,"streamIndex",[StreamIndex$1.STREAM_INDEX_MAIN,StreamIndex$1.STREAM_INDEX_SCREEN]),checkEnum(t,"VideoSourceType",[VideoSourceType.VIDEO_SOURCE_TYPE_EXTERNAL,VideoSourceType.VIDEO_SOURCE_TYPE_INTERNAL]);const T=e===StreamIndex$1.STREAM_INDEX_MAIN?"video":"screenVideo";if(this._trackSourceType[T]!==t){if(this._trackSourceType[T]=t,this.logger.print("setVideoSourceType",`set ${T} source type to ${t}`),this._localVideoTrack&&e===StreamIndex$1.STREAM_INDEX_MAIN){let e=!1;if(t===VideoSourceType.VIDEO_SOURCE_TYPE_EXTERNAL){e=!0;const t=this._ctx.extensionManager.getPluginByName(RTCExtensionType.PRE_PROCESSING,"RTCBeautyExtension");t&&t.emit("stop"),this._removeLocalTrackEvents(this._localVideoTrack),this._localVideoTrack.destroy()}null==(i=this._localVideoTrack)||i.destroy(),this._localVideoTrack=void 0;const _=null==(r=this._room)?void 0:r.config.isAutoPublish;e?null==(n=null==(s=null==(o=this._room)?void 0:o.localStream)?void 0:s.observer)||n.setEnableVideo(!1):null==(c=null==(d=null==(a=this._room)?void 0:a.localStream)?void 0:d.observer)||c.setPushVideo(!1),((null==(u=null==(l=this._room)?void 0:l.localStream)?void 0:u.pubVideo)||_)&&await this._updatePublish()}if(this._localScreenVideoTrack&&e===StreamIndex$1.STREAM_INDEX_SCREEN){let e=!1;t===VideoSourceType.VIDEO_SOURCE_TYPE_EXTERNAL&&(e=!0,this._removeLocalTrackEvents(this._localScreenVideoTrack),this._localScreenVideoTrack.destroy()),null==(_=this._localScreenVideoTrack)||_.destroy(),this._localScreenVideoTrack=void 0,e?null==(m=null==(p=null==(h=this._room)?void 0:h.localScreenStream)?void 0:p.observer)||m.setEnableVideo(!1):null==(v=null==(g=null==(S=this._room)?void 0:S.localScreenStream)?void 0:g.observer)||v.setPushVideo(!1),(null==(E=null==(f=this._room)?void 0:f.localScreenStream)?void 0:E.pubVideo)&&await this._updateScreenPublish()}}}async setExternalVideoTrack(e,t){var i,r,o,s,n,a,d,c;if(this.logger.print("setExternalVideoTrack()","index: %o, track: %o",e,t),checkEnum(e,"streamIndex",[StreamIndex$1.STREAM_INDEX_MAIN,StreamIndex$1.STREAM_INDEX_SCREEN]),checkMediaStreamTrack(t),e===StreamIndex$1.STREAM_INDEX_MAIN){if(this._trackSourceType.video!==VideoSourceType.VIDEO_SOURCE_TYPE_EXTERNAL)throw new SDKError(ErrorCode.STREAM_TYPE_NOT_MATCH,"setVideoSourceType as external first");this._localVideoTrack=await createCustomVideoLocalTrack(this._ctx,t);const e=this._ctx.videoProfile.getContentHint();!t.contentHint&&e&&this._localVideoTrack.setContentHint(e),this._initLocalTrackEvents(this._localVideoTrack),this._localVideoPlayerConfig[StreamIndex$1.STREAM_INDEX_MAIN].forEach((e=>{var t,i;null==(i=this._localVideoTrack)||i.setPlayer(e,this._mirrorType,null==(t=this._config)?void 0:t.autoPlayPolicy,this._initPlayerEvents.bind(this))}));const s=null==(i=this._room)?void 0:i.config.isAutoPublish;((null==(o=null==(r=this._room)?void 0:r.localStream)?void 0:o.pubVideo)||s)&&await this._updatePublish()}if(e===StreamIndex$1.STREAM_INDEX_SCREEN){if(this._trackSourceType.screenVideo!==VideoSourceType.VIDEO_SOURCE_TYPE_EXTERNAL)throw new SDKError(ErrorCode.STREAM_TYPE_NOT_MATCH,"setVideoSourceType as external first");this._localScreenVideoTrack=await createCustomScreenVideoLocalTrack(this._ctx,t),this._initLocalTrackEvents(this._localScreenVideoTrack,!0),this._localVideoPlayerConfig[StreamIndex$1.STREAM_INDEX_SCREEN].forEach((e=>{var t,i;null==(i=this._localScreenVideoTrack)||i.setPlayer(e,this._mirrorType,null==(t=this._config)?void 0:t.autoPlayPolicy,this._initPlayerEvents.bind(this))})),null==(a=null==(n=null==(s=this._room)?void 0:s.localScreenStream)?void 0:n.observer)||a.setPushVideo(!0),(null==(c=null==(d=this._room)?void 0:d.localScreenStream)?void 0:c.pubVideo)&&await this._updateScreenPublish()}}async setAudioSourceType(e,t){var i,r,o,s,n,a,d,c,l,u,_,h,p,m,S,g,v;this.logger.print("setAudioSourceType()","index: %o, audioSourceType: %o",e,t),checkEnum(e,"streamIndex",[StreamIndex$1.STREAM_INDEX_MAIN,StreamIndex$1.STREAM_INDEX_SCREEN]),checkEnum(t,"audioSourceType",[AudioSourceType.AUDIO_SOURCE_TYPE_EXTERNAL,AudioSourceType.AUDIO_SOURCE_TYPE_INTERNAL]);const f=e===StreamIndex$1.STREAM_INDEX_MAIN?"audio":"screenAudio";if(this._trackSourceType[f]!==t){if(this._trackSourceType[f]=t,this.logger.print("setVideoSourceType",`set ${f} source type to ${t}`),this._localAudioTrack&&e===StreamIndex$1.STREAM_INDEX_MAIN){let e=!1;this._trackSourceType.audio===AudioSourceType.AUDIO_SOURCE_TYPE_EXTERNAL&&(e=!0,this._removeLocalTrackEvents(this._localAudioTrack),this._localAudioTrack.destroy()),this._localAudioTrack=void 0;const t=null==(i=this._room)?void 0:i.config.isAutoPublish;e?null==(s=null==(o=null==(r=this._room)?void 0:r.localStream)?void 0:o.observer)||s.setEnableAudio(!1):null==(d=null==(a=null==(n=this._room)?void 0:n.localStream)?void 0:a.observer)||d.setPushAudio(!1),((null==(l=null==(c=this._room)?void 0:c.localStream)?void 0:l.pubAudio)||t)&&await this._updatePublish()}if(this._localScreenAudioTrack&&e===StreamIndex$1.STREAM_INDEX_SCREEN){let e=!1;this._trackSourceType.audio===AudioSourceType.AUDIO_SOURCE_TYPE_EXTERNAL&&(e=!0,this._removeLocalTrackEvents(this._localScreenAudioTrack),this._localScreenAudioTrack.destroy()),this._localScreenAudioTrack=void 0,e?null==(h=null==(_=null==(u=this._room)?void 0:u.localScreenStream)?void 0:_.observer)||h.setEnableAudio(!1):null==(S=null==(m=null==(p=this._room)?void 0:p.localScreenStream)?void 0:m.observer)||S.setPushAudio(!1),(null==(v=null==(g=this._room)?void 0:g.localScreenStream)?void 0:v.pubAudio)&&await this._updateScreenPublish()}}}async setExternalAudioTrack(e,t){var i,r,o,s,n,a,d,c,l,u,_;if(this.logger.print("setExternalAudioTrack()","index: %o, track: %o",e,t),checkEnum(e,"streamIndex",[StreamIndex$1.STREAM_INDEX_MAIN,StreamIndex$1.STREAM_INDEX_SCREEN]),checkMediaStreamTrack(t),e===StreamIndex$1.STREAM_INDEX_MAIN){if(this._trackSourceType.audio!==AudioSourceType.AUDIO_SOURCE_TYPE_EXTERNAL)throw new SDKError(ErrorCode.STREAM_TYPE_NOT_MATCH,"setAudioSourceType as external first");this._localAudioTrack=await createCustomAudioLocalTrack(this._ctx,t),this._localAudioTrack.setVolume(this._localAudioVolume),this._initLocalTrackEvents(this._localAudioTrack);const e=this._ctx._localAudioTrackDumpConfig[StreamIndex$1.STREAM_INDEX_MAIN];e.frameSize&&e.callback&&this._localAudioTrack.setDataFetcher(e.frameSize,e.callback);const{position:d,volume:c}=this._ctx.earMonitorSettings[StreamIndex$1.STREAM_INDEX_MAIN];d!==EarMonitorPosition.NONE&&(this.setEarMonitorMode(StreamIndex$1.STREAM_INDEX_MAIN,d),this.setEarMonitorVolume(StreamIndex$1.STREAM_INDEX_MAIN,c));const l=null==(i=this._room)?void 0:i.config.isAutoPublish;null==(s=null==(o=null==(r=this._room)?void 0:r.localStream)?void 0:o.observer)||s.setPushAudio(!0),((null==(a=null==(n=this._room)?void 0:n.localStream)?void 0:a.pubAudio)||l)&&await this._updatePublish()}if(e===StreamIndex$1.STREAM_INDEX_SCREEN){if(this._trackSourceType.screenAudio!==AudioSourceType.AUDIO_SOURCE_TYPE_EXTERNAL)throw new SDKError(ErrorCode.STREAM_TYPE_NOT_MATCH,"setAudioSourceType as external first");this._localScreenAudioTrack=await createCustomScreenAudioLocalTrack(this._ctx,t),this._localScreenAudioTrack.setVolume(this._localScreenAudioVolume),this._initLocalTrackEvents(this._localScreenAudioTrack);const e=this._ctx._localAudioTrackDumpConfig[StreamIndex$1.STREAM_INDEX_SCREEN];e.frameSize&&e.callback&&this._localScreenAudioTrack.setDataFetcher(e.frameSize,e.callback);const{position:i,volume:r}=this._ctx.earMonitorSettings[StreamIndex$1.STREAM_INDEX_SCREEN];i!==EarMonitorPosition.NONE&&(this.setEarMonitorMode(StreamIndex$1.STREAM_INDEX_SCREEN,i),this.setEarMonitorVolume(StreamIndex$1.STREAM_INDEX_SCREEN,r)),null==(l=null==(c=null==(d=this._room)?void 0:d.localScreenStream)?void 0:c.observer)||l.setPushAudio(!0),(null==(_=null==(u=this._room)?void 0:u.localScreenStream)?void 0:_.pubAudio)&&await this._updateScreenPublish()}}async login(e,t){return this.logger.info("login()","token: %o, userInfo: %o",e,t),isEmpty(e)||checkString(e,"token"),checkUserId(t),this._rtmClient.login(e,t)}async logout(){return this.logger.info("logout()"),this._rtmClient.logout()}async updateLoginToken(e){return this.logger.info("updateLoginToken()","token: %o",e),isEmpty(e)||checkString(e,"token"),this._rtmClient.updateLoginToken(e)}async getPeerOnlineStatus(e){return this.logger.info("getPeerOnlineStatus()","userId: %o",e),checkUserId(e),this._rtmClient.getPeerOnlineStatus(e)}async sendUserMessageOutsideRoom(e,t){checkUserId(e);const i=Date.now();return this._rtmClient.sendUserMessageOutsideRoom(e,t).then((t=>(this._messageStatisticsObserver.countUserMessageOutsideRoom(!0,e,!1,i,t),t.id))).catch((t=>{throw this._messageStatisticsObserver.countUserMessageOutsideRoom(!1,e,!1,i,t),t}))}async sendUserBinaryMessageOutsideRoom(e,t){checkUserId(e),checkArrayBuffer(t,"message");const i=Date.now();return this._rtmClient.sendUserMessageOutsideRoom(e,t).then((t=>(this._messageStatisticsObserver.countUserMessageOutsideRoom(!0,e,!0,i,t),t.id))).catch((t=>{throw this._messageStatisticsObserver.countUserMessageOutsideRoom(!1,e,!0,i,t),t}))}async setServerParams(e,t){return this.logger.info("setServerParams()","signature: %o, url: %0",e,t),this._rtmClient.setServerParams(e,t)}async sendServerMessage(e){checkString(e,"message");const t=Date.now();return this._rtmClient.sendServerMessage(e).then((e=>{this._messageStatisticsObserver.countServerMessage(!0,!1,t,e)})).catch((e=>{throw this._messageStatisticsObserver.countServerMessage(!1,!1,t,e),e}))}async sendServerBinaryMessage(e){checkArrayBuffer(e,"message");const t=Date.now();return this._rtmClient.sendServerMessage(e).then((e=>{this._messageStatisticsObserver.countServerMessage(!0,!0,t,e)})).catch((e=>{throw this._messageStatisticsObserver.countServerMessage(!1,!0,t,e),e}))}startCloudProxy(e){if(this._room)throw new SDKError(ErrorCode.START_CLOUD_PROXY_AFTER_JOIN,"[startCloudProxy] should be invoke before join room ");if(this.logger.info("startCloudProxy()",e),checkString(e.logProxy,"logProxy"),Array.isArray(e.accessProxy))for(const t of e.accessProxy)checkString(t,"accessProxy");else checkString(e.accessProxy,"accessProxy");checkString(e.configProxy,"configProxy"),this._originIceConfigRequestUrls=getParameter("ICE_CONFIG_REQUEST_URLS"),this._originLogServerUrl=getParameter("LOG_SERVER_URL"),this._originConfigServerUrls=getParameter("CONFIG_REQUEST_DOMAINS"),setParameter("ICE_CONFIG_REQUEST_URLS",e.accessProxy),setParameter("LOG_SERVER_URL",getFullLogServerUrl(e.logProxy)),setParameter("CONFIG_REQUEST_DOMAINS",[e.configProxy]),sdkCache.clearAccessNode(this._appId),sdkCache.clearAccessUrls(),this._ctx.useCloudProxy=!0}stopCloudProxy(){var e;if(this._room)throw new SDKError(ErrorCode.STOP_CLOUD_PROXY_BEFORE_LEAVE,"[stopCloudProxy] should be invoke after leave room ");this.logger.info("stopCloudProxy()");setParameter("ICE_CONFIG_REQUEST_URLS",(null==(e=this._originIceConfigRequestUrls)?void 0:e.map((e=>e.replace("https://","").replace("/dispatch/v1/AccessInfo?Action=GetAccessInfo",""))))??[]),setParameter("LOG_SERVER_URL",this._originLogServerUrl??""),setParameter("CONFIG_REQUEST_DOMAINS",this._originConfigServerUrls??[]),sdkCache.clearAccessNode(this._appId),sdkCache.clearAccessUrls(),this._ctx.useCloudProxy=!1,this._startCloudProxyTimestamp=void 0}async startPushPublicStream(e,t){var i,r,o,s;if(this.logger.print("startPushPublicStream()","publicStreamId: %o, publicStreamParam: %o",e,t),checkPublicStreamId(e),this._assertNotInRoom(),this._publicStreamIds.get(e))throw new SDKError(ErrorCode.REPEAT_PUSH,"repeat push public media stream");this._room&&(null==(r=null==(i=t.layout)?void 0:i.regions)||r.map((e=>{var t;e.roomId=null==(t=this._room)?void 0:t.config.roomId})));const n=getPublicStreamControlMessage(e,"started",t);return null==(s=null==(o=this._room)?void 0:o.publicStreamControlMessage(n))?void 0:s.then((()=>{this._publicStreamIds.set(e,e)}))}async updatePublicStreamParam(e,t){var i;this.logger.print("startPushPublicStream()","publicStreamId: %o, publicStreamParam: %o",e,t),checkPublicStreamId(e),this._assertNotInRoom();const r=getPublicStreamControlMessage(e,"layoutChanged",t);return null==(i=this._room)?void 0:i.publicStreamControlMessage(r)}async stopPushPublicStream(e){var t;return this.logger.print("startPushPublicStream()","publicStreamId: %o",e),checkPublicStreamId(e),this._assertNotInRoom(),null==(t=this._room)?void 0:t.publicStreamControlMessage({type:"publicstream",action:"stopped",publicStreamID:e}).then((()=>{this._publicStreamIds.delete(e)}))}async startPlayPublicStream(e){await this._wtnStreamManager.startPlayWTN(null,e,!1,!1)}async stopPlayPublicStream(e){await this._wtnStreamManager.stopPlayWTN(e)}async setAudioProfile(e){this.logger.info("setAudioProfile()","profile: %o",e);await this._shouldUpdateAudioConf("setAudioProfile")&&this._ctx.audioProfileManager.setAudioProfile(e)}async setAudioEncodeMaxBitrate(e){var t,i,r,o,s,n;if(this.logger.print("setAudioEncodeMaxBitrate()",e),checkNumber(e,"maxBitrate",6,256),this._ctx.audioProfileManager.setCustomMaxBitrate(e),this._ctx.audioProfileManager.customMaxBitrate){if(isFirefox&&((null==(i=null==(t=this._room)?void 0:t.localStream)?void 0:i.pubAudio)||(null==(o=null==(r=this._room)?void 0:r.localScreenStream)?void 0:o.pubAudio)))throw new SDKError(ErrorCode.NOT_SUPPORTED,"Your browser does not support set audio encode maxBitrate dynamically.");await(null==(s=this._room)?void 0:s.setAudioEncodeMaxBitrate(StreamIndex$1.STREAM_INDEX_MAIN,e)),await(null==(n=this._room)?void 0:n.setAudioEncodeMaxBitrate(StreamIndex$1.STREAM_INDEX_SCREEN,e))}}setPublicStreamVideoPlayer(e,t){return this._wtnStreamManager.setWTNRemoteVideoPlayer(e,t)}async setDummyCaptureImagePath(e,t){return new Promise(((i,r)=>{checkString(t,"filePath");const o=new Image;o.crossOrigin="anonymous",o.src=t,o.onload=()=>{e===StreamIndex$1.STREAM_INDEX_MAIN?this._dummyMainImage=o:this._dummyScreenImage=o;try{this._updateDummyCaptureImage(e),i()}catch(e){r(new SDKError(ErrorCode.UNEXPECTED_ERROR,e.message))}},o.onerror=()=>{r(new SDKError(ErrorCode.UNEXPECTED_ERROR,"Load image error"))}}))}_updateDummyCaptureImage(e){var t,i;let r,o;if(e===StreamIndex$1.STREAM_INDEX_MAIN?(r=this._dummyMainImage,o=this._ctx.videoProfile.getVideoEncodeConfig()[0]):(r=this._dummyScreenImage,o=this._ctx.videoProfile.getScreenEncodeConfig()),!r)return;const s=document.createElement("canvas"),n=s.getContext("2d"),a=constraints2number(o.width),d=constraints2number(o.height);if(!n)throw new SDKError(ErrorCode.UNEXPECTED_ERROR,"Not support canvas");let c,l;!a||!d||r.width<=a&&r.height<=d?(c=r.width,l=r.height):(c=Math.min(a,r.width*d/r.height),l=Math.min(d,r.height*a/r.width)),s.width=c,s.height=l,n.drawImage(r,0,0,r.width,r.height,0,0,c,l);const u=window.setInterval((()=>{r&&n.drawImage(r,0,0,r.width,r.height,0,0,c,l)}),200);e===StreamIndex$1.STREAM_INDEX_MAIN?(clearInterval(this._dummyMainTimer),this._dummyMainTimer=u):(clearInterval(this._dummyScreenTimer),this._dummyScreenTimer=u);const _=s.captureStream(5).getVideoTracks()[0];e===StreamIndex$1.STREAM_INDEX_MAIN?(this._localImgVideoTrack=_,(null==(t=this._localVideoTrack)?void 0:t.dummy)&&this._localVideoTrack.setTrack(this._localImgVideoTrack)):(this._localImgScreenTrack=_,(null==(i=this._localScreenVideoTrack)?void 0:i.dummy)&&this._localScreenVideoTrack.setTrack(this._localImgScreenTrack))}_addListenExtensionEvent(e){e.on("re-capture-audio",(()=>{this._localAudioTrack&&this.stopAudioCapture().then((()=>{this.startAudioCapture()}))})),e.on("re-capture-video",(()=>{this._localVideoTrack&&!this._localVideoTrack.dummy&&this.stopVideoCapture().then((()=>{this.startVideoCapture()}))})),e.on("reset-video-effect",(async(e,t)=>{var i,r;if(this._localVideoTrack&&!this._localVideoTrack.dummy){this._localVideoTrack&&this._removeLocalTrackEvents(this._localVideoTrack);try{await this._localVideoTrack.generatePreProcessingTrack()}catch(e){t(e)}this._initLocalTrackEvents(this._localVideoTrack),this._localVideoTrack.stopAll(),this._localVideoTrack.playAll(),this.safeEmit(EngineEventsTypes.onLocalStreamTrackChangedByExtension,{streamIndex:StreamIndex$1.STREAM_INDEX_MAIN,type:"video"}),e(),(null==(r=null==(i=this._room)?void 0:i.localStream)?void 0:r.pubVideo)&&await this._updatePublish(),this._wtnStreamManager._updatePushTrack()}e()}))}async registerExtension(e){var t,i,r;e.monitor=this.monitor,e.logger=new Logger$1(e.name,0,this.id);try{if(!await e.isSupported())throw new Error("This extension is not supported.")}catch{throw new Error("This extension is not supported.")}getParameter("VERSION")!==e.version&&(warnDevelopers(`This extension version is ${e.version}, but the sdk version is ${getParameter("VERSION")}.`),this.monitor.report("rtc_error",{message:`This extension version is ${e.version}, but the sdk version is ${getParameter("VERSION")}.`,error_code:-1}));let o={};if("RTCAIAnsExtension"===e.name){o={overloadThreshold:getParameter("AINR_OVERLOAD_THRESHOLD"),enableCache:getParameter("AINR_ENABLE_DUMP"),urls:getParameter("AINR_URLS"),cacheTime:getParameter("AINR_CACHE_TIME"),dumpTime:getParameter("AINR_DUMP_TIME")}}o=filterUndefined(o),await e.init(o),this._ctx.extensionManager.register(e),this._addListenExtensionEvent(e),null==(t=this._localAudioTrack)||t.generatePreProcessingTrack(),null==(i=this._localVideoTrack)||i.generatePreProcessingTrack(),null==(r=this._localScreenAudioTrack)||r.generatePreProcessingTrack()}defaultTranscoding(){return JSON.parse(JSON.stringify(LiveTranscoding.getDefaultValue()))}async _updatePublish(e={},t=!1){this.logger.info("_updatePublish()","config: %o",e);if(e={...{mediaType:void 0,invokeByJoinRoom:!1,pubState:PubState.PUB},...e},!this._ctx.visibility)throw new SDKError(ErrorCode.NO_PUBLISH_PERMISSION,"no publish permission");const i=await this._pubLock.lock();if(this._room&&this._ctx.signalingManager.isConnected())try{await this._room.publish(this._localVideoTrack,this._localAudioTrack,e.mediaType,e.pubState,e.invokeByJoinRoom)}catch(e){throw e instanceof SDKError?(e.code===ErrorCode.TOKEN_NO_PUBLISH_PERMISSION&&this._room.config.setTokenPublishPrivilegeExpired(!0),e):new SDKError(ErrorCode.UNEXPECTED_ERROR,"unexpected error",e)}finally{i()}else if(i(),t)throw new SDKError(ErrorCode.NOT_CONNECTED_YET,"not connected")}async startAudioPlaybackDeviceTest(e,t){return this.logger.print("startAudioPlaybackDeviceTest()","filePath: %o, indicationInterval: %o",e,t),checkString(e,"filePath"),checkNumber(t,"indicationInterval"),await this._audioDeviceManager.startAudioPlaybackDeviceTest(e,t)}stopAudioPlaybackDeviceTest(){this.logger.info("stopAudioPlaybackDeviceTest()"),this._audioDeviceManager.stopAudioPlaybackDeviceTest()}async startAudioDeviceRecordTest(e,t){this.logger.print("startAudioDeviceRecordTest()","indicationInterval: %o",e),checkNumber(e,"indicationInterval"),await this._audioDeviceManager.startAudioDeviceRecordTest(e,t,this._localAudioVolume)}stopAudioDeviceRecordAndPlayTest(){this.logger.info("stopAudioDeviceRecordAndPlayTest()"),this._audioDeviceManager.stopAudioDeviceRecordAndPlayTest()}stopAudioDevicePlayTest(){this.logger.info("stopAudioDevicePlayTest()"),this._audioDeviceManager.stopAudioDevicePlayTest()}setRemoteUserPriority(e,t){var i;this.logger.print("setRemoteUserPriority()","userId: %o, priority: %o",e,t);try{checkUserId(e),checkEnum(t,"priority",[RemoteUserPriority.HIGH,RemoteUserPriority.MEDIUM,RemoteUserPriority.LOW])}catch(e){return console.warn(e),!1}return this._ctx.userPriority.set(e,t),null==(i=this._room)||i.updateRemoteUserPriority(e),!0}async takeLocalSnapshot(e){this.logger.print("takeLocalSnapshot()","streamIndex: %o",e),checkEnum(e,"streamIndex",[StreamIndex$1.STREAM_INDEX_MAIN,StreamIndex$1.STREAM_INDEX_SCREEN]);const t=e===StreamIndex$1.STREAM_INDEX_MAIN?this.localVideoTrack:this.localScreenVideoTrack;if(!t)throw new SDKError(ErrorCode.INVOKED_BEFORE_CAPTURE,"capture first");return t.snapshot()}async takeRemoteSnapshot(e,t){var i,r,o;this.logger.print("takeRemoteSnapshot()","id: %o, streamIndex: %o",e,t),checkString(e,"id"),checkEnum(t,"streamIndex",[StreamIndex$1.STREAM_INDEX_MAIN,StreamIndex$1.STREAM_INDEX_SCREEN]);const s=(null==(o=null==(r=null==(i=this._room)?void 0:i.remoteStreams.get(e))?void 0:r.find((e=>e.isScreen===(t===StreamIndex$1.STREAM_INDEX_SCREEN))))?void 0:o.videoTrack)||this._wtnStreamManager.__getPublicStreamTrack(e,"video");if(!s)throw new SDKError(ErrorCode.STREAM_NOT_EXIST,"stream not exist");return s.snapshot()}setSubscribeFallbackOption(e){this.logger.info("setSubscribeFallbackOption()","option: %o",e);try{checkEnum(e,"option",[SubscribeFallbackOption.DISABLE,SubscribeFallbackOption.VIDEO_STREAM_LOW,SubscribeFallbackOption.AUDIO_ONLY])}catch(e){return console.warn(e),!1}return!this._room&&(this._ctx.subscribeFallbackOption=e,!0)}getLocalStreamTrack(e,t){let i,r;if(e===StreamIndex$1.STREAM_INDEX_MAIN?(i="video"===t?this.localVideoTrack:this.localAudioTrack,r=()=>{var e;return null==(e=this._room)?void 0:e.localStream}):(i="video"===t?this.localScreenVideoTrack:this.localScreenAudioTrack,r=()=>{var e;return null==(e=this._room)?void 0:e.localScreenStream}),!i)return;const o=i instanceof LocalAudioTrack&&i.mixedAudioTrack?i.mixedAudioTrack:i.preprocessingTrack;if(!o)return;const s=r();return this._reportMsTrackEvent(o,(null==s?void 0:s.stream.id)||"local"),o}getRemoteStreamTrack(e,t,i){var r;let o;const s=(null==(r=this._room)?void 0:r.remoteStreams.get(e))||[];if(!(null==s?void 0:s.length))return;let n;if(t===StreamIndex$1.STREAM_INDEX_MAIN?(n=s.find((e=>!e.isScreen)),o="video"===i?null==n?void 0:n.videoTrack:null==n?void 0:n.audioTrack):(n=s.find((e=>e.isScreen)),o="video"===i?null==n?void 0:n.videoTrack:null==n?void 0:n.audioTrack),!o)return;const a=o.preprocessingTrack;if(!a||!n)return;const{streamId:d}=n;return this._reportMsTrackEvent(a,d),a}getPublicStreamTrack(e,t){const i=this._wtnStreamManager.__getPublicStreamTrack(e,t),r=null==i?void 0:i.preprocessingTrack;if(r)return r?(this._reportMsTrackEvent(r,e),r):void 0}setRemoteStreamRenderSync(e){return!this._room&&(this._ctx.avSync=!!e,!0)}setJoinRoomParams(e){e&&(this._ctx.joinRoomParams=e)}async setAudioSelectionConfig(e){checkEnum(e,"audioSelectionPriority",[AudioSelectionPriority.DEFAULT,AudioSelectionPriority.HIGH]),this._ctx.mediaParams||(this._ctx.mediaParams={}),this._ctx.mediaParams.audioSelectionConfig={isHighPriority:e===AudioSelectionPriority.HIGH},this._room&&await this._room.updateMediaParams(this._ctx.mediaParams)}setCaptureVolume(e,t){var i,r,o,s,n;checkEnum(e,"streamIndex",[StreamIndex$1.STREAM_INDEX_MAIN,StreamIndex$1.STREAM_INDEX_SCREEN]),t=numberRangeGuide(t,"volume",0,400);e===StreamIndex$1.STREAM_INDEX_SCREEN?(null==(i=this._localScreenAudioTrack)||i.once("needReplaceTrack",(()=>{var e;null==(e=this._room)||e.updatePubScreenTrack()})),null==(r=this._localScreenAudioTrack)||r.setVolume(t),this._localScreenAudioVolume=t):(null==(o=this._localAudioTrack)||o.once("needReplaceTrack",(()=>{var e;null==(e=this._room)||e.updatePubTrack()})),null==(s=this._localAudioTrack)||s.setVolume(t),null==(n=this._audioDeviceManager.audioTrack)||n.setVolume(t),this._localAudioVolume=t)}setPlaybackVolume(e,t,i){var r,o,s,n;if(checkUserId(e),checkEnum(t,"streamIndex",[StreamIndex$1.STREAM_INDEX_MAIN,StreamIndex$1.STREAM_INDEX_SCREEN]),i=numberRangeGuide(i,"volume",0,400),null==(r=this._room)?void 0:r.config.isMultiChatMode())return void warnDevelopers("setPlaybackVolume is not supported in Conference mode");const a=t===StreamIndex$1.STREAM_INDEX_SCREEN;a?this._remoteScreenAudioVolume.set(e,i):this._remoteAudioVolume.set(e,i);const d=null==(s=null==(o=this._room)?void 0:o.remoteStreams.get(e))?void 0:s.find((e=>e.isScreen===a));null==(n=null==d?void 0:d.audioTrack)||n.setVolume(i)}setPublicStreamVolume(e,t){this._wtnStreamManager.setWTNRemoteAudioPlaybackVolume(e,t)}async startForwardStreamToRooms(e){e.forEach((e=>{checkRoomId(e.roomId)})),this._assertNotInRoom();return await this._room.startForwardStream2Rooms(e)}async updateForwardStreamToRooms(e){e.forEach((e=>{checkRoomId(e.roomId)})),this._assertNotInRoom();return await this._room.updateForwardStream2Rooms(e)}async stopForwardStreamToRooms(){this._assertNotInRoom();return await this._room.stopForwardStream2Rooms()}async pauseForwardStreamToAllRooms(){this._assertNotInRoom();return await this._room.pauseForwardStream2AllRooms()}async resumeForwardStreamToAllRooms(){this._assertNotInRoom();return await this._room.resumeForwardStream2AllRooms()}async ambulance(){const e=await ambulance(this),t=JSON.stringify(e);return this.monitor.reportLongString("ambulance",t),e}async setEarMonitorMode(e,t){this.logger.info("setEarMonitorMode()","streamIndex: %s, position: %s",e,t),checkEnum(e,"streamIndex",[StreamIndex$1.STREAM_INDEX_MAIN,StreamIndex$1.STREAM_INDEX_SCREEN]),checkEnum(t,"position",[EarMonitorPosition.NONE,EarMonitorPosition.AFTER_CAPTURE,EarMonitorPosition.AFTER_PROCESS]),this._ctx.earMonitorSettings[e].position=t;const i=e===StreamIndex$1.STREAM_INDEX_MAIN?this.localAudioTrack:e===StreamIndex$1.STREAM_INDEX_SCREEN?this.localScreenAudioTrack:void 0;if(i)return t!==EarMonitorPosition.NONE?i.play(t):i.stop();this.logger.warn("setEarMonitorMode()","local audio track not exist")}setEarMonitorVolume(e,t){this.logger.info("setEarMonitorVolume()","streamIndex: %s, volume: %s",e,t),checkEnum(e,"streamIndex",[StreamIndex$1.STREAM_INDEX_MAIN,StreamIndex$1.STREAM_INDEX_SCREEN]),t=numberRangeGuide(t,"volume",0,400),this._ctx.earMonitorSettings[e].volume=t;const i=e===StreamIndex$1.STREAM_INDEX_MAIN?this.localAudioTrack:e===StreamIndex$1.STREAM_INDEX_SCREEN?this.localScreenAudioTrack:void 0;if(i)return i.setPlaybackVolume(t);this.logger.warn("setEarMonitorVolume()","local audio track not exist")}setUserInfo(e,t){checkRoomId(e),checkUserId(t),this.monitor.set({room_id:e,user_id:t})}_reportMsTrackEvent(e,t){if(!e.hookStop){e.hookStop=!0;const i=e.stop;e.stop=()=>{reportRtcInvokeStatus(this.id,"stop",t,0,t),i.call(e)}}}async _updateScreenPublish(e={}){this.logger.info("_updateScreenPublish()");if(e={...{mediaType:void 0,pubState:PubState.PUB},...e},!this._ctx.visibility)throw new SDKError(ErrorCode.NO_PUBLISH_PERMISSION,"no publish permission");const t=await this._pubLock.lock();if(this._room&&this._ctx.signalingManager.isConnected())try{await this._room.publishScreen(this._localScreenVideoTrack,this._localScreenAudioTrack,e.mediaType,e.pubState)}catch(e){throw e instanceof SDKError?e:new SDKError(ErrorCode.UNEXPECTED_ERROR,"unexpected error",e)}finally{t()}else t()}_updateAudioPlayerState(e){var t,i,r,o;this.logger.info("_updateAudioPlayerState()");const{userId:s,isScreen:n,isPublic:a}=e;if(e.audioTrack&&e.attributes.audiostream&&e.subAudio){if(!e.audioTrack.havePlayer()){const r=new AudioPlayer(this.id,s,{muted:(null==(t=this._config)?void 0:t.autoPlayPolicy)===RTCAutoPlayPolicy.VIDEO_ONLY||(null==(i=this._config)?void 0:i.autoPlayPolicy)===RTCAutoPlayPolicy.PLAY_MANUALLY,isScreen:!a&&n});e.audioTrack.setPlayer(r),e.audioTrack.bindPlayerEvent(this._initPlayerEvents.bind(this));const o=this._audioDeviceManager.getSinkId();o&&e.audioTrack.setPlaybackDevice(o)}e.audioTrack.play();const o=a?this._ctx.publicAudioVolume.get(s)??100:n?this._remoteScreenAudioVolume.get(s)??100:this._remoteAudioVolume.get(s)??100;if(e.audioTrack.setVolume(o),isSafari&&isIPad){const e=(null==(r=this._room)?void 0:r.remoteStreams)??new Map;replayRemoteAudioWorkaround(e)}}else null==(o=e.audioTrack)||o.stop()}_updateVideoPlayerState(e){var t;if(this.logger.info("_updateVideoPlayerState()"),e.videoTrack){const i=e.isPublic?this._wtnStreamManager._publicVideoPlayerConfig:this._remoteVideoPlayerConfig[e.isScreen?StreamIndex$1.STREAM_INDEX_SCREEN:StreamIndex$1.STREAM_INDEX_MAIN].get(e.userId);if(i)for(const[,r]of i)e.videoTrack.setPlayer(this.id,r,null==(t=this._config)?void 0:t.autoPlayPolicy,this._initPlayerEvents.bind(this))}}get _localVideoTrack(){return this._ctx.localVideoTrack}get _localAudioTrack(){return this._ctx.localAudioTrack}set _localVideoTrack(e){this._ctx.localVideoTrack=e}set _localAudioTrack(e){this._ctx.localAudioTrack=e}async _onAddStream(e){const t=e.stream,{localaudio:i,audiostream:r,localvideo:o,videostream:s}=t.attributes;let n=ExtendMediaType.NONE;r&&(n|=MediaType$1.AUDIO),s&&(n|=MediaType$1.VIDEO),n&&(await new Promise((e=>setTimeout(e))),t.isScreen?this.safeEmit(EngineEventsTypes.onUserPublishScreen,{userId:t.userId,mediaType:n}):(this.safeEmit(EngineEventsTypes.onUserPublishStream,{userId:t.userId,mediaType:n,videoStreamDescriptions:t.attributes.videoDescriptions}),this._handleAutoSubscribe(t,!0)),this.safeEmit("onAddStream",{userId:t.userId,mediaType:n,isScreen:!!t.isScreen}),t.isScreen||(i&&this.safeEmit(EngineEventsTypes.onUserStartAudioCapture,{userId:t.userId}),o&&this.safeEmit(EngineEventsTypes.onUserStartVideoCapture,{userId:t.userId})))}_handleAutoSubscribe(e,t){var i,r,o,s,n;let a=ExtendMediaType.NONE;(null==(i=this._room)?void 0:i.config.isAutoSubscribeAudio)&&(a|=MediaType$1.AUDIO),(null==(r=this._room)?void 0:r.config.isAutoSubscribeVideo)&&(a|=MediaType$1.VIDEO),a&&(t&&audioInMediaType(a)&&(null==(o=e.observer)||o.setAutoSubscribeAudio(!0)),t&&videoInMediaType(a)&&(null==(s=e.observer)||s.setAutoSubscribeVideo(!0)),(null==(n=this._room)?void 0:n.config.tokenSubscribePrivilegeExpired)?(audioInMediaType(a)&&(this._pauseAllSubscribeState.resumeAudioStreamIds[e.streamId]=e.streamId),videoInMediaType(a)&&(this._pauseAllSubscribeState.resumeVideoStreamIds[e.streamId]=e.streamId)):this._subscribe(!1,e.userId,a))}_onRemoveStream(e){const t=e.stream,i=StreamRemoveReasonMap[e.reason]??StreamRemoveReason.STREAM_REMOVE_REASON_OTHER,r=t.isScreen?EngineEventsTypes.onUserUnpublishScreen:EngineEventsTypes.onUserUnpublishStream;let o=ExtendMediaType.NONE;t.attributes.audiostream&&(o|=MediaType$1.AUDIO),t.attributes.videostream&&(o|=MediaType$1.VIDEO),o!==ExtendMediaType.NONE&&(this.safeEmit(r,{userId:t.userId,mediaType:o,reason:i}),this.safeEmit("onRemoveStream",{userId:t.userId,isScreen:t.isScreen})),delete this._pauseAllSubscribeState.resumeAudioStreamIds[t.streamId],delete this._pauseAllSubscribeState.resumeVideoStreamIds[t.streamId]}_onUserConnection(e){setTimeout((()=>this.safeEmit(EngineEventsTypes.onUserJoined,e)))}_onUserLeave(e){this.safeEmit(EngineEventsTypes.onUserLeave,e)}_onRoomError(e){var t;this.safeEmit(EngineEventsTypes.onError,e),null==(t=this._room)||t.destroy(),this._room=void 0}_onNetworkQuality(...e){this.safeEmit(EngineEventsTypes.onNetworkQuality,...e)}_onConnectionStateChange(e){var t;if(void 0!==this._startCloudProxyTimestamp&&this._ctx.useCloudProxy&&e.state===ConnectionState.CONNECTION_STATE_CONNECTED&&this.safeEmit(EngineEventsTypes.onCloudProxyConnected,{interval:Date.now()-this._startCloudProxyTimestamp}),(this._ctx.isPreConnection||e.state!==ConnectionState.CONNECTION_STATE_CONNECTED&&e.state!==ConnectionState.CONNECTION_STATE_RECONNECTED)&&this.safeEmit(EngineEventsTypes.onConnectionStateChanged,e),e.state===ConnectionState.CONNECTION_STATE_RECONNECTING)for(const[e,i]of(null==(t=this._room)?void 0:t.remoteStreams)??new Map)e.startsWith("mux")&&i.forEach((e=>{var t;return null==(t=e.audioTrack)?void 0:t.stop()}));else e.state===ConnectionState.CONNECTION_STATE_CONNECTED&&this._rtmClient.setRTSMessageLimit(this._ctx.rtsLimiter.conf)}_stopAudioPropertiesReport(){null!==this._audioPropertiesReportTimer&&(clearInterval(this._audioPropertiesReportTimer),this._audioPropertiesReportTimer=null)}_onResubscribe(e){var t,i;e.stream&&(null==(t=e.stream.videoTrack)||t.stopAll(),null==(i=e.stream.audioTrack)||i.stop(),this._updateAudioPlayerState(e.stream),this._updateVideoPlayerState(e.stream))}_onSubscribePushTrack(e){e.stream&&this._updateAudioPlayerState(e.stream)}_onRemovePushTrack(e){e.stream&&this._updateAudioPlayerState(e.stream)}_onUserPublishStateChange({userId:e,isScreen:t,mediaType:i,pubState:r,remoteStream:o}){const s={userId:e,mediaType:i};i&MediaType$1.AUDIO&&setTimeout((()=>{this._updateAudioPlayerState(o)})),t?r===PubState.PUB?this.safeEmit(EngineEventsTypes.onUserPublishScreen,s):this.safeEmit(EngineEventsTypes.onUserUnpublishScreen,{...s,reason:StreamRemoveReason.STREAM_REMOVE_REASON_UNPUBLISH}):r===PubState.PUB?(s.videoStreamDescriptions=o.attributes.videoDescriptions,this.safeEmit(EngineEventsTypes.onUserPublishStream,s),this._handleAutoSubscribe(o,!0)):this.safeEmit(EngineEventsTypes.onUserUnpublishStream,{...s,reason:StreamRemoveReason.STREAM_REMOVE_REASON_UNPUBLISH})}_onCustomMessage(e){const{message:t}=e;e.binary?this.safeEmit(EngineEventsTypes.onRoomBinaryMessageReceived,{userId:e.clientId,message:t}):this.safeEmit(EngineEventsTypes.onRoomMessageReceived,{userId:e.clientId,message:t})}_onUserMessageReceived(e){this._messageStatisticsObserver.recvP2PMessage(e.userId),this.safeEmit(EngineEventsTypes.onUserMessageReceived,e)}_onUserBinaryMessageReceived(e){this._messageStatisticsObserver.recvP2PMessage(e.userId),this.safeEmit(EngineEventsTypes.onUserBinaryMessageReceived,e)}_onLiveTranscodingResult(e){this.safeEmit(EngineEventsTypes.onLiveTranscodingResult,e)}_onStreamMixingEvent(e){this.safeEmit(EngineEventsTypes.onStreamMixingEvent,e)}_onUserTokenWillExpire(){this.safeEmit(EngineEventsTypes.onTokenWillExpire)}_onUserTokenPublishPrivilegeWillExpire(){this.safeEmit(EngineEventsTypes.onTokenPublishPrivilegeWillExpire)}async _onUserTokenPublishPrivilegeDidExpired(){var e,t,i;await(null==(e=this._room)?void 0:e.unpublish()),await(null==(t=this._room)?void 0:t.unpublishScreen()),null==(i=this._room)||i.config.setTokenPublishPrivilegeExpired(!0),this.safeEmit(EngineEventsTypes.onTokenPublishPrivilegeDidExpired,{errorCode:ErrorCode.TOKEN_NO_PUBLISH_PERMISSION,message:"Token no longer has publish privilege"})}_onUserTokenSubscribePrivilegeWillExpire(){this.safeEmit(EngineEventsTypes.onTokenSubscribePrivilegeWillExpire)}async _onUserTokenSubscribePrivilegeDidExpired(){this._handleLoseSubscribePrivilege(),this.safeEmit(EngineEventsTypes.onTokenSubscribePrivilegeDidExpired,{errorCode:ErrorCode.TOKEN_NO_SUBSCRIBE_PERMISSION,message:"Token no longer has subscribe privilege"})}async _unSubscribeAllRemoteStreams(){return this._room?this._pauseAllRemoteStreams(MediaType$1.AUDIO_AND_VIDEO):Promise.resolve()}_onPushPublicStreamResult(e){this.safeEmit(EngineEventsTypes.onPushPublicStreamResult,e)}_handleRTMClient(e){e.on("onUserMessageReceivedOutsideRoom",(e=>{this._messageStatisticsObserver.recvP2POutRoomMessage(e.userId),this.safeEmit(EngineEventsTypes.onUserMessageReceivedOutsideRoom,e)})),e.on("onUserBinaryMessageReceivedOutsideRoom",(e=>{this._messageStatisticsObserver.recvP2POutRoomMessage(e.userId),this.safeEmit(EngineEventsTypes.onUserBinaryMessageReceivedOutsideRoom,e)})),e.on("onUserDisconnection",(()=>{this.safeEmit(EngineEventsTypes.onError,{errorCode:ErrorCode.RTM_DUPLICATE_LOGIN})})),e.on("onRTMTokenError",(()=>{this.safeEmit(EngineEventsTypes.onError,{errorCode:ErrorCode.RTM_TOKEN_ERROR})})),e.on("onServerParamsSetResult",(e=>{this.safeEmit(EngineEventsTypes.onServerParamsSetResult,null==e?void 0:e.code)}))}getSubLock(e,t){const i=e?this._subScreenLocks:this._subLocks;let r=i.get(t);return r||(r=new PromiseLock2(`sub_${e?1:0}_${t}`),i.set(t,r)),r}get localAudioTrack(){return this._localAudioTrack}get localVideoTrack(){return this._localVideoTrack}get localScreenAudioTrack(){return this._localScreenAudioTrack}get localScreenVideoTrack(){return this._localScreenVideoTrack}get remoteStreams(){var e;const t=[];return(null==(e=this._room)?void 0:e.remoteStreams)&&this._room.remoteStreams.forEach((e=>{Array.isArray(e)&&e.forEach((e=>{t.push({userId:e.userId,isScreen:e.isScreen,hasVideo:e.hasVideo,hasAudio:e.hasAudio,videoStreamDescriptions:e.attributes.videoDescriptions})}))})),t}get iceState(){var e;return null==(e=this._ctx.peerConnection)?void 0:e.getIceConnectionState()}get remoteUsers(){var e;const t=[];return(null==(e=this._room)?void 0:e.remoteUsers)&&this._room.remoteUsers.forEach((e=>{t.push({userId:e.userId})})),t}get multiChatMode(){var e;return!!(null==(e=this._room)?void 0:e.config.isMultiChatMode())}get checkMediaType(){return this._checkMediaType}get assertNotInRoom(){return this._assertNotInRoom}get peerConnection(){var e;return null==(e=this._ctx.peerConnection)?void 0:e.getOriginRTCPeerConnection()}_handleAudioDeviceManager(){this._audioDeviceManager.on("onAudioPlaybackDeviceTestVolume",(e=>{this.safeEmit(EngineEventsTypes.onAudioPlaybackDeviceTestVolume,e)}))}_assertNotInRoom(){if(!this._room||!this._ctx.signalingManager.isConnected())throw new SDKError(ErrorCode.NOT_CONNECTED_YET,"server not connected")}_checkMediaType(e){checkEnum(e,"mediaType",[MediaType$1.AUDIO,MediaType$1.VIDEO,MediaType$1.AUDIO_AND_VIDEO])}_getUserId(){var e;return(null==(e=this._room)?void 0:e.config.userInfo.userId)||"local_user"}async _switchTrack(e){var t,i;this._initLocalTrackEvents(e),this._localVideoTrack=e,this._localVideoPlayerConfig[StreamIndex$1.STREAM_INDEX_MAIN].forEach((t=>{var i;e.setPlayer(t,this._mirrorType,null==(i=this._config)?void 0:i.autoPlayPolicy,this._initPlayerEvents.bind(this))})),(null==(i=null==(t=this._room)?void 0:t.localStream)?void 0:i.pubVideo)&&await this._updatePublish(),this._wtnStreamManager._updatePushTrack()}async _shouldUpdateAudioConf(e){var t,i,r;const o=await(null==(t=this._room)?void 0:t.hasPublished())||(null==(r=null==(i=this._room)?void 0:i.localStream)?void 0:r.pubAudio)||this._localAudioTrack&&this._localAudioTrack.sourceType===SourceType.INTERNAL;if(o){const t=`engine.${e} should be called before publishing or capturing.`;console.warn(`[RTC WebSDK]: ${t}`),reportRtcInvokeStatus(this.id,e,t)}return!o}_getRemoteVideoPlayerConfig(e,t,i){var r;return null==(r=this._remoteVideoPlayerConfig[e].get(t))?void 0:r.get(i)}_setRemoteVideoPlayerConfig(e,t,i,r){const o=this._remoteVideoPlayerConfig[e].get(t)||new Map;o.set(i,r),this._remoteVideoPlayerConfig[e].set(t,o)}getRemoteVideoStats(){var e;const t=null==(e=this._room)?void 0:e.remoteStreams;if(!t||0===t.size)return{};const i={};return t.forEach(((e,t)=>{var r;let o,s;(null==(r=e[0])?void 0:r.isScreen)?(s=e[0],o=e[1]):(s=e[1],o=e[0]);const n={mainVideoStats:getPublicStats((null==o?void 0:o.getRemoteStreamStats().videoStats)||{}),screenVideoStats:getPublicStats((null==s?void 0:s.getRemoteStreamStats().videoStats)||{})};i[t]=n})),i}getRemoteAudioStats(){var e;const t=null==(e=this._room)?void 0:e.remoteStreams;if(!t||0===t.size)return{};const i={};return t.forEach(((e,t)=>{var r;let o,s;(null==(r=e[0])?void 0:r.isScreen)?(s=e[0],o=e[1]):(s=e[1],o=e[0]);const n={mainAudioStats:getPublicStats((null==o?void 0:o.getRemoteStreamStats().audioStats)||{}),screenAudioStats:getPublicStats((null==s?void 0:s.getRemoteStreamStats().audioStats)||{})};i[t]=n})),i}getLocalVideoStats(){var e,t,i,r;return{mainVideoStats:getPublicStats((null==(t=null==(e=this._room)?void 0:e.localStream)?void 0:t.getLocalStreamStats().videoStats)||{}),screenVideoStats:getPublicStats((null==(r=null==(i=this._room)?void 0:i.localScreenStream)?void 0:r.getLocalStreamStats().videoStats)||{})}}getLocalAudioStats(){var e,t,i,r;return{mainAudioStats:getPublicStats((null==(t=null==(e=this._room)?void 0:e.localStream)?void 0:t.getLocalStreamStats().audioStats)||{}),screenAudioStats:getPublicStats((null==(r=null==(i=this._room)?void 0:i.localScreenStream)?void 0:r.getLocalStreamStats().audioStats)||{})}}getPublicVideoStats(){const e=this._wtnStreamManager.__getRemoteStreams();if(!e||0===e.size)return{};const t={};return e.forEach(((e,i)=>{const r=getPublicStats(e.getRemoteStreamStats().videoStats||{});delete r.isScreen,t[i]=r})),t}getPublicAudioStats(){const e=this._wtnStreamManager.__getRemoteStreams();if(!e||0===e.size)return{};const t={};return e.forEach(((e,i)=>{const r=getPublicStats(e.getRemoteStreamStats().audioStats||{});delete r.isScreen,t[i]=r})),t}_initAutoplayFailedWorkaround(){if(Config2.AUTOPLAY_WORKAROUND&&(Config2.ENABLE_PLAY_AFTER_CLICK||isWeChat)){let e=[];this.on(EngineEventsTypes.onAutoplayFailed,(t=>{e.push(t),r()}));const t=()=>{e.length>0&&(reportRtcInvokeStatus(this.id,"resumePlay",JSON.stringify(e)),Promise.all(e.map((e=>this.play(e.userId,e.mediaType,e.streamIndex,e.playerId)))).then((()=>{e=[],reportRtcInvokeStatus(this.id,"resumePlaySuccess",JSON.stringify(e))})).catch((()=>{reportRtcInvokeStatus(this.id,"resumePlayFailed",JSON.stringify(e))})))};let i;Config2.ENABLE_PLAY_AFTER_CLICK&&(document.addEventListener("click",t),i=()=>{document.removeEventListener("click",t)});const r=()=>{var i,r;window.WeixinJSBridge&&(reportRtcInvokeStatus(this.id,"resumePlayInWxBridge",JSON.stringify(e)),null==(r=(i=window.WeixinJSBridge).invoke)||r.call(i,"getNetworkType",{},t))};let o;isWeChat&&!window.WeixinJSBridge&&(document.addEventListener("WeixinJSBridgeReady",r,!1),o=()=>{document.removeEventListener("WeixinJSBridgeReady",r)}),this._revokeAutoplayFailedWorkaround=()=>{null==i||i(),null==o||o()}}}},__publicField(_v,"hasReportNativeDetector",!1),_v);let RTCEngine=_RTCEngine;__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"updateToken",1),__decorateClass$1([reportRtcSdkApi(),captureLock("video")],RTCEngine.prototype,"setVideoCaptureDevice",1),__decorateClass$1([reportRtcSdkApi(),captureLock("audio")],RTCEngine.prototype,"setAudioCaptureDevice",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"connect",1),__decorateClass$1([setJoinRoomInfo,reportRtcSdkApi()],RTCEngine.prototype,"joinRoom",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"leaveRoom",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"destroy",1),__decorateClass$1([reportRtcSdkApi(),checkNotInRTSRoom],RTCEngine.prototype,"publishStream",1),__decorateClass$1([reportRtcSdkApi(),checkNotInRTSRoom],RTCEngine.prototype,"unpublishStream",1),__decorateClass$1([reportRtcSdkApi(),checkNotInRTSRoom],RTCEngine.prototype,"publishScreen",1),__decorateClass$1([reportRtcSdkApi(),checkNotInRTSRoom],RTCEngine.prototype,"unpublishScreen",1),__decorateClass$1([reportRtcSdkApi(),checkNotInRTSRoom],RTCEngine.prototype,"subscribeStream",1),__decorateClass$1([subLock],RTCEngine.prototype,"_subscribe",1),__decorateClass$1([reportRtcSdkApi(),checkNotInRTSRoom],RTCEngine.prototype,"unsubscribeStream",1),__decorateClass$1([reportRtcSdkApi(),checkNotInRTSRoom],RTCEngine.prototype,"subscribeScreen",1),__decorateClass$1([reportRtcSdkApi(),checkNotInRTSRoom],RTCEngine.prototype,"unsubscribeScreen",1),__decorateClass$1([subLock],RTCEngine.prototype,"_unsubscribe",1),__decorateClass$1([reportRtcSdkApi(),subLock2],RTCEngine.prototype,"setRemoteVideoConfig",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"setRemoteSimulcastStreamType",1),__decorateClass$1([reportRtcSdkApi(),captureLock("video")],RTCEngine.prototype,"startVideoCapture",1),__decorateClass$1([reportRtcSdkApi(),captureLock("video")],RTCEngine.prototype,"stopVideoCapture",1),__decorateClass$1([reportRtcSdkApi(),captureLock("audio")],RTCEngine.prototype,"startAudioCapture",1),__decorateClass$1([reportRtcSdkApi(),captureLock("audio")],RTCEngine.prototype,"stopAudioCapture",1),__decorateClass$1([reportRtcSdkApi(),captureLock("all")],RTCEngine.prototype,"startAudioAndVideoCapture",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"startVideoAndAudioCapture",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"getAudioMixingManager",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"getWTNStreamManager",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"getCallId",1),__decorateClass$1([reportRtcSdkApi(),screenCaptureLock],RTCEngine.prototype,"startScreenCapture",1),__decorateClass$1([reportRtcSdkApi(),screenCaptureLock],RTCEngine.prototype,"stopScreenCapture",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"setLocalVideoPlayer",1),__decorateClass$1([reportRtcSdkApi(),checkNotInRTSRoom],RTCEngine.prototype,"startLiveTranscoding",1),__decorateClass$1([reportRtcSdkApi(),checkNotInRTSRoom],RTCEngine.prototype,"updateLiveTranscoding",1),__decorateClass$1([reportRtcSdkApi(),checkNotInRTSRoom],RTCEngine.prototype,"stopLiveTranscoding",1),__decorateClass$1([reportRtcSdkApi(),checkNotInRTSRoom],RTCEngine.prototype,"startSubtitle",1),__decorateClass$1([reportRtcSdkApi(),checkNotInRTSRoom],RTCEngine.prototype,"updateSubtitleConfig",1),__decorateClass$1([reportRtcSdkApi(),checkNotInRTSRoom],RTCEngine.prototype,"stopSubtitle",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"setBusinessId",1),__decorateClass$1([reportRtcSdkApi(),checkNotInRTSRoom],RTCEngine.prototype,"setUserVisibility",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"setRemoteVideoPlayer",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"setLocalVideoMirrorType",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"setRemoteVideoMirrorType",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"setAudioPlaybackDevice",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"play",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"stop",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"getAudioVolume",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"setAudioFrameCallback",1),__decorateClass$1([reportRtcSdkApi(),checkNotInRTSRoom],RTCEngine.prototype,"pauseAllSubscribedStream",1),__decorateClass$1([reportRtcSdkApi(),checkNotInRTSRoom],RTCEngine.prototype,"resumeAllSubscribedStream",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"sendUserMessage",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"sendUserBinaryMessage",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"sendRoomMessage",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"sendRoomBinaryMessage",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"setAudioCaptureConfig",1),__decorateClass$1([warnDeprecatedApi("4.51"),reportRtcSdkApi()],RTCEngine.prototype,"setVideoCaptureConfig",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"enableSimulcastMode",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"setLocalSimulcastMode",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"setVideoEncoderConfig",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"setScreenEncoderConfig",1),__decorateClass$1([reportRtcSdkApi(),checkNotInRTSRoom],RTCEngine.prototype,"sendSEIMessage",1),__decorateClass$1([warnDeprecatedApi("4.42"),reportRtcSdkApi()],RTCEngine.prototype,"setAudioVolumeIndicationInterval",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"enableAudioPropertiesReport",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"setVideoSourceType",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"setExternalVideoTrack",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"setAudioSourceType",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"setExternalAudioTrack",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"login",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"logout",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"updateLoginToken",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"getPeerOnlineStatus",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"sendUserMessageOutsideRoom",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"sendUserBinaryMessageOutsideRoom",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"setServerParams",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"sendServerMessage",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"sendServerBinaryMessage",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"startCloudProxy",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"stopCloudProxy",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"startPushPublicStream",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"updatePublicStreamParam",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"stopPushPublicStream",1),__decorateClass$1([reportRtcSdkApi(["streamId"])],RTCEngine.prototype,"startPlayPublicStream",1),__decorateClass$1([reportRtcSdkApi(["streamId"])],RTCEngine.prototype,"stopPlayPublicStream",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"setAudioProfile",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"setAudioEncodeMaxBitrate",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"setPublicStreamVideoPlayer",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"setDummyCaptureImagePath",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"registerExtension",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"startAudioPlaybackDeviceTest",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"stopAudioPlaybackDeviceTest",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"startAudioDeviceRecordTest",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"stopAudioDeviceRecordAndPlayTest",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"stopAudioDevicePlayTest",1),__decorateClass$1([reportRtcSdkApi(),subLock2],RTCEngine.prototype,"setRemoteUserPriority",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"takeLocalSnapshot",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"takeRemoteSnapshot",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"setSubscribeFallbackOption",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"getLocalStreamTrack",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"getRemoteStreamTrack",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"getPublicStreamTrack",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"setRemoteStreamRenderSync",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"setJoinRoomParams",1),__decorateClass$1([reportRtcSdkApi(),checkNotInRTSRoom],RTCEngine.prototype,"setAudioSelectionConfig",1),__decorateClass$1([reportRtcSdkApi(),checkNotInRTSRoom],RTCEngine.prototype,"startForwardStreamToRooms",1),__decorateClass$1([reportRtcSdkApi(),checkNotInRTSRoom],RTCEngine.prototype,"updateForwardStreamToRooms",1),__decorateClass$1([reportRtcSdkApi(),checkNotInRTSRoom],RTCEngine.prototype,"stopForwardStreamToRooms",1),__decorateClass$1([reportRtcSdkApi(),checkNotInRTSRoom],RTCEngine.prototype,"pauseForwardStreamToAllRooms",1),__decorateClass$1([reportRtcSdkApi(),checkNotInRTSRoom],RTCEngine.prototype,"resumeForwardStreamToAllRooms",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"setEarMonitorMode",1),__decorateClass$1([reportRtcSdkApi([],{debounce:2e3,debounceTag:(e,...t)=>`${e}`})],RTCEngine.prototype,"setEarMonitorVolume",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"setUserInfo",1);const StreamRemoveReasonMap={"client unpublished":StreamRemoveReason.STREAM_REMOVE_REASON_UNPUBLISH,"publish failed":StreamRemoveReason.STREAM_REMOVE_REASON_PUBLISH_FAILED,"stream removed":StreamRemoveReason.STREAM_REMOVE_REASON_KEEP_LIVE_FAILED,"client disconnected":StreamRemoveReason.STREAM_REMOVE_REASON_CLIENT_DISCONNECTED,"client republish":StreamRemoveReason.STREAM_REMOVE_REASON_REPUBLISH,"token publish privilege expired":StreamRemoveReason.STREAM_REMOVE_REASON_TOKEN_PRIVILEGE_EXPIRED};function subLock(e,t,i){const r=i.value;return i.value=async function(...e){const[t,i,o]=e;this.checkMediaType(o),this.assertNotInRoom();const s=await this.getSubLock(t,i).lock();try{return await r.apply(this,e)}finally{s()}},i}function subLock2(e,t,i){const r=i.value;return i.value=async function(...e){const[t]=e,i=await this.getSubLock(!1,t).lock();try{return await r.apply(this,e)}finally{i()}},i}function captureLock(e){return function(t,i,r){const o=r.value;return r.value=async function(...t){const i=[];"video"!==e&&i.push(this._audioCaptureLock.lock()),"audio"!==e&&i.push(this._videoCaptureLock.lock());const r=await Promise.all(i);try{return await o.apply(this,t)}finally{r.forEach((e=>e()))}},r}}function screenCaptureLock(e,t,i){const r=i.value;return i.value=async function(...e){const t=await this._screenCaptureLock.lock();try{return await r.apply(this,e)}finally{t()}},i}var __defProp2=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__decorateClass=(e,t,i,r)=>{for(var o,s=r>1?void 0:r?__getOwnPropDesc(t,i):t,n=e.length-1;n>=0;n--)(o=e[n])&&(s=(r?o(t,i,s):o(s))||s);return r&&s&&__defProp2(t,i,s),s};class BLWRTCEngine extends RTCEngine{constructor(e,t,i){super(e,t,i),__publicField(this,"singleStreamRenderMode",!1),this.id=t,this.logger=new Logger$1("BLWEngine",0,t),setVideoEncoderAutoConfigList([{width:192,height:108,frameRate:15,maxKbps:100},{width:320,height:180,frameRate:15,maxKbps:140},{width:640,height:360,frameRate:15,maxKbps:400},{width:1280,height:720,frameRate:15,maxKbps:1e3},{width:1920,height:1080,frameRate:15,maxKbps:2e3}]),this._handleEngineEvents()}async subscribeStream(e,t){return this.logger.print("subscribeStream()","userId: %o, mediaType: %o",e,t),this.singleStreamRenderMode&&videoInMediaType(t)&&super.subscribeScreen(e,MediaType$1.VIDEO).catch((e=>{this.logger.error("singleStreamRenderMode subscribeScreen()",e)})),super.subscribeStream(e,t)}async unsubscribeStream(e,t){return this.logger.print("unsubscribeStream()","userId: %o, mediaType: %o",e,t),this.singleStreamRenderMode&&videoInMediaType(t)&&super.unsubscribeScreen(e,MediaType$1.VIDEO).catch((e=>{this.logger.error("singleStreamRenderMode unsubscribeScreen()",e)})),super.unsubscribeStream(e,t)}setRemoteScreenVideoStreamIndex(e){return this.logger.print("setRemoteScreenVideoStreamIndex()","streamIndex: %o",e),!this._room&&(this.singleStreamRenderMode=e===StreamIndex$1.STREAM_INDEX_MAIN,!0)}setRemoteVideoPlayer(e,t){if(this.logger.print("setRemoteVideoPlayer()","streamIndex: %o, videoPlayerOption: %o",e,t),null==t||delete t.playerId,!this.singleStreamRenderMode||e!==StreamIndex$1.STREAM_INDEX_SCREEN)return super.setRemoteVideoPlayer(e,t)}destroy(){this.singleStreamRenderMode=!1,super.destroy()}_updateVideoPlayerState(e){var t,i,r,o,s,n,a;if(!this.singleStreamRenderMode)return super._updateVideoPlayerState(e);const{userId:d}=e,c=null==(t=this._room)?void 0:t.remoteStreams.get(d);let l,u;Array.isArray(c)&&c.forEach((e=>{e.isScreen?l=e:u=e}));let _=null==(i=null==u?void 0:u.videoTrack)?void 0:i.dangerousGetPlayer(DEFAULT_PLAYER_ID);if(!_){const e=null==(r=this._remoteVideoPlayerConfig[StreamIndex$1.STREAM_INDEX_MAIN].get(d))?void 0:r.get(DEFAULT_PLAYER_ID);if(!e)return;null==(s=null==u?void 0:u.videoTrack)||s.setPlayer(this.id,e,null==(o=this._config)?void 0:o.autoPlayPolicy,this._initPlayerEvents.bind(this)),_=null==(n=null==u?void 0:u.videoTrack)?void 0:n.dangerousGetPlayer(DEFAULT_PLAYER_ID)}if(!e.isScreen&&(null==l?void 0:l.videoTrack)&&l.videoHasPublish)return this.logger.print("_updateVideoPlayerState","prevent play main stream"),void(null==_||_.playVideo(l.videoTrack));e.videoTrack?(null==(a=this._config)?void 0:a.autoPlayPolicy)!==RTCAutoPlayPolicy.PLAY_MANUALLY&&(null==_||_.playVideo(e.videoTrack)):(null==_?void 0:_.played)&&_.stop()}_handleEngineEvents(){this.on(EngineEventsTypes.onUserPublishScreen,(e=>{var t,i;if(this.singleStreamRenderMode&&videoInMediaType(e.mediaType)){const r=null==(t=this._room)?void 0:t.remoteStreams.get(e.userId),o=null==r?void 0:r.find((e=>!e.isScreen)),s=null==r?void 0:r.find((e=>e.isScreen));(null==s?void 0:s.hasSubscribed)?(this.logger.info("onUserPublishScreen","singleStreamRenderMode screen hasSubscribed"),this._updateVideoPlayerState(s)):((null==(i=this._room)?void 0:i.config.isAutoSubscribeVideo)||(null==o?void 0:o.hasSubscribed)&&videoInMediaType(o.subMediaType))&&(this.logger.info("onUserPublishScreen","singleStreamRenderMode subscribeScreen"),this.subscribeScreen(e.userId,MediaType$1.VIDEO))}})),this.on(EngineEventsTypes.onUserUnpublishScreen,(e=>{var t;if(this.singleStreamRenderMode&&videoInMediaType(e.mediaType)){const i=null==(t=this._room)?void 0:t.remoteStreams.get(e.userId),r=null==i?void 0:i.find((e=>!e.isScreen));r&&setTimeout((()=>{this._updateVideoPlayerState(r)}))}}))}}__decorateClass([reportRtcSdkApi()],BLWRTCEngine.prototype,"subscribeStream",1),__decorateClass([reportRtcSdkApi()],BLWRTCEngine.prototype,"unsubscribeStream",1),__decorateClass([reportRtcSdkApi()],BLWRTCEngine.prototype,"setRemoteScreenVideoStreamIndex",1),__decorateClass([reportRtcSdkApi()],BLWRTCEngine.prototype,"setRemoteVideoPlayer",1),__decorateClass([reportRtcSdkApi()],BLWRTCEngine.prototype,"destroy",1);const logger=new Logger$1("VERTC",0);iDB.storeKey=`${Date.now()}-${sdkCache.getDeviceId()}`,setGlobalStats({rtc_sdk_version:Config2.VERSION,device_id:sdkCache.getDeviceId(),log_cache_key:iDB.storeKey}),setReportUrl(Config2.LOG_SERVER_URL);let ENGINE_GUID=1;const createEngine=(e,t)=>{logger.info("createEngine","Invoke VERTC.createEngine"),checkString(e,"appId");const i=(ENGINE_GUID++).toString();return createMonitor(i,{rtc_app_id:e,auto_play_policy:null==t?void 0:t.autoPlayPolicy}),new RTCEngine(e,i,t)},createBLWEngine=(e,t)=>{logger.print("createBLWEngine","Invoke VERTC.createBLWEngine"),checkString(e,"appId");const i=(ENGINE_GUID++).toString();return createMonitor(i,{rtc_app_id:e,auto_play_policy:null==t?void 0:t.autoPlayPolicy}),new BLWRTCEngine(e,i,t)},destroyEngine=e=>{if(logger.info("destroyEngine","Invoke VERTC.destroyEngine"),!(e instanceof RTCEngine))throw new SDKError(ErrorCode.INVALID_ENGINE,"Invalid engine object");e.destroy(),destroyMonitor(e.monitor)},enumerateDevices=async()=>dd.enumerateDevices(),enableDevices=async(e={video:!0,audio:!0})=>{const{video:t,audio:i}=e,r={video:!1,audio:!1},o=[];return t&&o.push(dd.getPermissions({video:!0,force:!0}).then((e=>{r.video=e.video,e.video||(r.videoExceptionError=e.reason)}))),i&&o.push(dd.getPermissions({audio:!0,force:!0}).then((e=>{r.audio=e.audio,e.audio||(r.audioExceptionError=e.reason)}))),await Promise.allSettled(o),r},enumerateAudioCaptureDevices=async()=>dd.enumerateAudioCaptureDevices(),enumerateVideoCaptureDevices=async()=>dd.enumerateVideoCaptureDevices(),enumerateAudioPlaybackDevices=async()=>dd.enumerateAudioPlaybackDevices(),getSdkVersion=()=>Config2.VERSION,isSupported2=()=>isSupported(),getSupportedCodecs2=()=>getSupportedCodecs(),setLogConfig=({logLevel:e,LogfileSize:t})=>{e&&(iDB.logLevel=e),t&&(iDB.LogfileSize=t)},downloadLog=e=>{iDB.download(e)};function stringifyParams(...e){return JSON.stringify(e.map((e=>e instanceof RTCEngine?"[ENGINE]":e)))}function reportVERTCApiCall(e,t){return function(...i){reportGlobalApiCall(t,0,stringifyParams(...i));const r=e(...i);return"function"==typeof(null==r?void 0:r.then)?r.then((e=>(reportGlobalCallback(t,0,stringifyParams(e)),e))).catch((e=>{throw reportGlobalCallback(t,e.code,e.message),e})):(reportGlobalCallback(t,0,stringifyParams(r)),r)}}class VERTC{constructor(){__publicField(this,"getSdkVersion",reportVERTCApiCall(getSdkVersion,"getSdkVersion")),__publicField(this,"createEngine",reportVERTCApiCall(createEngine,"createEngine")),__publicField(this,"createBLWEngine",reportVERTCApiCall(createBLWEngine,"createBLWEngine")),__publicField(this,"destroyEngine",reportVERTCApiCall(destroyEngine,"destroyEngine")),__publicField(this,"enumerateDevices",reportVERTCApiCall(enumerateDevices,"enumerateDevices")),__publicField(this,"enableDevices",reportVERTCApiCall(enableDevices,"enableDevices")),__publicField(this,"enumerateAudioCaptureDevices",reportVERTCApiCall(enumerateAudioCaptureDevices,"enumerateAudioCaptureDevices")),__publicField(this,"enumerateVideoCaptureDevices",reportVERTCApiCall(enumerateVideoCaptureDevices,"enumerateVideoCaptureDevices")),__publicField(this,"enumerateAudioPlaybackDevices",reportVERTCApiCall(enumerateAudioPlaybackDevices,"enumerateAudioPlaybackDevices")),__publicField(this,"getParameter",getParameter),__publicField(this,"setParameter",setParameter),__publicField(this,"isSupported",reportVERTCApiCall(isSupported2,"isSupported")),__publicField(this,"getSupportedCodecs",reportVERTCApiCall(getSupportedCodecs2,"getSupportedCodecs")),__publicField(this,"getElectronScreenSources",reportVERTCApiCall(getElectronScreenSources,"getElectronScreenSources")),__publicField(this,"events",EngineEventsTypes),__publicField(this,"ErrorCode",ErrorCode),__publicField(this,"platform","VolcEngine"),__publicField(this,"commitInfo","HEAD<5f79dcb*>"),__publicField(this,"downloadLog",reportVERTCApiCall(downloadLog,"downloadLog")),__publicField(this,"setLogConfig",reportVERTCApiCall(setLogConfig,"setLogConfig"))}}var index=new VERTC;export{AAC_PROFILE,AudioMixingDualMonoMode,AudioMixingType,AudioProfileType,AudioReportMode,AudioSelectionPriority,AudioSourceType,ChannelProfile,ConnectionState,EarMonitorPosition,FallbackOrRecoverReason,ForwardStreamError,ForwardStreamState,LocalMainReportMode,LogChannel,MediaType$1 as MediaType,MirrorMode,MirrorType,NetworkQuality,PublicInterpolationMode,PublicStreamType,PublishState,RTCAutoPlayPolicy,ReconnectReason,RemoteUserPriority,RoomMode,RoomProfileType,SUBTITLE_MODE,SimulcastStreamType,StreamIndex$1 as StreamIndex,StreamRemoveReason,SubscribeFallbackOption,SubscribeMode,SubscribeState,SubtitleEventType,TRANSCODING_VIDEO_CODEC,USER_ONLINE_STATUS,UserDisconnectionTag$1 as UserDisconnectionTag,UserOfflineReason,VideoCodecType,VideoRenderMode,VideoSimulcastMode,VideoSourceType,WTNPlayState,WTNPlayStateChangedReason,WTNPushState,WTNPushStateChangedReason,WTNRemoteAudioState,WTNRemoteAudioStateChangeReason,WTNRemoteVideoState,WTNRemoteVideoStateChangeReason,WTNStreamEventsTypes,index as default};
6
+ var _a,_b,_c,_d,_e,_f,_g,_h,_i,_j,_k,_l,_m,_n,_o,_p,_q,_r,_s,_t,_u,_v,__defProp=Object.defineProperty,__defNormalProp=(e,t,i)=>t in e?__defProp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,__publicField=(e,t,i)=>(__defNormalProp(e,"symbol"!=typeof t?t+"":t,i),i);function _mergeNamespaces(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(i){if("default"!==i&&!(i in e)){var r=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,r.get?r:{enumerable:!0,get:function(){return t[i]}})}}))})),Object.freeze(e)}var getRandomValues$1,VideoSourceType=(e=>(e[e.VIDEO_SOURCE_TYPE_EXTERNAL=0]="VIDEO_SOURCE_TYPE_EXTERNAL",e[e.VIDEO_SOURCE_TYPE_INTERNAL=1]="VIDEO_SOURCE_TYPE_INTERNAL",e))(VideoSourceType||{}),AudioSourceType=(e=>(e[e.AUDIO_SOURCE_TYPE_EXTERNAL=0]="AUDIO_SOURCE_TYPE_EXTERNAL",e[e.AUDIO_SOURCE_TYPE_INTERNAL=1]="AUDIO_SOURCE_TYPE_INTERNAL",e))(AudioSourceType||{}),UserOfflineReason=(e=>(e[e.QUIT=0]="QUIT",e[e.DROPPED=1]="DROPPED",e[e.SWITCH_TO_INVISIBLE=2]="SWITCH_TO_INVISIBLE",e[e.KICKED_BY_ADMIN=3]="KICKED_BY_ADMIN",e))(UserOfflineReason||{}),UserDisconnectionTag$1=(e=>(e.userLeave="userLeave",e.connectionLost="connectionLost",e.userDuplicateLogin="userDuplicateLogin",e.kickedByAdmin="kickedByAdmin",e.roleChanged="roleChanged",e.onUserTokenDidExpire="onUserTokenDidExpire",e))(UserDisconnectionTag$1||{}),ChannelProfile=(e=>(e[e.CHANNEL_PROFILE_COMMUNICATION=0]="CHANNEL_PROFILE_COMMUNICATION",e[e.CHANNEL_PROFILE_LIVE_BROADCASTING=1]="CHANNEL_PROFILE_LIVE_BROADCASTING",e))(ChannelProfile||{}),SubscribeMode=(e=>(e[e.AUTO_SUBSCRIBE_MODE=0]="AUTO_SUBSCRIBE_MODE",e[e.MANUAL_SUBSCRIBE_MODE=1]="MANUAL_SUBSCRIBE_MODE",e))(SubscribeMode||{}),SubscribeState=(e=>(e[e.SUBSCRIBE_SUCC=0]="SUBSCRIBE_SUCC",e[e.SUBSCRIBE_FAIL=1]="SUBSCRIBE_FAIL",e))(SubscribeState||{}),PublishState=(e=>(e[e.PUBLISH_SUCC=0]="PUBLISH_SUCC",e[e.PUBLISH_FAIL=1]="PUBLISH_FAIL",e))(PublishState||{}),MirrorMode=(e=>(e[e.MIRROR_MODE_OFF=0]="MIRROR_MODE_OFF",e[e.MIRROR_MODE_ON=1]="MIRROR_MODE_ON",e))(MirrorMode||{}),VideoRenderMode=(e=>(e[e.RENDER_MODE_HIDDEN=0]="RENDER_MODE_HIDDEN",e[e.RENDER_MODE_FIT=1]="RENDER_MODE_FIT",e[e.RENDER_MODE_FILL=2]="RENDER_MODE_FILL",e))(VideoRenderMode||{}),StreamIndex$1=(e=>(e[e.STREAM_INDEX_MAIN=0]="STREAM_INDEX_MAIN",e[e.STREAM_INDEX_SCREEN=1]="STREAM_INDEX_SCREEN",e))(StreamIndex$1||{}),MediaType$1=(e=>(e[e.AUDIO=1]="AUDIO",e[e.VIDEO=2]="VIDEO",e[e.AUDIO_AND_VIDEO=3]="AUDIO_AND_VIDEO",e))(MediaType$1||{}),StreamRemoveReason=(e=>(e[e.STREAM_REMOVE_REASON_UNPUBLISH=0]="STREAM_REMOVE_REASON_UNPUBLISH",e[e.STREAM_REMOVE_REASON_PUBLISH_FAILED=1]="STREAM_REMOVE_REASON_PUBLISH_FAILED",e[e.STREAM_REMOVE_REASON_KEEP_LIVE_FAILED=2]="STREAM_REMOVE_REASON_KEEP_LIVE_FAILED",e[e.STREAM_REMOVE_REASON_CLIENT_DISCONNECTED=3]="STREAM_REMOVE_REASON_CLIENT_DISCONNECTED",e[e.STREAM_REMOVE_REASON_REPUBLISH=4]="STREAM_REMOVE_REASON_REPUBLISH",e[e.STREAM_REMOVE_REASON_OTHER=5]="STREAM_REMOVE_REASON_OTHER",e[e.STREAM_REMOVE_REASON_TOKEN_PRIVILEGE_EXPIRED=6]="STREAM_REMOVE_REASON_TOKEN_PRIVILEGE_EXPIRED",e))(StreamRemoveReason||{}),ConnectionState=(e=>(e[e.CONNECTION_START=0]="CONNECTION_START",e[e.CONNECTION_STATE_DISCONNECTED=1]="CONNECTION_STATE_DISCONNECTED",e[e.CONNECTION_STATE_CONNECTING=2]="CONNECTION_STATE_CONNECTING",e[e.CONNECTION_STATE_CONNECTED=3]="CONNECTION_STATE_CONNECTED",e[e.CONNECTION_STATE_RECONNECTING=4]="CONNECTION_STATE_RECONNECTING",e[e.CONNECTION_STATE_RECONNECTED=5]="CONNECTION_STATE_RECONNECTED",e[e.CONNECTION_STATE_LOST=6]="CONNECTION_STATE_LOST",e))(ConnectionState||{}),ReconnectReason=(e=>(e.ICE_FAILED="iceFailed",e.NODE_CHANGE="nodeChange",e.JOIN_TIMEOUT="joinTimeout",e.NOTIFY_RECONNECT="notifyReconnect",e))(ReconnectReason||{}),VideoCodecType=(e=>(e.AUTO="auto",e.H264="h264",e.VP8="vp8",e.ByteVC1="ByteVC1",e))(VideoCodecType||{}),MirrorType=(e=>(e[e.MIRROR_TYPE_NONE=0]="MIRROR_TYPE_NONE",e[e.MIRROR_TYPE_RENDER=1]="MIRROR_TYPE_RENDER",e))(MirrorType||{}),LocalMainReportMode=(e=>(e[e.NORMAL=0]="NORMAL",e[e.DISCONNECT=1]="DISCONNECT",e[e.RESET=2]="RESET",e))(LocalMainReportMode||{}),AudioReportMode=(e=>(e[e.MICROPHONE=0]="MICROPHONE",e[e.AUDIOMIXING=1]="AUDIOMIXING",e))(AudioReportMode||{}),LogChannel=(e=>(e[e.domestic=0]="domestic",e[e.overseas=1]="overseas",e))(LogChannel||{}),USER_ONLINE_STATUS=(e=>(e[e.OFFLINE=0]="OFFLINE",e[e.ONLINE=1]="ONLINE",e[e.UNREACHABLE=2]="UNREACHABLE",e))(USER_ONLINE_STATUS||{}),PublicStreamType=(e=>(e[e.AUDIO_AND_VIDEO=0]="AUDIO_AND_VIDEO",e[e.AUDIO_ONLY=1]="AUDIO_ONLY",e[e.VIDEO_ONLY=2]="VIDEO_ONLY",e))(PublicStreamType||{}),PublicInterpolationMode=(e=>(e[e.PREV_FRAME=0]="PREV_FRAME",e[e.OTHER_FRAME=1]="OTHER_FRAME",e))(PublicInterpolationMode||{}),SubscribeFallbackOption=(e=>(e[e.DISABLE=0]="DISABLE",e[e.VIDEO_STREAM_LOW=1]="VIDEO_STREAM_LOW",e[e.AUDIO_ONLY=2]="AUDIO_ONLY",e))(SubscribeFallbackOption||{}),RemoteUserPriority=(e=>(e[e.LOW=0]="LOW",e[e.MEDIUM=100]="MEDIUM",e[e.HIGH=200]="HIGH",e))(RemoteUserPriority||{}),NetworkQuality=(e=>(e[e.UNKNOWN=0]="UNKNOWN",e[e.EXCELLENT=1]="EXCELLENT",e[e.GOOD=2]="GOOD",e[e.POOR=3]="POOR",e[e.BAD=4]="BAD",e[e.VBAD=5]="VBAD",e[e.DOWN=6]="DOWN",e))(NetworkQuality||{}),FallbackOrRecoverReason=(e=>(e[e.Unknown=-1]="Unknown",e[e.SubscribeFallbackByBandwidth=0]="SubscribeFallbackByBandwidth",e[e.SubscribeRecoverByBandwidth=2]="SubscribeRecoverByBandwidth",e))(FallbackOrRecoverReason||{}),RoomProfileType=(e=>(e[e.communication=0]="communication",e[e.chat=5]="chat",e[e.chatRoom=6]="chatRoom",e[e.coHost=9]="coHost",e[e.meeting=16]="meeting",e[e.classRoom=18]="classRoom",e))(RoomProfileType||{}),AudioProfileType=(e=>(e[e.default=0]="default",e[e.fluent=1]="fluent",e[e.standard=2]="standard",e[e.hd=3]="hd",e[e.standardStereo=4]="standardStereo",e[e.hdMono=5]="hdMono",e))(AudioProfileType||{}),RTCAutoPlayPolicy=(e=>(e[e.AUTO_PLAY=0]="AUTO_PLAY",e[e.VIDEO_ONLY=1]="VIDEO_ONLY",e[e.PLAY_MANUALLY=2]="PLAY_MANUALLY",e))(RTCAutoPlayPolicy||{}),AAC_PROFILE=(e=>(e.LC="LC",e.HEv1="HEv1",e.HEv2="HEv2",e))(AAC_PROFILE||{}),TRANSCODING_VIDEO_CODEC=(e=>(e.H264="H264",e.H265="H265",e))(TRANSCODING_VIDEO_CODEC||{}),SUBTITLE_MODE=(e=>(e[e.ASR_ONLY=0]="ASR_ONLY",e[e.ASR_AND_TRANSLATION=1]="ASR_AND_TRANSLATION",e))(SUBTITLE_MODE||{}),SubtitleEventType=(e=>(e[e.STARTED=0]="STARTED",e[e.STOPPED=1]="STOPPED",e[e.ERROR=2]="ERROR",e[e.UPDATED=3]="UPDATED",e))(SubtitleEventType||{}),ForwardStreamState=(e=>(e[e.FORWARD_STREAM_STATE_SUCCESS=0]="FORWARD_STREAM_STATE_SUCCESS",e[e.FORWARD_STREAM_STATE_FAILURE=1]="FORWARD_STREAM_STATE_FAILURE",e))(ForwardStreamState||{}),ForwardStreamError=(e=>(e[e.FORWARD_STREAM_ERROR_OK=0]="FORWARD_STREAM_ERROR_OK",e[e.FORWARD_STREAM_ERROR_INVALID_TOKEN=1202]="FORWARD_STREAM_ERROR_INVALID_TOKEN",e[e.FORWARD_STREAM_ERROR_RESPONSE=1203]="FORWARD_STREAM_ERROR_RESPONSE",e[e.FORWARD_STREAM_ERROR_REMOTE_KICKED=1204]="FORWARD_STREAM_ERROR_REMOTE_KICKED",e[e.FORWARD_STREAM_ERROR_NOT_SUPPORT=1205]="FORWARD_STREAM_ERROR_NOT_SUPPORT",e))(ForwardStreamError||{}),AudioSelectionPriority=(e=>(e[e.DEFAULT=0]="DEFAULT",e[e.HIGH=1]="HIGH",e))(AudioSelectionPriority||{}),VideoSimulcastMode=(e=>(e[e.VIDEO_ONLY_ONE=0]="VIDEO_ONLY_ONE",e[e.VIDEO_ON_DEMAND=1]="VIDEO_ON_DEMAND",e[e.VIDEO_ALWAYS_SIMULCAST=2]="VIDEO_ALWAYS_SIMULCAST",e))(VideoSimulcastMode||{}),SimulcastStreamType=(e=>(e.VIDEO_STREAM_HIGH="high",e.VIDEO_STREAM_MID="mid",e.VIDEO_STREAM_LOW="low",e))(SimulcastStreamType||{}),EarMonitorPosition=(e=>(e[e.NONE=0]="NONE",e[e.AFTER_CAPTURE=1]="AFTER_CAPTURE",e[e.AFTER_PROCESS=2]="AFTER_PROCESS",e))(EarMonitorPosition||{}),RoomMode=(e=>(e[e.ROOM_MODE_RTC=0]="ROOM_MODE_RTC",e[e.ROOM_MODE_RTS_ONLY=1]="ROOM_MODE_RTS_ONLY",e))(RoomMode||{}),rnds8$1=new Uint8Array(16);function rng$1(){if(!getRandomValues$1&&!(getRandomValues$1="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return getRandomValues$1(rnds8$1)}var REGEX=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function validate(e){return"string"==typeof e&&REGEX.test(e)}for(var byteToHex$1=[],i=0;i<256;++i)byteToHex$1.push((i+256).toString(16).substr(1));function stringify(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=(byteToHex$1[e[t+0]]+byteToHex$1[e[t+1]]+byteToHex$1[e[t+2]]+byteToHex$1[e[t+3]]+"-"+byteToHex$1[e[t+4]]+byteToHex$1[e[t+5]]+"-"+byteToHex$1[e[t+6]]+byteToHex$1[e[t+7]]+"-"+byteToHex$1[e[t+8]]+byteToHex$1[e[t+9]]+"-"+byteToHex$1[e[t+10]]+byteToHex$1[e[t+11]]+byteToHex$1[e[t+12]]+byteToHex$1[e[t+13]]+byteToHex$1[e[t+14]]+byteToHex$1[e[t+15]]).toLowerCase();if(!validate(i))throw TypeError("Stringified UUID is invalid");return i}function v4$1(e,t,i){var r=(e=e||{}).random||(e.rng||rng$1)();if(r[6]=15&r[6]|64,r[8]=63&r[8]|128,t){i=i||0;for(var o=0;o<16;++o)t[i+o]=r[o];return t}return stringify(r)}const isSSR$1=()=>"undefined"==typeof window,genUuid$1=()=>v4$1(),assertValidMsgId=e=>"number"==typeof e,isNativeFunction=e=>Function.prototype.toString.call(e).includes("[native code]");function mediaTrackStringify(e){return null==e?"undefined | null":"string"==typeof e?e:JSON.stringify({contentHint:e.contentHint,enabled:e.enabled,id:e.id,kind:e.kind,label:e.label,muted:e.muted,readyState:e.readyState})}function mediaStreamStringify(e){return null==e?"undefined | null":"string"==typeof e?e:JSON.stringify({id:e.id,active:e.active})}function mediaSenderStringify(e){return null==e?"undefined | null":"string"==typeof e?e:JSON.stringify({track:mediaTrackStringify(e.track)})}function mediaReceiverStringify(e){return null==e?"undefined | null":"string"==typeof e?e:JSON.stringify({track:mediaTrackStringify(e.track)})}function mediaTransceiverStringify(e){return null==e?"undefined | null":"string"==typeof e?e:JSON.stringify({currentDirection:e.currentDirection,direction:e.direction,mid:e.mid,stopped:e.stopped,receiver:mediaReceiverStringify(e.receiver),sender:mediaSenderStringify(e.sender)})}const DB_NAME$1="@byted/ve-rtc",STORE_NAME="@byted/ve-rtc",STORE_CACHED_SIZE_KEY="@byted/ve-rtc-cache-size";class IDB{constructor(){__publicField(this,"storeKey"),__publicField(this,"logLevel"),__publicField(this,"LogfileSize"),__publicField(this,"db"),__publicField(this,"logId"),__publicField(this,"cacheLog"),__publicField(this,"cachedSize"),__publicField(this,"preCacheTime"),__publicField(this,"timer"),__publicField(this,"_getSize",(e=>new Blob(e).size/1048576)),this.storeKey="",this.logId=1,this.cacheLog="",this.logLevel="none",this.LogfileSize=100,this._createStore()}_createStore(){if(isSSR$1()||!window.indexedDB)return;const e=indexedDB.open(DB_NAME$1);e.onupgradeneeded=()=>{e.result.createObjectStore(STORE_NAME);try{localStorage.removeItem(STORE_CACHED_SIZE_KEY)}catch(e){}},e.onerror=e=>{},e.onsuccess=()=>{this.db=e.result,this._getCachedSize()}}_getCachedSize(){try{const e=localStorage.getItem(STORE_CACHED_SIZE_KEY);e?this.cachedSize=Number(e):this.values().then((e=>{this.cachedSize=this._getSize(e),this._setCachedSize()}))}catch(e){}}_setCachedSize(){try{localStorage.setItem(STORE_CACHED_SIZE_KEY,`${this.cachedSize}`)}catch(e){}}_getStore(e){if(this.db)return this.db.transaction(STORE_NAME,e).objectStore(STORE_NAME)}set(e){return new Promise(((t,i)=>{if("none"===this.logLevel)return t();if(e&&this.preCacheTime&&this.preCacheTime-Date.now()<1e3)return this.cacheLog+=`\n\n${this.logId}: ${e}`,this.logId++,this.timer||(this.timer=setTimeout((()=>{this.set("")}),1e3-(this.preCacheTime-Date.now()))),t();clearTimeout(this.timer),this.timer=null;const r=this._getStore("readwrite");if(!r)return i("get store fail");this.cachedSize&&this.cachedSize>this.LogfileSize&&this.keyEarliest().then((e=>{this.get(e).then((t=>{this.del(e).then((()=>{this.cachedSize=this.cachedSize-this._getSize([`${t}`]),this._setCachedSize()}))}))}));const o=r.get(this.storeKey);o.onsuccess=()=>{try{const i=`${o.result||""}${this.cacheLog}`,s=e?`${i?"\n\n":""}${this.logId}: ${e}`:"";r.put(`${i}${s}`,this.storeKey),e&&this.logId++,this.cacheLog="",this.cachedSize=(this.cachedSize||0)+this._getSize([`${this.cacheLog}${s}`]),this._setCachedSize(),this.preCacheTime=Date.now(),t()}catch(t){if(!e)return i(t);this.cacheLog+=`\n\n${this.logId}: ${e}`,this.logId++,i(t)}},o.onerror=t=>{if(!e)return i(t);this.cacheLog+=`\n\n${this.logId}: ${e}`,this.logId++,i(t)}}))}get(e){return new Promise(((t,i)=>{const r=this._getStore("readonly");if(!r)return i();const o=r.get(e);o.onsuccess=()=>{t(o.result)},o.onerror=e=>{i(e)}}))}del(e=this.storeKey){return new Promise(((t,i)=>{const r=this._getStore("readwrite");if(!r)return i();const o=r.delete(e);o.onsuccess=()=>t(o.result),o.onerror=e=>i(e)}))}keyEarliest(){return this.keys().then((e=>{let t,i=Date.now();return e.forEach((e=>{if(!e||!e.length)return;const r=e.split("-")[0];Number(r)<i&&(i=Number(r),t=e)})),t}))}keys(){return new Promise(((e,t)=>{const i=this._getStore("readonly");if(!i)return t();if(i.getAllKeys){const r=i.getAllKeys();return r.onsuccess=()=>{e(r.result)},void(r.onerror=()=>{t()})}const r=[];i.openCursor().onsuccess=function(){this.result&&(r.push(this.result.key),this.result.continue())},i.transaction.oncomplete=()=>e(r)}))}values(){return new Promise(((e,t)=>{const i=this._getStore("readonly");if(!i)return t();if(i.getAll){const r=i.getAll();return r.onsuccess=()=>{e(r.result)},void(r.onerror=()=>{t()})}const r=[];i.openCursor().onsuccess=function(){this.result&&(r.push(this.result.value),this.result.continue())},i.transaction.oncomplete=()=>e(r)}))}download(e){e=e||this.storeKey,this.get(e).then((t=>{const i=document.createElement("a");i.download=`${e}.txt`,i.href=`data:text/paint;utf-8,${t||""}`,i.click()}))}}var iDB=new IDB;let EventEmitter$1=class{constructor(){__publicField(this,"_all",{})}on(e,t){const i=this._all[e];i?i.push(t):this._all[e]=[t]}once(e,t){const i=(...r)=>{t(...r),this.off(e,i)};this.on(e,i)}off(e,t){const i=this._all[e];null==i||i.splice(i.indexOf(t)>>>0,1)}emit(e,...t){const i=this._all[e];null==i||i.slice().forEach((e=>e(...t)))}safeEmit(e,...t){try{return this.emit(e,...t)}catch(e){console.error(e)}}destroy(){this._all={}}};const configNumberKeys=["UPLOAD_CONSOLE_LENGTH_CUT","UPLOAD_REPORT_LIMIT"];function needToNumber(e){return configNumberKeys.includes(e)}let Config$2=class extends EventEmitter$1{constructor(){super(...arguments),__publicField(this,"config",{UPLOAD_CONSOLE_ON:!1,UPLOAD_CONSOLE_LENGTH_CUT:200,UPLOAD_REPORT_LIMIT:45e4,ENABLE_REPORT_IDB_BUFFER:!1})}setParameter(e,t){if(needToNumber(e))try{const i=Number(t);if(Number.isNaN(i))return;this.config[e]=i}catch{return void console.warn(`Cannot convert core lib parameter ${e}:${t} into number`)}else this.config[e]=t;this.emit(e,this.config[e])}getParameter(e){return this.config[e]}getKeys(){return Object.keys(this.config)}};const CoreConfig=new Config$2;var commonjsGlobal="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function getDefaultExportFromCjs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function getAugmentedNamespace(e){if(e.__esModule)return e;var t=e.default;if("function"==typeof t){var i=function e(){if(this instanceof e){var i=[null];return i.push.apply(i,arguments),new(Function.bind.apply(t,i))}return t.apply(this,arguments)};i.prototype=t.prototype}else i={};return Object.defineProperty(i,"__esModule",{value:!0}),Object.keys(e).forEach((function(t){var r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(i,t,r.get?r:{enumerable:!0,get:function(){return e[t]}})})),i}var common={};!function(e){var t="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;function i(e,t){return Object.prototype.hasOwnProperty.call(e,t)}e.assign=function(e){for(var t=Array.prototype.slice.call(arguments,1);t.length;){var r=t.shift();if(r){if("object"!=typeof r)throw new TypeError(r+"must be non-object");for(var o in r)i(r,o)&&(e[o]=r[o])}}return e},e.shrinkBuf=function(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)};var r={arraySet:function(e,t,i,r,o){if(t.subarray&&e.subarray)e.set(t.subarray(i,i+r),o);else for(var s=0;s<r;s++)e[o+s]=t[i+s]},flattenChunks:function(e){var t,i,r,o,s,n;for(r=0,t=0,i=e.length;t<i;t++)r+=e[t].length;for(n=new Uint8Array(r),o=0,t=0,i=e.length;t<i;t++)s=e[t],n.set(s,o),o+=s.length;return n}},o={arraySet:function(e,t,i,r,o){for(var s=0;s<r;s++)e[o+s]=t[i+s]},flattenChunks:function(e){return[].concat.apply([],e)}};e.setTyped=function(t){t?(e.Buf8=Uint8Array,e.Buf16=Uint16Array,e.Buf32=Int32Array,e.assign(e,r)):(e.Buf8=Array,e.Buf16=Array,e.Buf32=Array,e.assign(e,o))},e.setTyped(t)}(common);var deflate$4={},deflate$3={},trees$1={},utils$6=common,Z_FIXED$1=4,Z_BINARY=0,Z_TEXT=1,Z_UNKNOWN$1=2;function zero$1(e){for(var t=e.length;--t>=0;)e[t]=0}var STORED_BLOCK=0,STATIC_TREES=1,DYN_TREES=2,MIN_MATCH$1=3,MAX_MATCH$1=258,LENGTH_CODES$1=29,LITERALS$1=256,L_CODES$1=LITERALS$1+1+LENGTH_CODES$1,D_CODES$1=30,BL_CODES$1=19,HEAP_SIZE$1=2*L_CODES$1+1,MAX_BITS$1=15,Buf_size=16,MAX_BL_BITS=7,END_BLOCK=256,REP_3_6=16,REPZ_3_10=17,REPZ_11_138=18,extra_lbits=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],extra_dbits=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],extra_blbits=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],bl_order=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],DIST_CODE_LEN=512,static_ltree=new Array(2*(L_CODES$1+2));zero$1(static_ltree);var static_dtree=new Array(2*D_CODES$1);zero$1(static_dtree);var _dist_code=new Array(DIST_CODE_LEN);zero$1(_dist_code);var _length_code=new Array(MAX_MATCH$1-MIN_MATCH$1+1);zero$1(_length_code);var base_length=new Array(LENGTH_CODES$1);zero$1(base_length);var static_l_desc,static_d_desc,static_bl_desc,base_dist=new Array(D_CODES$1);function StaticTreeDesc(e,t,i,r,o){this.static_tree=e,this.extra_bits=t,this.extra_base=i,this.elems=r,this.max_length=o,this.has_stree=e&&e.length}function TreeDesc(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}function d_code(e){return e<256?_dist_code[e]:_dist_code[256+(e>>>7)]}function put_short(e,t){e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255}function send_bits(e,t,i){e.bi_valid>Buf_size-i?(e.bi_buf|=t<<e.bi_valid&65535,put_short(e,e.bi_buf),e.bi_buf=t>>Buf_size-e.bi_valid,e.bi_valid+=i-Buf_size):(e.bi_buf|=t<<e.bi_valid&65535,e.bi_valid+=i)}function send_code(e,t,i){send_bits(e,i[2*t],i[2*t+1])}function bi_reverse(e,t){var i=0;do{i|=1&e,e>>>=1,i<<=1}while(--t>0);return i>>>1}function bi_flush(e){16===e.bi_valid?(put_short(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)}function gen_bitlen(e,t){var i,r,o,s,n,a,d=t.dyn_tree,c=t.max_code,l=t.stat_desc.static_tree,u=t.stat_desc.has_stree,_=t.stat_desc.extra_bits,h=t.stat_desc.extra_base,p=t.stat_desc.max_length,m=0;for(s=0;s<=MAX_BITS$1;s++)e.bl_count[s]=0;for(d[2*e.heap[e.heap_max]+1]=0,i=e.heap_max+1;i<HEAP_SIZE$1;i++)(s=d[2*d[2*(r=e.heap[i])+1]+1]+1)>p&&(s=p,m++),d[2*r+1]=s,r>c||(e.bl_count[s]++,n=0,r>=h&&(n=_[r-h]),a=d[2*r],e.opt_len+=a*(s+n),u&&(e.static_len+=a*(l[2*r+1]+n)));if(0!==m){do{for(s=p-1;0===e.bl_count[s];)s--;e.bl_count[s]--,e.bl_count[s+1]+=2,e.bl_count[p]--,m-=2}while(m>0);for(s=p;0!==s;s--)for(r=e.bl_count[s];0!==r;)(o=e.heap[--i])>c||(d[2*o+1]!==s&&(e.opt_len+=(s-d[2*o+1])*d[2*o],d[2*o+1]=s),r--)}}function gen_codes(e,t,i){var r,o,s=new Array(MAX_BITS$1+1),n=0;for(r=1;r<=MAX_BITS$1;r++)s[r]=n=n+i[r-1]<<1;for(o=0;o<=t;o++){var a=e[2*o+1];0!==a&&(e[2*o]=bi_reverse(s[a]++,a))}}function tr_static_init(){var e,t,i,r,o,s=new Array(MAX_BITS$1+1);for(i=0,r=0;r<LENGTH_CODES$1-1;r++)for(base_length[r]=i,e=0;e<1<<extra_lbits[r];e++)_length_code[i++]=r;for(_length_code[i-1]=r,o=0,r=0;r<16;r++)for(base_dist[r]=o,e=0;e<1<<extra_dbits[r];e++)_dist_code[o++]=r;for(o>>=7;r<D_CODES$1;r++)for(base_dist[r]=o<<7,e=0;e<1<<extra_dbits[r]-7;e++)_dist_code[256+o++]=r;for(t=0;t<=MAX_BITS$1;t++)s[t]=0;for(e=0;e<=143;)static_ltree[2*e+1]=8,e++,s[8]++;for(;e<=255;)static_ltree[2*e+1]=9,e++,s[9]++;for(;e<=279;)static_ltree[2*e+1]=7,e++,s[7]++;for(;e<=287;)static_ltree[2*e+1]=8,e++,s[8]++;for(gen_codes(static_ltree,L_CODES$1+1,s),e=0;e<D_CODES$1;e++)static_dtree[2*e+1]=5,static_dtree[2*e]=bi_reverse(e,5);static_l_desc=new StaticTreeDesc(static_ltree,extra_lbits,LITERALS$1+1,L_CODES$1,MAX_BITS$1),static_d_desc=new StaticTreeDesc(static_dtree,extra_dbits,0,D_CODES$1,MAX_BITS$1),static_bl_desc=new StaticTreeDesc(new Array(0),extra_blbits,0,BL_CODES$1,MAX_BL_BITS)}function init_block(e){var t;for(t=0;t<L_CODES$1;t++)e.dyn_ltree[2*t]=0;for(t=0;t<D_CODES$1;t++)e.dyn_dtree[2*t]=0;for(t=0;t<BL_CODES$1;t++)e.bl_tree[2*t]=0;e.dyn_ltree[2*END_BLOCK]=1,e.opt_len=e.static_len=0,e.last_lit=e.matches=0}function bi_windup(e){e.bi_valid>8?put_short(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0}function copy_block(e,t,i,r){bi_windup(e),r&&(put_short(e,i),put_short(e,~i)),utils$6.arraySet(e.pending_buf,e.window,t,i,e.pending),e.pending+=i}function smaller(e,t,i,r){var o=2*t,s=2*i;return e[o]<e[s]||e[o]===e[s]&&r[t]<=r[i]}function pqdownheap(e,t,i){for(var r=e.heap[i],o=i<<1;o<=e.heap_len&&(o<e.heap_len&&smaller(t,e.heap[o+1],e.heap[o],e.depth)&&o++,!smaller(t,r,e.heap[o],e.depth));)e.heap[i]=e.heap[o],i=o,o<<=1;e.heap[i]=r}function compress_block(e,t,i){var r,o,s,n,a=0;if(0!==e.last_lit)do{r=e.pending_buf[e.d_buf+2*a]<<8|e.pending_buf[e.d_buf+2*a+1],o=e.pending_buf[e.l_buf+a],a++,0===r?send_code(e,o,t):(send_code(e,(s=_length_code[o])+LITERALS$1+1,t),0!==(n=extra_lbits[s])&&send_bits(e,o-=base_length[s],n),send_code(e,s=d_code(--r),i),0!==(n=extra_dbits[s])&&send_bits(e,r-=base_dist[s],n))}while(a<e.last_lit);send_code(e,END_BLOCK,t)}function build_tree(e,t){var i,r,o,s=t.dyn_tree,n=t.stat_desc.static_tree,a=t.stat_desc.has_stree,d=t.stat_desc.elems,c=-1;for(e.heap_len=0,e.heap_max=HEAP_SIZE$1,i=0;i<d;i++)0!==s[2*i]?(e.heap[++e.heap_len]=c=i,e.depth[i]=0):s[2*i+1]=0;for(;e.heap_len<2;)s[2*(o=e.heap[++e.heap_len]=c<2?++c:0)]=1,e.depth[o]=0,e.opt_len--,a&&(e.static_len-=n[2*o+1]);for(t.max_code=c,i=e.heap_len>>1;i>=1;i--)pqdownheap(e,s,i);o=d;do{i=e.heap[1],e.heap[1]=e.heap[e.heap_len--],pqdownheap(e,s,1),r=e.heap[1],e.heap[--e.heap_max]=i,e.heap[--e.heap_max]=r,s[2*o]=s[2*i]+s[2*r],e.depth[o]=(e.depth[i]>=e.depth[r]?e.depth[i]:e.depth[r])+1,s[2*i+1]=s[2*r+1]=o,e.heap[1]=o++,pqdownheap(e,s,1)}while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],gen_bitlen(e,t),gen_codes(s,c,e.bl_count)}function scan_tree(e,t,i){var r,o,s=-1,n=t[1],a=0,d=7,c=4;for(0===n&&(d=138,c=3),t[2*(i+1)+1]=65535,r=0;r<=i;r++)o=n,n=t[2*(r+1)+1],++a<d&&o===n||(a<c?e.bl_tree[2*o]+=a:0!==o?(o!==s&&e.bl_tree[2*o]++,e.bl_tree[2*REP_3_6]++):a<=10?e.bl_tree[2*REPZ_3_10]++:e.bl_tree[2*REPZ_11_138]++,a=0,s=o,0===n?(d=138,c=3):o===n?(d=6,c=3):(d=7,c=4))}function send_tree(e,t,i){var r,o,s=-1,n=t[1],a=0,d=7,c=4;for(0===n&&(d=138,c=3),r=0;r<=i;r++)if(o=n,n=t[2*(r+1)+1],!(++a<d&&o===n)){if(a<c)do{send_code(e,o,e.bl_tree)}while(0!=--a);else 0!==o?(o!==s&&(send_code(e,o,e.bl_tree),a--),send_code(e,REP_3_6,e.bl_tree),send_bits(e,a-3,2)):a<=10?(send_code(e,REPZ_3_10,e.bl_tree),send_bits(e,a-3,3)):(send_code(e,REPZ_11_138,e.bl_tree),send_bits(e,a-11,7));a=0,s=o,0===n?(d=138,c=3):o===n?(d=6,c=3):(d=7,c=4)}}function build_bl_tree(e){var t;for(scan_tree(e,e.dyn_ltree,e.l_desc.max_code),scan_tree(e,e.dyn_dtree,e.d_desc.max_code),build_tree(e,e.bl_desc),t=BL_CODES$1-1;t>=3&&0===e.bl_tree[2*bl_order[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t}function send_all_trees(e,t,i,r){var o;for(send_bits(e,t-257,5),send_bits(e,i-1,5),send_bits(e,r-4,4),o=0;o<r;o++)send_bits(e,e.bl_tree[2*bl_order[o]+1],3);send_tree(e,e.dyn_ltree,t-1),send_tree(e,e.dyn_dtree,i-1)}function detect_data_type(e){var t,i=4093624447;for(t=0;t<=31;t++,i>>>=1)if(1&i&&0!==e.dyn_ltree[2*t])return Z_BINARY;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return Z_TEXT;for(t=32;t<LITERALS$1;t++)if(0!==e.dyn_ltree[2*t])return Z_TEXT;return Z_BINARY}zero$1(base_dist);var static_init_done=!1;function _tr_init(e){static_init_done||(tr_static_init(),static_init_done=!0),e.l_desc=new TreeDesc(e.dyn_ltree,static_l_desc),e.d_desc=new TreeDesc(e.dyn_dtree,static_d_desc),e.bl_desc=new TreeDesc(e.bl_tree,static_bl_desc),e.bi_buf=0,e.bi_valid=0,init_block(e)}function _tr_stored_block(e,t,i,r){send_bits(e,(STORED_BLOCK<<1)+(r?1:0),3),copy_block(e,t,i,!0)}function _tr_align(e){send_bits(e,STATIC_TREES<<1,3),send_code(e,END_BLOCK,static_ltree),bi_flush(e)}function _tr_flush_block(e,t,i,r){var o,s,n=0;e.level>0?(e.strm.data_type===Z_UNKNOWN$1&&(e.strm.data_type=detect_data_type(e)),build_tree(e,e.l_desc),build_tree(e,e.d_desc),n=build_bl_tree(e),o=e.opt_len+3+7>>>3,(s=e.static_len+3+7>>>3)<=o&&(o=s)):o=s=i+5,i+4<=o&&-1!==t?_tr_stored_block(e,t,i,r):e.strategy===Z_FIXED$1||s===o?(send_bits(e,(STATIC_TREES<<1)+(r?1:0),3),compress_block(e,static_ltree,static_dtree)):(send_bits(e,(DYN_TREES<<1)+(r?1:0),3),send_all_trees(e,e.l_desc.max_code+1,e.d_desc.max_code+1,n+1),compress_block(e,e.dyn_ltree,e.dyn_dtree)),init_block(e),r&&bi_windup(e)}function _tr_tally(e,t,i){return e.pending_buf[e.d_buf+2*e.last_lit]=t>>>8&255,e.pending_buf[e.d_buf+2*e.last_lit+1]=255&t,e.pending_buf[e.l_buf+e.last_lit]=255&i,e.last_lit++,0===t?e.dyn_ltree[2*i]++:(e.matches++,t--,e.dyn_ltree[2*(_length_code[i]+LITERALS$1+1)]++,e.dyn_dtree[2*d_code(t)]++),e.last_lit===e.lit_bufsize-1}function adler32$2(e,t,i,r){for(var o=65535&e,s=e>>>16&65535,n=0;0!==i;){i-=n=i>2e3?2e3:i;do{s=s+(o=o+t[r++]|0)|0}while(--n);o%=65521,s%=65521}return o|s<<16}trees$1._tr_init=_tr_init,trees$1._tr_stored_block=_tr_stored_block,trees$1._tr_flush_block=_tr_flush_block,trees$1._tr_tally=_tr_tally,trees$1._tr_align=_tr_align;var adler32_1=adler32$2;function makeTable(){for(var e,t=[],i=0;i<256;i++){e=i;for(var r=0;r<8;r++)e=1&e?3988292384^e>>>1:e>>>1;t[i]=e}return t}var crcTable=makeTable();function crc32$2(e,t,i,r){var o=crcTable,s=r+i;e^=-1;for(var n=r;n<s;n++)e=e>>>8^o[255&(e^t[n])];return~e}var configuration_table,crc32_1=crc32$2,messages={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},utils$5=common,trees=trees$1,adler32$1=adler32_1,crc32$1=crc32_1,msg$2=messages,Z_NO_FLUSH$1=0,Z_PARTIAL_FLUSH=1,Z_FULL_FLUSH=3,Z_FINISH$2=4,Z_BLOCK$1=5,Z_OK$2=0,Z_STREAM_END$2=1,Z_STREAM_ERROR$1=-2,Z_DATA_ERROR$1=-3,Z_BUF_ERROR$1=-5,Z_DEFAULT_COMPRESSION$1=-1,Z_FILTERED=1,Z_HUFFMAN_ONLY=2,Z_RLE=3,Z_FIXED=4,Z_DEFAULT_STRATEGY$1=0,Z_UNKNOWN=2,Z_DEFLATED$2=8,MAX_MEM_LEVEL=9,MAX_WBITS$1=15,DEF_MEM_LEVEL=8,LENGTH_CODES=29,LITERALS=256,L_CODES=LITERALS+1+LENGTH_CODES,D_CODES=30,BL_CODES=19,HEAP_SIZE=2*L_CODES+1,MAX_BITS=15,MIN_MATCH=3,MAX_MATCH=258,MIN_LOOKAHEAD=MAX_MATCH+MIN_MATCH+1,PRESET_DICT=32,INIT_STATE=42,EXTRA_STATE=69,NAME_STATE=73,COMMENT_STATE=91,HCRC_STATE=103,BUSY_STATE=113,FINISH_STATE=666,BS_NEED_MORE=1,BS_BLOCK_DONE=2,BS_FINISH_STARTED=3,BS_FINISH_DONE=4,OS_CODE=3;function err(e,t){return e.msg=msg$2[t],t}function rank(e){return(e<<1)-(e>4?9:0)}function zero(e){for(var t=e.length;--t>=0;)e[t]=0}function flush_pending(e){var t=e.state,i=t.pending;i>e.avail_out&&(i=e.avail_out),0!==i&&(utils$5.arraySet(e.output,t.pending_buf,t.pending_out,i,e.next_out),e.next_out+=i,t.pending_out+=i,e.total_out+=i,e.avail_out-=i,t.pending-=i,0===t.pending&&(t.pending_out=0))}function flush_block_only(e,t){trees._tr_flush_block(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,flush_pending(e.strm)}function put_byte(e,t){e.pending_buf[e.pending++]=t}function putShortMSB(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t}function read_buf(e,t,i,r){var o=e.avail_in;return o>r&&(o=r),0===o?0:(e.avail_in-=o,utils$5.arraySet(t,e.input,e.next_in,o,i),1===e.state.wrap?e.adler=adler32$1(e.adler,t,o,i):2===e.state.wrap&&(e.adler=crc32$1(e.adler,t,o,i)),e.next_in+=o,e.total_in+=o,o)}function longest_match(e,t){var i,r,o=e.max_chain_length,s=e.strstart,n=e.prev_length,a=e.nice_match,d=e.strstart>e.w_size-MIN_LOOKAHEAD?e.strstart-(e.w_size-MIN_LOOKAHEAD):0,c=e.window,l=e.w_mask,u=e.prev,_=e.strstart+MAX_MATCH,h=c[s+n-1],p=c[s+n];e.prev_length>=e.good_match&&(o>>=2),a>e.lookahead&&(a=e.lookahead);do{if(c[(i=t)+n]===p&&c[i+n-1]===h&&c[i]===c[s]&&c[++i]===c[s+1]){s+=2,i++;do{}while(c[++s]===c[++i]&&c[++s]===c[++i]&&c[++s]===c[++i]&&c[++s]===c[++i]&&c[++s]===c[++i]&&c[++s]===c[++i]&&c[++s]===c[++i]&&c[++s]===c[++i]&&s<_);if(r=MAX_MATCH-(_-s),s=_-MAX_MATCH,r>n){if(e.match_start=t,n=r,r>=a)break;h=c[s+n-1],p=c[s+n]}}}while((t=u[t&l])>d&&0!=--o);return n<=e.lookahead?n:e.lookahead}function fill_window(e){var t,i,r,o,s,n=e.w_size;do{if(o=e.window_size-e.lookahead-e.strstart,e.strstart>=n+(n-MIN_LOOKAHEAD)){utils$5.arraySet(e.window,e.window,n,n,0),e.match_start-=n,e.strstart-=n,e.block_start-=n,t=i=e.hash_size;do{r=e.head[--t],e.head[t]=r>=n?r-n:0}while(--i);t=i=n;do{r=e.prev[--t],e.prev[t]=r>=n?r-n:0}while(--i);o+=n}if(0===e.strm.avail_in)break;if(i=read_buf(e.strm,e.window,e.strstart+e.lookahead,o),e.lookahead+=i,e.lookahead+e.insert>=MIN_MATCH)for(s=e.strstart-e.insert,e.ins_h=e.window[s],e.ins_h=(e.ins_h<<e.hash_shift^e.window[s+1])&e.hash_mask;e.insert&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[s+MIN_MATCH-1])&e.hash_mask,e.prev[s&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=s,s++,e.insert--,!(e.lookahead+e.insert<MIN_MATCH)););}while(e.lookahead<MIN_LOOKAHEAD&&0!==e.strm.avail_in)}function deflate_stored(e,t){var i=65535;for(i>e.pending_buf_size-5&&(i=e.pending_buf_size-5);;){if(e.lookahead<=1){if(fill_window(e),0===e.lookahead&&t===Z_NO_FLUSH$1)return BS_NEED_MORE;if(0===e.lookahead)break}e.strstart+=e.lookahead,e.lookahead=0;var r=e.block_start+i;if((0===e.strstart||e.strstart>=r)&&(e.lookahead=e.strstart-r,e.strstart=r,flush_block_only(e,!1),0===e.strm.avail_out))return BS_NEED_MORE;if(e.strstart-e.block_start>=e.w_size-MIN_LOOKAHEAD&&(flush_block_only(e,!1),0===e.strm.avail_out))return BS_NEED_MORE}return e.insert=0,t===Z_FINISH$2?(flush_block_only(e,!0),0===e.strm.avail_out?BS_FINISH_STARTED:BS_FINISH_DONE):(e.strstart>e.block_start&&(flush_block_only(e,!1),e.strm.avail_out),BS_NEED_MORE)}function deflate_fast(e,t){for(var i,r;;){if(e.lookahead<MIN_LOOKAHEAD){if(fill_window(e),e.lookahead<MIN_LOOKAHEAD&&t===Z_NO_FLUSH$1)return BS_NEED_MORE;if(0===e.lookahead)break}if(i=0,e.lookahead>=MIN_MATCH&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+MIN_MATCH-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),0!==i&&e.strstart-i<=e.w_size-MIN_LOOKAHEAD&&(e.match_length=longest_match(e,i)),e.match_length>=MIN_MATCH)if(r=trees._tr_tally(e,e.strstart-e.match_start,e.match_length-MIN_MATCH),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=MIN_MATCH){e.match_length--;do{e.strstart++,e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+MIN_MATCH-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart}while(0!=--e.match_length);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+1])&e.hash_mask;else r=trees._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(r&&(flush_block_only(e,!1),0===e.strm.avail_out))return BS_NEED_MORE}return e.insert=e.strstart<MIN_MATCH-1?e.strstart:MIN_MATCH-1,t===Z_FINISH$2?(flush_block_only(e,!0),0===e.strm.avail_out?BS_FINISH_STARTED:BS_FINISH_DONE):e.last_lit&&(flush_block_only(e,!1),0===e.strm.avail_out)?BS_NEED_MORE:BS_BLOCK_DONE}function deflate_slow(e,t){for(var i,r,o;;){if(e.lookahead<MIN_LOOKAHEAD){if(fill_window(e),e.lookahead<MIN_LOOKAHEAD&&t===Z_NO_FLUSH$1)return BS_NEED_MORE;if(0===e.lookahead)break}if(i=0,e.lookahead>=MIN_MATCH&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+MIN_MATCH-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=MIN_MATCH-1,0!==i&&e.prev_length<e.max_lazy_match&&e.strstart-i<=e.w_size-MIN_LOOKAHEAD&&(e.match_length=longest_match(e,i),e.match_length<=5&&(e.strategy===Z_FILTERED||e.match_length===MIN_MATCH&&e.strstart-e.match_start>4096)&&(e.match_length=MIN_MATCH-1)),e.prev_length>=MIN_MATCH&&e.match_length<=e.prev_length){o=e.strstart+e.lookahead-MIN_MATCH,r=trees._tr_tally(e,e.strstart-1-e.prev_match,e.prev_length-MIN_MATCH),e.lookahead-=e.prev_length-1,e.prev_length-=2;do{++e.strstart<=o&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+MIN_MATCH-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart)}while(0!=--e.prev_length);if(e.match_available=0,e.match_length=MIN_MATCH-1,e.strstart++,r&&(flush_block_only(e,!1),0===e.strm.avail_out))return BS_NEED_MORE}else if(e.match_available){if((r=trees._tr_tally(e,0,e.window[e.strstart-1]))&&flush_block_only(e,!1),e.strstart++,e.lookahead--,0===e.strm.avail_out)return BS_NEED_MORE}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(r=trees._tr_tally(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<MIN_MATCH-1?e.strstart:MIN_MATCH-1,t===Z_FINISH$2?(flush_block_only(e,!0),0===e.strm.avail_out?BS_FINISH_STARTED:BS_FINISH_DONE):e.last_lit&&(flush_block_only(e,!1),0===e.strm.avail_out)?BS_NEED_MORE:BS_BLOCK_DONE}function deflate_rle(e,t){for(var i,r,o,s,n=e.window;;){if(e.lookahead<=MAX_MATCH){if(fill_window(e),e.lookahead<=MAX_MATCH&&t===Z_NO_FLUSH$1)return BS_NEED_MORE;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=MIN_MATCH&&e.strstart>0&&(r=n[o=e.strstart-1])===n[++o]&&r===n[++o]&&r===n[++o]){s=e.strstart+MAX_MATCH;do{}while(r===n[++o]&&r===n[++o]&&r===n[++o]&&r===n[++o]&&r===n[++o]&&r===n[++o]&&r===n[++o]&&r===n[++o]&&o<s);e.match_length=MAX_MATCH-(s-o),e.match_length>e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=MIN_MATCH?(i=trees._tr_tally(e,1,e.match_length-MIN_MATCH),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(i=trees._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),i&&(flush_block_only(e,!1),0===e.strm.avail_out))return BS_NEED_MORE}return e.insert=0,t===Z_FINISH$2?(flush_block_only(e,!0),0===e.strm.avail_out?BS_FINISH_STARTED:BS_FINISH_DONE):e.last_lit&&(flush_block_only(e,!1),0===e.strm.avail_out)?BS_NEED_MORE:BS_BLOCK_DONE}function deflate_huff(e,t){for(var i;;){if(0===e.lookahead&&(fill_window(e),0===e.lookahead)){if(t===Z_NO_FLUSH$1)return BS_NEED_MORE;break}if(e.match_length=0,i=trees._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,i&&(flush_block_only(e,!1),0===e.strm.avail_out))return BS_NEED_MORE}return e.insert=0,t===Z_FINISH$2?(flush_block_only(e,!0),0===e.strm.avail_out?BS_FINISH_STARTED:BS_FINISH_DONE):e.last_lit&&(flush_block_only(e,!1),0===e.strm.avail_out)?BS_NEED_MORE:BS_BLOCK_DONE}function Config$1(e,t,i,r,o){this.good_length=e,this.max_lazy=t,this.nice_length=i,this.max_chain=r,this.func=o}function lm_init(e){e.window_size=2*e.w_size,zero(e.head),e.max_lazy_match=configuration_table[e.level].max_lazy,e.good_match=configuration_table[e.level].good_length,e.nice_match=configuration_table[e.level].nice_length,e.max_chain_length=configuration_table[e.level].max_chain,e.strstart=0,e.block_start=0,e.lookahead=0,e.insert=0,e.match_length=e.prev_length=MIN_MATCH-1,e.match_available=0,e.ins_h=0}function DeflateState(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Z_DEFLATED$2,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new utils$5.Buf16(2*HEAP_SIZE),this.dyn_dtree=new utils$5.Buf16(2*(2*D_CODES+1)),this.bl_tree=new utils$5.Buf16(2*(2*BL_CODES+1)),zero(this.dyn_ltree),zero(this.dyn_dtree),zero(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new utils$5.Buf16(MAX_BITS+1),this.heap=new utils$5.Buf16(2*L_CODES+1),zero(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new utils$5.Buf16(2*L_CODES+1),zero(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function deflateResetKeep(e){var t;return e&&e.state?(e.total_in=e.total_out=0,e.data_type=Z_UNKNOWN,(t=e.state).pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap?INIT_STATE:BUSY_STATE,e.adler=2===t.wrap?0:1,t.last_flush=Z_NO_FLUSH$1,trees._tr_init(t),Z_OK$2):err(e,Z_STREAM_ERROR$1)}function deflateReset(e){var t=deflateResetKeep(e);return t===Z_OK$2&&lm_init(e.state),t}function deflateSetHeader(e,t){return e&&e.state?2!==e.state.wrap?Z_STREAM_ERROR$1:(e.state.gzhead=t,Z_OK$2):Z_STREAM_ERROR$1}function deflateInit2(e,t,i,r,o,s){if(!e)return Z_STREAM_ERROR$1;var n=1;if(t===Z_DEFAULT_COMPRESSION$1&&(t=6),r<0?(n=0,r=-r):r>15&&(n=2,r-=16),o<1||o>MAX_MEM_LEVEL||i!==Z_DEFLATED$2||r<8||r>15||t<0||t>9||s<0||s>Z_FIXED)return err(e,Z_STREAM_ERROR$1);8===r&&(r=9);var a=new DeflateState;return e.state=a,a.strm=e,a.wrap=n,a.gzhead=null,a.w_bits=r,a.w_size=1<<a.w_bits,a.w_mask=a.w_size-1,a.hash_bits=o+7,a.hash_size=1<<a.hash_bits,a.hash_mask=a.hash_size-1,a.hash_shift=~~((a.hash_bits+MIN_MATCH-1)/MIN_MATCH),a.window=new utils$5.Buf8(2*a.w_size),a.head=new utils$5.Buf16(a.hash_size),a.prev=new utils$5.Buf16(a.w_size),a.lit_bufsize=1<<o+6,a.pending_buf_size=4*a.lit_bufsize,a.pending_buf=new utils$5.Buf8(a.pending_buf_size),a.d_buf=1*a.lit_bufsize,a.l_buf=3*a.lit_bufsize,a.level=t,a.strategy=s,a.method=i,deflateReset(e)}function deflateInit(e,t){return deflateInit2(e,t,Z_DEFLATED$2,MAX_WBITS$1,DEF_MEM_LEVEL,Z_DEFAULT_STRATEGY$1)}function deflate$2(e,t){var i,r,o,s;if(!e||!e.state||t>Z_BLOCK$1||t<0)return e?err(e,Z_STREAM_ERROR$1):Z_STREAM_ERROR$1;if(r=e.state,!e.output||!e.input&&0!==e.avail_in||r.status===FINISH_STATE&&t!==Z_FINISH$2)return err(e,0===e.avail_out?Z_BUF_ERROR$1:Z_STREAM_ERROR$1);if(r.strm=e,i=r.last_flush,r.last_flush=t,r.status===INIT_STATE)if(2===r.wrap)e.adler=0,put_byte(r,31),put_byte(r,139),put_byte(r,8),r.gzhead?(put_byte(r,(r.gzhead.text?1:0)+(r.gzhead.hcrc?2:0)+(r.gzhead.extra?4:0)+(r.gzhead.name?8:0)+(r.gzhead.comment?16:0)),put_byte(r,255&r.gzhead.time),put_byte(r,r.gzhead.time>>8&255),put_byte(r,r.gzhead.time>>16&255),put_byte(r,r.gzhead.time>>24&255),put_byte(r,9===r.level?2:r.strategy>=Z_HUFFMAN_ONLY||r.level<2?4:0),put_byte(r,255&r.gzhead.os),r.gzhead.extra&&r.gzhead.extra.length&&(put_byte(r,255&r.gzhead.extra.length),put_byte(r,r.gzhead.extra.length>>8&255)),r.gzhead.hcrc&&(e.adler=crc32$1(e.adler,r.pending_buf,r.pending,0)),r.gzindex=0,r.status=EXTRA_STATE):(put_byte(r,0),put_byte(r,0),put_byte(r,0),put_byte(r,0),put_byte(r,0),put_byte(r,9===r.level?2:r.strategy>=Z_HUFFMAN_ONLY||r.level<2?4:0),put_byte(r,OS_CODE),r.status=BUSY_STATE);else{var n=Z_DEFLATED$2+(r.w_bits-8<<4)<<8;n|=(r.strategy>=Z_HUFFMAN_ONLY||r.level<2?0:r.level<6?1:6===r.level?2:3)<<6,0!==r.strstart&&(n|=PRESET_DICT),n+=31-n%31,r.status=BUSY_STATE,putShortMSB(r,n),0!==r.strstart&&(putShortMSB(r,e.adler>>>16),putShortMSB(r,65535&e.adler)),e.adler=1}if(r.status===EXTRA_STATE)if(r.gzhead.extra){for(o=r.pending;r.gzindex<(65535&r.gzhead.extra.length)&&(r.pending!==r.pending_buf_size||(r.gzhead.hcrc&&r.pending>o&&(e.adler=crc32$1(e.adler,r.pending_buf,r.pending-o,o)),flush_pending(e),o=r.pending,r.pending!==r.pending_buf_size));)put_byte(r,255&r.gzhead.extra[r.gzindex]),r.gzindex++;r.gzhead.hcrc&&r.pending>o&&(e.adler=crc32$1(e.adler,r.pending_buf,r.pending-o,o)),r.gzindex===r.gzhead.extra.length&&(r.gzindex=0,r.status=NAME_STATE)}else r.status=NAME_STATE;if(r.status===NAME_STATE)if(r.gzhead.name){o=r.pending;do{if(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>o&&(e.adler=crc32$1(e.adler,r.pending_buf,r.pending-o,o)),flush_pending(e),o=r.pending,r.pending===r.pending_buf_size)){s=1;break}s=r.gzindex<r.gzhead.name.length?255&r.gzhead.name.charCodeAt(r.gzindex++):0,put_byte(r,s)}while(0!==s);r.gzhead.hcrc&&r.pending>o&&(e.adler=crc32$1(e.adler,r.pending_buf,r.pending-o,o)),0===s&&(r.gzindex=0,r.status=COMMENT_STATE)}else r.status=COMMENT_STATE;if(r.status===COMMENT_STATE)if(r.gzhead.comment){o=r.pending;do{if(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>o&&(e.adler=crc32$1(e.adler,r.pending_buf,r.pending-o,o)),flush_pending(e),o=r.pending,r.pending===r.pending_buf_size)){s=1;break}s=r.gzindex<r.gzhead.comment.length?255&r.gzhead.comment.charCodeAt(r.gzindex++):0,put_byte(r,s)}while(0!==s);r.gzhead.hcrc&&r.pending>o&&(e.adler=crc32$1(e.adler,r.pending_buf,r.pending-o,o)),0===s&&(r.status=HCRC_STATE)}else r.status=HCRC_STATE;if(r.status===HCRC_STATE&&(r.gzhead.hcrc?(r.pending+2>r.pending_buf_size&&flush_pending(e),r.pending+2<=r.pending_buf_size&&(put_byte(r,255&e.adler),put_byte(r,e.adler>>8&255),e.adler=0,r.status=BUSY_STATE)):r.status=BUSY_STATE),0!==r.pending){if(flush_pending(e),0===e.avail_out)return r.last_flush=-1,Z_OK$2}else if(0===e.avail_in&&rank(t)<=rank(i)&&t!==Z_FINISH$2)return err(e,Z_BUF_ERROR$1);if(r.status===FINISH_STATE&&0!==e.avail_in)return err(e,Z_BUF_ERROR$1);if(0!==e.avail_in||0!==r.lookahead||t!==Z_NO_FLUSH$1&&r.status!==FINISH_STATE){var a=r.strategy===Z_HUFFMAN_ONLY?deflate_huff(r,t):r.strategy===Z_RLE?deflate_rle(r,t):configuration_table[r.level].func(r,t);if(a!==BS_FINISH_STARTED&&a!==BS_FINISH_DONE||(r.status=FINISH_STATE),a===BS_NEED_MORE||a===BS_FINISH_STARTED)return 0===e.avail_out&&(r.last_flush=-1),Z_OK$2;if(a===BS_BLOCK_DONE&&(t===Z_PARTIAL_FLUSH?trees._tr_align(r):t!==Z_BLOCK$1&&(trees._tr_stored_block(r,0,0,!1),t===Z_FULL_FLUSH&&(zero(r.head),0===r.lookahead&&(r.strstart=0,r.block_start=0,r.insert=0))),flush_pending(e),0===e.avail_out))return r.last_flush=-1,Z_OK$2}return t!==Z_FINISH$2?Z_OK$2:r.wrap<=0?Z_STREAM_END$2:(2===r.wrap?(put_byte(r,255&e.adler),put_byte(r,e.adler>>8&255),put_byte(r,e.adler>>16&255),put_byte(r,e.adler>>24&255),put_byte(r,255&e.total_in),put_byte(r,e.total_in>>8&255),put_byte(r,e.total_in>>16&255),put_byte(r,e.total_in>>24&255)):(putShortMSB(r,e.adler>>>16),putShortMSB(r,65535&e.adler)),flush_pending(e),r.wrap>0&&(r.wrap=-r.wrap),0!==r.pending?Z_OK$2:Z_STREAM_END$2)}function deflateEnd(e){var t;return e&&e.state?(t=e.state.status)!==INIT_STATE&&t!==EXTRA_STATE&&t!==NAME_STATE&&t!==COMMENT_STATE&&t!==HCRC_STATE&&t!==BUSY_STATE&&t!==FINISH_STATE?err(e,Z_STREAM_ERROR$1):(e.state=null,t===BUSY_STATE?err(e,Z_DATA_ERROR$1):Z_OK$2):Z_STREAM_ERROR$1}function deflateSetDictionary(e,t){var i,r,o,s,n,a,d,c,l=t.length;if(!e||!e.state)return Z_STREAM_ERROR$1;if(2===(s=(i=e.state).wrap)||1===s&&i.status!==INIT_STATE||i.lookahead)return Z_STREAM_ERROR$1;for(1===s&&(e.adler=adler32$1(e.adler,t,l,0)),i.wrap=0,l>=i.w_size&&(0===s&&(zero(i.head),i.strstart=0,i.block_start=0,i.insert=0),c=new utils$5.Buf8(i.w_size),utils$5.arraySet(c,t,l-i.w_size,i.w_size,0),t=c,l=i.w_size),n=e.avail_in,a=e.next_in,d=e.input,e.avail_in=l,e.next_in=0,e.input=t,fill_window(i);i.lookahead>=MIN_MATCH;){r=i.strstart,o=i.lookahead-(MIN_MATCH-1);do{i.ins_h=(i.ins_h<<i.hash_shift^i.window[r+MIN_MATCH-1])&i.hash_mask,i.prev[r&i.w_mask]=i.head[i.ins_h],i.head[i.ins_h]=r,r++}while(--o);i.strstart=r,i.lookahead=MIN_MATCH-1,fill_window(i)}return i.strstart+=i.lookahead,i.block_start=i.strstart,i.insert=i.lookahead,i.lookahead=0,i.match_length=i.prev_length=MIN_MATCH-1,i.match_available=0,e.next_in=a,e.input=d,e.avail_in=n,i.wrap=s,Z_OK$2}configuration_table=[new Config$1(0,0,0,0,deflate_stored),new Config$1(4,4,8,4,deflate_fast),new Config$1(4,5,16,8,deflate_fast),new Config$1(4,6,32,32,deflate_fast),new Config$1(4,4,16,16,deflate_slow),new Config$1(8,16,32,32,deflate_slow),new Config$1(8,16,128,128,deflate_slow),new Config$1(8,32,128,256,deflate_slow),new Config$1(32,128,258,1024,deflate_slow),new Config$1(32,258,258,4096,deflate_slow)],deflate$3.deflateInit=deflateInit,deflate$3.deflateInit2=deflateInit2,deflate$3.deflateReset=deflateReset,deflate$3.deflateResetKeep=deflateResetKeep,deflate$3.deflateSetHeader=deflateSetHeader,deflate$3.deflate=deflate$2,deflate$3.deflateEnd=deflateEnd,deflate$3.deflateSetDictionary=deflateSetDictionary,deflate$3.deflateInfo="pako deflate (from Nodeca project)";var strings$2={},utils$4=common,STR_APPLY_OK=!0,STR_APPLY_UIA_OK=!0;try{String.fromCharCode.apply(null,[0])}catch(e){STR_APPLY_OK=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){STR_APPLY_UIA_OK=!1}for(var _utf8len=new utils$4.Buf8(256),q=0;q<256;q++)_utf8len[q]=q>=252?6:q>=248?5:q>=240?4:q>=224?3:q>=192?2:1;function buf2binstring(e,t){if(t<65534&&(e.subarray&&STR_APPLY_UIA_OK||!e.subarray&&STR_APPLY_OK))return String.fromCharCode.apply(null,utils$4.shrinkBuf(e,t));for(var i="",r=0;r<t;r++)i+=String.fromCharCode(e[r]);return i}function ZStream$2(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}_utf8len[254]=_utf8len[254]=1,strings$2.string2buf=function(e){var t,i,r,o,s,n=e.length,a=0;for(o=0;o<n;o++)55296==(64512&(i=e.charCodeAt(o)))&&o+1<n&&56320==(64512&(r=e.charCodeAt(o+1)))&&(i=65536+(i-55296<<10)+(r-56320),o++),a+=i<128?1:i<2048?2:i<65536?3:4;for(t=new utils$4.Buf8(a),s=0,o=0;s<a;o++)55296==(64512&(i=e.charCodeAt(o)))&&o+1<n&&56320==(64512&(r=e.charCodeAt(o+1)))&&(i=65536+(i-55296<<10)+(r-56320),o++),i<128?t[s++]=i:i<2048?(t[s++]=192|i>>>6,t[s++]=128|63&i):i<65536?(t[s++]=224|i>>>12,t[s++]=128|i>>>6&63,t[s++]=128|63&i):(t[s++]=240|i>>>18,t[s++]=128|i>>>12&63,t[s++]=128|i>>>6&63,t[s++]=128|63&i);return t},strings$2.buf2binstring=function(e){return buf2binstring(e,e.length)},strings$2.binstring2buf=function(e){for(var t=new utils$4.Buf8(e.length),i=0,r=t.length;i<r;i++)t[i]=e.charCodeAt(i);return t},strings$2.buf2string=function(e,t){var i,r,o,s,n=t||e.length,a=new Array(2*n);for(r=0,i=0;i<n;)if((o=e[i++])<128)a[r++]=o;else if((s=_utf8len[o])>4)a[r++]=65533,i+=s-1;else{for(o&=2===s?31:3===s?15:7;s>1&&i<n;)o=o<<6|63&e[i++],s--;s>1?a[r++]=65533:o<65536?a[r++]=o:(o-=65536,a[r++]=55296|o>>10&1023,a[r++]=56320|1023&o)}return buf2binstring(a,r)},strings$2.utf8border=function(e,t){var i;for((t=t||e.length)>e.length&&(t=e.length),i=t-1;i>=0&&128==(192&e[i]);)i--;return i<0||0===i?t:i+_utf8len[e[i]]>t?i:t};var zstream=ZStream$2,zlib_deflate=deflate$3,utils$3=common,strings$1=strings$2,msg$1=messages,ZStream$1=zstream,toString$1=Object.prototype.toString,Z_NO_FLUSH=0,Z_FINISH$1=4,Z_OK$1=0,Z_STREAM_END$1=1,Z_SYNC_FLUSH=2,Z_DEFAULT_COMPRESSION=-1,Z_DEFAULT_STRATEGY=0,Z_DEFLATED$1=8;function Deflate(e){if(!(this instanceof Deflate))return new Deflate(e);this.options=utils$3.assign({level:Z_DEFAULT_COMPRESSION,method:Z_DEFLATED$1,chunkSize:16384,windowBits:15,memLevel:8,strategy:Z_DEFAULT_STRATEGY,to:""},e||{});var t=this.options;t.raw&&t.windowBits>0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new ZStream$1,this.strm.avail_out=0;var i=zlib_deflate.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(i!==Z_OK$1)throw new Error(msg$1[i]);if(t.header&&zlib_deflate.deflateSetHeader(this.strm,t.header),t.dictionary){var r;if(r="string"==typeof t.dictionary?strings$1.string2buf(t.dictionary):"[object ArrayBuffer]"===toString$1.call(t.dictionary)?new Uint8Array(t.dictionary):t.dictionary,(i=zlib_deflate.deflateSetDictionary(this.strm,r))!==Z_OK$1)throw new Error(msg$1[i]);this._dict_set=!0}}function deflate$1(e,t){var i=new Deflate(t);if(i.push(e,!0),i.err)throw i.msg||msg$1[i.err];return i.result}function deflateRaw(e,t){return(t=t||{}).raw=!0,deflate$1(e,t)}function gzip(e,t){return(t=t||{}).gzip=!0,deflate$1(e,t)}Deflate.prototype.push=function(e,t){var i,r,o=this.strm,s=this.options.chunkSize;if(this.ended)return!1;r=t===~~t?t:!0===t?Z_FINISH$1:Z_NO_FLUSH,"string"==typeof e?o.input=strings$1.string2buf(e):"[object ArrayBuffer]"===toString$1.call(e)?o.input=new Uint8Array(e):o.input=e,o.next_in=0,o.avail_in=o.input.length;do{if(0===o.avail_out&&(o.output=new utils$3.Buf8(s),o.next_out=0,o.avail_out=s),(i=zlib_deflate.deflate(o,r))!==Z_STREAM_END$1&&i!==Z_OK$1)return this.onEnd(i),this.ended=!0,!1;0!==o.avail_out&&(0!==o.avail_in||r!==Z_FINISH$1&&r!==Z_SYNC_FLUSH)||("string"===this.options.to?this.onData(strings$1.buf2binstring(utils$3.shrinkBuf(o.output,o.next_out))):this.onData(utils$3.shrinkBuf(o.output,o.next_out)))}while((o.avail_in>0||0===o.avail_out)&&i!==Z_STREAM_END$1);return r===Z_FINISH$1?(i=zlib_deflate.deflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===Z_OK$1):r!==Z_SYNC_FLUSH||(this.onEnd(Z_OK$1),o.avail_out=0,!0)},Deflate.prototype.onData=function(e){this.chunks.push(e)},Deflate.prototype.onEnd=function(e){e===Z_OK$1&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=utils$3.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},deflate$4.Deflate=Deflate,deflate$4.deflate=deflate$1,deflate$4.deflateRaw=deflateRaw,deflate$4.gzip=gzip;var inflate$4={},inflate$3={},BAD$1=30,TYPE$1=12,inffast=function(e,t){var i,r,o,s,n,a,d,c,l,u,_,h,p,m,S,g,v,f,E,T,R,b,y,I,C;i=e.state,r=e.next_in,I=e.input,o=r+(e.avail_in-5),s=e.next_out,C=e.output,n=s-(t-e.avail_out),a=s+(e.avail_out-257),d=i.dmax,c=i.wsize,l=i.whave,u=i.wnext,_=i.window,h=i.hold,p=i.bits,m=i.lencode,S=i.distcode,g=(1<<i.lenbits)-1,v=(1<<i.distbits)-1;e:do{p<15&&(h+=I[r++]<<p,p+=8,h+=I[r++]<<p,p+=8),f=m[h&g];t:for(;;){if(h>>>=E=f>>>24,p-=E,0===(E=f>>>16&255))C[s++]=65535&f;else{if(!(16&E)){if(64&E){if(32&E){i.mode=TYPE$1;break e}e.msg="invalid literal/length code",i.mode=BAD$1;break e}f=m[(65535&f)+(h&(1<<E)-1)];continue t}for(T=65535&f,(E&=15)&&(p<E&&(h+=I[r++]<<p,p+=8),T+=h&(1<<E)-1,h>>>=E,p-=E),p<15&&(h+=I[r++]<<p,p+=8,h+=I[r++]<<p,p+=8),f=S[h&v];;){if(h>>>=E=f>>>24,p-=E,16&(E=f>>>16&255)){if(R=65535&f,p<(E&=15)&&(h+=I[r++]<<p,(p+=8)<E&&(h+=I[r++]<<p,p+=8)),(R+=h&(1<<E)-1)>d){e.msg="invalid distance too far back",i.mode=BAD$1;break e}if(h>>>=E,p-=E,R>(E=s-n)){if((E=R-E)>l&&i.sane){e.msg="invalid distance too far back",i.mode=BAD$1;break e}if(b=0,y=_,0===u){if(b+=c-E,E<T){T-=E;do{C[s++]=_[b++]}while(--E);b=s-R,y=C}}else if(u<E){if(b+=c+u-E,(E-=u)<T){T-=E;do{C[s++]=_[b++]}while(--E);if(b=0,u<T){T-=E=u;do{C[s++]=_[b++]}while(--E);b=s-R,y=C}}}else if(b+=u-E,E<T){T-=E;do{C[s++]=_[b++]}while(--E);b=s-R,y=C}for(;T>2;)C[s++]=y[b++],C[s++]=y[b++],C[s++]=y[b++],T-=3;T&&(C[s++]=y[b++],T>1&&(C[s++]=y[b++]))}else{b=s-R;do{C[s++]=C[b++],C[s++]=C[b++],C[s++]=C[b++],T-=3}while(T>2);T&&(C[s++]=C[b++],T>1&&(C[s++]=C[b++]))}break}if(64&E){e.msg="invalid distance code",i.mode=BAD$1;break e}f=S[(65535&f)+(h&(1<<E)-1)]}}break}}while(r<o&&s<a);r-=T=p>>3,h&=(1<<(p-=T<<3))-1,e.next_in=r,e.next_out=s,e.avail_in=r<o?o-r+5:5-(r-o),e.avail_out=s<a?a-s+257:257-(s-a),i.hold=h,i.bits=p},utils$2=common,MAXBITS=15,ENOUGH_LENS$1=852,ENOUGH_DISTS$1=592,CODES$1=0,LENS$1=1,DISTS$1=2,lbase=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],lext=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],dbase=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],dext=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64],inftrees=function(e,t,i,r,o,s,n,a){var d,c,l,u,_,h,p,m,S,g=a.bits,v=0,f=0,E=0,T=0,R=0,b=0,y=0,I=0,C=0,A=0,k=null,M=0,N=new utils$2.Buf16(MAXBITS+1),O=new utils$2.Buf16(MAXBITS+1),P=null,D=0;for(v=0;v<=MAXBITS;v++)N[v]=0;for(f=0;f<r;f++)N[t[i+f]]++;for(R=g,T=MAXBITS;T>=1&&0===N[T];T--);if(R>T&&(R=T),0===T)return o[s++]=20971520,o[s++]=20971520,a.bits=1,0;for(E=1;E<T&&0===N[E];E++);for(R<E&&(R=E),I=1,v=1;v<=MAXBITS;v++)if(I<<=1,(I-=N[v])<0)return-1;if(I>0&&(e===CODES$1||1!==T))return-1;for(O[1]=0,v=1;v<MAXBITS;v++)O[v+1]=O[v]+N[v];for(f=0;f<r;f++)0!==t[i+f]&&(n[O[t[i+f]]++]=f);if(e===CODES$1?(k=P=n,h=19):e===LENS$1?(k=lbase,M-=257,P=lext,D-=257,h=256):(k=dbase,P=dext,h=-1),A=0,f=0,v=E,_=s,b=R,y=0,l=-1,u=(C=1<<R)-1,e===LENS$1&&C>ENOUGH_LENS$1||e===DISTS$1&&C>ENOUGH_DISTS$1)return 1;for(;;){p=v-y,n[f]<h?(m=0,S=n[f]):n[f]>h?(m=P[D+n[f]],S=k[M+n[f]]):(m=96,S=0),d=1<<v-y,E=c=1<<b;do{o[_+(A>>y)+(c-=d)]=p<<24|m<<16|S}while(0!==c);for(d=1<<v-1;A&d;)d>>=1;if(0!==d?(A&=d-1,A+=d):A=0,f++,0==--N[v]){if(v===T)break;v=t[i+n[f]]}if(v>R&&(A&u)!==l){for(0===y&&(y=R),_+=E,I=1<<(b=v-y);b+y<T&&!((I-=N[b+y])<=0);)b++,I<<=1;if(C+=1<<b,e===LENS$1&&C>ENOUGH_LENS$1||e===DISTS$1&&C>ENOUGH_DISTS$1)return 1;o[l=A&u]=R<<24|b<<16|_-s}}return 0!==A&&(o[_+A]=v-y<<24|64<<16),a.bits=R,0},utils$1=common,adler32=adler32_1,crc32=crc32_1,inflate_fast2=inffast,inflate_table2=inftrees,CODES=0,LENS=1,DISTS=2,Z_FINISH=4,Z_BLOCK=5,Z_TREES=6,Z_OK=0,Z_STREAM_END=1,Z_NEED_DICT=2,Z_STREAM_ERROR=-2,Z_DATA_ERROR=-3,Z_MEM_ERROR=-4,Z_BUF_ERROR=-5,Z_DEFLATED=8,HEAD=1,FLAGS=2,TIME=3,OS=4,EXLEN=5,EXTRA=6,NAME=7,COMMENT=8,HCRC=9,DICTID=10,DICT=11,TYPE=12,TYPEDO=13,STORED=14,COPY_=15,COPY=16,TABLE=17,LENLENS=18,CODELENS=19,LEN_=20,LEN=21,LENEXT=22,DIST=23,DISTEXT=24,MATCH=25,LIT=26,CHECK=27,LENGTH=28,DONE=29,BAD=30,MEM=31,SYNC=32,ENOUGH_LENS=852,ENOUGH_DISTS=592,MAX_WBITS=15,DEF_WBITS=MAX_WBITS;function zswap32(e){return(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}function InflateState(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new utils$1.Buf16(320),this.work=new utils$1.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function inflateResetKeep(e){var t;return e&&e.state?(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=HEAD,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new utils$1.Buf32(ENOUGH_LENS),t.distcode=t.distdyn=new utils$1.Buf32(ENOUGH_DISTS),t.sane=1,t.back=-1,Z_OK):Z_STREAM_ERROR}function inflateReset(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,inflateResetKeep(e)):Z_STREAM_ERROR}function inflateReset2(e,t){var i,r;return e&&e.state?(r=e.state,t<0?(i=0,t=-t):(i=1+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?Z_STREAM_ERROR:(null!==r.window&&r.wbits!==t&&(r.window=null),r.wrap=i,r.wbits=t,inflateReset(e))):Z_STREAM_ERROR}function inflateInit2(e,t){var i,r;return e?(r=new InflateState,e.state=r,r.window=null,(i=inflateReset2(e,t))!==Z_OK&&(e.state=null),i):Z_STREAM_ERROR}function inflateInit(e){return inflateInit2(e,DEF_WBITS)}var lenfix,distfix,virgin=!0;function fixedtables(e){if(virgin){var t;for(lenfix=new utils$1.Buf32(512),distfix=new utils$1.Buf32(32),t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(inflate_table2(LENS,e.lens,0,288,lenfix,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;inflate_table2(DISTS,e.lens,0,32,distfix,0,e.work,{bits:5}),virgin=!1}e.lencode=lenfix,e.lenbits=9,e.distcode=distfix,e.distbits=5}function updatewindow(e,t,i,r){var o,s=e.state;return null===s.window&&(s.wsize=1<<s.wbits,s.wnext=0,s.whave=0,s.window=new utils$1.Buf8(s.wsize)),r>=s.wsize?(utils$1.arraySet(s.window,t,i-s.wsize,s.wsize,0),s.wnext=0,s.whave=s.wsize):((o=s.wsize-s.wnext)>r&&(o=r),utils$1.arraySet(s.window,t,i-r,o,s.wnext),(r-=o)?(utils$1.arraySet(s.window,t,i-r,r,0),s.wnext=r,s.whave=s.wsize):(s.wnext+=o,s.wnext===s.wsize&&(s.wnext=0),s.whave<s.wsize&&(s.whave+=o))),0}function inflate$2(e,t){var i,r,o,s,n,a,d,c,l,u,_,h,p,m,S,g,v,f,E,T,R,b,y,I,C=0,A=new utils$1.Buf8(4),k=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!e||!e.state||!e.output||!e.input&&0!==e.avail_in)return Z_STREAM_ERROR;(i=e.state).mode===TYPE&&(i.mode=TYPEDO),n=e.next_out,o=e.output,d=e.avail_out,s=e.next_in,r=e.input,a=e.avail_in,c=i.hold,l=i.bits,u=a,_=d,b=Z_OK;e:for(;;)switch(i.mode){case HEAD:if(0===i.wrap){i.mode=TYPEDO;break}for(;l<16;){if(0===a)break e;a--,c+=r[s++]<<l,l+=8}if(2&i.wrap&&35615===c){i.check=0,A[0]=255&c,A[1]=c>>>8&255,i.check=crc32(i.check,A,2,0),c=0,l=0,i.mode=FLAGS;break}if(i.flags=0,i.head&&(i.head.done=!1),!(1&i.wrap)||(((255&c)<<8)+(c>>8))%31){e.msg="incorrect header check",i.mode=BAD;break}if((15&c)!==Z_DEFLATED){e.msg="unknown compression method",i.mode=BAD;break}if(l-=4,R=8+(15&(c>>>=4)),0===i.wbits)i.wbits=R;else if(R>i.wbits){e.msg="invalid window size",i.mode=BAD;break}i.dmax=1<<R,e.adler=i.check=1,i.mode=512&c?DICTID:TYPE,c=0,l=0;break;case FLAGS:for(;l<16;){if(0===a)break e;a--,c+=r[s++]<<l,l+=8}if(i.flags=c,(255&i.flags)!==Z_DEFLATED){e.msg="unknown compression method",i.mode=BAD;break}if(57344&i.flags){e.msg="unknown header flags set",i.mode=BAD;break}i.head&&(i.head.text=c>>8&1),512&i.flags&&(A[0]=255&c,A[1]=c>>>8&255,i.check=crc32(i.check,A,2,0)),c=0,l=0,i.mode=TIME;case TIME:for(;l<32;){if(0===a)break e;a--,c+=r[s++]<<l,l+=8}i.head&&(i.head.time=c),512&i.flags&&(A[0]=255&c,A[1]=c>>>8&255,A[2]=c>>>16&255,A[3]=c>>>24&255,i.check=crc32(i.check,A,4,0)),c=0,l=0,i.mode=OS;case OS:for(;l<16;){if(0===a)break e;a--,c+=r[s++]<<l,l+=8}i.head&&(i.head.xflags=255&c,i.head.os=c>>8),512&i.flags&&(A[0]=255&c,A[1]=c>>>8&255,i.check=crc32(i.check,A,2,0)),c=0,l=0,i.mode=EXLEN;case EXLEN:if(1024&i.flags){for(;l<16;){if(0===a)break e;a--,c+=r[s++]<<l,l+=8}i.length=c,i.head&&(i.head.extra_len=c),512&i.flags&&(A[0]=255&c,A[1]=c>>>8&255,i.check=crc32(i.check,A,2,0)),c=0,l=0}else i.head&&(i.head.extra=null);i.mode=EXTRA;case EXTRA:if(1024&i.flags&&((h=i.length)>a&&(h=a),h&&(i.head&&(R=i.head.extra_len-i.length,i.head.extra||(i.head.extra=new Array(i.head.extra_len)),utils$1.arraySet(i.head.extra,r,s,h,R)),512&i.flags&&(i.check=crc32(i.check,r,h,s)),a-=h,s+=h,i.length-=h),i.length))break e;i.length=0,i.mode=NAME;case NAME:if(2048&i.flags){if(0===a)break e;h=0;do{R=r[s+h++],i.head&&R&&i.length<65536&&(i.head.name+=String.fromCharCode(R))}while(R&&h<a);if(512&i.flags&&(i.check=crc32(i.check,r,h,s)),a-=h,s+=h,R)break e}else i.head&&(i.head.name=null);i.length=0,i.mode=COMMENT;case COMMENT:if(4096&i.flags){if(0===a)break e;h=0;do{R=r[s+h++],i.head&&R&&i.length<65536&&(i.head.comment+=String.fromCharCode(R))}while(R&&h<a);if(512&i.flags&&(i.check=crc32(i.check,r,h,s)),a-=h,s+=h,R)break e}else i.head&&(i.head.comment=null);i.mode=HCRC;case HCRC:if(512&i.flags){for(;l<16;){if(0===a)break e;a--,c+=r[s++]<<l,l+=8}if(c!==(65535&i.check)){e.msg="header crc mismatch",i.mode=BAD;break}c=0,l=0}i.head&&(i.head.hcrc=i.flags>>9&1,i.head.done=!0),e.adler=i.check=0,i.mode=TYPE;break;case DICTID:for(;l<32;){if(0===a)break e;a--,c+=r[s++]<<l,l+=8}e.adler=i.check=zswap32(c),c=0,l=0,i.mode=DICT;case DICT:if(0===i.havedict)return e.next_out=n,e.avail_out=d,e.next_in=s,e.avail_in=a,i.hold=c,i.bits=l,Z_NEED_DICT;e.adler=i.check=1,i.mode=TYPE;case TYPE:if(t===Z_BLOCK||t===Z_TREES)break e;case TYPEDO:if(i.last){c>>>=7&l,l-=7&l,i.mode=CHECK;break}for(;l<3;){if(0===a)break e;a--,c+=r[s++]<<l,l+=8}switch(i.last=1&c,l-=1,3&(c>>>=1)){case 0:i.mode=STORED;break;case 1:if(fixedtables(i),i.mode=LEN_,t===Z_TREES){c>>>=2,l-=2;break e}break;case 2:i.mode=TABLE;break;case 3:e.msg="invalid block type",i.mode=BAD}c>>>=2,l-=2;break;case STORED:for(c>>>=7&l,l-=7&l;l<32;){if(0===a)break e;a--,c+=r[s++]<<l,l+=8}if((65535&c)!=(c>>>16^65535)){e.msg="invalid stored block lengths",i.mode=BAD;break}if(i.length=65535&c,c=0,l=0,i.mode=COPY_,t===Z_TREES)break e;case COPY_:i.mode=COPY;case COPY:if(h=i.length){if(h>a&&(h=a),h>d&&(h=d),0===h)break e;utils$1.arraySet(o,r,s,h,n),a-=h,s+=h,d-=h,n+=h,i.length-=h;break}i.mode=TYPE;break;case TABLE:for(;l<14;){if(0===a)break e;a--,c+=r[s++]<<l,l+=8}if(i.nlen=257+(31&c),c>>>=5,l-=5,i.ndist=1+(31&c),c>>>=5,l-=5,i.ncode=4+(15&c),c>>>=4,l-=4,i.nlen>286||i.ndist>30){e.msg="too many length or distance symbols",i.mode=BAD;break}i.have=0,i.mode=LENLENS;case LENLENS:for(;i.have<i.ncode;){for(;l<3;){if(0===a)break e;a--,c+=r[s++]<<l,l+=8}i.lens[k[i.have++]]=7&c,c>>>=3,l-=3}for(;i.have<19;)i.lens[k[i.have++]]=0;if(i.lencode=i.lendyn,i.lenbits=7,y={bits:i.lenbits},b=inflate_table2(CODES,i.lens,0,19,i.lencode,0,i.work,y),i.lenbits=y.bits,b){e.msg="invalid code lengths set",i.mode=BAD;break}i.have=0,i.mode=CODELENS;case CODELENS:for(;i.have<i.nlen+i.ndist;){for(;g=(C=i.lencode[c&(1<<i.lenbits)-1])>>>16&255,v=65535&C,!((S=C>>>24)<=l);){if(0===a)break e;a--,c+=r[s++]<<l,l+=8}if(v<16)c>>>=S,l-=S,i.lens[i.have++]=v;else{if(16===v){for(I=S+2;l<I;){if(0===a)break e;a--,c+=r[s++]<<l,l+=8}if(c>>>=S,l-=S,0===i.have){e.msg="invalid bit length repeat",i.mode=BAD;break}R=i.lens[i.have-1],h=3+(3&c),c>>>=2,l-=2}else if(17===v){for(I=S+3;l<I;){if(0===a)break e;a--,c+=r[s++]<<l,l+=8}l-=S,R=0,h=3+(7&(c>>>=S)),c>>>=3,l-=3}else{for(I=S+7;l<I;){if(0===a)break e;a--,c+=r[s++]<<l,l+=8}l-=S,R=0,h=11+(127&(c>>>=S)),c>>>=7,l-=7}if(i.have+h>i.nlen+i.ndist){e.msg="invalid bit length repeat",i.mode=BAD;break}for(;h--;)i.lens[i.have++]=R}}if(i.mode===BAD)break;if(0===i.lens[256]){e.msg="invalid code -- missing end-of-block",i.mode=BAD;break}if(i.lenbits=9,y={bits:i.lenbits},b=inflate_table2(LENS,i.lens,0,i.nlen,i.lencode,0,i.work,y),i.lenbits=y.bits,b){e.msg="invalid literal/lengths set",i.mode=BAD;break}if(i.distbits=6,i.distcode=i.distdyn,y={bits:i.distbits},b=inflate_table2(DISTS,i.lens,i.nlen,i.ndist,i.distcode,0,i.work,y),i.distbits=y.bits,b){e.msg="invalid distances set",i.mode=BAD;break}if(i.mode=LEN_,t===Z_TREES)break e;case LEN_:i.mode=LEN;case LEN:if(a>=6&&d>=258){e.next_out=n,e.avail_out=d,e.next_in=s,e.avail_in=a,i.hold=c,i.bits=l,inflate_fast2(e,_),n=e.next_out,o=e.output,d=e.avail_out,s=e.next_in,r=e.input,a=e.avail_in,c=i.hold,l=i.bits,i.mode===TYPE&&(i.back=-1);break}for(i.back=0;g=(C=i.lencode[c&(1<<i.lenbits)-1])>>>16&255,v=65535&C,!((S=C>>>24)<=l);){if(0===a)break e;a--,c+=r[s++]<<l,l+=8}if(g&&!(240&g)){for(f=S,E=g,T=v;g=(C=i.lencode[T+((c&(1<<f+E)-1)>>f)])>>>16&255,v=65535&C,!(f+(S=C>>>24)<=l);){if(0===a)break e;a--,c+=r[s++]<<l,l+=8}c>>>=f,l-=f,i.back+=f}if(c>>>=S,l-=S,i.back+=S,i.length=v,0===g){i.mode=LIT;break}if(32&g){i.back=-1,i.mode=TYPE;break}if(64&g){e.msg="invalid literal/length code",i.mode=BAD;break}i.extra=15&g,i.mode=LENEXT;case LENEXT:if(i.extra){for(I=i.extra;l<I;){if(0===a)break e;a--,c+=r[s++]<<l,l+=8}i.length+=c&(1<<i.extra)-1,c>>>=i.extra,l-=i.extra,i.back+=i.extra}i.was=i.length,i.mode=DIST;case DIST:for(;g=(C=i.distcode[c&(1<<i.distbits)-1])>>>16&255,v=65535&C,!((S=C>>>24)<=l);){if(0===a)break e;a--,c+=r[s++]<<l,l+=8}if(!(240&g)){for(f=S,E=g,T=v;g=(C=i.distcode[T+((c&(1<<f+E)-1)>>f)])>>>16&255,v=65535&C,!(f+(S=C>>>24)<=l);){if(0===a)break e;a--,c+=r[s++]<<l,l+=8}c>>>=f,l-=f,i.back+=f}if(c>>>=S,l-=S,i.back+=S,64&g){e.msg="invalid distance code",i.mode=BAD;break}i.offset=v,i.extra=15&g,i.mode=DISTEXT;case DISTEXT:if(i.extra){for(I=i.extra;l<I;){if(0===a)break e;a--,c+=r[s++]<<l,l+=8}i.offset+=c&(1<<i.extra)-1,c>>>=i.extra,l-=i.extra,i.back+=i.extra}if(i.offset>i.dmax){e.msg="invalid distance too far back",i.mode=BAD;break}i.mode=MATCH;case MATCH:if(0===d)break e;if(h=_-d,i.offset>h){if((h=i.offset-h)>i.whave&&i.sane){e.msg="invalid distance too far back",i.mode=BAD;break}h>i.wnext?(h-=i.wnext,p=i.wsize-h):p=i.wnext-h,h>i.length&&(h=i.length),m=i.window}else m=o,p=n-i.offset,h=i.length;h>d&&(h=d),d-=h,i.length-=h;do{o[n++]=m[p++]}while(--h);0===i.length&&(i.mode=LEN);break;case LIT:if(0===d)break e;o[n++]=i.length,d--,i.mode=LEN;break;case CHECK:if(i.wrap){for(;l<32;){if(0===a)break e;a--,c|=r[s++]<<l,l+=8}if(_-=d,e.total_out+=_,i.total+=_,_&&(e.adler=i.check=i.flags?crc32(i.check,o,_,n-_):adler32(i.check,o,_,n-_)),_=d,(i.flags?c:zswap32(c))!==i.check){e.msg="incorrect data check",i.mode=BAD;break}c=0,l=0}i.mode=LENGTH;case LENGTH:if(i.wrap&&i.flags){for(;l<32;){if(0===a)break e;a--,c+=r[s++]<<l,l+=8}if(c!==(4294967295&i.total)){e.msg="incorrect length check",i.mode=BAD;break}c=0,l=0}i.mode=DONE;case DONE:b=Z_STREAM_END;break e;case BAD:b=Z_DATA_ERROR;break e;case MEM:return Z_MEM_ERROR;default:return Z_STREAM_ERROR}return e.next_out=n,e.avail_out=d,e.next_in=s,e.avail_in=a,i.hold=c,i.bits=l,(i.wsize||_!==e.avail_out&&i.mode<BAD&&(i.mode<CHECK||t!==Z_FINISH))&&updatewindow(e,e.output,e.next_out,_-e.avail_out),u-=e.avail_in,_-=e.avail_out,e.total_in+=u,e.total_out+=_,i.total+=_,i.wrap&&_&&(e.adler=i.check=i.flags?crc32(i.check,o,_,e.next_out-_):adler32(i.check,o,_,e.next_out-_)),e.data_type=i.bits+(i.last?64:0)+(i.mode===TYPE?128:0)+(i.mode===LEN_||i.mode===COPY_?256:0),(0===u&&0===_||t===Z_FINISH)&&b===Z_OK&&(b=Z_BUF_ERROR),b}function inflateEnd(e){if(!e||!e.state)return Z_STREAM_ERROR;var t=e.state;return t.window&&(t.window=null),e.state=null,Z_OK}function inflateGetHeader(e,t){var i;return e&&e.state&&2&(i=e.state).wrap?(i.head=t,t.done=!1,Z_OK):Z_STREAM_ERROR}function inflateSetDictionary(e,t){var i,r=t.length;return e&&e.state?0!==(i=e.state).wrap&&i.mode!==DICT?Z_STREAM_ERROR:i.mode===DICT&&adler32(1,t,r,0)!==i.check?Z_DATA_ERROR:updatewindow(e,t,r,r)?(i.mode=MEM,Z_MEM_ERROR):(i.havedict=1,Z_OK):Z_STREAM_ERROR}inflate$3.inflateReset=inflateReset,inflate$3.inflateReset2=inflateReset2,inflate$3.inflateResetKeep=inflateResetKeep,inflate$3.inflateInit=inflateInit,inflate$3.inflateInit2=inflateInit2,inflate$3.inflate=inflate$2,inflate$3.inflateEnd=inflateEnd,inflate$3.inflateGetHeader=inflateGetHeader,inflate$3.inflateSetDictionary=inflateSetDictionary,inflate$3.inflateInfo="pako inflate (from Nodeca project)";var constants$1={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8};function GZheader$1(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}var gzheader=GZheader$1,zlib_inflate=inflate$3,utils=common,strings=strings$2,c=constants$1,msg=messages,ZStream=zstream,GZheader=gzheader,toString=Object.prototype.toString;function Inflate(e){if(!(this instanceof Inflate))return new Inflate(e);this.options=utils.assign({chunkSize:16384,windowBits:0,to:""},e||{});var t=this.options;t.raw&&t.windowBits>=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(t.windowBits>=0&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&(15&t.windowBits||(t.windowBits|=15)),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new ZStream,this.strm.avail_out=0;var i=zlib_inflate.inflateInit2(this.strm,t.windowBits);if(i!==c.Z_OK)throw new Error(msg[i]);if(this.header=new GZheader,zlib_inflate.inflateGetHeader(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=strings.string2buf(t.dictionary):"[object ArrayBuffer]"===toString.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(i=zlib_inflate.inflateSetDictionary(this.strm,t.dictionary))!==c.Z_OK))throw new Error(msg[i])}function inflate$1(e,t){var i=new Inflate(t);if(i.push(e,!0),i.err)throw i.msg||msg[i.err];return i.result}function inflateRaw(e,t){return(t=t||{}).raw=!0,inflate$1(e,t)}Inflate.prototype.push=function(e,t){var i,r,o,s,n,a=this.strm,d=this.options.chunkSize,l=this.options.dictionary,u=!1;if(this.ended)return!1;r=t===~~t?t:!0===t?c.Z_FINISH:c.Z_NO_FLUSH,"string"==typeof e?a.input=strings.binstring2buf(e):"[object ArrayBuffer]"===toString.call(e)?a.input=new Uint8Array(e):a.input=e,a.next_in=0,a.avail_in=a.input.length;do{if(0===a.avail_out&&(a.output=new utils.Buf8(d),a.next_out=0,a.avail_out=d),(i=zlib_inflate.inflate(a,c.Z_NO_FLUSH))===c.Z_NEED_DICT&&l&&(i=zlib_inflate.inflateSetDictionary(this.strm,l)),i===c.Z_BUF_ERROR&&!0===u&&(i=c.Z_OK,u=!1),i!==c.Z_STREAM_END&&i!==c.Z_OK)return this.onEnd(i),this.ended=!0,!1;a.next_out&&(0!==a.avail_out&&i!==c.Z_STREAM_END&&(0!==a.avail_in||r!==c.Z_FINISH&&r!==c.Z_SYNC_FLUSH)||("string"===this.options.to?(o=strings.utf8border(a.output,a.next_out),s=a.next_out-o,n=strings.buf2string(a.output,o),a.next_out=s,a.avail_out=d-s,s&&utils.arraySet(a.output,a.output,o,s,0),this.onData(n)):this.onData(utils.shrinkBuf(a.output,a.next_out)))),0===a.avail_in&&0===a.avail_out&&(u=!0)}while((a.avail_in>0||0===a.avail_out)&&i!==c.Z_STREAM_END);return i===c.Z_STREAM_END&&(r=c.Z_FINISH),r===c.Z_FINISH?(i=zlib_inflate.inflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===c.Z_OK):r!==c.Z_SYNC_FLUSH||(this.onEnd(c.Z_OK),a.avail_out=0,!0)},Inflate.prototype.onData=function(e){this.chunks.push(e)},Inflate.prototype.onEnd=function(e){e===c.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=utils.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},inflate$4.Inflate=Inflate,inflate$4.inflate=inflate$1,inflate$4.inflateRaw=inflateRaw,inflate$4.ungzip=inflate$1;var assign=common.assign,deflate=deflate$4,inflate=inflate$4,constants=constants$1,pako={};assign(pako,deflate,inflate,constants);var pako_1=pako,pako$1=getDefaultExportFromCjs(pako_1);let lockId$1=1,PromiseLock$1=class{constructor(e){__publicField(this,"lockingPromise",Promise.resolve()),__publicField(this,"locks",0),__publicField(this,"name",""),__publicField(this,"lockId"),this.lockId=lockId$1++,e&&(this.name=e)}get isLocked(){return this.locks>0}lock(){let e;this.locks+=1;const t=new Promise((t=>{e=()=>{this.locks-=1,t()}})),i=this.lockingPromise.then((()=>e));return this.lockingPromise=this.lockingPromise.then((()=>t)),i}};const DB_NAME="VERTC",indexedDB$1=()=>window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB,_IndexedDBInterface=class{constructor(e){__publicField(this,"storeName"),__publicField(this,"pendingList",[]),this.storeName=e,!isSSR$1()&&indexedDB$1()&&this._checkAndCreateStore(e)}async _checkAndCreateStore(e,t){const i=await _IndexedDBInterface._promiseLock.lock();if(indexedDB$1().databases){let e;await new Promise((t=>{const i=()=>indexedDB$1().databases().finally(t);e=setInterval(i,100),i()})).finally((()=>clearInterval(e)))}return new Promise((r=>{_IndexedDBInterface.db&&(_IndexedDBInterface.db.close(),delete _IndexedDBInterface.db);const o=t?indexedDB$1().open(DB_NAME,t):indexedDB$1().open(DB_NAME);o.onupgradeneeded=()=>{o.result.createObjectStore(e)},o.onerror=()=>{console.error("IndexedDBInterface error",o.error)},o.onsuccess=()=>{const t=o.result;_IndexedDBInterface.db=t;try{_IndexedDBInterface.db.transaction(this.storeName,"readonly"),this.pendingList.forEach((async({txMode:e,pendResolve:t,pendReject:i})=>{try{t(await this._getStore(e))}catch(e){i()}})),r()}catch{r(this._checkAndCreateStore(e,t.version+1))}finally{i()}}}))}async _getStore(e){const t=await _IndexedDBInterface._promiseLock.lock();return new Promise(((i,r)=>{if(!_IndexedDBInterface.db)return this.pendingList.push({txMode:e,pendResolve:i,pendReject:r}),void t();try{i(_IndexedDBInterface.db.transaction(this.storeName,e).objectStore(this.storeName))}catch(t){return void this.pendingList.push({txMode:e,pendResolve:i,pendReject:r})}finally{t()}}))}async put2String(e,t){let i;try{i=JSON.stringify(e)}catch{i=e}return await this.put(i,t)}async get4String(e){const t=await this.get(e);let i;try{i=JSON.parse(t)}catch{i=t}return i}async put(e,t){const i=await this._getStore("readwrite");return new Promise(((r,o)=>{const s=i.put(e,t);s.onsuccess=()=>{r()},s.onerror=e=>{o(e)}}))}async get(e){const t=await this._getStore("readonly");return new Promise(((i,r)=>{const o=t.get(e);o.onsuccess=()=>{i(o.result)},o.onerror=e=>{r(e)}}))}async del(e){const t=await this._getStore("readwrite");return new Promise(((i,r)=>{const o=t.delete(e);o.onsuccess=()=>{i()},o.onerror=e=>{r(e)}}))}};let IndexedDBInterface=_IndexedDBInterface;function isOutBufferItem(e){return void 0!==e.report_id}__publicField(IndexedDBInterface,"db"),__publicField(IndexedDBInterface,"state","init"),__publicField(IndexedDBInterface,"_promiseLock",new PromiseLock$1("iDB"));class LongStringReportor{constructor(){__publicField(this,"name","LongStringReportor"),__publicField(this,"inBuffer",[]),__publicField(this,"outBuffer",[])}push(e){e.message&&this.inBuffer.push({...e,message:{id:genUuid$1().slice(0,3),index:0,end:!0,msg:e.message}})}splice(e){const t=[];let i=0;for(;this.outBuffer.length;){const r=JSON.stringify(this.outBuffer[0]).length;if(!(r<e))break;e-=r,i+=r,t.push(this.outBuffer.shift())}for(;this.inBuffer[0]&&e>0;){const{message:r,...o}=this.inBuffer[0],s={...o,message:{...r,msg:""}},n=JSON.stringify(s).length,a=e-n,d={...s};if(a>r.msg.length)d.message.msg=r.msg,this.inBuffer.shift();else{if(!(a>=10))break;{const e=r.msg.slice(0,a);d.message.msg=e,d.message.end=!1,this.inBuffer[0].message.msg=r.msg.slice(a),this.inBuffer[0].message.index++}}const c=JSON.stringify(d.message),l=c.length;e-=l+n,i+=l+n,t.push({...d,message:c})}return{payload:t,payloadSize:i}}unshift(e){this.outBuffer=e.concat(this.outBuffer)}get(){return[...this.outBuffer,...this.inBuffer.map((e=>({...e,message:JSON.stringify(e.message)})))]}set(e){e.forEach((e=>{isOutBufferItem(e)?this.outBuffer.push(e):(e.message||(e.message=""),this.inBuffer.push({...e,message:JSON.parse(e.message)}))})),this.outBuffer=[].concat(this.outBuffer),this.inBuffer=[].concat(this.inBuffer)}isEmpty(){return 0===this.inBuffer.length&&0===this.outBuffer.length}}var longStringReportor=new LongStringReportor;const HARDCODE_UPLOAD_MAX_LIMIT=5e5,HARDCODE_UPLOAD_MIN_LIMIT=5e4,DEFAULT_UPLOAD_LIMIT=5e5,HTTP_REQUEST_TIMEOUT=1e4,REPORT_INTERVAL=2e3,defaultCommonStats={product_line:"rtc",report_version:"5",os:"web",user_agent:isSSR$1()?"":null==navigator?void 0:navigator.userAgent,platform:"web",product:"webrtc",app_state:"active"},REPORT_DB_BUFFER_STORE="LogReportor",DEBUG$1="undefined"!=typeof window&&(window.location.search.includes("_rtc_debug_")||(null==(_a=window.localStorage)?void 0:_a.getItem("_rtc_debug_")));class ReportorDBBuffer{constructor(e){__publicField(this,"_buffer"),this._buffer=new IndexedDBInterface(e)}async set(e,t){await this._buffer.put2String(e,t)}async get(e){let t=[];try{t=await this._buffer.get4String(e)}catch(e){}return t??[]}}class Reportor{constructor(){__publicField(this,"reportCommon",defaultCommonStats),__publicField(this,"reportIds",new Map),__publicField(this,"dataBuffer",[]),__publicField(this,"reportorList",[]),__publicField(this,"dbBuffer"),__publicField(this,"posting",!1),__publicField(this,"sucSendTimer"),__publicField(this,"preSucTime",0),__publicField(this,"errSendTimer"),__publicField(this,"errSendDelay",100),__publicField(this,"_logServerUrl"),__publicField(this,"_retryCount",0),__publicField(this,"_reportLimit",5e5),__publicField(this,"_disableTimeout",!1),isSSR$1()||(window.addEventListener("beforeunload",(()=>{clearTimeout(this.errSendTimer),clearTimeout(this.sucSendTimer),this.send(void 0,!0)})),document.addEventListener("visibilitychange",(()=>{"visible"===document.visibilityState?this.setCommonStats({app_state:"active"}):"hidden"===document.visibilityState&&this.setCommonStats({app_state:"background"})})),DEBUG$1&&(window.__rtc_debug_reportor__=this)),CoreConfig.on("UPLOAD_REPORT_LIMIT",(e=>{this.setReportLimit(e)})),CoreConfig.on("ENABLE_REPORT_IDB_BUFFER",(e=>{e&&this.enableIndexedDBBuffer()})),setTimeout((()=>{this.reportorList.push(consoleReportor),this.reportorList.push(longStringReportor)}))}setUrl(e){this._logServerUrl=e}setCommonStats(e){this.reportCommon=Object.assign(this.reportCommon,e)}getCommonStats(){return this.reportCommon}setReportLimit(e){this._reportLimit=Math.max(e,5e4),this._reportLimit=Math.min(e,5e5)}getReportId(e){e=e??"__global__",this.reportIds.has(e)||this.reportIds.set(e,0);let t=this.reportIds.get(e);return void 0===t&&(reportGlobalError(`no reportId in reportId map with engine-session-id ${e}`,0,{}),t=0),this.reportIds.set(e,t+1),t}push(e,t=!1){if(t)this.send(e);else{const t=e.engine_session_id??"__global__";this.reportIds.has(t)||this.reportIds.set(t,0),this.dataBuffer.push(e),!this.posting&&!this.errSendTimer&&Date.now()-this.preSucTime>2e3&&(clearTimeout(this.sucSendTimer),this.send())}}enableIndexedDBBuffer(){this.dbBuffer||(this.dbBuffer=new ReportorDBBuffer("ReportorDBBuffer"),this.dbBuffer.get("LogReportor").then((e=>{e.forEach((e=>{this.push(e)}))})),this.reportorList.forEach((e=>{var t;null==(t=this.dbBuffer)||t.get(e.name).then((t=>{e.set(t)}))})))}backup(){var e;try{null==(e=this.dbBuffer)||e.set([...this.dataBuffer],"LogReportor"),this.reportorList.forEach((e=>{var t;null==(t=this.dbBuffer)||t.set([...e.get()],e.name)}))}catch(e){reportGlobalError("Error when save log into IDB",-1,e)}}unshift(e){this.dataBuffer=e[0].concat(this.dataBuffer),this.reportorList.forEach(((t,i)=>{t.unshift(e[i+1]??[])}))}_splice(){let e=findSizeIndex$1(this.dataBuffer,this._reportLimit);0===e&&this.dataBuffer.length>0&&(this._reportLimit=JSON.stringify(this.dataBuffer[0]).length+10,e=1,reportGlobalError(`update report limit to ${this._reportLimit}`,0,null));const t=this.dataBuffer.splice(0,e),i=JSON.stringify(t).length,r=[t];let o=this._reportLimit-i;return this.reportorList.forEach((e=>{const{payload:t,payloadSize:i}=e.splice(o);t.forEach((e=>{var t;void 0===e.report_id&&(e.report_id=this.getReportId(e.engine_session_id),!isSSR$1()&&window.__onRTCReport&&(null==(t=window.__onRTCReport)||t.call(window,e.engine_session_id??"global",e,this.getCommonStats())))})),r.push(t),o-=i})),r}async send(e,t){this.backup();const i=this.reportorList.reduce(((e,t)=>e&&t.isEmpty()),!0);if(!e&&!this.dataBuffer.length&&i||!this._logServerUrl)return;e||(this.posting=!0);let r=[];e||(r=this._splice());const o=DEBUG$1,s={data:e||r.flat(),header:{...this.reportCommon,http_retry_count:this._retryCount},from:"web",os:"web",version:"1"},n={method:"POST",body:o?JSON.stringify(s):pako$1.gzip(JSON.stringify(s))};if(!this._disableTimeout)try{const e=new AbortController;n.signal=e.signal,setTimeout((()=>{e.abort()}),1e4)}catch{console.warn("AbortController is not supported"),this._disableTimeout=!0}o||(n.headers={"Content-Encoding":"gzip","Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"});let a,d,c=null;try{a=await fetch(this._logServerUrl,n),200!==a.status&&304!==a.status||(c=JSON.parse(await a.text()))}catch(e){d=e}e||(this.posting=!1),c&&0===c.StatusCode?e||t||this.sucSend():(setTimeout((()=>{reportGlobalError(`reportor post error, resJSON:${null==c?void 0:c.toString()} err:${d}`,(null==a?void 0:a.status)??-1,d)}),0),e?this.send(e):(this.unshift(r),t?this.send():this.errSend()))}_getDataBufferTotalSize(){return this.dataBuffer.reduce(((e,t)=>e+JSON.stringify(t).length),0)}sucSend(){this.errSendDelay=100,this._retryCount=0,this.preSucTime=Date.now();const e=this._getDataBufferTotalSize()>1e6?1e3:2e3;this.sucSendTimer=setTimeout((()=>this.send()),e)}errSend(){this.errSendTimer=setTimeout((()=>{this.send(),delete this.errSendTimer}),this.errSendDelay),this.errSendDelay*=2,this._retryCount++}}function findSizeIndex$1(e,t){let i=0;for(let r=0;r<e.length;r++)if(i+=JSON.stringify(e[r]).length,i>t)return r;return e.length}var commonReportor=new Reportor;class Monitor{constructor(e){__publicField(this,"modifyIds",{pre_connection:!1}),this.id=e}report(e,t,i){var r;const o={event_key:e,rtc_timestamp:Date.now(),...this.modifyIds,...t,report_id:commonReportor.getReportId(this.modifyIds.engine_session_id)};"object"==typeof i&&Object.keys(i).length>0&&(o.common_extra_info=JSON.stringify(i)),Object.keys(o).forEach((e=>{void 0!==o[e]&&""!==o[e]||delete o[e]})),!isSSR$1()&&window.__onRTCReport&&(null==(r=window.__onRTCReport)||r.call(window,this.modifyIds.engine_session_id,o,commonReportor.getCommonStats())),"UT"!=={}.VITE_TEST&&commonReportor.push(o)}reportLog(e){const t={event_key:"rtc_invoke_status",sdk_api_name:"console_log",rtc_timestamp:Date.now(),...this.modifyIds,message:e};consoleReportor.push(t)}reportLongString(e,t){const i={event_key:"rtc_invoke_status",sdk_api_name:`sdk_long_string_${e}`,rtc_timestamp:Date.now(),...this.modifyIds,message:t};longStringReportor.push(i)}set(e){this.modifyIds=Object.assign(this.modifyIds,e)}destroy(){}}const RESET_DURATION=36e5,_MessageReportor=class{constructor(e){__publicField(this,"_preTime",Date.now()),__publicField(this,"_one2oneNum",0),__publicField(this,"_one2manyNum",0),__publicField(this,"_one2oneMsgCache",new Map),__publicField(this,"_one2manyMsgCache",new Map),__publicField(this,"roomId",""),__publicField(this,"userId",""),__publicField(this,"rtsSessionId",""),__publicField(this,"logger"),__publicField(this,"serverUrl","server"),this.id=e,this.logger=new Logger$1("MessageReportor",1)}needReport(e){return!!_MessageReportor.config&&(Date.now()-this._preTime>=36e5&&(this._preTime=Date.now(),this._one2oneNum=0,this._one2manyNum=0),"one2one"===e&&this._one2oneNum<_MessageReportor.config.max_one2one_fpt_per_hour&&Math.random()<=_MessageReportor.config.one2one_fpt_ratio/100||"one2many"===e&&this._one2manyNum<_MessageReportor.config.max_one2many_fpt_per_hour&&Math.random()<=_MessageReportor.config.one2many_fpt_ratio/100)}cacheP2PMsg(e){var t;this._one2oneMsgCache.set(e.msg_id,{config_version:(null==(t=_MessageReportor.config)?void 0:t.version)||"",...e})}updateP2PMsg(e,t){const i=this._one2oneMsgCache.get(e);i&&this._one2oneMsgCache.set(e,{...i,...t})}cacheCustomMsg(e){var t;this._one2manyMsgCache.set(e.msg_id,{config_version:(null==(t=_MessageReportor.config)?void 0:t.version)||"",...e})}updateOne2ManyMsg(e,t){const i=this._one2manyMsgCache.get(e);i&&this._one2manyMsgCache.set(e,{...i,...t})}reportP2PMsg(e){var t;const i=this._one2oneMsgCache.get(e);i&&(this.logger.info("reportP2PMsg",i.type,JSON.stringify(i)),null==(t=getMonitor(this.id))||t.report("rts_message",i))}reportOne2ManyMsg(e){var t;const i=this._one2manyMsgCache.get(e);i&&(this.logger.info("reportOne2ManyMsg",i.type,JSON.stringify(i)),null==(t=getMonitor(this.id))||t.report("rts_message",i))}reportMsgRecv(e){var t,i;e.config_version=(null==(t=_MessageReportor.config)?void 0:t.version)||"",this.logger.info("reportMsgRecv",e.type,JSON.stringify(e)),null==(i=getMonitor(this.id))||i.report("rts_message",e)}destroy(){this._one2manyNum=0,this._one2oneNum=0,this._one2manyMsgCache.clear(),this._one2oneMsgCache.clear(),this._preTime=Date.now(),this.roomId="",this.userId="",this.rtsSessionId=""}};let MessageReportor=_MessageReportor;__publicField(MessageReportor,"config");const _cache=new Map,setConfig=e=>{new Logger$1("MessageReportor",1).info("setConfig",`get config: ${JSON.stringify(e)}`),MessageReportor.config=e},createRTSMsgReportor=e=>{const t=_cache.get(e)||new MessageReportor(e);return _cache.set(e,t),t},destroyRTSMsgReportor=e=>{const t=_cache.get(e);t&&(t.destroy(),_cache.delete(e))},setServerUrl=(e,t)=>{const i=_cache.get(e);i&&(i.serverUrl=t)},setRoomId=(e,t)=>{const i=_cache.get(e);i&&(i.roomId=t||"")},setUserId=(e,t)=>{const i=_cache.get(e);i&&(i.userId=t||"")},setRtsSessionId=(e,t)=>{const i=_cache.get(e);i&&(i.rtsSessionId=t)},samplingP2PMsg=(e,t)=>{const i=_cache.get(e);if(null==i?void 0:i.needReport("one2one")){const e=t.to?"one2one":"one2server";t.enable_report=!0,t.report_msg_id=t.id,i.cacheP2PMsg({rts_session_id:i.rtsSessionId,msg_id:`${t.id}`,node_role:"src_sdk",from:t.from,to:t.to||i.serverUrl,msg_type:e,type:e,rts_room_id:t.room,req_ts:Date.now(),send_ts:Date.now(),ack_ts:Date.now(),msg_size:0,error_code:0,recv_msg_ts:0,fwd_msg_ts:0,reply_ack_ts:0,cur_dst_uid:""})}return t},updateP2PMsgReq=(e,t,i)=>{var r;t.enable_report&&assertValidMsgId(t.report_msg_id)&&(null==(r=_cache.get(e))||r.updateP2PMsg(`${t.report_msg_id}`,{send_ts:Date.now(),msg_size:i}))},updateP2PMsgAck=(e,t,i)=>{if(t.enable_report&&assertValidMsgId(t.report_msg_id)){const r=_cache.get(e);null==r||r.updateP2PMsg(`${t.report_msg_id}`,{ack_ts:Date.now(),error_code:i}),null==r||r.reportP2PMsg(`${t.report_msg_id}`)}},samplingOne2ManyMsg=(e,t,i)=>{const r=_cache.get(e);return(null==r?void 0:r.needReport("one2many"))&&(i.enable_report=!0,i.report_msg_id=t,r.cacheCustomMsg({rts_session_id:r.rtsSessionId,msg_id:`${t}`,node_role:"src_sdk",from:i.clientId,to:r.roomId||i.roomId,msg_type:"one2many",type:"one2many",rts_room_id:r.roomId,req_ts:Date.now(),send_ts:Date.now(),ack_ts:Date.now(),msg_size:0,error_code:0,recv_msg_ts:0,fwd_msg_ts:0,reply_ack_ts:0,cur_dst_uid:""})),i},updateOne2ManyMsgReq=(e,t,i)=>{if(t.enable_report&&assertValidMsgId(t.report_msg_id)){const r=_cache.get(e);r&&r.updateOne2ManyMsg(`${t.report_msg_id}`,{send_ts:Date.now(),msg_size:i})}},updateOne2ManyMsgAck=(e,t,i)=>{if(t.enable_report&&assertValidMsgId(t.report_msg_id)){const r=_cache.get(e);r&&(null==r||r.updateOne2ManyMsg(`${t.report_msg_id}`,{ack_ts:Date.now(),error_code:i}),null==r||r.reportOne2ManyMsg(`${t.report_msg_id}`))}},reportP2PMsgRecv=(e,t,i)=>{if(t.enable_report&&assertValidMsgId(t.report_msg_id)){const r=_cache.get(e),o=t.to?"one2one":"one2many";null==r||r.reportMsgRecv({rts_session_id:r.rtsSessionId,msg_id:`${t.report_msg_id}`,msg_size:i.msg_size,node_role:"dst_sdk",msg_type:o,type:o,rts_room_id:t.room,from:t.from,to:t.to||t.room,error_code:0,recv_msg_ts:i.recv_msg_ts,fwd_msg_ts:i.fwd_msg_ts,reply_ack_ts:Date.now(),cur_dst_uid:t.to?"":r.userId,config_version:"",req_ts:0,send_ts:0,ack_ts:0})}},reportOne2ManyMsgRecv=(e,t,i)=>{if(t.enable_report&&assertValidMsgId(t.report_msg_id)){const r=_cache.get(e);null==r||r.reportMsgRecv({rts_session_id:r.rtsSessionId,msg_id:`${t.report_msg_id}`,msg_size:i.msg_size,node_role:"dst_sdk",msg_type:"one2many",type:"one2many",rts_room_id:t.roomId,from:t.clientId,to:t.roomId,error_code:0,recv_msg_ts:i.recv_msg_ts,fwd_msg_ts:i.fwd_msg_ts,reply_ack_ts:Date.now(),cur_dst_uid:r.userId,config_version:"",req_ts:0,send_ts:0,ack_ts:0})}},RTSMsgReportor={_cache:_cache,setServerUrl:setServerUrl,setConfig:setConfig,setRtsSessionId:setRtsSessionId,createRTSMsgReportor:createRTSMsgReportor,destroyRTSMsgReportor:destroyRTSMsgReportor,setRoomId:setRoomId,setUserId:setUserId,samplingP2PMsg:samplingP2PMsg,updateP2PMsgReq:updateP2PMsgReq,updateP2PMsgAck:updateP2PMsgAck,samplingOne2ManyMsg:samplingOne2ManyMsg,reportP2PMsgRecv:reportP2PMsgRecv,updateOne2ManyMsgAck:updateOne2ManyMsgAck,updateOne2ManyMsgReq:updateOne2ManyMsgReq,reportOne2ManyMsgRecv:reportOne2ManyMsgRecv};class MessageStatisticsObserver{constructor(e){__publicField(this,"_timer"),__publicField(this,"userMessage",{}),__publicField(this,"roomMessage",{}),this.id=e,this._setTimer()}_setTimer(){const e=()=>{this._reportAndgReset(),clearTimeout(this._timer),this._timer=setTimeout(e,1e4)};e()}_reportAndgReset(){(Object.keys(this.userMessage).length||Object.keys(this.roomMessage).length)&&(this._report(),this._reset())}_report(){var e;null==(e=getMonitor(this.id))||e.report("rtc_message_statistics",{dc_user_message:Object.keys(this.userMessage).map((e=>this.userMessage[e])),dc_room_message:Object.keys(this.roomMessage).map((e=>this.roomMessage[e])),media_server_ip:""})}_reset(){this.userMessage={},this.roomMessage={}}_checkInitUserMessage(e,t){this.userMessage[`${t}-${e}`]||(this.userMessage[`${t}-${e}`]={dc_peer_user_id:e,dc_send_total:0,dc_recv_total:0,dc_send_ack:0,dc_send_fail:0,dc_fail_timeout:0,dc_fail_no_receiver:0,dc_fail_no_relay_path:0,dc_cost_time:0,dc_cost_e2s:0,dc_cost_s2s:0,dc_least_time:Number(1/0),dc_most_time:0,dc_cost_peer_s2e:0,dc_send_ack_100:0,dc_send_ack_200:0,dc_send_ack_400:0,dc_send_ack_1s:0,dc_message_type:t,dc_send_binary:0})}_sendUserMessage(e,t,i){this._checkInitUserMessage(e,t),this.userMessage[`${t}-${e}`].dc_send_total++,i&&this.userMessage[`${t}-${e}`].dc_send_binary++}_recvUserMessage(e,t){this._checkInitUserMessage(e,t),this.userMessage[`${t}-${e}`].dc_recv_total++}_sendUserFail(e,t,i){const r=this.userMessage[`${t}-${e}`];r&&(r.dc_send_fail++,this._handleUserFail(r,i))}_handleUserFail(e,t){t&&(t.code||t.err)&&(["TIME_OUT","USER_MESSAGE_TIMEOUT"].includes(t.code)?e.dc_fail_timeout++:3===t.err?e.dc_fail_no_receiver++:4===t.err?e.dc_fail_no_relay_path++:1===t.err&&e.dc_fail_timeout++)}_sendUserAck(e,t,i,r,o){const s=this.userMessage[`${t}-${e}`];s&&(s.dc_send_ack++,s.dc_cost_time+=i,s.dc_cost_s2s+=r||0,s.dc_cost_peer_s2e+=o,s.dc_cost_e2s+=i-(r||0)-o,i/2<=100?(s.dc_send_ack_100++,s.dc_send_ack_200++,s.dc_send_ack_400++,s.dc_send_ack_1s++):i/2<=200?(s.dc_send_ack_200++,s.dc_send_ack_400++,s.dc_send_ack_1s++):i/2<=400?(s.dc_send_ack_400++,s.dc_send_ack_1s++):i/2<=1e3&&s.dc_send_ack_1s++,i<s.dc_least_time&&(s.dc_least_time=i),i>s.dc_most_time&&(s.dc_most_time=i))}sendRoomMessage(e,t){this.roomMessage[e]||(this.roomMessage[e]={dc_room_id:e,dc_send_total:0,dc_send_ack:0,dc_cost_time:0,dc_least_time:Number(1/0),dc_most_time:0,dc_send_fail:0,dc_send_ack_100:0,dc_send_ack_200:0,dc_send_ack_400:0,dc_send_ack_1s:0,dc_send_binary:0}),this.roomMessage[e].dc_send_total++,t&&this.roomMessage[e].dc_send_binary++}sendRoomFail(e){const t=this.roomMessage[e];t&&t.dc_send_fail++}sendRoomAck(e,t){const i=this.roomMessage[e];i&&(i.dc_send_ack++,i.dc_cost_time+=t,t<i.dc_least_time&&(i.dc_least_time=t),t>i.dc_most_time&&(i.dc_most_time=t),t/2<=100?(i.dc_send_ack_100++,i.dc_send_ack_200++,i.dc_send_ack_400++,i.dc_send_ack_1s++):t/2<=200?(i.dc_send_ack_200++,i.dc_send_ack_400++,i.dc_send_ack_1s++):t/2<=400?(i.dc_send_ack_400++,i.dc_send_ack_1s++):t/2<=1e3&&i.dc_send_ack_1s++)}sendP2PMessage(e,t){this._sendUserMessage(e,"p2p",t)}recvP2PMessage(e){this._recvUserMessage(e,"p2p")}sendP2PFail(e,t){this._sendUserFail(e,"p2p",t)}sendP2PAck(e,t,i,r){this._sendUserAck(e,"p2p",t,i,r)}sendP2POutRoomMessage(e,t){this._sendUserMessage(e,"p2p_outside_room",t)}recvP2POutRoomMessage(e){this._recvUserMessage(e,"p2p_outside_room")}sendP2POutRoomFail(e,t){this._sendUserFail(e,"p2p_outside_room",t)}sendP2POutRoomAck(e,t,i,r){this._sendUserAck(e,"p2p_outside_room",t,i,r)}sendP2serverMessage(e){this._sendUserMessage("","p2server",e)}sendP2serverFail(e){this._sendUserFail("","p2server",e)}sendP2serveAck(e,t,i){this._sendUserAck("","p2server",e,t,i)}countP2PMessage(e,t,i,r,o){this.sendP2PMessage(t,i),e?this.sendP2PAck(t,Date.now()-r,o.s2s_time||0,o.s2e_time||0):this.sendP2PFail(t,o)}countRoomMessage(e,t,i,r){this.sendRoomMessage(t,i),e?this.sendRoomAck(t,Date.now()-r):this.sendRoomFail(t)}countUserMessageOutsideRoom(e,t,i,r,o){this.sendP2POutRoomMessage(t,i),e?this.sendP2POutRoomAck(t,Date.now()-r,o.s2s_time,o.s2e_time):this.sendP2POutRoomFail(t,o)}countServerMessage(e,t,i,r){this.sendP2serverMessage(t),e?(r=r||{},this.sendP2serveAck(Date.now()-i,r.s2s_time||0,r.s2e_time||0)):this.sendP2serverFail(r)}destroy(){this._reset(),clearTimeout(this._timer)}}const setGlobalStats=e=>{commonReportor.setCommonStats(e)},setReportUrl=e=>{commonReportor.setUrl(e)},globalMonitor=new Monitor("global"),reportGlobalApiCall=(e,t,i)=>{globalMonitor.report("rtc_sdk_api_call",{sdk_api_name:e,error_code:t,message:i})},reportGlobalCallback=(e,t,i)=>{globalMonitor.report("rtc_sdk_callback",{sdk_callback_name:e,error_code:t,message:i})},reportGlobalError=(e,t,i)=>{globalMonitor.report("rtc_error",{message:e,error_code:t},i)},reportGlobalInvokeStatus=(e,t,i=0,r="",o)=>{globalMonitor.report("rtc_invoke_status",{sdk_api_name:e,message:t,error_code:i,stream_id:r,elapse:0},o)};function reportGlobalLog(e){globalMonitor.reportLog(e)}const monitorMap=new Map,getMonitor=e=>monitorMap.get(e),createMonitor=(e,t)=>{const i=new Monitor(e);return i.set({...t,engine_session_id:genUuid$1()}),i.report("sdk_init_engine",{start:Date.now(),type:"begin"}),monitorMap.set(e,i),i},destroyMonitor=e=>{e.report("sdk_init_engine",{start:Date.now(),type:"end"}),monitorMap.delete(e.id)},apiReportCache=new Map;function reportRtcSdkApi(e=[],t={}){t=Object.assign({debounce:0},t);const{debounce:i,debounceTag:r}=t;function o(e,t,r,o){if(!i)return t(...r);{const s=`${o}_${e}`,n=apiReportCache.get(s);clearTimeout(n);const a=setTimeout((()=>{t(...r)}),i);apiReportCache.set(s,a)}}return function(t,i,s){if("function"==typeof s.value){const t=s.value;s.value=function(...s){var n,a;const d=this.engineId||this.id,c=genUuid$1(),l={};e.forEach(((e,t)=>{l[e]=s[t]})),"joinRoom"===i&&(null==(a=getMonitor(d))||a.set({room_id:s[1],user_id:null==(n=s[2])?void 0:n.userId}));let u,_="";if(r)try{_=r(...s)}catch{}o(i,reportRtcSdkApiCall,[d,i,s,l,{event_session_id:c}],`start_${_}`);try{u=t.apply(this,s)}catch(e){throw o(i,reportRtcSdkCallback,[d,i,e.message,e.code||-1,{event_session_id:c}],`end_${_}`),e}return"function"==typeof(null==u?void 0:u.then)?u.then((e=>(o(i,reportRtcSdkCallback,[d,i,[e??{}],0,{event_session_id:c}],`end_${_}`),e))).catch((e=>{throw o(i,reportRtcSdkCallback,[d,i,e.message,e.code,{event_session_id:c}],`end_${_}`),e})):(o(i,reportRtcSdkCallback,[d,i,[u??{}],0,{event_session_id:c}],`end_${_}`),u)}}}}const reportRtcSdkApiCall=(e,t,i,r,o={})=>{var s;const n={sdk_api_name:t,message:JSON.stringify(reportParamsCheck(i)),error_code:0,...o};null==(s=getMonitor(e))||s.report("rtc_sdk_api_call",n,r)},reportRtcSdkCallback=(e,t,i,r=0,o={})=>{var s;const n={sdk_callback_name:t,error_code:r,message:JSON.stringify(Array.isArray(i)?reportParamsCheck(i):i),...o};null==(s=getMonitor(e))||s.report("rtc_sdk_callback",n)},reportRtcInvokeStatus=(e,t,i,r=0,o="",s)=>{var n;null==(n=getMonitor(e))||n.report("rtc_invoke_status",{sdk_api_name:t,message:i,error_code:r,stream_id:o,elapse:0},s)},maxBinaryLength=10;function reportParamsCheck(e){const t=e=>{if(null==e?void 0:e._reportName)return e._reportName;if(e instanceof HTMLElement)return e.toString();if(e instanceof ArrayBuffer||ArrayBuffer.isView(e)){const t=ArrayBuffer.isView(e)?e.buffer:e,i=t.byteLength;let r=[];if(i>maxBinaryLength){const e=new DataView(t),o=Array.from({length:maxBinaryLength/2}).map(((t,i)=>e.getUint8(i))),s=Array.from({length:maxBinaryLength/2}).map(((e,t)=>i-1-t)).reverse().map((t=>e.getUint8(t)));r=[...o,"...",...s]}else r=Array.from(new Uint8Array(t));return`${e.constructor.name}(${i}) [${r.join(", ")}]`}if(e instanceof ImageData)return"ImageData";if(Array.isArray(e))return e.map(t);if(["[object Object]","[object MediaStreamTrack]"].includes(Object.prototype.toString.call(e))){const i={};for(const r in e)i[r]=t(e[r]);return i}return e instanceof Function?"[User Function]":e};return e.map(t)}const ENABLE_CONSOLE_UPLOAD="undefined"!=typeof window&&window.location.search.includes("_rtc_upload_console_");class ConsoleReportor{constructor(){__publicField(this,"name","ConsoleReportor"),__publicField(this,"_uuid",`${Math.floor(899*Math.random())+100}`),__publicField(this,"_consoleReportId",0),__publicField(this,"_engineReportIdMap",new Map),__publicField(this,"_enabled","NULL"),__publicField(this,"_consoleCutLength",CoreConfig.getParameter("UPLOAD_CONSOLE_LENGTH_CUT")),__publicField(this,"buffer",[]),ENABLE_CONSOLE_UPLOAD&&setTimeout((()=>{this.switchOn()}),0),CoreConfig.on("UPLOAD_CONSOLE_ON",(e=>{e?this.switchOn():this.turnOff()})),CoreConfig.on("UPLOAD_CONSOLE_LENGTH_CUT",(e=>{this._consoleCutLength=e}))}get enabled(){return"OFF"!==this._enabled}switchOn(){"NULL"===this._enabled&&(console.log("[LoggerReportor.constructor] console upload switch ON"),this._enabled="ON")}turnOff(){"NULL"===this._enabled&&(console.log("[LoggerReportor.constructor] console upload switch OFF"),this._enabled="OFF",this.buffer=[])}getEngineConsoleId(e){const t=this._engineReportIdMap.get(e)??0;return this._engineReportIdMap.set(e,t+1),t}report(e,t,i,r,o,s,n,a,d){if("OFF"===this._enabled)return;const c=getMonitor(t),l=this._consoleReportId++,u=this.getEngineConsoleId(t),_=shallowJson(d,this._consoleCutLength),h=[...d],p=`${a}`.replace(/%o|%s/gi,(()=>shallowJson([h.shift()],this._consoleCutLength))),m=`[${this._uuid}-${l}][${t}-${u}]-${i}-${e}[${r}]${o}[${s}.${n}] ${p} ${_}`;c?c.reportLog(m):reportGlobalLog(m)}push(e){"OFF"!==this._enabled&&this.buffer.push(e)}splice(e){if("ON"!==this._enabled)return{payload:[],payloadSize:0};const{index:t,size:i}=findSizeIndex(this.buffer,e);return{payload:this.buffer.splice(0,t),payloadSize:i}}unshift(e){this.buffer=e.concat(this.buffer)}get(){return this.buffer}set(e){this.buffer=e.concat(this.buffer)}isEmpty(){return"OFF"===this._enabled||0===this.buffer.length}}function shallowJson(e,t){return e.map((e=>{let i="";try{if("string"==typeof e)return e;if(void 0===e)return"undefined";if(null===e)return"null";if(e instanceof MediaStreamTrack)return mediaTrackStringify(e);if(e instanceof MediaStream)return mediaStreamStringify(e);if(e instanceof RTCRtpSender)return mediaSenderStringify(e);if(e instanceof RTCRtpReceiver)return mediaReceiverStringify(e);if(e instanceof RTCRtpTransceiver)return mediaTransceiverStringify(e);i=JSON.stringify(e)}catch(t){i=e.toString()}return i&&i.length>=t&&(i=i.slice(0,t)),i})).join(", ")}function findSizeIndex(e,t){let i=0;for(let r=0;r<e.length;r++){const o=JSON.stringify(e[r]).length;if(i+=o,i>t)return{index:r,size:i-o}}return{index:e.length,size:i}}var consoleReportor=new ConsoleReportor;const HEAD_TEXT="[VERTC]",baseColor="#0050b3",colorMap={DEBUG:"rgba(0, 0, 0, 0)"," INFO":"rgba(93, 173, 226, 0)"," WARN":"rgba(255, 119, 0, 0.3)",ERROR:"rgba(255, 0, 0, 0.3)"," SUCC":"rgba(0, 119, 0, 0.3)"},DEBUG="undefined"!=typeof window&&(window.location.search.includes("_rtc_debug_")||(null==(_b=window.localStorage)?void 0:_b.getItem("_rtc_debug_")));class Logger{constructor(e,t,i="global"){__publicField(this,"indent"),__publicField(this,"module"),__publicField(this,"_engineId"),this.module=e,this.indent=t,this._engineId=i}_print(e,t,...i){const r=i.shift();try{const e=[...i],o=`${r}`.replace(/%o/gi,(()=>{const t=e.shift();return JSON.stringify(t)}));iDB.set(`[VERTC][${this.module}.${t}] ${o} ${e.map((e=>JSON.stringify(e))).join(", ")}`)}catch(e){}let o="";for(let e=0;e<this.indent;e++)o+=" ";const s=getTimestamp();consoleReportor.report("[VERTC]",this._engineId,s,e,o,this.module,t,r,i),DEBUG&&console.log(`%c${s}-[VERTC]%c[${e}]%c${o}[${this.module}.${t}] ${r}`,"color:#0050b3;",`background-color:${colorMap[e]};`,"color:#0050b3;",...i)}print(e,...t){this._print(" INFO",e,...t)}debug(e,...t){this._print("DEBUG",e,...t)}info(e,...t){this._print(" INFO",e,...t)}warn(e,...t){this._print(" WARN",e,...t)}error(e,...t){this._print("ERROR",e,...t)}success(e,...t){this._print(" SUCC",e,...t)}}const getTimestamp=()=>{const e=new Date;return`${e.toTimeString().split(" ")[0]}:${e.getMilliseconds().toString().padStart(3,"0")}`};var Logger$1=Logger;const isSSR=()=>"undefined"==typeof window,userAgentString=isSSR()?"":window.navigator.userAgent;function getBrowser(){let e="none";return isSSR()||(null!==userAgentString.match("Firefox")?e="mozilla":null!==userAgentString.match("Chrome")?(e="chrome-stable",null!==userAgentString.match("Electron")&&(e="electron")):(null!==userAgentString.match("Safari")||null!==userAgentString.match("AppleWebKit"))&&(e="safari")),e}const isFirefox="mozilla"===getBrowser(),isSafari="safari"===getBrowser(),isChrome="chrome-stable"===getBrowser(),isCriOS=!isSSR()&&/CriOS/i.test(userAgentString),isEdgeForDesktop=!isSSR()&&/Edg\//i.test(userAgentString),isEdgeForAndroid=!isSSR()&&/EdgA/i.test(userAgentString),isEdgeForIOS=!isSSR()&&/EdgiOS/i.test(userAgentString),isEdge=isEdgeForDesktop||isEdgeForAndroid||isEdgeForIOS,isDingTalk=!isSSR()&&/DingTalk/i.test(navigator.userAgent),isOpera=!isSSR()&&/OPR\//.test(navigator.userAgent),isIPad=!isSSR()&&(!!/(iPad)/i.exec(userAgentString)||/Macintosh/i.test(userAgentString)&&"ontouchend"in document),isMac=!isSSR()&&/Macintosh/i.test(userAgentString),isWeChat=!isSSR()&&/MicroMessenger/i.test(userAgentString),isMobile=!isSSR()&&userAgentString.toLowerCase().includes("mobile"),isIOS=!isSSR()&&!!/(iPhone|iPad|iPod)/i.exec(userAgentString),isAndroid=!isSSR()&&/Android/i.test(userAgentString),isWindows=!isSSR()&&/Windows/i.test(userAgentString),isOpenHarmony=!isSSR()&&/OpenHarmony/i.test(userAgentString);let sv=0,sv2="0";const v=!isSSR()&&(null==(_c=userAgentString.match(/version\/(\d+)/i))?void 0:_c[1]);isSafari&&v&&(sv=Number(v),sv2=null==(_d=navigator.userAgent.match(/version\/(\d+\.\d+)/i))?void 0:_d[1]);const v2=!isSSR()&&(null==(_e=userAgentString.match(/Firefox\/(\d+)/i))?void 0:_e[1]);isFirefox&&v2&&(sv=Number(v2));const safariVersion=sv,firefoxVersion=sv,safariMinorVersion=sv2,iOSVersion=(!isSSR()&&(null==(_g=null==(_f=userAgentString.match(/ ([\d_]+) like Mac OS X/i))?void 0:_f[1])?void 0:_g.split("_").map((e=>parseInt(e)))))??[];let cv=0;const cvs=!isSSR()&&(null==(_h=userAgentString.match(/Chrome\/(\d+)/i))?void 0:_h[1]);cvs&&(cv=Number(cvs));const chromeVersion=cv,PLATFORM_KEY="VolcEngine",RTC_DEVICE_ID="RTC_DEVICE_ID",RTC_ACCESS_NODE="RTC_ACCESS_NODE",RTC_ACCESS_URLS="RTC_ACCESS_URLS",ENGINE_WEB_CONFIG="ENGINE_WEB_CONFIG",SERVER_CONFIG="SERVER_CONFIG";class Cache{get(e){const t=localStorage.getItem(e);if(!t)return null;try{const i=JSON.parse(t);return i.ttl>0&&Date.now()-i.saveTime>i.ttl?(this.delete(e),null):i.message}catch(e){return null}}set(e,t,i=-1){const r={ttl:i,saveTime:Date.now(),message:t};try{return localStorage.setItem(e,JSON.stringify(r)),!0}catch(e){return!1}}getTtl(e){const t=localStorage.getItem(e);if(!t)return null;try{return JSON.parse(t).ttl}catch(e){return null}}delete(e){try{return localStorage.removeItem(e),!0}catch(e){return!1}}}class SDKCache extends Cache{constructor(){super(...arguments),__publicField(this,"_accessVersion","v2")}getDeviceId(){if(isSSR())return"";let e=this.get(RTC_DEVICE_ID);return e&&!/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(e)||(e=randomNum(16)),this.setDeviceId(e),e}setDeviceId(e){return setGlobalStats({device_id:e}),this.set(RTC_DEVICE_ID,e),e}getAccessKey(e){return`${RTC_ACCESS_NODE}_${e}-${PLATFORM_KEY}-${this._accessVersion}`}getAccessNode(e){return this.get(this.getAccessKey(e))}setAccessNode(e,t,i){return this.set(this.getAccessKey(e),t,1e3*i)}deleteAccessNode(e,t){let i=this.getAccessNode(e);const r=this.getTtl(this.getAccessKey(e));Array.isArray(i)&&i.length>0&&(i=i.filter((e=>e.mediaID!==t.mediaID&&e.msgKey!==t.msgKey)),i.length>0?this.setAccessNode(e,i,r||0):this.clearAccessNode(e))}clearAccessNode(e){if(e)this.delete(this.getAccessKey(e));else for(const e in localStorage)e.startsWith(RTC_ACCESS_NODE)&&localStorage.removeItem(e)}getAccessUrls(){return this.get(`${RTC_ACCESS_URLS}-${PLATFORM_KEY}`)}setAccessUrls(e){const t=e.map((({host:e,path:t})=>`https://${e}${t}`));return this.set(`${RTC_ACCESS_URLS}-${PLATFORM_KEY}`,t)}clearAccessUrls(){this.delete(`${RTC_ACCESS_URLS}-${PLATFORM_KEY}`)}getEngineWebConfig(e,t){var i;const r=`${e}_${t}_${this.getDeviceId()}`,o=this.get(ENGINE_WEB_CONFIG),s=(null==(i=null==o?void 0:o.find((e=>e.key===r)))?void 0:i.config)||{};return Object.assign({},getParameter("ENGINE_WEB_CONFIG"),s)}setEngineWebConfig(e,t,i){if(!i)return;const r=`${e}_${t}_${this.getDeviceId()}`;let o=this.get(ENGINE_WEB_CONFIG)||[];return o=o.filter((e=>e.key!==r)),o.push({key:r,config:i}),this.set(ENGINE_WEB_CONFIG,o.slice(-5))}getServerConfig(e){var t;const i=`${e}`,r=this.get(SERVER_CONFIG);return(null==(t=null==r?void 0:r.find((e=>e.key===i)))?void 0:t.config)||{}}setServerConfig(e,t){if(!t)return;const i=`${e}`;let r=this.get(SERVER_CONFIG)||[];return r=r.filter((e=>e.key!==i)),r.push({key:i,config:t}),this.set(SERVER_CONFIG,r.slice(-5))}}var sdkCache=new SDKCache;const logger$b=new Logger$1("JoinRoomConfig",0),_JoinRoomConfig=class{constructor(e){__publicField(this,"_useTcpAfterJoinTimeout",_JoinRoomConfig.DEFAULT_CONF.useTcpAfterJoinTimeout),__publicField(this,"_joinWithTcpOnly",_JoinRoomConfig.DEFAULT_CONF.joinWithTcpOnly),__publicField(this,"_joinWithTcpOnlyDelay",_JoinRoomConfig.DEFAULT_CONF.joinWithTcpOnlyDelay),__publicField(this,"_blackBrowserRegexList",[]),this._engineId=e,location.search.indexOf("__rtc_tcp_only__")>-1&&(this._joinWithTcpOnly=!0,this._joinWithTcpOnlyDelay=0),this._report()}static setDefaulConf({useTcpAfterJoinTimeout:e,joinWithTcpOnly:t,joinWithTcpOnlyDelay:i}){return"boolean"==typeof e&&(_JoinRoomConfig.DEFAULT_CONF.useTcpAfterJoinTimeout=e),"boolean"==typeof t&&(_JoinRoomConfig.DEFAULT_CONF.joinWithTcpOnly=t),"number"==typeof i&&(_JoinRoomConfig.DEFAULT_CONF.joinWithTcpOnlyDelay=Math.max(0,i)),_JoinRoomConfig.DEFAULT_CONF}get useTcpAfterJoinTimeout(){return this._useTcpAfterJoinTimeout}get useTcpJoin(){return this._joinWithTcpOnly}get useTcpJoinDelay(){return this._joinWithTcpOnlyDelay}isBlackBrower(){return this._blackBrowserRegexList.find((e=>new RegExp(e).test(navigator.userAgent)))}setServerConfig(e){var t,i,r;let o=!1;"boolean"==typeof(null==(t=null==e?void 0:e.use_tcp_after_join_timeout)?void 0:t.enable)&&(this._useTcpAfterJoinTimeout=e.use_tcp_after_join_timeout.enable,o=!0),"boolean"==typeof(null==(i=null==e?void 0:e.join_with_tcp_only)?void 0:i.enable)&&(this._joinWithTcpOnly=e.join_with_tcp_only.enable,o=!0),"number"==typeof(null==(r=null==e?void 0:e.join_with_tcp_only)?void 0:r.delay_ms)&&(this._joinWithTcpOnlyDelay=e.join_with_tcp_only.delay_ms,o=!0),e&&Array.isArray(e.black_browser_regex_list)&&(this._blackBrowserRegexList=e.black_browser_regex_list,o=!0),o&&this._report()}toString(){return JSON.stringify({use_tcp_after_join_timeout:this._useTcpAfterJoinTimeout,join_with_tcp_only:this._joinWithTcpOnly,join_with_tcp_only_delay:this._joinWithTcpOnlyDelay,black_browser_regex_list:this._blackBrowserRegexList})}_report(){logger$b.print("_report",this.toString()),reportRtcInvokeStatus(this._engineId,"web_join_room_config",this.toString())}};let JoinRoomConfig=_JoinRoomConfig;__publicField(JoinRoomConfig,"DEFAULT_CONF",{useTcpAfterJoinTimeout:!0,joinWithTcpOnly:!1,joinWithTcpOnlyDelay:5e3});var ErrorCode=(e=>(e.INVALID_ENGINE="INVALID_ENGINE",e.INVALID_PARAMS="INVALID_PARAMS",e.INVOKED_BEFORE_JOIN_ROOM="INVOKED_BEFORE_JOIN_ROOM",e.INVALID_TOKEN="INVALID_TOKEN",e.JOIN_ROOM_FAILED="JOIN_ROOM_FAILED",e.UPDATE_TOKEN_WITH_INVALID_TOKEN="UPDATE_TOKEN_WITH_INVALID_TOKEN",e.UPDATE_TOKEN_BEFORE_JOIN="UPDATE_TOKEN_BEFORE_JOIN",e.REPEAT_JOIN="REPEAT_JOIN",e.REPEAT_PUBLISH="REPEAT_PUBLISH",e.REPEAT_PUSH="REPEAT_PUSH",e.REPEAT_PLAY="REPEAT_PLAY",e.PUBLISH_BEFORE_JOIN="PUBLISH_BEFORE_JOIN",e.UNPUBLISH_BEFORE_JOIN="UNPUBLISH_BEFORE_JOIN",e.SUBSCRIBE_BEFORE_JOIN="SUBSCRIBE_BEFORE_JOIN",e.UNSUBSCRIBE_BEFORE_JOIN="UNSUBSCRIBE_BEFORE_JOIN",e.NO_PUBLISH_PERMISSION="NO_PUBLISH_PERMISSION",e.STREAM_NOT_EXIST="STREAM_NOT_EXIST",e.EMPTY_STREAM="EMPTY_STREAM",e.NOT_CONNECTED_YET="NOT_CONNECTED_YET",e.IM_BEFORE_JOIN="IM_BEFORE_JOIN",e.USER_NOT_EXIST="USER_NOT_EXIST",e.ALREADY_IN_ROOM="ALREADY_IN_ROOM",e.KICKED_OUT="KICKED_OUT",e.ROOM_DISMISS="ROOM_DISMISS",e.TOKEN_EXPIRED="TOKEN_EXPIRED",e.TOKEN_NO_PUBLISH_PERMISSION="TOKEN_NO_PUBLISH_PERMISSION",e.TOKEN_NO_SUBSCRIBE_PERMISSION="TOKEN_NO_SUBSCRIBE_PERMISSION",e.DUPLICATE_LOGIN="DUPLICATE_LOGIN",e.INVOKED_BEFORE_CAPTURE="INVOKED_BEFORE_CAPTURE",e.REPEAT_CAPTURE="REPEAT_CAPTURE",e.GET_VIDEO_TRACK_FAILED="GET_VIDEO_TRACK_FAILED",e.GET_AUDIO_TRACK_FAILED="GET_AUDIO_TRACK_FAILED",e.GET_SCREEN_TRACK_FAILED="GET_SCREEN_TRACK_FAILED",e.STREAM_TYPE_NOT_MATCH="STREAM_TYPE_NOT_MATCH",e.CANT_FIND_DOM="CANT_FIND_DOM",e.INVALID_DEVICE_ID="INVALID_DEVICE_ID",e.NO_PERMISSION="NO_PERMISSION",e.NOT_SUPPORTED="NOT_SUPPORTED",e.INTERRUPT="INTERRUPT",e.ICE_SERVER_WRONG="ICE_SERVER_WRONG",e.ESTABLISH_DATACHANNEL_FAILED="ESTABLISH_DATACHANNEL_FAILED",e.LOAD_RESOURCES_FAILED="LOAD_RESOURCES_FAILED",e.SIGNALING_CHANNEL_NOT_OPEN="SIGNALING_CHANNEL_NOT_OPEN",e.TIME_OUT="TIME_OUT",e.REFUSE_OPERATION_IN_DISCONNECT="REFUSE_OPERATION_IN_DISCONNECT",e.ADD_TRANSCEIVER_FAILED="ADD_TRANSCEIVER_FAILED",e.UPDATE_TRACK_FAILED="UPDATE_TRACK_FAILED",e.PUBLISH_FAILED="PUBLISH_FAILED",e.UNPUBLISH_FAILED="UNPUBLISH_FAILED",e.SUBSCRIBE_FAILED="SUBSCRIBE_FAILED",e.UNSUBSCRIBE_FAILED="UNSUBSCRIBE_FAILED",e.OPERATION_CANCEL="OPERATION_CANCEL",e.START_CLOUD_PROXY_AFTER_JOIN="START_CLOUD_PROXY_AFTER_JOIN",e.STOP_CLOUD_PROXY_BEFORE_LEAVE="STOP_CLOUD_PROXY_BEFORE_LEAVE",e.UNEXPECTED_ERROR="UNEXPECTED_ERROR",e.REPEAT_DEVICE_TEST="REPEAT_DEVICE_TEST",e.AUDIO_DEVICE_TEST_FAILED="AUDIO_DEVICE_RECORD_FAILED",e.ALREADY_LOGIN="ALREADY_LOGIN",e.LOGIN_FAILED="LOGIN_FAILED",e.NOT_LOGIN="NOT_LOGIN",e.RTM_DUPLICATE_LOGIN="RTM_DUPLICATE_LOGIN",e.RTM_TOKEN_ERROR="RTM_TOKEN_ERROR",e.USER_MESSAGE_TIMEOUT="USER_MESSAGE_TIMEOUT",e.USER_MESSAGE_BROKEN="USER_MESSAGE_BROKEN",e.USER_MESSAGE_NO_RECEIVER="USER_MESSAGE_NO_RECEIVER",e.USER_MESSAGE_NO_RELAYPATH="USER_MESSAGE_NO_RELAYPATH",e.USER_MESSAGE_EXCEED_QPS="USER_MESSAGE_EXCEED_QPS",e.USER_MESSAGE_SEND_TO_SERVER_ERROR="USER_MESSAGE_SEND_TO_SERVER_ERROR",e.USER_MESSAGE_SERVER_RESPONSE_ERROR="USER_MESSAGE_SERVER_RESPONSE_ERROR",e.USER_MESSAGE_NOT_JOIN="USER_MESSAGE_NOT_JOIN",e.USER_MESSAGE_INIT="USER_MESSAGE_INIT",e.USER_MESSAGE_NO_CONNECTION="USER_MESSAGE_NO_CONNECTION",e.USER_MESSAGE_NOT_LOGIN="USER_MESSAGE_NOT_LOGIN",e.USER_MESSAGE_SERVER_PARAMS_NOTSET="USER_MESSAGE_SERVER_PARAMS_NOTSET",e.USER_MESSAGE_UNKNOWN="USER_MESSAGE_UNKNOWN",e.START_PUBLIC_STREAM_BEFORE_JOIN="START_PUBLIC_STREAM_BEFORE_JOIN",e.RECONNECT_FAILED="RECONNECT_FAILED",e.SUBTITLE_ALREADY_ON="SUBTITLE_ALREADY_ON",e.SUBTITLE_NOT_TURNED_ON="SUBTITLE_NOT_TURNED_ON",e.SUBTITLE_ERR_POSTPROCESS="SUBTITLE_ERR_POSTPROCESS",e.SUBTITLE_ERR_CONNECTION_ERROR="SUBTITLE_ERR_CONNECTION_ERROR",e.SUBTITLE_ERR_PROCESS_ERROR="SUBTITLE_ERR_PROCESS_ERROR",e.SUBTITLE_ERR_UNKNOWN="SUBTITLE_ERR_UNKNOWN",e.UNEXPECTED_INVOKE_FORWARD_STREAM="UNEXPECTED_INVOKE_FORWARD_STREAM",e.ROOM_FORBIDDEN="ROOM_FORBIDDEN",e.USER_FORBIDDEN="USER_FORBIDDEN",e.ERR_ELECTRON_IS_NULL="ERR_ELECTRON_IS_NULL",e.ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR="ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR",e.SET_SIMULCAST_FAILED="SET_SIMULCAST_FAILED",e.MIXING_OLD_AND_NEW_APIS="MIXING_OLD_AND_NEW_APIS",e.WTN_PUSH_FAILED="WTN_PUSH_FAILED",e.WTN_PLAY_FAILED="WTN_PLAY_FAILED",e.NOT_ALLOWED_IN_RTS_ROOM="NOT_ALLOWED_IN_RTS_ROOM",e.NOT_ALLOWED_IN_RESTRICTED_MODE="NOT_ALLOWED_IN_RESTRICTED_MODE",e))(ErrorCode||{}),AudioMixingError=(e=>(e[e.AUDIO_MIXING_ERROR_OK=0]="AUDIO_MIXING_ERROR_OK",e[e.AUDIO_MIXING_ERROR_PRELOAD_FAILED=1]="AUDIO_MIXING_ERROR_PRELOAD_FAILED",e[e.AUDIO_MIXING_ERROR_START_FAILED=2]="AUDIO_MIXING_ERROR_START_FAILED",e[e.AUDIO_MIXING_ERROR_ID_NOT_FOUND=3]="AUDIO_MIXING_ERROR_ID_NOT_FOUND",e[e.AUDIO_MIXING_ERROR_SET_POSITION_FAILED=4]="AUDIO_MIXING_ERROR_SET_POSITION_FAILED",e[e.AUDIO_MIXING_ERROR_INVALID_VOLUME=5]="AUDIO_MIXING_ERROR_INVALID_VOLUME",e[e.AUDIO_MIXING_ERROR_LOAD_CONFLICT=6]="AUDIO_MIXING_ERROR_LOAD_CONFLICT",e[e.AUDIO_MIXING_ERROR_ID_TYPE_NOT_MATCH=7]="AUDIO_MIXING_ERROR_ID_TYPE_NOT_MATCH",e[e.AUDIO_MIXING_ERROR_ID_TYPE_INVALID_PITCH=8]="AUDIO_MIXING_ERROR_ID_TYPE_INVALID_PITCH",e[e.AUDIO_MIXING_ERROR_INVALID_AUDIO_TRACK=9]="AUDIO_MIXING_ERROR_INVALID_AUDIO_TRACK",e))(AudioMixingError||{});class SDKError extends Error{constructor(e,t,i){super(t),__publicField(this,"code"),__publicField(this,"message"),__publicField(this,"error"),this.code=e,this.message=t,this.error=i,Object.setPrototypeOf(this,SDKError.prototype)}toString(){return`SDKError: ${this.code} ${this.message}`}}var EngineEventsTypes=(e=>(e.onTrackEnded="onTrackEnded",e.onTrackMute="onTrackMute",e.onTrackUnmute="onTrackUnmute",e.onPlayerEvent="onPlayerEvent",e.onAutoplayFailed="onAutoplayFailed",e.onUserJoined="onUserJoined",e.onUserLeave="onUserLeave",e.onConnectionStateChanged="onConnectionStateChanged",e.onUserPublishStream="onUserPublishStream",e.onUserUnpublishStream="onUserUnpublishStream",e.onUserPublishScreen="onUserPublishScreen",e.onUserUnpublishScreen="onUserUnpublishScreen",e.onRoomMessageReceived="onRoomMessageReceived",e.onRoomBinaryMessageReceived="onRoomBinaryMessageReceived",e.onUserMessageReceived="onUserMessageReceived",e.onUserBinaryMessageReceived="onUserBinaryMessageReceived",e.onVideoFirstFrameRendered="onVideoFirstFrameRendered",e.onVideoFirstFrameDecoded="onVideoFirstFrameDecoded",e.onRemoteVideoFirstFrame="onRemoteVideoFirstFrame",e.onAudioFirstFrameDecoded="onAudioFirstFrameDecoded",e.onRemoteAudioFirstFrame="onRemoteAudioFirstFrame",e.onFirstPublicStreamVideoFrameRendered="onFirstPublicStreamVideoFrameRendered",e.onFirstPublicStreamVideoFrameDecoded="onFirstPublicStreamVideoFrameDecoded",e.onFirstPublicStreamAudioFrameDecoded="onFirstPublicStreamAudioFrameDecoded",e.onVideoDeviceStateChanged="onVideoDeviceStateChanged",e.onAudioDeviceStateChanged="onAudioDeviceStateChanged",e.onRemoteStreamStats="onRemoteStreamStats",e.onPublicStreamStats="onPublicStreamStats",e.onLocalStreamStats="onLocalStreamStats",e.onAudioVolumeIndication="onAudioVolumeIndication",e.onLocalAudioPropertiesReport="onLocalAudioPropertiesReport",e.onRemoteAudioPropertiesReport="onRemoteAudioPropertiesReport",e.onActiveSpeaker="onActiveSpeaker",e.onAudioPlaybackDeviceChanged="onAudioPlaybackDeviceChanged",e.onUserStartVideoCapture="onUserStartVideoCapture",e.onUserStopVideoCapture="onUserStopVideoCapture",e.onUserStartAudioCapture="onUserStartAudioCapture",e.onUserStopAudioCapture="onUserStopAudioCapture",e.onAutoPublishResult="onAutoPublishResult",e.onAutoSubscribeResult="onAutoSubscribeResult",e.onLiveTranscodingResult="onLiveTranscodingResult",e.onStreamMixingEvent="onStreamMixingEvent",e.onAudioPlaybackDeviceTestVolume="onAudioPlaybackDeviceTestVolume",e.onSEIMessageReceived="onSEIMessageReceived",e.onError="onError",e.onAudioMixingStateChanged="onAudioMixingStateChanged",e.onUserMessageReceivedOutsideRoom="onUserMessageReceivedOutsideRoom",e.onUserBinaryMessageReceivedOutsideRoom="onUserBinaryMessageReceivedOutsideRoom",e.onTokenWillExpire="onTokenWillExpire",e.onTokenPublishPrivilegeWillExpire="onTokenPublishPrivilegeWillExpire",e.onTokenPublishPrivilegeDidExpired="onTokenPublishPrivilegeDidExpired",e.onTokenSubscribePrivilegeWillExpire="onTokenSubscribePrivilegeWillExpire",e.onTokenSubscribePrivilegeDidExpired="onTokenSubscribePrivilegeDidExpired",e.onCloudProxyConnected="onCloudProxyConnected",e.onPushPublicStreamResult="onPushPublicStreamResult",e.onPublicStreamSEIMessageReceived="onPublicStreamSEIMessageReceived",e.onNetworkQuality="onNetworkQuality",e.onSimulcastSubscribeFallback="onSimulcastSubscribeFallback",e.onRemoteVideoSizeChanged="onRemoteVideoSizeChanged",e.onVideoStreamBanned="onVideoStreamBanned",e.onAudioStreamBanned="onAudioStreamBanned",e.onLocalVideoSizeChanged="onLocalVideoSizeChanged",e.onSubtitleStateChanged="onSubtitleStateChanged",e.onSubtitleMessageReceived="onSubtitleMessageReceived",e.onServerParamsSetResult="onServerParamsSetResult",e.onLocalStreamTrackChangedByExtension="onLocalStreamTrackChangedByExtension",e.onVendorConnectionStateChanged="onVendorConnectionStateChanged",e.onForwardStreamError="onForwardStreamError",e.onRejoinWithTcp="onRejoinWithTcp",e.onIceConnectWithTcp="onIceConnectWithTcp",e.onPublishRetry="onPublishRetry",e.onSubscribeRetry="onSubscribeRetry",e.onPublishResult="onPublishResult",e.onSubscribeResult="onSubscribeResult",e.onSEIStreamUpdate="onSEIStreamUpdate",e))(EngineEventsTypes||{});function checkBoolean(e,t){if("boolean"!=typeof e)throw new SDKError(ErrorCode.INVALID_PARAMS,`Invalid ${t}: The value should be boolean type.`)}const checkVideoFrameCallback=()=>!isSSR$1()&&"function"==typeof HTMLVideoElement.prototype.requestVideoFrameCallback;function checkNumber(e,t,i=1,r=Number.POSITIVE_INFINITY){if(e<i||e>r||"number"!=typeof e){throw new SDKError(ErrorCode.INVALID_PARAMS,`Invalid ${t}: the value range is [${i}, ${r}]. integer only`)}}function checkString(e,t,i=1,r=Number.POSITIVE_INFINITY){if(null==e)throw new SDKError(ErrorCode.INVALID_PARAMS,`${t} cannot be empty`);if(!isValidString(e,i,r))throw new SDKError(ErrorCode.INVALID_PARAMS,`Invalid ${t}: The value should be string type. Length of the string: [${i},${r}]`)}function checkEnum(e,t,i){if(!i.includes(e))throw new SDKError(ErrorCode.INVALID_PARAMS,`Invalid ${t}: The value can only be set as ${JSON.stringify(i)}`)}function checkMediaStreamTrack(e){if(!(e instanceof MediaStreamTrack))throw new SDKError(ErrorCode.INVALID_PARAMS,"Invalid track, The value should be MediaStreamTrack type.")}function checkEmpty(e,t){if(isEmpty(e))throw new SDKError(ErrorCode.INVALID_PARAMS,`Invalid ${t}, should not be empty`)}function checkArray(e,t){if(!Array.isArray(e))throw new SDKError(ErrorCode.INVALID_PARAMS,`Invalid ${t}, should be array`)}function checkArrayBuffer(e,t){if(!(e instanceof ArrayBuffer))throw new SDKError(ErrorCode.INVALID_PARAMS,`Invalid ${t}, should be ArrayBuffer`)}function checkSupportedConstraints(e){try{const t=navigator.mediaDevices.getSupportedConstraints();for(const i of Object.keys(e))t[i]||delete e[i]}catch(e){}}function isValidString(e,t=1,i=Number.POSITIVE_INFINITY){return"string"==typeof e&&e.length<=i&&e.length>=t}function isEmpty(e){return null==e}function checkRoomId(e){if("string"!=typeof e||!/^[a-zA-Z0-9@._-]{1,128}$/.test(e))throw new SDKError(ErrorCode.INVALID_PARAMS,"The RoomId must be within 128 bytes. The supported characters: a-z,A-Z,0-9,@,-,_,.")}function checkUserId(e){if("string"!=typeof e||!/^[a-zA-Z0-9@._-]{1,128}$/.test(e))throw new SDKError(ErrorCode.INVALID_PARAMS,"The userId must be within 128 bytes. The supported characters: a-z,A-Z,0-9,@,-,_,.")}function checkPublicStreamId(e){if("string"!=typeof e||!/^[a-zA-Z0-9@._-]{1,128}$/.test(e))throw new SDKError(ErrorCode.INVALID_PARAMS,"The publicStreamId must be within 128 bytes. The supported characters: a-z,A-Z,0-9,@,-,_,.")}function illegalBusinessId(e){return"string"!=typeof e}function checkUserInfo(e){checkEmpty(e,"userInfo"),checkUserId(e.userId),isEmpty(e.extraInfo)||checkString(e.extraInfo,"userInfo.extraInfo",1,200)}function checkRoomConfig(e){checkEmpty(e,"roomConfig"),checkBoolean(e.isAutoPublish,"roomConfig.isAutoPublish"),checkBoolean(e.isAutoSubscribeAudio,"roomConfig.isAutoSubscribeAudio"),checkBoolean(e.isAutoSubscribeVideo,"roomConfig.isAutoSubscribeVideo"),isEmpty(e.roomProfileType)||checkEnum(e.roomProfileType,"roomConfig",[RoomProfileType.communication,RoomProfileType.chat,RoomProfileType.chatRoom,RoomProfileType.coHost,RoomProfileType.meeting,RoomProfileType.classRoom])}function checkVideoPlayerOption(e){checkEmpty(e,"videoPlayerOption")}function checkBufferSize(e,t=64){if(!e||0===(null==e?void 0:e.byteLength))throw new SDKError(ErrorCode.INVALID_PARAMS,"The message cannot be empty");let i;if(e instanceof ArrayBuffer)i=e;else{if("string"!=typeof e)throw new SDKError(ErrorCode.INVALID_PARAMS,"The message must be string or ArrayBuffer");i=Utils.str2ab(e)}if((null==i?void 0:i.byteLength)>1024*t)throw new SDKError(ErrorCode.INVALID_PARAMS,`The message length must be less than ${t}KB`);return i.byteLength??0}function isReportCallback(e){const t=getParameter("FORCE_ENABLED_REPORT_CALLBACKS");if(null==t?void 0:t.includes(e))return!0;if(e===EngineEventsTypes.onRemoteStreamStats){if(!!getParameter("UPLOAD_REMOTE_STATS"))return!0}return![EngineEventsTypes.onRemoteStreamStats,EngineEventsTypes.onLocalStreamStats,EngineEventsTypes.onAudioVolumeIndication,EngineEventsTypes.onLocalAudioPropertiesReport,EngineEventsTypes.onRemoteAudioPropertiesReport].includes(e)}function checkRemoteConfig(e){if("number"!=typeof(null==e?void 0:e.width)||"number"!=typeof(null==e?void 0:e.height))throw new SDKError(ErrorCode.INVALID_PARAMS,"remoteVideoConfig must contain width, height, frameRate")}function checkConstrainULongg(e,t){if("number"==typeof e&&!Number.isNaN(e)&&e>=1)return;const i=e;if(!((null==i?void 0:i.min)||(null==i?void 0:i.max)||(null==i?void 0:i.exact)||(null==i?void 0:i.ideal)))throw new SDKError(ErrorCode.INVALID_PARAMS,`${t} is not a valid ConstrainULong`)}function checkVideoEncoderConfig(e){checkArray(e,"videoEncoderConfig");for(const t of e)checkEmpty(t,"videoEncoderConfigItem"),checkNumber(null==t?void 0:t.maxKbps,"maxKbps"),checkConstrainULongg(null==t?void 0:t.width,"width"),checkConstrainULongg(null==t?void 0:t.height,"height"),checkConstrainULongg(null==t?void 0:t.frameRate,"frameRate")}function numberRangeGuide(e,t,i=Number.NEGATIVE_INFINITY,r=Number.POSITIVE_INFINITY){return checkNumber(e,t,Number.NEGATIVE_INFINITY,Number.POSITIVE_INFINITY),e=(e=e>i?e:i)<r?e:r}function checkAudioAndVideoDeviceId(e,t){let i;return isEmpty(t)||checkString(t,"videoDeviceId"),isEmpty(e)||("string"==typeof e?(checkString(e,"audioDeviceId"),i=e):(i=null==e?void 0:e.audioDeviceId,t=null==e?void 0:e.videoDeviceId,checkString(i,"audioDeviceId"),checkString(t,"videoDeviceId"))),{audioDeviceId:i,videoDeviceId:t}}var ExtendMediaType=(e=>(e[e.NONE=0]="NONE",e))(ExtendMediaType||{}),VideoCodecName=(e=>(e.H264="H264",e.VP8="VP8",e.ByteVC1="ByteVC1",e))(VideoCodecName||{});const isSupported=async()=>{try{return!(isSSR()||!window.RTCPeerConnection||!window.RTCPeerConnection.prototype.addTransceiver||!window.RTCPeerConnection.prototype.createDataChannel)&&(await isH264DecodeSupported()&&await isH264EncodeSupported())}catch(e){return!1}},internalGetSupportedCodecs=async()=>{const e=[];return await isH265DecodeSupported()&&await isH265EncodeSupported()&&e.push(VideoCodecName.ByteVC1),await isH264DecodeSupported()&&await isH264EncodeSupported()&&e.push(VideoCodecName.H264),await isVP8DecodeSupported()&&await isVP8EncodeSupported()&&e.push(VideoCodecName.VP8),e},getSupportedCodecs=async()=>(await internalGetSupportedCodecs()).map((e=>e===VideoCodecName.ByteVC1?"H265":e.toUpperCase())),hasHardwareEncodeProfile=()=>{let e=!1;if("function"==typeof RTCRtpSender.getCapabilities){const{codecs:t}=RTCRtpSender.getCapabilities("video")||{};t&&t.length>0&&t.forEach((t=>{var i;((null==(i=null==t?void 0:t.sdpFmtpLine)?void 0:i.indexOf("profile-level-id=42001f"))??-1)>-1&&(e=!0)}))}return e},codecsSupportMap={};function supportH264(e){const t=e.split("\n");let i=!1;for(const e of t)if(e.includes("level-asymmetry-allowed=1")&&e.includes("packetization-mode=1")&&e.includes("profile-level-id=42e0")){i=!0;break}if(i){const e=navigator.userAgent.toLowerCase();let t=!1;const i=[/miuibrowser/,/70.*HeyTapBrowser/i];for(const r of i)r.test(e)&&(t=!0);return!t}return!1}const createOfferSdp=async e=>{const t=new RTCPeerConnection;t.addTransceiver("video",{direction:e});const i=await t.createOffer();return t.close(),i.sdp.toLowerCase()},checkCodecsEncodeSupport=async()=>{let e=await createOfferSdp("sendonly");return navigator.userAgent.includes("VivoBrowser")&&(e=await createOfferSdp("sendonly")),codecsSupportMap.h264encode=supportH264(e),codecsSupportMap.vp8encode=e.indexOf("vp8")>-1,codecsSupportMap.h265encode=e.indexOf("h265")>-1,codecsSupportMap},checkCodecsDecodeSupport=async()=>{let e=await createOfferSdp("recvonly");return navigator.userAgent.includes("VivoBrowser")&&(e=await createOfferSdp("recvonly")),codecsSupportMap.h264decode=supportH264(e),codecsSupportMap.vp8decode=e.indexOf("vp8")>-1,codecsSupportMap.h265decode=e.indexOf("h265")>-1,codecsSupportMap},isH264EncodeSupported=async()=>{if(void 0===codecsSupportMap.h264encode)try{await checkCodecsEncodeSupport()}catch{return!1}return codecsSupportMap.h264encode||!1},isH264DecodeSupported=async()=>{if(void 0===codecsSupportMap.h264decode)try{await checkCodecsDecodeSupport()}catch{return!1}return codecsSupportMap.h264decode||!1},isVP8EncodeSupported=async()=>{if(void 0===codecsSupportMap.vp8encode)try{await checkCodecsEncodeSupport()}catch{return!1}return codecsSupportMap.vp8encode||!1},isVP8DecodeSupported=async()=>{if(void 0===codecsSupportMap.vp8decode)try{await checkCodecsDecodeSupport()}catch{return!1}return codecsSupportMap.vp8decode||!1},isH265EncodeSupported=async()=>{if(void 0===codecsSupportMap.h265encode)try{await checkCodecsEncodeSupport()}catch{return!1}return codecsSupportMap.h265encode||!1},isH265DecodeSupported=async()=>{if(void 0===codecsSupportMap.h265decode)try{await checkCodecsDecodeSupport()}catch{return!1}return codecsSupportMap.h265decode||!1},isEncodedTransformSupported=()=>"undefined"!=typeof TransformStream&&"undefined"!=typeof RTCRtpSender&&"undefined"!=typeof RTCRtpReceiver&&"undefined"!=typeof RTCRtpScriptTransform&&"transform"in RTCRtpSender.prototype&&"transform"in RTCRtpReceiver.prototype&&isWorkerSupported()&&isMessageChannelSupported(),isLegacyEncodedTransformSupported=()=>"undefined"!=typeof TransformStream&&"undefined"!=typeof RTCRtpSender&&"undefined"!=typeof RTCRtpReceiver&&void 0!==RTCRtpSender.prototype.createEncodedStreams&&void 0!==RTCRtpReceiver.prototype.createEncodedStreams,isWebAudioSupported=()=>isMac?isChrome&&chromeVersion>=70||isFirefox&&firefoxVersion>=80||isSafari&&safariVersion>=14:isWindows?isChrome&&chromeVersion>=70||isFirefox&&firefoxVersion>=80:isIOS?iOSVersion[0]>=14:!(!isAndroid&&!isOpenHarmony)&&(isChrome&&chromeVersion>=86),isStatsCallbackSupport=isChrome&&chromeVersion<=114,isTransportCCSupport=!isFirefox||firefoxVersion>=96,isRRTRSupported=!(isSafari&&safariVersion<=14),unsupportedSimultaneousCapture=isAndroid&&isChrome||isIOS&&iOSVersion[0]>=16,isSimulcastSupported=()=>!isFirefox&&!isOpera&&14!==(null==iOSVersion?void 0:iOSVersion[0]),isComputePressureSupported="undefined"!=typeof globalThis&&"PressureObserver"in globalThis,isWorkerSupported=()=>"undefined"!=typeof window&&window.Worker,notSupport48k=isSafari&&safariVersion<=14,is48kSupported=!notSupport48k,isMessageChannelSupported=()=>"undefined"!=typeof MessageChannel,notSupportConstraintInGetDisplayMedia=isSafari&&((null==safariMinorVersion?void 0:safariMinorVersion.includes("16.1"))||(null==safariMinorVersion?void 0:safariMinorVersion.includes("16.2"))||(null==safariMinorVersion?void 0:safariMinorVersion.includes("16.3"))),isConstraintInGetDisplayMediaSupported=!notSupportConstraintInGetDisplayMedia,internalAccessDomains="access.rtc.volcvideo.com,access2-hl.rtc.volcvideo.com,rtcg-access.volcvideos.com".split(",");function getFullAccessUrl(e=""){return e?(/^https?:\/\/.+/.test(e)||(e=`https://${e}`),`${e}/dispatch/v1/AccessInfo?Action=GetAccessInfo`):""}function getFullLogServerUrl(e=""){return e?(/^https?:\/\/.+/.test(e)||(e=`https://${e}`),`${e}/video/v1/webrtc_log/`):""}const domesticLogServerUrl="https://web-log-report.rtc.volcvideo.com/video/v1/webrtc_log/",overseasLogServerUrl="https://web-log-report.volcvideos.com/video/v1/webrtc_log/",configDomains="common.rtc.volcvideo.com,rtcg.volcvideos.com".split(","),Config2={VERSION:"4.66.36",ICE_CONFIG_REQUEST_URLS_INTERNAL:internalAccessDomains.map(getFullAccessUrl),ICE_CONFIG_REQUEST_URLS:[],EXPECTED_ADDR:"",LOG_SERVER_URL:domesticLogServerUrl,CONFIG_REQUEST_DOMAINS:configDomains,DEVICE_ID:"",OVERSEA:!1,PLATFORM:"",PRODUCT:"",FORCE_ENABLED_REPORT_CALLBACKS:[],SKIP_WEB_AUDIO_IN_TRACK:!1,ENFORCE_WEB_AUDIO_SUPPORTED:!1,AUDIO_STALL:!0,VIDEO_STALL:!0,VIDEO_STALL_100MS:!1,STATS_SCALLBACK_SUPPORT:!0,JOIN_ROOM_CONFIG:JoinRoomConfig.DEFAULT_CONF,SIGNAL_COMPRESSION:!0,SIGNAL_CROP_JOINROOM:!0,VIDEO_STALL_DATA:500,AUDIO_STALL_DATA:200,IOS_SAFARI_ORIENTATION:!1,BLACK_FRAME_LIFETIME:6e4,FALLBACK_ENCODE_CODEC:"",SEI_TIME_OUT:2e3,SEI_COUNT_FPS:1,PRE_ICE:!1,STATS_LOOP_INTERVAL:1e3,HIDDEN_STATS:!1,UPLOAD_REMOTE_STATS:ExtendMediaType.NONE,SDK_CODEC_NEGOTIATION:!0,AUDIO_CODEC:"OPUS",DISABLE_ENCODED_TRANSFORM:!1,SKIP_SEI_FILTER:!1,AREA_CODE:"",DISABLE_COMPUTE_PRESSURE:!1,SEND_MESSAGE_SYNC:!1,H264_HW_ENCODER:!1,GPU_URL:"",ENABLE_FALLBACK_HANDLER:!1,ENABLE_STANDARD_HANDLER:isStandardModeEnableByDefault(),PC_KILLSWITCH:{},ENABLE_PLAY_AFTER_CLICK:!1,AUTOPLAY_WORKAROUND:!0,ENGINE_WEB_CONFIG:{},DISABLE_IOS_MUTE_WORKAROUND:!1,AUTOPLAY_THROTTLE:0},originalSetRemoteDescription="undefined"==typeof window?()=>Promise.resolve():null==(_i=null==window?void 0:window.RTCPeerConnection)?void 0:_i.prototype.setRemoteDescription;function setParameter(e,t){if(reportGlobalApiCall("setParameter",0,`key: ${e}, value: ${t}`),"VERSION"===e)return;if("H264_HW_ENCODER"===e){if(Config2.H264_HW_ENCODER=!!t,t){hasHardwareEncodeProfile()?(reportGlobalApiCall("setParameter",0,`key: ${e}, value: ${t} is executed as it met 42001f`),RTCPeerConnection.prototype.setRemoteDescription=function(e){var t;return originalSetRemoteDescription.call(this,{type:e.type,sdp:null==(t=e.sdp)?void 0:t.replaceAll("42e01f","42001f")})}):reportGlobalApiCall("setParameter",0,`key: ${e}, value: ${t} fails as sdp contains no 42001f`)}else RTCPeerConnection.prototype.setRemoteDescription=originalSetRemoteDescription;return}if("GPU_URL"===e)return void(Config2.GPU_URL=t);if("JOIN_ROOM_CONFIG"===e)return JoinRoomConfig.setDefaulConf(t);if("ICE_CONFIG_REQUEST_URLS"===e){const e="string"==typeof t?[t]:t;return Config2.ICE_CONFIG_REQUEST_URLS=e.map(getFullAccessUrl),sdkCache.clearAccessUrls(),void sdkCache.clearAccessNode()}if("VIDEO_STALL_DATA"===e)return void(Config2.VIDEO_STALL_DATA=Math.max(500,Number(t)));if("AUDIO_STALL_DATA"===e)return void(Config2.AUDIO_STALL_DATA=Math.max(200,Number(t)));if("VIDEO_STALL_100MS"===e)return void(Config2.VIDEO_STALL_100MS=checkVideoFrameCallback()&&!!t);if("PLATFORM"===e&&"string"==typeof t)return void setGlobalStats({platform:t});if("PRODUCT"===e&&"string"==typeof t)return void setGlobalStats({product:t});if("FORCE_ENABLED_REPORT_CALLBACKS"===e){const e="string"==typeof t?[t]:t;return void(Config2.FORCE_ENABLED_REPORT_CALLBACKS=e)}if("LOG_SERVER_URL"===e){const e=t===LogChannel.overseas?overseasLogServerUrl:t===LogChannel.domestic?domesticLogServerUrl:"string"==typeof t?t:void 0;e&&(Config2.LOG_SERVER_URL=e,setReportUrl(e))}else if("OVERSEA"===e)return setGlobalStats({extra_is_oversea:t?"1":"0"}),void(Config2.OVERSEA=t);if("CONFIG_REQUEST_DOMAINS"===e&&Array.isArray(t)&&t.length>0)return void(Config2.CONFIG_REQUEST_DOMAINS=t);if("SEI_TIME_OUT"===e&&"number"!=typeof t)return;if("SEI_COUNT_FPS"===e&&"number"!=typeof t)return;if("UPLOAD_REMOTE_STATS"===e&&"string"==typeof t){const e=t.split(",").map((e=>e.trim())).reduce(((e,t)=>"video"===t?e|MediaType$1.VIDEO:"audio"===t?e|MediaType$1.AUDIO:e),ExtendMediaType.NONE);return void(Config2.UPLOAD_REMOTE_STATS=e)}if("AINR_URLS"===e&&"string"==typeof t)try{const{gulpUrl:e,wasmUrl:i,type5ModelUrl:r,type6ModelUrl:o}=JSON.parse(t);return void(Config2.AINR_URLS={gulpUrl:e,wasmUrl:i,type5ModelUrl:r,type6ModelUrl:o})}catch(e){console.error(e)}"DEVICE_ID"===e&&sdkCache.setDeviceId(t);CoreConfig.getKeys().includes(e)?CoreConfig.setParameter(e,t):Reflect.set(Config2,e,t)}function getParameter(e){return"DEVICE_ID"===e?sdkCache.getDeviceId():Config2[e]}function getPublicStreamControlMessage(e,t,i){var r,o,s,n,a,d,c,l,u;return{type:"publicstream",action:t,publicStreamID:e,publicStreamMeta:{audio:{},video:{fps:(null==(r=i.video)?void 0:r.fps)||15,bitrate:1e3*((null==(o=i.video)?void 0:o.kBitRate)||40),width:(null==(s=i.video)?void 0:s.width)||640,height:(null==(n=i.video)?void 0:n.height)||360},layout:{layoutMode:2,interpolationMode:(null==(a=i.layout)?void 0:a.interpolationMode)||PublicInterpolationMode.PREV_FRAME,canvas:{bgColor:(null==(d=i.layout)?void 0:d.backgroundColor)||"#000000",bgImage:(null==(c=i.layout)?void 0:c.backgroundImage)||""},regions:(null==(u=null==(l=i.layout)?void 0:l.regions)?void 0:u.map((e=>({roomId:e.roomId,userId:e.userId,alterImage:e.alertImage||"",alpha:!e.alpha||Number(e.alpha)>1||Number(e.alpha)<=0?1:Number(e.alpha),x:!e.x||Number(e.x)>=1||Number(e.x)<0?0:Number(e.x),y:!e.y||Number(e.y)>=1||Number(e.y)<0?0:Number(e.y),w:!e.w||Number(e.w)>1||Number(e.w)<=0?1:Number(e.w),h:!e.h||Number(e.h)>1||Number(e.h)<=0?1:Number(e.h),zorder:!e.zorder||Number(e.zorder)<0||Number(e.zorder)>100?0:Number(e.zorder),renderMode:void 0===e.renderMode?1:e.renderMode,streamType:e.isScreenStream?1:0,mediaType:e.mediaType||0,sourceCrop:e.sourceCrop}))))||[]}}}}let videoEncoderAutoConfigList=[];function getVideoEncoderAutoConfigList(){return videoEncoderAutoConfigList}function setVideoEncoderAutoConfigList(e){videoEncoderAutoConfigList=e}const autoResetVideoEncoderConfig=(e,t)=>{const i=getVideoEncoderAutoConfigList();if(!i.length)return;const r=e[0],o=t.width||constraints2number(r.width),s=t.height||constraints2number(r.height),n=o*s;if(constraints2number(r.width)*constraints2number(r.height)<=n)return;let a,d,c=i[0];i.forEach((e=>{const t=constraints2number(e.width)*constraints2number(e.height);a||(n<t?a=e:c=e)})),d=a&&constraints2number(a.width)*constraints2number(a.height)-n<n-constraints2number(c.width)*constraints2number(c.height)?Object.assign({},a):Object.assign({},c);const l=e.filter((e=>!(d&&constraints2number(e.width)*constraints2number(e.height)>=n)||(d.maxKbps=Math.min(e.maxKbps,d.maxKbps),!1)));return l.unshift({width:o,height:s,frameRate:t.frameRate?Math.round(t.frameRate):l[0].frameRate,maxKbps:d.maxKbps}),l},defaultVideoEncoderConfig={width:640,height:480,frameRate:15,maxKbps:600},defaultScreenEncoderConfig={width:1920,height:1080,frameRate:15,maxKbps:3e3};function isStandardModeEnableByDefault(){return(isChrome||isEdge)&&!isIOS}let getRandomValues;const rnds8=new Uint8Array(16);function rng(){if(!getRandomValues&&(getRandomValues="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!getRandomValues))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return getRandomValues(rnds8)}const byteToHex=[];for(let e=0;e<256;++e)byteToHex.push((e+256).toString(16).slice(1));function unsafeStringify(e,t=0){return byteToHex[e[t+0]]+byteToHex[e[t+1]]+byteToHex[e[t+2]]+byteToHex[e[t+3]]+"-"+byteToHex[e[t+4]]+byteToHex[e[t+5]]+"-"+byteToHex[e[t+6]]+byteToHex[e[t+7]]+"-"+byteToHex[e[t+8]]+byteToHex[e[t+9]]+"-"+byteToHex[e[t+10]]+byteToHex[e[t+11]]+byteToHex[e[t+12]]+byteToHex[e[t+13]]+byteToHex[e[t+14]]+byteToHex[e[t+15]]}const randomUUID="undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);var native={randomUUID:randomUUID};function v4(e,t,i){if(native.randomUUID&&!t&&!e)return native.randomUUID();const r=(e=e||{}).random||(e.rng||rng)();if(r[6]=15&r[6]|64,r[8]=63&r[8]|128,t){i=i||0;for(let e=0;e<16;++e)t[i+e]=r[e];return t}return unsafeStringify(r)}var libTypedarrays={exports:{}};function commonjsRequire(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var hasRequiredCore,core={exports:{}},__viteBrowserExternal=new Proxy({},{get(e,t){throw new Error(`Module "" has been externalized for browser compatibility. Cannot access ".${t}" in client code. See http://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`)}}),__viteBrowserExternal$1=Object.freeze({__proto__:null,default:__viteBrowserExternal}),require$$0=getAugmentedNamespace(__viteBrowserExternal$1);function requireCore(){return hasRequiredCore||(hasRequiredCore=1,core.exports=(e=e||function(e,t){var i;if("undefined"!=typeof window&&window.crypto&&(i=window.crypto),"undefined"!=typeof self&&self.crypto&&(i=self.crypto),"undefined"!=typeof globalThis&&globalThis.crypto&&(i=globalThis.crypto),!i&&"undefined"!=typeof window&&window.msCrypto&&(i=window.msCrypto),!i&&void 0!==commonjsGlobal&&commonjsGlobal.crypto&&(i=commonjsGlobal.crypto),!i&&"function"==typeof commonjsRequire)try{i=require$$0}catch(e){}var r=function(){if(i){if("function"==typeof i.getRandomValues)try{return i.getRandomValues(new Uint32Array(1))[0]}catch(e){}if("function"==typeof i.randomBytes)try{return i.randomBytes(4).readInt32LE()}catch(e){}}throw new Error("Native crypto module could not be used to get secure random number.")},o=Object.create||function(){function e(){}return function(t){var i;return e.prototype=t,i=new e,e.prototype=null,i}}(),s={},n=s.lib={},a=n.Base={extend:function(e){var t=o(this);return e&&t.mixIn(e),t.hasOwnProperty("init")&&this.init!==t.init||(t.init=function(){t.$super.init.apply(this,arguments)}),t.init.prototype=t,t.$super=this,t},create:function(){var e=this.extend();return e.init.apply(e,arguments),e},init:function(){},mixIn:function(e){for(var t in e)e.hasOwnProperty(t)&&(this[t]=e[t]);e.hasOwnProperty("toString")&&(this.toString=e.toString)},clone:function(){return this.init.prototype.extend(this)}},d=n.WordArray=a.extend({init:function(e,i){e=this.words=e||[],this.sigBytes=i!=t?i:4*e.length},toString:function(e){return(e||l).stringify(this)},concat:function(e){var t=this.words,i=e.words,r=this.sigBytes,o=e.sigBytes;if(this.clamp(),r%4)for(var s=0;s<o;s++){var n=i[s>>>2]>>>24-s%4*8&255;t[r+s>>>2]|=n<<24-(r+s)%4*8}else for(var a=0;a<o;a+=4)t[r+a>>>2]=i[a>>>2];return this.sigBytes+=o,this},clamp:function(){var t=this.words,i=this.sigBytes;t[i>>>2]&=4294967295<<32-i%4*8,t.length=e.ceil(i/4)},clone:function(){var e=a.clone.call(this);return e.words=this.words.slice(0),e},random:function(e){for(var t=[],i=0;i<e;i+=4)t.push(r());return new d.init(t,e)}}),c=s.enc={},l=c.Hex={stringify:function(e){for(var t=e.words,i=e.sigBytes,r=[],o=0;o<i;o++){var s=t[o>>>2]>>>24-o%4*8&255;r.push((s>>>4).toString(16)),r.push((15&s).toString(16))}return r.join("")},parse:function(e){for(var t=e.length,i=[],r=0;r<t;r+=2)i[r>>>3]|=parseInt(e.substr(r,2),16)<<24-r%8*4;return new d.init(i,t/2)}},u=c.Latin1={stringify:function(e){for(var t=e.words,i=e.sigBytes,r=[],o=0;o<i;o++){var s=t[o>>>2]>>>24-o%4*8&255;r.push(String.fromCharCode(s))}return r.join("")},parse:function(e){for(var t=e.length,i=[],r=0;r<t;r++)i[r>>>2]|=(255&e.charCodeAt(r))<<24-r%4*8;return new d.init(i,t)}},_=c.Utf8={stringify:function(e){try{return decodeURIComponent(escape(u.stringify(e)))}catch(e){throw new Error("Malformed UTF-8 data")}},parse:function(e){return u.parse(unescape(encodeURIComponent(e)))}},h=n.BufferedBlockAlgorithm=a.extend({reset:function(){this._data=new d.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=_.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var i,r=this._data,o=r.words,s=r.sigBytes,n=this.blockSize,a=s/(4*n),c=(a=t?e.ceil(a):e.max((0|a)-this._minBufferSize,0))*n,l=e.min(4*c,s);if(c){for(var u=0;u<c;u+=n)this._doProcessBlock(o,u);i=o.splice(0,c),r.sigBytes-=l}return new d.init(i,l)},clone:function(){var e=a.clone.call(this);return e._data=this._data.clone(),e},_minBufferSize:0});n.Hasher=h.extend({cfg:a.extend(),init:function(e){this.cfg=this.cfg.extend(e),this.reset()},reset:function(){h.reset.call(this),this._doReset()},update:function(e){return this._append(e),this._process(),this},finalize:function(e){return e&&this._append(e),this._doFinalize()},blockSize:16,_createHelper:function(e){return function(t,i){return new e.init(i).finalize(t)}},_createHmacHelper:function(e){return function(t,i){return new p.HMAC.init(e,i).finalize(t)}}});var p=s.algo={};return s}(Math),e)),core.exports;var e}!function(){var e;libTypedarrays.exports=(e=requireCore(),function(){if("function"==typeof ArrayBuffer){var t=e.lib.WordArray,i=t.init,r=t.init=function(e){if(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),(e instanceof Int8Array||"undefined"!=typeof Uint8ClampedArray&&e instanceof Uint8ClampedArray||e instanceof Int16Array||e instanceof Uint16Array||e instanceof Int32Array||e instanceof Uint32Array||e instanceof Float32Array||e instanceof Float64Array)&&(e=new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),e instanceof Uint8Array){for(var t=e.byteLength,r=[],o=0;o<t;o++)r[o>>>2]|=e[o]<<24-o%4*8;i.call(this,r,t)}else i.apply(this,arguments)};r.prototype=t}}(),e.lib.WordArray)}();var hasRequiredEncBase64,libTypedarraysExports=libTypedarrays.exports,WordArray=getDefaultExportFromCjs(libTypedarraysExports),aes={exports:{}},encBase64={exports:{}};function requireEncBase64(){return hasRequiredEncBase64||(hasRequiredEncBase64=1,encBase64.exports=(e=requireCore(),function(){var t=e,i=t.lib.WordArray;function r(e,t,r){for(var o=[],s=0,n=0;n<t;n++)if(n%4){var a=r[e.charCodeAt(n-1)]<<n%4*2|r[e.charCodeAt(n)]>>>6-n%4*2;o[s>>>2]|=a<<24-s%4*8,s++}return i.create(o,s)}t.enc.Base64={stringify:function(e){var t=e.words,i=e.sigBytes,r=this._map;e.clamp();for(var o=[],s=0;s<i;s+=3)for(var n=(t[s>>>2]>>>24-s%4*8&255)<<16|(t[s+1>>>2]>>>24-(s+1)%4*8&255)<<8|t[s+2>>>2]>>>24-(s+2)%4*8&255,a=0;a<4&&s+.75*a<i;a++)o.push(r.charAt(n>>>6*(3-a)&63));var d=r.charAt(64);if(d)for(;o.length%4;)o.push(d);return o.join("")},parse:function(e){var t=e.length,i=this._map,o=this._reverseMap;if(!o){o=this._reverseMap=[];for(var s=0;s<i.length;s++)o[i.charCodeAt(s)]=s}var n=i.charAt(64);if(n){var a=e.indexOf(n);-1!==a&&(t=a)}return r(e,t,o)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}}(),e.enc.Base64)),encBase64.exports;var e}var hasRequiredMd5,md5={exports:{}};function requireMd5(){return hasRequiredMd5||(hasRequiredMd5=1,md5.exports=(e=requireCore(),function(t){var i=e,r=i.lib,o=r.WordArray,s=r.Hasher,n=i.algo,a=[];!function(){for(var e=0;e<64;e++)a[e]=4294967296*t.abs(t.sin(e+1))|0}();var d=n.MD5=s.extend({_doReset:function(){this._hash=new o.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(e,t){for(var i=0;i<16;i++){var r=t+i,o=e[r];e[r]=16711935&(o<<8|o>>>24)|4278255360&(o<<24|o>>>8)}var s=this._hash.words,n=e[t+0],d=e[t+1],h=e[t+2],p=e[t+3],m=e[t+4],S=e[t+5],g=e[t+6],v=e[t+7],f=e[t+8],E=e[t+9],T=e[t+10],R=e[t+11],b=e[t+12],y=e[t+13],I=e[t+14],C=e[t+15],A=s[0],k=s[1],M=s[2],N=s[3];A=c(A,k,M,N,n,7,a[0]),N=c(N,A,k,M,d,12,a[1]),M=c(M,N,A,k,h,17,a[2]),k=c(k,M,N,A,p,22,a[3]),A=c(A,k,M,N,m,7,a[4]),N=c(N,A,k,M,S,12,a[5]),M=c(M,N,A,k,g,17,a[6]),k=c(k,M,N,A,v,22,a[7]),A=c(A,k,M,N,f,7,a[8]),N=c(N,A,k,M,E,12,a[9]),M=c(M,N,A,k,T,17,a[10]),k=c(k,M,N,A,R,22,a[11]),A=c(A,k,M,N,b,7,a[12]),N=c(N,A,k,M,y,12,a[13]),M=c(M,N,A,k,I,17,a[14]),A=l(A,k=c(k,M,N,A,C,22,a[15]),M,N,d,5,a[16]),N=l(N,A,k,M,g,9,a[17]),M=l(M,N,A,k,R,14,a[18]),k=l(k,M,N,A,n,20,a[19]),A=l(A,k,M,N,S,5,a[20]),N=l(N,A,k,M,T,9,a[21]),M=l(M,N,A,k,C,14,a[22]),k=l(k,M,N,A,m,20,a[23]),A=l(A,k,M,N,E,5,a[24]),N=l(N,A,k,M,I,9,a[25]),M=l(M,N,A,k,p,14,a[26]),k=l(k,M,N,A,f,20,a[27]),A=l(A,k,M,N,y,5,a[28]),N=l(N,A,k,M,h,9,a[29]),M=l(M,N,A,k,v,14,a[30]),A=u(A,k=l(k,M,N,A,b,20,a[31]),M,N,S,4,a[32]),N=u(N,A,k,M,f,11,a[33]),M=u(M,N,A,k,R,16,a[34]),k=u(k,M,N,A,I,23,a[35]),A=u(A,k,M,N,d,4,a[36]),N=u(N,A,k,M,m,11,a[37]),M=u(M,N,A,k,v,16,a[38]),k=u(k,M,N,A,T,23,a[39]),A=u(A,k,M,N,y,4,a[40]),N=u(N,A,k,M,n,11,a[41]),M=u(M,N,A,k,p,16,a[42]),k=u(k,M,N,A,g,23,a[43]),A=u(A,k,M,N,E,4,a[44]),N=u(N,A,k,M,b,11,a[45]),M=u(M,N,A,k,C,16,a[46]),A=_(A,k=u(k,M,N,A,h,23,a[47]),M,N,n,6,a[48]),N=_(N,A,k,M,v,10,a[49]),M=_(M,N,A,k,I,15,a[50]),k=_(k,M,N,A,S,21,a[51]),A=_(A,k,M,N,b,6,a[52]),N=_(N,A,k,M,p,10,a[53]),M=_(M,N,A,k,T,15,a[54]),k=_(k,M,N,A,d,21,a[55]),A=_(A,k,M,N,f,6,a[56]),N=_(N,A,k,M,C,10,a[57]),M=_(M,N,A,k,g,15,a[58]),k=_(k,M,N,A,y,21,a[59]),A=_(A,k,M,N,m,6,a[60]),N=_(N,A,k,M,R,10,a[61]),M=_(M,N,A,k,h,15,a[62]),k=_(k,M,N,A,E,21,a[63]),s[0]=s[0]+A|0,s[1]=s[1]+k|0,s[2]=s[2]+M|0,s[3]=s[3]+N|0},_doFinalize:function(){var e=this._data,i=e.words,r=8*this._nDataBytes,o=8*e.sigBytes;i[o>>>5]|=128<<24-o%32;var s=t.floor(r/4294967296),n=r;i[15+(o+64>>>9<<4)]=16711935&(s<<8|s>>>24)|4278255360&(s<<24|s>>>8),i[14+(o+64>>>9<<4)]=16711935&(n<<8|n>>>24)|4278255360&(n<<24|n>>>8),e.sigBytes=4*(i.length+1),this._process();for(var a=this._hash,d=a.words,c=0;c<4;c++){var l=d[c];d[c]=16711935&(l<<8|l>>>24)|4278255360&(l<<24|l>>>8)}return a},clone:function(){var e=s.clone.call(this);return e._hash=this._hash.clone(),e}});function c(e,t,i,r,o,s,n){var a=e+(t&i|~t&r)+o+n;return(a<<s|a>>>32-s)+t}function l(e,t,i,r,o,s,n){var a=e+(t&r|i&~r)+o+n;return(a<<s|a>>>32-s)+t}function u(e,t,i,r,o,s,n){var a=e+(t^i^r)+o+n;return(a<<s|a>>>32-s)+t}function _(e,t,i,r,o,s,n){var a=e+(i^(t|~r))+o+n;return(a<<s|a>>>32-s)+t}i.MD5=s._createHelper(d),i.HmacMD5=s._createHmacHelper(d)}(Math),e.MD5)),md5.exports;var e}var hasRequiredSha1,evpkdf={exports:{}},sha1={exports:{}};function requireSha1(){return hasRequiredSha1||(hasRequiredSha1=1,sha1.exports=(a=requireCore(),t=(e=a).lib,i=t.WordArray,r=t.Hasher,o=e.algo,s=[],n=o.SHA1=r.extend({_doReset:function(){this._hash=new i.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(e,t){for(var i=this._hash.words,r=i[0],o=i[1],n=i[2],a=i[3],d=i[4],c=0;c<80;c++){if(c<16)s[c]=0|e[t+c];else{var l=s[c-3]^s[c-8]^s[c-14]^s[c-16];s[c]=l<<1|l>>>31}var u=(r<<5|r>>>27)+d+s[c];u+=c<20?1518500249+(o&n|~o&a):c<40?1859775393+(o^n^a):c<60?(o&n|o&a|n&a)-1894007588:(o^n^a)-899497514,d=a,a=n,n=o<<30|o>>>2,o=r,r=u}i[0]=i[0]+r|0,i[1]=i[1]+o|0,i[2]=i[2]+n|0,i[3]=i[3]+a|0,i[4]=i[4]+d|0},_doFinalize:function(){var e=this._data,t=e.words,i=8*this._nDataBytes,r=8*e.sigBytes;return t[r>>>5]|=128<<24-r%32,t[14+(r+64>>>9<<4)]=Math.floor(i/4294967296),t[15+(r+64>>>9<<4)]=i,e.sigBytes=4*t.length,this._process(),this._hash},clone:function(){var e=r.clone.call(this);return e._hash=this._hash.clone(),e}}),e.SHA1=r._createHelper(n),e.HmacSHA1=r._createHmacHelper(n),a.SHA1)),sha1.exports;var e,t,i,r,o,s,n,a}var hasRequiredHmac,hasRequiredEvpkdf,hmac={exports:{}};function requireHmac(){return hasRequiredHmac||(hasRequiredHmac=1,hmac.exports=(e=requireCore(),i=(t=e).lib.Base,r=t.enc.Utf8,void(t.algo.HMAC=i.extend({init:function(e,t){e=this._hasher=new e.init,"string"==typeof t&&(t=r.parse(t));var i=e.blockSize,o=4*i;t.sigBytes>o&&(t=e.finalize(t)),t.clamp();for(var s=this._oKey=t.clone(),n=this._iKey=t.clone(),a=s.words,d=n.words,c=0;c<i;c++)a[c]^=1549556828,d[c]^=909522486;s.sigBytes=n.sigBytes=o,this.reset()},reset:function(){var e=this._hasher;e.reset(),e.update(this._iKey)},update:function(e){return this._hasher.update(e),this},finalize:function(e){var t=this._hasher,i=t.finalize(e);return t.reset(),t.finalize(this._oKey.clone().concat(i))}})))),hmac.exports;var e,t,i,r}function requireEvpkdf(){return hasRequiredEvpkdf||(hasRequiredEvpkdf=1,evpkdf.exports=(a=requireCore(),requireSha1(),requireHmac(),t=(e=a).lib,i=t.Base,r=t.WordArray,o=e.algo,s=o.MD5,n=o.EvpKDF=i.extend({cfg:i.extend({keySize:4,hasher:s,iterations:1}),init:function(e){this.cfg=this.cfg.extend(e)},compute:function(e,t){for(var i,o=this.cfg,s=o.hasher.create(),n=r.create(),a=n.words,d=o.keySize,c=o.iterations;a.length<d;){i&&s.update(i),i=s.update(e).finalize(t),s.reset();for(var l=1;l<c;l++)i=s.finalize(i),s.reset();n.concat(i)}return n.sigBytes=4*d,n}}),e.EvpKDF=function(e,t,i){return n.create(i).compute(e,t)},a.EvpKDF)),evpkdf.exports;var e,t,i,r,o,s,n,a}var hasRequiredCipherCore,cipherCore={exports:{}};function requireCipherCore(){return hasRequiredCipherCore||(hasRequiredCipherCore=1,cipherCore.exports=(e=requireCore(),requireEvpkdf(),void(e.lib.Cipher||function(t){var i=e,r=i.lib,o=r.Base,s=r.WordArray,n=r.BufferedBlockAlgorithm,a=i.enc;a.Utf8;var d=a.Base64,c=i.algo.EvpKDF,l=r.Cipher=n.extend({cfg:o.extend(),createEncryptor:function(e,t){return this.create(this._ENC_XFORM_MODE,e,t)},createDecryptor:function(e,t){return this.create(this._DEC_XFORM_MODE,e,t)},init:function(e,t,i){this.cfg=this.cfg.extend(i),this._xformMode=e,this._key=t,this.reset()},reset:function(){n.reset.call(this),this._doReset()},process:function(e){return this._append(e),this._process()},finalize:function(e){return e&&this._append(e),this._doFinalize()},keySize:4,ivSize:4,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,_createHelper:function(){function e(e){return"string"==typeof e?f:g}return function(t){return{encrypt:function(i,r,o){return e(r).encrypt(t,i,r,o)},decrypt:function(i,r,o){return e(r).decrypt(t,i,r,o)}}}}()});r.StreamCipher=l.extend({_doFinalize:function(){return this._process(!0)},blockSize:1});var u=i.mode={},_=r.BlockCipherMode=o.extend({createEncryptor:function(e,t){return this.Encryptor.create(e,t)},createDecryptor:function(e,t){return this.Decryptor.create(e,t)},init:function(e,t){this._cipher=e,this._iv=t}}),h=u.CBC=function(){var e=_.extend();function i(e,i,r){var o,s=this._iv;s?(o=s,this._iv=t):o=this._prevBlock;for(var n=0;n<r;n++)e[i+n]^=o[n]}return e.Encryptor=e.extend({processBlock:function(e,t){var r=this._cipher,o=r.blockSize;i.call(this,e,t,o),r.encryptBlock(e,t),this._prevBlock=e.slice(t,t+o)}}),e.Decryptor=e.extend({processBlock:function(e,t){var r=this._cipher,o=r.blockSize,s=e.slice(t,t+o);r.decryptBlock(e,t),i.call(this,e,t,o),this._prevBlock=s}}),e}(),p=(i.pad={}).Pkcs7={pad:function(e,t){for(var i=4*t,r=i-e.sigBytes%i,o=r<<24|r<<16|r<<8|r,n=[],a=0;a<r;a+=4)n.push(o);var d=s.create(n,r);e.concat(d)},unpad:function(e){var t=255&e.words[e.sigBytes-1>>>2];e.sigBytes-=t}};r.BlockCipher=l.extend({cfg:l.cfg.extend({mode:h,padding:p}),reset:function(){var e;l.reset.call(this);var t=this.cfg,i=t.iv,r=t.mode;this._xformMode==this._ENC_XFORM_MODE?e=r.createEncryptor:(e=r.createDecryptor,this._minBufferSize=1),this._mode&&this._mode.__creator==e?this._mode.init(this,i&&i.words):(this._mode=e.call(r,this,i&&i.words),this._mode.__creator=e)},_doProcessBlock:function(e,t){this._mode.processBlock(e,t)},_doFinalize:function(){var e,t=this.cfg.padding;return this._xformMode==this._ENC_XFORM_MODE?(t.pad(this._data,this.blockSize),e=this._process(!0)):(e=this._process(!0),t.unpad(e)),e},blockSize:4});var m=r.CipherParams=o.extend({init:function(e){this.mixIn(e)},toString:function(e){return(e||this.formatter).stringify(this)}}),S=(i.format={}).OpenSSL={stringify:function(e){var t=e.ciphertext,i=e.salt;return(i?s.create([1398893684,1701076831]).concat(i).concat(t):t).toString(d)},parse:function(e){var t,i=d.parse(e),r=i.words;return 1398893684==r[0]&&1701076831==r[1]&&(t=s.create(r.slice(2,4)),r.splice(0,4),i.sigBytes-=16),m.create({ciphertext:i,salt:t})}},g=r.SerializableCipher=o.extend({cfg:o.extend({format:S}),encrypt:function(e,t,i,r){r=this.cfg.extend(r);var o=e.createEncryptor(i,r),s=o.finalize(t),n=o.cfg;return m.create({ciphertext:s,key:i,iv:n.iv,algorithm:e,mode:n.mode,padding:n.padding,blockSize:e.blockSize,formatter:r.format})},decrypt:function(e,t,i,r){return r=this.cfg.extend(r),t=this._parse(t,r.format),e.createDecryptor(i,r).finalize(t.ciphertext)},_parse:function(e,t){return"string"==typeof e?t.parse(e,this):e}}),v=(i.kdf={}).OpenSSL={execute:function(e,t,i,r,o){if(r||(r=s.random(8)),o)n=c.create({keySize:t+i,hasher:o}).compute(e,r);else var n=c.create({keySize:t+i}).compute(e,r);var a=s.create(n.words.slice(t),4*i);return n.sigBytes=4*t,m.create({key:n,iv:a,salt:r})}},f=r.PasswordBasedCipher=g.extend({cfg:g.cfg.extend({kdf:v}),encrypt:function(e,t,i,r){var o=(r=this.cfg.extend(r)).kdf.execute(i,e.keySize,e.ivSize,r.salt,r.hasher);r.iv=o.iv;var s=g.encrypt.call(this,e,t,o.key,r);return s.mixIn(o),s},decrypt:function(e,t,i,r){r=this.cfg.extend(r),t=this._parse(t,r.format);var o=r.kdf.execute(i,e.keySize,e.ivSize,t.salt,r.hasher);return r.iv=o.iv,g.decrypt.call(this,e,t,o.key,r)}})}()))),cipherCore.exports;var e}!function(){var e;aes.exports=(e=requireCore(),requireEncBase64(),requireMd5(),requireEvpkdf(),requireCipherCore(),function(){var t=e,i=t.lib.BlockCipher,r=t.algo,o=[],s=[],n=[],a=[],d=[],c=[],l=[],u=[],_=[],h=[];!function(){for(var e=[],t=0;t<256;t++)e[t]=t<128?t<<1:t<<1^283;var i=0,r=0;for(t=0;t<256;t++){var p=r^r<<1^r<<2^r<<3^r<<4;p=p>>>8^255&p^99,o[i]=p,s[p]=i;var m=e[i],S=e[m],g=e[S],v=257*e[p]^16843008*p;n[i]=v<<24|v>>>8,a[i]=v<<16|v>>>16,d[i]=v<<8|v>>>24,c[i]=v,v=16843009*g^65537*S^257*m^16843008*i,l[p]=v<<24|v>>>8,u[p]=v<<16|v>>>16,_[p]=v<<8|v>>>24,h[p]=v,i?(i=m^e[e[e[g^m]]],r^=e[e[r]]):i=r=1}}();var p=[0,1,2,4,8,16,32,64,128,27,54],m=r.AES=i.extend({_doReset:function(){if(!this._nRounds||this._keyPriorReset!==this._key){for(var e=this._keyPriorReset=this._key,t=e.words,i=e.sigBytes/4,r=4*((this._nRounds=i+6)+1),s=this._keySchedule=[],n=0;n<r;n++)n<i?s[n]=t[n]:(c=s[n-1],n%i?i>6&&n%i==4&&(c=o[c>>>24]<<24|o[c>>>16&255]<<16|o[c>>>8&255]<<8|o[255&c]):(c=o[(c=c<<8|c>>>24)>>>24]<<24|o[c>>>16&255]<<16|o[c>>>8&255]<<8|o[255&c],c^=p[n/i|0]<<24),s[n]=s[n-i]^c);for(var a=this._invKeySchedule=[],d=0;d<r;d++){if(n=r-d,d%4)var c=s[n];else c=s[n-4];a[d]=d<4||n<=4?c:l[o[c>>>24]]^u[o[c>>>16&255]]^_[o[c>>>8&255]]^h[o[255&c]]}}},encryptBlock:function(e,t){this._doCryptBlock(e,t,this._keySchedule,n,a,d,c,o)},decryptBlock:function(e,t){var i=e[t+1];e[t+1]=e[t+3],e[t+3]=i,this._doCryptBlock(e,t,this._invKeySchedule,l,u,_,h,s),i=e[t+1],e[t+1]=e[t+3],e[t+3]=i},_doCryptBlock:function(e,t,i,r,o,s,n,a){for(var d=this._nRounds,c=e[t]^i[0],l=e[t+1]^i[1],u=e[t+2]^i[2],_=e[t+3]^i[3],h=4,p=1;p<d;p++){var m=r[c>>>24]^o[l>>>16&255]^s[u>>>8&255]^n[255&_]^i[h++],S=r[l>>>24]^o[u>>>16&255]^s[_>>>8&255]^n[255&c]^i[h++],g=r[u>>>24]^o[_>>>16&255]^s[c>>>8&255]^n[255&l]^i[h++],v=r[_>>>24]^o[c>>>16&255]^s[l>>>8&255]^n[255&u]^i[h++];c=m,l=S,u=g,_=v}m=(a[c>>>24]<<24|a[l>>>16&255]<<16|a[u>>>8&255]<<8|a[255&_])^i[h++],S=(a[l>>>24]<<24|a[u>>>16&255]<<16|a[_>>>8&255]<<8|a[255&c])^i[h++],g=(a[u>>>24]<<24|a[_>>>16&255]<<16|a[c>>>8&255]<<8|a[255&l])^i[h++],v=(a[_>>>24]<<24|a[c>>>16&255]<<16|a[l>>>8&255]<<8|a[255&u])^i[h++],e[t]=m,e[t+1]=S,e[t+2]=g,e[t+3]=v},keySize:8});t.AES=i._createHelper(m)}(),e.AES)}();var aesExports=aes.exports,encHex$1={exports:{}};encHex$1.exports=requireCore().enc.Hex;var encHexExports=encHex$1.exports,encHex=getDefaultExportFromCjs(encHexExports),modeCtr={exports:{}};!function(){var e,t,i;modeCtr.exports=(i=requireCore(),requireCipherCore(),i.mode.CTR=(e=i.lib.BlockCipherMode.extend(),t=e.Encryptor=e.extend({processBlock:function(e,t){var i=this._cipher,r=i.blockSize,o=this._iv,s=this._counter;o&&(s=this._counter=o.slice(0),this._iv=void 0);var n=s.slice(0);i.encryptBlock(n,0),s[r-1]=s[r-1]+1|0;for(var a=0;a<r;a++)e[t+a]^=n[a]}}),e.Decryptor=t,e),i.mode.CTR)}();var modeCtrExports=modeCtr.exports,ModeCTR=getDefaultExportFromCjs(modeCtrExports),padNopadding={exports:{}};!function(){var e;padNopadding.exports=(e=requireCore(),requireCipherCore(),e.pad.NoPadding={pad:function(){},unpad:function(){}},e.pad.NoPadding)}();var padNopaddingExports=padNopadding.exports,PadNoPadding=getDefaultExportFromCjs(padNopaddingExports);const textDecoder=new TextDecoder,textEncoder=new TextEncoder;let gpuInfo;const genUuid=()=>v4(),getServerNow=()=>Date.now();function concatenate(e,...t){let i=0;for(const e of t)i+=e.length;const r=new e(i);let o=0;for(const e of t)r.set(e,o),o+=e.length;return r}class Utils{static token2auth(e,t,i,r){return r?`Bearer ${r}`:`Basic ${Utils.createUnsafeToken(e,t,i)}`}static createUnsafeToken(e,t,i){return window.btoa([e,t,i].filter((e=>null!==e)).join(":"))}static merge(e={},t={}){for(const[i,r]of Object.entries(e))null!==r&&"object"==typeof r?Utils.merge(e[i],t[i]):void 0!==t[i]&&(e[i]=t[i])}static ab2str(e){return textDecoder.decode(e)}static ab2obj(e){try{const t=Utils.ab2str(e);return JSON.parse(t)}catch(e){return{}}}static str2ab(e){return textEncoder.encode(e).buffer}static async ab2b64str(e){if(getParameter("SEND_MESSAGE_SYNC")){const t=String.fromCharCode.apply(null,new Uint8Array(e));return window.btoa(t)}return(await new Promise((t=>{const i=new FileReader;i.onload=()=>t(i.result),i.readAsDataURL(new Blob([e]))}))).split(",",2)[1]}static async b64str2ab(e,t){return fetch(`data:application/octet;base64,${e}`).then((e=>e.arrayBuffer())).catch((i=>{throw t&&t.report("rtc_error",{error_code:2001,message:`${i.message} -> ${e}`}),i}))}}function wait(e){return new Promise((t=>{setTimeout(t,e)}))}function createRandomId(){const e=Number(`${Math.random()}`.slice(-7).padEnd(7,"0")).toString(2).padEnd(28,"1").split(""),t=[];for(;e.length;)t.push(e.splice(0,7));return t.map(((e,i)=>{const r=i===t.length-1?"0":"1";return Number.parseInt(r+e.join(""),2)}))}const genEventSessionId=()=>Math.floor(65535*Math.random());function isByteId(e){return!(128&~e)}function isRttMessage(e){return"string"==typeof e&&e.indexOf("__web__rtc__rtt__")>-1}function randomNum(e){let t="";for(let i=0;i<e;i++)t+=Math.floor(10*Math.random());return t}let defaultSdp;const createDefaultSdp=async(e=!1)=>{if(defaultSdp)return defaultSdp;const t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan"});t.createDataChannel("default"),t.addTransceiver("audio",{direction:"recvonly"}),t.addTransceiver("video",{direction:"recvonly"}),e&&(t.addTransceiver("audio",{direction:"sendonly"}),t.addTransceiver("video",{direction:"sendonly"}));const i=await t.createOffer();return t.close(),defaultSdp=i.sdp,i.sdp},promiseAny=e=>new Promise(((t,i)=>{let r=(e=Array.isArray(e)?e:[]).length;const o=[];0===r?i([]):e.forEach((e=>{e.then((e=>{t(e)}),(e=>{r--,o.push(e),0===r&&i(o)}))}))}));function getNonlinearVolume(e){return Number(Math.max(-127,10*Math.log10(Math.pow(e/255,2))).toFixed(2))}function audioInMediaType(e){return(e&MediaType$1.AUDIO)===MediaType$1.AUDIO}function videoInMediaType(e){return(e&MediaType$1.VIDEO)===MediaType$1.VIDEO}function getPublicStats(e){const t={};return Object.keys(e).forEach((i=>{"object"==typeof e[i]?t[i]=getPublicStats(e[i]):i.startsWith("_")&&!getParameter("HIDDEN_STATS")||(t[i]=e[i])})),t}function splitPublicStreamSei(e){const t=new DataView(e.buffer);if(t.byteLength<=4||65535!==t.getUint16(0))return{seiCount:1,seis:[e]};const i={seiCount:0,seis:[]};let r=!1,o=2;for(;o<t.byteLength;){const s=t.getUint16(o);if(o+=2,t.byteLength-o<s){r=!0;break}const n=new Uint8Array(e.buffer,o,s);if(o+=s,t.byteLength-o>0&&t.byteLength-o<=2){r=!0;break}i.seiCount++,i.seis.push(n)}return r&&(i.seiCount=1,i.seis=[e]),i}function isUndefined(e){return void 0===e}function warnDeprecatedApi(e){return function(t,i,r){const o=r.value;r.value=function(...t){return console.warn(`[RTC WebSDK]: Api: ${i} has been abandoned from version ${e}`),o.apply(this,t)}}}function warnDevelopers(e){console.warn(`[RTC WebSDK]: ${e}`)}function constraints2number(e){return"number"==typeof e?e:"number"==typeof(null==e?void 0:e.exact)?e.exact:"number"==typeof(null==e?void 0:e.ideal)?e.ideal:"number"==typeof(null==e?void 0:e.max)?e.max:"number"==typeof(null==e?void 0:e.min)?e.min:1}function setJoinRoomInfo(e,t,i){if("function"==typeof i.value){const e=i.value;i.value=function(...t){var i;const r=getMonitor(this.id);return null==r||r.set({room_id:t[1],user_id:null==(i=t[2])?void 0:i.userId}),e.apply(this,t)}}}const MAX_MESSAGE_ID=Math.pow(2,15);class MessageId{constructor(){__publicField(this,"_id"),this._id=Math.ceil(Math.random()*MAX_MESSAGE_ID)}getMessageId(){return++this._id>MAX_MESSAGE_ID&&(this._id=0),this._id}}function filterUndefined(e){const t={};return Object.keys(e).forEach((i=>{void 0!==e[i]&&(t[i]=e[i])})),t}const isDebuggerMode="undefined"!=typeof window&&(window.location.search.includes("_rtc_debug_")||!!(null==(_j=window.localStorage)?void 0:_j.getItem("_rtc_debug_")));function base64ToUint8(e){const t=atob(e),i=t.length,r=new Uint8Array(i);for(let e=0;e<i;e++)r[e]=t.charCodeAt(e);return r}function uint8ToBase64(e){let t="";const i=e.byteLength;for(let r=0;r<i;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function aesCtrEncrypt(e,t,i){const r=uint8ArrayToWordArray(e),o=uint8ArrayToWordArray(t),s=uint8ArrayToWordArray(i);return wordArrayToUint8Array(aesExports.encrypt(r,o,{iv:s,mode:ModeCTR,padding:PadNoPadding}).ciphertext)}function wordArrayToUint8Array(e){const t=e.toString(encHex),i=new Uint8Array(t.length/2);for(let e=0;e<t.length;e+=2)i[e/2]=parseInt(t.substr(e,2),16);return i}function uint8ArrayToWordArray(e){const t=[];for(let i=0;i<e.length;i+=4)t.push(e[i]<<24|(e[i+1]||0)<<16|(e[i+2]||0)<<8|(e[i+3]||0));return WordArray.create(t,e.length)}function getGpuInfo(){return gpuInfo||(gpuInfo=_getGpuInfo()),gpuInfo}function _getGpuInfo(){let e=document.createElement("canvas"),t=e.getContext("webgl")||e.getContext("experimental-webgl");if(!t)return{renderer:"unknown(WebGLRenderingContext not existed)",vendor:"unknown(WebGLRenderingContext not existed)"};const i=t.getExtension("WEBGL_debug_renderer_info");if(!i)return{renderer:"unknown(info not existed)",vendor:"unknown(info not existed)"};const r=t.getParameter(i.UNMASKED_RENDERER_WEBGL),o=t.getParameter(i.UNMASKED_VENDOR_WEBGL);return e&&e.parentNode&&e.parentNode.removeChild(e),e=void 0,t=void 0,{renderer:r,vendor:o}}function getErrorString(e){var t,i;return e instanceof Error&&e.code?`${e} | native.name=${null==(t=e.error)?void 0:t.name} native.message=${null==(i=e.error)?void 0:i.message}`:e instanceof Error?`NativeError: ${e.name} ${e.message}`:`UnknownError: ${e}`}const throttle=function(e,t,i={leading:!0,trailing:!0}){let r,o,s,n,a=0;function d(){a=!1===(null==i?void 0:i.leading)?0:Date.now(),r=null,n=e.apply(o,s),r||(o=null,s=null)}return function(...c){const l=Date.now();a||!1!==(null==i?void 0:i.leading)||(a=l);const u=t-(l-a);return o=this,s=c,u<=0||u>t?(r&&(clearTimeout(r),r=null),a=l,n=e.apply(o,s),r||(o=null,s=null)):r||!1===(null==i?void 0:i.trailing)||(r=setTimeout(d,u)),n}},detectorResults={};function getObjectFunctions(e,t){if(!e)return[];return Object.getOwnPropertyNames(e).filter((t=>{if("peerIdentity"===t)return!1;try{return"function"==typeof e[t]||void 0===e[t]}catch{return!1}})).map((i=>({obj:e,prefix:t,attr:i})))}function isNativeCode(e,t){try{return e[t].toString().includes("[native code]")?"native":"non-native"}catch(e){return"untouchable"}}const detectorList=("undefined"!=typeof window?[[null==(_k=window.RTCPeerConnection)?void 0:_k.prototype,"RTCPeerConnection.prototype"],[window.RTCPeerConnection,"RTCPeerConnection"],[null==(_l=window.RTCDataChannel)?void 0:_l.prototype,"RTCDataChannel.prototype"],[window.RTCDataChannel,"RTCDataChannel"],[null==(_m=window.MediaStreamTrack)?void 0:_m.prototype,"MediaStreamTrack.prototype"],[window.MediaStreamTrack,"MediaStreamTrack"],[null==(_n=window.MediaStream)?void 0:_n.prototype,"MediaStream.prototype"],[window.MediaStream,"MediaStream"],[null==(_o=window.HTMLAudioElement)?void 0:_o.prototype,"HTMLAudioElement.prototype"],[null==(_p=window.HTMLVideoElement)?void 0:_p.prototype,"HTMLVideoElement.prototype"],[null==(_q=window.HTMLMediaElement)?void 0:_q.prototype,"HTMLMediaElement.prototype"],[(null==(_r=window.AudioContext)?void 0:_r.prototype)??(null==(_s=window.webkitAudioContext)?void 0:_s.prototype),"AudioContext.prototype"],[null==(_t=window.BaseAudioContext)?void 0:_t.prototype,"BaseAudioContext.prototype"],[null==(_u=window.AudioNode)?void 0:_u.prototype,"AudioNode.prototype"],[window.navigator.mediaDevices,"navigator.mediaDevices"],[window.console,"console"]]:[]).reduce(((e,[t,i])=>e.concat(getObjectFunctions(t,i))),[]);"undefined"!=typeof window&&detectorList.push({obj:window.navigator.mediaDevices,prefix:"navigator.mediaDevices",attr:"getUserMedia"},{obj:window.navigator.mediaDevices,prefix:"navigator.mediaDevices",attr:"getDisplayMedia"},{obj:window.navigator.mediaDevices,prefix:"navigator.mediaDevices",attr:"enumerateDevices"},{obj:window.navigator.mediaDevices,prefix:"navigator.mediaDevices",attr:"getSupportedConstraints"});for(const{obj:e,prefix:t,attr:i}of detectorList){detectorResults[`${t}.${i}`]=isNativeCode(e,i)}isDebuggerMode&&console.log("RTC_AMBULANCE",detectorResults);const filtedResult=Object.entries(detectorResults).filter((([e,t])=>"non-native"===t)).map((([e,t])=>e));Object.keys(filtedResult).length&&console.warn("RTC_AMBULANCE","have non-native code:\n",filtedResult.join("\n"));let logDisabled_=!0,deprecationWarnings_=!0;function extractVersion(e,t,i){const r=e.match(t);return r&&r.length>=i&&parseInt(r[i],10)}function wrapPeerConnectionEvent(e,t,i){if(!e.RTCPeerConnection)return;const r=e.RTCPeerConnection.prototype,o=r.addEventListener;r.addEventListener=function(e,r){if(e!==t)return o.apply(this,arguments);const s=e=>{const t=i(e);t&&(r.handleEvent?r.handleEvent(t):r(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(r,s),o.apply(this,[e,s])};const s=r.removeEventListener;r.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t])return s.apply(this,arguments);if(!this._eventMap[t].has(i))return s.apply(this,arguments);const r=this._eventMap[t].get(i);return this._eventMap[t].delete(i),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,s.apply(this,[e,r])},Object.defineProperty(r,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function disableLog(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(logDisabled_=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function disableWarnings(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(deprecationWarnings_=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function log(){if("object"==typeof window){if(logDisabled_)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function deprecated(e,t){deprecationWarnings_&&console.warn(e+" is deprecated, please use "+t+" instead.")}function detectBrowser(e){const t={browser:null,version:null};if(void 0===e||!e.navigator||!e.navigator.userAgent)return t.browser="Not a browser.",t;const{navigator:i}=e;if(i.mozGetUserMedia)t.browser="firefox",t.version=extractVersion(i.userAgent,/Firefox\/(\d+)\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=extractVersion(i.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else{if(!e.RTCPeerConnection||!i.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=extractVersion(i.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}function isObject(e){return"[object Object]"===Object.prototype.toString.call(e)}function compactObject(e){return isObject(e)?Object.keys(e).reduce((function(t,i){const r=isObject(e[i]),o=r?compactObject(e[i]):e[i],s=r&&!Object.keys(o).length;return void 0===o||s?t:Object.assign(t,{[i]:o})}),{}):e}function walkStats(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach((r=>{r.endsWith("Id")?walkStats(e,e.get(t[r]),i):r.endsWith("Ids")&&t[r].forEach((t=>{walkStats(e,e.get(t),i)}))})))}function filterStats(e,t,i){const r=i?"outbound-rtp":"inbound-rtp",o=new Map;if(null===t)return o;const s=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&s.push(e)})),s.forEach((t=>{e.forEach((i=>{i.type===r&&i.trackId===t.id&&walkStats(e,i,o)}))})),o}const logging=log;function shimGetUserMedia$2(e,t){const i=e&&e.navigator;if(!i.mediaDevices)return;const r=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((i=>{if("require"===i||"advanced"===i||"mediaSource"===i)return;const r="object"==typeof e[i]?e[i]:{ideal:e[i]};void 0!==r.exact&&"number"==typeof r.exact&&(r.min=r.max=r.exact);const o=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==r.ideal){t.optional=t.optional||[];let e={};"number"==typeof r.ideal?(e[o("min",i)]=r.ideal,t.optional.push(e),e={},e[o("max",i)]=r.ideal,t.optional.push(e)):(e[o("",i)]=r.ideal,t.optional.push(e))}void 0!==r.exact&&"number"!=typeof r.exact?(t.mandatory=t.mandatory||{},t.mandatory[o("",i)]=r.exact):["min","max"].forEach((e=>{void 0!==r[e]&&(t.mandatory=t.mandatory||{},t.mandatory[o(e,i)]=r[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},o=function(e,o){if(t.version>=61)return o(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=r(e.audio)}if(e&&"object"==typeof e.video){let s=e.video.facingMode;s=s&&("object"==typeof s?s:{ideal:s});const n=t.version<66;if(s&&("user"===s.exact||"environment"===s.exact||"user"===s.ideal||"environment"===s.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||n)){let t;if(delete e.video.facingMode,"environment"===s.exact||"environment"===s.ideal?t=["back","rear"]:"user"!==s.exact&&"user"!==s.ideal||(t=["front"]),t)return i.mediaDevices.enumerateDevices().then((i=>{let n=(i=i.filter((e=>"videoinput"===e.kind))).find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!n&&i.length&&t.includes("back")&&(n=i[i.length-1]),n&&(e.video.deviceId=s.exact?{exact:n.deviceId}:{ideal:n.deviceId}),e.video=r(e.video),logging("chrome: "+JSON.stringify(e)),o(e)}))}e.video=r(e.video)}return logging("chrome: "+JSON.stringify(e)),o(e)},s=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(i.getUserMedia=function(e,t,r){o(e,(e=>{i.webkitGetUserMedia(e,t,(e=>{r&&r(s(e))}))}))}.bind(i),i.mediaDevices.getUserMedia){const e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(t){return o(t,(t=>e(t).then((e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach((e=>{e.stop()})),new DOMException("","NotFoundError");return e}),(e=>Promise.reject(s(e))))))}}}function shimGetDisplayMedia$1(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&("function"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function(i){return t(i).then((t=>{const r=i.video&&i.video.width,o=i.video&&i.video.height,s=i.video&&i.video.frameRate;return i.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:s||3}},r&&(i.video.mandatory.maxWidth=r),o&&(i.video.mandatory.maxHeight=o),e.navigator.mediaDevices.getUserMedia(i)}))}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}function shimMediaStream(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function shimOnTrack$1(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",(i=>{let r;r=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.track.id)):{track:i.track};const o=new Event("track");o.track=i.track,o.receiver=r,o.transceiver={receiver:r},o.streams=[t.stream],this.dispatchEvent(o)})),t.stream.getTracks().forEach((i=>{let r;r=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.id)):{track:i};const o=new Event("track");o.track=i,o.receiver=r,o.transceiver={receiver:r},o.streams=[t.stream],this.dispatchEvent(o)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else wrapPeerConnectionEvent(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function shimGetSendersWithDtmf(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const i=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,r){let o=i.apply(this,arguments);return o||(o=t(this,e),this._senders.push(o)),o};const r=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){r.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(t(this,e))}))};const r=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],r.apply(this,[e]),e.getTracks().forEach((e=>{const t=this._senders.find((t=>t.track===e));t&&this._senders.splice(this._senders.indexOf(t),1)}))}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function shimGetStats(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,i,r]=arguments;if(arguments.length>0&&"function"==typeof e)return t.apply(this,arguments);if(0===t.length&&(0===arguments.length||"function"!=typeof e))return t.apply(this,[]);const o=function(e){const t={};return e.result().forEach((e=>{const i={id:e.id,timestamp:e.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type};e.names().forEach((t=>{i[t]=e.stat(t)})),t[i.id]=i})),t},s=function(e){return new Map(Object.keys(e).map((t=>[t,e[t]])))};if(arguments.length>=2){const r=function(e){i(s(o(e)))};return t.apply(this,[r,e])}return new Promise(((e,i)=>{t.apply(this,[function(t){e(s(o(t)))},i])})).then(i,r)}}function shimSenderReceiverGetStats(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>filterStats(t,e.track,!0)))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),wrapPeerConnectionEvent(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>filterStats(t,e.track,!1)))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,i,r;return this.getSenders().forEach((i=>{i.track===e&&(t?r=!0:t=i)})),this.getReceivers().forEach((t=>(t.track===e&&(i?r=!0:i=t),t.track===e))),r||t&&i?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():i?i.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function shimAddTrackRemoveTrackWithNative(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((e=>this._shimmedLocalStreams[e][0]))};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){if(!i)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const r=t.apply(this,arguments);return this._shimmedLocalStreams[i.id]?-1===this._shimmedLocalStreams[i.id].indexOf(r)&&this._shimmedLocalStreams[i.id].push(r):this._shimmedLocalStreams[i.id]=[i,r],r};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")}));const t=this.getSenders();i.apply(this,arguments);const r=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(r)};const r=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],r.apply(this,arguments)};const o=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const i=this._shimmedLocalStreams[t].indexOf(e);-1!==i&&this._shimmedLocalStreams[t].splice(i,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),o.apply(this,arguments)}}function shimAddTrackRemoveTrack(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return shimAddTrackRemoveTrackWithNative(e);const i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=i.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){const i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i}r.apply(this,[t])};const o=e.RTCPeerConnection.prototype.removeStream;function s(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const r=e._reverseStreams[t],o=e._streams[r.id];i=i.replace(new RegExp(o.id,"g"),r.id)})),new RTCSessionDescription({type:t.type,sdp:i})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},o.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,i){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const r=[].slice.call(arguments,1);if(1!==r.length||!r[0].getTracks().find((e=>e===t)))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find((e=>e.track===t)))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const o=this._streams[i.id];if(o)o.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const r=new e.MediaStream([t]);this._streams[i.id]=r,this._reverseStreams[r.id]=i,this.addStream(r)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],r={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?i.apply(this,[t=>{const i=s(this,t);e[0].apply(null,[i])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):i.apply(this,arguments).then((e=>s(this,e)))}};e.RTCPeerConnection.prototype[t]=r[t]}));const n=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const r=e._reverseStreams[t],o=e._streams[r.id];i=i.replace(new RegExp(r.id,"g"),o.id)})),new RTCSessionDescription({type:t.type,sdp:i})}(this,arguments[0]),n.apply(this,arguments)):n.apply(this,arguments)};const a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=a.get.apply(this);return""===e.type?e:s(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(e._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach((i=>{this._streams[i].getTracks().find((t=>e.track===t))&&(t=this._streams[i])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function shimPeerConnection$1(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],r={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=r[t]}))}function fixNegotiationNeeded(e,t){wrapPeerConnectionEvent(e,"negotiationneeded",(e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e}))}var chromeShim=Object.freeze({__proto__:null,fixNegotiationNeeded:fixNegotiationNeeded,shimAddTrackRemoveTrack:shimAddTrackRemoveTrack,shimAddTrackRemoveTrackWithNative:shimAddTrackRemoveTrackWithNative,shimGetDisplayMedia:shimGetDisplayMedia$1,shimGetSendersWithDtmf:shimGetSendersWithDtmf,shimGetStats:shimGetStats,shimGetUserMedia:shimGetUserMedia$2,shimMediaStream:shimMediaStream,shimOnTrack:shimOnTrack$1,shimPeerConnection:shimPeerConnection$1,shimSenderReceiverGetStats:shimSenderReceiverGetStats});function shimGetUserMedia$1(e,t){const i=e&&e.navigator,r=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,r){deprecated("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),i.mediaDevices.getUserMedia(e).then(t,r)},!(t.version>55&&"autoGainControl"in i.mediaDevices.getSupportedConstraints())){const e=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])},t=i.mediaDevices.getUserMedia.bind(i.mediaDevices);if(i.mediaDevices.getUserMedia=function(i){return"object"==typeof i&&"object"==typeof i.audio&&(i=JSON.parse(JSON.stringify(i)),e(i.audio,"autoGainControl","mozAutoGainControl"),e(i.audio,"noiseSuppression","mozNoiseSuppression")),t(i)},r&&r.prototype.getSettings){const t=r.prototype.getSettings;r.prototype.getSettings=function(){const i=t.apply(this,arguments);return e(i,"mozAutoGainControl","autoGainControl"),e(i,"mozNoiseSuppression","noiseSuppression"),i}}if(r&&r.prototype.applyConstraints){const t=r.prototype.applyConstraints;r.prototype.applyConstraints=function(i){return"audio"===this.kind&&"object"==typeof i&&(i=JSON.parse(JSON.stringify(i)),e(i,"autoGainControl","mozAutoGainControl"),e(i,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[i])}}}}function shimGetDisplayMedia(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(i){if(!i||!i.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===i.video?i.video={mediaSource:t}:i.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(i)})}function shimOnTrack(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function shimPeerConnection(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],r={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=r[t]}));const i={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},r=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,o,s]=arguments;return r.apply(this,[e||null]).then((e=>{if(t.version<53&&!o)try{e.forEach((e=>{e.type=i[e.type]||e.type}))}catch(t){if("TypeError"!==t.name)throw t;e.forEach(((t,r)=>{e.set(r,Object.assign({},t,{type:i[t.type]||t.type}))}))}return e})).then(o,s)}}function shimSenderGetStats(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function shimReceiverGetStats(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),wrapPeerConnectionEvent(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function shimRemoveStream(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){deprecated("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function shimRTCDataChannel(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function shimAddTransceiver(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const i=e.length>0;i&&e.forEach((e=>{if("rid"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));const r=t.apply(this,arguments);if(i){const{sender:t}=r,i=t.getParameters();(!("encodings"in i)||1===i.encodings.length&&0===Object.keys(i.encodings[0]).length)&&(i.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(i).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return r})}function shimGetParameters(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function shimCreateOffer(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}function shimCreateAnswer(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}var firefoxShim=Object.freeze({__proto__:null,shimAddTransceiver:shimAddTransceiver,shimCreateAnswer:shimCreateAnswer,shimCreateOffer:shimCreateOffer,shimGetDisplayMedia:shimGetDisplayMedia,shimGetParameters:shimGetParameters,shimGetUserMedia:shimGetUserMedia$1,shimOnTrack:shimOnTrack,shimPeerConnection:shimPeerConnection,shimRTCDataChannel:shimRTCDataChannel,shimReceiverGetStats:shimReceiverGetStats,shimRemoveStream:shimRemoveStream,shimSenderGetStats:shimSenderGetStats});function shimLocalStreamsAPI(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach((i=>t.call(this,i,e))),e.getVideoTracks().forEach((i=>t.call(this,i,e)))},e.RTCPeerConnection.prototype.addTrack=function(e,...i){return i&&i.forEach((e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]})),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const i=e.getTracks();this.getSenders().forEach((e=>{i.includes(e.track)&&this.removeTrack(e)}))})}}function shimRemoteStreamsAPI(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach((e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t)}))})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach((t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const i=new Event("addstream");i.stream=t,e.dispatchEvent(i)}))}),t.apply(e,arguments)}}}function shimCallbacksAPI(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,i=t.createOffer,r=t.createAnswer,o=t.setLocalDescription,s=t.setRemoteDescription,n=t.addIceCandidate;t.createOffer=function(e,t){const r=arguments.length>=2?arguments[2]:arguments[0],o=i.apply(this,[r]);return t?(o.then(e,t),Promise.resolve()):o},t.createAnswer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],o=r.apply(this,[i]);return t?(o.then(e,t),Promise.resolve()):o};let a=function(e,t,i){const r=o.apply(this,[e]);return i?(r.then(t,i),Promise.resolve()):r};t.setLocalDescription=a,a=function(e,t,i){const r=s.apply(this,[e]);return i?(r.then(t,i),Promise.resolve()):r},t.setRemoteDescription=a,a=function(e,t,i){const r=n.apply(this,[e]);return i?(r.then(t,i),Promise.resolve()):r},t.addIceCandidate=a}function shimGetUserMedia(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,i=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>i(shimConstraints(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,r){t.mediaDevices.getUserMedia(e).then(i,r)}.bind(t))}function shimConstraints(e){return e&&void 0!==e.video?Object.assign({},e,{video:compactObject(e.video)}):e}function shimRTCIceServerUrls(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,i){if(e&&e.iceServers){const t=[];for(let i=0;i<e.iceServers.length;i++){let r=e.iceServers[i];void 0===r.urls&&r.url?(deprecated("RTCIceServer.url","RTCIceServer.urls"),r=JSON.parse(JSON.stringify(r)),r.urls=r.url,delete r.url,t.push(r)):t.push(e.iceServers[i])}e.iceServers=t}return new t(e,i)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function shimTrackEventTransceiver(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function shimCreateOfferLegacy(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find((e=>"audio"===e.receiver.track.kind));!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const i=this.getTransceivers().find((e=>"video"===e.receiver.track.kind));!1===e.offerToReceiveVideo&&i?"sendrecv"===i.direction?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":"recvonly"===i.direction&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):!0!==e.offerToReceiveVideo||i||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function shimAudioContext(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var safariShim=Object.freeze({__proto__:null,shimAudioContext:shimAudioContext,shimCallbacksAPI:shimCallbacksAPI,shimConstraints:shimConstraints,shimCreateOfferLegacy:shimCreateOfferLegacy,shimGetUserMedia:shimGetUserMedia,shimLocalStreamsAPI:shimLocalStreamsAPI,shimRTCIceServerUrls:shimRTCIceServerUrls,shimRemoteStreamsAPI:shimRemoteStreamsAPI,shimTrackEventTransceiver:shimTrackEventTransceiver}),sdp$1={exports:{}};!function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((e=>e.trim()))},t.splitSections=function(e){return e.split("\nm=").map(((e,t)=>(t>0?"m="+e:e).trim()+"\r\n"))},t.getDescription=function(e){const i=t.splitSections(e);return i&&i[0]},t.getMediaSections=function(e){const i=t.splitSections(e);return i.shift(),i},t.matchPrefix=function(e,i){return t.splitLines(e).filter((e=>0===e.indexOf(i)))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const i={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let e=8;e<t.length;e+=2)switch(t[e]){case"raddr":i.relatedAddress=t[e+1];break;case"rport":i.relatedPort=parseInt(t[e+1],10);break;case"tcptype":i.tcpType=t[e+1];break;case"ufrag":i.ufrag=t[e+1],i.usernameFragment=t[e+1];break;default:void 0===i[t[e]]&&(i[t[e]]=t[e+1])}return i},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const i=e.component;"rtp"===i?t.push(1):"rtcp"===i?t.push(2):t.push(i),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const r=e.type;return t.push("typ"),t.push(r),"host"!==r&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substring(14).split(" ")},t.parseRtpMap=function(e){let t=e.substring(9).split(" ");const i={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),i.name=t[0],i.clockRate=parseInt(t[1],10),i.channels=3===t.length?parseInt(t[2],10):1,i.numChannels=i.channels,i},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const i=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==i?"/"+i:"")+"\r\n"},t.parseExtmap=function(e){const t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let i;const r=e.substring(e.indexOf(" ")+1).split(";");for(let e=0;e<r.length;e++)i=r[e].trim().split("="),t[i[0].trim()]=i[1];return t},t.writeFmtp=function(e){let t="",i=e.payloadType;if(void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const r=[];Object.keys(e.parameters).forEach((t=>{void 0!==e.parameters[t]?r.push(t+"="+e.parameters[t]):r.push(t)})),t+="a=fmtp:"+i+" "+r.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",i=e.payloadType;return void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((e=>{t+="a=rtcp-fb:"+i+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),i={ssrc:parseInt(e.substring(7,t),10)},r=e.indexOf(":",t);return r>-1?(i.attribute=e.substring(t+1,r),i.value=e.substring(r+1)):i.attribute=e.substring(t+1),i},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((e=>parseInt(e,10)))}},t.getMid=function(e){const i=t.matchPrefix(e,"a=mid:")[0];if(i)return i.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,i){return{role:"auto",fingerprints:t.matchPrefix(e+i,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let i="a=setup:"+t+"\r\n";return e.fingerprints.forEach((e=>{i+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),i},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,i){return t.matchPrefix(e+i,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,i){const r=t.matchPrefix(e+i,"a=ice-ufrag:")[0],o=t.matchPrefix(e+i,"a=ice-pwd:")[0];return r&&o?{usernameFragment:r.substring(12),password:o.substring(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},r=t.splitLines(e)[0].split(" ");i.profile=r[2];for(let o=3;o<r.length;o++){const s=r[o],n=t.matchPrefix(e,"a=rtpmap:"+s+" ")[0];if(n){const r=t.parseRtpMap(n),o=t.matchPrefix(e,"a=fmtp:"+s+" ");switch(r.parameters=o.length?t.parseFmtp(o[0]):{},r.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+s+" ").map(t.parseRtcpFb),i.codecs.push(r),r.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(r.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach((e=>{i.headerExtensions.push(t.parseExtmap(e))}));const o=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return i.codecs.forEach((e=>{o.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),i},t.writeRtpDescription=function(e,i){let r="";r+="m="+e+" ",r+=i.codecs.length>0?"9":"0",r+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",r+=i.codecs.map((e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType)).join(" ")+"\r\n",r+="c=IN IP4 0.0.0.0\r\n",r+="a=rtcp:9 IN IP4 0.0.0.0\r\n",i.codecs.forEach((e=>{r+=t.writeRtpMap(e),r+=t.writeFmtp(e),r+=t.writeRtcpFb(e)}));let o=0;return i.codecs.forEach((e=>{e.maxptime>o&&(o=e.maxptime)})),o>0&&(r+="a=maxptime:"+o+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach((e=>{r+=t.writeExtmap(e)})),r},t.parseRtpEncodingParameters=function(e){const i=[],r=t.parseRtpParameters(e),o=-1!==r.fecMechanisms.indexOf("RED"),s=-1!==r.fecMechanisms.indexOf("ULPFEC"),n=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),a=n.length>0&&n[0].ssrc;let d;const c=t.matchPrefix(e,"a=ssrc-group:FID").map((e=>e.substring(17).split(" ").map((e=>parseInt(e,10)))));c.length>0&&c[0].length>1&&c[0][0]===a&&(d=c[0][1]),r.codecs.forEach((e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&d&&(t.rtx={ssrc:d}),i.push(t),o&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:s?"red+ulpfec":"red"},i.push(t))}})),0===i.length&&a&&i.push({ssrc:a});let l=t.matchPrefix(e,"b=");return l.length&&(l=0===l[0].indexOf("b=TIAS:")?parseInt(l[0].substring(7),10):0===l[0].indexOf("b=AS:")?1e3*parseInt(l[0].substring(5),10)*.95-16e3:void 0,i.forEach((e=>{e.maxBitrate=l}))),i},t.parseRtcpParameters=function(e){const i={},r=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];r&&(i.cname=r.value,i.ssrc=r.ssrc);const o=t.matchPrefix(e,"a=rtcp-rsize");i.reducedSize=o.length>0,i.compound=0===o.length;const s=t.matchPrefix(e,"a=rtcp-mux");return i.mux=s.length>0,i},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},t.parseMsid=function(e){let i;const r=t.matchPrefix(e,"a=msid:");if(1===r.length)return i=r[0].substring(7).split(" "),{stream:i[0],track:i[1]};const o=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return o.length>0?(i=o[0].value.split(" "),{stream:i[0],track:i[1]}):void 0},t.parseSctpDescription=function(e){const i=t.parseMLine(e),r=t.matchPrefix(e,"a=max-message-size:");let o;r.length>0&&(o=parseInt(r[0].substring(19),10)),isNaN(o)&&(o=65536);const s=t.matchPrefix(e,"a=sctp-port:");if(s.length>0)return{port:parseInt(s[0].substring(12),10),protocol:i.fmt,maxMessageSize:o};const n=t.matchPrefix(e,"a=sctpmap:");if(n.length>0){const e=n[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:o}}},t.writeSctpDescription=function(e,t){let i=[];return i="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&i.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),i.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,i,r){let o;const s=void 0!==i?i:2;o=e||t.generateSessionId();return"v=0\r\no="+(r||"thisisadapterortc")+" "+o+" "+s+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,i){const r=t.splitLines(e);for(let e=0;e<r.length;e++)switch(r[e]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return r[e].substring(2)}return i?t.getDirection(i):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const i=t.splitLines(e)[0].substring(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},t.parseOLine=function(e){const i=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:i[0],sessionId:i[1],sessionVersion:parseInt(i[2],10),netType:i[3],addressType:i[4],address:i[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const i=t.splitLines(e);for(let e=0;e<i.length;e++)if(i[e].length<2||"="!==i[e].charAt(1))return!1;return!0},e.exports=t}(sdp$1);var sdpExports=sdp$1.exports,SDPUtils=getDefaultExportFromCjs(sdpExports),sdp=_mergeNamespaces({__proto__:null,default:SDPUtils},[sdpExports]);function shimRTCIceCandidate(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substring(2)),e.candidate&&e.candidate.length){const i=new t(e),r=SDPUtils.parseCandidate(e.candidate);for(const e in r)e in i||Object.defineProperty(i,e,{value:r[e]});return i.toJSON=function(){return{candidate:i.candidate,sdpMid:i.sdpMid,sdpMLineIndex:i.sdpMLineIndex,usernameFragment:i.usernameFragment}},i}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,wrapPeerConnectionEvent(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function shimRTCIceCandidateRelayProtocol(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||wrapPeerConnectionEvent(e,"icecandidate",(e=>{if(e.candidate){const t=SDPUtils.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function shimMaxMessageSize(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(function(e){if(!e||!e.sdp)return!1;const t=SDPUtils.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=SDPUtils.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))}(arguments[0])){const e=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const i=parseInt(t[1],10);return i!=i?-1:i}(arguments[0]),i=function(e){let i=65536;return"firefox"===t.browser&&(i=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),i}(e),r=function(e,i){let r=65536;"firefox"===t.browser&&57===t.version&&(r=65535);const o=SDPUtils.matchPrefix(e.sdp,"a=max-message-size:");return o.length>0?r=parseInt(o[0].substring(19),10):"firefox"===t.browser&&-1!==i&&(r=2147483637),r}(arguments[0],e);let o;o=0===i&&0===r?Number.POSITIVE_INFINITY:0===i||0===r?Math.max(i,r):Math.min(i,r);const s={};Object.defineProperty(s,"maxMessageSize",{get:()=>o}),this._sctp=s}return i.apply(this,arguments)}}function shimSendThrowTypeError(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const i=e.send;e.send=function(){return i.apply(e,arguments)}}const i=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=i.apply(this,arguments);return t(e),e},wrapPeerConnectionEvent(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function shimConnectionState(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;const t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach((e=>{const i=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{const t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;const i=new Event("connectionstatechange",e);t.dispatchEvent(i)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}}))}function removeExtmapAllowMixed(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t.version>=605)return;const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const i=t.sdp.split("\n").filter((e=>"a=extmap-allow-mixed"!==e.trim())).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:i}):t.sdp=i}return i.apply(this,arguments)}}function shimAddIceCandidateNullOrEmpty(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.addIceCandidate;i&&0!==i.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():i.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function shimParameterlessSetLocalDescription(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.setLocalDescription;i&&0!==i.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return i.apply(this,arguments);if(e={type:e.type,sdp:e.sdp},!e.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":e.type="offer";break;default:e.type="answer"}if(e.sdp||"offer"!==e.type&&"answer"!==e.type)return i.apply(this,[e]);return("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then((e=>i.apply(this,[e])))})}var commonShim=Object.freeze({__proto__:null,removeExtmapAllowMixed:removeExtmapAllowMixed,shimAddIceCandidateNullOrEmpty:shimAddIceCandidateNullOrEmpty,shimConnectionState:shimConnectionState,shimMaxMessageSize:shimMaxMessageSize,shimParameterlessSetLocalDescription:shimParameterlessSetLocalDescription,shimRTCIceCandidate:shimRTCIceCandidate,shimRTCIceCandidateRelayProtocol:shimRTCIceCandidateRelayProtocol,shimSendThrowTypeError:shimSendThrowTypeError});function adapterFactory({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const i=log,r=detectBrowser(e),o={browserDetails:r,commonShim:commonShim,extractVersion:extractVersion,disableLog:disableLog,disableWarnings:disableWarnings,sdp:sdp};switch(r.browser){case"chrome":if(!chromeShim||!shimPeerConnection$1||!t.shimChrome)return i("Chrome shim is not included in this adapter release."),o;if(null===r.version)return i("Chrome shim can not determine version, not shimming."),o;i("adapter.js shimming chrome."),o.browserShim=chromeShim,shimAddIceCandidateNullOrEmpty(e,r),shimParameterlessSetLocalDescription(e),shimGetUserMedia$2(e,r),shimMediaStream(e),shimPeerConnection$1(e,r),shimOnTrack$1(e),shimAddTrackRemoveTrack(e,r),shimGetSendersWithDtmf(e),shimGetStats(e),shimSenderReceiverGetStats(e),fixNegotiationNeeded(e,r),shimRTCIceCandidate(e),shimRTCIceCandidateRelayProtocol(e),shimConnectionState(e),shimMaxMessageSize(e,r),shimSendThrowTypeError(e),removeExtmapAllowMixed(e,r);break;case"firefox":if(!firefoxShim||!shimPeerConnection||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),o;i("adapter.js shimming firefox."),o.browserShim=firefoxShim,shimAddIceCandidateNullOrEmpty(e,r),shimParameterlessSetLocalDescription(e),shimGetUserMedia$1(e,r),shimPeerConnection(e,r),shimOnTrack(e),shimRemoveStream(e),shimSenderGetStats(e),shimReceiverGetStats(e),shimRTCDataChannel(e),shimAddTransceiver(e),shimGetParameters(e),shimCreateOffer(e),shimCreateAnswer(e),shimRTCIceCandidate(e),shimConnectionState(e),shimMaxMessageSize(e,r),shimSendThrowTypeError(e);break;case"safari":if(!safariShim||!t.shimSafari)return i("Safari shim is not included in this adapter release."),o;i("adapter.js shimming safari."),o.browserShim=safariShim,shimAddIceCandidateNullOrEmpty(e,r),shimParameterlessSetLocalDescription(e),shimRTCIceServerUrls(e),shimCreateOfferLegacy(e),shimCallbacksAPI(e),shimLocalStreamsAPI(e),shimRemoteStreamsAPI(e),shimTrackEventTransceiver(e),shimGetUserMedia(e),shimAudioContext(e),shimRTCIceCandidate(e),shimRTCIceCandidateRelayProtocol(e),shimMaxMessageSize(e,r),shimSendThrowTypeError(e),removeExtmapAllowMixed(e,r);break;default:i("Unsupported browser!")}return o}if(adapterFactory({window:"undefined"==typeof window?void 0:window}),"undefined"!=typeof MediaStreamTrack){const e=MediaStreamTrack.prototype.getSettings;MediaStreamTrack.prototype.getSettings=function(){const t=e.call(this);return t.width&&(t.width=Math.floor(t.width)),t.height&&(t.height=Math.floor(t.height)),t.frameRate&&(t.frameRate=Math.floor(t.frameRate)),t}}var eventemitter3={exports:{}};!function(e){var t=Object.prototype.hasOwnProperty,i="~";function r(){}function o(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function s(e,t,r,s,n){if("function"!=typeof r)throw new TypeError("The listener must be a function");var a=new o(r,s||e,n),d=i?i+t:t;return e._events[d]?e._events[d].fn?e._events[d]=[e._events[d],a]:e._events[d].push(a):(e._events[d]=a,e._eventsCount++),e}function n(e,t){0==--e._eventsCount?e._events=new r:delete e._events[t]}function a(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),(new r).__proto__||(i=!1)),a.prototype.eventNames=function(){var e,r,o=[];if(0===this._eventsCount)return o;for(r in e=this._events)t.call(e,r)&&o.push(i?r.slice(1):r);return Object.getOwnPropertySymbols?o.concat(Object.getOwnPropertySymbols(e)):o},a.prototype.listeners=function(e){var t=i?i+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var o=0,s=r.length,n=new Array(s);o<s;o++)n[o]=r[o].fn;return n},a.prototype.listenerCount=function(e){var t=i?i+e:e,r=this._events[t];return r?r.fn?1:r.length:0},a.prototype.emit=function(e,t,r,o,s,n){var a=i?i+e:e;if(!this._events[a])return!1;var d,c,l=this._events[a],u=arguments.length;if(l.fn){switch(l.once&&this.removeListener(e,l.fn,void 0,!0),u){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,t),!0;case 3:return l.fn.call(l.context,t,r),!0;case 4:return l.fn.call(l.context,t,r,o),!0;case 5:return l.fn.call(l.context,t,r,o,s),!0;case 6:return l.fn.call(l.context,t,r,o,s,n),!0}for(c=1,d=new Array(u-1);c<u;c++)d[c-1]=arguments[c];l.fn.apply(l.context,d)}else{var _,h=l.length;for(c=0;c<h;c++)switch(l[c].once&&this.removeListener(e,l[c].fn,void 0,!0),u){case 1:l[c].fn.call(l[c].context);break;case 2:l[c].fn.call(l[c].context,t);break;case 3:l[c].fn.call(l[c].context,t,r);break;case 4:l[c].fn.call(l[c].context,t,r,o);break;default:if(!d)for(_=1,d=new Array(u-1);_<u;_++)d[_-1]=arguments[_];l[c].fn.apply(l[c].context,d)}}return!0},a.prototype.on=function(e,t,i){return s(this,e,t,i,!1)},a.prototype.once=function(e,t,i){return s(this,e,t,i,!0)},a.prototype.removeListener=function(e,t,r,o){var s=i?i+e:e;if(!this._events[s])return this;if(!t)return n(this,s),this;var a=this._events[s];if(a.fn)a.fn!==t||o&&!a.once||r&&a.context!==r||n(this,s);else{for(var d=0,c=[],l=a.length;d<l;d++)(a[d].fn!==t||o&&!a[d].once||r&&a[d].context!==r)&&c.push(a[d]);c.length?this._events[s]=1===c.length?c[0]:c:n(this,s)}return this},a.prototype.removeAllListeners=function(e){var t;return e?(t=i?i+e:e,this._events[t]&&n(this,t)):(this._events=new r,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=i,a.EventEmitter=a,e.exports=a}(eventemitter3);var eventemitter3Exports=eventemitter3.exports,EventEmitter2=getDefaultExportFromCjs(eventemitter3Exports);const logger$a=new Logger$1("VERTC",0);class EnhancedEventEmitter extends eventemitter3Exports.EventEmitter{safeEmit(e,...t){const i=this.listenerCount(e);try{return super.emit(e,...t)}catch(t){return logger$a.error("safeEmit","safeEmit() | event listener threw an error [event:%s]:%o",e,t),console.error(t),Boolean(i)}}async asyncEmit(e,...t){await Promise.resolve().then((()=>{try{super.emit(e,...t)}catch(t){logger$a.error("safeEmit","safeEmit() | event listener threw an error [event:%s]:%o",e,t),console.error(t)}}))}}var SEIStreamEventType=(e=>(e[e.BLACK=0]="BLACK",e[e.NORMAL=1]="NORMAL",e))(SEIStreamEventType||{}),RemoveStreamMessage=(e=>(e.streamRemovedBySchedule308="stream removed",e.clientRePublish="client republish",e.publishStreamFaied="publish failed",e.clientUnPublish="client unpublished",e.clientDisconnected="client disconnected",e.videoMuted="video muted",e))(RemoveStreamMessage||{}),StreamControlType=(e=>(e.PushLimitWarn="PushLimitWarn",e.OTHER="OTHER",e))(StreamControlType||{}),EngineControlType=(e=>(e.CHANGE_CODEC="changeCodec",e))(EngineControlType||{}),SignalEvent=(e=>(e.ON_ADD_STREAM="onAddStream",e.ON_ADD_STREAM_LIST="onAddStreamList",e.ON_REMOVE_STREAM="onRemoveStream",e.ON_REMOVE_STREAM_LIST="onRemoveStreamList",e.USER_DISCONNECTION="userDisconnection",e.USER_DISCONNECTION_LIST="userDisconnectionList",e.USER_CONNECTION="userConnection",e.USER_CONNECTION_LIST="userConnectionList",e.ON_UPDATE_STREAM_ATTRIBUTES="onUpdateStreamAttributes",e.ON_UPDATE_ROOM_ATTRIBUTES="onUpdateRoomAttributes",e.ON_UPDATE_USER_ATTRIBUTES="onUpdateUserAttributes",e.ON_PUSH_TRACK="onPushTrack",e.ON_REMOVE_TRACK="onRemoveTrack",e.ON_CUSTOM_MESSAGE="onCustomMessage",e.NODE_CHANGE="nodeChange",e.USER_MESSAGE_RECEIVED="userMessageReceived",e.USER_BINARY_MESSAGE_RECEIVED="userBinaryMessageReceived",e.USER_MESSAGE_RECEIVED_OUTSIDE_ROOM="userMessageReceivedOutsideRoom",e.USER_BINARY_MESSAGE_RECEIVED_OUTSIDE_ROOM="userBinaryMessageReceivedOutsideRoom",e.POST_PROCESSING_MESSAGE="postProcessingMessage",e.ON_USER_TOKEN_WILL_EXPIRE="onUserTokenWillExpire",e.ON_TOKEN_PUBLISH_PRIVILEGE_WILL_EXPIRE="onTokenPublishPrivilegeWillExpire",e.ON_TOKEN_PUBLISH_PRIVILEGE_DID_EXPIRED="onTokenPublishPrivilegeDidExpired",e.ON_TOKEN_SUBSCRIBE_PRIVILEGE_WILL_EXPIRE="onTokenSubscribePrivilegeWillExpire",e.ON_TOKEN_SUBSCRIBE_PRIVILEGE_DID_EXPIRED="onTokenSubscribePrivilegeDidExpired",e.STREAM_CONTROL_MESSAGE="streamControlMessage",e.ON_SPEAKER_CHANGE="onSpeakerChange",e.ON_STREAM_FAILED="streamFailed",e.ON_NOTIFY_RECONNECT="notifyReconnect",e.ON_FORWARD_DST_ROOM_USER_KICK="onForwardDstRoomUserKick",e.ENGINE_CONTROL_MESSAGE="engineControlMessage",e.ON_STREAM_PUSHED_BY_OTHER="onStreamPushedByOther",e.ON_STREAM_PULL_STATE_CHANGED="onStreamPullStateChanged",e))(SignalEvent||{}),MediaServerSignalEvent=(e=>(e.RSCP="RSCP",e.RTT="RTT",e.SSC="SSC",e))(MediaServerSignalEvent||{}),StateEvent=(e=>(e.ON_CONNECTION_STATE_CHANGE="onConnectionStateChange",e.ON_VENDOR_CONNECTION_STATE_CHANGE="onVendorConnectionStateChange",e.ABNORMAL_DISCONNECTION="normalConnection",e.ON_RECONNECT_FAILED="onReconnectFailed",e.CONNECT_WITH_TCP="onIceConnectWithTcp",e))(StateEvent||{}),UserDisconnectionTag=(e=>(e.userLeave="userLeave",e.connectionLost="connectionLost",e.userDuplicateLogin="userDuplicateLogin",e.kickedByAdmin="kickedByAdmin",e.roleChanged="roleChanged",e.onUserTokenDidExpire="onUserTokenDidExpire",e))(UserDisconnectionTag||{}),UserDisconnectionCode=(e=>(e[e.roomDismissByAdmin=2]="roomDismissByAdmin",e))(UserDisconnectionCode||{}),RTS_MODE=(e=>(e[e.LIMIT_MODE=1]="LIMIT_MODE",e[e.NORMAL_MODE=2]="NORMAL_MODE",e))(RTS_MODE||{}),VideoType=(e=>(e[e.NORMAL=0]="NORMAL",e[e.BLACK=1]="BLACK",e))(VideoType||{}),SourceType=(e=>(e[e.EXTERNAL=0]="EXTERNAL",e[e.INTERNAL=1]="INTERNAL",e))(SourceType||{}),MediaType=(e=>(e.AUDIO="audio",e.VIDEO="video",e))(MediaType||{}),ExtendStreamIndex=(e=>(e.MAIN="main",e.SCREEN="screen",e.PUBLIC="public",e.VIRTUAL="virtual",e))(ExtendStreamIndex||{});class Track extends EnhancedEventEmitter{constructor(e,t,i){super(),__publicField(this,"trackId",genUuid()),__publicField(this,"_logger"),__publicField(this,"trackInfo"),__publicField(this,"_originTrack"),__publicField(this,"_channelCount"),this._ctx=e,this._logger=new Logger$1("Track",4,e.id),this.trackInfo=i,this._originTrack=t,this._channelCount=t.getSettings().channelCount}get dummy(){return this.trackInfo.isDummy}get virtual(){return"virtual"===this.trackInfo.streamIndex}get isScreen(){return"screen"===this.trackInfo.streamIndex}get isPublic(){return"public"===this.trackInfo.streamIndex}get sourceType(){return this.trackInfo.sourceType}get mediaType(){return this.trackInfo.mediaType}get captureSessionId(){return this.trackInfo.captureSessionId}get streamIndex(){const{streamIndex:e}=this.trackInfo;return"main"===e?StreamIndex$1.STREAM_INDEX_MAIN:"screen"===e?StreamIndex$1.STREAM_INDEX_SCREEN:void 0}get channelCount(){return this._channelCount??0}get originTrack(){return this._originTrack}set originTrack(e){this._originTrack=e,this._channelCount=mediaTrack.getSettings().channelCount}get logger(){return this._logger.module=this.constructor.name,this._logger}destroy(){this._originTrack.stop()}}class LocalTrack extends Track{constructor(e,t,i){super(e,t,i),__publicField(this,"_mediaTrack"),__publicField(this,"_preProcessingTrack"),__publicField(this,"isTrackReady"),__publicField(this,"handleTrackEnded",(()=>{this.emit("track-ended",this),this.destroy()})),__publicField(this,"handleMute",(()=>{this.emit("track-mute",this)})),__publicField(this,"handleUnmute",(()=>{this.emit("track-unmute",this)})),this._initListeners(),this.isTrackReady=this.generatePreProcessingTrack()}get mediaTrack(){return this._mediaTrack??this._originTrack}set mediaTrack(e){this.mediaTrack.id!==e.id&&(this._mediaTrack=e,this.isTrackReady=this.generatePreProcessingTrack())}get preprocessingTrack(){return this._preProcessingTrack??this.mediaTrack}async generatePreProcessingTrack(){var e;const t=null==(e=this._preProcessingTrack)?void 0:e.id;this._preProcessingTrack=void 0;try{const e=await this._ctx.extensionManager.getPreProcessingTrack(this);e instanceof MediaStreamTrack&&(this._preProcessingTrack=e,t!==this._preProcessingTrack.id&&setTimeout((()=>{this.emit("needReplaceTrack")})))}catch(e){console.error(e)}}destroy(){var e,t;this._originTrack.removeEventListener("ended",this.handleTrackEnded),this._originTrack.removeEventListener("mute",this.handleMute),this._originTrack.removeEventListener("unmute",this.handleUnmute),null==(e=this._preProcessingTrack)||e.stop(),null==(t=this._mediaTrack)||t.stop(),super.destroy()}_initListeners(){this._originTrack instanceof MediaStreamTrack&&(this._originTrack.addEventListener("ended",this.handleTrackEnded),this._originTrack.addEventListener("mute",this.handleMute),this._originTrack.addEventListener("unmute",this.handleUnmute))}}class RemoteTrack extends Track{constructor(e,t,i){super(e,t,i),__publicField(this,"_mediaTrack"),this._originTrack=t}get mediaTrack(){return this._mediaTrack??this._originTrack}set mediaTrack(e){this.mediaTrack.id!==e.id&&(this._mediaTrack=e)}get preprocessingTrack(){return this.mediaTrack}}var RTC_SEI_TYPE=(e=>(e[e.internal=0]="internal",e[e.external=1]="external",e[e.bypass=2]="bypass",e))(RTC_SEI_TYPE||{});const EPB=3,MAX_NUMBER_OF_CONSECUTIVE_ZEROS=2,UUID_INTERNAL=new Uint8Array([109,167,53,190,103,90,72,1,170,89,63,164,194,199,19,85]),UUID_EXTERNAL=new Uint8Array([109,167,53,190,103,90,72,1,170,89,63,164,194,199,19,84]),UUID_EXTERNAL_2=new Uint8Array([31,239,3,50,242,120,76,85,169,42,161,91,75,186,22]),rbsp2ebsp=e=>{const t=[];let i=0;for(const r of e)i>=2&&r<=3&&(t.push(3),i=0),0===r?i++:i=0,t.push(r);return new Uint8Array(t)},ebsp2rbsp=e=>{const t=[];for(let i=0;i<e.length;i++)e[i]<=3&&0===e[i-1]&&0===e[i-2]||t.push(e[i]);return new Uint8Array(t)};function serializeData(e){const t=[];for(;e>=255;)e-=255,t.push(255);return t.push(e),new Uint8Array(t)}function deserializeData(e,t=0){let i=0;for(;255===e[t]&&t<e.byteLength;)t++,i+=255;return t<e.byteLength&&(i+=e[t++]),[i,t]}const HEVC_SEI_NALU_HEADER=new Uint8Array([80,1]),_SEIHelper=class{static generateSEI(e,t,i=!1){const r=new Uint8Array([0,0,0,1]),o=t?HEVC_SEI_NALU_HEADER:new Uint8Array([6]),s=new Uint8Array([5]),n=_SEIHelper.__uuid||(i?UUID_INTERNAL:UUID_EXTERNAL),a=serializeData(e.byteLength+n.byteLength),d=rbsp2ebsp(e);return new Uint8Array([...r,...o,...s,...a,...n,...d,128])}static decodeSEIBody(e,t){e=e.slice(0,e.length-1);const i=ebsp2rbsp(e);if(i.byteLength<2)return;let r=0;const o=t?2:1;if(5!==i[o]&&100!==i[o])return;r+=1+o;const[s,n]=deserializeData(i,r);r=n;let a=2;const d=r+s;i.byteLength>=UUID_EXTERNAL.byteLength&&s>=UUID_EXTERNAL.byteLength&&(i.slice(r,r+UUID_EXTERNAL.byteLength).toString()===UUID_EXTERNAL.toString()||i.slice(r,r+UUID_EXTERNAL_2.byteLength).toString()===UUID_EXTERNAL_2.toString())?(r+=UUID_EXTERNAL.byteLength,a=1):i.byteLength>=UUID_EXTERNAL.byteLength&&s>=UUID_EXTERNAL.byteLength&&i.slice(r,r+UUID_INTERNAL.byteLength).toString()===UUID_INTERNAL.toString()&&(r+=UUID_INTERNAL.byteLength,a=0);return{type:a,payload:i.slice(r,d)}}static parseInternalSEI(e){const t=new Map;let i=0;if(0===e.type){for(;e.payload.byteLength-i>=2;){const[r,o]=deserializeData(e.payload,i);i=o;const[s,n]=deserializeData(e.payload,i);if(i=n,t.get(r)||!(s<=e.payload.byteLength-i))break;t.set(r,e.payload.slice(i,i+s)),i+=s}return t}}static makeInternalSei(e){const t=[];for(const[i,r]of e){const e=serializeData(i),o=serializeData(r.byteLength);t.push(e,o,r)}const i=t.reduce(((e,t)=>e+t.byteLength),0),r=new Uint8Array(i);return t.reduce(((e,t)=>(r.set(t,e),e+t.byteLength)),0),r}};let SEIHelper=_SEIHelper;function setPressureObserver(e){const t=PressureObserver.supportedSources;let i="thermal";i=(null==t?void 0:t.includes("thermal"))?"thermal":"cpu";const r=new PressureObserver((t=>{t.forEach((t=>{t.source===i&&e(t.state)}))}));return r.observe(i,{sampleInterval:2e3}),r}__publicField(SEIHelper,"__uuid");class ComputePressureMonitor{constructor(){__publicField(this,"_state"),__publicField(this,"_handler",!1)}init(){if(isComputePressureSupported&&!getParameter("DISABLE_COMPUTE_PRESSURE")&&"UT"!=={}.VITE_TEST)try{if(isWorkerSupported()){const e=new Blob([`(${setPressureObserver.toString()})(self.postMessage)`],{type:"text/javascript"}),t=new Worker(URL.createObjectURL(e));t.onmessage=e=>{this._state=e.data},this._handler=t}else this._handler=setPressureObserver((e=>{this._state=e}))}catch{}}get state(){return isDebuggerMode&&!isSSR$1()&&(window.thermal_status=this._state),this._handler||this.init(),this._state}}var computePressureMonitor=new ComputePressureMonitor;const stasType=["codec","inbound-rtp","outbound-rtp","remote-inbound-rtp","remote-outbound-rtp","media-source","csrc","peer-connection","data-channel","stream","track","transceiver","sender","receiver","transport","sctp-transport","candidate-pair","local-candidate","remote-candidate","certificate","ice-server"],THROTTLE_DURATION=150,STATS_CACHE=new Map;let canIUseGetStatsCallback=!0;const getExtraChromeStatsReport=async e=>new Promise((t=>{var i,r,o,s;const n={all:[],getTrackStats:()=>[]},a=getParameter("STATS_SCALLBACK_SUPPORT");if(canIUseGetStatsCallback&&isChrome&&void 0===window.InstallTrigger&&isStatsCallbackSupport&&a)try{null==(s=null==(o=null==(r=null==(i=e.getStats((e=>{const i=[];e.result().forEach((e=>{if(stasType.includes(e.type))return;const t={};e.names().forEach((function(i){t[i]=e.stat(i)})),i.push({...t,id:e.id,type:e.type,timestamp:e.timestamp})})),t({all:i,getTrackStats:e=>i.filter((t=>"ssrc"!==t.type||t.googTrackId===e))})})))?void 0:i.then)?void 0:r.call(i,(()=>{t(n)})))?void 0:o.catch)||s.call(o,(()=>{canIUseGetStatsCallback=!1,t(n)}))}catch{canIUseGetStatsCallback=!1,t(n)}else t(n)})),getAllStatsReport=async e=>{var t,i,r;const o=await e.getStats(),s={all:[]},n=new Map;o.forEach((e=>{const t=n.get(e.type)||new Map;t.set(e.id,e),n.set(e.type,t),s.all.push(e)}));const a=(e,t)=>{e.forEach((({codecId:e,transportId:i,trackId:r,playoutId:o})=>{var s,a,d,c,l,u,_,h;let p,m;if(null==(s=n.get("codec"))||s.forEach((i=>{i.id===e&&t.add(i)})),null==(a=n.get("transport"))||a.forEach((e=>{e.id===i&&(p=e,t.add(e))})),null==(d=n.get("track"))||d.forEach((e=>{e.id===r&&t.add(e)})),null==(c=n.get("media-playout"))||c.forEach((e=>{e.id===o&&t.add(e)})),p){const{localCertificateId:e,remoteCertificateId:i,selectedCandidatePairId:r}=p;null==(l=n.get("certificate"))||l.forEach((r=>{(r.id===e||r.id===i)&&t.add(r)})),null==(u=n.get("candidate-pair"))||u.forEach((e=>{e.id===r&&(m=e,t.add(e))}))}if(m){const{localCandidateId:e,remoteCandidateId:i}=m;null==(_=n.get("local-candidate"))||_.forEach((i=>{i.id===e&&t.add(i)})),null==(h=n.get("remote-candidate"))||h.forEach((e=>{e.id===i&&t.add(e)}))}}))};return n.get("media-source")?null==(t=n.get("media-source"))||t.forEach((e=>{var t;const i=new Set;i.add(e);const r=[];null==(t=n.get("outbound-rtp"))||t.forEach((t=>{var o;t.mediaSourceId===e.id&&(i.add(t),r.push(t),null==(o=n.get("remote-inbound-rtp"))||o.forEach((e=>{e.localId===t.id&&i.add(e)})))})),a(r,i),s[e.trackIdentifier]=Array.from(i)})):n.get("track")&&(null==(i=n.get("track"))||i.forEach((e=>{var t;const i=new Set;i.add(e);const r=[];null==(t=n.get("outbound-rtp"))||t.forEach((t=>{var o;t.trackId===e.id&&(i.add(t),r.push(t),null==(o=n.get("remote-inbound-rtp"))||o.forEach((e=>{e.localId===t.id&&i.add(e)})))})),a(r,i),s[e.trackIdentifier]=Array.from(i)}))),null==(r=n.get("inbound-rtp"))||r.forEach((e=>{var t,i;const r=new Set;r.add(e),null==(t=n.get("remote-outbound-rtp"))||t.forEach((t=>{t.localId===e.id&&r.add(t)})),a([e],r);let{trackIdentifier:o}=e;o||null==(i=n.get("track"))||i.forEach((t=>{t.id===e.trackId&&(o=t.trackIdentifier)})),s[o]=Array.from(r)})),s},getStats$1=async(e,t,i,r)=>{const o=null==t?void 0:t.id;if(!(e instanceof RTCPeerConnection))return[];if(isFirefox||isSafari){const i=[];try{(r?await r.getStats():await e.getStats(t)).forEach((e=>{i.push(e)}))}catch{}return i}let s=STATS_CACHE.get(e);(!s||Date.now()-s.timestamp>150)&&(s={timestamp:Date.now(),statsPromise:getAllStatsReport(e),extraStatsPromise:getExtraChromeStatsReport(e)},STATS_CACHE.set(e,s));const n=await s.statsPromise;let a=(o?n[o]:n.all)||[];if(!i){const e=await s.extraStatsPromise;a=a.concat((o?e.getTrackStats(o):e.all)||[])}return a},clearPeerCache=e=>{STATS_CACHE.has(e)&&STATS_CACHE.delete(e)};class StatsMonitor extends EnhancedEventEmitter{constructor(){super(...arguments),__publicField(this,"_continuousVideoEncodeFailure",0),__publicField(this,"_remoteStreamDecodeStatus",new Map)}setLocalVideoStats(e,t){this.checkVideoEncodeFailure(e,t)}setRemoteVideoStats(e,t){this.checkVideoDecodeFailure(e,t)}destroy(){this._continuousVideoEncodeFailure=0,this._remoteStreamDecodeStatus=new Map}checkVideoEncodeFailure(e,t){var i;const r=e.frame_rate_input;window.__createEncodeError__&&(e.frame_rate_sent=0,e.frame_rate_encoded=0);const o=e.frame_rate_sent,s=e.frame_rate_encoded,n=void 0!==r&&r>0&&void 0!==s&&0===s&&void 0!==o&&0===o,a=(null==e?void 0:e.is_screen)?10:5;n?(this._continuousVideoEncodeFailure++,this._continuousVideoEncodeFailure>a&&(this.emit("rtc-encode-error",{codec:null==e?void 0:e.codecName,media_type:"video",track_frame_size_width:null==t?void 0:t.getSettings().width,track_frame_size_height:null==t?void 0:t.getSettings().height,track_frame_rate:null==t?void 0:t.getSettings().frameRate,stats_frame_size_width:null==e?void 0:e.frame_size_width,stats_frame_size_height:null==e?void 0:e.frame_size_height,stats_frame_rate_input:null==e?void 0:e.frame_rate_input,stats_frame_rate_sent:null==e?void 0:e.frame_rate_sent,stats_frame_rate_encoded:null==e?void 0:e.frame_rate_encoded,stats_frame_encoder_name:e.encoder_implementation,stats_is_hardware_encoder_enabled:Config2.H264_HW_ENCODER,stats_gpu_url:Config2.GPU_URL||(null==(i=getGpuInfo())?void 0:i.renderer),is_screen:null==e?void 0:e.is_screen}),this._continuousVideoEncodeFailure=0)):this._continuousVideoEncodeFailure=0}checkVideoDecodeFailure(e,t){var i;const r=e.stream_id;if(this._remoteStreamDecodeStatus.has(r)){const o=this._remoteStreamDecodeStatus.get(r),s=0===e.frame_rate_decoded&&e.packetsReceived>o.packets_received&&e.framesDecoded<10;o.packets_received=e.packetsReceived,o.frames_decoded=e.framesDecoded,o.frame_rate_decoded=e.frame_rate_decoded,o.continuous_video_decode_failure=s?o.continuous_video_decode_failure+1:0,o.continuous_video_decode_failure>5&&(this.emit("rtc-decode-error",{codec:e.codecName,media_type:"video",track_frame_size_width:t.getSettings().width,track_frame_size_height:t.getSettings().height,track_frame_rate:t.getSettings().frameRate,stats_frame_size_width:e.frame_size_width,stats_frame_size_height:e.frame_size_height,stats_frame_rate_decode:e.frame_rate_decoded,stats_frame_rate_receive:e.frame_rate_received,stats_frame_decoder_name:e.decoder_name,stats_gpu_url:Config2.GPU_URL||(null==(i=getGpuInfo())?void 0:i.renderer),is_screen:e.is_screen}),o.continuous_video_decode_failure=0)}else this._remoteStreamDecodeStatus.set(r,{packets_received:e.packetsReceived,frames_decoded:e.framesDecoded,frame_rate_decoded:e.frame_rate_decoded,continuous_video_decode_failure:0})}}class Stats extends EnhancedEventEmitter{constructor(e){super(),__publicField(this,"_timer"),__publicField(this,"_reportTimer"),__publicField(this,"handler"),__publicField(this,"_monitor"),__publicField(this,"logger"),__publicField(this,"_destroyed",!1),__publicField(this,"_isReportStarted",!1),this._context=e,this._monitor=getMonitor(e.id),this.logger=new Logger$1("Stats",3,e.id)}setVar(e){this.handler=e}stopReport(e){this._isReportStarted&&(this.logger.info("stopReport","invoke"),this._isReportStarted=!1,clearTimeout(this._reportTimer),delete this._reportTimer,reportRtcInvokeStatus(this._context.id,"del_media_statistics_timer",`reason: ${e}, stack: ${(new Error).stack}`,0,this._stream.streamId||""))}filterIllegal(e){const t={};return Object.keys(e).forEach((i=>{null===e[i]||void 0===e[i]||Number.isNaN(e[i])||(t[i]=e[i])})),t}destroy(){this.logger.info("destroy","invoke"),reportRtcInvokeStatus(this._context.id,"media_statistics_destroy",`${(new Error).stack}`,0,`${this._stream.streamId}`),this.stopReport("destroy"),clearTimeout(this._timer),this._destroyed=!0}}class LocalStatsReport extends Stats{constructor(e,t){super(e),__publicField(this,"_stats",{audioStats:{},videoStats:{}}),__publicField(this,"_preReports",{audio:{},video:{}}),__publicField(this,"statsMonitor"),this._stream=t,this.statsMonitor=new StatsMonitor,this.statsMonitor.on("stats-exception",(e=>{this.emit("stats-exception",e)})),this.statsMonitor.on("rtc-encode-error",(e=>{var t;this.logger.info("rtc_encode_error",JSON.stringify(e)),null==(t=this._monitor)||t.report("rtc_encode_error",e)}));const i=async()=>{this._stats=await this._getLocalStats(this._stream,this._preReports,!1),this._destroyed||(this._timer=setTimeout(i,getParameter("STATS_LOOP_INTERVAL")))};i()}setLocalStreamStatsEvtInterval(e,t){if(this._isReportStarted)return;this.logger.info("setLocalStreamStatsEvtInterval","invoke"),this._isReportStarted=!0,this.setVar(t),this._destroyed=!1;const i={audio:{},video:{}},r=async()=>{const t=await this._getLocalStats(this._stream,i,!0);e(t),this._destroyed||(this._reportTimer=setTimeout(r,2e3))};r()}getLocalStats(){return this._stats}async _getLocalStats(e,t,i){var r,o,s,n,a,d,c;const l=void 0!==(null==(r=e.audioTrack)?void 0:r.mixType)&&e.audioTrack.mixType!==AudioMixingType.PLAYOUT?(null==(o=e.audioTrack)?void 0:o.mixedAudioTrack)??(null==(s=e.audioTrack)?void 0:s.preprocessingTrack):null==(n=e.audioTrack)?void 0:n.preprocessingTrack,u=null==(a=e.videoTrack)?void 0:a.preprocessingTrack;0===Object.keys(t.audio).length&&0===Object.keys(t.video).length&&(await this.getAudioStats(l,t,null==(d=e.audioTrack)?void 0:d.getAudioLevel(),i),await this.getVideoStats(u,t,i),await wait(150));return{audioStats:await this.getAudioStats(l,t,null==(c=e.audioTrack)?void 0:c.getAudioLevel(),i),videoStats:await this.getVideoStats(u,t,i),isScreen:e.isScreen}}async getAudioStats(e,t,i,r){var o,s,n,a;const d={},c={timestamp:Date.now()},{streamId:l,audioMid:u,isScreen:_,pubAttributes:h,pubAudio:p,audioTrack:m}=this._stream,S={media_type:"audio",is_screen:!!_,direction:"up",stream_id:l,vid:u,connection_status:navigator.onLine,track_enabled:null==e?void 0:e.enabled,capture_state:h.localaudio?"capture_state_on":"capture_state_off",mute_state:p?"mute_state_off":"mute_state_on",thermal_status:computePressureMonitor.state,is_public_stream:this._stream.isPublicStream};if(m&&(S.playback_volume=m.getVolume()),!e||!this.handler)return d;const g=await(null==(s=this.handler.peer)?void 0:s.getStatsWithLowFrequency(e,!1,null==(o=this._stream.audioTransceiver)?void 0:o.sender));if(!g.length)return d;if(g.forEach((({type:e,packetsSent:t,packetsLost:i,bytesSent:r,clockRate:o,roundTripTime:s,channels:n,audioLevel:a,mimeType:l,availableIncomingBitrate:u,availableOutgoingBitrate:_,bytesReceived:h,nominated:p,id:m,currentRoundTripTime:g,state:v,writable:f,requestsReceived:E,responsesReceived:T,requestsSent:R,consentRequestsSent:b,responsesSent:y,jitter:I,candidateType:C,ip:A,address:k,networkType:M,port:N,protocol:O,nackCount:P,retransmittedBytesSent:D,retransmittedPacketsSent:w,audioInputLevel:L,ssrc:x,totalAudioEnergy:F,totalSamplesDuration:U,mediaType:V,fractionLost:B})=>{"outbound-rtp"===e?(c.packetsSent=t,c.bytesSent=r,S.bytes=r,S.packetsSent=t,S.nackCount=P,S.ssrc=x,S.retransmitted_bytes_sent=D,S.retransmitted_packets_sent=w,c.retransmittedBytesSent=D,c.retransmittedPacketsSent=w):"remote-inbound-rtp"===e?(c.packetsLost=i,S.packetsLost=i,S.net_jitter=1e3*I,d.rtt=1e3*s,S.rtt=d.rtt,d._fractionLost=B||0):"codec"===e?(d.recordSampleRate=o,d.numChannels=n,S.codecName=l):"media-source"===e&&void 0!==a?(S.audio_level=a?-10*Math.log10(Math.pow(a,2)):a,S.volume=255*a,S.total_audio_energy=F,S.totalInputDuration=U,S.send_level||(S.send_level=a)):"ssrc"===e&&"audio"===V?L&&(S.send_level=L):"candidate-pair"===e?(S.ice_available_incoming_bitrate=u,S.ice_available_outgoing_bitrate=_,S.ice_bytes_received=h,S.ice_bytes_sent=r,S.ice_nominated=Number(p),S.ice_pair_id=m,S.ice_pair_rtt=g,S.ice_pair_state=v,S.ice_pair_writable=f,S.recv_ping_requests=E,S.recv_ping_responses=T,S.sent_ping_requests_before_first_response=R,S.sent_ping_requests_total=R+(b||0),S.sent_ping_responses=y):"local-candidate"===e?(S.local_candidate_type=C,S.local_ip=A||k,S.local_network_type=M,S.local_port=N,S.protocol=O):"remote-candidate"===e&&(S.remote_candidate_type=C,S.remote_ip=A||k,S.remote_port=N)})),S.send_level)S.send_level<1?S._sendVolumeLevel=32767*S.send_level:S._sendVolumeLevel=S.send_level;else{const e=(null==m?void 0:m.getAudioLevel())||0;S._sendVolumeLevel=Math.round(e/255*32767)}void 0===S.volume&&void 0!==i&&(S.volume=i,S.audio_level=i?-10*Math.log10(Math.pow(i/255,2)):i);const{audio:v}=t;return v.timestamp?(void 0!==c.packetsLost&&(d.audioLossRate=Math.max(0,c.packetsLost-v.packetsLost)/(c.packetsSent-v.packetsSent),d.audioLossRate=Number.isNaN(d.audioLossRate)?0:d.audioLossRate,S.fraction_lost=d.audioLossRate),d.statsInterval=c.timestamp-v.timestamp,S.stats_interval=d.statsInterval,d.sendKBitrate=(c.bytesSent-v.bytesSent||0)/d.statsInterval*8,S.mediaBitratebps=Math.round(1e3*d.sendKBitrate),S.bandwidth=Math.round(S.mediaBitratebps/1024),void 0!==c.retransmittedBytesSent&&(S.retransmitBitratebps=(c.retransmittedBytesSent-v.retransmittedBytesSent||0)/d.statsInterval),t.audio=c,S.vendor_mode=this._stream.vendorCode||0,S.pc_session_id=null==(n=this.handler)?void 0:n.peerConnectionId,r&&(null==(a=this._monitor)||a.report("rtc_media_statistics",S)),d._retransmittedRate=(c.retransmittedPacketsSent-v.retransmittedPacketsSent)/(c.packetsSent-v.packetsSent),void 0===d.audioLossRate&&(d.audioLossRate=d._retransmittedRate,S.fraction_lost=d.audioLossRate),d._fractionLost=Math.max(d._fractionLost,d.audioLossRate),d._sendVolumeLevel=S._sendVolumeLevel,this.filterIllegal(d)):(t.audio=c,this.filterIllegal(d))}async getVideoStats(e,t,i){var r,o,s,n,a,d,c,l;const u={},_={timestamp:Date.now(),simulcast:{}},{streamId:h,videoMid:p,isScreen:m,pubAttributes:S,enableSimulcast:g,pubVideo:v}=this._stream,f={media_type:"video",is_screen:!!m,direction:"up",stream_id:h,vid:p,connection_status:navigator.onLine,track_enabled:null==e?void 0:e.enabled,capture_state:S.localvideo?"capture_state_on":"capture_state_off",mute_state:v?"mute_state_off":"mute_state_on",thermal_status:computePressureMonitor.state,is_public_stream:this._stream.isPublicStream};if(!e||!this.handler)return u;f.cap_frame_width=e.getSettings().width,f.cap_frame_height=e.getSettings().height,f.frameRateSent=e.getSettings().frameRate,u.isScreen=m,f.is_intersecting=JSON.stringify(null==(o=null==(r=this._stream)?void 0:r.videoTrack)?void 0:o.intersection());const E=await(null==(n=this.handler.peer)?void 0:n.getStatsWithLowFrequency(e,!1,null==(s=this._stream.videoTransceiver)?void 0:s.sender));if(!E.length)return u;let T=0;E.forEach((e=>{const{type:i,framesEncoded:r,packetsLost:o,bytesSent:s,framesSent:n,retransmittedBytesSent:a,totalPacketSendDelay:d,totalEncodeTime:c,firCount:l,targetBitrate:h,roundTripTime:p,mimeType:m,frameWidth:S,frameHeight:v,packetsSent:E,googActualEncBitrate:R,googAvailableReceiveBandwidth:b,googAvailableSendBandwidth:y,googAvgEncodeMs:I,googBucketDelay:C,googEncodeUsagePercent:A,googFrameRateInput:k,availableIncomingBitrate:M,availableOutgoingBitrate:N,bytesReceived:O,nominated:P,id:D,currentRoundTripTime:w,state:L,writable:x,candidateType:F,ip:U,address:V,networkType:B,port:$,nackCount:G,pliCount:W,protocol:H,qpSum:K,requestsReceived:X,responsesReceived:Z,googRetransmitBitrate:z,requestsSent:Y,consentRequestsSent:j,responsesSent:J,ssrc:Q,googTargetEncBitrate:q,googTransmitBitrate:ee,retransmittedPacketsSent:te,encoderImplementation:ie,jitter:re,rid:oe,fractionLost:se,googAdaptationChanges:ne,qualityLimitationReason:ae,qualityLimitationDurations:de,googFirsReceived:ce,googFrameRateSent:le,keyFramesEncoded:ue,scalabilityMode:_e,framesPerSecond:he,frames:pe}=e;"outbound-rtp"===i?(g&&(oe?_.simulcast[oe]=e:_.simulcast[T]=e,T++),_.framesEncoded=r||_.framesEncoded||0,f.key_frames_encoded=ue||0,_.bytesSent=s||_.bytesSent||0,_.framesSent=n||_.framesSent,f.bytes=s||f.bytes||0,_.packetsSent=E||_.packetsSent||0,f.packetsSent=E||f.packetsSent||0,f.nackCount=G||f.nackCount||0,f.pli_count=W||f.pli_count||0,f.qp_sum=K||f.qp_sum||0,f.ssrc=Q||f.ssrc||0,f.retransmitted_packets_sent=te,_.retransmittedPacketsSent=te,_.retransmittedBytesSent=a,f.encoder_implementation=ie,f.qualityLimitationReason=ae,f.qualityLimitationDurations=de,f.scalabilityMode=_e,void 0!==S&&((!u.encodedFrameWidth||S>u.encodedFrameWidth)&&(u.encodedFrameWidth=S),(!u.encodedFrameHeight||v>u.encodedFrameHeight)&&(u.encodedFrameHeight=v),f.frame_size_height=v,f.frame_size_width=S)):"track"===i?(u.encodedFrameWidth=S,u.encodedFrameHeight=v,f.frame_size_height=v,f.frame_size_width=S):"remote-inbound-rtp"===i?(_.packetsLost=o,u.rtt=1e3*p,f.rtt=u.rtt,f.jitter=1e3*re,f.packetsLost=o,u._fractionLost=se||0):"codec"===i?(u.codecType=m,f.codecName=m):"candidate-pair"===i?(f.ice_available_incoming_bitrate=M,f.ice_available_outgoing_bitrate=N,f.ice_bytes_received=O,f.ice_bytes_sent=s,f.ice_nominated=Number(P),f.ice_pair_id=D,f.ice_pair_rtt=w,f.ice_pair_state=L,f.ice_pair_writable=x,f.recv_ping_requests=X,f.recv_ping_responses=Z,f.sent_ping_requests_before_first_response=Y,f.sent_ping_requests_total=Y+j,f.sent_ping_responses=J):"local-candidate"===i?(f.local_candidate_type=F,f.local_ip=U||V,f.local_network_type=B,f.local_port=$,f.protocol=H):"remote-candidate"===i?(f.remote_candidate_type=F,f.remote_ip=U||V,f.remote_port=$):"VideoBwe"===i?(f.encBitratebps=R,f.available_receive_bandwidth=b,f.available_send_bandwidth=y,f.bucket_delay=C,f.retransmitBitratebps=z,f.targetEncBitratebps=q,f.transmit_bitrate=ee,u._sendBandWidth=Number(y)):"ssrc"===i&&(f.avg_encode_ms=I,f.encodeUsage=A,f.frame_rate_input=k,f.orignal_input_Framerate=Number(k),f.ddaptationChanges=ne,f.firsReceived=ce,f.frameRateSent=le);const me=getParameter("STATS_SCALLBACK_SUPPORT");if(!isStatsCallbackSupport||!me){const{video:e}=t,o=_.timestamp-e.timestamp;if("outbound-rtp"===i){const t=s-e.bytesSent,i=a-e.retransmittedBytesSent;f.encBitratebps=Math.round(8e3*(t-i)/o),f.bucket_delay=d/E,f.retransmitBitratebps=Math.round(8e3*i/o),f.targetEncBitratebps=h,f.transmit_bitrate=Math.round(1e3*(s-e.bytesSent)*8/o),f.avg_encode_ms=1e3*c/r,f.firsReceived=l+W}else"candidate-pair"===i?(f.available_send_bandwidth=N,u._sendBandWidth=N):"media-source"===i&&(f.frame_rate_input=he,f.orignal_input_Framerate=Number(he),f.frame_input=pe)}}));const{video:R}=t;if(!R.timestamp)return t.video=_,this.filterIllegal(u);u.statsInterval=_.timestamp-R.timestamp,f.stats_interval=u.statsInterval;const b=Object.keys(_.simulcast);if(g){f.sim_enc_width=[],f.sim_enc_height=[],f.sim_enc_bps=[],f.sim_enc_framerate=[],f.sim_enc_key_frames=[],f.sim_rids=[],f.sim_enc_bandwidth=[],f.sim_sent_framerate=[],f.sim_fraction_lost=[],f.sim_keyencoded=[],f.active_sim_streams=this._context.videoProfile.activeSimStreams||[],f.sim_retransmittedRate=[];let e=!1;b.sort(((e,t)=>Number(e)-Number(t))).forEach((t=>{const{frameWidth:i,frameHeight:r,bytesSent:o,framesEncoded:s,framesSent:n,packetsLost:a,packetsSent:d,qualityLimitationReason:c,qualityLimitationDurations:l,qualityLimitationResolutionChanges:h,retransmittedPacketsSent:p,pliCount:m,keyFramesEncoded:S}=_.simulcast[t];void 0!==c&&(f.sim_qualityLimitationReason||(f.sim_qualityLimitationReason=[],f.sim_qualityLimitationDurations=[],f.sim_qualityLimitationResolutionChanges=[]),f.sim_qualityLimitationReason.push(c),f.sim_qualityLimitationDurations.push(l),f.sim_qualityLimitationResolutionChanges.push(h));const g=R.simulcast[t];if(f.sim_enc_width.push(i||0),f.sim_enc_height.push(r||0),f.sim_enc_key_frames.push(S||0),g){const r=(o-g.bytesSent||0)/u.statsInterval;f.sim_enc_bps.push(Math.round(8e3*r)),f.sim_enc_bandwidth.push(Math.round(8e3*r/1024));const c=1e3*(s-g.framesEncoded)/u.statsInterval;f.sim_enc_framerate.push(Math.round(c)),f.sim_rids.push(t);const l=void 0!==n?n-g.framesSent:s-g.framesEncoded,_=1e3*l/u.statsInterval;f.sim_sent_framerate.push(Math.round(_));let h=(a-g.packetsLost)/(d-g.packetsSent);u._retransmittedRate=(p-g.retransmittedPacketsSent)/(d-g.packetsSent),h=Number.isNaN(h)?0:h,f.sim_fraction_lost.push(h),f.sim_keyencoded.push(m-g.pliCount>0),f.sim_retransmittedRate.push(u._retransmittedRate),i>0&&!e&&(u.rid=t,u.sentKBitrate=8*r,u.encoderOutputFrameRate=c,u.encodedFrameCount=l,u.sentFrameRate=_,u.videoLossRate=h,e=!0)}})),f.vendor_mode=this._stream.vendorCode||0,f.pc_session_id=null==(a=this.handler)?void 0:a.peerConnectionId,i&&(null==(d=this._monitor)||d.report("rtc_media_statistics",f))}else u.encodedFrameCount=void 0!==_.framesSent?_.framesSent-R.framesSent:_.framesEncoded-R.framesEncoded,u.sentKBitrate=(_.bytesSent-R.bytesSent||0)/u.statsInterval*8,f.bitrate=Math.round(1e3*u.sentKBitrate),f.bandwidth=Math.round(f.bitrate/1024),u.encoderOutputFrameRate=1e3*(_.framesEncoded-R.framesEncoded)/u.statsInterval,f.frame_rate_encoded=Math.round(u.encoderOutputFrameRate),u.sentFrameRate=1e3*u.encodedFrameCount/u.statsInterval,f.frame_rate_sent=Math.round(u.sentFrameRate),u.videoLossRate=Math.max(0,_.packetsLost-R.packetsLost)/(_.packetsSent-R.packetsSent),u.videoLossRate=Number.isNaN(u.videoLossRate)?0:u.videoLossRate,f.fraction_lost=u.videoLossRate,u._retransmittedRate=(_.retransmittedPacketsSent-R.retransmittedPacketsSent)/(_.packetsSent-R.packetsSent),f.vendor_mode=this._stream.vendorCode||0,f.pc_session_id=null==(c=this.handler)?void 0:c.peerConnectionId,f.sentKBitrate=u.sentKBitrate,u.inputFrameRate=f.orignal_input_Framerate,u.encoderName=f.encoder_implementation,i?null==(l=this._monitor)||l.report("rtc_media_statistics",f):this.statsMonitor.setLocalVideoStats(f,e);return t.video=_,u._fractionLost=Math.max(u._fractionLost,u.videoLossRate),u._captureResolutionWidth=f.cap_frame_width,u._captureResolutionHeight=f.cap_frame_height,this.filterIllegal(u)}destroy(){super.destroy(),this.statsMonitor.destroy()}}class RemoteStatsReport extends Stats{constructor(e,t){super(e),__publicField(this,"_stats",{audioStats:{},videoStats:{}}),__publicField(this,"_preReports",{audio:{},video:{}}),__publicField(this,"statsMonitor"),this._stream=t,this.statsMonitor=new StatsMonitor,this.statsMonitor.on("stats-exception",(e=>{this.emit("stats-exception",e)})),this.statsMonitor.on("rtc-decode-error",(e=>{var t;this.logger.info("rtc_decode_error",JSON.stringify(e)),null==(t=this._monitor)||t.report("rtc_decode_error",e)}));const i=async()=>{this._stats=await this._getRemoteStreamStats(this._stream,this._preReports,!1),this._destroyed||(this._timer=setTimeout(i,getParameter("STATS_LOOP_INTERVAL")))};i()}async setRemoteStreamStatsEvtInterval(e,t){if(this._isReportStarted)return;this.logger.info("setRemoteStreamStatsEvtInterval","invoke"),this._isReportStarted=!0,this.setVar(t),this._destroyed=!1;const i={audio:{},video:{}},r=async()=>{const t=await this._getRemoteStreamStats(this._stream,i,!0);e(t),this._destroyed||(this._reportTimer=setTimeout(r,2e3))};r()}getRemoteStreamStats(){return this._stats}async _getRemoteStreamStats(e,t,i){var r,o,s,n;const a=null==(r=e.videoTrack)?void 0:r.originTrack,d=null==(o=e.audioTrack)?void 0:o.originTrack;0===Object.keys(t.audio).length&&0===Object.keys(t.video).length&&(await this.getRemoteAudioStats(d,t,null==(s=this._stream.audioTrack)?void 0:s.getAudioLevel(),i),await this.getRemoteVideoStats(a,t,i),await wait(150));return{audioStats:await this.getRemoteAudioStats(d,t,null==(n=this._stream.audioTrack)?void 0:n.getAudioLevel(),i),videoStats:await this.getRemoteVideoStats(a,t,i),isScreen:e.isScreen,userId:e.userId,streamId:e.streamId}}unsubscribe(){this.logger.info("unsubscribe","invoke"),super.stopReport("unsubscribe"),this._stream.stopAudioStallObserve()}async getRemoteAudioStats(e,t,i,r){var o,s,n,a,d,c;const l={},u={},{streamId:_,userId:h,isScreen:p,audioMid:m,subMediaType:S,_attributes:g,virtual:v,audioTrack:f}=this._stream,E={media_type:"audio",is_screen:!!p,direction:"down",stream_id:_,stream_user_id:h,vid:m,audio_mux:v,connection_status:navigator.onLine,track_enabled:null==e?void 0:e.enabled,mute_state:audioInMediaType(S)?"mute_state_off":"mute_state_on",remote_user_capture_state:g.localaudio?"capture_state_on":"capture_state_off",remote_user_mute_state:g.localaudio&&g.audiostream?"mute_state_off":"mute_state_on",thermal_status:computePressureMonitor.state,is_public_stream:this._stream.isPublicStream};if(f&&(E.playback_volume=f.getVolume()),!e||!this.handler)return l;const T=await(null==(s=this.handler.peer)?void 0:s.getStatsWithLowFrequency(e,!1,null==(o=this._stream.audioTransceiver)?void 0:o.receiver));if(!T.length)return l;T.forEach((({type:e,packetsLost:t,packetsReceived:r,bytesReceived:o,jitterBufferDelay:s,jitterBufferEmittedCount:n,clockRate:a,channels:d,totalSamplesReceived:c,concealedSamples:h,silentConcealedSamples:p,concealmentEvents:m,totalRoundTripTime:S,packetsDiscarded:g,state:v,currentRoundTripTime:f,audioLevel:T,totalAudioEnergy:R,totalSamplesDuration:b,mimeType:y,googDecodingNormal:I,googDecodingMuted:C,availableIncomingBitrate:A,availableOutgoingBitrate:k,bytesSent:M,nominated:N,id:O,writable:P,jitter:D,candidateType:w,ip:L,address:x,networkType:F,port:U,protocol:V,audioOutputLevel:B,requestsReceived:$,responsesReceived:G,requestsSent:W,consentRequestsSent:H,responsesSent:K,ssrc:X,nackCount:Z,lastPacketReceivedTimestamp:z,concealmentevents:Y,fecPacketsReceived:j,retransmittedBytesReceived:J})=>{var Q,q;"inbound-rtp"===e?(u.packetsLost=t,u.packetsReceived=r,E.packetsLost=t,E.packetsReceived=r,E.packetsDiscarded=g,E.nackCount=Z,E.lastPacketReceivedTimestamp=z,E.concealmentevents=Y,u.bytesReceived=o,void 0!==s&&(l.jitterBufferDelay=s/n*1e3,E.average_jitter_buffer_delay_ms=l.jitterBufferDelay),void 0!==c&&(u.totalSamplesReceived=c,l.concealedSamples=h,u.concealedSamples=h,u.silentConcealedSamples=p,E.concealedSamples=h,l.concealmentEvents=m,E.totalSamplesReceived=c),void 0!==j&&(E.fec_packets_received=j,u.fecPacketsReceived=j),E.jitter=1e3*D,E.ssrc=X,void 0!==T&&0!==T?(E.audio_level=T?-10*Math.log10(Math.pow(T,2)):T,E.volume=255*T):(E.volume=i??255*T,E.audio_level=i?-10*Math.log10(Math.pow(i/255,2)):i),void 0!==R&&(E.total_audio_energy=R),void 0!==b&&(E.totalAudioDuration=b),u.retransmittedBytesReceived=J):"codec"===e?(l.recordSampleRate=a,d&&(l.numChannels=d),E.codecName=y,l.codecType=y):"candidate-pair"===e?(E.ice_available_incoming_bitrate=A,E.ice_available_outgoing_bitrate=k,E.ice_bytes_received=o,E.ice_bytes_sent=M,E.ice_nominated=Number(N),E.ice_pair_id=O,E.ice_pair_rtt=f,E.rtt=1e3*f,E.rtt&&(null==(q=null==(Q=this._context.streamRTT)?void 0:Q[_])?void 0:q.audio)&&(E.total_rtt_ms=Math.round(E.rtt+this._context.streamRTT[_].audio)),E.ice_pair_state=v,E.ice_pair_writable=P,E.recv_ping_requests=$,E.recv_ping_responses=G,E.sent_ping_requests_before_first_response=W,E.sent_ping_requests_total=W+(H||0),E.sent_ping_responses=K,"succeeded"===v&&(l.rtt=1e3*f,l.total_rtt=1e3*S)):"track"===e&&void 0!==T?(0===T&&0!==i?(E.volume=i,E.audio_level=i?-10*Math.log10(Math.pow(i/255,2)):i):(E.audio_level=T?-10*Math.log10(Math.pow(T,2)):T,E.volume=255*T),E.total_audio_energy=R,E.totalAudioDuration=b):"ssrc"===e?(E.decodingNormal=I,E.recvAudioLevel=B,E.decodingMuted=C):"local-candidate"===e?(E.local_candidate_type=w,E.local_ip=L||x,E.local_network_type=F,E.local_port=U,E.protocol=V):"remote-candidate"===e&&(E.remote_candidate_type=w,E.remote_ip=L||x,E.remote_port=U)}));const{audio:R}=t;if(!R.timestamp)return u.timestamp=Date.now(),t.audio=u,this.filterIllegal(l);let b;if(void 0!==u.concealedSamples&&(E.interval_concealed_samples=u.concealedSamples-R.concealedSamples,E.interval_samples_received=u.totalSamplesReceived-R.totalSamplesReceived,E.interval_silent_concealed_samples=u.silentConcealedSamples-R.silentConcealedSamples,b=await this._stream.updateAudioStallInfo(E,l,u)),u.timestamp=Date.now(),l.audioLossRate=Math.max(0,u.packetsLost-R.packetsLost)/(u.packetsReceived-R.packetsReceived+(u.packetsLost-R.packetsLost)),l.audioLossRate=Number.isNaN(l.audioLossRate)?0:l.audioLossRate,E.fraction_lost=l.audioLossRate,l.statsInterval=u.timestamp-R.timestamp,E.stats_interval=l.statsInterval,l.receivedKBitrate=(u.bytesReceived-R.bytesReceived||0)/l.statsInterval*8,E.bandwidth=Math.round(1e3*l.receivedKBitrate/1024),void 0!==u.concealedSamples&&(l.receivedSampleRate=1e3*E.interval_samples_received/l.statsInterval),void 0!==u.fecPacketsReceived&&(E.fecBitratebps=(u.fecPacketsReceived-R.fecPacketsReceived||0)/l.statsInterval),E.average_jitter_buffer_delay_ms&&E.total_rtt_ms&&(l.e2eDelay=E.average_jitter_buffer_delay_ms+E.total_rtt_ms),(null==(a=null==(n=this._context.streamRTT)?void 0:n[_])?void 0:a.audio)&&(l.totalRtt=(E.rtt?E.rtt:0)+this._context.streamRTT[_].audio),void 0!==R.retransmittedBytesReceived&&void 0!==u.retransmittedBytesReceived){const e=u.retransmittedBytesReceived-R.retransmittedBytesReceived;E.retransmitBitratebps=Math.round(8e3*e/l.stats_interval)}return t.audio=u,E.vendor_mode=this._stream.vendorCode||0,E.pc_session_id=null==(d=this.handler)?void 0:d.peerConnectionId,r&&(null==(c=this._monitor)||c.report("rtc_media_statistics",E,b)),this.filterIllegal(l)}async getRemoteVideoStats(e,t,i){var r,o,s,n,a,d,c;const l={},u={timestamp:Date.now()},{streamId:_,userId:h,isScreen:p,subMediaType:m,_attributes:S}=this._stream,g={media_type:"video",is_screen:!!p,direction:"down",stream_id:_,stream_user_id:h,vid:this._stream.videoMid,connection_status:navigator.onLine,track_enabled:null==e?void 0:e.enabled,mute_state:videoInMediaType(m)?"mute_state_off":"mute_state_on",remote_user_capture_state:S.localvideo?"capture_state_on":"capture_state_off",remote_user_mute_state:S.localvideo&&S.videostream?"mute_state_off":"mute_state_on",is_intersecting:JSON.stringify(null==(r=this._stream.videoTrack)?void 0:r.intersection()),thermal_status:computePressureMonitor.state,is_public_stream:this._stream.isPublicStream,...this._stream.getVideoRenderInfo()};if(!e||!this.handler)return l;l.isScreen=p;const v=await(null==(s=this.handler.peer)?void 0:s.getStatsWithLowFrequency(e,!1,null==(o=this._stream.videoTransceiver)?void 0:o.receiver));if(!v.length)return l;v.forEach((({type:e,frameHeight:t,frameWidth:i,packetsLost:r,packetsReceived:o,bytesReceived:s,framesDecoded:n,jitterBufferDelay:a,jitterBufferEmittedCount:d,mimeType:c,firCount:h,availableIncomingBitrate:p,availableOutgoingBitrate:m,bytesSent:v,nominated:f,id:E,currentRoundTripTime:T,state:R,writable:b,candidateType:y,ip:I,address:C,networkType:A,port:k,nackCount:M,pliCount:N,protocol:O,requestsReceived:P,responsesReceived:D,requestsSent:w,consentRequestsSent:L,responsesSent:x,ssrc:F,jitter:U,framesReceived:V,keyFramesDecoded:B,totalDecodeTime:$,decoderImplementation:G,lastPacketReceivedTimestamp:W,retransmittedBytesReceived:H,framesDropped:K})=>{var X,Z;if("inbound-rtp"===e){if(u.packetsLost=r,g.packetsLost=r,u.packetsReceived=o,g.packetsReceived=o,u.bytesReceived=s,g.bytes=s,u.framesDecoded=n,u.totalDecodeTime=$,void 0!==a&&(u.jitterBufferDelay=a/d*1e3,g.average_jitter_buffer_delay_ms=u.jitterBufferDelay),g.fir_count=h,g.nackCount=M,u.nackCount=M,g.pli_count=N,g.ssrc=F,g.framesDropped=K,g.jitter=1e3*U,g.framesReceived=V,u.framesReceived=V,g.framesDecoded=n,g.key_frames_decoded=B,g.decoder_name=G,l.decoderName=G,g.last_packet_received_timestamp=W,u.retransmittedBytesReceived=H,void 0!==i){g.frame_size_width=i,g.frame_size_height=t;const e=null==S?void 0:S.alphaInfo;(null==e?void 0:e.enableAlpha)?(l.width=e.alphaWidth??i,l.height=e.alphaHeight??(t??0)/2):(l.width=i,l.height=t)}}else if("track"===e&&void 0!==i){g.frame_size_width=i,g.frame_size_height=t;const e=null==S?void 0:S.alphaInfo;(null==e?void 0:e.enableAlpha)?(l.width=e.alphaWidth??i,l.height=e.alphaHeight??(t??0)/2):(l.width=i,l.height=t),void 0!==V&&(g.framesReceived=V,u.framesReceived=V)}else"codec"===e?(g.codecName=c,l.codecType=c):"candidate-pair"===e?(g.ice_available_incoming_bitrate=p,g.ice_available_outgoing_bitrate=m,g.ice_bytes_received=s,g.ice_bytes_sent=v,g.ice_nominated=Number(f),g.ice_pair_id=E,g.ice_pair_rtt=T,g.rtt=1e3*T,g.rtt&&(null==(Z=null==(X=this._context.streamRTT)?void 0:X[_])?void 0:Z.video)&&(g.total_rtt_ms=Math.round(g.rtt+(this._context.streamRTT[_].video||0))),l.rtt=g.rtt,g.ice_pair_state=R,g.ice_pair_writable=b,g.recv_ping_requests=P,g.recv_ping_responses=D,g.sent_ping_requests_before_first_response=w,g.sent_ping_requests_total=w+(L||0),g.sent_ping_responses=x):"local-candidate"===e?(g.local_candidate_type=y,g.local_ip=I||C,g.local_network_type=A,g.local_port=k,g.protocol=O):"remote-candidate"===e&&(g.remote_candidate_type=y,g.remote_ip=I||C,g.remote_port=k)}));const{video:f}=t;if(!f.timestamp)return t.video=u,this.filterIllegal(l);const E=Math.max(0,u.packetsLost-f.packetsLost),T=u.packetsReceived-f.packetsReceived;if(l.videoLossRate=E/(T+E),l._receivePackets=u.packetsReceived,l._receivePacketsLost=u.packetsLost,f.totalDecodeTime&&f.framesDecoded&&u.framesDecoded!==f.framesDecoded){const e=u.totalDecodeTime-f.totalDecodeTime,t=u.framesDecoded-f.framesDecoded;g.decode_elapse_per_frame=Number((e/t*1e3).toFixed(2))}l._retransmittedRate=(u.nackCount-f.nackCount)/(T+E),l.videoLossRate=Number.isNaN(l.videoLossRate)?0:l.videoLossRate,g.fraction_lost=l.videoLossRate,l.statsInterval=u.timestamp-f.timestamp,g.stats_interval=l.statsInterval,l.receivedKBitrate=(u.bytesReceived-f.bytesReceived||0)/l.statsInterval*8,g.bitrate=Math.round(1e3*l.receivedKBitrate),g.bandwidth=Math.round(g.bitrate/1024),l.decoderOutputFrameRate=1e3*(u.framesDecoded-f.framesDecoded)/l.statsInterval,l.receivedFrameRate=1e3*(u.framesReceived-f.framesReceived)/l.statsInterval,g.frame_rate_decoded=Math.round(l.decoderOutputFrameRate),g.frame_rate_received=Math.round(l.receivedFrameRate),g.average_jitter_buffer_delay_ms&&g.total_rtt_ms&&(l.e2eDelay=g.average_jitter_buffer_delay_ms+g.total_rtt_ms),(null==(a=null==(n=this._context.streamRTT)?void 0:n[_])?void 0:a.video)&&(l.totalRtt=(g.rtt?g.rtt:0)+(this._context.streamRTT[_].video||0)),t.video=u,this._stream.updateVideoStallInfo(g,l,i),g.vendor_mode=this._stream.vendorCode||0,g.pc_session_id=null==(d=this.handler)?void 0:d.peerConnectionId;const R=null==S?void 0:S.alphaInfo;if((null==R?void 0:R.enableAlpha)&&void 0!==g.frame_size_width&&void 0!==g.frame_size_height?(l.frameSizeWidth=R.alphaWidth??g.frame_size_width,l.frameSizeHeight=R.alphaHeight??g.frame_size_height/2):(l.frameSizeWidth=g.frame_size_width,l.frameSizeHeight=g.frame_size_height),l.decoderName=g.decoder_name,void 0!==f.retransmittedBytesReceived&&void 0!==u.retransmittedBytesReceived){const e=u.retransmittedBytesReceived-f.retransmittedBytesReceived;g.retransmitBitratebps=Math.round(8e3*e/g.stats_interval)}return i?null==(c=this._monitor)||c.report("rtc_media_statistics",g):this.statsMonitor.setRemoteVideoStats(g,e),this.filterIllegal(l)}destroy(){super.destroy(),super.stopReport("destroy"),this._stream.stopAudioStallObserve(),this.statsMonitor.destroy()}}class VideoStallObserver{constructor(e,t){__publicField(this,"_removeHandler"),__publicField(this,"_remotePauseHandler"),__publicField(this,"_prePts"),__publicField(this,"_stallList"),__publicField(this,"_videoInWaiting",!1),__publicField(this,"_videoInWaitingCallback",!1),__publicField(this,"_videoInWaiting100ms",!1),__publicField(this,"_isPaused"),__publicField(this,"_pauseStart",0),__publicField(this,"_pauseDuration",0),__publicField(this,"_requestVideoFrameCallbackTimer"),__publicField(this,"_logger"),__publicField(this,"_player"),__publicField(this,"_recentVideoInfo"),__publicField(this,"_stallTimeThreshold"),__publicField(this,"_openVideoStall100ms",Config2.VIDEO_STALL_100MS);const i=e?1500:isSafari||isFirefox?550:500;this._stallTimeThreshold={report:i,callback:Math.max(Config2.VIDEO_STALL_DATA,i)},this._logger=new Logger$1("VideoStallObserver",1,t)}start(e){if(this._logger.print("start","invoke"),this._player=e,checkVideoFrameCallback())e.domElement&&(this._requestVideoFrameCallbackTimer=e.domElement.requestVideoFrameCallback(this._onVideoRefresh.bind(this)),this._removeHandler=()=>{var t;this._requestVideoFrameCallbackTimer&&(null==(t=e.domElement)||t.cancelVideoFrameCallback(this._requestVideoFrameCallbackTimer))});else{const t=t=>this._onVideoTimeupdate(t,e);e.on("playback_event",t),this._removeHandler=()=>e.off("playback_event",t)}const t=e=>this._onVideoPause(e);e.on("playback_event",t),this._remotePauseHandler=()=>e.off("playback_event",t)}getRecentRenderInfo4Report(){const e={};return this._recentVideoInfo&&Object.keys(this._recentVideoInfo).forEach((t=>{var i;const r=t.replace(/[a-z]{1}[A-Z]{1}/g,(e=>`${e[0]}_${e[1].toLowerCase()}`));e[`video_${r}`]=null==(i=this._recentVideoInfo)?void 0:i[t]})),e}stop(){var e,t;this._logger.print("stop","invoke"),delete this._player,null==(e=this._removeHandler)||e.call(this),delete this._removeHandler,null==(t=this._remotePauseHandler)||t.call(this),delete this._remotePauseHandler,delete this._stallList,delete this._prePts,delete this._recentVideoInfo,this._videoInWaiting=!1,this._videoInWaitingCallback=!1,this._videoInWaiting100ms=!1}destroy(){this.stop()}getStallInfo({interval:e,frameRateReceived:t,frameRateDecoded:i,bitrate:r}){const o={pts:0,report:{stallCount:0,stallDuration:0,list:[]},callback:{stallCount:0,stallDuration:0},pauseDuration:this._getPauseDuration()};if(this._stallList){(isSafari||isFirefox)&&(0===r||(i||1/0)<=1||(t||1/0)<=1)||0===this._stallList.length?(o.report.stallDuration=o.callback.stallDuration=2e3,o.report.stallCount=o.callback.stallCount=this._videoInWaiting?0:1,this._openVideoStall100ms&&(o.stall100ms={count:this._videoInWaiting100ms?0:1,duration:2e3}),this._videoInWaiting=!0,this._videoInWaitingCallback=!0,this._videoInWaiting100ms=!0):this._stallList.forEach(((t,i)=>{let r=t.timeUpdateInterval;0===i&&this._videoInWaiting&&(r=Math.round(t.timeUpdateInterval%e));const s=t.timeUpdateInterval>this._stallTimeThreshold.report;s&&(o.report.list.push(t.timeUpdateInterval),o.report.stallDuration+=r,this._videoInWaiting||o.report.stallCount++),this._videoInWaiting=s,t.timeUpdateInterval>this._stallTimeThreshold.callback?(o.callback.stallDuration+=r,this._videoInWaitingCallback||o.callback.stallCount++,this._videoInWaitingCallback=!0):this._videoInWaitingCallback=!1,this._openVideoStall100ms&&(o.stall100ms||(o.stall100ms={count:0,duration:0}),t.timeUpdateInterval>100?(o.stall100ms.duration+=r,this._videoInWaiting100ms||o.stall100ms.count++,this._videoInWaiting100ms=!0):this._videoInWaiting100ms=!1),o.pts=t.playTime})),this._stallList=[]}return o}_getPauseDuration(){let e=this._pauseDuration;if(this._pauseDuration=0,this._isPaused){const t=getServerNow(),i=t-(this._pauseStart||0);i>500&&(this._pauseStart=t,e+=i)}return e}_onVideoPause(e){if("pause"===e.eventName)this._isPaused=!0,this._pauseStart=getServerNow();else if("play"===e.eventName&&this._isPaused){this._isPaused=!1;const e=getServerNow()-this._pauseStart;e>500&&(this._pauseDuration+=e)}}_onVideoTimeupdate(e,t){if("timeupdate"===e.eventName){const e=t.domElement;if(!e||0===e.currentTime)return;if(void 0===this._prePts)return void(this._prePts=e.currentTime);if(this._stallList||(this._stallList=[]),e.currentTime>this._prePts){const t=e.currentTime-this._prePts;this._stallList.push({playTime:e.currentTime,timeUpdateInterval:Math.round(1e3*t)})}this._prePts=e.currentTime}}_onVideoRefresh(e,t){var i,r;if(this._stallList||(this._stallList=[]),this._prePts){const e=t.presentationTime-this._prePts;this._stallList.push({playTime:t.presentationTime,timeUpdateInterval:Math.round(e)})}this._recentVideoInfo=t,this._prePts=t.presentationTime,null==(r=null==(i=this._player)?void 0:i.domElement)||r.requestVideoFrameCallback(this._onVideoRefresh.bind(this))}}const _AudioStallObserver=class{constructor(e){__publicField(this,"_audioStallTimer"),__publicField(this,"_preSample"),__publicField(this,"_isStallInPreCallbackEnd",!1),__publicField(this,"_isStallInPreReportEnd",!1),__publicField(this,"_stallList",[]),this._stream=e}static setAudioStallConfig(e){_AudioStallObserver.interval=((null==e?void 0:e.audio_stall_interval)||200)/2,_AudioStallObserver.ratio=(null==e?void 0:e.audio_stall_ratio)||.6}start(e,t){this.stop(),Config2.AUDIO_STALL&&_AudioStallObserver.interval>0&&"number"==typeof e&&"number"==typeof t&&(this._preSample={ts:getServerNow(),concealedSamples:e,totalSamplesReceived:t},this._startStallCountInterval())}stop(){this._stallList=[],this._audioStallTimer&&(clearTimeout(this._audioStallTimer),delete this._audioStallTimer)}destroy(){this.stop()}async getAudioStallInfo(){const e={stats_count:this._stallList.filter((e=>!!e.get_stats_cost)).length,stall_list:[...this._stallList]};try{await this._audioStallCount()}catch(e){}const t=computeStallInfo(this._stallList,2,this._isStallInPreReportEnd);this._isStallInPreReportEnd=t.isStallInEnd;const i=Config2.AUDIO_STALL_DATA/_AudioStallObserver.interval,r=computeStallInfo(this._stallList,i,this._isStallInPreCallbackEnd);return this._isStallInPreCallbackEnd=r.isStallInEnd,this.stop(),this._startStallCountInterval(),{report:{stall_count:t.stall_count,stall_duration:t.stall_duration,list:t.list},callback:{stall_count:r.stall_count,stall_duration:r.stall_duration,list:r.list},extra:e}}_startStallCountInterval(){const e=async()=>{clearTimeout(this._audioStallTimer),delete this._audioStallTimer,await this._audioStallCount(),this._audioStallTimer||(this._audioStallTimer=setTimeout(e,_AudioStallObserver.interval))};this._audioStallTimer=setTimeout(e,_AudioStallObserver.interval)}async _audioStallCount(){var e;if(!this._preSample||getServerNow()-this._preSample.ts<.5*_AudioStallObserver.interval)return;const{hasAudio:t,subAudio:i,virtual:r,virtualOccupy:o,removeTrack:s,audioTrack:n}=this._stream;if(s||!n)return clearTimeout(this._audioStallTimer),void delete this._audioStallTimer;const a=t&&i;if(!a||r&&!o)this._preSample.ts=getServerNow(),this._stallList.push({reason:a?`virtual: ${r}, virtualOccupy: ${o}`:`hasAudio: ${t}, subAudio: ${i}`});else{const t=getServerNow();let i,r,o=0;try{const t=await(null==(e=this._stream.audioTransceiver)?void 0:e.receiver.getStats());null==t||t.forEach((e=>{"inbound-rtp"===e.type&&(i=e),o++}))}catch(e){r=e.message||JSON.stringify(e)}const s=getServerNow(),n=getServerNow(),a=n-this._preSample.ts;if(i){const{concealedSamples:e,totalSamplesReceived:r}=i,o=e-this._preSample.concealedSamples,d=r-this._preSample.totalSamplesReceived,c=o>=0&&d>=0&&o>=_AudioStallObserver.ratio*d;this._stallList.push({concealed:o,received:d,diff:a,start:this._preSample.ts,end:n,get_stats_cost:s-t,get_stats_start:t,get_stats_end:s,is_stall:c}),this._preSample.concealedSamples=e,this._preSample.totalSamplesReceived=r,this._preSample.ts=n}else this._stallList.push({diff:a,start:this._preSample.ts,end:n,get_stats_cost:s-t,get_stats_start:t,get_stats_end:s,reason:o?r||"no inbound-rtp":"no report"})}}};let AudioStallObserver=_AudioStallObserver;__publicField(AudioStallObserver,"interval",100),__publicField(AudioStallObserver,"ratio",.6);const computeStallInfo=(e,t,i)=>{var r;const o={stall_count:0,stall_duration:0,isStallInEnd:!1,list:[]};let s=0,n=0;for(let i=0;i<e.length;i++){const r=e[i];r.is_stall&&(s++,n+=r.diff||0);const a=i===e.length-1;if(!r.is_stall||a){let r=s>=t;const d=i+t-s-1;if(!r&&s>2){let o=0;e.slice(i+1,d+1).forEach((e=>{e.is_stall&&(o+=e.diff||0)})),r=n+o>AudioStallObserver.interval*t*AudioStallObserver.ratio,r&&(i=d,n+=o)}r&&(o.stall_count++,o.stall_duration+=n,o.list.push(n)),a&&(o.isStallInEnd=r),s=n=0}}return!0===(null==(r=e[0])?void 0:r.is_stall)&&i&&o.stall_count>0&&o.stall_count--,o};var RTCExtensionType=(e=>(e[e.CAPTURE=0]="CAPTURE",e[e.PRE_PROCESSING=1]="PRE_PROCESSING",e[e.ENCODE=2]="ENCODE",e[e.TRANSFER=3]="TRANSFER",e[e.POST_PROCESSING=4]="POST_PROCESSING",e[e.DECODE=5]="DECODE",e[e.RENDERING=6]="RENDERING",e))(RTCExtensionType||{}),StreamIndex=(e=>(e[e.STREAM_INDEX_MAIN=0]="STREAM_INDEX_MAIN",e[e.STREAM_INDEX_SCREEN=1]="STREAM_INDEX_SCREEN",e))(StreamIndex||{});class ExtensionManager{constructor(e){__publicField(this,"_plugins",new Map),this.id=e}register(e){const t=this._plugins.get(e.type)||[];if(t.findIndex((t=>t.name===e.name))>-1)throw new Error(`Failed to register ${e.name}: name is repeated.`);t.push(e),this._plugins.set(e.type,t)}getPluginsByType(e){return this._plugins.get(e)||[]}getPluginByName(e,t){return(this._plugins.get(e)||[]).find((e=>e.name===t))}async getPreProcessingTrack(e){const t=this._plugins.get(1)||[];let i=e.mediaTrack;for(const r of t)i=await r.effect(e,i);return i}destroy(){this._plugins.forEach((e=>{e.forEach((e=>e.destroy()))})),this._plugins.clear()}}const logger$9=new Logger$1("InternalEventBus",1);var InternalEvent=(e=>(e.ON_IOS_INTERRUPTION_START="ON_IOS_INTERRUPTION_START",e.ON_IOS_INTERRUPTION_END="ON_IOS_INTERRUPTION_END",e.ON_IOS_LOCAL_TRACK_MUTE="ON_IOS_LOCAL_TRACK_MUTE",e.ON_IOS_LOCAL_TRACK_UNMUTE="ON_IOS_LOCAL_TRACK_UNMUTE",e))(InternalEvent||{});class InternalEventBus extends eventemitter3Exports.EventEmitter{emit(e,...t){return logger$9.info(e),super.emit(e,...t)}}const internalEventBus=new InternalEventBus;var dumpAudioDataWorklet="data:application/javascript;base64,Y2xhc3MgRHVtcEF1ZGlvRGF0YSBleHRlbmRzIEF1ZGlvV29ya2xldFByb2Nlc3NvciB7CiAgcHJvY2VzcyhpbnB1dHMpIHsKICAgIHRoaXMucG9ydC5wb3N0TWVzc2FnZSh7CiAgICAgIGRhdGE6IGlucHV0c1swXSwKICAgICAgY2hhbm5lbENvdW50OiBpbnB1dHNbMF0ubGVuZ3RoLAogICAgICBzYW1wbGVSYXRlLAogICAgfSk7CiAgICByZXR1cm4gdHJ1ZTsKICB9Cn0KCnJlZ2lzdGVyUHJvY2Vzc29yKCdkdW1wLWF1ZGlvLWRhdGEnLCBEdW1wQXVkaW9EYXRhKTsK";const logger$8=new Logger$1("AudioContext",1);class WebAudioManager{constructor(){__publicField(this,"isWorkletReady"),__publicField(this,"_audioContextInstance"),__publicField(this,"_previousState",""),__publicField(this,"_currentState",""),__publicField(this,"_contextStuckAt",0);let e=0;isSSR()||setInterval((()=>{if(this._audioContextInstance){const t=this._audioContextInstance.currentTime;this._contextStuckAt?this._contextStuckAt!==t&&(this._contextStuckAt=0,logger$8.info("currentTime resume"),reportGlobalInvokeStatus("currentTime resume","")):t&&e===t&&(this._contextStuckAt=t,logger$8.warn("currentTime stuck",this._contextStuckAt),this._audioContextInstance.suspend(),this._audioContextInstance.resume(),reportGlobalInvokeStatus("AudioContext currentTime stuck",this._contextStuckAt)),e=t}}),3e3)}getAudioContextInstance(){if(!this._audioContextInstance){const e=window.AudioContext||window.webkitAudioContext;this._audioContextInstance=is48kSupported?new e:new e({sampleRate:44100});try{this.isWorkletReady=this._audioContextInstance.audioWorklet.addModule(dumpAudioDataWorklet),this.isWorkletReady.catch((e=>{reportGlobalError("initial AudioWorklet error in promise",-1,`${e.name}-${e.message}`),logger$8.error("isWorkletReady",e),this.isWorkletReady=null}))}catch(e){reportGlobalError("initial AudioWorklet error in catch",-1,`${e.name}-${e.message}`),logger$8.error("isWorkletReady",e),this.isWorkletReady=null}this._audioContextInstance.onstatechange=()=>{var e,t,i;logger$8.warn("state change",null==(e=this._audioContextInstance)?void 0:e.state),this._previousState=this._currentState,this._currentState=(null==(t=this._audioContextInstance)?void 0:t.state)||"","interrupted"===(null==(i=this._audioContextInstance)?void 0:i.state)&&this._audioContextInstance.resume(),(isIOS||isIPad)&&("running"===this._previousState&&"interrupted"===this._currentState&&internalEventBus.emit(InternalEvent.ON_IOS_INTERRUPTION_START),"interrupted"===this._previousState&&"running"===this._currentState&&internalEventBus.emit(InternalEvent.ON_IOS_INTERRUPTION_END))}}return this._audioContextInstance}}class AudioLevelFetcher{constructor(e){__publicField(this,"_ctx"),__publicField(this,"_analyserNode"),__publicField(this,"_audioSource"),__publicField(this,"currentTrackId"),this.currentTrackId=e.id;const t=audioContextManager.getAudioContextInstance();if(e instanceof MediaStreamTrack){const i=new MediaStream;i.addTrack(e),this._audioSource=t.createMediaStreamSource(i)}else this._audioSource=t.createMediaElementSource(e),this._audioSource.connect(t.destination);const i=t.createAnalyser();this._audioSource.connect(i),this._analyserNode=i,this._ctx=t}getAudioLevel(){var e;"suspended"===(null==(e=this._ctx)?void 0:e.state)&&this._ctx.resume();const t=new Uint8Array(2048);this._analyserNode.getByteTimeDomainData(t);let i=0;t.forEach((e=>i=Math.max(i,Math.abs(e-128))));const r=i/128*255;return r>2?r:0}async resume(){var e;await(null==(e=this._ctx)?void 0:e.resume())}destroy(){this._audioSource.disconnect(),this._analyserNode.disconnect()}}class AudioDataFetcher extends eventemitter3Exports.EventEmitter{constructor(e,t,i=audioContextManager.getAudioContextInstance(),r=audioContextManager.isWorkletReady){super(),__publicField(this,"_ctx"),__publicField(this,"_worklet"),__publicField(this,"_source"),__publicField(this,"_buffers",[]),__publicField(this,"_bufferLength",0),__publicField(this,"_sampleRate"),__publicField(this,"_channelCount"),__publicField(this,"_frameSize"),e instanceof MediaStreamTrack?this._channelCount=e.getSettings().channelCount??1:this._channelCount=e.channelCount,this._ctx=i,this._frameSize=t,null==r||r.then((()=>{this._worklet=new AudioWorkletNode(this._ctx,"dump-audio-data"),e instanceof MediaStreamTrack?this._source=this._ctx.createMediaStreamSource(new MediaStream([e])):this._source=e,this._source.connect(this._worklet),this._initWorkletEventListener(this._worklet)})).catch()}_initWorkletEventListener(e){e.port.onmessage=this._handleWorkletMessage.bind(this)}_handleWorkletMessage(e){const{data:t,sampleRate:i}=e.data;if(this._bufferLength>=this._frameSize||this._sampleRate!==i){if(this._sampleRate){const e=1===this._channelCount||1===t.length?1:2;this.emit("data",{channels:[...this._buffers],sampleRate:this._sampleRate,channelCount:e})}this._sampleRate=i,this._buffers=new Array(this._channelCount).fill(0).map((()=>new Float32Array(this._frameSize))),this._bufferLength=0}for(let e=0;e<this._channelCount;e++)this._buffers[e].set(t[e],this._bufferLength);this._bufferLength=this._bufferLength+t[0].length}setFrameSize(e){this._frameSize=e}destroy(){var e,t,i;this.removeAllListeners("data"),this._worklet&&(null==(e=this._source)||e.disconnect(this._worklet)),null==(t=this._worklet)||t.disconnect(),null==(i=this._worklet)||i.port.close(),this._buffers=[],delete this._source,delete this._worklet}}const audioContextManager=new WebAudioManager,createElement=(e,t={})=>{const i=document.createElement(e);return t.id&&(i.id=t.id),t.classList&&t.classList.forEach((e=>{i.classList.add(e)})),t.style&&Object.assign(i.style,t.style),t.attributes&&Object.entries(t.attributes).forEach((([e,t])=>{"muted"===e?i.muted=!0:i.setAttribute(e,t)})),i};class DeviceDetector extends EnhancedEventEmitter{constructor(){var e;super(),__publicField(this,"deviceMap",{audioinput:new Map,audiooutput:new Map,videoinput:new Map}),__publicField(this,"checkDeviceChangeTimer",null),__publicField(this,"isSupportedPermissionsQuery",!1),__publicField(this,"isGrantedMicrophonePermission",!1),__publicField(this,"isGrantedCameraPermission",!1),this.isSupportedPermissionsQuery=!isSSR()&&!!(null==(e=null==navigator?void 0:navigator.permissions)?void 0:e.query),this._handleDeviceChange=this._handleDeviceChange.bind(this),!isSSR()&&this.initListener().then((()=>{this.updateDeviceListInSilent()}))}async refreshDevices(e="audio"){if(!navigator.mediaDevices)return;let t;if(isFirefox)try{t="audio"===e?await navigator.mediaDevices.getUserMedia({audio:!0}):await navigator.mediaDevices.getUserMedia({video:!0})}catch(e){}const i=await navigator.mediaDevices.enumerateDevices();t&&t.getTracks().forEach((e=>e.stop())),i.forEach((e=>{var t;e.deviceId&&(null==(t=this.deviceMap[e.kind])||t.set(e.deviceId,e))}))}async initListener(){var e,t;if(void 0!==(null==(e=navigator.mediaDevices)?void 0:e.ondevicechange)&&"function"==typeof(null==(t=navigator.mediaDevices)?void 0:t.addEventListener)?navigator.mediaDevices.addEventListener("devicechange",(()=>{this._handleDeviceChange(),setTimeout((()=>{this._handleDeviceChange()}),300)})):this.checkDeviceChangeTimer=window.setInterval((()=>{this._handleDeviceChange()}),3e3),this.isSupportedPermissionsQuery){try{const e=await navigator.permissions.query({name:"microphone"});this.isGrantedMicrophonePermission="granted"===e.state,e.addEventListener("change",(()=>{this.isGrantedMicrophonePermission="granted"===e.state}))}catch{}try{const e=await navigator.permissions.query({name:"camera"});this.isGrantedCameraPermission="granted"===e.state,e.addEventListener("change",(()=>{this.isGrantedCameraPermission="granted"===e.state}))}catch{}}}async _handleDeviceChange(){if(!navigator.mediaDevices)return;let e;isFirefox&&(e=await navigator.mediaDevices.getUserMedia({audio:!0}));let t=await navigator.mediaDevices.enumerateDevices();t=t.filter((e=>!!e.deviceId)),e&&e.getTracks().forEach((e=>e.stop()));const i=Array.from([...this.deviceMap.audioinput.values(),...this.deviceMap.videoinput.values(),...this.deviceMap.audiooutput.values()]);(isMobile||isIPad)&&!i.length&&t.length&&t.forEach((e=>{var t;null==(t=this.deviceMap[e.kind])||t.set(e.deviceId,e)})),i.forEach((e=>{t.find((t=>t.deviceId===e.deviceId&&t.kind===e.kind&&t.label===e.label))||(this.deviceMap[e.kind].delete(e.deviceId),e.kind.includes("video")?this.emit(EngineEventsTypes.onVideoDeviceStateChanged,{mediaDeviceInfo:e,deviceState:"inactive"}):e.kind.includes("audio")&&this.emit(EngineEventsTypes.onAudioDeviceStateChanged,{mediaDeviceInfo:e,deviceState:"inactive"}))})),t.forEach((e=>{const t=this.deviceMap[e.kind].get(e.deviceId);this.deviceMap[e.kind].set(e.deviceId,e),t||(e.kind.includes("video")?this.emit(EngineEventsTypes.onVideoDeviceStateChanged,{mediaDeviceInfo:e,deviceState:"active"}):e.kind.includes("audio")&&this.emit(EngineEventsTypes.onAudioDeviceStateChanged,{mediaDeviceInfo:e,deviceState:"active"}))}))}async getUserMedia(e){const t=await navigator.mediaDevices.getUserMedia(e);return(null==e?void 0:e.audio)&&(this.isGrantedMicrophonePermission=!0),(null==e?void 0:e.video)&&(this.isGrantedCameraPermission=!0),(null==e?void 0:e.video)?this.refreshDevices("video"):this.refreshDevices("audio"),t}async checkPermissionsByDevices(){const e={audio:!1,video:!1};if(!navigator.mediaDevices)return e;const t=await navigator.mediaDevices.enumerateDevices();return e.audio=t.filter((e=>"audioinput"===e.kind&&e.label&&e.deviceId)).length>0,e.video=t.filter((e=>"videoinput"===e.kind&&e.label&&e.deviceId)).length>0,e}async getPermissions(e={}){var t,i,r;let{audio:o,video:s}=e;const{force:n}=e;o||s||(o=!0,s=!0);const a={audio:!1,video:!1,reason:void 0};if(!n)if(this.isSupportedPermissionsQuery){if(o&&s){if(this.isGrantedMicrophonePermission&&this.isGrantedCameraPermission)return a.audio=!0,a.video=!0,a}else if(o&&this.isGrantedMicrophonePermission||s&&this.isGrantedCameraPermission)return a.audio=this.isGrantedMicrophonePermission,a.video=this.isGrantedCameraPermission,a}else{const e=await this.checkPermissionsByDevices();if(o&&s){if(e.audio&&e.video)return e}else if(o&&e.audio||s&&e.video)return e}if(null==(t=navigator.mediaDevices)?void 0:t.getUserMedia)try{const e=await navigator.mediaDevices.getUserMedia({audio:o,video:s});e&&(e.getTracks().forEach((e=>e.stop())),o&&(a.audio=!0,this.isGrantedMicrophonePermission=!0),s&&(a.video=!0,this.isGrantedCameraPermission=!0))}catch(e){a.reason=e,this.isSupportedPermissionsQuery&&(o&&(a.audio="granted"===(null==(i=await navigator.permissions.query({name:"microphone"}).catch((()=>{})))?void 0:i.state)),s&&(a.video="granted"===(null==(r=await navigator.permissions.query({name:"camera"}).catch((()=>{})))?void 0:r.state)))}return o?await this.refreshDevices("audio"):await this.refreshDevices("video"),a}async updateDeviceListInSilent(){this.isGrantedCameraPermission&&this.isGrantedMicrophonePermission&&this.refreshDevices("audio")}async enumerateDevices(){return await this.getPermissions(),await this.refreshDevices(),Array.from([...this.deviceMap.audioinput.values(),...this.deviceMap.videoinput.values(),...this.deviceMap.audiooutput.values()])}async enumerateAudioCaptureDevices(){return await this.getPermissions({audio:!0}),await this.refreshDevices(),Array.from(this.deviceMap.audioinput.values())}async enumerateVideoCaptureDevices(){return await this.getPermissions({video:!0}),await this.refreshDevices("video"),Array.from(this.deviceMap.videoinput.values())}async enumerateAudioPlaybackDevices(){return await this.getPermissions({audio:!0}),await this.refreshDevices("audio"),Array.from(this.deviceMap.audiooutput.values())}async getAudioPlaybackDeviceById(e){return(await this.enumerateAudioPlaybackDevices()).find((t=>t.deviceId===e))}}const dd=new DeviceDetector;isDebuggerMode&&(window.__rtc_dd__=dd);var RtcErrorCode=(e=>(e[e.AUTOPLAY_FAILED=-1e3]="AUTOPLAY_FAILED",e[e.TRACK_ERROR=-1001]="TRACK_ERROR",e[e.Fetch_MODIFY=-1002]="Fetch_MODIFY",e[e.BLACK_BROWSER=-1003]="BLACK_BROWSER",e[e.DC_SEND_ERROR=-1004]="DC_SEND_ERROR",e[e.DUPLICATE_DOM=-1005]="DUPLICATE_DOM",e))(RtcErrorCode||{});const logger$7=new Logger$1("VideoSnapshot",1),getPlayingVideoDom=e=>{const t=null==e?void 0:e.domElement;if(t&&!t.paused&&4===t.readyState)return t},takeSnapshot=async(e,t)=>{const i=document.createElement("canvas"),r=i.getContext("2d");if(!r)throw new Error("canvas.getContext error");const o=(e,t,o)=>(t=t||e.width,o=o||e.height,i.width=t,i.height=o,r.setTransform(1,0,0,1,0,0),r.drawImage(e,0,0,t,o),r.getImageData(0,0,t,o)),s=Date.now(),n=getPlayingVideoDom(t);if(n){if(logger$7.info("takeSnapshot","VideoPlayer already set."),null==t?void 0:t.isAlpha){logger$7.info("takeSnapshot","manually process alpha video");const e=n.videoWidth,o=n.videoHeight,a=t.videoHeight;i.width=e,i.height=a,r.drawImage(n,0,o/2,e,o/2,0,0,e,a);const d=r.getImageData(0,0,e,a);return logger$7.info("takeSnapshot",`success (alpha manual), cost ${Date.now()-s}ms`),d}const e=(null==t?void 0:t.videoWidth)||n.videoWidth,a=(null==t?void 0:t.videoHeight)||n.videoHeight,d=await o(n,e,a);return logger$7.info("takeSnapshot",`success, cost ${Date.now()-s}ms`),d}if(window.ImageCapture){const t=new window.ImageCapture(e);if("live"===t.track.readyState&&t.track.enabled&&!t.track.muted){logger$7.info("takeSnapshot","use ImageCapture");const e=await o(await t.grabFrame());return logger$7.info("takeSnapshot",`success, cost ${Date.now()-s}ms`),e}}return logger$7.info("takeSnapshot","use temp video"),new Promise(((t,i)=>{const r=new MediaStream([e]),n=document.createElement("video");n.setAttribute("playsinline",""),n.muted=!0,document.body.appendChild(n),n.onplaying=()=>{const i=o(n,n.videoWidth,n.videoHeight);logger$7.info("takeSnapshot",`success, cost ${Date.now()-s}ms`),t(i),r.removeTrack(e),n.srcObject=null,n.load()},n.onerror=i,n.srcObject=r,n.play()}))},DEFAULT_PLAYER_ID=Symbol("default");var PlayerStallEvent=(e=>(e.START_STALL_OBSERVE="start_stall_observe",e.STOP_STALL_OBSERVE="stop_stall_observe",e))(PlayerStallEvent||{});class LocalVideoTrack extends LocalTrack{constructor(e,t,i){super(e,t,{...i,mediaType:MediaType.VIDEO}),__publicField(this,"resolution"),__publicField(this,"videoPlayers",new Map),this.resolution={width:0,height:0}}intersection(){const e={};return this.videoPlayers.forEach(((t,i)=>{e[i.toString()]=t.isIntersecting})),e}async updateVideoCaptureConfig(e){this.logger.info("updateVideoEncoderConfig","update localVideoTrack: ",e);const t={...e};delete t.contentHint,isFirefox&&this.trackInfo.streamIndex===ExtendStreamIndex.MAIN&&(t.frameRate={ideal:30,max:30}),await this.originTrack.applyConstraints(t);const i=this.originTrack.getSettings();(i.width&&i.width!==this.resolution.width||i.height&&i.height!==this.resolution.height)&&(this.resolution={width:i.width,height:i.height},this.emit("resolution-change",this.resolution))}setContentHint(e){"contentHint"in this.originTrack&&["text","motion","detail"].includes(e)&&(this.originTrack.contentHint=e)}setTrack(e,t){this._originTrack=e,this.trackInfo={...this.trackInfo,...t},this.isTrackReady=this.generatePreProcessingTrack()}setPlayer(e,t,i,r){const o=e.playerId??DEFAULT_PLAYER_ID;let s=this.videoPlayers.get(o);return e.player!==s&&(s=e.player,this.videoPlayers.set(o,s),r(s,this.isPublic,this.streamIndex)),this.mirror(!!t),this.dummy||i===RTCAutoPlayPolicy.PLAY_MANUALLY||this.play(o),s.domElement}setUserId(e){this.trackInfo.streamUserId=e,this.videoPlayers.forEach((t=>{t.userId=e}))}snapshot(){let e;for(const t of this.videoPlayers.values())if(t.played){e=t;break}return takeSnapshot(this.preprocessingTrack,e)}setRenderMode(e,t){var i;return null==(i=this.videoPlayers.get(e))?void 0:i.setRenderMode(t)}mirror(e){this.videoPlayers.forEach((t=>{t.mirror(e)}))}removePlayerTrack(){this.videoPlayers.forEach(((e,t)=>{var i;null==(i=this.videoPlayers.get(t))||i.removeTrack()}))}play(e){const t=this.videoPlayers.get(e);return(null==t?void 0:t.played)?t.manuallyPlay():null==t?void 0:t.playVideo(this)}playAll(){this.videoPlayers.forEach(((e,t)=>{this.play(t)}))}manuallyPlay(e){var t;return null==(t=this.videoPlayers.get(e))?void 0:t.manuallyPlay()}pause(e){var t;null==(t=this.videoPlayers.get(e))||t.manuallyPause()}stop(e){var t;return null==(t=this.videoPlayers.get(e))?void 0:t.stop()}stopAll(){return this.videoPlayers.forEach(((e,t)=>{this.stop(t)}))}removePlayer(e){this.videoPlayers.delete(e)}destroy(){this.videoPlayers.forEach(((e,t)=>{this.stop(t),e.removeAllListeners(),this.videoPlayers.delete(t)})),super.destroy()}}class RemoteVideoTrack extends RemoteTrack{constructor(e,t,i,r){super(e,t,{...r,mediaType:MediaType.VIDEO}),__publicField(this,"videoPlayers",new Map),__publicField(this,"_stream"),__publicField(this,"_observingPlayer"),this._stream=i}get observingPlayerId(){var e;return null==(e=this._observingPlayer)?void 0:e.playerId}getSizeByPlayer(){let e=0,t=0;return this.videoPlayers.forEach((i=>{i.videoWidth&&i.videoHeight&&(e=i.videoWidth,t=i.videoHeight)})),{width:e,height:t}}intersection(){const e={};return this.videoPlayers.forEach(((t,i)=>{e[i.toString()]=t.isIntersecting})),e}setPlayer(e,t,i,r){const o=t.playerId??DEFAULT_PLAYER_ID;let s=this.videoPlayers.get(o);return t.player!==s&&(s=t.player,isUndefined(this.streamIndex)||s.mirror(this._ctx.getRemoteMirrorType(this.trackInfo.streamUserId??"",this.streamIndex)),this.videoPlayers.set(o,s),this._handlePlayerStallEvent(s),r(s,this.isPublic,this.streamIndex)),this.dummy||this.play(o),null==s?void 0:s.domElement}mirror(e){this.videoPlayers.forEach((t=>{t.mirror(e)}))}dangerousGetPlayer(e){return this.videoPlayers.get(e)}snapshot(){let e;for(const t of this.videoPlayers.values())if(t.played){e=t;break}return takeSnapshot(this.preprocessingTrack,e)}stop(e){var t;null==(t=this.videoPlayers.get(e))||t.stop()}stopAll(){this.videoPlayers.forEach(((e,t)=>{this.stop(t)}))}play(e){if(this._ctx.autoPlayPolicy===RTCAutoPlayPolicy.PLAY_MANUALLY)return;const t=this.videoPlayers.get(e);return null==t?void 0:t.playVideo(this)}manuallyPlay(e){const t=this.videoPlayers.get(e);return(null==t?void 0:t.played)?t.manuallyPlay():null==t?void 0:t.playVideo(this)}pause(e){var t;return null==(t=this.videoPlayers.get(e))?void 0:t.manuallyPause()}_handlePlayerStallEvent(e){e.on("start_stall_observe",(()=>{!this._observingPlayer&&e&&(this._observingPlayer=e,this._stream.startVideoStallObserve(this._observingPlayer))})),e.on("stop_stall_observe",(()=>{this._observingPlayer===e&&(this._stream.stopVideoStallObserve(),this._observingPlayer=void 0,this.videoPlayers.forEach((e=>{!this._observingPlayer&&e.played&&(this._observingPlayer=e,this._stream.startVideoStallObserve(e))})))}))}removePlayer(e){this.videoPlayers.delete(e)}setAlphaInfo(e){this.videoPlayers.forEach((t=>{t.setAlphaInfo(e)}))}destroy(){this.videoPlayers.forEach(((e,t)=>{this.stop(t),e.removeAllListeners(),this.videoPlayers.delete(t)})),super.destroy()}}class AlphaVideoRenderer{constructor(){__publicField(this,"canvas"),__publicField(this,"gl",null),__publicField(this,"program",null),__publicField(this,"videoTexture",null),__publicField(this,"animationFrameId",null),__publicField(this,"isRendering",!1),__publicField(this,"positionBuffer",null),__publicField(this,"texCoordBuffer",null),__publicField(this,"positionLocation",-1),__publicField(this,"texCoordLocation",-1),__publicField(this,"textureLocation",null),__publicField(this,"render",(e=>{if(this.isRendering&&this.gl&&this.program){if(e.videoWidth>0&&e.videoHeight>0){const t=e.videoHeight/2;this.canvas.width===e.videoWidth&&this.canvas.height===t||(this.canvas.width=e.videoWidth,this.canvas.height=t,this.gl.viewport(0,0,this.canvas.width,this.canvas.height))}this.gl.clearColor(0,0,0,0),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.enable(this.gl.BLEND),this.gl.blendFunc(this.gl.SRC_ALPHA,this.gl.ONE_MINUS_SRC_ALPHA),this.gl.useProgram(this.program),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.positionBuffer),this.gl.enableVertexAttribArray(this.positionLocation),this.gl.vertexAttribPointer(this.positionLocation,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.texCoordBuffer),this.gl.enableVertexAttribArray(this.texCoordLocation),this.gl.vertexAttribPointer(this.texCoordLocation,2,this.gl.FLOAT,!1,0,0),this.gl.uniform1i(this.textureLocation,0),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4),this.animationFrameId=requestAnimationFrame((()=>this.render(e)))}})),this.canvas=document.createElement("canvas"),this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.objectFit="contain",this.initWebGL()}initWebGL(){try{if(this.gl=this.canvas.getContext("webgl")||this.canvas.getContext("experimental-webgl"),!this.gl)return console.error("WebGL not supported"),!1;const e="\n attribute vec2 a_position;\n attribute vec2 a_texCoord;\n varying vec2 v_texCoord;\n\n void main() {\n gl_Position = vec4(a_position, 0.0, 1.0);\n v_texCoord = a_texCoord;\n }\n ",t="\n precision mediump float;\n varying vec2 v_texCoord;\n uniform sampler2D u_texture;\n\n void main() {\n // 上半部分是 alpha 通道 (0.0 - 0.5)\n // 下半部分是 RGB 通道 (0.5 - 1.0)\n\n // 获取 RGB 值(从下半部分)\n vec2 rgbCoord = vec2(v_texCoord.x, v_texCoord.y * 0.5 + 0.5);\n vec4 rgbColor = texture2D(u_texture, rgbCoord);\n\n // 获取 Alpha 值(从上半部分)\n vec2 alphaCoord = vec2(v_texCoord.x, v_texCoord.y * 0.5);\n vec4 alphaColor = texture2D(u_texture, alphaCoord);\n\n // 使用 alpha 通道的灰度值作为透明度\n float alpha = (alphaColor.r + alphaColor.g + alphaColor.b) / 3.0;\n\n gl_FragColor = vec4(rgbColor.rgb, alpha);\n }\n ",i=this.createShader(this.gl.VERTEX_SHADER,e),r=this.createShader(this.gl.FRAGMENT_SHADER,t);return i&&r?(this.program=this.createProgram(i,r),this.program?(this.positionLocation=this.gl.getAttribLocation(this.program,"a_position"),this.texCoordLocation=this.gl.getAttribLocation(this.program,"a_texCoord"),this.textureLocation=this.gl.getUniformLocation(this.program,"u_texture"),this.setupBuffers(),this.videoTexture=this.gl.createTexture(),!0):(console.error("Failed to create program"),!1)):(console.error("Failed to create shaders"),!1)}catch(e){return console.error("Failed to initialize WebGL:",e),!1}}createShader(e,t){if(!this.gl)return null;const i=this.gl.createShader(e);return i?(this.gl.shaderSource(i,t),this.gl.compileShader(i),this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS)?i:(console.error("Shader compile error:",this.gl.getShaderInfoLog(i)),this.gl.deleteShader(i),null)):null}createProgram(e,t){if(!this.gl)return null;const i=this.gl.createProgram();return i?(this.gl.attachShader(i,e),this.gl.attachShader(i,t),this.gl.linkProgram(i),this.gl.getProgramParameter(i,this.gl.LINK_STATUS)?i:(console.error("Program link error:",this.gl.getProgramInfoLog(i)),this.gl.deleteProgram(i),null)):null}setupBuffers(){if(!this.gl)return;this.positionBuffer=this.gl.createBuffer(),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.positionBuffer);const e=new Float32Array([-1,-1,1,-1,-1,1,1,1]);this.gl.bufferData(this.gl.ARRAY_BUFFER,e,this.gl.STATIC_DRAW),this.texCoordBuffer=this.gl.createBuffer(),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.texCoordBuffer);const t=new Float32Array([0,1,1,1,0,0,1,0]);this.gl.bufferData(this.gl.ARRAY_BUFFER,t,this.gl.STATIC_DRAW)}startRender(e){this.isRendering||(this.isRendering=!0,this.render(e))}stopRender(){this.isRendering=!1,null!==this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null)}getCanvas(){return this.canvas}setObjectFit(e){this.canvas.style.objectFit=e}setMirror(e){this.canvas.style.transform=e?"rotateY(180deg)":""}destroy(){this.stopRender(),this.gl&&(this.videoTexture&&(this.gl.deleteTexture(this.videoTexture),this.videoTexture=null),this.positionBuffer&&(this.gl.deleteBuffer(this.positionBuffer),this.positionBuffer=null),this.texCoordBuffer&&(this.gl.deleteBuffer(this.texCoordBuffer),this.texCoordBuffer=null),this.program&&(this.gl.deleteProgram(this.program),this.program=null),this.gl=null),this.canvas.parentElement&&this.canvas.parentElement.removeChild(this.canvas)}}const MEDIA_EVENTS=["play","playing","pause","ended","error","seeking","seeked","waiting","canplay","canplaythrough","durationchange","volumechange","loadedmetadata","loadeddata","loadstart","timeupdate"],AUDIO_ATTRIBUTES={playsinline:"","webkit-playsinline":""},VIDEO_ATTRIBUTES={playsinline:"","webkit-playsinline":"","x5-playsinline":"","x5-video-player-type":"h5","x-webkit-airplay":"allow",preload:"",muted:""},NO_RENDER_VERSION=15,NO_RENDER_RETRY_INTERVAL=1e3,NO_RENDER_RESET_INTERVAL=500;class VideoPlayer extends eventemitter3Exports.EventEmitter{constructor(e,t,i){var r;super(),__publicField(this,"_containerDom"),__publicField(this,"_videoDom"),__publicField(this,"_alphaRenderer"),__publicField(this,"_canvasDom"),__publicField(this,"userId"),__publicField(this,"renderMode"),__publicField(this,"mirrorType",MirrorType.MIRROR_TYPE_NONE),__publicField(this,"isScreen"),__publicField(this,"isLocal"),__publicField(this,"isAlpha"),__publicField(this,"alphaInfo"),__publicField(this,"played",!1),__publicField(this,"_needLoad",!1),__publicField(this,"_emitPlayFailed",!1),__publicField(this,"_videoContainer"),__publicField(this,"_safari15VideoTimer"),__publicField(this,"_monitor"),__publicField(this,"logger"),__publicField(this,"_onLocalTrackMute"),__publicField(this,"_onInterruptionEnd"),__publicField(this,"_needResume",!1),__publicField(this,"_rotate",0),__publicField(this,"_rotateDom"),__publicField(this,"_resizeObserver"),__publicField(this,"_hasManuallyPaused",!1),__publicField(this,"isIntersecting"),__publicField(this,"intersectionObserver"),__publicField(this,"hasStartPlaying",!1),__publicField(this,"emitVideoEvent",(e=>{var t,i;const r={type:"video",rawEvent:e,readyState:(null==(t=this._videoDom)?void 0:t.readyState)||0,userId:this.userId,eventName:e.type,currentTime:(null==(i=this._videoDom)?void 0:i.currentTime)||0,isScreen:this.isScreen};switch(this.emit("playback_event",r),e.type){case"canplay":this.refreshRenderSize("the video started playing."),this._internalPlay();break;case"loadeddata":this._internalPlay();break;case"playing":this.logger.info("VideoPlayerPlaying",`[userId-${this.userId}] video element playing`);break;case"pause":this.logger.info("VideoPlayerPause",`[userId-${this.userId}] video element pause`),this._needResume?(this.logger.info("VideoPlayerPause",`[userId-${this.userId}] video element resume`),this._internalPlay(),this._needResume=!1):this._hasManuallyPaused||(this.logger.info("VideoPlayerPause",`[userId-${this.userId}] video element resume`),getParameter("AUTOPLAY_THROTTLE")?this._throttledInternalPlay():this._internalPlay())}})),__publicField(this,"_internalPlay",(()=>{var e,t;if(reportRtcInvokeStatus(this.engineId,"video _internalPlay",{paused:null==(e=this._videoDom)?void 0:e.paused,hasManuallyPaused:this._hasManuallyPaused}),this._hasManuallyPaused||!(null==(t=this._videoDom)?void 0:t.paused))return;const i=this._videoDom.play();(null==i?void 0:i.then)&&i.then((()=>{var e;this.isLocal&&isCriOS&&!this._needLoad&&(null==(e=this._videoDom)||e.load(),this._needLoad=!0)})).catch((e=>{var t,i,r,o;this._emitPlayFailed||("AbortError"!==e.name?(this._emitPlayFailed=!0,null==(i=this._monitor)||i.report("rtc_error",{message:`video autoplay failed, userId: ${this.userId}, ${e.name}`,error_code:RtcErrorCode.AUTOPLAY_FAILED}),this.emit("playback_event",{type:"video",rawEvent:e,readyState:(null==(r=this._videoDom)?void 0:r.readyState)||0,userId:this.userId,eventName:"autoplay-error",currentTime:(null==(o=this._videoDom)?void 0:o.currentTime)||0,isScreen:this.isScreen})):null==(t=this._monitor)||t.report("rtc_error",{message:`video autoplay failed, userId: ${this.userId}, ${e.name}`,error_code:RtcErrorCode.AUTOPLAY_FAILED}))}))})),__publicField(this,"_throttledInternalPlay",throttle(this._internalPlay,getParameter("AUTOPLAY_THROTTLE"))),this.engineId=e,this.playerId=t;const o=i.renderDom;this._monitor=getMonitor(e),this.logger=new Logger$1("Player",0,e);const{userId:s}=i,n=i.isScreen?VideoRenderMode.RENDER_MODE_FIT:VideoRenderMode.RENDER_MODE_HIDDEN;this.renderMode=void 0!==i.renderMode?i.renderMode:n,this._rotate=Number(i.rotation||0);const a="string"==typeof o?document.getElementById(o):o;if(!a)throw new SDKError(ErrorCode.CANT_FIND_DOM,"can't find dom");this._videoContainer=document.createElement("div"),this._videoContainer.style.width="100%",this._videoContainer.style.height="100%",this._videoContainer.style.position="relative",this._videoContainer.style.overflow="hidden",this._containerDom=a,this.userId=s,this.isLocal=!!i.isLocal,this.isScreen=!!i.isScreen,this.isAlpha=!!(null==(r=i.alphaInfo)?void 0:r.enableAlpha),this.alphaInfo=i.alphaInfo,this._initVideo(),!this.isLocal||15!==(null==iOSVersion?void 0:iOSVersion[0])&&15!==safariVersion||(this._safari15VideoTimer=setTimeout((()=>{try{this._videoContainer.style.display="block",setTimeout((()=>{this._videoContainer.style.display="flex"}),500)}catch(e){}}),1e3))}_initVideo(){this._videoDom||(this._videoDom=createElement("video",{style:{width:"100%",height:"100%"},attributes:VIDEO_ATTRIBUTES}),this._videoDom.id=`${this.userId}_${genUuid()}`,this.setRenderMode(this.renderMode),this.mirror(this.mirrorType===MirrorType.MIRROR_TYPE_RENDER)),this.isAlpha&&this._initAlphaRenderer(),this._containerDom.appendChild(this._videoContainer),[90,270].indexOf(this._rotate)>-1?(this._rotateDom=this._createRotationDiv(),this.isAlpha&&this._canvasDom?(this._videoDom.style.display="none",this._rotateDom.appendChild(this._videoDom),this._rotateDom.appendChild(this._canvasDom)):this._rotateDom.appendChild(this._videoDom),this._videoContainer.appendChild(this._rotateDom)):(180===this._rotate&&(this._videoContainer.style.transform="rotate(180deg)"),this.isAlpha&&this._canvasDom?(this._videoDom.style.display="none",this._videoContainer.appendChild(this._videoDom),this._videoContainer.appendChild(this._canvasDom)):this._videoContainer.appendChild(this._videoDom)),this._initInterSectionObserver(),this._initListeners(),this._onLocalTrackMute=()=>{this._needResume=!0},this._onInterruptionEnd=()=>{this.logger.warn("resume player after iOS interruption"),this._internalPlay()},internalEventBus.on(InternalEvent.ON_IOS_LOCAL_TRACK_MUTE,this._onLocalTrackMute),internalEventBus.on(InternalEvent.ON_IOS_LOCAL_TRACK_UNMUTE,this._onInterruptionEnd),internalEventBus.on(InternalEvent.ON_IOS_INTERRUPTION_END,this._onInterruptionEnd)}_initAlphaRenderer(){this._alphaRenderer||(this._alphaRenderer=new AlphaVideoRenderer,this._canvasDom=this._alphaRenderer.getCanvas(),this._alphaRenderer.setObjectFit(this._getObjectFitFromRenderMode(this.renderMode)),this._alphaRenderer.setMirror(this.mirrorType===MirrorType.MIRROR_TYPE_RENDER))}_getObjectFitFromRenderMode(e){return e===VideoRenderMode.RENDER_MODE_FIT?"contain":e===VideoRenderMode.RENDER_MODE_FILL?"fill":"cover"}_initInterSectionObserver(){!this.intersectionObserver&&"undefined"!=typeof IntersectionObserver&&this._videoDom&&(this.intersectionObserver=new IntersectionObserver((e=>{e[0]&&(this.isIntersecting=e[0].isIntersecting)}),{}),this.intersectionObserver.observe(this._videoDom))}_closeIntersectionObserver(){this.intersectionObserver&&this._videoDom&&(this.intersectionObserver.disconnect(),this.intersectionObserver.unobserve(this._videoDom),delete this.intersectionObserver)}_createRotationDiv(){const e=document.createElement("div");return e.style.transform=`rotate(${this._rotate}deg)`,180!==this._rotate&&(e.style.position="absolute",this.refreshRenderSize("init"),window.ResizeObserver&&(this._resizeObserver=new ResizeObserver((()=>{this.refreshRenderSize("the container size has changed.")})),this._resizeObserver.observe(this._containerDom))),e}refreshRenderSize(e){var t,i;if(this._rotateDom){this.logger.print("refreshRenderSize",`Because ${e}`);const r=Number(window.getComputedStyle(this._containerDom).width.replace("px","")),o=Number(window.getComputedStyle(this._containerDom).height.replace("px","")),s=null==(t=this._videoDom)?void 0:t.videoWidth,n=null==(i=this._videoDom)?void 0:i.videoHeight;if(r&&o&&n&&s){let e,t;if(this.renderMode===VideoRenderMode.RENDER_MODE_FILL)e=o,t=r;else{const i=this.renderMode===VideoRenderMode.RENDER_MODE_HIDDEN?Math.max(r/n,o/s):Math.min(r/n,o/s);e=s*i,t=n*i}this._rotateDom.style.width=`${e}px`,this._rotateDom.style.height=`${t}px`,this._rotateDom.style.left=(r-e)/2+"px",this._rotateDom.style.top=(o-t)/2+"px"}}}_initListeners(){this._videoDom&&MEDIA_EVENTS.forEach((e=>{var t;null==(t=this._videoDom)||t.addEventListener(e,this.emitVideoEvent)}))}_removeListeners(){this._videoDom&&MEDIA_EVENTS.forEach((e=>{var t;null==(t=this._videoDom)||t.removeEventListener(e,this.emitVideoEvent)}))}setRenderMode(e){this.renderMode=e,this._videoDom&&(this._videoDom.style.objectFit=this._getObjectFitFromRenderMode(e)),this._alphaRenderer&&this._alphaRenderer.setObjectFit(this._getObjectFitFromRenderMode(e))}async playVideo(e){var t;let i=this._videoDom;if(this.logger.info("playVideo",`play video track: ${this.userId}`),i&&i.srcObject instanceof MediaStream&&i.srcObject.getTrackById(null==(t=e.preprocessingTrack)?void 0:t.id)){try{reportRtcInvokeStatus(this.engineId,"playVideo","play video repeatedly",0,this.userId)}catch(e){}return}i||(this._initVideo(),i=this._videoDom),this.logger.info("playVideo",`play video by dom: ${null==i?void 0:i.id}`);const r=new MediaStream;r.addTrack(e.preprocessingTrack),i.srcObject=r,i&&!this._containerDom.contains(this._videoContainer)&&this._containerDom.appendChild(this._videoContainer),i&&!this._videoContainer.contains(i)&&this._videoContainer.appendChild(i),setTimeout((()=>this._internalPlay())),this.isAlpha&&this._alphaRenderer&&i&&this._alphaRenderer.startRender(i),Config2.VIDEO_STALL&&this.emit(PlayerStallEvent.START_STALL_OBSERVE),this.played=!0,this.hasStartPlaying=!1}updateSrcObject(e){const t=e.preprocessingTrack;if(!t||!this._videoDom)return;const i=new MediaStream;i.addTrack(t),this._videoDom.srcObject=i}removeTrack(){var e;const t=null==(e=this._videoDom)?void 0:e.srcObject;if(t){const e=t.getVideoTracks();(null==e?void 0:e.length)&&e.forEach((e=>{t.removeTrack(e)}))}}manuallyPlay(){if(this.logger.info("Invoke VideoPlayer.manuallyPlay",this.userId,this.isScreen),this._emitPlayFailed=!1,this._hasManuallyPaused=!1,!this._videoDom)throw new SDKError(ErrorCode.INVALID_PARAMS,"Player not found");return 0!==this._videoDom.readyState||isWeChat?this._videoDom.play():Promise.resolve()}manuallyPause(){if(this.logger.print("Invoke VideoPlayer.manuallyPause",this.userId,this.isScreen),this.played){if(this._hasManuallyPaused=!0,!this._videoDom)throw new SDKError(ErrorCode.INVALID_PARAMS,"Player not found");return this._videoDom.pause()}}mirror(e){this.logger.info("mirror",`${this.userId} set mirror: ${e}`),this.mirrorType=e?MirrorType.MIRROR_TYPE_RENDER:MirrorType.MIRROR_TYPE_NONE,this._videoDom&&(this._videoDom.style.transform=e?"rotateY(180deg)":"",this._alphaRenderer&&this._alphaRenderer.setMirror(e))}stop(e=!1){var t,i,r;const{_containerDom:o}=this;this.logger.info("stop",`stop video track: ${this.userId} ${this.playerId.toString()}`),this._alphaRenderer&&this._alphaRenderer.stopRender(),this._videoDom&&(e||(this._videoDom.srcObject=null),(null==o?void 0:o.contains(this._videoContainer))&&o.removeChild(this._videoContainer),null==(t=this._videoContainer)||t.childNodes.forEach((e=>{e!==this._videoDom&&e!==this._rotateDom&&e!==this._canvasDom||this._videoContainer.removeChild(e)})),(null==(i=this._rotateDom)?void 0:i.contains(this._videoDom))&&this._rotateDom.removeChild(this._videoDom),this._canvasDom&&(null==(r=this._rotateDom)?void 0:r.contains(this._canvasDom))&&this._rotateDom.removeChild(this._canvasDom)),this._hasManuallyPaused=!1,this.played=!1,this.hasStartPlaying=!1,Config2.VIDEO_STALL&&this.emit(PlayerStallEvent.STOP_STALL_OBSERVE),this._closeIntersectionObserver()}destroy(e=!1){var t;this.logger.info("destroy",`video player: ${this.userId}`),this.stop(e),this._alphaRenderer&&(this._alphaRenderer.destroy(),this._alphaRenderer=void 0,this._canvasDom=void 0),null==(t=this._resizeObserver)||t.disconnect(),super.removeAllListeners(),this._removeListeners(),internalEventBus.off(InternalEvent.ON_IOS_LOCAL_TRACK_MUTE,this._onLocalTrackMute),internalEventBus.off(InternalEvent.ON_IOS_LOCAL_TRACK_UNMUTE,this._onInterruptionEnd),internalEventBus.off(InternalEvent.ON_IOS_INTERRUPTION_END,this._onInterruptionEnd),this._videoDom&&delete this._videoDom,this._safari15VideoTimer&&(window.clearInterval(this._safari15VideoTimer),this._safari15VideoTimer=void 0)}get domElement(){return this._videoDom}get videoWidth(){var e;return this._videoDom?this.isAlpha&&(null==(e=this.alphaInfo)?void 0:e.alphaWidth)?this.alphaInfo.alphaWidth:this._videoDom.videoWidth:0}get videoHeight(){var e;return this._videoDom?this.isAlpha?(null==(e=this.alphaInfo)?void 0:e.alphaHeight)?this.alphaInfo.alphaHeight:this._videoDom.videoHeight/2:this._videoDom.videoHeight:0}setAlphaInfo(e){var t;this.logger.info("setAlphaInfo",`set alpha info for user: ${this.userId}`,e),this.isAlpha=!!e.enableAlpha,this.alphaInfo=e,this.isAlpha?(this._alphaRenderer||this._initAlphaRenderer(),this._canvasDom&&this._alphaRenderer?(this._videoDom&&(this._videoDom.style.display="none"),this._rotateDom?this._rotateDom.contains(this._canvasDom)||this._rotateDom.appendChild(this._canvasDom):this._videoContainer.contains(this._canvasDom)||this._videoContainer.appendChild(this._canvasDom),(null==(t=this._videoDom)?void 0:t.srcObject)&&this._alphaRenderer.startRender(this._videoDom)):this.logger.info("setAlphaInfo","alpha renderer already exists or canvas not created")):this.logger.warn("setAlphaInfo","alphaInfo.enableAlpha is false, skip alpha renderer creation")}}class AudioPlayer extends eventemitter3Exports.EventEmitter{constructor(e,t,{divId:i,muted:r,isScreen:o}={divId:void 0,muted:!1,isScreen:!1}){if(super(),__publicField(this,"_containerDom"),__publicField(this,"_audioDom"),__publicField(this,"_fakeAudioDom"),__publicField(this,"userId"),__publicField(this,"muted",!1),__publicField(this,"_emitPlayFailed",!1),__publicField(this,"played",!1),__publicField(this,"isScreen"),__publicField(this,"_wechatTimer"),__publicField(this,"_edgeTimer"),__publicField(this,"_monitor"),__publicField(this,"logger"),__publicField(this,"_pasued",!0),__publicField(this,"hasStartPlaying",!1),__publicField(this,"emitAudioEvent",(e=>{var t,i,r,o;const s={type:"audio",rawEvent:e,readyState:(null==(t=this._audioDom)?void 0:t.readyState)||0,userId:this.userId,eventName:e.type,currentTime:(null==(i=this._audioDom)?void 0:i.currentTime)||0};"playing"===e.type&&this.logger.info("AudioPlayerPlaying",`[userId-${this.userId}] audio element playing`),"pause"===e.type&&(this.logger.info("AudioPlayerPause",`[userId-${this.userId}] audio element pause`),!this._pasued&&(null==(o=null==(r=this._audioDom)?void 0:r.srcObject)?void 0:o.active)&&(getParameter("AUTOPLAY_THROTTLE")?this._throttledInternalPlay():this._internalPlay())),isAndroid&&isWeChat&&("canplay"===e.type?(clearTimeout(this._wechatTimer),this._wechatTimer=setTimeout((()=>{this._autoPlayError("wechat")}),500)):"playing"===e.type&&clearTimeout(this._wechatTimer)),isMobile&&isEdge&&"error"===e.type&&(clearTimeout(this._edgeTimer),this._edgeTimer=setTimeout((()=>{var e;0===(null==(e=this._audioDom)?void 0:e.currentTime)&&this._autoPlayError("edge")}),500)),this.emit("playback_event",s)})),__publicField(this,"_internalPlay",(()=>{var e,t,i;if(reportRtcInvokeStatus(this.engineId,"audio _internalPlay",{paused:null==(e=this._audioDom)?void 0:e.paused,userId:this.userId,screen:this.isScreen}),null==(t=this._audioDom)?void 0:t.paused)try{let e=this._audioDom.play();const t=audioContextManager.getAudioContextInstance();if("suspended"===t.state){const e=t.resume(),i=setTimeout((()=>{var e;"suspended"===t.state&&(this._autoPlayError("AudioContext cannot resume"),null==(e=this._monitor)||e.report("rtc_error",{message:`audio autoplay failed, userId: ${this.userId}: Cannot resume the AudioContext - timeout`,error_code:RtcErrorCode.AUTOPLAY_FAILED})),clearTimeout(i)}));e.catch((e=>{var t;this._autoPlayError("AudioContext cannot resume"),null==(t=this._monitor)||t.report("rtc_error",{message:`audio autoplay failed, userId: ${this.userId}: Cannot resume the AudioContext - rejected by: [${null==e?void 0:e.name}]${null==e?void 0:e.message}`,error_code:RtcErrorCode.AUTOPLAY_FAILED})})).finally((()=>{clearTimeout(i)}))}(null==e?void 0:e.then)&&(isAndroid&&isMobile&&1!==this._audioDom.volume&&(e=e.then((()=>new Promise((e=>{setTimeout((async()=>{var t;null==(t=this._audioDom)||t.pause(),this._audioDom.volume=1,await this._audioDom.play(),e()}),500)}))))),e.then((()=>{reportRtcInvokeStatus(this.engineId,"_internalPlay successfully",{userId:this.userId,screen:this.isScreen}),this._pasued=!1})).catch((e=>{var t;this._autoPlayError(e),null==(t=this._monitor)||t.report("rtc_error",{message:`audio autoplay failed, userId: ${this.userId}: ${e.message} ${e.name}`,error_code:RtcErrorCode.AUTOPLAY_FAILED})})))}catch(e){this._autoPlayError(e),null==(i=this._monitor)||i.report("rtc_error",{message:`audio autoplay failed, userId: ${this.userId}: ${e.message} ${e.name}`,error_code:RtcErrorCode.AUTOPLAY_FAILED})}})),__publicField(this,"_throttledInternalPlay",throttle(this._internalPlay,getParameter("AUTOPLAY_THROTTLE"))),this.engineId=e,i){const e=document.getElementById(i);if(!e)throw new SDKError(ErrorCode.CANT_FIND_DOM,"can't find dom");this._containerDom=e}else this._containerDom=document.body;this.userId=t,this.muted=r,this.isScreen=o,this._monitor=getMonitor(e),this.logger=new Logger$1("Player",0,e),this._initAudio()}_initAudio(){this._audioDom||(this._audioDom=createElement("audio",{style:{display:"none"},attributes:AUDIO_ATTRIBUTES}),this._audioDom.volume=this.muted?0:1,this._audioDom.muted=this.muted,this._audioDom.id=`${this.userId}_${genUuid()}`,this._containerDom.appendChild(this._audioDom)),this._initListeners()}_initListeners(){this._audioDom&&MEDIA_EVENTS.forEach((e=>{var t;null==(t=this._audioDom)||t.addEventListener(e,this.emitAudioEvent)}))}_removeListeners(){this._audioDom&&(MEDIA_EVENTS.forEach((e=>{var t;null==(t=this._audioDom)||t.removeEventListener(e,this.emitAudioEvent)})),this._audioDom.removeEventListener("canplay",this._internalPlay),this._audioDom.removeEventListener("loadeddata",this._internalPlay))}async playAudio(e){var t;this.logger.info("playAudio",`play audio track: ${this.userId}`);let i=this._audioDom;if(i&&i.srcObject instanceof MediaStream&&i.srcObject.getTrackById(null==(t=e.preprocessingTrack)?void 0:t.id))return;i||(this._initAudio(),i=this._audioDom);const r=new MediaStream;e instanceof RemoteAudioTrack?(this._fakeAudioDom=new Audio,this._fakeAudioDom.muted=!0,this._fakeAudioDom.srcObject=new MediaStream([e.originTrack]),r.addTrack(e.preprocessingTrack)):r.addTrack(e.preprocessingTrack),e.withWebAudio&&isAndroid&&isMobile&&(this._audioDom.volume=0),i.srcObject=r,null==i||i.addEventListener("canplay",this._internalPlay),null==i||i.addEventListener("loadeddata",this._internalPlay),setTimeout((()=>this._internalPlay())),this.played=!0,this.hasStartPlaying=!1}_autoPlayError(e){var t,i;this._emitPlayFailed||(this._emitPlayFailed=!0,this.emit("playback_event",{type:"audio",rawEvent:e,readyState:(null==(t=this._audioDom)?void 0:t.readyState)||0,userId:this.userId,eventName:"autoplay-error",currentTime:(null==(i=this._audioDom)?void 0:i.currentTime)||0}))}pause(){if(!this._audioDom)throw new SDKError(ErrorCode.INVALID_PARAMS,"Player not found");this._pasued=!0,this._audioDom.pause(),this.hasStartPlaying=!1}manuallyPause(){return this.pause()}manuallyPlay(){var e;if(this.logger.info("Invoke AudioPlayer.manuallyPlay"),this._emitPlayFailed=!1,!this._audioDom)throw new SDKError(ErrorCode.INVALID_PARAMS,"Player not found");if(!this.played)return Promise.resolve();this._audioDom.volume=1,this._audioDom.muted=!1,null==(e=this._fakeAudioDom)||e.play();const t=[],i=this._audioDom.play();(null==i?void 0:i.then)&&t.push(i);const r=audioContextManager.getAudioContextInstance();if("suspended"===r.state){const e=r.resume();(null==e?void 0:e.then)&&t.push(e)}const o=t.length>0?Promise.all(t):Promise.resolve(i);return o.then((()=>{this._pasued=!1})),o}async setPlaybackDevice(e){this.logger.info("setPlaybackDevice",`setPlaybackDevice: ${e}`);(await dd.enumerateAudioPlaybackDevices()).map((e=>e.deviceId)).includes(e)&&this._audioDom&&this._audioDom.setSinkId&&await this._audioDom.setSinkId(e)}stop(){const{_containerDom:e}=this;this.logger.info("stopAudio",`stop audio track: ${this.userId}`),this._audioDom&&(this._audioDom.srcObject=null,(null==e?void 0:e.contains(this._audioDom))&&e.removeChild(this._audioDom)),this._fakeAudioDom&&(this._fakeAudioDom.srcObject=null,this._fakeAudioDom=void 0),this.played=!1,this.hasStartPlaying=!1}get domElement(){return this._audioDom}destroy(){this.logger.info("destroy",`audio player: ${this.userId}`),this.stop(),super.removeAllListeners(),this._removeListeners(),this._audioDom&&(this._audioDom.srcObject=null,delete this._audioDom),this._edgeTimer&&clearTimeout(this._edgeTimer)}}class AudioProcessor{constructor(){__publicField(this,"_ac"),__publicField(this,"_sourceNode"),__publicField(this,"_gainNode"),__publicField(this,"_destNode"),this._ac=audioContextManager.getAudioContextInstance(),this._gainNode=this._ac.createGain(),this._destNode=this._ac.createMediaStreamDestination(),this._gainNode.connect(this._destNode)}setVolume(e){this._gainNode.gain.value=e/100}getVolume(){return Math.round(100*this._gainNode.gain.value)}updateInputTrack(e){this._sourceNode&&(this._sourceNode.mediaStream.getTracks().forEach((e=>{e.stop()})),delete this._sourceNode);const t=new MediaStream;t.addTrack(e),this._sourceNode=this._ac.createMediaStreamSource(t),this._sourceNode.connect(this._gainNode)}getOutputTrack(){return this._destNode.stream.getTracks()[0]}destroy(){var e,t;null==(e=this._sourceNode)||e.mediaStream.getTracks().forEach((e=>{e.stop()})),13!==safariVersion&&this._destNode.stream.getTracks().forEach((e=>{e.stop()})),null==(t=this._sourceNode)||t.disconnect(),this._gainNode.disconnect(),delete this._sourceNode}}class LocalAudioTrack extends LocalTrack{constructor(e,t,i){super(e,t,{...i,mediaType:MediaType.AUDIO}),__publicField(this,"audioCaptureConfig"),__publicField(this,"_ap"),__publicField(this,"mixedAudioTrack"),__publicField(this,"mixType",AudioMixingType.PLAYOUT_AND_PUBLISH),__publicField(this,"_audioFetchMap",new Map),__publicField(this,"_audioDataFetcher"),__publicField(this,"_localPlaybackTrack"),__publicField(this,"notSupportedWebAudio",!1)}get withWebAudio(){return!!this._ap}getAudioLevel(e=AudioReportMode.MICROPHONE){const t=e===AudioReportMode.AUDIOMIXING&&this.mixType!==AudioMixingType.PLAYOUT?this.mixedAudioTrack??this.preprocessingTrack:this.preprocessingTrack;let i=this._audioFetchMap.get(e);return i&&i.currentTrackId===t.id||(null==i||i.destroy(),i=new AudioLevelFetcher(t),this._audioFetchMap.set(e,i)),i.getAudioLevel()}async updateAudioCaptureConfig(){this.audioCaptureConfig&&(this.logger.print("updateAudioCaptureConfig","update localAudioTrack: ",this.audioCaptureConfig),await this.originTrack.applyConstraints(this.audioCaptureConfig))}setVolume(e){var t;const i=!getParameter("SKIP_WEB_AUDIO_IN_TRACK")&&(isWebAudioSupported()||getParameter("ENFORCE_WEB_AUDIO_SUPPORTED"));i||(this.notSupportedWebAudio=!0);const r=!this.withWebAudio&&100!==e;try{i&&r&&(this.logger.print("Create AudioProcess"),this._ap=new AudioProcessor,this._ap.updateInputTrack(this.originTrack),this.mediaTrack=this._ap.getOutputTrack())}catch(e){this.logger.warn("WebAudio may not supported, quired return"),this.notSupportedWebAudio=!0}this.notSupportedWebAudio||null==(t=this._ap)||t.setVolume(e),i&&r&&this.emit("needReplaceTrack",this)}getVolume(){return this._ap?this._ap.getVolume():100}setUserId(e){this.trackInfo.streamUserId=e}setDataFetcher(e,t){this.logger.info("setDataFetcher","frameSize %s",e),null!==audioContextManager.isWorkletReady?this._audioDataFetcher?this._audioDataFetcher.setFrameSize(e):(this._audioDataFetcher=new AudioDataFetcher(this.preprocessingTrack,e),this._audioDataFetcher.on("data",t)):this.logger.info("setDataFetcher","audioContextManager.isWorkletReady is null")}stopDataFetcher(){var e,t;null==(e=this._audioDataFetcher)||e.removeAllListeners("data"),null==(t=this._audioDataFetcher)||t.destroy(),this._audioDataFetcher=void 0}play(e){this._localPlaybackTrack&&this.stop();const t=e===EarMonitorPosition.AFTER_CAPTURE?this.originTrack:e===EarMonitorPosition.AFTER_PROCESS?this.preprocessingTrack:void 0;if(!t)return void this.logger.error("play()","no target track for %s",e);this._localPlaybackTrack=new RemoteAudioTrack(this._ctx,t.clone(),{...this.trackInfo});const i=this._ctx.earMonitorSettings[this.streamIndex??StreamIndex$1.STREAM_INDEX_MAIN].volume;this.setPlaybackVolume(i);const r=new AudioPlayer(this._ctx.id,this.trackInfo.streamUserId??"",{isScreen:this.streamIndex===StreamIndex$1.STREAM_INDEX_SCREEN,muted:!1});return r.on("playback_event",(e=>{"autoplay-error"===e.eventName&&this.emit("autoplay-error",{kind:"audio",streamIndex:this.streamIndex??StreamIndex$1.STREAM_INDEX_MAIN,mediaType:MediaType.AUDIO})})),this._localPlaybackTrack.setPlayer(r),this._localPlaybackTrack.play()}stop(){var e;null==(e=this._localPlaybackTrack)||e.destroy(),this._localPlaybackTrack=void 0}setPlaybackVolume(e){var t;return null==(t=this._localPlaybackTrack)?void 0:t.setVolume(e)}destroy(){var e,t;this._audioFetchMap.forEach((e=>e.destroy())),this._audioFetchMap.clear(),null==(e=this._ap)||e.destroy(),null==(t=this._audioDataFetcher)||t.destroy(),this._audioDataFetcher=void 0,this.stop(),super.destroy()}}class RemoteAudioTrack extends RemoteTrack{constructor(e,t,i){super(e,t,{...i,mediaType:MediaType.AUDIO}),__publicField(this,"_ap"),__publicField(this,"_audioPlayer"),__publicField(this,"_audioLevelFetcher"),__publicField(this,"_audioDataFetcher"),__publicField(this,"notSupportedWebAudio",!1),__publicField(this,"_sourceNode")}get withWebAudio(){return!!this._ap}getAudioLevel(){return this._audioLevelFetcher||(this._audioLevelFetcher=new AudioLevelFetcher(this.originTrack)),this._audioLevelFetcher.getAudioLevel()}setVolume(e){var t,i,r;const o=!getParameter("SKIP_WEB_AUDIO_IN_TRACK")&&(isWebAudioSupported()||getParameter("ENFORCE_WEB_AUDIO_SUPPORTED"));o||(this.notSupportedWebAudio=!0);const s=!this.withWebAudio&&100!==e;try{o&&s&&(this.logger.print("Create AudioProcess"),this._ap=new AudioProcessor,this._ap.updateInputTrack(this.originTrack),this.mediaTrack=this._ap.getOutputTrack())}catch(e){this.logger.warn("WebAudio may not supported, quite return"),this.notSupportedWebAudio=!0}if(this.notSupportedWebAudio){const i=null==(t=this._audioPlayer)?void 0:t.domElement;i&&(i.volume=Math.min(e/100,1))}else null==(i=this._ap)||i.setVolume(e);o&&s&&(this.emit("needReplaceTrack",this),null==(r=this._audioPlayer)||r.playAudio(this))}getVolume(){var e,t;return this.notSupportedWebAudio?100*((null==(t=null==(e=this._audioPlayer)?void 0:e.domElement)?void 0:t.volume)??1):this._ap?this._ap.getVolume():100}setPlaybackDevice(e){var t;return null==(t=this._audioPlayer)?void 0:t.setPlaybackDevice(e)}setPlayer(e){this._audioPlayer=e,this._wechatAutoplayWorkaround(e)}havePlayer(){return!!this._audioPlayer}bindPlayerEvent(e){this._audioPlayer&&e(this._audioPlayer,this.isPublic,this.streamIndex??StreamIndex$1.STREAM_INDEX_MAIN)}pause(){var e;return null==(e=this._audioPlayer)?void 0:e.pause()}play(){var e;return null==(e=this._audioPlayer)?void 0:e.playAudio(this)}manuallyPlay(){var e,t,i;return(null==(e=this._audioPlayer)?void 0:e.played)?null==(t=this._audioPlayer)?void 0:t.manuallyPlay():null==(i=this._audioPlayer)?void 0:i.playAudio(this)}manuallyPause(){var e;return null==(e=this._audioPlayer)?void 0:e.manuallyPause()}stop(){var e;return null==(e=this._audioPlayer)?void 0:e.stop()}setDataFetcher(e,t){this.logger.info("setDataFetcher","frameSize %s",e),null!==audioContextManager.isWorkletReady?this._audioDataFetcher?this._audioDataFetcher.setFrameSize(e):(this._audioDataFetcher=new AudioDataFetcher(this.originTrack,e),this._audioDataFetcher.on("data",t)):this.logger.warn("setDataFetcher","audioContextManager.isWorkletReady is null")}stopDataFetcher(){var e;this.logger.info("stopDataFetcher"),null==(e=this._audioDataFetcher)||e.destroy(),this._audioDataFetcher=void 0}destroy(){var e,t,i;null==(e=this._audioLevelFetcher)||e.destroy(),null==(t=this._audioDataFetcher)||t.destroy(),this._audioDataFetcher=void 0,this._ap&&this._ap.destroy(),null==(i=this._audioPlayer)||i.destroy(),this._audioPlayer=void 0,super.destroy()}_wechatAutoplayWorkaround(e){isWeChat&&e.on("playback_event",(e=>{const t=audioContextManager.getAudioContextInstance();"autoplay-error"===e.eventName?t&&"running"===t.state&&(this._sourceNode||(this._sourceNode=t.createMediaStreamSource(new MediaStream([this.originTrack]))),this._sourceNode.connect(t.destination),reportRtcInvokeStatus(this._ctx.id,"wechatAutoplayWorkaround.connect",{userId:this.trackInfo.streamUserId,streamIndex:this.streamIndex,contextState:t.state,trackInfo:this.trackInfo})):"playing"===e.eventName&&this._sourceNode&&(this._sourceNode.disconnect(),this._sourceNode=void 0,reportRtcInvokeStatus(this._ctx.id,"wechatAutoplayWorkaround.disconnect",{userId:this.trackInfo.streamUserId,streamIndex:this.streamIndex,contextState:t.state,trackInfo:this.trackInfo}))}))}}const logger$6=new Logger$1("VERTC",0);let desktopCapturer,electron=null;const inElectron=()=>!!fetchElectronInstance();function fetchElectronInstance(){if(electron)return electron;try{electron=window.require("electron");const{ipcRenderer:e}=electron;return desktopCapturer={getSources:t=>e.invoke("DESKTOP_CAPTURER_GET_SOURCES",t)},electron}catch(e){return null}}async function getElectronScreenStream(e,t,i){let r;return t||(t={width:1920,height:1080,frameRate:15}),r=i?{audio:{mandatory:{chromeMediaSource:"desktop"}},video:{mandatory:{chromeMediaSource:"desktop",maxHeight:t.height,maxWidth:t.width,maxFrameRate:t.frameRate}}}:{audio:!1,video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:e,maxHeight:t.height,maxWidth:t.width,maxFrameRate:t.frameRate}}},logger$6.info("getUserMediaConfig",JSON.stringify(r)),await navigator.mediaDevices.getUserMedia(r)}async function getElectronScreenSources(e){let t=["window","screen"];"window"===e&&(t=["window"]),"screen"===e&&(t=["screen"]);if(!fetchElectronInstance())throw new SDKError(ErrorCode.ERR_ELECTRON_IS_NULL,"Unable to get Electron object");let i=null;try{i=desktopCapturer.getSources({types:t})}catch(e){i=null}i&&i.then||(i=new Promise(((e,i)=>{desktopCapturer.getSources({types:t},((t,r)=>{t?i(t):e(r)}))})));try{return await i}catch(e){throw new SDKError(ErrorCode.ERR_ELECTRON_IS_NULL,e.toString())}}function showElectronSelectSourceWindow(e){return new Promise(((t,i)=>{const r=document.createElement("div");r.innerText="share screen",r.setAttribute("style","text-align: center; height: 25px; line-height: 25px; border-radius: 4px 4px 0 0; background: #D4D2D4; border-bottom: solid 1px #B9B8B9;");const o=document.createElement("div");o.setAttribute("style","width: 100%; height: 500px; padding: 15px 25px ; box-sizing: border-box;");const s=document.createElement("div");s.innerText="Web Screensharing wants to share the contents of your screen. Choose what you'd like to share.",s.setAttribute("style","height: 12%;");const n=document.createElement("div");n.setAttribute("style","width: 100%; height: 80%; background: #FFF; border: solid 1px #CBCBCB; display: flex; flex-wrap: wrap; justify-content: space-around; overflow-y: scroll; padding: 0 15px; box-sizing: border-box;");const a=document.createElement("div");a.setAttribute("style","text-align: right; padding: 16px 0;");const d=document.createElement("button");d.innerHTML="cancel",d.setAttribute("style","width: 85px;"),d.onclick=()=>{document.body.removeChild(c);const e=new Error("NotAllowedError");e.name="NotAllowedError",i(e)},a.appendChild(d),o.appendChild(s),o.appendChild(n),o.appendChild(a);const c=document.createElement("div");c.setAttribute("style","position: fixed; z-index: 99999999; top: 50%; left: 50%; width: 620px; height: 525px; background: #ECECEC; border-radius: 4px; -webkit-transform: translate(-50%,-50%); transform: translate(-50%,-50%);"),c.appendChild(r),c.appendChild(o),document.body.appendChild(c),e.map((e=>{if(e.id){const i=document.createElement("div");i.setAttribute("style","width: 30%; height: 160px; padding: 20px 0; text-align: center;box-sizing: content-box;"),i.innerHTML=`<div style='height: 120px; display: table-cell; vertical-align: middle;'> \n <img style='width: 100%; background: #333333; box-shadow: 1px 1px 1px 1px rgba(0, 0, 0, 0.2);' src=\n ${e.thumbnail.toDataURL()}\n />\n </div>\n <span style='\theight: 40px; line-height: 40px; display: inline-block; width: 70%; word-break: keep-all; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;'>\n ${e.name}\n </span>`,i.onclick=()=>{document.body.removeChild(c),t(e.id)},n.appendChild(i)}}))}))}async function getElectronScreenStreamByUserSelect(e,t){const i=await getElectronScreenSources(),r=await showElectronSelectSourceWindow(i);return await getElectronScreenStream(r,e,t)}async function createDummyVideoLocalTrack(e,t){const i=new LocalVideoTrack(e,t,{streamIndex:ExtendStreamIndex.MAIN,sourceType:SourceType.INTERNAL,isDummy:!0});return await i.isTrackReady,i}async function createDummyScreenVideoLocalTrack(e,t){const i=new LocalVideoTrack(e,t,{isDummy:!0,streamIndex:ExtendStreamIndex.SCREEN,sourceType:SourceType.INTERNAL});return await i.isTrackReady,i}async function createCameraVideoTrack(e,t){var i,r,o,s,n;let a;const d=(null==(i=(t=t||e.videoProfile.getCaptureConfig()).deviceId)?void 0:i.exact)||"default",c=genUuid$1(),l=new Logger$1("TrackFactory",0,e.id);try{l.info("createCameraVideoTrack","constraints:",t),null==(r=e.monitor)||r.report("rtc_video_capture_event",{event_type:"start",media_device_id:d,capture_session_id:c});const i=getServerNow();isFirefox&&(t.frameRate={ideal:30,max:30}),a=await dd.getUserMedia({video:t}),null==(s=e.monitor)||s.report("rtc_video_capture_event",{event_type:"start_capture_result",media_device_id:d,media_device_name:(null==(o=a.getVideoTracks()[0])?void 0:o.label)||"",reason:"success",elapse:getServerNow()-i,capture_session_id:c})}catch(t){throw null==(n=e.monitor)||n.report("rtc_video_capture_event",{event_type:"running_failed",media_device_id:d,error_code:t.code,reason:t.name+t.message,capture_session_id:c}),new SDKError(ErrorCode.GET_VIDEO_TRACK_FAILED,`throw error from getUserMedia. [${t.name||"unknown name"}]: ${t.message||"unknown message"}.`,t)}const u=a.getVideoTracks()[0],_=new LocalVideoTrack(e,u,{streamIndex:ExtendStreamIndex.MAIN,sourceType:SourceType.INTERNAL,captureSessionId:c});return await _.isTrackReady,_}async function createMicrophoneAudioTrack(e,t){var i,r,o,s,n;let a;new Logger$1("TrackFactory",0,e.id).info("createMicrophoneAudioTrack","constraints:",t);const d=(null==(i=t.deviceId)?void 0:i.exact)||"default",c=genUuid$1();try{null==(r=e.monitor)||r.report("rtc_audio_device_event",{device_type:"audio_record",event_type:"start_begin",media_device_id:d,event_session_id:c});const i=getServerNow();e.extensionManager.getPluginByName(RTCExtensionType.PRE_PROCESSING,"RTCAIAnsExtension")&&(t.autoGainControl=!0,t.noiseSuppression=!1),a=await dd.getUserMedia({audio:t}),null==(s=e.monitor)||s.report("rtc_audio_device_event",{device_type:"audio_record",event_type:"start_result",media_device_id:d,media_device_name:(null==(o=a.getAudioTracks()[0])?void 0:o.label)||"",reason:"success",elapse:getServerNow()-i,event_session_id:c})}catch(t){throw null==(n=e.monitor)||n.report("rtc_audio_device_event",{device_type:"audio_record",event_type:"start_end",media_device_id:d,error_code:t.code,reason:t.name+t.message,event_session_id:c}),new SDKError(ErrorCode.GET_AUDIO_TRACK_FAILED,`throw error from getUserMedia. [${t.name||"unknown name"}]: ${t.message||"unknown message"}.`,t)}const l=a.getAudioTracks()[0],u=new LocalAudioTrack(e,l,{streamIndex:ExtendStreamIndex.MAIN,sourceType:SourceType.INTERNAL,captureSessionId:c});return await u.isTrackReady,u}async function createMicrophoneAndCameraTrack(e,t,i){var r,o,s,n,a,d,c,l,u,_;let h;new Logger$1("TrackFactory",0,e.id).print("createCameraAndMicrophoneTrack","audioConstraints:",t,"videoConstraints:",i);const p=(null==(r=t.deviceId)?void 0:r.exact)||"default",m=(null==(o=i.deviceId)?void 0:o.exact)||"default",S=genUuid$1(),g=genUuid$1();try{null==(s=e.monitor)||s.report("rtc_video_capture_event",{event_type:"start",media_device_id:m,capture_session_id:S}),null==(n=e.monitor)||n.report("rtc_audio_device_event",{device_type:"audio_record",event_type:"start_begin",media_device_id:p,event_session_id:g});const r=getServerNow();isFirefox&&(i.frameRate={ideal:30,max:30});e.extensionManager.getPluginByName(RTCExtensionType.PRE_PROCESSING,"RTCAIAnsExtension")&&(t.autoGainControl=!0,t.noiseSuppression=!1),h=await dd.getUserMedia({audio:t,video:i}),null==(d=e.monitor)||d.report("rtc_video_capture_event",{event_type:"start_capture_result",media_device_id:m,media_device_name:(null==(a=h.getVideoTracks()[0])?void 0:a.label)||"",reason:"success",elapse:getServerNow()-r,capture_session_id:S}),null==(l=e.monitor)||l.report("rtc_audio_device_event",{device_type:"audio_record",event_type:"start_result",media_device_id:p,media_device_name:(null==(c=h.getAudioTracks()[0])?void 0:c.label)||"",reason:"success",elapse:getServerNow()-r,event_session_id:g})}catch(t){throw null==(u=e.monitor)||u.report("rtc_video_capture_event",{event_type:"running_failed",media_device_id:m,error_code:t.code,reason:t.name+t.message,capture_session_id:S}),null==(_=e.monitor)||_.report("rtc_audio_device_event",{device_type:"audio_record",event_type:"start_end",media_device_id:p,error_code:t.code,reason:t.name+t.message,event_session_id:g}),new SDKError(ErrorCode.GET_VIDEO_TRACK_FAILED,`throw error from getUserMedia. [${t.name||"unknown name"}]: ${t.message||"unknown message"}.`,t)}const v=h.getVideoTracks()[0],f=new LocalVideoTrack(e,v,{streamIndex:ExtendStreamIndex.MAIN,sourceType:SourceType.INTERNAL,captureSessionId:S}),E=h.getAudioTracks()[0],T=new LocalAudioTrack(e,E,{streamIndex:ExtendStreamIndex.MAIN,sourceType:SourceType.INTERNAL,captureSessionId:g});return await Promise.all([f.isTrackReady,T.isTrackReady]),{videoTrack:f,audioTrack:T}}async function createScreenTracks(e,t){var i,r,o,s,n;const a=new Logger$1("TrackFactory",0,e.id);let d,c=e.videoProfile.getScreenEncodeConfig();a.info("createScreenTracks","screenConfig: %o, constraints: %o",t,c);const l=genUuid$1(),{enableAudio:u=!1,displaySurface:_,systemAudio:h,surfaceSwitching:p,selfBrowserSurface:m,sourceId:S}=t,g={};_&&["monitor","browser","window"].includes(_)&&(c?c.displaySurface=_:c={displaySurface:_}),h&&["include","exclude"].includes(h)&&(g.systemAudio=h),p&&["include","exclude"].includes(p)&&(g.surfaceSwitching=p),m&&["include","exclude"].includes(m)&&(g.selfBrowserSurface=m);try{null==(i=e.monitor)||i.report("rtc_video_capture_event",{event_type:"start",media_device_id:"screen",capture_session_id:l});const t=getServerNow();d=inElectron()?S?await getElectronScreenStream(S,c,u):await getElectronScreenStreamByUserSelect(c,u):await navigator.mediaDevices.getDisplayMedia({video:!(!c||isConstraintInGetDisplayMediaSupported)||c,audio:!!u&&{channelCount:2,noiseSuppression:!1,echoCancellation:!0,autoGainControl:!1},...g}),null==(s=e.monitor)||s.report("rtc_video_capture_event",{event_type:"start_capture_result",media_device_id:"screen",media_device_name:`${(null==(r=d.getVideoTracks()[0])?void 0:r.label)||""}, ${(null==(o=d.getAudioTracks()[0])?void 0:o.label)||""}`,reason:"success",elapse:getServerNow()-t,capture_session_id:l})}catch(t){throw null==(n=e.monitor)||n.report("rtc_video_capture_event",{event_type:"running_failed",media_device_id:"screen",error_code:t.code,reason:t.name+t.message,capture_session_id:l}),new SDKError(ErrorCode.GET_SCREEN_TRACK_FAILED,"throw error from getDisplayMedia",t)}const v=d.getVideoTracks()[0],f=new LocalVideoTrack(e,v,{streamIndex:ExtendStreamIndex.SCREEN,sourceType:SourceType.INTERNAL,captureSessionId:l}),E=d.getAudioTracks()[0];if(d.getAudioTracks().length){const t=new LocalAudioTrack(e,E,{streamIndex:ExtendStreamIndex.SCREEN,sourceType:SourceType.INTERNAL,captureSessionId:l});return await Promise.all([f.isTrackReady,t.isTrackReady]),[f,t]}return await f.isTrackReady,[f,void 0]}function createRemoteVideoTrack(e,t,i,r){return new RemoteVideoTrack(e,t,i,{...r})}function createRemoteAudioTrack(e,t,i){return new RemoteAudioTrack(e,t,{...i})}async function createCustomVideoLocalTrack(e,t){const i=new LocalVideoTrack(e,t,{streamIndex:ExtendStreamIndex.MAIN,sourceType:SourceType.EXTERNAL});return await i.isTrackReady,i}async function createCustomAudioLocalTrack(e,t){const i=new LocalAudioTrack(e,t,{streamIndex:ExtendStreamIndex.MAIN,sourceType:SourceType.EXTERNAL});return await i.isTrackReady,i}async function createCustomScreenVideoLocalTrack(e,t){const i=new LocalVideoTrack(e,t,{sourceType:SourceType.EXTERNAL,streamIndex:ExtendStreamIndex.SCREEN});return await i.isTrackReady,i}async function createCustomScreenAudioLocalTrack(e,t){const i=new LocalAudioTrack(e,t,{sourceType:SourceType.EXTERNAL,streamIndex:ExtendStreamIndex.SCREEN});return await i.isTrackReady,i}const encodedJs$1="dmFyIF9fZGVmUHJvcD1PYmplY3QuZGVmaW5lUHJvcGVydHksX19kZWZOb3JtYWxQcm9wPShlLHQsbik9PnQgaW4gZT9fX2RlZlByb3AoZSx0LHtlbnVtZXJhYmxlOiEwLGNvbmZpZ3VyYWJsZTohMCx3cml0YWJsZTohMCx2YWx1ZTpufSk6ZVt0XT1uLF9fcHVibGljRmllbGQ9KGUsdCxuKT0+KF9fZGVmTm9ybWFsUHJvcChlLCJzeW1ib2wiIT10eXBlb2YgdD90KyIiOnQsbiksbik7IWZ1bmN0aW9uKCl7InVzZSBzdHJpY3QiO2NvbnN0IGU9e2dldE5BTFVuaXRzKHQsbj0hMSl7aWYodC5sZW5ndGgtdC5wb3NpdGlvbjw0KXJldHVybltdO2NvbnN0e3Bvc2l0aW9uOnN9PXQ7cmV0dXJuIDE9PT10LmdldEludDMyKHMpfHwwPT09dC5nZXRJbnQxNihzKSYmMT09PXQuZ2V0SW50OChzKzIpP2UuZ2V0QW5uZXhiTmFscyh0LG4pOmUuZ2V0QXZjY05hbHModCxuKX0sZ2V0QW5uZXhiTmFscyh0LG4pe2NvbnN0IHM9W107bGV0IHI9ZS5nZXRIZWFkZXJQb3NpdGlvbkFubmV4Qih0KSxvPXIucG9zLGk9bztmb3IoO288dC5sZW5ndGgtNDspe2NvbnN0IGE9bmV3IFVpbnQ4QXJyYXkodC5idWZmZXIuc2xpY2UobyxvK3IuaGVhZGVyTGVuZ3RoKSk7ci5wb3M9PT10LnBvc2l0aW9uJiZ0LnNraXAoci5oZWFkZXJMZW5ndGgpLHI9ZS5nZXRIZWFkZXJQb3NpdGlvbkFubmV4Qih0KSxpPXIucG9zO2NvbnN0IGM9e2hlYWRlcjphLGJvZHk6bmV3IFVpbnQ4QXJyYXkodC5idWZmZXIuc2xpY2UobythLmJ5dGVMZW5ndGgsaSkpLHR5cGU6LTF9O24/ZS5hbmFseXNlSDI2NU5hbChjKTplLmFuYWx5c2VOYWwoYyksKGMudHlwZTw9OXx8biYmYy50eXBlPD00MCkmJjAhPT1jLnR5cGUmJnMucHVzaChjKSx0LnNraXAoaS10LnBvc2l0aW9uKSxvPWl9cmV0dXJuIHN9LGdldEF2Y2NOYWxzKHQsbil7Y29uc3Qgcz1bXTtmb3IoO3QucG9zaXRpb248dC5sZW5ndGgtNDspe2NvbnN0IHI9dC5nZXRJbnQzMih0LnBvc2l0aW9uKTtpZighKHQubGVuZ3RoLXQucG9zaXRpb24+PXIpKWJyZWFrO3tjb25zdCBvPW5ldyBVaW50OEFycmF5KHQuYnVmZmVyLnNsaWNlKHQucG9zaXRpb24sdC5wb3NpdGlvbis0KSk7dC5za2lwKDQpO2NvbnN0IGk9bmV3IFVpbnQ4QXJyYXkodC5idWZmZXIuc2xpY2UodC5wb3NpdGlvbix0LnBvc2l0aW9uK3IpKTt0LnNraXAocik7Y29uc3QgYT17aGVhZGVyOm8sYm9keTppLHR5cGU6LTF9O24/ZS5hbmFseXNlSDI2NU5hbChhKTplLmFuYWx5c2VOYWwoYSksYS50eXBlPD05JiYwIT09YS50eXBlJiZzLnB1c2goYSl9fXJldHVybiBzfSxhbmFseXNlTmFsKGUpe2NvbnN0IHQ9MzEmZS5ib2R5WzBdO3N3aXRjaChlLnR5cGU9dCx0KXtjYXNlIDE6ZS5uZHI9ITA7YnJlYWs7Y2FzZSA1OmUuaWRyPSEwO2JyZWFrO2Nhc2UgNjplLnNlaT0hMDticmVhaztjYXNlIDc6ZS5zcHM9ITA7YnJlYWs7Y2FzZSA4OmUucHBzPSEwfX0sYW5hbHlzZUgyNjVOYWwoZSl7Y29uc3QgdD0oMTI2JmUuYm9keVswXSk+PjE7c3dpdGNoKGUudHlwZT10LHQpe2Nhc2UgMzk6Y2FzZSA0MDplLnNlaT0hMH19LGdldEhlYWRlclBvc2l0aW9uQW5uZXhCKGUpe2xldCB0PWUucG9zaXRpb24sbj0wO2NvbnN0IHM9ZS5sZW5ndGg7Zm9yKDszIT09biYmNCE9PW4mJnQ8cy00OykwPT09ZS5nZXRJbnQxNih0KT8xPT09ZS5nZXRJbnQxNih0KzIpP249NDoxPT09ZS5nZXRJbnQ4KHQrMik/bj0zOnQrKzp0Kys7cmV0dXJuIHQ9PT1zLTQmJigwPT09ZS5nZXRJbnQxNih0KT8xPT09ZS5nZXRJbnQxNih0KzIpP249NDp0PXM6KHQrKywwPT09ZS5nZXRJbnQxNih0KSYmMT09PWUuZ2V0SW50OCh0KT9uPTM6dD1zKSkse3Bvczp0LGhlYWRlckxlbmd0aDpufX0saXNIMjY1VmlkZW9GcmFtZShlKXt2YXIgdCxuO3JldHVybigobnVsbD09KG49bnVsbD09KHQ9ZS5nZXRNZXRhZGF0YSk/dm9pZCAwOnQuY2FsbChlKSk/dm9pZCAwOm4ubWltZVR5cGUpfHwiIikudG9Mb3dlckNhc2UoKS5pbmNsdWRlcygiaDI2NSIpfX0sdD1uZXcgVWludDhBcnJheShbMTA5LDE2Nyw1MywxOTAsMTAzLDkwLDcyLDEsMTcwLDg5LDYzLDE2NCwxOTQsMTk5LDE5LDg1XSksbj1uZXcgVWludDhBcnJheShbMTA5LDE2Nyw1MywxOTAsMTAzLDkwLDcyLDEsMTcwLDg5LDYzLDE2NCwxOTQsMTk5LDE5LDg0XSkscz1uZXcgVWludDhBcnJheShbMzEsMjM5LDMsNTAsMjQyLDEyMCw3Niw4NSwxNjksNDIsMTYxLDkxLDc1LDE4NiwyMl0pO2Z1bmN0aW9uIHIoZSl7Y29uc3QgdD1bXTtmb3IoO2U+PTI1NTspZS09MjU1LHQucHVzaCgyNTUpO3JldHVybiB0LnB1c2goZSksbmV3IFVpbnQ4QXJyYXkodCl9ZnVuY3Rpb24gbyhlLHQ9MCl7bGV0IG49MDtmb3IoOzI1NT09PWVbdF0mJnQ8ZS5ieXRlTGVuZ3RoOyl0Kyssbis9MjU1O3JldHVybiB0PGUuYnl0ZUxlbmd0aCYmKG4rPWVbdCsrXSksW24sdF19Y29uc3QgaT1uZXcgVWludDhBcnJheShbODAsMV0pLGE9Y2xhc3N7c3RhdGljIGdlbmVyYXRlU0VJKGUscyxvPSExKXtjb25zdCBjPW5ldyBVaW50OEFycmF5KFswLDAsMCwxXSksbD1zP2k6bmV3IFVpbnQ4QXJyYXkoWzZdKSxwPW5ldyBVaW50OEFycmF5KFs1XSkseT1hLl9fdXVpZHx8KG8/dDpuKSx1PXIoZS5ieXRlTGVuZ3RoK3kuYnl0ZUxlbmd0aCksZz0oZT0+e2NvbnN0IHQ9W107bGV0IG49MDtmb3IoY29uc3QgcyBvZiBlKW4+PTImJnM8PTMmJih0LnB1c2goMyksbj0wKSwwPT09cz9uKys6bj0wLHQucHVzaChzKTtyZXR1cm4gbmV3IFVpbnQ4QXJyYXkodCl9KShlKTtyZXR1cm4gbmV3IFVpbnQ4QXJyYXkoWy4uLmMsLi4ubCwuLi5wLC4uLnUsLi4ueSwuLi5nLDEyOF0pfXN0YXRpYyBkZWNvZGVTRUlCb2R5KGUscil7Y29uc3QgaT0oZT0+e2NvbnN0IHQ9W107Zm9yKGxldCBuPTA7bjxlLmxlbmd0aDtuKyspZVtuXTw9MyYmMD09PWVbbi0xXSYmMD09PWVbbi0yXXx8dC5wdXNoKGVbbl0pO3JldHVybiBuZXcgVWludDhBcnJheSh0KX0pKGU9ZS5zbGljZSgwLGUubGVuZ3RoLTEpKTtpZihpLmJ5dGVMZW5ndGg8MilyZXR1cm47bGV0IGE9MDtjb25zdCBjPXI/MjoxO2lmKDUhPT1pW2NdJiYxMDAhPT1pW2NdKXJldHVybjthKz0xK2M7Y29uc3RbbCxwXT1vKGksYSk7YT1wO2xldCB5PTI7Y29uc3QgdT1hK2w7aS5ieXRlTGVuZ3RoPj1uLmJ5dGVMZW5ndGgmJmw+PW4uYnl0ZUxlbmd0aCYmKGkuc2xpY2UoYSxhK24uYnl0ZUxlbmd0aCkudG9TdHJpbmcoKT09PW4udG9TdHJpbmcoKXx8aS5zbGljZShhLGErcy5ieXRlTGVuZ3RoKS50b1N0cmluZygpPT09cy50b1N0cmluZygpKT8oYSs9bi5ieXRlTGVuZ3RoLHk9MSk6aS5ieXRlTGVuZ3RoPj1uLmJ5dGVMZW5ndGgmJmw+PW4uYnl0ZUxlbmd0aCYmaS5zbGljZShhLGErdC5ieXRlTGVuZ3RoKS50b1N0cmluZygpPT09dC50b1N0cmluZygpJiYoYSs9dC5ieXRlTGVuZ3RoLHk9MCk7cmV0dXJue3R5cGU6eSxwYXlsb2FkOmkuc2xpY2UoYSx1KX19c3RhdGljIHBhcnNlSW50ZXJuYWxTRUkoZSl7Y29uc3QgdD1uZXcgTWFwO2xldCBuPTA7aWYoMD09PWUudHlwZSl7Zm9yKDtlLnBheWxvYWQuYnl0ZUxlbmd0aC1uPj0yOyl7Y29uc3RbcyxyXT1vKGUucGF5bG9hZCxuKTtuPXI7Y29uc3RbaSxhXT1vKGUucGF5bG9hZCxuKTtpZihuPWEsdC5nZXQocyl8fCEoaTw9ZS5wYXlsb2FkLmJ5dGVMZW5ndGgtbikpYnJlYWs7dC5zZXQocyxlLnBheWxvYWQuc2xpY2UobixuK2kpKSxuKz1pfXJldHVybiB0fX1zdGF0aWMgbWFrZUludGVybmFsU2VpKGUpe2NvbnN0IHQ9W107Zm9yKGNvbnN0W28saV1vZiBlKXtjb25zdCBlPXIobyksbj1yKGkuYnl0ZUxlbmd0aCk7dC5wdXNoKGUsbixpKX1jb25zdCBuPXQucmVkdWNlKCgoZSx0KT0+ZSt0LmJ5dGVMZW5ndGgpLDApLHM9bmV3IFVpbnQ4QXJyYXkobik7cmV0dXJuIHQucmVkdWNlKCgoZSx0KT0+KHMuc2V0KHQsZSksZSt0LmJ5dGVMZW5ndGgpKSwwKSxzfX07bGV0IGM9YTtfX3B1YmxpY0ZpZWxkKGMsIl9fdXVpZCIpO2NsYXNzIGx7Y29uc3RydWN0b3IoZSl7X19wdWJsaWNGaWVsZCh0aGlzLCJzZWlMaXN0IixbXSksX19wdWJsaWNGaWVsZCh0aGlzLCJtYXhTRUlDb3VudCIsMSksdGhpcy5tYXhTRUlDb3VudD1lLm1heFNFSUNvdW50fXNlbmRTRUlUcmFuc2Zvcm0odCxuKXtjb25zdHttYXhTRUlDb3VudDpzLHNlaUxpc3Q6cn09dGhpcztpZighdGhpcy5zZWlMaXN0Lmxlbmd0aClyZXR1cm4gdm9pZCBuLmVucXVldWUodCk7Y29uc3Qgbz1bXTtsZXQgaT0wO2Zvcihjb25zdCBwIG9mIHIpe2lmKG8ubGVuZ3RoPj1zKWJyZWFrO2NvbnN0IG49Yy5nZW5lcmF0ZVNFSShwLmNvbnRlbnQsZS5pc0gyNjVWaWRlb0ZyYW1lKHQpKTtpKz1uLmJ5dGVMZW5ndGgscC5yZXBlYXRDb3VudC0tLG8ucHVzaChuKX10aGlzLnNlaUxpc3Q9ci5maWx0ZXIoKGU9PmUucmVwZWF0Q291bnQ+MCkpO2NvbnN0IGE9bmV3IFVpbnQ4QXJyYXkoaSt0LmRhdGEuYnl0ZUxlbmd0aCk7YS5zZXQobmV3IFVpbnQ4QXJyYXkodC5kYXRhKSk7bGV0IGw9dC5kYXRhLmJ5dGVMZW5ndGg7by5mb3JFYWNoKChlPT57YS5zZXQoZSxsKSxsKz1lLmJ5dGVMZW5ndGh9KSksdC5kYXRhPWEuYnVmZmVyLG4uZW5xdWV1ZSh0KX1wdXNoU0VJKGUpe3RoaXMuc2VpTGlzdC5wdXNoKGUpfXJldm9rZVNFSShlKXtjb25zdCB0PXRoaXMuc2VpTGlzdC5maW5kSW5kZXgoKHQ9PnQudXVpZD09PWUpKTtyZXR1cm4tMSE9PXQmJih0aGlzLnNlaUxpc3Quc3BsaWNlKHQsMSksITApfX0idW5kZWZpbmVkIiE9dHlwZW9mIHNlbGYmJiJEZWRpY2F0ZWRXb3JrZXJHbG9iYWxTY29wZSI9PT1zZWxmLmNvbnN0cnVjdG9yLm5hbWUmJnNlbGYuYWRkRXZlbnRMaXN0ZW5lcigicnRjdHJhbnNmb3JtIiwoZT0+e2NvbnN0e3RyYW5zZm9ybWVyOnR9PWUse21heFNFSUNvdW50Om59PXQub3B0aW9ucyxzPW5ldyBsKHttYXhTRUlDb3VudDpufSkscj1uZXcgVHJhbnNmb3JtU3RyZWFtKHt0cmFuc2Zvcm06cy5zZW5kU0VJVHJhbnNmb3JtLmJpbmQocyl9KTtzZWxmLmFkZEV2ZW50TGlzdGVuZXIoIm1lc3NhZ2UiLCgoe2RhdGE6ZX0pPT57Y29uc3R7dHlwZTp0LGNvbnRlbnQ6bn09ZTtpZigicHVzaCI9PT10KXMucHVzaFNFSShuKTtlbHNlIGlmKCJyZXZva2UiPT09dCl7Y29uc3QgZT1zLnJldm9rZVNFSShuKTtyZXR1cm4gc2VsZi5wb3N0TWVzc2FnZSh7dHlwZToicmV2b2tlLWFjayIsY29udGVudDp7dXVpZDpuLGlzTm90U2VuZDplfX0pfX0pKSx0LnJlYWRhYmxlLnBpcGVUaHJvdWdoKHIpLnBpcGVUbyh0LndyaXRhYmxlKX0pKX0oKTsK",blob$1="undefined"!=typeof window&&window.Blob&&new Blob([atob(encodedJs$1)],{type:"text/javascript;charset=utf-8"});function WorkerWrapper$1(){let e;try{if(e=blob$1&&(window.URL||window.webkitURL).createObjectURL(blob$1),!e)throw"";return new Worker(e)}catch(e){return new Worker("data:application/javascript;base64,"+encodedJs$1)}finally{!("undefined"!=typeof window&&navigator.userAgent.indexOf("Trident/")>0)&&e&&(window.URL||window.webkitlRL).revokeObjectURL(e)}}const Nalunit={getNALUnits(e,t=!1){if(e.length-e.position<4)return[];const{position:i}=e;return 1===e.getInt32(i)||0===e.getInt16(i)&&1===e.getInt8(i+2)?Nalunit.getAnnexbNals(e,t):Nalunit.getAvccNals(e,t)},getAnnexbNals(e,t){const i=[];let r=Nalunit.getHeaderPositionAnnexB(e),o=r.pos,s=o;for(;o<e.length-4;){const n=new Uint8Array(e.buffer.slice(o,o+r.headerLength));r.pos===e.position&&e.skip(r.headerLength),r=Nalunit.getHeaderPositionAnnexB(e),s=r.pos;const a={header:n,body:new Uint8Array(e.buffer.slice(o+n.byteLength,s)),type:-1};t?Nalunit.analyseH265Nal(a):Nalunit.analyseNal(a),(a.type<=9||t&&a.type<=40)&&0!==a.type&&i.push(a),e.skip(s-e.position),o=s}return i},getAvccNals(e,t){const i=[];for(;e.position<e.length-4;){const r=e.getInt32(e.position);if(!(e.length-e.position>=r))break;{const o=new Uint8Array(e.buffer.slice(e.position,e.position+4));e.skip(4);const s=new Uint8Array(e.buffer.slice(e.position,e.position+r));e.skip(r);const n={header:o,body:s,type:-1};t?Nalunit.analyseH265Nal(n):Nalunit.analyseNal(n),n.type<=9&&0!==n.type&&i.push(n)}}return i},analyseNal(e){const t=31&e.body[0];switch(e.type=t,t){case 1:e.ndr=!0;break;case 5:e.idr=!0;break;case 6:e.sei=!0;break;case 7:e.sps=!0;break;case 8:e.pps=!0}},analyseH265Nal(e){const t=(126&e.body[0])>>1;switch(e.type=t,t){case 39:case 40:e.sei=!0}},getHeaderPositionAnnexB(e){let t=e.position,i=0;const r=e.length;for(;3!==i&&4!==i&&t<r-4;)0===e.getInt16(t)?1===e.getInt16(t+2)?i=4:1===e.getInt8(t+2)?i=3:t++:t++;return t===r-4&&(0===e.getInt16(t)?1===e.getInt16(t+2)?i=4:t=r:(t++,0===e.getInt16(t)&&1===e.getInt8(t)?i=3:t=r)),{pos:t,headerLength:i}},isH265VideoFrame(e){var t,i;return((null==(i=null==(t=e.getMetadata)?void 0:t.call(e))?void 0:i.mimeType)||"").toLowerCase().includes("h265")}};class RTCDataView{constructor(e){__publicField(this,"_position",0),__publicField(this,"_dataview"),this._dataview=new DataView(e)}get length(){return this.buffer.byteLength}get buffer(){return this._dataview.buffer}set position(e){this._position=e}get position(){return this._position}back(e){this.position-=e}getUint8(e){return this._dataview.getUint8(e)}getInt8(e){return this._dataview.getInt8(e)}getInt16(e){return this._dataview.getInt16(e)}getUint16(e){return this._dataview.getUint16(e)}getUint32(e){return this._dataview.getUint32(e)}getInt32(e){return this._dataview.getInt32(e)}skip(e){const t=Math.floor(e/4),i=e%4;for(let e=0;e<t;e++)RTCDataView.readByte(this,4);i>0&&RTCDataView.readByte(this,i)}static readByte(e,t,i){let r;switch(t){case 1:r=i?e.getInt8(e.position):e.getUint8(e.position);break;case 2:r=i?e.getInt16(e.position):e.getUint16(e.position);break;case 3:if(i)throw new Error("not supported for readByte 3");r=e.getUint8(e.position)<<16,r|=e.getUint8(e.position+1)<<8,r|=e.getUint8(e.position+2);break;case 4:r=i?e.getInt32(e.position):e.getUint32(e.position);break;case 8:if(i)throw new Error("not supported for readBody 8");r=e.getUint32(e.position)<<32,r|=e.getUint32(e.position+4);break;default:r=""}return e.position+=t,r}readUint8(){return RTCDataView.readByte(this,1)}readUint16(){return RTCDataView.readByte(this,2)}readUint24(){return RTCDataView.readByte(this,3)}readUint32(){return RTCDataView.readByte(this,4)}readUint64(){return RTCDataView.readByte(this,8)}readInt8(){return RTCDataView.readByte(this,1,!0)}readInt16(){return RTCDataView.readByte(this,2,!0)}readInt32(){return RTCDataView.readByte(this,4,!0)}writeUint32(e){return new Uint8Array([e>>>24&255,e>>>16&255,e>>>8&255,255&e])}}function receiveSEITransform({postMessage:e,skipFilter:t}){return new TransformStream({transform(i,r){const o=Nalunit.isH265VideoFrame(i);Nalunit.getNALUnits(new RTCDataView(i.data),o).forEach((i=>{if(i.sei){const r=SEIHelper.decodeSEIBody(i.body,o);r&&(t||r.type===RTC_SEI_TYPE.external)&&e(r)}})),r.enqueue(i)}})}"undefined"!=typeof self&&"DedicatedWorkerGlobalScope"===self.constructor.name&&self.addEventListener("rtctransform",(e=>{const{transformer:t}=e,{streamId:i,skipFilter:r}=t.options,o=receiveSEITransform({postMessage:e=>{self.postMessage({streamId:i,msg:e},[e.payload.buffer])},skipFilter:r});t.readable.pipeThrough(o).pipeTo(e.transformer.writable)}));class EncodedTransformer{constructor(e){__publicField(this,"seiList",[]),__publicField(this,"maxSEICount",1),this.maxSEICount=e.maxSEICount}sendSEITransform(e,t){const{maxSEICount:i,seiList:r}=this;if(!this.seiList.length)return void t.enqueue(e);const o=[];let s=0;for(const t of r){if(o.length>=i)break;const r=SEIHelper.generateSEI(t.content,Nalunit.isH265VideoFrame(e));s+=r.byteLength,t.repeatCount--,o.push(r)}this.seiList=r.filter((e=>e.repeatCount>0));const n=new Uint8Array(s+e.data.byteLength);n.set(new Uint8Array(e.data));let a=e.data.byteLength;o.forEach((e=>{n.set(e,a),a+=e.byteLength})),e.data=n.buffer,t.enqueue(e)}pushSEI(e){this.seiList.push(e)}revokeSEI(e){const t=this.seiList.findIndex((t=>t.uuid===e));return-1!==t&&(this.seiList.splice(t,1),!0)}}"undefined"!=typeof self&&"DedicatedWorkerGlobalScope"===self.constructor.name&&self.addEventListener("rtctransform",(e=>{const{transformer:t}=e,{maxSEICount:i}=t.options,r=new EncodedTransformer({maxSEICount:i}),o=new TransformStream({transform:r.sendSEITransform.bind(r)});self.addEventListener("message",(({data:e})=>{const{type:t,content:i}=e;if("push"===t)r.pushSEI(i);else if("revoke"===t){const e=r.revokeSEI(i);return self.postMessage({type:"revoke-ack",content:{uuid:i,isNotSend:e}})}})),t.readable.pipeThrough(o).pipeTo(t.writable)}));class StreamBase extends EnhancedEventEmitter{constructor(e){super(),__publicField(this,"uuid",genUuid$1()),__publicField(this,"isScreen",!1),__publicField(this,"audioMid"),__publicField(this,"videoMid"),__publicField(this,"audioMLine"),__publicField(this,"videoMLine"),__publicField(this,"videoTransceiver"),__publicField(this,"audioTransceiver"),__publicField(this,"vendorHandler"),__publicField(this,"vendorCode",0),__publicField(this,"engineId"),__publicField(this,"logger"),__publicField(this,"__seiHelper",SEIHelper),__publicField(this,"logName","StreamBase"),__publicField(this,"isPublicStream",!1),this._ctx=e,this.engineId=e.id,this.logger=new Logger$1(this.constructor.name,2,e.id)}stopReport(e){this.statsReport.stopReport(e)}destroy(){var e,t;delete this.audioMid,delete this.videoMid,this.statsReport.destroy(),null==(e=this.observer)||e.reset(),delete this.videoTransceiver,delete this.audioTransceiver,null==(t=this.vendorHandler)||t.destroy(),this.vendorCode=0,delete this.vendorHandler}}var StreamState=(e=>(e[e.INIT=0]="INIT",e[e.SUB_ING=1]="SUB_ING",e[e.SUB_ED=2]="SUB_ED",e))(StreamState||{});class LocalStream extends StreamBase{constructor(e,t=StreamIndex.STREAM_INDEX_MAIN){super(e),__publicField(this,"id"),__publicField(this,"stream"),__publicField(this,"streamId"),__publicField(this,"videoTrack"),__publicField(this,"audioTrack"),__publicField(this,"subVideoDescriptions",[]),__publicField(this,"observer"),__publicField(this,"statsReport"),__publicField(this,"pubAudio",!1),__publicField(this,"pubVideo",!1),__publicField(this,"blackFrameRenderInterval"),__publicField(this,"blackFrameLifetimeInterval"),__publicField(this,"pubAttributes"),__publicField(this,"pcSessionId"),__publicField(this,"maxSeiCount",1),__publicField(this,"preReports",{audio:{},video:{}}),__publicField(this,"remoteSdp"),__publicField(this,"currentVideoCodec"),__publicField(this,"_changeCodecs",[]),__publicField(this,"_videoCaps",[]),__publicField(this,"_sendSEIHandler"),__publicField(this,"_trackMatchingTimer"),__publicField(this,"logName","LocalStream"),this.stream=new MediaStream,this.id=genUuid$1(),this.pubAttributes={localaudio:!1,localvideo:!1,videostream:!1,audiostream:!1,extvideo:!1,extaudio:!1,videoDescriptions:[],videoType:VideoType.NORMAL},this.isScreen=t===StreamIndex.STREAM_INDEX_SCREEN,this.statsReport=new LocalStatsReport(e,this);const i=getParameter("SEI_COUNT_FPS");"number"==typeof i&&i<=10&&(this.maxSeiCount=i),this._trackMatchingTimer=setInterval(this._checkTrackMatching.bind(this),5e3)}get enableSimulcast(){return!this.isScreen&&this._ctx.videoProfile.getSimulcastMode()}get videoEncodeConfig(){return this.isScreen?[this._ctx.videoProfile.getScreenEncodeConfig()]:this._ctx.videoProfile.getVideoEncodeConfig()}get audioHasCapture(){return this.pubAttributes.localaudio}get audioHasPublish(){return this.pubAttributes.audiostream}get videoHasCapture(){return this.pubAttributes.localvideo}get videoHasPublish(){return this.pubAttributes.videostream}get isEmptyStream(){return!this.audioTrack&&!this.videoTrack}get initStreamId(){return this.stream.id}async getSelectedCodec(){var e;const t=this._changeCodecs.length>0?this._changeCodecs:this._videoCaps.length>0?this._videoCaps:await internalGetSupportedCodecs(),i=this._ctx.videoProfile.getPreferCodec(this.isScreen),r=this.isScreen?this._ctx.targetScreenCodec:this._ctx.targetCodec;if(i&&i!==VideoCodecType.AUTO){if(i===VideoCodecType.H264&&t.includes(VideoCodecName.H264))return VideoCodecName.H264;if(i===VideoCodecType.VP8&&t.includes(VideoCodecName.VP8))return VideoCodecName.VP8;if(i===VideoCodecType.ByteVC1&&t.includes(VideoCodecName.ByteVC1))return VideoCodecName.ByteVC1}if((null==(e=this._ctx.serverConfig)?void 0:e.videoCodec)&&t.includes(this._ctx.serverConfig.videoCodec))return this._ctx.serverConfig.videoCodec;if(i===VideoCodecType.AUTO&&t.length>0)return t[0];if(r&&t.includes(r))return r;if(t.includes(VideoCodecName.H264))return VideoCodecName.H264;if(t.includes(VideoCodecName.VP8))return VideoCodecName.VP8;throw new Error("no available codec")}startReport(e,t){this.statsReport.setLocalStreamStatsEvtInterval(e,t)}getLocalStreamStats(){return this.statsReport.getLocalStats()}initVideoEncodedTransform(){if(getParameter("DISABLE_ENCODED_TRANSFORM"))return void this.logger.warn("initVideoEncodedTransform","DISABLE_ENCODED_TRANSFORM");if(!this.videoTransceiver||!this.videoTransceiver.sender)return void this.logger.warn("initVideoEncodedTransform","no sender found when trying to bind encodedTransform");const{sender:e}=this.videoTransceiver;if(this._ctx.pcKillSwitch.ctor_encodedinsetablestream_add&&isLegacyEncodedTransformSupported()){const{readable:t,writable:i}=e.createEncodedStreams();if(window.__createDecodeError__)t.pipeThrough(new TransformStream({transform:(e,t)=>{const i=e.data,r=new DataView(i,16);r.setInt16(4,10),r.setInt16(11,20),t.enqueue(e)}})).pipeTo(i);else{const e=new EncodedTransformer({maxSEICount:this.maxSeiCount}),r=new TransformStream({transform:e.sendSEITransform.bind(e)});t.pipeThrough(r).pipeTo(i),this._sendSEIHandler=e}}else if(isEncodedTransformSupported()){const e=new WorkerWrapper$1;this.videoTransceiver.sender.transform=new RTCRtpScriptTransform(e,{maxSEICount:this.maxSeiCount}),this._sendSEIHandler={pushSEI:t=>{e.postMessage({type:"push",content:t},[t.content.buffer])},revokeSEI:async t=>(e.postMessage({type:"revoke",content:t}),new Promise((i=>{e.addEventListener("message",(({data:e})=>{const{type:r,content:o}=e,{uuid:s,isNotSend:n}=o;"revoke-ack"===r&&s===t&&i(n)}))})))}}}initAudioEncodedTransform(){if(getParameter("DISABLE_ENCODED_TRANSFORM"))return void this.logger.warn("initAudioEncodedTransform","DISABLE_ENCODED_TRANSFORM");if(!this.audioTransceiver||!this.audioTransceiver.sender)return void this.logger.warn("initAudioEncodedTransform","no sender found when trying to bind encodedTransform");if(!this._ctx.pcKillSwitch.ctor_encodedinsetablestream_add)return void this.logger.warn("initAudioEncodedTransform","legacy EncodedTransform is not supported");if(!isLegacyEncodedTransformSupported())return void this.logger.warn("initAudioEncodedTransform","legacy EncodedTransform is not supported");const{sender:e}=this.audioTransceiver,{readable:t,writable:i}=e.createEncodedStreams();t.pipeThrough(new TransformStream({transform:(e,t)=>{t.enqueue(e)}})).pipeTo(i)}clean(){reportRtcInvokeStatus(this.engineId,"localstream_clean",`${(new Error).stack}`,0,this.streamId||""),super.destroy(),this.subVideoDescriptions=[],clearTimeout(this.blackFrameLifetimeInterval),clearInterval(this.blackFrameRenderInterval)}switchTrackEnableState(e,t){let i;"audio"===e?i=this.audioTrack:"video"===e&&(i=this.videoTrack);const r=null==i?void 0:i.mediaTrack;return!(!r||(null==r?void 0:r.enabled)===t)&&(r.enabled=t,!0)}resetStream(){this.stream=new MediaStream}genBlackFrame(){var e,t;this.logger.info("genBlackFrame()");const i=(null==(e=this.videoEncodeConfig[0])?void 0:e.frameRate)?constraints2number(null==(t=this.videoEncodeConfig[0])?void 0:t.frameRate):15,r=Math.ceil(1e3/i),o=document.createElement("canvas"),s=o.getContext("2d");o.width=16,o.height=16;const n=e=>{e.fillRect(0,0,16,16)};s&&(s.fillStyle="#000",n(s),this.blackFrameRenderInterval=window.setInterval((()=>{n(s)}),r),this.refreshBlackFrameLifetime());return o.captureStream(i).getVideoTracks()[0]}stopBlackFrame(){this.logger.info("stopBlackFrame()"),clearTimeout(this.blackFrameLifetimeInterval),clearInterval(this.blackFrameRenderInterval),delete this.blackFrameRenderInterval}refreshBlackFrameLifetime(){this.logger.info("refreshBlackFrameLifetime()"),this.blackFrameRenderInterval&&(clearTimeout(this.blackFrameLifetimeInterval),this.blackFrameLifetimeInterval=setTimeout((()=>{clearInterval(this.blackFrameRenderInterval),delete this.blackFrameRenderInterval,this.emit("black-frame-ended")}),Config2.BLACK_FRAME_LIFETIME))}setChangeCodecs(e){this._changeCodecs=e}setVideoCaps(e){if(!e)return;const t=e.split(",").map((e=>{const t=e.trim().toUpperCase();return{H264:VideoCodecName.H264,VP8:VideoCodecName.VP8,BYTEVC1:VideoCodecName.ByteVC1}[t]||null})).filter((e=>null!==e));this._videoCaps=t}sendSEIMessage(e){var t;this.logger.info("sendSEIMessage"),null==(t=this._sendSEIHandler)||t.pushSEI(e)}async revokeSEIMessage(e){var t;return this.logger.info("revokeSEIMessage"),this._sendSEIHandler?null==(t=this._sendSEIHandler)?void 0:t.revokeSEI(e):(this.logger.warn("revokeSEIMessage","no sei handler found"),!1)}destroy(){clearInterval(this._trackMatchingTimer),super.removeAllListeners(),super.destroy()}_checkTrackMatching(){var e,t,i,r,o,s,n,a;const d=null==(e=this.audioTrack)?void 0:e.preprocessingTrack.id,c=null==(t=this.videoTrack)?void 0:t.preprocessingTrack.id,l=null==(r=null==(i=this.audioTransceiver)?void 0:i.sender.track)?void 0:r.id,u=null==(s=null==(o=this.videoTransceiver)?void 0:o.sender.track)?void 0:s.id;this.pubAudio&&d!==l&&(this.logger.error("_checkTrackMatching",`audio track id: ${d} not matching transceiver track id ${l}, streamId: ${this.streamId}`),null==(n=this._ctx.monitor)||n.report("rtc_error",{message:`audio track id: ${d} not matching transceiver track id ${l}`,error_code:-1,stream_id:this.streamId})),this.pubVideo&&c!==u&&(this.logger.error("_checkTrackMatching",`video track id: ${c} not matching transceiver track id ${u}, streamId: ${this.streamId}`),null==(a=this._ctx.monitor)||a.report("rtc_error",{message:`video track id: ${c} not matching transceiver track id ${u}`,error_code:-1,stream_id:this.streamId}))}}class RemoteStream extends StreamBase{constructor(e,t,i,r,o,s){super(e),__publicField(this,"streamId"),__publicField(this,"userId"),__publicField(this,"isPublic"),__publicField(this,"hasVideo"),__publicField(this,"hasAudio"),__publicField(this,"_attributes"),__publicField(this,"streamState"),__publicField(this,"removeTrack",!1),__publicField(this,"observer"),__publicField(this,"statsReport"),__publicField(this,"subVideo"),__publicField(this,"subAudio"),__publicField(this,"subMediaType"),__publicField(this,"subLayer"),__publicField(this,"_sequenceId"),__publicField(this,"stream"),__publicField(this,"videoTrack"),__publicField(this,"audioTrack"),__publicField(this,"recordedVideoFrames"),__publicField(this,"stillExist"),__publicField(this,"originalMediaType"),__publicField(this,"priority"),__publicField(this,"remoteSessionId",""),__publicField(this,"originalStreamIndex",0),__publicField(this,"virtual"),__publicField(this,"pcSessionId"),__publicField(this,"_virtualOccupy"),__publicField(this,"_videoStallObserver"),__publicField(this,"_audioStallObserver"),__publicField(this,"preReports",{audio:{},video:{}}),__publicField(this,"_installInfo"),__publicField(this,"_seiWorkerHandler"),this.virtual=!1,this._virtualOccupy=!1,this.userId=t,this.isScreen=r,this.isPublic=o,this.streamId=i,this.logName=`RemoteStream-${i}`,this.hasAudio=s.audiostream&&s.localaudio,this.hasVideo=s.videostream&&s.localvideo,this._attributes=s,this.vendorCode=(null==s?void 0:s.vendorCode)||0,this.subVideo=!1,this.subAudio=!1,this._sequenceId=0,this.subMediaType=ExtendMediaType.NONE,this.subLayer={spatialLayer:0,spatialSubLayer:-1},this.streamState=0,this.statsReport=new RemoteStatsReport(e,this),this.enableVendorMode&&(this.pcSessionId=genUuid$1())}get vendor(){return this._attributes.vendorCode}get audioHasCapture(){return this._attributes.localaudio}get audioHasPublish(){return this._attributes.audiostream}get videoHasCapture(){return this._attributes.localvideo}get videoHasPublish(){return this._attributes.videostream}get sequenceId(){return this._sequenceId||-1}set sequenceId(e){"number"==typeof e&&(this._sequenceId=e)}get enableVendorMode(){return"number"==typeof this.attributes.vendorCode&&0!==this.attributes.vendorCode}get hasSubscribed(){return 2===this.streamState}get attributes(){var e;return(null==(e=this._attributes.alphaInfo)?void 0:e.enableAlpha)?{...this._attributes,videoDescriptions:this._attributes.videoDescriptions.map((e=>{var t,i;return{...e,height:(null==(t=this._attributes.alphaInfo)?void 0:t.alphaHeight)??e.height/2,width:(null==(i=this._attributes.alphaInfo)?void 0:i.alphaWidth)??e.width}}))}:this._attributes}set attributes(e){this.hasVideo=e.localvideo&&e.videostream,this.hasAudio=e.localaudio&&e.audiostream,this._attributes=e,this.vendorCode=e.vendorCode||0,e.alphaInfo&&this.videoTrack&&this.videoTrack.setAlphaInfo(e.alphaInfo)}get virtualOccupy(){return this._virtualOccupy}set virtualOccupy(e){var t,i;this._virtualOccupy&&!e?null==(t=this.observer)||t.setPushTrack(!1):!this._virtualOccupy&&e&&(null==(i=this.observer)||i.setPushTrack(!0)),this._virtualOccupy=e}startReport(e,t){this.statsReport.setRemoteStreamStatsEvtInterval(e,t)}getRemoteStreamStats(){return this.statsReport.getRemoteStreamStats()}initVideoEncodedTransform(){var e,t;if(getParameter("DISABLE_ENCODED_TRANSFORM"))this.logger.warn("initVideoEncodedTransform","DISABLE_ENCODED_TRANSFORM");else if(this.videoTransceiver&&this.videoTransceiver.receiver){if(this._ctx.pcKillSwitch.ctor_encodedinsetablestream_add&&isLegacyEncodedTransformSupported()){null==(e=this._ctx.monitor)||e.report("rtc_invoke_status",{sdk_api_name:"initVideoEncodedTransform",message:"using legacy EncodedTransform",error_code:0,stream_id:this.streamId,elapse:0});const{receiver:t}=this.videoTransceiver,{readable:i,writable:r}=t.createEncodedStreams();i.pipeThrough(receiveSEITransform({postMessage:e=>{this.safeEmit("onSEIMessage",e.payload)},skipFilter:!!getParameter("SKIP_SEI_FILTER")})).pipeTo(r)}else if(isEncodedTransformSupported()){null==(t=this._ctx.monitor)||t.report("rtc_invoke_status",{sdk_api_name:"initVideoEncodedTransform",message:"using standard EncodedTransform",error_code:0,stream_id:this.streamId,elapse:0});const e=this._ctx.receiveSEIWorker;this.videoTransceiver.receiver.transform=new RTCRtpScriptTransform(e,{streamId:this.streamId,skipFilter:!!getParameter("SKIP_SEI_FILTER")}),this._seiWorkerHandler=e=>{e.data.streamId===this.streamId&&this.safeEmit("onSEIMessage",e.data.msg.payload)},e.addEventListener("message",this._seiWorkerHandler)}}else this.logger.warn("no receiver found when trying to bind encodedTransform")}initAudioEncodedTransform(){if(getParameter("DISABLE_ENCODED_TRANSFORM"))return void this.logger.warn("initVideoEncodedTransform","DISABLE_ENCODED_TRANSFORM");if(!this.audioTransceiver||!this.audioTransceiver.receiver)return void this.logger.warn("no receiver found when trying to bind encodedTransform");if(!this._ctx.pcKillSwitch.ctor_encodedinsetablestream_add)return void this.logger.warn("legacy EncodedTransform is not supported");if(!isLegacyEncodedTransformSupported())return void this.logger.warn("legacy EncodedTransform is not supported");const{receiver:e}=this.audioTransceiver,{readable:t,writable:i}=e.createEncodedStreams();t.pipeThrough(new TransformStream({transform:(e,t)=>{e.data.byteLength<=1e3?t.enqueue(e):this.logger.print("too large audio frame",e.data.byteLength)}})).pipeTo(i)}ontrack(e){var t,i,r,o;try{reportRtcInvokeStatus(this.engineId,"Stream.ontrack",JSON.stringify({uid:this.userId,streamId:this.streamId,streams:e.streams.reduce(((e,t)=>e+mediaStreamStringify(t)),""),transceiver:mediaTransceiverStringify(e.transceiver),track:mediaTrackStringify(e.track)}),0,this.streamId||"")}catch(e){}if(this.enableVendorMode||(null==(r=null==(i=null==(t=e.streams)?void 0:t[0])?void 0:i.id)?void 0:r.includes(this.streamId))){const{track:t}=e;"video"===(null==t?void 0:t.kind)?this._setVideoTrack(t):"audio"===(null==(o=e.track)?void 0:o.kind)&&this._setAudioTrack(t),this._setStream(e.streams[0])}this.safeEmit("ontrack",e)}startVideoStallObserve(e){this.logger.info("startVideoStallObserve","invoke",e.playerId),this._videoStallObserver||(this._videoStallObserver=new VideoStallObserver(this.isScreen,this.engineId)),this._videoStallObserver.start(e)}stopVideoStallObserve(){var e;this.logger.info("stopVideoStallObserve","invoke"),null==(e=this._videoStallObserver)||e.stop()}updateVideoStallInfo(e,t,i){var r,o;let s;if(i?(s=null==(r=this._videoStallObserver)?void 0:r.getStallInfo({interval:e.stats_interval||0,bitrate:e.bitrate,frameRateDecoded:e.frame_rate_decoded,frameRateReceived:e.frame_rate_received}),this._installInfo=s):s=this._installInfo,s){const r=Math.min(s.report.stallDuration,e.stats_interval||0);if(e.play_time=s.pts,e.stall_count=s.report.stallCount,e.is_screen?e.stuck_length=r:e.stall_duration=r,e.pause_duration=Math.min(r,s.pauseDuration),t.stallCount=s.callback.stallCount,t.stallDuration=s.callback.stallDuration,s.stall100ms){const i=Math.min(s.stall100ms.duration,e.stats_interval||0);e.stall_duration_100ms=i,e.stall_count_100ms=s.stall100ms.count,t.stallDuration100MS=i,t.stallCount100MS=s.stall100ms.count}0===s.report.stallCount&&0===s.report.stallDuration||this.logger.print("video_stall_report",this.userId,null==(o=this.videoTrack)?void 0:o.observingPlayerId,JSON.stringify(s.report),i)}}getVideoRenderInfo(){var e;return(null==(e=this._videoStallObserver)?void 0:e.getRecentRenderInfo4Report())||{}}stopAudioStallObserve(){var e;this.logger.info("stopAudioStallObserve","invoke"),null==(e=this._audioStallObserver)||e.stop()}async updateAudioStallInfo(e,t,i){if(this._audioStallObserver){const i=await this._audioStallObserver.getAudioStallInfo();return e.concealedSamples===e.interval_concealed_samples&&e.totalSamplesReceived===e.interval_samples_received?(e.stall_count=0,e.stall_duration=0,t.stallCount=0,t.stallDuration=0):(e.stall_count=i.report.stall_count,e.stall_duration=i.report.stall_duration,t.stallCount=i.callback.stall_count,t.stallDuration=i.callback.stall_duration),0===i.report.stall_count&&0===i.report.stall_duration||this.logger.print("audio_stall_report",this.userId,JSON.stringify({...i.report,callbackList:i.callback.list})),i.extra}this._audioStallObserver=new AudioStallObserver(this),this._audioStallObserver.start(i.concealedSamples,i.totalSamplesReceived),this.logger.print("startAduioObserver","start")}resetStream(){var e,t;null==(e=this.audioTransceiver)||e.stop(),null==(t=this.videoTransceiver)||t.stop(),this.audioTransceiver=void 0,this.videoTransceiver=void 0}clean(){var e,t;this.logger.info("clean",`exec stream.clean ${this.streamId} ${this.userId}`),reportRtcInvokeStatus(this.engineId,"remotestream_clean",`${(new Error).stack}`,0,this.streamId),super.destroy(),this.subAudio=!1,this.subVideo=!1,this.sequenceId=0,null==(e=this.videoTrack)||e.destroy(),this.videoTrack=void 0,null==(t=this.audioTrack)||t.destroy(),this.audioTrack=void 0,this.stream=void 0,this.recordedVideoFrames=void 0,delete this.priority,this._seiWorkerHandler&&this._ctx.receiveSEIWorker.removeEventListener("message",this._seiWorkerHandler)}destroy(){var e,t;this.clean(),null==(e=this._audioStallObserver)||e.destroy(),delete this._audioStallObserver,null==(t=this._videoStallObserver)||t.destroy(),delete this._videoStallObserver,this.attributes={audiostream:!1,localaudio:!1,localvideo:!1,videostream:!1,extvideo:!1,extaudio:!1,videoDescriptions:[]},super.removeAllListeners()}resetHasSubscribed(){this.streamState=0}_setStream(e){this.stream=e,e.onaddtrack=e=>{"video"===e.track.kind?this._setVideoTrack(e.track):"audio"===e.track.kind&&this._setAudioTrack(e.track)}}_setAudioTrack(e){var t,i,r;if((null==(i=null==(t=this.audioTrack)?void 0:t.preprocessingTrack)?void 0:i.id)!==e.id){this.audioTrack=createRemoteAudioTrack(this._ctx,e,{streamIndex:this.isPublic?ExtendStreamIndex.PUBLIC:this.virtual?ExtendStreamIndex.VIRTUAL:this.isScreen?ExtendStreamIndex.SCREEN:ExtendStreamIndex.MAIN,streamUserId:this.userId});const t=this._ctx._remoteAudioTrackDumpConfig[this.isScreen?StreamIndex.STREAM_INDEX_SCREEN:StreamIndex.STREAM_INDEX_MAIN].get(this.userId);(null==t?void 0:t.callback)&&(null==t?void 0:t.frameSize)&&(null==(r=this.audioTrack)||r.setDataFetcher(t.frameSize,(e=>{var i;this.audioHasCapture&&this.audioHasPublish&&(null==(i=t.callback)||i.call(t,e))}))),this.emit("ontrack",this.audioTrack)}}_setVideoTrack(e){var t,i;(null==(i=null==(t=this.videoTrack)?void 0:t.preprocessingTrack)?void 0:i.id)!==e.id&&(this.videoTrack=createRemoteVideoTrack(this._ctx,e,this,{streamIndex:this.isPublic?ExtendStreamIndex.PUBLIC:this.virtual?ExtendStreamIndex.VIRTUAL:this.isScreen?ExtendStreamIndex.SCREEN:ExtendStreamIndex.MAIN,streamUserId:this.userId}),this.emit("ontrack",this.videoTrack))}}var RoomEvent=(e=>(e.RESUBSCRIBE="resubscribe",e.STREAM_FAILED="stream_failed",e.SUBSCRIBE_PUSH_TRACK="subscribe_push_track",e.REMOVE_PUSH_TRACK="remove_push_track",e.VIDEO_FIRST_FRAME="video_first_frame",e.ON_USER_PUBLISH_STATE_CHANGE="on_user_publish_state_change",e.ON_USER_START_AUDIO_CAPTURE="on_user_start_audio_capture",e.ON_USER_STOP_AUDIO_CAPTURE="on_user_stop_audio_capture",e.ON_USER_START_VIDEO_CAPTURE="on_user_start_video_capture",e.ON_USER_STOP_VIDEO_CAPTURE="on_user_stop_video_capture",e.ON_SEI_MESSAGED_RECEIVED="on_sei_messaged_received",e.ON_PUBLISH_RESULT="on_publish_result",e.ON_SUBSCRIBE_RESULT="ON_SUBSCRIBE_RESULT",e.ON_UPDATE_TOKEN_SUCCESS="on_update_token_success",e.ON_REMOTE_STREAM_STATS="ON_REMOTE_STREAM_STATS",e.ON_LOCAL_STREAM_STATS="ON_LOCAL_STREAM_STATS",e.ON_USER_LEAVE="on_user_leave",e.ON_ROOM_ERROR="on_room_error",e.ON_NETWORK_QUALITY="on_network_quality",e.ON_SIMULCAST_SUBSCRIBE_FALLBACK="on_simulcast_subscribe_fallback",e.ON_REMOTE_VIDEO_SIZE_CHANGED="on_remote_video_size_changed",e.ON_SUBTITLE_STATE_CHANGED="ON_SUBTITLE_STATE_CHANGED",e.ON_SUBTITLE_MESSAGE_RECEIVED="ON_SUBTITLE_MESSAGE_RECEIVED",e.ON_VIDEO_STREAM_BANNED="ON_VIDEO_STREAM_BANNED",e.ON_AUDIO_STREAM_BANNED="ON_AUDIO_STREAM_BANNED",e.ON_FORWARD_STREAM_ERROR="ON_FORWARD_STREAM_ERROR",e.ON_REJOIN_WITH_TCP="ON_REJOIN_WITH_TCP",e.PUB_RETRY="PUB_RETRY",e.SUB_RETRY="SUB_RETRY",e.VIDEO_TYPE_CHANGE="VIDEO_TYPE_CHANGE",e.JOIN_SUCCESS="JOIN_SUCCESS",e.UPDATE_PUBLISH="UPDATE_PUBLISH",e))(RoomEvent||{}),StreamMixingEventType=(e=>(e[e.START=1]="START",e[e.START_SUCCESS=2]="START_SUCCESS",e[e.START_FAILED=3]="START_FAILED",e[e.UPDATE=4]="UPDATE",e[e.UPDATE_SUCCESS=5]="UPDATE_SUCCESS",e[e.UPDATE_FAILED=6]="UPDATE_FAILED",e[e.STOP=7]="STOP",e[e.STOP_SUCCESS=8]="STOP_SUCCESS",e[e.STOP_FAILED=9]="STOP_FAILED",e))(StreamMixingEventType||{}),PubState=(e=>(e[e.PUB=0]="PUB",e[e.UNPUB=1]="UNPUB",e))(PubState||{});const reportFirstFrameRecvError=async(e,t,i,r)=>{var o,s,n,a,d,c,l;try{let u="",_=-1;const h="video"===t?null==(o=null==i?void 0:i.videoTrack)?void 0:o.originTrack:null==(s=null==i?void 0:i.audioTrack)?void 0:s.originTrack,p="video"===t?null==(n=null==i?void 0:i.videoTransceiver)?void 0:n.receiver:null==(a=null==i?void 0:i.audioTransceiver)?void 0:a.receiver;try{const i=await(null==(d=e.peerConnection)?void 0:d.getStatsWithLowFrequency(h,!0,p)),r=(i||[]).find((e=>"inbound-rtp"===e.type)),o=await(null==p?void 0:p.getStats()),s=[];let n;null==o||o.forEach((e=>s.push(e.type))),0===(null==i?void 0:i.length)&&0!==s.length&&(n=await(null==(c=e.peerConnection)?void 0:c.getStatsWithLowFrequency(void 0,void 0,p))),u=JSON.stringify({type:t,reports:i.map((e=>e.type)),reports2:s,pc:(null==(l=e.peerConnection)?void 0:l.getOriginRTCPeerConnection())||null,track:(null==h?void 0:h.id)||null,bytes:null==r?void 0:r.bytesReceived,framesReceived:null==r?void 0:r.framesReceived,packetsReceived:null==r?void 0:r.packetsReceived,allReports:n})}catch(e){_=-999,u=e.mseeage||JSON.stringify(e)}null==r||r.report("rtc_invoke_status",{sdk_api_name:"first_frame_recv_timeout",error_code:_,message:u,stream_id:(null==i?void 0:i.streamId)||"",stream_user_id:null==i?void 0:i.userId,elapse:0})}catch(e){}},reportFirstFrameSendError=async(e,t,i,r)=>{var o,s,n,a,d,c,l;try{let u="",_=-1;const h="video"===t?null==(o=null==i?void 0:i.videoTrack)?void 0:o.preprocessingTrack:null==(s=null==i?void 0:i.audioTrack)?void 0:s.preprocessingTrack,p="video"===t?null==(n=null==i?void 0:i.videoTransceiver)?void 0:n.sender:null==(a=null==i?void 0:i.audioTransceiver)?void 0:a.sender;try{const i=await(null==(d=e.peerConnection)?void 0:d.getStatsWithLowFrequency(h,!0,p)),r=(i||[]).find((e=>"outbound-rtp"===e.type)),o=await(null==p?void 0:p.getStats()),s=[];let n;null==o||o.forEach((e=>s.push(e.type))),0===i.length&&0!==s.length&&(n=await(null==(c=e.peerConnection)?void 0:c.getStatsWithLowFrequency(void 0,void 0,p))),u=JSON.stringify({type:t,reports:i.map((e=>e.type)),reports2:s,pc:(null==(l=e.peerConnection)?void 0:l.getOriginRTCPeerConnection())||null,track:(null==h?void 0:h.id)||null,bytes:null==r?void 0:r.bytesSent,framesSent:null==r?void 0:r.framesSent,packetsSent:null==r?void 0:r.packetsSent,allReports:n})}catch(e){_=-999,u=e.mseeage||JSON.stringify(e)}null==r||r.report("rtc_invoke_status",{sdk_api_name:"first_frame_send_timeout",error_code:_,message:u,stream_id:(null==i?void 0:i.streamId)||"",stream_user_id:null==i?void 0:i.userId,elapse:0})}catch(e){}};class RecvFrameObserver extends eventemitter3Exports.EventEmitter{constructor(e,t){super(),__publicField(this,"_audioEventSessionId",genEventSessionId()),__publicField(this,"_videoEventSessionId",genEventSessionId()),__publicField(this,"_stream"),__publicField(this,"_firstAudioFrameTimer"),__publicField(this,"_firstVideoFrameTimer"),__publicField(this,"_transportDelayInterval"),__publicField(this,"_transportDelay"),__publicField(this,"_firstVideoFrameInterval"),__publicField(this,"_firstAudioFrameInterval"),__publicField(this,"_isScreen",!1),__publicField(this,"_audioFirstFrameState",0),__publicField(this,"_videoFirstFrameState",0),__publicField(this,"_timeout",1e4),__publicField(this,"_currentAudioRecv",{startTime:0,eventSessionId:0,type:"login"}),__publicField(this,"_currentVideoRecv",{startTime:0,eventSessionId:0,type:"login"}),__publicField(this,"_login",!1),__publicField(this,"_unMuteAudio",!1),__publicField(this,"_enableAudio",!1),__publicField(this,"_unMuteVideo",!1),__publicField(this,"_enableVideo",!1),__publicField(this,"_remoteUnmuteAudio",!1),__publicField(this,"_remoteUnmuteVideo",!1),__publicField(this,"_audioExternal",!1),__publicField(this,"_pushAudio",!1),__publicField(this,"_videoExternal",!1),__publicField(this,"_pushVideo",!1),__publicField(this,"_autoSubscribeVideo",!1),__publicField(this,"_autoSubscribeAudio",!1),__publicField(this,"_autoSubscribe",!1),__publicField(this,"_publishVideo",!1),__publicField(this,"_publishAudio",!1),__publicField(this,"_subscribeAudio",!1),__publicField(this,"_subscribeVideo",!1),__publicField(this,"_subscribe",!1),__publicField(this,"_pushTrack",!1),__publicField(this,"_multiChatMode",!1),__publicField(this,"_monitor"),__publicField(this,"logger"),this._ctx=e,this._stream=t,this.getTransportDelay(),this._monitor=getMonitor(t.engineId),this.logger=new Logger$1("RecvFrameObserver",0,t.engineId)}async beginRecvFrame(e,t){var i,r,o,s,n,a,d,c,l,u,_,h,p,m,S,g,v,f;await this.getTransportDelay();let E=this._transportDelay,T=!0;if(["login","unmute","subscribe","push_track"].indexOf(t)>=0&&(E=0,T=!1),"audio"===e){T||this._audioEventSessionId++,this._currentAudioRecv={startTime:Date.now(),eventSessionId:this._audioEventSessionId,type:t};const u={media_type:e,event_type:"begin_recv",type:t,is_screen:!!(null==(i=this._stream)?void 0:i.isScreen),start:null==(r=this._currentAudioRecv)?void 0:r.startTime,event_session_id:this._audioEventSessionId,stream_user_id:null==(o=this._stream)?void 0:o.userId,transport_delay:E,vendor_mode:(null==(s=this._stream)?void 0:s.vendorCode)||0,pc_session_id:(null==(n=this._stream)?void 0:n.pcSessionId)||(null==(a=this._ctx.peerConnection)?void 0:a.getConnectionId()),remote_rtc_session_id:null==(d=this._stream)?void 0:d.remoteSessionId,is_public_stream:null==(c=this._stream)?void 0:c.isPublicStream};this._firstAudioFrameTimer&&window.clearTimeout(this._firstAudioFrameTimer),this._firstAudioFrameTimer=setTimeout((()=>{reportFirstFrameRecvError(this._ctx,"audio",this._stream,this._monitor),this.stopRecvFrame("audio","timeout"),this._firstAudioFrameInterval&&window.clearInterval(this._firstAudioFrameInterval)}),this._timeout),this.logger.info("rtcFirstFrameRecv",JSON.stringify(u)),null==(l=this._monitor)||l.report("rtc_first_frame",u),this._watchForFirstAudioFrameRecv(),this._audioFirstFrameState=1,this._login=!0,this._unMuteAudio=!0,this._enableAudio=!0,this._remoteUnmuteAudio=!0}else if("video"===e){T||this._videoEventSessionId++,this._currentVideoRecv={startTime:Date.now(),eventSessionId:this._videoEventSessionId,type:t};const i={media_type:e,event_type:"begin_recv",type:t,is_screen:!!(null==(u=this._stream)?void 0:u.isScreen),start:null==(_=this._currentVideoRecv)?void 0:_.startTime,event_session_id:this._videoEventSessionId,stream_user_id:null==(h=this._stream)?void 0:h.userId,transport_delay:E,vendor_mode:(null==(p=this._stream)?void 0:p.vendorCode)||0,pc_session_id:(null==(m=this._stream)?void 0:m.pcSessionId)||(null==(S=this._ctx.peerConnection)?void 0:S.getConnectionId()),remote_rtc_session_id:null==(g=this._stream)?void 0:g.remoteSessionId,is_public_stream:null==(v=this._stream)?void 0:v.isPublicStream};this._firstVideoFrameTimer&&window.clearTimeout(this._firstVideoFrameTimer),this._firstVideoFrameTimer=setTimeout((()=>{reportFirstFrameRecvError(this._ctx,"video",this._stream,this._monitor),this.stopRecvFrame("video","timeout"),this._firstVideoFrameInterval&&window.clearInterval(this._firstVideoFrameInterval)}),this._timeout),this._watchForFirstVideoFrameRecv(),this.logger.info("rtcFirstFrameRecv",JSON.stringify(i)),null==(f=this._monitor)||f.report("rtc_first_frame",i),this._videoFirstFrameState=1,this._login=!0,this._unMuteVideo=!0,this._enableVideo=!0,this._remoteUnmuteVideo=!0}}stopRecvFrame(e,t){var i,r,o,s,n,a,d,c,l,u,_,h,p,m,S,g,v,f,E,T,R,b,y,I,C,A,k,M,N,O,P,D,w,L,x,F,U,V,B,$,G,W,H,K,X,Z,z,Y;if("audio"===e){if(1!==this._audioFirstFrameState)return;const _={event_type:"recv_end",media_type:e,is_screen:!!(null==(i=this._stream)?void 0:i.isScreen),start:null==(r=this._currentAudioRecv)?void 0:r.startTime,reason:t,result:!1,stream_user_id:null==(o=this._stream)?void 0:o.userId,event_session_id:this._audioEventSessionId,type:null==(s=this._currentAudioRecv)?void 0:s.type,vendor_mode:(null==(n=this._stream)?void 0:n.vendorCode)||0,pc_session_id:(null==(a=this._stream)?void 0:a.pcSessionId)||(null==(d=this._ctx.peerConnection)?void 0:d.getConnectionId()),remote_rtc_session_id:null==(c=this._stream)?void 0:c.remoteSessionId,is_public_stream:null==(l=this._stream)?void 0:l.isPublicStream};this._firstAudioFrameTimer&&window.clearTimeout(this._firstAudioFrameTimer),delete this._currentAudioRecv,this.logger.info("rtcFirstFrameRecv",JSON.stringify(_)),null==(u=this._monitor)||u.report("rtc_first_frame",_),this._audioFirstFrameState=2}else if("video"===e){if(1!==this._videoFirstFrameState)return;const i={event_type:"recv_end",media_type:e,is_screen:!!(null==(_=this._stream)?void 0:_.isScreen),start:null==(h=this._currentVideoRecv)?void 0:h.startTime,reason:t,result:!1,stream_user_id:null==(p=this._stream)?void 0:p.userId,event_session_id:this._videoEventSessionId,type:null==(m=this._currentVideoRecv)?void 0:m.type,vendor_mode:(null==(S=this._stream)?void 0:S.vendorCode)||0,pc_session_id:(null==(g=this._stream)?void 0:g.pcSessionId)||(null==(v=this._ctx.peerConnection)?void 0:v.getConnectionId()),remote_rtc_session_id:null==(f=this._stream)?void 0:f.remoteSessionId,codec:null==(R=null==(T=null==(E=this._stream)?void 0:E.getRemoteStreamStats())?void 0:T.videoStats)?void 0:R.codecType,stats_frame_size_width:null==(I=null==(y=null==(b=this._stream)?void 0:b.getRemoteStreamStats())?void 0:y.videoStats)?void 0:I.frame_size_width,stats_frame_size_height:null==(k=null==(A=null==(C=this._stream)?void 0:C.getRemoteStreamStats())?void 0:A.videoStats)?void 0:k.frame_size_height,stats_frame_rate_decode:null==(O=null==(N=null==(M=this._stream)?void 0:M.getRemoteStreamStats())?void 0:N.videoStats)?void 0:O.decoderOutputFrameRate,stats_frame_rate_receive:null==(w=null==(D=null==(P=this._stream)?void 0:P.getRemoteStreamStats())?void 0:D.videoStats)?void 0:w.receivedFrameRate,stats_frame_decoder_name:null==(F=null==(x=null==(L=this._stream)?void 0:L.getRemoteStreamStats())?void 0:x.videoStats)?void 0:F.decoderName,stats_gpu_url:Config2.GPU_URL||(null==(U=getGpuInfo())?void 0:U.renderer),track_frame_size_width:null==($=null==(B=null==(V=this._stream)?void 0:V.videoTrack)?void 0:B.originTrack.getSettings())?void 0:$.width,track_frame_size_height:null==(H=null==(W=null==(G=this._stream)?void 0:G.videoTrack)?void 0:W.originTrack.getSettings())?void 0:H.height,track_frame_rate:null==(Z=null==(X=null==(K=this._stream)?void 0:K.videoTrack)?void 0:X.originTrack.getSettings())?void 0:Z.frameRate,is_public_stream:null==(z=this._stream)?void 0:z.isPublicStream};this._firstVideoFrameTimer&&window.clearTimeout(this._firstVideoFrameTimer),delete this._currentVideoRecv,this.logger.info("rtcFirstFrameRecv",JSON.stringify(i)),null==(Y=this._monitor)||Y.report("rtc_first_frame",i),this._videoFirstFrameState=2,setTimeout((()=>{var i,r,o,s,n,a,d,c,l,u,_,h,p,m,S,g,v,f,E,T,R,b,y,I,C,A,k,M,N,O,P,D,w,L,x,F,U,V;const B={event_type:"recv_end",media_type:e,is_screen:!!(null==(i=this._stream)?void 0:i.isScreen),start:null==(r=this._currentVideoRecv)?void 0:r.startTime,reason:t,result:!1,stream_user_id:null==(o=this._stream)?void 0:o.userId,event_session_id:this._videoEventSessionId,type:null==(s=this._currentVideoRecv)?void 0:s.type,vendor_mode:(null==(n=this._stream)?void 0:n.vendorCode)||0,pc_session_id:(null==(a=this._stream)?void 0:a.pcSessionId)||(null==(d=this._ctx.peerConnection)?void 0:d.getConnectionId()),remote_rtc_session_id:null==(c=this._stream)?void 0:c.remoteSessionId,codec:null==(_=null==(u=null==(l=this._stream)?void 0:l.getRemoteStreamStats())?void 0:u.videoStats)?void 0:_.codecType,stats_frame_size_width:null==(m=null==(p=null==(h=this._stream)?void 0:h.getRemoteStreamStats())?void 0:p.videoStats)?void 0:m.frame_size_width,stats_frame_size_height:null==(v=null==(g=null==(S=this._stream)?void 0:S.getRemoteStreamStats())?void 0:g.videoStats)?void 0:v.frame_size_height,stats_frame_rate_decode:null==(T=null==(E=null==(f=this._stream)?void 0:f.getRemoteStreamStats())?void 0:E.videoStats)?void 0:T.decoderOutputFrameRate,stats_frame_rate_receive:null==(y=null==(b=null==(R=this._stream)?void 0:R.getRemoteStreamStats())?void 0:b.videoStats)?void 0:y.receivedFrameRate,stats_frame_decoder_name:null==(A=null==(C=null==(I=this._stream)?void 0:I.getRemoteStreamStats())?void 0:C.videoStats)?void 0:A.decoderName,stats_gpu_url:Config2.GPU_URL||(null==(k=getGpuInfo())?void 0:k.renderer),track_frame_size_width:null==(O=null==(N=null==(M=this._stream)?void 0:M.videoTrack)?void 0:N.originTrack.getSettings())?void 0:O.width,track_frame_size_height:null==(w=null==(D=null==(P=this._stream)?void 0:P.videoTrack)?void 0:D.originTrack.getSettings())?void 0:w.height,track_frame_rate:null==(F=null==(x=null==(L=this._stream)?void 0:L.videoTrack)?void 0:x.originTrack.getSettings())?void 0:F.frameRate,is_public_stream:null==(U=this._stream)?void 0:U.isPublicStream};this.logger.info("rtc_first_frame_statistics",JSON.stringify(B)),null==(V=this._monitor)||V.report("rtc_first_frame_statistics",B)}),8e3)}}async recvFrameFinish(e){var t,i,r,o,s,n,a,d,c,l,u,_,h,p,m,S,g,v,f,E,T,R,b,y,I,C,A,k,M,N,O,P,D,w,L,x,F,U,V,B,$,G,W,H;await this.getTransportDelay();let K=this._transportDelay;if("audio"===e){if(1!==this._audioFirstFrameState)return;if(!this._currentAudioRecv)return;const{type:c,startTime:l}=this._currentAudioRecv;["login","unmute","subscribe","push_track"].indexOf(c)>=0&&(K=0);const u={event_type:"recv_end",media_type:e,start:l,result:!0,is_screen:!!(null==(t=this._stream)?void 0:t.isScreen),stream_user_id:null==(i=this._stream)?void 0:i.userId,event_session_id:this._audioEventSessionId,type:c,transport_delay:K,vendor_mode:(null==(r=this._stream)?void 0:r.vendorCode)||0,pc_session_id:(null==(o=this._stream)?void 0:o.pcSessionId)||(null==(s=this._ctx.peerConnection)?void 0:s.getConnectionId()),remote_rtc_session_id:null==(n=this._stream)?void 0:n.remoteSessionId,is_public_stream:null==(a=this._stream)?void 0:a.isPublicStream};delete this._currentAudioRecv,this._firstAudioFrameTimer&&window.clearTimeout(this._firstAudioFrameTimer),this.logger.info("rtcFirstFrameRecv",JSON.stringify(u)),null==(d=this._monitor)||d.report("rtc_first_frame",u),this.emit("recvAudioFirstFrame"),this._audioFirstFrameState=3}else if("video"===e){if(1!==this._videoFirstFrameState)return;if(!this._currentVideoRecv)return;const{type:t,startTime:i}=this._currentVideoRecv;["login","unmute","subscribe","push_track"].indexOf(t)>=0&&(K=0);const r={event_type:"recv_end",media_type:e,is_screen:!!(null==(c=this._stream)?void 0:c.isScreen),start:i,result:!0,stream_user_id:null==(l=this._stream)?void 0:l.userId,event_session_id:this._videoEventSessionId,type:t,transport_delay:K,vendor_mode:(null==(u=this._stream)?void 0:u.vendorCode)||0,pc_session_id:(null==(_=this._stream)?void 0:_.pcSessionId)||(null==(h=this._ctx.peerConnection)?void 0:h.getConnectionId()),remote_rtc_session_id:null==(p=this._stream)?void 0:p.remoteSessionId,codec:null==(g=null==(S=null==(m=this._stream)?void 0:m.getRemoteStreamStats())?void 0:S.videoStats)?void 0:g.codecType,stats_frame_size_width:null==(E=null==(f=null==(v=this._stream)?void 0:v.getRemoteStreamStats())?void 0:f.videoStats)?void 0:E.frameSizeWidth,stats_frame_size_height:null==(b=null==(R=null==(T=this._stream)?void 0:T.getRemoteStreamStats())?void 0:R.videoStats)?void 0:b.frameSizeHeight,stats_frame_rate_decode:null==(C=null==(I=null==(y=this._stream)?void 0:y.getRemoteStreamStats())?void 0:I.videoStats)?void 0:C.decoderOutputFrameRate,stats_frame_rate_receive:null==(M=null==(k=null==(A=this._stream)?void 0:A.getRemoteStreamStats())?void 0:k.videoStats)?void 0:M.receivedFrameRate,stats_frame_decoder_name:null==(P=null==(O=null==(N=this._stream)?void 0:N.getRemoteStreamStats())?void 0:O.videoStats)?void 0:P.decoderName,stats_gpu_url:Config2.GPU_URL||(null==(D=getGpuInfo())?void 0:D.renderer),track_frame_size_width:null==(x=null==(L=null==(w=this._stream)?void 0:w.videoTrack)?void 0:L.originTrack.getSettings())?void 0:x.width,track_frame_size_height:null==(V=null==(U=null==(F=this._stream)?void 0:F.videoTrack)?void 0:U.originTrack.getSettings())?void 0:V.height,track_frame_rate:null==(G=null==($=null==(B=this._stream)?void 0:B.videoTrack)?void 0:$.originTrack.getSettings())?void 0:G.frameRate,is_public_stream:null==(W=this._stream)?void 0:W.isPublicStream};delete this._currentVideoRecv,this._firstVideoFrameTimer&&window.clearTimeout(this._firstVideoFrameTimer),this.logger.info("rtcFirstFrameRecv",JSON.stringify(r)),null==(H=this._monitor)||H.report("rtc_first_frame",r),this.emit("recvVideoFirstFrame"),this._videoFirstFrameState=3,setTimeout((()=>{var r,o,s,n,a,d,c,l,u,_,h,p,m,S,g,v,f,E,T,R,b,y,I,C,A,k,M,N,O,P,D,w,L,x,F,U;const V={event_type:"recv_end",media_type:e,is_screen:!!(null==(r=this._stream)?void 0:r.isScreen),start:i,result:!0,stream_user_id:null==(o=this._stream)?void 0:o.userId,event_session_id:this._videoEventSessionId,type:t,transport_delay:K,vendor_mode:(null==(s=this._stream)?void 0:s.vendorCode)||0,pc_session_id:(null==(n=this._stream)?void 0:n.pcSessionId)||(null==(a=this._ctx.peerConnection)?void 0:a.getConnectionId()),remote_rtc_session_id:null==(d=this._stream)?void 0:d.remoteSessionId,codec:null==(u=null==(l=null==(c=this._stream)?void 0:c.getRemoteStreamStats())?void 0:l.videoStats)?void 0:u.codecType,stats_frame_size_width:null==(p=null==(h=null==(_=this._stream)?void 0:_.getRemoteStreamStats())?void 0:h.videoStats)?void 0:p.frameSizeWidth,stats_frame_size_height:null==(g=null==(S=null==(m=this._stream)?void 0:m.getRemoteStreamStats())?void 0:S.videoStats)?void 0:g.frameSizeHeight,stats_frame_rate_decode:null==(E=null==(f=null==(v=this._stream)?void 0:v.getRemoteStreamStats())?void 0:f.videoStats)?void 0:E.decoderOutputFrameRate,stats_frame_rate_receive:null==(b=null==(R=null==(T=this._stream)?void 0:T.getRemoteStreamStats())?void 0:R.videoStats)?void 0:b.receivedFrameRate,stats_frame_decoder_name:null==(C=null==(I=null==(y=this._stream)?void 0:y.getRemoteStreamStats())?void 0:I.videoStats)?void 0:C.decoderName,stats_gpu_url:Config2.GPU_URL||(null==(A=getGpuInfo())?void 0:A.renderer),track_frame_size_width:null==(N=null==(M=null==(k=this._stream)?void 0:k.videoTrack)?void 0:M.originTrack.getSettings())?void 0:N.width,track_frame_size_height:null==(D=null==(P=null==(O=this._stream)?void 0:O.videoTrack)?void 0:P.originTrack.getSettings())?void 0:D.height,track_frame_rate:null==(x=null==(L=null==(w=this._stream)?void 0:w.videoTrack)?void 0:L.originTrack.getSettings())?void 0:x.frameRate,is_public_stream:null==(F=this._stream)?void 0:F.isPublicStream};this.logger.info("rtc_first_frame_statistics",JSON.stringify(V)),null==(U=this._monitor)||U.report("rtc_first_frame_statistics",V)}),8e3)}}setLogin(e,t={audio:!0,video:!0}){var i,r,o,s;this._login!==e&&(this._login=e,e&&(null==(i=this._stream)?void 0:i.hasAudio)&&t.audio&&this.beginRecvFrame("audio","login"),e&&(null==(r=this._stream)?void 0:r.hasVideo)&&t.video&&this.beginRecvFrame("video","login"),!e&&(null==(o=this._stream)?void 0:o.hasAudio)&&this.stopRecvFrame("audio","leave_room"),!e&&(null==(s=this._stream)?void 0:s.hasVideo)&&this.stopRecvFrame("video","leave_room"))}setUnmuteAudio(e){var t,i,r;if(this._unMuteAudio===e)return;this._unMuteAudio=e;const o=!!(null==(t=this._stream)?void 0:t.hasAudio);(null==(i=this._stream)?void 0:i.audioHasCapture)&&(null==(r=this._stream)?void 0:r.audioHasPublish)&&(this._unMuteAudio&&o?this.beginRecvFrame("audio","unmute"):o&&this.stopRecvFrame("audio","mute"))}setRemoteUnmuteAudio(e){this._remoteUnmuteAudio!==e&&(this._remoteUnmuteAudio=e,this._remoteUnmuteAudio?this.beginRecvFrame("audio","remote_unmute"):this.stopRecvFrame("audio","remote_mute"))}setEnableAudio(e){this._enableAudio!==e&&(this._enableAudio=e,this._enableAudio?this.beginRecvFrame("audio","enable"):this.stopRecvFrame("audio","disable"))}setUnmuteVideo(e){var t,i,r;if(this._unMuteVideo===e)return;this._unMuteVideo=e;const o=!!(null==(t=this._stream)?void 0:t.hasVideo);(null==(i=this._stream)?void 0:i.videoHasCapture)&&(null==(r=this._stream)?void 0:r.videoHasPublish)&&(this._unMuteVideo&&o?this.beginRecvFrame("video","unmute"):o&&this.stopRecvFrame("video","mute"))}setRemoteUnmuteVideo(e){this._remoteUnmuteVideo!==e&&(this._remoteUnmuteVideo=e,this._remoteUnmuteVideo?this.beginRecvFrame("video","remote_unmute"):this.stopRecvFrame("video","remote_mute"))}setEnableVideo(e){this._enableVideo!==e&&(this._enableVideo=e,this._enableVideo?this.beginRecvFrame("video","enable"):this.stopRecvFrame("video","disable"))}setExternalAudioSource(e){this._audioExternal=e}setPushAudio(e){var t;this._audioExternal&&this._pushAudio!==e&&(this._pushAudio=e),this._pushAudio&&this.beginRecvFrame("audio","push"),!e&&(null==(t=this._stream)?void 0:t.hasAudio)&&this.stopRecvFrame("audio","stop_push")}setExternalVideoSource(e){this._videoExternal=e}setPushVideo(e){var t;this._videoExternal&&this._pushVideo!==e&&(this._pushVideo=e),this._pushVideo&&this.beginRecvFrame("video","push"),!e&&(null==(t=this._stream)?void 0:t.hasVideo)&&this.stopRecvFrame("video","stop_push")}setPublishVideo(e){var t;this._publishVideo!==e&&(this._publishVideo=e),this._publishVideo&&this.beginRecvFrame("video","publish"),!e&&(null==(t=this._stream)?void 0:t.hasVideo)&&this.stopRecvFrame("video","unpublish")}setPublishAudio(e){var t;this._publishAudio!==e&&(this._publishAudio=e),this._publishAudio&&this.beginRecvFrame("audio","publish"),!e&&(null==(t=this._stream)?void 0:t.hasAudio)&&this.stopRecvFrame("audio","unpublish")}setAutoSubscribe(e){this._autoSubscribe=e}setAutoSubscribeVideo(e){this._autoSubscribeVideo=e}setAutoSubscribeAudio(e){this._autoSubscribeAudio=e}setSubscribeAudio(e){var t,i;this._autoSubscribeAudio||this._subscribeAudio===e||(this._subscribe=e,e&&(null==(t=this._stream)?void 0:t.hasAudio)&&this.beginRecvFrame("audio","subscribe")),!e&&(null==(i=this._stream)?void 0:i.hasAudio)&&this.stopRecvFrame("audio","unsubscribe")}setSubscribeVideo(e){var t,i;this._autoSubscribeVideo||this._subscribeVideo===e||(this._subscribeVideo=e,e&&(null==(t=this._stream)?void 0:t.hasVideo)&&this.beginRecvFrame("video","subscribe")),!e&&(null==(i=this._stream)?void 0:i.hasVideo)&&this.stopRecvFrame("video","unsubscribe")}setPushTrack(e){var t;this._pushTrack!==e&&(this._pushTrack=e,e&&!this._isScreen&&this.beginRecvFrame("audio","push_track"),!e&&(null==(t=this._stream)?void 0:t.hasAudio)&&this.stopRecvFrame("audio","remove_track"))}setMultiChatMode(e){this._multiChatMode=e}setTimeout(e){this._timeout=e}_watchForFirstVideoFrameRecv(){let e=-1,t=-1;this._firstVideoFrameInterval&&window.clearInterval(this._firstVideoFrameInterval),this._firstVideoFrameInterval=window.setInterval((async()=>{var i,r,o,s,n,a,d;const c=(null==(r=null==(i=this._stream)?void 0:i.vendorHandler)?void 0:r.peer)??this._ctx.peerConnection;if(c&&(null==(s=null==(o=this._stream)?void 0:o.videoTrack)?void 0:s.preprocessingTrack)){const i=null==(n=this._stream.videoTransceiver)?void 0:n.receiver,r=(await c.getStatsWithLowFrequency(null==(d=null==(a=this._stream)?void 0:a.videoTrack)?void 0:d.preprocessingTrack,!0,i)).find((e=>"inbound-rtp"===e.type));if(r&&(r.framesReceived>e||r.packetsReceived>t)){if(-1===e&&-1===t)return e=r.framesReceived,void(t=r.packetsReceived);this.recvFrameFinish("video"),window.clearInterval(this._firstVideoFrameInterval)}}}),200)}_watchForFirstAudioFrameRecv(){let e=-1,t=-1;this._firstAudioFrameInterval&&window.clearInterval(this._firstAudioFrameInterval),this._firstAudioFrameInterval=window.setInterval((async()=>{var i,r,o,s,n,a;const d=(null==(r=null==(i=this._stream)?void 0:i.vendorHandler)?void 0:r.peer)??this._ctx.peerConnection;if(d&&(null==(s=null==(o=this._stream)?void 0:o.audioTrack)?void 0:s.originTrack)){const i=(await d.getStatsWithLowFrequency(null==(a=null==(n=this._stream)?void 0:n.audioTrack)?void 0:a.originTrack)).find((e=>"inbound-rtp"===e.type));if(i&&(i.totalSamplesReceived>e||i.packetsReceived>t)){if(-1===e&&-1===t)return e=i.totalSamplesReceived,void(t=i.packetsReceived);this.recvFrameFinish("audio"),window.clearInterval(this._firstAudioFrameInterval)}}}),200)}async getTransportDelay(){await this.getTransportDelayIntl(),window.clearInterval(this._transportDelayInterval),this._transportDelayInterval=window.setInterval((async()=>{await this.getTransportDelayIntl()}),2e3)}async getTransportDelayIntl(){var e,t;const i=this._ctx.peerConnection;if(i){const r=null==(t=null==(e=this._stream)?void 0:e.videoTransceiver)?void 0:t.receiver,o=await i.getStatsWithLowFrequency(void 0,!0,r),s=o.find((e=>"transport"===e.type&&"connected"===e.dtlsState)),n=o.find((e=>"candidate-pair"===e.type&&"succeeded"===e.state&&e.id===(null==s?void 0:s.selectedCandidatePairId)));n&&(this._transportDelay=Math.round(1e3*n.currentRoundTripTime/2))}}setDisconnect(){this.stopRecvFrame("audio","connection_lost"),this.stopRecvFrame("video","connection_lost"),this.reset()}reset(){this._currentAudioRecv={startTime:0,eventSessionId:0,type:"login"},this._currentVideoRecv={startTime:0,eventSessionId:0,type:"login"},this._login=!1,this._unMuteAudio=!1,this._enableAudio=!1,this._unMuteVideo=!1,this._remoteUnmuteAudio=!1,this._remoteUnmuteVideo=!1,this._enableVideo=!1,this._audioExternal=!1,this._pushAudio=!1,this._videoExternal=!1,this._pushVideo=!1,this._autoSubscribeVideo=!1,this._autoSubscribeAudio=!1,this._autoSubscribe=!1,this._subscribeAudio=!1,this._subscribeVideo=!1,this._subscribe=!1,this._pushTrack=!1,this._multiChatMode=!1,this._firstAudioFrameTimer&&window.clearTimeout(this._firstAudioFrameTimer),this._firstVideoFrameTimer&&window.clearTimeout(this._firstVideoFrameTimer),this._firstAudioFrameInterval&&window.clearInterval(this._firstAudioFrameInterval),this._firstVideoFrameInterval&&window.clearInterval(this._firstVideoFrameInterval),this._transportDelayInterval&&window.clearInterval(this._transportDelayInterval)}get audioFirstFrameReceived(){return 3===this._audioFirstFrameState}get FirstFrameReceived(){return 3===this._audioFirstFrameState}}class SendFrameObserver{constructor(e,t){__publicField(this,"_audioEventSessionId",genEventSessionId()),__publicField(this,"_videoEventSessionId",genEventSessionId()),__publicField(this,"_pcSessionId"),__publicField(this,"_firstAudioFrameTimer"),__publicField(this,"_firstVideoFrameTimer"),__publicField(this,"_stream"),__publicField(this,"_firstVideoFrameInterval"),__publicField(this,"_firstAudioFrameInterval"),__publicField(this,"_currentAudioSend",{startTime:0,eventSessionId:0,type:"login"}),__publicField(this,"_currentVideoSend",{startTime:0,eventSessionId:0,type:"login"}),__publicField(this,"_login",!1),__publicField(this,"_publisher",!1),__publicField(this,"_unMuteAudio",!1),__publicField(this,"_enableAudio",!1),__publicField(this,"_unMuteVideo",!1),__publicField(this,"_enableVideo",!1),__publicField(this,"_audioExternal",!1),__publicField(this,"_pushAudio",!1),__publicField(this,"_videoExternal",!1),__publicField(this,"_pushVideo",!1),__publicField(this,"_autoPublish",!1),__publicField(this,"_publish",!1),__publicField(this,"_timeout",1e4),__publicField(this,"_audioFirstFrameState",0),__publicField(this,"_videoFirstFrameState",0),__publicField(this,"_monitor"),__publicField(this,"logger"),this._ctx=e,this._stream=t,this._monitor=getMonitor(t.engineId),this.logger=new Logger$1("SendFrameObserver",0,t.engineId)}beginSendFrame(e,t){var i,r,o,s,n,a,d,c,l,u,_,h,p,m,S,g;if("audio"===e){this._audioEventSessionId++,this._currentAudioSend={startTime:Date.now(),eventSessionId:this._audioEventSessionId,type:t};const l={event_type:"begin_send",media_type:e,is_screen:!!(null==(i=this._stream)?void 0:i.isScreen),type:t,start:this._currentAudioSend.startTime,event_session_id:this._audioEventSessionId,vendor_mode:(null==(r=this._stream)?void 0:r.vendorCode)||0,pc_session_id:(null==(o=this._stream)?void 0:o.pcSessionId)||(null==(s=this._ctx.peerConnection)?void 0:s.getConnectionId()),capture_session_id:null==(a=null==(n=this._stream)?void 0:n.audioTrack)?void 0:a.captureSessionId,is_public_stream:null==(d=this._stream)?void 0:d.isPublicStream};this._firstAudioFrameTimer&&window.clearTimeout(this._firstAudioFrameTimer),this._firstAudioFrameTimer=setTimeout((()=>{reportFirstFrameSendError(this._ctx,"audio",this._stream,this._monitor),this.stopSendFrame("audio","timeout"),this._firstAudioFrameInterval&&window.clearInterval(this._firstAudioFrameInterval)}),this._timeout),this.logger.info("rtcFirstFrameSend",JSON.stringify(l)),null==(c=this._monitor)||c.report("rtc_first_frame",l),this._watchForFirstAudioFrameSend(),this._audioFirstFrameState=1,this._login=!0,this._publisher=!0,this._publish=!0,this._unMuteAudio=!0,this._pushAudio||(this._enableAudio=!0)}else if("video"===e){this._videoEventSessionId++,this._currentVideoSend={startTime:Date.now(),eventSessionId:this._videoEventSessionId,type:t};const i={event_type:"begin_send",media_type:e,is_screen:!!(null==(l=this._stream)?void 0:l.isScreen),type:t,start:this._currentVideoSend.startTime,event_session_id:this._videoEventSessionId,vendor_mode:(null==(u=this._stream)?void 0:u.vendorCode)||0,pc_session_id:(null==(_=this._stream)?void 0:_.pcSessionId)||(null==(h=this._ctx.peerConnection)?void 0:h.getConnectionId()),capture_session_id:null==(m=null==(p=this._stream)?void 0:p.videoTrack)?void 0:m.captureSessionId,is_public_stream:null==(S=this._stream)?void 0:S.isPublicStream};this._firstVideoFrameTimer&&window.clearTimeout(this._firstVideoFrameTimer),this._firstVideoFrameTimer=setTimeout((()=>{reportFirstFrameSendError(this._ctx,"video",this._stream,this._monitor),this.stopSendFrame("video","timeout"),this._firstVideoFrameInterval&&window.clearInterval(this._firstVideoFrameInterval)}),this._timeout),this._watchForFirstVideoFrameSend(),this.logger.info("rtcFirstFrameSend",JSON.stringify(i)),null==(g=this._monitor)||g.report("rtc_first_frame",i),this._videoFirstFrameState=1,this._login=!0,this._publisher=!0,this._publish=!0,this._unMuteVideo=!0,this._pushVideo||(this._enableVideo=!0)}}stopSendFrame(e,t){var i,r,o,s,n,a,d,c,l,u,_,h,p,m,S,g,v,f,E,T,R,b,y,I,C,A,k,M,N,O,P,D,w,L,x,F,U,V,B,$,G,W,H,K,X,Z,z,Y,j;if("audio"===e){if(1!==this._audioFirstFrameState)return;const _={event_type:"sent_end",media_type:e,is_screen:!!(null==(i=this._stream)?void 0:i.isScreen),start:null==(r=this._currentAudioSend)?void 0:r.startTime,reason:t,result:!1,event_session_id:this._audioEventSessionId,type:null==(o=this._currentAudioSend)?void 0:o.type,vendor_mode:(null==(s=this._stream)?void 0:s.vendorCode)||0,pc_session_id:(null==(n=this._stream)?void 0:n.pcSessionId)||(null==(a=this._ctx.peerConnection)?void 0:a.getConnectionId()),capture_session_id:null==(c=null==(d=this._stream)?void 0:d.audioTrack)?void 0:c.captureSessionId,is_public_stream:null==(l=this._stream)?void 0:l.isPublicStream};this._firstAudioFrameTimer&&window.clearTimeout(this._firstAudioFrameTimer),delete this._currentAudioSend,this.logger.info("rtcFirstFrameSend",JSON.stringify(_)),null==(u=this._monitor)||u.report("rtc_first_frame",_),this._audioFirstFrameState=2}else if("video"===e){if(1!==this._videoFirstFrameState)return;const i={event_type:"sent_end",media_type:e,start:null==(_=this._currentVideoSend)?void 0:_.startTime,is_screen:!!(null==(h=this._stream)?void 0:h.isScreen),reason:t,result:!1,event_session_id:this._videoEventSessionId,type:null==(p=this._currentVideoSend)?void 0:p.type,vendor_mode:(null==(m=this._stream)?void 0:m.vendorCode)||0,pc_session_id:(null==(S=this._stream)?void 0:S.pcSessionId)||(null==(g=this._ctx.peerConnection)?void 0:g.getConnectionId()),capture_session_id:null==(f=null==(v=this._stream)?void 0:v.videoTrack)?void 0:f.captureSessionId,codec:null==(E=this._stream)?void 0:E.currentVideoCodec,track_frame_size_width:null==(b=null==(R=null==(T=this._stream)?void 0:T.videoTrack)?void 0:R.originTrack)?void 0:b.getSettings().width,track_frame_size_height:null==(C=null==(I=null==(y=this._stream)?void 0:y.videoTrack)?void 0:I.originTrack)?void 0:C.getSettings().height,track_frame_rate:null==(M=null==(k=null==(A=this._stream)?void 0:A.videoTrack)?void 0:k.originTrack)?void 0:M.getSettings().frameRate,stats_frame_size_width:null==(P=null==(O=null==(N=this._stream)?void 0:N.getLocalStreamStats())?void 0:O.videoStats)?void 0:P.frame_size_width,stats_frame_size_height:null==(L=null==(w=null==(D=this._stream)?void 0:D.getLocalStreamStats())?void 0:w.videoStats)?void 0:L.frame_size_height,stats_frame_rate_input:null==(U=null==(F=null==(x=this._stream)?void 0:x.getLocalStreamStats())?void 0:F.videoStats)?void 0:U.inputFrameRate,stats_frame_rate_sent:null==($=null==(B=null==(V=this._stream)?void 0:V.getLocalStreamStats())?void 0:B.videoStats)?void 0:$.sentFrameRate,stats_frame_rate_encode:null==(H=null==(W=null==(G=this._stream)?void 0:G.getLocalStreamStats())?void 0:W.videoStats)?void 0:H.encoderOutputFrameRate,stats_frame_encoder_name:null==(Z=null==(X=null==(K=this._stream)?void 0:K.getLocalStreamStats())?void 0:X.videoStats)?void 0:Z.encoderName,stats_is_hardware_encoder_enabled:Config2.H264_HW_ENCODER,stats_gpu_url:Config2.GPU_URL||(null==(z=getGpuInfo())?void 0:z.renderer),is_public_stream:null==(Y=this._stream)?void 0:Y.isPublicStream};this._firstVideoFrameTimer&&window.clearTimeout(this._firstVideoFrameTimer),delete this._currentVideoSend,this.logger.info("rtcFirstFrameSend",JSON.stringify(i)),null==(j=this._monitor)||j.report("rtc_first_frame",i),this._videoFirstFrameState=2,setTimeout((()=>{var i,r,o,s,n,a,d,c,l,u,_,h,p,m,S,g,v,f,E,T,R,b,y,I,C,A,k,M,N,O,P,D,w,L,x,F,U,V,B;const $={event_type:"sent_end",media_type:e,start:null==(i=this._currentVideoSend)?void 0:i.startTime,is_screen:!!(null==(r=this._stream)?void 0:r.isScreen),reason:t,result:!1,event_session_id:this._videoEventSessionId,type:null==(o=this._currentVideoSend)?void 0:o.type,vendor_mode:(null==(s=this._stream)?void 0:s.vendorCode)||0,pc_session_id:(null==(n=this._stream)?void 0:n.pcSessionId)||(null==(a=this._ctx.peerConnection)?void 0:a.getConnectionId()),capture_session_id:null==(c=null==(d=this._stream)?void 0:d.videoTrack)?void 0:c.captureSessionId,codec:null==(l=this._stream)?void 0:l.currentVideoCodec,track_frame_size_width:null==(h=null==(_=null==(u=this._stream)?void 0:u.videoTrack)?void 0:_.originTrack)?void 0:h.getSettings().width,track_frame_size_height:null==(S=null==(m=null==(p=this._stream)?void 0:p.videoTrack)?void 0:m.originTrack)?void 0:S.getSettings().height,track_frame_rate:null==(f=null==(v=null==(g=this._stream)?void 0:g.videoTrack)?void 0:v.originTrack)?void 0:f.getSettings().frameRate,stats_frame_size_width:null==(R=null==(T=null==(E=this._stream)?void 0:E.getLocalStreamStats())?void 0:T.videoStats)?void 0:R.frame_size_width,stats_frame_size_height:null==(I=null==(y=null==(b=this._stream)?void 0:b.getLocalStreamStats())?void 0:y.videoStats)?void 0:I.frame_size_height,stats_frame_rate_input:null==(k=null==(A=null==(C=this._stream)?void 0:C.getLocalStreamStats())?void 0:A.videoStats)?void 0:k.inputFrameRate,stats_frame_rate_sent:null==(O=null==(N=null==(M=this._stream)?void 0:M.getLocalStreamStats())?void 0:N.videoStats)?void 0:O.sentFrameRate,stats_frame_rate_encode:null==(w=null==(D=null==(P=this._stream)?void 0:P.getLocalStreamStats())?void 0:D.videoStats)?void 0:w.encoderOutputFrameRate,stats_frame_encoder_name:null==(F=null==(x=null==(L=this._stream)?void 0:L.getLocalStreamStats())?void 0:x.videoStats)?void 0:F.encoderName,stats_is_hardware_encoder_enabled:Config2.H264_HW_ENCODER,stats_gpu_url:Config2.GPU_URL||(null==(U=getGpuInfo())?void 0:U.renderer),is_public_stream:null==(V=this._stream)?void 0:V.isPublicStream};this.logger.info("rtc_first_frame_statistics",JSON.stringify($)),null==(B=this._monitor)||B.report("rtc_first_frame_statistics",$)}),8e3)}}sendFrameFinish(e){var t,i,r,o,s,n,a,d,c,l,u,_,h,p,m,S,g,v,f,E,T,R,b,y,I,C,A,k,M,N,O,P,D,w,L,x,F,U,V,B,$,G,W,H,K;if("audio"===e){if(1!==this._audioFirstFrameState)return;if(!this._currentAudioSend)return;const{type:c,startTime:l}=this._currentAudioSend,u={event_type:"sent_end",media_type:e,is_screen:!!(null==(t=this._stream)?void 0:t.isScreen),start:l,result:!0,event_session_id:this._audioEventSessionId,type:c,vendor_mode:(null==(i=this._stream)?void 0:i.vendorCode)||0,pc_session_id:(null==(r=this._stream)?void 0:r.pcSessionId)||(null==(o=this._ctx.peerConnection)?void 0:o.getConnectionId()),capture_session_id:null==(n=null==(s=this._stream)?void 0:s.audioTrack)?void 0:n.captureSessionId,is_public_stream:null==(a=this._stream)?void 0:a.isPublicStream};delete this._currentAudioSend,this._firstAudioFrameTimer&&window.clearTimeout(this._firstAudioFrameTimer),this.logger.info("rtcFirstFrameSend",JSON.stringify(u)),null==(d=this._monitor)||d.report("rtc_first_frame",u),this._audioFirstFrameState=3}else if("video"===e){if(1!==this._videoFirstFrameState)return;if(!this._currentVideoSend)return;const{type:t,startTime:i}=this._currentVideoSend,r={event_type:"sent_end",media_type:e,is_screen:!!(null==(c=this._stream)?void 0:c.isScreen),start:i,result:!0,event_session_id:this._videoEventSessionId,type:t,vendor_mode:(null==(l=this._stream)?void 0:l.vendorCode)||0,pc_session_id:(null==(u=this._stream)?void 0:u.pcSessionId)||(null==(_=this._ctx.peerConnection)?void 0:_.getConnectionId()),capture_session_id:null==(p=null==(h=this._stream)?void 0:h.videoTrack)?void 0:p.captureSessionId,codec:null==(m=this._stream)?void 0:m.currentVideoCodec,track_frame_size_width:null==(v=null==(g=null==(S=this._stream)?void 0:S.videoTrack)?void 0:g.originTrack)?void 0:v.getSettings().width,track_frame_size_height:null==(T=null==(E=null==(f=this._stream)?void 0:f.videoTrack)?void 0:E.originTrack)?void 0:T.getSettings().height,track_frame_rate:null==(y=null==(b=null==(R=this._stream)?void 0:R.videoTrack)?void 0:b.originTrack)?void 0:y.getSettings().frameRate,stats_frame_size_width:null==(A=null==(C=null==(I=this._stream)?void 0:I.getLocalStreamStats())?void 0:C.videoStats)?void 0:A._captureResolutionWidth,stats_frame_size_height:null==(N=null==(M=null==(k=this._stream)?void 0:k.getLocalStreamStats())?void 0:M.videoStats)?void 0:N._captureResolutionHeight,stats_frame_rate_input:null==(D=null==(P=null==(O=this._stream)?void 0:O.getLocalStreamStats())?void 0:P.videoStats)?void 0:D.inputFrameRate,stats_frame_rate_sent:null==(x=null==(L=null==(w=this._stream)?void 0:w.getLocalStreamStats())?void 0:L.videoStats)?void 0:x.sentFrameRate,stats_frame_rate_encode:null==(V=null==(U=null==(F=this._stream)?void 0:F.getLocalStreamStats())?void 0:U.videoStats)?void 0:V.encoderOutputFrameRate,stats_frame_encoder_name:null==(G=null==($=null==(B=this._stream)?void 0:B.getLocalStreamStats())?void 0:$.videoStats)?void 0:G.encoderName,stats_is_hardware_encoder_enabled:Config2.H264_HW_ENCODER,stats_gpu_url:Config2.GPU_URL||(null==(W=getGpuInfo())?void 0:W.renderer),is_public_stream:null==(H=this._stream)?void 0:H.isPublicStream};delete this._currentVideoSend,this._firstVideoFrameTimer&&window.clearTimeout(this._firstVideoFrameTimer),this.logger.info("rtcFirstFrameSend",JSON.stringify(r)),null==(K=this._monitor)||K.report("rtc_first_frame",r),this._videoFirstFrameState=3,setTimeout((()=>{var r,o,s,n,a,d,c,l,u,_,h,p,m,S,g,v,f,E,T,R,b,y,I,C,A,k,M,N,O,P,D,w,L,x,F,U,V;const B={event_type:"sent_end",media_type:e,is_screen:!!(null==(r=this._stream)?void 0:r.isScreen),start:i,result:!0,event_session_id:this._videoEventSessionId,type:t,vendor_mode:(null==(o=this._stream)?void 0:o.vendorCode)||0,pc_session_id:(null==(s=this._stream)?void 0:s.pcSessionId)||(null==(n=this._ctx.peerConnection)?void 0:n.getConnectionId()),capture_session_id:null==(d=null==(a=this._stream)?void 0:a.videoTrack)?void 0:d.captureSessionId,codec:null==(c=this._stream)?void 0:c.currentVideoCodec,track_frame_size_width:null==(_=null==(u=null==(l=this._stream)?void 0:l.videoTrack)?void 0:u.originTrack)?void 0:_.getSettings().width,track_frame_size_height:null==(m=null==(p=null==(h=this._stream)?void 0:h.videoTrack)?void 0:p.originTrack)?void 0:m.getSettings().height,track_frame_rate:null==(v=null==(g=null==(S=this._stream)?void 0:S.videoTrack)?void 0:g.originTrack)?void 0:v.getSettings().frameRate,stats_frame_size_width:null==(T=null==(E=null==(f=this._stream)?void 0:f.getLocalStreamStats())?void 0:E.videoStats)?void 0:T._captureResolutionWidth,stats_frame_size_height:null==(y=null==(b=null==(R=this._stream)?void 0:R.getLocalStreamStats())?void 0:b.videoStats)?void 0:y._captureResolutionHeight,stats_frame_rate_input:null==(A=null==(C=null==(I=this._stream)?void 0:I.getLocalStreamStats())?void 0:C.videoStats)?void 0:A.inputFrameRate,stats_frame_rate_sent:null==(N=null==(M=null==(k=this._stream)?void 0:k.getLocalStreamStats())?void 0:M.videoStats)?void 0:N.sentFrameRate,stats_frame_rate_encode:null==(D=null==(P=null==(O=this._stream)?void 0:O.getLocalStreamStats())?void 0:P.videoStats)?void 0:D.encoderOutputFrameRate,stats_frame_encoder_name:null==(x=null==(L=null==(w=this._stream)?void 0:w.getLocalStreamStats())?void 0:L.videoStats)?void 0:x.encoderName,stats_is_hardware_encoder_enabled:Config2.H264_HW_ENCODER,stats_gpu_url:Config2.GPU_URL||(null==(F=getGpuInfo())?void 0:F.renderer),is_public_stream:null==(U=this._stream)?void 0:U.isPublicStream};this.logger.info("rtc_first_frame_statistics",JSON.stringify(B)),null==(V=this._monitor)||V.report("rtc_first_frame_statistics",B)}),8e3)}}setLogin(e){var t,i;this._login!==e&&(this._login=e,e&&((null==(t=this._stream)?void 0:t.videoTrack)&&this._stream.pubVideo&&this.beginSendFrame("video","login"),(null==(i=this._stream)?void 0:i.audioTrack)&&this._stream.pubAudio&&this.beginSendFrame("audio","login")),!e&&this._audioSending&&this.stopSendFrame("audio","leave_room"),!e&&this._videoSending&&this.stopSendFrame("video","leave_room"))}setPublish(e){var t,i;this._publish!==e&&(this._publish=e,e&&((null==(t=this._stream)?void 0:t.videoTrack)&&this._stream.pubVideo&&this.beginSendFrame("video","publish"),(null==(i=this._stream)?void 0:i.audioTrack)&&this._stream.pubAudio&&this.beginSendFrame("audio","publish")),!e&&this._audioSending&&this.stopSendFrame("audio","unpublish"),!e&&this._videoSending&&this.stopSendFrame("video","unpublish"))}setUnmuteAudio(e){var t;this._unMuteAudio!==e&&(this._unMuteAudio=e,(null==(t=this._stream)?void 0:t.audioHasCapture)&&(e&&this.beginSendFrame("audio","unmute"),!e&&this._audioSending&&this.stopSendFrame("audio","mute")))}setEnableAudio(e){var t;this._enableAudio!==e&&(null==(t=this._stream)?void 0:t.pubAudio)&&(this._enableAudio=e,e&&this.beginSendFrame("audio","enable"),!e&&this._audioSending&&this.stopSendFrame("audio","disable"))}setUnmuteVideo(e){var t;this._unMuteVideo!==e&&(this._unMuteVideo=e,(null==(t=this._stream)?void 0:t.videoHasCapture)&&(e&&this.beginSendFrame("video","unmute"),!e&&this._videoSending&&this.stopSendFrame("video","mute")))}setEnableVideo(e){var t;this._enableVideo!==e&&(null==(t=this._stream)?void 0:t.pubVideo)&&(this._enableVideo=e,e&&this.beginSendFrame("video","enable"),!e&&this._videoSending&&this.stopSendFrame("video","disable"))}setPushAudio(e){this._pushAudio!==e&&(this._pushAudio=e,e&&this.beginSendFrame("audio","push"),!e&&this._audioSending&&this.stopSendFrame("audio","stop_push"))}setPushVideo(e){this._pushVideo!==e&&(this._pushVideo=e,e&&this.beginSendFrame("video","push"),!e&&this._videoSending&&this.stopSendFrame("video","stop_push"))}setAutoPublish(e){this._autoPublish=e}setPublisher(e){this._publisher!==e&&(this._publisher=e,!e&&this._audioSending&&this.stopSendFrame("audio","audience"),!e&&this._videoSending&&this.stopSendFrame("video","audience"))}setDisconnect(){this._audioSending&&this.stopSendFrame("audio","connection_lost"),this._videoSending&&this.stopSendFrame("video","connection_lost"),this.reset()}setTimeout(e){this._timeout=e}setPCSessionId(e){this._pcSessionId=e}async _getFirstVideoFrameStats(){var e,t,i,r,o,s;const n=null==(t=null==(e=this._stream)?void 0:e.videoTrack)?void 0:t.preprocessingTrack,a=null==(r=null==(i=this._stream)?void 0:i.videoTransceiver)?void 0:r.sender,d=(null==(s=null==(o=this._stream)?void 0:o.vendorHandler)?void 0:s.peer)??this._ctx.peerConnection;if(d&&n){return(await d.getStatsWithLowFrequency(n,!0,a)).filter((e=>"outbound-rtp"===e.type))}}async _getFirstAudioFrameStats(){var e,t,i,r,o,s;const n=null==(t=null==(e=this._stream)?void 0:e.audioTrack)?void 0:t.preprocessingTrack,a=null==(r=null==(i=this._stream)?void 0:i.audioTransceiver)?void 0:r.sender,d=(null==(s=null==(o=this._stream)?void 0:o.vendorHandler)?void 0:s.peer)??this._ctx.peerConnection;if(d&&n){return(await d.getStatsWithLowFrequency(n,!0,a)).find((e=>"outbound-rtp"===e.type))}}_watchForFirstVideoFrameSend(){let e=-1,t=-1;this._firstVideoFrameInterval&&window.clearInterval(this._firstVideoFrameInterval),this._firstVideoFrameInterval=window.setInterval((async()=>{const i=await this._getFirstVideoFrameStats();let r=0,o=0;if(null==i||i.map((e=>{r+=e.framesSent,o+=e.packetsSent})),i&&i.length>0&&(r>e||o>t)){if(-1===e&&-1===t)return e=r,void(t=o);this.sendFrameFinish("video"),window.clearInterval(this._firstVideoFrameInterval)}}),100)}_watchForFirstAudioFrameSend(){let e=-1;this._firstAudioFrameInterval&&window.clearInterval(this._firstAudioFrameInterval),this._firstAudioFrameInterval=window.setInterval((async()=>{const t=await this._getFirstAudioFrameStats();if(t&&t.packetsSent>e){if(-1===e)return void(e=t.packetsSent);this.sendFrameFinish("audio"),window.clearInterval(this._firstAudioFrameInterval)}}),100)}reset(){this._login=!1,this._publisher=!1,this._unMuteAudio=!1,this._enableAudio=!1,this._unMuteVideo=!1,this._enableVideo=!1,this._audioExternal=!1,this._pushAudio=!1,this._videoExternal=!1,this._pushVideo=!1,this._autoPublish=!1,this._publish=!1,this._audioFirstFrameState=0,this._videoFirstFrameState=0,this._currentAudioSend={startTime:0,eventSessionId:0,type:"login"},this._currentVideoSend={startTime:0,eventSessionId:0,type:"login"},window.clearTimeout(this._firstAudioFrameTimer),window.clearTimeout(this._firstVideoFrameTimer),window.clearInterval(this._firstAudioFrameInterval),window.clearInterval(this._firstVideoFrameInterval)}destroy(){this.reset(),delete this._stream}get _audioSending(){return 1===this._audioFirstFrameState}get _videoSending(){return 1===this._videoFirstFrameState}}const CONFIG={audio:{delay:1200,stallRadio:.3},video:{delay:1200,stallRadio:.6},screen_audio:{delay:1600,stallRadio:.8},screen_video:{delay:1600,stallRadio:.8}};class NetworkQualityManager{constructor(e){__publicField(this,"_preUplinkStats",new Map),__publicField(this,"_preDownlinkStats",new Map),__publicField(this,"_timer"),__publicField(this,"_delayTimer"),__publicField(this,"reportor"),this._ctx=e}updateUplinkStats(e,t){const{audioStats:i,videoStats:r,isScreen:o}=e;if(i.sendKBitrate>0&&i.rtt){const e=o?"screen_audio":"audio",{rtt:t,_fractionLost:r,_retransmittedRate:s}=i,n=this._getQosLevel(t,r||0,s||0),a=this._preUplinkStats.get(e)||[n];this._preUplinkStats.set(e,[...a,n].slice(-2))}if(r.sentKBitrate>0&&r.rtt){const i=o?"screen_video":"video";let{_fractionLost:s}=r;const{rtt:n,_sendBandWidth:a,_retransmittedRate:d}=r;0===a&&(s=Math.max(.65,s));const c=this._getQosLevel(n,s||0,d||0),l=this._getUplinkVideoQoE(e,t),u=this._getVideoUplinkNetworkQuality(c,l),_=this._preUplinkStats.get(i)||[u];this._preUplinkStats.set(i,[..._,u].slice(-2))}this._startNetworkQualityReport()}updateDownlinkStats(e,t){if(!t)return;const{audioActive:i,videoActive:r}=this._getStreamActiveState(t),{audioStats:o,videoStats:s,isScreen:n,userId:a}=e;let d,c,l=!0,u=!0;if(i)if(0===o.receivedKBitrate)l=!1;else{const{rtt:e,audioLossRate:t,stallDuration:i,statsInterval:r,e2eDelay:a}=o,c=i/r,l=n?"screen_audio":"audio",u=this._getQosLevel(e,t||0,s._retransmittedRate||0),_=this._getDownlinkQoE(l,c,a);d=this._getNetworkQuality(u,_)}if(r)if(0===s.receivedKBitrate||0===s.rtt)u=!1;else{const{rtt:e,videoLossRate:t,stallDuration:i,statsInterval:r,e2eDelay:o,_retransmittedRate:a}=s,d=i/r,l=n?"screen_video":"video",u=this._getQosLevel(e,t||0,a||0),_=this._getDownlinkQoE(l,d,o);c=this._getNetworkQuality(u,_)}const _=`${a}${n?"_screen":""}`;if(!l&&!u)return void this._preDownlinkStats.delete(_);const h=d&&c?Math.ceil((d+c)/2):d||c;if(h){const e=this._preDownlinkStats.get(_)||[h];this._preDownlinkStats.set(_,[...e,h].slice(-2)),this._startNetworkQualityReport()}}destroy(){this._timer&&(window.clearInterval(this._timer),delete this._timer),this._delayTimer&&(window.clearTimeout(this._delayTimer),delete this._delayTimer),this._preUplinkStats.clear(),this._preDownlinkStats.clear()}_startNetworkQualityReport(){this._delayTimer||this._timer||(this._preUplinkStats.size>0||this._preDownlinkStats.size>0)&&(this._delayTimer=setTimeout((()=>{delete this._delayTimer,this._reportNetworkQuality(),this._timer=window.setInterval((()=>{this._reportNetworkQuality()}),2e3)}),300))}_reportNetworkQuality(){var e;let t,i;if(["connected","connecting"].includes(null==(e=this._ctx.handler)?void 0:e.getConnectionState())){const e=this._getBetterQualityAndRemoveOldest("audio","up"),r=this._getBetterQualityAndRemoveOldest("video","up");t=e&&r?Math.ceil((e+r)/2):e||r||this._getBetterQualityAndRemoveOldest("screen_video","up")||this._getBetterQualityAndRemoveOldest("screen_audio","up")||NetworkQuality.EXCELLENT;const o=Array.from(this._preDownlinkStats.keys()).map((e=>this._getBetterQualityAndRemoveOldest(e,"down"))).filter((e=>e));i=Math.ceil(o.reduce(((e,t)=>t+e),0)/o.length)||NetworkQuality.UNKNOWN}else t=i=NetworkQuality.DOWN;navigator.onLine||(t=NetworkQuality.DOWN,i=NetworkQuality.DOWN),"function"==typeof this.reportor&&this.reportor(t,i)}_getNetworkQuality(e,t){return 1===t?Math.max(e-2,1):2===t?e:Math.min(e+1,5)}_getVideoUplinkNetworkQuality(e,t){return 1===t||0===t?e:2===t?Math.min(e+1,5):Math.min(e+2,5)}_getQosLevel(e,t,i){let r;return r=(!e||e<=250)&&t<=.15?1:(!e||e<=500)&&t<=.3?2:(!e||e<=750)&&t<=.45?3:(!e||e<=1e3)&&t<=.6?4:5,i>.5?r=Math.max(r,4):i>.35?r=Math.max(r,3):i>.15&&(r=Math.max(r,2)),r}_getUplinkQoE(e,t){let i=0;switch(e){case"audio":case"video":i=t<.05?1:t<.1?2:3;break;case"screen_video":case"screen_audio":i=t<.04?1:t<.08?2:3}return i}_getUplinkVideoQoE(e,t){var i;const r=(null==(i=null==e?void 0:e.videoStats)?void 0:i.rid)||"0";if(!t)return 0;const o=t.pubAttributes.videoDescriptions[r],s=e.videoStats,n=s.encodedFrameWidth*s.encodedFrameHeight/(o.width*o.height),a=s.sentFrameRate/o.framerate;let d=0,c=0;return"number"!=typeof n||Number.isNaN(n)||(d=n>=.9?1:n<.9&&n>=.8?2:3),"number"!=typeof a||Number.isNaN(a)||(c=a>=.8?1:a<.8&&a>=.6?2:3),Math.max(0,d,c)}_getDownlinkQoE(e,t,i){const r=CONFIG[e];return t>r.stallRadio||i>r.delay||t>r.stallRadio/2&&i>r.delay/2?3:(t>r.stallRadio/2||r.delay,2)}_getBetterQualityAndRemoveOldest(e,t){let i=NetworkQuality.UNKNOWN;const r="up"===t?this._preUplinkStats:this._preDownlinkStats,o=r.get(e);if(o){const t=o.filter((e=>e));t.length>0&&(i=Math.min(...t)),o.shift(),0===o.length&&r.delete(e)}return i}_getStreamActiveState({subMediaType:e,_attributes:t,subVideo:i,subAudio:r}){return{audioActive:r&&audioInMediaType(e)&&t.localaudio&&t.audiostream,videoActive:i&&videoInMediaType(e)&&t.localvideo&&t.videostream}}}class VideoSizeObserver{constructor(e){__publicField(this,"_timer"),__publicField(this,"_remoteVideoSizeCache",{}),__publicField(this,"_remoteScreenSizeCache",{}),__publicField(this,"onchange"),this._room=e,this._start()}destroy(){this._timer&&(window.clearInterval(this._timer),delete this._timer),this._remoteVideoSizeCache={},this._remoteScreenSizeCache={}}_start(){this._timer||(this._timer=window.setInterval((()=>{const e={},t={};this._room.remoteStreams.forEach(((i,r)=>{i.forEach((i=>{var o,s,n;const a=null==(o=i.videoTrack)?void 0:o.preprocessingTrack;if(a){const o=i.isScreen?this._remoteScreenSizeCache:this._remoteVideoSizeCache,{width:d=0,height:c=0}=o[r]||{};let l=0,u=0;if(isFirefox)({width:l,height:u}=(null==(s=null==i?void 0:i.videoTrack)?void 0:s.getSizeByPlayer())??{width:0,height:0});else{const e=a.getSettings();l=e.width||0,u=e.height||0;const t=null==(n=i._attributes)?void 0:n.alphaInfo;(null==t?void 0:t.enableAlpha)&&(l=t.alphaWidth??l,u=t.alphaHeight??u/2)}c===u&&d===l||"function"==typeof this.onchange&&this.onchange(r,i.isScreen,l,u),delete o[r],(i.isScreen?t:e)[r]={width:l,height:u}}}))})),Object.keys(this._remoteVideoSizeCache).forEach((e=>{"function"==typeof this.onchange&&this.onchange(e,!1,0,0)})),Object.keys(this._remoteScreenSizeCache).forEach((e=>{"function"==typeof this.onchange&&this.onchange(e,!0,0,0)})),this._remoteVideoSizeCache=e,this._remoteScreenSizeCache=t}),1e3))}}const SUBTITLE_PREFIX=Array.from((new TextEncoder).encode("subt")),ERROR_CODE_MAP={1:ErrorCode.SUBTITLE_ERR_POSTPROCESS,2:ErrorCode.SUBTITLE_ERR_CONNECTION_ERROR,3:ErrorCode.SUBTITLE_ERR_PROCESS_ERROR},logger$5=new Logger$1("SubtitleTool",1),checkSourceLanguage=e=>{var t;if(e.extraInfo)try{const t=JSON.parse(e.extraInfo);t.source_language&&["zh","en","ja"].indexOf(t.source_language)}catch{}else{const i=(null==(t=navigator.language)?void 0:t.substring(0,2))||"";["zh","en","ja"].indexOf(i)>-1&&(e.extraInfo=JSON.stringify({source_language:i}))}},_SubtitleTool=class{constructor(e,t){__publicField(this,"_taskId"),__publicField(this,"_sourceLanguage","zh"),__publicField(this,"_updating",!1),__publicField(this,"onEvent"),__publicField(this,"onMessage"),__publicField(this,"_preConfig"),__publicField(this,"_timer"),this._ctx=e,this._roomConf=t;const{extraInfo:i}=t.userInfo;if(i)try{const e=JSON.parse(i);e.source_language&&(this._sourceLanguage=e.source_language)}catch{}}async start(e){logger$5.info("start","Invoke config: %o",e),checkEnum(e.mode,"mode",[SUBTITLE_MODE.ASR_ONLY,SUBTITLE_MODE.ASR_AND_TRANSLATION]);const t=Array.isArray(e.targetLanguage)?e.targetLanguage:[e.targetLanguage||""];if(e.mode===SUBTITLE_MODE.ASR_AND_TRANSLATION&&t.findIndex((e=>-1===SUPPORT_LANG.indexOf(e)))>-1)throw new SDKError(ErrorCode.INVALID_PARAMS,"Invalid targetLanguage.");if(this._taskId)throw new SDKError(ErrorCode.SUBTITLE_ALREADY_ON,"Already turned on subtitle");this._preConfig={targetLanguage:t,mode:e.mode},this._taskId=(Date.now().toString()+this._roomConf.roomId+this._roomConf.userId).substring(0,20),await this._sendSubtitleSignalingWithRetry(e,this._taskId)}async update(e){if(logger$5.info("update","Invoke config: %o",e),!this._taskId)throw new SDKError(ErrorCode.SUBTITLE_NOT_TURNED_ON,"Start subtitle first.");this._sourceLanguage=e.sourceLanguage,this._updating=!0;try{await this._ctx.signalingManager.sendSignaling("controlMessage",this._genChangeSubtitleLanguageSignaling(e,this._taskId))}catch(e){throw this._updating=!1,e}}stop(){logger$5.info("stop","Invoke"),this._taskId&&this._ctx.signalingManager.sendSignaling("controlMessage",{type:"subtitle",action:"stopped",appId:this._ctx.appId,roomId:this._roomConf.roomId,userId:this._roomConf.userId,taskId:this._taskId}).finally((()=>{var e;delete this._taskId,null==(e=this.onEvent)||e.call(this,{event:SubtitleEventType.STOPPED}),this._clearTimer()}))}async reconnect(){this._taskId&&this._preConfig&&(await this._ctx.signalingManager.sendSignaling("controlMessage",{type:"subtitle",action:"stopped",appId:this._ctx.appId,roomId:this._roomConf.roomId,userId:this._roomConf.userId,taskId:this._taskId}),delete this._taskId,this.start(this._preConfig))}getConfig(){return this._preConfig}destroy(){logger$5.info("destroy","Invoke"),this.stop(),delete this._preConfig,delete this._taskId}onResult(e){var t,i,r;const{error:o,errorMessage:s,eventType:n}=e.body;if(0!==o){const e=new SDKError(ERROR_CODE_MAP[o]||ErrorCode.SUBTITLE_ERR_UNKNOWN,s||"");null==(t=this.onEvent)||t.call(this,{event:SubtitleEventType.ERROR,errorCode:e.code,errorMessage:e.message}),this._clearTimer()}else"SubtitleStarted"===n?(null==(i=this.onEvent)||i.call(this,{event:SubtitleEventType.STARTED}),this._clearTimer()):this._updating&&"LanguageChanged"===n&&(this._updating=!1,null==(r=this.onEvent)||r.call(this,{event:SubtitleEventType.UPDATED}))}onMessageRecv(e,t=!1){var i;if(t||this._taskId&&this._preConfig){const t=parseSubtitleMessage(e);if(!t||0===t.length)return!1;if(this._taskId&&this._preConfig){const{mode:e,targetLanguage:r}=this._preConfig,o=[];t.forEach((t=>{if(e===SUBTITLE_MODE.ASR_ONLY)t.mode===e&&o.push(t);else{const e=r.includes(t.language);(e||t.mode===SUBTITLE_MODE.ASR_ONLY)&&o.push(t),t.mode===SUBTITLE_MODE.ASR_ONLY&&e&&o.push({...t,mode:SUBTITLE_MODE.ASR_AND_TRANSLATION})}})),o.length>0&&(null==(i=this.onMessage)||i.call(this,o))}return!0}return!1}async _sendSubtitleSignalingWithRetry(e,t,i=0){await this._ctx.signalingManager.sendSignaling("controlMessage",this._genSubtitleSignaling(e,t)),this._timer=self.setTimeout((()=>{var r;2===i?(null==(r=this.onEvent)||r.call(this,{event:SubtitleEventType.ERROR,errorCode:ErrorCode.TIME_OUT,errorMessage:"start subtitle timeout."}),delete this._timer,this.stop()):this._sendSubtitleSignalingWithRetry(e,t,i+1)}),_SubtitleTool.retryIntervel)}_genSubtitleSignaling(e,t){return{taskId:t,type:"subtitle",action:"started",roomId:this._roomConf.roomId,appId:this._ctx.appId,userId:this._roomConf.userId,subtitleMeta:{subtitleConfig:{mode:e.mode,usersConfig:[{userId:this._roomConf.userId,targetLanguages:Array.isArray(e.targetLanguage)?e.targetLanguage:[e.targetLanguage||""]}]},vendorConfig:{type:0}}}}_genChangeSubtitleLanguageSignaling(e,t){return{taskId:t,type:"subtitle",action:"subtitleUpdated",roomId:this._roomConf.roomId,appId:this._ctx.appId,userId:this._roomConf.userId,subtitleMeta:{protocol:1,languageConfig:{sourceLanguages:[{userId:this._roomConf.userId,languageCode:[e.sourceLanguage]}]}}}}_clearTimer(){this._timer&&(self.clearTimeout(this._timer),delete this._timer)}};let SubtitleTool=_SubtitleTool;__publicField(SubtitleTool,"retryIntervel",3e4);const parseSubtitleMessage=({message:e})=>{if(e instanceof ArrayBuffer&&e.byteLength>8)try{const t=new DataView(e,0);let i=0;if(SUBTITLE_PREFIX.every((e=>t.getUint8(i++)===e))){const r=t.getUint32(i);if(i+=4,r===t.byteLength-8){const t=Utils.ab2str(e.slice(8)),{data:i,type:r}=JSON.parse(t);if("subtitle"===r)return i}}}catch{}return!1},SUPPORT_LANG=["zh","zh-Hant","tn","vi","iu","it","id","hi","en","ho","he","es","el","uk","ur","tk","tr","ti","ty","tl","to","th","ta","te","sl","sk","ss","eo","sm","sg","st","sv","ja","tw","qu","pt","pa","no","nb","nr","my","bn","mn","mh","mk","ml","mr","ms","lu","ro","lt","lv","lo","kj","hr","kn","ki","cs","ca","nl","ko","ht","gu","ka","kl","km","lg","kg","fi","fj","fr","ru","ng","de","tt","da","ts","cv","fa","bs","pl","bi","nd","ba","bg","az","ar","af","sq","ab","os","ee","et","ay","lzh","am","ckb","cy","gl","ha","hy","ig","kmr","ln","nso","ny","om","sn","so","sr","sw","xh","yo","zu"];function camel2Snake(e){return e.replace(/[A-Z]/g,(e=>`_${e.toLowerCase()}`))}function assignIn(e,t){return{...e,...t}}function cloneDeep(e){const t={};return Object.keys(e).forEach((i=>{const r=e[i];try{Array.isArray(r)?t[i]=r.map((e=>null!==e&&"object"==typeof e?cloneDeep(e):e)):t[i]=null!==r&&"object"==typeof r?cloneDeep(r):r}catch{}})),t}function values(e){return null===e?[]:Object.keys(e).map((t=>e[t]))}const logger$4=new Logger$1("Locker",2);let lockId=1;class PromiseLock2{constructor(e){__publicField(this,"lockingPromise",Promise.resolve()),__publicField(this,"locks",0),__publicField(this,"name",""),__publicField(this,"lockId"),__publicField(this,"closeReason"),this.lockId=lockId++,e&&(this.name=e),logger$4.info(`lock-${this.name}-${this.lockId}`,"is created.")}get isLocked(){return this.locks>0}lock(){let e;this.locks+=1,logger$4.info(`lock-${this.name}-${this.lockId}`,`locked, current queue ${this.locks}.`);const t=new Promise((t=>{e=()=>{this.locks-=1,logger$4.info(`lock-${this.name}-${this.lockId}`,`unlocked, current queue ${this.locks}.`),t()}})),i=this.lockingPromise.then((()=>e));return this.lockingPromise=this.lockingPromise.then((()=>t)),i}}var DC_MESSAGE_DIRECTION=(e=>(e[e.SEND=0]="SEND",e[e.FEEDBACK=1]="FEEDBACK",e))(DC_MESSAGE_DIRECTION||{}),DC_MESSAGE_FUNCTION_TYPE=(e=>(e[e.P2P=0]="P2P",e[e.SIGNAL=1]="SIGNAL",e[e.BROADCAST=2]="BROADCAST",e[e.BUSINESS_SERVER=3]="BUSINESS_SERVER",e))(DC_MESSAGE_FUNCTION_TYPE||{}),USER_MESSAGE_SEND_RESULT=(e=>(e[e.SUCCESS=0]="SUCCESS",e[e.TIMEOUT=1]="TIMEOUT",e[e.BROKEN=2]="BROKEN",e[e.NO_RECEIVER=3]="NO_RECEIVER",e[e.NO_RELAYPATH=4]="NO_RELAYPATH",e[e.EXCEED_QPS=5]="EXCEED_QPS",e[e.SEND_TO_SERVER_ERROR=17]="SEND_TO_SERVER_ERROR",e[e.SERVER_RESPONSE_ERROR=18]="SERVER_RESPONSE_ERROR",e[e.NOT_JOIN=100]="NOT_JOIN",e[e.NOT_LOGIN=105]="NOT_LOGIN",e[e.SERVER_PARAMS_NOTSET=106]="SERVER_PARAMS_NOTSET",e[e.UNKNOWN=1e3]="UNKNOWN",e))(USER_MESSAGE_SEND_RESULT||{});const USER_MESSAGE_SEND_RESULT_EXPLAIN={0:[0,"success"],1:[ErrorCode.USER_MESSAGE_TIMEOUT,"timeout, failed to send."],2:[ErrorCode.USER_MESSAGE_BROKEN,"dataChannel broken, failed to send."],3:[ErrorCode.USER_MESSAGE_NO_RECEIVER,"cannot find the receiver."],4:[ErrorCode.USER_MESSAGE_NO_RECEIVER,"cannot find relay path."],5:[ErrorCode.USER_MESSAGE_EXCEED_QPS,"cannot find relay path."],17:[ErrorCode.USER_MESSAGE_SEND_TO_SERVER_ERROR,"failed to send to business server."],18:[ErrorCode.USER_MESSAGE_SERVER_RESPONSE_ERROR,"business server response error."],100:[ErrorCode.USER_MESSAGE_NOT_JOIN,"not join room"],105:[ErrorCode.USER_MESSAGE_NOT_LOGIN,"not login."],106:[ErrorCode.USER_MESSAGE_SERVER_PARAMS_NOTSET,"server param is not set."],1e3:[ErrorCode.USER_MESSAGE_UNKNOWN,"unknown."]},noPrintSignaling=[],noAckSignaling=[SignalEvent.ENGINE_CONTROL_MESSAGE];var SIGNALING_FUNCTION_TYPE=(e=>(e[e.C2S=0]="C2S",e[e.C2C=1]="C2C",e[e.C2GW=2]="C2GW",e[e.C2CDirect=3]="C2CDirect",e[e.C2RTM=4]="C2RTM",e))(SIGNALING_FUNCTION_TYPE||{});const DATA_CHANNEL_MESSAGE_TIMEOUT=6e4,P2P_MESSAGE_TIMEOUT=12e3;class DataChannelSignaling extends eventemitter3Exports.EventEmitter{constructor(e,t,i){super(),__publicField(this,"_singlingCache",new Map),__publicField(this,"_p2pCache",new Map),__publicField(this,"_rttIds",{}),__publicField(this,"_p2pMessageId",new MessageId),__publicField(this,"_clearDataChannelListener"),__publicField(this,"_monitor"),__publicField(this,"logger"),this.id=e,this._dataChannel=t,this.connectionIds=i,this._clearDataChannelListener=this._handleHandler(),this._monitor=getMonitor(e),this.logger=new Logger$1("DataChannelSignaling",3,e)}destroy(){this._clearDataChannelListener(),delete this._dataChannel,this._singlingCache.forEach(((e,t)=>{e.error(new SDKError(ErrorCode.OPERATION_CANCEL,"disconnect")),this._singlingCache.delete(t)})),this._singlingCache.clear(),this._p2pCache.clear(),this._rttIds={}}sendSignaling(e,t,i,r=6e4){return new Promise(((o,s)=>{var n;const a=this._genHeader(i);a.id=createRandomId();const d=a.id.join("-"),c={error_code:0,message:JSON.stringify(t),signaling_event:`call-${e}`,signaling_type:"Send",stream_id:t.streamId,stream_user_id:t.streamUserId,direction:"up",event_session_id:d,...this.connectionIds};null==(n=this._monitor)||n.report("rtc_signaling",c);const l="customMessage"===e;l&&RTSMsgReportor.samplingOne2ManyMsg(this.id,Number(a.id.join("")),t);const u=setTimeout((()=>{this._singlingCache.delete(d),s(new SDKError(ErrorCode.TIME_OUT,`${e} message time out`)),l&&RTSMsgReportor.updateOne2ManyMsgAck(this.id,t,999)}),r);this._singlingCache.set(d,{start:getServerNow(),signalingType:e,success:e=>{clearTimeout(u),o(e),l&&RTSMsgReportor.updateOne2ManyMsgAck(this.id,t,0)},error:e=>{clearTimeout(u),s(e),l&&RTSMsgReportor.updateOne2ManyMsgAck(this.id,t,e.code)},id:d}),this.logger.info("Signal",`>>>>>> [${e}{${a.functionType}}][${d}]`,t),this._sendMessage(e,a,t)}))}sendPingSignaling(){return this.sendSignaling("CheckConnectivity",{ts:Date.now()},{functionType:2})}async sendP2PMessage({msg:e,...t},i){const r=e instanceof ArrayBuffer;return this._sendP2PMessage(RTSMsgReportor.samplingP2PMsg(this.id,{ver:1,id:this._p2pMessageId.getMessageId(),time:Date.now(),dir:DC_MESSAGE_DIRECTION.SEND,type:DC_MESSAGE_FUNCTION_TYPE.P2P,err:USER_MESSAGE_SEND_RESULT.SUCCESS,...t,binary:r,msg:r?await Utils.ab2b64str(e):e}),i)}_sendP2PMessage(e,t={}){const i=this._genHeader({needAck:!0,functionType:1,...t,id:createRandomId()});return isRttMessage(e.msg)?this._rttIds[e.id]=e.id:e.dir===DC_MESSAGE_DIRECTION.SEND&&this.logger.info(`_sendP2PMessage [DC Signaling p2p{${i.functionType}} >>]`,JSON.stringify(e)),new Promise(((t,r)=>{if(e.dir===DC_MESSAGE_DIRECTION.SEND){const i=setTimeout((()=>{this._p2pCache.delete(e.id),r(new SDKError(ErrorCode.USER_MESSAGE_TIMEOUT,"P2P message timeout")),RTSMsgReportor.updateP2PMsgAck(this.id,e,999)}),12e3);this._p2pCache.set(e.id,{success:(r,o)=>{clearTimeout(i),t(o),RTSMsgReportor.updateP2PMsgAck(this.id,e,0)},error:t=>{clearTimeout(i),RTSMsgReportor.updateP2PMsgAck(this.id,e,t.err);const[o,s]=USER_MESSAGE_SEND_RESULT_EXPLAIN[t.err]||[ErrorCode.USER_MESSAGE_UNKNOWN,`err: ${t.err}, msg: ${t.msg}`];r({err:t.err,code:o,message:t.msg||s})}})}try{this._sendMessage("p2p",i,e)}catch(e){throw e.code===ErrorCode.NOT_CONNECTED_YET&&(e.code=ErrorCode.USER_MESSAGE_BROKEN),e}}))}_sendMessage(e,t,i){var r;if(!this._dataChannel||"open"!==this._dataChannel.readyState)throw new SDKError(ErrorCode.NOT_CONNECTED_YET,"DataChannel not open");const o=getParameter("SIGNAL_COMPRESSION")||t.zip,s=t.version+(Number(o)<<4)+(Number(t.encrypt)<<5),n=Number(t.needAck)+(Number(t.direction)<<1)+(Number(t.functionType)<<2)+(Number(t.binary)<<6),a=Utils.str2ab(JSON.stringify([e,i])),d=concatenate(Uint8Array,[s,n,...t.id||[]],o||t.zip?pako$1.deflate(new Uint8Array(a)):new Uint8Array(a));try{this._dataChannel.send(d.buffer)}catch(e){throw null==(r=this._monitor)||r.report("rtc_error",{message:`datachannel send error: ${e.message}`,error_code:RtcErrorCode.DC_SEND_ERROR}),e}"p2p"===e?RTSMsgReportor.updateP2PMsgReq(this.id,i,d.buffer.byteLength):"customMessage"===e&&RTSMsgReportor.updateOne2ManyMsgReq(this.id,i,d.buffer.byteLength)}_dispartData(e){const t=new Uint8Array(e);let i=0;const r=t[i++],o=t[i++],s={version:15&r,zip:!(16&~r),encrypt:!(32&~r),needAck:!(1&~o),direction:(2&o)>>1,functionType:(60&o)>>2,binary:!(64&~o)};if(s.needAck||1===s.direction){for(;i<=6;i++)if(!isByteId(t[i])){i++;break}s.id=Array.from(t.slice(2,i))}return{header:s,data:t.slice(i)}}_feedbackSignaling(e,t,i){const r=this._genHeader({needAck:!0,direction:1,id:e.split("-").map((e=>Number(e)))});noPrintSignaling.includes(t)||this.logger.info("Signal",`>>>>>> [${t}-res][${e}]`),this._sendMessage(`${t}-res`,r,i)}async _handleMessage(e){var t;const i=Date.now(),{byteLength:r}=e,o=this._dispartData(e);let{data:s}=o;const{header:n}=o;if(n.zip){const e=new pako$1.Inflate;e.push(s,!0),s=e.result}const a=Utils.ab2str(s);let d=[];try{d=JSON.parse(a)}catch(e){return void(e instanceof Error&&(null==(t=this._monitor)||t.report("rtc_signaling_msg_error",{error_code:-1,message:e.message,reason:"message parse failed",...this.connectionIds})))}switch(n.functionType){case 0:case 4:this.C2S(n,d,a,r,i);break;case 1:this.C2C(d,r,i);break;case 2:this.C2GW(n,d,a)}}async C2S(e,t,i,r,o){var s,n;const a=(null==(s=e.id)?void 0:s.join("-"))||"";if(1===e.direction)this._handleAckMessage(a,t[0]||{},i,e.functionType);else if(Array.isArray(t)){const s=t[0];t=t[1],noPrintSignaling.includes(s)||this.logger.info("Signal",`<<<<<< ${s}{${e.functionType}}`,t,a),noAckSignaling.includes(s)||this._feedbackSignaling(a,s,s===SignalEvent.ON_CUSTOM_MESSAGE?{...t,message:""}:""),t.binary&&"string"==typeof t.message&&(t.message=await Utils.b64str2ab(t.message,this._monitor));const d=Date.now();this.emit(s,{...t}),s===SignalEvent.ON_CUSTOM_MESSAGE&&RTSMsgReportor.reportOne2ManyMsgRecv(this.id,t,{msg_size:r,recv_msg_ts:o,fwd_msg_ts:d}),null==(n=this._monitor)||n.report("rtc_signaling",{error_code:0,message:i,signaling_event:`on-${s}`,signaling_type:"Recv",stream_id:t.streamId,stream_user_id:t.clientId,direction:"down",...this.connectionIds})}}async C2C(e,t,i){Array.isArray(e)&&(e=e[1]);const r=null==e?void 0:e.id;switch(this._rttIds[r]||(null==e?void 0:e.dir)===DC_MESSAGE_DIRECTION.FEEDBACK||isRttMessage(null==e?void 0:e.msg)?delete this._rttIds[r]:this.logger.info("Signal","<<<<<< p2p response",e),e.dir){case DC_MESSAGE_DIRECTION.SEND:const r=Date.now();if(!isRttMessage(null==e?void 0:e.msg)){const{binary:t,msg:i,room:r,to:o,from:s}=e,n=""===r?t?SignalEvent.USER_BINARY_MESSAGE_RECEIVED_OUTSIDE_ROOM:SignalEvent.USER_MESSAGE_RECEIVED_OUTSIDE_ROOM:t?SignalEvent.USER_BINARY_MESSAGE_RECEIVED:SignalEvent.USER_MESSAGE_RECEIVED;o?this.emit(n,{...e,msg:t?await Utils.b64str2ab(i,this._monitor):i}):this.emit(SignalEvent.ON_CUSTOM_MESSAGE,{clientId:s,binary:t,message:t?await Utils.b64str2ab(i,this._monitor):i})}this._sendP2PMessage({...e,dir:DC_MESSAGE_DIRECTION.FEEDBACK,msg:""}),RTSMsgReportor.reportP2PMsgRecv(this.id,e,{msg_size:t,recv_msg_ts:i,fwd_msg_ts:r});break;case DC_MESSAGE_DIRECTION.FEEDBACK:this._handleP2PMsgFeedback(e)}}C2GW(e,t,i){var r,o;if(1===e.direction){const o=(null==(r=e.id)?void 0:r.join("-"))||"";this._handleAckMessage(o,t[0]||{},i,e.functionType)}else{const[r,s={}]=t;if("RXMediaMsg"===r){const{type:e,data:t}=s;switch(null==(o=this._monitor)||o.report("rtc_signaling",{error_code:0,message:i,signaling_event:`on-${e}`,signaling_type:"Recv",stream_id:"",stream_user_id:"",direction:"down",...this.connectionIds}),e){case"RSCP":try{const i=JSON.parse(t);Array.isArray(i)&&this.emit(e,i)}catch(e){}break;case"RTT":try{const i=JSON.parse(t);i.length&&this.emit(e,i[0])}catch(e){}break;case"SSC":try{const i=JSON.parse(t);i.length&&(this.logger.info("Signal",`<<<<<< ${e}`,i),this.emit(e,i[0]))}catch(e){}}}else"engineControlMessage"===r&&this.C2S(e,t,i,0,0)}}_handleHandler(){const e=e=>{this.logger.warn("_handleHandler","dataChannel close",e)},t=e=>{this.logger.error("_handleHandler","dataChannel error",e)},i=e=>{this._handleMessage(e.data)};return this._dataChannel.addEventListener("close",e),this._dataChannel.addEventListener("error",t),this._dataChannel.addEventListener("message",i),()=>{const r=this._dataChannel;null==r||r.removeEventListener("close",e),null==r||r.removeEventListener("error",t),null==r||r.removeEventListener("message",i)}}_genHeader(e={}){return{version:2,zip:!1,encrypt:!1,needAck:!0,direction:0,functionType:0,binary:!1,...e}}_handleAckMessage(e,t,i,r){var o;const s=this._singlingCache.get(e);s&&(this._singlingCache.delete(e),200===t.code?s.success(t):s.error(t),this.logger.info("Signal",`<<<<<< [${s.signalingType}{${r}}-ack] ${e}`,t));const n={error_code:0,message:i,signaling_event:null==s?void 0:s.signalingType,signaling_type:"Ack",stream_id:"",stream_user_id:"",direction:"down",elapse:s?getServerNow()-s.start:0,...this.connectionIds};(null==s?void 0:s.id)&&(n.event_session_id=s.id),null==(o=this._monitor)||o.report("rtc_signaling",n)}_handleP2PMsgFeedback(e){const t=this._p2pCache.get(e.id);t&&(this._p2pCache.delete(e.id),e.err===USER_MESSAGE_SEND_RESULT.SUCCESS?t.success(e.id,e):t.error(e))}}class RoomContext{constructor(e,t){__publicField(this,"roomId"),__publicField(this,"userInfo"),__publicField(this,"userId"),__publicField(this,"sessionId",genUuid$1()),__publicField(this,"token"),__publicField(this,"rtcVid"),__publicField(this,"joinPromise"),__publicField(this,"startJoinTimestamp"),__publicField(this,"_liveControlMessage"),__publicField(this,"_userStreamMap",new Map),__publicField(this,"_roomConfig",{isAutoPublish:!0,isAutoSubscribeAudio:!0,isAutoSubscribeVideo:!0,roomProfileType:RoomProfileType.communication}),__publicField(this,"_vendorConfig",{enableMultiVendor:!1,vendorCode:0}),__publicField(this,"_roomAttr",{multiChatMode:!1,bigRoomMode:!1}),__publicField(this,"_tokenPublishPrivilegeExpired",!1),__publicField(this,"_tokenSubscribePrivilegeExpired",!1),__publicField(this,"_streamQueueMap",new Map),__publicField(this,"_monitor"),this._ctx=t,this.roomId=e.roomId,this.userInfo=e.userInfo,this.userId=e.userInfo.userId,this.token=e.token,this._monitor=getMonitor(t.id)}async checkJoinRoom(){await this.joinPromise}get vendorConfig(){return this._vendorConfig}setVendorConfig(e){this._vendorConfig=e}updateRoomAttributes(e){this._roomAttr={...this._roomAttr,...e}}setLiveControlMessage(e){this._liveControlMessage=e}getLiveControlMessage(){return this._liveControlMessage}isMultiChatMode(){return this._roomAttr.multiChatMode}updateRoomConfig(e){return this._roomConfig=assignIn(this._roomConfig,e),this._roomConfig}get isAutoPublish(){return!this.isRTSOnlyRoom()&&this._roomConfig.isAutoPublish}get isAutoSubscribeAudio(){return!this.isRTSOnlyRoom()&&this._roomConfig.isAutoSubscribeAudio}get isAutoSubscribeVideo(){return!this.isRTSOnlyRoom()&&this._roomConfig.isAutoSubscribeVideo}get remoteVideoConfig(){return this._roomConfig.remoteVideoConfig}get roomProfileType(){return this._roomConfig.roomProfileType||RoomProfileType.communication}isRTSOnlyRoom(){return this._roomConfig.roomMode===RoomMode.ROOM_MODE_RTS_ONLY}get rtsOnlySignalHeader(){return this.isRTSOnlyRoom()?{functionType:SIGNALING_FUNCTION_TYPE.C2RTM}:void 0}updateUserPubInfo(e){const t=this._userStreamMap.get(e.clientId)||{};e.screen?(t.screenAudio=e.attributes.audiostream,t.screenVideo=e.attributes.videostream):(t.audio=e.attributes.audiostream,t.video=e.attributes.videostream),this._userStreamMap.set(e.clientId,t)}getUserPubInfo(e){return{audio:!1,video:!1,screenAudio:!1,screenVideo:!1,...this._userStreamMap.get(e)||{}}}resetUserPubInfo(){this._userStreamMap.clear()}get tokenPublishPrivilegeExpired(){return this._tokenPublishPrivilegeExpired}get tokenSubscribePrivilegeExpired(){return this._tokenSubscribePrivilegeExpired}setTokenPublishPrivilegeExpired(e){this._tokenPublishPrivilegeExpired=e}setTokenSubscribePrivilegeExpired(e){this._tokenSubscribePrivilegeExpired=e}getStayRoomDuration(){return this.startJoinTimestamp?getServerNow()-this.startJoinTimestamp:0}getStreamQueueLock(e){let t=this._streamQueueMap.get(e);return t||(t=new PromiseLock2(e),this._streamQueueMap.set(e,t)),t}report(e,t,i){var r;null==(r=this._monitor)||r.report(e,{room_id:this.roomId,user_id:this.userId,rtc_session_id:this.sessionId,rtc_vid:this.rtcVid,...t},i)}}const WAIT_TRACK_TIMEOUT=6e4,logRemoteStream=(e,t,i)=>{i.info(e,"userId: %o, subAudio: %o, subVideo: %o, audioMid: %o, videoMid: %o, sequenceId: %o",t.userId,t.subAudio,t.subVideo,t.audioMid,t.videoMid,t.sequenceId)};function checkRoomState(e,t,i){const r=i.value;return i.value=async function(...e){if(!this._ctx.signalingManager.isConnected())throw new SDKError(ErrorCode.NOT_CONNECTED_YET,`error in ${t}: try again after connect`);try{await(this._roomConf||this.config).checkJoinRoom()}catch(e){throw new SDKError(ErrorCode.JOIN_ROOM_FAILED,`error in ${t}: try again after joined`)}return r.apply(this,e)},i}const enableStreamQueue=!0;function streamQueue(e,t,i){const r=i.value;return i.value=async function(...e){const i=this._roomConf,o=this._logger,s=getStreamIdentification(e[0]);if(!s)return null==r?void 0:r.apply(this,e);o.info("streamQueue","lock stream %o, task %o",s.slice(-5),t);const n=await i.getStreamQueueLock(s).lock();try{return await(null==r?void 0:r.apply(this,e))}finally{o.info("streamQueue","unlock stream %o, task %o",s.slice(-5),t),n()}},i}function getStreamIdentification(e){return e instanceof LocalStream?e.id:null==e?void 0:e.streamId}var __defProp$9=Object.defineProperty,__getOwnPropDesc$9=Object.getOwnPropertyDescriptor,__decorateClass$9=(e,t,i,r)=>{for(var o,s=r>1?void 0:r?__getOwnPropDesc$9(t,i):t,n=e.length-1;n>=0;n--)(o=e[n])&&(s=(r?o(t,i,s):o(s))||s);return r&&s&&__defProp$9(t,i,s),s};class ForwardStreamManager extends EnhancedEventEmitter{constructor(e,t){super(),__publicField(this,"_forwardDstRooms",new Map),__publicField(this,"forwardStreamState","stopped"),this._ctx=e,this._roomConf=t}async startForwardStream2Rooms(e){if("running"===this.forwardStreamState||"paused"===this.forwardStreamState)throw new SDKError(ErrorCode.UNEXPECTED_INVOKE_FORWARD_STREAM,`should not invoke startForwardStreamToRooms in state: ${this.forwardStreamState}`);const t=await this._sendForwardStreamSignaling("start",this._roomConf.roomId,e);this._updateDstRooms(e,t);const i=this._transformForwardStreamResult(t);return this.forwardStreamState="running",i}async updateForwardStream2Rooms(e){if("stopped"===this.forwardStreamState)throw new SDKError(ErrorCode.UNEXPECTED_INVOKE_FORWARD_STREAM,`should not invoke updateForwardStreamToRooms in state: ${this.forwardStreamState}`);let t=this._mockForwardStreamResult(e);"running"===this.forwardStreamState&&(t=await this._sendForwardStreamSignaling("update",this._roomConf.roomId,e)),this._updateDstRooms(e,t);return this._transformForwardStreamResult(t)}async stopForwardStream2Rooms(){if("stopped"===this.forwardStreamState)throw new SDKError(ErrorCode.UNEXPECTED_INVOKE_FORWARD_STREAM,`should not invoke stopForwardStreamToRooms in state: ${this.forwardStreamState}`);let e=this._mockForwardStreamResult([]);if("running"===this.forwardStreamState&&(e=await this._sendForwardStreamSignaling("stop",this._roomConf.roomId)),this._updateDstRooms([],e),[...this._forwardDstRooms.keys()].length>0)throw new SDKError(ErrorCode.UNEXPECTED_ERROR,`stopforwardstream failed: ${JSON.stringify(e)}`);const t=this._transformForwardStreamResult(e);return this.forwardStreamState="stopped",t}async pauseForwardStream2AllRooms(){if("paused"===this.forwardStreamState||"stopped"===this.forwardStreamState)throw new SDKError(ErrorCode.UNEXPECTED_INVOKE_FORWARD_STREAM,`should not invoke pauseForwardStreamToAllRooms in state: ${this.forwardStreamState}`);const e=await this._sendForwardStreamSignaling("stop",this._roomConf.roomId),t=this._transformForwardStreamResult(e);return this.forwardStreamState="paused",t}async resumeForwardStream2AllRooms(e=!1){if(!e&&["running","stopped"].includes(this.forwardStreamState))throw new SDKError(ErrorCode.UNEXPECTED_INVOKE_FORWARD_STREAM,`should not invoke resumeForwardStreamToAllRooms in state: ${this.forwardStreamState}`);const t=this._getDstRooms(),i=await this._sendForwardStreamSignaling("start",this._roomConf.roomId,t);this._updateDstRooms(t,i);const r=this._transformForwardStreamResult(i);return this.forwardStreamState="running",r}resumeFromReconnect(){"running"===this.forwardStreamState&&this.resumeForwardStream2AllRooms(!0).then((e=>{e.forEach((e=>{e.state===ForwardStreamState.FORWARD_STREAM_STATE_FAILURE&&this.safeEmit(RoomEvent.ON_FORWARD_STREAM_ERROR,e)}))}))}onForwardDstRoomUserKick(e){const t=[{dstRoomId:e.dstRoomId,code:200,forwardStreamType:"stop"}];this._updateDstRooms([],t),this.safeEmit(RoomEvent.ON_FORWARD_STREAM_ERROR,{roomId:e.dstRoomId,state:ForwardStreamState.FORWARD_STREAM_STATE_FAILURE,error:ForwardStreamError.FORWARD_STREAM_ERROR_REMOTE_KICKED})}destoy(){super.removeAllListeners(),this._forwardDstRooms.clear(),this.forwardStreamState="stopped"}_mockForwardStreamResult(e){const t=[];return this._forwardDstRooms.forEach(((e,i)=>{t.push({dstRoomId:i,forwardStreamType:"stop",code:200})})),e.forEach((e=>{const i=t.findIndex((t=>t.dstRoomId===e.roomId));-1===i?t.push({dstRoomId:e.roomId,forwardStreamType:"start",code:e.roomId===this._roomConf.roomId?400:200}):t[i].forwardStreamType="update"})),t}_transformForwardStreamResult(e){e||(e=[]);const t=[];for(const{dstRoomId:i,code:r}of e){const e={roomId:i,state:ForwardStreamState.FORWARD_STREAM_STATE_SUCCESS,error:ForwardStreamError.FORWARD_STREAM_ERROR_OK};200===r||(400===r?(e.state=ForwardStreamState.FORWARD_STREAM_STATE_FAILURE,e.error=ForwardStreamError.FORWARD_STREAM_ERROR_REMOTE_KICKED):r>=700&&r<800?(e.state=ForwardStreamState.FORWARD_STREAM_STATE_FAILURE,e.error=ForwardStreamError.FORWARD_STREAM_ERROR_INVALID_TOKEN):(e.state=ForwardStreamState.FORWARD_STREAM_STATE_FAILURE,e.error=ForwardStreamError.FORWARD_STREAM_ERROR_RESPONSE)),t.push(e)}return t}_updateDstRooms(e,t=[]){0===t.length&&this._forwardDstRooms.clear(),t.forEach((({dstRoomId:t,code:i,forwardStreamType:r})=>{if(200===i)if("stop"===r)this._forwardDstRooms.delete(t);else{const i=e.find((e=>e.roomId===t));if(!i&&!this._forwardDstRooms.has(t))throw new SDKError(ErrorCode.UNEXPECTED_ERROR,`unknow roomid ${t} in signaling return`);let r=this._forwardDstRooms.get(t)??{token:void 0};r=Object.assign(r,i),this._forwardDstRooms.set(t,r)}else this._forwardDstRooms.has(t)&&this._forwardDstRooms.delete(t)}))}_getDstRooms(){const e=[];return this._forwardDstRooms.forEach(((t,i)=>{e.push({roomId:i,token:t.token})})),e}async _sendForwardStreamSignaling(e,t,i){var r,o;const s=`${genEventSessionId()}`;if("stop"!==e){const e=i.map((e=>e.roomId));this._roomConf.report("rtc_forward_stream",{type:"begin",dst_rooms:`{ ${e.map((e=>`"${e}"`)).join(",")} }`,event_session_id:s})}const n={forwardStreamType:e,roomId:t};("start"===e||"update"===e)&&(n.dstRoomInfos=null==i?void 0:i.map((e=>({dstRoomId:e.roomId,dstToken:Utils.token2auth(this._ctx.appId,e.roomId,this._roomConf.userId,e.token)}))));const a=await this._ctx.signalingManager.sendSignaling("forwardStream",n),d=[];if(200!==(null==a?void 0:a.code))throw"stop"!==e&&(null==i||i.forEach((e=>{d.push({dst_room_id:e.roomId,result:`server error ${null==a?void 0:a.code}`})})),this._roomConf.report("rtc_forward_stream",{type:"end",dst_rooms:JSON.stringify(d),event_session_id:s})),new SDKError(ErrorCode.UNEXPECTED_ERROR,`server side internal error, error code: ${a}`);return"stop"!==e&&(null==(r=a.forwardStreamResults)||r.forEach((e=>{d.push({dst_room_id:e.dstRoomId,result:"dst room lost"})})),null==(o=a.forwardStreamResults)||o.forEach((e=>{const t=d.find((t=>t.dst_room_id===e.dstRoomId));t&&(200===e.code?"update"===e.forwardStreamType?t.result="update":t.result="success":t.result=`server error ${e.code}`)})),this._roomConf.report("rtc_forward_stream",{type:"end",dst_rooms:JSON.stringify(d),event_session_id:s})),a.forwardStreamResults}}__decorateClass$9([checkRoomState],ForwardStreamManager.prototype,"startForwardStream2Rooms",1),__decorateClass$9([checkRoomState],ForwardStreamManager.prototype,"updateForwardStream2Rooms",1),__decorateClass$9([checkRoomState],ForwardStreamManager.prototype,"stopForwardStream2Rooms",1),__decorateClass$9([checkRoomState],ForwardStreamManager.prototype,"pauseForwardStream2AllRooms",1),__decorateClass$9([checkRoomState],ForwardStreamManager.prototype,"resumeForwardStream2AllRooms",1);const simulcastFormats=[{maxLayers:3,totalPixels:2073600},{maxLayers:3,totalPixels:921600},{maxLayers:3,totalPixels:518400},{maxLayers:2,totalPixels:230400},{maxLayers:2,totalPixels:129600},{maxLayers:1,totalPixels:57600},{maxLayers:1,totalPixels:0}],getSimulcastLayers=(e,t)=>{const i=simulcastFormats.findIndex((i=>e*t>=i.totalPixels)),r=e*t;if(0===i)return simulcastFormats[i].maxLayers;const o=simulcastFormats[i-1].totalPixels;return(o-r)/(o-simulcastFormats[i].totalPixels)<.1?simulcastFormats[i-1].maxLayers:simulcastFormats[i].maxLayers};function calculateKbps(e,t,i){var r;const o=e?null==(r=i.find((t=>t.rid===e)))?void 0:r.maxkbps:i[0].maxkbps;return Math.min(o??Number.POSITIVE_INFINITY,t)}const getSubLayerByVideoConfig=(e,t)=>{var i,r;let o=0,s=-1;const{videoDescriptions:n,subVideoDescriptions:a}=(null==t?void 0:t.attributes)||{},d=Array.isArray(a)?a:n;let c=-1;const l=e.width*e.height;for(let e=0;e<(null==d?void 0:d.length);e++)if(l>=(null==(i=d[e])?void 0:i.width)*(null==(r=d[e])?void 0:r.height)){c=e;break}let u=d[0];if(-1===c)c=d.length-1,u=d[c];else if(0!==c){const e=d[c-1].width*d[c-1].height,t=(e-l)/(e-d[c].width*d[c].height);u=t<.1?d[c-1]:d[c],c=t<.1?c-1:c}return s=(null==u?void 0:u.sub_index)??-1,o=(null==u?void 0:u.video_index)??c,{spatialLayer:o,spatialSubLayer:s}},videoCaptureConf2EncodeConf=e=>({width:constraints2number(e.width),height:constraints2number(e.height),frameRate:constraints2number(e.frameRate),maxKbps:e.maxKbps}),getResolution=({width:e,height:t})=>constraints2number(e)*constraints2number(t),checkVideoConfigQuotient=(e,t)=>{const i=constraints2number(e.width)/constraints2number(t.width)||1,r=constraints2number(e.height)/constraints2number(t.height)||1;Math.floor(i)===i&&Math.floor(r)===r||warnDevelopers("setLocalSimulcastMode: The resolution setting needs to be an integer multiple")};class AudioProfileManager{constructor(e){__publicField(this,"_roomId"),__publicField(this,"_constraints",{}),__publicField(this,"_profile"),__publicField(this,"_customMaxBitrate",0),this._appId=e}setRoomId(e){this._roomId=e}setAudioProfile(e){this._profile=e,this._customMaxBitrate=0}get customMaxBitrate(){return this._customMaxBitrate}setCustomMaxBitrate(e){const{audio_encode:t}=sdkCache.getEngineWebConfig(this._appId,this._roomId||"");this._customMaxBitrate=(null==t?void 0:t.bitrate)?0:1e3*e}getOpusConfigStr(e=""){const{audio_encode:t}=sdkCache.getEngineWebConfig(this._appId,this._roomId||""),{sampleRate:i,channelCount:r}=this.getConstraints(),o="number"==typeof i?i:null==i?void 0:i.exact,s="number"==typeof r?r:null==r?void 0:r.exact,n={};e.split(";").forEach((e=>{const[t,i]=e.split("=");t&&i&&(n[t]=i)}));const a=(null==t?void 0:t.bitrate)||this._customMaxBitrate||this._getConfigByAudioProfile().bitrate;a&&(n.maxaveragebitrate=a);const d=(null==t?void 0:t.enc_sample_rate)||o;d&&(n["sprop-maxcapturerate"]=d);const c=(null==t?void 0:t.playback_rate)||o;return c&&(n.maxplaybackrate=c),(s&&s>1||(null==t?void 0:t.stereo))&&(n["sprop-stereo"]=1,n.stereo=1),(null==t?void 0:t.dtx)&&(n.usedtx=1),Object.keys(n).map((e=>`${e}=${n[e]}`)).join(";")}updateConstraints(e){this._constraints={...this._constraints,...e}}getConstraints(){const e={...this._constraints},{audio_capture:t}=sdkCache.getEngineWebConfig(this._appId,this._roomId||"");isUndefined(null==t?void 0:t.sample_rate)||(e.sampleRate=t.sample_rate),isUndefined(null==t?void 0:t.channel)||(e.channelCount=t.channel),isUndefined(null==t?void 0:t.agc)||(e.autoGainControl=t.agc),isUndefined(null==t?void 0:t.ans)||(e.noiseSuppression=t.ans),isUndefined(null==t?void 0:t.aec)||(e.echoCancellation=t.aec);const{sampleRate:i,channel:r}=this._getConfigByAudioProfile();return isUndefined(e.sampleRate)&&!isUndefined(i)&&(e.sampleRate=i),isUndefined(e.channelCount)&&!isUndefined(r)&&(e.channelCount=r),e}_getConfigByAudioProfile(){const e={};switch(this._profile){case AudioProfileType.fluent:e.sampleRate=16e3,e.bitrate=24e3;break;case AudioProfileType.standard:e.sampleRate=48e3,e.bitrate=48e3;break;case AudioProfileType.hd:e.sampleRate=48e3,e.bitrate=128e3,e.channel=2;break;case AudioProfileType.standardStereo:e.sampleRate=48e3,e.bitrate=8e4,e.channel=2;break;case AudioProfileType.hdMono:e.sampleRate=48e3,e.bitrate=128e3}return e}}const defaultConfig={start_interval:100,multiplier:2,max_interval:3e4};class RetryLimiter{constructor(){__publicField(this,"_times",0),__publicField(this,"_config",defaultConfig),__publicField(this,"initTs",getServerNow())}getRetryDelay(){return Math.min(this._config.max_interval,Math.pow(this._config.multiplier,this._times++)*this._config.start_interval)}setConfig(e){this._config=e}reset(){this._times=0}}class DecisionConfig{constructor(e){__publicField(this,"_logger"),__publicField(this,"_monitor"),this._ctx=e;const t=sdkCache.getServerConfig(this._ctx.appId);this._logger=new Logger$1("DecisionConfig",1,this._ctx.id),this._monitor=getMonitor(this._ctx.id),setTimeout((()=>{this.updateConfig(t,!0)}),0)}updateConfig(e,t){!t&&sdkCache.setServerConfig(this._ctx.appId,e),e.rts_report&&RTSMsgReportor.setConfig(e.rts_report),this._ctx.joinRoomConfig.setServerConfig(e.web_join_room),this._setRtsConfig(e.rts_config),this._setRtsQpsConfig(e.rts_qps),this._preConnect(e),this._getServerConfigExecutor(e,t)}_setRtsConfig(e){(null==e?void 0:e.rts_mode)&&e.rts_mode!==this._ctx.rtsMode&&(this._logger.print("_setRtsConfig","setRtsMode to %o",e.rts_mode),this._ctx.setRTSMode(e.rts_mode===RTS_MODE.NORMAL_MODE?RTS_MODE.NORMAL_MODE:RTS_MODE.LIMIT_MODE))}_setRtsQpsConfig(e){this._logger.print("_setRtsQpsConfig",JSON.stringify(e)),this._ctx.setRtsQpsConf(e),Object.keys(this._ctx.rtsLimiter).length>0&&reportRtcInvokeStatus(this._ctx.id,"setRtsQpsConf",JSON.stringify(e))}_getServerConfigExecutor(e,t){var i,r,o,s,n,a,d,c,l,u,_,h,p;const{upload_console_length_cut:m,upload_report_limit:S}=(null==e?void 0:e.web_rtc_config)||{};if(CoreConfig.setParameter("UPLOAD_CONSOLE_ON",!!(null==(i=null==e?void 0:e.web_rtc_config)?void 0:i.upload_console_on)),m&&CoreConfig.setParameter("UPLOAD_CONSOLE_LENGTH_CUT",m),S&&CoreConfig.setParameter("UPLOAD_REPORT_LIMIT",S),CoreConfig.setParameter("ENABLE_REPORT_IDB_BUFFER",!!(null==(r=null==e?void 0:e.web_rtc_config)?void 0:r.enable_report_idb_buffer)),!1===(null==(o=null==e?void 0:e.web_rtc_config)?void 0:o.sdk_codec_negotiation)&&setParameter("SDK_CODEC_NEGOTIATION",!1),void 0!==(null==(s=null==e?void 0:e.web_rtc_config)?void 0:s.ainr_enable_dump)&&setParameter("AINR_ENABLE_DUMP",e.web_rtc_config.ainr_enable_dump),void 0!==(null==(n=null==e?void 0:e.web_rtc_config)?void 0:n.ainr_overload_threshold)&&setParameter("AINR_OVERLOAD_THRESHOLD",e.web_rtc_config.ainr_overload_threshold),void 0!==(null==(a=null==e?void 0:e.web_rtc_config)?void 0:a.ainr_urls))try{setParameter("AINR_URLS",JSON.parse(e.web_rtc_config.ainr_urls))}catch(e){this._logger.warn("_getServerConfigExecutor","parse AINR_URLS error %o",e)}void 0!==(null==(d=null==e?void 0:e.web_rtc_config)?void 0:d.ainr_cache_time)&&setParameter("AINR_CACHE_TIME",e.web_rtc_config.ainr_cache_time),void 0!==(null==(c=null==e?void 0:e.web_rtc_config)?void 0:c.ainr_dump_time)&&setParameter("AINR_DUMP_TIME",e.web_rtc_config.ainr_dump_time),(null==(l=null==e?void 0:e.web_rtc_config)?void 0:l.web_pc_killswitch)&&(this._logger.print("web_pc_killswitch update: ",JSON.stringify(e.web_rtc_config.web_pc_killswitch)),this._ctx.pcKillSwitch={...this._ctx.pcKillSwitch,...e.web_rtc_config.web_pc_killswitch}),"boolean"==typeof(null==(u=null==e?void 0:e.web_rtc_config)?void 0:u.fallback)&&(!1===(null==e?void 0:e.web_rtc_config.fallback)?this._ctx.enableFallbackHandler=!1:Array.isArray(null==(_=null==e?void 0:e.web_rtc_config)?void 0:_.fallback_ua_reg)?this._ctx.enableFallbackHandler=null==e?void 0:e.web_rtc_config.fallback_ua_reg.every((e=>"string"==typeof e&&new RegExp(e).test(navigator.userAgent))):this._ctx.enableFallbackHandler=!1),"boolean"==typeof(null==(h=null==e?void 0:e.web_rtc_config)?void 0:h.standard)&&(!1===(null==e?void 0:e.web_rtc_config.standard)?this._ctx.enableStandardHandler=!1:Array.isArray(null==(p=null==e?void 0:e.web_rtc_config)?void 0:p.standard_ua_reg)?this._ctx.enableStandardHandler=null==e?void 0:e.web_rtc_config.standard_ua_reg.every((e=>"string"==typeof e&&new RegExp(e).test(navigator.userAgent))):this._ctx.enableStandardHandler=!1)}_preConnect(e){var t,i;let r=getParameter("PRE_ICE");"boolean"==typeof(null==(t=null==e?void 0:e.web_rtc_config)?void 0:t.pre_ice)&&(r=e.web_rtc_config.pre_ice),r&&(this._logger.print("preConnect","start pre ice connection."),this._ctx.signalingManager.connect(),null==(i=this._monitor)||i.set({pre_connection:!0}),this._ctx.isPreConnection=!0)}}class IceConfigRequestManager{constructor(e){__publicField(this,"_reconnectTimer"),__publicField(this,"_retryFunc"),__publicField(this,"_abortControllers",[]),__publicField(this,"_monitor"),__publicField(this,"logger"),__publicField(this,"_groupConfigId",genUuid()),__publicField(this,"_retryLimiter",new RetryLimiter),__publicField(this,"_timer"),__publicField(this,"_destroyed",!1),__publicField(this,"_onlineListener",(()=>{this._reconnectTimer&&this._retryFunc&&(clearTimeout(this._reconnectTimer),this._retryFunc())})),__publicField(this,"_decisionConfig"),this._ctx=e,this._monitor=getMonitor(e.id),this.logger=new Logger$1("ICERequest",4,e.id),this._decisionConfig=new DecisionConfig(e),window.addEventListener("online",this._onlineListener)}async getICENode(e){let t;this.logger.info("getICENode","invoke");try{if(t=await this._getAccessWithRetry(e),0===t.length)throw new Error("server return empty nodes.")}catch(e){throw this._reportRtcInvokeStatus("es.join.getNodeFailed",e),new SDKError(ErrorCode.ICE_SERVER_WRONG,`get ICE config failed: ${e.message}`,e)}return this.logger.success("getICENode","success"),this._reportRtcInvokeStatus("es.join.getNodeSuccess",t),t}_getAccessWithRetry(e,t=0){return 0!==t&&this.logger.info("_getAccessWithRetry()","invoke feedbackInfo: %o, 201count: %o",e,t),new Promise(((i,r)=>{this._getAccessNode(e).then((e=>{this._retryLimiter.reset(),i(e)})).catch((o=>{if(this._destroyed)return;if(Array.isArray(o)&&o.length>0){if(o.findIndex((e=>400<=e.code&&e.code<500))>-1)return this._retryLimiter.reset(),r(new Error("HTTP request failed(4xx)"));if(o.every((e=>{var t;return 201===e.code||201===(null==(t=e.error)?void 0:t.code)}))&&t++,3===t)return this._retryLimiter.reset(),r(new Error("HTTP request failed(201)"))}const s=this._retryLimiter.getRetryDelay();this.logger.warn("_getAccessWithRetry()",`_getAccessWithRetry error, will retry after ${s}ms`,o),this._retryFunc=()=>{this._getAccessWithRetry(e,t).then(i).catch(r)},this._reconnectTimer=self.setTimeout(this._retryFunc,s)}))}))}async _getAccessNode(e){return new Promise(((t,i)=>{const r=sdkCache.getAccessNode(this._ctx.appId);if(r){const i=(Array.isArray(r)?r:[r]).map((e=>(e.cache_status=!0,e)));this.logger.info("getAccessNode","use cache node."),t(i),this._timer=setTimeout((()=>{this._getAccessNodeFromServer(e).catch((()=>{})),this._reportRtcInvokeStatus("es.R.node.cache",r),delete this._timer}),0)}else this._getAccessNodeFromServer(e).then(t).catch(i)}))}async _getAccessNodeFromServer(e){const{urls:t,needFallback:i}=this._getAccessUrls();return this.getICEConfigFromServer(t,e).then((e=>{const{nodes:t,decisionConfig:i}=e;return!this._ctx.useCloudProxy&&(null==t?void 0:t.length)>0&&sdkCache.setAccessNode(this._ctx.appId,t,e.ttl||11200),i&&this._decisionConfig.updateConfig(i,!1),e.dispatchDomains&&!this._ctx.useCloudProxy&&sdkCache.setAccessUrls(e.dispatchDomains),t})).catch((t=>{if(i)return this._reportRtcInvokeStatus("es.R.req.fallback",""),sdkCache.clearAccessUrls(),this._getAccessNodeFromServer(e);throw t}))}_getAccessUrls(){let e=sdkCache.getAccessUrls()||[],t=!0;return 0!==e.length?this._reportRtcInvokeStatus("es.R.req.cache.urls",e):(t=!1,e=Config2.ICE_CONFIG_REQUEST_URLS,0!==e.length?this._reportRtcInvokeStatus("es.R.req.external.urls",e):(e=Config2.ICE_CONFIG_REQUEST_URLS_INTERNAL,this._reportRtcInvokeStatus("es.R.req.internal.urls",e))),{urls:e,needFallback:t}}async getICEConfigFromServer(e,t){var i,r;const o={appID:this._ctx.appId,deviceID:sdkCache.getDeviceId(),os:"web",sdkVersion:Config2.VERSION,isOversea:Config2.OVERSEA,expectedAddr:getParameter("EXPECTED_ADDR"),productPlatform:"VolcEngine",enableCloudProxy:this._ctx.useCloudProxy,expectedIDC:this._ctx.expectedIDC,decisionKeys:["rts_report","web_join_room","web_rtc_config","rts_qps","rts_config"],accessParams:JSON.stringify({requireICEUfragV2:!0}),userAgent:null==navigator?void 0:navigator.userAgent};t&&(o.feedbackInfo=t,"ICE_FAILED"!==(null==(r=null==(i=t[0])?void 0:i.feedbackReason)?void 0:r.type)&&delete o.expectedAddr),"AREA_CODE_US_OPCO"===getParameter("AREA_CODE")&&(o.mediaArea=JSON.stringify([{AreaList:["GEO:US_OPCO"],Attribute:"include"}]),o.accessArea=JSON.stringify([{AreaList:["GEO:US_OPCO"],Attribute:"include"}]));const s=e.map((e=>this._httpRequest(e,o)));return promiseAny(s)}async _httpRequest(e,t){var i,r,o,s;const n=genUuid();t.connectSessionID=n;const a=Date.now();null==(i=this._monitor)||i.report("rtc_get_access",{error_code:0,message:JSON.stringify(t),elapse:0,type:"request",host:e,config_id:n,group_config_id:this._groupConfigId});const d=new AbortController;let c;this._abortControllers.push(d);try{try{c=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},mode:"cors",body:JSON.stringify(t),signal:d.signal})}catch(e){throw isNativeFunction(fetch)||null==(r=this._monitor)||r.report("rtc_error",{error_code:RtcErrorCode.Fetch_MODIFY,message:"get access failed, possibly due to modifying the browser's Fetch API."},{origin_error:e}),e}if(this._abortControllers=this._abortControllers.filter((e=>e!==d)),200!==c.status)throw{message:c.statusText,code:c.status};const i=await c.json();if(200!==i.code)throw i;return null==(o=this._monitor)||o.report("rtc_get_access",{error_code:200,message:JSON.stringify(i),elapse:Date.now()-a,type:"response",host:e,config_id:n,group_config_id:this._groupConfigId}),i}catch(t){throw null==(s=this._monitor)||s.report("rtc_get_access",{error_code:Number((null==t?void 0:t.code)||(null==t?void 0:t.server_code)),message:null==t?void 0:t.message,elapse:Date.now()-a,type:"response",host:e,config_id:n,group_config_id:this._groupConfigId},{error:JSON.stringify(t)}),t}}destroy(){this._destroyed=!0,window.removeEventListener("online",this._onlineListener),this._abortControllers.forEach((e=>e.abort("engine destroy"))),this._reconnectTimer&&(window.clearTimeout(this._reconnectTimer),delete this._reconnectTimer),this._timer&&(window.clearTimeout(this._timer),delete this._timer)}_reportRtcInvokeStatus(e,t){var i;null==(i=this._monitor)||i.report("rtc_invoke_status",{sdk_api_name:e,message:t,error_code:0,stream_id:"",elapse:0,group_config_id:this._groupConfigId})}}var lib={},parser$1={},grammar$3={exports:{}},grammar$2=grammar$3.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return null!=e.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),t+=null!=e["network-id"]?" network-id %d":"%v",t+=null!=e["network-cost"]?" network-cost %d":"%v"}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return null!=e.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",t+=null!=e.rateNumerator?" rate=%s":"",t+=null!=e.rateDenominator?"/%s":""}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(grammar$2).forEach((function(e){grammar$2[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))}));var grammarExports=grammar$3.exports;!function(e){var t=function(e){return String(Number(e))===e?Number(e):e},i=function(e,i,r){var o=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:o&&!i[e.name]&&(i[e.name]={});var s=e.push?{}:o?i[e.name]:i;!function(e,i,r,o){if(o&&!r)i[o]=t(e[1]);else for(var s=0;s<r.length;s+=1)null!=e[s+1]&&(i[r[s]]=t(e[s+1]))}(r.match(e.reg),s,e.names,e.name),e.push&&i[e.push].push(s)},r=grammarExports,o=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},s=[],n=t;return e.split(/(\r\n|\r|\n)/).filter(o).forEach((function(e){var t=e[0],o=e.slice(2);"m"===t&&(s.push({rtp:[],fmtp:[]}),n=s[s.length-1]);for(var a=0;a<(r[t]||[]).length;a+=1){var d=r[t][a];if(d.reg.test(o))return i(d,n,o)}})),t.media=s,t};var s=function(e,i){var r=i.split(/=(.+)/,2);return 2===r.length?e[r[0]]=t(r[1]):1===r.length&&i.length>1&&(e[r[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(s,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var i=[],r=e.split(" ").map(t),o=0;o<r.length;o+=3)i.push({component:r[o],ip:r[o+1],port:r[o+2]});return i},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(s,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var i,r=!1;return"~"!==e[0]?i=t(e):(i=t(e.substring(1,e.length)),r=!0),{scid:i,paused:r}}))}))}}(parser$1);var grammar$1=grammarExports,formatRegExp=/%[sdv%]/g,format=function(e){var t=1,i=arguments,r=i.length;return e.replace(formatRegExp,(function(e){if(t>=r)return e;var o=i[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(o);case"%d":return Number(o);case"%v":return""}}))},makeLine=function(e,t,i){var r=[e+"="+(t.format instanceof Function?t.format(t.push?i:i[t.name]):t.format)];if(t.names)for(var o=0;o<t.names.length;o+=1){var s=t.names[o];t.name?r.push(i[t.name][s]):r.push(i[t.names[o]])}else r.push(i[t.name]);return format.apply(null,r)},defaultOuterOrder=["v","o","s","i","u","e","p","c","b","t","r","z","a"],defaultInnerOrder=["i","c","b","a"],writer$1=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var i=t.outerOrder||defaultOuterOrder,r=t.innerOrder||defaultInnerOrder,o=[];return i.forEach((function(t){grammar$1[t].forEach((function(i){i.name in e&&null!=e[i.name]?o.push(makeLine(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){o.push(makeLine(t,i,e))}))}))})),e.media.forEach((function(e){o.push(makeLine("m",grammar$1.m[0],e)),r.forEach((function(t){grammar$1[t].forEach((function(i){i.name in e&&null!=e[i.name]?o.push(makeLine(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){o.push(makeLine(t,i,e))}))}))}))})),o.join("\r\n")+"\r\n"},parser=parser$1,writer=writer$1,grammar=grammarExports;lib.grammar=grammar,lib.write=writer,lib.parse=parser.parse,lib.parseParams=parser.parseParams,lib.parseFmtpConfig=parser.parseFmtpConfig,lib.parsePayloads=parser.parsePayloads,lib.parseRemoteCandidates=parser.parseRemoteCandidates,lib.parseImageAttributes=parser.parseImageAttributes,lib.parseSimulcastStreamList=parser.parseSimulcastStreamList;const logger$3=new Logger$1("FirefoxHandler",3),SSRC_MAX=Math.pow(2,32),SSRC_MIN=1e4,clientCname="kp34Za0H+aVf862l",serverCname="o/i14u9pJrxRKAsu",generateRandomSsrc=()=>Math.floor(Math.random()*SSRC_MAX+1e4);function generateAllSsrc(e){return e>SSRC_MAX-18?(logger$3.warn("generateAllSsrc","reset start id",e),generateAllSsrc(e=e-SSRC_MAX+1e4+18)):{audio:e,audioFec:e+1,audioRtx:e+2,video:e+3,videoFec:e+4,videoRtx:e+5,next:e+18}}const generateSsrc=(e,t,i,r=serverCname)=>[{id:i,attribute:"cname",value:r},{id:i,attribute:"msid",value:`${e} ${e}-${t}`},{id:i,attribute:"mslabel",value:`${e}`},{id:i,attribute:"label",value:`${e}-${t}`}],generateSsrcs=(e,t,i={})=>{const r=t.video,o=t.videoRtx,s=t.videoFec,n=[r,o],{cname:a,flexfec:d}=i;d&&n.push(s);const c=n.reduce(((t,i)=>t.concat(generateSsrc(e,"video",i,a))),[]),l=[{semantics:"FID",ssrcs:`${r} ${o}`}];return d&&l.push({semantics:"FEC-FR",ssrcs:`${r} ${s}`}),{ssrcs:c,ssrcGroups:l}};function closeMline(e){return e.direction="inactive",e.port=0,delete e.ext,delete e.ssrcs,delete e.ssrcGroups,delete e.simulcast,delete e.simulcast_03,delete e.rids,delete e.extmapAllowMixed,delete e.msid,delete e.bundleOnly,e}const getLocalPartialSdp=(e,t,i,r=!0)=>{const o={...e,media:[]};return r&&(o.invalid=[{value:"realx-exts:rscp"}]),t&&o.media.push(cloneDeep(t)),i&&o.media.push(cloneDeep(i)),delete o.groups,delete o.msidSemantic,H265ToByteVC1(o)};function parseAnswerIceParams(e){const t={},{publicIPs:i,certFingerprint:r,iceParams:o,iceConfig:s}=e;return t.fingerprint={type:"sha-256",hash:r},t.icePwd=o.serverIcePwd,t.iceUfrag=getServerUfrag(o.serverIceUfrag),t.candidates=genCandidates(i,s),t.setup="active",t.iceOptions="renomination",t}function genCandidates(e,t){if(!Array.isArray(e))return[];let i=0;const r=2130706431,o=[];return e.forEach((e=>{const s={component:1,ip:e.ip,type:"host",generation:e.generation};e.udpPorts&&!t.tcpOnly&&e.udpPorts.forEach((e=>{o.push({...s,foundation:i++,transport:"udp",port:e,priority:r})})),e.tcpPorts&&e.tcpPorts.forEach((e=>{o.push({...s,foundation:i++,transport:"tcp",port:e,tcptype:"passive",priority:2130705431})}))})),o}const getServerUfrag=e=>{const t=(new TextEncoder).encode("PREC"),i=base64ToUint8(e),r=new Uint8Array(4);crypto.getRandomValues(r);const o=new Uint8Array(2);o[0]=0,o[1]=1;return uint8ToBase64(concatenate(Uint8Array,t,i,r,o))};var ICEConfigType=(e=>(e[e.kICEConfigTypeSrtpDtlsType=0]="kICEConfigTypeSrtpDtlsType",e[e.kICEConfigTypeRenominationType=1]="kICEConfigTypeRenominationType",e[e.kICEConfigTypeTcpType=2]="kICEConfigTypeTcpType",e[e.kICEConfigTypeMultiSendType=3]="kICEConfigTypeMultiSendType",e[e.kICEConfigTypeKcpType=4]="kICEConfigTypeKcpType",e[e.kICEConfigTypeSrtpSdesType=5]="kICEConfigTypeSrtpSdesType",e))(ICEConfigType||{});function getServerUfragV2({random:e,serverUfrag:t,serverPwd:i,clientPwd:r,options:o}){let s=0;const n=(new TextEncoder).encode("WPRE");s+=4,e||(e=new Uint8Array(4),crypto.getRandomValues(e)),s+=4;const a=base64ToUint8(t);s+=1,s+=a.byteLength;const d=aesCtrEncrypt(base64ToUint8(r),base64ToUint8(i).subarray(0,16),base64ToUint8(t).subarray(0,16));s+=1,s+=d.byteLength;const c=new Uint8Array(Object.keys(o).reduce(((e,t)=>{const i=Number(t);return e.push(i),e.push(o[i]?1:0),e}),[]));s+=c.byteLength;let l=concatenate(Uint8Array,n,e,[a.byteLength],a,[d.byteLength],d,c);l.byteLength%3!=0&&(l=concatenate(Uint8Array,l,new Uint8Array(3-l.byteLength%3).fill(255)));return[uint8ToBase64(l),uint8ToBase64(concatenate(Uint8Array,e,a.subarray(0,20)))]}const setAudioCodecPreferences=(e,t)=>{if(!Array.isArray(e.fmtp)||!Array.isArray(e.rtp))return;for(let i=0;i<e.rtp.length;i++){if(e.rtp[i].codec.toUpperCase()===t.toUpperCase()){e.rtp.unshift(e.rtp.splice(i,1)[0]);break}}const i=[];e.rtp.forEach((e=>i.push(e.payload))),e.payloads=i.join(" ")},setCodecPreferences=(e,t)=>{let i=0;if(!Array.isArray(e.fmtp)||!Array.isArray(e.rtp))return;for(const t of e.fmtp)if(t.config.includes("level-asymmetry-allowed=1")&&t.config.includes("packetization-mode=1")&&t.config.includes("profile-level-id=42e0")){i=t.payload;break}for(let r=0;r<e.rtp.length;r++){const o=e.rtp[r];if("H264"===t){if(o.payload===i){e.rtp.unshift(e.rtp.splice(r,1)[0]);break}}else if(o.codec===t){e.rtp.unshift(e.rtp.splice(r,1)[0]);break}}const r=[];e.rtp.forEach((e=>r.push(e.payload))),e.payloads=r.join(" ")},cropSdpMediaSection=e=>{const t=lib.parse(e);return t.media=t.media.map((e=>{if("audio"===e.type){return cropAudioMediaSection(e,t)}return cropVideoMediaSection(e,["H264","VP8","ByteVC1"],t)})),lib.write(t)},pushRRTR=e=>{e.media.forEach((e=>{"audio"!==e.type&&"video"!==e.type||e.rtp.forEach((t=>{e.rtcpFb||(e.rtcpFb=[]),e.rtcpFb.find((e=>e.payload===t.payload&&"rrtr"===e.type))||e.rtcpFb.push({payload:t.payload,type:"rrtr"})}))}))},cropVideoMediaSection=(e,t,i,r={rrtr:!1})=>{const o={},s={};let n=-1;const a=[];return Array.isArray(e.fmtp)&&e.fmtp.forEach((({payload:e,config:t})=>{if(t.startsWith("apt=")){const i=t.slice(4);o[e]=i}else t.includes("42e0")&&t.includes("packetization-mode=1")&&(n=e)})),Array.isArray(e.rtp)&&(e.rtp=e.rtp.filter((e=>{const i=e.codec,r=e.payload;let d;switch(i){case"H264":return d=!1,t.map((e=>{"H264"===e&&r===n&&(s[r]=r,a.push(r),d=!0)})),d;case"rtx":return!!s[o[r]]&&(s[r]=r,!0);case"red":case"ulpfec":case"flexfec-03":return s[r]=r,!0;default:return d=!1,t.map((e=>{e===i&&(s[r]=r,a.push(r),d=!0)})),d}}))),Array.isArray(e.fmtp)&&(e.fmtp=e.fmtp.filter((e=>s[e.payload]))),Array.isArray(e.rtcpFb)?e.rtcpFb=e.rtcpFb.filter((e=>s[e.payload])):e.rtcpFb=[],r.rrtr&&a.forEach((t=>{var i;null==(i=e.rtcpFb)||i.push({payload:t,type:"rrtr"})})),deleteProperty(e,i),Array.isArray(e.ext)&&(e.ext=e.ext.filter((e=>{if("http://www.webrtc.org/experiments/rtp-hdrext/video-content-type"!==e.uri&&"http://www.webrtc.org/experiments/rtp-hdrext/video-timing"!==e.uri&&"http://www.webrtc.org/experiments/rtp-hdrext/color-space"!==e.uri)return e}))),"string"==typeof e.payloads&&(e.payloads=e.payloads.split(" ").filter((e=>s[e])).join(" ")),e},cropAudioMediaSection=(e,t,i={rrtr:!1})=>{const r={};if(Array.isArray(e.rtp)&&(e.rtp=e.rtp.filter((e=>{const t=e.codec,i=e.payload;return("opus"===t||"red"===t)&&(r[i]=i,!0)}))),Array.isArray(e.rtcpFb)||(e.rtcpFb=[]),i.rrtr&&Object.keys(r).forEach((t=>{var i;null==(i=e.rtcpFb)||i.push({payload:Number(t),type:"rrtr"})})),deleteProperty(e,t),"string"==typeof e.payloads){const t=[];e.payloads.split(" ").forEach((e=>{r[e]&&t.push(e)})),e.payloads=t.join(" ")}return e},deleteProperty=(e,t)=>{e.iceOptions&&delete e.iceOptions,e.icePwd&&(t.icePwd=e.icePwd,delete e.icePwd),e.iceUfrag&&(t.iceUfrag=e.iceUfrag,delete e.iceUfrag),e.fingerprint&&(t.fingerprint=e.fingerprint,delete e.fingerprint)},H265ToByteVC1=e=>vcodecTransform(e,"H265","ByteVC1"),ByteVC1ToH265=e=>vcodecTransform(e,"ByteVC1","H265"),vcodecTransform=(e,t,i)=>{const r="string"==typeof e?lib.parse(e):e;return r.media=r.media.map((e=>("video"===e.type&&(e.rtp=e.rtp.map((e=>(e.codec===t&&(e.codec=i),e)))),e))),lib.write(r)};function DCHECK(e,t,...i){const r=(new Error).stack;reportGlobalError(`[DCHECK FAILED] ${t}`,-1,{stack:r})}const encodedTransformSupported$3=isLegacyEncodedTransformSupported(),peerConnectionConfiguration={iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"};var ConnectFailCode=(e=>(e[e.DC_ERROR=0]="DC_ERROR",e[e.DC_CLOSE=1]="DC_CLOSE",e[e.ICE_FAILED=2]="ICE_FAILED",e[e.DESTROY=3]="DESTROY",e[e.TIMEOUT=4]="TIMEOUT",e))(ConnectFailCode||{});let PeerConnectionGUID=0;class PeerConnection extends EnhancedEventEmitter{constructor(e,t,i=!1){super(),__publicField(this,"uuid",(PeerConnectionGUID++).toString()),__publicField(this,"_peerConnectionId",""),__publicField(this,"audioTrack4ff"),__publicField(this,"_pc"),__publicField(this,"_dc"),__publicField(this,"_iceNode"),__publicField(this,"_initSctpEvents",!1),__publicField(this,"_monitor"),__publicField(this,"_offerIce",{}),__publicField(this,"_answerIce",{}),__publicField(this,"_offerSession"),__publicField(this,"_answerSession"),__publicField(this,"_offerMlines",[]),__publicField(this,"_answerMlines",[]),__publicField(this,"_connectReject"),__publicField(this,"_logger"),__publicField(this,"_destroyed",!1),__publicField(this,"_reportTimer"),__publicField(this,"_onLineCheckerTimer"),__publicField(this,"_clearPeerListeners"),__publicField(this,"_peerConfig"),__publicField(this,"_iceStartTs",0),__publicField(this,"_icePreStepTs",0),this._ctx=e,this._groupConnectionId=t,this._isReconnect=i,this._monitor=getMonitor(e.id),this._logger=new Logger$1(`PeerConnection_${this.uuid}`,4,e.id),this._ctx.enableFallbackHandler&&this._logger.warn("ctor","PeerConnection running in fallback mode"),this._peerConfig=genPeerConfig(e),this._pc=new RTCPeerConnection(this._peerConfig),this._pc.ontrack=e=>{var t,i;const r=null==(i=null==(t=e.streams)?void 0:t[0])?void 0:i.id;this._print("pc.ontrack",`${e.track.kind} ${e.track.id} ${r}`),"ff-stream"===r&&(this.audioTrack4ff=e.track),this.emit("ontrack",e)},this._pc.onconnectionstatechange=()=>{this._print("onconnectionstatechange",`${this._pc.connectionState}. ice -> ${this._pc.iceConnectionState}`),"failed"!==this._pc.iceConnectionState&&"closed"!==this._pc.iceConnectionState&&"failed"!==this._pc.connectionState?"disconnected"!==this._pc.connectionState?"connecting"!==this._pc.connectionState&&"connected"!==this._pc.connectionState||clearInterval(this._onLineCheckerTimer):navigator.onLine?this.emit("disconnect",InternalReconnectReason.ICE_FAILED):this._onLineCheckerTimer=setInterval((()=>{navigator.onLine&&(clearInterval(this._onLineCheckerTimer),this.emit("disconnect",InternalReconnectReason.ICE_FAILED))}),1e3):this.emit("disconnect",InternalReconnectReason.ICE_FAILED)},this._pc.oniceconnectionstatechange=()=>{const e=this._pc.iceConnectionState;this._report("rtc_pre_ice_state",{message:e,ice_state:e.toUpperCase()}),this.emit("ice_state",e)}}static checkSupported(){if(!RTCPeerConnection)throw new SDKError(ErrorCode.NOT_SUPPORTED,"missing RTCPeerConnection API.");["addTransceiver","createDataChannel","createOffer","setLocalDescription","setRemoteDescription"].forEach((e=>{var t;if(!(null==(t=null==RTCPeerConnection?void 0:RTCPeerConnection.prototype)?void 0:t[e]))throw new SDKError(ErrorCode.NOT_SUPPORTED,`missing peer.${e} API.`)}))}getOriginRTCPeerConnection(){return this._pc}getConnectionId(){return this._peerConnectionId}getGroupConnectionId(){return this._groupConnectionId}getIceConnectionState(){return this._pc.iceConnectionState}async createOfferSdp(){let{sdp:e}=await this._pc.createOffer();return e}async startIceConnect(e){var t,i;if(this._ctx.enableStandardHandler&&!this._ctx.enableFallbackHandler)return this.startIceConnectStandard(e);this._print("connect","invoke. %o",e),this._iceNode=e;const r=this._pc.createDataChannel("signaling",{negotiated:!0,id:100});r.binaryType="arraybuffer",this._dc=r;const{offerIce:o,answerIce:s}=this._genIceInfo(e);this._offerIce=o,this._answerIce=s,isFirefox&&firefoxVersion<138&&(this._pc.addTransceiver("audio",{direction:"recvonly"}),this._pc.addTransceiver("video",{direction:"recvonly"}));const n=await this.createOfferSdp();if(!n)throw new SDKError(ErrorCode.NOT_SUPPORTED,"create offer sdp failed.");const a=lib.parse(n);this._peerConnectionId=s.iceUfrag||"";const d=!o.iceUfrag&&!o.icePwd;if(d){const r="renomination"===(null==(t=a.media[0])?void 0:t.iceOptions)||!this._ctx.enableFallbackHandler&&this._ctx.pcKillSwitch.sld_iceoption_renomination;r||(delete o.iceOptions,delete s.iceOptions),delete o.iceUfrag,delete o.icePwd;const[n,d]=getServerUfragV2({serverUfrag:e.iceParams.serverIceUfrag,serverPwd:e.iceParams.serverIcePwd,clientPwd:null==(i=a.media[0])?void 0:i.icePwd,options:{[ICEConfigType.kICEConfigTypeSrtpDtlsType]:!0,[ICEConfigType.kICEConfigTypeRenominationType]:r}});this._peerConnectionId=d,s.iceUfrag=n,this._logger.info("use serverUfrag v2",JSON.stringify({dtls:!0,renomination:r}))}this.reportRtcPreIce("ice_start");const[c]=a.media;if(this._offerIce.fingerprint=a.fingerprint||c.fingerprint,isFirefox||this._ctx.enableFallbackHandler){a.media=a.media.map((e=>{var t,i,r,o;const s={...e,...this._offerIce};return"video"===s.type&&(isTransportCCSupport?(s.ext=null==(t=s.ext)?void 0:t.filter((e=>-1===e.uri.indexOf("abs-send-time"))),s.rtcpFb=null==(i=s.rtcpFb)?void 0:i.filter((e=>"goog-remb"!==e.type))):(s.rtcpFb=null==(r=s.rtcpFb)?void 0:r.filter((e=>"transport-cc"!==e.type)),s.ext=null==(o=s.ext)?void 0:o.filter((e=>-1===e.uri.indexOf("transport"))))),s})),isRRTRSupported&&pushRRTR(a);const e={...a};e.fingerprint=this._answerIce.fingerprint,e.media=e.media.map((e=>(delete(e={...e,...this._answerIce}).bundleOnly,e.port=9,"application"===e.type?e.sctpmap={sctpmapNumber:5e3,app:"webrtc-datachannel",maxMessageSize:262144}:("audio"===e.type&&(e.msid="ff-stream ff-stream-audio"),e.direction="sendonly"),e))),isRRTRSupported&&pushRRTR(e),this._ctx.enableFallbackHandler?await this.setLocalDescription(n):await this.setLocalDescription(lib.write(a)),await this.setRemoteDescription(lib.write(e))}else{delete a.media,this._offerSession={...a},this._answerSession={...a},this._answerSession.fingerprint&&(this._answerSession.fingerprint=this._answerIce.fingerprint);const e=0;d&&(this._offerIce.iceUfrag=c.iceUfrag,this._offerIce.icePwd=c.icePwd),this._offerMlines=[{...c,...this._offerIce,mid:`${e}`}],this._answerMlines=[{...c,...this._answerIce,sctpmap:{sctpmapNumber:5e3,app:"webrtc-datachannel",maxMessageSize:262144},mid:`${e}`}],this.setDescription()}return this._reportTransportStats(),await new Promise(((e,t)=>{this._connectReject=t;const i=setTimeout((()=>{var e;this.reportRtcPreIce("timeout"),null==(e=this._connectReject)||e.call(this,{code:4,message:"connect timeout"}),delete this._connectReject}),8e3),o=()=>{this._print("connect","dataChannel open"),this._reportRtcInvokeStatus("es.dc.open",""),this.reportRtcPreIce("datachannel_opened"),clearTimeout(i),e(""),delete this._connectReject},s=e=>{var t,r,o,s;this._report("rtc_signaling_msg_error",{error_code:null==(t=null==e?void 0:e.error)?void 0:t.sdpLineNumber,message:null==(r=null==e?void 0:e.error)?void 0:r.errorDetail,reason:"invalid data"}),this._reportRtcInvokeStatus("es.dc.error",""),null==(s=this._connectReject)||s.call(this,{message:`dc.onerror, ${null==(o=e.error)?void 0:o.errorDetail}`,code:0}),this.emit("disconnect",InternalReconnectReason.DC_ERROR),delete this._connectReject,clearTimeout(i)},n=()=>{var e;this._reportRtcInvokeStatus("es.dc.close",""),null==(e=this._connectReject)||e.call(this,{message:"dc.onclose",code:1}),this.reportRtcPreIce("datachannel_closed"),this.emit("disconnect",InternalReconnectReason.DC_CLOSE),delete this._connectReject,clearTimeout(i)},a=()=>{"connected"===this._pc.iceConnectionState?this.reportRtcPreIce("ice_connected"):"failed"!==this._pc.iceConnectionState&&"closed"!==this._pc.iceConnectionState||this.reportRtcPreIce("ice_failed")},d=()=>{var e;"failed"!==this._pc.iceConnectionState&&"closed"!==this._pc.iceConnectionState&&"failed"!==this._pc.connectionState||(null==(e=this._connectReject)||e.call(this,{message:`pc.connectionstatechange -> ${this._pc.connectionState}, ice -> ${this._pc.iceConnectionState}`,code:2}),delete this._connectReject,clearTimeout(i))};r.addEventListener("open",o),r.addEventListener("error",s),r.addEventListener("close",n),this._pc.addEventListener("iceconnectionstatechange",a),this._pc.addEventListener("connectionstatechange",d),this._clearPeerListeners=()=>{r.removeEventListener("open",o),r.removeEventListener("error",s),r.removeEventListener("close",n),this._pc.removeEventListener("iceconnectionstatechange",a),this._pc.removeEventListener("connectionstatechange",d)}})),this._print("connect","dataChannel establish success"),r}async startIceConnectStandard(e){this._print("connect","standard invoke. %o",e),this._iceNode=e;const t=this._pc.createDataChannel("signaling",{negotiated:!0,id:100});t.binaryType="arraybuffer",this._dc=t;const{offerIce:i,answerIce:r}=this._genIceInfo(e);this._offerIce=i,this._answerIce=r,isFirefox&&firefoxVersion<138&&(this._pc.addTransceiver("audio",{direction:"recvonly"}),this._pc.addTransceiver("video",{direction:"recvonly"}));const o=await this.createOfferSdp();if(!o)throw new SDKError(ErrorCode.NOT_SUPPORTED,"create offer sdp failed.");const s=lib.parse(o);this._answerSession={...s},this._answerSession.fingerprint&&(this._answerSession.fingerprint=this._answerIce.fingerprint);const n=s.media.find((e=>"application"===e.type));this._peerConnectionId=r.iceUfrag||"";if(!i.iceUfrag&&!i.icePwd){const t=this._ctx.pcKillSwitch.sld_iceoption_renomination||"renomination"===(null==n?void 0:n.iceOptions);t||(delete i.iceOptions,delete r.iceOptions),delete i.iceUfrag,delete i.icePwd;const[o,s]=getServerUfragV2({serverUfrag:e.iceParams.serverIceUfrag,serverPwd:e.iceParams.serverIcePwd,clientPwd:null==n?void 0:n.icePwd,options:{[ICEConfigType.kICEConfigTypeSrtpDtlsType]:!0,[ICEConfigType.kICEConfigTypeRenominationType]:t}});this._peerConnectionId=s,r.iceUfrag=o,this._logger.info("use serverUfrag v2",JSON.stringify({dtls:!0,renomination:t}))}this.reportRtcPreIce("ice_start"),this._offerIce.fingerprint=s.fingerprint||n.fingerprint;const a={...s};return a.fingerprint=this._answerIce.fingerprint,a.media=a.media.map((e=>{var t,i,r,o;return"application"===(e={...e,...this._answerIce}).type&&(e.sctpmap={sctpmapNumber:5e3,app:"webrtc-datachannel",maxMessageSize:262144}),isFirefox&&(delete e.bundleOnly,e.port=9,"audio"===e.type?(e.msid="ff-stream ff-stream-audio",e.direction="sendonly"):"video"===e.type&&(isTransportCCSupport?(e.ext=null==(t=e.ext)?void 0:t.filter((e=>-1===e.uri.indexOf("abs-send-time"))),e.rtcpFb=null==(i=e.rtcpFb)?void 0:i.filter((e=>"goog-remb"!==e.type))):(e.rtcpFb=null==(r=e.rtcpFb)?void 0:r.filter((e=>"transport-cc"!==e.type)),e.ext=null==(o=e.ext)?void 0:o.filter((e=>-1===e.uri.indexOf("transport")))),e.direction="sendonly")),e})),"v1"===this.getIceVersion()||this._ctx.pcKillSwitch.sld_iceoption_renomination?(s.media=s.media.map((e=>e={...e,...this._offerIce})),await this.setLocalDescription(lib.write(s))):await this.setLocalDescription(o),await this.setRemoteDescription(lib.write(a)),this._reportTransportStats(),await new Promise(((e,i)=>{this._connectReject=i;const r=setTimeout((()=>{var e;this.reportRtcPreIce("timeout"),null==(e=this._connectReject)||e.call(this,{code:4,message:"connect timeout"}),delete this._connectReject}),8e3),o=()=>{this._print("connect","dataChannel open"),this._reportRtcInvokeStatus("es.dc.open",""),this.reportRtcPreIce("datachannel_opened"),clearTimeout(r),e(""),delete this._connectReject},s=e=>{var t,i,o,s;this._report("rtc_signaling_msg_error",{error_code:null==(t=null==e?void 0:e.error)?void 0:t.sdpLineNumber,message:null==(i=null==e?void 0:e.error)?void 0:i.errorDetail,reason:"invalid data"}),this._reportRtcInvokeStatus("es.dc.error",""),null==(s=this._connectReject)||s.call(this,{message:`dc.onerror, ${null==(o=e.error)?void 0:o.errorDetail}`,code:0}),this.emit("disconnect",InternalReconnectReason.DC_ERROR),delete this._connectReject,clearTimeout(r)},n=()=>{var e;this._reportRtcInvokeStatus("es.dc.close",""),null==(e=this._connectReject)||e.call(this,{message:"dc.onclose",code:1}),this.reportRtcPreIce("datachannel_closed"),this.emit("disconnect",InternalReconnectReason.DC_CLOSE),delete this._connectReject,clearTimeout(r)},a=()=>{"connected"===this._pc.iceConnectionState?this.reportRtcPreIce("ice_connected"):"failed"!==this._pc.iceConnectionState&&"closed"!==this._pc.iceConnectionState||this.reportRtcPreIce("ice_failed")},d=()=>{var e;"failed"!==this._pc.iceConnectionState&&"closed"!==this._pc.iceConnectionState&&"failed"!==this._pc.connectionState||(null==(e=this._connectReject)||e.call(this,{message:`pc.connectionstatechange -> ${this._pc.connectionState}, ice -> ${this._pc.iceConnectionState}`,code:2}),delete this._connectReject,clearTimeout(r))};t.addEventListener("open",o),t.addEventListener("error",s),t.addEventListener("close",n),this._pc.addEventListener("iceconnectionstatechange",a),this._pc.addEventListener("connectionstatechange",d),this._clearPeerListeners=()=>{t.removeEventListener("open",o),t.removeEventListener("error",s),t.removeEventListener("close",n),this._pc.removeEventListener("iceconnectionstatechange",a),this._pc.removeEventListener("connectionstatechange",d)}})),this._print("connect","dataChannel establish success"),t}async setDescription(e){this._print("setDescription","invoke."),this._offerSession.media=this._offerMlines,this._answerSession.media=this._answerMlines;const t=[];this._offerMlines.forEach((e=>{"inactive"!==e.direction&&e.mid&&t.push(e.mid)})),this._offerSession.groups&&this._answerSession.groups&&(this._offerSession.groups[0].mids=t.join(" "),this._answerSession.groups[0].mids=t.join(" "));const i=getServerNow();e&&this._report("rtc_begin_create_offer",{direction:"local"===e.streamUserId?"up":"down",stream_id:e.streamId,stream_user_id:e.streamUserId,pc_session_id:this._peerConnectionId,vendor_mode:0}),e&&this._report("rtc_create_offer",{error_code:0,direction:"local"===e.streamUserId?"up":"down",stream_id:e.streamId,stream_user_id:e.streamUserId,elapse:getServerNow()-i}),await this.setLocalDescription(lib.write(this._offerSession),e),await this.setRemoteDescription(lib.write(this._answerSession),e)}async setLocalDescription(e,t){var i;const r=getServerNow();try{if(await this._pc.setLocalDescription({type:"offer",sdp:e}),this._report("rtc_set_description",{error_code:0,message:e,is_local:"1",direction:"local"===(null==t?void 0:t.streamUserId)?"up":"down",stream_id:(null==t?void 0:t.streamId)||"",stream_user_id:(null==t?void 0:t.streamUserId)||"",elapse:getServerNow()-r},{type:"offer"}),!this._initSctpEvents){this._initSctpEvents=!0;const e=null==(i=this._pc)?void 0:i.sctp;e&&(e.onstatechange=()=>{this._reportRtcInvokeStatus("sctp",`sctp state change TO: ${e.state}`)},e.transport&&(e.transport.onstatechange=()=>{var t;this._reportRtcInvokeStatus("dtls",`dtls state change TO: ${null==(t=null==e?void 0:e.transport)?void 0:t.state}`)}))}}catch(i){throw console.error("setLocal",i),this._report("rtc_set_description",{error_code:-1,message:i.message+e,is_local:"1",direction:"local"===(null==t?void 0:t.streamUserId)?"up":"down",stream_id:"",stream_user_id:"",elapse:getServerNow()-r},{type:"offer"}),i}}async setRemoteDescription(e,t){const i=getServerNow();try{e=ByteVC1ToH265(e),await this._pc.setRemoteDescription({type:"answer",sdp:e}),this._report("rtc_set_description",{error_code:0,message:e,is_local:"0",direction:"local"===(null==t?void 0:t.streamUserId)?"up":"down",stream_id:(null==t?void 0:t.streamId)||"",stream_user_id:(null==t?void 0:t.streamUserId)||"",elapse:getServerNow()-i},{type:"answer"})}catch(r){throw console.error("setRemote",r),this._report("rtc_set_description",{error_code:-1,message:r.message+e,is_local:"0",direction:"local"===(null==t?void 0:t.streamUserId)?"up":"down",stream_id:(null==t?void 0:t.streamId)||"",stream_user_id:(null==t?void 0:t.streamUserId)||"",elapse:getServerNow()-i},{type:"answer"}),r}}closeIceConnect(){var e,t,i,r;null==(e=this._connectReject)||e.call(this,{code:3,message:"invoke destroy()"}),delete this._connectReject,null==(t=this._pc)||t.close(),null==(i=this._dc)||i.close(),delete this._dc,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,clearPeerCache(this._pc),null==(r=this._clearPeerListeners)||r.call(this),delete this._clearPeerListeners}reportRtcPreIce(e){var t;const i=getServerNow();"ice_start"===e&&(this._iceStartTs=i,this._icePreStepTs=i),this._report("rtc_pre_ice",{connect_event:e,message:e,elapse:i-this._icePreStepTs,total_elapse:i-this._iceStartTs,cache_status:!!(null==(t=this._iceNode)?void 0:t.cache_status),is_reconnect:this._isReconnect}),this._icePreStepTs=i}getStatsWithLowFrequency(e,t,i){return getStats$1(this._pc,e,t,i)}getIceVersion(){var e,t;return(null==(e=this._iceNode)?void 0:e.iceParams.clientIceUfrag)||(null==(t=this._iceNode)?void 0:t.iceParams.clientIcePwd)?"v1":"v2"}createAnswerSdp(e,t){DCHECK(this._answerSession,"_answerSession should be existed");const i={...this._answerSession};i.media=e,i.groups=t;return lib.write(i)}destroy(){this._print("destroy",this._peerConnectionId),super.removeAllListeners(),this.closeIceConnect(),this._destroyed=!0,this._reportTimer&&(clearTimeout(this._reportTimer),delete this._reportTimer),this._onLineCheckerTimer&&(clearInterval(this._onLineCheckerTimer),delete this._onLineCheckerTimer),delete this._pc}_genIceInfo(e){var t,i;return{offerIce:{iceUfrag:null==(t=e.iceParams)?void 0:t.clientIceUfrag,icePwd:null==(i=e.iceParams)?void 0:i.clientIcePwd,iceOptions:"renomination"},answerIce:parseAnswerIceParams(e)}}async _reportTransportStats(){var e;const t=await this.getStatsWithLowFrequency(),i={};if(t.forEach((e=>{"transport"===e.type?(i.dtls_state=e.dtlsState,i.bytes_received=e.bytesReceived,i.bytes_sent=e.bytesSent,i.ice_state=e.iceState,i.packets_received=e.packetsReceived,i.packets_sent=e.packetsSent,i.selected_candidate_pair_changes=e.selectedCandidatePairChanges):"local-candidate"===e.type||"remote-candidate"===e.type?i.candidates_info=[...i.candidates_info||[],{id:e.id,is_remote:e.isRemote,port:e.port,protocol:e.protocol,candidate_type:e.candidateType,priority:e.priority,network_type:e.networkType,candidate_ip:e.ip}]:"candidate-pair"===e.type&&(i.candidatePairsInfo={},i.candidatePairsInfo.candidate_state=e.state,i.candidatePairsInfo.writable_state=e.writable,i.candidatePairsInfo.sent_ping_requests_total=e.requestsSent,i.candidatePairsInfo.recv_ping_requests=e.requestsReceived,i.candidatePairsInfo.sent_ping_responses=e.responsesSent,i.candidatePairsInfo.recv_ping_responses=e.responsesReceived,i.candidatePairsInfo.current_rtt=e.currentRoundTripTime,i.candidatePairsInfo.total_rtt=e.totalRoundTripTime,["localCandidateId","remoteCandidateId","bytesSent","bytesReceived","availableOutgoingBitrate","availableIncomingBitrate","bytesDiscardedOnSend","consentRequestsSent","packetsDiscardedOnSend","lastPacketReceivedTimestamp","lastPacketSentTimestamp"].forEach((t=>{void 0!==e[t]&&(i.candidatePairsInfo[camel2Snake(t)]=e[t])})))})),Object.keys(i).length>0&&(null==(e=this._monitor)||e.report("rtc_transport_statistics",i)),!this._destroyed){const e="connected"===this._pc.iceConnectionState&&"connected"===this._pc.connectionState;this._reportTimer=setTimeout((()=>{this._reportTransportStats()}),e?5e3:1e3)}}_print(e,...t){this._logger.info(`${e}`,...t)}_report(e,t,i){var r,o,s;null==(s=this._monitor)||s.report(e,{...t,connection_id:this._peerConnectionId,group_connection_id:this._groupConnectionId},{...i,tcp_only:null==(r=this._iceNode)?void 0:r.iceConfig.tcpOnly,ms_addr:JSON.stringify((null==(o=this._iceNode)?void 0:o.publicIPs.map((e=>({ip:e.ip,tcp:e.tcpPorts,udp:e.udpPorts}))))||[])})}_reportRtcInvokeStatus(e,t){this._report("rtc_invoke_status",{sdk_api_name:e,message:t,error_code:0,stream_id:"",elapse:0})}}const genPeerConfig=e=>{const t={...peerConnectionConfiguration};return e.pcKillSwitch.ctor_sdpsemantics_add&&(t.sdpSemantics="unified-plan"),e.pcKillSwitch.ctor_encodedinsetablestream_add&&encodedTransformSupported$3&&!getParameter("DISABLE_ENCODED_TRANSFORM")&&(t.encodedInsertableStreams=!0),t};var InternalReconnectReason=(e=>(e.ICE_FAILED="ice failed",e.DC_ERROR="datachannel onerror",e.DC_CLOSE="datachannel onclose",e.NODE_CHANGE="recv nodeChange signaling",e.NOTIFY_RECONNECT="recv notifyReconnect signaling",e.JOIN_TIMEOUT="joinRoom timeout, retry with tcp only",e))(InternalReconnectReason||{});class ConnectionManager extends EnhancedEventEmitter{constructor(e){super(),__publicField(this,"id"),__publicField(this,"_monitor"),__publicField(this,"logger"),__publicField(this,"_getAccessManager"),__publicField(this,"_connectionPool",new Map),__publicField(this,"_curConnection"),__publicField(this,"_hasReportBrowerWarning",!1),__publicField(this,"_reconnectTimer"),__publicField(this,"_connecting",!1),__publicField(this,"_isFirstTimeConnected",!0),__publicField(this,"_feedbackNodes",[]),__publicField(this,"_preIceStartTime",-1),__publicField(this,"_tcpOnlyTimer"),__publicField(this,"_destroyed",!1),this._ctx=e,this.id=e.id,this._monitor=getMonitor(this.id),this.logger=new Logger$1("ConnectionManager",3,this.id),this.logger.info("constructor","invoke"),this._getAccessManager=new IceConfigRequestManager(e)}startup(){this.logger.info("connect","invoke");try{PeerConnection.checkSupported()}catch(e){this.asyncEmit("disconnected",e)}this._connecting||(this._onConnectStart(),Promise.resolve().then((()=>this.emit("__onGetIceConfigHook"))),this._getAccess())}async reconnectByNodeChange(e){var t,i,r,o;this.logger.info("reconnectByNodeChange","invoke %o",e);const{nodes:s,reason:n}=e;null==(t=this._monitor)||t.report("rtc_node_change",{error_code:0,message:JSON.stringify(e),reason:JSON.stringify(n)}),sdkCache.clearAccessNode(this._ctx.appId),null==(i=this._curConnection)||i.pc.reportRtcPreIce("node_change");const a=(null==(o=null==(r=this._curConnection)?void 0:r.node.publicIPs[0])?void 0:o.ip)||"";this._closeCurrentConnection(),this._clearConnectionPool(),this._clearReconnectTimer(),this._onConnectStart("recv nodeChange signaling"),Array.isArray(s)&&s.length>0?this._startIceConnect(s):this._getAccess([{feedbackIP:a,feedbackReason:{type:"NODE_CHANGED",reason:n}}])}async reconnect(e,t=!1){this.logger.info("reconnect","invoke. "+(t?"ICE over TCP":"")),this._closeCurrentConnection(),this._clearConnectionPool(),this._clearReconnectTimer(),this._onConnectStart(e),this._getAccess(void 0,t)}shotdown(){this.logger.info("destroy","invoke"),this._destroyed=!0,this.asyncEmit("disconnected",new SDKError(ErrorCode.OPERATION_CANCEL,"destroy")).then((()=>{super.removeAllListeners()})),this._clearReconnectTimer(),this._clearConnectionPool(),this._getAccessManager.destroy(),this._closeCurrentConnection()}_getAccess(e,t=!1){this._getAccessManager.getICENode(e).then((e=>{this.emit("__onGetIceSuccessHook",e),this._startIceConnect(e,t)})).catch((e=>{this.asyncEmit("disconnected",e)})).finally((()=>{this._feedbackNodes=[]}))}_startIceConnect(e,t=!1){if(this._destroyed)return;this.logger.info("_startIceConnect","invoke");const i=genUuid$1();this._preIceStartTime=getServerNow();const r=this._ctx.joinRoomConfig.useTcpJoin,o=this._ctx.joinRoomConfig.useTcpJoinDelay,s=async r=>{t&&((r=cloneDeep(r)).iceConfig.tcpOnly=!0);const o={node:r};try{const t=new PeerConnection(this._ctx,i,!this._isFirstTimeConnected);o.pc=t,this._connectionPool.set(t.uuid,o);const s=await t.startIceConnect(r),n=new DataChannelSignaling(this.id,s,{connection_id:t.getConnectionId(),group_connection_id:i});o.signaling=n,t.reportRtcPreIce("datachannel_send_ping"),await n.sendPingSignaling(),t.reportRtcPreIce("datachannel_recv_pong"),this._onConnectSuccess({node:r,pc:t,signaling:n,dc:s}),this.safeEmit("__onConnectSuccessHook",e.length)}catch(e){this._onConnectionFailed(o,e)}};this.emit("__onIceConnectStartHook"),e.forEach(s),r&&!t&&(this.logger.info("_startIceConnect",`tcp-only will try after ${o}ms`),this._tcpOnlyTimer=setTimeout((()=>{this.emit("connectWidthTcp"),e.forEach((e=>{(e=cloneDeep(e)).iceConfig.tcpOnly=!0,s(e)})),delete this._tcpOnlyTimer}),o))}_onConnectSuccess(e){var t;this.logger.info("connect","peer_%s connect success.",e.pc.uuid),this.emit("__onIceConnectSuccessHook",e),this._curConnection?(e.pc.destroy(),e.signaling.destroy(),this._connectionPool.delete(e.pc.uuid)):(this._curConnection=e,this._addConnectionHandler(e.pc),null==(t=this._monitor)||t.set({connection_id:e.pc.getConnectionId()}),this._connectionPool.delete(e.pc.uuid),this._feedbackNodes.forEach((e=>this._feedbackBySignaling(e))),this._feedbackNodes=[],this._onConnectEnded(e))}_onConnectionFailed(e,t){var i,r;this.logger.info("connect","peer_%s connect failed. %s",(null==(i=e.pc)?void 0:i.uuid)||"",t.message),this.emit("__onIceConnectFailedHook",e),t.code!==ConnectFailCode.DESTROY&&t.code!==ErrorCode.OPERATION_CANCEL&&(this._curConnection?this._feedbackBySignaling(e.node):this._feedbackNodes.push(e.node),this.logger.info("connect","remove cache node"),sdkCache.deleteAccessNode(this._ctx.appId,e.node),e.pc&&(this._connectionPool.delete(e.pc.uuid),e.pc.destroy()),null==(r=e.signaling)||r.destroy(),0!==this._connectionPool.size||this._curConnection||this._destroyed||(this.logger.error("connect","establish peerConnection failed"),this._checkBrowserUA(),getServerNow()-this._preIceStartTime<1e3?(this._clearReconnectTimer(),this._reconnectTimer=setTimeout((()=>{delete this._reconnectTimer,this._reconnectWithIceFailed(this._feedbackNodes)}),1e3)):this._reconnectWithIceFailed(this._feedbackNodes)))}_feedbackBySignaling(e){var t;null==(t=this._curConnection)||t.signaling.sendSignaling("scheduleMessage",{type:"feedback",body:{feedbackIP:e.publicIPs[0].ip,feedbackReason:{type:"ICE_FAILED",reason:{}}}})}async _reconnectWithIceFailed(e){this._onConnectStart("ice failed"),this.logger.warn("reconnect","because of ice failed"),this._getAccess(e.map((e=>({feedbackIP:e.publicIPs[0].ip,feedbackReason:{type:"ICE_FAILED",reason:{}}}))))}_checkBrowserUA(){var e;!this._hasReportBrowerWarning&&this._ctx.joinRoomConfig.isBlackBrower()&&(this._hasReportBrowerWarning=!0,null==(e=this._monitor)||e.report("rtc_error",{error_code:RtcErrorCode.BLACK_BROWSER,message:"failed to establish data-channel, and the current browser is on the browser blacklist."}))}_onConnectStart(e){var t,i;this.logger.info("_onConnectStart",`invoke, reason: ${e||"init"}`),this._connecting=!0,e?this.asyncEmit("reconnecting",e):this.asyncEmit("connecting");const r=genUuid$1();null==(t=this._monitor)||t.set({connect_session_id:r}),this._isFirstTimeConnected||null==(i=this._monitor)||i.report("rtc_reconnect",{error_code:1002,message:"peerconnection reconnecting",reconnect_id:r,reconnect_type:"peerconnection"},{reason:e})}_onConnectEnded(e){var t;this.logger.info("_onConnectEnded","invoke"),this._connecting=!1,this._isFirstTimeConnected||null==(t=this._monitor)||t.report("rtc_reconnected",{message:"peerconnection reconnected",reconnect_type:"peerconnection"}),this._isFirstTimeConnected=!1,this.asyncEmit("connected",e),e.node.iceConfig.tcpOnly&&(this.logger.info("_onConnectEnded","use tcp only"),reportRtcInvokeStatus(this._ctx.id,"connected_with_tcp_only",JSON.stringify(e.node))),this._tcpOnlyTimer&&(window.clearTimeout(this._tcpOnlyTimer),delete this._tcpOnlyTimer),this._clearConnectionPool()}_addConnectionHandler(e){e.on("disconnect",(e=>{this._closeCurrentConnection(),this._clearReconnectTimer(),navigator.onLine?this.reconnect(e):this._reconnectTimer=setTimeout((()=>this.reconnect(e)),3e3)}))}_closeCurrentConnection(){var e,t;null==(e=this._curConnection)||e.pc.destroy(),null==(t=this._curConnection)||t.signaling.destroy(),delete this._curConnection}_clearConnectionPool(){this._connectionPool.forEach(((e,t)=>{var i,r;null==(i=e.signaling)||i.destroy(),null==(r=e.pc)||r.destroy(),this._connectionPool.delete(t)}))}_clearReconnectTimer(){this._reconnectTimer&&(window.clearTimeout(this._reconnectTimer),delete this._reconnectTimer)}}var AudioMixingDualMonoMode=(e=>(e[e.AUTO=0]="AUTO",e[e.MODE_L=1]="MODE_L",e[e.MODE_R=2]="MODE_R",e[e.MODE_MIX=3]="MODE_MIX",e))(AudioMixingDualMonoMode||{}),AudioMixingType=(e=>(e[e.PLAYOUT=0]="PLAYOUT",e[e.PUBLISH=1]="PUBLISH",e[e.PLAYOUT_AND_PUBLISH=2]="PLAYOUT_AND_PUBLISH",e))(AudioMixingType||{}),AudioMixingState=(e=>(e[e.AUDIO_MIXING_STATE_PRELOADED=0]="AUDIO_MIXING_STATE_PRELOADED",e[e.AUDIO_MIXING_STATE_PLAYING=1]="AUDIO_MIXING_STATE_PLAYING",e[e.AUDIO_MIXING_STATE_PAUSED=2]="AUDIO_MIXING_STATE_PAUSED",e[e.AUDIO_MIXING_STATE_STOPPED=3]="AUDIO_MIXING_STATE_STOPPED",e[e.AUDIO_MIXING_STATE_FAILED=4]="AUDIO_MIXING_STATE_FAILED",e[e.AUDIO_MIXING_STATE_FINISHED=5]="AUDIO_MIXING_STATE_FINISHED",e[e.AUDIO_MIXING_STATE_PCM_ENABLED=6]="AUDIO_MIXING_STATE_PCM_ENABLED",e[e.AUDIO_MIXING_STATE_PCM_DISABLED=7]="AUDIO_MIXING_STATE_PCM_DISABLED",e))(AudioMixingState||{});class BasicHandler extends eventemitter3Exports.EventEmitter{constructor(e,t){super(),__publicField(this,"_context"),__publicField(this,"peerConnectionMode",0),__publicField(this,"id"),__publicField(this,"_monitor"),__publicField(this,"logger"),__publicField(this,"_nextSsrc",generateRandomSsrc()),__publicField(this,"_aSendonlyAnswerTpl"),__publicField(this,"_vSendonlyAnswerTpl"),__publicField(this,"_enableSubFlexfec",!1),__publicField(this,"audioTrack4ff"),__publicField(this,"setLocalDescription"),__publicField(this,"setRemoteDescription"),this.peer=t,this.id=e.id,this._monitor=getMonitor(this.id),this.logger=new Logger$1("BasicHandler",3,e.id),this.setLocalDescription=t.setLocalDescription.bind(t),this.setRemoteDescription=t.setRemoteDescription.bind(t),this._context=e,this.peer.on("ontrack",(e=>{this.emit("ontrack",e)}))}destroy(){this.logger.info("destroy",this.peerConnectionId||""),super.removeAllListeners()}get _peerConnection(){return this.peer.getOriginRTCPeerConnection()}getTransceivers(){return this._peerConnection.getTransceivers()}getConnectionState(){return this._peerConnection.connectionState}internalPublish(e){const{stream:t,videoTrack:i,audioTrack:r,pubAudio:o,pubVideo:s}=e,n={direction:"sendonly",streams:[t]},a={direction:"sendonly",streams:[t]},{sendEncodings:d,videoDescriptions:c,subVideoDescriptions:l,activeSimulcastStreams:u}=this._context.videoProfile.genVideoDescriptions(e);a.sendEncodings=d,this._context.videoProfile.activeSimStreams=u,this.logger.info("publish videoTransceiverInit videoDescriptions","",a,c);let _=null==r?void 0:r.preprocessingTrack;(null==r?void 0:r.mixType)!==AudioMixingType.PLAYOUT&&(null==r?void 0:r.mixedAudioTrack)&&(_=null==r?void 0:r.mixedAudioTrack),_=o&&_?_:"audio";let h=null==i?void 0:i.preprocessingTrack;h=s&&h?h:"video";try{this._reportRtcInvokeStatus("Handler.internalPublish",JSON.stringify({aTrack:mediaTrackStringify(_),vTrack:mediaTrackStringify(h),audioTransceiverInit:n,videoTransceiverInit:a}))}catch(e){}return{semantics:"unified-plan",videoDescriptions:c,subVideoDescriptions:l,audioTransceiverInit:{track:_,init:n},videoTransceiverInit:{track:h,init:a}}}async setCurrentDescription(){}createAVMlineAnswerTpl(e){const t=lib.parse(e);t.media.forEach((e=>{if("audio"===e.type){if("sendonly"===e.direction){const t=null==e?void 0:e.rtp.find((e=>"opus"===e.codec));if(t&&(null==e?void 0:e.fmtp)){const i=null==e?void 0:e.fmtp.find((e=>e.payload===t.payload));i&&this._context&&(i.config+=";stereo=1;sprop-stereo=1")}this._aSendonlyAnswerTpl=e}}else"video"===e.type&&("sendonly"===e.direction&&(this._vSendonlyAnswerTpl=e),Array.isArray(e.rtp)&&e.rtp.forEach((e=>{var t;(null==(t=e.codec)?void 0:t.includes("flexfec"))&&(this._enableSubFlexfec=!0)})))})),isRRTRSupported&&pushRRTR(t)}get peerConnectionId(){return this.peer.getConnectionId()||""}addBitrateLimit(e,t){null==e||e.rtp.forEach((({codec:i,payload:r})=>{if(["vp8","h264"].includes(i.toLocaleLowerCase())){const i=e.fmtp.find((e=>e.payload===r));i?i.config=[...i.config.split(";"),"x-google-min-bitrate=100",`x-google-start-bitrate=${t}`].join(";"):e.fmtp.push({payload:r,config:`x-google-min-bitrate=100;x-google-start-bitrate=${t}`})}}))}_report(e,t,i){var r;null==(r=this._monitor)||r.report(e,{...t,connection_id:this.peer.getConnectionId(),group_connection_id:this.peer.getGroupConnectionId()},i)}_reportRtcInvokeStatus(e,t,i=0,r="",o){this._report("rtc_invoke_status",{sdk_api_name:e,message:t,error_code:i,stream_id:r,elapse:0},o)}}const logger$2=new Logger$1("queue",4);var SdpStrategy=(e=>(e[e.ADD=0]="ADD",e[e.CLOSE=1]="CLOSE",e))(SdpStrategy||{}),SdpAction=(e=>(e.publish="publish",e.unpublish="unpublish",e.subscribe="subscribe",e.unsubscribe="unsubscribe",e.pushtrack="pushtrack",e.removetrack="removetrack",e))(SdpAction||{});const negativedAction={publish:"unpublish",subscribe:"unsubscribe",pushtrack:"removetrack"},aggregationSdpStrategy={publish:0,subscribe:0,pushtrack:0,unpublish:1,unsubscribe:1,removetrack:1};class SdpQueue extends EventEmitter2{constructor(){super(),__publicField(this,"_queue"),this._queue=[]}get queue(){return this._queue}enqueue(e){const t=this._queue.length;let i="";return this._queue=this._queue.filter((t=>t.streamId!==e.streamId||e.action!==negativedAction[t.action]||(i=t.streamId,logger$2.info("offsetStreamId",i),!1))),this._queue.length===t&&this._queue.push(e),this.emit("start"),i}dequeue(){if(!this._queue.length)return null;let e=this._queue.length;isChrome&&chromeVersion>=86&&chromeVersion<=92&&(e=Math.min(this._queue.length,5));const t=aggregationSdpStrategy[this._queue[0].action];for(let i=1;i<e;i++)if(aggregationSdpStrategy[this._queue[i].action]!==t)return{sdpStrategy:t,items:this._queue.splice(0,i)};return{sdpStrategy:t,items:this._queue.splice(0,e)}}destroy(){this._queue=[]}}const encodedTransformSupported$2=isLegacyEncodedTransformSupported()||isEncodedTransformSupported();class ChromeHandler extends BasicHandler{constructor(e,t){var i;super(e,t),__publicField(this,"name","chrome"),__publicField(this,"_queueBusy",!1),__publicField(this,"_sdpQueue"),__publicField(this,"_aSendonlyOfferTpl"),__publicField(this,"_vSendonlyOfferTpl"),__publicField(this,"_aRecvonlyOfferTpl"),__publicField(this,"_vRecvonlyOfferTpl"),__publicField(this,"_mid",10),__publicField(this,"_inactiveMlineIndex",[]),__publicField(this,"setDescription"),this.logger=new Logger$1("ChromeHandler",3,e.id),this.setDescription=t.setDescription.bind(t),this._sdpQueue=new SdpQueue,this._sdpQueue.on("start",(()=>{this._queueBusy||"stable"!==this._peerConnection.signalingState||(this.logger.info("dequeue start"),this.dequeue())})),null==(i=this._context.monitor)||i.set({handler_mode:"chrome"})}destroy(){super.destroy(),this._sdpQueue.destroy()}async publish(e){var t;const{stream:i,enableSimulcast:r}=e,{videoDescriptions:o,subVideoDescriptions:s,audioTransceiverInit:n,videoTransceiverInit:a}=super.internalPublish(e),d=generateAllSsrc(this._nextSsrc);this._nextSsrc=d.next;const c=""+this._mid++,l=""+this._mid++,u={...this._aSendonlyOfferTpl,...this.peer._offerIce,mid:c,msid:`${i.id} ${i.id}-audio`,ssrcs:generateSsrc(i.id,"audio",d.audio,clientCname)},_={...this._vSendonlyOfferTpl,...this.peer._offerIce,mid:l,msid:`${i.id} ${i.id}-video`};if(r){this.logger.info("subVideoDesc","desc: %o ",s),delete _.ssrcGroups,delete _.ssrcs;const e=[];_.rids=o.map((({rid:t})=>(e.unshift(t),{id:t,direction:"send"}))),_.simulcast={dir1:"send",list1:e.join(";")}}else{const{ssrcs:e,ssrcGroups:t}=generateSsrcs(i.id,d,{cname:clientCname});_.ssrcs=e,_.ssrcGroups=t}if((null==(t=this._context.serverConfig)?void 0:t.audioRed)&&Array.isArray(u.rtp)){this.logger.info("audioCodec","use Red");const e=u.rtp.findIndex((e=>"red"===e.codec));if(-1!==e){const[t]=u.rtp.splice(e,1);u.rtp.unshift(t)}const t=[];u.rtp.forEach((e=>t.push(e.payload))),u.payloads=t.join(" ")}Array.isArray(_.ext)&&(getParameter("IOS_SAFARI_ORIENTATION")||!isSafari&&!isIOS||(_.ext=_.ext.filter((e=>{var t;return!(null==(t=null==e?void 0:e.uri)?void 0:t.includes("video-orientation"))}))),_.ext=_.ext.filter((e=>{var t;return!(null==(t=null==e?void 0:e.uri)?void 0:t.includes("framemarking"))})));const h=null==u?void 0:u.rtp.find((e=>"opus"===e.codec));if(h&&u.fmtp){const e=u.fmtp.find((e=>e.payload===h.payload));e&&this._context.audioProfileManager&&(e.config=this._context.audioProfileManager.getOpusConfigStr(e.config))}return r||isSafari||this.addBitrateLimit(_,e.videoEncodeConfig[0].maxKbps),e.audioMLine=u,e.videoMLine=_,{partialSdp:getLocalPartialSdp(this.peer._offerSession,u,_),audioMid:c,videoMid:l,type:"incroffer",semantics:"unified-plan",videoDescriptions:o,subVideoDescriptions:s,audioTransceiverInit:n,videoTransceiverInit:a,peerConnectionMode:this.peerConnectionMode}}async subscribe(e,t){this.logger.info("subscribe");if(!this._aRecvonlyOfferTpl||!this._vRecvonlyOfferTpl){const e=await this._genOfferSdp();await this.createAVMlineOfferTpl(e)}let i,r,o,s,n="",a="",d=!1,c=!1;e.audioMLine=i,e.videoMLine=r,e.virtual?(n=""+this._mid++,d=!0):t.multiChatMode?(n=""+this._mid++,a=""+this._mid++,c=!0):(d=!0,c=!0,n=""+this._mid++,a=""+this._mid++),n&&(i={...cloneDeep(this._aRecvonlyOfferTpl),mid:n}),d&&(e.audioMLine=i,o={track:"audio",init:{direction:"recvonly"}}),a&&(r={...cloneDeep(this._vRecvonlyOfferTpl),mid:a}),c&&(e.videoMLine=r,s={track:"video",init:{direction:"recvonly"}});const l=getLocalPartialSdp(this.peer._offerSession,i,r);let u,_;if(!e.enableVendorMode&&!t.multiChatMode&&!e.virtual&&this._aSendonlyAnswerTpl&&this._vSendonlyAnswerTpl){u=generateAllSsrc(this._nextSsrc),this._nextSsrc=u.next;const t={...this._aSendonlyAnswerTpl,...this.peer._answerIce,mid:n,msid:`${e.streamId}${this._context.avSync?"":"-audio"} ${e.streamId}-audio`,ssrcs:generateSsrc(e.streamId,"audio",u.audio)},i={...this._vSendonlyAnswerTpl,...this.peer._answerIce,mid:a,msid:`${e.streamId}${this._context.avSync?"":"-video"} ${e.streamId}-video`,...generateSsrcs(e.streamId,u,{flexfec:this._enableSubFlexfec})};_={sdp:lib.write({...this.peer._answerSession,media:[t,i]}),sequenceId:e.sequenceId?++e.sequenceId:0},null==u||delete u.next}const h=null==i?void 0:i.rtp.find((e=>"opus"===e.codec));if(h&&(null==i?void 0:i.fmtp)){const e=null==i?void 0:i.fmtp.find((e=>e.payload===h.payload));e&&this._context&&(e.config+=";stereo=1;sprop-stereo=1")}if(e.isPublic&&chromeVersion>=86){const e=null==r?void 0:r.rtp.filter((e=>"H264"===e.codec));(null==e?void 0:e.length)&&(null==r?void 0:r.fmtp)&&(null==r||r.fmtp.forEach((t=>{e.find((e=>e.payload===t.payload))&&(t.config+=";sps-pps-idr-in-keyframe=1")})))}return{partialSdp:l,audioMid:n,videoMid:a,type:"incroffer",semantics:"unified-plan",audioTransceiverInit:o,videoTransceiverInit:s,allSsrc:u,peerConnectionMode:this.peerConnectionMode,signalingAck:_}}async handleAck(e){return this.logger.info("handleAck()","item: %o",e),this._sdpQueue.enqueue(e)}async dequeue(){var e,t;this._queueBusy=!0;const i=this._sdpQueue.dequeue();if(this.logger.info("dequeue()","ret: %o",i),!i)return void(this._queueBusy=!1);const r=[];try{const{items:o,sdpStrategy:s}=i,n=[],a=[],d=[];if(s===SdpStrategy.ADD){delete{...this.peer._answerIce}.candidates;for await(const i of o){const{audioMid:o,videoMid:s,action:c,audioTransceiverInit:l,videoTransceiverInit:u,signalingAck:_,stream:h,videoCodec:p,onSuccess:m,onFail:S}=i,g=h instanceof RemoteStream;if(m&&d.push(m),S&&r.push(S),g&&_.sequenceId<h.sequenceId)break;const v=lib.parse(_.sdp);if(!Array.isArray(v.media))break;v.media.sort(((e,t)=>{var i;return null==(i=null==e?void 0:e.type)?void 0:i.localeCompare(null==t?void 0:t.type)}));const f=v.media.find((e=>"audio"===e.type)),E=v.media.find((e=>"video"===e.type));if(!f||!E)break;const T={...f,...this.peer._answerIce,mid:o},R={...E,...this.peer._answerIce,mid:s},{audioMLine:b,videoMLine:y,audioTransceiver:I,videoTransceiver:C}=h;if(b){let t=this.peer._offerMlines.findIndex((e=>e.mid===o));if(I){if(this._reportRtcInvokeStatus("chromeHandler.updateTrack",JSON.stringify({audioStreamTrack:mediaTrackStringify(null==(e=h.audioTrack)?void 0:e.preprocessingTrack)})),-1===t){this.logger.error("dequeue","audio mid not found when update sdp, %s from %o",o,this.peer._offerMlines);continue}}else l&&b&&(h.audioTransceiver=this._peerConnection.addTransceiver(l.track,l.init),this._reportRtcInvokeStatus("chromeHandler.addTrack",JSON.stringify({audioStreamTrack:mediaTrackStringify(l.track)})),t=this._inactiveMlineIndex.shift(),t||(t=this.peer._offerMlines.length),encodedTransformSupported$2&&h.initAudioEncodedTransform());c===SdpAction.publish&&"OPUS"!==getParameter("AUDIO_CODEC")&&(setAudioCodecPreferences(b,getParameter("AUDIO_CODEC")),setAudioCodecPreferences(T,getParameter("AUDIO_CODEC"))),this.peer._offerMlines[t]={...b},this.peer._answerMlines[t]={...T}}if(y){let e=this.peer._offerMlines.findIndex((e=>e.mid===s));if(C){if(this._reportRtcInvokeStatus("chromeHandler.updateTrack",JSON.stringify({audioStreamTrack:mediaTrackStringify(null==(t=h.videoTrack)?void 0:t.preprocessingTrack)})),-1===e){this.logger.error("dequeue","video mid not found when update sdp, %s from %o",s,this.peer._offerMlines);continue}}else u&&y&&(h.videoTransceiver=this._peerConnection.addTransceiver(u.track,u.init),this._reportRtcInvokeStatus("chromeHandler.addTrack",JSON.stringify({videoStreamTrack:mediaTrackStringify(u.track)})),e=this._inactiveMlineIndex.shift(),e||(e=this.peer._offerMlines.length),encodedTransformSupported$2&&h.initVideoEncodedTransform());this.peer._offerMlines[e]={...y},c===SdpAction.publish&&p&&(setCodecPreferences(y,p),setCodecPreferences(R,p)),this.peer._answerMlines[e]=R}n.push(h.streamId||""),a.push(g?h.userId:"local"),g&&(h.sequenceId=_.sequenceId)}}else{const e={};o.forEach((t=>{const{audioMid:i,videoMid:r,action:o}=t;e[i]=i,o!==SdpAction.removetrack&&(e[r]=r),e[i]=i})),this.peer._offerMlines=this.peer._offerMlines.map(((t,i)=>(t.mid&&e[t.mid]&&(t=closeMline(t),this._inactiveMlineIndex.push(i)),t))),this._inactiveMlineIndex=[...new Set(this._inactiveMlineIndex)],this._inactiveMlineIndex.sort(((e,t)=>e-t)),this.peer._answerMlines=this.peer._answerMlines.map((t=>(t.mid&&e[t.mid]&&(t=closeMline(t)),t)))}try{await this.peer.getOriginRTCPeerConnection().createOffer(),await this.setDescription(n.length?{streamId:n.join(","),streamUserId:a.join(",")}:void 0)}catch(e){throw"have-local-offer"===this._peerConnection.signalingState&&await this._peerConnection.setLocalDescription({type:"rollback"}),e}try{d.forEach((e=>e()))}catch(e){}this.logger.info("dequeue","loop")}catch(e){this.logger.error("dequeue","unknown error: %o",e),r.forEach((t=>t(e)))}finally{this.dequeue()}}async getDefaultSdp(){const e=await this._genOfferSdp();this.createAVMlineOfferTpl(e);const t=lib.parse(e),i=[];return t.media=t.media.filter((e=>"recvonly"===e.direction&&(Array.isArray(e.ext)&&(e.ext=e.ext.filter((e=>"urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id"!==e.uri))),i.push(`${e.mid}`),!0))),t.groups=[{mids:i.join(" "),type:"BUNDLE"}],isRRTRSupported&&pushRRTR(t),{sdp:lib.write(t),semantics:"unified-plan",type:"incroffer"}}async rollback({stream:e}){e instanceof LocalStream||await this.handleAck({action:SdpAction.unsubscribe,streamId:e.streamId,audioMid:e.audioMid,videoMid:e.videoMid,stream:e}),delete e.audioMLine,delete e.videoMLine}createAVMlineOfferTpl(e){const t=lib.parse(e);t.media.forEach((e=>{e.icePwd=this.peer._offerIce.icePwd,e.iceUfrag=this.peer._offerIce.iceUfrag,"audio"===e.type?"sendonly"===e.direction?this._aSendonlyOfferTpl=e:(Array.isArray(e.ext)&&(e.ext=e.ext.filter((e=>"urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id"!==e.uri))),this._aRecvonlyOfferTpl=e):"video"===e.type&&("sendonly"===e.direction?this._vSendonlyOfferTpl=e:(Array.isArray(e.ext)&&(e.ext=e.ext.filter((e=>"urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id"!==e.uri))),this._vRecvonlyOfferTpl=e))})),isRRTRSupported&&pushRRTR(t)}async _genOfferSdp(){let e;try{if(e=await createDefaultSdp(!0),!e)throw"pc.createOffer() return empty."}catch(e){const t="Get offer Error. "+(e.message|e);throw new SDKError(ErrorCode.NOT_SUPPORTED,t)}return e}}class FirefoxHandler extends BasicHandler{constructor(e,t){var i;super(e,t),__publicField(this,"name","firefox"),__publicField(this,"_aRecvonlyOfferTpl"),this.logger=new Logger$1("FirefoxHandler",3,e.id),null==(i=this._context.monitor)||i.set({handler_mode:"firefox"})}async publish(e){var t,i;const{videoDescriptions:r,subVideoDescriptions:o,audioTransceiverInit:s,videoTransceiverInit:n}=super.internalPublish(e);e.audioTransceiver=this._peerConnection.addTransceiver(s.track,s.init),Array.isArray(n.init.sendEncodings)&&1===n.init.sendEncodings.length&&(n.init.sendEncodings=n.init.sendEncodings.map((e=>(delete e.rid,e)))),e.videoTransceiver=this._peerConnection.addTransceiver(n.track,n.init);const a=getServerNow();this._report("rtc_begin_create_offer",{direction:"up",stream_id:"",stream_user_id:"",pc_session_id:this.peerConnectionId,vendor_mode:0});const d=await this.peer.createOfferSdp();this._report("rtc_create_offer",{direction:"up",error_code:0,stream_id:"",stream_user_id:"",elapse:getServerNow()-a});const c=lib.parse(d);c.media=null==(t=c.media)?void 0:t.map((e=>({...e,...this.peer._offerIce}))),pushRRTR(c),await this.setLocalDescription(lib.write(c));const l=e.audioTransceiver.mid,u=e.videoTransceiver.mid;let _=null,h=null;return c.media=null==(i=c.media)?void 0:i.map((e=>{var t;if(`${e.mid}`===l){_=e;const i=null==_?void 0:_.rtp.find((e=>"opus"===e.codec));if(i&&_.fmtp){const e=_.fmtp.find((e=>e.payload===i.payload));e&&(null==(t=this._context)?void 0:t.audioProfileManager)&&(e.config=this._context.audioProfileManager.getOpusConfigStr(e.config))}}else`${e.mid}`===u&&(h=e);return e})),this.addBitrateLimit(h,e.videoEncodeConfig[0].maxKbps),await this.setLocalDescription(lib.write(c)),e.initVideoEncodedTransform(),e.initAudioEncodedTransform(),{partialSdp:getLocalPartialSdp(c,_,h),audioMid:l,videoMid:u,type:"incroffer",semantics:"unified-plan",videoDescriptions:r,subVideoDescriptions:o,audioTransceiverInit:s,videoTransceiverInit:n,peerConnectionMode:this.peerConnectionMode}}async _internalChangePubCodec(){const{localDescription:e}=this._peerConnection;e&&(await this.peer.createOfferSdp(),await this._peerConnection.setLocalDescription(e))}async subscribe(e,t){var i,r,o,s,n,a;this.logger.info("subscribe()");let d,c,l="",u="",_=!1,h=!1;e.virtual?_=!0:(t.multiChatMode||(_=!0),h=!0),_&&(e.audioTransceiver=this._peerConnection.addTransceiver("audio",{direction:"recvonly"})),h&&(e.videoTransceiver=this._peerConnection.addTransceiver("video",{direction:"recvonly"}));const p=getServerNow();this._report("rtc_begin_create_offer",{direction:"up",stream_id:e.streamId,stream_user_id:e.userId,pc_session_id:this.peerConnectionId,vendor_mode:0});const m=await this.peer.createOfferSdp();this._report("rtc_create_offer",{error_code:0,direction:"up",stream_id:e.streamId,stream_user_id:e.userId,elapse:getServerNow()-p});const S=lib.parse(m);let g,v;if(S.media=null==(i=S.media)?void 0:i.map((e=>({...e,...this.peer._offerIce}))),S.media.map((e=>{var t,i,r,o;"video"===e.type&&(isTransportCCSupport?(e.ext=null==(t=e.ext)?void 0:t.filter((e=>-1===e.uri.indexOf("abs-send-time"))),e.rtcpFb=null==(i=e.rtcpFb)?void 0:i.filter((e=>"goog-remb"!==e.type))):(e.rtcpFb=null==(r=e.rtcpFb)?void 0:r.filter((e=>"transport-cc"!==e.type)),e.ext=null==(o=e.ext)?void 0:o.filter((e=>-1===e.uri.indexOf("transport")))))})),isRRTRSupported&&pushRRTR(S),await this.setLocalDescription(lib.write(S),{streamId:e.streamId||"",streamUserId:e.userId}),l=null==(r=e.audioTransceiver)?void 0:r.mid,u=null==(o=e.videoTransceiver)?void 0:o.mid,null==(s=S.media)||s.forEach((e=>{`${e.mid}`===l?d=e:`${e.mid}`===u&&(c=e)})),l&&d||(l=`audio_${u}`,d={...this._aRecvonlyOfferTpl,mid:l}),e.audioMid=l,e.videoMid=u,!t.multiChatMode&&!e.virtual&&this._aSendonlyAnswerTpl&&this._aSendonlyAnswerTpl){g=generateAllSsrc(this._nextSsrc),this._nextSsrc=g.next;const t={...this._aSendonlyAnswerTpl,...this.peer._answerIce,mid:l,msid:`${e.streamId}${(null==(n=this._context)?void 0:n.avSync)?"":"-audio"} ${e.streamId}-audio`,ssrcs:generateSsrc(e.streamId,"audio",g.audio)},i={...this._vSendonlyAnswerTpl,...this.peer._answerIce,mid:u,msid:`${e.streamId}${(null==(a=this._context)?void 0:a.avSync)?"":"-video"} ${e.streamId}-video`,...generateSsrcs(e.streamId,g,{flexfec:this._enableSubFlexfec})};v={sdp:lib.write({...this.peer._answerSession,media:[t,i]}),sequenceId:e.sequenceId?++e.sequenceId:0},null==g||delete g.next}return e.initVideoEncodedTransform(),e.initAudioEncodedTransform(),{partialSdp:getLocalPartialSdp(S,d,c,!1),audioMid:l,videoMid:u,type:"incroffer",semantics:"unified-plan",audioTransceiverInit:e.audioTransceiver?{track:"audio",init:{direction:"recvonly"}}:void 0,videoTransceiverInit:e.videoTransceiver?{track:"video",init:{direction:"recvonly"}}:void 0,allSsrc:g,peerConnectionMode:this.peerConnectionMode,signalingAck:v}}async handleAck(e){const{stream:t,action:i}=e;if(i===SdpAction.removetrack)return"";if(i===SdpAction.unpublish||i===SdpAction.unsubscribe){try{await this.close(t),"function"==typeof e.onSuccess&&e.onSuccess()}catch(t){"function"==typeof e.onFail&&e.onFail(t)}return t.streamId||""}const{signalingAck:r,videoCodec:o}=e,s=lib.parse(r.sdp);try{await this._internalSetRemoteDescription(s.media,t,o),"function"==typeof e.onSuccess&&e.onSuccess()}catch(t){"function"==typeof e.onFail&&e.onFail(t)}return""}async _internalSetRemoteDescription(e,t,i){var r,o;const s={},n=lib.parse(null==(r=this._peerConnection.remoteDescription)?void 0:r.sdp);n.media.forEach((e=>{void 0!==e.mid&&(s[e.mid]=e)})),e.forEach((e=>{if("audio"===(e={...e,...this.peer._answerIce}).type&&(t.audioMid?(e.mid=t.audioMid,s[t.audioMid]=e):s[e.mid]=e),"video"===e.type){if(t instanceof LocalStream&&firefoxVersion<=87){const t={};Array.isArray(e.rtp)&&(e.rtp=e.rtp.filter((e=>"rtx"!==e.codec||(t[e.payload]=e.payload,!1)))),"string"==typeof e.payloads&&(e.payloads=e.payloads.split(" ").filter((e=>!t[e])).join(" ")),Array.isArray(e.fmtp)&&(e.fmtp=e.fmtp.filter((e=>!t[e.payload]))),Array.isArray(e.rtcpFb)&&(e.fmtp=e.fmtp.filter((e=>!t[e.payload])))}i&&setCodecPreferences(e,i),t.videoMid?(e.mid=t.videoMid,s[t.videoMid]=e):s[e.mid]=e}}));const a=lib.parse(null==(o=this._peerConnection.localDescription)?void 0:o.sdp),d=a.media.map((e=>{const t=s[e.mid];return"inactive"===e.direction?e:t}));n.groups=a.groups,n.media=d,n.media.map((e=>{var t,i,r,o,s;"video"===e.type&&(isTransportCCSupport?(e.ext=null==(t=e.ext)?void 0:t.filter((e=>-1===e.uri.indexOf("abs-send-time"))),e.rtcpFb=null==(i=e.rtcpFb)?void 0:i.filter((e=>"goog-remb"!==e.type))):(e.rtcpFb=null==(r=e.rtcpFb)?void 0:r.filter((e=>"transport-cc"!==e.type)),e.ext=null==(o=e.ext)?void 0:o.filter((e=>-1===e.uri.indexOf("transport")))),firefoxVersion>=138&&(e.ext=null==(s=e.ext)?void 0:s.filter((e=>!e.uri.includes("sdes:mid")))))})),isRRTRSupported&&pushRRTR(n),await this.setRemoteDescription(lib.write(n))}async getDefaultSdp(){const e=new RTCPeerConnection;e.addTransceiver("audio",{direction:"recvonly"}),e.addTransceiver("video",{direction:"recvonly"});const t=await e.createOffer(),i=lib.parse(t.sdp);this.createAVMlineOfferTpl(t.sdp);const r=[];return i.media=i.media.filter((e=>{if("recvonly"===e.direction){const t=`template_${e.type}`;return e.mid=t,r.push(t),!0}return!1})),isRRTRSupported&&pushRRTR(i),i.groups=[{mids:r.join(" "),type:"BUNDLE"}],e.close(),{sdp:lib.write(i),semantics:"unified-plan",type:"incroffer"}}async rollback({msid:e,stream:t,audioMid:i,videoMid:r}){return this.logger.warn("rollback()"),this.close(t,i,r)}async close(e,t,i){var r;this.logger.info("close()");const o=e.audioMid||t,s=e.videoMid||i,n={};e.audioTransceiver&&o&&(e.audioTransceiver.stop(),n[o]=o),e.videoTransceiver&&s&&(e.videoTransceiver.stop(),n[s]=s);const a=[],d=await this.peer.createOfferSdp(),c=lib.parse(d);c.media=c.media.map((e=>(n[e.mid]&&(e=closeMline(e)),"inactive"!==e.direction&&a.push(e.mid),{...e,...this.peer._offerIce})));const l=lib.parse(null==(r=this._peerConnection.remoteDescription)?void 0:r.sdp),u={};l.media.forEach((e=>{void 0!==e.mid&&(u[e.mid]=e)})),l.media=c.media.map((e=>"inactive"===e.direction?e:u[e.mid])),c.groups&&l.groups&&(c.groups[0].mids=a.join(" "),l.groups[0].mids=a.join(" ")),await this.setLocalDescription(lib.write(c)),await this.setRemoteDescription(lib.write(l))}async setCurrentDescription(){await this.peer.createOfferSdp(),this._peerConnection.localDescription&&this._peerConnection.remoteDescription&&(await this._peerConnection.setLocalDescription(this._peerConnection.localDescription),await this._peerConnection.setRemoteDescription(this._peerConnection.remoteDescription))}createAVMlineOfferTpl(e){const t=lib.parse(e);t.media.forEach((e=>{"audio"===e.type&&(this._aRecvonlyOfferTpl=e)})),isRRTRSupported&&pushRRTR(t)}}class FallbackHandler extends BasicHandler{constructor(e,t){var i,r;super(e,t),__publicField(this,"name","fallback"),__publicField(this,"_aRecvonlyOfferTpl"),this.logger=new Logger$1("FallbackHandler",3,e.id),this.logger.warn("ctor","using fallback handler"),null==(i=this._context.monitor)||i.report("rtc_error",{message:"using fallback handler",error_code:-1}),null==(r=this._context.monitor)||r.set({handler_mode:"fallback"})}async publish(e){var t;const{videoDescriptions:i,subVideoDescriptions:r,audioTransceiverInit:o,videoTransceiverInit:s}=super.internalPublish(e);e.audioTransceiver=this._peerConnection.addTransceiver(o.track,o.init),Array.isArray(s.init.sendEncodings)&&1===s.init.sendEncodings.length&&(s.init.sendEncodings=s.init.sendEncodings.map((e=>(delete e.rid,e)))),e.videoTransceiver=this._peerConnection.addTransceiver(s.track,s.init);const n=getServerNow();this._report("rtc_begin_create_offer",{direction:"up",stream_id:"",stream_user_id:"",pc_session_id:this.peerConnectionId,vendor_mode:0});const a=await this.peer.createOfferSdp();this._report("rtc_create_offer",{direction:"up",error_code:0,stream_id:"",stream_user_id:"",elapse:getServerNow()-n});const d=lib.parse(a);await this.setLocalDescription(a);const c=e.audioTransceiver.mid,l=e.videoTransceiver.mid;let u=null,_=null;return d.media=null==(t=d.media)?void 0:t.map((e=>(`${e.mid}`===c?u=e:`${e.mid}`===l&&(_=e),e))),e.initVideoEncodedTransform(),e.initAudioEncodedTransform(),{partialSdp:getLocalPartialSdp(d,u,_),audioMid:c,videoMid:l,type:"incroffer",semantics:"unified-plan",videoDescriptions:i,subVideoDescriptions:r,audioTransceiverInit:o,videoTransceiverInit:s,peerConnectionMode:this.peerConnectionMode}}async _internalChangePubCodec(){const{localDescription:e}=this._peerConnection;e&&(await this.peer.createOfferSdp(),await this._peerConnection.setLocalDescription(e))}async subscribe(e,t){var i,r,o,s,n;this.logger.info("subscribe()");let a,d,c="",l="",u=!1,_=!1;e.virtual?u=!0:(t.multiChatMode||(u=!0),_=!0),u&&(e.audioTransceiver=this._peerConnection.addTransceiver("audio",{direction:"recvonly"})),_&&(e.videoTransceiver=this._peerConnection.addTransceiver("video",{direction:"recvonly"}));const h=getServerNow();this._report("rtc_begin_create_offer",{direction:"up",stream_id:e.streamId,stream_user_id:e.userId,pc_session_id:this.peerConnectionId,vendor_mode:0});const p=await this.peer.createOfferSdp();this._report("rtc_create_offer",{error_code:0,direction:"up",stream_id:e.streamId,stream_user_id:e.userId,elapse:getServerNow()-h});const m=lib.parse(p);let S,g;if(await this.setLocalDescription(p,{streamId:e.streamId||"",streamUserId:e.userId}),c=null==(i=e.audioTransceiver)?void 0:i.mid,l=null==(r=e.videoTransceiver)?void 0:r.mid,null==(o=m.media)||o.forEach((e=>{`${e.mid}`===c?a=e:`${e.mid}`===l&&(d=e)})),c&&a||(c=`audio_${l}`,a={...this._aRecvonlyOfferTpl,mid:c}),e.audioMid=c,e.videoMid=l,!t.multiChatMode&&!e.virtual&&this._aSendonlyAnswerTpl&&this._aSendonlyAnswerTpl){S=generateAllSsrc(this._nextSsrc),this._nextSsrc=S.next;const t={...this._aSendonlyAnswerTpl,...this.peer._answerIce,mid:c,msid:`${e.streamId}${(null==(s=this._context)?void 0:s.avSync)?"":"-audio"} ${e.streamId}-audio`,ssrcs:generateSsrc(e.streamId,"audio",S.audio)},i={...this._vSendonlyAnswerTpl,...this.peer._answerIce,mid:l,msid:`${e.streamId}${(null==(n=this._context)?void 0:n.avSync)?"":"-video"} ${e.streamId}-video`,...generateSsrcs(e.streamId,S,{flexfec:this._enableSubFlexfec})};g={sdp:lib.write({...this.peer._answerSession,media:[t,i]}),sequenceId:e.sequenceId?++e.sequenceId:0},null==S||delete S.next}return e.initVideoEncodedTransform(),e.initAudioEncodedTransform(),{partialSdp:getLocalPartialSdp(m,a,d,!1),audioMid:c,videoMid:l,type:"incroffer",semantics:"unified-plan",audioTransceiverInit:e.audioTransceiver?{track:"audio",init:{direction:"recvonly"}}:void 0,videoTransceiverInit:e.videoTransceiver?{track:"video",init:{direction:"recvonly"}}:void 0,allSsrc:S,peerConnectionMode:this.peerConnectionMode,signalingAck:g}}async handleAck(e){const{stream:t,action:i}=e;if(i===SdpAction.removetrack)return"";if(i===SdpAction.unpublish||i===SdpAction.unsubscribe){try{await this.close(t),"function"==typeof e.onSuccess&&e.onSuccess()}catch(t){"function"==typeof e.onFail&&e.onFail(t)}return t.streamId||""}const{signalingAck:r,videoCodec:o}=e,s=lib.parse(r.sdp);try{await this._internalSetRemoteDescription(s.media,t,o),"function"==typeof e.onSuccess&&e.onSuccess()}catch(t){"function"==typeof e.onFail&&e.onFail(t)}return""}async _internalSetRemoteDescription(e,t,i){var r,o;const s={},n=lib.parse(null==(r=this._peerConnection.remoteDescription)?void 0:r.sdp);n.media.forEach((e=>{void 0!==e.mid&&(s[e.mid]=e)})),e.forEach((e=>{"audio"===(e={...e,...this.peer._answerIce}).type&&(t.audioMid?(e.mid=t.audioMid,s[t.audioMid]=e):s[e.mid]=e),"video"===e.type&&(i&&setCodecPreferences(e,i),t.videoMid?(e.mid=t.videoMid,s[t.videoMid]=e):s[e.mid]=e)}));const a=lib.parse(null==(o=this._peerConnection.localDescription)?void 0:o.sdp),d=a.media.map((e=>{const t=s[e.mid];return"inactive"===e.direction?e:t}));n.groups=a.groups,n.media=d,n.media.map((e=>{var t,i,r,o;"video"===e.type&&(isTransportCCSupport?(e.ext=null==(t=e.ext)?void 0:t.filter((e=>-1===e.uri.indexOf("abs-send-time"))),e.rtcpFb=null==(i=e.rtcpFb)?void 0:i.filter((e=>"goog-remb"!==e.type))):(e.rtcpFb=null==(r=e.rtcpFb)?void 0:r.filter((e=>"transport-cc"!==e.type)),e.ext=null==(o=e.ext)?void 0:o.filter((e=>-1===e.uri.indexOf("transport")))))})),await this.setRemoteDescription(lib.write(n))}async getDefaultSdp(){const e=new RTCPeerConnection;e.addTransceiver("audio",{direction:"recvonly"}),e.addTransceiver("video",{direction:"recvonly"});const t=await e.createOffer(),i=lib.parse(t.sdp);this.createAVMlineOfferTpl(t.sdp);const r=[];return i.media=i.media.filter((e=>{if("recvonly"===e.direction){const t=`template_${e.type}`;return e.mid=t,r.push(t),!0}return!1})),i.groups=[{mids:r.join(" "),type:"BUNDLE"}],e.close(),{sdp:lib.write(i),semantics:"unified-plan",type:"incroffer"}}async rollback({msid:e,stream:t,audioMid:i,videoMid:r}){return this.logger.warn("rollback()"),this.close(t,i,r)}async close(e,t,i){var r;this.logger.info("close()");const o=e.audioMid||t,s=e.videoMid||i,n={};e.audioTransceiver&&o&&(e.audioTransceiver.stop(),n[o]=o),e.videoTransceiver&&s&&(e.videoTransceiver.stop(),n[s]=s);const a=[],d=await this.peer.createOfferSdp(),c=lib.parse(d);c.media=c.media.map((e=>(n[e.mid]&&(e=closeMline(e)),"inactive"!==e.direction&&a.push(e.mid),{...e,...this.peer._offerIce})));const l=lib.parse(null==(r=this._peerConnection.remoteDescription)?void 0:r.sdp),u={};l.media.forEach((e=>{void 0!==e.mid&&(u[e.mid]=e)})),l.media=c.media.map((e=>"inactive"===e.direction?e:u[e.mid])),c.groups&&l.groups&&(c.groups[0].mids=a.join(" "),l.groups[0].mids=a.join(" ")),await this.setLocalDescription(d),await this.setRemoteDescription(lib.write(l))}async setCurrentDescription(){await this.peer.createOfferSdp(),this._peerConnection.localDescription&&this._peerConnection.remoteDescription&&(await this._peerConnection.setLocalDescription(this._peerConnection.localDescription),await this._peerConnection.setRemoteDescription(this._peerConnection.remoteDescription))}createAVMlineOfferTpl(e){lib.parse(e).media.forEach((e=>{"audio"===e.type&&(this._aRecvonlyOfferTpl=e)}))}}var __defProp$8=Object.defineProperty,__getOwnPropDesc$8=Object.getOwnPropertyDescriptor,__decorateClass$8=(e,t,i,r)=>{for(var o,s=r>1?void 0:r?__getOwnPropDesc$8(t,i):t,n=e.length-1;n>=0;n--)(o=e[n])&&(s=(r?o(t,i,s):o(s))||s);return r&&s&&__defProp$8(t,i,s),s};class BatchProcessor{constructor(e){__publicField(this,"_queue",[]),__publicField(this,"_runningTask",[]),__publicField(this,"executor"),__publicField(this,"busy",!1),this.executor=e}add(e){const{promise:t,resolve:i,reject:r}=promiseWithResolves();return this._queue.push({item:e,resolve:i,reject:r}),this.busy||this._emit(),t}destroy(){[...this._queue,...this._runningTask].forEach((({reject:e})=>{e(new SDKError(ErrorCode.OPERATION_CANCEL,"queue close"))})),this.busy=!1,this._queue=[]}async _emit(){const e=this._queue;if(this._runningTask=e,this._queue=[],0===e.length)return void(this.busy=!1);const t=e.map((e=>e.item)),i=e.map((e=>e.resolve)),r=e.map((e=>e.reject));try{this.busy=!0;const e=await this.executor(t);i.forEach((t=>t(e)))}catch(e){r.forEach((t=>t(e)))}this._runningTask=[],setTimeout((()=>{this._emit()}))}}function encodedTransformSupported$1(){return isLegacyEncodedTransformSupported()||isEncodedTransformSupported()}class StandardHandler extends BasicHandler{constructor(e,t){var i;super(e,t),__publicField(this,"name","standard"),__publicField(this,"_applyQueue",new BatchProcessor(this.apply.bind(this))),__publicField(this,"_createQueue",new BatchProcessor(this.create.bind(this))),__publicField(this,"_pqueue",new PriorityQueue),__publicField(this,"_midMap",new Map),__publicField(this,"_aRecvonlyOfferTpl"),this.logger=new Logger$1("StandardHandler",3,e.id),this.logger.warn("ctor","using standard handler"),null==(i=this._context.monitor)||i.set({handler_mode:"standard"}),this._peerConnection.addTransceiver("audio",{direction:"recvonly"}),this._peerConnection.addTransceiver("video",{direction:"recvonly"})}async publish(e){var t;this.logger.info("publish()",`streamId: ${e.streamId}`);const{videoDescriptions:i,subVideoDescriptions:r,audioTransceiverInit:o,videoTransceiverInit:s}=super.internalPublish(e);e.audioTransceiver=this._peerConnection.addTransceiver(o.track,{...o.init,direction:"sendonly"}),Array.isArray(s.init.sendEncodings)&&1===s.init.sendEncodings.length&&(s.init.sendEncodings=s.init.sendEncodings.map((e=>(delete e.rid,e)))),e.videoTransceiver=this._peerConnection.addTransceiver(s.track,{...s.init,direction:"sendonly"});const n=getServerNow();this._report("rtc_begin_create_offer",{direction:"up",stream_id:"",stream_user_id:"",pc_session_id:this.peerConnectionId,vendor_mode:0});const a=await this._createQueue.add();this._report("rtc_create_offer",{direction:"up",error_code:0,stream_id:"",stream_user_id:"",elapse:getServerNow()-n});const d=e.audioTransceiver.mid,c=e.videoTransceiver.mid;DCHECK(d&&c,"Transceiver not return MID after setLocalDescription"),e.audioMid=d,e.videoMid=c;let l=null,u=null;const _=lib.parse(a);return _.media=null==(t=_.media)?void 0:t.map((e=>(`${e.mid}`===d?l=e:`${e.mid}`===c&&(u=e),e))),encodedTransformSupported$1()&&(e.initVideoEncodedTransform(),e.initAudioEncodedTransform()),{partialSdp:getLocalPartialSdp(_,l,u),audioMid:d,videoMid:c,type:"incroffer",semantics:"unified-plan",videoDescriptions:i,subVideoDescriptions:r,audioTransceiverInit:o,videoTransceiverInit:s,peerConnectionMode:this.peerConnectionMode}}async subscribe(e,t){var i,r,o,s,n;this.logger.info("subscribe()",`streamId: ${e.streamId}`);let a,d,c=!1,l=!1;e.virtual?c=!0:(t.multiChatMode||(c=!0),l=!0),c&&(e.audioTransceiver=this._peerConnection.addTransceiver("audio",{direction:"recvonly"})),l&&(e.videoTransceiver=this._peerConnection.addTransceiver("video",{direction:"recvonly"}));const u=getServerNow();this._report("rtc_begin_create_offer",{direction:"up",stream_id:e.streamId,stream_user_id:e.userId,pc_session_id:this.peerConnectionId,vendor_mode:0});const _=await this._createQueue.add();this._report("rtc_create_offer",{error_code:0,direction:"up",stream_id:e.streamId,stream_user_id:e.userId,elapse:getServerNow()-u});let h=(null==(i=e.audioTransceiver)?void 0:i.mid)??void 0;const p=(null==(r=e.videoTransceiver)?void 0:r.mid)??void 0,m=lib.parse(_);let S,g;if(null==(o=m.media)||o.forEach((e=>{`${e.mid}`===h?a=e:`${e.mid}`===p&&(d=e)})),h&&a||(h=`audio_${p}`,a={...this._aRecvonlyOfferTpl,mid:h}),e.audioMid=h,e.videoMid=p,!t.multiChatMode&&!e.virtual&&this._aSendonlyAnswerTpl&&this._aSendonlyAnswerTpl){S=this._generateAllSsrc();const t={...this._aSendonlyAnswerTpl,...this.peer._answerIce,mid:h,msid:`${e.streamId}${(null==(s=this._context)?void 0:s.avSync)?"":"-audio"} ${e.streamId}-audio`,ssrcs:generateSsrc(e.streamId,"audio",S.audio)},i={...this._vSendonlyAnswerTpl,...this.peer._answerIce,mid:p,msid:`${e.streamId}${(null==(n=this._context)?void 0:n.avSync)?"":"-video"} ${e.streamId}-video`,...generateSsrcs(e.streamId,S,{flexfec:this._enableSubFlexfec})};g={sdp:lib.write({...this.peer._answerSession,media:[t,i]}),sequenceId:e.sequenceId?++e.sequenceId:0},null==S||delete S.next}return encodedTransformSupported$1()&&(e.initVideoEncodedTransform(),e.initAudioEncodedTransform()),{partialSdp:getLocalPartialSdp(m,a,d),audioMid:h,videoMid:p||"",type:"incroffer",semantics:"unified-plan",audioTransceiverInit:e.audioTransceiver?{track:"audio",init:{direction:"recvonly"}}:void 0,videoTransceiverInit:e.videoTransceiver?{track:"video",init:{direction:"recvonly"}}:void 0,allSsrc:S,peerConnectionMode:this.peerConnectionMode,signalingAck:g}}async handleAck(e){const{stream:t,action:i}=e;if(i===SdpAction.removetrack)return"";if(i===SdpAction.unpublish||i===SdpAction.unsubscribe){try{await this.close(t),"function"==typeof e.onSuccess&&e.onSuccess()}catch(t){"function"==typeof e.onFail&&e.onFail(t)}return t.streamId||""}const{signalingAck:r,videoCodec:o}=e,s=lib.parse(r.sdp);try{await this._internalSetRemoteDescription(s.media,t,o),"function"==typeof e.onSuccess&&e.onSuccess()}catch(t){"function"==typeof e.onFail&&e.onFail(t)}return""}async _internalSetRemoteDescription(e,t,i){e.forEach((e=>{"audio"===(e={...e,...this.peer._answerIce}).type&&(t.audioMid?(e.mid=t.audioMid,this._midMap.set(t.audioMid,e)):this._midMap.set(e.mid,e)),"video"===e.type&&(i&&setCodecPreferences(e,i),t.videoMid?(e.mid=t.videoMid,this._midMap.set(t.videoMid,e)):this._midMap.set(e.mid,e))}));t instanceof LocalStream?this.handlePublishAction({stream:t,videoCodec:i}):this.handleSubscribeAction({stream:t}),await this._applyQueue.add()}handlePublishAction(e){var t;const{videoCodec:i,stream:r}=e,o=r.audioMid?this._midMap.get(r.audioMid):void 0,s=r.videoMid?this._midMap.get(r.videoMid):void 0;this._context.pcKillSwitch.sld_rtcpfb_rrtr_add&&isRRTRSupported&&(SDPTools.addRRTR(o),SDPTools.addRRTR(s));const n=(null==(t=this._context.serverConfig)?void 0:t.audioRed)?"RED":getParameter("AUDIO_CODEC");"OPUS"!==n&&o&&setAudioCodecPreferences(o,n),this._context.pcKillSwitch.sld_fmtp_opus_add&&SDPTools.decorateOpusConfig(o,this._context.audioProfileManager),isFirefox&&firefoxVersion<=87&&SDPTools.removeRtxInMLine(s),i&&s&&setCodecPreferences(s,i),this._context.pcKillSwitch.sld_ext_sdesmid_remove&&isFirefox&&firefoxVersion>=138&&SDPTools.removeExtSdesMid(s),this._context.pcKillSwitch.sld_fmtp_bitrate_add&&(r.enableSimulcast||isSafari||!s||this.addBitrateLimit(s,r.videoEncodeConfig[0].maxKbps)),isFirefox&&SDPTools.selectCC(s,isTransportCCSupport?"tcc":"remb"),r.audioMid&&o&&this._midMap.set(r.audioMid,o),r.videoMid&&s&&this._midMap.set(r.videoMid,s)}handleSubscribeAction(e){const{stream:t}=e,i=t.audioMid?this._midMap.get(t.audioMid):void 0,r=t.videoMid?this._midMap.get(t.videoMid):void 0;isFirefox||(SDPTools.removeRtpStreamId(i),SDPTools.removeRtpStreamId(r)),this._context.pcKillSwitch.sld_rtcpfb_rrtr_add&&isRRTRSupported&&(SDPTools.addRRTR(i),SDPTools.addRRTR(r)),this._context.pcKillSwitch.sld_fmtp_opus_add&&SDPTools.decorateOpusConfig(i),getParameter("IOS_SAFARI_ORIENTATION")||!isSafari&&!isIOS||SDPTools.removeExtVideoOrientation(r),this._context.pcKillSwitch.sld_fmtp_sps_add&&t.isPublic&&isChrome&&chromeVersion>=86&&SDPTools.decorateSpsPpsIdrInKeyframe(r),t.audioMid&&i&&this._midMap.set(t.audioMid,i),t.videoMid&&r&&this._midMap.set(t.videoMid,r)}async getDefaultSdp(){const e=new RTCPeerConnection;e.addTransceiver("audio",{direction:"recvonly"}),e.addTransceiver("video",{direction:"recvonly"});const t=await e.createOffer(),i=lib.parse(t.sdp);this.createAVMlineOfferTpl(t.sdp);const r=[];return i.media=i.media.filter((e=>{if("recvonly"===e.direction){const t=`template_${e.type}`;return e.mid=t,r.push(t),!0}return!1})),isRRTRSupported&&pushRRTR(i),i.groups=[{mids:r.join(" "),type:"BUNDLE"}],e.close(),{sdp:lib.write(i),semantics:"unified-plan",type:"incroffer"}}async rollback({msid:e,stream:t,audioMid:i,videoMid:r}){return this.logger.warn("rollback()"),this.close(t,i,r)}async close(e,t,i){this.logger.info("close()");const r=e.audioMid||t,o=e.videoMid||i;if(e.audioTransceiver&&r)try{e.audioTransceiver.stop(),delete e.audioTransceiver}catch{}if(e.videoTransceiver&&o)try{e.videoTransceiver.stop(),delete e.videoTransceiver}catch{}const s=r?this._midMap.get(r):void 0,n=o?this._midMap.get(o):void 0;s&&closeMline(s),n&&closeMline(n),r&&s&&this._midMap.set(r,s),o&&n&&this._midMap.set(o,n),await this._applyQueue.add()}async setCurrentDescription(){await this._applyQueue.add()}createAVMlineOfferTpl(e){lib.parse(e).media.forEach((e=>{"audio"===e.type&&(this._aRecvonlyOfferTpl=e)}))}_generateAllSsrc(){const e=generateAllSsrc(this._nextSsrc);return this._nextSsrc=e.next,e}async create(){this.logger.info("RTCPeerConnection create");const e=await this.peer.createOfferSdp();return DCHECK(e,"RTCPeerConnection not return SDP"),await this.peer.setLocalDescription(e),e}async apply(){this.logger.info("RTCPeerConnection apply");let e=await this.peer.createOfferSdp();DCHECK(e,"RTCPeerConnection not return SDP",e);const t=lib.parse(e);e=this.generateOffer(t,e);const i=this.generateAnswer(t);await this.setLocalDescription(e),await this.setRemoteDescription(i)}generateOffer(e,t){let i=!1;return"v1"===this.peer.getIceVersion()&&isFirefox&&(e.media=e.media.map((e=>({...e,...this.peer._offerIce}))),i=!0),this._context.pcKillSwitch.sld_fmtp_opus_add&&(e.media=e.media.map((e=>{if("audio"===e.type){const t="sendonly"===e.direction;SDPTools.decorateOpusConfig(e,t?this._context.audioProfileManager:void 0)}return e})),i=!0),this._context.pcKillSwitch.sld_rtcpfb_rrtr_add&&(e.media=e.media.map((e=>(!isRRTRSupported||"audio"!==e.type&&"video"!==e.type||SDPTools.addRRTR(e),e))),i=!0),i?lib.write(e):t}generateAnswer(e){const t=[];return e.media.forEach((e=>{if("application"===e.type){DCHECK(void 0!==e.mid,"should always have mid in mline",e);let i=this._midMap.get(e.mid);return i||(i=this.generateDCAnswer(e),this._midMap.set(e.mid,i)),void t.push({...i})}const i=`${e.mid}`;DCHECK(i,`No MID in offer m-line: ${e}`);let r=this._midMap.get(i);r||(this.logger.info("generateInactiveAnswerMLine","mid: %o, mLine: %o",e.mid,e),r=this.generateInactiveAnswerMLine(e)),t.push(r)})),this.peer.createAnswerSdp(t,e.groups)}generateInactiveAnswerMLine(e){return{...e,...this.peer._answerIce,direction:"inactive"}}generateDCAnswer(e){const t={...e,...this.peer._answerIce,sctpmap:{sctpmapNumber:5e3,app:"webrtc-datachannel",maxMessageSize:262144}};return isFirefox&&(delete t.bundleOnly,t.port=9),t}destroy(){super.destroy(),this._pqueue.destroy(),this._applyQueue.destroy(),this._createQueue.destroy()}}function highPLock(e,t,i){const r=i.value;return i.value=async function(...e){const i=this.logger;i.info("SDP Lock","pending task %o",t);const o=await this._pqueue.enqueue(0);i.info("SDP Lock","running task %o",t);try{return await(null==r?void 0:r.apply(this,e))}finally{i.info("SDP Lock","unlocking by task %o",t),o()}},i}function lowPLock(e,t,i){const r=i.value;return i.value=async function(...e){const i=this.logger;i.info("SDP Lock","pending task %o",t);const o=await this._pqueue.enqueue(1);i.info("SDP Lock","running task %o",t);try{return await(null==r?void 0:r.apply(this,e))}finally{i.info("SDP Lock","unlocking by task %o",t),o()}},i}__decorateClass$8([highPLock],StandardHandler.prototype,"create",1),__decorateClass$8([lowPLock],StandardHandler.prototype,"apply",1);const SDPTools={decorateOpusConfig(e,t){if(!e)return;const i=null==e?void 0:e.rtp.find((e=>"opus"===e.codec));if(!i||!e.fmtp)return;const r=e.fmtp.find((e=>e.payload===i.payload));r&&(t&&(r.config=t.getOpusConfigStr(r.config)),r.config=addStereo(r.config))},removeRtxInMLine(e){var t;if(!e)return;const i=[];e.rtp=e.rtp.filter((e=>("rtx"===e.codec&&i.push(e.payload),"rtx"!==e.codec))),e.fmtp=e.fmtp.filter((e=>i.includes(e.payload))),e.payloads=null==(t=e.payloads)?void 0:t.split(" ").filter((e=>!i.includes(parseInt(e)))).join(" ")},removeExtSdesMid(e){var t;e&&(e.ext=null==(t=e.ext)?void 0:t.filter((e=>!e.uri.includes("sdes:mid"))))},selectCC(e,t){var i,r,o,s;e&&("tcc"===t?(e.ext=null==(i=e.ext)?void 0:i.filter((e=>-1===e.uri.indexOf("abs-send-time"))),e.rtcpFb=null==(r=e.rtcpFb)?void 0:r.filter((e=>"goog-remb"!==e.type))):"remb"===t&&(e.rtcpFb=null==(o=e.rtcpFb)?void 0:o.filter((e=>"transport-cc"!==e.type)),e.ext=null==(s=e.ext)?void 0:s.filter((e=>-1===e.uri.indexOf("transport")))))},addRRTR(e){e&&e.rtp.forEach((t=>{e.rtcpFb||(e.rtcpFb=[]),e.rtcpFb.find((e=>e.payload===t.payload&&"rrtr"===e.type))||e.rtcpFb.push({payload:t.payload,type:"rrtr"})}))},removeRtpStreamId(e){e&&Array.isArray(e.ext)&&(e.ext=e.ext.filter((e=>"urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id"!==e.uri)))},decorateSpsPpsIdrInKeyframe(e){if(!e)return;const t=e.rtp.filter((e=>"H264"===e.codec));t.length&&e.fmtp&&e.fmtp.forEach((e=>{t.find((t=>t.payload===e.payload))&&(e.config+=";sps-pps-idr-in-keyframe=1")}))},removeExtVideoOrientation(e){e&&Array.isArray(e.ext)&&(e.ext=e.ext.filter((e=>!e.uri.includes("video-orientation"))))},removeExtFramemarking(e){e&&Array.isArray(e.ext)&&(e.ext=e.ext.filter((e=>!e.uri.includes("framemarking"))))}};class PriorityQueue{constructor(){__publicField(this,"queue",[]),__publicField(this,"processing",!1)}async enqueue(e=0){const{promise:t,resolve:i}=promiseWithResolves(),r={priority:e,resolve:i},o=this.queue.findIndex((t=>t.priority>e));return-1===o?this.queue.push(r):this.queue.splice(o,0,r),this.tryProcess(),await t,this.processing=!0,()=>{this.processing=!1,this.tryProcess()}}destroy(){this.queue.forEach((({resolve:e})=>{e()})),this.queue=[],this.processing=!1}tryProcess(){if(this.processing)return;const e=this.queue.shift();e&&e.resolve()}}function promiseWithResolves(){let e,t;const i=new Promise(((i,r)=>{e=i,t=r}));if(!e||!t)throw Error("Broken Implement of Promise");return{promise:i,resolve:e,reject:t}}const addStereo=e=>{const t={};return e.split(";").forEach((e=>{const[i,r]=e.split("=");i&&r&&(t[i]=r)})),t["sprop-stereo"]=1,t.stereo=1,Object.keys(t).map((e=>`${e}=${t[e]}`)).join(";")},createHandler=(e,t)=>e.enableFallbackHandler?new FallbackHandler(e,t):e.enableStandardHandler?new StandardHandler(e,t):isFirefox?new FirefoxHandler(e,t):new ChromeHandler(e,t),ReconnectReasonMap={[InternalReconnectReason.ICE_FAILED]:ReconnectReason.ICE_FAILED,[InternalReconnectReason.DC_ERROR]:ReconnectReason.ICE_FAILED,[InternalReconnectReason.DC_CLOSE]:ReconnectReason.ICE_FAILED,[InternalReconnectReason.NODE_CHANGE]:ReconnectReason.NODE_CHANGE,[InternalReconnectReason.NOTIFY_RECONNECT]:ReconnectReason.NOTIFY_RECONNECT,[InternalReconnectReason.JOIN_TIMEOUT]:ReconnectReason.JOIN_TIMEOUT};class SignalingManager extends EnhancedEventEmitter{constructor(e){super(),__publicField(this,"_connectionManager"),__publicField(this,"_dataChannelSignal"),__publicField(this,"_state"),__publicField(this,"_connectionLostTimer"),__publicField(this,"_isReconnecting",!1),__publicField(this,"logger"),this._ctx=e,this.logger=new Logger$1("SignalingManager",1,e.id),this.logger.info("constructor","invoke"),this._connectionManager=new ConnectionManager(e),this._addConnectorHandler()}connect(){return this.isConnected()?Promise.resolve():new Promise(((e,t)=>{this._connectionManager.once("connected",(()=>e())),this._connectionManager.once("disconnected",t),this._connectionManager.startup()}))}reconnect(e,t){this._connectionManager.reconnect(e,t)}sendSignaling(e,t,i,r){if(!this._dataChannelSignal)throw new SDKError(ErrorCode.NOT_CONNECTED_YET,"signaling channel is not connected");return this._dataChannelSignal.sendSignaling(e,t,i,r)}sendP2PMessage(e,t){if(!this._dataChannelSignal)throw new SDKError(ErrorCode.NOT_CONNECTED_YET,"signaling channel is not connected");return this._dataChannelSignal.sendP2PMessage(e,t)}destroy(){var e,t;this.logger.info("destroy()"),this._clearConnectionLostTimer(),this._connectionManager.shotdown(),null==(e=this._ctx.handler)||e.destroy(),this._ctx.handler=void 0,null==(t=this._dataChannelSignal)||t.destroy(),this._state&&this._setState(ConnectionState.CONNECTION_STATE_DISCONNECTED),this.removeAllListeners()}isConnected(){return this._state===ConnectionState.CONNECTION_STATE_CONNECTED||this._state===ConnectionState.CONNECTION_STATE_RECONNECTED}isReconnecting(){return this._state===ConnectionState.CONNECTION_STATE_CONNECTING||this._state===ConnectionState.CONNECTION_STATE_RECONNECTING}_setState(e,t){if(this._state===e)return;this._state=e;const i={state:e};t&&(i.reason=ReconnectReasonMap[t]||ReconnectReason.ICE_FAILED),this.safeEmit(StateEvent.ON_CONNECTION_STATE_CHANGE,i)}_addConnectorHandler(){this._connectionManager.on("connected",(e=>{var t;this.logger.info("connectStateChange","connected"),this._clearConnectionLostTimer(),null==(t=this._dataChannelSignal)||t.destroy(),this._ctx.peerConnection=e.pc,this._ctx.handler=createHandler(this._ctx,e.pc),this._dataChannelSignal=e.signaling,this._addSignalEventHandler(),this._setState(this._isReconnecting?ConnectionState.CONNECTION_STATE_RECONNECTED:ConnectionState.CONNECTION_STATE_CONNECTED)})),this._connectionManager.on("disconnected",(e=>{this._clearConnectionLostTimer(),this._setState(ConnectionState.CONNECTION_STATE_DISCONNECTED),this.logger.error("connectStateChange","disconnected. %o",e.message),this._isReconnecting&&this.safeEmit(StateEvent.ON_RECONNECT_FAILED)})),this._connectionManager.on("connecting",(()=>{this._isReconnecting=!1,this._ctx.handler=void 0,this._setState(ConnectionState.CONNECTION_STATE_CONNECTING),this.logger.info("connectStateChange","connecting")})),this._connectionManager.on("reconnecting",(e=>{this._setState(ConnectionState.CONNECTION_STATE_DISCONNECTED,e),this._connectionLostTimer||(this._connectionLostTimer=setTimeout((()=>{this.safeEmit(StateEvent.ON_CONNECTION_STATE_CHANGE,{state:ConnectionState.CONNECTION_STATE_LOST})}),1e4)),this._isReconnecting=!0,this._ctx.handler=void 0,this._setState(ConnectionState.CONNECTION_STATE_RECONNECTING,e),this.logger.warn("connectStateChange","reconnecting")})),this._connectionManager.on("connectWidthTcp",(()=>{this.safeEmit(StateEvent.CONNECT_WITH_TCP)})),["__onGetIceConfigHook","__onIceConnectSuccessHook","__onConnectSuccessHook"].forEach((e=>{this._connectionManager.on(e,((...t)=>this.emit(e,...t)))}))}_clearConnectionLostTimer(){this._connectionLostTimer&&(clearTimeout(this._connectionLostTimer),delete this._connectionLostTimer)}_addSignalEventHandler(){var e,t;[SignalEvent.ON_ADD_STREAM,SignalEvent.ON_ADD_STREAM_LIST,SignalEvent.ON_REMOVE_STREAM,SignalEvent.ON_REMOVE_STREAM_LIST,SignalEvent.USER_CONNECTION,SignalEvent.USER_CONNECTION_LIST,SignalEvent.USER_DISCONNECTION,SignalEvent.USER_DISCONNECTION_LIST,SignalEvent.ON_UPDATE_STREAM_ATTRIBUTES,SignalEvent.ON_UPDATE_ROOM_ATTRIBUTES,SignalEvent.ON_PUSH_TRACK,SignalEvent.ON_REMOVE_TRACK,SignalEvent.ON_CUSTOM_MESSAGE,SignalEvent.USER_MESSAGE_RECEIVED_OUTSIDE_ROOM,SignalEvent.USER_BINARY_MESSAGE_RECEIVED_OUTSIDE_ROOM,SignalEvent.USER_MESSAGE_RECEIVED,SignalEvent.USER_BINARY_MESSAGE_RECEIVED,SignalEvent.POST_PROCESSING_MESSAGE,SignalEvent.ON_USER_TOKEN_WILL_EXPIRE,SignalEvent.ON_TOKEN_PUBLISH_PRIVILEGE_WILL_EXPIRE,SignalEvent.ON_TOKEN_PUBLISH_PRIVILEGE_DID_EXPIRED,SignalEvent.ON_TOKEN_SUBSCRIBE_PRIVILEGE_WILL_EXPIRE,SignalEvent.ON_TOKEN_SUBSCRIBE_PRIVILEGE_DID_EXPIRED,SignalEvent.STREAM_CONTROL_MESSAGE,SignalEvent.ENGINE_CONTROL_MESSAGE,SignalEvent.ON_UPDATE_USER_ATTRIBUTES,SignalEvent.ON_SPEAKER_CHANGE,SignalEvent.ON_STREAM_FAILED,SignalEvent.ON_FORWARD_DST_ROOM_USER_KICK,SignalEvent.ON_STREAM_PULL_STATE_CHANGED,SignalEvent.ON_STREAM_PUSHED_BY_OTHER,MediaServerSignalEvent.RSCP,MediaServerSignalEvent.RTT,MediaServerSignalEvent.SSC].forEach((e=>{var t;null==(t=this._dataChannelSignal)||t.on(e,(t=>{this.safeEmit(e,t)}))})),null==(e=this._dataChannelSignal)||e.on(SignalEvent.NODE_CHANGE,(e=>{this._connectionManager.reconnectByNodeChange(e)})),null==(t=this._dataChannelSignal)||t.on(SignalEvent.ON_NOTIFY_RECONNECT,(()=>{this._connectionManager.reconnect(InternalReconnectReason.NOTIFY_RECONNECT)}))}}var UserRole=(e=>(e.NORMAL_USER="normalUser",e.SILENT_USER="silentUser",e))(UserRole||{});class EngineVideoProfile{constructor(e){__publicField(this,"_captureDeviceId"),__publicField(this,"_contentHint"),__publicField(this,"_videoCaptureConf",{...defaultVideoEncoderConfig}),__publicField(this,"_mainPreferCodec"),__publicField(this,"_screenPreferCodec"),__publicField(this,"_remoteVideoConfig",new Map),__publicField(this,"_remoteSimulcastStreamType",new Map),__publicField(this,"_simulcastMode",VideoSimulcastMode.VIDEO_ONLY_ONE),__publicField(this,"_highVideoEncodeConf",videoCaptureConf2EncodeConf(defaultVideoEncoderConfig)),__publicField(this,"_midVideoEncodeConf"),__publicField(this,"_lowVideoEncodeConf"),__publicField(this,"_screenEncodeConfig",defaultScreenEncoderConfig),__publicField(this,"_invalidVideoEncodeConf"),__publicField(this,"activeSimStreams",[]),__publicField(this,"_logger"),__publicField(this,"_apiVersion"),this._ctx=e,this._logger=new Logger$1("EngineVideoProfile",1,e.id)}setCaptureDeviceId(e){this._captureDeviceId=e}setCaptureConfig(e){this._videoCaptureConf={...this._videoCaptureConf,...e}}getCaptureConfig(e){e=e||this._captureDeviceId;const t={...this._videoCaptureConf};return"user"===e||"environment"===e||"left"===e||"right"===e?(delete t.deviceId,t.facingMode=e):e&&(!isDingTalk||isIOS?t.deviceId={exact:e}:delete t.deviceId),t}getContentHint(){return this._contentHint}getPreferCodec(e){return e?this._screenPreferCodec:this._mainPreferCodec}setRemoteUserVideoConfig(e,t){"object"==typeof t?this._remoteVideoConfig.set(e,t):this._remoteSimulcastStreamType.set(e,t)}getSubLayer(e,t){var i,r;const o=this._remoteSimulcastStreamType.get(e.userId),s=this._remoteVideoConfig.get(e.userId);if(o){const{videoDescriptions:t,subVideoDescriptions:s}=e.attributes||{},n=Array.isArray(s)?s:t;let a;return 1===n.length?a=0:2===n.length?a=o===SimulcastStreamType.VIDEO_STREAM_HIGH?0:1:n.length>=3&&(a={[SimulcastStreamType.VIDEO_STREAM_HIGH]:0,[SimulcastStreamType.VIDEO_STREAM_MID]:1,[SimulcastStreamType.VIDEO_STREAM_LOW]:2}[o]),{spatialLayer:(a&&(null==(i=n[a])?void 0:i.video_index))??a??0,spatialSubLayer:(a&&(null==(r=n[a])?void 0:r.sub_index))??a??-1}}return s?getSubLayerByVideoConfig(s,e):t?getSubLayerByVideoConfig(t,e):void 0}getSimulcastMode(){return this._simulcastMode}async setSimulcastMode(e,t){var i,r;if(!isSimulcastSupported())throw new SDKError(ErrorCode.NOT_SUPPORTED,"Simulcast is not supported");if(this._simulcastMode!==e){if(null==t?void 0:t.hasPublished){if((null==(i=t.localStream)?void 0:i.videoHasPublish)||(null==(r=t.localStream)?void 0:r.audioHasPublish))throw new SDKError(ErrorCode.SET_SIMULCAST_FAILED,"Cannot change simulcast mode after publishing the video streams");this._logger.print("setSimulcastMode()","change simulcast mode and unpublish."),await t.unpublish()}this._simulcastMode=e,e!==VideoSimulcastMode.VIDEO_ONLY_ONE&&this._autoGenerateSubVideoEncodeConfig()}}closeSimulcast(){this._simulcastMode=VideoSimulcastMode.VIDEO_ONLY_ONE}async setVideoEncodeConfigPolyfill(e){if(Array.isArray(e)){checkVideoEncoderConfig(e);const[t,...i]=e;this.setVideoEncodeConfig(t),await this.setSubVideoEncodeConfig(i.reverse())}else this.setVideoEncodeConfig(e)}setVideoEncodeConfig(e){checkVideoEncoderConfig([e]);const t=this._midVideoEncodeConf||this._lowVideoEncodeConf;t&&getResolution(t)>=getResolution(e)?(this._logger.warn("setVideoEncodeConfig","smaller then substream"),this._invalidVideoEncodeConf=videoCaptureConf2EncodeConf(e),e=t):delete this._invalidVideoEncodeConf;const{preferCodecName:i,...r}={...e};checkSupportedConstraints(r),this._logger.print("setVideoEncodeConfig","update encode config",e),this._highVideoEncodeConf=videoCaptureConf2EncodeConf(e),this._contentHint=e.contentHint,this._mainPreferCodec=i,this._logger.print("setVideoEncodeConfig","update capture config",r),this._videoCaptureConf=r}async setSubVideoEncodeConfig(e,t,i){var r,o;if(this._logger.print("setSubVideoEncodeConfig","%o, published=%s",e,null==t?void 0:t.hasPublished),e&&e.length>0){checkVideoEncoderConfig(e),e.sort(((e,t)=>getResolution(e)-getResolution(t)));const s=this._invalidVideoEncodeConf||this._highVideoEncodeConf,n=e[e.length-1];if(getResolution(n)>=getResolution(s))throw new SDKError(ErrorCode.SET_SIMULCAST_FAILED,"The resolution cannot exceed the mainstream");if((null==t?void 0:t.hasPublished)&&e.length!==this._getSubLayers().length){if((null==(r=t.localStream)?void 0:r.videoHasPublish)||(null==(o=t.localStream)?void 0:o.audioHasPublish))throw new SDKError(ErrorCode.SET_SIMULCAST_FAILED,"Cannot change the number of substreams after publishing the video streams");await t.unpublish()}e.length>2&&(reportRtcInvokeStatus(this._ctx.id,"simulcast_over_limit","setLocalSimulcastMode: You can set parameters for up to 2 streams"),warnDevelopers("setLocalSimulcastMode: You can set parameters for up to 2 streams"));const[a,d]=e;a&&(checkVideoConfigQuotient(s,a),this._lowVideoEncodeConf=videoCaptureConf2EncodeConf(a)),d&&(checkVideoConfigQuotient(s,d),this._midVideoEncodeConf=videoCaptureConf2EncodeConf(d)),this._invalidVideoEncodeConf&&(this.setVideoEncodeConfig(this._invalidVideoEncodeConf),await(null==i?void 0:i.updateVideoCaptureConfig(this._ctx.videoProfile.getCaptureConfig())))}else this._autoGenerateSubVideoEncodeConfig()}genVideoDescriptions(e){var t;const i=[];let r=[];const o=[],s=[];let{width:n,height:a,frameRate:d,maxKbps:c}=e.videoEncodeConfig[0];n=constraints2number(n),a=constraints2number(a);const l=null==(t=e.videoTrack)?void 0:t.preprocessingTrack,{width:u,height:_,frameRate:h}=(null==l?void 0:l.getSettings())??{};u&&(n=Math.floor(u)),_&&(a=Math.floor(_)),h&&(d=Math.floor(h)),("number"!=typeof d||Number.isNaN(d))&&(d=30),i.push({width:n,height:a,framerate:d,maxkbps:c,rid:"0"}),o.unshift({maxBitrate:1e3*c,rid:"0",maxFramerate:d});const{serverConfig:p}=this._ctx;if(!(e.isScreen||this._simulcastMode===VideoSimulcastMode.VIDEO_ONLY_ONE||isFirefox&&"VP8"!==(null==p?void 0:p.videoCodec))){const e=getSimulcastLayers(n,a);if(e>1){const t=this._getSubVideoEncodeConfig(e,{width:n,height:a});this._logger.info("simulcast() ","simulcastLayers: %o",t),s.push(!0),t.forEach(((e,t)=>{const r={maxBitrate:1e3*e.maxkbps,scaleResolutionDownBy:e.scaleResolutionDownBy,rid:`${t+1}`,maxFramerate:e.frameRate};o.unshift(r),i.push({width:e.width,height:e.height,framerate:e.frameRate,maxkbps:e.maxkbps,rid:`${t+1}`}),s.push(!0)})),(null==p?void 0:p.simulcastOnDemand)&&(r=i.map(((e,t)=>({...e,video_index:t,sub_index:t}))))}}return(null==p?void 0:p.e2eFeedback)&&(r=i.map(((e,t)=>({...e,video_index:t,sub_index:t})))),{videoDescriptions:i,subVideoDescriptions:r,sendEncodings:o,activeSimulcastStreams:s}}getVideoEncodeConfig(){return[this._highVideoEncodeConf,this._midVideoEncodeConf,this._lowVideoEncodeConf].filter((e=>e))}setScreenEncodeConfig(e){this._screenEncodeConfig=e}getScreenEncodeConfig(){return this._screenEncodeConfig}checkSimulcastApiVersion(e){if(this._apiVersion){if(this._apiVersion!==e){const e=`mixing old and new apis, please use ${"new"===this._apiVersion?"setLocalSimulcastMode/setRemoteSimulcastStreamType":"enableSimulcastMode/setRemoteVideoConfig"} instead.`;throw reportRtcInvokeStatus(this._ctx.id,"mixingOldAndNewApis",e),new SDKError(ErrorCode.MIXING_OLD_AND_NEW_APIS,e)}}else this._apiVersion=e}destroy(){this._videoCaptureConf=defaultVideoEncoderConfig,this._highVideoEncodeConf=videoCaptureConf2EncodeConf(defaultVideoEncoderConfig),delete this._invalidVideoEncodeConf,this._remoteVideoConfig.clear(),this._remoteSimulcastStreamType.clear()}_autoGenerateSubVideoEncodeConfig(){this._logger.print("_autoGenerateSubVideoEncodeConfig()","generate low stream.");const e=this._highVideoEncodeConf,t=constraints2number(e.width),i=constraints2number(e.height),r=Math.min(t,i)/90;this._lowVideoEncodeConf={width:Math.floor(t/r),height:Math.floor(i/r),maxKbps:100,frameRate:10}}_getSubLayers(){const e=[];return this._midVideoEncodeConf&&e.push(this._midVideoEncodeConf),this._lowVideoEncodeConf&&e.push(this._lowVideoEncodeConf),e}_getSubVideoEncodeConfig(e,t){return this._getSubLayers().slice(1-e).map((e=>{if(e.width>e.height&&t.width<t.height||e.width<e.height&&t.width>t.height){const t=e.width;e.width=e.height,e.height=t}const i=constraints2number(e.width),r=constraints2number(e.height),o=Math.max(t.width/i,t.height/r);return{width:Math.floor(t.width/o),height:Math.floor(t.height/o),scaleResolutionDownBy:o,frameRate:constraints2number(e.frameRate)||15,maxkbps:e.maxKbps||600}}))}__autoResetVideoEncoderConfig(e){const t=autoResetVideoEncoderConfig(this.getVideoEncodeConfig(),e);t&&(this.setVideoEncodeConfigPolyfill(t),this._logger.print("autoResetVideoEncoderConfig() result",JSON.stringify(t)),reportRtcInvokeStatus(this._ctx.id,"autoResetVideoEncoderConfig",JSON.stringify(t)))}}class RTSMessageLimiter{constructor(e){__publicField(this,"_sendTimes",[]),__publicField(this,"_bufferSizeLimit"),__publicField(this,"_totalSizeLimitPerSecond"),__publicField(this,"_limitModeInterval"),__publicField(this,"_limitModeQPS"),__publicField(this,"_interval"),__publicField(this,"_qps"),this.setLimitMode(e)}setLimitMode(e){e===RTS_MODE.LIMIT_MODE?(this._bufferSizeLimit=1,this._totalSizeLimitPerSecond=30720,this._limitModeInterval=1e3,this._limitModeQPS=60):(this._bufferSizeLimit=64,delete this._totalSizeLimitPerSecond,delete this._limitModeInterval,delete this._limitModeQPS)}setQPS(e,t){this._interval=e,this._qps=t}check(e){const t=Date.now(),i=checkBufferSize(e,this._bufferSizeLimit);if("number"==typeof this._totalSizeLimitPerSecond){if(this._sendTimes.reduce(((e,i)=>t-i.ts<1e3?e+i.size:e),0)+i>this._totalSizeLimitPerSecond)throw new SDKError(ErrorCode.USER_MESSAGE_EXCEED_QPS,`user message exceed total size(${this._totalSizeLimitPerSecond})`)}const r=this._limitModeInterval??this._interval,o=this._limitModeQPS??this._qps;if("number"==typeof r&&"number"==typeof o)if(this._sendTimes.length<o)this._sendTimes.push({ts:t,size:i});else{if(t-this._sendTimes[0].ts<r)throw new SDKError(ErrorCode.USER_MESSAGE_EXCEED_QPS,`user message exceed qps(${o})`);this._sendTimes.splice(0,1),this._sendTimes.push({ts:t,size:i})}}}const encodedJs="dmFyIF9fZGVmUHJvcD1PYmplY3QuZGVmaW5lUHJvcGVydHksX19kZWZOb3JtYWxQcm9wPSh0LGUsbik9PmUgaW4gdD9fX2RlZlByb3AodCxlLHtlbnVtZXJhYmxlOiEwLGNvbmZpZ3VyYWJsZTohMCx3cml0YWJsZTohMCx2YWx1ZTpufSk6dFtlXT1uLF9fcHVibGljRmllbGQ9KHQsZSxuKT0+KF9fZGVmTm9ybWFsUHJvcCh0LCJzeW1ib2wiIT10eXBlb2YgZT9lKyIiOmUsbiksbik7IWZ1bmN0aW9uKCl7InVzZSBzdHJpY3QiO2NvbnN0IHQ9e2dldE5BTFVuaXRzKGUsbj0hMSl7aWYoZS5sZW5ndGgtZS5wb3NpdGlvbjw0KXJldHVybltdO2NvbnN0e3Bvc2l0aW9uOnJ9PWU7cmV0dXJuIDE9PT1lLmdldEludDMyKHIpfHwwPT09ZS5nZXRJbnQxNihyKSYmMT09PWUuZ2V0SW50OChyKzIpP3QuZ2V0QW5uZXhiTmFscyhlLG4pOnQuZ2V0QXZjY05hbHMoZSxuKX0sZ2V0QW5uZXhiTmFscyhlLG4pe2NvbnN0IHI9W107bGV0IGk9dC5nZXRIZWFkZXJQb3NpdGlvbkFubmV4QihlKSxzPWkucG9zLG89cztmb3IoO3M8ZS5sZW5ndGgtNDspe2NvbnN0IGE9bmV3IFVpbnQ4QXJyYXkoZS5idWZmZXIuc2xpY2UocyxzK2kuaGVhZGVyTGVuZ3RoKSk7aS5wb3M9PT1lLnBvc2l0aW9uJiZlLnNraXAoaS5oZWFkZXJMZW5ndGgpLGk9dC5nZXRIZWFkZXJQb3NpdGlvbkFubmV4QihlKSxvPWkucG9zO2NvbnN0IHA9e2hlYWRlcjphLGJvZHk6bmV3IFVpbnQ4QXJyYXkoZS5idWZmZXIuc2xpY2UocythLmJ5dGVMZW5ndGgsbykpLHR5cGU6LTF9O24/dC5hbmFseXNlSDI2NU5hbChwKTp0LmFuYWx5c2VOYWwocCksKHAudHlwZTw9OXx8biYmcC50eXBlPD00MCkmJjAhPT1wLnR5cGUmJnIucHVzaChwKSxlLnNraXAoby1lLnBvc2l0aW9uKSxzPW99cmV0dXJuIHJ9LGdldEF2Y2NOYWxzKGUsbil7Y29uc3Qgcj1bXTtmb3IoO2UucG9zaXRpb248ZS5sZW5ndGgtNDspe2NvbnN0IGk9ZS5nZXRJbnQzMihlLnBvc2l0aW9uKTtpZighKGUubGVuZ3RoLWUucG9zaXRpb24+PWkpKWJyZWFrO3tjb25zdCBzPW5ldyBVaW50OEFycmF5KGUuYnVmZmVyLnNsaWNlKGUucG9zaXRpb24sZS5wb3NpdGlvbis0KSk7ZS5za2lwKDQpO2NvbnN0IG89bmV3IFVpbnQ4QXJyYXkoZS5idWZmZXIuc2xpY2UoZS5wb3NpdGlvbixlLnBvc2l0aW9uK2kpKTtlLnNraXAoaSk7Y29uc3QgYT17aGVhZGVyOnMsYm9keTpvLHR5cGU6LTF9O24/dC5hbmFseXNlSDI2NU5hbChhKTp0LmFuYWx5c2VOYWwoYSksYS50eXBlPD05JiYwIT09YS50eXBlJiZyLnB1c2goYSl9fXJldHVybiByfSxhbmFseXNlTmFsKHQpe2NvbnN0IGU9MzEmdC5ib2R5WzBdO3N3aXRjaCh0LnR5cGU9ZSxlKXtjYXNlIDE6dC5uZHI9ITA7YnJlYWs7Y2FzZSA1OnQuaWRyPSEwO2JyZWFrO2Nhc2UgNjp0LnNlaT0hMDticmVhaztjYXNlIDc6dC5zcHM9ITA7YnJlYWs7Y2FzZSA4OnQucHBzPSEwfX0sYW5hbHlzZUgyNjVOYWwodCl7Y29uc3QgZT0oMTI2JnQuYm9keVswXSk+PjE7c3dpdGNoKHQudHlwZT1lLGUpe2Nhc2UgMzk6Y2FzZSA0MDp0LnNlaT0hMH19LGdldEhlYWRlclBvc2l0aW9uQW5uZXhCKHQpe2xldCBlPXQucG9zaXRpb24sbj0wO2NvbnN0IHI9dC5sZW5ndGg7Zm9yKDszIT09biYmNCE9PW4mJmU8ci00OykwPT09dC5nZXRJbnQxNihlKT8xPT09dC5nZXRJbnQxNihlKzIpP249NDoxPT09dC5nZXRJbnQ4KGUrMik/bj0zOmUrKzplKys7cmV0dXJuIGU9PT1yLTQmJigwPT09dC5nZXRJbnQxNihlKT8xPT09dC5nZXRJbnQxNihlKzIpP249NDplPXI6KGUrKywwPT09dC5nZXRJbnQxNihlKSYmMT09PXQuZ2V0SW50OChlKT9uPTM6ZT1yKSkse3BvczplLGhlYWRlckxlbmd0aDpufX0saXNIMjY1VmlkZW9GcmFtZSh0KXt2YXIgZSxuO3JldHVybigobnVsbD09KG49bnVsbD09KGU9dC5nZXRNZXRhZGF0YSk/dm9pZCAwOmUuY2FsbCh0KSk/dm9pZCAwOm4ubWltZVR5cGUpfHwiIikudG9Mb3dlckNhc2UoKS5pbmNsdWRlcygiaDI2NSIpfX07Y2xhc3MgZXtjb25zdHJ1Y3Rvcih0KXtfX3B1YmxpY0ZpZWxkKHRoaXMsIl9wb3NpdGlvbiIsMCksX19wdWJsaWNGaWVsZCh0aGlzLCJfZGF0YXZpZXciKSx0aGlzLl9kYXRhdmlldz1uZXcgRGF0YVZpZXcodCl9Z2V0IGxlbmd0aCgpe3JldHVybiB0aGlzLmJ1ZmZlci5ieXRlTGVuZ3RofWdldCBidWZmZXIoKXtyZXR1cm4gdGhpcy5fZGF0YXZpZXcuYnVmZmVyfXNldCBwb3NpdGlvbih0KXt0aGlzLl9wb3NpdGlvbj10fWdldCBwb3NpdGlvbigpe3JldHVybiB0aGlzLl9wb3NpdGlvbn1iYWNrKHQpe3RoaXMucG9zaXRpb24tPXR9Z2V0VWludDgodCl7cmV0dXJuIHRoaXMuX2RhdGF2aWV3LmdldFVpbnQ4KHQpfWdldEludDgodCl7cmV0dXJuIHRoaXMuX2RhdGF2aWV3LmdldEludDgodCl9Z2V0SW50MTYodCl7cmV0dXJuIHRoaXMuX2RhdGF2aWV3LmdldEludDE2KHQpfWdldFVpbnQxNih0KXtyZXR1cm4gdGhpcy5fZGF0YXZpZXcuZ2V0VWludDE2KHQpfWdldFVpbnQzMih0KXtyZXR1cm4gdGhpcy5fZGF0YXZpZXcuZ2V0VWludDMyKHQpfWdldEludDMyKHQpe3JldHVybiB0aGlzLl9kYXRhdmlldy5nZXRJbnQzMih0KX1za2lwKHQpe2NvbnN0IG49TWF0aC5mbG9vcih0LzQpLHI9dCU0O2ZvcihsZXQgaT0wO2k8bjtpKyspZS5yZWFkQnl0ZSh0aGlzLDQpO3I+MCYmZS5yZWFkQnl0ZSh0aGlzLHIpfXN0YXRpYyByZWFkQnl0ZSh0LGUsbil7bGV0IHI7c3dpdGNoKGUpe2Nhc2UgMTpyPW4/dC5nZXRJbnQ4KHQucG9zaXRpb24pOnQuZ2V0VWludDgodC5wb3NpdGlvbik7YnJlYWs7Y2FzZSAyOnI9bj90LmdldEludDE2KHQucG9zaXRpb24pOnQuZ2V0VWludDE2KHQucG9zaXRpb24pO2JyZWFrO2Nhc2UgMzppZihuKXRocm93IG5ldyBFcnJvcigibm90IHN1cHBvcnRlZCBmb3IgcmVhZEJ5dGUgMyIpO3I9dC5nZXRVaW50OCh0LnBvc2l0aW9uKTw8MTYscnw9dC5nZXRVaW50OCh0LnBvc2l0aW9uKzEpPDw4LHJ8PXQuZ2V0VWludDgodC5wb3NpdGlvbisyKTticmVhaztjYXNlIDQ6cj1uP3QuZ2V0SW50MzIodC5wb3NpdGlvbik6dC5nZXRVaW50MzIodC5wb3NpdGlvbik7YnJlYWs7Y2FzZSA4OmlmKG4pdGhyb3cgbmV3IEVycm9yKCJub3Qgc3VwcG9ydGVkIGZvciByZWFkQm9keSA4Iik7cj10LmdldFVpbnQzMih0LnBvc2l0aW9uKTw8MzIscnw9dC5nZXRVaW50MzIodC5wb3NpdGlvbis0KTticmVhaztkZWZhdWx0OnI9IiJ9cmV0dXJuIHQucG9zaXRpb24rPWUscn1yZWFkVWludDgoKXtyZXR1cm4gZS5yZWFkQnl0ZSh0aGlzLDEpfXJlYWRVaW50MTYoKXtyZXR1cm4gZS5yZWFkQnl0ZSh0aGlzLDIpfXJlYWRVaW50MjQoKXtyZXR1cm4gZS5yZWFkQnl0ZSh0aGlzLDMpfXJlYWRVaW50MzIoKXtyZXR1cm4gZS5yZWFkQnl0ZSh0aGlzLDQpfXJlYWRVaW50NjQoKXtyZXR1cm4gZS5yZWFkQnl0ZSh0aGlzLDgpfXJlYWRJbnQ4KCl7cmV0dXJuIGUucmVhZEJ5dGUodGhpcywxLCEwKX1yZWFkSW50MTYoKXtyZXR1cm4gZS5yZWFkQnl0ZSh0aGlzLDIsITApfXJlYWRJbnQzMigpe3JldHVybiBlLnJlYWRCeXRlKHRoaXMsNCwhMCl9d3JpdGVVaW50MzIodCl7cmV0dXJuIG5ldyBVaW50OEFycmF5KFt0Pj4+MjQmMjU1LHQ+Pj4xNiYyNTUsdD4+PjgmMjU1LDI1NSZ0XSl9fXZhciBuPSh0PT4odFt0LmludGVybmFsPTBdPSJpbnRlcm5hbCIsdFt0LmV4dGVybmFsPTFdPSJleHRlcm5hbCIsdFt0LmJ5cGFzcz0yXT0iYnlwYXNzIix0KSkobnx8e30pO2NvbnN0IHI9bmV3IFVpbnQ4QXJyYXkoWzEwOSwxNjcsNTMsMTkwLDEwMyw5MCw3MiwxLDE3MCw4OSw2MywxNjQsMTk0LDE5OSwxOSw4NV0pLGk9bmV3IFVpbnQ4QXJyYXkoWzEwOSwxNjcsNTMsMTkwLDEwMyw5MCw3MiwxLDE3MCw4OSw2MywxNjQsMTk0LDE5OSwxOSw4NF0pLHM9bmV3IFVpbnQ4QXJyYXkoWzMxLDIzOSwzLDUwLDI0MiwxMjAsNzYsODUsMTY5LDQyLDE2MSw5MSw3NSwxODYsMjJdKTtmdW5jdGlvbiBvKHQpe2NvbnN0IGU9W107Zm9yKDt0Pj0yNTU7KXQtPTI1NSxlLnB1c2goMjU1KTtyZXR1cm4gZS5wdXNoKHQpLG5ldyBVaW50OEFycmF5KGUpfWZ1bmN0aW9uIGEodCxlPTApe2xldCBuPTA7Zm9yKDsyNTU9PT10W2VdJiZlPHQuYnl0ZUxlbmd0aDspZSsrLG4rPTI1NTtyZXR1cm4gZTx0LmJ5dGVMZW5ndGgmJihuKz10W2UrK10pLFtuLGVdfWNvbnN0IHA9bmV3IFVpbnQ4QXJyYXkoWzgwLDFdKSxjPWNsYXNze3N0YXRpYyBnZW5lcmF0ZVNFSSh0LGUsbj0hMSl7Y29uc3Qgcz1uZXcgVWludDhBcnJheShbMCwwLDAsMV0pLGE9ZT9wOm5ldyBVaW50OEFycmF5KFs2XSksbD1uZXcgVWludDhBcnJheShbNV0pLGc9Yy5fX3V1aWR8fChuP3I6aSkseT1vKHQuYnl0ZUxlbmd0aCtnLmJ5dGVMZW5ndGgpLGQ9KHQ9Pntjb25zdCBlPVtdO2xldCBuPTA7Zm9yKGNvbnN0IHIgb2YgdCluPj0yJiZyPD0zJiYoZS5wdXNoKDMpLG49MCksMD09PXI/bisrOm49MCxlLnB1c2gocik7cmV0dXJuIG5ldyBVaW50OEFycmF5KGUpfSkodCk7cmV0dXJuIG5ldyBVaW50OEFycmF5KFsuLi5zLC4uLmEsLi4ubCwuLi55LC4uLmcsLi4uZCwxMjhdKX1zdGF0aWMgZGVjb2RlU0VJQm9keSh0LGUpe2NvbnN0IG49KHQ9Pntjb25zdCBlPVtdO2ZvcihsZXQgbj0wO248dC5sZW5ndGg7bisrKXRbbl08PTMmJjA9PT10W24tMV0mJjA9PT10W24tMl18fGUucHVzaCh0W25dKTtyZXR1cm4gbmV3IFVpbnQ4QXJyYXkoZSl9KSh0PXQuc2xpY2UoMCx0Lmxlbmd0aC0xKSk7aWYobi5ieXRlTGVuZ3RoPDIpcmV0dXJuO2xldCBvPTA7Y29uc3QgcD1lPzI6MTtpZig1IT09bltwXSYmMTAwIT09bltwXSlyZXR1cm47bys9MStwO2NvbnN0W2MsbF09YShuLG8pO289bDtsZXQgZz0yO2NvbnN0IHk9bytjO24uYnl0ZUxlbmd0aD49aS5ieXRlTGVuZ3RoJiZjPj1pLmJ5dGVMZW5ndGgmJihuLnNsaWNlKG8sbytpLmJ5dGVMZW5ndGgpLnRvU3RyaW5nKCk9PT1pLnRvU3RyaW5nKCl8fG4uc2xpY2UobyxvK3MuYnl0ZUxlbmd0aCkudG9TdHJpbmcoKT09PXMudG9TdHJpbmcoKSk/KG8rPWkuYnl0ZUxlbmd0aCxnPTEpOm4uYnl0ZUxlbmd0aD49aS5ieXRlTGVuZ3RoJiZjPj1pLmJ5dGVMZW5ndGgmJm4uc2xpY2UobyxvK3IuYnl0ZUxlbmd0aCkudG9TdHJpbmcoKT09PXIudG9TdHJpbmcoKSYmKG8rPXIuYnl0ZUxlbmd0aCxnPTApO3JldHVybnt0eXBlOmcscGF5bG9hZDpuLnNsaWNlKG8seSl9fXN0YXRpYyBwYXJzZUludGVybmFsU0VJKHQpe2NvbnN0IGU9bmV3IE1hcDtsZXQgbj0wO2lmKDA9PT10LnR5cGUpe2Zvcig7dC5wYXlsb2FkLmJ5dGVMZW5ndGgtbj49Mjspe2NvbnN0W3IsaV09YSh0LnBheWxvYWQsbik7bj1pO2NvbnN0W3Msb109YSh0LnBheWxvYWQsbik7aWYobj1vLGUuZ2V0KHIpfHwhKHM8PXQucGF5bG9hZC5ieXRlTGVuZ3RoLW4pKWJyZWFrO2Uuc2V0KHIsdC5wYXlsb2FkLnNsaWNlKG4sbitzKSksbis9c31yZXR1cm4gZX19c3RhdGljIG1ha2VJbnRlcm5hbFNlaSh0KXtjb25zdCBlPVtdO2Zvcihjb25zdFtpLHNdb2YgdCl7Y29uc3QgdD1vKGkpLG49byhzLmJ5dGVMZW5ndGgpO2UucHVzaCh0LG4scyl9Y29uc3Qgbj1lLnJlZHVjZSgoKHQsZSk9PnQrZS5ieXRlTGVuZ3RoKSwwKSxyPW5ldyBVaW50OEFycmF5KG4pO3JldHVybiBlLnJlZHVjZSgoKHQsZSk9PihyLnNldChlLHQpLHQrZS5ieXRlTGVuZ3RoKSksMCkscn19O2xldCBsPWM7X19wdWJsaWNGaWVsZChsLCJfX3V1aWQiKSwidW5kZWZpbmVkIiE9dHlwZW9mIHNlbGYmJiJEZWRpY2F0ZWRXb3JrZXJHbG9iYWxTY29wZSI9PT1zZWxmLmNvbnN0cnVjdG9yLm5hbWUmJnNlbGYuYWRkRXZlbnRMaXN0ZW5lcigicnRjdHJhbnNmb3JtIiwocj0+e2NvbnN0e3RyYW5zZm9ybWVyOml9PXIse3N0cmVhbUlkOnMsc2tpcEZpbHRlcjpvfT1pLm9wdGlvbnMsYT1mdW5jdGlvbih7cG9zdE1lc3NhZ2U6cixza2lwRmlsdGVyOml9KXtyZXR1cm4gbmV3IFRyYW5zZm9ybVN0cmVhbSh7dHJhbnNmb3JtKHMsbyl7Y29uc3QgYT10LmlzSDI2NVZpZGVvRnJhbWUocyk7dC5nZXROQUxVbml0cyhuZXcgZShzLmRhdGEpLGEpLmZvckVhY2goKHQ9PntpZih0LnNlaSl7Y29uc3QgZT1sLmRlY29kZVNFSUJvZHkodC5ib2R5LGEpO2UmJihpfHxlLnR5cGU9PT1uLmV4dGVybmFsKSYmcihlKX19KSksby5lbnF1ZXVlKHMpfX0pfSh7cG9zdE1lc3NhZ2U6dD0+e3NlbGYucG9zdE1lc3NhZ2Uoe3N0cmVhbUlkOnMsbXNnOnR9LFt0LnBheWxvYWQuYnVmZmVyXSl9LHNraXBGaWx0ZXI6b30pO2kucmVhZGFibGUucGlwZVRocm91Z2goYSkucGlwZVRvKHIudHJhbnNmb3JtZXIud3JpdGFibGUpfSkpfSgpOwo=",blob="undefined"!=typeof window&&window.Blob&&new Blob([atob(encodedJs)],{type:"text/javascript;charset=utf-8"});function WorkerWrapper(){let e;try{if(e=blob&&(window.URL||window.webkitURL).createObjectURL(blob),!e)throw"";return new Worker(e)}catch(e){return new Worker("data:application/javascript;base64,"+encodedJs)}finally{!("undefined"!=typeof window&&navigator.userAgent.indexOf("Trident/")>0)&&e&&(window.URL||window.webkitlRL).revokeObjectURL(e)}}var ResetPubSubLockReason=(e=>(e.RECONNECT="ice-reconnect",e.LEAVE="leave_room",e))(ResetPubSubLockReason||{});const DEFAULT_RTS_MODE=RTS_MODE.NORMAL_MODE;class RTCContext{constructor(e,t,i){__publicField(this,"engineDestroyed",!1),__publicField(this,"avSync",!0),__publicField(this,"callId"),__publicField(this,"streamRTT",{}),__publicField(this,"useCloudProxy",!1),__publicField(this,"videoProfile"),__publicField(this,"audioProfileManager"),__publicField(this,"extensionManager"),__publicField(this,"userPriority",new Map),__publicField(this,"expectedIDC"),__publicField(this,"autoPlayPolicy"),__publicField(this,"joinRoomConfig"),__publicField(this,"signalingManager"),__publicField(this,"peerConnection"),__publicField(this,"pubSubLock",new PromiseLock2("pubSubLock")),__publicField(this,"pcKillSwitch",{ctor_sdpsemantics_add:!0,ctor_encodedinsetablestream_add:!0,sld_rtcpfb_rrtr_add:!0,sld_ext_sdesmid_remove:!0,sld_fmtp_sps_add:!0,sld_fmtp_bitrate_add:!0,sld_fmtp_opus_add:!0,sld_iceoption_renomination:!0,...getParameter("PC_KILLSWITCH")}),__publicField(this,"visibility",!0),__publicField(this,"rtsLimiter",{e2e:new RTSMessageLimiter(DEFAULT_RTS_MODE),e2s:new RTSMessageLimiter(DEFAULT_RTS_MODE),boradcast:new RTSMessageLimiter(DEFAULT_RTS_MODE),conf:void 0,rtsMode:DEFAULT_RTS_MODE}),__publicField(this,"serverConfig"),__publicField(this,"mediaParams"),__publicField(this,"subscribeFallbackOption"),__publicField(this,"joinRoomParams"),__publicField(this,"isPreConnection",!1),__publicField(this,"_handler"),__publicField(this,"monitor"),__publicField(this,"enableFallbackHandler",!!getParameter("ENABLE_FALLBACK_HANDLER")),__publicField(this,"enableStandardHandler",!!getParameter("ENABLE_STANDARD_HANDLER")),__publicField(this,"_businessId"),__publicField(this,"_userStreamConfig",new Map),__publicField(this,"_localAudioTrackDumpConfig",{[StreamIndex$1.STREAM_INDEX_MAIN]:{callback:void 0,frameSize:void 0},[StreamIndex$1.STREAM_INDEX_SCREEN]:{callback:void 0,frameSize:void 0}}),__publicField(this,"_remoteAudioTrackDumpConfig",{[StreamIndex$1.STREAM_INDEX_MAIN]:new Map,[StreamIndex$1.STREAM_INDEX_SCREEN]:new Map}),__publicField(this,"_targetCodec"),__publicField(this,"_targetScreenCodec"),__publicField(this,"earMonitorSettings",{[StreamIndex$1.STREAM_INDEX_MAIN]:{position:EarMonitorPosition.NONE,volume:100},[StreamIndex$1.STREAM_INDEX_SCREEN]:{position:EarMonitorPosition.NONE,volume:100}}),__publicField(this,"localVideoTrack"),__publicField(this,"localAudioTrack"),__publicField(this,"publicAudioVolume",new Map),__publicField(this,"_receiveSEIWorker"),this.id=e,this.appId=t,this.monitor=getMonitor(e),this.expectedIDC=null==i?void 0:i.expectedIDC,this.autoPlayPolicy=null==i?void 0:i.autoPlayPolicy,this.audioProfileManager=new AudioProfileManager(t),this.extensionManager=new ExtensionManager(e),this.joinRoomConfig=new JoinRoomConfig(e),this.signalingManager=new SignalingManager(this),this.videoProfile=new EngineVideoProfile(this)}set businessId(e){var t;this._businessId=e,null==(t=this.monitor)||t.set({rtc_business_id:e})}get businessId(){return this._businessId}set handler(e){var t;e&&this.resetPubSubLock("ice-reconnect"),null==(t=this._handler)||t.destroy(),this._handler=e}get handler(){return this._handler}get role(){return this.visibility?UserRole.NORMAL_USER:UserRole.SILENT_USER}set targetCodec(e){e&&[VideoCodecName.H264,VideoCodecName.VP8,VideoCodecName.ByteVC1].forEach((t=>{e.toLowerCase()===t.toLowerCase()&&(this._targetCodec=t)}))}set targetScreenCodec(e){e&&[VideoCodecName.H264,VideoCodecName.VP8,VideoCodecName.ByteVC1].forEach((t=>{e.toLowerCase()===t.toLowerCase()&&(this._targetScreenCodec=t)}))}get targetCodec(){return this._targetCodec}get targetScreenCodec(){return this._targetScreenCodec}resetPubSubLock(e){this.pubSubLock.closeReason=e,this.pubSubLock=new PromiseLock2("pubSubLock")}setUserStreamConf(e,t,i){const r=this._userStreamConfig.get(e)||{},o=r[t]||{};r[t]={...o,...i},this._userStreamConfig.set(e,r)}getRemoteMirrorType(e,t){var i,r;return!!(null==(r=null==(i=this._userStreamConfig.get(e))?void 0:i[t])?void 0:r.mirrorType)}get rtsMode(){return this.rtsLimiter.rtsMode}setRTSMode(e){this.rtsLimiter.e2e.setLimitMode(e),this.rtsLimiter.boradcast.setLimitMode(e),this.rtsLimiter.e2s.setLimitMode(e),this.rtsLimiter.rtsMode=e}setRtsQpsConf(e){this.rtsLimiter.e2e.setQPS(null==e?void 0:e.rts_qps_interval,null==e?void 0:e.rts_e2e_qps_value),this.rtsLimiter.boradcast.setQPS(null==e?void 0:e.rts_qps_interval,null==e?void 0:e.rts_broadcast_qps_value),this.rtsLimiter.e2s.setQPS(null==e?void 0:e.rts_qps_interval,null==e?void 0:e.rts_e2s_qps_value),this.rtsLimiter.conf=e}get receiveSEIWorker(){return this._receiveSEIWorker||(this._receiveSEIWorker=new WorkerWrapper),this._receiveSEIWorker}updatePCKillSwitch(e){this.pcKillSwitch={...this.pcKillSwitch,...e}}destroy(){this.engineDestroyed=!0,this.signalingManager.destroy(),this.userPriority.clear(),this.avSync=!0,this._localAudioTrackDumpConfig={[StreamIndex$1.STREAM_INDEX_MAIN]:{callback:void 0,frameSize:void 0},[StreamIndex$1.STREAM_INDEX_SCREEN]:{callback:void 0,frameSize:void 0}},this._remoteAudioTrackDumpConfig[StreamIndex$1.STREAM_INDEX_MAIN].clear(),this._remoteAudioTrackDumpConfig[StreamIndex$1.STREAM_INDEX_SCREEN].clear(),this.extensionManager.destroy(),this.earMonitorSettings={[StreamIndex$1.STREAM_INDEX_MAIN]:{position:EarMonitorPosition.NONE,volume:100},[StreamIndex$1.STREAM_INDEX_SCREEN]:{position:EarMonitorPosition.NONE,volume:100}},this.publicAudioVolume.clear()}}function pubSubLock(e,t,i){const r=i.value;return i.value=async function(...e){var t,i,o,s;const n=await this._ctx.pubSubLock.lock();"chrome"!==(null==(t=this._ctx.handler)?void 0:t.name)&&"standard"!==(null==(i=this._ctx.handler)?void 0:i.name)||n();try{const{closeReason:t}=this._ctx.pubSubLock;if(t)throw new SDKError(ErrorCode.UNEXPECTED_ERROR,t);return await r.apply(this,e)}finally{"chrome"!==(null==(o=this._ctx.handler)?void 0:o.name)&&"standard"!==(null==(s=this._ctx.handler)?void 0:s.name)&&n()}},i}function checkNotInRTSRoom(e,t,i){const r=i.value;return i.value=async function(...e){var i;if(null==(i=this._room)?void 0:i.config.isRTSOnlyRoom())throw new SDKError(ErrorCode.NOT_ALLOWED_IN_RTS_ROOM,`Engine.${t}() is not allowed in RTS room`);return await r.apply(this,e)},i}const encodedTransformSupported=isLegacyEncodedTransformSupported()||isEncodedTransformSupported();class VendorHandler extends BasicHandler{constructor(e,t){super(e,t),__publicField(this,"_peerConnectionId",genUuid()),__publicField(this,"peerConnectionMode",1),__publicField(this,"name","vendor"),__publicField(this,"direction","up"),__publicField(this,"stream"),t.on("ice_state",(e=>{this._report("rtc_ice_state",{pc_session_id:this.peerConnectionId,direction:this.direction,error_code:0,ice_state:e.toUpperCase(),message:"",peer_connection_id:this.peerConnectionId,stream_id:"",stream_user_id:""})})),t.on("disconnect",(()=>{this.emit("disconnect")}))}async publish(e){this._context.videoProfile.closeSimulcast(),this.stream=e;const{videoDescriptions:t,subVideoDescriptions:i,audioTransceiverInit:r,videoTransceiverInit:o}=super.internalPublish(e);e.audioTransceiver=this._peerConnection.addTransceiver(r.track,r.init),e.videoTransceiver=this._peerConnection.addTransceiver(o.track,o.init),encodedTransformSupported&&(e.initAudioEncodedTransform(),e.initVideoEncodedTransform()),this._report("rtc_begin_create_offer",{direction:"up",stream_id:"",stream_user_id:"",pc_session_id:this.peerConnectionId,vendor_mode:(null==e?void 0:e.vendorCode)||0});const s=await this.peer.createOfferSdp(),n=getServerNow(),a=lib.parse(s);Array.isArray(a.media)&&(a.media=a.media.map((e=>{var t;if("video"===e.type)(isSafari||isIOS)&&Array.isArray(e.ext)&&(e.ext=e.ext.filter((e=>{var t;return!(null==(t=null==e?void 0:e.uri)?void 0:t.includes("video-orientation"))}))),isSafari||this.addBitrateLimit(e,this._context.videoProfile.getVideoEncodeConfig()[0].maxKbps);else if("audio"===e.type){const i=null==e?void 0:e.rtp.find((e=>"opus"===e.codec));if(i&&e.fmtp){const r=e.fmtp.find((e=>e.payload===i.payload));r&&(null==(t=this._context)?void 0:t.audioProfileManager)&&(r.config=this._context.audioProfileManager.getOpusConfigStr(r.config))}}return e})));const d={type:"offer",sdp:lib.write(a)};try{await this._peerConnection.setLocalDescription(d),this._report("rtc_set_description",{error_code:0,message:d.sdp||"",is_local:"1",direction:"up",stream_id:"",stream_user_id:"",elapse:getServerNow()-n},{type:"offer"})}catch(e){throw this._report("rtc_set_description",{error_code:-1,message:e.message+d.sdp,is_local:"1",direction:"up",stream_id:"",stream_user_id:"",elapse:getServerNow()-n},{type:"offer"}),e}return{partialSdp:d.sdp||"",audioMid:"0",videoMid:"1",type:"offer",semantics:"unified-plan",videoDescriptions:t,subVideoDescriptions:i,audioTransceiverInit:r,videoTransceiverInit:o,peerConnectionMode:this.peerConnectionMode,peerConnectionId:this.peerConnectionId}}async subscribe(e){this.stream=e,this.direction="down",e.audioTransceiver=this._peerConnection.addTransceiver("audio",{direction:"recvonly"}),e.videoTransceiver=this._peerConnection.addTransceiver("video",{direction:"recvonly"}),encodedTransformSupported&&(e.initAudioEncodedTransform(),e.initVideoEncodedTransform()),this._report("rtc_begin_create_offer",{direction:"down",stream_id:e.streamId,stream_user_id:e.userId,pc_session_id:this.peerConnectionId,vendor_mode:e.vendorCode||0});const t=await this.peer.createOfferSdp(),i=getServerNow(),r=lib.parse(t);Array.isArray(r.media)&&(r.media=r.media.map((e=>{if("audio"===e.type){const t=null==e?void 0:e.rtp.find((e=>"opus"===e.codec));if(t&&(null==e?void 0:e.fmtp)){const i=null==e?void 0:e.fmtp.find((e=>e.payload===t.payload));i&&this._context&&(i.config+=";stereo=1;sprop-stereo=1")}}return e})));const o={type:"offer",sdp:lib.write(r)};try{await this._peerConnection.setLocalDescription(o),this._report("rtc_set_description",{error_code:0,message:o.sdp||"",is_local:"1",direction:"down",stream_id:e.streamId,stream_user_id:e.userId,elapse:getServerNow()-i},{type:"offer"})}catch(t){throw this._report("rtc_set_description",{error_code:-1,message:t.message+o.sdp,is_local:"1",direction:"down",stream_id:e.streamId,stream_user_id:e.userId,elapse:getServerNow()-i},{type:"offer"}),t}return{partialSdp:o.sdp||"",audioMid:"0",videoMid:"1",type:"offer",semantics:"unified-plan",peerConnectionMode:this.peerConnectionMode,peerConnectionId:this.peerConnectionId}}async handleAck(e){var t,i,r,o;if(e.action===SdpAction.publish||e.action===SdpAction.subscribe){const{signalingAck:s,videoMid:n,videoCodec:a}=e,{sdp:d}=s,c=lib.parse(d);c.media=c.media.map((e=>(e.mid===n&&a&&setCodecPreferences(e,a),e)));const l={sdp:lib.write(c),type:"answer"},u=getServerNow();try{await this._peerConnection.setRemoteDescription(l),this._report("rtc_set_description",{error_code:0,message:l.sdp||"",is_local:"1",direction:"down",stream_id:(null==(t=e.stream)?void 0:t.streamId)||"",stream_user_id:null==(i=e.stream)?void 0:i.userId,elapse:getServerNow()-u},{type:"answer"})}catch(t){throw this._report("rtc_set_description",{error_code:-1,message:t.message+l.sdp,is_local:"1",direction:"down",stream_id:(null==(r=e.stream)?void 0:r.streamId)||"",stream_user_id:null==(o=e.stream)?void 0:o.userId,elapse:getServerNow()-u},{type:"offer"}),t}"function"==typeof e.onSuccess&&e.onSuccess()}else e.action!==SdpAction.unpublish&&e.action!==SdpAction.unsubscribe||this.destroy();return""}destroy(){this.peer.destroy(),super.destroy()}async getDefaultSdp(){return{sdp:"",type:"offer",semantics:""}}connect(){throw new Error("Method not implemented.")}async rollback(){try{this._peerConnection.close()}catch(e){}}get peerConnectionId(){return this._peerConnectionId}set peerConnectionId(e){this._peerConnectionId=e}}var __defProp$7=Object.defineProperty,__getOwnPropDesc$7=Object.getOwnPropertyDescriptor,__decorateClass$7=(e,t,i,r)=>{for(var o,s=r>1?void 0:r?__getOwnPropDesc$7(t,i):t,n=e.length-1;n>=0;n--)(o=e[n])&&(s=(r?o(t,i,s):o(s))||s);return r&&s&&__defProp$7(t,i,s),s};class RoomPublisher extends EnhancedEventEmitter{constructor(e,t){super(),__publicField(this,"_logger"),__publicField(this,"_pubBackOff",new Map),this._ctx=e,this._roomConf=t,this._logger=new Logger$1("RoomPublisher",2,e.id)}async hasPublished(e){return!!e.audioMid&&!!e.videoMid}async publish(e){return this._publish(e)}async _publish(e){var t,i,r,o,s,n,a,d,c;this._logger.info("publish()","localStream: %o",e);const{videoTrack:l}=e,{audioTrack:u}=e,_=getServerNow();let h,{handler:p}=this._ctx;this._roomConf.vendorConfig.enableMultiVendor?[p,h]=await this._getVendorPubSdpInfo(e):h=await this._ctx.handler.publish(e),this.emit("_test_pub_sdpInfo_",h);const{audioMid:m,videoMid:S}=h;e.pubAttributes={localaudio:!!u,localvideo:!!l,videostream:e.pubVideo,audiostream:e.pubAudio,extvideo:(null==l?void 0:l.sourceType)===SourceType.EXTERNAL,extaudio:(null==u?void 0:u.sourceType)===SourceType.EXTERNAL,videoDescriptions:h.videoDescriptions,videoType:VideoType.NORMAL};const g={attributes:{...e.pubAttributes},audio:!0,video:!0,screen:e.isScreen,audioMid:m,videoMid:S,sdpInfo:{msid:e.stream.id,type:h.type,sdp:h.partialSdp,semantics:h.semantics},peerConnectionMode:null==h?void 0:h.peerConnectionMode,supportMultiVendor:!0},v=!this._roomConf.vendorConfig.enableMultiVendor&&e.enableSimulcast&&(null==(t=this._ctx.serverConfig)?void 0:t.simulcastOnDemand)&&(null==(i=h.subVideoDescriptions)?void 0:i.length);let f;(v||(null==(r=this._ctx.serverConfig)?void 0:r.e2eFeedback))&&(g.attributes.subVideoDescriptions=h.subVideoDescriptions),(null==h?void 0:h.peerConnectionId)&&(g.peerConnectionId=h.peerConnectionId);try{this.emit("_test_pub_body_",g),f=await this._ctx.signalingManager.sendSignaling("publish",g)}catch(t){if(this._logger.error("_publish",getErrorString(t)),null==(o=this._ctx.monitor)||o.report("rtc_error",{message:`[publisher._publish] ${getErrorString(t)}`,error_code:-1}),t instanceof Error?this._roomConf.report("rtc_publish_stat",{result:"fail",is_screen:"0",start:_,message:`${t.name}: ${t.message}`}):t instanceof SDKError&&this._roomConf.report("rtc_publish_stat",{result:"fail",is_screen:"0",start:_,message:`${t.code}: ${t.message}`}),await(null==p?void 0:p.rollback({msid:e.stream.id,stream:e,audioMid:m,videoMid:S})),t.code>=500&&t.code<600){this.emit("_test_pub_5xx_");const t=this._getPubBackOff(e.id);if(t.retryDuration<6e4)return this._logger.info("pubRetry",e.id,t.retryDuration),await new Promise((e=>setTimeout(e,t.interval))),t.retryDuration+=t.interval,t.interval=t.interval>4e3?8e3:2*t.interval,e.resetStream(),this.emit(RoomEvent.PUB_RETRY,{screen:e.isScreen}),this._publish(e);this._logger.info("pubRetry","end"),this._pubBackOff.delete(e.id)}else if(403===t.code)throw new SDKError(ErrorCode.TOKEN_NO_PUBLISH_PERMISSION,t.message||"token no publish permission");throw t}this._roomConf.report("rtc_recv_answer",{error_code:0,answer_type:null==f?void 0:f.relayMessage.type,sequence_id:(null==(s=null==f?void 0:f.relayMessage)?void 0:s.sequenceId)||0,message:null==(n=null==f?void 0:f.relayMessage)?void 0:n.sdp,direction:"up",stream_id:"",stream_user_id:"",pc_session_id:(null==p?void 0:p.peerConnectionId)||""}),e.isScreen?e.setVideoCaps(null==(a=f.relayMessage.content)?void 0:a.screenCaps):e.setVideoCaps(null==(d=f.relayMessage.content)?void 0:d.videoCaps),e.streamId=f.streamId;const E=await e.getSelectedCodec();e.currentVideoCodec=E;const T=new Promise(((t,i)=>{var r,o;null==p||p.handleAck({action:SdpAction.publish,streamId:f.streamId,audioMid:m,videoMid:S,audioTransceiverInit:null==h?void 0:h.audioTransceiverInit,videoTransceiverInit:null==h?void 0:h.videoTransceiverInit,signalingAck:{sdp:null==(r=null==f?void 0:f.relayMessage)?void 0:r.sdp,sequenceId:null==(o=null==f?void 0:f.relayMessage)?void 0:o.sequenceId},stream:e,videoCodec:E,onSuccess:()=>{this._logger.info("publish()","publish success"),t(0)},onFail:e=>{this._logger.info("publish()","publish fail"),i(e)}})}));!isFirefox&&await T,this.emit("___afterHandleAckInPub"),(v&&this._ctx.videoProfile.getSimulcastMode()===VideoSimulcastMode.VIDEO_ON_DEMAND||(null==(c=this._ctx.serverConfig)?void 0:c.e2eFeedback))&&this.emit(MediaServerSignalEvent.RSCP,[{StreamIds:[e.stream.id],Metadata:{VideoIndex:0}}],!0),e.videoMid=S,e.audioMid=m,e.subVideoDescriptions=h.subVideoDescriptions,e.remoteSdp=f.relayMessage.sdp,this._roomConf.report("rtc_publish_stat",{result:"success",is_screen:"0",start:_,message:"unknown"})}async updatePubTrack(e){var t,i,r,o;this._logger.info("updatePubTrack()","localStream: %o",e);const{videoTrack:s,audioTrack:n,pubAudio:a,pubVideo:d}=e,c=e.vendorHandler||this._ctx.handler;let l=null==n?void 0:n.preprocessingTrack;const u=null==s?void 0:s.preprocessingTrack;if(d&&u?(e.stopBlackFrame(),await(null==(t=e.videoTransceiver)?void 0:t.sender.replaceTrack(u)),this._updateVideoDescriptions(e)):await(null==(i=e.videoTransceiver)?void 0:i.sender.replaceTrack(null)),a&&l){const{mixType:t,mixedAudioTrack:i}=n;i&&t!==AudioMixingType.PLAYOUT&&l.enabled&&(l=i),await(null==(r=e.audioTransceiver)?void 0:r.sender.replaceTrack(l))}else await(null==(o=e.audioTransceiver)?void 0:o.sender.replaceTrack(null)),reportRtcInvokeStatus(this._ctx.id,"MediaClient.updatePubTrack(audio)","null");await this._updatePublishCodec(e),this.emit("___onAfterReplaceTrack");try{reportRtcInvokeStatus(this._ctx.id,"MediaClient.updatePubTrack",JSON.stringify({audioStreamTrack:mediaTrackStringify(l),videoStreamTrack:mediaTrackStringify(u)}))}catch(e){}const _={localaudio:!!n,localvideo:!!s,videostream:d,audiostream:a,extvideo:(null==s?void 0:s.sourceType)===SourceType.EXTERNAL,extaudio:(null==n?void 0:n.sourceType)===SourceType.EXTERNAL,videoType:s?VideoType.NORMAL:e.pubAttributes.videoType},h={};for(const[t,i]of Object.entries(_))i!==Reflect.get(e.pubAttributes,t)&&Reflect.set(h,t,i);if(!Object.keys(h).length)return;if(e.observer){const{observer:t}=e,{audiostream:i,videostream:r,localaudio:o,localvideo:s,extaudio:n,extvideo:a}=h;void 0!==s?void 0!==a?t.setPushVideo(a):t.setEnableVideo(s):void 0!==r&&t.setUnmuteVideo(r),void 0!==o?void 0!==n?t.setPushAudio(n):t.setEnableAudio(o):void 0!==i&&t.setUnmuteAudio(i)}e.pubAttributes={...e.pubAttributes,..._},e.pubAttributes.videostream||e.stopBlackFrame();const p={roomId:this._roomConf.roomId,streamId:e.streamId,attributes:h};await this._ctx.signalingManager.sendSignaling("updateStreamAttributes",p),this.emit("___onAfterUpdateSignaling"),isFirefox&&await(null==c?void 0:c.setCurrentDescription())}async _updatePublishCodec(e){var t;this._logger.info("updatePublishCodec()","localStream: %o",e);const{audioMid:i,videoMid:r,remoteSdp:o,streamId:s,currentVideoCodec:n}=e,a=await e.getSelectedCodec();if(this._logger.info("updatePublishCodec()","selectedCodec: %o",a),a!==n){if(e.currentVideoCodec=a,i&&r&&s&&o)return(this._ctx.handler instanceof FirefoxHandler||this._ctx.handler instanceof FallbackHandler)&&await(null==(t=this._ctx.handler)?void 0:t._internalChangePubCodec()),new Promise(((t,n)=>{var d;null==(d=this._ctx.handler)||d.handleAck({action:SdpAction.publish,streamId:s,audioMid:i,videoMid:r,signalingAck:{sdp:o,sequenceId:-1},videoCodec:a,onSuccess:t,onFail:n,stream:e})}));{const t=["audioMid","videoMid","streamId","remoteSdp"].filter((t=>!Reflect.get(e,t)));this._logger.warn("updatePublishCodec()","fast return, because params: %o",t)}}else this._logger.warn("updatePublishCodec()","selectedCodec is equal to currentVideoCodec")}async unpublish(e){this._logger.info("unpublish()","localStream: %o",e);const t={roomId:this._roomConf.roomId,initStreamId:e.initStreamId,streamId:e.streamId};this._ctx.signalingManager.sendSignaling("unpublish",t).catch((()=>{}));const i=e.vendorHandler||this._ctx.handler;e.stopBlackFrame(),await(null==i?void 0:i.handleAck({action:SdpAction.unpublish,audioMid:e.audioMid,videoMid:e.videoMid,stream:e,streamId:e.streamId}))}async updatePubBlackFrame(e){var t,i;const r=e.genBlackFrame();r&&(null==(i=null==(t=e.videoTransceiver)?void 0:t.sender)||i.replaceTrack(r),e.pubAttributes.videoType=VideoType.BLACK,this._ctx.signalingManager.sendSignaling("updateStreamAttributes",{roomId:this._roomConf.roomId,streamId:e.streamId,attributes:{videoType:VideoType.BLACK}}),e.on("black-frame-ended",(()=>{var t,i;null==(i=null==(t=e.videoTransceiver)?void 0:t.sender)||i.replaceTrack(null),e.pubAttributes.videoType=VideoType.NORMAL,this._ctx.signalingManager.sendSignaling("updateStreamAttributes",{roomId:this._roomConf.roomId,streamId:e.streamId,attributes:{videoType:VideoType.NORMAL}})})))}async cleanStream(e){return this._logger.info("cleanStream()","localStream: %o",e),null==e?void 0:e.clean()}async destroyStream(e){return this._logger.info("destroyStream()","localStream: %o",e),null==e?void 0:e.destroy()}destroy(e){e.forEach((e=>{e&&(this.unpublish(e).catch((()=>{})),this.destroyStream(e).catch((()=>{})))})),this._pubBackOff.clear(),super.removeAllListeners()}async _updateVideoDescriptions(e){var t,i,r,o;const s=this._ctx.videoProfile.genVideoDescriptions(e),n=e.pubAttributes.videoDescriptions;if(n.length!==s.videoDescriptions.length)return;const a={};if(n.find(((e,t)=>{if(e.framerate!==s.videoDescriptions[t].framerate||e.maxkbps!==s.videoDescriptions[t].maxkbps||e.width!==s.videoDescriptions[t].width||e.height!==s.videoDescriptions[t].height)return a.videoDescriptions=s.videoDescriptions,!0})),null==(t=e.subVideoDescriptions)||t.find(((e,t)=>{if(e.framerate!==s.subVideoDescriptions[t].framerate||e.maxkbps!==s.subVideoDescriptions[t].maxkbps||e.width!==s.subVideoDescriptions[t].width||e.height!==s.subVideoDescriptions[t].height)return a.subVideoDescriptions=s.subVideoDescriptions,!0})),Object.keys(a).length>0){this._ctx.signalingManager.sendSignaling("updateStreamAttributes",{roomId:this._roomConf.roomId,streamId:e.streamId,attributes:a});const t=null==(r=null==(i=e.videoTransceiver)?void 0:i.sender)?void 0:r.getParameters();reportRtcInvokeStatus(this._ctx.id,"sender.getParameters",JSON.stringify(t),0,e.streamId),t&&Array.isArray(null==t?void 0:t.encodings)&&(t.encodings=t.encodings.map(((e,i)=>((e.rid??(1===t.encodings.length?"0":void 0))===s.sendEncodings[i].rid&&(e.maxBitrate=s.sendEncodings[i].maxBitrate,e.maxFramerate=s.sendEncodings[i].maxFramerate,e.scaleResolutionDownBy=s.sendEncodings[i].scaleResolutionDownBy),e))),this._logger.info("sender.setParameters()",JSON.stringify(t.encodings)),reportRtcInvokeStatus(this._ctx.id,"sender.setParameters",JSON.stringify(t),0,e.streamId),null==(o=e.videoTransceiver)||o.sender.setParameters(t),reportRtcInvokeStatus(this._ctx.id,"Handler.updateScaleResolutionDownBy",JSON.stringify(t.encodings)))}}async _getVendorPubSdpInfo(e){const t=new PeerConnection(this._ctx,"");e.vendorHandler=new VendorHandler(this._ctx,t),e.pcSessionId&&(e.vendorHandler.peerConnectionId=e.pcSessionId);const i=await e.vendorHandler.publish(e),r=e.vendorHandler;return r.on("ice_state",(e=>{this.emit(StateEvent.ON_VENDOR_CONNECTION_STATE_CHANGE,{state:{checking:ConnectionState.CONNECTION_STATE_CONNECTING,connected:ConnectionState.CONNECTION_STATE_CONNECTED,disconnected:ConnectionState.CONNECTION_STATE_RECONNECTING}[e],userId:this._roomConf.userId})})),r.once("disconnect",(async()=>{var t;r.removeAllListeners(),"connected"===(null==(t=this._ctx.peerConnection)?void 0:t.getIceConnectionState())?(await this.unpublish(e),await this.publish(e),e.vendorHandler&&e.statsReport.setVar(e.vendorHandler)):this._logger.info("vendor ice failed",e.streamId)})),[r,i]}_getPubBackOff(e){return this._pubBackOff.has(e)||this._pubBackOff.set(e,{interval:1e3,retryDuration:0}),this._pubBackOff.get(e)}}__decorateClass$7([streamQueue],RoomPublisher.prototype,"hasPublished",1),__decorateClass$7([streamQueue,pubSubLock,checkRoomState],RoomPublisher.prototype,"publish",1),__decorateClass$7([streamQueue,pubSubLock,checkRoomState],RoomPublisher.prototype,"updatePubTrack",1),__decorateClass$7([streamQueue,pubSubLock,checkRoomState],RoomPublisher.prototype,"unpublish",1),__decorateClass$7([streamQueue,checkRoomState],RoomPublisher.prototype,"updatePubBlackFrame",1),__decorateClass$7([streamQueue],RoomPublisher.prototype,"cleanStream",1),__decorateClass$7([streamQueue],RoomPublisher.prototype,"destroyStream",1),__decorateClass$7([checkRoomState],RoomPublisher.prototype,"_updateVideoDescriptions",1);var __defProp$6=Object.defineProperty,__getOwnPropDesc$6=Object.getOwnPropertyDescriptor,__decorateClass$6=(e,t,i,r)=>{for(var o,s=r>1?void 0:r?__getOwnPropDesc$6(t,i):t,n=e.length-1;n>=0;n--)(o=e[n])&&(s=(r?o(t,i,s):o(s))||s);return r&&s&&__defProp$6(t,i,s),s};class RoomSubscriber extends EnhancedEventEmitter{constructor(e,t){super(),__publicField(this,"_logger"),__publicField(this,"_subBackOff",new Map),__publicField(this,"_subResolves",{}),__publicField(this,"_ontrackCallbackMap",new Map),this._ctx=e,this._roomConf=t,this._logger=new Logger$1("RoomSubscriber",2,e.id)}async hasSubscribed(e){return e.streamState===StreamState.SUB_ED}async subscribe(e,t,i){if(e.streamState!==StreamState.SUB_ED)return this._subscribe(e,t,i);this._logger.warn("subscribe()",`remoteStream ${e.streamId} has been subscribed, silently return`)}async _subscribe(e,t,i){var r,o,s,n,a,d,c;this._logger.info("subscribe()","mediaType: %o",t),logRemoteStream("subscribe()",e,this._logger),e.streamState=StreamState.SUB_ING;let l=!1,u=!1;if(audioInMediaType(t)&&(u=!0),videoInMediaType(t)&&(l=!0),!l&&this._roomConf.isMultiChatMode())return void(e.streamState=StreamState.INIT);const _=getServerNow(),h=e.subVideo,p=[];this._subResolves[e.streamId]||(this._subResolves[e.streamId]=[]),p.push(new Promise(((t,i)=>{this._subResolves[e.streamId].push(t);const r=setTimeout((()=>i(new SDKError(ErrorCode.TIME_OUT,`wait video timeout for userId: ${e.userId}`))),6e4),o=i=>{"video"===i.mediaType&&(this._logger.info(`remoteStream ${e.userId} received video track`),e.off("ontrack",o),clearTimeout(r),t(0))};e.on("ontrack",o)}))),this._roomConf.isMultiChatMode()||p.push(new Promise(((t,i)=>{this._subResolves[e.streamId].push(t);const r=setTimeout((()=>i(new SDKError(ErrorCode.TIME_OUT,`wait audio timeout for userId: ${e.userId}`))),6e4),o=i=>{"audio"===i.mediaType&&(this._logger.info(`remoteStream ${e.userId} received audio track`),e.off("ontrack",o),clearTimeout(r),t(0))};e.on("ontrack",o)})));const m=t=>{e.ontrack(t)};null==(r=this._ctx.handler)||r.on("ontrack",m),this._ontrackCallbackMap.set(e,m);let S,{handler:g}=this._ctx;!(null==(o=this._ctx.serverConfig)?void 0:o.forceUniHandler)&&e.enableVendorMode?[g,S]=await this._getVendorSubSdpInfo(e,m):S=await this._ctx.handler.subscribe(e,{multiChatMode:this._roomConf.isMultiChatMode()});const{audioMid:v,videoMid:f}=S;e.subVideo=l;const E={spatialLayer:(null==i?void 0:i.spatialLayer)||0,temporalLayer:0,spatialSubLayer:(null==i?void 0:i.spatialSubLayer)||-1},T={audio:!this._roomConf.isMultiChatMode(),video:!0,data:!0,screen:e.isScreen,browser:"chrome-stable",videoMid:f,audioMid:v,sdpInfo:{sdp:null==S?void 0:S.partialSdp,semantics:null==S?void 0:S.semantics,type:null==S?void 0:S.type},streamUserId:e.userId,streamId:e.streamId,config:{enableMediaType:{audio:!!this._roomConf.isMultiChatMode()||u,video:l},qualityLayer:E},extra:{enableSendRTT:!0},peerConnectionMode:null==S?void 0:S.peerConnectionMode,supportMultiVendor:!0};(null==S?void 0:S.peerConnectionId)&&(T.peerConnectionId=S.peerConnectionId);const{subscribeFallbackOption:R,userPriority:b}=this._ctx;"number"==typeof R&&(T.config.fallbackOption=R),b.has(e.userId)&&(T.config.priority=b.get(e.userId)),(null==S?void 0:S.allSsrc)&&(T.extra.subscribeSSRC=S.allSsrc),this.emit("_test_before_ack_");const{signalingAck:y,audioTransceiverInit:I,videoTransceiverInit:C}=S;let A;y&&(e.videoMid=f,e.audioMid=v,await new Promise(((t,i)=>{null==g||g.handleAck({action:SdpAction.subscribe,streamId:e.streamId,audioMid:v,videoMid:f,audioTransceiverInit:I,videoTransceiverInit:C,signalingAck:y,stream:e,onSuccess:()=>{this._logger.info("ssrc","success"),t(0)},onFail:e=>{this._logger.info("ssrc","fail",e),i(e)}})})));try{this.emit("_test_sub_body_",T);const e=this._ctx.signalingManager.sendSignaling("subscribe",T);this.emit("_test_during_signaling_",T),A=await e}catch(r){if(null==(s=this._ctx.monitor)||s.report("rtc_error",{message:`[subscriber._subscribe] ${getErrorString(r)}`,error_code:-1}),e.streamState=StreamState.INIT,r instanceof Error&&this._roomConf.report("rtc_subscribe_stat",{result:"fail",start:_,message:r.message,stream_user_id:e.userId}),r.code>=500&&r.code<600){this.emit("_test_sub_5xx_");const r=this._getSubBackOff(e.streamId);if(r.retryDuration<6e4)return this._logger.info("subRetry",e.streamId,r.retryDuration),await new Promise((e=>setTimeout(e,r.interval))),r.retryDuration+=r.interval,r.interval=r.interval>4e3?8e3:2*r.interval,this.emit(RoomEvent.SUB_RETRY,{screen:e.isScreen,userId:e.userId}),await(null==g?void 0:g.handleAck({action:SdpAction.unsubscribe,streamId:e.streamId,audioMid:v,videoMid:f,stream:e})),e.resetStream(),this._subscribe(e,t,i);this._logger.info("subRetry","end",e.streamId),this._subBackOff.delete(e.streamId)}e.subVideo=h,await(null==g?void 0:g.rollback({msid:e.streamId,stream:e}));const o={roomId:this._roomConf.roomId,streamId:e.streamId,userId:e.userId};if(await this._ctx.signalingManager.sendSignaling("unsubscribe",o).catch((()=>{})),e.streamState=StreamState.INIT,403===r.code)throw new SDKError(ErrorCode.TOKEN_NO_SUBSCRIBE_PERMISSION,r.message||"token no subscribe permission");throw r}if(!A.relayMessage)throw this._roomConf.report("rtc_error",{error_code:-1009,message:"relayMessage is null"}),new SDKError(ErrorCode.UNEXPECTED_ERROR,"unable to subscribe");const{audioMid:k,videoMid:M}=(null==A?void 0:A.relayMessage)??{},N={[v]:k,[f]:M};this._logger.info("sub midmap",e.userId,N),e.videoMid=f,e.audioMid=v,e.subMediaType=t,e.streamState=StreamState.SUB_ED,e.subLayer=E,this._roomConf.report("rtc_recv_answer",{error_code:0,answer_type:null==(n=null==A?void 0:A.relayMessage)?void 0:n.type,sequence_id:(null==(a=null==A?void 0:A.relayMessage)?void 0:a.sequenceId)||0,message:null==(d=null==A?void 0:A.relayMessage)?void 0:d.sdp,direction:"down",stream_id:e.streamId,stream_user_id:e.userId,pc_session_id:(null==g?void 0:g.peerConnectionId)||""});try{(null==S?void 0:S.signalingAck)||await new Promise(((t,i)=>{var r,o;null==g||g.handleAck({action:SdpAction.subscribe,streamId:e.streamId,audioMid:v,videoMid:f,audioTransceiverInit:null==S?void 0:S.audioTransceiverInit,videoTransceiverInit:null==S?void 0:S.videoTransceiverInit,signalingAck:{sdp:null==(r=null==A?void 0:A.relayMessage)?void 0:r.sdp,sequenceId:null==(o=null==A?void 0:A.relayMessage)?void 0:o.sequenceId},stream:e,onSuccess:()=>{this._logger.info("sub ack","success"),t(0)},onFail:e=>{this._logger.info("sub ack","fail",e),i(e)}})})),await Promise.all(p)}catch(t){null==(c=this._ctx.monitor)||c.report("rtc_error",{message:`[subscriber._subscribe] ${getErrorString(t)}`,error_code:-1}),t instanceof Error&&this._roomConf.report("rtc_subscribe_stat",{result:"fail",start:_,message:t.message,stream_user_id:e.userId});const i={roomId:this._roomConf.roomId,streamId:e.streamId,userId:e.userId};throw await this._ctx.signalingManager.sendSignaling("unsubscribe",i).catch((()=>{})),await(null==g?void 0:g.handleAck({action:SdpAction.unsubscribe,streamId:e.streamId,audioMid:v,videoMid:f,stream:e})),e.streamState=StreamState.INIT,e.resetStream(),t}this._roomConf.isMultiChatMode()||(e.subAudio=u),this._roomConf.report("rtc_subscribe_stat",{result:"success",start:_,message:"unknown",stream_user_id:e.userId}),e.startReport((e=>this.emit("onRemoteStreamStats",e)),g)}async unsubscribe(e){return this._unsubscribe(e)}async _unsubscribe(e){var t,i;logRemoteStream("unsubscribe()",e,this._logger);const r={roomId:this._roomConf.roomId,streamId:e.streamId,userId:e.userId},o=e.vendorHandler||this._ctx.handler;this._ctx.signalingManager.sendSignaling("unsubscribe",r).catch((()=>{})),e.streamState=StreamState.INIT,e.subVideo=!1,null==(t=e.observer)||t.setSubscribeVideo(!1),!this._roomConf.isMultiChatMode()&&(null==(i=e.observer)||i.setSubscribeAudio(!1));const s=await(null==o?void 0:o.handleAck({action:SdpAction.unsubscribe,streamId:e.streamId,audioMid:e.audioMid,videoMid:e.videoMid,stream:e}));this._subResolves[s]&&this._subResolves[s].forEach((e=>e(0))),this._logger.info("unsubscribe",`clean unsub ${e.userId}`),e.clean(),e.subMediaType=ExtendMediaType.NONE,this._removeOnTrackListener(e),e.statsReport.unsubscribe()}async unsubscribe4removeTrack(e,t,i){var r,o,s,n;if(logRemoteStream("unsubscribe4removeTrack()",e,this._logger),this._logger.info("unsubscribe4removeTrack()","sequenceId: ",t.sequenceId,"trackType: ",i),t.sequenceId<e.sequenceId)return void this._logger.warn("unsubscribe4removeTrack()","sequenceId return");const a=i+1,d=!!(a&MediaType$1.AUDIO),c=!!(a&MediaType$1.VIDEO);await(null==(r=this._ctx.handler)?void 0:r.handleAck({action:SdpAction.removetrack,streamId:e.streamId,audioMid:e.audioMid,videoMid:e.videoMid,stream:e})),null==(o=e.observer)||o.setPushTrack(!1),null==(s=e.observer)||s.setUnmuteAudio(!d),e.subAudio=!d,null==(n=e.observer)||n.setUnmuteVideo(!c),e.subVideo=!c,e.subMediaType=e.subMediaType-(e.subMediaType&a),e.virtual&&(e.clean(),e.resetHasSubscribed(),e.statsReport.unsubscribe())}async handleStreamFailed(e){const t=e.subMediaType,i=e.subLayer;await this._unsubscribe(e),await this._subscribe(e,t,i)}async handleRemoveStream(e){logRemoteStream("handleRemoveStream()",e,this._logger),e.subVideo=!1,e.streamState!==StreamState.INIT&&(await this._unsubscribe(e),await this._cleanStream(e),this._destroyStream(e))}_removeOnTrackListener(e){const t=this._ontrackCallbackMap.get(e);if(t){const i=e.vendorHandler||this._ctx.handler;null==i||i.off("ontrack",t),this._ontrackCallbackMap.delete(e)}}async _getVendorSubSdpInfo(e,t){const i=new PeerConnection(this._ctx,"");e.vendorHandler=new VendorHandler(this._ctx,i),e.pcSessionId&&(e.vendorHandler.peerConnectionId=e.pcSessionId);const r=e.vendorHandler;r.on("ontrack",t);const o=await e.vendorHandler.subscribe(e);return r.on("ice_state",(t=>{this.emit(StateEvent.ON_VENDOR_CONNECTION_STATE_CHANGE,{state:{checking:ConnectionState.CONNECTION_STATE_CONNECTING,connected:ConnectionState.CONNECTION_STATE_CONNECTED,disconnected:ConnectionState.CONNECTION_STATE_RECONNECTING}[t],userId:e.userId})})),r.once("disconnect",(async()=>{var t;if(null==r||r.removeAllListeners(),"connected"!==(null==(t=this._ctx.peerConnection)?void 0:t.getIceConnectionState()))return void this._logger.info("vendor ice failed",e.streamId);const i=e.subMediaType;await this.unsubscribe(e),await this.subscribe(e,i),e.vendorHandler&&e.statsReport.setVar(e.vendorHandler),this.emit(RoomEvent.RESUBSCRIBE,{stream:e})})),[r,o]}async subscribe4pushTrack(e,t){var i,r,o;this._logger.info("subscribe4pushTrack()","streamInfo: %o",t),logRemoteStream("subscribe4pushTrack()",e,this._logger),e.subAudio=!0;const s=await(null==(i=this._ctx.handler)?void 0:i.subscribe(e,{multiChatMode:this._roomConf.isMultiChatMode()}));if(!s)throw new SDKError(ErrorCode.ADD_TRANSCEIVER_FAILED,"add transceiver failed");const{audioMid:n}=s,{videoMid:a}=s,d=[];d.push(new Promise(((t,i)=>{const r=setTimeout((()=>i(new SDKError(ErrorCode.TIME_OUT,`wait audio timeout for userId: ${e.userId}`))),6e4),o=i=>{"audio"===i.mediaType&&(this._logger.success(`remoteStream ${e.userId} received audio track`),e.off("ontrack",o),clearTimeout(r),t(0))};e.on("ontrack",o)})));const c=t=>{e.ontrack(t)};null==(r=this._ctx.handler)||r.on("ontrack",c),this._ontrackCallbackMap.set(e,c),await(null==(o=this._ctx.handler)?void 0:o.handleAck({action:SdpAction.pushtrack,streamId:e.streamId,audioMid:n,videoMid:a,stream:e,audioTransceiverInit:null==s?void 0:s.audioTransceiverInit,videoTransceiverInit:null==s?void 0:s.videoTransceiverInit,signalingAck:null==t?void 0:t.message})),await Promise.all(d),e.videoMid=a,e.audioMid=n,e.startReport((e=>this.emit("onRemoteStreamStats",e)),this._ctx.handler)}async updateUserAttributes(e){this._logger.info("updateUserAttributes()","attributes: %o",e),await this._ctx.signalingManager.sendSignaling("updateUserAttributes",{roomId:this._roomConf.roomId,sessionId:this._roomConf.sessionId,attributes:e})}async updateSubTrackLayer(e,t){if(this._logger.info("updateSubTrack()","subLayer: %o",t),e.subLayer.spatialLayer===t.spatialLayer&&e.subLayer.spatialSubLayer===t.spatialSubLayer)return void this._logger.warn("updateSubTrack()","subLayer no change");const i={roomId:this._roomConf.roomId,streamList:[e.streamId],streamId:e.streamId,streamUserId:e.userId,config:{qualityLayer:t}};return await this._ctx.signalingManager.sendSignaling("updateSubscribe",i),this.emit("___afterUpdateSubscribeSend"),e.subLayer=t,e}async updateSubPriority(e,t){if(this._logger.info("updateSubPriority()","priority: %o",t),e.priority===t)return this._logger.warn("updateSubPriority()","priority no change"),e;const i={roomId:this._roomConf.roomId,streamList:[e.streamId],streamId:e.streamId,streamUserId:e.userId,config:{priority:t}};return await this._ctx.signalingManager.sendSignaling("updateSubscribe",i),e.priority=t,e}async updateSubMediaType(e,t){var i,r;let o=!1,s=!1;audioInMediaType(t)&&(s=!0),videoInMediaType(t)&&(o=!0);const n={roomId:this._roomConf.roomId,streamList:[e.streamId],config:{enableMediaType:{video:o,audio:!!this._roomConf.isMultiChatMode()||s}}};return await this._ctx.signalingManager.sendSignaling("updateSubscribe",n),this._roomConf.isMultiChatMode()||(null==(i=e.observer)||i.setUnmuteAudio(s),e.subAudio=s),null==(r=e.observer)||r.setUnmuteVideo(o),e.subVideo=o,e.subMediaType=t,e}async cleanStream(e){return this._cleanStream(e)}async _cleanStream(e){this._logger.info("cleanStream()","stream: %o",e),null==e||e.clean()}destroyStream(e){return this._destroyStream(e)}_destroyStream(e){this._logger.info("destroyStream()","stream: %o",e),null==e||e.destroy()}destroy(e){var t;this._logger.info("destroy()","remoteStream: %o",e),e.forEach((e=>{this.unsubscribe(e).catch((()=>{})),this.destroyStream(e)})),this._subBackOff.clear(),this._ontrackCallbackMap.forEach(((e,t)=>{this._removeOnTrackListener(t),this._ontrackCallbackMap.delete(t)})),this._subResolves={},null==(t=this._ctx.handler)||t.removeAllListeners("ontrack"),super.removeAllListeners()}_getSubBackOff(e){return this._subBackOff.has(e)||this._subBackOff.set(e,{interval:1e3,retryDuration:0}),this._subBackOff.get(e)}}__decorateClass$6([streamQueue],RoomSubscriber.prototype,"hasSubscribed",1),__decorateClass$6([streamQueue,pubSubLock,checkRoomState],RoomSubscriber.prototype,"subscribe",1),__decorateClass$6([streamQueue,pubSubLock,checkRoomState],RoomSubscriber.prototype,"unsubscribe",1),__decorateClass$6([streamQueue,pubSubLock,checkRoomState],RoomSubscriber.prototype,"unsubscribe4removeTrack",1),__decorateClass$6([streamQueue],RoomSubscriber.prototype,"handleStreamFailed",1),__decorateClass$6([streamQueue,checkRoomState],RoomSubscriber.prototype,"handleRemoveStream",1),__decorateClass$6([streamQueue,pubSubLock,checkRoomState],RoomSubscriber.prototype,"subscribe4pushTrack",1),__decorateClass$6([streamQueue,checkRoomState],RoomSubscriber.prototype,"updateUserAttributes",1),__decorateClass$6([streamQueue,checkRoomState],RoomSubscriber.prototype,"updateSubTrackLayer",1),__decorateClass$6([streamQueue,checkRoomState],RoomSubscriber.prototype,"updateSubPriority",1),__decorateClass$6([streamQueue],RoomSubscriber.prototype,"updateSubMediaType",1),__decorateClass$6([streamQueue],RoomSubscriber.prototype,"cleanStream",1),__decorateClass$6([streamQueue],RoomSubscriber.prototype,"destroyStream",1);const RoomProfileMap={[RoomProfileType.communication]:[0],[RoomProfileType.chat]:[0],[RoomProfileType.chatRoom]:[1,"IES_chatroom"],[RoomProfileType.coHost]:[1,"IES_PK"],[RoomProfileType.meeting]:[16],[RoomProfileType.classRoom]:[0]},_RoomJoin=class extends EnhancedEventEmitter{constructor(e,t){super(),__publicField(this,"_logger"),__publicField(this,"_authorization"),__publicField(this,"_joinRoom5xxTimer"),__publicField(this,"_joinTask"),__publicField(this,"_sdpInfo"),this._ctx=e,this._roomConf=t,this._logger=new Logger$1("RoomJoin",2,e.id),this._logger.info("constructor","invoke")}join(e=!1){let t,i;this._logger.info("join()");const r=new Promise(((r,o)=>{t=r,i=o,this._callJoinRoom(e).catch((e=>{const t=Array.isArray(e)&&e.length>0?e[0]:e;this._joinRoomFailed(t.message)}))}));return this._joinTask&&e?this._joinTask.startTime=getServerNow():(this._joinTask={startTime:getServerNow(),success:t,fail:i},this._roomConf.joinPromise=r),this._reportJoinRoomStart(),r}async updateToken(e){if(this._logger.info("updateToken()","newToken: %o",e),!this._ctx.appId||!this._roomConf.userId||!this._roomConf.roomId)return;const t={roomId:this._roomConf.roomId,userId:this._roomConf.userId,appId:this._ctx.appId,token:`Bearer ${e}`};try{await this._ctx.signalingManager.sendSignaling("updateToken",t)}catch(e){throw new SDKError(ErrorCode.UPDATE_TOKEN_WITH_INVALID_TOKEN,"invoke updateToken with an invalid token")}}async leave(){this._logger.info("leave()"),this._stopJoinRoom5xxRetry(),this._joinRoomFailed("leave_room");const e={Authorization:this._authorization,roomId:this._roomConf.roomId,sessionId:this._roomConf.sessionId};if(await this._ready2join(),!this._ctx.signalingManager.isConnected())return Promise.reject(new SDKError(ErrorCode.NOT_CONNECTED_YET,"server not connected"));await this._ctx.signalingManager.sendSignaling("leaveRoom",e,this._roomConf.rtsOnlySignalHeader)}destroy(){this._logger.info("destroy()"),this._joinRoomFailed("leave_room"),this._authorization=void 0,this._stopJoinRoom5xxRetry(),this.removeAllListeners()}async _ready2join(){var e;return await this._ctx.signalingManager.connect(),this._sdpInfo||(this._sdpInfo=await(null==(e=this._ctx.handler)?void 0:e.getDefaultSdp())),_RoomJoin.supportedCodecs||(_RoomJoin.supportedCodecs=await internalGetSupportedCodecs()),{sdpInfo:this._sdpInfo,supportedCodecs:_RoomJoin.supportedCodecs}}async _callJoinRoom(e){var t,i,r,o,s,n,a,d,c,l,u,_;this._logger.info("_callJoinRoom","invoke"),delete this._sdpInfo;const{appId:h,role:p,businessId:m,useCloudProxy:S,joinRoomParams:g,mediaParams:v}=this._ctx,{sdpInfo:f,supportedCodecs:E}=await this._ready2join(),T={Authorization:Utils.token2auth(h,this._roomConf.roomId,this._roomConf.userId,this._roomConf.token),sessionId:this._roomConf.sessionId,timestamp:Date.now(),controlMessage:this._roomConf.getLiveControlMessage(),userAttributes:{extra_info:this._roomConf.userInfo.extraInfo,role:p},sdpInfo:f,params:{supportedCodecs:E,userAgent:window.navigator.userAgent,sdkVersion:Config2.VERSION,deviceId:sdkCache.getDeviceId(),appId:h,roomId:this._roomConf.roomId,userId:this._roomConf.userId,businessId:m,enableCloudProxy:S,channelProfile:RoomProfileMap[this._roomConf.roomProfileType]?`${RoomProfileMap[this._roomConf.roomProfileType][0]}`:"0",SDKCodecNegotiation:getParameter("SDK_CODEC_NEGOTIATION"),sdkType:"rtc",joinRoomMode:this._roomConf.isRTSOnlyRoom()?2:1,deviceType:"web",platformType:2,rtsMode:this._ctx.rtsMode,mediaProcessingType:Config2.MEDIA_PROCESSING_TYPE??0},options:{supportCheckTokenPrivilege:!0,supportTokenExpireCallBack:!0,enableSceneConfigV2:!0,enableUnBundleMode:!0,enableAudioMux:!0,enableBigRoomMode:!0,needNegotiateSDP:!0,supportMultiVendor:!0},accessParams:JSON.stringify({requireICEUfragV2:!0})};if("AREA_CODE_US_OPCO"===getParameter("AREA_CODE")&&(T.params.mediaArea=JSON.stringify([{AreaList:["GEO:US_OPCO"],Attribute:"include"}])),g)for(const[e,t]of Object.entries(g))T.params[e]=t;v&&(T.mediaParams=v);getParameter("SIGNAL_CROP_JOINROOM")&&(null==(t=T.sdpInfo)?void 0:t.sdp)&&(T.sdpInfo.sdp=cropSdpMediaSection(T.sdpInfo.sdp)),Promise.resolve().then((()=>this.emit("onSendingJoinMessageHook")));try{const t=e?"reconnected":"joinRoom",_=await this._joinRoomWithRetry(t,T);this._logger.success("join","send join message success");const{_abtest_vid:h}=_.config||{};let{engine_WEB:p}=_.config||{};this._authorization=T.Authorization,sdkCache.setEngineWebConfig(this._ctx.appId,this._roomConf.roomId,p),p=Object.assign({},getParameter("ENGINE_WEB_CONFIG"),p),this._ctx.serverConfig={videoCodec:null==p?void 0:p.video_codec,audioRed:!!(null==p?void 0:p.pub_audio_red),muteReplaceUnsub:!!(null==(i=_.config)?void 0:i.mute_replace_unsub),simulcastOnDemand:!(!1===(null==(s=null==(o=null==(r=_.config)?void 0:r.engine_VPM)?void 0:o.ondemand)?void 0:s.enable)),forceUniHandler:1===(null==(a=null==(n=_.config)?void 0:n.vendor_param)?void 0:a.vendor_stream_sub_mode),e2eFeedback:null==p?void 0:p.e2e_feedback},getParameter("SDK_CODEC_NEGOTIATION")&&(this._ctx.targetCodec=null==(d=_.config)?void 0:d.targetCodec,this._ctx.targetScreenCodec=null==(c=_.config)?void 0:c.targetScreenCodec),"boolean"==typeof(null==p?void 0:p.av_sync)&&(this._ctx.avSync=p.av_sync),this._roomConf.rtcVid=h,_.vendorConfig&&this._roomConf.setVendorConfig(_.vendorConfig),AudioStallObserver.setAudioStallConfig(p),(null==(l=_.relayMessage)?void 0:l.sdp)&&(null==(u=this._ctx.handler)||u.createAVMlineAnswerTpl(_.relayMessage.sdp)),this.emit(RoomEvent.JOIN_SUCCESS,{joinRes:_,reconnect:e}),this._joinRoomSuccess(_)}catch(e){null==(_=this._ctx.monitor)||_.report("rtc_error",{message:`[join._callJoinRoom] ${getErrorString(e)}`,error_code:-1});const t={461:ErrorCode.ROOM_FORBIDDEN,462:ErrorCode.USER_FORBIDDEN};(null==e?void 0:e.code)>=700&&(null==e?void 0:e.code)<800?this._joinRoomFailed("token_error",ErrorCode.INVALID_TOKEN):t[null==e?void 0:e.code]?this._joinRoomFailed((null==e?void 0:e.message)||t[null==e?void 0:e.code],t[null==e?void 0:e.code]):(null==e?void 0:e.code)===ErrorCode.TIME_OUT&&this._ctx.joinRoomConfig.useTcpAfterJoinTimeout?(this._logger.error("join",InternalReconnectReason.JOIN_TIMEOUT),this.safeEmit(RoomEvent.ON_REJOIN_WITH_TCP),this._ctx.signalingManager.reconnect(InternalReconnectReason.JOIN_TIMEOUT,!0)):e.code===ErrorCode.OPERATION_CANCEL&&this._ctx.signalingManager.isReconnecting()||this._joinRoomFailed((null==e?void 0:e.message)||"signaling_error")}}_joinRoomWithRetry(e,t,i){return new Promise(((r,o)=>{this._ctx.signalingManager.sendSignaling(e,t,this._roomConf.rtsOnlySignalHeader,1e4).then((e=>{this.emit("onJoinRoomAck",e),r(e)})).catch((s=>{if(i=i||new RetryLimiter,s.code>=500&&s.code<600&&getServerNow()-i.initTs<6e4){const n=i.getRetryDelay();return this._logger.warn("_joinRoomWithRetry",`joinRoom failed(code: ${s.code}), will retry after ${n}ms`),void(this._joinRoom5xxTimer=setTimeout((()=>{delete this._joinRoom5xxTimer,this._joinRoomWithRetry(e,t,i).then(r).catch(o)}),n))}o(s)}))}))}_stopJoinRoom5xxRetry(){this._joinRoom5xxTimer&&(clearTimeout(this._joinRoom5xxTimer),delete this._joinRoom5xxTimer)}_reportJoinRoomStart(){this._joinTask&&(this.emit("__joinRoomStartReport"),this._roomConf.report("join_room",{type:"begin",start:this._joinTask.startTime,result:!1,reason:""},{enable_cloud_proxy:this._ctx.useCloudProxy,expectedIDC:this._ctx.expectedIDC}))}_joinRoomSuccess(e){this._joinTask&&(this._joinTask.success(e),this.emit("__joinRoomSuccessReport"),this._roomConf.report("join_room",{type:"end",start:this._joinTask.startTime,result:!0,reason:""},{enable_cloud_proxy:this._ctx.useCloudProxy,expectedIDC:this._ctx.expectedIDC}),this._roomConf.report("rtc_join_room",{error_code:0,deviceModel:"web",deviceManufacturer:"web",elapse:getServerNow()-this._joinTask.startTime}),delete this._joinTask,delete this._roomConf.joinPromise)}_joinRoomFailed(e,t){this._joinTask&&(this._joinTask.fail(new SDKError(t||ErrorCode.JOIN_ROOM_FAILED,e)),this.emit("__joinRoomFailedReport"),this._roomConf.report("join_room",{type:"end",start:this._joinTask.startTime,result:!1,reason:e},{enable_cloud_proxy:this._ctx.useCloudProxy,expectedIDC:this._ctx.expectedIDC}),delete this._joinTask,delete this._roomConf.joinPromise)}};let RoomJoin=_RoomJoin;__publicField(RoomJoin,"supportedCodecs");var __defProp$5=Object.defineProperty,__getOwnPropDesc$5=Object.getOwnPropertyDescriptor,__decorateClass$5=(e,t,i,r)=>{for(var o,s=r>1?void 0:r?__getOwnPropDesc$5(t,i):t,n=e.length-1;n>=0;n--)(o=e[n])&&(s=(r?o(t,i,s):o(s))||s);return r&&s&&__defProp$5(t,i,s),s};class RoomMessage{constructor(e,t){__publicField(this,"_logger"),this._ctx=e,this._roomConf=t,this._logger=new Logger$1("RoomMessage",2,e.id)}sendUserMessage(e,t){return this._ctx.signalingManager.sendP2PMessage({to:e,from:this._roomConf.userId,room:this._roomConf.roomId,app:this._ctx.appId,msg:t})}async sendRoomMessage(e,t){const i={clientId:this._roomConf.userId,binary:t,message:"",roomId:this._roomConf.roomId};return i.message=t?await Utils.ab2b64str(e):e,this._ctx.signalingManager.sendSignaling("customMessage",i,this._roomConf.rtsOnlySignalHeader)}async controlMessage(e){this._logger.info("controlMessage()","params: %o",e);const t=e;"transcode"===e.type&&(t.roomId=this._roomConf.roomId),await this._ctx.signalingManager.sendSignaling("controlMessage",t)}}__decorateClass$5([checkRoomState],RoomMessage.prototype,"sendUserMessage",1),__decorateClass$5([checkRoomState],RoomMessage.prototype,"sendRoomMessage",1),__decorateClass$5([checkRoomState],RoomMessage.prototype,"controlMessage",1);var __defProp$4=Object.defineProperty,__getOwnPropDesc$4=Object.getOwnPropertyDescriptor,__decorateClass$4=(e,t,i,r)=>{for(var o,s=r>1?void 0:r?__getOwnPropDesc$4(t,i):t,n=e.length-1;n>=0;n--)(o=e[n])&&(s=(r?o(t,i,s):o(s))||s);return r&&s&&__defProp$4(t,i,s),s};const virtualStreamAttributes={audiostream:!0,extaudio:!1,extvideo:!1,localaudio:!0,localvideo:!1,videoDescriptions:[],videostream:!1,publishTime:0};class Room extends EnhancedEventEmitter{constructor(e,t){super(),__publicField(this,"_localStream"),__publicField(this,"_localScreenStream"),__publicField(this,"_remoteUsers",new Map),__publicField(this,"_remoteStreams",new Map),__publicField(this,"_remoteStreamStreamIdUserIdMap",{}),__publicField(this,"_remoteUserMediaBanned",new Map),__publicField(this,"_virtualStreams",[]),__publicField(this,"_serverConfig"),__publicField(this,"_userDuplicateLoginTimerMap",new Map),__publicField(this,"_networkQualityManager"),__publicField(this,"_videoSizeObserver"),__publicField(this,"_hasPublished",!1),__publicField(this,"_subtitleTool"),__publicField(this,"_csrcUserIdMap",{}),__publicField(this,"_publishOnDemandItem"),__publicField(this,"_onceTriggerBySignal",!1),__publicField(this,"_pubTransceiverReady",!1),__publicField(this,"_publishOnDemandBusy",!1),__publicField(this,"logger"),__publicField(this,"_forwardStreamManager"),__publicField(this,"_publisher"),__publicField(this,"_subscriber"),__publicField(this,"_roomJoin"),__publicField(this,"_roomMessage"),__publicField(this,"_clearSignalListeners"),this.config=e,this._ctx=t,this.logger=new Logger$1("Room",1,t.id),this.logger.info("constructor","invoke"),this._publisher=new RoomPublisher(t,e),this._addPublisherListeners(),this._subscriber=new RoomSubscriber(t,e),this._addSubscriberListeners(),this._roomJoin=new RoomJoin(t,e),this._addJoinRoomHandler(),this._forwardStreamManager=new ForwardStreamManager(t,e),this._addForwardStreamListeners(),this._roomMessage=new RoomMessage(t,e),this._networkQualityManager=new NetworkQualityManager(t),this._networkQualityManager.reportor=this._reportNetworkQuality.bind(this),this._videoSizeObserver=new VideoSizeObserver(this),this._videoSizeObserver.onchange=this._emitVideoSizeChange.bind(this),this._addSignalListeners()}get remoteUsers(){return this._remoteUsers}get remoteStreams(){return this._remoteStreams}get localStream(){return this._localStream}get localScreenStream(){return this._localScreenStream}get virtualStreams(){return this._virtualStreams}_addSignalListeners(){const e={[SignalEvent.ON_ADD_STREAM]:this._onAddStream.bind(this),[SignalEvent.ON_ADD_STREAM_LIST]:e=>{e&&Array.isArray(e.streamList)&&e.streamList.forEach((e=>this._onAddStream(e)))},[SignalEvent.ON_REMOVE_STREAM]:this._onRemoveStream.bind(this),[SignalEvent.ON_REMOVE_STREAM_LIST]:e=>{e&&Array.isArray(e.streamList)&&e.streamList.forEach((e=>this._onRemoveStream(e)))},[SignalEvent.USER_CONNECTION]:this._onUserConnection.bind(this),[SignalEvent.USER_CONNECTION_LIST]:e=>{e&&Array.isArray(e.userList)&&e.userList.forEach((e=>this._onUserConnection(e)))},[SignalEvent.USER_DISCONNECTION]:this._onUserDisconnection.bind(this),[SignalEvent.USER_DISCONNECTION_LIST]:e=>{e&&Array.isArray(e.userList)&&e.userList.forEach((e=>this._onUserDisconnection(e)))},[SignalEvent.ON_UPDATE_ROOM_ATTRIBUTES]:this._onUpdateRoomAttributes.bind(this),[SignalEvent.ON_UPDATE_USER_ATTRIBUTES]:this._onUpdateUserAttributes.bind(this),[SignalEvent.ON_UPDATE_STREAM_ATTRIBUTES]:this._onUpdateStreamAttributes.bind(this),[SignalEvent.ON_PUSH_TRACK]:this._onPushTrack.bind(this),[SignalEvent.ON_REMOVE_TRACK]:this._onRemoveTrack.bind(this),[SignalEvent.ON_CUSTOM_MESSAGE]:this._onCustomMessage.bind(this),[SignalEvent.USER_MESSAGE_RECEIVED]:this._onUserMessageReceived.bind(this),[SignalEvent.USER_BINARY_MESSAGE_RECEIVED]:this._onUserBinaryMessageReceived.bind(this),[SignalEvent.POST_PROCESSING_MESSAGE]:this._onPostProcessingMessage.bind(this),[SignalEvent.ON_USER_TOKEN_WILL_EXPIRE]:this._onUserTokenWillExpire.bind(this),[SignalEvent.ON_TOKEN_PUBLISH_PRIVILEGE_WILL_EXPIRE]:this._onUserTokePublishPrivilegeWillExpire.bind(this),[SignalEvent.ON_TOKEN_PUBLISH_PRIVILEGE_DID_EXPIRED]:this._onUserTokenPublishPrivilegeDidExpire.bind(this),[SignalEvent.ON_TOKEN_SUBSCRIBE_PRIVILEGE_WILL_EXPIRE]:this._onUserTokeSubscribePrivilegeWillExpire.bind(this),[SignalEvent.ON_TOKEN_SUBSCRIBE_PRIVILEGE_DID_EXPIRED]:this._onUserTokenSubscribePrivilegeDidExpire.bind(this),[SignalEvent.STREAM_CONTROL_MESSAGE]:this._onStreamControlMessage.bind(this),[SignalEvent.ENGINE_CONTROL_MESSAGE]:this._onEngineControlMessage.bind(this),[SignalEvent.ON_STREAM_FAILED]:this._onStreamFailed.bind(this),[MediaServerSignalEvent.RTT]:this._onRTT.bind(this),[MediaServerSignalEvent.SSC]:this._onSSC.bind(this),[StateEvent.ON_CONNECTION_STATE_CHANGE]:this._onConnectionStateChange.bind(this),[SignalEvent.ON_SPEAKER_CHANGE]:this._onMeetingSpeakerChange.bind(this),[SignalEvent.ON_FORWARD_DST_ROOM_USER_KICK]:this._forwardStreamManager.onForwardDstRoomUserKick.bind(this._forwardStreamManager),[MediaServerSignalEvent.RSCP]:this._onRSCP.bind(this)};Object.keys(e).forEach((t=>{this._ctx.signalingManager.on(t,e[t])})),this._clearSignalListeners=()=>{Object.keys(e).forEach((t=>{this._ctx.signalingManager.off(t,e[t])}))}}_addPublisherListeners(){this._publisher.on(RoomEvent.PUB_RETRY,(e=>{this.emit(RoomEvent.PUB_RETRY,e)})),this._publisher.on(MediaServerSignalEvent.RSCP,this._onRSCP.bind(this)),this._publisher.on(StateEvent.ON_VENDOR_CONNECTION_STATE_CHANGE,(e=>this.emit(StateEvent.ON_VENDOR_CONNECTION_STATE_CHANGE,e)))}_addSubscriberListeners(){this._subscriber.on(StateEvent.ON_VENDOR_CONNECTION_STATE_CHANGE,(e=>this.emit(StateEvent.ON_VENDOR_CONNECTION_STATE_CHANGE,e))),this._subscriber.on("onRemoteStreamStats",(e=>{this._networkQualityManager.updateDownlinkStats(e,this._findRemoteStreamByScreen(e.userId,e.isScreen)),getParameter("HIDDEN_STATS")||(e=getPublicStats(e)),this.emit(RoomEvent.ON_REMOTE_STREAM_STATS,e)})),this._subscriber.on(RoomEvent.RESUBSCRIBE,(e=>{this.emit(RoomEvent.RESUBSCRIBE,e)})),this._subscriber.on(RoomEvent.SUB_RETRY,(e=>{this.emit(RoomEvent.SUB_RETRY,e)}))}_addJoinRoomHandler(){this._roomJoin.on(RoomEvent.JOIN_SUCCESS,this._onJoinSucc.bind(this)),this._roomJoin.on(RoomEvent.ON_REJOIN_WITH_TCP,(()=>{this.emit(RoomEvent.ON_REJOIN_WITH_TCP)}))}_addForwardStreamListeners(){this._forwardStreamManager.on(RoomEvent.ON_FORWARD_STREAM_ERROR,(e=>{this.safeEmit(RoomEvent.ON_FORWARD_STREAM_ERROR,e)}))}_onLocalStreamStats(e){const t=e.isScreen?this._localScreenStream:this.localStream;this._networkQualityManager.updateUplinkStats(e,t),getParameter("HIDDEN_STATS")||(e=getPublicStats(e)),this.emit(RoomEvent.ON_LOCAL_STREAM_STATS,e)}async join(){var e,t;this.logger.info("join()"),this.config.startJoinTimestamp=getServerNow();try{const t=await this._roomJoin.join();return this._ctx.callId=t.callId,(null==(e=t.roomAttributes)?void 0:e.multiChatMode)&&this._handleFFAudioTrack(),this._initSubtitleTool(),{users:t.clients,streams:t.streams}}catch(e){if(null==(t=this._ctx.monitor)||t.report("rtc_error",{message:`[room.join] ${getErrorString(e)}`,error_code:-1}),e.code!==ErrorCode.OPERATION_CANCEL)throw e}}async hasScreenPublished(){return!!this._localScreenStream&&this._publisher.hasPublished(this._localScreenStream)}async hasPublished(){return!!this._localStream&&this._publisher.hasPublished(this._localStream)}async publishScreen(e,t,i,r){var o,s,n,a,d;this.logger.info("publishScreen()"),this._localScreenStream||(this._localScreenStream=new LocalStream(this._ctx,StreamIndex$1.STREAM_INDEX_SCREEN),this.config.vendorConfig.enableMultiVendor&&(this._localScreenStream.pcSessionId=genUuid$1()),this._localScreenStream.isScreen=!0,this._localScreenStream.observer=new SendFrameObserver(this._ctx,this._localScreenStream));let c=!1,l=!1,u=!1,_=!1;!this._localScreenStream.videoTrack&&e?(e.sourceType===SourceType.EXTERNAL&&(l=!0),c=!0):this._localScreenStream.videoTrack&&!e&&(c=!1),!this._localScreenStream.audioTrack&&t?(t.sourceType===SourceType.EXTERNAL&&(_=!0),u=!0):this._localScreenStream.audioTrack&&!t&&(u=!1),this._localScreenStream.videoTrack=e,this._localScreenStream.audioTrack=t,i&&(audioInMediaType(i)&&(this._localScreenStream.pubAudio=r===PubState.PUB),videoInMediaType(i)&&(this._localScreenStream.pubVideo=r===PubState.PUB),this.logger.info("publishScreen mediaType","pubAudio: %o, pubVideo: %o",this._localScreenStream.pubAudio,this._localScreenStream.pubVideo));const h=await this._publisher.hasPublished(this._localScreenStream);if(!this._localScreenStream.pubAudio&&!this._localScreenStream.pubVideo)return h?this.unpublishScreen():void 0;h?(l?null==(s=this._localScreenStream.observer)||s.setPushVideo(c):null==(n=this._localScreenStream.observer)||n.setEnableVideo(c),_?null==(a=this._localScreenStream.observer)||a.setPushAudio(u):null==(d=this._localScreenStream.observer)||d.setEnableAudio(u),await this.updatePubScreenTrack()):(null==(o=this._localScreenStream.observer)||o.setPublish(!0),await this._publisher.publish(this._localScreenStream)),this._localScreenStream.pubAudio||this._localScreenStream.pubVideo?this._ctx.handler&&this._localScreenStream.startReport(this._onLocalStreamStats.bind(this),this._localScreenStream.vendorHandler||this._ctx.handler):this._localScreenStream.stopReport("unpublish screen")}async updatePubScreenTrack(){this.logger.info("updatePubScreenTrack","Invoke updatePubScreenTrack"),this._localScreenStream&&await this._publisher.updatePubTrack(this._localScreenStream)}async unpublishScreen(){var e,t;this.logger.info("unpublish","Invoke unpublishScreen"),this._localScreenStream&&(null==(e=this._localScreenStream.observer)||e.setPublish(!1),await this._publisher.unpublish(this._localScreenStream),null==(t=this._localScreenStream)||t.stopReport("unpublish screen"),await this._publisher.cleanStream(this._localScreenStream),this._localScreenStream=void 0)}async liveControlMessage(e){var t;this.logger.info("controlMessage","Invoke controlMessage"),null==(t=e.transcodeMeta)||t.layout.regions.forEach((e=>{e.roomID=this.config.roomId})),this.config.setLiveControlMessage("stopped"===e.action?void 0:e);try{await this._roomMessage.controlMessage(e)}catch(t){if("stopped"!==e.action)throw t}}async publicStreamControlMessage(e){"stopped"===e.action&&delete e.publicStreamMeta,await this._roomMessage.controlMessage(e)}getLocalStreamStats(){var e;return null==(e=this.localStream)?void 0:e.getLocalStreamStats()}async updateUserAttributes(){this.logger.info("updateUserAttributes","Invoke updateUserAttributes"),await this._subscriber.updateUserAttributes({role:this._ctx.role})}async publish(e,t,i,r,o=!1){var s,n,a,d,c,l,u,_,h;this.logger.info("publish","Invoke publish");let p=!1;this._localStream||(this._localStream=new LocalStream(this._ctx),this.config.vendorConfig.enableMultiVendor&&(this._localStream.pcSessionId=genUuid$1()),this._localStream.observer=new SendFrameObserver(this._ctx,this._localStream),p=!0,this._localStream.vendorCode=this.config.vendorConfig.vendorCode||0),this._localStream.videoTrack=e,this._localStream.audioTrack=t;const{pubAudio:m,pubVideo:S}=this._localStream;i&&(audioInMediaType(i)&&(this._localStream.pubAudio=r===PubState.PUB),videoInMediaType(i)&&(this._localStream.pubVideo=r===PubState.PUB),this.logger.info("publish mediaType","pubAudio: %o, pubVideo: %o",this._localStream.pubAudio,this._localStream.pubVideo));if(await this._publisher.hasPublished(this._localStream))try{this.emit("___onMediaServerClientPublish"),await this.updatePubTrack()}catch(e){throw this._localStream.pubAudio=m,this._localStream.pubVideo=S,e}else{if(!this._localStream.pubAudio&&!this._localStream.pubVideo)return;try{if(o)null==(s=this._localStream.observer)||s.setLogin(!0);else if(p){const e=!!this._localStream.videoTrack,t=!!this._localStream.audioTrack,i=(null==(n=this._localStream.videoTrack)?void 0:n.sourceType)===SourceType.EXTERNAL,r=(null==(a=this._localStream.audioTrack)?void 0:a.sourceType)===SourceType.EXTERNAL;this.config.isAutoPublish&&!this._hasPublished?(e&&(i?null==(d=this._localStream.observer)||d.setPushVideo(!0):null==(c=this._localStream.observer)||c.setEnableVideo(!0)),t&&(r?null==(l=this._localStream.observer)||l.setPushAudio(!0):null==(u=this._localStream.observer)||u.setEnableAudio(!0))):null==(_=this._localStream.observer)||_.setPublish(!0)}this.emit("___onMediaServerClientPublish"),await this._publisher.publish(this._localStream),this._hasPublished=!0,this.emit(RoomEvent.ON_PUBLISH_RESULT,{isScreen:!1,state:PublishState.PUBLISH_SUCC})}catch(e){throw null==(h=this._ctx.monitor)||h.report("rtc_error",{message:`[room.publish] ${getErrorString(e)}`,error_code:-1}),this.emit(RoomEvent.ON_PUBLISH_RESULT,{isScreen:!1,state:PublishState.PUBLISH_FAIL,errorCode:e.code}),delete this._localStream,e}}this._localStream.pubAudio||this._localStream.pubVideo?this._ctx.handler&&this._localStream.startReport(this._onLocalStreamStats.bind(this),this._localStream.vendorHandler||this._ctx.handler):this._localStream.stopReport("unpublish")}async updatePubTrack(){var e;if(this.logger.info("updatePubTrack","Invoke updatePubTrack"),this._localStream)try{await this._publisher.updatePubTrack(this._localStream)}catch(t){throw null==(e=this._ctx.monitor)||e.report("rtc_error",{message:`[room.updatePubTrack] ${getErrorString(t)}`,error_code:-1}),t}}async unpublish(){var e,t;if(this.logger.info("unpublish","Invoke unpublish"),this._localStream)try{await this._publisher.unpublish(this._localStream),null==(e=this._localStream)||e.stopReport("unpublish"),await this._publisher.cleanStream(this._localStream),this._localStream=void 0}catch(e){throw null==(t=this._ctx.monitor)||t.report("rtc_error",{message:`[room.unpublish] ${getErrorString(e)}`,error_code:-1}),e}}async subscribe(e,t){var i;this.logger.info("subscribe","remoteStream %o",e);if(await this._subscriber.hasSubscribed(e)){const i=e.subMediaType|t;return i!==e.subMediaType?await this._subscriber.updateSubMediaType(e,i):void 0}const r=this._ctx.videoProfile.getSubLayer(e,this.config.remoteVideoConfig);try{await this._subscriber.subscribe(e,t,r)}catch(e){throw null==(i=this._ctx.monitor)||i.report("rtc_error",{message:`[room.subscribe] ${getErrorString(e)}`,error_code:-1}),e}}async updateSubVideoConfig(e){var t,i;const r=this._findRemoteStreamByScreen(e,!1);if(this.logger.info("updateSubVideoConfig","userId %s",e),!r)return;if(!await this._subscriber.hasSubscribed(r)||(null==(i=null==(t=r.attributes)?void 0:t.videoDescriptions)?void 0:i.length)<=1)return;const o=this._ctx.videoProfile.getSubLayer(r);return o?(r.originalStreamIndex=o.spatialLayer,this._subscriber.updateSubTrackLayer(r,o)):void 0}async unsubscribe(e,t){var i,r;this.logger.info("unsubscribe","Invoke unsubscribe");try{if(!await this._subscriber.hasSubscribed(e))return;const r=e.subMediaType-(e.subMediaType&t);if(!(null==(i=this._ctx.serverConfig)?void 0:i.muteReplaceUnsub)&&(r===ExtendMediaType.NONE||this.config.isMultiChatMode()&&r===MediaType$1.AUDIO))return await this._subscriber.unsubscribe(e);await this._subscriber.updateSubMediaType(e,r)}catch(e){throw null==(r=this._ctx.monitor)||r.report("rtc_error",{message:`[room.unsubscribe] ${getErrorString(e)}`,error_code:-1}),e}}async startSubtitle(e){if(!this._subtitleTool)throw new SDKError(ErrorCode.INVOKED_BEFORE_JOIN_ROOM,"join first");await this._subtitleTool.start(e)}async updateSubtitleConfig(e){if(!this._subtitleTool)throw new SDKError(ErrorCode.INVOKED_BEFORE_JOIN_ROOM,"join first");await this._subtitleTool.update(e)}async stopSubtitle(){var e;null==(e=this._subtitleTool)||e.stop()}async startForwardStream2Rooms(e){return this._forwardStreamManager.startForwardStream2Rooms(e)}async updateForwardStream2Rooms(e){return this._forwardStreamManager.updateForwardStream2Rooms(e)}async stopForwardStream2Rooms(){return this._forwardStreamManager.stopForwardStream2Rooms()}async pauseForwardStream2AllRooms(){return this._forwardStreamManager.pauseForwardStream2AllRooms()}async resumeForwardStream2AllRooms(){return this._forwardStreamManager.resumeForwardStream2AllRooms()}async updateMediaParams(e){return this._ctx.signalingManager.sendSignaling("updateMediaParams",{roomId:this.config.roomId,mediaParams:e})}async leave(e=!1){var t,i,r;this.logger.info("leave","Invoke leave"),null==(t=this._subtitleTool)||t.destroy(),delete this._subtitleTool;try{for(const e of this._remoteStreams.values())Array.isArray(e)&&e.forEach((e=>{var t;null==(t=e.observer)||t.setLogin(!1)}));this._localStream&&(null==(i=this._localStream.observer)||i.setLogin(!1)),await this._roomJoin.leave().catch((()=>{})),this.destroy(),this.config.report("rtc_leave_room",{error_code:0,message:"",elapse:this.config.getStayRoomDuration()})}catch(t){if(null==(r=this._ctx.monitor)||r.report("rtc_error",{message:`[room.leave] ${getErrorString(t)}`,error_code:-1}),t instanceof Error&&this.config.report("rtc_leave_room",{error_code:-1,message:t.message,elapse:this.config.getStayRoomDuration()}),e)throw t;this.destroy()}}updateRemoteUserPriority(e){var t;null==(t=this.remoteStreams.get(e))||t.forEach((t=>{const{userPriority:i}=this._ctx;t.hasSubscribed&&i.has(e)&&this._subscriber.updateSubPriority(t,i.get(e))}))}destroy(){var e,t;this.logger.info("destroy","Invoke destroy"),reportRtcInvokeStatus(this._ctx.id,"room_destroy",`${(new Error).stack}`),null==(e=this._subtitleTool)||e.destroy(),delete this._subtitleTool;const i=Array.from(this._remoteStreams.values()).flat();this._subscriber.destroy(i),this._subscriber.destroy(this._virtualStreams),this._publisher.destroy([this.localStream,this.localScreenStream]),this._roomJoin.destroy(),null==(t=this._clearSignalListeners)||t.call(this),this._remoteUsers=new Map,this._remoteStreams=new Map,this._localStream&&(this._localStream=void 0),this._localScreenStream&&(this._localScreenStream=void 0),this._userDuplicateLoginTimerMap.forEach((e=>{clearTimeout(e)})),this._userDuplicateLoginTimerMap.clear(),this._networkQualityManager.destroy(),this._videoSizeObserver.destroy(),this._csrcUserIdMap={},this._virtualStreams=[],this._remoteStreamStreamIdUserIdMap={},this._forwardStreamManager.destoy(),this._remoteUserMediaBanned.clear()}async updateToken(e){if(this.logger.info("updateToken","Invoke updateToken"),this.config.token=e,!this.config.isRTSOnlyRoom())try{await this._roomJoin.updateToken(e)}catch(e){throw this.safeEmit(RoomEvent.ON_ROOM_ERROR,{errorCode:ErrorCode.UPDATE_TOKEN_WITH_INVALID_TOKEN}),e}}sendUserMessage(e,t){return this._ctx.rtsLimiter.e2e.check(t),this._roomMessage.sendUserMessage(e,t)}sendRoomMessage(e,t=!1){return this._ctx.rtsLimiter.boradcast.check(e),this._roomMessage.sendRoomMessage(e,t)}async maybeFillBackFrame2Stream(e){var t;e.refreshBlackFrameLifetime(),(null==(t=e.videoTransceiver)?void 0:t.sender.track)||this._publisher.updatePubBlackFrame(e)}_onJoinSucc({joinRes:e,reconnect:t}){var i,r;this.logger.info("_onJoinSucc()","invoke. "+(t?"[reconnect]":"")),this.emit(RoomEvent.JOIN_SUCCESS,t),this._serverConfig=e.config,this.config.updateRoomAttributes(e.roomAttributes);const o=[],s=[],n=[],a=[],d=[];this.config.isRTSOnlyRoom()&&Array.isArray(e.userInfos)&&(e.clientsDetail=e.userInfos.map((e=>({clientId:e.userId,clientJoinTime:e.userJoinTime})))),null==(i=e.clientsDetail)||i.forEach((t=>{if(this._checkClientBanned(t),t.clientId===e.clientId)return;const i=this._remoteUsers.get(t.clientId);i?i._stillExist=!0:o.push(t)}));for(const e of this._remoteUsers.values())e._stillExist||s.push({clientId:e.userId}),delete e._stillExist;null==(r=e.streams)||r.forEach((e=>{const t=this._findRemoteStreamByScreen(e.clientId,e.screen);this.config.updateUserPubInfo(e),t?(t.stillExist=!0,t.streamId=e.streamId,d.push(e)):a.push(e)}));for(const e of this._remoteStreams.values())Array.isArray(e)&&e.forEach((e=>{e.stillExist?delete e.stillExist:n.push({clientId:e.userId,streamId:e.streamId,message:RemoveStreamMessage.clientDisconnected})}));s.forEach((e=>this._onUserDisconnection(e))),o.forEach((e=>this._onUserConnection(e))),n.forEach((e=>this._onRemoveStream(e))),a.forEach((e=>this._onAddStream(e,{fromSignal:!1}))),d.forEach((e=>this._onUpdateStreamAttributes(e))),this.config.resetUserPubInfo(),t&&this._handleSendOrRecvStreamAfterReconnect(),this.emit("__joinSuccess")}_handleSendOrRecvStreamAfterReconnect(){var e;this._localStream&&(this._publisher.cleanStream(this._localStream).then((()=>{var e;this._localStream&&(this._localStream.vendorCode=this.config.vendorConfig.vendorCode||0,null==(e=this._localStream.observer)||e.setLogin(!0))})),this._publisher.publish(this._localStream).then((()=>{var e;this._ctx.handler&&(null==(e=this._localStream)||e.startReport(this._onLocalStreamStats.bind(this),this._localStream.vendorHandler||this._ctx.handler)),this.emit(RoomEvent.ON_PUBLISH_RESULT,{isScreen:!1,state:PublishState.PUBLISH_SUCC,retry:!0})})).catch((e=>{this.logger.error(`failed repub error:${e}`),this.emit(RoomEvent.ON_PUBLISH_RESULT,{isScreen:!1,state:PublishState.PUBLISH_FAIL,errorCode:e.code,retry:!0})}))),this._localScreenStream&&(this._publisher.cleanStream(this._localScreenStream).then((()=>{var e;this._localScreenStream&&(null==(e=this._localScreenStream.observer)||e.setLogin(!0))})),this._publisher.publish(this._localScreenStream).then((()=>{var e;this._ctx.handler&&(null==(e=this._localScreenStream)||e.startReport(this._onLocalStreamStats.bind(this),this._localScreenStream.vendorHandler||this._ctx.handler)),this.emit(RoomEvent.ON_PUBLISH_RESULT,{isScreen:!0,state:PublishState.PUBLISH_SUCC,retry:!0})})).catch((e=>{this.logger.error(`failed repub screen stream error:${e}`),this.emit(RoomEvent.ON_PUBLISH_RESULT,{isScreen:!0,state:PublishState.PUBLISH_FAIL,errorCode:e.code,retry:!0})})));for(const e of this._remoteStreams.values())Array.isArray(e)&&e.forEach((async e=>{var t,i;if(e.hasSubscribed){e.resetHasSubscribed();try{this.logger.info(`start resubscribe ${e.userId} with ${e.subMediaType}`),videoInMediaType(e.subMediaType)&&(null==(t=e.observer)||t.setSubscribeVideo(!0)),audioInMediaType(e.subMediaType)&&(null==(i=e.observer)||i.setSubscribeAudio(!0)),await this._subscriber.subscribe(e,e.subMediaType),this.logger.info(`success resubscribe ${e.userId} with ${e.subMediaType}`),this.safeEmit(RoomEvent.RESUBSCRIBE,{stream:e}),this.emit(RoomEvent.ON_SUBSCRIBE_RESULT,{state:SubscribeState.SUBSCRIBE_SUCC,userId:e.userId,isScreen:e.isScreen,retry:!0})}catch(t){if(this.emit(RoomEvent.ON_SUBSCRIBE_RESULT,{state:SubscribeState.SUBSCRIBE_FAIL,userId:e.userId,isScreen:e.isScreen,errorCode:t.code,retry:!0}),this.logger.error(`failed resubscribe ${e.userId} with ${e.subMediaType}, error:${t}`),t.code===ErrorCode.NOT_CONNECTED_YET)return void(e.streamState=StreamState.SUB_ED);await this._subscriber.cleanStream(e),e.resetHasSubscribed()}}}));null==(e=this._subtitleTool)||e.reconnect(),this._forwardStreamManager.resumeFromReconnect()}_handleFFAudioTrack(){var e,t;const i=null==(e=this._ctx.handler)?void 0:e.audioTrack4ff,r=null==(t=this._ctx.handler)?void 0:t.getTransceivers();if(i&&Array.isArray(r)){const e=r.find((e=>{var t;return(null==(t=null==e?void 0:e.receiver)?void 0:t.track)===i}));if(e){const t=new RemoteStream(this._ctx,"ff-stream","ff-stream",!1,!1,virtualStreamAttributes);t.virtual=!0,t.audioTransceiver=e,t.audioMid="0",t.audioTrack=createRemoteAudioTrack(this._ctx,i,{streamIndex:ExtendStreamIndex.VIRTUAL}),this._virtualStreams.push(t),this.safeEmit(RoomEvent.SUBSCRIBE_PUSH_TRACK,{stream:t})}}}_findRemoteStream(e,t){const i=this._remoteStreams.get(e);return Array.isArray(i)?i.find((e=>e.streamId===t)):null}_findRemoteStreamByScreen(e,t){const i=this._remoteStreams.get(e);return Array.isArray(i)?i.find((e=>e.isScreen===t)):null}_onAddStream(e,{needEmit:t=!0,fromSignal:i=!0,virtual:r=!1}={}){var o;if(e.clientId===this.config.userId)return;const{isAutoSubscribeAudio:s,isAutoSubscribeVideo:n}=this.config,a=this._findRemoteStreamByScreen(e.clientId,e.screen);if(a&&a.streamId!==e.streamId){const t=null==(o=this._remoteStreams.get(e.clientId))?void 0:o.filter((e=>e.streamId!==a.streamId));this._subscriber.cleanStream(a),this._remoteStreams.set(e.clientId,t||[])}let d=this._findRemoteStream(e.clientId,e.streamId);if(this._remoteStreamStreamIdUserIdMap[e.streamId]=e.clientId,d)d.attributes=e.attributes;else if(d=new RemoteStream(this._ctx,e.clientId,e.streamId,e.screen,!1,e.attributes),d.virtual=r,this._initStreamListeners(d),!r){const t=this._remoteStreams.get(e.clientId);t?t.push(d):this._remoteStreams.set(e.clientId,[d])}if(d.remoteSessionId=e.remoteSessionId||"",d.observer=new RecvFrameObserver(this._ctx,d),!d.isScreen&&n&&!this._getRemoteUserMediaBanned(e.clientId,MediaType$1.VIDEO)&&(i&&d.hasVideo&&(d.attributes.extvideo?(d.observer.setExternalVideoSource(!0),d.observer.setPushVideo(!0)):(d.observer.setExternalVideoSource(!1),d.observer.setPublishVideo(!0))),i&&d.hasAudio&&s&&!this.config.isMultiChatMode()&&!this._getRemoteUserMediaBanned(e.clientId,MediaType$1.AUDIO)&&(d.attributes.extaudio?(d.observer.setExternalAudioSource(!0),d.observer.setPushAudio(!0)):(d.observer.setExternalAudioSource(!1),d.observer.setPublishAudio(!0))),t&&!i)){const{isAutoSubscribeAudio:e,isAutoSubscribeVideo:t}=this.config;d.observer.setLogin(!0,{audio:!!e&&!this.config.isMultiChatMode(),video:!!t})}return t&&this.safeEmit(SignalEvent.ON_ADD_STREAM,{stream:d}),d}_onUserConnection(e){var t;if(e.clientId===this.config.userId)return;const i=this._userDuplicateLoginTimerMap.get(e.clientId);if("number"==typeof i)return this._userDuplicateLoginTimerMap.delete(e.clientId),void self.clearTimeout(i);const r={userId:e.clientId,extraInfo:null==(t=e.attributes)?void 0:t.extra_info};this._remoteUsers.set(e.clientId,{...r}),this.safeEmit(SignalEvent.USER_CONNECTION,{userInfo:r,publishState:this.config.getUserPubInfo(r.userId)}),this._checkClientBanned(e)}_onUserDisconnection({clientId:e,tag:t,code:i,forbiddenTime:r}){if(e)if(e===this.config.userInfo.userId){let e=null;t===UserDisconnectionTag.kickedByAdmin?e=ErrorCode.KICKED_OUT:t===UserDisconnectionTag.onUserTokenDidExpire?e=ErrorCode.TOKEN_EXPIRED:t===UserDisconnectionTag.userDuplicateLogin&&(e=ErrorCode.DUPLICATE_LOGIN),i===UserDisconnectionCode.roomDismissByAdmin&&(e=ErrorCode.ROOM_DISMISS),e&&this.safeEmit(RoomEvent.ON_ROOM_ERROR,{errorCode:e,forbiddenTime:r})}else{let i=UserOfflineReason.DROPPED;t===UserDisconnectionTag.userLeave?i=UserOfflineReason.QUIT:t===UserDisconnectionTag.kickedByAdmin?i=UserOfflineReason.KICKED_BY_ADMIN:t===UserDisconnectionTag.roleChanged&&(i=UserOfflineReason.SWITCH_TO_INVISIBLE);const r=()=>{var r;this._remoteUsers.delete(e);const o=[];null==(r=this._remoteStreams.get(e))||r.forEach((e=>{o.push(this._onRemoveStream({clientId:e.userId,streamId:e.streamId,message:RemoveStreamMessage.clientDisconnected}))})),this._remoteStreams.delete(e),Promise.all(o).finally((()=>{this.safeEmit(RoomEvent.ON_USER_LEAVE,{userInfo:{userId:e},reason:i,tag:t})}))};if(t===UserDisconnectionTag.userDuplicateLogin){const t=this._userDuplicateLoginTimerMap.get(e);t&&self.clearTimeout(t);const i=self.setTimeout(r,5e3);this._userDuplicateLoginTimerMap.set(e,i)}else r()}}async _onRemoveStream(e){var t,i;if(e.clientId===this.config.userId)return;const r=this._remoteStreams.get(e.clientId);if(!r)return;const o=r.find((t=>t.streamId===e.streamId));if(!o)return;o.hasVideo&&(null==(t=o.observer)||t.setPublishVideo(!1)),o.hasAudio&&!this.config.isMultiChatMode()&&(null==(i=o.observer)||i.setPublishAudio(!1));const s=r.filter((t=>t.streamId!==e.streamId));this._remoteStreams.set(e.clientId,s);const n={isScreen:o.isScreen,userId:o.userId,streamId:o.streamId,attributes:{audiostream:o.attributes.audiostream,videostream:o.attributes.videostream}};try{await this._subscriber.handleRemoveStream(o)}catch(e){console.error(e)}this.safeEmit(SignalEvent.ON_REMOVE_STREAM,{stream:n,reason:e.message})}_onUpdateUserAttributes(e){this._checkClientBanned(e)}_onUpdateRoomAttributes(e){var t;e.roomAttributes&&(this.config.updateRoomAttributes(e.roomAttributes),this._ctx&&(this._ctx.callId=e.roomAttributes.callId)),(null==(t=e.roomAttributes)?void 0:t.multiChatMode)&&this._handleFFAudioTrack()}_onUpdateStreamAttributes(e){var t,i,r,o,s,n,a,d,c,l,u,_,h,p,m,S,g,v;const{isAutoSubscribeAudio:f,isAutoSubscribeVideo:E}=this.config,{clientId:T,streamId:R,attributes:b}=e,y=this._findRemoteStream(T,R);if(!y)return;const I=y.attributes,C={...I,...b};let A=!1;const k=C.localaudio!==I.localaudio;let M=!1,N=!1;const O=C.localvideo!==I.localvideo;let P=!1,D=ExtendMediaType.NONE,w=ExtendMediaType.NONE;C.audiostream!==I.audiostream&&(A=C.localaudio,M=!!C.audiostream,C.audiostream?D|=MediaType$1.AUDIO:w|=MediaType$1.AUDIO),C.videostream!==I.videostream&&(N=C.localvideo,P=!!C.videostream,C.videostream?D|=MediaType$1.VIDEO:w|=MediaType$1.VIDEO),D&&this.safeEmit(RoomEvent.ON_USER_PUBLISH_STATE_CHANGE,{userId:T,mediaType:D,isScreen:y.isScreen,pubState:PubState.PUB,remoteStream:y}),w&&this.safeEmit(RoomEvent.ON_USER_PUBLISH_STATE_CHANGE,{userId:T,mediaType:w,isScreen:y.isScreen,pubState:PubState.UNPUB,remoteStream:y}),y.remoteSessionId=e.remoteSessionId||"",y.attributes=C,C.localaudio!==I.localaudio&&(C.localaudio?((f||y.subAudio)&&C.audiostream&&(C.extaudio?(null==(t=y.observer)||t.setExternalAudioSource(!0),null==(i=y.observer)||i.setPushAudio(!0)):(null==(r=y.observer)||r.setExternalAudioSource(!1),null==(o=y.observer)||o.setEnableAudio(!0))),this.safeEmit(RoomEvent.ON_USER_START_AUDIO_CAPTURE,{userId:T},y)):(C.extaudio?(null==(s=y.observer)||s.setExternalAudioSource(!0),null==(n=y.observer)||n.setPushAudio(!1)):(null==(a=y.observer)||a.setExternalAudioSource(!1),null==(d=y.observer)||d.setEnableAudio(!1)),!y.isScreen&&this.safeEmit(RoomEvent.ON_USER_STOP_AUDIO_CAPTURE,{userId:T}))),C.localvideo!==I.localvideo&&(C.localvideo?((E||y.subVideo)&&C.videostream&&(C.extvideo?(null==(c=y.observer)||c.setExternalVideoSource(!0),null==(l=y.observer)||l.setPushVideo(!0)):(null==(u=y.observer)||u.setExternalVideoSource(!1),null==(_=y.observer)||_.setEnableVideo(!0))),this.safeEmit(RoomEvent.ON_USER_START_VIDEO_CAPTURE,{userId:T})):(C.extvideo?(null==(h=y.observer)||h.setExternalVideoSource(!0),null==(p=y.observer)||p.setPushVideo(!1)):(null==(m=y.observer)||m.setExternalVideoSource(!1),null==(S=y.observer)||S.setEnableVideo(!1)),!y.isScreen&&this.safeEmit(RoomEvent.ON_USER_STOP_VIDEO_CAPTURE,{userId:T}))),A&&!k&&f&&(null==(g=y.observer)||g.setRemoteUnmuteAudio(M)),N&&!O&&E&&(null==(v=y.observer)||v.setRemoteUnmuteVideo(P)),"number"==typeof C.videoType&&C.videoType!==I.videoType&&this.safeEmit(RoomEvent.VIDEO_TYPE_CHANGE,{userId:y.userId,isScreen:y.isScreen,type:C.videoType===VideoType.BLACK?SEIStreamEventType.BLACK:SEIStreamEventType.NORMAL})}_onPushTrack(e){var t;if(!(null==(t=e.streamId)?void 0:t.startsWith("audio_mux")))return void this.config.report("rtc_error",{message:`onPushTrack, userId: ${e.clientId}, ${e.streamId}`,error_code:RtcErrorCode.TRACK_ERROR});const i=this._onAddStream({...e,attributes:virtualStreamAttributes},{needEmit:!1,fromSignal:!1,virtual:!0});i&&this._subscriber.subscribe4pushTrack(i,e).then((()=>{this.safeEmit(RoomEvent.SUBSCRIBE_PUSH_TRACK,{stream:i}),this._virtualStreams.push(i)})).catch((e=>{this.logger.error("subscribe","push track failed %o",e)}))}_onRemoveTrack({clientId:e,streamId:t,message:i,trackType:r}){this.logger.info("_onRemoveTrack","remove track: %o",e);const o=this._findRemoteStream(e,t);o&&(o.removeTrack=!0,this._subscriber.unsubscribe4removeTrack(o,i,r),this.emit(RoomEvent.REMOVE_PUSH_TRACK,{stream:o,mediaType:r+1}))}_onMeetingSpeakerChange(e){if(Array.isArray(null==e?void 0:e.speakerCsrcInfo)){const t={};null==e||e.speakerCsrcInfo.forEach((({csrc:e,userId:i,isScreen:r})=>{r||(t[e]=i)})),this._csrcUserIdMap=t}Array.isArray(e.muxStreamInUse)&&this._virtualStreams.forEach((t=>{var i;(null==(i=e.muxStreamInUse)?void 0:i.includes(t.streamId))?t.virtualOccupy=!0:t.virtualOccupy=!1}))}getActiveSpeakerInMultiChatMode(){const e=[];return this._virtualStreams.forEach((t=>{var i;const r=null==(i=t.audioTransceiver)?void 0:i.receiver;if(r){const[t]=r.getContributingSources()||[];if(t){const{audioLevel:i,source:r}=t;this._csrcUserIdMap[r]&&e.push({userId:this._csrcUserIdMap[r],audioLevel:i})}}})),e.length&&e.sort(((e,t)=>e.audioLevel-t.audioLevel)),e}_onReconnecting(){var e,t,i,r;for(const e of this._remoteStreams.values())Array.isArray(e)&&e.forEach((e=>{var t;null==(t=e.observer)||t.setDisconnect(),this._subscriber.cleanStream(e)}));this._virtualStreams.forEach((e=>{var t;this.emit(RoomEvent.REMOVE_PUSH_TRACK,{stream:e,mediaType:MediaType$1.AUDIO}),null==(t=e.observer)||t.setDisconnect(),this._subscriber.cleanStream(e)})),this._virtualStreams=[],null==(t=null==(e=this.localStream)?void 0:e.observer)||t.setDisconnect(),this._publisher.cleanStream(this.localStream),null==(r=null==(i=this.localScreenStream)?void 0:i.observer)||r.setDisconnect(),this._publisher.cleanStream(this.localScreenStream)}_onConnectionStateChange(e){e.state===ConnectionState.CONNECTION_STATE_RECONNECTING?this._onReconnecting():e.state===ConnectionState.CONNECTION_STATE_RECONNECTED&&this._roomJoin.join(!0)}_initStreamListeners(e){e.on("ontrack",(e=>{e.track})),e.on("onSEIMessage",(t=>{this.emit(RoomEvent.ON_SEI_MESSAGED_RECEIVED,{sei:t,remoteStreamKey:{userId:e.userId,roomId:this.config.roomId,streamIndex:e.isScreen?StreamIndex$1.STREAM_INDEX_SCREEN:StreamIndex$1.STREAM_INDEX_MAIN}})}))}_onCustomMessage(e){var t;(null==(t=this._subtitleTool)?void 0:t.onMessageRecv(e))||this.safeEmit(SignalEvent.ON_CUSTOM_MESSAGE,e)}_onUserMessageReceived(e){this.safeEmit(SignalEvent.USER_MESSAGE_RECEIVED,{userId:e.from,message:e.msg})}_onUserBinaryMessageReceived(e){var t;const i={userId:e.from,message:e.msg};(null==(t=this._subtitleTool)?void 0:t.onMessageRecv(i))||this.safeEmit(SignalEvent.USER_BINARY_MESSAGE_RECEIVED,i)}_initSubtitleTool(){this._subtitleTool=new SubtitleTool(this._ctx,this.config),this._subtitleTool.onEvent=e=>{this.emit(RoomEvent.ON_SUBTITLE_STATE_CHANGED,e)},this._subtitleTool.onMessage=e=>{this.emit(RoomEvent.ON_SUBTITLE_MESSAGE_RECEIVED,e)}}_onPostProcessingMessage(e){var t;if(!e.body)return;if("subtitleCallback"===e.type)return void(null==(t=this._subtitleTool)||t.onResult(e));const i=e.body,r=i.error||0;let o=StreamMixingEventType.START;const s=["success","parameter error","subscription timeout","ffmpeg error","cdn error","publish error"];if("2.0"===i.protocol){switch(i.eventType){case"TranscodeStarted":0!==i.error&&(o=StreamMixingEventType.START_FAILED);break;case"TranscodeStateChanged":o=0!==i.error?StreamMixingEventType.START_FAILED:StreamMixingEventType.START_SUCCESS;break;case"TranscodeStopped":o=0!==i.error?StreamMixingEventType.STOP_FAILED:StreamMixingEventType.STOP_SUCCESS;break;case"TranscodeUpdated":o=0!==i.error?StreamMixingEventType.UPDATE_FAILED:StreamMixingEventType.UPDATE_SUCCESS}this.safeEmit(SignalEvent.POST_PROCESSING_MESSAGE,{code:r,protocol:i.protocol,error:i.error,eventType:o,message:s[r]})}this.safeEmit(SignalEvent.POST_PROCESSING_MESSAGE,{code:r,message:s[r],type:e.type})}_onUserTokenWillExpire(){this.safeEmit(SignalEvent.ON_USER_TOKEN_WILL_EXPIRE,null)}_onUserTokePublishPrivilegeWillExpire(){this.safeEmit(SignalEvent.ON_TOKEN_PUBLISH_PRIVILEGE_WILL_EXPIRE,null)}_onUserTokenPublishPrivilegeDidExpire(){this.safeEmit(SignalEvent.ON_TOKEN_PUBLISH_PRIVILEGE_DID_EXPIRED,null)}_onUserTokeSubscribePrivilegeWillExpire(){this.safeEmit(SignalEvent.ON_TOKEN_SUBSCRIBE_PRIVILEGE_WILL_EXPIRE,null)}_onUserTokenSubscribePrivilegeDidExpire(){this.safeEmit(SignalEvent.ON_TOKEN_SUBSCRIBE_PRIVILEGE_DID_EXPIRED,null)}async _onStreamFailed(e){var t,i;if("publish"===e.type){let r;if((null==(t=this.localStream)?void 0:t.streamId)===e.streamId?r=this.localStream:(null==(i=this.localScreenStream)?void 0:i.streamId)===e.streamId&&(r=this.localScreenStream),!r)return;await this._publisher.unpublish(r).catch((()=>{})),await this._publisher.cleanStream(r),await this._publisher.publish(r).catch((()=>{}))}else if("subscribe"===e.type){const t=this._remoteStreamStreamIdUserIdMap[e.streamId],i=this._findRemoteStream(t,e.streamId);i&&(await this._subscriber.handleStreamFailed(i),this.safeEmit(RoomEvent.RESUBSCRIBE,{stream:i}))}}_onStreamControlMessage(e){var t,i;e.type===StreamControlType.PushLimitWarn&&((null==(t=this._localStream)?void 0:t.pubAudio)||(null==(i=this._localStream)?void 0:i.pubVideo)||this.unpublish())}async _onPublishOnDemand(){var e,t,i,r,o;if(this._publishOnDemandItem&&!this._publishOnDemandBusy&&!1!==(null==(i=null==(t=null==(e=this._serverConfig)?void 0:e.engine_VPM)?void 0:t.ondemand)?void 0:i.enable)){if(null==(r=this._localStream)?void 0:r.videoTransceiver){this._publishOnDemandBusy=!0;const e=this._publishOnDemandItem;this._publishOnDemandItem=void 0;const t=[],i=this._localStream.stream.id,{sender:r}=this._localStream.videoTransceiver,o=r.getParameters();if(reportRtcInvokeStatus(this._ctx.id,"sender.getParameters",JSON.stringify(o),0,i),Array.isArray(o.encodings)&&Array.isArray(e)){const r={};this.logger.info("_onPublishOnDemand exec","usedDescriptions: %o",e),e.forEach((e=>{var t,o,s,n;if(null==(t=e.StreamIds)?void 0:t.includes(i)){const t=(null==(o=e.Metadata)?void 0:o.VideoIndex)??0;let i=0;(null==(s=this._ctx.serverConfig)?void 0:s.e2eFeedback)&&(i=Math.max(...Object.keys((null==(n=e.Metadata)?void 0:n.VideoKbpsHist)??{}).map((e=>Number(e))),0)),r[t]={kbps:i}}}));const s=[...this._localStream.pubAttributes.videoDescriptions];o.encodings=o.encodings.map((e=>{var i,o;if(e.rid){if(r[e.rid]){e.active=!0;const t=null==(i=r[e.rid])?void 0:i.kbps;t&&(e.maxBitrate=1e3*calculateKbps(e.rid,t,s))}else e.active=!1;const o=Number(e.rid);t[o]=e.active}else{const t=null==(o=r[0])?void 0:o.kbps;t&&(e.maxBitrate=1e3*calculateKbps(void 0,t,s))}return e})),this.config.report("rtc_invoke_status",{sdk_api_name:"onPublishOnDemand",message:JSON.stringify(o.encodings),error_code:0,stream_id:i,elapse:0}),this._ctx.videoProfile.activeSimStreams=t}this.logger.info("sender.setParameters()",JSON.stringify(o.encodings)),reportRtcInvokeStatus(this._ctx.id,"sender.setParameters",JSON.stringify(o),0,i),await r.setParameters(o),this._publishOnDemandBusy=!1}else if(!(null==(o=this._localStream)?void 0:o.videoTransceiver))return;this._onPublishOnDemand()}}_onRTT(e){const{StreamIds:t,Metadata:i}=e;if((null==t?void 0:t.length)&&i){const e=t[0];this._ctx.streamRTT[e]={audio:i.audio_rtt,video:i.video_rtt}}}_onRSCP(e,t){!!e.find((e=>{var t,i,r;return null==(r=null==e?void 0:e.StreamIds)?void 0:r.includes(null==(i=null==(t=this._localStream)?void 0:t.stream)?void 0:i.id)}))&&(t?this._pubTransceiverReady=!0:this._onceTriggerBySignal=!0,t&&this._onceTriggerBySignal||(this._publishOnDemandItem=e),this._pubTransceiverReady&&this._onPublishOnDemand())}_onSSC(e){const{StreamIds:t,Metadata:i}=e,r=t[0],o=this._remoteStreamStreamIdUserIdMap[r],s=this._findRemoteStream(o,r),n={userId:o,isScreen:!!s&&s.isScreen,beforeVideoIndex:i.ssc_items[0].prev_layer_id,afterVideoIndex:i.ssc_items[0].cur_layer_id,beforeEnable:0!==i.ssc_items[0].prev_video_open,afterEnable:0!==i.ssc_items[0].cur_video_open,reason:i.ssc_items[0].change_reason};this.emit(RoomEvent.ON_SIMULCAST_SUBSCRIBE_FALLBACK,n)}_reportNetworkQuality(e,t){this.emit(RoomEvent.ON_NETWORK_QUALITY,e,t)}_emitVideoSizeChange(e,t,i,r){this.emit(RoomEvent.ON_REMOTE_VIDEO_SIZE_CHANGED,{roomId:this.config.roomId,userId:e,streamIndex:t?StreamIndex$1.STREAM_INDEX_SCREEN:StreamIndex$1.STREAM_INDEX_MAIN},{width:i,height:r})}async setAudioEncodeMaxBitrate(e,t){var i,r;const o=e===StreamIndex$1.STREAM_INDEX_MAIN?this.localStream:this.localScreenStream;if(null==o?void 0:o.pubAudio){const e=null==(i=o.audioTransceiver)?void 0:i.sender.getParameters();reportRtcInvokeStatus(this._ctx.id,"sender.getParameters",JSON.stringify(e),0,o.streamId),(null==e?void 0:e.encodings.length)&&(e.encodings[0].maxBitrate=1e3*t,reportRtcInvokeStatus(this._ctx.id,"sender.setParameters",JSON.stringify(e),0,o.streamId),await(null==(r=o.audioTransceiver)?void 0:r.sender.setParameters(e)))}}_onEngineControlMessage({type:e,body:t}){var i,r;if(e===EngineControlType.CHANGE_CODEC){if(!getParameter("SDK_CODEC_NEGOTIATION"))return void this.logger.info("_onEngineControlMessage","SDK_CODEC_NEGOTIATION is false, ignore");const{codec:e,media:o,streamId:s}=t;if(!o||"audio"===o)return;const n=e.split(",").map((e=>e.trim().toUpperCase()));let a;this.logger.info("_onEngineControlMessage","changeCodec to %s",e),s?((null==(i=this.localStream)?void 0:i.streamId)===s?a=this.localStream:(null==(r=this.localScreenStream)?void 0:r.streamId)===s&&(a=this.localScreenStream),null==a||a.setChangeCodecs(n)):"video"===o?(a=this.localStream,this._ctx.targetCodec=n[0]):"screen"===o&&(a=this.localScreenStream,this._ctx.targetScreenCodec=n[0]),a&&this.emit(RoomEvent.UPDATE_PUBLISH,{streamIndex:a.isScreen?StreamIndex$1.STREAM_INDEX_SCREEN:StreamIndex$1.STREAM_INDEX_MAIN})}}_checkClientBanned({clientId:e,attributes:t}){if(!t||!e)return;const{serverMuteAudio:i,serverMuteVideo:r}=t;if(r){const t=1===r;this.safeEmit(RoomEvent.ON_VIDEO_STREAM_BANNED,{uid:e,banned:t}),this._setRemoteUserMediaBanned(e,MediaType$1.VIDEO,t),this._maybeStartReceiveFirstFrameForServerMute(e,MediaType$1.VIDEO,t)}if(i){const t=1===i;this.safeEmit(RoomEvent.ON_AUDIO_STREAM_BANNED,{uid:e,banned:t}),this._setRemoteUserMediaBanned(e,MediaType$1.AUDIO,t),this._maybeStartReceiveFirstFrameForServerMute(e,MediaType$1.AUDIO,t)}}_setRemoteUserMediaBanned(e,t,i){let r=this._remoteUserMediaBanned.get(e)??0;i?r|=t:r&=~t,this._remoteUserMediaBanned.set(e,r)}_getRemoteUserMediaBanned(e,t){return t&(this._remoteUserMediaBanned.get(e)??0)}_maybeStartReceiveFirstFrameForServerMute(e,t,i){var r,o;if(i)return;const s=this._remoteStreams.get(e)??[];for(const e of s)e.isScreen||e.attributes.localvideo&&e.subVideo&&(null==(r=e.observer)||r.setExternalVideoSource(e.attributes.extvideo),null==(o=e.observer)||o.setUnmuteVideo(!0))}}__decorateClass$4([checkRoomState],Room.prototype,"publishScreen",1),__decorateClass$4([checkRoomState],Room.prototype,"updatePubScreenTrack",1),__decorateClass$4([checkRoomState],Room.prototype,"unpublishScreen",1),__decorateClass$4([checkRoomState],Room.prototype,"liveControlMessage",1),__decorateClass$4([checkRoomState],Room.prototype,"publicStreamControlMessage",1),__decorateClass$4([checkRoomState],Room.prototype,"updateUserAttributes",1),__decorateClass$4([checkRoomState],Room.prototype,"publish",1),__decorateClass$4([checkRoomState],Room.prototype,"updatePubTrack",1),__decorateClass$4([checkRoomState],Room.prototype,"unpublish",1),__decorateClass$4([checkRoomState],Room.prototype,"subscribe",1),__decorateClass$4([checkRoomState],Room.prototype,"updateSubVideoConfig",1),__decorateClass$4([checkRoomState],Room.prototype,"unsubscribe",1),__decorateClass$4([checkRoomState],Room.prototype,"startSubtitle",1),__decorateClass$4([checkRoomState],Room.prototype,"stopSubtitle",1),__decorateClass$4([checkRoomState],Room.prototype,"startForwardStream2Rooms",1),__decorateClass$4([checkRoomState],Room.prototype,"updateForwardStream2Rooms",1),__decorateClass$4([checkRoomState],Room.prototype,"stopForwardStream2Rooms",1),__decorateClass$4([checkRoomState],Room.prototype,"pauseForwardStream2AllRooms",1),__decorateClass$4([checkRoomState],Room.prototype,"resumeForwardStream2AllRooms",1),__decorateClass$4([checkRoomState],Room.prototype,"updateMediaParams",1),__decorateClass$4([checkRoomState],Room.prototype,"updateRemoteUserPriority",1),__decorateClass$4([checkRoomState],Room.prototype,"updateToken",1),__decorateClass$4([checkRoomState],Room.prototype,"sendUserMessage",1),__decorateClass$4([checkRoomState],Room.prototype,"sendRoomMessage",1),__decorateClass$4([checkRoomState],Room.prototype,"maybeFillBackFrame2Stream",1);const isValidAudioFile=async(e,t)=>{const i=new Audio(URL.createObjectURL(new Blob([e],t)));try{return i.muted=!0,await i.play(),i.pause(),!0}catch(e){return!1}};var __defProp$3=Object.defineProperty,__getOwnPropDesc$3=Object.getOwnPropertyDescriptor,__decorateClass$3=(e,t,i,r)=>{for(var o,s=r>1?void 0:r?__getOwnPropDesc$3(t,i):t,n=e.length-1;n>=0;n--)(o=e[n])&&(s=(r?o(t,i,s):o(s))||s);return r&&s&&__defProp$3(t,i,s),s};class AudioMixingManager{constructor(e,t){var i,r;__publicField(this,"_sharedAudioContext",new AudioContext),__publicField(this,"_workletReady"),__publicField(this,"_audioDestination",this._sharedAudioContext.createMediaStreamDestination()),__publicField(this,"_localGainNode",this._sharedAudioContext.createGain()),__publicField(this,"_bufferGainNode",this._sharedAudioContext.createGain()),__publicField(this,"_audioBufferSource"),__publicField(this,"_localSource"),__publicField(this,"_context"),__publicField(this,"_failedAudioList",[]),__publicField(this,"_startingIds",new Map),__publicField(this,"_revokeURLs",new Set),__publicField(this,"_audioFetchMap",new Map),__publicField(this,"_audioFetchConfig",new Map),__publicField(this,"mixingMap",new Map),__publicField(this,"resourcesCache",new Map),__publicField(this,"volumeConfig",new Map),__publicField(this,"cachedBuffer",[]),__publicField(this,"id","AudioMixingManager"),this.engineId=t,this._context=e;try{this._workletReady=null==(r=null==(i=this._sharedAudioContext.audioWorklet)?void 0:i.addModule)?void 0:r.call(i,dumpAudioDataWorklet),this._workletReady.catch((()=>{this._workletReady=null}))}catch{this._workletReady=null}this._localGainNode.gain.value=1}mixMediaStream(e){this._localSource&&this._localSource.disconnect(this._localGainNode),this._localSource=this._sharedAudioContext.createMediaStreamSource(e),this._localSource.connect(this._localGainNode).connect(this._audioDestination)}async startAudioMixing(e,t,i){if(void 0!==this._startingIds.get(e))return void console.warn(`AudioMixing task id: ${e} is starting`);this._startingIds.set(e,e);const{playCount:r,type:o}=i;checkEnum(o,"mixingType",values(AudioMixingType));const s=this._context.getLocalAudioTrack();if(!s)return;const n=s.preprocessingTrack;n&&this.mixMediaStream(new MediaStream([n])),s.once("needReplaceTrack",(()=>{this.mixMediaStream(new MediaStream([s.preprocessingTrack]))}));const a=this.mixingMap.get(e);if(null==a?void 0:a.audioNode){a.audioNode.pause(),this._context.emitMessage({mixId:e,state:AudioMixingState.AUDIO_MIXING_STATE_STOPPED,error:AudioMixingError.AUDIO_MIXING_ERROR_OK});try{a.gainNode.disconnect(this._audioDestination),a.audioSource.disconnect(a.gainNode)}catch(e){}}let d;const c=this.resourcesCache.get(e);if(c&&c.filePath===t)d=c.getAudioNode();else{const i=await fetch(t,{mode:"cors"}).then((t=>{if(t.ok)return t.arrayBuffer();throw this._context.emitMessage({mixId:e,state:AudioMixingState.AUDIO_MIXING_STATE_FAILED,error:AudioMixingError.AUDIO_MIXING_ERROR_START_FAILED}),this._startingIds.delete(e),this.mixingMap.delete(e),new SDKError(ErrorCode.LOAD_RESOURCES_FAILED,t.statusText)}));let r;t.endsWith("mp3")?r={type:"audio/mpeg"}:t.endsWith("aac")&&(r={type:"audio/aac"});if(!await isValidAudioFile(i,r))throw this._context.emitMessage({mixId:e,state:AudioMixingState.AUDIO_MIXING_STATE_FAILED,error:AudioMixingError.AUDIO_MIXING_ERROR_START_FAILED}),this._startingIds.delete(e),this.mixingMap.delete(e),new SDKError(ErrorCode.LOAD_RESOURCES_FAILED,"invalid audio resource");d=new Audio,d.crossOrigin="anonymous",d.src=URL.createObjectURL(new Blob([i],r))}if(r<=0)d.loop=!0;else if(r>0){let t=r;d.onended=()=>{--t>0?d.play():(this.mixingMap.delete(e),this._context.emitMessage({mixId:e,state:AudioMixingState.AUDIO_MIXING_STATE_FINISHED,error:AudioMixingError.AUDIO_MIXING_ERROR_OK}))}}try{await d.play()}catch(e){console.error(e),this._failedAudioList.push(d),this._context.onAutoPlayFailed({userId:this.id,kind:"audio",streamIndex:StreamIndex$1.STREAM_INDEX_MAIN,mediaType:MediaType$1.AUDIO})}this._startingIds.delete(e);const l=this._sharedAudioContext.createMediaElementSource(d),u=this._sharedAudioContext.createGain(),_=this.volumeConfig.get(e);if(u.gain.value=_?_/100:1,l.connect(u).connect(this._audioDestination),this.mixingMap.set(e,{audioSource:l,audioNode:d,gainNode:u,type:"file"}),o===AudioMixingType.PUBLISH)try{u.disconnect(this._sharedAudioContext.destination)}catch(e){}else u.connect(this._sharedAudioContext.destination);this._context.updateLocalAudioTrack(this._audioDestination.stream.getAudioTracks()[0],i.type),this._context.emitMessage({mixId:e,state:AudioMixingState.AUDIO_MIXING_STATE_PLAYING,error:AudioMixingError.AUDIO_MIXING_ERROR_OK}),this.updateFetcher(e)}stopAudioMixing(e){const t=this.mixingMap.get(e);t&&"file"===t.type&&(this.mixingMap.delete(e),t.audioNode.pause(),t.audioSource.disconnect(t.gainNode),t.gainNode.disconnect(this._audioDestination),this.updateFetcher(e),this._context.emitMessage({mixId:e,state:AudioMixingState.AUDIO_MIXING_STATE_STOPPED,error:AudioMixingError.AUDIO_MIXING_ERROR_OK}))}pauseAudioMixing(e){const t=this.mixingMap.get(e);t&&(this._context.emitMessage({mixId:e,state:AudioMixingState.AUDIO_MIXING_STATE_PAUSED,error:AudioMixingError.AUDIO_MIXING_ERROR_OK}),t.audioNode.pause())}resumeAudioMixing(e){const t=this.mixingMap.get(e);t&&(this._context.emitMessage({mixId:e,state:AudioMixingState.AUDIO_MIXING_STATE_PLAYING,error:AudioMixingError.AUDIO_MIXING_ERROR_OK}),t.audioNode.play())}async preloadAudioMixing(e,t){this.stopAudioMixing(e);const i=await fetch(t,{mode:"cors"}).then((e=>{if(e.ok)return e.arrayBuffer();throw new SDKError(ErrorCode.LOAD_RESOURCES_FAILED,e.statusText)})).catch((t=>{if(this._context.emitMessage({mixId:e,state:AudioMixingState.AUDIO_MIXING_STATE_FAILED,error:AudioMixingError.AUDIO_MIXING_ERROR_PRELOAD_FAILED}),t instanceof SDKError)throw t;throw new SDKError(ErrorCode.LOAD_RESOURCES_FAILED,"Load resources failed",t)}));let r;t.endsWith("mp3")?r={type:"audio/mpeg"}:t.endsWith("aac")&&(r={type:"audio/aac"});if(!await isValidAudioFile(i,r))throw this._context.emitMessage({mixId:e,state:AudioMixingState.AUDIO_MIXING_STATE_FAILED,error:AudioMixingError.AUDIO_MIXING_ERROR_PRELOAD_FAILED}),new SDKError(ErrorCode.LOAD_RESOURCES_FAILED,"Load resources failed");this._context.emitMessage({mixId:e,state:AudioMixingState.AUDIO_MIXING_STATE_PRELOADED,error:AudioMixingError.AUDIO_MIXING_ERROR_OK}),this.resourcesCache.set(e,{getAudioNode:()=>{const e=URL.createObjectURL(new Blob([i],r));return this._revokeURLs.add(e),new Audio(e)},filePath:t,duration:0}),await new Promise((t=>{const o=URL.createObjectURL(new Blob([i],r)),s=new Audio(o);s.addEventListener("durationchange",(()=>{const i=this.resourcesCache.get(e);i&&(i.duration=s.duration,this.resourcesCache.set(e,i)),URL.revokeObjectURL(o),t(null)}))}))}unloadAudioMixing(e){this.resourcesCache.has(e)&&this.resourcesCache.delete(e)}getAudioMixingVolume(e){const t=this.mixingMap.get(e);return t?100*t.gainNode.gain.value:0}setAudioMixingVolume(e,t){t<0?t=0:t>400&&(t=400),this.volumeConfig.set(e,t);const i=this.mixingMap.get(e);i&&(i.gainNode.gain.value=Number(t)/100)}getAudioMixingDuration(e){const t=this.mixingMap.get(e),i=this.resourcesCache.get(e);return t||i?t?1e3*t.audioNode.duration:i?1e3*i.duration:0:0}getAudioMixingCurrentPosition(e){const t=this.mixingMap.get(e);return t?1e3*t.audioNode.currentTime:0}setAudioMixingPosition(e,t){const i=this.mixingMap.get(e);i&&(i.audioNode.currentTime=t/1e3,i.audioNode.play())}setAudioFrameCallback(e,t,i=4096){if(checkEnum(i,"frameSize",[256,512,1024,2048,4096,8192,16384]),i=i??4096,null===this._workletReady)throw new SDKError(ErrorCode.NOT_SUPPORTED,"Not support AudioWorklet");t?this._audioFetchConfig.set(e,{callback:t,frameSize:i}):this._audioFetchConfig.delete(e),this.updateFetcher(e)}updateFetcher(e){var t;const{callback:i,frameSize:r}=this._audioFetchConfig.get(e)??{},o=null==(t=this.mixingMap.get(e))?void 0:t.gainNode;if(o&&i&&r){let t=this._audioFetchMap.get(e);t?t.setFrameSize(r):t=new AudioDataFetcher(o,r,this._sharedAudioContext,this._workletReady),t.on("data",i),this._audioFetchMap.set(e,t)}else{const t=this._audioFetchMap.get(e);null==t||t.removeAllListeners("data"),null==t||t.destroy(),this._audioFetchMap.delete(e)}}enableAudioMixingBuffer(e){checkEnum(e,"type",values(AudioMixingType));const t=this._context.getLocalAudioTrack();if(!t)return;const i=t.preprocessingTrack;if(i&&this.mixMediaStream(new MediaStream([i])),e===AudioMixingType.PUBLISH)try{this._bufferGainNode.disconnect(this._sharedAudioContext.destination)}catch(e){}else this._bufferGainNode.connect(this._sharedAudioContext.destination);this._context.updateLocalAudioTrack(this._audioDestination.stream.getAudioTracks()[0],e),this._bufferGainNode.connect(this._audioDestination),this._context.emitMessage({mixId:-1,state:AudioMixingState.AUDIO_MIXING_STATE_PCM_ENABLED,error:AudioMixingError.AUDIO_MIXING_ERROR_OK})}disableAudioMixingBuffer(){if(this.cachedBuffer=[],this._audioBufferSource){try{this._audioBufferSource.onended=null,this._audioBufferSource.disconnect(this._bufferGainNode),this._bufferGainNode.disconnect(this._audioDestination),this._bufferGainNode.disconnect(this._sharedAudioContext.destination)}catch(e){}finally{this._audioBufferSource=void 0}this._context.updateLocalAudioTrack(),this._context.emitMessage({mixId:-1,state:AudioMixingState.AUDIO_MIXING_STATE_PCM_DISABLED,error:AudioMixingError.AUDIO_MIXING_ERROR_OK})}}pushAudioMixingBuffer(e){if(!(this._audioBufferSource&&(this.cachedBuffer.push(e),this.cachedBuffer.length>0))){this._audioBufferSource=this._sharedAudioContext.createBufferSource(),this._audioBufferSource.buffer=e,this._audioBufferSource.connect(this._bufferGainNode);try{this._audioBufferSource.start()}catch(e){this._failedAudioList.push(this._audioBufferSource)}this._audioBufferSource.onended=()=>{var e;if(null==(e=this._audioBufferSource)||e.disconnect(this._bufferGainNode),this._audioBufferSource=void 0,this.cachedBuffer.length){const e=this.cachedBuffer.shift();e&&this.pushAudioMixingBuffer(e)}}}}stopAll(){if(this._localSource)try{this._localSource.disconnect(this._localGainNode),delete this._localSource}catch(e){}this.mixingMap.forEach(((e,t)=>{this.stopAudioMixing(t)}))}get mixTrack(){return this._audioDestination.stream.getAudioTracks()[0]}get sharedAudioContext(){return this._sharedAudioContext}async resumeLocalPlay(){const e=[];for(const t of this._failedAudioList)try{t instanceof HTMLAudioElement?(t.muted=!1,await t.play()):t.start()}catch(i){e.push(t),console.error(i),this._context.onAutoPlayFailed({userId:this.id,kind:"audio",streamIndex:StreamIndex$1.STREAM_INDEX_MAIN,mediaType:MediaType$1.AUDIO});break}this._failedAudioList=e}destroy(){const{_sharedAudioContext:e}=this;"closed"!==e.state&&"function"==typeof e.close&&e.close(),this.cachedBuffer=[],this.mixingMap.clear(),this.resourcesCache.clear(),this.volumeConfig.clear(),this._startingIds=new Map,this._revokeURLs.forEach((e=>{URL.revokeObjectURL(e)}))}}__decorateClass$3([reportRtcSdkApi(["id","filePath","options"])],AudioMixingManager.prototype,"startAudioMixing",1),__decorateClass$3([reportRtcSdkApi(["id"])],AudioMixingManager.prototype,"stopAudioMixing",1),__decorateClass$3([reportRtcSdkApi(["id"])],AudioMixingManager.prototype,"pauseAudioMixing",1),__decorateClass$3([reportRtcSdkApi(["id"])],AudioMixingManager.prototype,"resumeAudioMixing",1),__decorateClass$3([reportRtcSdkApi(["id"])],AudioMixingManager.prototype,"preloadAudioMixing",1),__decorateClass$3([reportRtcSdkApi(["id"])],AudioMixingManager.prototype,"unloadAudioMixing",1),__decorateClass$3([reportRtcSdkApi(["id"])],AudioMixingManager.prototype,"getAudioMixingVolume",1),__decorateClass$3([reportRtcSdkApi(["id","volume"])],AudioMixingManager.prototype,"setAudioMixingVolume",1),__decorateClass$3([reportRtcSdkApi(["id"])],AudioMixingManager.prototype,"getAudioMixingDuration",1),__decorateClass$3([reportRtcSdkApi(["id"])],AudioMixingManager.prototype,"getAudioMixingCurrentPosition",1),__decorateClass$3([reportRtcSdkApi(["id","position"])],AudioMixingManager.prototype,"setAudioMixingPosition",1),__decorateClass$3([reportRtcSdkApi(["id","callback","frameSize"])],AudioMixingManager.prototype,"setAudioFrameCallback",1),__decorateClass$3([reportRtcSdkApi(["type"])],AudioMixingManager.prototype,"enableAudioMixingBuffer",1),__decorateClass$3([reportRtcSdkApi()],AudioMixingManager.prototype,"disableAudioMixingBuffer",1),__decorateClass$3([reportRtcSdkApi(["buffer"])],AudioMixingManager.prototype,"pushAudioMixingBuffer",1);class RTSClient extends eventemitter3Exports.EventEmitter{constructor(e){super(),__publicField(this,"_loginSessionId",null),__publicField(this,"_userId",null),__publicField(this,"_token",null),__publicField(this,"_loginResolveCallback"),__publicField(this,"_loginRejectCallback"),__publicField(this,"_waitLoginToken",!1),__publicField(this,"_serverParamsCache"),__publicField(this,"id"),__publicField(this,"logger"),__publicField(this,"_clearListeners"),this._ctx=e,this.id=e.id,this.logger=new Logger$1("RTSClient",1,e.id)}login(e,t){return new Promise(((i,r)=>{var o;if(this.logger.info("login","invoke login, token: %o, userId: %o",e,t),this._loginSessionId)throw new SDKError(ErrorCode.ALREADY_LOGIN,"Already logined");if(this._loginResolveCallback)throw new SDKError(ErrorCode.LOGIN_FAILED,"Is logging in, please try again later.");this._userId=t,this._token=e,null==(o=getMonitor(this.id))||o.set({rtm_user_id:t}),this._loginResolveCallback=i,this._loginRejectCallback=r,this._ctx.signalingManager.connect().then((()=>{this._addSignalEventHandler(),this._login()}))}))}async logout(){if(!this._loginSessionId||!this._userId)throw new SDKError(ErrorCode.NOT_LOGIN,"login first");this._checkNotInLimitMode("logout"),await this._ctx.signalingManager.sendSignaling("logout",{loginSessionId:this._loginSessionId,userId:this._userId,appId:this._ctx.appId},{functionType:SIGNALING_FUNCTION_TYPE.C2RTM}).catch((()=>{})),this._clearState()}async updateLoginToken(e){return this._checkNotInLimitMode("updateLoginToken"),this._token=e,new Promise(((e,t)=>{this._waitLoginToken?(this._loginResolveCallback=e,this._loginRejectCallback=t,this._login()):e()}))}async getPeerOnlineStatus(e){if(!this._loginSessionId||!this._userId)throw new SDKError(ErrorCode.NOT_LOGIN,"login first");this._checkNotInLimitMode("getPeerOnlineStatus");const t=await this._ctx.signalingManager.sendSignaling("getPeerOnlineStatus",{loginSessionId:this._loginSessionId,userId:this._userId,appId:this._ctx.appId,peerUserId:e},{functionType:SIGNALING_FUNCTION_TYPE.C2RTM});return null==t?void 0:t.status}async sendUserMessageOutsideRoom(e,t){if(!this._loginSessionId||!this._userId)throw new SDKError(ErrorCode.NOT_LOGIN,"login first");return this._checkNotInLimitMode("sendUserMessageOutsideRoom"),this._ctx.rtsLimiter.e2e.check(t),this._ctx.signalingManager.sendP2PMessage({from:this._userId,app:this._ctx.appId,to:e,room:"",msg:t})}async setRTSMessageLimit(e){e&&this._ctx.signalingManager.sendSignaling("RTSMessageLimit",{appId:this._ctx.appId,interval:e.rts_qps_interval,broadcast:e.rts_broadcast_qps_value,one2one:e.rts_e2e_qps_value,e2bs:e.rts_e2s_qps_value},{functionType:SIGNALING_FUNCTION_TYPE.C2RTM}).catch((()=>{}))}async setServerParams(e,t){try{if(checkString(e,"signature"),checkString(t,"url"),!this._loginSessionId||!this._userId)throw new SDKError(ErrorCode.NOT_LOGIN,"login first");await this._ctx.signalingManager.sendSignaling("setServerParams",{loginSessionId:this._loginSessionId,userId:this._userId,appId:this._ctx.appId,signature:e,url:t},{functionType:SIGNALING_FUNCTION_TYPE.C2RTM}).catch((e=>{throw new SDKError(ErrorCode.UNEXPECTED_ERROR,e.msg)})),RTSMsgReportor.setServerUrl(this.id,t),this._serverParamsCache={signature:e,url:t},this.emit("onServerParamsSetResult")}catch(e){throw this.emit("onServerParamsSetResult",e),e}}async sendServerMessage(e){if(!this._loginSessionId||!this._userId)throw new SDKError(ErrorCode.NOT_LOGIN,"login first");return this._checkNotInLimitMode("sendServerMessage"),this._ctx.rtsLimiter.e2s.check(e),this._ctx.signalingManager.sendP2PMessage({from:this._userId,app:this._ctx.appId,to:"",room:"",type:DC_MESSAGE_FUNCTION_TYPE.BUSINESS_SERVER,msg:e})}destroy(){this.logger.info("destroy","invoke."),super.removeAllListeners(),this._loginResolveCallback&&this._loginRejectCallback&&(this._loginRejectCallback(new SDKError(ErrorCode.LOGIN_FAILED,"logout")),delete this._loginResolveCallback,delete this._loginRejectCallback),this._clearState(),delete this._serverParamsCache}_login(){var e;if(!this._userId)return;const t=genUuid();try{this._checkNotInLimitMode("login")}catch(t){null==(e=this._loginRejectCallback)||e.call(this,t)}this._ctx.signalingManager.sendSignaling("login",{Token:Utils.token2auth(this._ctx.appId,null,this._userId,this._token),timestamp:Date.now(),loginSessionId:t,params:{userAgent:window.navigator.userAgent,sdkVersion:Config2.VERSION,deviceId:sdkCache.getDeviceId(),appId:this._ctx.appId,userId:this._userId,deviceType:"web",platformType:2,rtsMode:this._ctx.rtsMode,mediaProcessingType:Config2.MEDIA_PROCESSING_TYPE??0},accessParams:JSON.stringify({requireICEUfragV2:!0})},{functionType:SIGNALING_FUNCTION_TYPE.C2RTM}).then((()=>{"function"==typeof this._loginResolveCallback&&this._loginResolveCallback(),this._loginSessionId=t,RTSMsgReportor.setRtsSessionId(this.id,t),this._waitLoginToken=!1,this._serverParamsCache&&this.setServerParams(this._serverParamsCache.signature,this._serverParamsCache.url)})).catch((e=>{const{code:t,message:i}=e||{};let r,o;this._waitLoginToken=!1,t>=700&&t<800?708===t?(r=ErrorCode.INVALID_PARAMS,o="Invalid userId"):(r=ErrorCode.INVALID_TOKEN,o="Invalid token",this._waitLoginToken=!0,this._loginRejectCallback||this.emit("onRTMTokenError")):(r=ErrorCode.LOGIN_FAILED,o="login failed"),"function"==typeof this._loginRejectCallback&&this._loginRejectCallback(new SDKError(r,i||o))})).finally((()=>{delete this._loginResolveCallback,delete this._loginRejectCallback}))}_addSignalEventHandler(){const e=e=>{e.state===ConnectionState.CONNECTION_STATE_RECONNECTED&&this._login()},t=()=>this._clearState(),i=e=>{this.emit("onUserMessageReceivedOutsideRoom",{userId:e.from,message:e.msg})},r=e=>{this.emit("onUserBinaryMessageReceivedOutsideRoom",{userId:e.from,message:e.msg})},o=e=>{e.clientId!==this._userId||e.roomId||(this.emit("onUserDisconnection"),this._clearState())};this._ctx.signalingManager.on(StateEvent.ON_CONNECTION_STATE_CHANGE,e),this._ctx.signalingManager.on(StateEvent.ON_RECONNECT_FAILED,t),this._ctx.signalingManager.on(SignalEvent.USER_MESSAGE_RECEIVED_OUTSIDE_ROOM,i),this._ctx.signalingManager.on(SignalEvent.USER_BINARY_MESSAGE_RECEIVED_OUTSIDE_ROOM,r),this._ctx.signalingManager.on(SignalEvent.USER_DISCONNECTION,o),this._clearListeners=()=>{this._ctx.signalingManager.off(StateEvent.ON_CONNECTION_STATE_CHANGE,e),this._ctx.signalingManager.off(StateEvent.ON_RECONNECT_FAILED,t),this._ctx.signalingManager.off(SignalEvent.USER_MESSAGE_RECEIVED_OUTSIDE_ROOM,i),this._ctx.signalingManager.off(SignalEvent.USER_BINARY_MESSAGE_RECEIVED_OUTSIDE_ROOM,r),this._ctx.signalingManager.off(SignalEvent.USER_DISCONNECTION,o)}}_clearState(){var e;null==(e=this._clearListeners)||e.call(this),this._userId=null,this._token=null,this._loginSessionId=null,RTSMsgReportor.setRtsSessionId(this.id,"")}_checkNotInLimitMode(e){if(this._ctx.rtsMode===RTS_MODE.LIMIT_MODE)throw new SDKError(ErrorCode.NOT_ALLOWED_IN_RESTRICTED_MODE,`not allow to call ${e} in rts restricted mode`)}}var WTNStreamEventsTypes=(e=>(e.onWTNPushStateChanged="onWTNPushStateChanged",e.onWTNPlayStateChanged="onWTNPlayStateChanged",e.onWTNRemoteAudioStateChanged="onWTNRemoteAudioStateChanged",e.onWTNRemoteVideoStateChanged="onWTNRemoteVideoStateChanged",e.onWTNRemoteVideoStats="onWTNRemoteVideoStats",e.onWTNRemoteAudioStats="onWTNRemoteAudioStats",e.onWTNFirstRemoteVideoFrameDecoded="onWTNFirstRemoteVideoFrameDecoded",e.onWTNSEIMessageReceived="onWTNSEIMessageReceived",e))(WTNStreamEventsTypes||{}),WTNPushState=(e=>(e[e.INIT=0]="INIT",e[e.START=1]="START",e[e.SUCCESS=2]="SUCCESS",e[e.STOP=3]="STOP",e[e.FAIL=4]="FAIL",e))(WTNPushState||{}),WTNPushStateChangedReason=(e=>(e[e.PUSH_SUCCESS=0]="PUSH_SUCCESS",e[e.START_PUSH=1]="START_PUSH",e[e.STOP_PUSH=2]="STOP_PUSH",e[e.IN_RETRY=3]="IN_RETRY",e[e.RETRY_FAIL=4]="RETRY_FAIL",e[e.NO_PUSH_PERMISSION=5]="NO_PUSH_PERMISSION",e[e.STREAM_PUSH_BY_OTHER=6]="STREAM_PUSH_BY_OTHER",e))(WTNPushStateChangedReason||{}),WTNPlayState=(e=>(e[e.INIT=0]="INIT",e[e.START=1]="START",e[e.SUCCESS=2]="SUCCESS",e[e.STOP=3]="STOP",e[e.FAIL=4]="FAIL",e))(WTNPlayState||{}),WTNPlayStateChangedReason=(e=>(e[e.PLAY_SUCCESS=0]="PLAY_SUCCESS",e[e.START_PLAY=1]="START_PLAY",e[e.STOP_PLAY=2]="STOP_PLAY",e[e.REMOTE_STOP=3]="REMOTE_STOP",e[e.REMOTE_FAILURE=4]="REMOTE_FAILURE",e[e.STREAM_BANNED=5]="STREAM_BANNED",e[e.NO_PLAY_PERMISSION=6]="NO_PLAY_PERMISSION",e[e.STREAM_NOT_EXIST=7]="STREAM_NOT_EXIST",e[e.IN_RETRY=8]="IN_RETRY",e[e.RETRY_FAIL=9]="RETRY_FAIL",e[e.INTERNAL=10]="INTERNAL",e[e.OVER_CLIENT_SUBSCRIBE_STREAM_LIMIT=1310]="OVER_CLIENT_SUBSCRIBE_STREAM_LIMIT",e[e.OVER_STREAM_SUBSCRIBE_USER_LIMIT=1311]="OVER_STREAM_SUBSCRIBE_USER_LIMIT",e[e.OVER_STREAM_SUBSCRIBE_REQUES_TLIMIT=1312]="OVER_STREAM_SUBSCRIBE_REQUES_TLIMIT",e))(WTNPlayStateChangedReason||{}),WTNRemoteAudioState=(e=>(e[e.STOPED=0]="STOPED",e[e.STARTING=1]="STARTING",e[e.DECODING=2]="DECODING",e[e.FROZEN=3]="FROZEN",e[e.FAILED=4]="FAILED",e))(WTNRemoteAudioState||{}),WTNRemoteAudioStateChangeReason=(e=>(e[e.INTERNAL=0]="INTERNAL",e[e.NETWORK_CONGESTION=1]="NETWORK_CONGESTION",e[e.NETWORK_RECOVERY=2]="NETWORK_RECOVERY",e[e.UNMUTE=3]="UNMUTE",e[e.MUTE=4]="MUTE",e[e.REMOTE_START=5]="REMOTE_START",e[e.REMOTE_STOP=6]="REMOTE_STOP",e))(WTNRemoteAudioStateChangeReason||{}),WTNRemoteVideoState=(e=>(e[e.STOPED=0]="STOPED",e[e.STARTING=1]="STARTING",e[e.DECODING=2]="DECODING",e[e.FROZEN=3]="FROZEN",e[e.FAILED=4]="FAILED",e))(WTNRemoteVideoState||{}),WTNRemoteVideoStateChangeReason=(e=>(e[e.INTERNAL=0]="INTERNAL",e[e.NETWORK_CONGESTION=1]="NETWORK_CONGESTION",e[e.NETWORK_RECOVERY=2]="NETWORK_RECOVERY",e[e.UNMUTE=3]="UNMUTE",e[e.MUTE=4]="MUTE",e[e.REMOTE_START=5]="REMOTE_START",e[e.REMOTE_STOP=6]="REMOTE_STOP",e))(WTNRemoteVideoStateChangeReason||{});const BACK_OFF_INIT_STATE={interval:1e3,retryDuration:0};class WTNLocalStream extends LocalStream{constructor(e,t,i,r=!1){super(i,StreamIndex.STREAM_INDEX_MAIN),__publicField(this,"_state",WTNPushState.INIT),__publicField(this,"_stateChangeTs",getServerNow()),__publicField(this,"streamId"),__publicField(this,"Authorization"),__publicField(this,"_backOff",BACK_OFF_INIT_STATE),this.token=t,this.streamId=e,this.logName=`WTNLocalStream-${e}`,this.observer=new SendFrameObserver(this._ctx,this),this.Authorization=Utils.token2auth(i.appId,"",e,t),this._state=r?WTNPushState.FAIL:WTNPushState.INIT,this.isPublicStream=!0}setState(e,t){const i=this._state;if(i===e)return;this.logger.print("setState",e,t),this._state=e;const r=getServerNow();this.safeEmit(WTNStreamEventsTypes.onWTNPushStateChanged,{streamId:this.streamId,oldState:i,newState:e,reason:t,elapse:r-this._stateChangeTs}),this._stateChangeTs=r}getPushBackOff(){return this._backOff}updatePushBackOff(){this._backOff.retryDuration+=this._backOff.interval,this._backOff.interval=this._backOff.interval>4e3?8e3:2*this._backOff.interval}resetPushBackOff(){this._backOff=BACK_OFF_INIT_STATE}}class WTNRemoteStream extends RemoteStream{constructor(e,t,i,r=!1){super(i,e,e,!1,!0,{audiostream:!0,localaudio:!0,videostream:!0,localvideo:!0,extaudio:!1,extvideo:!1,videoDescriptions:[]}),__publicField(this,"_state",WTNPlayState.INIT),__publicField(this,"Authorization"),__publicField(this,"_stateChangeTs",getServerNow()),__publicField(this,"streamId"),__publicField(this,"_backOff",BACK_OFF_INIT_STATE),__publicField(this,"_audioState",WTNRemoteAudioState.STOPED),__publicField(this,"_videoState",WTNRemoteVideoState.STOPED),this.token=t,this.streamId=e,this.logName=`WTNRemoteStream-${e}`,this.observer=new RecvFrameObserver(this._ctx,this),this._initObserverEvent(r),this.Authorization=Utils.token2auth(i.appId,"",e,t),this._state=r?WTNPlayState.FAIL:WTNPlayState.INIT,this.isPublicStream=!0}setState(e,t){const i=this._state;if(i===e)return;this.logger.print("setState",e,t),this._state=e;const r=getServerNow();this.safeEmit(WTNStreamEventsTypes.onWTNPlayStateChanged,{streamId:this.streamId,oldState:i,newState:e,reason:t,elapse:r-this._stateChangeTs}),this._stateChangeTs=r}get state(){return this._state}getPushBackOff(){return this._backOff}updatePushBackOff(){this._backOff.retryDuration+=this._backOff.interval,this._backOff.interval=this._backOff.interval>4e3?8e3:2*this._backOff.interval}resetPushBackOff(){this._backOff=BACK_OFF_INIT_STATE}setVideoState(e,t){this._videoState!==e&&(e===WTNRemoteVideoState.DECODING&&this.setVideoState(WTNRemoteVideoState.STARTING,t),this.logger.print("setVideoState",e,t),this._videoState=e,this.safeEmit(WTNStreamEventsTypes.onWTNRemoteVideoStateChanged,{streamId:this.streamId,state:e,reason:t}))}setAudioState(e,t){this._audioState!==e&&(e===WTNRemoteAudioState.DECODING&&this.setAudioState(WTNRemoteAudioState.STARTING,t),this.logger.print("setAudioState",e,t),this._audioState=e,this.safeEmit(WTNStreamEventsTypes.onWTNRemoteAudioStateChanged,{streamId:this.streamId,state:e,reason:t}))}muteToSubMediaType(e,t){let i=!1;const r=audioInMediaType(this.subMediaType),o=videoInMediaType(this.subMediaType);return"boolean"==typeof e&&r===e&&(this.subMediaType+=e?-MediaType$1.AUDIO:MediaType$1.AUDIO,i=!0),"boolean"==typeof t&&o===t&&(this.subMediaType+=t?-MediaType$1.VIDEO:MediaType$1.VIDEO,i=!0),i}getEnableMediaType(){return{audio:audioInMediaType(this.subMediaType),video:videoInMediaType(this.subMediaType)}}_initObserverEvent(e){var t,i;null==(t=this.observer)||t.once("recvAudioFirstFrame",(()=>{this.setAudioState(WTNRemoteAudioState.DECODING,e?WTNRemoteAudioStateChangeReason.NETWORK_RECOVERY:WTNRemoteAudioStateChangeReason.REMOTE_START)})),null==(i=this.observer)||i.once("recvVideoFirstFrame",(()=>{this.setVideoState(WTNRemoteVideoState.DECODING,e?WTNRemoteVideoStateChangeReason.NETWORK_RECOVERY:WTNRemoteVideoStateChangeReason.REMOTE_START)}))}}var __defProp$2=Object.defineProperty,__getOwnPropDesc$2=Object.getOwnPropertyDescriptor,__decorateClass$2=(e,t,i,r)=>{for(var o,s=r>1?void 0:r?__getOwnPropDesc$2(t,i):t,n=e.length-1;n>=0;n--)(o=e[n])&&(s=(r?o(t,i,s):o(s))||s);return r&&s&&__defProp$2(t,i,s),s};class WTNStream extends EnhancedEventEmitter{constructor(e){super(),__publicField(this,"_reportName","WTNStream"),__publicField(this,"_localStreams",new Map),__publicField(this,"_remoteStreams",new Map),__publicField(this,"_logger"),__publicField(this,"_monitor"),__publicField(this,"_ontrackCallbackMap",new Map),__publicField(this,"_wtnPlayLocks",new Map),__publicField(this,"_pushTaskMap",new Map),__publicField(this,"_playTaskMap",new Map),__publicField(this,"engineId"),__publicField(this,"_publicVideoPlayerConfig",new Map),__publicField(this,"__onSEIMessageReceived"),__publicField(this,"__onRemoteStreamStats"),__publicField(this,"__onResubscribe"),__publicField(this,"__onPlayerEvents"),__publicField(this,"_clearSignalListeners"),this._ctx=e,this._monitor=getMonitor(e.id),this._logger=new Logger$1("WTNStream",1,e.id),this.engineId=e.id,this._addSignalListeners()}async startPushWTN(e,t,i,r,o=!1){var s;if(i=!!i,r=!!r,this._logger.print("startPushWTN",e,t,i,r),checkPublicStreamId(t),!isEmpty(e)&&checkString(e,"token"),this._localStreams.get(t))return;const n=new WTNLocalStream(t,e,this._ctx,o);this._addLocalStreamEventHandler(n),n.setState(WTNPushState.START,WTNPushStateChangedReason.START_PUSH),this._localStreams.set(t,n),await this._ctx.signalingManager.connect(),n.videoTrack=this._ctx.localVideoTrack,n.audioTrack=this._ctx.localAudioTrack,n.pubAudio=!r,n.pubVideo=!i,null==(s=n.observer)||s.setLogin(!0),await new Promise(((e,i)=>{o||this._pushTaskMap.set(t,{resolve:()=>{e(),n.startReport((()=>{}),this._ctx.handler)},reject:i}),this._sendStartPushStreamSignal(n).catch((e=>i(e)))}))}async stopPushWTN(e){var t;this._logger.print("stopPushWTN",e);const i=this._localStreams.get(e);i&&(null==(t=i.observer)||t.setLogin(!1),i.setState(WTNPushState.STOP,WTNPushStateChangedReason.STOP_PUSH),this._ctx.signalingManager.sendSignaling("stopPushStream",{appId:this._ctx.appId,streamId:e}).catch((()=>{})),await this._stopLocalStream(i))}async muteWTNLocalAudio(e,t){var i;this._logger.print("muteWTNLocalAudio",e,t);const r=this._localStreams.get(e);if(!r)throw new SDKError(ErrorCode.INVALID_PARAMS,"streamId not found");this._assertNotConnect(),r.pubAudio=!t,null==(i=r.observer)||i.setUnmuteAudio(!t),await this._updatePushStream(r)}async muteWTNLocalVideo(e,t){var i;this._logger.print("muteWTNLocalVideo",e,t);const r=this._localStreams.get(e);if(!r)throw new SDKError(ErrorCode.INVALID_PARAMS,"streamId not found");this._assertNotConnect(),null==(i=r.observer)||i.setUnmuteVideo(!t),r.pubVideo=!t,await this._updatePushStream(r)}sendWTNSEIMessage(e,t,i){this._logger.info("sendWTNSEIMessage()","streamId: %o, sei: %o, repeatCount: %o",e,t,i);const r=this._localStreams.get(e);if(!r||!r.pubVideo&&!r.pubAudio)return;if(!isLegacyEncodedTransformSupported()&&!isEncodedTransformSupported())return warnDevelopers("Your browser does not support sending SEI"),!1;checkNumber(i,"repeatCount",0,30);const o="string"==typeof t?new Uint8Array(Utils.str2ab(t)):t;if(!t.length)return this._logger.warn("sei message must not be empty"),!1;if(o.byteLength>4096)return void this._logger.warn("sei size must not bigger than 4KB");isAndroid||this._maybeFillBackFrame2Stream(r);const s=genUuid();r.sendSEIMessage({content:o,uuid:s,repeatCount:i+1}),setTimeout((async()=>{var e;if(!r)return;await r.revokeSEIMessage(s)&&(console.error("[RTC WebSDK] sei timeout for message: %o",t),null==(e=this._monitor)||e.report("rtc_sdk_callback",{sdk_callback_name:"sendSEIMessage",message:`timeout for message: ${t}`,error_code:400}))}),getParameter("SEI_TIME_OUT"))}async startPlayWTN(e,t,i,r,o=!1){await this._startPlayWTNInternal(e,t,i,r,o)}async _startPlayWTNInternal(e,t,i,r,o=!1){var s;i=!!i,r=!!r,this._logger.print("startPlayWTN",e,t,i,r),checkPublicStreamId(t),!isEmpty(e)&&checkString(e,"token");let n=this._remoteStreams.get(t);if(n){if(n.state===WTNPlayState.START||n.state===WTNPlayState.SUCCESS)throw new SDKError(ErrorCode.REPEAT_PLAY,"repeat play public media stream");await this._stopPlayWTNInternal(t)}n=new WTNRemoteStream(t,e,this._ctx,o),this._addRemoteStreamEventHandler(n),n.setState(WTNPlayState.START,WTNPlayStateChangedReason.START_PLAY),n.muteToSubMediaType(r,i),this._remoteStreams.set(t,n),null==(s=n.observer)||s.setLogin(!0,n.getEnableMediaType());try{await this._ctx.signalingManager.connect(),await new Promise(((e,i)=>{o||this._playTaskMap.set(t,{resolve:e,reject:i}),this._sendStartPullStreamSignal(n).catch((e=>i(e)))}))}catch(e){throw this._remoteStreams.delete(t),e}}async stopPlayWTN(e){await this._stopPlayWTNInternal(e)}async _stopPlayWTNInternal(e){var t,i;this._logger.print("stopPlayWTN",e);const r=this._remoteStreams.get(e);if(r)return r.setState(WTNPlayState.STOP,WTNPlayStateChangedReason.STOP_PLAY),r.setAudioState(WTNRemoteAudioState.STOPED,WTNRemoteAudioStateChangeReason.MUTE),r.setVideoState(WTNRemoteVideoState.STOPED,WTNRemoteVideoStateChangeReason.MUTE),null==(t=r.observer)||t.setLogin(!1),null==(i=null==r?void 0:r.audioTrack)||i.stop(),this._remoteStreams.delete(e),await this._ctx.signalingManager.connect(),this._unsubscribePublicStream(r)}async muteWTNRemoteAudio(e,t){var i;this._logger.print("muteWTNRemoteAudio",e,t),this._assertNotConnect();const r=this._remoteStreams.get(e);if(!r)throw new SDKError(ErrorCode.INVALID_PARAMS,"streamId not found");r.muteToSubMediaType(t,null)&&(null==(i=r.observer)||i.setUnmuteAudio(!t),await this._updatePullStream(e,r),r.setAudioState(t?WTNRemoteAudioState.STOPED:WTNRemoteAudioState.DECODING,t?WTNRemoteAudioStateChangeReason.MUTE:WTNRemoteAudioStateChangeReason.UNMUTE))}async muteWTNRemoteVideo(e,t){var i;this._logger.print("muteWTNRemoteVideo",e,t),this._assertNotConnect();const r=this._remoteStreams.get(e);if(!r)throw new SDKError(ErrorCode.INVALID_PARAMS,"streamId not found");r.muteToSubMediaType(null,t)&&(null==(i=r.observer)||i.setUnmuteVideo(!t),await this._updatePullStream(e,r),r.setVideoState(t?WTNRemoteVideoState.STOPED:WTNRemoteVideoState.DECODING,t?WTNRemoteVideoStateChangeReason.MUTE:WTNRemoteVideoStateChangeReason.UNMUTE))}setWTNRemoteVideoPlayer(e,t){var i,r;if(this._logger.print("setWTNRemoteVideoPlayer()","streamId: %o, videoPlayerOption: %o",e,t),null==(r=null==(i=this._publicVideoPlayerConfig.get(e))?void 0:i.player)||r.destroy(),!t.renderDom)return void this._publicVideoPlayerConfig.delete(e);const o=new VideoPlayer(this._ctx.id,DEFAULT_PLAYER_ID,{...t,isLocal:!1,userId:e}),s={...t,player:o};return this._publicVideoPlayerConfig.set(e,s),this._updateVideoPlayerState(e),o.domElement}setWTNRemoteAudioPlaybackVolume(e,t){var i,r;checkString(e,"publicStreamId"),t=numberRangeGuide(t,"volume",0,400),this._ctx.publicAudioVolume.set(e,t),null==(r=null==(i=this._remoteStreams.get(e))?void 0:i.audioTrack)||r.setVolume(t)}__getRemoteStreams(){return this._remoteStreams}__getPublicStreamTrack(e,t){const i=this._remoteStreams.get(e);if(i)return"video"===t?i.videoTrack:i.audioTrack}async _updatePushTrack(){0!==this._localStreams.size&&(this._logger.info("_updatePushTrack()"),await this._ctx.signalingManager.connect(),this._localStreams.forEach((async e=>{var t;e.videoTrack=this._ctx.localVideoTrack,e.audioTrack=this._ctx.localAudioTrack,null==(t=e.observer)||t.setEnableVideo(!0),await this._updatePushStream(e)})))}destroy(){var e;this._remoteStreams.forEach((e=>{e.destroy()})),this._remoteStreams=new Map,this.removeAllListeners(),this._ontrackCallbackMap.clear(),this._publicVideoPlayerConfig.forEach((e=>{e.player.destroy()})),this._publicVideoPlayerConfig.clear(),null==(e=this._clearSignalListeners)||e.call(this),this._wtnPlayLocks=new Map}async _sendStartPushStreamSignal(e){var t,i,r;this._logger.print("_sendStartPushStreamSignal()","streamId: %s",e.streamId);const{streamId:o,Authorization:s,pubAudio:n,pubVideo:a}=e,{handler:d}=this._ctx;await(null==d?void 0:d.getDefaultSdp());const c=await d.publish(e),l=await internalGetSupportedCodecs(),{appId:u,businessId:_,useCloudProxy:h}=this._ctx,p={appId:u,streamId:o,Authorization:s,sdpInfo:{msid:e.stream.id,type:c.type,sdp:c.partialSdp,semantics:c.semantics},timestamp:Date.now(),params:{appId:u,businessId:_,userAgent:window.navigator.userAgent,sdkVersion:Config2.VERSION,deviceId:sdkCache.getDeviceId(),enableCloudProxy:h,channelProfile:"0",SDKCodecNegotiation:!0,supportedCodecs:l,sdkType:"rtc",joinRoomMode:1,deviceType:"web",platformType:2,rtsMode:this._ctx.rtsMode,mediaProcessingType:Config2.MEDIA_PROCESSING_TYPE??0},options:{supportCheckTokenPrivilege:!0,supportTokenExpireCallBack:!0,enableSceneConfigV2:!0,enableUnBundleMode:!0,enableAudioMux:!0,enableBigRoomMode:!0,needNegotiateSDP:!0,supportMultiVendor:!0,enableStreamStatusCallback:!0},attributes:{localaudio:!!e.audioTrack,localvideo:!!e.videoTrack,videostream:a,audiostream:n,extvideo:(null==(t=e.videoTrack)?void 0:t.sourceType)===SourceType.EXTERNAL,extaudio:(null==(i=e.audioTrack)?void 0:i.sourceType)===SourceType.EXTERNAL,videoDescriptions:c.videoDescriptions.map((({rid:e,...t})=>t)),videoType:VideoType.NORMAL},video:a,audio:n,screen:e.isScreen,accessParams:JSON.stringify({requireICEUfragV2:!0})};let m;try{this.emit("__onSendingPushStreamMessageHook"),m=await this._ctx.signalingManager.sendSignaling("startPushStream",p)}catch(t){if(await(null==d?void 0:d.rollback({msid:e.stream.id,stream:e,audioMid:c.audioMid,videoMid:c.videoMid})),t.code>=500&&t.code<600){const i=e.getPushBackOff();if(i.retryDuration<6e4)return this._logger.info("pushRetry","start msid: %s, retryDuration: %s",e.id,i.retryDuration),await new Promise((e=>setTimeout(e,i.interval))),e.updatePushBackOff(),e.resetStream(),e.setState(WTNPushState.START,WTNPushStateChangedReason.IN_RETRY),this._sendStartPushStreamSignal(e);throw this._logger.info("pushRetry","end"),e.setState(WTNPushState.FAIL,WTNPushStateChangedReason.RETRY_FAIL),await this._stopLocalStream(e),e.resetPushBackOff(),new SDKError(ErrorCode.WTN_PUSH_FAILED,t.message||"server error")}if(401===t.code)throw e.setState(WTNPushState.FAIL,WTNPushStateChangedReason.NO_PUSH_PERMISSION),await this._stopLocalStream(e),new SDKError(ErrorCode.WTN_PUSH_FAILED,t.message||"token error");if(t.code===ErrorCode.OPERATION_CANCEL&&this._ctx.signalingManager.isReconnecting())return;throw new SDKError(ErrorCode.WTN_PUSH_FAILED,t.message||"push error")}e.pubAttributes=p.attributes;const S=await e.getSelectedCodec();e.currentVideoCodec=S;const g=new Promise(((t,i)=>{var r,s;null==d||d.handleAck({action:SdpAction.publish,streamId:o,audioMid:c.audioMid,videoMid:c.videoMid,audioTransceiverInit:null==c?void 0:c.audioTransceiverInit,videoTransceiverInit:null==c?void 0:c.videoTransceiverInit,signalingAck:{sdp:null==(r=null==m?void 0:m.relayMessage)?void 0:r.sdp,sequenceId:null==(s=null==m?void 0:m.relayMessage)?void 0:s.sequenceId},stream:e,videoCodec:S,onSuccess:()=>{this._logger.info("pushStream()","pushStream success"),e.setState(WTNPushState.SUCCESS,WTNPushStateChangedReason.PUSH_SUCCESS),t(0)},onFail:e=>{this._logger.info("pushStream()","pushStream fail"),i(e)}})}));!isFirefox&&await g,null==(r=this._pushTaskMap.get(o))||r.resolve(),this._pushTaskMap.delete(o)}async _stopLocalStream(e){var t;e.stopBlackFrame(),await(null==(t=this._ctx.handler)?void 0:t.handleAck({action:SdpAction.unpublish,audioMid:e.audioMid,videoMid:e.videoMid,stream:e,streamId:e.streamId})),e.destroy(),this._localStreams.delete(e.streamId)}async _updatePushStream(e){var t,i,r,o,s,n,a;const{videoTrack:d,audioTrack:c,pubAudio:l,pubVideo:u}=e;let _=null==(t=e.audioTrack)?void 0:t.preprocessingTrack;const h=null==(i=e.videoTrack)?void 0:i.preprocessingTrack;if(u&&h?(e.stopBlackFrame(),await(null==(r=e.videoTransceiver)?void 0:r.sender.replaceTrack(h))):await(null==(o=e.videoTransceiver)?void 0:o.sender.replaceTrack(null)),l&&_){const{mixType:t,mixedAudioTrack:i}=e.audioTrack;i&&t!==AudioMixingType.PLAYOUT&&_.enabled&&(_=i),await(null==(s=e.audioTransceiver)?void 0:s.sender.replaceTrack(_))}else await(null==(n=e.audioTransceiver)?void 0:n.sender.replaceTrack(null));const p={localaudio:!!c,localvideo:!!d,videostream:u,audiostream:l,extvideo:(null==d?void 0:d.sourceType)===SourceType.EXTERNAL,extaudio:(null==c?void 0:c.sourceType)===SourceType.EXTERNAL,videoType:d?VideoType.NORMAL:e.pubAttributes.videoType},m={};for(const[t,i]of Object.entries(p))i!==Reflect.get(e.pubAttributes,t)&&Reflect.set(m,t,i);Object.keys(m).length&&(e.pubAudio=p.audiostream??e.pubAudio,e.pubVideo=p.videostream??e.pubVideo,e.pubAttributes={...e.pubAttributes,...p},e.pubAttributes.videostream||e.stopBlackFrame(),await this._ctx.signalingManager.sendSignaling("updatePushStream",{appId:this._ctx.appId,streamId:e.streamId,attributes:p}),isFirefox&&await(null==(a=this._ctx.handler)?void 0:a.setCurrentDescription()))}async _sendStartPullStreamSignal(e){var t,i,r,o;this._logger.print("startPullStream()","streamId:",e.streamId);const{streamId:s,Authorization:n}=e,{handler:a}=this._ctx,d=await(null==a?void 0:a.subscribe(e,{multiChatMode:!1}));if(!d)throw new SDKError(ErrorCode.ADD_TRANSCEIVER_FAILED,"add transceiver failed");const c=getServerNow(),{audioMid:l,videoMid:u}=d,{appId:_,businessId:h,useCloudProxy:p}=this._ctx,m=await internalGetSupportedCodecs(),S={appId:_,streamId:s,Authorization:n,audio:!0,video:!0,screen:!1,timestamp:Date.now(),sdpInfo:{sdp:d.partialSdp,semantics:d.semantics,type:d.type},params:{appId:_,businessId:h,userAgent:window.navigator.userAgent,sdkVersion:Config2.VERSION,deviceId:sdkCache.getDeviceId(),enableCloudProxy:p,channelProfile:"0",SDKCodecNegotiation:!0,supportedCodecs:m,sdkType:"rtc",joinRoomMode:1,deviceType:"web",platformType:2,rtsMode:this._ctx.rtsMode,mediaProcessingType:Config2.MEDIA_PROCESSING_TYPE??0},options:{supportCheckTokenPrivilege:!0,supportTokenExpireCallBack:!0,enableSceneConfigV2:!0,enableUnBundleMode:!0,enableAudioMux:!0,enableBigRoomMode:!0,needNegotiateSDP:!0,supportMultiVendor:!0,enableStreamStatusCallback:!0},config:{enableMediaType:e.getEnableMediaType(),qualityLayer:{spatialLayer:0,temporalLayer:0}},accessParams:JSON.stringify({requireICEUfragV2:!0}),extra:{enableSendRTT:!0}};let g;try{this.emit("__onSendingPullStreamMessageHook"),g=await this._ctx.signalingManager.sendSignaling("startPullStream",S)}catch(t){if(await(null==a?void 0:a.rollback({msid:s,stream:e}).catch((()=>{}))),401===t.code)throw e.setState(WTNPlayState.FAIL,WTNPlayStateChangedReason.NO_PLAY_PERMISSION),new SDKError(ErrorCode.WTN_PLAY_FAILED,t.message||"token error");if(433===t.code)throw e.setState(WTNPlayState.FAIL,WTNPlayStateChangedReason.OVER_CLIENT_SUBSCRIBE_STREAM_LIMIT),new SDKError(ErrorCode.WTN_PLAY_FAILED,t.message||"over client subscribe stream limit");if(434===t.code)throw e.setState(WTNPlayState.FAIL,WTNPlayStateChangedReason.OVER_STREAM_SUBSCRIBE_USER_LIMIT),new SDKError(ErrorCode.WTN_PLAY_FAILED,t.message||"over stream subscribe user limit");if(t.code===ErrorCode.OPERATION_CANCEL&&this._ctx.signalingManager.isReconnecting())return;throw e.setState(WTNPlayState.FAIL,WTNPlayStateChangedReason.INTERNAL),new SDKError(ErrorCode.WTN_PLAY_FAILED,t.message||"play wtn error")}const v=[];v.push(new Promise(((t,i)=>{const r=setTimeout((()=>i(new SDKError(ErrorCode.WTN_PLAY_FAILED,`wait video timeout for streamId: ${s}`))),6e4),o=i=>{"video"===i.mediaType&&(this._logger.success(`remoteStream ${e.userId} received video track`),e.off("ontrack",o),clearTimeout(r),t(0))};e.on("ontrack",o)}))),v.push(new Promise(((t,i)=>{const r=setTimeout((()=>i(new SDKError(ErrorCode.WTN_PLAY_FAILED,`wait audio timeout for streamId: ${s}`))),6e4),o=i=>{"audio"===i.mediaType&&(this._logger.success(`remoteStream ${e.userId} received audio track`),e.off("ontrack",o),clearTimeout(r),t(0))};e.on("ontrack",o)})));const f=t=>{e.ontrack(t)};null==(t=this._ctx.handler)||t.on("ontrack",f),this._ontrackCallbackMap.set(e,f);const{sequenceId:E,sdp:T}=g.relayMessage;e.videoMid=u,e.audioMid=l,e.sequenceId=E,e.streamState=StreamState.SUB_ED,await(null==(i=this._ctx.handler)?void 0:i.handleAck({action:SdpAction.subscribe,streamId:s,audioMid:l,videoMid:u,audioTransceiverInit:d.audioTransceiverInit,videoTransceiverInit:d.videoTransceiverInit,signalingAck:{sdp:T,sequenceId:E},stream:e})),await Promise.all(v),null==(r=this._monitor)||r.report("rtc_subscribe_stat",{result:"success",start:c,message:"unknown",stream_user_id:e.userId}),e.startReport((t=>{var i;t.publicStreamId=t.userId,delete t.userId,delete t.isScreen;const r=getPublicStats(t);r.audioStats&&this.safeEmit(WTNStreamEventsTypes.onWTNRemoteAudioStats,{streamId:e.streamId,audioStats:r.audioStats}),r.videoStats&&this.safeEmit(WTNStreamEventsTypes.onWTNRemoteVideoStats,{streamId:e.streamId,videoStats:r.videoStats}),null==(i=this.__onRemoteStreamStats)||i.call(this,r)}),this._ctx.handler),this._updateVideoPlayerState(s),this._initAudioPlayer(s),e.subVideo=e.getEnableMediaType().video,e.subAudio=e.getEnableMediaType().audio,null==(o=this._playTaskMap.get(s))||o.resolve(),this._playTaskMap.delete(s)}async _unsubscribePublicStream(e){var t;logRemoteStream("_unsubscribePublicStream()",e,this._logger);const i={appId:this._ctx.appId,streamId:e.streamId};try{await this._ctx.signalingManager.sendSignaling("stopPullStream",i)}catch(e){}e.streamState=StreamState.INIT,await(null==(t=this._ctx.handler)?void 0:t.handleAck({action:SdpAction.unsubscribe,streamId:e.streamId,audioMid:e.audioMid,videoMid:e.videoMid,stream:e})),e.subMediaType=ExtendMediaType.NONE,this._removeOnTrackListener(e),e.statsReport.unsubscribe(),e.destroy()}async _updatePullStream(e,t){const i=t.getEnableMediaType();await this._ctx.signalingManager.sendSignaling("updatePullStream",{appId:this._ctx.appId,streamId:e,config:{enableMediaType:i}}),t.subVideo=i.video,t.subAudio=i.audio}_removeOnTrackListener(e){const t=this._ontrackCallbackMap.get(e);if(t){const i=e.vendorHandler||this._ctx.handler;null==i||i.off("ontrack",t),this._ontrackCallbackMap.delete(e)}}_addSignalListeners(){const e={[StateEvent.ON_CONNECTION_STATE_CHANGE]:e=>{e.state===ConnectionState.CONNECTION_STATE_RECONNECTED?(Array.from(this._remoteStreams.values()).forEach((e=>{const{streamId:t,token:i}=e,{audio:r,video:o}=e.getEnableMediaType();e.destroy(),this._remoteStreams.delete(t),this._startPlayWTNInternal(i,t,!o,!r,!0).then((()=>{var t;null==(t=this.__onResubscribe)||t.call(this,{stream:e})}))})),Array.from(this._localStreams.values()).forEach((e=>{const{token:t,pubAudio:i,pubVideo:r}=e;e.destroy(),this._localStreams.delete(e.streamId),this.startPushWTN(t,e.streamId,!r,!i,!0)}))):e.state===ConnectionState.CONNECTION_STATE_DISCONNECTED&&(this._remoteStreams.forEach((e=>{e.setState(WTNPlayState.FAIL,WTNPlayStateChangedReason.IN_RETRY),e.setAudioState(WTNRemoteAudioState.FROZEN,WTNRemoteAudioStateChangeReason.NETWORK_CONGESTION),e.setVideoState(WTNRemoteVideoState.FROZEN,WTNRemoteVideoStateChangeReason.NETWORK_CONGESTION)})),this._localStreams.forEach((e=>{e.setState(WTNPushState.FAIL,WTNPushStateChangedReason.IN_RETRY)})))},[SignalEvent.ON_STREAM_PUSHED_BY_OTHER]:e=>{const t=this._localStreams.get(e.streamId);this._logger.print("_addSignalListeners","onStreamPushedByOther",e.streamId),t&&(t.setState(WTNPushState.FAIL,WTNPushStateChangedReason.STREAM_PUSH_BY_OTHER),this._stopLocalStream(t))},[SignalEvent.ON_STREAM_PULL_STATE_CHANGED]:async e=>{var t,i;const r=this._remoteStreams.get(e.streamId);if(this._logger.print("_addSignalListeners","onStreamPullStateChanged",e),r)switch(e.code){case 0:r.setState(WTNPlayState.SUCCESS,WTNPlayStateChangedReason.PLAY_SUCCESS);break;case 1:case 2:case 3:const o={1:WTNPlayStateChangedReason.STREAM_NOT_EXIST,2:WTNPlayStateChangedReason.REMOTE_STOP,3:WTNPlayStateChangedReason.REMOTE_FAILURE}[e.code];r.setAudioState(WTNRemoteAudioState.STOPED,WTNRemoteAudioStateChangeReason.REMOTE_STOP),r.setVideoState(WTNRemoteVideoState.STOPED,WTNRemoteVideoStateChangeReason.REMOTE_STOP),r.setState(WTNPlayState.FAIL,o);break;case 4:const s=r.getPushBackOff();s.retryDuration<6e4?(this._logger.info("subRetry",r.streamId,s.retryDuration),r.setState(WTNPlayState.START,WTNPlayStateChangedReason.IN_RETRY),await new Promise((e=>setTimeout(e,s.interval))),r.updatePushBackOff(),await(null==(i=null==(t=this._ctx)?void 0:t.handler)?void 0:i.handleAck({action:SdpAction.unsubscribe,streamId:r.streamId,audioMid:r.audioMid,videoMid:r.videoMid,stream:r})),r.clean(),await this._sendStartPullStreamSignal(r)):(r.setState(WTNPlayState.FAIL,WTNPlayStateChangedReason.RETRY_FAIL),this._logger.info("subRetry","end",r.streamId),r.resetPushBackOff())}},[MediaServerSignalEvent.RTT]:e=>{const{StreamIds:t,Metadata:i}=e;if((null==t?void 0:t.length)&&i){const e=t[0];this._ctx.streamRTT[e]={audio:i.audio_rtt,video:i.video_rtt}}}};Object.keys(e).forEach((t=>{this._ctx.signalingManager.on(t,e[t])})),this._clearSignalListeners=()=>{Object.keys(e).forEach((t=>{this._ctx.signalingManager.off(t,e[t])}))}}_addLocalStreamEventHandler(e){e.on(WTNStreamEventsTypes.onWTNPushStateChanged,(e=>{this.safeEmit(WTNStreamEventsTypes.onWTNPushStateChanged,e)}))}_addRemoteStreamEventHandler(e){e.on(WTNStreamEventsTypes.onWTNPlayStateChanged,(e=>{this.safeEmit(WTNStreamEventsTypes.onWTNPlayStateChanged,e)})),e.on(WTNStreamEventsTypes.onWTNRemoteAudioStateChanged,(e=>{this.safeEmit(WTNStreamEventsTypes.onWTNRemoteAudioStateChanged,e)})),e.on(WTNStreamEventsTypes.onWTNRemoteVideoStateChanged,(e=>{this.safeEmit(WTNStreamEventsTypes.onWTNRemoteVideoStateChanged,e)})),e.on("onSEIMessage",(t=>{var i;if(t instanceof Uint8Array){const r=splitPublicStreamSei(t);for(let t=0;t<r.seiCount;t++)null==(i=this.__onSEIMessageReceived)||i.call(this,{sei:r.seis[t],publicStreamId:e.streamId}),this.safeEmit(WTNStreamEventsTypes.onWTNSEIMessageReceived,{streamId:e.streamId,sei:r.seis[t]})}}))}_updateVideoPlayerState(e){var t,i;const r=this._remoteStreams.get(e);if(r){const o=this._publicVideoPlayerConfig.get(e);o&&(null==(i=r.videoTrack)||i.setPlayer(this._ctx.id,o,null==(t=this._ctx)?void 0:t.autoPlayPolicy,this._initPlayerEvents.bind(this)))}}_initAudioPlayer(e){var t,i;const r=this._remoteStreams.get(e);if(null==r?void 0:r.audioTrack){const o=new AudioPlayer(this._ctx.id,e,{muted:(null==(t=this._ctx)?void 0:t.autoPlayPolicy)===RTCAutoPlayPolicy.VIDEO_ONLY||(null==(i=this._ctx)?void 0:i.autoPlayPolicy)===RTCAutoPlayPolicy.PLAY_MANUALLY,isScreen:!1});r.audioTrack.setPlayer(o),r.audioTrack.bindPlayerEvent(this._initPlayerEvents.bind(this)),r.audioTrack.play()}}_initPlayerEvents(e,t=!1,i=StreamIndex$1.STREAM_INDEX_MAIN){var r;null==(r=this.__onPlayerEvents)||r.call(this,e,t,i),e.on("playback_event",(t=>{const i=this._remoteStreams.get(e.userId);if("loadeddata"===t.eventName){const e=()=>{i&&"video"===t.type&&this.safeEmit(WTNStreamEventsTypes.onWTNFirstRemoteVideoFrameDecoded,{streamId:i.streamId})};!(null==i?void 0:i.observer)||i.observer.audioFirstFrameReceived?e():i.observer.once("recvVideoFirstFrame",e)}}))}async _maybeFillBackFrame2Stream(e){var t,i,r;if(e.refreshBlackFrameLifetime(),!(null==(t=e.videoTransceiver)?void 0:t.sender.track)){const t=e.genBlackFrame();if(!t)return;null==(r=null==(i=e.videoTransceiver)?void 0:i.sender)||r.replaceTrack(t),e.pubAttributes.videoType=VideoType.BLACK,this._ctx.signalingManager.sendSignaling("updatePushStream",{streamId:e.streamId,appId:this._ctx.appId,attributes:{videoType:VideoType.BLACK}}),e.on("black-frame-ended",(()=>{var t,i;null==(i=null==(t=e.videoTransceiver)?void 0:t.sender)||i.replaceTrack(null),e.pubAttributes.videoType=VideoType.NORMAL,this._ctx.signalingManager.sendSignaling("updatePushStream",{streamId:e.streamId,appId:this._ctx.appId,attributes:{videoType:VideoType.NORMAL}})}))}}safeEmit(e,...t){return reportRtcSdkCallback(this._ctx.id,e,t),super.safeEmit(e,...t)}_assertNotConnect(){if(!this._ctx.signalingManager.isConnected())throw new SDKError(ErrorCode.NOT_CONNECTED_YET,"server not connected")}getWTNPlayLock(e){let t=this._wtnPlayLocks.get(e);return t||(t=new PromiseLock2(`wtn_play_${e}`),this._wtnPlayLocks.set(e,t)),t}}function wtnPlayLock(e,t,i){const r=i.value;return i.value=async function(...e){let i="";"startPlayWTN"===t?i=e[1]:"stopPlayWTN"===t&&(i=e[0]);const o=await this.getWTNPlayLock(i).lock();try{return await r.apply(this,e)}finally{o()}},i}__decorateClass$2([reportRtcSdkApi()],WTNStream.prototype,"startPushWTN",1),__decorateClass$2([reportRtcSdkApi()],WTNStream.prototype,"stopPushWTN",1),__decorateClass$2([reportRtcSdkApi()],WTNStream.prototype,"muteWTNLocalAudio",1),__decorateClass$2([reportRtcSdkApi()],WTNStream.prototype,"muteWTNLocalVideo",1),__decorateClass$2([reportRtcSdkApi()],WTNStream.prototype,"sendWTNSEIMessage",1),__decorateClass$2([reportRtcSdkApi(),wtnPlayLock],WTNStream.prototype,"startPlayWTN",1),__decorateClass$2([reportRtcSdkApi(),wtnPlayLock],WTNStream.prototype,"stopPlayWTN",1),__decorateClass$2([reportRtcSdkApi()],WTNStream.prototype,"muteWTNRemoteAudio",1),__decorateClass$2([reportRtcSdkApi()],WTNStream.prototype,"muteWTNRemoteVideo",1),__decorateClass$2([reportRtcSdkApi()],WTNStream.prototype,"setWTNRemoteVideoPlayer",1),__decorateClass$2([reportRtcSdkApi()],WTNStream.prototype,"setWTNRemoteAudioPlaybackVolume",1),__decorateClass$2([pubSubLock],WTNStream.prototype,"_sendStartPushStreamSignal",1),__decorateClass$2([pubSubLock],WTNStream.prototype,"_stopLocalStream",1),__decorateClass$2([pubSubLock],WTNStream.prototype,"_sendStartPullStreamSignal",1),__decorateClass$2([pubSubLock],WTNStream.prototype,"_unsubscribePublicStream",1);const MAX_RECORDER_DURATION=3e4,logger$1=new Logger$1("AudioDeviceManager",1);class AudioDeviceManager extends eventemitter3Exports.EventEmitter{constructor(e){super(),__publicField(this,"_audioLevelFetcher"),__publicField(this,"_playbackDeviceTestTimer"),__publicField(this,"_audioElement"),__publicField(this,"_audioTrack"),__publicField(this,"_mediaRecorder"),__publicField(this,"_recoderTimer"),__publicField(this,"_isAudioPlaybackDeviceTesting",!1),__publicField(this,"_isAudioDeviceRecordTesting",!1),__publicField(this,"_audioCaptureAndRecoderResolve"),__publicField(this,"_onAutoplayFailed"),__publicField(this,"_audioPlaybackDeviceId"),this._ctx=e}get audioTrack(){return this._audioTrack}async startAudioPlaybackDeviceTest(e,t){if(this._isAudioPlaybackDeviceTesting||this._isAudioDeviceRecordTesting)throw new SDKError(ErrorCode.REPEAT_DEVICE_TEST,"device test cannot be called repeatedly at the same time.");this._isAudioPlaybackDeviceTesting=!0,logger$1.info("startAudioPlaybackDeviceTest()","Invoke");try{await this._playAudioFile(e,{loop:!0})}catch(e){throw logger$1.error("startAudioPlaybackDeviceTest()","error",e),this.stopAudioPlaybackDeviceTest(),e}this._startEmitAudioPlaybackDeviceTestVolume(t)}stopAudioPlaybackDeviceTest(){this._isAudioPlaybackDeviceTesting&&(logger$1.info("stopAudioPlaybackDeviceTest()","Invoke"),this._isAudioPlaybackDeviceTesting=!1,this._stopEmitAudioPlaybackDeviceTestVolume(),this._destroyAudioElement())}async startAudioDeviceRecordTest(e,t,i,r=3e4){if(!window.MediaRecorder)throw new SDKError(ErrorCode.NOT_SUPPORTED,"Your browser does not support MediaRecorder.");if(this._isAudioDeviceRecordTesting||this._isAudioPlaybackDeviceTesting)throw new SDKError(ErrorCode.REPEAT_DEVICE_TEST,"device test cannot be called repeatedly at the same time.");this._isAudioDeviceRecordTesting=!0,logger$1.info("startAudioDeviceRecordTest()","Invoke"),this._recoderTimer=setTimeout((()=>{logger$1.info("startAudioDeviceRecordTest()",`${r}ms automatic call method "stopAudioDeviceRecordAndPlayTest"`),this._stopAudioCaptureAndRecoder()}),r);try{this._onAutoplayFailed=t,await this._startAudioCaptureAndRecoder(e,i??100)}catch(e){throw this._isAudioDeviceRecordTesting=!1,delete this._onAutoplayFailed,e}delete this._audioCaptureAndRecoderResolve}stopAudioDeviceRecordAndPlayTest(){logger$1.info("stopAudioDeviceRecordAndPlayTest()","Invoke"),void 0!==this._recoderTimer&&(clearTimeout(this._recoderTimer),delete this._recoderTimer),this._stopAudioCaptureAndRecoder()}stopAudioDevicePlayTest(){this._isAudioDeviceRecordTesting&&(logger$1.info("stopAudioDevicePlayTest()","Invoke"),this._isAudioDeviceRecordTesting=!1,this._mediaRecorder&&(this._mediaRecorder.ondataavailable=null),this.stopAudioDeviceRecordAndPlayTest(),this._stopEmitAudioPlaybackDeviceTestVolume(),this._destroyAudioElement()),delete this._onAutoplayFailed}getRecordTrack(){return this._audioTrack}async setSinkId(e){if(logger$1.info("setSinkId()","Invoke"),void 0===HTMLAudioElement.prototype.setSinkId)throw new SDKError(ErrorCode.NOT_SUPPORTED,"setSinkId not supported by current browser");const t=await dd.getAudioPlaybackDeviceById(e);if(!t)throw new SDKError(ErrorCode.INVALID_DEVICE_ID,`audio playback device id ${e} is invalid`);return this._audioPlaybackDeviceId=e,this._setAudioCtxSinkId(),t}getSinkId(){return this._audioPlaybackDeviceId}destroy(){logger$1.info("destroy()","Invoke"),super.removeAllListeners(),this.stopAudioPlaybackDeviceTest(),this.stopAudioDevicePlayTest()}async _playAudioFile(e,t){return logger$1.info("_playAudioFile()",`Invoke url=${e}; loop=${t.loop}`),new Promise(((i,r)=>{const o=createElement("audio",{attributes:{src:e,crossOrigin:"anonymous"}});this._audioElement=o,o.loop=t.loop,this._audioLevelFetcher=new AudioLevelFetcher(o),o.onplaying=()=>{o.onplaying=null,logger$1.info("_playAudioFile()","onplaying"),i()},o.onerror=async e=>{var t;logger$1.error("_playAudioFile()","onerror",e);const i=e.message||(null==(t=null==o?void 0:o.error)?void 0:t.message);r(new SDKError(ErrorCode.LOAD_RESOURCES_FAILED,"Failed to play recorded audio"+(i?`, reason: ${i}`:".")))},this._setAudioCtxSinkId().then((()=>{var e,t;return null==(t=null==(e=o.play())?void 0:e.catch)?void 0:t.call(e,(e=>{logger$1.warn("_playAudioFile()","autoplay error",e);const t=`Failed to play recorded audio, ${e.name}: ${e.message}`;"NotAllowedError"===e.name&&this._onAutoplayFailed?this._onAutoplayFailed((()=>{var e;return Promise.all([null==(e=this._audioLevelFetcher)?void 0:e.resume(),o.play()])})):r(new SDKError(ErrorCode.LOAD_RESOURCES_FAILED,t))}))}))}))}_destroyAudioElement(){this._audioElement&&(logger$1.info("_destroyAudioElement()","Invoke"),this._audioElement.onplaying=null,this._audioElement.onerror=null,this._audioElement.src="",delete this._audioElement,"function"==typeof this._audioCaptureAndRecoderResolve&&this._audioCaptureAndRecoderResolve())}_startEmitAudioPlaybackDeviceTestVolume(e){e=Math.max(e,100),this._audioElement&&(logger$1.info("_startEmitAudioPlaybackDeviceTestVolume()",`start timer(${e}ms)`),this._playbackDeviceTestTimer=self.setInterval((()=>{this._audioLevelFetcher&&this.emit("onAudioPlaybackDeviceTestVolume",this._audioLevelFetcher.getAudioLevel())}),e))}_stopEmitAudioPlaybackDeviceTestVolume(){var e;void 0!==this._playbackDeviceTestTimer&&(logger$1.info("_stopEmitAudioPlaybackDeviceTestVolume()","stop timer"),self.clearInterval(this._playbackDeviceTestTimer),delete this._playbackDeviceTestTimer),null==(e=this._audioLevelFetcher)||e.destroy(),delete this._audioLevelFetcher}async _startAudioCaptureAndRecoder(e,t){this._audioTrack=await createMicrophoneAudioTrack(this._ctx,this._ctx.audioProfileManager.getConstraints()),this._audioTrack.setVolume(t+.01);const i=new MediaStream([this._audioTrack.preprocessingTrack]);return logger$1.info("startAudioDeviceRecordTest()","create microphone track success!"),new Promise(((t,r)=>{let o;"function"==typeof MediaRecorder.isTypeSupported&&(o=["audio/webm","audio/mp4"].find((e=>MediaRecorder.isTypeSupported(e))),logger$1.info("startAudioDeviceRecordTest()",`use mimeType: ${o}`)),this._mediaRecorder=new MediaRecorder(i,o?{mimeType:o}:void 0);const s=this._mediaRecorder.mimeType;this._mediaRecorder.ondataavailable=async i=>{var o;if(this._isAudioDeviceRecordTesting){logger$1.info("startAudioDeviceRecordTest()",`get recorded file(mimeType: ${s}).`);const n=new Blob([i.data],{type:s});try{await this._playAudioFile(URL.createObjectURL(n),{loop:!1})}catch(e){return r(e)}this._startEmitAudioPlaybackDeviceTestVolume(e),null==(o=this._audioElement)||o.addEventListener("ended",(()=>{this.stopAudioDevicePlayTest(),t()})),this._audioCaptureAndRecoderResolve=t}else t()},this._mediaRecorder.onerror=e=>{r(new SDKError(ErrorCode.AUDIO_DEVICE_TEST_FAILED,e.message||"mediaRecorder error"))},this._audioCaptureAndRecoderResolve=t,this._mediaRecorder.start()}))}_stopAudioCaptureAndRecoder(){var e;this._mediaRecorder&&("recording"===this._mediaRecorder.state&&this._mediaRecorder.stop(),delete this._mediaRecorder),null==(e=this._audioTrack)||e.destroy(),delete this._audioTrack}async _setAudioCtxSinkId(){var e,t;let i=this._audioPlaybackDeviceId;if(i){"default"===i&&(i="");try{null==(t=null==(e=audioContextManager.getAudioContextInstance())?void 0:e.setSinkId)||t.call(e,i),logger$1.info("setSinkId",`ctx.sinkId=${i}`)}catch(e){logger$1.error("setSinkId",`failed, ${e.name} - ${e.message}`)}}}}const getDefaultValue=()=>({url:"",video:{codec:TRANSCODING_VIDEO_CODEC.H264,width:640,height:360,fps:15,gop:2,kBitRate:getKBitRate(640,360,15)},audio:{codec:"AAC",kBitRate:64,sampleRate:48e3,channels:2,AACProfile:AAC_PROFILE.LC},layout:{regions:[],appData:"",backgroundColor:"#000000"}});function getKBitRate(e,t,i){return e*t<=288e3?i<=15?800:1200:e*t<=864e3?i<=15?1200:1800:e*t<=1152e3?i<=15?1600:2400:e*t<=2592e3?i<=15?2500:3750:i<=15?3300:5e3}function checkRtmpUrl(e){if("string"!=typeof e||!/^rtmps?:\/\//.test(e))throw new SDKError(ErrorCode.INVALID_PARAMS,"Invalid rtmp address")}function checkTranscodeRegions(e=[]){if(!(null==e?void 0:e.length))throw new SDKError(ErrorCode.INVALID_PARAMS,"regions should not be empty.");for(const t of e){if("string"!=typeof t.userId)throw new SDKError(ErrorCode.INVALID_PARAMS,`region.userId(${t.userId}) should be a string.`);if(checkUserId(t.userId),"boolean"!=typeof t.isScreenStream)throw new SDKError(ErrorCode.INVALID_PARAMS,`region.isScreenStream(${t.isScreenStream}) should be a boolean.`)}}function getTranscodeControlMessage(e,t){var i,r,o;const s=(e,i)=>{const r=e.reduce(((e,t)=>null==e?void 0:e[t]),t),o=e.reduce(((e,t)=>null==e?void 0:e[t]),getDefaultValue());return r&&i(r)?r:o},n=e=>e%2==0?e:e+1,a=n(s(["video","width"],(e=>e>=2&&e<=1920))),d=n(s(["video","height"],(e=>e>=2&&e<=1920))),c=s(["video","fps"],(e=>e>=1&&e<=60)),l=(null==(i=t.video)?void 0:i.kBitRate)||0,u=s(["audio","sampleRate"],(e=>!![32e3,44100,48e3].find((t=>t===e||t/1e3===e))));return{type:"transcode",action:e,transcodeMeta:{transcode:{url:t.url},control:{protocol:"2.0"},audio:{codec:s(["audio","codec"],(e=>"AAC"===e)),bitRate:1e3*s(["audio","kBitRate"],(e=>e>=32&&e<=192)),sampleRate:u<100?1e3*u:u,channels:s(["audio","channels"],(e=>[1,2].includes(e))),profile:s(["audio","AACProfile"],(e=>[AAC_PROFILE.LC,AAC_PROFILE.HEv1,AAC_PROFILE.HEv2].includes(e)))},video:{codec:s(["video","codec"],(e=>["H264","H265"].includes(e))),fps:c,gop:s(["video","gop"],(e=>e>=1&&e<=5))*c,bitRate:1e3*(l>=16&&l<=1e4?l:getKBitRate(a,d,c)),width:a,height:d},layout:{canvas:{bgnd:s(["layout","backgroundColor"],(e=>/^#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})$/.test(e)))},regions:(null==(o=null==(r=t.layout)?void 0:r.regions)?void 0:o.map((e=>({alpha:!e.alpha||Number(e.alpha)>1||Number(e.alpha)<=0?1:Number(e.alpha),uid:e.userId,zorder:!e.zorder||Number(e.zorder)<0||Number(e.zorder)>100?0:Number(e.zorder),x:!e.x||Number(e.x)>=1||Number(e.x)<0?0:Number(e.x),y:!e.y||Number(e.y)>=1||Number(e.y)<0?0:Number(e.y),w:!e.w||Number(e.w)>1||Number(e.w)<=0?1:Number(e.w),h:!e.h||Number(e.h)>1||Number(e.h)<=0?1:Number(e.h),renderMode:e.renderMode&&[1,2,3].includes(e.renderMode)?e.renderMode:1,contentControl:e.contentControl&&[0,1,2].includes(e.contentControl)?e.contentControl:0,screen:!!e.isScreenStream}))))||[],app_data:s(["layout","appData"],(e=>"string"==typeof e))}}}}function checkStartParams(e){var t;checkRtmpUrl(e.url),checkTranscodeRegions(null==(t=e.layout)?void 0:t.regions)}function checkUpdateParams(e){var t;e.url&&checkRtmpUrl(e.url),checkTranscodeRegions(null==(t=e.layout)?void 0:t.regions)}function getStartParams(e){return getTranscodeControlMessage("started",e)}function getUpdateParams(e){return getTranscodeControlMessage("layoutChanged",e)}const LiveTranscoding={getDefaultValue:getDefaultValue,checkStartParams:checkStartParams,checkUpdateParams:checkUpdateParams,getStartParams:getStartParams,getUpdateParams:getUpdateParams};let remoteAudioReplayTimer;const replayRemoteAudioWorkaround=e=>{remoteAudioReplayTimer&&clearTimeout(remoteAudioReplayTimer),remoteAudioReplayTimer=setTimeout((()=>{for(const[t,i]of e)(null==t?void 0:t.startsWith("mux"))&&i.forEach((e=>{var t;null==(t=e.audioTrack)||t.pause()}));for(const[t,i]of e)(null==t?void 0:t.startsWith("mux"))&&i.forEach((e=>{var t;null==(t=e.audioTrack)||t.play()}))}),2e3)},MEDIA_STATES=["currentTime","duration","ended","error","muted","networkState","paused","readyState","seekable","sinkId","src","volume"],AUDIOCONTEXT_STATES=["currentTime","sampleRate","state","baseLatency","outputLatency","sinkId"],TRACK_STATES=["contentHint","enabled","id","kind","label","muted","readyState"],TRANSCEIVER_STATES=["currentDirection","direction","mid","stopped"];let ac;async function getStats(e){const t=Date.now();let i=[];e._ctx.handler&&e._ctx.handler._peerConnection&&(i=await e._ctx.handler._peerConnection.getStats());const r=[];return i.forEach((e=>{r.push(e)})),{timestamp:t,stats:r}}function formatSrcObject(e){const t={};if(e instanceof MediaStream){t.id=e.id,t.active=e.active;const i=e.getTracks();t.tracks=i.map((e=>Object.fromEntries(TRACK_STATES.map((t=>[t,e[t]])))))}return t}async function getMediaElementState(e){var t;const i=Date.now(),r=[];e._videoPlayer&&r.push({userId:"__local__",mediaType:"video",isScreen:!1,isPublic:!1,ele:e._videoPlayer._videoDom}),e._screenPlayer&&r.push({userId:"__local__",mediaType:"video",isScreen:!0,isPublic:!1,ele:e._screenPlayer._videoDom}),e._remoteVideoPlayer&&e._remoteVideoPlayer.forEach(((e,t)=>{r.push({userId:t,mediaType:"video",isScreen:!1,isPublic:!1,ele:e?e._videoDom:void 0})})),e._remoteScreenPlayer&&(null==(t=e._remoteScreenPlayer)||t.forEach(((e,t)=>{r.push({userId:t,mediaType:"video",isScreen:!0,isPublic:!1,ele:e?e._videoDom:void 0})}))),e._remoteAudioPlayer&&e._remoteAudioPlayer.forEach(((e,t)=>{r.push({userId:t,mediaType:"audio",isScreen:!1,isPublic:!1,ele:e?e._audioDom:void 0,fakeEle:e?e._fakeAudioDom:void 0})})),e._remoteScreenAudioPlayer&&e._remoteScreenAudioPlayer.forEach(((e,t)=>{r.push({userId:t,mediaType:"audio",isScreen:!0,isPublic:!1,ele:e?e._audioDom:void 0,fakeEle:e?e._fakeAudioDom:void 0})})),e._publicStreamVideoPlayer&&e._publicStreamVideoPlayer.forEach(((e,t)=>{r.push({userId:t,mediaType:"video",isScreen:!1,isPublic:!0,ele:e?e._videoDom:void 0})})),e._publicStreamAudioPlayer&&e._publicStreamAudioPlayer.forEach(((e,t)=>{r.push({userId:t,mediaType:"audio",isScreen:!1,isPublic:!0,ele:e?e._audioDom:void 0,fakeEle:e?e._fakeAudioDom:void 0})})),e._localVideoTrack&&e._localVideoTrack.videoPlayers&&e._localVideoTrack.videoPlayers.forEach(((e,t)=>{r.push({playerId:t.toString(),userId:"__local__",mediaType:"video",isScreen:!1,isPublic:!1,ele:e._videoDom})})),e._localScreenTrack&&e._localScreenTrack.videoPlayers&&e._localScreenTrack.videoPlayers.forEach(((e,t)=>{r.push({playerId:t.toString(),userId:"__local__",mediaType:"video",isScreen:!0,isPublic:!1,ele:e._videoDom})})),e._room&&e._room._remoteStreams&&e._room._remoteStreams.forEach(((e,t)=>{e.forEach((e=>{if(e.audioTrack){const i=e.audioTrack._audioPlayer;r.push({userId:t,mediaType:"audio",isScreen:e.isScreen,isPublic:!1,ele:i?i._audioDom:void 0,fakeEle:i?i._fakeAudioDom:void 0})}e.videoTrack&&e.videoTrack.videoPlayers&&e.videoTrack.videoPlayers.forEach(((i,o)=>{r.push({playerId:o.toString(),userId:t,mediaType:"video",isScreen:e.isScreen,isPublic:!1,ele:i?i._videoDom:void 0})}))}))}));let o=e._publicStreamManager;o||(o=e._outsideRoom),o&&o.remoteStreams&&o.remoteStreams.forEach(((e,t)=>{if(e.audioTrack){const i=e.audioTrack._audioPlayer;r.push({userId:t,mediaType:"audio",isScreen:!1,isPublic:!0,ele:i?i._audioDom:void 0,fakeEle:i?i._fakeAudioDom:void 0})}e.videoTrack&&e.videoTrack.videoPlayers&&e.videoTrack.videoPlayers.forEach(((e,i)=>{r.push({playerId:i.toString(),userId:t,mediaType:"video",isScreen:!1,isPublic:!0,ele:e?e._videoDom:void 0})}))})),e&&e._room&&e._room._virtualStreams&&e._room._virtualStreams.forEach(((e,t)=>{if(e.audioTrack){const i=e.audioTrack._audioPlayer;r.push({userId:`virtualStream-${t}`,mediaType:"audio",isScreen:!1,isPublic:!1,isVirtual:!0,ele:i?i._audioDom:void 0,fakeEle:i?i._fakeAudioDom:void 0})}}));return{timestamp:i,elementStats:r.map((({ele:e,fakeEle:t,...i})=>{const r={ele:{srcObject:e?formatSrcObject(e.srcObject):void 0,...Object.fromEntries(MEDIA_STATES.map((t=>[t,e[t]])))},...i};return t&&(r.fakeEle={srcObject:formatSrcObject(t.srcObject),...Object.fromEntries(MEDIA_STATES.map((e=>[e,t[e]])))}),r}))}}function findAudioContextInEngine(e){const t=[];let i=[];e&&e._room&&e._room._remoteStreams&&(i=e._room._remoteStreams.values());for(const e of i)e.forEach((e=>{e.audioTrack&&t.push(e.audioTrack)}));e._localAudioTrack&&t.push(e._localAudioTrack),e._localScreenAudioTrack&&t.push(e._localScreenAudioTrack);for(const e of t){if(e._audioLevelFetcher&&e._audioLevelFetcher._ctx)return e._audioLevelFetcher._ctx;if(e._ac)return e._ac;if(e._audioFetchMap&&Array.from(e._audioFetchMap.values()).length)return Array.from(e._audioFetchMap.values())[0]._ctx;if(e._ap&&e._ap._ac)return e._ap._ac}return null}async function getAudioContextState(e){const t=Date.now(),i=findAudioContextInEngine(e),r={};return i?(AUDIOCONTEXT_STATES.forEach((e=>{r[e]=i[e]})),{timestamp:t,acState:r}):{timestamp:t,acState:void 0}}function getTrack(e){const t=[];e._localAudioTrack&&t.push({userId:"__local__",mediaType:"audio",isScreen:!1,isPublic:!1,isVirtual:!1,orgTrack:e._localAudioTrack._originTrack,mediaTrack:e._localAudioTrack._mediaTrack,preprocessingTrack:e._localAudioTrack._preProcessingTrack}),e._localScreenAudioTrack&&t.push({userId:"__local__",mediaType:"audio",isScreen:!0,isPublic:!1,isVirtual:!1,orgTrack:e._localScreenAudioTrack._originTrack,mediaTrack:e._localScreenAudioTrack._mediaTrack,preprocessingTrack:e._localScreenAudioTrack._preProcessingTrack}),e._localVideoTrack&&t.push({userId:"__local__",mediaType:"video",isScreen:!1,isPublic:!1,isVirtual:!1,orgTrack:e._localVideoTrack._originTrack,mediaTrack:e._localVideoTrack._mediaTrack,preprocessingTrack:e._localVideoTrack._preProcessingTrack}),e._localScreenVideoTrack&&t.push({userId:"__local__",mediaType:"video",isScreen:!0,isPublic:!1,isVirtual:!1,orgTrack:e._localScreenVideoTrack._originTrack,mediaTrack:e._localScreenVideoTrack._mediaTrack,preprocessingTrack:e._localScreenVideoTrack._preProcessingTrack}),e._room&&e._room._remoteStreams&&e._room._remoteStreams.forEach(((e,i)=>{e.forEach((e=>{e.audioTrack&&t.push({userId:i,mediaType:"audio",isScreen:e.isScreen,isPublic:!1,isVirtual:!1,orgTrack:e.audioTrack._originTrack,mediaTrack:e.audioTrack._mediaTrack}),e.videoTrack&&t.push({userId:i,mediaType:"video",isScreen:e.isScreen,isPublic:!1,isVirtual:!1,orgTrack:e.videoTrack._originTrack,mediaTrack:e.videoTrack._mediaTrack})}))}));let i=e._publicStreamManager;return i||(i=e._outsideRoom),i&&i.remoteStreams&&i.remoteStreams.forEach(((e,i)=>{e.audioTrack&&t.push({userId:i,mediaType:"audio",isScreen:e.isScreen,isPublic:!0,isVirtual:!1,orgTrack:e.audioTrack._originTrack,mediaTrack:e.audioTrack._mediaTrack}),e.videoTrack&&t.push({userId:i,mediaType:"video",isScreen:e.isScreen,isPublic:!0,isVirtual:!1,orgTrack:e.videoTrack._originTrack,mediaTrack:e.videoTrack._mediaTrack})})),e&&e._room&&e._room._virtualStreams&&e._room._virtualStreams.forEach(((e,i)=>{e.audioTrack&&t.push({userId:`virtualStream-${i}`,mediaType:"audio",isScreen:!1,isPublic:!1,isVirtual:!0,orgTrack:e.audioTrack._originTrack,mediaTrack:e.audioTrack._mediaTrack}),e.videoTrack&&t.push({userId:`virtualStream-${i}`,mediaType:"video",isScreen:!1,isPublic:!1,isVirtual:!0,orgTrack:e.videoTrack._originTrack,mediaTrack:e.videoTrack._mediaTrack})})),t}async function getVolumeFromTrack(e,t){if(!e)return;const i=new MediaStream;i.addTrack(e);const r=t.createMediaStreamSource(i),o=t.createAnalyser();r.connect(o),"suspended"===t.state&&(console.warn(t.state),t.resume());const s=new Uint8Array(2048);o.getByteTimeDomainData(s),await new Promise((e=>{setTimeout(e,50)})),o.getByteTimeDomainData(s),await new Promise((e=>{setTimeout(e,50)}));let n=0;s.forEach((e=>n=Math.max(n,Math.abs(e-128))));const a=n/128*256,d=a>2?a:0;return r.disconnect(),o.disconnect(),d}async function getVolume(e){const t=Date.now();if(ac||(ac=new AudioContext),"suspended"===ac.state&&await new Promise((t=>{const i=setTimeout((()=>{console.warn("[RTC_AMBULANCE] AudioContext resume failed, try to find one in RTCEngine"),ac=findAudioContextInEngine(e),ac&&console.warn("[RTC_AMBULANCE] find AudioContext in RTCEngine success"),t()}),1e3);ac.resume().then((()=>{clearTimeout(i),t()}),(()=>{clearTimeout(i),ac=null,t()}))})),!ac)return void console.error("[RTC_AMBULANCE] get volume is not supported");const i=getTrack(e),r=[];return await Promise.all(i.filter((e=>"audio"===e.mediaType)).map((async({orgTrack:e,mediaTrack:t,preprocessingTrack:i,...o})=>{const s={...o};await Promise.all([getVolumeFromTrack(e,ac).then((e=>{s.orgTrackVolume=e})),getVolumeFromTrack(t,ac).then((e=>{s.mediaTrackVolume=e})),getVolumeFromTrack(i,ac).then((e=>{s.preprocessingTrackVolume=e}))]),r.push(s)}))),{timestamp:t,trackVolumes:r}}async function getTrackState(e){return{timestamp:Date.now(),trackStates:getTrack(e).map((({orgTrack:e,mediaTrack:t,preprocessingTrack:i,...r})=>({orgTrack:e?Object.fromEntries(TRACK_STATES.map((t=>[t,e[t]]))):void 0,mediaTrack:t?Object.fromEntries(TRACK_STATES.map((e=>[e,t[e]]))):void 0,preprocessingTrack:i?Object.fromEntries(TRACK_STATES.map((e=>[e,i[e]]))):void 0,...r})))}}function formatSenderOrReceiver(e){if(!e)return;const t={track:e.track?e.track.id:void 0,transport:{state:e.transport?e.transport.state:void 0}};return e.transport&&e.transport.iceTransport&&(t.iceTransport={state:e.transport.iceTransport.state,role:e.transport.iceTransport.role,gatheringState:e.transport.iceTransport.gatheringState,component:e.transport.iceTransport.component}),t}async function getTranceiverState(e){const t=Date.now();let i=[];e._ctx._handler&&e._ctx._handler._peerConnection&&(i=e._ctx._handler._peerConnection.getTransceivers());const r=[];return i.forEach((e=>{const t={sender:formatSenderOrReceiver(e.sender),receiver:formatSenderOrReceiver(e.receiver),...Object.fromEntries(TRANSCEIVER_STATES.map((t=>[t,e[t]])))};r.push(t)})),{timestamp:t,tranceiverStates:r}}async function ambulance(e){const t={stats:[],mediaElementStates:[],audioContextStates:[],volumes:[],trackStates:[],tranceiverStates:[]},i=[];return await new Promise((r=>{let o,s=0;const n=()=>{i.push(getStats(e).then((e=>{t.stats.push(e)})),getMediaElementState(e).then((e=>{t.mediaElementStates.push(e)})),getAudioContextState(e).then((e=>{t.audioContextStates.push(e)})),getVolume(e).then((e=>{t.volumes.push(e)})),getTrackState(e).then((e=>{t.trackStates.push(e)})),getTranceiverState(e).then((e=>{t.tranceiverStates.push(e)}))),s++,s>=10?Promise.all(i).then((()=>{r()})):(clearTimeout(o),o=setTimeout(n,500))};o=setTimeout(n,500)})),console.log("RTC_AMBULANCE",t),t}class ContainerCollisionDetector{constructor(){__publicField(this,"containers",new WeakSet)}getContainerById(e){return document.getElementById(e)}registerContainer(e){return"string"==typeof e&&(e=this.getContainerById(e)??void 0),!(!e||this.containers.has(e))&&(this.containers.add(e),!0)}unregisterContainer(e){return"string"==typeof e&&(e=this.getContainerById(e)??void 0),!!e&&(this.containers.delete(e),!0)}}var __defProp$1=Object.defineProperty,__getOwnPropDesc$1=Object.getOwnPropertyDescriptor,__decorateClass$1=(e,t,i,r)=>{for(var o,s=r>1?void 0:r?__getOwnPropDesc$1(t,i):t,n=e.length-1;n>=0;n--)(o=e[n])&&(s=(r?o(t,i,s):o(s))||s);return r&&s&&__defProp$1(t,i,s),s};const _RTCEngine=(_v=class extends EnhancedEventEmitter{constructor(e,t,i){super(),__publicField(this,"monitor"),__publicField(this,"logger"),__publicField(this,"_room"),__publicField(this,"_wtnStreamManager"),__publicField(this,"_appId"),__publicField(this,"_localImgVideoTrack"),__publicField(this,"_localImgScreenTrack"),__publicField(this,"_localScreenVideoTrack"),__publicField(this,"_localScreenAudioTrack"),__publicField(this,"_tempMixingAudioTrack"),__publicField(this,"_localAudioVolume",100),__publicField(this,"_localScreenAudioVolume",100),__publicField(this,"_remoteAudioVolume",new Map),__publicField(this,"_remoteScreenAudioVolume",new Map),__publicField(this,"_localVideoPlayerConfig",{[StreamIndex$1.STREAM_INDEX_MAIN]:new Map,[StreamIndex$1.STREAM_INDEX_SCREEN]:new Map}),__publicField(this,"_remoteVideoPlayerConfig",{[StreamIndex$1.STREAM_INDEX_MAIN]:new Map,[StreamIndex$1.STREAM_INDEX_SCREEN]:new Map}),__publicField(this,"_publicStreamIds",new Map),__publicField(this,"_dummyMainImage"),__publicField(this,"_dummyScreenImage"),__publicField(this,"_trackSourceType"),__publicField(this,"_liveTranscodeConfig"),__publicField(this,"_startCloudProxyTimestamp"),__publicField(this,"_pauseAllSubscribeState",{audio:void 0,video:void 0,resumeAudioStreamIds:{},resumeVideoStreamIds:{}}),__publicField(this,"_audioVolumeIndicationTimer"),__publicField(this,"_dummyMainTimer"),__publicField(this,"_dummyScreenTimer"),__publicField(this,"_audioPropertiesReportTimer",null),__publicField(this,"_mirrorType",MirrorType.MIRROR_TYPE_RENDER),__publicField(this,"_audioMixingManager"),__publicField(this,"_pubLock"),__publicField(this,"_subLocks"),__publicField(this,"_audioCaptureLock"),__publicField(this,"_videoCaptureLock"),__publicField(this,"_screenCaptureLock"),__publicField(this,"_subScreenLocks"),__publicField(this,"_rtmClient"),__publicField(this,"_messageStatisticsObserver"),__publicField(this,"_waitForNewToken",!1),__publicField(this,"_originIceConfigRequestUrls"),__publicField(this,"_originConfigServerUrls"),__publicField(this,"_originLogServerUrl"),__publicField(this,"_audioDeviceManager"),__publicField(this,"_config"),__publicField(this,"_needClosePreTrack",!1),__publicField(this,"_containerCollisionDetector",new ContainerCollisionDetector),__publicField(this,"_ctx"),__publicField(this,"_removeDeviceEventHandler"),__publicField(this,"_updateMixAudioTrack",(async(e,t=AudioMixingType.PLAYOUT_AND_PUBLISH)=>{var i;if(this.logger.info("_updateMixAudioTrack()"),!this._localAudioTrack)return void(e&&(this._tempMixingAudioTrack={track:e,type:t}));e?(this._localAudioTrack.mixType=t,this._localAudioTrack.mixedAudioTrack=e):(delete this._localAudioTrack.mixType,delete this._localAudioTrack.mixedAudioTrack);await(null==(i=this._room)?void 0:i.hasPublished())&&await this._updatePublish(),this._wtnStreamManager._updatePushTrack()})),__publicField(this,"_onVideoDeviceStateChange",(e=>{this.safeEmit(EngineEventsTypes.onVideoDeviceStateChanged,e)})),__publicField(this,"_onAudioDeviceStateChange",(e=>{this.safeEmit(EngineEventsTypes.onAudioDeviceStateChanged,e)})),__publicField(this,"_onAudioMixingMessage",(e=>{this.safeEmit(EngineEventsTypes.onAudioMixingStateChanged,e)})),__publicField(this,"_onAudioMixingAutoplayFailed",(e=>{this.safeEmit(EngineEventsTypes.onAutoplayFailed,e)})),__publicField(this,"_revokeAutoplayFailedWorkaround"),this.id=t,this._appId=e,this.monitor=getMonitor(t),this._ctx=new RTCContext(t,e,i),this._pubLock=new PromiseLock2("pubLock"),this._subLocks=new Map,this._subScreenLocks=new Map,this._audioCaptureLock=new PromiseLock2("audioCap"),this._videoCaptureLock=new PromiseLock2("videoCap"),this._screenCaptureLock=new PromiseLock2("screenCap"),this._addDeviceEventHandler(),this._audioDeviceManager=new AudioDeviceManager(this._ctx),this._addSignalingEventHandler(),this._wtnStreamManager=new WTNStream(this._ctx),this._addWTNStreamEventHandler(),isDebuggerMode&&(window.__rtc_engine__=this,window[`__rtc_engine__${Math.floor(100*Math.random()+1)}`]=this),this._trackSourceType={video:VideoSourceType.VIDEO_SOURCE_TYPE_INTERNAL,screenVideo:VideoSourceType.VIDEO_SOURCE_TYPE_INTERNAL,audio:AudioSourceType.AUDIO_SOURCE_TYPE_INTERNAL,screenAudio:AudioSourceType.AUDIO_SOURCE_TYPE_INTERNAL},this._config=i,this._rtmClient=new RTSClient(this._ctx),this._handleRTMClient(this._rtmClient),this._handleAudioDeviceManager(),this._messageStatisticsObserver=new MessageStatisticsObserver(t),this.logger=new Logger$1("Engine",0,t),RTSMsgReportor.createRTSMsgReportor(this.id),_RTCEngine.hasReportNativeDetector||(this.monitor.reportLongString("NativeDetector",JSON.stringify(detectorResults)),_RTCEngine.hasReportNativeDetector=!0),this._initAutoplayFailedWorkaround()}get appId(){return this._appId}set appId(e){this._appId=e}async updateToken(e){if(this.logger.info("updateToken()","token: %s",e),checkString(e,"token"),this._room&&this._waitForNewToken)return this._waitForNewToken=!1,this._room.config.token=e,await this._join(this._room);if(!this._room)throw new SDKError(ErrorCode.UPDATE_TOKEN_BEFORE_JOIN,"update token before join room");await this._room.updateToken(e);const t=[];if(this._room.config.tokenPublishPrivilegeExpired&&this._room.config.isAutoPublish&&this._ctx.visibility&&t.push(this._updatePublish({mediaType:MediaType$1.AUDIO_AND_VIDEO})),this._room.config.tokenSubscribePrivilegeExpired){const{isAutoSubscribeAudio:e,isAutoSubscribeVideo:i}=this._room.config,r=(e?MediaType$1.AUDIO:0)|(i?MediaType$1.VIDEO:0);r&&t.push(this._triedResumeAllRemoteStreams(r,!0))}await Promise.allSettled(t)}async setVideoCaptureDevice(e){var t;if(this.logger.info("setVideoCaptureDevice()","deviceId: %s",e),checkString(e,"deviceId"),!this._localVideoTrack)return void this._ctx.videoProfile.setCaptureDeviceId(e);if(isWeChat&&isAndroid){if(this._localVideoTrack.originTrack.getSettings().deviceId===e)return}const i=this._ctx.videoProfile.getCaptureConfig(e);isAndroid&&isChrome&&chromeVersion>=85&&chromeVersion<=91&&(null==(t=this.localVideoTrack)||t.removePlayerTrack()),this._needClosePreTrack=this._needClosePreTrack||unsupportedSimultaneousCapture,this._needClosePreTrack&&(this._removeLocalTrackEvents(this._localVideoTrack),this._localVideoTrack.destroy(),delete this._localVideoTrack),this.logger.info("setVideoCaptureDevice()","start createCameraVideoTrack...");const r=await createCameraVideoTrack(this._ctx,i).catch((e=>{if(this._localVideoTrack&&!this._localVideoTrack.dummy)return this.logger.warn("setVideoCaptureDevice()","createCameraVideoTrack failed, stop pre VideoTrack."),this._removeLocalTrackEvents(this._localVideoTrack),this._localVideoTrack.destroy(),delete this._localVideoTrack,createCameraVideoTrack(this._ctx,i).then((e=>(this._needClosePreTrack=!0,e))).catch((async()=>{this.logger.error("setVideoCaptureDevice()","createCameraVideoTrack failed, rollback.");const t=await createCameraVideoTrack(this._ctx);throw this._switchTrack(t),e}));throw e}));this.logger.success("setVideoCaptureDevice()","createCameraVideoTrack success."),this._ctx.videoProfile.setCaptureDeviceId(e),this._localVideoTrack&&(this._removeLocalTrackEvents(this._localVideoTrack),this._localVideoTrack.destroy());const o=this._ctx.videoProfile.getContentHint();o&&r.setContentHint(o),await this._switchTrack(r)}async setAudioCaptureDevice(e){var t;if(this.logger.info("setAudioCaptureDevice()","deviceId: %s",e),checkString(e,"deviceId"),this._ctx.audioProfileManager.updateConstraints({deviceId:{exact:e}}),!this._localAudioTrack)return;this._localAudioTrack.destroy(),this._removeLocalTrackEvents(this._localAudioTrack);const i=await createMicrophoneAudioTrack(this._ctx,this._ctx.audioProfileManager.getConstraints());this._initLocalTrackEvents(i),this._localAudioTrack=i,this._localAudioTrack.setVolume(this._localAudioVolume),this._wtnStreamManager._updatePushTrack(),this._room&&(null==(t=this._room.localStream)?void 0:t.pubAudio)&&await this._updatePublish()}_addDeviceEventHandler(){dd.on(EngineEventsTypes.onVideoDeviceStateChanged,this._onVideoDeviceStateChange),dd.on(EngineEventsTypes.onAudioDeviceStateChanged,this._onAudioDeviceStateChange),this._removeDeviceEventHandler=()=>{dd.off(EngineEventsTypes.onVideoDeviceStateChanged,this._onVideoDeviceStateChange),dd.off(EngineEventsTypes.onAudioDeviceStateChanged,this._onAudioDeviceStateChange)}}_addSignalingEventHandler(){const e=this._ctx.signalingManager;e.on(StateEvent.ON_CONNECTION_STATE_CHANGE,this._onConnectionStateChange.bind(this)),e.on(StateEvent.ON_RECONNECT_FAILED,(()=>{this.safeEmit(EngineEventsTypes.onError,{errorCode:ErrorCode.RECONNECT_FAILED})})),e.on(StateEvent.CONNECT_WITH_TCP,(()=>{this.safeEmit(EngineEventsTypes.onIceConnectWithTcp)}))}_addWTNStreamEventHandler(){this._wtnStreamManager.__onResubscribe=e=>{const t=e.stream;t&&(t.audioTrack&&this._updateAudioPlayerState(t),t.videoTrack&&this._updateVideoPlayerState(t))},this._wtnStreamManager.__onRemoteStreamStats=e=>{this.safeEmit(EngineEventsTypes.onPublicStreamStats,e)},this._wtnStreamManager.__onSEIMessageReceived=e=>{this.safeEmit(EngineEventsTypes.onPublicStreamSEIMessageReceived,e)},this._wtnStreamManager.__onPlayerEvents=(e,t,i)=>{this._initPlayerEvents(e,t,i)}}_addHandlerEventHandler(){var e,t,i,r,o,s,n,a,d,c,l,u,_,h,p,m,S,g,v,f,E,T,R,b,y,I,C,A,k,M,N,O,P,D,w,L,x,F,U,V,B,$;null==(e=this._room)||e.on(SignalEvent.ON_ADD_STREAM,this._onAddStream.bind(this)),null==(t=this._room)||t.on(SignalEvent.ON_REMOVE_STREAM,this._onRemoveStream.bind(this)),null==(i=this._room)||i.on(SignalEvent.USER_CONNECTION,this._onUserConnection.bind(this)),null==(r=this._room)||r.on(RoomEvent.ON_USER_LEAVE,this._onUserLeave.bind(this)),null==(o=this._room)||o.on(RoomEvent.ON_ROOM_ERROR,this._onRoomError.bind(this)),null==(s=this._room)||s.on(RoomEvent.ON_NETWORK_QUALITY,this._onNetworkQuality.bind(this)),null==(n=this._room)||n.on(SignalEvent.ON_CUSTOM_MESSAGE,this._onCustomMessage.bind(this)),null==(a=this._room)||a.on(SignalEvent.USER_MESSAGE_RECEIVED,this._onUserMessageReceived.bind(this)),null==(d=this._room)||d.on(SignalEvent.USER_BINARY_MESSAGE_RECEIVED,this._onUserBinaryMessageReceived.bind(this)),null==(c=this._room)||c.on(SignalEvent.ON_USER_TOKEN_WILL_EXPIRE,this._onUserTokenWillExpire.bind(this)),null==(l=this._room)||l.on(SignalEvent.ON_TOKEN_PUBLISH_PRIVILEGE_WILL_EXPIRE,this._onUserTokenPublishPrivilegeWillExpire.bind(this)),null==(u=this._room)||u.on(SignalEvent.ON_TOKEN_PUBLISH_PRIVILEGE_DID_EXPIRED,this._onUserTokenPublishPrivilegeDidExpired.bind(this)),null==(_=this._room)||_.on(SignalEvent.ON_TOKEN_SUBSCRIBE_PRIVILEGE_WILL_EXPIRE,this._onUserTokenSubscribePrivilegeWillExpire.bind(this)),null==(h=this._room)||h.on(SignalEvent.ON_TOKEN_SUBSCRIBE_PRIVILEGE_DID_EXPIRED,this._onUserTokenSubscribePrivilegeDidExpired.bind(this)),null==(p=this._room)||p.on(SignalEvent.POST_PROCESSING_MESSAGE,(e=>{var t;"2.0"===(null==(t=e)?void 0:t.protocol)?this._onStreamMixingEvent({error:e.error,event:e.eventType,message:e.message}):"publicStreamCallback"===e.type?this._onPushPublicStreamResult(e):"transcodeStatusCallback"===e.type&&this._onLiveTranscodingResult(e)})),null==(m=this._room)||m.on(StateEvent.ON_VENDOR_CONNECTION_STATE_CHANGE,(e=>this.safeEmit(EngineEventsTypes.onVendorConnectionStateChanged,e))),null==(S=this._room)||S.on(RoomEvent.RESUBSCRIBE,this._onResubscribe.bind(this)),null==(g=this._room)||g.on(RoomEvent.SUBSCRIBE_PUSH_TRACK,this._onSubscribePushTrack.bind(this)),null==(v=this._room)||v.on(RoomEvent.REMOVE_PUSH_TRACK,this._onRemovePushTrack.bind(this)),null==(f=this._room)||f.on(RoomEvent.ON_PUBLISH_RESULT,(e=>{var t,i,r;e.state===PublishState.PUBLISH_SUCC&&(null==(t=this._room)||t.config.setTokenPublishPrivilegeExpired(!1)),e.state===PublishState.PUBLISH_FAIL&&e.errorCode===ErrorCode.TOKEN_NO_PUBLISH_PERMISSION&&(null==(i=this._room)||i.config.setTokenPublishPrivilegeExpired(!0));const o=!(e.retry||!(null==(r=this._room)?void 0:r.config.isAutoPublish));o&&this.safeEmit(EngineEventsTypes.onAutoPublishResult,e),this.safeEmit(EngineEventsTypes.onPublishResult,{isScreen:e.isScreen,isAutoPublish:o,errorCode:e.errorCode})})),null==(E=this._room)||E.on(RoomEvent.ON_SUBSCRIBE_RESULT,(e=>{var t;e.state===SubscribeState.SUBSCRIBE_SUCC&&(null==(t=this._room)||t.config.setTokenSubscribePrivilegeExpired(!1)),e.state===SubscribeState.SUBSCRIBE_FAIL&&e.errorCode===ErrorCode.TOKEN_NO_SUBSCRIBE_PERMISSION&&this._handleLoseSubscribePrivilege(),this.safeEmit(EngineEventsTypes.onSubscribeResult,{userId:e.userId,isScreen:e.isScreen,isAutoSubscribe:!1,errorCode:e.errorCode})})),null==(T=this._room)||T.on(RoomEvent.ON_REMOTE_STREAM_STATS,(e=>{this.safeEmit(EngineEventsTypes.onRemoteStreamStats,e)})),null==(R=this._room)||R.on(RoomEvent.ON_LOCAL_STREAM_STATS,(e=>{this.safeEmit(EngineEventsTypes.onLocalStreamStats,e)})),null==(b=this._room)||b.on(RoomEvent.ON_SUBTITLE_STATE_CHANGED,(e=>{this.safeEmit(EngineEventsTypes.onSubtitleStateChanged,e)})),null==(y=this._room)||y.on(RoomEvent.ON_SUBTITLE_MESSAGE_RECEIVED,(e=>{this.safeEmit(EngineEventsTypes.onSubtitleMessageReceived,e)})),null==(I=this._room)||I.on(RoomEvent.ON_USER_PUBLISH_STATE_CHANGE,this._onUserPublishStateChange.bind(this)),null==(C=this._room)||C.on(RoomEvent.ON_USER_START_AUDIO_CAPTURE,(({userId:e},t)=>{this._updateAudioPlayerState(t),this.safeEmit(EngineEventsTypes.onUserStartAudioCapture,{userId:e})})),null==(A=this._room)||A.on(RoomEvent.ON_USER_STOP_AUDIO_CAPTURE,(({userId:e})=>{this.safeEmit(EngineEventsTypes.onUserStopAudioCapture,{userId:e})})),null==(k=this._room)||k.on(RoomEvent.ON_USER_START_VIDEO_CAPTURE,(({userId:e})=>{this.safeEmit(EngineEventsTypes.onUserStartVideoCapture,{userId:e})})),null==(M=this._room)||M.on(RoomEvent.ON_USER_STOP_VIDEO_CAPTURE,(({userId:e})=>{this.safeEmit(EngineEventsTypes.onUserStopVideoCapture,{userId:e})})),null==(N=this._room)||N.on(RoomEvent.ON_SEI_MESSAGED_RECEIVED,(e=>{this.safeEmit(EngineEventsTypes.onSEIMessageReceived,e)})),null==(O=this._room)||O.on(RoomEvent.ON_REMOTE_VIDEO_SIZE_CHANGED,((e,t)=>{this.safeEmit(EngineEventsTypes.onRemoteVideoSizeChanged,e,t)})),null==(P=this._room)||P.on(RoomEvent.ON_SIMULCAST_SUBSCRIBE_FALLBACK,(e=>this.safeEmit(EngineEventsTypes.onSimulcastSubscribeFallback,e))),null==(D=this._room)||D.on(RoomEvent.ON_VIDEO_STREAM_BANNED,(e=>{this.safeEmit(EngineEventsTypes.onVideoStreamBanned,{uid:e.uid,banned:e.banned})})),null==(w=this._room)||w.on(RoomEvent.ON_AUDIO_STREAM_BANNED,(e=>{this.safeEmit(EngineEventsTypes.onAudioStreamBanned,{uid:e.uid,banned:e.banned})})),null==(L=this._room)||L.on(RoomEvent.ON_FORWARD_STREAM_ERROR,(e=>{this.safeEmit(EngineEventsTypes.onForwardStreamError,e)})),null==(x=this._room)||x.on(RoomEvent.ON_REJOIN_WITH_TCP,(()=>{this.safeEmit(EngineEventsTypes.onRejoinWithTcp)})),null==(F=this._room)||F.on(RoomEvent.PUB_RETRY,(e=>{this.safeEmit(EngineEventsTypes.onPublishRetry,e)})),null==(U=this._room)||U.on(RoomEvent.SUB_RETRY,(e=>{this.safeEmit(EngineEventsTypes.onSubscribeRetry,e)})),null==(V=this._room)||V.on(RoomEvent.VIDEO_TYPE_CHANGE,(e=>{this.safeEmit(EngineEventsTypes.onSEIStreamUpdate,e)})),null==(B=this._room)||B.on(RoomEvent.JOIN_SUCCESS,(e=>{this._ctx.isPreConnection||this.safeEmit(EngineEventsTypes.onConnectionStateChanged,{state:e?ConnectionState.CONNECTION_STATE_RECONNECTED:ConnectionState.CONNECTION_STATE_CONNECTED})})),null==($=this._room)||$.on(RoomEvent.UPDATE_PUBLISH,(({streamIndex:e})=>{e===StreamIndex$1.STREAM_INDEX_MAIN?this._updatePublish():e===StreamIndex$1.STREAM_INDEX_SCREEN&&this._updateScreenPublish()}))}safeEmit(e,...t){if(isReportCallback(e)){if(e===EngineEventsTypes.onRemoteStreamStats){const e=getParameter("UPLOAD_REMOTE_STATS"),i=getParameter("FORCE_ENABLED_REPORT_CALLBACKS").includes("onRemoteStreamStats"),{videoStats:r,audioStats:o,...s}=t[0];t[0]={...s},(e&MediaType$1.VIDEO||i)&&(t[0].videoStats=r),(e&MediaType$1.AUDIO||i)&&(t[0].audioStats=o)}reportRtcSdkCallback(this.id,e,t)}return super.safeEmit(e,...t)}_removeHandlerEventHandler(){var e;null==(e=this._room)||e.removeAllListeners()}async connect(){await this._ctx.signalingManager.connect()}async joinRoom(e,t,i,r){var o,s,n,a,d;if(this.logger.info("joinRoom()","token: %o roomId: %o, userInfo: %o, roomConfig: %o",e,t,i,r),isEmpty(e)||checkString(e,"token"),this._room)throw new SDKError(ErrorCode.REPEAT_JOIN,"Already joined");null==(o=this._ctx.monitor)||o.report("rtc_sdk_api_call",{sdk_api_name:"host",message:location.host,error_code:0}),checkRoomId(t),checkUserInfo(i);const c=new RoomContext({token:e,roomId:t,userInfo:i},this._ctx);return checkRoomConfig(c.updateRoomConfig(r)),c.setLiveControlMessage(this._liveTranscodeConfig&&LiveTranscoding.getStartParams(this._liveTranscodeConfig)),this._room=new Room(c,this._ctx),this.monitor.set({rtc_session_id:this._room.config.sessionId}),this._addHandlerEventHandler(),this._ctx.useCloudProxy&&(this._startCloudProxyTimestamp=Date.now()),null==(s=this._localVideoTrack)||s.setUserId(i.userId),null==(n=this._localScreenVideoTrack)||n.setUserId(i.userId),null==(a=this._localAudioTrack)||a.setUserId(i.userId),null==(d=this._localScreenAudioTrack)||d.setUserId(i.userId),checkSourceLanguage(i),await this._join(this._room)}async _join(e){var t;try{const i=await e.join();return this._waitForNewToken=!1,this._ctx.audioProfileManager.setRoomId(e.config.roomId),(null==(t=this._room)?void 0:t.config.isAutoPublish)&&(this._ctx.visibility?this._updatePublish({invokeByJoinRoom:!0,mediaType:MediaType$1.AUDIO_AND_VIDEO}).catch((e=>{this.logger.error("_join","_updatePublish failed",e)})):(this.safeEmit(EngineEventsTypes.onAutoPublishResult,{isScreen:!1,state:PublishState.PUBLISH_FAIL}),this.safeEmit(EngineEventsTypes.onPublishResult,{isScreen:!1,isAutoPublish:!0,errorCode:ErrorCode.NO_PUBLISH_PERMISSION}))),this.monitor.set({rtc_vid:e.config.rtcVid}),RTSMsgReportor.setRoomId(this.id,e.config.roomId),RTSMsgReportor.setUserId(this.id,e.config.userId),i}catch(t){throw t.code===ErrorCode.INVALID_TOKEN?this._waitForNewToken=!0:(e.destroy(),this._room===e&&delete this._room),t}}async leaveRoom(e=!1){this.logger.info("leaveRoom()");const t=this._room;delete this._room,this._ctx.resetPubSubLock(ResetPubSubLockReason.LEAVE),this._ctx.callId=void 0,e?await(null==t?void 0:t.leave(e)):null==t||t.leave(e).catch(),this._removeHandlerEventHandler(),this._subLocks=new Map,this._subScreenLocks=new Map,this._ctx.audioProfileManager.setRoomId(),this._liveTranscodeConfig&&this.stopLiveTranscoding(),null==t||t.destroy(),this._remoteVideoPlayerConfig[StreamIndex$1.STREAM_INDEX_MAIN].forEach((e=>{e.forEach((e=>{const{player:t,renderDom:i}=e;null==t||t.destroy(),this._containerCollisionDetector.unregisterContainer(i)}))})),this._remoteVideoPlayerConfig[StreamIndex$1.STREAM_INDEX_MAIN].clear(),this._remoteVideoPlayerConfig[StreamIndex$1.STREAM_INDEX_SCREEN].forEach((e=>{e.forEach((e=>{const{player:t,renderDom:i}=e;null==t||t.destroy(),this._containerCollisionDetector.unregisterContainer(i)}))})),this._remoteVideoPlayerConfig[StreamIndex$1.STREAM_INDEX_SCREEN].clear(),this._publicStreamIds=new Map,RTSMsgReportor.setRoomId(this.id,""),RTSMsgReportor.setUserId(this.id,""),this.monitor.set({rtc_session_id:"",rtc_vid:""})}_destroyLocalTrack(){this._localAudioTrack&&(this._removeLocalTrackEvents(this._localAudioTrack),this._localAudioTrack.destroy(),this._localAudioTrack=void 0),this._localVideoTrack&&(this._removeLocalTrackEvents(this._localVideoTrack),this._localVideoTrack.destroy(),this._localVideoTrack=void 0),this._localScreenAudioTrack&&(this._removeLocalTrackEvents(this._localScreenAudioTrack),this._localScreenAudioTrack.destroy(),this._localScreenAudioTrack=void 0),this._localScreenVideoTrack&&(this._removeLocalTrackEvents(this._localScreenVideoTrack),this._localScreenVideoTrack.destroy(),this._localScreenVideoTrack=void 0),this._localImgVideoTrack&&(this._localImgVideoTrack.stop(),this._localImgVideoTrack=void 0),this._localImgScreenTrack&&(this._localImgScreenTrack.stop(),this._localImgScreenTrack=void 0)}destroy(){var e,t,i,r;this.logger.info("destroy()"),this.removeAllListeners(),this._removeHandlerEventHandler(),null==(e=this._removeDeviceEventHandler)||e.call(this),null==(t=this._revokeAutoplayFailedWorkaround)||t.call(this),null==(i=this._room)||i.destroy(),this._room=void 0,this._subLocks=new Map,this._subScreenLocks=new Map,this._audioCaptureLock=new PromiseLock2("audioCap"),this._videoCaptureLock=new PromiseLock2("videoCap"),this._screenCaptureLock=new PromiseLock2("screenCap"),this._pauseAllSubscribeState={audio:void 0,video:void 0,resumeVideoStreamIds:{},resumeAudioStreamIds:{}},this._messageStatisticsObserver.destroy(),this.monitor.destroy(),RTSMsgReportor.destroyRTSMsgReportor(this.id),clearInterval(this._audioVolumeIndicationTimer),clearInterval(this._dummyMainTimer),clearInterval(this._dummyScreenTimer),this._audioVolumeIndicationTimer=void 0,this._stopAudioPropertiesReport(),this._destroyLocalTrack(),null==(r=this._audioMixingManager)||r.destroy(),this._rtmClient.destroy(),this._wtnStreamManager.destroy(),this._publicStreamIds=new Map,this._audioDeviceManager.destroy(),this._ctx.destroy(),this._localAudioVolume=100,this._localScreenAudioVolume=100,this._remoteAudioVolume.clear(),this._remoteScreenAudioVolume.clear(),this._localVideoPlayerConfig[StreamIndex$1.STREAM_INDEX_MAIN].forEach((e=>{e.player.destroy()})),this._localVideoPlayerConfig[StreamIndex$1.STREAM_INDEX_MAIN].clear(),this._localVideoPlayerConfig[StreamIndex$1.STREAM_INDEX_SCREEN].forEach((e=>{e.player.destroy()})),this._localVideoPlayerConfig[StreamIndex$1.STREAM_INDEX_SCREEN].clear(),this._remoteVideoPlayerConfig[StreamIndex$1.STREAM_INDEX_MAIN].forEach((e=>{e.forEach((e=>{e.player.destroy()}))})),this._remoteVideoPlayerConfig[StreamIndex$1.STREAM_INDEX_MAIN].clear(),this._remoteVideoPlayerConfig[StreamIndex$1.STREAM_INDEX_SCREEN].forEach((e=>{e.forEach((e=>{e.player.destroy()}))})),this._remoteVideoPlayerConfig[StreamIndex$1.STREAM_INDEX_SCREEN].clear()}async publishStream(e){this.logger.info("publishStream()","mediaType: %o",e),this._checkMediaType(e),this._assertNotInRoom(),videoInMediaType(e)&&!this._localVideoTrack&&this._localImgVideoTrack&&(this._localVideoTrack=await createDummyVideoLocalTrack(this._ctx,this._localImgVideoTrack)),await this._updatePublish({mediaType:e},!0)}async unpublishStream(e,t){var i;if(this.logger.info("unpublishStream()","mediaType: %o",e),this._checkMediaType(e),this._assertNotInRoom(),t)return null==(i=this._room)?void 0:i.unpublish();await this._updatePublish({mediaType:e,pubState:PubState.UNPUB},!0)}async publishScreen(e){this.logger.info("publishScreen()","mediaType: %o",e),this._checkMediaType(e),this._assertNotInRoom();try{videoInMediaType(e)&&!this._localScreenVideoTrack&&this._localImgScreenTrack&&(this._localScreenVideoTrack=await createDummyScreenVideoLocalTrack(this._ctx,this._localImgScreenTrack)),await this._updateScreenPublish({mediaType:e,pubState:PubState.PUB})}catch(e){throw e instanceof SDKError?e:new SDKError(ErrorCode.UNEXPECTED_ERROR,"unexpected error",e)}}async unpublishScreen(e){this.logger.info("unpublishScreen()","mediaType: %o",e),this._checkMediaType(e),this._assertNotInRoom(),await this._updateScreenPublish({mediaType:e,pubState:PubState.UNPUB})}async subscribeStream(e,t){return this.logger.info("subscribeStream()","userId: %o, mediaType: %o",e,t),this._subscribe(!1,e,t)}async _subscribe(e,t,i){var r,o,s,n,a,d;const c=i;if(i===MediaType$1.AUDIO&&(null==(r=this._room)?void 0:r.config.isMultiChatMode()))return void this.logger.warn("subscribeStream()","due to multiChatMode return");const l=this._room.remoteStreams.get(t),u=null==l?void 0:l.find((t=>t.isScreen===e));if(!u)throw new SDKError(ErrorCode.STREAM_NOT_EXIST,"stream not exist");const _=this._pauseAllSubscribeState.audio,h=this._pauseAllSubscribeState.video;this._pauseAllSubscribeState.audio&&(i-=i&MediaType$1.AUDIO),this._pauseAllSubscribeState.video&&(i-=i&MediaType$1.VIDEO),this.logger.warn("subscribeStream()","due to pauseAll mediaType: %o",i);const{hasSubscribed:p}=u;u.originalMediaType=i;try{await this._room.subscribe(u,i),audioInMediaType(i)&&this._updateAudioPlayerState(u),videoInMediaType(i)&&this._updateVideoPlayerState(u);let r=0,l=0;if(_!==this._pauseAllSubscribeState.audio&&(this._pauseAllSubscribeState.audio?r|=MediaType$1.AUDIO:l|=MediaType$1.AUDIO),h!==this._pauseAllSubscribeState.video&&(this._pauseAllSubscribeState.video?r|=MediaType$1.VIDEO:l|=MediaType$1.VIDEO),r&&this.pauseAllSubscribedStream(r),l&&this.resumeAllSubscribedStream(l),audioInMediaType(c)&&(this._pauseAllSubscribeState.resumeAudioStreamIds[u.streamId]=u.streamId),videoInMediaType(c)&&(this._pauseAllSubscribeState.resumeVideoStreamIds[u.streamId]=u.streamId),u.audioTrack||u.videoTrack){const i=!(e||!(null==(o=this._room)?void 0:o.config.isAutoSubscribeAudio)&&!(null==(s=this._room)?void 0:s.config.isAutoSubscribeVideo)),r={userId:t,isScreen:!1,state:SubscribeState.SUBSCRIBE_SUCC};i&&this.safeEmit(EngineEventsTypes.onAutoSubscribeResult,r),this.safeEmit(EngineEventsTypes.onSubscribeResult,{userId:t,isScreen:e,isAutoSubscribe:i})}!(null==(n=this._room)?void 0:n.config.isMultiChatMode())&&!p&&audioInMediaType(i)&&u.hasAudio&&(null==(a=u.observer)||a.setSubscribeAudio(!0)),!p&&videoInMediaType(i)&&u.hasVideo&&(null==(d=u.observer)||d.setSubscribeVideo(!0))}catch(e){throw e instanceof SDKError&&e.code===ErrorCode.TOKEN_NO_SUBSCRIBE_PERMISSION&&this._handleLoseSubscribePrivilege(),e}}async _handleLoseSubscribePrivilege(){var e;null==(e=this._room)||e.config.setTokenSubscribePrivilegeExpired(!0);try{await this._unSubscribeAllRemoteStreams()}catch(e){}}async unsubscribeStream(e,t){return this.logger.info("unsubscribeStream()","userId: %o, mediaType: %o",e,t),this._unsubscribe(!1,e,t)}async subscribeScreen(e,t){return this.logger.info("subscribeScreen() userId: %o, mediaType: %o",e,t),this._subscribe(!0,e,t)}async unsubscribeScreen(e,t){return this.logger.info("unsubscribeScreen() userId: %o, mediaType: %o",e,t),this._unsubscribe(!0,e,t)}_unsubscribe(e,t,i,r){var o,s;if(i===MediaType$1.AUDIO&&(null==(o=this._room)?void 0:o.config.isMultiChatMode()))return void this.logger.warn("subscribeStream()","due to multiChatMode return");const n=this._room.remoteStreams.get(t),a=null==n?void 0:n.find((t=>t.isScreen===e));if(!a)throw new SDKError(ErrorCode.STREAM_NOT_EXIST,"stream not exist");return isAndroid&&chromeVersion&&chromeVersion>=85&&chromeVersion<=91&&i!==MediaType$1.AUDIO&&(null==(s=a.videoTrack)||s.stopAll()),this._room.unsubscribe(a,i).then((()=>{r||(audioInMediaType(i)&&delete this._pauseAllSubscribeState.resumeAudioStreamIds[a.streamId],videoInMediaType(i)&&delete this._pauseAllSubscribeState.resumeVideoStreamIds[a.streamId])}))}async setRemoteVideoConfig(e,t){var i;return this.logger.info("setRemoteVideoConfig() userId: %o, remoteVideoConfig: %o",e,t),this._ctx.videoProfile.checkSimulcastApiVersion("old"),checkUserId(e),checkRemoteConfig(t),this._ctx.videoProfile.setRemoteUserVideoConfig(e,t),null==(i=this._room)?void 0:i.updateSubVideoConfig(e).then((()=>{}))}async setRemoteSimulcastStreamType(e,t){var i;this.logger.info("setRemoteSimulcastStreamType()","userId: %s, streamType: %s",e,t),this._ctx.videoProfile.checkSimulcastApiVersion("new"),checkUserId(e),checkEnum(t,"SimulcastStreamType",[SimulcastStreamType.VIDEO_STREAM_HIGH,SimulcastStreamType.VIDEO_STREAM_MID,SimulcastStreamType.VIDEO_STREAM_LOW]),this._ctx.videoProfile.setRemoteUserVideoConfig(e,t),await(null==(i=this._room)?void 0:i.updateSubVideoConfig(e))}async startVideoCapture(e){var t,i,r;if(this.logger.info("startVideoCapture()","deviceId: %s",e),isEmpty(e)||checkString(e,"deviceId"),e&&this._ctx.videoProfile.setCaptureDeviceId(e),this._trackSourceType.video===VideoSourceType.VIDEO_SOURCE_TYPE_EXTERNAL)throw new SDKError(ErrorCode.STREAM_TYPE_NOT_MATCH,"setVideoSourceType as internal first");if(this._localVideoTrack&&!this._localVideoTrack.dummy)throw new SDKError(ErrorCode.REPEAT_CAPTURE,"Has already capture");let o={};const s=await createCameraVideoTrack(this._ctx),n=this._ctx.videoProfile.getContentHint();n&&s.setContentHint(n),this._initLocalTrackEvents(s),this._localVideoTrack=s;this._localVideoPlayerConfig[StreamIndex$1.STREAM_INDEX_MAIN].forEach((e=>{var t,i;null==(i=this._localVideoTrack)||i.setPlayer(e,this._mirrorType,null==(t=this._config)?void 0:t.autoPlayPolicy,this._initPlayerEvents.bind(this))}));o=s.originTrack.getSettings();const a={width:o.width,height:o.height};if(this._localVideoTrack.resolution=a,this._ctx.videoProfile.__autoResetVideoEncoderConfig(o),setTimeout((()=>this.safeEmit(EngineEventsTypes.onLocalVideoSizeChanged,{streamIndex:StreamIndex$1.STREAM_INDEX_MAIN,info:a}))),this._ctx.engineDestroyed)return this._destroyLocalTrack(),o;if(this._wtnStreamManager._updatePushTrack(),!this._room)return o;const{isAutoPublish:d}=this._room.config;return((null==(t=this._room.localStream)?void 0:t.pubVideo)||d)&&this._ctx.visibility&&this._updatePublish(),null==(r=null==(i=this._room.localStream)?void 0:i.observer)||r.setEnableVideo(!0),o}async getLocalStreamStats(){var e;return await(null==(e=this._room)?void 0:e.getLocalStreamStats())}async stopVideoCapture(){var e,t,i;if(this.logger.info("stopVideoCapture()"),this._trackSourceType.video===VideoSourceType.VIDEO_SOURCE_TYPE_EXTERNAL)throw new SDKError(ErrorCode.STREAM_TYPE_NOT_MATCH,"setVideoSourceType as internal first");if(this._localVideoTrack&&!this._localVideoTrack.dummy){const e=this._ctx.extensionManager.getPluginByName(RTCExtensionType.PRE_PROCESSING,"RTCBeautyExtension");e&&e.emit("stop"),this._removeLocalTrackEvents(this._localVideoTrack),this._localVideoTrack.destroy(),this._localImgVideoTrack?this._localVideoTrack.setTrack(this._localImgVideoTrack,{isDummy:!0}):this._localVideoTrack=void 0}this._wtnStreamManager._updatePushTrack(),this._room&&((null==(e=this._room.localStream)?void 0:e.pubVideo)&&await this._updatePublish(),null==(i=null==(t=this._room.localStream)?void 0:t.observer)||i.setEnableVideo(!1))}async startAudioCapture(e){var t,i,r;if(this.logger.info("startAudioCapture()","deviceId: $o",e),isEmpty(e)||checkString(e,"deviceId"),e&&this._ctx.audioProfileManager.updateConstraints({deviceId:{exact:e}}),this._trackSourceType.audio===AudioSourceType.AUDIO_SOURCE_TYPE_EXTERNAL)throw new SDKError(ErrorCode.STREAM_TYPE_NOT_MATCH,"setAudioSourceType as internal first");if(this._localAudioTrack)throw new SDKError(ErrorCode.REPEAT_CAPTURE,"Has already capture");let o={};const s=await createMicrophoneAudioTrack(this._ctx,this._ctx.audioProfileManager.getConstraints());o=s.originTrack.getSettings(),this._initLocalTrackEvents(s),this._localAudioTrack=s,this._localAudioTrack.setVolume(this._localAudioVolume);const{frameSize:n,callback:a}=this._ctx._localAudioTrackDumpConfig[StreamIndex$1.STREAM_INDEX_MAIN];n&&a&&this._localAudioTrack.setDataFetcher(n,a);const{position:d,volume:c}=this._ctx.earMonitorSettings[StreamIndex$1.STREAM_INDEX_MAIN];if(d!==EarMonitorPosition.NONE&&(this._localAudioTrack.play(d),this._localAudioTrack.setPlaybackVolume(c)),this._tempMixingAudioTrack&&(this._localAudioTrack.mixType=this._tempMixingAudioTrack.type,this._localAudioTrack.mixedAudioTrack=this._tempMixingAudioTrack.track,delete this._tempMixingAudioTrack),this._ctx.engineDestroyed)return this._destroyLocalTrack(),o;if(this._wtnStreamManager._updatePushTrack(),!this._room)return o;const{isAutoPublish:l}=this._room.config;return((null==(t=this._room.localStream)?void 0:t.pubAudio)||l)&&this._ctx.visibility&&this._updatePublish(),null==(r=null==(i=this._room.localStream)?void 0:i.observer)||r.setEnableAudio(!0),o}async stopAudioCapture(){var e,t,i,r;if(this.logger.info("stopAudioCapture()"),this._trackSourceType.audio===AudioSourceType.AUDIO_SOURCE_TYPE_EXTERNAL)throw new SDKError(ErrorCode.STREAM_TYPE_NOT_MATCH,"setAudioSourceType as internal first");this._localAudioTrack&&(this._removeLocalTrackEvents(this._localAudioTrack),this._localAudioTrack.destroy()),this._localAudioTrack=void 0,null==(e=this._audioMixingManager)||e.stopAll(),this._wtnStreamManager._updatePushTrack(),this._room&&((null==(t=this._room.localStream)?void 0:t.pubAudio)&&await this._updatePublish(),null==(r=null==(i=this._room.localStream)?void 0:i.observer)||r.setEnableAudio(!1))}async startAudioAndVideoCapture(e,t){var i,r,o,s,n,a;this.logger.print("startAudioAndVideoCapture","optionsOrAudioDeviceId: $o",e,"videoDeviceId: $o",t);const{audioDeviceId:d,videoDeviceId:c}=checkAudioAndVideoDeviceId(e,t);if(d&&this._ctx.audioProfileManager.updateConstraints({deviceId:{exact:d}}),this._trackSourceType.video===VideoSourceType.VIDEO_SOURCE_TYPE_EXTERNAL||this._trackSourceType.audio===AudioSourceType.AUDIO_SOURCE_TYPE_EXTERNAL)throw new SDKError(ErrorCode.STREAM_TYPE_NOT_MATCH,this._trackSourceType.video===VideoSourceType.VIDEO_SOURCE_TYPE_EXTERNAL?"setVideoSourceType as internal first":"setAudioSourceType as internal first");if(this._localVideoTrack&&!this._localVideoTrack.dummy)throw new SDKError(ErrorCode.REPEAT_CAPTURE,"video has already capture");if(this._localAudioTrack)throw new SDKError(ErrorCode.REPEAT_CAPTURE,"audio has already capture");const l=this._ctx.videoProfile.getCaptureConfig(c);let u={},_={};const{audioTrack:h,videoTrack:p}=await createMicrophoneAndCameraTrack(this._ctx,this._ctx.audioProfileManager.getConstraints(),l),m=this._ctx.videoProfile.getContentHint();m&&p.setContentHint(m),c&&this._ctx.videoProfile.setCaptureDeviceId(c),this._initLocalTrackEvents(p),this._localVideoTrack=p;this._localVideoPlayerConfig[StreamIndex$1.STREAM_INDEX_MAIN].forEach((e=>{var t,i;null==(i=this._localVideoTrack)||i.setPlayer(e,this._mirrorType,null==(t=this._config)?void 0:t.autoPlayPolicy,this._initPlayerEvents.bind(this))})),this._initLocalTrackEvents(h),this._localAudioTrack=h,this._localAudioTrack.setVolume(this._localAudioVolume);const{frameSize:S,callback:g}=this._ctx._localAudioTrackDumpConfig[StreamIndex$1.STREAM_INDEX_MAIN];S&&g&&this._localAudioTrack.setDataFetcher(S,g),this._tempMixingAudioTrack&&(this._localAudioTrack.mixType=this._tempMixingAudioTrack.type,this._localAudioTrack.mixedAudioTrack=this._tempMixingAudioTrack.track,delete this._tempMixingAudioTrack);let v=p.originTrack;u=v.getSettings();const f={width:u.width||0,height:u.height||0};if(this._localVideoTrack.resolution=f,this._ctx.videoProfile.__autoResetVideoEncoderConfig(u),setTimeout((()=>this.safeEmit(EngineEventsTypes.onLocalVideoSizeChanged,{streamIndex:StreamIndex$1.STREAM_INDEX_MAIN,info:f}))),v=h.originTrack,_=v.getSettings(),this._ctx.engineDestroyed)return this._destroyLocalTrack(),{audioTrackSettings:_,videoTrackSettings:u};if(this._wtnStreamManager._updatePushTrack(),!this._room)return{audioTrackSettings:_,videoTrackSettings:u};const{isAutoPublish:E}=this._room.config;return((null==(i=this._room.localStream)?void 0:i.pubVideo)||(null==(r=this._room.localStream)?void 0:r.pubAudio)||E)&&this._ctx.visibility&&this._updatePublish(),null==(s=null==(o=this._room.localStream)?void 0:o.observer)||s.setEnableVideo(!0),null==(a=null==(n=this._room.localStream)?void 0:n.observer)||a.setEnableAudio(!0),{audioTrackSettings:_,videoTrackSettings:u}}async startVideoAndAudioCapture(e,t){return this.startAudioAndVideoCapture(t,e)}getAudioMixingManager(){return this.logger.info("getAudioMixingManager()","invoke"),this._audioMixingManager||(this._audioMixingManager=new AudioMixingManager({getLocalAudioTrack:()=>this._localAudioTrack,updateLocalAudioTrack:this._updateMixAudioTrack,emitMessage:this._onAudioMixingMessage,onAutoPlayFailed:this._onAudioMixingAutoplayFailed},this.id)),this._audioMixingManager}getWTNStreamManager(){return this._wtnStreamManager}getCallId(){var e;return null==(e=this._ctx)?void 0:e.callId}async startScreenCapture(e={}){var t,i,r,o,s;if(this.logger.info("startScreenCapture()","config: %o",e),this._trackSourceType.screenVideo===VideoSourceType.VIDEO_SOURCE_TYPE_EXTERNAL)throw new SDKError(ErrorCode.STREAM_TYPE_NOT_MATCH,"setVideoSourceType as internal first");if(this._trackSourceType.screenAudio===AudioSourceType.AUDIO_SOURCE_TYPE_EXTERNAL)throw new SDKError(ErrorCode.STREAM_TYPE_NOT_MATCH,"setAudioSourceType as internal first");const[n,a]=await createScreenTracks(this._ctx,e);null==a||a.setVolume(this._localScreenAudioVolume),this._localScreenVideoTrack&&!this._localScreenVideoTrack.dummy&&(this._removeLocalTrackEvents(this._localScreenVideoTrack),this._localScreenVideoTrack.destroy()),null==(t=this._localScreenAudioTrack)||t.destroy(),delete this._localScreenAudioTrack,this._localScreenVideoTrack=n;const{contentHint:d}=this._ctx.videoProfile.getScreenEncodeConfig();d&&n.setContentHint(d);const c=n.originTrack;setTimeout((()=>{const e=c.getSettings(),t={width:e.width,height:e.height};n.resolution=t,this.safeEmit(EngineEventsTypes.onLocalVideoSizeChanged,{streamIndex:StreamIndex$1.STREAM_INDEX_SCREEN,info:{width:e.width,height:e.height}})}),500),a&&(this._localScreenAudioTrack=a,this._initLocalTrackEvents(a));this._localVideoPlayerConfig[StreamIndex$1.STREAM_INDEX_SCREEN].forEach((e=>{var t,i;null==(i=this._localScreenVideoTrack)||i.setPlayer(e,MirrorType.MIRROR_TYPE_NONE,null==(t=this._config)?void 0:t.autoPlayPolicy,this._initPlayerEvents.bind(this))})),this._initLocalTrackEvents(this._localScreenVideoTrack,!0),((null==(r=null==(i=this._room)?void 0:i.localScreenStream)?void 0:r.pubAudio)||(null==(s=null==(o=this._room)?void 0:o.localScreenStream)?void 0:s.pubVideo))&&await this._updateScreenPublish()}async stopScreenCapture(){var e,t,i,r,o,s;this.logger.info("stopScreenCapture()"),null==(e=this._localScreenVideoTrack)||e.stopAll(),this._localScreenVideoTrack&&(this._localScreenVideoTrack.dummy||(this._removeLocalTrackEvents(this._localScreenVideoTrack),this._localScreenVideoTrack.destroy(),this._localImgScreenTrack&&this._localScreenVideoTrack.setTrack(this._localImgScreenTrack,{isDummy:!0}))),this._localScreenAudioTrack&&(this._removeLocalTrackEvents(this._localScreenAudioTrack),this._localScreenAudioTrack.destroy()),this._localScreenAudioTrack=void 0,(null==(t=this._localScreenVideoTrack)?void 0:t.dummy)||(this._localScreenVideoTrack=void 0),((null==(r=null==(i=this._room)?void 0:i.localScreenStream)?void 0:r.pubAudio)||(null==(s=null==(o=this._room)?void 0:o.localScreenStream)?void 0:s.pubVideo))&&await this._updateScreenPublish()}setLocalVideoPlayer(e,t){var i,r,o,s,n;this.logger.info("setLocalVideoPlayer()","streamIndex: %o, videoPlayerOption: %o",e,t),checkEnum(e,"streamIndex",[StreamIndex$1.STREAM_INDEX_MAIN,StreamIndex$1.STREAM_INDEX_SCREEN]);const a=e===StreamIndex$1.STREAM_INDEX_MAIN?this._localVideoTrack:this._localScreenVideoTrack,d=(null==t?void 0:t.playerId)??DEFAULT_PLAYER_ID;if(!(null==t?void 0:t.renderDom)){null==(r=null==(i=this._localVideoPlayerConfig[e].get(d))?void 0:i.player)||r.destroy(),null==a||a.removePlayer(d);const t=null==(o=this._localVideoPlayerConfig[e].get(d))?void 0:o.renderDom;return this._containerCollisionDetector.unregisterContainer(t),void this._localVideoPlayerConfig[e].delete(d)}checkVideoPlayerOption(t);const c=this._localVideoPlayerConfig[e].get(d);if(!c){const{renderDom:i}=t;if(!this._containerCollisionDetector.registerContainer(i))return this.monitor.report("rtc_error",{message:"RenderDom is not empty",error_code:RtcErrorCode.DUPLICATE_DOM}),void warnDevelopers("renderDom is not empty");const r=new VideoPlayer(this._ctx.id,d,{...t,isLocal:!0,isScreen:e===StreamIndex$1.STREAM_INDEX_SCREEN,userId:t.userId??"_local_"}),o={...t,player:r};return this._localVideoPlayerConfig[e].set(d,o),null==a||a.setPlayer(o,e===StreamIndex$1.STREAM_INDEX_MAIN?this._mirrorType:MirrorType.MIRROR_TYPE_NONE,null==(s=this._config)?void 0:s.autoPlayPolicy,this._initPlayerEvents.bind(this)),null==(n=o.player)?void 0:n.domElement}void 0!==t.renderMode&&(null==a||a.setRenderMode(d,t.renderMode),c.renderMode=t.renderMode)}async startLiveTranscoding(e){var t;this.logger.info("startLiveTranscoding()","transcode: %o",e),LiveTranscoding.checkStartParams(e),this._liveTranscodeConfig=e;const i=null==(t=this._room)?void 0:t.config;if(i&&i.roomId.length+i.userId.length>126)throw new SDKError(ErrorCode.INVALID_PARAMS,"The roomId+userId must be within 126 bytes");try{this.safeEmit(EngineEventsTypes.onStreamMixingEvent,{event:StreamMixingEventType.START,error:0,message:""}),this._room&&this._ctx.signalingManager.isConnected()&&await this._room.liveControlMessage(LiveTranscoding.getStartParams(this._liveTranscodeConfig))}catch(e){throw e instanceof SDKError?e:new SDKError(ErrorCode.UNEXPECTED_ERROR,"unexpected error",e)}}async updateLiveTranscoding(e){var t,i,r;if(this.logger.info("updateLiveTranscoding()","transcode: %o",e),!this._liveTranscodeConfig)return;const o=assignIn({},e);delete o.audio,null==(t=o.video)||delete t.codec,null==(i=o.video)||delete i.gop,LiveTranscoding.checkUpdateParams(o),this._liveTranscodeConfig=assignIn(this._liveTranscodeConfig,o);try{this.safeEmit(EngineEventsTypes.onStreamMixingEvent,{event:StreamMixingEventType.UPDATE,error:0,message:""}),await(null==(r=this._room)?void 0:r.liveControlMessage(LiveTranscoding.getUpdateParams(this._liveTranscodeConfig)))}catch(e){throw e instanceof SDKError?e:new SDKError(ErrorCode.UNEXPECTED_ERROR,"unexpected error",e)}}async stopLiveTranscoding(){var e;if(this.logger.info("stopLiveTranscoding()"),this._liveTranscodeConfig){delete this._liveTranscodeConfig;try{this.safeEmit(EngineEventsTypes.onStreamMixingEvent,{event:StreamMixingEventType.STOP,error:0,message:""}),await(null==(e=this._room)?void 0:e.liveControlMessage({action:"stopped",type:"transcode"}))}catch(e){throw e instanceof SDKError?e:new SDKError(ErrorCode.UNEXPECTED_ERROR,"unexpected error",e)}}}async startSubtitle(e){var t;this.logger.info("startSubtitle()","config: %o",e),this._assertNotInRoom(),await(null==(t=this._room)?void 0:t.startSubtitle(e))}async updateSubtitleConfig(e){var t;this.logger.info("updateSubtitleConfig()","config: %o",e),this._assertNotInRoom(),await(null==(t=this._room)?void 0:t.updateSubtitleConfig(e))}stopSubtitle(){var e;this.logger.info("stopSubtitle()","invoke"),null==(e=this._room)||e.stopSubtitle()}setBusinessId(e){return this.logger.info("setBusinessId()","businessId: %s",e),!illegalBusinessId(e)&&!this._room&&(this._ctx.businessId=e,!0)}async setUserVisibility(e){var t,i;if(this.logger.info("setUserVisibility()","enable: %o",e),e=!!e,this._ctx.visibility!==e)if(this._room){if(this._assertNotInRoom(),this._room.localStream&&(null==(t=this._room.localStream.observer)||t.setPublisher(e)),!e){const e=await this._pubLock.lock();try{this._room.unpublish(),this._room.unpublishScreen()}finally{e()}}this._ctx.visibility=e;try{await this._room.updateUserAttributes()}catch(t){throw this._ctx.visibility=!e,t}e&&(null==(i=this._room)?void 0:i.config.isAutoPublish)&&this._updatePublish({mediaType:MediaType$1.AUDIO_AND_VIDEO})}else this._ctx.visibility=e}_initPlayerEvents(e,t=!1,i=StreamIndex$1.STREAM_INDEX_MAIN){const r=i===StreamIndex$1.STREAM_INDEX_SCREEN;e.on("playback_event",(i=>{var o,s,n,a,d,c;switch(i.eventName){case"timeupdate":if(!e.hasStartPlaying&&e instanceof AudioPlayer){e.hasStartPlaying=!0;const t=e.userId.replace("_screen",""),i=null==(s=null==(o=this._room)?void 0:o.remoteStreams.get(t))?void 0:s.find((e=>e.isScreen===r));setTimeout((()=>{var e,t;const o={is_screen:r,media_type:"audio",codec:null==(t=null==(e=null==i?void 0:i.getRemoteStreamStats())?void 0:e.audioStats)?void 0:t.codecType};this.logger.info("remote_audio_playing",JSON.stringify(o)),this.monitor.report("remote_audio_playing",o)}),8e3)}return;case"loadeddata":if("audio"===i.type){const i=e.userId.replace("_screen",""),o=null==(a=null==(n=this._room)?void 0:n.remoteStreams.get(i))?void 0:a.find((e=>e.isScreen===r)),s=()=>{t?this.safeEmit(EngineEventsTypes.onFirstPublicStreamAudioFrameDecoded,{publicStreamId:i}):(this.safeEmit(EngineEventsTypes.onAudioFirstFrameDecoded,{userId:i,isScreen:r}),this.safeEmit(EngineEventsTypes.onRemoteAudioFirstFrame,{userId:i,isScreen:r})),this.monitor.report("first_remote_audio_render",{stream_id:"",stream_user_id:i||""},{isScreen:r})};!(null==o?void 0:o.observer)||o.observer.audioFirstFrameReceived?s():o.observer.once("recvAudioFirstFrame",s)}else{const o={userId:e.userId,height:e.videoHeight||0,width:e.videoWidth||0,isScreen:r,playerId:e.playerId};t?(o.publicStreamId=o.userId,delete o.userId,delete o.isScreen,this.safeEmit(EngineEventsTypes.onFirstPublicStreamVideoFrameRendered,o),this.safeEmit(EngineEventsTypes.onFirstPublicStreamVideoFrameDecoded,o)):e.isLocal||(this.safeEmit(EngineEventsTypes.onVideoFirstFrameRendered,o),this.safeEmit(EngineEventsTypes.onVideoFirstFrameDecoded,o),this.safeEmit(EngineEventsTypes.onRemoteVideoFirstFrame,o)),this.monitor.report("first_remote_video_render",{stream_id:"",stream_user_id:i.userId||""},{isScreen:r})}break;case"autoplay-error":{t&&(i.publicStreamId=i.userId),reportRtcInvokeStatus(this.id,"autoplay-error",e instanceof VideoPlayer?"video":"audio",0,i.userId||"");const r={userId:i.userId,kind:e instanceof VideoPlayer?"video":"audio",mediaType:e instanceof VideoPlayer?MediaType$1.VIDEO:MediaType$1.AUDIO,streamIndex:e.isScreen?StreamIndex$1.STREAM_INDEX_SCREEN:StreamIndex$1.STREAM_INDEX_MAIN};return e instanceof VideoPlayer&&(r.playerId=e.playerId===DEFAULT_PLAYER_ID?void 0:e.playerId),void this.safeEmit(EngineEventsTypes.onAutoplayFailed,r)}case"playing":{const t=e.userId.replace("_screen",""),o=null==(c=null==(d=this._room)?void 0:d.remoteStreams.get(t))?void 0:c.find((e=>e.isScreen===r));"video"===i.type&&setTimeout((()=>{var e,t,i,s,n,a,d,c,l,u,_,h,p,m,S,g,v,f,E;const T={is_screen:r,media_type:"video",codec:null==(t=null==(e=null==o?void 0:o.getRemoteStreamStats())?void 0:e.videoStats)?void 0:t.codecType,stats_frame_size_width:null==(s=null==(i=null==o?void 0:o.getRemoteStreamStats())?void 0:i.videoStats)?void 0:s.frameSizeWidth,stats_frame_size_height:null==(a=null==(n=null==o?void 0:o.getRemoteStreamStats())?void 0:n.videoStats)?void 0:a.frameSizeHeight,stats_frame_rate_decode:null==(c=null==(d=null==o?void 0:o.getRemoteStreamStats())?void 0:d.videoStats)?void 0:c.decoderOutputFrameRate,stats_frame_rate_receive:null==(u=null==(l=null==o?void 0:o.getRemoteStreamStats())?void 0:l.videoStats)?void 0:u.receivedFrameRate,stats_frame_decoder_name:null==(h=null==(_=null==o?void 0:o.getRemoteStreamStats())?void 0:_.videoStats)?void 0:h.decoderName,stats_gpu_url:Config2.GPU_URL||(null==(p=getGpuInfo())?void 0:p.renderer),track_frame_size_width:null==(S=null==(m=null==o?void 0:o.videoTrack)?void 0:m.originTrack)?void 0:S.getSettings().width,track_frame_size_height:null==(v=null==(g=null==o?void 0:o.videoTrack)?void 0:g.originTrack)?void 0:v.getSettings().height,track_frame_rate:null==(E=null==(f=null==o?void 0:o.videoTrack)?void 0:f.originTrack)?void 0:E.getSettings().frameRate};this.logger.info("remote_video_playing",JSON.stringify(T)),this.monitor.report("remote_video_playing",T)}),8e3);break}}e instanceof VideoPlayer&&(i.playerId=e.playerId===DEFAULT_PLAYER_ID?void 0:e.playerId),this.safeEmit(EngineEventsTypes.onPlayerEvent,i)}))}_initLocalTrackEvents(e,t=!1){["track-ended","track-mute","track-unmute"].forEach((t=>{e.on(t,(async e=>{this.monitor.report("rtc_error",{message:`track-${t} mediaType: ${e.originTrack.kind}`,error_code:RtcErrorCode.TRACK_ERROR,capture_session_id:e.captureSessionId,media_type:t,reason:t});let i=!1;e!==this._localScreenAudioTrack&&e!==this._localScreenVideoTrack||(i=!0);const{kind:r}=e.originTrack,o=e.sourceType;this.safeEmit({"track-ended":EngineEventsTypes.onTrackEnded,"track-mute":EngineEventsTypes.onTrackMute,"track-unmute":EngineEventsTypes.onTrackUnmute}[t],{kind:r,isScreen:i}),Config2.DISABLE_IOS_MUTE_WORKAROUND||!isIOS&&!isIPad||("track-mute"===t&&(internalEventBus.emit(InternalEvent.ON_IOS_LOCAL_TRACK_MUTE,r),"audio"===r&&o===SourceType.INTERNAL&&(await this.stopAudioCapture(),this.startAudioCapture())),"track-unmute"===t&&internalEventBus.emit(InternalEvent.ON_IOS_LOCAL_TRACK_UNMUTE,r))}))})),e.on("resolution-change",(e=>{this._ctx.extensionManager.getPluginsByType(RTCExtensionType.PRE_PROCESSING).forEach((i=>{var r;null==(r=null==i?void 0:i.applyConstraints)||r.call(i,t?StreamIndex$1.STREAM_INDEX_SCREEN:StreamIndex$1.STREAM_INDEX_MAIN,e)})),this.safeEmit(EngineEventsTypes.onLocalVideoSizeChanged,{streamIndex:t?StreamIndex$1.STREAM_INDEX_SCREEN:StreamIndex$1.STREAM_INDEX_MAIN,info:e})})),e.on("needReplaceTrack",(()=>{var t,i;if(e instanceof LocalAudioTrack){e.stopDataFetcher();const r=this._ctx._localAudioTrackDumpConfig[e.streamIndex??StreamIndex$1.STREAM_INDEX_MAIN];(null==r?void 0:r.frameSize)&&(null==r?void 0:r.callback)&&e.setDataFetcher(r.frameSize,r.callback);const{position:o,volume:s}=this._ctx.earMonitorSettings[e.streamIndex??StreamIndex$1.STREAM_INDEX_MAIN];if(o!==EarMonitorPosition.NONE&&(e.play(o),e.setPlaybackVolume(s)),this._room){const{streamIndex:r}=e;r===StreamIndex$1.STREAM_INDEX_MAIN?(null==(t=this._room.localStream)?void 0:t.pubAudio)&&this._ctx.visibility&&this._updatePublish():(null==(i=this._room.localStream)?void 0:i.pubAudio)&&this._ctx.visibility&&this._updateScreenPublish()}}})),e.on("autoplay-error",(e=>{this.safeEmit(EngineEventsTypes.onAutoplayFailed,e)}))}_removeLocalTrackEvents(e){e.removeAllListeners("track-ended"),e.removeAllListeners("track-mute"),e.removeAllListeners("track-unmute"),e.removeAllListeners("resolution-change")}setRemoteVideoPlayer(e,t){var i,r,o,s,n,a,d,c;this.logger.info("setRemoteVideoPlayer()","streamIndex: %o, videoPlayerOption: %o",e,t),checkEnum(e,"streamIndex",[StreamIndex$1.STREAM_INDEX_MAIN,StreamIndex$1.STREAM_INDEX_SCREEN]),checkVideoPlayerOption(t);const{userId:l}=t,u=e===StreamIndex$1.STREAM_INDEX_SCREEN,_=null==(r=null==(i=this._room)?void 0:i.remoteStreams.get(l))?void 0:r.find((e=>e.isScreen===u)),h=null==_?void 0:_.videoTrack,p=t.playerId??DEFAULT_PLAYER_ID;null==(s=null==(o=this._getRemoteVideoPlayerConfig(e,l,p))?void 0:o.player)||s.destroy();const m=null==(n=this._getRemoteVideoPlayerConfig(e,l,p))?void 0:n.renderDom;if(this._containerCollisionDetector.unregisterContainer(m),!t.renderDom)return null==(a=this._remoteVideoPlayerConfig[e].get(l))||a.delete(p),void(null==h||h.removePlayer(p));const{renderDom:S}=t;if(!this._containerCollisionDetector.registerContainer(S))return this.monitor.report("rtc_error",{message:"RenderDom is not empty",error_code:RtcErrorCode.DUPLICATE_DOM}),void warnDevelopers("renderDom is not empty");const g=new VideoPlayer(this.id,p,{...t,isLocal:!1,isScreen:u,userId:l,alphaInfo:null==_?void 0:_.attributes.alphaInfo}),v={...t,player:g};return this._setRemoteVideoPlayerConfig(e,l,p,v),null==h||h.setPlayer(this.id,v,null==(d=this._config)?void 0:d.autoPlayPolicy,this._initPlayerEvents.bind(this)),_&&this._updateVideoPlayerState(_),null==(c=v.player)?void 0:c.domElement}setLocalVideoMirrorType(e){var t;this.logger.info("setLocalVideoMirrorType()","mirrorType: %o",e),checkEnum(e,"mirrorType",[MirrorType.MIRROR_TYPE_NONE,MirrorType.MIRROR_TYPE_RENDER]),this._mirrorType=e,null==(t=this.localVideoTrack)||t.mirror(!!e)}setRemoteVideoMirrorType(e,t,i){var r,o,s,n;this.logger.info("setRemoteVideoMirrorType()","userId: %s, streamIndex: %o, mirrorType: %o",e,t,i),checkUserId(e),checkEnum(t,"streamIndex",[StreamIndex$1.STREAM_INDEX_MAIN,StreamIndex$1.STREAM_INDEX_SCREEN]),checkEnum(i,"mirrorType",[MirrorType.MIRROR_TYPE_NONE,MirrorType.MIRROR_TYPE_RENDER]),this._ctx.setUserStreamConf(e,t,{mirrorType:i}),null==(n=null==(s=null==(o=null==(r=this._room)?void 0:r.remoteStreams.get(e))?void 0:o.find((e=>e.isScreen===(t===StreamIndex$1.STREAM_INDEX_SCREEN))))?void 0:s.videoTrack)||n.mirror(!!i)}async setAudioPlaybackDevice(e){var t;this.logger.info("setAudioPlaybackDevice()","deviceId: %s",e),checkString(e,"deviceId");const i=await this._audioDeviceManager.setSinkId(e);null==(t=this._room)||t.remoteStreams.forEach((t=>{t.forEach((t=>{var i;null==(i=t.audioTrack)||i.setPlaybackDevice(e)}))})),this.safeEmit(EngineEventsTypes.onAudioPlaybackDeviceChanged,i),this.monitor.report("rtc_audio_device",{audio_event:"playout_device_switch",message:JSON.stringify(i),error_code:0})}async play(e,t=MediaType$1.AUDIO_AND_VIDEO,i,r){var o,s,n;this.logger.info("play()","userId: %s, mediaType: %s, streamIndex: %s",e,t,i);const a=r??DEFAULT_PLAYER_ID,d=!e||e===this._getUserId()||"local_user"===e,c=void 0===i||i===StreamIndex$1.STREAM_INDEX_MAIN,l=void 0===i||i===StreamIndex$1.STREAM_INDEX_SCREEN,u=t!==MediaType$1.VIDEO,_=t!==MediaType$1.AUDIO,h=[];if(d&&_){if(c&&this._localVideoTrack){this._localVideoTrack.mirror(!!this._mirrorType);const e=this._localVideoTrack.play(a);e&&h.push(e)}if(l&&this._localScreenVideoTrack){(null==(o=this._localScreenVideoTrack)?void 0:o.manuallyPlay(a))&&h.push()}}this._audioMixingManager&&e===this._audioMixingManager.id&&h.push(this._audioMixingManager.resumeLocalPlay());let p=[];return null==(s=this._room)||s.remoteStreams.forEach(((t,i)=>{e&&e!==i||t.forEach((e=>{e.audioTrack&&p.push(e.audioTrack),e.videoTrack&&p.push(e.videoTrack)}))})),this._wtnStreamManager.__getRemoteStreams().forEach(((t,i)=>{e&&e!==i||(t.audioTrack&&p.push(t.audioTrack),t.videoTrack&&p.push(t.videoTrack))})),c||(p=p.filter((e=>!!e.isScreen))),l||(p=p.filter((e=>!e.isScreen))),u||(p=p.filter((e=>"audio"!==e.mediaType))),_||(p=p.filter((e=>"video"!==e.mediaType))),u&&(null==(n=this._room)||n.virtualStreams.forEach((e=>{e.audioTrack&&p.push(e.audioTrack)}))),p.forEach((e=>{const t=e.manuallyPlay(a);t&&h.push(t)})),Promise.all(h).then((()=>{}))}async stop(e,t=MediaType$1.AUDIO_AND_VIDEO,i,r){var o,s;this.logger.info("stop()","userId: %s, mediaType: %s, streamIndex: %s, playerId: %s",e,t,i,r);const n=r??DEFAULT_PLAYER_ID,a=!e||e===this._getUserId()||"local_user"===e,d=void 0===i||i===StreamIndex$1.STREAM_INDEX_MAIN,c=void 0===i||i===StreamIndex$1.STREAM_INDEX_SCREEN,l=t!==MediaType$1.VIDEO,u=t!==MediaType$1.AUDIO;if(a&&u&&(d&&this._localVideoTrack&&this._localVideoTrack.pause(n),c&&this._localScreenVideoTrack&&this._localScreenVideoTrack.pause(n)),e){let t=[];null==(s=null==(o=this._room)?void 0:o.remoteStreams.get(e))||s.forEach((e=>{e.audioTrack&&t.push(e.audioTrack),e.videoTrack&&t.push(e.videoTrack)}));const i=this._wtnStreamManager.__getPublicStreamTrack(e,"audio"),r=this._wtnStreamManager.__getPublicStreamTrack(e,"video");i&&t.push(i),r&&t.push(r),d||(t=t.filter((e=>!!e.isScreen))),c||(t=t.filter((e=>!e.isScreen))),l||(t=t.filter((e=>"audio"!==e.mediaType))),u||(t=t.filter((e=>"video"!==e.mediaType))),t.forEach((e=>{e.pause(n)}))}}getAudioVolume(e,t){var i,r,o;checkEnum(e,"streamIndex",[StreamIndex$1.STREAM_INDEX_MAIN,StreamIndex$1.STREAM_INDEX_SCREEN]);let s=0;if(t){const n=null==(o=null==(r=null==(i=this._room)?void 0:i.remoteStreams.get(t))?void 0:r.find((t=>t.isScreen===(e===StreamIndex$1.STREAM_INDEX_SCREEN))))?void 0:o.audioTrack;n&&(s=n.getAudioLevel())}else{const t=e===StreamIndex$1.STREAM_INDEX_MAIN?this._localAudioTrack:this._localScreenAudioTrack;t&&(s=t.getAudioLevel())}return{linearVolume:s,nonlinearVolume:getNonlinearVolume(s)}}setAudioFrameCallback(e,t,i,r=4096){var o,s,n;if(this.logger.info("setAudioFrameCallback()","streamIndex: %s, userId: %s, callback: %s, frameSize: %s",e,t,i?"true":"false",r),checkEnum(r,"frameSize",[256,512,1024,2048,4096,8192,16384]),void 0===audioContextManager.isWorkletReady&&audioContextManager.getAudioContextInstance(),null===audioContextManager.isWorkletReady)throw this.logger.error("setAudioFrameCallback()","Not support AudioWorklet"),new SDKError(ErrorCode.NOT_SUPPORTED,"Not support AudioWorklet");t?i?this._ctx._remoteAudioTrackDumpConfig[e].set(t,{callback:i,frameSize:r}):this._ctx._remoteAudioTrackDumpConfig[e].delete(t):this._ctx._localAudioTrackDumpConfig[e]={callback:i,frameSize:i?r:void 0};const a=t?null==(n=null==(s=null==(o=this._room)?void 0:o.remoteStreams.get(t))?void 0:s.find((t=>t.isScreen===(e===StreamIndex$1.STREAM_INDEX_SCREEN))))?void 0:n.audioTrack:e===StreamIndex$1.STREAM_INDEX_MAIN?this._localAudioTrack:this._localScreenAudioTrack;a?i?a.setDataFetcher(r,i):a.stopDataFetcher():this.logger.warn("setAudioFrameCallback()","track not found")}async pauseAllSubscribedStream(e){this.logger.info("pauseAllSubscribedStream()","mediaType: %o",e),this._checkMediaType(e);return(()=>{audioInMediaType(e)&&(this._pauseAllSubscribeState.audio=!0),videoInMediaType(e)&&(this._pauseAllSubscribeState.video=!0)})(),this._room?this._pauseAllRemoteStreams(e):Promise.resolve()}async _pauseAllRemoteStreams(e){if(!this._room)return Promise.resolve();const t=[];return this._room.remoteStreams.forEach((i=>{Array.isArray(i)&&i.forEach((i=>{if(i.hasSubscribed){i.attributes.audiostream&&audioInMediaType(e)&&(this._pauseAllSubscribeState.resumeAudioStreamIds[i.streamId]=i.streamId),i.attributes.videostream&&videoInMediaType(e)&&(this._pauseAllSubscribeState.resumeVideoStreamIds[i.streamId]=i.streamId);const r=this._unsubscribe(i.isScreen,i.userId,e,!0);r&&t.push(r)}}))})),Promise.all(t).then((()=>{}))}async resumeAllSubscribedStream(e){this.logger.info("resumeAllSubscribedStream()","mediaType: %o",e),this._checkMediaType(e);if((()=>{audioInMediaType(e)&&(this._pauseAllSubscribeState.audio=!1),videoInMediaType(e)&&(this._pauseAllSubscribeState.video=!1)})(),!this._room)return Promise.resolve();await this._triedResumeAllRemoteStreams(e,!1)}async _triedResumeAllRemoteStreams(e,t){if(!this._room)return Promise.resolve();if(this._pauseAllSubscribeState.audio&&e===MediaType$1.AUDIO)return Promise.resolve();if(this._pauseAllSubscribeState.video&&e===MediaType$1.VIDEO)return Promise.resolve();if(this._pauseAllSubscribeState.video&&this._pauseAllSubscribeState.audio&&e===MediaType$1.AUDIO_AND_VIDEO)return Promise.resolve();const i=[],r=[...Object.keys(this._pauseAllSubscribeState.resumeAudioStreamIds)],o=[...Object.keys(this._pauseAllSubscribeState.resumeVideoStreamIds)];return this._room.remoteStreams.forEach((r=>{Array.isArray(r)&&r.forEach((r=>{if(t&&r.isScreen)return;const o=this._pauseAllSubscribeState.resumeAudioStreamIds[r.streamId],s=this._pauseAllSubscribeState.resumeVideoStreamIds[r.streamId];if(o&&audioInMediaType(e)||s&&videoInMediaType(e)){const t=this._subscribe(r.isScreen,r.userId,e).then((()=>{o&&audioInMediaType(e)&&delete this._pauseAllSubscribeState.resumeAudioStreamIds[r.streamId],s&&videoInMediaType(e)&&delete this._pauseAllSubscribeState.resumeVideoStreamIds[r.streamId]}));t&&i.push(t)}}))})),Promise.all(i).then((()=>{var e;return null==(e=this._room)||e.remoteStreams.forEach((e=>{Array.isArray(e)&&e.forEach((e=>{this._updateAudioPlayerState(e),this._updateVideoPlayerState(e)}))})),Promise.resolve()})).finally((()=>{var e;return(null==(e=this._room)?void 0:e.config.tokenSubscribePrivilegeExpired)&&(r.forEach((e=>{this._pauseAllSubscribeState.resumeAudioStreamIds[e]=e})),o.forEach((e=>{this._pauseAllSubscribeState.resumeVideoStreamIds[e]=e}))),Promise.resolve()}))}async sendUserMessage(e,t){var i,r;checkUserId(e),this._assertNotInRoom();const o=Date.now();return null==(r=null==(i=this._room)?void 0:i.sendUserMessage(e,t))?void 0:r.then((t=>(this._messageStatisticsObserver.countP2PMessage(!0,e,!1,o,t),t.id))).catch((t=>{throw this._messageStatisticsObserver.countP2PMessage(!1,e,!1,o,t),t}))}async sendUserBinaryMessage(e,t){var i,r;checkUserId(e),checkArrayBuffer(t,"message"),this._assertNotInRoom();const o=Date.now();return null==(r=null==(i=this._room)?void 0:i.sendUserMessage(e,t))?void 0:r.then((t=>(this._messageStatisticsObserver.countP2PMessage(!0,e,!0,o,t),t.id))).catch((t=>{throw this._messageStatisticsObserver.countP2PMessage(!1,e,!0,o,t),t}))}async sendRoomMessage(e){var t,i,r;this._assertNotInRoom();const o=null==(t=this._room)?void 0:t.config.roomId,s=Date.now();return null==(r=null==(i=this._room)?void 0:i.sendRoomMessage(e))?void 0:r.then((e=>(this._messageStatisticsObserver.countRoomMessage(!0,o,!1,s),e))).catch((e=>{throw this._messageStatisticsObserver.countRoomMessage(!1,o,!1,s),e}))}async sendRoomBinaryMessage(e){var t,i,r;this._assertNotInRoom();const o=null==(t=this._room)?void 0:t.config.roomId,s=Date.now();return null==(r=null==(i=this._room)?void 0:i.sendRoomMessage(e,!0))?void 0:r.then((e=>(this._messageStatisticsObserver.countRoomMessage(!0,o,!0,s),e))).catch((e=>{throw this._messageStatisticsObserver.countRoomMessage(!1,o,!0,s),e}))}async setAudioCaptureConfig(e={}){this.logger.info("setAudioCaptureConfig()","config: %o",e),delete e.deviceId,checkSupportedConstraints(e);await this._shouldUpdateAudioConf("setAudioCaptureConfig")&&this._ctx.audioProfileManager.updateConstraints(e)}async setVideoCaptureConfig(e={}){return this.logger.info("setVideoCaptureConfig()","config: %o",e),this._setVideoCaptureConfig(e)}async _setVideoCaptureConfig(e={}){var t;delete e.deviceId,checkSupportedConstraints(e);const i={...this._ctx.videoProfile.getCaptureConfig(),...e};return this._localVideoTrack&&await this._localVideoTrack.updateVideoCaptureConfig(i),this._ctx.videoProfile.setCaptureConfig(i),(null==(t=this._localVideoTrack)?void 0:t.originTrack.getSettings())||{}}enableSimulcastMode(e){this.logger.info("enableSimulcastMode()","enabled: %o",e),this._ctx.videoProfile.checkSimulcastApiVersion("old");try{return this._ctx.videoProfile.setSimulcastMode(e?VideoSimulcastMode.VIDEO_ON_DEMAND:VideoSimulcastMode.VIDEO_ONLY_ONE,this._room),!0}catch{return!1}}async setLocalSimulcastMode(e,t){var i;this.logger.info("setLocalSimulcastMode()","mode: %o, config: %o",e,t),this._ctx.videoProfile.checkSimulcastApiVersion("new"),await this._ctx.videoProfile.setSimulcastMode(e,this._room),await this._ctx.videoProfile.setSubVideoEncodeConfig(t,this._room,this._localVideoTrack);await(null==(i=this._room)?void 0:i.hasPublished())&&this._updatePublish()}async setVideoEncoderConfig(e){var t;if(this.logger.info("setVideoEncoderConfig()","descriptions: %o",e),await this._ctx.videoProfile.setVideoEncodeConfigPolyfill(e),this._localVideoTrack){const e=this._ctx.videoProfile.getContentHint();e&&this._localVideoTrack.setContentHint(e),await this._localVideoTrack.updateVideoCaptureConfig(this._ctx.videoProfile.getCaptureConfig())}this._updateDummyCaptureImage(StreamIndex$1.STREAM_INDEX_MAIN);await(null==(t=this._room)?void 0:t.hasPublished())&&this._updatePublish()}setVideoEncoderAutoConfigList(e){if(Array.isArray(e))return e.sort(((e,t)=>e.maxKbps-t.maxKbps)),setVideoEncoderAutoConfigList(e)}async setScreenEncoderConfig(e){var t;this.logger.info("setScreenEncoderConfig()","description: %o",e),this._ctx.videoProfile.setScreenEncodeConfig(e),this._localScreenVideoTrack&&("16.1"!==safariMinorVersion&&await this._localScreenVideoTrack.updateVideoCaptureConfig(e),e.contentHint&&this._localScreenVideoTrack.setContentHint(e.contentHint)),this._updateDummyCaptureImage(StreamIndex$1.STREAM_INDEX_SCREEN);await(null==(t=this._room)?void 0:t.hasScreenPublished())&&this._updateScreenPublish()}sendSEIMessage(e,t,i){var r,o,s,n,a,d,c,l,u;if(this.logger.info("sendSEIMessage()","streamIdex: %o, message: %o, repeatCount: %o",e,t,i),!isLegacyEncodedTransformSupported()&&!isEncodedTransformSupported())return warnDevelopers("Your browser does not support sending SEI"),!1;checkEnum(e,"streamIndex",[StreamIndex$1.STREAM_INDEX_MAIN,StreamIndex$1.STREAM_INDEX_SCREEN]),checkNumber(i,"repeatCount",0,30);const _="string"==typeof t?new Uint8Array(Utils.str2ab(t)):t;if(!t.length)return this.logger.warn("sei message must not be empty"),!1;let h;if(e===StreamIndex$1.STREAM_INDEX_MAIN){if(!(null==(o=null==(r=this._room)?void 0:r.localStream)?void 0:o.pubAudio)&&!(null==(n=null==(s=this._room)?void 0:s.localStream)?void 0:n.pubVideo))return;h=this._room.localStream}else{if(!(null==(d=null==(a=this._room)?void 0:a.localScreenStream)?void 0:d.pubAudio)&&!(null==(l=null==(c=this._room)?void 0:c.localScreenStream)?void 0:l.pubVideo))return;h=this._room.localScreenStream}if(_.byteLength>4096)return void this.logger.warn("sei size must not bigger than 4KB");isAndroid||null==(u=this._room)||u.maybeFillBackFrame2Stream(h);const p=genUuid();return h.sendSEIMessage({content:_,uuid:p,repeatCount:i+1}),setTimeout((async()=>{if(!h)return;if(await h.revokeSEIMessage(p)){const e=`timeout for sei message(id: ${p})`;console.error(`[RTC WebSDK] ${e}`),this.monitor.report("rtc_sdk_callback",{sdk_callback_name:"sendSEIMessageTimeout",message:e,error_code:400})}}),getParameter("SEI_TIME_OUT")),p}setAudioVolumeIndicationInterval(e){this.logger.info("setAudioVolumeIndicationInterval()","interval %o: ",e),("number"!=typeof e||e<200)&&(e=200);let t=[];this._audioVolumeIndicationTimer&&clearInterval(this._audioVolumeIndicationTimer),this._audioVolumeIndicationTimer=setInterval((()=>{var e,i;t=[],null==(e=this._room)||e.remoteStreams.forEach(((e,i)=>{var r;if(0===e.length)return;const o=e.find((e=>!e.isScreen)),s=null==(r=null==o?void 0:o.audioTrack)?void 0:r.getAudioLevel();t.push({userId:i,volume:s||0})}));const r=null==(i=this._localAudioTrack)?void 0:i.getAudioLevel();t.push({userId:this._getUserId(),volume:r||0}),this.safeEmit(EngineEventsTypes.onAudioVolumeIndication,{speakers:t})}),e)}_sendActiveSpeaker(e,t){if(this._room&&this._room.remoteUsers.size>=1){const i=e[0],r=t.reduce(((e,t)=>e&&e.audioPropertiesInfo.nonlinearVolume>t.audioPropertiesInfo.nonlinearVolume?e:t),void 0);let o;if(o=i?r?i.audioPropertiesInfo.nonlinearVolume>r.audioPropertiesInfo.nonlinearVolume?i:r:i:r,o&&o.audioPropertiesInfo.nonlinearVolume>-35){let e;e=o.streamKey?this._room.remoteUsers.get(o.streamKey.userId):this._room.config.userInfo,e&&this.safeEmit(EngineEventsTypes.onActiveSpeaker,{userId:e.userId,extraInfo:e.extraInfo})}}}enableAudioPropertiesReport(e={}){this.logger.info("enableAudioPropertiesReport()","config %o: ",e);const{enableInBackground:t=!0,localMainReportMode:i=LocalMainReportMode.NORMAL,audioReportMode:r=AudioReportMode.MICROPHONE}=e;let{interval:o=100}=e;this._stopAudioPropertiesReport(),o<=0||(o=Math.max(100,o),this._audioPropertiesReportTimer=self.setInterval((()=>{var e,o;if(!t&&"hidden"===document.visibilityState)return;const s=[],n=this._audioDeviceManager.getRecordTrack()||this._localAudioTrack;if(n){const t=null==(o=null==(e=this._room)?void 0:e.localStream)?void 0:o.audioHasPublish,a=!!this._audioDeviceManager.getRecordTrack(),d=n.getAudioLevel(r),c=getNonlinearVolume(d),l={streamIndex:StreamIndex$1.STREAM_INDEX_MAIN,audioPropertiesInfo:{linearVolume:d,nonlinearVolume:c}};if(t||a)s.push(l);else switch(i){case LocalMainReportMode.DISCONNECT:break;case LocalMainReportMode.RESET:l.audioPropertiesInfo.linearVolume=0,l.audioPropertiesInfo.nonlinearVolume=-127,s.push(l);break;case LocalMainReportMode.NORMAL:s.push(l);break;default:throw new SDKError(ErrorCode.INVALID_PARAMS,`invalid localMainReportMode: ${i} in config`)}}if(this._localScreenAudioTrack){const e=this._localScreenAudioTrack.getAudioLevel();s.push({streamIndex:StreamIndex$1.STREAM_INDEX_SCREEN,audioPropertiesInfo:{linearVolume:e,nonlinearVolume:getNonlinearVolume(e)}})}if(this.safeEmit(EngineEventsTypes.onLocalAudioPropertiesReport,s),this._room){const e=[];if(this._room.config.isMultiChatMode()){this._room.getActiveSpeakerInMultiChatMode().forEach((t=>{var i;const r=255*t.audioLevel;e.push({streamKey:{userId:t.userId,streamIndex:StreamIndex$1.STREAM_INDEX_MAIN,roomId:(null==(i=this._room)?void 0:i.config.roomId)??""},audioPropertiesInfo:{linearVolume:r,nonlinearVolume:getNonlinearVolume(r)}})}))}else this._room.remoteStreams.forEach(((t,i)=>{t.forEach((t=>{var r;if(t.audioTrack){const o=t.audioTrack.getAudioLevel();e.push({streamKey:{userId:i,streamIndex:t.isScreen?StreamIndex$1.STREAM_INDEX_SCREEN:StreamIndex$1.STREAM_INDEX_MAIN,roomId:(null==(r=this._room)?void 0:r.config.roomId)??""},audioPropertiesInfo:{linearVolume:o,nonlinearVolume:getNonlinearVolume(o)}})}}))}));this.safeEmit(EngineEventsTypes.onRemoteAudioPropertiesReport,e),this._sendActiveSpeaker(s,e.filter((e=>e.streamKey.streamIndex!==StreamIndex$1.STREAM_INDEX_SCREEN)))}}),o))}async setVideoSourceType(e,t){var i,r,o,s,n,a,d,c,l,u,_,h,p,m,S,g,v,f,E;this.logger.print("setVideoSourceType()","index: %o, videoSourceType: %o",e,t),checkEnum(e,"streamIndex",[StreamIndex$1.STREAM_INDEX_MAIN,StreamIndex$1.STREAM_INDEX_SCREEN]),checkEnum(t,"VideoSourceType",[VideoSourceType.VIDEO_SOURCE_TYPE_EXTERNAL,VideoSourceType.VIDEO_SOURCE_TYPE_INTERNAL]);const T=e===StreamIndex$1.STREAM_INDEX_MAIN?"video":"screenVideo";if(this._trackSourceType[T]!==t){if(this._trackSourceType[T]=t,this.logger.print("setVideoSourceType",`set ${T} source type to ${t}`),this._localVideoTrack&&e===StreamIndex$1.STREAM_INDEX_MAIN){let e=!1;if(t===VideoSourceType.VIDEO_SOURCE_TYPE_EXTERNAL){e=!0;const t=this._ctx.extensionManager.getPluginByName(RTCExtensionType.PRE_PROCESSING,"RTCBeautyExtension");t&&t.emit("stop"),this._removeLocalTrackEvents(this._localVideoTrack),this._localVideoTrack.destroy()}null==(i=this._localVideoTrack)||i.destroy(),this._localVideoTrack=void 0;const _=null==(r=this._room)?void 0:r.config.isAutoPublish;e?null==(n=null==(s=null==(o=this._room)?void 0:o.localStream)?void 0:s.observer)||n.setEnableVideo(!1):null==(c=null==(d=null==(a=this._room)?void 0:a.localStream)?void 0:d.observer)||c.setPushVideo(!1),((null==(u=null==(l=this._room)?void 0:l.localStream)?void 0:u.pubVideo)||_)&&await this._updatePublish()}if(this._localScreenVideoTrack&&e===StreamIndex$1.STREAM_INDEX_SCREEN){let e=!1;t===VideoSourceType.VIDEO_SOURCE_TYPE_EXTERNAL&&(e=!0,this._removeLocalTrackEvents(this._localScreenVideoTrack),this._localScreenVideoTrack.destroy()),null==(_=this._localScreenVideoTrack)||_.destroy(),this._localScreenVideoTrack=void 0,e?null==(m=null==(p=null==(h=this._room)?void 0:h.localScreenStream)?void 0:p.observer)||m.setEnableVideo(!1):null==(v=null==(g=null==(S=this._room)?void 0:S.localScreenStream)?void 0:g.observer)||v.setPushVideo(!1),(null==(E=null==(f=this._room)?void 0:f.localScreenStream)?void 0:E.pubVideo)&&await this._updateScreenPublish()}}}async setExternalVideoTrack(e,t){var i,r,o,s,n,a,d,c;if(this.logger.print("setExternalVideoTrack()","index: %o, track: %o",e,t),checkEnum(e,"streamIndex",[StreamIndex$1.STREAM_INDEX_MAIN,StreamIndex$1.STREAM_INDEX_SCREEN]),checkMediaStreamTrack(t),e===StreamIndex$1.STREAM_INDEX_MAIN){if(this._trackSourceType.video!==VideoSourceType.VIDEO_SOURCE_TYPE_EXTERNAL)throw new SDKError(ErrorCode.STREAM_TYPE_NOT_MATCH,"setVideoSourceType as external first");this._localVideoTrack=await createCustomVideoLocalTrack(this._ctx,t);const e=this._ctx.videoProfile.getContentHint();!t.contentHint&&e&&this._localVideoTrack.setContentHint(e),this._initLocalTrackEvents(this._localVideoTrack),this._localVideoPlayerConfig[StreamIndex$1.STREAM_INDEX_MAIN].forEach((e=>{var t,i;null==(i=this._localVideoTrack)||i.setPlayer(e,this._mirrorType,null==(t=this._config)?void 0:t.autoPlayPolicy,this._initPlayerEvents.bind(this))}));const s=null==(i=this._room)?void 0:i.config.isAutoPublish;((null==(o=null==(r=this._room)?void 0:r.localStream)?void 0:o.pubVideo)||s)&&await this._updatePublish()}if(e===StreamIndex$1.STREAM_INDEX_SCREEN){if(this._trackSourceType.screenVideo!==VideoSourceType.VIDEO_SOURCE_TYPE_EXTERNAL)throw new SDKError(ErrorCode.STREAM_TYPE_NOT_MATCH,"setVideoSourceType as external first");this._localScreenVideoTrack=await createCustomScreenVideoLocalTrack(this._ctx,t),this._initLocalTrackEvents(this._localScreenVideoTrack,!0),this._localVideoPlayerConfig[StreamIndex$1.STREAM_INDEX_SCREEN].forEach((e=>{var t,i;null==(i=this._localScreenVideoTrack)||i.setPlayer(e,this._mirrorType,null==(t=this._config)?void 0:t.autoPlayPolicy,this._initPlayerEvents.bind(this))})),null==(a=null==(n=null==(s=this._room)?void 0:s.localScreenStream)?void 0:n.observer)||a.setPushVideo(!0),(null==(c=null==(d=this._room)?void 0:d.localScreenStream)?void 0:c.pubVideo)&&await this._updateScreenPublish()}}async setAudioSourceType(e,t){var i,r,o,s,n,a,d,c,l,u,_,h,p,m,S,g,v;this.logger.print("setAudioSourceType()","index: %o, audioSourceType: %o",e,t),checkEnum(e,"streamIndex",[StreamIndex$1.STREAM_INDEX_MAIN,StreamIndex$1.STREAM_INDEX_SCREEN]),checkEnum(t,"audioSourceType",[AudioSourceType.AUDIO_SOURCE_TYPE_EXTERNAL,AudioSourceType.AUDIO_SOURCE_TYPE_INTERNAL]);const f=e===StreamIndex$1.STREAM_INDEX_MAIN?"audio":"screenAudio";if(this._trackSourceType[f]!==t){if(this._trackSourceType[f]=t,this.logger.print("setVideoSourceType",`set ${f} source type to ${t}`),this._localAudioTrack&&e===StreamIndex$1.STREAM_INDEX_MAIN){let e=!1;this._trackSourceType.audio===AudioSourceType.AUDIO_SOURCE_TYPE_EXTERNAL&&(e=!0,this._removeLocalTrackEvents(this._localAudioTrack),this._localAudioTrack.destroy()),this._localAudioTrack=void 0;const t=null==(i=this._room)?void 0:i.config.isAutoPublish;e?null==(s=null==(o=null==(r=this._room)?void 0:r.localStream)?void 0:o.observer)||s.setEnableAudio(!1):null==(d=null==(a=null==(n=this._room)?void 0:n.localStream)?void 0:a.observer)||d.setPushAudio(!1),((null==(l=null==(c=this._room)?void 0:c.localStream)?void 0:l.pubAudio)||t)&&await this._updatePublish()}if(this._localScreenAudioTrack&&e===StreamIndex$1.STREAM_INDEX_SCREEN){let e=!1;this._trackSourceType.audio===AudioSourceType.AUDIO_SOURCE_TYPE_EXTERNAL&&(e=!0,this._removeLocalTrackEvents(this._localScreenAudioTrack),this._localScreenAudioTrack.destroy()),this._localScreenAudioTrack=void 0,e?null==(h=null==(_=null==(u=this._room)?void 0:u.localScreenStream)?void 0:_.observer)||h.setEnableAudio(!1):null==(S=null==(m=null==(p=this._room)?void 0:p.localScreenStream)?void 0:m.observer)||S.setPushAudio(!1),(null==(v=null==(g=this._room)?void 0:g.localScreenStream)?void 0:v.pubAudio)&&await this._updateScreenPublish()}}}async setExternalAudioTrack(e,t){var i,r,o,s,n,a,d,c,l,u,_;if(this.logger.print("setExternalAudioTrack()","index: %o, track: %o",e,t),checkEnum(e,"streamIndex",[StreamIndex$1.STREAM_INDEX_MAIN,StreamIndex$1.STREAM_INDEX_SCREEN]),checkMediaStreamTrack(t),e===StreamIndex$1.STREAM_INDEX_MAIN){if(this._trackSourceType.audio!==AudioSourceType.AUDIO_SOURCE_TYPE_EXTERNAL)throw new SDKError(ErrorCode.STREAM_TYPE_NOT_MATCH,"setAudioSourceType as external first");this._localAudioTrack=await createCustomAudioLocalTrack(this._ctx,t),this._localAudioTrack.setVolume(this._localAudioVolume),this._initLocalTrackEvents(this._localAudioTrack);const e=this._ctx._localAudioTrackDumpConfig[StreamIndex$1.STREAM_INDEX_MAIN];e.frameSize&&e.callback&&this._localAudioTrack.setDataFetcher(e.frameSize,e.callback);const{position:d,volume:c}=this._ctx.earMonitorSettings[StreamIndex$1.STREAM_INDEX_MAIN];d!==EarMonitorPosition.NONE&&(this.setEarMonitorMode(StreamIndex$1.STREAM_INDEX_MAIN,d),this.setEarMonitorVolume(StreamIndex$1.STREAM_INDEX_MAIN,c));const l=null==(i=this._room)?void 0:i.config.isAutoPublish;null==(s=null==(o=null==(r=this._room)?void 0:r.localStream)?void 0:o.observer)||s.setPushAudio(!0),((null==(a=null==(n=this._room)?void 0:n.localStream)?void 0:a.pubAudio)||l)&&await this._updatePublish()}if(e===StreamIndex$1.STREAM_INDEX_SCREEN){if(this._trackSourceType.screenAudio!==AudioSourceType.AUDIO_SOURCE_TYPE_EXTERNAL)throw new SDKError(ErrorCode.STREAM_TYPE_NOT_MATCH,"setAudioSourceType as external first");this._localScreenAudioTrack=await createCustomScreenAudioLocalTrack(this._ctx,t),this._localScreenAudioTrack.setVolume(this._localScreenAudioVolume),this._initLocalTrackEvents(this._localScreenAudioTrack);const e=this._ctx._localAudioTrackDumpConfig[StreamIndex$1.STREAM_INDEX_SCREEN];e.frameSize&&e.callback&&this._localScreenAudioTrack.setDataFetcher(e.frameSize,e.callback);const{position:i,volume:r}=this._ctx.earMonitorSettings[StreamIndex$1.STREAM_INDEX_SCREEN];i!==EarMonitorPosition.NONE&&(this.setEarMonitorMode(StreamIndex$1.STREAM_INDEX_SCREEN,i),this.setEarMonitorVolume(StreamIndex$1.STREAM_INDEX_SCREEN,r)),null==(l=null==(c=null==(d=this._room)?void 0:d.localScreenStream)?void 0:c.observer)||l.setPushAudio(!0),(null==(_=null==(u=this._room)?void 0:u.localScreenStream)?void 0:_.pubAudio)&&await this._updateScreenPublish()}}async login(e,t){return this.logger.info("login()","token: %o, userInfo: %o",e,t),isEmpty(e)||checkString(e,"token"),checkUserId(t),this._rtmClient.login(e,t)}async logout(){return this.logger.info("logout()"),this._rtmClient.logout()}async updateLoginToken(e){return this.logger.info("updateLoginToken()","token: %o",e),isEmpty(e)||checkString(e,"token"),this._rtmClient.updateLoginToken(e)}async getPeerOnlineStatus(e){return this.logger.info("getPeerOnlineStatus()","userId: %o",e),checkUserId(e),this._rtmClient.getPeerOnlineStatus(e)}async sendUserMessageOutsideRoom(e,t){checkUserId(e);const i=Date.now();return this._rtmClient.sendUserMessageOutsideRoom(e,t).then((t=>(this._messageStatisticsObserver.countUserMessageOutsideRoom(!0,e,!1,i,t),t.id))).catch((t=>{throw this._messageStatisticsObserver.countUserMessageOutsideRoom(!1,e,!1,i,t),t}))}async sendUserBinaryMessageOutsideRoom(e,t){checkUserId(e),checkArrayBuffer(t,"message");const i=Date.now();return this._rtmClient.sendUserMessageOutsideRoom(e,t).then((t=>(this._messageStatisticsObserver.countUserMessageOutsideRoom(!0,e,!0,i,t),t.id))).catch((t=>{throw this._messageStatisticsObserver.countUserMessageOutsideRoom(!1,e,!0,i,t),t}))}async setServerParams(e,t){return this.logger.info("setServerParams()","signature: %o, url: %0",e,t),this._rtmClient.setServerParams(e,t)}async sendServerMessage(e){checkString(e,"message");const t=Date.now();return this._rtmClient.sendServerMessage(e).then((e=>{this._messageStatisticsObserver.countServerMessage(!0,!1,t,e)})).catch((e=>{throw this._messageStatisticsObserver.countServerMessage(!1,!1,t,e),e}))}async sendServerBinaryMessage(e){checkArrayBuffer(e,"message");const t=Date.now();return this._rtmClient.sendServerMessage(e).then((e=>{this._messageStatisticsObserver.countServerMessage(!0,!0,t,e)})).catch((e=>{throw this._messageStatisticsObserver.countServerMessage(!1,!0,t,e),e}))}startCloudProxy(e){if(this._room)throw new SDKError(ErrorCode.START_CLOUD_PROXY_AFTER_JOIN,"[startCloudProxy] should be invoke before join room ");if(this.logger.info("startCloudProxy()",e),checkString(e.logProxy,"logProxy"),Array.isArray(e.accessProxy))for(const t of e.accessProxy)checkString(t,"accessProxy");else checkString(e.accessProxy,"accessProxy");checkString(e.configProxy,"configProxy"),this._originIceConfigRequestUrls=getParameter("ICE_CONFIG_REQUEST_URLS"),this._originLogServerUrl=getParameter("LOG_SERVER_URL"),this._originConfigServerUrls=getParameter("CONFIG_REQUEST_DOMAINS"),setParameter("ICE_CONFIG_REQUEST_URLS",e.accessProxy),setParameter("LOG_SERVER_URL",getFullLogServerUrl(e.logProxy)),setParameter("CONFIG_REQUEST_DOMAINS",[e.configProxy]),sdkCache.clearAccessNode(this._appId),sdkCache.clearAccessUrls(),this._ctx.useCloudProxy=!0}stopCloudProxy(){var e;if(this._room)throw new SDKError(ErrorCode.STOP_CLOUD_PROXY_BEFORE_LEAVE,"[stopCloudProxy] should be invoke after leave room ");this.logger.info("stopCloudProxy()");setParameter("ICE_CONFIG_REQUEST_URLS",(null==(e=this._originIceConfigRequestUrls)?void 0:e.map((e=>e.replace("https://","").replace("/dispatch/v1/AccessInfo?Action=GetAccessInfo",""))))??[]),setParameter("LOG_SERVER_URL",this._originLogServerUrl??""),setParameter("CONFIG_REQUEST_DOMAINS",this._originConfigServerUrls??[]),sdkCache.clearAccessNode(this._appId),sdkCache.clearAccessUrls(),this._ctx.useCloudProxy=!1,this._startCloudProxyTimestamp=void 0}async startPushPublicStream(e,t){var i,r,o,s;if(this.logger.print("startPushPublicStream()","publicStreamId: %o, publicStreamParam: %o",e,t),checkPublicStreamId(e),this._assertNotInRoom(),this._publicStreamIds.get(e))throw new SDKError(ErrorCode.REPEAT_PUSH,"repeat push public media stream");this._room&&(null==(r=null==(i=t.layout)?void 0:i.regions)||r.map((e=>{var t;e.roomId=null==(t=this._room)?void 0:t.config.roomId})));const n=getPublicStreamControlMessage(e,"started",t);return null==(s=null==(o=this._room)?void 0:o.publicStreamControlMessage(n))?void 0:s.then((()=>{this._publicStreamIds.set(e,e)}))}async updatePublicStreamParam(e,t){var i;this.logger.print("startPushPublicStream()","publicStreamId: %o, publicStreamParam: %o",e,t),checkPublicStreamId(e),this._assertNotInRoom();const r=getPublicStreamControlMessage(e,"layoutChanged",t);return null==(i=this._room)?void 0:i.publicStreamControlMessage(r)}async stopPushPublicStream(e){var t;return this.logger.print("startPushPublicStream()","publicStreamId: %o",e),checkPublicStreamId(e),this._assertNotInRoom(),null==(t=this._room)?void 0:t.publicStreamControlMessage({type:"publicstream",action:"stopped",publicStreamID:e}).then((()=>{this._publicStreamIds.delete(e)}))}async startPlayPublicStream(e){await this._wtnStreamManager.startPlayWTN(null,e,!1,!1)}async stopPlayPublicStream(e){await this._wtnStreamManager.stopPlayWTN(e)}async setAudioProfile(e){this.logger.info("setAudioProfile()","profile: %o",e);await this._shouldUpdateAudioConf("setAudioProfile")&&this._ctx.audioProfileManager.setAudioProfile(e)}async setAudioEncodeMaxBitrate(e){var t,i,r,o,s,n;if(this.logger.print("setAudioEncodeMaxBitrate()",e),checkNumber(e,"maxBitrate",6,256),this._ctx.audioProfileManager.setCustomMaxBitrate(e),this._ctx.audioProfileManager.customMaxBitrate){if(isFirefox&&((null==(i=null==(t=this._room)?void 0:t.localStream)?void 0:i.pubAudio)||(null==(o=null==(r=this._room)?void 0:r.localScreenStream)?void 0:o.pubAudio)))throw new SDKError(ErrorCode.NOT_SUPPORTED,"Your browser does not support set audio encode maxBitrate dynamically.");await(null==(s=this._room)?void 0:s.setAudioEncodeMaxBitrate(StreamIndex$1.STREAM_INDEX_MAIN,e)),await(null==(n=this._room)?void 0:n.setAudioEncodeMaxBitrate(StreamIndex$1.STREAM_INDEX_SCREEN,e))}}setPublicStreamVideoPlayer(e,t){return this._wtnStreamManager.setWTNRemoteVideoPlayer(e,t)}async setDummyCaptureImagePath(e,t){return new Promise(((i,r)=>{checkString(t,"filePath");const o=new Image;o.crossOrigin="anonymous",o.src=t,o.onload=()=>{e===StreamIndex$1.STREAM_INDEX_MAIN?this._dummyMainImage=o:this._dummyScreenImage=o;try{this._updateDummyCaptureImage(e),i()}catch(e){r(new SDKError(ErrorCode.UNEXPECTED_ERROR,e.message))}},o.onerror=()=>{r(new SDKError(ErrorCode.UNEXPECTED_ERROR,"Load image error"))}}))}_updateDummyCaptureImage(e){var t,i;let r,o;if(e===StreamIndex$1.STREAM_INDEX_MAIN?(r=this._dummyMainImage,o=this._ctx.videoProfile.getVideoEncodeConfig()[0]):(r=this._dummyScreenImage,o=this._ctx.videoProfile.getScreenEncodeConfig()),!r)return;const s=document.createElement("canvas"),n=s.getContext("2d"),a=constraints2number(o.width),d=constraints2number(o.height);if(!n)throw new SDKError(ErrorCode.UNEXPECTED_ERROR,"Not support canvas");let c,l;!a||!d||r.width<=a&&r.height<=d?(c=r.width,l=r.height):(c=Math.min(a,r.width*d/r.height),l=Math.min(d,r.height*a/r.width)),s.width=c,s.height=l,n.drawImage(r,0,0,r.width,r.height,0,0,c,l);const u=window.setInterval((()=>{r&&n.drawImage(r,0,0,r.width,r.height,0,0,c,l)}),200);e===StreamIndex$1.STREAM_INDEX_MAIN?(clearInterval(this._dummyMainTimer),this._dummyMainTimer=u):(clearInterval(this._dummyScreenTimer),this._dummyScreenTimer=u);const _=s.captureStream(5).getVideoTracks()[0];e===StreamIndex$1.STREAM_INDEX_MAIN?(this._localImgVideoTrack=_,(null==(t=this._localVideoTrack)?void 0:t.dummy)&&this._localVideoTrack.setTrack(this._localImgVideoTrack)):(this._localImgScreenTrack=_,(null==(i=this._localScreenVideoTrack)?void 0:i.dummy)&&this._localScreenVideoTrack.setTrack(this._localImgScreenTrack))}_addListenExtensionEvent(e){e.on("re-capture-audio",(()=>{this._localAudioTrack&&this.stopAudioCapture().then((()=>{this.startAudioCapture()}))})),e.on("re-capture-video",(()=>{this._localVideoTrack&&!this._localVideoTrack.dummy&&this.stopVideoCapture().then((()=>{this.startVideoCapture()}))})),e.on("reset-video-effect",(async(e,t)=>{var i,r;if(this._localVideoTrack&&!this._localVideoTrack.dummy){this._localVideoTrack&&this._removeLocalTrackEvents(this._localVideoTrack);try{await this._localVideoTrack.generatePreProcessingTrack()}catch(e){t(e)}this._initLocalTrackEvents(this._localVideoTrack),this._localVideoTrack.stopAll(),this._localVideoTrack.playAll(),this.safeEmit(EngineEventsTypes.onLocalStreamTrackChangedByExtension,{streamIndex:StreamIndex$1.STREAM_INDEX_MAIN,type:"video"}),e(),(null==(r=null==(i=this._room)?void 0:i.localStream)?void 0:r.pubVideo)&&await this._updatePublish(),this._wtnStreamManager._updatePushTrack()}e()}))}async registerExtension(e){var t,i,r;e.monitor=this.monitor,e.logger=new Logger$1(e.name,0,this.id);try{if(!await e.isSupported())throw new Error("This extension is not supported.")}catch{throw new Error("This extension is not supported.")}getParameter("VERSION")!==e.version&&(warnDevelopers(`This extension version is ${e.version}, but the sdk version is ${getParameter("VERSION")}.`),this.monitor.report("rtc_error",{message:`This extension version is ${e.version}, but the sdk version is ${getParameter("VERSION")}.`,error_code:-1}));let o={};if("RTCAIAnsExtension"===e.name){o={overloadThreshold:getParameter("AINR_OVERLOAD_THRESHOLD"),enableCache:getParameter("AINR_ENABLE_DUMP"),urls:getParameter("AINR_URLS"),cacheTime:getParameter("AINR_CACHE_TIME"),dumpTime:getParameter("AINR_DUMP_TIME")}}o=filterUndefined(o),await e.init(o),this._ctx.extensionManager.register(e),this._addListenExtensionEvent(e),null==(t=this._localAudioTrack)||t.generatePreProcessingTrack(),null==(i=this._localVideoTrack)||i.generatePreProcessingTrack(),null==(r=this._localScreenAudioTrack)||r.generatePreProcessingTrack()}defaultTranscoding(){return JSON.parse(JSON.stringify(LiveTranscoding.getDefaultValue()))}async _updatePublish(e={},t=!1){this.logger.info("_updatePublish()","config: %o",e);if(e={...{mediaType:void 0,invokeByJoinRoom:!1,pubState:PubState.PUB},...e},!this._ctx.visibility)throw new SDKError(ErrorCode.NO_PUBLISH_PERMISSION,"no publish permission");const i=await this._pubLock.lock();if(this._room&&this._ctx.signalingManager.isConnected())try{await this._room.publish(this._localVideoTrack,this._localAudioTrack,e.mediaType,e.pubState,e.invokeByJoinRoom)}catch(e){throw e instanceof SDKError?(e.code===ErrorCode.TOKEN_NO_PUBLISH_PERMISSION&&this._room.config.setTokenPublishPrivilegeExpired(!0),e):new SDKError(ErrorCode.UNEXPECTED_ERROR,"unexpected error",e)}finally{i()}else if(i(),t)throw new SDKError(ErrorCode.NOT_CONNECTED_YET,"not connected")}async startAudioPlaybackDeviceTest(e,t){return this.logger.print("startAudioPlaybackDeviceTest()","filePath: %o, indicationInterval: %o",e,t),checkString(e,"filePath"),checkNumber(t,"indicationInterval"),await this._audioDeviceManager.startAudioPlaybackDeviceTest(e,t)}stopAudioPlaybackDeviceTest(){this.logger.info("stopAudioPlaybackDeviceTest()"),this._audioDeviceManager.stopAudioPlaybackDeviceTest()}async startAudioDeviceRecordTest(e,t){this.logger.print("startAudioDeviceRecordTest()","indicationInterval: %o",e),checkNumber(e,"indicationInterval"),await this._audioDeviceManager.startAudioDeviceRecordTest(e,t,this._localAudioVolume)}stopAudioDeviceRecordAndPlayTest(){this.logger.info("stopAudioDeviceRecordAndPlayTest()"),this._audioDeviceManager.stopAudioDeviceRecordAndPlayTest()}stopAudioDevicePlayTest(){this.logger.info("stopAudioDevicePlayTest()"),this._audioDeviceManager.stopAudioDevicePlayTest()}setRemoteUserPriority(e,t){var i;this.logger.print("setRemoteUserPriority()","userId: %o, priority: %o",e,t);try{checkUserId(e),checkEnum(t,"priority",[RemoteUserPriority.HIGH,RemoteUserPriority.MEDIUM,RemoteUserPriority.LOW])}catch(e){return console.warn(e),!1}return this._ctx.userPriority.set(e,t),null==(i=this._room)||i.updateRemoteUserPriority(e),!0}async takeLocalSnapshot(e){this.logger.print("takeLocalSnapshot()","streamIndex: %o",e),checkEnum(e,"streamIndex",[StreamIndex$1.STREAM_INDEX_MAIN,StreamIndex$1.STREAM_INDEX_SCREEN]);const t=e===StreamIndex$1.STREAM_INDEX_MAIN?this.localVideoTrack:this.localScreenVideoTrack;if(!t)throw new SDKError(ErrorCode.INVOKED_BEFORE_CAPTURE,"capture first");return t.snapshot()}async takeRemoteSnapshot(e,t){var i,r,o;this.logger.print("takeRemoteSnapshot()","id: %o, streamIndex: %o",e,t),checkString(e,"id"),checkEnum(t,"streamIndex",[StreamIndex$1.STREAM_INDEX_MAIN,StreamIndex$1.STREAM_INDEX_SCREEN]);const s=(null==(o=null==(r=null==(i=this._room)?void 0:i.remoteStreams.get(e))?void 0:r.find((e=>e.isScreen===(t===StreamIndex$1.STREAM_INDEX_SCREEN))))?void 0:o.videoTrack)||this._wtnStreamManager.__getPublicStreamTrack(e,"video");if(!s)throw new SDKError(ErrorCode.STREAM_NOT_EXIST,"stream not exist");return s.snapshot()}setSubscribeFallbackOption(e){this.logger.info("setSubscribeFallbackOption()","option: %o",e);try{checkEnum(e,"option",[SubscribeFallbackOption.DISABLE,SubscribeFallbackOption.VIDEO_STREAM_LOW,SubscribeFallbackOption.AUDIO_ONLY])}catch(e){return console.warn(e),!1}return!this._room&&(this._ctx.subscribeFallbackOption=e,!0)}getLocalStreamTrack(e,t){let i,r;if(e===StreamIndex$1.STREAM_INDEX_MAIN?(i="video"===t?this.localVideoTrack:this.localAudioTrack,r=()=>{var e;return null==(e=this._room)?void 0:e.localStream}):(i="video"===t?this.localScreenVideoTrack:this.localScreenAudioTrack,r=()=>{var e;return null==(e=this._room)?void 0:e.localScreenStream}),!i)return;const o=i instanceof LocalAudioTrack&&i.mixedAudioTrack?i.mixedAudioTrack:i.preprocessingTrack;if(!o)return;const s=r();return this._reportMsTrackEvent(o,(null==s?void 0:s.stream.id)||"local"),o}getRemoteStreamTrack(e,t,i){var r;let o;const s=(null==(r=this._room)?void 0:r.remoteStreams.get(e))||[];if(!(null==s?void 0:s.length))return;let n;if(t===StreamIndex$1.STREAM_INDEX_MAIN?(n=s.find((e=>!e.isScreen)),o="video"===i?null==n?void 0:n.videoTrack:null==n?void 0:n.audioTrack):(n=s.find((e=>e.isScreen)),o="video"===i?null==n?void 0:n.videoTrack:null==n?void 0:n.audioTrack),!o)return;const a=o.preprocessingTrack;if(!a||!n)return;const{streamId:d}=n;return this._reportMsTrackEvent(a,d),a}getPublicStreamTrack(e,t){const i=this._wtnStreamManager.__getPublicStreamTrack(e,t),r=null==i?void 0:i.preprocessingTrack;if(r)return r?(this._reportMsTrackEvent(r,e),r):void 0}setRemoteStreamRenderSync(e){return!this._room&&(this._ctx.avSync=!!e,!0)}setJoinRoomParams(e){e&&(this._ctx.joinRoomParams=e)}async setAudioSelectionConfig(e){checkEnum(e,"audioSelectionPriority",[AudioSelectionPriority.DEFAULT,AudioSelectionPriority.HIGH]),this._ctx.mediaParams||(this._ctx.mediaParams={}),this._ctx.mediaParams.audioSelectionConfig={isHighPriority:e===AudioSelectionPriority.HIGH},this._room&&await this._room.updateMediaParams(this._ctx.mediaParams)}setCaptureVolume(e,t){var i,r,o,s,n;checkEnum(e,"streamIndex",[StreamIndex$1.STREAM_INDEX_MAIN,StreamIndex$1.STREAM_INDEX_SCREEN]),t=numberRangeGuide(t,"volume",0,400);e===StreamIndex$1.STREAM_INDEX_SCREEN?(null==(i=this._localScreenAudioTrack)||i.once("needReplaceTrack",(()=>{var e;null==(e=this._room)||e.updatePubScreenTrack()})),null==(r=this._localScreenAudioTrack)||r.setVolume(t),this._localScreenAudioVolume=t):(null==(o=this._localAudioTrack)||o.once("needReplaceTrack",(()=>{var e;null==(e=this._room)||e.updatePubTrack()})),null==(s=this._localAudioTrack)||s.setVolume(t),null==(n=this._audioDeviceManager.audioTrack)||n.setVolume(t),this._localAudioVolume=t)}setPlaybackVolume(e,t,i){var r,o,s,n;if(checkUserId(e),checkEnum(t,"streamIndex",[StreamIndex$1.STREAM_INDEX_MAIN,StreamIndex$1.STREAM_INDEX_SCREEN]),i=numberRangeGuide(i,"volume",0,400),null==(r=this._room)?void 0:r.config.isMultiChatMode())return void warnDevelopers("setPlaybackVolume is not supported in Conference mode");const a=t===StreamIndex$1.STREAM_INDEX_SCREEN;a?this._remoteScreenAudioVolume.set(e,i):this._remoteAudioVolume.set(e,i);const d=null==(s=null==(o=this._room)?void 0:o.remoteStreams.get(e))?void 0:s.find((e=>e.isScreen===a));null==(n=null==d?void 0:d.audioTrack)||n.setVolume(i)}setPublicStreamVolume(e,t){this._wtnStreamManager.setWTNRemoteAudioPlaybackVolume(e,t)}async startForwardStreamToRooms(e){e.forEach((e=>{checkRoomId(e.roomId)})),this._assertNotInRoom();return await this._room.startForwardStream2Rooms(e)}async updateForwardStreamToRooms(e){e.forEach((e=>{checkRoomId(e.roomId)})),this._assertNotInRoom();return await this._room.updateForwardStream2Rooms(e)}async stopForwardStreamToRooms(){this._assertNotInRoom();return await this._room.stopForwardStream2Rooms()}async pauseForwardStreamToAllRooms(){this._assertNotInRoom();return await this._room.pauseForwardStream2AllRooms()}async resumeForwardStreamToAllRooms(){this._assertNotInRoom();return await this._room.resumeForwardStream2AllRooms()}async ambulance(){const e=await ambulance(this),t=JSON.stringify(e);return this.monitor.reportLongString("ambulance",t),e}async setEarMonitorMode(e,t){this.logger.info("setEarMonitorMode()","streamIndex: %s, position: %s",e,t),checkEnum(e,"streamIndex",[StreamIndex$1.STREAM_INDEX_MAIN,StreamIndex$1.STREAM_INDEX_SCREEN]),checkEnum(t,"position",[EarMonitorPosition.NONE,EarMonitorPosition.AFTER_CAPTURE,EarMonitorPosition.AFTER_PROCESS]),this._ctx.earMonitorSettings[e].position=t;const i=e===StreamIndex$1.STREAM_INDEX_MAIN?this.localAudioTrack:e===StreamIndex$1.STREAM_INDEX_SCREEN?this.localScreenAudioTrack:void 0;if(i)return t!==EarMonitorPosition.NONE?i.play(t):i.stop();this.logger.warn("setEarMonitorMode()","local audio track not exist")}setEarMonitorVolume(e,t){this.logger.info("setEarMonitorVolume()","streamIndex: %s, volume: %s",e,t),checkEnum(e,"streamIndex",[StreamIndex$1.STREAM_INDEX_MAIN,StreamIndex$1.STREAM_INDEX_SCREEN]),t=numberRangeGuide(t,"volume",0,400),this._ctx.earMonitorSettings[e].volume=t;const i=e===StreamIndex$1.STREAM_INDEX_MAIN?this.localAudioTrack:e===StreamIndex$1.STREAM_INDEX_SCREEN?this.localScreenAudioTrack:void 0;if(i)return i.setPlaybackVolume(t);this.logger.warn("setEarMonitorVolume()","local audio track not exist")}setUserInfo(e,t){checkRoomId(e),checkUserId(t),this.monitor.set({room_id:e,user_id:t})}_reportMsTrackEvent(e,t){if(!e.hookStop){e.hookStop=!0;const i=e.stop;e.stop=()=>{reportRtcInvokeStatus(this.id,"stop",t,0,t),i.call(e)}}}async _updateScreenPublish(e={}){this.logger.info("_updateScreenPublish()");if(e={...{mediaType:void 0,pubState:PubState.PUB},...e},!this._ctx.visibility)throw new SDKError(ErrorCode.NO_PUBLISH_PERMISSION,"no publish permission");const t=await this._pubLock.lock();if(this._room&&this._ctx.signalingManager.isConnected())try{await this._room.publishScreen(this._localScreenVideoTrack,this._localScreenAudioTrack,e.mediaType,e.pubState)}catch(e){throw e instanceof SDKError?e:new SDKError(ErrorCode.UNEXPECTED_ERROR,"unexpected error",e)}finally{t()}else t()}_updateAudioPlayerState(e){var t,i,r,o;this.logger.info("_updateAudioPlayerState()");const{userId:s,isScreen:n,isPublic:a}=e;if(e.audioTrack&&e.attributes.audiostream&&e.subAudio){if(!e.audioTrack.havePlayer()){const r=new AudioPlayer(this.id,s,{muted:(null==(t=this._config)?void 0:t.autoPlayPolicy)===RTCAutoPlayPolicy.VIDEO_ONLY||(null==(i=this._config)?void 0:i.autoPlayPolicy)===RTCAutoPlayPolicy.PLAY_MANUALLY,isScreen:!a&&n});e.audioTrack.setPlayer(r),e.audioTrack.bindPlayerEvent(this._initPlayerEvents.bind(this));const o=this._audioDeviceManager.getSinkId();o&&e.audioTrack.setPlaybackDevice(o)}e.audioTrack.play();const o=a?this._ctx.publicAudioVolume.get(s)??100:n?this._remoteScreenAudioVolume.get(s)??100:this._remoteAudioVolume.get(s)??100;if(e.audioTrack.setVolume(o),isSafari&&isIPad){const e=(null==(r=this._room)?void 0:r.remoteStreams)??new Map;replayRemoteAudioWorkaround(e)}}else null==(o=e.audioTrack)||o.stop()}_updateVideoPlayerState(e){var t;if(this.logger.info("_updateVideoPlayerState()"),e.videoTrack){const i=e.isPublic?this._wtnStreamManager._publicVideoPlayerConfig:this._remoteVideoPlayerConfig[e.isScreen?StreamIndex$1.STREAM_INDEX_SCREEN:StreamIndex$1.STREAM_INDEX_MAIN].get(e.userId);if(i)for(const[,r]of i)e.videoTrack.setPlayer(this.id,r,null==(t=this._config)?void 0:t.autoPlayPolicy,this._initPlayerEvents.bind(this))}}get _localVideoTrack(){return this._ctx.localVideoTrack}get _localAudioTrack(){return this._ctx.localAudioTrack}set _localVideoTrack(e){this._ctx.localVideoTrack=e}set _localAudioTrack(e){this._ctx.localAudioTrack=e}async _onAddStream(e){const t=e.stream,{localaudio:i,audiostream:r,localvideo:o,videostream:s}=t.attributes;let n=ExtendMediaType.NONE;r&&(n|=MediaType$1.AUDIO),s&&(n|=MediaType$1.VIDEO),n&&(await new Promise((e=>setTimeout(e))),t.isScreen?this.safeEmit(EngineEventsTypes.onUserPublishScreen,{userId:t.userId,mediaType:n}):(this.safeEmit(EngineEventsTypes.onUserPublishStream,{userId:t.userId,mediaType:n,videoStreamDescriptions:t.attributes.videoDescriptions}),this._handleAutoSubscribe(t,!0)),this.safeEmit("onAddStream",{userId:t.userId,mediaType:n,isScreen:!!t.isScreen}),t.isScreen||(i&&this.safeEmit(EngineEventsTypes.onUserStartAudioCapture,{userId:t.userId}),o&&this.safeEmit(EngineEventsTypes.onUserStartVideoCapture,{userId:t.userId})))}_handleAutoSubscribe(e,t){var i,r,o,s,n;let a=ExtendMediaType.NONE;(null==(i=this._room)?void 0:i.config.isAutoSubscribeAudio)&&(a|=MediaType$1.AUDIO),(null==(r=this._room)?void 0:r.config.isAutoSubscribeVideo)&&(a|=MediaType$1.VIDEO),a&&(t&&audioInMediaType(a)&&(null==(o=e.observer)||o.setAutoSubscribeAudio(!0)),t&&videoInMediaType(a)&&(null==(s=e.observer)||s.setAutoSubscribeVideo(!0)),(null==(n=this._room)?void 0:n.config.tokenSubscribePrivilegeExpired)?(audioInMediaType(a)&&(this._pauseAllSubscribeState.resumeAudioStreamIds[e.streamId]=e.streamId),videoInMediaType(a)&&(this._pauseAllSubscribeState.resumeVideoStreamIds[e.streamId]=e.streamId)):this._subscribe(!1,e.userId,a))}_onRemoveStream(e){const t=e.stream,i=StreamRemoveReasonMap[e.reason]??StreamRemoveReason.STREAM_REMOVE_REASON_OTHER,r=t.isScreen?EngineEventsTypes.onUserUnpublishScreen:EngineEventsTypes.onUserUnpublishStream;let o=ExtendMediaType.NONE;t.attributes.audiostream&&(o|=MediaType$1.AUDIO),t.attributes.videostream&&(o|=MediaType$1.VIDEO),o!==ExtendMediaType.NONE&&(this.safeEmit(r,{userId:t.userId,mediaType:o,reason:i}),this.safeEmit("onRemoveStream",{userId:t.userId,isScreen:t.isScreen})),delete this._pauseAllSubscribeState.resumeAudioStreamIds[t.streamId],delete this._pauseAllSubscribeState.resumeVideoStreamIds[t.streamId]}_onUserConnection(e){setTimeout((()=>this.safeEmit(EngineEventsTypes.onUserJoined,e)))}_onUserLeave(e){this.safeEmit(EngineEventsTypes.onUserLeave,e)}_onRoomError(e){var t;this.safeEmit(EngineEventsTypes.onError,e),null==(t=this._room)||t.destroy(),this._room=void 0}_onNetworkQuality(...e){this.safeEmit(EngineEventsTypes.onNetworkQuality,...e)}_onConnectionStateChange(e){var t;if(void 0!==this._startCloudProxyTimestamp&&this._ctx.useCloudProxy&&e.state===ConnectionState.CONNECTION_STATE_CONNECTED&&this.safeEmit(EngineEventsTypes.onCloudProxyConnected,{interval:Date.now()-this._startCloudProxyTimestamp}),(this._ctx.isPreConnection||e.state!==ConnectionState.CONNECTION_STATE_CONNECTED&&e.state!==ConnectionState.CONNECTION_STATE_RECONNECTED)&&this.safeEmit(EngineEventsTypes.onConnectionStateChanged,e),e.state===ConnectionState.CONNECTION_STATE_RECONNECTING)for(const[e,i]of(null==(t=this._room)?void 0:t.remoteStreams)??new Map)e.startsWith("mux")&&i.forEach((e=>{var t;return null==(t=e.audioTrack)?void 0:t.stop()}));else e.state===ConnectionState.CONNECTION_STATE_CONNECTED&&this._rtmClient.setRTSMessageLimit(this._ctx.rtsLimiter.conf)}_stopAudioPropertiesReport(){null!==this._audioPropertiesReportTimer&&(clearInterval(this._audioPropertiesReportTimer),this._audioPropertiesReportTimer=null)}_onResubscribe(e){var t,i;e.stream&&(null==(t=e.stream.videoTrack)||t.stopAll(),null==(i=e.stream.audioTrack)||i.stop(),this._updateAudioPlayerState(e.stream),this._updateVideoPlayerState(e.stream))}_onSubscribePushTrack(e){e.stream&&this._updateAudioPlayerState(e.stream)}_onRemovePushTrack(e){e.stream&&this._updateAudioPlayerState(e.stream)}_onUserPublishStateChange({userId:e,isScreen:t,mediaType:i,pubState:r,remoteStream:o}){const s={userId:e,mediaType:i};i&MediaType$1.AUDIO&&setTimeout((()=>{this._updateAudioPlayerState(o)})),t?r===PubState.PUB?this.safeEmit(EngineEventsTypes.onUserPublishScreen,s):this.safeEmit(EngineEventsTypes.onUserUnpublishScreen,{...s,reason:StreamRemoveReason.STREAM_REMOVE_REASON_UNPUBLISH}):r===PubState.PUB?(s.videoStreamDescriptions=o.attributes.videoDescriptions,this.safeEmit(EngineEventsTypes.onUserPublishStream,s),this._handleAutoSubscribe(o,!0)):this.safeEmit(EngineEventsTypes.onUserUnpublishStream,{...s,reason:StreamRemoveReason.STREAM_REMOVE_REASON_UNPUBLISH})}_onCustomMessage(e){const{message:t}=e;e.binary?this.safeEmit(EngineEventsTypes.onRoomBinaryMessageReceived,{userId:e.clientId,message:t}):this.safeEmit(EngineEventsTypes.onRoomMessageReceived,{userId:e.clientId,message:t})}_onUserMessageReceived(e){this._messageStatisticsObserver.recvP2PMessage(e.userId),this.safeEmit(EngineEventsTypes.onUserMessageReceived,e)}_onUserBinaryMessageReceived(e){this._messageStatisticsObserver.recvP2PMessage(e.userId),this.safeEmit(EngineEventsTypes.onUserBinaryMessageReceived,e)}_onLiveTranscodingResult(e){this.safeEmit(EngineEventsTypes.onLiveTranscodingResult,e)}_onStreamMixingEvent(e){this.safeEmit(EngineEventsTypes.onStreamMixingEvent,e)}_onUserTokenWillExpire(){this.safeEmit(EngineEventsTypes.onTokenWillExpire)}_onUserTokenPublishPrivilegeWillExpire(){this.safeEmit(EngineEventsTypes.onTokenPublishPrivilegeWillExpire)}async _onUserTokenPublishPrivilegeDidExpired(){var e,t,i;await(null==(e=this._room)?void 0:e.unpublish().catch((()=>{}))),await(null==(t=this._room)?void 0:t.unpublishScreen().catch((()=>{}))),null==(i=this._room)||i.config.setTokenPublishPrivilegeExpired(!0),this.safeEmit(EngineEventsTypes.onTokenPublishPrivilegeDidExpired,{errorCode:ErrorCode.TOKEN_NO_PUBLISH_PERMISSION,message:"Token no longer has publish privilege"})}_onUserTokenSubscribePrivilegeWillExpire(){this.safeEmit(EngineEventsTypes.onTokenSubscribePrivilegeWillExpire)}async _onUserTokenSubscribePrivilegeDidExpired(){this._handleLoseSubscribePrivilege(),this.safeEmit(EngineEventsTypes.onTokenSubscribePrivilegeDidExpired,{errorCode:ErrorCode.TOKEN_NO_SUBSCRIBE_PERMISSION,message:"Token no longer has subscribe privilege"})}async _unSubscribeAllRemoteStreams(){return this._room?this._pauseAllRemoteStreams(MediaType$1.AUDIO_AND_VIDEO):Promise.resolve()}_onPushPublicStreamResult(e){this.safeEmit(EngineEventsTypes.onPushPublicStreamResult,e)}_handleRTMClient(e){e.on("onUserMessageReceivedOutsideRoom",(e=>{this._messageStatisticsObserver.recvP2POutRoomMessage(e.userId),this.safeEmit(EngineEventsTypes.onUserMessageReceivedOutsideRoom,e)})),e.on("onUserBinaryMessageReceivedOutsideRoom",(e=>{this._messageStatisticsObserver.recvP2POutRoomMessage(e.userId),this.safeEmit(EngineEventsTypes.onUserBinaryMessageReceivedOutsideRoom,e)})),e.on("onUserDisconnection",(()=>{this.safeEmit(EngineEventsTypes.onError,{errorCode:ErrorCode.RTM_DUPLICATE_LOGIN})})),e.on("onRTMTokenError",(()=>{this.safeEmit(EngineEventsTypes.onError,{errorCode:ErrorCode.RTM_TOKEN_ERROR})})),e.on("onServerParamsSetResult",(e=>{this.safeEmit(EngineEventsTypes.onServerParamsSetResult,null==e?void 0:e.code)}))}getSubLock(e,t){const i=e?this._subScreenLocks:this._subLocks;let r=i.get(t);return r||(r=new PromiseLock2(`sub_${e?1:0}_${t}`),i.set(t,r)),r}get localAudioTrack(){return this._localAudioTrack}get localVideoTrack(){return this._localVideoTrack}get localScreenAudioTrack(){return this._localScreenAudioTrack}get localScreenVideoTrack(){return this._localScreenVideoTrack}get remoteStreams(){var e;const t=[];return(null==(e=this._room)?void 0:e.remoteStreams)&&this._room.remoteStreams.forEach((e=>{Array.isArray(e)&&e.forEach((e=>{t.push({userId:e.userId,isScreen:e.isScreen,hasVideo:e.hasVideo,hasAudio:e.hasAudio,videoStreamDescriptions:e.attributes.videoDescriptions})}))})),t}get iceState(){var e;return null==(e=this._ctx.peerConnection)?void 0:e.getIceConnectionState()}get remoteUsers(){var e;const t=[];return(null==(e=this._room)?void 0:e.remoteUsers)&&this._room.remoteUsers.forEach((e=>{t.push({userId:e.userId})})),t}get multiChatMode(){var e;return!!(null==(e=this._room)?void 0:e.config.isMultiChatMode())}get checkMediaType(){return this._checkMediaType}get assertNotInRoom(){return this._assertNotInRoom}get peerConnection(){var e;return null==(e=this._ctx.peerConnection)?void 0:e.getOriginRTCPeerConnection()}_handleAudioDeviceManager(){this._audioDeviceManager.on("onAudioPlaybackDeviceTestVolume",(e=>{this.safeEmit(EngineEventsTypes.onAudioPlaybackDeviceTestVolume,e)}))}_assertNotInRoom(){if(!this._room||!this._ctx.signalingManager.isConnected())throw new SDKError(ErrorCode.NOT_CONNECTED_YET,"server not connected")}_checkMediaType(e){checkEnum(e,"mediaType",[MediaType$1.AUDIO,MediaType$1.VIDEO,MediaType$1.AUDIO_AND_VIDEO])}_getUserId(){var e;return(null==(e=this._room)?void 0:e.config.userInfo.userId)||"local_user"}async _switchTrack(e){var t,i;this._initLocalTrackEvents(e),this._localVideoTrack=e,this._localVideoPlayerConfig[StreamIndex$1.STREAM_INDEX_MAIN].forEach((t=>{var i;e.setPlayer(t,this._mirrorType,null==(i=this._config)?void 0:i.autoPlayPolicy,this._initPlayerEvents.bind(this))})),(null==(i=null==(t=this._room)?void 0:t.localStream)?void 0:i.pubVideo)&&await this._updatePublish(),this._wtnStreamManager._updatePushTrack()}async _shouldUpdateAudioConf(e){var t,i,r;const o=await(null==(t=this._room)?void 0:t.hasPublished())||(null==(r=null==(i=this._room)?void 0:i.localStream)?void 0:r.pubAudio)||this._localAudioTrack&&this._localAudioTrack.sourceType===SourceType.INTERNAL;if(o){const t=`engine.${e} should be called before publishing or capturing.`;console.warn(`[RTC WebSDK]: ${t}`),reportRtcInvokeStatus(this.id,e,t)}return!o}_getRemoteVideoPlayerConfig(e,t,i){var r;return null==(r=this._remoteVideoPlayerConfig[e].get(t))?void 0:r.get(i)}_setRemoteVideoPlayerConfig(e,t,i,r){const o=this._remoteVideoPlayerConfig[e].get(t)||new Map;o.set(i,r),this._remoteVideoPlayerConfig[e].set(t,o)}getRemoteVideoStats(){var e;const t=null==(e=this._room)?void 0:e.remoteStreams;if(!t||0===t.size)return{};const i={};return t.forEach(((e,t)=>{var r;let o,s;(null==(r=e[0])?void 0:r.isScreen)?(s=e[0],o=e[1]):(s=e[1],o=e[0]);const n={mainVideoStats:getPublicStats((null==o?void 0:o.getRemoteStreamStats().videoStats)||{}),screenVideoStats:getPublicStats((null==s?void 0:s.getRemoteStreamStats().videoStats)||{})};i[t]=n})),i}getRemoteAudioStats(){var e;const t=null==(e=this._room)?void 0:e.remoteStreams;if(!t||0===t.size)return{};const i={};return t.forEach(((e,t)=>{var r;let o,s;(null==(r=e[0])?void 0:r.isScreen)?(s=e[0],o=e[1]):(s=e[1],o=e[0]);const n={mainAudioStats:getPublicStats((null==o?void 0:o.getRemoteStreamStats().audioStats)||{}),screenAudioStats:getPublicStats((null==s?void 0:s.getRemoteStreamStats().audioStats)||{})};i[t]=n})),i}getLocalVideoStats(){var e,t,i,r;return{mainVideoStats:getPublicStats((null==(t=null==(e=this._room)?void 0:e.localStream)?void 0:t.getLocalStreamStats().videoStats)||{}),screenVideoStats:getPublicStats((null==(r=null==(i=this._room)?void 0:i.localScreenStream)?void 0:r.getLocalStreamStats().videoStats)||{})}}getLocalAudioStats(){var e,t,i,r;return{mainAudioStats:getPublicStats((null==(t=null==(e=this._room)?void 0:e.localStream)?void 0:t.getLocalStreamStats().audioStats)||{}),screenAudioStats:getPublicStats((null==(r=null==(i=this._room)?void 0:i.localScreenStream)?void 0:r.getLocalStreamStats().audioStats)||{})}}getPublicVideoStats(){const e=this._wtnStreamManager.__getRemoteStreams();if(!e||0===e.size)return{};const t={};return e.forEach(((e,i)=>{const r=getPublicStats(e.getRemoteStreamStats().videoStats||{});delete r.isScreen,t[i]=r})),t}getPublicAudioStats(){const e=this._wtnStreamManager.__getRemoteStreams();if(!e||0===e.size)return{};const t={};return e.forEach(((e,i)=>{const r=getPublicStats(e.getRemoteStreamStats().audioStats||{});delete r.isScreen,t[i]=r})),t}_initAutoplayFailedWorkaround(){if(Config2.AUTOPLAY_WORKAROUND&&(Config2.ENABLE_PLAY_AFTER_CLICK||isWeChat)){let e=[];this.on(EngineEventsTypes.onAutoplayFailed,(t=>{e.push(t),r()}));const t=()=>{e.length>0&&(reportRtcInvokeStatus(this.id,"resumePlay",JSON.stringify(e)),Promise.all(e.map((e=>this.play(e.userId,e.mediaType,e.streamIndex,e.playerId)))).then((()=>{e=[],reportRtcInvokeStatus(this.id,"resumePlaySuccess",JSON.stringify(e))})).catch((()=>{reportRtcInvokeStatus(this.id,"resumePlayFailed",JSON.stringify(e))})))};let i;Config2.ENABLE_PLAY_AFTER_CLICK&&(document.addEventListener("click",t),i=()=>{document.removeEventListener("click",t)});const r=()=>{var i,r;window.WeixinJSBridge&&(reportRtcInvokeStatus(this.id,"resumePlayInWxBridge",JSON.stringify(e)),null==(r=(i=window.WeixinJSBridge).invoke)||r.call(i,"getNetworkType",{},t))};let o;isWeChat&&!window.WeixinJSBridge&&(document.addEventListener("WeixinJSBridgeReady",r,!1),o=()=>{document.removeEventListener("WeixinJSBridgeReady",r)}),this._revokeAutoplayFailedWorkaround=()=>{null==i||i(),null==o||o()}}}},__publicField(_v,"hasReportNativeDetector",!1),_v);let RTCEngine=_RTCEngine;__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"updateToken",1),__decorateClass$1([reportRtcSdkApi(),captureLock("video")],RTCEngine.prototype,"setVideoCaptureDevice",1),__decorateClass$1([reportRtcSdkApi(),captureLock("audio")],RTCEngine.prototype,"setAudioCaptureDevice",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"connect",1),__decorateClass$1([setJoinRoomInfo,reportRtcSdkApi()],RTCEngine.prototype,"joinRoom",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"leaveRoom",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"destroy",1),__decorateClass$1([reportRtcSdkApi(),checkNotInRTSRoom],RTCEngine.prototype,"publishStream",1),__decorateClass$1([reportRtcSdkApi(),checkNotInRTSRoom],RTCEngine.prototype,"unpublishStream",1),__decorateClass$1([reportRtcSdkApi(),checkNotInRTSRoom],RTCEngine.prototype,"publishScreen",1),__decorateClass$1([reportRtcSdkApi(),checkNotInRTSRoom],RTCEngine.prototype,"unpublishScreen",1),__decorateClass$1([reportRtcSdkApi(),checkNotInRTSRoom],RTCEngine.prototype,"subscribeStream",1),__decorateClass$1([subLock],RTCEngine.prototype,"_subscribe",1),__decorateClass$1([reportRtcSdkApi(),checkNotInRTSRoom],RTCEngine.prototype,"unsubscribeStream",1),__decorateClass$1([reportRtcSdkApi(),checkNotInRTSRoom],RTCEngine.prototype,"subscribeScreen",1),__decorateClass$1([reportRtcSdkApi(),checkNotInRTSRoom],RTCEngine.prototype,"unsubscribeScreen",1),__decorateClass$1([subLock],RTCEngine.prototype,"_unsubscribe",1),__decorateClass$1([reportRtcSdkApi(),subLock2],RTCEngine.prototype,"setRemoteVideoConfig",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"setRemoteSimulcastStreamType",1),__decorateClass$1([reportRtcSdkApi(),captureLock("video")],RTCEngine.prototype,"startVideoCapture",1),__decorateClass$1([reportRtcSdkApi(),captureLock("video")],RTCEngine.prototype,"stopVideoCapture",1),__decorateClass$1([reportRtcSdkApi(),captureLock("audio")],RTCEngine.prototype,"startAudioCapture",1),__decorateClass$1([reportRtcSdkApi(),captureLock("audio")],RTCEngine.prototype,"stopAudioCapture",1),__decorateClass$1([reportRtcSdkApi(),captureLock("all")],RTCEngine.prototype,"startAudioAndVideoCapture",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"startVideoAndAudioCapture",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"getAudioMixingManager",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"getWTNStreamManager",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"getCallId",1),__decorateClass$1([reportRtcSdkApi(),screenCaptureLock],RTCEngine.prototype,"startScreenCapture",1),__decorateClass$1([reportRtcSdkApi(),screenCaptureLock],RTCEngine.prototype,"stopScreenCapture",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"setLocalVideoPlayer",1),__decorateClass$1([reportRtcSdkApi(),checkNotInRTSRoom],RTCEngine.prototype,"startLiveTranscoding",1),__decorateClass$1([reportRtcSdkApi(),checkNotInRTSRoom],RTCEngine.prototype,"updateLiveTranscoding",1),__decorateClass$1([reportRtcSdkApi(),checkNotInRTSRoom],RTCEngine.prototype,"stopLiveTranscoding",1),__decorateClass$1([reportRtcSdkApi(),checkNotInRTSRoom],RTCEngine.prototype,"startSubtitle",1),__decorateClass$1([reportRtcSdkApi(),checkNotInRTSRoom],RTCEngine.prototype,"updateSubtitleConfig",1),__decorateClass$1([reportRtcSdkApi(),checkNotInRTSRoom],RTCEngine.prototype,"stopSubtitle",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"setBusinessId",1),__decorateClass$1([reportRtcSdkApi(),checkNotInRTSRoom],RTCEngine.prototype,"setUserVisibility",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"setRemoteVideoPlayer",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"setLocalVideoMirrorType",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"setRemoteVideoMirrorType",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"setAudioPlaybackDevice",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"play",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"stop",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"getAudioVolume",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"setAudioFrameCallback",1),__decorateClass$1([reportRtcSdkApi(),checkNotInRTSRoom],RTCEngine.prototype,"pauseAllSubscribedStream",1),__decorateClass$1([reportRtcSdkApi(),checkNotInRTSRoom],RTCEngine.prototype,"resumeAllSubscribedStream",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"sendUserMessage",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"sendUserBinaryMessage",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"sendRoomMessage",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"sendRoomBinaryMessage",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"setAudioCaptureConfig",1),__decorateClass$1([warnDeprecatedApi("4.51"),reportRtcSdkApi()],RTCEngine.prototype,"setVideoCaptureConfig",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"enableSimulcastMode",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"setLocalSimulcastMode",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"setVideoEncoderConfig",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"setScreenEncoderConfig",1),__decorateClass$1([reportRtcSdkApi(),checkNotInRTSRoom],RTCEngine.prototype,"sendSEIMessage",1),__decorateClass$1([warnDeprecatedApi("4.42"),reportRtcSdkApi()],RTCEngine.prototype,"setAudioVolumeIndicationInterval",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"enableAudioPropertiesReport",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"setVideoSourceType",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"setExternalVideoTrack",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"setAudioSourceType",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"setExternalAudioTrack",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"login",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"logout",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"updateLoginToken",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"getPeerOnlineStatus",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"sendUserMessageOutsideRoom",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"sendUserBinaryMessageOutsideRoom",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"setServerParams",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"sendServerMessage",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"sendServerBinaryMessage",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"startCloudProxy",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"stopCloudProxy",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"startPushPublicStream",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"updatePublicStreamParam",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"stopPushPublicStream",1),__decorateClass$1([reportRtcSdkApi(["streamId"])],RTCEngine.prototype,"startPlayPublicStream",1),__decorateClass$1([reportRtcSdkApi(["streamId"])],RTCEngine.prototype,"stopPlayPublicStream",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"setAudioProfile",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"setAudioEncodeMaxBitrate",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"setPublicStreamVideoPlayer",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"setDummyCaptureImagePath",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"registerExtension",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"startAudioPlaybackDeviceTest",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"stopAudioPlaybackDeviceTest",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"startAudioDeviceRecordTest",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"stopAudioDeviceRecordAndPlayTest",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"stopAudioDevicePlayTest",1),__decorateClass$1([reportRtcSdkApi(),subLock2],RTCEngine.prototype,"setRemoteUserPriority",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"takeLocalSnapshot",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"takeRemoteSnapshot",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"setSubscribeFallbackOption",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"getLocalStreamTrack",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"getRemoteStreamTrack",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"getPublicStreamTrack",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"setRemoteStreamRenderSync",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"setJoinRoomParams",1),__decorateClass$1([reportRtcSdkApi(),checkNotInRTSRoom],RTCEngine.prototype,"setAudioSelectionConfig",1),__decorateClass$1([reportRtcSdkApi(),checkNotInRTSRoom],RTCEngine.prototype,"startForwardStreamToRooms",1),__decorateClass$1([reportRtcSdkApi(),checkNotInRTSRoom],RTCEngine.prototype,"updateForwardStreamToRooms",1),__decorateClass$1([reportRtcSdkApi(),checkNotInRTSRoom],RTCEngine.prototype,"stopForwardStreamToRooms",1),__decorateClass$1([reportRtcSdkApi(),checkNotInRTSRoom],RTCEngine.prototype,"pauseForwardStreamToAllRooms",1),__decorateClass$1([reportRtcSdkApi(),checkNotInRTSRoom],RTCEngine.prototype,"resumeForwardStreamToAllRooms",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"setEarMonitorMode",1),__decorateClass$1([reportRtcSdkApi([],{debounce:2e3,debounceTag:(e,...t)=>`${e}`})],RTCEngine.prototype,"setEarMonitorVolume",1),__decorateClass$1([reportRtcSdkApi()],RTCEngine.prototype,"setUserInfo",1);const StreamRemoveReasonMap={"client unpublished":StreamRemoveReason.STREAM_REMOVE_REASON_UNPUBLISH,"publish failed":StreamRemoveReason.STREAM_REMOVE_REASON_PUBLISH_FAILED,"stream removed":StreamRemoveReason.STREAM_REMOVE_REASON_KEEP_LIVE_FAILED,"client disconnected":StreamRemoveReason.STREAM_REMOVE_REASON_CLIENT_DISCONNECTED,"client republish":StreamRemoveReason.STREAM_REMOVE_REASON_REPUBLISH,"token publish privilege expired":StreamRemoveReason.STREAM_REMOVE_REASON_TOKEN_PRIVILEGE_EXPIRED};function subLock(e,t,i){const r=i.value;return i.value=async function(...e){const[t,i,o]=e;this.checkMediaType(o),this.assertNotInRoom();const s=await this.getSubLock(t,i).lock();try{return await r.apply(this,e)}finally{s()}},i}function subLock2(e,t,i){const r=i.value;return i.value=async function(...e){const[t]=e,i=await this.getSubLock(!1,t).lock();try{return await r.apply(this,e)}finally{i()}},i}function captureLock(e){return function(t,i,r){const o=r.value;return r.value=async function(...t){const i=[];"video"!==e&&i.push(this._audioCaptureLock.lock()),"audio"!==e&&i.push(this._videoCaptureLock.lock());const r=await Promise.all(i);try{return await o.apply(this,t)}finally{r.forEach((e=>e()))}},r}}function screenCaptureLock(e,t,i){const r=i.value;return i.value=async function(...e){const t=await this._screenCaptureLock.lock();try{return await r.apply(this,e)}finally{t()}},i}var __defProp2=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__decorateClass=(e,t,i,r)=>{for(var o,s=r>1?void 0:r?__getOwnPropDesc(t,i):t,n=e.length-1;n>=0;n--)(o=e[n])&&(s=(r?o(t,i,s):o(s))||s);return r&&s&&__defProp2(t,i,s),s};class BLWRTCEngine extends RTCEngine{constructor(e,t,i){super(e,t,i),__publicField(this,"singleStreamRenderMode",!1),this.id=t,this.logger=new Logger$1("BLWEngine",0,t),setVideoEncoderAutoConfigList([{width:192,height:108,frameRate:15,maxKbps:100},{width:320,height:180,frameRate:15,maxKbps:140},{width:640,height:360,frameRate:15,maxKbps:400},{width:1280,height:720,frameRate:15,maxKbps:1e3},{width:1920,height:1080,frameRate:15,maxKbps:2e3}]),this._handleEngineEvents()}async subscribeStream(e,t){return this.logger.print("subscribeStream()","userId: %o, mediaType: %o",e,t),this.singleStreamRenderMode&&videoInMediaType(t)&&super.subscribeScreen(e,MediaType$1.VIDEO).catch((e=>{this.logger.error("singleStreamRenderMode subscribeScreen()",e)})),super.subscribeStream(e,t)}async unsubscribeStream(e,t){return this.logger.print("unsubscribeStream()","userId: %o, mediaType: %o",e,t),this.singleStreamRenderMode&&videoInMediaType(t)&&super.unsubscribeScreen(e,MediaType$1.VIDEO).catch((e=>{this.logger.error("singleStreamRenderMode unsubscribeScreen()",e)})),super.unsubscribeStream(e,t)}setRemoteScreenVideoStreamIndex(e){return this.logger.print("setRemoteScreenVideoStreamIndex()","streamIndex: %o",e),!this._room&&(this.singleStreamRenderMode=e===StreamIndex$1.STREAM_INDEX_MAIN,!0)}setRemoteVideoPlayer(e,t){if(this.logger.print("setRemoteVideoPlayer()","streamIndex: %o, videoPlayerOption: %o",e,t),null==t||delete t.playerId,!this.singleStreamRenderMode||e!==StreamIndex$1.STREAM_INDEX_SCREEN)return super.setRemoteVideoPlayer(e,t)}destroy(){this.singleStreamRenderMode=!1,super.destroy()}_updateVideoPlayerState(e){var t,i,r,o,s,n,a;if(!this.singleStreamRenderMode)return super._updateVideoPlayerState(e);const{userId:d}=e,c=null==(t=this._room)?void 0:t.remoteStreams.get(d);let l,u;Array.isArray(c)&&c.forEach((e=>{e.isScreen?l=e:u=e}));let _=null==(i=null==u?void 0:u.videoTrack)?void 0:i.dangerousGetPlayer(DEFAULT_PLAYER_ID);if(!_){const e=null==(r=this._remoteVideoPlayerConfig[StreamIndex$1.STREAM_INDEX_MAIN].get(d))?void 0:r.get(DEFAULT_PLAYER_ID);if(!e)return;null==(s=null==u?void 0:u.videoTrack)||s.setPlayer(this.id,e,null==(o=this._config)?void 0:o.autoPlayPolicy,this._initPlayerEvents.bind(this)),_=null==(n=null==u?void 0:u.videoTrack)?void 0:n.dangerousGetPlayer(DEFAULT_PLAYER_ID)}if(!e.isScreen&&(null==l?void 0:l.videoTrack)&&l.videoHasPublish)return this.logger.print("_updateVideoPlayerState","prevent play main stream"),void(null==_||_.playVideo(l.videoTrack));e.videoTrack?(null==(a=this._config)?void 0:a.autoPlayPolicy)!==RTCAutoPlayPolicy.PLAY_MANUALLY&&(null==_||_.playVideo(e.videoTrack)):(null==_?void 0:_.played)&&_.stop()}_handleEngineEvents(){this.on(EngineEventsTypes.onUserPublishScreen,(e=>{var t,i;if(this.singleStreamRenderMode&&videoInMediaType(e.mediaType)){const r=null==(t=this._room)?void 0:t.remoteStreams.get(e.userId),o=null==r?void 0:r.find((e=>!e.isScreen)),s=null==r?void 0:r.find((e=>e.isScreen));(null==s?void 0:s.hasSubscribed)?(this.logger.info("onUserPublishScreen","singleStreamRenderMode screen hasSubscribed"),this._updateVideoPlayerState(s)):((null==(i=this._room)?void 0:i.config.isAutoSubscribeVideo)||(null==o?void 0:o.hasSubscribed)&&videoInMediaType(o.subMediaType))&&(this.logger.info("onUserPublishScreen","singleStreamRenderMode subscribeScreen"),this.subscribeScreen(e.userId,MediaType$1.VIDEO))}})),this.on(EngineEventsTypes.onUserUnpublishScreen,(e=>{var t;if(this.singleStreamRenderMode&&videoInMediaType(e.mediaType)){const i=null==(t=this._room)?void 0:t.remoteStreams.get(e.userId),r=null==i?void 0:i.find((e=>!e.isScreen));r&&setTimeout((()=>{this._updateVideoPlayerState(r)}))}}))}}__decorateClass([reportRtcSdkApi()],BLWRTCEngine.prototype,"subscribeStream",1),__decorateClass([reportRtcSdkApi()],BLWRTCEngine.prototype,"unsubscribeStream",1),__decorateClass([reportRtcSdkApi()],BLWRTCEngine.prototype,"setRemoteScreenVideoStreamIndex",1),__decorateClass([reportRtcSdkApi()],BLWRTCEngine.prototype,"setRemoteVideoPlayer",1),__decorateClass([reportRtcSdkApi()],BLWRTCEngine.prototype,"destroy",1);const logger=new Logger$1("VERTC",0);iDB.storeKey=`${Date.now()}-${sdkCache.getDeviceId()}`,setGlobalStats({rtc_sdk_version:Config2.VERSION,device_id:sdkCache.getDeviceId(),log_cache_key:iDB.storeKey}),setReportUrl(Config2.LOG_SERVER_URL);let ENGINE_GUID=1;const createEngine=(e,t)=>{logger.info("createEngine","Invoke VERTC.createEngine"),checkString(e,"appId");const i=(ENGINE_GUID++).toString();return createMonitor(i,{rtc_app_id:e,auto_play_policy:null==t?void 0:t.autoPlayPolicy}),new RTCEngine(e,i,t)},createBLWEngine=(e,t)=>{logger.print("createBLWEngine","Invoke VERTC.createBLWEngine"),checkString(e,"appId");const i=(ENGINE_GUID++).toString();return createMonitor(i,{rtc_app_id:e,auto_play_policy:null==t?void 0:t.autoPlayPolicy}),new BLWRTCEngine(e,i,t)},destroyEngine=e=>{if(logger.info("destroyEngine","Invoke VERTC.destroyEngine"),!(e instanceof RTCEngine))throw new SDKError(ErrorCode.INVALID_ENGINE,"Invalid engine object");e.destroy(),destroyMonitor(e.monitor)},enumerateDevices=async()=>dd.enumerateDevices(),enableDevices=async(e={video:!0,audio:!0})=>{const{video:t,audio:i}=e,r={video:!1,audio:!1},o=[];return t&&o.push(dd.getPermissions({video:!0,force:!0}).then((e=>{r.video=e.video,e.video||(r.videoExceptionError=e.reason)}))),i&&o.push(dd.getPermissions({audio:!0,force:!0}).then((e=>{r.audio=e.audio,e.audio||(r.audioExceptionError=e.reason)}))),await Promise.allSettled(o),r},enumerateAudioCaptureDevices=async()=>dd.enumerateAudioCaptureDevices(),enumerateVideoCaptureDevices=async()=>dd.enumerateVideoCaptureDevices(),enumerateAudioPlaybackDevices=async()=>dd.enumerateAudioPlaybackDevices(),getSdkVersion=()=>Config2.VERSION,isSupported2=()=>isSupported(),getSupportedCodecs2=()=>getSupportedCodecs(),setLogConfig=({logLevel:e,LogfileSize:t})=>{e&&(iDB.logLevel=e),t&&(iDB.LogfileSize=t)},downloadLog=e=>{iDB.download(e)};function stringifyParams(...e){return JSON.stringify(e.map((e=>e instanceof RTCEngine?"[ENGINE]":e)))}function reportVERTCApiCall(e,t){return function(...i){reportGlobalApiCall(t,0,stringifyParams(...i));const r=e(...i);return"function"==typeof(null==r?void 0:r.then)?r.then((e=>(reportGlobalCallback(t,0,stringifyParams(e)),e))).catch((e=>{throw reportGlobalCallback(t,e.code,e.message),e})):(reportGlobalCallback(t,0,stringifyParams(r)),r)}}class VERTC{constructor(){__publicField(this,"getSdkVersion",reportVERTCApiCall(getSdkVersion,"getSdkVersion")),__publicField(this,"createEngine",reportVERTCApiCall(createEngine,"createEngine")),__publicField(this,"createBLWEngine",reportVERTCApiCall(createBLWEngine,"createBLWEngine")),__publicField(this,"destroyEngine",reportVERTCApiCall(destroyEngine,"destroyEngine")),__publicField(this,"enumerateDevices",reportVERTCApiCall(enumerateDevices,"enumerateDevices")),__publicField(this,"enableDevices",reportVERTCApiCall(enableDevices,"enableDevices")),__publicField(this,"enumerateAudioCaptureDevices",reportVERTCApiCall(enumerateAudioCaptureDevices,"enumerateAudioCaptureDevices")),__publicField(this,"enumerateVideoCaptureDevices",reportVERTCApiCall(enumerateVideoCaptureDevices,"enumerateVideoCaptureDevices")),__publicField(this,"enumerateAudioPlaybackDevices",reportVERTCApiCall(enumerateAudioPlaybackDevices,"enumerateAudioPlaybackDevices")),__publicField(this,"getParameter",getParameter),__publicField(this,"setParameter",setParameter),__publicField(this,"isSupported",reportVERTCApiCall(isSupported2,"isSupported")),__publicField(this,"getSupportedCodecs",reportVERTCApiCall(getSupportedCodecs2,"getSupportedCodecs")),__publicField(this,"getElectronScreenSources",reportVERTCApiCall(getElectronScreenSources,"getElectronScreenSources")),__publicField(this,"events",EngineEventsTypes),__publicField(this,"ErrorCode",ErrorCode),__publicField(this,"platform","VolcEngine"),__publicField(this,"commitInfo","HEAD<59c1644*>"),__publicField(this,"downloadLog",reportVERTCApiCall(downloadLog,"downloadLog")),__publicField(this,"setLogConfig",reportVERTCApiCall(setLogConfig,"setLogConfig"))}}var index=new VERTC;export{AAC_PROFILE,AudioMixingDualMonoMode,AudioMixingType,AudioProfileType,AudioReportMode,AudioSelectionPriority,AudioSourceType,ChannelProfile,ConnectionState,EarMonitorPosition,FallbackOrRecoverReason,ForwardStreamError,ForwardStreamState,LocalMainReportMode,LogChannel,MediaType$1 as MediaType,MirrorMode,MirrorType,NetworkQuality,PublicInterpolationMode,PublicStreamType,PublishState,RTCAutoPlayPolicy,ReconnectReason,RemoteUserPriority,RoomMode,RoomProfileType,SUBTITLE_MODE,SimulcastStreamType,StreamIndex$1 as StreamIndex,StreamRemoveReason,SubscribeFallbackOption,SubscribeMode,SubscribeState,SubtitleEventType,TRANSCODING_VIDEO_CODEC,USER_ONLINE_STATUS,UserDisconnectionTag$1 as UserDisconnectionTag,UserOfflineReason,VideoCodecType,VideoRenderMode,VideoSimulcastMode,VideoSourceType,WTNPlayState,WTNPlayStateChangedReason,WTNPushState,WTNPushStateChangedReason,WTNRemoteAudioState,WTNRemoteAudioStateChangeReason,WTNRemoteVideoState,WTNRemoteVideoStateChangeReason,WTNStreamEventsTypes,index as default};