agora-rtc-sdk-ng
Version:
Agora WebRTC SDK for JavaScript
6 lines • 584 kB
JavaScript
/**
* AgoraWebSDK_N-v4.24.7-0-g26ae785a0-dirty Copyright AgoraInc.
*/
import{detectSupportPrePc as e,LocalAudioTrack as t,MicrophoneAudioTrack as i,LocalVideoTrack as n,getCompatibility as o,TrackHint as s,MixingAudioTrack as a,DEFAULT_LOCAL_AUDIO_TRACK_STATS as r,DEFAULT_LOCAL_VIDEO_TRACK_STATS as c,DEFAULT_REMOTE_AUDIO_TRACK_STATS as d,DEFAULT_REMOTE_VIDEO_TRACK_STATS as l,DEFAULT_NETWORK_QUALITY_STATS as h,CameraVideoTrack as u,detectSupportPreSub as _,detectSupportSDPEndpoint as p,VideoPlayer as E,AgoraRTCPlayer as m,audioElementPlayCenter as S,getOriginSenderConfig as f,audioTimerLoop as C,MediaElementNumStatus as R,visibilityWatcher as T,MediaElementStatus as g,RemoteAudioTrack as I,RemoteVideoTrack as v,RemoteTrackEvents as A,TrackInternalEvent as y,TrackEvents as N,StreamType as w,detectSupportInstantVideo as b,createCustomAudioTrack as O,LocalTrack as D,TrackMediaType as P,isLowStreamParameter as L,autoPlayGestureEventEmitter as k,deviceManager as M,DeviceManagerEvent as U,audioContextState as V,AUDIO_CONTEXT_EVENT as x,__TRACK_LIST__ as F}from"@agora-js/media";export{RemoteStreamFallbackType,RemoteStreamType,__TRACK_LIST__,audioContextState,audioElementPlayCenter,createBufferSourceAudioTrack,createCameraVideoTrack,createCustomAudioTrack,createCustomVideoTrack,createMicrophoneAndCameraTracks,createMicrophoneAudioTrack,createScreenVideoTrack,getElectronScreenSources}from"@agora-js/media";import{logger as B,AgoraRTCError as j,report as G,AgoraRTCErrorCode as W,isConfigBlocked as H,EventReportAlarmType as K,EventReportAlarmStatus as Y,onConfigApplied as q,AgoraRTCEvent as J,AgoraRTCEventUploadType as X,apiInvoke as Q,isEventCustomReportParams as z}from"@agora-js/report";import{MUTABLE_PARAMS as Z,MUTABLE_PARAMS_LOCAL_CACHE as $,MUTABLE_GATEWAY_PARAMS as ee,CONFIG_DISTRIBUTE_TYPE as te,MUTABLE_REALTIME_PARAMS as ie,AgoraRTCErrorCode as ne,isValidString as oe,checkValidString as se,IS_GLOBAL_VERSION as ae,EventEmitter as re,getParameter as ce,createDefer as de,isMacOS as le,isFirefox as he,PromiseMutex as ue,NETWORK_STATE as _e,networkIndicator as pe,NETWORK_INDICATOR_EVENTS as Ee,AgoraRTCError as me,getRetryWaitTime as Se,wait as fe,emitAsPromise as Ce,emitAsInvokerNoResponse as Re,Rolling as Te,ConnectionDisconnectedReason as ge,WebSocketQuitReason as Ie,getRandomString as ve,emitAsInvoker as Ae,DEFAULT_TURN_CONFIG as ye,SHA256 as Ne,ScalabilityMode as we,parseSdp as be,jsonClone as Oe,printSdp as De,getBrowserInfo as Pe,BrowserName as Le,BrowserOS as ke,withTimeout as Me,nextTick as Ue,setParameter as Ve,getUTF8StringByteLength as xe,getMultiUnilbsFormDataByteLength as Fe,AgoraAPIName as Be,AgoraAPITag as je,retryable as Ge,loadInstallId as We,VERSION as He,DEFAULT_RETRY_CONFIG as Ke,isJsonEqual as Ye,isSafari as qe,isChromeBelow90 as Je,isAboveChrome as Xe,isAboveEdge as Qe,isWebKit as ze,isChrome as Ze,isFirefoxVersion as $e,isBelowIOS14_6 as et,VideoCodec as tt,OVERUSE_DETECTOR_PARAMS as it,QualityLimitationReason as nt,isAboveIOS as ot,isBelowIOS as st,isAboveSafari as at,isBelowSafari as rt,isChromeKernel as ct,isRTCIceServerList as dt,createWebRTCStatsFilter as lt,DEFAULT_CANDIDATE_STATS as ht,noop as ut,PeerConnectionState as _t,compareArray as pt,emitAsPromiseNoResponse as Et,isMobile as mt,getUniqueList as St,ClientEvents as ft,isWkWebview as Ct,runOnce as Rt,generateSessionID as Tt,md5 as gt,convertStringToFixedLengthUint8Array as It,base64ToUint8Array as vt,uint8ArrayToBase64 as At,checkValidNumber as yt,removeItemFromList as Nt,isIOS as wt,SDKStore as bt,BUILD as Ot,isClientRoleOptions as Dt,concurrent as Pt,isHttpsEnv as Lt,supportIsSecureContext as kt,checkValidBoolean as Mt,checkValidArray as Ut,checkValidElement as Vt,encryptRSA as xt,generateIv as Ft,generateKey as Bt,ClientFallbackToHlsType as jt,checkValidEnum as Gt,SIMULCAST_STREAM_MODE as Wt,isClientRole as Ht,isTurnServerConfig as Kt,isEncryptionMode as Yt,encryptAesGcm as qt,CRYPTO_HEADER_LENGTH as Jt,decryptAesGcm as Xt,isP2PTransport as Qt,isClientConfig as zt,isAndroid as Zt,isBelowChrome as $t,isSupportedWkWebview as ei,isIpadOS as ti,isWechatBrowser as ii,isQQBrowser as ni,setBigUint64 as oi,getBigUint64 as si,generateProcessID as ai}from"@agora-js/shared";export{AgoraRTCErrorCode,AudienceLatencyLevelType,BUILD,ConnectionDisconnectedReason,VERSION,getParameter}from"@agora-js/shared";import{SERVICE_IDS as ri,getJoinV3Message as ci,getSDPEndPointPb as di,parseSDPEndPointResponseJson as li,parseSDPEndPointResponse as hi}from"@agora-js/protocol";import ui from"axios";import"formdata-polyfill";import{deflateRaw as _i,inflateRaw as pi}from"pako";const Ei=!0,mi=!1,Si=!1,fi=!1,Ci=["CHINA","GLOBAL"];const Ri=[[0,1,2,3,4,5,5],[0,2,2,3,4,5,5],[0,3,3,3,4,5,5],[0,4,4,4,4,5,5],[0,5,5,5,5,5,5]],Ti=[],gi=[];function Ii(e,t){return!!t&&Ti.some((i=>i.uid===e&&i.channelName===t))}function vi(){return gi.length>0}function Ai(e,t){this.v=e,this.k=t}function yi(e,t,i,n,o){var s={};return Object.keys(n).forEach((function(e){s[e]=n[e]})),s.enumerable=!!s.enumerable,s.configurable=!!s.configurable,("value"in s||s.initializer)&&(s.writable=!0),s=i.slice().reverse().reduce((function(i,n){return n(e,t,i)||i}),s),o&&void 0!==s.initializer&&(s.value=s.initializer?s.initializer.call(o):void 0,s.initializer=void 0),void 0===s.initializer?(Object.defineProperty(e,t,s),null):s}function Ni(e,t){(null==t||t>e.length)&&(t=e.length);for(var i=0,n=Array(t);i<t;i++)n[i]=e[i];return n}function wi(e){var t={},i=!1;function n(t,n){return i=!0,n=new Promise((function(i){i(e[t](n))})),{done:!1,value:new Ai(n,1)}}return t["undefined"!=typeof Symbol&&Symbol.iterator||"@@iterator"]=function(){return this},t.next=function(e){return i?(i=!1,e):n("next",e)},"function"==typeof e.throw&&(t.throw=function(e){if(i)throw i=!1,e;return n("throw",e)}),"function"==typeof e.return&&(t.return=function(e){return i?(i=!1,e):n("return",e)}),t}function bi(e){var t,i,n,o=2;for("undefined"!=typeof Symbol&&(i=Symbol.asyncIterator,n=Symbol.iterator);o--;){if(i&&null!=(t=e[i]))return t.call(e);if(n&&null!=(t=e[n]))return new Oi(t.call(e));i="@@asyncIterator",n="@@iterator"}throw new TypeError("Object is not async iterable")}function Oi(e){function t(e){if(Object(e)!==e)return Promise.reject(new TypeError(e+" is not an object."));var t=e.done;return Promise.resolve(e.value).then((function(e){return{value:e,done:t}}))}return Oi=function(e){this.s=e,this.n=e.next},Oi.prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(e){var i=this.s.return;return void 0===i?Promise.resolve({value:e,done:!0}):t(i.apply(this.s,arguments))},throw:function(e){var i=this.s.return;return void 0===i?Promise.reject(e):t(i.apply(this.s,arguments))}},new Oi(e)}function Di(e){return new Ai(e,0)}function Pi(e,t,i){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var n=i.call(e,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function Li(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function ki(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Li(Object(i),!0).forEach((function(t){Pi(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Li(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function Mi(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var i=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=i){var n,o,s,a,r=[],c=!0,d=!1;try{if(s=(i=i.call(e)).next,0===t){if(Object(i)!==i)return;c=!1}else for(;!(c=(n=s.call(i)).done)&&(r.push(n.value),r.length!==t);c=!0);}catch(e){d=!0,o=e}finally{try{if(!c&&null!=i.return&&(a=i.return(),Object(a)!==a))return}finally{if(d)throw o}}return r}}(e,t)||function(e,t){if(e){if("string"==typeof e)return Ni(e,t);var i={}.toString.call(e).slice(8,-1);return"Object"===i&&e.constructor&&(i=e.constructor.name),"Map"===i||"Set"===i?Array.from(e):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?Ni(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function Ui(e){return function(){return new Vi(e.apply(this,arguments))}}function Vi(e){var t,i;function n(t,i){try{var s=e[t](i),a=s.value,r=a instanceof Ai;Promise.resolve(r?a.v:a).then((function(i){if(r){var c="return"===t&&a.k?t:"next";if(!a.k||i.done)return n(c,i);i=e[c](i).value}o(!!s.done,i)}),(function(e){n("throw",e)}))}catch(e){o(2,e)}}function o(e,o){2===e?t.reject(o):t.resolve({value:o,done:e}),(t=t.next)?n(t.key,t.arg):i=null}this._invoke=function(e,o){return new Promise((function(s,a){var r={key:e,arg:o,resolve:s,reject:a,next:null};i?i=i.next=r:(t=i=r,n(e,o))}))},"function"!=typeof e.return&&(this.return=void 0)}Vi.prototype["function"==typeof Symbol&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},Vi.prototype.next=function(e){return this._invoke("next",e)},Vi.prototype.throw=function(e){return this._invoke("throw",e)},Vi.prototype.return=function(e){return this._invoke("return",e)};let xi=function(e){return e[e.ACCESS_POINT=101]="ACCESS_POINT",e[e.UNILBS=201]="UNILBS",e[e.STRING_UID_ALLOCATOR=901]="STRING_UID_ALLOCATOR",e}({}),Fi=function(e){return e[e.IIIEGAL_APPID=1]="IIIEGAL_APPID",e[e.IIIEGAL_UID=2]="IIIEGAL_UID",e[e.INTERNAL_ERROR=3]="INTERNAL_ERROR",e}({}),Bi=function(e){return e[e.INVALID_VENDOR_KEY=5]="INVALID_VENDOR_KEY",e[e.INVALID_CHANNEL_NAME=7]="INVALID_CHANNEL_NAME",e[e.INTERNAL_ERROR=8]="INTERNAL_ERROR",e[e.NO_AUTHORIZED=9]="NO_AUTHORIZED",e[e.DYNAMIC_KEY_TIMEOUT=10]="DYNAMIC_KEY_TIMEOUT",e[e.NO_ACTIVE_STATUS=11]="NO_ACTIVE_STATUS",e[e.DYNAMIC_KEY_EXPIRED=13]="DYNAMIC_KEY_EXPIRED",e[e.STATIC_USE_DYNAMIC_KEY=14]="STATIC_USE_DYNAMIC_KEY",e[e.DYNAMIC_USE_STATIC_KEY=15]="DYNAMIC_USE_STATIC_KEY",e[e.USER_OVERLOAD=16]="USER_OVERLOAD",e[e.FORBIDDEN_REGION=18]="FORBIDDEN_REGION",e[e.CANNOT_MEET_AREA_DEMAND=19]="CANNOT_MEET_AREA_DEMAND",e[e.REQ_DOWNGRADE_FALLBACK=27]="REQ_DOWNGRADE_FALLBACK",e}({}),ji=function(e){return e[e.NO_FLAG_SET=100]="NO_FLAG_SET",e[e.FLAG_SET_BUT_EMPTY=101]="FLAG_SET_BUT_EMPTY",e[e.INVALID_FALG_SET=102]="INVALID_FALG_SET",e[e.FLAG_SET_BUT_NO_RE=103]="FLAG_SET_BUT_NO_RE",e[e.INVALID_SERVICE_ID=104]="INVALID_SERVICE_ID",e[e.NO_SERVICE_AVAILABLE=200]="NO_SERVICE_AVAILABLE",e[e.NO_SERVICE_AVAILABLE_P2P=201]="NO_SERVICE_AVAILABLE_P2P",e[e.NO_SERVICE_AVAILABLE_VOICE=202]="NO_SERVICE_AVAILABLE_VOICE",e[e.NO_SERVICE_AVAILABLE_WEBRTC=203]="NO_SERVICE_AVAILABLE_WEBRTC",e[e.NO_SERVICE_AVAILABLE_CDS=204]="NO_SERVICE_AVAILABLE_CDS",e[e.NO_SERVICE_AVAILABLE_CDN=205]="NO_SERVICE_AVAILABLE_CDN",e[e.NO_SERVICE_AVAILABLE_TDS=206]="NO_SERVICE_AVAILABLE_TDS",e[e.NO_SERVICE_AVAILABLE_REPORT=207]="NO_SERVICE_AVAILABLE_REPORT",e[e.NO_SERVICE_AVAILABLE_APP_CENTER=208]="NO_SERVICE_AVAILABLE_APP_CENTER",e[e.NO_SERVICE_AVAILABLE_ENV0=209]="NO_SERVICE_AVAILABLE_ENV0",e[e.NO_SERVICE_AVAILABLE_VOET=210]="NO_SERVICE_AVAILABLE_VOET",e[e.NO_SERVICE_AVAILABLE_STRING_UID=211]="NO_SERVICE_AVAILABLE_STRING_UID",e[e.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS=212]="NO_SERVICE_AVAILABLE_WEBRTC_UNILBS",e[e.NO_SERVICE_AVAILABLE_UNILBS_FLV=213]="NO_SERVICE_AVAILABLE_UNILBS_FLV",e}({}),Gi=function(e){return e[e.K_TIMESTAMP_EXPIRED=2]="K_TIMESTAMP_EXPIRED",e[e.K_CHANNEL_PERMISSION_INVALID=3]="K_CHANNEL_PERMISSION_INVALID",e[e.K_CERTIFICATE_INVALID=4]="K_CERTIFICATE_INVALID",e[e.K_CHANNEL_NAME_EMPTY=5]="K_CHANNEL_NAME_EMPTY",e[e.K_CHANNEL_NOT_FOUND=6]="K_CHANNEL_NOT_FOUND",e[e.K_TICKET_INVALID=7]="K_TICKET_INVALID",e[e.K_CHANNEL_CONFLICTED=8]="K_CHANNEL_CONFLICTED",e[e.K_SERVICE_NOT_READY=9]="K_SERVICE_NOT_READY",e[e.K_SERVICE_TOO_HEAVY=10]="K_SERVICE_TOO_HEAVY",e[e.K_UID_BANNED=14]="K_UID_BANNED",e[e.K_IP_BANNED=15]="K_IP_BANNED",e[e.K_CHANNEL_BANNED=16]="K_CHANNEL_BANNED",e[e.DATASTREAM2_NOT_AVAILABLE=27]="DATASTREAM2_NOT_AVAILABLE",e[e.K_AUTO_REBALANCE=28]="K_AUTO_REBALANCE",e[e.K_VOS_FALLBACK=30]="K_VOS_FALLBACK",e[e.WARN_NO_AVAILABLE_CHANNEL=103]="WARN_NO_AVAILABLE_CHANNEL",e[e.WARN_LOOKUP_CHANNEL_TIMEOUT=104]="WARN_LOOKUP_CHANNEL_TIMEOUT",e[e.WARN_LOOKUP_CHANNEL_REJECTED=105]="WARN_LOOKUP_CHANNEL_REJECTED",e[e.WARN_OPEN_CHANNEL_TIMEOUT=106]="WARN_OPEN_CHANNEL_TIMEOUT",e[e.WARN_OPEN_CHANNEL_REJECTED=107]="WARN_OPEN_CHANNEL_REJECTED",e[e.WARN_REQUEST_DEFERRED=108]="WARN_REQUEST_DEFERRED",e[e.ERR_DYNAMIC_KEY_TIMEOUT=109]="ERR_DYNAMIC_KEY_TIMEOUT",e[e.ERR_NO_AUTHORIZED=110]="ERR_NO_AUTHORIZED",e[e.ERR_VOM_SERVICE_UNAVAILABLE=111]="ERR_VOM_SERVICE_UNAVAILABLE",e[e.ERR_NO_CHANNEL_AVAILABLE_CODE=112]="ERR_NO_CHANNEL_AVAILABLE_CODE",e[e.ERR_MASTER_VOCS_UNAVAILABLE=114]="ERR_MASTER_VOCS_UNAVAILABLE",e[e.ERR_INTERNAL_ERROR=115]="ERR_INTERNAL_ERROR",e[e.ERR_NO_ACTIVE_STATUS=116]="ERR_NO_ACTIVE_STATUS",e[e.ERR_INVALID_UID=117]="ERR_INVALID_UID",e[e.ERR_DYNAMIC_KEY_EXPIRED=118]="ERR_DYNAMIC_KEY_EXPIRED",e[e.ERR_STATIC_USE_DYANMIC_KE=119]="ERR_STATIC_USE_DYANMIC_KE",e[e.ERR_DYNAMIC_USE_STATIC_KE=120]="ERR_DYNAMIC_USE_STATIC_KE",e[e.ERR_NO_VOCS_AVAILABLE=2e3]="ERR_NO_VOCS_AVAILABLE",e[e.ERR_NO_VOS_AVAILABLE=2001]="ERR_NO_VOS_AVAILABLE",e[e.ERR_JOIN_CHANNEL_TIMEOUT=2002]="ERR_JOIN_CHANNEL_TIMEOUT",e[e.ERR_REPEAT_JOIN_CHANNEL=2003]="ERR_REPEAT_JOIN_CHANNEL",e[e.ERR_JOIN_BY_MULTI_IP=2004]="ERR_JOIN_BY_MULTI_IP",e[e.ERR_NOT_JOINED=2011]="ERR_NOT_JOINED",e[e.ERR_REPEAT_JOIN_REQUEST=2012]="ERR_REPEAT_JOIN_REQUEST",e[e.ERR_INVALID_VENDOR_KEY=2013]="ERR_INVALID_VENDOR_KEY",e[e.ERR_INVALID_CHANNEL_NAME=2014]="ERR_INVALID_CHANNEL_NAME",e[e.ERR_INVALID_STRINGUID=2015]="ERR_INVALID_STRINGUID",e[e.ERR_TOO_MANY_USERS=2016]="ERR_TOO_MANY_USERS",e[e.ERR_SET_CLIENT_ROLE_TIMEOUT=2017]="ERR_SET_CLIENT_ROLE_TIMEOUT",e[e.ERR_SET_CLIENT_ROLE_NO_PERMISSION=2018]="ERR_SET_CLIENT_ROLE_NO_PERMISSION",e[e.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE=2019]="ERR_SET_CLIENT_ROLE_ALREADY_IN_USE",e[e.ERR_PUBLISH_REQUEST_INVALID=2020]="ERR_PUBLISH_REQUEST_INVALID",e[e.ERR_SUBSCRIBE_REQUEST_INVALID=2021]="ERR_SUBSCRIBE_REQUEST_INVALID",e[e.ERR_NOT_SUPPORTED_MESSAGE=2022]="ERR_NOT_SUPPORTED_MESSAGE",e[e.ERR_ILLEAGAL_PLUGIN=2023]="ERR_ILLEAGAL_PLUGIN",e[e.ERR_REJOIN_TOKEN_INVALID=2024]="ERR_REJOIN_TOKEN_INVALID",e[e.ERR_REJOIN_USER_NOT_JOINED=2025]="ERR_REJOIN_USER_NOT_JOINED",e[e.ERR_INVALID_OPTIONAL_INFO=2027]="ERR_INVALID_OPTIONAL_INFO",e[e.ILLEGAL_AES_PASSWORD=2028]="ILLEGAL_AES_PASSWORD",e[e.ILLEGAL_CLIENT_ROLE_LEVEL=2029]="ILLEGAL_CLIENT_ROLE_LEVEL",e[e.ERR_TOO_MANY_BROADCASTERS=2031]="ERR_TOO_MANY_BROADCASTERS",e[e.ERR_TOO_MANY_SUBSCRIBERS=2032]="ERR_TOO_MANY_SUBSCRIBERS",e[e.ERR_LICENSE_MISSING=32769]="ERR_LICENSE_MISSING",e[e.ERR_LICENSE_EXPIRED=32771]="ERR_LICENSE_EXPIRED",e[e.ERR_LICENSE_MINUTES_EXCEEDED=32773]="ERR_LICENSE_MINUTES_EXCEEDED",e[e.ERR_LICENSE_PERIOD_INVALID=32774]="ERR_LICENSE_PERIOD_INVALID",e[e.ERR_LICENSE_MULTIPLE_SDK_SERVICE=32778]="ERR_LICENSE_MULTIPLE_SDK_SERVICE",e[e.ERR_LICENSE_ILLEGAL=32783]="ERR_LICENSE_ILLEGAL",e[e.ERR_TEST_RECOVER=9e3]="ERR_TEST_RECOVER",e[e.ERR_TEST_TRYNEXT=9001]="ERR_TEST_TRYNEXT",e[e.ERR_TEST_RETRY=9002]="ERR_TEST_RETRY",e}({}),Wi=function(e){return e.CONNECTING="connecting",e.CONNECTED="connected",e.RECONNECTING="reconnecting",e.CLOSED="closed",e}({}),Hi=function(e){return e.WS_CONNECTED="ws_connected",e.WS_RECONNECTING="ws_reconnecting",e.WS_CLOSED="ws_closed",e.WS_RECONNECT_CREATE_CONNECTION="ws_reconnect_create_connection",e.ON_BINARY_DATA="on_binary_data",e.REQUEST_RECOVER="request_recover",e.REQUEST_JOIN_INFO="request_join_info",e.REQUEST_JOIN_INFO_WITH_PRE_JOIN_RESPONSE="request_pre_join_response",e.REQUEST_REJOIN_INFO="req_rejoin_info",e.IS_P2P_DISCONNECTED="is_p2p_dis",e.DISCONNECT_P2P="dis_p2p",e.ABORT_P2P_EXECUTION="abort_p2p_execution",e.NEED_RENEW_SESSION="need-sid",e.REPORT_JOIN_GATEWAY="report_join_gateway",e.REQUEST_TIMEOUT="request_timeout",e.REQUEST_SUCCESS="request_success",e.JOIN_RESPONSE="join_response",e.PRE_CONNECT_PC="pre_connect_pc",e.DATACHANNEL_PRECONNECT="datachannel_preconnect",e.DATACHANNEL_CONNECTING="datachannel_connecting",e.DATACHANNEL_FAILBACK="datachannel_failback",e.P2P_CONNECTION="p2p_connection",e.P2P_REMOTE_CANDIDATE_UPDATE="p2p_remote_candidate_update",e.P2P_SUBSCRIBE="p2p_subscribe",e.P2P_UNSUBSCRIBE="p2p_unsubscribe",e.P2P_EXCHANGE_SDP="p2p_exchange_sdp",e.P2P_ON_ADD_VIDEO_STREAM="p2p_on_add_video_stream",e.P2P_ON_ADD_AUDIO_STREAM="p2p_on_add_audio_stream",e.RECOVER_NOTIFICATION="recover_notification",e.VOS_FALLBACK="vos_fallback",e.VOS_FALLBACK_PROMISE="vos_fallback_promise",e}({}),Ki=function(e){return e.PING="ping",e.PING_BACK="ping_back",e.JOIN="join_v3",e.REJOIN="rejoin_v3",e.LEAVE="leave",e.SET_CLIENT_ROLE="set_client_role",e.PUBLISH="publish",e.PUBLISH_DATASTREAM="publish_datastream",e.UNPUBLISH="unpublish",e.UNPUBLISH_DATASTREAM="unpublish_datastream",e.SUBSCRIBE="subscribe",e.PRE_SUBSCRIBE="pre_subscribe",e.SUBSCRIBE_DATASTREAM="subscribe_datastream",e.SUBSCRIBE_STREAMS="subscribe_streams",e.UNSUBSCRIBE="unsubscribe",e.UNSUBSCRIBE_DATASTREAM="unsubscribe_datastream",e.UNSUBSCRIBE_STREAMS="unsubscribe_streams",e.SUBSCRIBE_CHANGE="subscribe_change",e.TRAFFIC_STATS="traffic_stats",e.RENEW_TOKEN="renew_token",e.SET_DUAL_STREAM_MODE="set_dual_stream_mode",e.SWITCH_VIDEO_STREAM="switch_video_stream",e.DEFAULT_VIDEO_STREAM="default_video_stream",e.SET_FALLBACK_OPTION="set_fallback_option",e.CONFIGURE="configure",e.GATEWAY_INFO="gateway_info",e.CONTROL="control",e.SEND_METADATA="send_metadata",e.DATA_STREAM="data_stream",e.PICK_SVC_LAYER="pick_svc_layer",e.RESTART_ICE="restart_ice",e.CONNECT_PC="connect_pc",e.SET_VIDEO_PROFILE="set_video_profile",e.SET_PARAMETER="set_parameter",e.SET_RTM2_FLAG="set_rtm2_flag",e.DOWNGRADE_CODEC="downgrade_codec",e}({}),Yi=function(e){return e.WRTC_STATS="wrtc_stats",e.WS_INFLATE_DATA_LENGTH="ws_inflate_data_length",e.DENOISER_STATS="denoiser_stats",e.EXTENSION_USAGE_STATS="extension_usage_stats",e}({}),qi=function(e){return e.ON_USER_ONLINE="on_user_online",e.ON_USER_OFFLINE="on_user_offline",e.ON_STREAM_FALLBACK_UPDATE="on_stream_fallback_update",e.ON_PUBLISH_STREAM="on_publish_stream",e.ON_UPLINK_STATS="on_uplink_stats",e.ON_P2P_LOST="on_p2p_lost",e.ON_REMOVE_STREAM="on_remove_stream",e.ON_ADD_AUDIO_STREAM="on_add_audio_stream",e.ON_ADD_VIDEO_STREAM="on_add_video_stream",e.ON_TOKEN_PRIVILEGE_WILL_EXPIRE="on_token_privilege_will_expire",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="on_token_privilege_did_expire",e.ON_USER_BANNED="on_user_banned",e.ON_USER_LICENSE_BANNED="on_user_license_banned",e.ON_NOTIFICATION="on_notification",e.ON_CRYPT_ERROR="on_crypt_error",e.MUTE_AUDIO="mute_audio",e.MUTE_VIDEO="mute_video",e.UNMUTE_AUDIO="unmute_audio",e.UNMUTE_VIDEO="unmute_video",e.ON_P2P_OK="on_p2p_ok",e.RECEIVE_METADATA="receive_metadata",e.ON_DATA_STREAM="on_data_stream",e.ON_RTP_CAPABILITY_CHANGE="on_rtp_capability_change",e.ON_REMOTE_DATASTREAM_UPDATE="on_remote_datastream_update",e.ON_REMOTE_FULL_DATASTREAM_INFO="on_remote_full_datastream_info",e.ENABLE_LOCAL_VIDEO="enable_local_video",e.DISABLE_LOCAL_VIDEO="disable_local_video",e.ENABLE_LOCAL_AUDIO="enable_local_audio",e.DISABLE_LOCAL_AUDIO="disable_local_audio",e.ON_PUBLISHED_USER_LIST="on_published_user_list",e.ENABLE_MULTI_STREAM="enable_multi_stream",e.ON_USER_LIST="on_user_list",e}({}),Ji=function(e){return e.SEND_ONLY="SEND_ONLY",e.RECEIVE_ONLY="RECEIVE_ONLY",e}({}),Xi=function(e){return e.CONNECTED="websocket:connected",e.RECONNECTING="websocket:reconnecting",e.WILL_RECONNECT="websocket:will_reconnect",e.CLOSED="websocket:closed",e.FAILED="websocket:failed",e.ON_MESSAGE="websocket:on_message",e.REQUEST_NEW_URLS="websocket:request_new_urls",e.RECONNECT_CREATE_CONNECTION="websocket:reconnect_create_connection",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="websocket:on_token_privilege_did_expire",e.ON_FALLBACK="websocket:on_fallback",e}({});function Qi(e){if("string"!=typeof e||!/^[a-zA-Z0-9 \!\#\$\%\&\(\)\+\-\:\;\<\=\.\>\?\@\[\]\^\_\{\}\|\~\,]{1,64}$/.test(e))throw B.error("Invalid Channel Name ".concat(e)),new j(ne.INVALID_PARAMS,"The length must be within 64 bytes. The supported characters: a-z,A-Z,0-9,space,!, #, $, %, &, (, ), +, -, :, ;, <, =, ., >, ?, @, [, ], ^, _, {, }, |, ~, ,")}function zi(e){if(!(t=e,"number"==typeof t&&Math.floor(t)===t&&0<=t&&t<=4294967295||oe(e,1,255)))throw new j(ne.INVALID_PARAMS,"[String uid] Length of the string: [1,255]. ASCII characters only. [Number uid] The value range is [0,10000]");var t;"string"==typeof e&&B.warn("You input a string as the user ID, to ensure better end-user experience, Agora highly suggests not using a string as the user ID.")}let Zi=function(e){return e.TRANSCODE="mix_streaming",e.RAW="raw_streaming",e}({}),$i=function(e){return e.REQUEST_WORKER_MANAGER_LIST="@live_req_worker_manager",e}({});function en(e){if(!e.channelName)throw new j(ne.INVALID_PARAMS,"invalid channelName in info");if("number"!=typeof e.uid)throw new j(ne.INVALID_PARAMS,"invalid uid in info, uid must be a number");return e.token&&se(e.token,"info.token",1,2047),zi(e.uid),Qi(e.channelName),!0}let tn=function(e){return e.NETWORK_DISCONNECTED="NETWORK_DISCONNECTED",e.NETWORK_CONNECTED="NETWORK_CONNECTED",e.PACKET_JOINED_SRC_CHANNEL="PACKET_JOINED_SRC_CHANNEL",e.PACKET_JOINED_DEST_CHANNEL="PACKET_JOINED_DEST_CHANNEL",e.PACKET_SENT_TO_DEST_CHANNEL="PACKET_SENT_TO_DEST_CHANNEL",e.PACKET_RECEIVED_VIDEO_FROM_SRC="PACKET_RECEIVED_VIDEO_FROM_SRC",e.PACKET_RECEIVED_AUDIO_FROM_SRC="PACKET_RECEIVED_AUDIO_FROM_SRC",e.PACKET_UPDATE_DEST_CHANNEL="PACKET_UPDATE_DEST_CHANNEL",e.PACKET_UPDATE_DEST_CHANNEL_REFUSED="PACKET_UPDATE_DEST_CHANNEL_REFUSED",e.PACKET_UPDATE_DEST_CHANNEL_NOT_CHANGE="PACKET_UPDATE_DEST_CHANNEL_NOT_CHANGE",e}({}),nn=function(e){return e.RELAY_STATE_IDLE="RELAY_STATE_IDLE",e.RELAY_STATE_CONNECTING="RELAY_STATE_CONNECTING",e.RELAY_STATE_RUNNING="RELAY_STATE_RUNNING",e.RELAY_STATE_FAILURE="RELAY_STATE_FAILURE",e}({}),on=function(e){return e.RELAY_OK="RELAY_OK",e.SERVER_CONNECTION_LOST="SERVER_CONNECTION_LOST",e.SRC_TOKEN_EXPIRED="SRC_TOKEN_EXPIRED",e.DEST_TOKEN_EXPIRED="DEST_TOKEN_EXPIRED",e}({}),sn=function(e){return e.High="high",e.Low="low",e.Audio="audio",e.Screen="screen",e.ScreenLow="screen_low",e}({}),an=function(e){return e.DISCONNECT="disconnect",e.CONNECTION_STATE_CHANGE="connection-state-change",e.NETWORK_QUALITY="network-quality",e.STREAM_TYPE_CHANGE="stream-type-change",e.IS_P2P_DISCONNECTED="is-p2p-dis",e.DISCONNECT_P2P="dis-p2p",e.REQUEST_NEW_GATEWAY_LIST="req-gate-url",e.NEED_RENEW_SESSION="need-sid",e.REQUEST_P2P_CONNECTION_PARAMS="request-p2p-connection-params",e.JOIN_RESPONSE="join-response",e.RESET_CONNECTION_EVENTS="reset-connection-events",e.PRE_CONNECT_PC="pre-connect_pc",e.UPDATE_GATEWAY_CONFIG="update-gateway-config",e.VOS_FALLBACK="vos-fallback",e.VOS_FALLBACK_PROMISE="vos-fallback-promise",e.RESET_SIGNAL="reset-signal",e.DATACHANNEL_FAILBACK="datachannel-failback",e}({}),rn=function(e){return e.P2P_DISCONNECTED="P2P_DISCONNECTED",e.A_ROUND_WS_FAILED="A_ROUND_WS_FAILED",e.TIMEOUT="TIMEOUT",e.UNKNOWN_REASON="UNKNOWN_REASON",e}({}),cn=function(e){return e[e.Nothing=0]="Nothing",e[e.Audio=1]="Audio",e[e.LowVideo=2]="LowVideo",e[e.Video=4]="Video",e[e.Data=8]="Data",e[e.DataStream0=256]="DataStream0",e[e.DataStream1=512]="DataStream1",e[e.DataStream2=1024]="DataStream2",e[e.DataStream3=2048]="DataStream3",e[e.DataStream4=4096]="DataStream4",e[e.DataStream5=8192]="DataStream5",e[e.DataStream6=16384]="DataStream6",e[e.DataStream7=32768]="DataStream7",e}({}),dn=function(e){return e.CHINA="CHINA",e.ASIA="ASIA",e.NORTH_AMERICA="NORTH_AMERICA",e.EUROPE="EUROPE",e.JAPAN="JAPAN",e.INDIA="INDIA",e.KOREA="KOREA",e.HKMC="HKMC",e.US="US",e.OCEANIA="OCEANIA",e.SOUTH_AMERICA="SOUTH_AMERICA",e.AFRICA="AFRICA",e.OVERSEA="OVERSEA",e.GLOBAL="GLOBAL",e.EXTENSIONS="EXTENSIONS",e}({});const ln=[dn.AFRICA,dn.ASIA,dn.CHINA,dn.EUROPE,dn.GLOBAL,dn.INDIA,dn.JAPAN,dn.NORTH_AMERICA,dn.OCEANIA,dn.OVERSEA,dn.SOUTH_AMERICA];let hn=function(e){return e.CHINA="CN",e.ASIA="AS",e.NORTH_AMERICA="NA",e.EUROPE="EU",e.JAPAN="JP",e.INDIA="IN",e.KOREA="KR",e.HKMC="HK",e.US="US",e.OCEANIA="OC",e.SOUTH_AMERICA="SA",e.AFRICA="AF",e.OVERSEA="OVERSEA",e.GLOBAL="GLOBAL",e.EXTENSIONS="GLOBAL",e}({});const un={CHINA:{},ASIA:{CODE:hn.ASIA,WEBCS_DOMAIN:["ap-web-1-asia.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-asia.agora.io"],PROXY_CS:["proxy-ap-web-asia.agora.io"],CDS_AP:["cds-ap-web-asia.agora.io","cds-ap-web-asia2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-asia.agora.io","sua-ap-web-asia2.agora.io"],UAP_AP:["uap-ap-web-asia.agora.io","uap-ap-web-asia2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-asia.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-asia.agora.io"],LOG_UPLOAD_SERVER:["logservice-asia.agora.io"],PROXY_SERVER_TYPE3:["southeast-asia.webrtc-cloud-proxy.sd-rtn.com"]},NORTH_AMERICA:{CODE:hn.NORTH_AMERICA,WEBCS_DOMAIN:["ap-web-1-north-america.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-north-america.agora.io"],PROXY_CS:["proxy-ap-web-america.agora.io"],CDS_AP:["cds-ap-web-america.agora.io","cds-ap-web-america2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-america.agora.io","sua-ap-web-america2.agora.io"],UAP_AP:["uap-ap-web-america.agora.io","uap-ap-web-america2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-north-america.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-north-america.agora.io"],LOG_UPLOAD_SERVER:["logservice-north-america.agora.io"],PROXY_SERVER_TYPE3:["east-usa.webrtc-cloud-proxy.sd-rtn.com"]},EUROPE:{CODE:hn.EUROPE,WEBCS_DOMAIN:["ap-web-1-europe.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-europe.agora.io"],PROXY_CS:["proxy-ap-web-europe.agora.io"],CDS_AP:["cds-ap-web-europe.agora.io","cds-ap-web-europe2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-europe.agora.io","sua-ap-web-europe.agora.io"],UAP_AP:["uap-ap-web-europe.agora.io","uap-ap-web-europe2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-europe.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-europe.agora.io"],LOG_UPLOAD_SERVER:["logservice-europe.agora.io"],PROXY_SERVER_TYPE3:["europe.webrtc-cloud-proxy.sd-rtn.com"]},JAPAN:{CODE:hn.JAPAN,WEBCS_DOMAIN:["ap-web-1-japan.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-japan.agora.io"],PROXY_CS:["proxy-ap-web-japan.agora.io"],CDS_AP:["cds-ap-web-japan.agora.io","cds-ap-web-japan2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-japan.agora.io","sua-ap-web-japan2.agora.io"],UAP_AP:["uap-ap-web-japan.agora.io","uap-ap-web-japan2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-japan.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-japan.agora.io"],LOG_UPLOAD_SERVER:["logservice-japan.agora.io"],PROXY_SERVER_TYPE3:["japan.webrtc-cloud-proxy.sd-rtn.com"]},INDIA:{CODE:hn.INDIA,WEBCS_DOMAIN:["ap-web-1-india.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-india.agora.io"],PROXY_CS:["proxy-ap-web-india.agora.io"],CDS_AP:["cds-ap-web-india.agora.io","cds-ap-web-india2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-india.agora.io","sua-ap-web-india2.agora.io"],UAP_AP:["uap-ap-web-india.agora.io","uap-ap-web-india2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-india.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-india.agora.io"],LOG_UPLOAD_SERVER:["logservice-india.agora.io"],PROXY_SERVER_TYPE3:["india.webrtc-cloud-proxy.sd-rtn.com"]},KOREA:{CODE:hn.KOREA,WEBCS_DOMAIN:["ap-web-1-korea.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-korea.agora.io"],PROXY_CS:["proxy-ap-web-korea.agora.io"],CDS_AP:["cds-ap-web-korea.agora.io","cds-ap-web-korea2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-korea.agora.io","sua-ap-web-korea2.agora.io"],UAP_AP:["uap-ap-web-korea.agora.io","uap-ap-web-korea2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-korea.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-korea.agora.io"],LOG_UPLOAD_SERVER:["logservice-korea.agora.io"],PROXY_SERVER_TYPE3:["korea.webrtc-cloud-proxy.sd-rtn.com"]},HKMC:{CODE:hn.HKMC,WEBCS_DOMAIN:["ap-web-1-hkmc.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-hkmc.agora.io"],PROXY_CS:["proxy-ap-web-hkmc.agora.io"],CDS_AP:["cds-ap-web-hkmc.agora.io","cds-ap-web-hkmc2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-hkmc.agora.io","sua-ap-web-hkmc2.agora.io"],UAP_AP:["uap-ap-web-hkmc.agora.io","uap-ap-web-hkmc2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-hkmc.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-hkmc.agora.io"],LOG_UPLOAD_SERVER:["logservice-hkmc.agora.io"],PROXY_SERVER_TYPE3:["hkmc.webrtc-cloud-proxy.sd-rtn.com"]},US:{CODE:hn.US,WEBCS_DOMAIN:["ap-web-1-us.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-us.agora.io"],PROXY_CS:["proxy-ap-web-us.agora.io"],CDS_AP:["cds-ap-web-us.agora.io","cds-ap-web-us2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-us.agora.io","sua-ap-web-us2.agora.io"],UAP_AP:["uap-ap-web-us.agora.io","uap-ap-web-us2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-us.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-us.agora.io"],LOG_UPLOAD_SERVER:["logservice-us.agora.io"],PROXY_SERVER_TYPE3:["us.webrtc-cloud-proxy.sd-rtn.com"]},OVERSEA:{CODE:hn.OVERSEA,WEBCS_DOMAIN:["ap-web-1-oversea.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-oversea.agora.io"],PROXY_CS:["proxy-ap-web-oversea.agora.io"],CDS_AP:["cds-ap-web-oversea.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-oversea.agora.io"],UAP_AP:["uap-ap-web-oversea.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-oversea.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-oversea.agora.io"],LOG_UPLOAD_SERVER:["logservice-oversea.agora.io"],PROXY_SERVER_TYPE3:["webrtc-cloud-proxy.agora.io"]},GLOBAL:{CODE:hn.GLOBAL,WEBCS_DOMAIN:["webrtc2-ap-web-1.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["webrtc2-ap-web-3.agora.io"],PROXY_CS:["ap-proxy-1.agora.io","ap-proxy-2.agora.io"],CDS_AP:["cds-ap-web-1.agora.io","cds-ap-web-3.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-1.agora.io","sua-ap-web-3.agora.io"],UAP_AP:["uap-ap-web-1.agora.io","uap-ap-web-3.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2.agora.io"],LOG_UPLOAD_SERVER:["logservice.agora.io"],PROXY_SERVER_TYPE3:["webrtc-cloud-proxy.sd-rtn.com"]},OCEANIA:{CODE:hn.OCEANIA,WEBCS_DOMAIN:["ap-web-1-oceania.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-oceania.agora.io"],PROXY_CS:["proxy-ap-web-oceania.agora.io"],CDS_AP:["cds-ap-web-oceania.agora.io","cds-ap-web-oceania2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-oceania.agora.io","sua-ap-web-oceania2.agora.io"],UAP_AP:["uap-ap-web-oceania.agora.io","uap-ap-web-oceania2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-oceania.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-oceania.agora.io"],LOG_UPLOAD_SERVER:["logservice-oceania.agora.io"],PROXY_SERVER_TYPE3:["oceania.webrtc-cloud-proxy.sd-rtn.com"]},SOUTH_AMERICA:{CODE:hn.SOUTH_AMERICA,WEBCS_DOMAIN:["ap-web-1-south-america.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-south-america.agora.io"],PROXY_CS:["proxy-ap-web-south-america.agora.io"],CDS_AP:["cds-ap-web-south-america.agora.io","cds-ap-web-south-america2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-south-america.agora.io","sua-ap-web-south-america2.agora.io"],UAP_AP:["uap-ap-web-south-america.agora.io","uap-ap-web-south-america2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-south-america.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-south-america.agora.io"],LOG_UPLOAD_SERVER:["logservice-south-america.agora.io"],PROXY_SERVER_TYPE3:["south-america.webrtc-cloud-proxy.sd-rtn.com"]},AFRICA:{CODE:hn.AFRICA,WEBCS_DOMAIN:["ap-web-1-africa.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-africa.agora.io"],PROXY_CS:["proxy-ap-web-africa.agora.io"],CDS_AP:["cds-ap-web-africa.agora.io","cds-ap-web-africa2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-africa.agora.io","sua-ap-web-africa2.agora.io"],UAP_AP:["uap-ap-web-africa.agora.io","uap-ap-web-africa2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-africa.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-africa.agora.io"],LOG_UPLOAD_SERVER:["logservice-south-africa.agora.io"],PROXY_SERVER_TYPE3:["africa.webrtc-cloud-proxy.sd-rtn.com"]},EXTENSIONS:{}};ae&&(un.CHINA={CODE:hn.CHINA,WEBCS_DOMAIN:["webrtc2-2.ap.sd-rtn.com"],WEBCS_DOMAIN_BACKUP_LIST:["webrtc2-4.ap.sd-rtn.com"],PROXY_CS:["proxy-web.ap.sd-rtn.com"],CDS_AP:["cds-web-2.ap.sd-rtn.com","cds-web-4.ap.sd-rtn.com"],ACCOUNT_REGISTER:["sua-web-2.ap.sd-rtn.com","sua-web-4.ap.sd-rtn.com"],UAP_AP:["uap-web-2.ap.sd-rtn.com","uap-web-4.ap.sd-rtn.com"],EVENT_REPORT_DOMAIN:["web-3.statscollector.sd-rtn.com"],EVENT_REPORT_BACKUP_DOMAIN:["web-4.statscollector.sd-rtn.com"],LOG_UPLOAD_SERVER:["logservice-china.agora.io"],PROXY_SERVER_TYPE3:["east-cn.webrtc-cloud-proxy.sd-rtn.com"]});let _n=function(e){return e.UPDATE_BITRATE_LIMIT="update_bitrate_limit",e.UPDATE_CLIENT_ROLE_OPTIONS="update_client_role_options",e.UPDATE_REMOTE_VIDEO_STREAM_TYPE="update_remote_video_stream_type",e.FALLBACK_TO_HLS="fallback_to_hls",e.UPDATE_VOS_CONFIGURE="update_vos_configure",e}({});function pn(e){return!!e&&(!(!e.uplink||!e.id)&&(void 0!==e.uplink.max_bitrate&&void 0!==e.uplink.min_bitrate))}class En extends re{constructor(e,t){super(),this.onICEConnectionStateChange=void 0,this.onConnectionStateChange=void 0,this.onDTLSTransportStateChange=void 0,this.onDTLSTransportError=void 0,this.onICETransportStateChange=void 0,this.onFirstAudioReceived=void 0,this.onFirstVideoReceived=void 0,this.onFirstAudioDecoded=void 0,this.onFirstVideoDecoded=void 0,this.onFirstVideoRender=void 0,this.onFirstVideoBufferReady=void 0,this.onFirstVideoDecodedTimeout=void 0,this.onSelectedLocalCandidateChanged=void 0,this.onSelectedRemoteCandidateChanged=void 0,this.onICECandidateError=void 0,this.getLocalVideoStats=void 0}}class mn extends En{constructor(e,t){super(e,t),this.establishPromise=void 0}}let Sn=function(e){return e.VIDEO="video",e.AUDIO="audio",e}({}),fn=function(e){return e.UDP_RELAY="udp_relay",e.UDP_TCP_RELAY="udp_tcp_relay",e.TCP_RELAY="tcp_relay",e.RELAY="relay",e}({}),Cn=function(e){return e[e.FIRST_CONNECTION=0]="FIRST_CONNECTION",e[e.UDP_TCP_RESTART=1]="UDP_TCP_RESTART",e[e.RELAY_RESTART=2]="RELAY_RESTART",e[e.TCP_RESTART=3]="TCP_RESTART",e[e.OLD_FIRST_CONNECTION=10]="OLD_FIRST_CONNECTION",e[e.OLD_RESTART=11]="OLD_RESTART",e[e.DISCONNECTED_OR_FAILED=20]="DISCONNECTED_OR_FAILED",e}({});const Rn=["disconnected","failed"];let Tn=function(e){return e.LocalVideoTrack="videoTrack",e.LocalAudioTrack="audioTrack",e.LocalVideoLowTrack="videoLowTrack",e}({}),gn=function(e){return e.New="new",e.Connected="connected",e.Reconnecting="reconnecting",e.Disconnected="disconnected",e}({}),In=function(e){return e.AudioMetadata="audioMetadata",e.AudioPts="audioPts",e.StateChange="stateChange",e.IceConnectionStateChange="iceConnectionStateChange",e.RequestMuteLocal="requestMuteLocal",e.RequestUnmuteLocal="requestUnmuteLocal",e.RequestRePublish="requestRePublish",e.RequestRePublishDataChannel="requestRePublishDataChannel",e.RequestReSubscribe="requestReSubscribe",e.RequestUploadStats="requestUploadStats",e.RequestUpload="requestUpload",e.MediaReconnectStart="MediaReconnectStart",e.MediaReconnectEnd="MediaReconnectEnd",e.NeedSignalRTT="NeedSignalRTT",e.RequestRestartICE="RequestRestartIce",e.PeerConnectionStateChange="PeerConnectionStateChange",e.RequestReconnect="RequestReconnect",e.RequestReconnectPC="RequestReconnectPC",e.RequestUnpublishForReconnectPC="RequestUnpublishForReconnectPC",e.P2PLost="P2PLost",e.UpdateVideoEncoder="UpdateVideoEncoder",e.ConnectionTypeChange="ConnectionTypeChange",e.RequestLowStreamParameter="RequestLowStreamParameter",e.QueryClientConnectionState="QueryClientConnectionState",e.LocalCandidate="LocalCandidate",e.RequestP2PMuteLocal="requestP2PMuteLocal",e.RequestP2PUnPublish="RequestP2PUnPublish",e.RequestP2PUnmuteRemote="RequestP2PUnmuteRemote",e.RequestP2PMuteRemote="RequestP2PMuteRemote",e.RequestP2PRestartICE="RequestP2PRestartICE",e.FirstVideoPreRender="FirstVideoPreRender",e.FirstVideoBufferReady="FirstVideoBufferReady",e}({}),vn=function(e){return e.CONNECTING="CONNECTING",e.RECONNECTING="RECONNECTING",e.CONNECTED="CONNECTED",e.CLOSED="CLOSED",e}({}),An=function(e){return e.CONNECTION_STATE_CHANGE="connection-state-change",e.STATE_CHANGE="state-change",e.INSPECT_RESULT="inspect-result",e.CLIENT_LOCAL_VIDEO_TRACK="client-local-video-track",e.REQUEST_NEW_WORKER_URL="request-new-worker-url",e}({}),yn=function(e){return e.NETWORK_ERROR="NETWORK_ERROR",e.SERVER_ERROR="SERVER_ERROR",e.MULTI_IP="MULTI_IP",e.TIMEOUT="TIMEOUT",e.OFFLINE="OFFLINE",e.LEAVE="LEAVE",e.P2P_FAILED="P2P_FAILED",e.FALLBACK="FALLBACK",e}({}),Nn=function(e){return e.CONNECTED="transmitter:connected",e.RECONNECTING="transmitter:reconnecting",e.WILL_RECONNECT="transmitter:will_reconnect",e.CLOSED="transmitter:closed",e.FAILED="transmitter:failed",e.ON_MESSAGE="transmitter:on_message",e.REQUEST_NEW_URLS="transmitter:request_new_urls",e.RECONNECT_CREATE_CONNECTION="transmitter:reconnect_create_connection",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="transmitter:on_token_privilege_did_expire",e.TO_CONNECT_DATACHANNEL="transmitter:to_connect_datachannel",e.FAILBACK="transmitter:failback",e.PRE_CONNECT_PC="transmitter:pre_connect_pc",e}({}),wn=function(e){return e.CAMERA_CHANGED="camera-changed",e.MICROPHONE_CHANGED="microphone-changed",e.PLAYBACK_DEVICE_CHANGED="playback-device-changed",e.AUDIO_AUTOPLAY_FAILED="audio-autoplay-failed",e.AUTOPLAY_FAILED="autoplay-failed",e.AUDIO_CONTEXT_STATE_CHANGED="audio-context-state-changed",e.SECURITY_POLICY_VIOLATION="security-policy-violation",e}({}),bn=function(e){return e.CONNECTING="CONNECTING",e.RECONNECTING="RECONNECTING",e.CONNECTED="CONNECTED",e.CLOSED="CLOSED",e}({}),On=function(e){return e.CONNECTION_STATE_CHANGE="connection-state-change",e.STATE_CHANGE="state-change",e.INSPECT_RESULT="inspect-result",e.CLIENT_LOCAL_VIDEO_TRACK="client-local-video-track",e.REQUEST_NEW_WORKER_URL="request-new-worker-url",e}({}),Dn=function(e){return e.CALL="call",e.CANDIDATE="candidate",e.PUBLISH="publish",e.UNPUBLISH="unpublish",e.CONTROL="control",e.RESTART_ICE="restart_ice",e.ACK="ack",e.RESPONSE="response",e.JOIN="join",e.CHECK="check",e}({}),Pn=function(e){return e.MUTE_LOCAL_AUDIO="mute_local_audio",e.MUTE_LOCAL_VIDEO="mute_local_video",e.UNMUTE_LOCAL_AUDIO="unmute_local_audio",e.UNMUTE_LOCAL_VIDEO="unmute_local_video",e}({});const Ln={[xi.ACCESS_POINT]:{[ji.NO_FLAG_SET]:{desc:"flag is zero",retry:!1},[ji.FLAG_SET_BUT_EMPTY]:{desc:"flag is empty",retry:!1},[ji.INVALID_FALG_SET]:{desc:"invalid flag",retry:!1},[ji.FLAG_SET_BUT_NO_RE]:{desc:"flag set unilbs but no request",retry:!1},[ji.INVALID_SERVICE_ID]:{desc:"invalid service id",retry:!1},[ji.NO_SERVICE_AVAILABLE]:{desc:"no service available",retry:!0},[ji.NO_SERVICE_AVAILABLE_P2P]:{desc:"no unilbs p2p service available",retry:!0},[ji.NO_SERVICE_AVAILABLE_VOICE]:{desc:"no unilbs voice service available",retry:!0},[ji.NO_SERVICE_AVAILABLE_WEBRTC]:{desc:"no unilbs webrtc service available",retry:!0},[ji.NO_SERVICE_AVAILABLE_CDS]:{desc:"no cds service available",retry:!0},[ji.NO_SERVICE_AVAILABLE_CDN]:{desc:"no cdn dispatcher service available",retry:!0},[ji.NO_SERVICE_AVAILABLE_TDS]:{desc:"no tds service available",retry:!0},[ji.NO_SERVICE_AVAILABLE_REPORT]:{desc:"no unilbs report service available",retry:!0},[ji.NO_SERVICE_AVAILABLE_APP_CENTER]:{desc:"no app center service available",retry:!0},[ji.NO_SERVICE_AVAILABLE_ENV0]:{desc:"no unilbs sig env0 service available",retry:!0},[ji.NO_SERVICE_AVAILABLE_VOET]:{desc:"no unilbs voet service available",retry:!0},[ji.NO_SERVICE_AVAILABLE_STRING_UID]:{desc:"no string uid service available",retry:!0},[ji.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS]:{desc:"no webrtc unilbs service available",retry:!0}},[xi.UNILBS]:{[Bi.INVALID_VENDOR_KEY]:{desc:"invalid vendor key, can not find appid",retry:!1},[Bi.INVALID_CHANNEL_NAME]:{desc:"invalid channel name",retry:!1},[Bi.INTERNAL_ERROR]:{desc:"unilbs internal error",retry:!1},[Bi.NO_AUTHORIZED]:{desc:"invalid token, authorized failed",retry:!1},[Bi.DYNAMIC_KEY_TIMEOUT]:{desc:"dynamic key or token timeout",retry:!1},[Bi.NO_ACTIVE_STATUS]:{desc:"no active status",retry:!1},[Bi.DYNAMIC_KEY_EXPIRED]:{desc:"dynamic key expired",retry:!1},[Bi.STATIC_USE_DYNAMIC_KEY]:{desc:"static use dynamic key",retry:!1},[Bi.DYNAMIC_USE_STATIC_KEY]:{desc:"dynamic use static key",retry:!1},[Bi.USER_OVERLOAD]:{desc:"amount of users over load",retry:!1},[Bi.FORBIDDEN_REGION]:{desc:"the request is forbidden in this area",retry:!1},[Bi.CANNOT_MEET_AREA_DEMAND]:{desc:"unable to allocate services in this area",retry:!1},[Bi.REQ_DOWNGRADE_FALLBACK]:{desc:"request downgrade fallback",retry:!1}},[xi.STRING_UID_ALLOCATOR]:{[Fi.IIIEGAL_APPID]:{desc:"invalid appid",retry:!1},[Fi.IIIEGAL_UID]:{desc:"invalid string uid",retry:!1},[Fi.INTERNAL_ERROR]:{desc:"string uid allocator internal error",retry:!0}}};function kn(e){const t=Ln[Math.floor(e/1e4)];if(!t)return{desc:"unknown error",retry:!1};const i=t[e%1e4];if(!i){if(Math.floor(e/1e4)===xi.ACCESS_POINT){const t=e%1e4;if("1"===t.toString()[0])return{desc:e.toString(),retry:!1};if("2"===t.toString()[0])return{desc:e.toString(),retry:!0}}return{desc:"unknown error",retry:!1}}return i}const Mn={[Gi.K_TIMESTAMP_EXPIRED]:{desc:"K_TIMESTAMP_EXPIRED",action:"failed"},[Gi.K_CHANNEL_PERMISSION_INVALID]:{desc:"K_CHANNEL_PERMISSION_INVALID",action:"failed"},[Gi.K_CERTIFICATE_INVALID]:{desc:"K_CERTIFICATE_INVALID",action:"failed"},[Gi.K_CHANNEL_NAME_EMPTY]:{desc:"K_CHANNEL_NAME_EMPTY",action:"failed"},[Gi.K_CHANNEL_NOT_FOUND]:{desc:"K_CHANNEL_NOT_FOUND",action:"failed"},[Gi.K_TICKET_INVALID]:{desc:"K_TICKET_INVALID",action:"failed"},[Gi.K_CHANNEL_CONFLICTED]:{desc:"K_CHANNEL_CONFLICTED",action:"failed"},[Gi.K_SERVICE_NOT_READY]:{desc:"K_SERVICE_NOT_READY",action:"tryNext"},[Gi.K_SERVICE_TOO_HEAVY]:{desc:"K_SERVICE_TOO_HEAVY",action:"tryNext"},[Gi.K_UID_BANNED]:{desc:"K_UID_BANNED",action:"failed"},[Gi.K_IP_BANNED]:{desc:"K_IP_BANNED",action:"failed"},[Gi.DATASTREAM2_NOT_AVAILABLE]:{desc:"DATASTREAM2_NOT_AVAILABLE",action:"quit"},[Gi.K_AUTO_REBALANCE]:{desc:"k_AUTO_REBALANCE",action:"recover"},[Gi.K_VOS_FALLBACK]:{desc:"K_VOS_FALLBACK",action:"tryNext"},[Gi.ERR_INVALID_VENDOR_KEY]:{desc:"ERR_INVALID_VENDOR_KEY",action:"failed"},[Gi.ERR_INVALID_CHANNEL_NAME]:{desc:"ERR_INVALID_CHANNEL_NAME",action:"failed"},[Gi.WARN_NO_AVAILABLE_CHANNEL]:{desc:"WARN_NO_AVAILABLE_CHANNEL",action:"failed"},[Gi.WARN_LOOKUP_CHANNEL_TIMEOUT]:{desc:"WARN_LOOKUP_CHANNEL_TIMEOUT",action:"tryNext"},[Gi.WARN_LOOKUP_CHANNEL_REJECTED]:{desc:"WARN_LOOKUP_CHANNEL_REJECTED",action:"failed"},[Gi.WARN_OPEN_CHANNEL_TIMEOUT]:{desc:"WARN_OPEN_CHANNEL_TIMEOUT",action:"tryNext"},[Gi.WARN_OPEN_CHANNEL_REJECTED]:{desc:"WARN_OPEN_CHANNEL_REJECTED",action:"failed"},[Gi.WARN_REQUEST_DEFERRED]:{desc:"WARN_REQUEST_DEFERRED",action:"failed"},[Gi.ERR_DYNAMIC_KEY_TIMEOUT]:{desc:"ERR_DYNAMIC_KEY_TIMEOUT",action:"failed"},[Gi.ERR_NO_AUTHORIZED]:{desc:"ERR_NO_AUTHORIZED",action:"failed"},[Gi.ERR_VOM_SERVICE_UNAVAILABLE]:{desc:"ERR_VOM_SERVICE_UNAVAILABLE",action:"tryNext"},[Gi.ERR_NO_CHANNEL_AVAILABLE_CODE]:{desc:"ERR_NO_CHANNEL_AVAILABLE_CODE",action:"failed"},[Gi.ERR_MASTER_VOCS_UNAVAILABLE]:{desc:"ERR_MASTER_VOCS_UNAVAILABLE",action:"tryNext"},[Gi.ERR_INTERNAL_ERROR]:{desc:"ERR_INTERNAL_ERROR",action:"tryNext"},[Gi.ERR_NO_ACTIVE_STATUS]:{desc:"ERR_NO_ACTIVE_STATUS",action:"failed"},[Gi.ERR_INVALID_UID]:{desc:"ERR_INVALID_UID",action:"failed"},[Gi.ERR_DYNAMIC_KEY_EXPIRED]:{desc:"ERR_DYNAMIC_KEY_EXPIRED",action:"failed"},[Gi.ERR_STATIC_USE_DYANMIC_KE]:{desc:"ERR_STATIC_USE_DYANMIC_KE",action:"failed"},[Gi.ERR_DYNAMIC_USE_STATIC_KE]:{desc:"ERR_DYNAMIC_USE_STATIC_KE",action:"failed"},[Gi.ERR_NO_VOCS_AVAILABLE]:{desc:"ERR_NO_VOCS_AVAILABLE",action:"tryNext"},[Gi.ERR_NO_VOS_AVAILABLE]:{desc:"ERR_NO_VOS_AVAILABLE",action:"tryNext"},[Gi.ERR_JOIN_CHANNEL_TIMEOUT]:{desc:"ERR_JOIN_CHANNEL_TIMEOUT",action:"tryNext"},[Gi.ERR_JOIN_BY_MULTI_IP]:{desc:"ERR_JOIN_BY_MULTI_IP",action:"recover"},[Gi.ERR_NOT_JOINED]:{desc:"ERR_NOT_JOINED",action:"failed"},[Gi.ERR_REPEAT_JOIN_REQUEST]:{desc:"ERR_REPEAT_JOIN_REQUEST",action:"quit"},[Gi.ERR_REPEAT_JOIN_CHANNEL]:{desc:"ERR_REPEAT_JOIN_CHANNEL",action:"quit"},[Gi.ERR_INVALID_STRINGUID]:{desc:"ERR_INVALID_STRINGUID",action:"failed"},[Gi.ERR_TOO_MANY_USERS]:{desc:"ERR_TOO_MANY_USERS",action:"tryNext"},[Gi.ERR_SET_CLIENT_ROLE_TIMEOUT]:{desc:"ERR_SET_CLIENT_ROLE_TIMEOUT",action:"failed"},[Gi.ERR_SET_CLIENT_ROLE_NO_PERMISSION]:{desc:"ERR_SET_CLIENT_ROLE_TIMEOUT",action:"failed"},[Gi.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE]:{desc:"ERR_SET_CLIENT_ROLE_ALREADY_IN_USE",action:"success"},[Gi.ERR_PUBLISH_REQUEST_INVALID]:{desc:"ERR_PUBLISH_REQUEST_INVALID",action:"failed"},[Gi.ERR_SUBSCRIBE_REQUEST_INVALID]:{desc:"ERR_SUBSCRIBE_REQUEST_INVALID",action:"failed"},[Gi.ERR_NOT_SUPPORTED_MESSAGE]:{desc:"ERR_NOT_SUPPORTED_MESSAGE",action:"failed"},[Gi.ERR_ILLEAGAL_PLUGIN]:{desc:"ERR_ILLEAGAL_PLUGIN",action:"failed"},[Gi.ILLEGAL_CLIENT_ROLE_LEVEL]:{desc:"ILLEGAL_CLIENT_ROLE_LEVEL",action:"failed"},[Gi.ERR_REJOIN_TOKEN_INVALID]:{desc:"ERR_REJOIN_TOKEN_INVALID",action:"failed"},[Gi.ERR_REJOIN_USER_NOT_JOINED]:{desc:"ERR_REJOIN_NOT_JOINED",action:"failed"},[Gi.ERR_INVALID_OPTIONAL_INFO]:{desc:"ERR_INVALID_OPTIONAL_INFO",action:"quit"},[Gi.ERR_TEST_RECOVER]:{desc:"ERR_TEST_RECOVER",action:"recover"},[Gi.ERR_TEST_TRYNEXT]:{desc:"ERR_TEST_TRYNEXT",action:"recover"},[Gi.ERR_TEST_RETRY]:{desc:"ERR_TEST_RETRY",action:"recover"},[Gi.ILLEGAL_AES_PASSWORD]:{desc:"ERR_TEST_RETRY",action:"failed"},[Gi.ERR_TOO_MANY_BROADCASTERS]:{desc:"ERR_TOO_MANY_BROADCASTERS",action:"failed"},[Gi.ERR_TOO_MANY_SUBSCRIBERS]:{desc:"ERR_TOO_MANY_SUBSCRIBERS",action:"failed"},[Gi.ERR_LICENSE_ILLEGAL]:{desc:"ERR_LICENSE_ILLEGAL",action:"quit"},[Gi.ERR_LICENSE_MISSING]:{desc:"ERR_LICENSE_MISSING",action:"quit"},[Gi.ERR_LICENSE_EXPIRED]:{desc:"ERR_LICENSE_EXPIRED",action:"quit"},[Gi.ERR_LICENSE_MINUTES_EXCEEDED]:{desc:"ERR_LICENSE_MINUTES_EXCEEDED",action:"quit"},[Gi.ERR_LICENSE_PERIOD_INVALID]:{desc:"ERR_LICENSE_PERIOD_INVALID",action:"quit"},[Gi.ERR_LICENSE_MULTIPLE_SDK_SERVICE]:{desc:"ERR_LICENSE_MULTIPLE_SDK_SERVICE",action:"quit"}};function Un(e){const t=Mn[e];return t||{desc:"UNKNOWN_ERROR_".concat(e),action:"failed"}}function Vn(e,t){if("string"==typeof e)return e;const i=e.proxy,n=e.host,o=e.port;if(t){const e=ce("JOIN_GATEWAY_FALLBACK_PORT")||443;return 443===e?"wss://".concat(n,"/ws/?p=").concat(Number(o)+150):"wss://".concat(n,":").concat(e,"/ws/?p=").concat(Number(o)+150)}return i?"wss://".concat(i,"/ws/?h=").concat(n,"&p=").concat(o):"wss://".concat(n,":").concat(o)}const xn=/wss:\/\/(.+)\/ws\/\?h=(.+)&p=([0-9]+)\/?/,Fn=/wss:\/\/(.+)\/ws\/\?p=([0-9]+)\/?/,Bn=/wss:\/\/(.+):([0-9]+)\/?/,jn=/wss:\/\/(.[^\/]+)\/?/;let Gn=0;class Wn{constructor(e,t){this.id=0,this.store=void 0,this.recordIndex=void 0,this.websockets=[],this.try443PortDuration=2e3,this.forceCloseWSDuration=5e3,this.try443PortTimeout=null,this.forceCloseTimeout=null,this.isTry443PortFailed=!1,this.isNormalPortFailed=!1,this.useDoubleDomain=!1,this.useProxy=!1,this.startTime=Date.now(),this.id=++Gn,this.try443PortDuration=ce("JOIN_GATEWAY_TRY_443PORT_DURATION")||2e3,this.forceCloseWSDuration=e||5e3,this.store=t}closeAllWebsockets(){this.websockets.forEach((e=>{e.onopen=null,e.onclose=null,e.onmessage=null,e.close()})),this.websockets.length=0}clearTimeout(){this.forceCloseTimeout&&clearTimeout(this.forceCloseTimeout),this.try443PortTimeout&&clearTimeout(this.try443PortTimeout),this.forceCloseTimeout=null,this.try443PortTimeout=null}logger(){var e;const t=Date.now()-this.startTime;for(var i=arguments.length,n=new Array(i),o=0;o<i;o++)n[o]=arguments[o];B.debug("[choose-best-ws ".concat(null===(e=this.store)||void 0===e?void 0:e.clientId," ").concat(this.id,"] ").concat(t,"ms:"),...n)}createWebSocket(e,t,i){this.logger("createWebSocket:",e,{isTry443Port:t,hasTimeoutDetection:i});const n=ce("GATEWAY_DOMAINS"),o=Date.now(),s=[],a=n.find((t=>e.host.includes(t)));a||(this.useDoubleDomain=!1);const r=[];if(this.useDoubleDomain)n.forEach((i=>{r.push(Vn(ki(ki({},e),{},{host:e.host.replace(a,i)}),t))}));else{const i=ki({},e);if(t&&a){const e=n.find((e=>e!==a));e&&(i.host=i.host.replace(a,e))}r.push(Vn(i,t))}try{r.forEach((e=>{const t=new WebSocket(e);t.binaryType="arraybuffer",s.push(t),this.logger("ws is connecting:",t.url)}))}catch(n){if(this.logger("ws create failed"),s.forEach((e=>e.close())),s.length=0,this.useDoubleDomain)return this.useDoubleDomain=!1,this.createWebSocket(e,t,i);if(!t&&443!==Number(e.port))return this.createWebSocket(e,!0,i);throw new j(ne.WS_ERR,"init websocket failed! Error: ".concat(n.toString()))}const c=de();this.store&&this.store.recordJoinChannelService({urls:s.map((e=>e.url)),service:"gateway"},this.recordIndex),s.forEach((e=>{e.onopen=()=>{this.logger("onopen: ws ".concat(e.url," open cost ").concat(Date.now()-o,"ms")),this.websockets.forEach((t=>{t!==e&&(t.onopen=null,t.onclose=null,t.onmessage=null,t.close(),this.logger("close backup websocket: ".concat(t.url)))})),this.websockets.length=0,c.resolve(e)},e.onclose=i=>{this.logger("onclose: ws ".concat(e.url," closed cost ").concat(Date.now()-o,"ms state: ").concat(e.readyState));const n=s.every((e=>e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING));this.logger("".concat(t?"443":"47xx"," websocket closed, all failed: ").concat(n)),n&&(t||this.isTry443PortFailed||this.useProxy)?(this.logger("onclose: all websocket is closed, ".concat(i.reason)),c.reject({code:i.code,reason:rn.A_ROUND_WS_FAILED})):!t&&n&&!this.isNormalPortFailed&&this.try443PortTimeout&&(this.logger("all 47xx websocket is closed, try 443 port"),this.clearTimeout(),l()),t?this.isTry443PortFailed=n:this.isNormalPortFailed=n},e.onmessage=t=>this.logger("".concat(e.url," onmessage: ").concat(t.data))})),this.websockets.push(...s);const d=()=>{this.websockets.forEach((e=>e.readyState!==WebSocket.OPEN&&e.close()))},l=()=>{if(c.isResolved)return d();le()&&he()&&d(),this.createWebSocket(e,!0,!0).then((e=>{c.resolve(e)})).catch((e=>{this.isNormalPortFailed&&c.reject(e),this.logger("try 443 port to create ws failed")})),this.forceCloseTimeout=window.setTimeout((()=>{this.logger("5s timeout close un-opens, isWebsocket created: ",c.isResolved),this.forceCloseTimeout=null,d()}),this.forceCloseWSDuration)};return i||(()=>{if(t||this.useProxy)return this.logger("add 5s timeout at ".concat(t?"try-443":"proxy"," condition")),this.forceCloseTimeout=window.setTimeout((()=>{this.forceCloseTimeout=null,d()}),this.forceCloseWSDuration);this.try443PortTimeout=window.setTimeout((()=>{this.logger("2s timeout, isWebsocket created: ",c.isResolved),this.try443PortTimeout=null,l()}),this.try443PortDuration)})(),c.promise}chooseBestWebsocket(e,t,i,n){return this.useDoubleDomain=!!t,"string"==typeof e&&(e=function(e){let t,i,n;var o=Mi(e.match(xn)||[],4);if(t=o[1],i=o[2],n=o[3],!t){var s=Mi(e.match(Fn)||[],3);i=s[1],n=s[2]}if(!i||!n){var a=Mi(e.match(Bn)||[],3);i=a[1],n=a[2]}return i&&n||(i=Mi(e.match(jn)||[],2)[1]),i||B.warning("un-destructible url: ",e),{proxy:t,host:i,port:n||"443"}}(e)),this.recordIndex=n,this.useProxy=!!e.proxy,i&&this.useProxy&&(B.warn("cannot use 443 only when use proxy"),i=!1),this.createWebSocket(e,!!i,!1).finally((()=>this.clearTimeout()))}}class Hn extends re{get url(){return this.websocket&&this.websocket.url||this._websocketUrl}get reconnectMode(){return this._reconnectMode}set reconnectMode(e){["tryNext","recover"].includes(e)&&this.resetReconnectCount(e),this._reconnectMode=e}get state(){return this._state}set state(e){e!==this._state&&(this._state=e,"reconnecting"===this._state?this.emit(Xi.RECONNECTING,this.reconnectReason):"connected"===this._state?this.emit(Xi.CONNECTED):"closed"===this._state?this.emit(Xi.CLOSED):"failed"===this._state&&this.emit(Xi.FAILED))}resetReconnectCount(e){B.debug("websocket reset reconnect count, reason: "+e),this.reconnectCount=0}constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3],o=arguments.length>4&&void 0!==arguments[4]&&arguments[4],s=arguments.length>5?arguments[5]:void 0;super(),this._websocketUrl=null,this.connectionID=0,this.currentURLIndex=0,this.urls=[],this._reconnectMode="tryNext",this.reconnectReason=void 0,this._initMutex=void 0,this.name=void 0,this._state="closed",this.reconnectInterrupter=void 0,this.websocket=void 0,this.retryConfig=void 0,this.reconnectCount=0,this.forceCloseTimeout=5e3,this.onlineReconnectListener=void 0,this.useCompress=void 0,this.tryDoubleDomain=!1,this.use443PortOnly=!1,this.wsInflateLength=0,this.wsDeflateLength=0,this.closeEstablishingWs=()=>{},this.store=void 0,this.joinGatewayRecordIndex=void 0,this.store=s,this.name=e,this.retryConfig=ki({},t),this.useCompress=i,this.tryDoubleDomain=n,this.use443PortOnly=o,this._initMutex=new ue("websocket",s?s.clientId:void 0);const a=t.timeout,r=t.timeoutFactor,c=Math.max(300,Math.floor(3*a/5)),d=Math.max(1.2,Math.floor(8*r)/10);_e.ONLINE&&(this.retryConfig.timeout=c,this.retryConfig.timeoutFactor=d),pe.on(Ee.NETWORK_STATE_CHANGE,((e,t)=>{e!==t&&(this.resetReconnectCount("network state change: ".concat(t," -> ").concat(e)),e===_e.ONLINE?(this.retryConfig.timeout=c,this.retryConfig.timeoutFactor=d):(this.retryConfig.timeout=a,this.retryConfig.timeoutFactor=r))}))}getConnection(){return this.websocket||void 0}async init(t){let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const n=await this._initMutex.lock();this._reconnectMode="tryNext",this.forceCloseTimeout=i,this.urls=t,this.state="connecting";try{var o;const t=de(),i=this.urls[this.currentURLIndex];null===(o=this.store)||void 0===o||o.beforeConnect(),(e(this.store)||ce("ENABLE_JOIN_V4"))&&this.emit(Nn.PRE_CONNECT_PC),this.createWebSocketConnection(i).then(t.resolve).catch(t.reject),this.once(Xi.CLOSED,(()=>{t.reject(new me(ne.WS_DISCONNECT))})),this.once(Xi.CONNECTED,t.resolve),await t.promise}catch(e){}finally{n()}}close(e,t){if(this.currentURLIndex=0,this.resetReconnectCount("close"),this.reconnectInterrupter&&this.reconnectInterrupter(),this.websocket){this.websocket.onclose=null,this.websocket.onopen=null,this.websocket.onmessage=null;const e=this.websocket;t?setTimeout((()=>e.close()),500):e.close(),this.websocket=void 0,this._websocketUrl=null}this.state=e?"failed":"closed",this.closeEstablishingWs&&this.closeEstablishingWs()}reconnect(e,t){if(!this.websocket)return void B.warning("[".concat(this.name,"] can not reconnect, no websocket"));void 0!==e&&(this.reconnectMode=e),B.debug("[".concat(this.name,"] reconnect is triggered initiative")),"number"==typeof this.joinGatewayRecordIndex&&this.store&&this.store.recordJoinChannelService({status:"error",errors:[new Error(t)]},this.joinGatewayRecordIndex);const i=this.websocket.onclose;this.websocket.onclose=null,this.websocket.close(),i&&i.bind(this.websocket)({code:9999,reason:t})}sendMessage(e){let t=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw new me(ne.WS_ABORT,"websocket is not ready");try{t||(e=JSON.stringify(e)),this.websocket.send(e)}catch(e){throw new me(ne.WS_ERR,"send websocket message error"+e.toString())}}setWsInflateData(e){this.wsDeflateLength=this.wsDeflateLength+e.originLength,this.wsInflateLength=this.wsInflateLength+e.compressedLength}getWsInflateData(){const e=this.wsInflateLength,t=this.wsDeflateLength;return this.clearWsInflateData(),{wsInflateLength:e,wsDeflateLength:t}}clearWsInflateData(){this.wsInflateLength=0,this.wsDeflateLength=0}async createWebSocketConnection(e){var t;const i=de();this.connectionID+=1,this.joinGatewayRecordIndex=void 0;const n=e=>{var t;null===(t=this.store)||void 0===t||t.signalChannelOpen(),B.debug("[".concat(this.name,"] websocket opened:"),e),this.reconnectMode="retry",this.state="connected",this.resetReconnectCount("opened"),i.resolve()},o=async e=>{var t;if(B.debug("[".concat(this.name,"] websocket close ").concat(null===(t=this.websocket)||void 0===t?void 0:t.url,", code: ").concat(e.code,", reason: ").concat(e.reason,", current mode: ").concat(this.reconnectMode)),this.reconnectCount>=this.retryConfig.maxRetryCount)i.reject(new me(ne.WS_DISCONNECT,"websocket close: ".concat(e.code))),this.close();else{"connected"===this.state&&(this.reconnectReason=e.reason,this.state="reconnecting");const t=Re(this,Xi.WILL_RECONNECT,this.reconnectMode,e.reason)||this.reconnectMode,n=await this.reconnectWithAction(t);if("closed"===this.state)return void B.debug("[".concat(this.connectionID,"] ws is closed, no need to reconnect"));if(!n)return i.reject(new me(ne.WS_DISCONNECT,"websocket reconnect failed: ".concat(e.code))),this.close(!0);i.resolve()}},s=e=>{this.emit(Xi.ON_MESSAGE,e)},a=e=>{B.warn("[".concat(this.connectionID,"] ws open error ").concat(e))};this.websocket&&(this.websocket.onclose=null,this.websocket.close()),ce("GATEWAY_WSS_ADDRESS")&&this.name.startsWith("gateway")&&(e=ce("GATEWAY_WSS_ADDRESS")),B.debug("[".concat(this.name,"] start connect, url:"),e);const r=null===(t=this.store)||void 0===t?void 0:t.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"gateway"});try{var c;this._websocketUrl=Vn(e);const t=await this.chooseBestWebsocketConnection(e);this.websocket=t,n&&n(this.websocket.url),this.websocket.onclose=o,this.websocket.onmessage=s,this.websocket.onerror=a,null===(c=this.store)||void 0===c||c.recordJoinChannelService({endTs:Date.now(),status:"success"},r),this.joinGatewayRecordIndex=r}catch(e){const t="closed"===this.state,n=e instanceof me,s=n&&e.code===ne.WS_ABORT,a=n&&e.code===ne.WS_ERR,c=n?e.message:e&&(e.reason||e.toString());B.warning("[choose-best-ws] chooseBestWebsocket error: ".concat(c)),this.store&&this.store.recordJoinChannelService({endTs:Date.now(),status:s?"aborted":"error",errors:[e]},r),t||a?(i.reject(t?new me(ne.WS_DISCONNECT,"websocket is closed: ".concat(c)):new me(ne.WS_ERR,"init websocket failed: ".concat(c))),a&&B.error("[".concat(this.name,"] init websocket failed: ").concat(c))):o&&o(e)}return i.promise}async reconnectWithAction(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(this.reconnectCount>=this.retryConfig.maxRetryCount)return!1;if(0===this.urls.length)return!1;if("closed"===this.state)return!1;B.warning("[choose-best-ws] action: =>",e),this.onlineReconnectListener||pe.isOnline||!pe.onlineWaiter||(this.onlineReconnectListener=pe.onlineWaiter.then((()=>{this.onlineReconnectListener=void 0})));let i=!0;if(this.reconnectInterrupter=()=>i=!1,t){const t=Se(this.reconnectCount,this.retryConfig);B.debug("[".concat(this.name,"] wait ").concat(t,"ms to reconnect websocket, mode: ").concat(e)),await Promise.race([fe(t),this.onlineReconnectListener||new Promise((()=>{}))])}if("closed"===this._state||!i)return!1;this.reconnectCount+=1;const n=async(e,t)=>{this.emit(Xi.RECONNECT_CREATE_CONNECTION,t),await this.createWebSocketConnection(e)};try{if("retry"===e)await n(this.urls[this.currentURLIndex],e);else if("tryNext"===e){if(this.currentURLIndex+=1,this.currentURLIndex>=this.urls.length)return this.reconnectWithAction("recover",!1);B.debug("[".concat(this.name,"] websocket url length: ").concat(this.urls.length," current index: ").concat(this.currentURLIndex)),await n(this.urls[this.currentURLIndex],e)}else"recover"===e&&(B.debug("[".concat(this.name,"] request new urls")),this.resetReconnectCount("recover mode"),this.urls=await Ce(this,Xi.REQUEST_NEW_URLS),this.currentURLIndex=0,await n(this.urls[this.currentURLIndex],e))}catch(i){var o;B.error("[".concat(this.name,"] reconnect failed ").concat(i&&i.toString()));const n=null==i||null===(o=i.data)||void 0===o?void 0:o.desc;if(Array.isArray(n)){if(n.includes("dynamic key expired"))return this.emit(Xi.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1;if(n.includes("request downgrade fallback"))return this.emit(Xi.ON_FALLBACK),!1}return this.reconnectWithAction(e,t)}return!0}}class Kn extends Hn{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]&&arguments[2],arguments.length>3&&void 0!==arguments[3]&&arguments[3],arguments.length>4&&void 0!==arguments[4]&&arguments[4],arguments.length>5?arguments[5]:void 0)}async chooseBestWebsocketConnection(e,t){const i=de(),n=(o=this.forceCloseTimeout,s=this.store,new Wn(o,s));var o,s;this.closeEstablishingWs=()=>{B.debug("[choose-best-ws] close establishing websockets"),n.closeAllWebsockets(),i.reject(new me(ne.WS_ABORT,"choose best websocket aborted"))};const a=ce("GATEWAY_DOMAINS");return B.debug("[choose-best-ws] currentDomain: ",e,", domains: ",a,"total: ".concat(this.urls.length),"current: ".concat(this.currentURLIndex+1)),n.chooseBestWebsocket(e,this.tryDoubleDomain,this.use443PortOnly,t).then(i.resolve).catch(i.reject),i.promise.finally((()=>{this.closeEstablishingWs=void 0}))}}class Yn extends re{get connectionState(){return this._connectionState}set connectionState(e){e!==this._connectionState&&(this._connectionState=e,e===Wi.CONNECTED?this.emit(Hi.WS_CONNECTED):e===Wi.RECONNECTING?this.emit(Hi.WS_RECONNECTING,this._websocketReconnectReason):e===Wi.CLOSED&&this.emit(Hi.WS_CLOSED,this._disconnectedReason))}get currentURLIndex(){return this.websocket.currentURLIndex}get url(){return this.websocket&&this.websocket.url||null}get rtt(){return this.rttRolling.mean()}constructor(e,t){super(),this.__name__="AgoraRTCSignal",this._disconnectedReason=void 0,this._websocketReconnectReason=void 0,this._connectionState=Wi.CLOSED,this.reconnectToken=void 0,this.websocket=void 0,this.openConnectionTime=void 0,this.clientId=void 0,this.lastMsgTime=Date.now(),this.uploadCache=[],this.uploadCacheInterval=void 0,this.rttRolling=new Te(5),this.pingpongTimer=void 0,this.wsInflateDataTimer=void 0,this.pingpongTimeoutCount=0,this.ortc=void 0,this.joinResponse=void 0,this.multiIpOption=void 0,this.initError=void 0,this.spec=void 0,this.store=void 0,this.onWebsocketMessage=e=>{if(e.data instanceof ArrayBuffer)return void this.emit(Hi.ON_BINARY_DATA,e.data);const t=JSON.parse(e.data);if(this.lastMsgTime=Date.now(),Object.prototype.hasOwnProperty.call(t,"_id")){const e="res-@".concat(t._id);this.emit(e,t._result,t._message)}else if(Object.prototype.hasOwnProperty.call(t,"_type")){if(this.emit(t._type,t._message),t._type===qi.ON_NOTIFICATION&&this.handleNotification(t._message),t._type===qi.ON_USER_BANNED)switch(t._message.error_code){case 14:this.close(ge.UID_BANNED);break;case 15:this.close(ge.IP_BANNED);break;case 16:this.close(ge.CHANNEL_BANNED)}if(t._type===qi.ON_USER_LICENSE_BANNED)switch(t._message.error_code){case Gi.ERR_LICENSE_MISSING:this.close(ge.LICENSE_MISSING);break;case Gi.ERR_LICENSE_EXPIRED:this.close(ge.LICENSE_EXPIRED);break;case Gi.ERR_LICENSE_MINUTES_EXCEEDED:this.close(ge.LICENSE_MINUTES_EXCEEDED);break;case Gi.ERR_LICENSE_PERIOD_INVALID:this.close(ge.LICENSE_PERIOD_INVALID);break;case Gi.ERR_LICENSE_MULTIPLE_SDK_SERVICE:this.close(ge.LICENSE_MULTIPLE_SDK_SERVICE);break;case Gi.ERR_LICENSE_ILLEGAL:this.close(ge.LICENSE_ILLEGAL);break;default:this.close()}}},this.clientId=e.clientId,this.spec=e,this.store=t,this.websocket=new Kn("gateway-".concat(this.clientId),this.spec.retryConfig,!0,ce("JOIN_GATEWAY_USE_DUAL_DOMAIN"),ce("JOIN_GATEWAY_USE_443PORT_ONLY"),t),this.handleWebsocketEvents(),window.addEventListener("offline",(()=>{this.connectionState===Wi.CONNECTED&&this.reconnect("retry",Ie.OFFLINE)}))}async request(e,t,i,n){const o=ve(6,""),s={_id:o,_type:e,_message:t},a=this.websocket.connectionID,r=()=>new Promise(((t,i)=>{if(this.connectionState===Wi.CONNECTED)return t();const n=()=>{this.off(Hi.WS_CLOSED,o),t()},o=()=>{this.off(Hi.WS_CONNECTED,n),i(new j(ne.WS_ABORT))};this.once(Hi.WS_CONNECTED,n),this.once(Hi.WS_CLOSED,o),e!==Ki.PUBLISH&&e!==Ki.PUBLISH_DATASTREAM&&e!==Ki.SUBSCRIBE&&e!==Ki.SUBSCRIBE_DATASTREAM&&e!==Ki.UNSUBSCRIBE&&e!==Ki.UNSUBSCRIBE_DATASTREAM&&e!==Ki.UNPUBLISH&&e!==Ki.UNPUBLISH_DATASTREAM&&e!==Ki.CONTROL&&e!==Ki.RESTART_ICE||this.once(Hi.DISCONNECT_P2P,(()=>{i(new j(ne.DISCONNECT_P2P))})),e!==Ki.PUBLISH&&e!==Ki.RESTART_ICE||this.once(Hi.ABORT_P2P_EXECUTION,(()=>{i(new j(ne.DISCONNECT_P2P))}))}));if(this.connectionState!==Wi.CONNECTING&&this.connectionState!==Wi.RECONNECTING||e===Ki.JOIN||e===Ki.REJOIN||await r(),this.websocket.sendMessage(s,!0),n)return;const c=new Promise(((i,n)=>{let s=!1;const r=(n,o)=>{s=!0,i({isSuccess:"success"===n,message:o||{}}),this.off(Hi.WS_CLOSED,c),this.off(Hi.WS_RECONNECTING,c),this.emit(Hi.REQUEST_SUCCESS,e,t)};this.once("res-@".concat(o),r);const c=()=>{n(new j(ne.WS_ABORT,"type: ".concat(e))),this.off(Hi.WS_CLOSED,c),this.off(Hi.WS_RECONNECTING,c),this.off("res-@".concat(o),r)};this.once(Hi.WS_CLOSED,c),this.once(Hi.WS_RECONNECTING,c),fe(ce("SIGNAL_REQUEST_TIMEOUT")).then((()=>{this.websocket.connectionID!==a||s||(B.warning("[".concat(this.clientId,"] ws request timeout, type: ").concat(e)),this.emit(Hi.REQUEST_TIMEOUT,e,t))}))}));let d=null;try{d=await c}catch(n){if(this.connectionState===Wi.CLOSED||e===Ki.LEAVE)throw new j(ne.WS_ABORT);return!this.spec.forceWaitGatewayResponse||i?n.throw():e===Ki.JOIN||e===Ki.REJOIN?null:(await r(),await this.request(e,t))}if(d.isSuccess)return d.message;const l=Number(d.message.error_code||d.message.code),h=Un(l),u=new j(ne.UNEXPECTED_RESPONSE,"".concat(h.desc,": ").concat(d.message.error_str),{code:l,data:d.message,desc:h.desc});return"success"===h.action?d.message:(B.warning("[".concat(this.clientId,"] [").concat(this.websocket.connectionID,"] unexpected response from type ").concat(e,", error_code: ").concat(l,", message: ").concat(h.desc,", action: ").concat(h.action)),l===Gi.ERR_TOO_MANY_BROADCASTERS?e===Ki.JOIN||e===Ki.REJOIN?(this.initError=u,this.close(),u.throw()):u.throw():"failed"===h.action?u.throw():"quit"===h.action?(this.initError=u,this.close(),u.throw()):(l===Gi.ERR_JOIN_BY_MULTI_IP?(this.multiIpOption=d.message.option,B.warning("[".concat(this.clientId,"] detect multi ip, recover")),this.reconnect("recover",Ie.MULTI_IP)):this.reconnect(h.action,Ie.SERVER_ERROR),e===Ki.JOIN||e===Ki.REJOIN?null:await this.request(e,t)))}waitMessage(e,t){return new Promise((i=>{const n=o=>{(!t||t(o))&&(this.off(e,n),i(o))};this.on(e,n)}))}uploadWRTCStats(e){if(!this.store.sessionId)return void B.warn("[".concat(this.clientId,"] no session id when upload wrtc stats"));const t={lts:Date.now(),sid:this.store.sessionId,uid:this.store.intUid,stats:e};this.upload(Yi.WRTC_STATS,t)}upload(e,t){const i={_type:e,_message:t};try{this.websocket.sendMessage(i)}catch(e){const t=ce("MAX_UPLOAD_CACHE")||50;this.uploadCache.push(i),this.uploadCache.length>t&&this.uploadCache.splice(0,1),this.uploadCache.length>0&&!this.uploadCacheInterval&&(this.uploadCacheInterval=window.setInterval((()=>{if(this.connectionState!==Wi.CONNECTED)return;const e=this.uploadCache.splice(0,1)[0];0===this.uploadCache.length&&(window.clearInterval(this.uploadCacheInterval),this.uploadCacheInterval=void 0),this.upload(e._type,e._message)}),ce("UPLOAD_CACHE_INTERVAL")||2e3))}}send(e,t){const i={_type:e,_message:t};this.websocket.sendMessage(i)}init(e){return this.initError=void 0,this.multiIpOption=void 0,this.joinResponse=void 0,this.reconnectToken=void 0,this.openConnectionTime=void 0,new Promise(((t,i)=>{this.once(Hi.WS_CONNECTED,(()=>t(this.joinResponse))),this.once(Hi.WS_CLOSED,(e=>i(this.initError||new j(ne.WS_ABORT,e)))),this.connectionState=Wi.CONNECTING,this.websocket.init(e).catch(i),this.wsInflateDataTimer&&window.clearInterval(this.wsInflateDataTimer),this.wsInflateDataTimer=window.setInterval((()=>{this.handleWsInflateData()}),2e4)}))}close(e){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.wsInflateDataTimer&&(this.handleWsInflateData(),window.clearInterval(this.wsInflateDataTimer),this.wsInflateDataTimer=void 0),this.reconnectToken=void 0,this.joinResponse=void 0,this._disconnectedReason=e||ge.LEAVE,this.connectionState=Wi.CLOSED,B.debug("[".concat(this.clientId,"] ")+"will close websocket in signal"),this.websocket.close()}async join(){if(!this.joinResponse){this.emit(Hi.ABORT_P2P_EXECUTION),this.store.signalConnected();const e=await Ce(this,Hi.REQUEST_JOIN_INFO);this.store.joinReq();let t=await Ce(this,Hi.REQUEST_JOIN_INFO_WITH_PRE_JOIN_RESPONSE);if(t){B.debug("join response from pre join response");const i=await this.request(Ki.JOIN,e);i&&"ortc"in i&&(t=i)}else B.debug("join response from request join_v3"),t=await this.request(Ki.JOIN,e);if(this.ortc=null==e?void 0:e.ortc,this.store.joinRep(),!t)return this.emit(Hi.REPORT_JOIN_GATEWAY,rn.TIMEOUT,this.url||""),!1;this.joinResponse=t,this.emit(Hi.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token}return this.connectionState=Wi.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),!0}async rejoin(){if(!this.reconnectToken)throw new j(ne.UNEXPECTED_ERROR,"can not rejoin, no rejoin token");const e=Ae(this,Hi.REQUEST_REJOIN_INFO);e.token=this.reconnectToken;const t=await this.request(Ki.REJOIN,e);return!!t&&(this.connectionState=Wi.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),t.peers&&t.peers.forEach((e=>{this.emit(qi.ON_USER_ONLINE,{uid:e.uid}),e.audio&&this.emit(qi.ON_ADD_AUDIO_STREAM,{uid:e.uid,uint_id:e.uint_id,audio:!0,ssrcId:e.audio_ssrc}),e.video&&this.emit(qi.ON_ADD_VIDEO_STREAM,{uid:e.uid,uint_id:e.uint_id,video:!0,ssrcId:e.video_ssrc}),e.audio_mute?this.emit(qi.MUTE_AUDIO,{uid:e.uid}):this.emit(qi.UNMUTE_AUDIO,{uid:e.uid}),e.video_mute?this.emit(qi.MUTE_VIDEO,{uid:e.uid}):this.emit(qi.UNMUTE_VIDEO,{uid:e.uid}),e.audio_enable_local?this.emit(qi.ENABLE_LOCAL_AUDIO,{uid:e.uid}):this.emit(qi.DISABLE_LOCAL_AUDIO,{uid:e.uid}),e.video_enable_local?this.emit(qi.ENABLE_LOCAL_VIDEO,{uid:e.uid}):this.emit(qi.DISABLE_LOCAL_VIDEO,{uid:e.uid}),e.audio||e.video||this.emit(qi.ON_REMOVE_STREAM,{uid:e.uid,uint_id:e.uint_id})})),!0)}reconnect(e,t){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.websocket.reconnect(e,t)}async downgradeCodec(e){if(!this.ortc)return!1;const t={downgrade_codec:e,ortc:this.ortc};return!!await this.request(Ki.DOWNGRADE_CODEC,t)}handleNotification(e){B.debug("[".concat(this.clientId,"] receive notification: "),e);const t=Un(e.code);if(28===e.code&&"detail"in e&&(B.info("[".concat(this.clientId,"] receive recover notification: "),e.detail),this.emit(Hi.RECOVER_NOTIFICATION,e.detail)),"success"!==t.action){if("failed"!==t.action)return"quit"===t.action?e.code===Gi.ERR_REPEAT_JOIN_CHANNEL&&ce("IGNORE_UID_CHECK")?void this.close(ge.UID_CONFLICT):("ERR_REPEAT_JOIN_CHANNEL"===t.desc&&this.close(ge.UID_BANNED),void this.close()):e.code===Gi.K_VOS_FALLBACK&&"detail"in e?(B.info("[".concat(this.clientId,"] receive vos fallback notification: "),e.detail),"FALLBACKCN"===e.detail&&ce("ENABLE_QUALITY_FALLBACK")?void Ce(this,Hi.VOS_FALLBACK_PROMISE,e.detail).then((()=>{this.reconnect("recover",t.desc)})).catch((e=>{B.debug("[".concat(this.clientId,"] cancel vos fallback cn, error: "),e)})):"fallback_hls"===e.detail&&ce("ENABLE_FALLBACK_TO_HLS")?(this.emit(Hi.VOS_FALLBACK,e.detail),void this.close(ge.FALLBACK_TO_HLS)):this.reconnect(t.action,t.desc)):void this.reconnect(t.action,Ie.SERVER_ERROR);B.error("[".concat(this.clientId,"] ignore error: "),t.desc)}}handlePingPong(){if(!this.websocket||"connected"!==this.websocket.state)return;this.pingpongTimeoutCount>0&&this.rttRolling.add(3e3),this.pingpongTimeoutCount+=1;const e=ce("PING_PONG_TIME_OUT"),t=Date.now();this.pingpongTimeoutCount>=e&&(B.warning("[".concat(this.clientId,"] PING-PONG Timeout. Last Socket Message: ").concat(t-this.lastMsgTime,"ms")),t-this.lastMsgTime>ce("WEBSOCKET_TIMEOUT_MIN"))?this.reconnect("retry",Ie.TIMEOUT):this.request(Ki.PING,void 0,!0).then((()=>{this.pingpongTimeoutCount=0;const e=Date.now()-t;this.rttRolling.add(e),ce("REPORT_STATS")&&this.send(Ki.PING_BACK,{pingpongElapse:e})})).catch((e=>{}))}handleWsInflateData(){const e=this.websocket.getWsInflateData(),t=e.wsInflateLength,i=e.wsDeflateLength;0!==t&&0!==i&&this.upload(Yi.WS_INFLATE_DATA_LENGTH,{ws_deflate_length:i,ws_inflate_length:t})}handleWebsocketEvents(){this.websocket.on(Xi.RECONNECT_CREATE_CONNECTION,(e=>{this.emit(Hi.WS_RECONNECT_CREATE_CONNECTION,e)})),this.websocket.on(Xi.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(Xi.CLOSED,(()=>{this.connectionState=Wi.CLOSED})),this.websocket.on(Xi.FAILED,(()=>{this._disconnectedReason=ge.NETWORK_ERROR,this.connectionState=Wi.CLOSED})),this.websocket.on(Xi.RECONNECTING,(e=>{this._websocketReconnectReason=e,this.joinResponse=void 0,this.connectionState===Wi.CONNECTED?this.connectionState=Wi.RECONNECTING:this.connectionState=Wi.CONNECTING})),this.websocket.on(Xi.WILL_RECONNECT,((e,t,i)=>{const n=Ae(this,Hi.IS_P2P_DISCONNECTED),o=n||"retry"!==e;n&&"retry"===e&&(B.debug("".concat(this.clientId," reconnect mode is retry, but p2p lost, change to tryNext")),e="tryNext",t=rn.P2P_DISCONNECTED),o&&(B.debug("".concat(this.clientId," will renewSession, reconnect mode: ").concat(e)),this.emit(Hi.REPORT_JOIN_GATEWAY,t||rn.UNKNOWN_REASON,this.url||""),this.reconnectToken=void 0,this.emit(Hi.DISCONNECT_P2P)),i(e)})),this.websocket.on(Xi.CONNECTED,(()=>{this.openConnectionTime=Date.now(),this.reconnectToken?this.rejoin().catch((e=>{B.warning("[".concat(this.clientId,"] rejoin failed ").concat(e)),this.reconnect("tryNext",Ie.SERVER_ERROR)})):this.join().catch((e=>{if(this.emit(Hi.REPORT_JOIN_GATEWAY,e,this.url||""),e instanceof j){if(e.code===ne.UNEXPECTED_RESPONSE&&e.data.code===Gi.ERR_NO_AUTHORIZED)return this.initError=new j(ne.TOKEN_EXPIRE,"dynamic key expired"),void this.close(ge.TOKEN_EXPIRE);B.error("[".concat(this.clientId,"] join gateway request failed"),e.toString()),this.spec.forceWaitGatewayResponse?this.reconnect("tryNext",Ie.SERVER_ERROR):(this.initError=e,this.close())}}))})),this.websocket.on(Xi.REQUEST_NEW_URLS,((e,t)=>{Ce(this,Hi.REQUEST_RECOVER,this.multiIpOption).then(e).catch(t)})),this.websocket.on(Xi.ON_TOKEN_PRIVILEGE_DID_EXPIRE,(()=>{this.emit(qi.ON_TOKEN_PRIVILEGE_DID_EXPIRE)})),this.websocket.on(Nn.PRE_CONNECT_PC,(()=>{this.emit(Hi.PRE_CONNECT_PC)})),this.websocket.on(Xi.ON_FALLBACK,(()=>{ce("ENABLE_FALLBACK_TO_HLS")&&this.emit(Hi.VOS_FALLBACK,"fallback_hls")}))}}let qn=0;function Jn(e){const t=ce("TURN_DOMAINS");qn=(qn+1)%t.length;const i=t[qn]||"edge.agora.io";return e.match(/^[\.\:\d]+$/)?"".concat(e.replace(/[^\d]/g,"-"),".").concat(i):(B.debug("Cannot recognized as ip address: ".concat(e,", use as host2")),e)}function Xn(e){try{const t=ce("TURN_DOMAINS"),i=ce("GATEWAY_DOMAINS").concat(t).find((t=>e.includes(t)));if(i){return e.split(".".concat(i))[0].replace(/-/g,".")}return e}catch(t){return B.debug("serverUrlToIp error, fallback to url",e),e}}function Qn(e,t){e.addresses||(e.addresses=[]);const i=function(e,t){if(ce("CONNECT_GATEWAY_WITHOUT_DOMAIN"))return e.map((e=>{let t=e.ip,i=e.port;return{address:"".concat(t,":").concat(i)}}));const i=ce("GATEWAY_DOMAINS");let n=i[1]&&t.includes(i[1])?1:0;return e.map((e=>{let t=e.domain_prefix,o=e.port,s=e.ip;if(t)return{address:"".concat(t,".").concat(i[n++%i.length],":").concat(o)};const a=/^[\.\:\d]+$/.test(s),r=a?"".concat(s.replace(/[^\d]/g,"-"),".").concat(i[n++%i.length],":").concat(o):"".concat(s,":").concat(o);return a||B.debug("Cannot recognized as ip address: ".concat(s,", use as host3")),{ip:s,port:o,address:r}}))}(e.addresses,t),n=Array.isArray(e.detail)&&e.detail[18];if(n&&"string"==typeof n){const e=n.split(";");for(let t=0;t<e.length;t++){const n=e[t].trim();i[t]&&n&&(i[t].ip6=n)}}const o=e.detail&&e.detail.candidate;let s;if(o){const e=Mi(o.split(":"),2),t=e[0],i=e[1];t&&i&&(s={port:Number(i),ip:t,address:"".concat(t,":").concat(i)})}return{gatewayAddrs:i,apGatewayAddress:s,uid:e.uid,cid:e.cid,cert:e.cert,vid:e.detail&&e.detail[8],uni_lbs_ip:e.detail&&e.detail[1],res:e,csIp:e.detail&&e.detail[502]}}function zn(e){return"number"==typeof e?e:e.exact||e.ideal||e.max||e.min||0}function Zn(e){const t=e._encoderConfig;if(!t)return{};const i={resolution:t.width&&t.height?"".concat(zn(t.width),"x").concat(zn(t.height)):void 0,maxVideoBW:t.bitrateMax,minVideoBW:t.bitrateMin};return"number"==typeof t.frameRate?(i.maxFrameRate=t.frameRate,i.minFrameRate=t.frameRate):t.frameRate&&(i.maxFrameRate=t.frameRate.max||t.frameRate.ideal||t.frameRate.exact||t.frameRate.min,i.minFrameRate=t.frameRate.min||t.frameRate.ideal||t.frameRate.exact||t.frameRate.max),i}function $n(e){return e>=0&&e<.17?1:e>=.17&&e<.36?2:e>=.36&&e<.59?3:e>=.59&&e<=1?4:e>1?5:0}function eo(e,t){let i,n,o;switch(t){case ri.CHOOSE_SERVER:n=4096,o="choose server";break;case ri.CLOUD_PROXY:n=1048576,o="proxy";break;case ri.CLOUD_PROXY_5:n=4194304,o="proxy5";break;case ri.CLOUD_PROXY_FALLBACK:n=4194310,o="proxy fallback";break;default:throw new j(ne.UNEXPECTED_ERROR,"multi unlibs response transformer get unknown service id",{csIp:e.detail&&e.detail[502],retry:!1})}if(e.response_body.forEach((t=>{t.buffer&&t.buffer.flag===n&&(i={code:t.buffer.code,addresses:(t.buffer.edges_services||[]).map((e=>ki(ki({},e),{},{ticket:t.buffer.cert}))),server_ts:e.enter_ts,uid:t.buffer.uid,cid:t.buffer.cid,cname:t.buffer.cname,detail:ki(ki({},t.buffer.detail),e.detail),flag:t.buffer.flag,opid:e.opid,cert:t.buffer.cert,signalResponse:"signalResponse"in e?e.signalResponse:void 0})})),!i)throw new j(ne.MULTI_UNILBS_RESPONSE_ERROR,"cannot parse response ".concat(o," from multi unilbs response"),{csIp:e.detail&&e.detail[502]});return i}async function to(e,t){return await Promise.all(e.addresses.map((async e=>({address:Jn(e.ip),tcpport:e.port,udpport:e.port,username:t&&ce("ENCRYPT_PROXY_USERNAME_AND_PSW")&&window.isSecureContext?t.toString():ye.username,password:t&&ce("ENCRYPT_PROXY_USERNAME_AND_PSW")&&window.isSecureContext?await Ne(t.toString()):ye.password}))))}function io(e,t){const i=t.getMediaStreamTrack(!0).getSettings(),n=t.videoHeight||i.height,o=t.videoWidth||i.width;return n&&o?Math.max(Math.min(n,o)/Math.min(zn(e.height),zn(e.width)),1):(B.warning("can't get ori-track's height, default scale down 4 times for low stream"),4)}function no(e){let t=e.candidateType,i=e.relayProtocol,n=e.type,o=e.address,s=e.port;const a={candidateType:t,relayProtocol:i,protocol:e.protocol};if("local-candidate"!==n){const e=o.split(".");e.length>=4&&(e[1]="*",e[2]="*"),a.address=e.join("."),a.port=s}return a}function oo(e){const t=e.split(":"),i=e.split(/[-.]/),n=e.includes("-")?"-":".";let o=e;return t.length>1?i.length>1?(i[1]="**",o=i[0]+n+"**:"+t[t.length-1]):o=t.length>2?t[0]+n+"**:"+t[t.length-1]:"**:"+t[t.length-1]:i.length>1&&(o=i[0]+n+"**"),o}function so(e,t){return e.getTransceivers().find((e=>e.sender.track===t||e.receiver.track===t))}function ao(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ce("SVC_MODE");if(ce("ENABLE_SVC"))return function(e){return e in we}(e)?e:we.L1T3}const ro={[Sn.VIDEO]:[{key:"abs-send-time",extensionName:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"},{key:"video-orientation",extensionName:"urn:3gpp:video-orientation"},{key:"draft-holmer-rmcat-transport-wide-cc-extensions-01",extensionName:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"},{key:"playout-delay",extensionName:"http://www.webrtc.org/experiments/rtp-hdrext/playout-delay"},{key:"video-content-type",extensionName:"http://www.webrtc.org/experiments/rtp-hdrext/video-content-type"},{key:"color-space",extensionName:"http://www.webrtc.org/experiments/rtp-hdrext/color-space"},{key:"video-timing",extensionName:"http://www.webrtc.org/experiments/rtp-hdrext/video-timing"}],[Sn.AUDIO]:[{key:"ssrc-audio-level",extensionName:"urn:ietf:params:rtp-hdrext:ssrc-audio-level"},{key:"draft-holmer-rmcat-transport-wide-cc-extensions-01",extensionName:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"},{key:"abs-send-time",extensionName:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"}]};function co(e){e.send&&(uo(Sn.VIDEO,e.send.videoExtensions),uo(Sn.AUDIO,e.send.audioExtensions)),e.recv&&(uo(Sn.VIDEO,e.recv.videoExtensions),uo(Sn.AUDIO,e.recv.audioExtensions)),e.sendrecv&&(uo(Sn.VIDEO,e.sendrecv.videoExtensions),uo(Sn.AUDIO,e.sendrecv.audioExtensions))}function lo(e,t){e.send&&(ho(Sn.VIDEO,e.send.videoExtensions,t.send.videoExtensions),ho(Sn.AUDIO,e.send.audioExtensions,t.send.audioExtensions)),e.recv&&(ho(Sn.VIDEO,e.recv.videoExtensions,t.recv.videoExtensions),ho(Sn.AUDIO,e.recv.audioExtensions,t.recv.audioExtensions))}function ho(e,t,i){t.forEach((t=>{const n=ro[e].find((e=>{let i=e.key;return t.extensionName.includes(i)}));if(!n)return;const o=i.find((e=>e.extensionName.includes(n.key)));o&&o.extensionName.includes("gdpr_forbidden")&&(t.extensionName=o.extensionName)}))}function uo(e,t){t.forEach((t=>{const i=ro[e].find((e=>{let i=e.key;return t.extensionName.includes(i)}));t.extensionName.includes("gdpr_forbidden")&&i&&(t.extensionName=i.extensionName)}))}function _o(e){return"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"===e||e.includes("abs-send-time")}function po(e){return"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"===e||e.includes("draft-holmer-rmcat-transport-wide-cc-extensions-01")}function Eo(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=arguments.length>3?arguments[3]:void 0;const o=t.filterRTX,s=t.filterVideoFec,a=t.filterAudioFec,r=t.filterAudioCodec,c=t.filterVideoCodec,d=t.unsupportedVideoUplinkCodec,l=t.unsupportedVideoDownlinkCodec,h=i.useXR;let u=[],_=[],p=[],E=[],m=!1,S=!1;if(be(e).mediaDescriptions.forEach((e=>{n&&n!==e.attributes.direction||("video"!==e.media.mediaType||m||(_=e.attributes.payloads,E=e.attributes.extmaps,m=!0),"audio"!==e.media.mediaType||S||(u=e.attributes.payloads,p=e.attributes.extmaps,S=!0))})),!E||0===_.length)throw new Error("Cannot get video capabilities from SDP.");if(!p||0===u.length)throw new Error("Cannot get audio capabilities from SDP.");if(_.forEach((e=>{var t;null!==(t=e.rtpMap)&&void 0!==t&&t.clockRate&&(e.rtpMap.clockRate=parseInt(e.rtpMap.clockRate)),h&&e.rtcpFeedbacks.push({type:"rrtr"})})),u.forEach((e=>{var t;null!==(t=e.rtpMap)&&void 0!==t&&t.clockRate&&(e.rtpMap.clockRate=parseInt(e.rtpMap.clockRate)),h&&e.rtcpFeedbacks.push({type:"rrtr"})})),o&&(u=u.filter((e=>{var t;return"rtx"!==(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())})),_=_.filter((e=>{var t;return"rtx"!==(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())}))),s){const e=_.filter((e=>{var t;return/(red)|(ulpfec)|(flexfec)/i.test((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName)||"")})),t=Do(e,_).map((e=>e.payloadType)),i=[...e.map((e=>e.payloadType)),...t];_=_.filter((e=>!i.includes(e.payloadType)))}if(a&&(u=u.filter((e=>{var t;return!/(red)|(ulpfec)|(flexfec)/i.test((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName)||"")}))),r&&(null==r?void 0:r.length)>0&&(u=u.filter((e=>{var t;return r.includes((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())||"")}))),c&&(null==c?void 0:c.length)>0){const e=_.filter((e=>{var t;return c.includes((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())||"")}));_=e.concat(o?[]:Do(e,_))}const f=ce("UNSUPPORTED_VIDEO_CODEC");if(f&&f.length>0){const e=_.filter((e=>e.rtpMap&&f.includes(e.rtpMap.encodingName.toLowerCase()))),t=Do(e,_),i=e.concat(t).map((e=>e.payloadType));_=_.filter((e=>!i.includes(e.payloadType))),B.debug("unsupportedVideoCodec: ".concat(f,", toBeRemoved: ").concat(i))}if(d&&d.length>0&&"sendonly"===n){const e=_.filter((e=>e.rtpMap&&d.includes(e.rtpMap.encodingName.toLowerCase()))),t=Do(e,_),i=e.concat(t).map((e=>e.payloadType));_=_.filter((e=>!i.includes(e.payloadType))),B.debug("unsupportedVideoUplinkCodec: ".concat(d,", toBeRemoved: ").concat(i))}if(l&&l.length>0&&"recvonly"===n){const e=_.filter((e=>e.rtpMap&&l.includes(e.rtpMap.encodingName.toLowerCase()))),t=Do(e,_),i=e.concat(t).map((e=>e.payloadType));_=_.filter((e=>!i.includes(e.payloadType))),B.debug("unsupportedVideoDownlinkCodec: ".concat(l,", toBeRemoved: ").concat(i))}return{audioCodecs:u,videoCodecs:_,audioExtensions:p,videoExtensions:E}}function mo(e){const t=be(e);let i,n;for(const e of t.mediaDescriptions){if(!i){const t=e.attributes.iceUfrag,n=e.attributes.icePwd;if(!t||!n)throw new Error("Cannot get iceUfrag or icePwd from SDP.");i={iceUfrag:t,icePwd:n}}if(!n){const t=e.attributes.fingerprints;t.length>0&&(n={fingerprints:t})}}if(!n&&t.attributes.fingerprints.length>0&&(n={fingerprints:t.attributes.fingerprints}),!n||!i)throw new Error("Cannot get iceParameters or dtlsParameters from SDP.");return{iceParameters:i,dtlsParameters:n}}function So(e,t){const i=[],n=e.attributes.ssrcGroups.filter((e=>"FID"===e.semantic)),o=e.attributes.ssrcGroups.find((e=>"SIM"===e.semantic)),s=e.attributes.ssrcs;if(o)o.ssrcIds.forEach((e=>{var o;const s=null===(o=n.find((t=>t.ssrcIds[0]===e)))||void 0===o?void 0:o.ssrcIds[1];i.push({ssrcId:e,rtx:t?s:void 0})}));else if(n.length>0){const e=n[0].ssrcIds[0],o=n[0].ssrcIds[1];i.push({ssrcId:e,rtx:t?o:void 0})}else{if(0===s.length)throw new Error("No ssrcs found on local media description.");i.push({ssrcId:s[0].ssrcId})}return i}function fo(e,t,i){const n=e.cname;let o=[];t&&(o=Ro(t)),0===o.length&&(o=e.iceParameters.candidates.map((e=>({foundation:e.foundation,componentId:"1",transport:e.protocol,priority:e.priority.toString(),connectionAddress:e.ip,port:e.port.toString(),type:e.type,extension:{}}))),B.debug("Using candidates from gateway."));const s={fingerprints:e.dtlsParameters.fingerprints.map((e=>({hashFunction:e.algorithm,fingerprint:e.fingerprint})))},a={iceUfrag:e.iceParameters.iceUfrag,icePwd:e.iceParameters.icePwd};let r;switch(e.dtlsParameters.role){case"server":r="passive";break;case"client":r="active";break;case"auto":r="actpass"}return{dtlsParameters:s,iceParameters:a,candidates:o,rtpCapabilities:wo(e.rtpCapabilities),setup:r,cname:n,preSSRCs:Co(i)}}function Co(e){const t=[];return Array.isArray(e)&&e.length>0&&e.forEach((e=>{t.push({kind:Sn.VIDEO,ssrcMsg:[{ssrcId:e.v,rtx:e.v_rtx}],mslabel:"".concat(e.v,"_").concat(e.a)},{kind:Sn.AUDIO,ssrcMsg:[{ssrcId:e.a}],mslabel:"".concat(e.v,"_").concat(e.a)})})),t}function Ro(e){let t=[];return e.ip&&"number"==typeof e.port&&(t=[{foundation:"udpcandidate",componentId:"1",transport:"udp",priority:"2103266323",connectionAddress:e.ip,port:e.port.toString(),type:"host",extension:{}}],B.debug("Using remote candidate from AP ".concat(oo(e.ip),":").concat(e.port)),e.ip6&&(t.push({foundation:"udpcandidate",componentId:"1",transport:"udp",priority:"2103266323",connectionAddress:e.ip6,port:e.port.toString(),type:"host",extension:{}}),B.debug("Using IPV6 remote candidate from AP ".concat(oo(e.ip6),":").concat(e.port)))),t}function To(e,t,i){const n=[],o=[];return e.forEach((e=>{let s=e.ssrcId,a=e.rtx;const r=ve(8,"track-"),c={ssrcId:s,attributes:ki({label:r,mslabel:i=i||ve(10,""),msid:"".concat(i," ").concat(r)},t&&{cname:t})};if(n.push(c),void 0!==a){const e={ssrcId:a,attributes:ki({label:r,mslabel:i,msid:"".concat(i," ").concat(r)},t&&{cname:t})};n.push(e),o.push({semantic:"FID",ssrcIds:[s,a]})}})),e.length>1&&o.push({semantic:"SIM",ssrcIds:e.map((e=>e.ssrcId))}),{ssrcs:n,ssrcGroups:o}}function go(e,n){n instanceof t&&e.attributes.payloads.forEach((e=>{var t;const o=null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase();if(!o||-1===["opus","pcmu","pcma","g722"].indexOf(o))return;e.fmtp||(e.fmtp={parameters:{}}),"opus"===o&&"number"==typeof ce("OPUS_PTIME")?e.fmtp.parameters.ptime=ce("OPUS_PTIME"):e.fmtp.parameters.minptime="10",e.fmtp.parameters.useinbandfec="1";const s=n._encoderConfig;s&&("pcmu"!==o&&"pcma"!==o&&"g722"!==o&&(s.bitrate&&!he()&&(e.fmtp.parameters.maxaveragebitrate="".concat(Math.floor(1e3*s.bitrate))),s.sampleRate&&(e.fmtp.parameters.maxplaybackrate="".concat(s.sampleRate),e.fmtp.parameters["sprop-maxcapturerate"]="".concat(s.sampleRate)),s.stereo&&(e.fmtp.parameters.stereo="1",e.fmtp.parameters["sprop-stereo"]="1")),n instanceof i&&"opus"===o&&n._config.DTX&&(e.fmtp.parameters.usedtx="1"))}))}function Io(e,t,i){if(!t)return;let n,o;if("video"===e.media.mediaType?(n=i.videoExtensions,o=i.videoCodecs):(n=i.audioExtensions,o=i.audioCodecs),!0===t.twcc){const t=n.find((e=>po(e.extensionName)));if(t){const i=t.extensionName;e.attributes.extmaps.find((e=>po(e.extensionName)))||e.attributes.extmaps.push({entry:t.entry,extensionName:i});const n=function(e,t){return t.filter((t=>!!e.find((e=>e.payloadType===t.payloadType&&!!e.rtcpFeedbacks.find((e=>"transport-cc"===e.type))))))}(o,e.attributes.payloads);n.forEach((e=>{e.rtcpFeedbacks.find((e=>"transport-cc"===e.type))||e.rtcpFeedbacks.push({type:"transport-cc"})}))}}else if(!1===t.twcc){const t=e.attributes.extmaps.findIndex((e=>po(e.extensionName)));-1!==t&&e.attributes.extmaps.splice(t,1),e.attributes.payloads.forEach((e=>{const t=e.rtcpFeedbacks.findIndex((e=>"transport-cc"===e.type));-1!==t&&e.rtcpFeedbacks.splice(t,1)}))}if(!0===t.remb){const t=n.find((e=>_o(e.extensionName)));if(t){const i=t.extensionName;e.attributes.extmaps.find((e=>e.extensionName===i))||e.attributes.extmaps.push({entry:t.entry,extensionName:i});const n=function(e,t){return t.filter((t=>!!e.find((e=>e.payloadType===t.payloadType&&!!e.rtcpFeedbacks.find((e=>"goog-remb"===e.type))))))}(o,e.attributes.payloads);n.forEach((e=>{e.rtcpFeedbacks.find((e=>"goog-remb"===e.type))||e.rtcpFeedbacks.push({type:"goog-remb"})}))}}else if(!1===t.remb){const t=e.attributes.extmaps.findIndex((e=>_o(e.extensionName)));-1!==t&&e.attributes.extmaps.splice(t,1),e.attributes.payloads.forEach((e=>{const t=e.rtcpFeedbacks.findIndex((e=>"goog-remb"===e.type));-1!==t&&e.rtcpFeedbacks.splice(t,1)}))}}function vo(e,t,i){if(he())return;if("video"!==e.media.mediaType)return;if(!(t instanceof n))return;if("vp9"!==i&&"vp8"!==i)return;if("vp8"===i&&!ce("SIMULCAST"))return;if("vp9"===i&&ce("ENABLE_SVC"))return;if(void 0===t._scalabilityMode||t._scalabilityMode.numSpatialLayers<=1)return;const o="vp8"===i?2:t._scalabilityMode.numSpatialLayers,s=e.attributes.ssrcs[0],a=e.attributes.ssrcGroups.find((e=>"FID"===e.semantic&&e.ssrcIds[0]===s.ssrcId)),r={semantic:"SIM",ssrcIds:[s.ssrcId]};for(let t=1;t<o;t++)e.attributes.ssrcs.push({ssrcId:s.ssrcId+t,attributes:Oe(s.attributes)}),r.ssrcIds.push(s.ssrcId+t),a&&(e.attributes.ssrcs.push({ssrcId:a.ssrcIds[1]+t,attributes:Oe(s.attributes)}),e.attributes.ssrcGroups.push({semantic:"FID",ssrcIds:[s.ssrcId+t,a.ssrcIds[1]+t]}));e.attributes.ssrcGroups.unshift(r)}async function Ao(){try{const e=new RTCPeerConnection;e.addTransceiver("video",{direction:"sendonly",sendEncodings:[{scalabilityMode:we.L1T3}]});const t=await e.createOffer();if(!t.sdp)return void e.close();const i=be(t.sdp).mediaDescriptions[0];if(!i)return;const n=i.attributes.extmaps.find((e=>"https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension"===e.extensionName));return e.close(),n}catch(e){return}}async function yo(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=new RTCPeerConnection;i.addTransceiver("video",{direction:"sendonly"}),i.addTransceiver("audio",{direction:"sendonly"}),i.addTransceiver("video",{direction:"recvonly"}),i.addTransceiver("audio",{direction:"recvonly"});const n=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=arguments.length>2?arguments[2]:void 0;const n=Eo(i,e,t,"sendonly"),o=Eo(i,e,t,"recvonly"),s={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},a={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},r={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]};if(No(n,o,"videoExtensions",s,a,r),No(n,o,"videoCodecs",s,a,r),No(n,o,"audioExtensions",s,a,r),No(n,o,"audioCodecs",s,a,r),ce("RAISE_H264_BASELINE_PRIORITY")){const e=[],t=[];if(r.videoCodecs.forEach(((i,n)=>{var o;if("h264"===(null===(o=i.rtpMap)||void 0===o?void 0:o.encodingName.toLocaleLowerCase())){var s,a;const o=r.videoCodecs[n+1],c=o&&Vo(i,o),d=null===(s=i.fmtp)||void 0===s?void 0:s.parameters["profile-level-id"],l=null===(a=i.fmtp)||void 0===a?void 0:a.parameters["packetization-mode"];!d||d!==ce("FIRST_H264_PROFILE_LEVEL_ID")||ce("FIRST_PACKETIZATION_MODE")&&l!==ce("FIRST_PACKETIZATION_MODE")?c?t.push([i,o]):t.push([i]):c?e.push([i,o]):e.push([i])}})),e.length>0&&t.length>0){B.debug("raising H264 baseline profile priority"),r.videoCodecs.forEach(((i,n)=>{var o;if("h264"===(null===(o=i.rtpMap)||void 0===o?void 0:o.encodingName.toLocaleLowerCase())){const o=Vo(i,r.videoCodecs[n+1]),s=e.shift()||t.shift()||[];s.length>0&&(o?r.videoCodecs.splice(n,2,...s):r.videoCodecs.splice(n,1,...s))}}));const i=a.videoCodecs.filter((e=>{var t,i;return"h264"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLocaleLowerCase())&&(null===(i=e.fmtp)||void 0===i?void 0:i.parameters["profile-level-id"])!==ce("FIRST_H264_PROFILE_LEVEL_ID")}));if(i.length>0){const e=Do(i,a.videoCodecs).map((e=>e.payloadType)),t=[...i.map((e=>e.payloadType)),...e];a.videoCodecs=a.videoCodecs.filter((e=>!t.includes(e.payloadType)))}ce("FILTER_SEND_H264_BASELINE")&&(s.videoCodecs=s.videoCodecs.filter((e=>{var t,i;return!("h264"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLocaleLowerCase())&&(null===(i=e.fmtp)||void 0===i?void 0:i.parameters["profile-level-id"])!==ce("FIRST_H264_PROFILE_LEVEL_ID"))})))}return{send:s,recv:a,sendrecv:r}}return{send:s,recv:a,sendrecv:r}}(e,t,(await i.createOffer()).sdp),o=n.send,s=n.recv,a=n.sendrecv;try{i.close()}catch(e){}return{send:o,recv:s,sendrecv:a}}function No(e,t,i,n,o,s){if("videoExtensions"===i||"audioExtensions"===i){const a=[];return e[i].forEach((e=>{t[i].some(((t,i)=>{if(e.entry===t.entry&&e.extensionName===t.extensionName)return a.push(i),!0}))?s[i].push(e):n[i].push(e)})),void t[i].forEach(((e,t)=>{-1===a.indexOf(t)&&o[i].push(e)}))}if("videoCodecs"===i||"audioCodecs"===i){const a=[];return e[i].forEach((e=>{t[i].some(((t,i)=>{if(e.payloadType===t.payloadType&&JSON.stringify(e)===JSON.stringify(t))return a.push(i),!0}))?s[i].push(e):n[i].push(e)})),void t[i].forEach(((e,t)=>{-1===a.indexOf(t)&&o[i].push(e)}))}}function wo(e){const t=e.send,i=e.recv,n=e.sendrecv;if(!n){if(!t||!i)throw new Error("cannot merge rtp capabilities because one of send or recv is empty!");return{send:t,recv:i}}let o,s;return t?(o={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},o.audioCodecs=[...t.audioCodecs,...n.audioCodecs],o.videoCodecs=[...t.videoCodecs,...n.videoCodecs],o.audioExtensions=[...t.audioExtensions,...n.audioExtensions],o.videoExtensions=[...t.videoExtensions,...n.videoExtensions]):o=Oe(n),i?(s={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},s.audioCodecs=[...i.audioCodecs,...n.audioCodecs],s.videoCodecs=[...i.videoCodecs,...n.videoCodecs],s.audioExtensions=[...i.audioExtensions,...n.audioExtensions],s.videoExtensions=[...i.videoExtensions,...n.videoExtensions]):s=Oe(n),{send:o,recv:s}}function bo(e){if("audio"!==e.media.mediaType)return;e.attributes.payloads.filter((e=>{var t;return"opus"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())})).forEach((e=>{e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters.stereo="1",e.fmtp.parameters["sprop-stereo"]="1"}))}function Oo(e,t,i,n){let o=[];if(e===Sn.VIDEO){if(ce("H264_PROFILE_LEVEL_ID")&&"h264"===n&&(o=t.videoCodecs.filter((e=>(e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").includes(n)&&e&&e.fmtp&&e.fmtp.parameters["profile-level-id"]===ce("H264_PROFILE_LEVEL_ID")))),!Array.isArray(o)||0===o.length){let e=[];const s=[],a=[],r=[];if(i.videoCodecs.forEach((t=>{const i=t.rtpMap&&t.rtpMap.encodingName.toLowerCase()||"";i.includes(n)?e.push(t):i.includes("vp9")?s.push(t):i.includes("vp8")?a.push(t):i.includes("h264")&&r.push(t)})),0===e.length){let t="";0!==s.length?(e=s,t="vp9"):0!==a.length?(e=a,t="vp8"):0!==r.length&&(e=r,t="h264"),B.warning("codec ".concat(n," not included in rtpCapabilities, fallback to default payloads: ").concat(t))}0!==e.length&&(o=t.videoCodecs.filter((t=>e.some((e=>e.payloadType===t.payloadType)))))}if(0===o.length&&(B.warning("codec ".concat(n," not included in rtpCapabilities, fallback to default payloads: ").concat(t.videoCodecs[0].rtpMap&&t.videoCodecs[0].rtpMap.encodingName)),o=t.videoCodecs),ce("USE_PUB_RTX")||ce("USE_SUB_RTX")){const e=Do(o,t.videoCodecs);o=[...o,...e]}}else{o=t.audioCodecs.filter((e=>(e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").includes(n)));const e=t.audioCodecs.filter((e=>(e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").includes("red")));0===o.length&&(B.warning("codec ".concat(n," not included in rtpCapabilities, fallback to opus")),o=t.audioCodecs.filter((e=>(e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").includes("opus")))),ce("ENABLE_AUDIO_RED")&&0!==e.length&&(o=[...e,...o])}return o}function Do(e,t){const i=e.map((e=>e.payloadType.toString()));return t.filter((e=>e.rtpMap&&"rtx"===e.rtpMap.encodingName&&e.fmtp&&e.fmtp.parameters.apt&&i.includes(e.fmtp&&e.fmtp.parameters.apt)))}async function Po(e,t,i){const n=t.toString(),o=ko(n,"offer","remote","exchangeSDP");await e.setRemoteDescription({type:"offer",sdp:n});const s=await e.createAnswer();if(!s.sdp)throw new Error("cannot get answer sdp");let a=s.sdp;a=Lo(a,i||{}),null==o||o(a||""),await e.setLocalDescription({type:"answer",sdp:a})}function Lo(e,t,i){if(ce("FORBID_MODIFY_LOCAL_OFFER_SDP"))return e;const n=be(e),o=t.useXR;return n.mediaDescriptions.forEach((e=>{e.attributes.mid&&(Array.isArray(i)&&!i.includes(e.attributes.mid)||("audio"===e.media.mediaType&&bo(e),"video"===e.media.mediaType&&function(e){if("video"!==e.media.mediaType)return;if(!ce("ENABLE_DOWN_SPS_PPS"))return;e.attributes.payloads.filter((e=>{var t;return"h264"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())})).forEach((e=>{e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters["sps-pps-idr-in-keyframe"]="1"}))}(e),o&&["audio","video"].includes(e.media.mediaType)&&e.attributes.payloads.forEach((e=>{-1===e.rtcpFeedbacks.findIndex((e=>"rrtr"===e.type))&&e.rtcpFeedbacks.push({type:"rrtr"})}))))})),De(n)}function ko(e,t,i,n){if(ce("SDP_LOGGING"))return B.upload("exchanging ".concat(i," ").concat(t," SDP during P2PConnection.").concat(n,"\n"),e),"offer"===t?e=>{ko(e,"answer","local"===i?"remote":"local",n)}:void 0}async function Mo(e,t,i){try{var n;if(!o().supportSetRtpSenderParameters)return;if(!function(e){return"vp9"===e||"av1"===e}(e)||!ce("ENABLE_SVC"))return;const s={},a={},r=t.getParameters(),c=null===(n=r.encodings)||void 0===n?void 0:n[0];a.scalabilityMode=ao(i),c&&Object.assign(c,a),Object.assign(r,s),await t.setParameters(r),B.debug("[updateAdaptation] updateRtpSenderEncodings scalabilityMode success: ".concat(JSON.stringify(r.encodings)))}catch(e){B.debug("[updateAdaptation] updateRtpSenderEncodings scalabilityMode failed",e)}}function Uo(e){const t=ce("COMPATIBLE_SDP_EXTENSION");return!!(Array.isArray(t)&&t.length>0)&&t.some((t=>e.includes(t)))}function Vo(e,t){try{var i;return(null===(i=e.fmtp)||void 0===i?void 0:i.parameters.apt)===t.payloadType.toString()}catch(e){return!1}}const xo={};function Fo(e){(!(arguments.length>1&&void 0!==arguments[1])||arguments[1])&&B.debug("install service ".concat(e.name)),xo[e.name]=e}function Bo(e){const t=xo[e];if(!t)throw new me(ne.INVALID_OPERATION,"".concat(e," not found, please use AgoraRTC.use(").concat(e,"Service) to load it first"));return t}function jo(e,t){return Bo("DataStream").create(e,t)}function Go(){return Bo("InterceptFrame").create()}function Wo(e,t){return!(e.length<4||e.length>256)&&!(t.length<22||t.length>256)}const Ho=new Map;class Ko extends re{get state(){return this._state}set state(e){if(e===this._state)return;const t=this._state;this._state=e,"DISCONNECTED"===e&&this._disconnectedReason?this.emit(an.CONNECTION_STATE_CHANGE,e,t,this._disconnectedReason):this.emit(an.CONNECTION_STATE_CHANGE,e,t)}get joinGatewayStartTime(){return this._joinGatewayStartTime}set joinGatewayStartTime(e){B.debug("[".concat(this.store.clientId,"] set joinGatewayStartTime at ").concat(e)),this._joinGatewayStartTime=e}constructor(e,t){var i,n,o;super(),this.store=void 0,this.joinInfo=void 0,this.key=void 0,this.ntpOffset=0,this.usingProxy=!1,this.signal=void 0,this.role=void 0,this.isPreallocation=void 0,this.isPreSub=void 0,this.inChannelInfo={joinAt:null,duration:0},this.spec=void 0,this._state="DISCONNECTED",this._statsCollector=void 0,this._disconnectedReason=void 0,this.isSignalRecover=!1,this.hasChangeBGPAddress=!1,this.trafficStatsInterval=void 0,this.networkQualityInterval=void 0,this._joinGatewayStartTime=0,this._signalTimeout=!1,this._clientRoleOptions=void 0,this._isProactiveJoin=!1,this.store=e,this.spec=t,this.signal=this.store.useP2P?(i={spec:ki(ki({},t),{},{retryConfig:t.websocketRetryConfig}),store:e},null===(n=(o=Bo("P2PChannel")).createSubmodule)||void 0===n?void 0:n.call(o,i)):this.store.useDcSignal?function(e){return Bo("DataChannelSignal").create(e)}({spec:ki(ki({},t),{},{retryConfig:t.websocketRetryConfig}),store:e}):new Yn(ki(ki({},t),{},{retryConfig:t.websocketRetryConfig}),e),this._statsCollector=t.statsCollector,this.role=t.role||"audience",this._clientRoleOptions=t.clientRoleOptions,this.handleSignalEvents()}setUsingProxy(e){this.usingProxy=e}async join(e,t,i){if(this.store.useDcSignal){let t=!1;const i=e.apResponse.addresses[0],n=i.iceUfrag||"".concat(e.apResponse.cid,"_").concat(e.apResponse.cert),o=i.icePwd||"".concat(e.apResponse.cid,"_").concat(e.apResponse.cert);"disabled"!==e.cloudProxyServer?(B.debug("[".concat(this.store.clientId,"] Dc is not supported, because cloudProxyServer are not supported (").concat(e.cloudProxyServer,")")),t=!0):Wo(n,o)?e.apResponse.addresses.some((e=>e.fingerprint))||ce("FINGERPRINT")||(B.debug("[".concat(this.store.clientId,"] Dc is not supported, because fingerprint does not exist")),t=!0):(B.debug("[".concat(this.store.clientId,"] Dc is not supported, because ticket length is incorrect, it has to be between 22 and 255")),t=!0),t&&this.resetSignal()}this.store.joinGatewayStart(),"disabled"!==e.cloudProxyServer&&(this.hasChangeBGPAddress=!0);const n=Date.now();let o=Ho.get(e.cname);if(o||(o=new Map,Ho.set(e.cname,o)),this._isProactiveJoin=!0,o.has(e.uid)){const t=new j(ne.UID_CONFLICT);throw G.joinGateway(e.sid,{lts:n,succ:!1,ec:t.code,addr:null,uid:e.uid,cid:e.cid,firstSuccess:this._isProactiveJoin,isProxy:!!e.proxyServer||this.usingProxy,signalChannel:this.store.useDcSignal?"1":"0",preload:e.preload}),t}o.set(e.uid,!0),this.joinInfo=e,this.key=t;let s=0;this.joinGatewayStartTime=n;const a=e.proxyServer,r=this.store.useDcSignal?"datachannel":"websocket";try{B.debug("[".concat(this.store.clientId,"] use ").concat(r," join uid ").concat(s));const t=e.gatewayAddrs.map((t=>{const i=Mi(t.address.split(":"),2),n={host:i[0],port:i[1]};return e.proxyServer&&(n.proxy=e.proxyServer),n}));let i;i=this.store.useDcSignal?await this.signal.init(e.apResponse.addresses):await this.signal.init(t),s=i.uid,B.debug("[".concat(this.store.clientId,"] ").concat(r," join uid ").concat(s," cost ").concat(Date.now()-this.joinGatewayStartTime))}catch(t){var c;if(t.code===ne.INIT_DATACHANNEL_TIMEOUT&&"AgoraRTCSignal"===this.signal.__name__);else G.joinGateway(e.sid,{lts:n,succ:!1,ec:(null===(c=t.data)||void 0===c?void 0:c.desc)||t.code,errorMsg:t.message,addr:this.signal.url,uid:e.uid,cid:e.cid,firstSuccess:this._isProactiveJoin,isProxy:!!a||this.usingProxy,signalChannel:"DataChannelSignal"===this.signal.__name__?"1":"0",preload:e.preload});if(t&&t.code===ne.INIT_DATACHANNEL_TIMEOUT)throw B.warning("[".concat(this.store.clientId,"] User join datachannel failed"),t.toString()),this.resetSignal(),t;throw B.error("[".concat(this.store.clientId,"] User join failed"),t.toString()),o.delete(e.uid),this.signal.close(),t}return this.state="CONNECTED",this.inChannelInfo.joinAt=Date.now(),B.debug("[".concat(this.store.clientId,"] Connected to gateway server")),this.trafficStatsInterval=window.setInterval((()=>{this.updateTrafficStats().catch((e=>{B.warning("[".concat(this.store.clientId,"] get traffic stats error"),e.toString())}))}),3e3),this.networkQualityInterval=window.setInterval((()=>{navigator&&void 0!==navigator.onLine&&!navigator.onLine?this.emit(an.NETWORK_QUALITY,{downlinkNetworkQuality:6,uplinkNetworkQuality:6}):this._signalTimeout?this.emit(an.NETWORK_QUALITY,{downlinkNetworkQuality:5,uplinkNetworkQuality:5}):"CONNECTED"===this.state&&this._statsCollector.trafficStats?this.emit(an.NETWORK_QUALITY,{uplinkNetworkQuality:$n(this._statsCollector.trafficStats.B_unq),downlinkNetworkQuality:$n(this._statsCollector.trafficStats.B_dnq)}):this.emit(an.NETWORK_QUALITY,{uplinkNetworkQuality:0,downlinkNetworkQuality:0})}),2e3),this.store.joinGatewayEnd(),s}async leave(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=arguments.length>1?arguments[1]:void 0;if("DISCONNECTED"!==this.state){t!==ge.FALLBACK&&(this.state="DISCONNECTING");try{e||this.signal.connectionState!==Wi.CONNECTED||await Me(this.signal.request(Ki.LEAVE,void 0,!0),3e3)}catch(e){B.warning("[".concat(this.store.clientId,"] leave request failed, ignore"),e)}this.signal.close(t),t!==ge.FALLBACK&&(this.state="DISCONNECTED"),this.reset()}}async publish(e,t,i){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new j(ne.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));const n={state:"offer",p2p_id:this.store.p2pId,ortc:t,mode:this.spec.mode,extend:ce("PUB_EXTEND"),twcc:!!ce("PUBLISH_TWCC"),rtx:!!ce("USE_PUB_RTX")};try{return(await this.signal.request(Ki.PUBLISH,n,!0))._message}catch(n){if(i&&n.data&&n.data.code===Gi.ERR_PUBLISH_REQUEST_INVALID)return B.warning("[".concat(this.store.clientId,"] receive publish error code, retry"),n.toString()),await this.tryUnpubBeforeRepub(e,t),this.publish(e,t,!1);throw n}}async publishDataChannel(e,t,i){var n;if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new j(ne.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));const o={stream_id:t.streamId,ordered:t.ordered?1:0,max_retrans_times:null!==(n=t.maxRetransmits)&&void 0!==n?n:10,channel_id:t.channelId,metadata:t.metadata};try{await this.signal.request(Ki.PUBLISH_DATASTREAM,o,!0)}catch(n){if(i&&n.data&&n.data.code===Gi.ERR_PUBLISH_REQUEST_INVALID)return B.warning("[".concat(this.store.clientId,"] receive publish datachannels error code, retry"),n.toString()),await this.tryUnpubDataChannelBeforeRepub(e,t),this.publishDataChannel(e,t,!1);throw n}}async unpublish(e,t){try{if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new j(ne.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));await this.signal.request(Ki.UNPUBLISH,{stream_id:t,ortc:e},!0)}catch(e){B.warning("[".concat(this.store.clientId,"] unpublish warning: "),e)}}async unpublishDataChannel(e){try{if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new j(ne.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));await Promise.all(e.map((e=>this.signal.request(Ki.UNPUBLISH_DATASTREAM,{channel_id:e},!0))))}catch(e){B.warning("unpublish datachannels warning: ",e)}}async presubscribe(e,t,i){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new j(ne.INVALID_OPERATION,"can not presubscribe when connection state is ".concat(this.state));const n={stream_id:e,stream_type:t,mode:this.spec.mode,codec:this.spec.codec,p2p_id:this.store.p2pId,twcc:!!ce("SUBSCRIBE_TWCC"),rtx:!!ce("USE_SUB_RTX")||void 0,extend:ce("SUB_EXTEND"),svc:Array.isArray(ce("SVC"))&&0!==ce("SVC").length?ce("SVC"):void 0};try{return await this.signal.request(Ki.PRE_SUBSCRIBE,n,!0)}catch(n){if(i&&n.data&&n.data.code===Gi.ERR_SUBSCRIBE_REQUEST_INVALID)return B.warning("[".concat(this.store.clientId,"] pre-subscribe error, retry"),n.toString()),this.presubscribe(e,t,!1);throw n}}async subscribe(e,t,i){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new j(ne.INVALID_OPERATION,"can not subscribe when connection state is ".concat(this.state));const n={stream_id:e,stream_type:t.stream_type,mode:this.spec.mode,codec:this.spec.codec,p2p_id:this.store.p2pId,twcc:!!ce("SUBSCRIBE_TWCC"),rtx:!!ce("USE_SUB_RTX"),extend:ce("SUB_EXTEND"),ssrcId:t.ssrcId,svc:Array.isArray(ce("SVC"))&&0!==ce("SVC").length?ce("SVC"):void 0};try{return(await this.signal.request(Ki.SUBSCRIBE,n,!0))._message}catch(n){if(i&&n.data&&n.data.code===Gi.ERR_SUBSCRIBE_REQUEST_INVALID)return B.warning("[".concat(this.store.clientId,"] receiver subscribe error code, retry"),n.toString()),await this.tryUnsubBeforeResub(e,t),await this.subscribe(e,t,!1);throw n}}async subscribeDataChannel(e,t,i){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new j(ne.INVALID_OPERATION,"can not subscribe datachannel when connection state is ".concat(this.state));const n={uid:e,stream_id:t.id,channel_id:t.datachannelId};try{return void await this.signal.request(Ki.SUBSCRIBE_DATASTREAM,n,!0)}catch(n){if(i&&n.data&&n.data.code===Gi.ERR_SUBSCRIBE_REQUEST_INVALID)return B.warning("[".concat(this.store.clientId,"] receiver subscribe datachannel error code, retry"),n.toString()),await this.tryUnsubDataChannelBeforeResub(e,t),await this.subscribeDataChannel(e,t,!1);throw n}}async subscribeAll(e,t){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new j(ne.INVALID_OPERATION,"can not massSubscribe when connection state is ".concat(this.state));const i={p2p_id:this.store.p2pId,users:e,dtx:!1,rtx:!!ce("USE_SUB_RTX"),twcc:!!ce("SUBSCRIBE_TWCC"),svc:Array.isArray(ce("SVC"))&&0!==ce("SVC").length?ce("SVC"):void 0};try{return await this.signal.request(Ki.SUBSCRIBE_STREAMS,i,!0)}catch(i){if(t&&i.data&&i.data.code===Gi.ERR_SUBSCRIBE_REQUEST_INVALID)return B.warning("[".concat(this.store.clientId,"] receiver massSubscribe error code, retry"),i.toString()),await this.tryMassUnsubBeforeResub(e),await this.subscribeAll(e,!1);throw i}}async setVideoProfile(e){const t=function(e){if(!(e.bitrateMax&&e.bitrateMin&&e.frameRate&&e.height&&e.width))return;let t=e.frameRate,i=e.width,n=e.height,o=!0;return"number"!=typeof t&&(t=t.exact||t.ideal||t.max||t.min||0,t||(o=!1)),"number"!=typeof i&&(i=i.exact||i.ideal||i.max||i.min||0,i||(o=!1)),"number"!=typeof n&&(n=n.exact||n.ideal||n.max||n.min||0,n||(o=!1)),o?{stream_type:0,width:i,height:n,fps:t,start_bps:1e3*e.bitrateMax,min_bps:1e3*e.bitrateMin,target_bps:1e3*e.bitrateMax}:void 0}(e);if(t)return this.signal.request(Ki.SET_VIDEO_PROFILE,t);B.debug("[".concat(this.store.clientId,"] encoder config is not complete, do not report to gateway"))}async unsubscribe(e,t){try{await this.signal.request(Ki.UNSUBSCRIBE,{p2p_id:this.store.p2pId,ortc:e,stream_id:t},!0)}catch(e){B.warning("[".concat(this.store.clientId,"] unsubscribe warning: "),e)}}async unsubscribeDataChannel(e,t){try{if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new j(ne.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));await Promise.all(e.map((e=>this.signal.request(Ki.UNSUBSCRIBE_DATASTREAM,{stream_id:e,uid:t},!0))))}catch(e){B.warning("unsubscribeDataChannel warning: ",e)}}async massUnsubscribe(e){try{await this.signal.request(Ki.UNSUBSCRIBE_STREAMS,e,!0)}catch(e){B.warning("[".concat(this.store.clientId,"] massUnsubscribeAll warning: "),e)}}async reconnectPC(e){const t=e.iceParameters,i=e.dtlsParameters,n=e.rtpCapabilities;return{gatewayEstablishParams:await this.signal.request(Ki.CONNECT_PC,{p2p_id:this.store.p2pId,stream_id:this.store.uid,ortc:{iceParameters:t,dtlsParameters:i,rtpCapabilities:n}},!0),gatewayAddress:this.getCurrentGatewayAddress()}}getGatewayInfo(){return this.signal.request(Ki.GATEWAY_INFO)}async renewToken(e){await this.signal.request(Ki.RENEW_TOKEN,e),this.key=e.token}updateClientRole(e,t){t&&(this._clientRoleOptions=Object.assign({},t)),ce("CLIENT_ROLE_OPTIONS")&&(B.debug("[".concat(this.store.clientId,"] Set roleOptions for ").concat(JSON.stringify(ce("CLIENT_ROLE_OPTIONS"))," instead of ").concat(JSON.stringify(this._clientRoleOptions)," ")),this._clientRoleOptions=Object.assign({},ce("CLIENT_ROLE_OPTIONS"))),this.role=e}async setClientRole(e,t){if(t&&(this._clientRoleOptions=Object.assign({},t)),ce("CLIENT_ROLE_OPTIONS")&&(this._clientRoleOptions=Object.assign({},ce("CLIENT_ROLE_OPTIONS")),B.debug("[".concat(this.store.clientId,"] Set roleOptions for ").concat(JSON.stringify(ce("CLIENT_ROLE_OPTIONS"))," instead of ").concat(JSON.stringify(this._clientRoleOptions)," "))),"CONNECTED"!==this.state)return void(this.role=e);let i,n=0;"audience"===e?this._clientRoleOptions&&this._clientRoleOptions.delay?(i=this._clientRoleOptions.delay,n=1):n=this._clientRoleOptions&&this._clientRoleOptions.level?this._clientRoleOptions.level:2:n=0;const o=Object.assign({},t);delete o.delay,delete o.level,await this.signal.request(Ki.SET_CLIENT_ROLE,ki(ki({role:e,level:n,delay:i},o),{},{client_ts:Date.now()})),this.role=e}async setDualStreamMode(e,t,i){await this.signal.request(Ki.SET_DUAL_STREAM_MODE,{mode:e},i,t)}async setRemoteVideoStreamType(e,t){await this.signal.request(Ki.SWITCH_VIDEO_STREAM,{stream_id:e,stream_type:t})}async setDefaultRemoteVideoStreamType(e){await this.signal.request(Ki.DEFAULT_VIDEO_STREAM,{stream_type:e})}async setStreamFallbackOption(e,t){await this.signal.request(Ki.SET_FALLBACK_OPTION,{stream_id:e,fallback_type:t})}async pickSVCLayer(e,t){await this.signal.request(Ki.PICK_SVC_LAYER,{stream_id:e,spatial_layer:t.spatialLayer,temporal_layer:t.temporalLayer})}async setRTM2Flag(e){await this.signal.request(Ki.SET_RTM2_FLAG,{rtm2_flag:e})}async sendExtensionMessage(e,t,i){if(this.store.useP2P)return this.signal.sendExtensionMessage(e,t,i)}getInChannelInfo(){return this.inChannelInfo.joinAt&&(this.inChannelInfo.duration=Date.now()-this.inChannelInfo.joinAt),ki({},this.inChannelInfo)}async setConfigure(e){if(e&&Array.isArray(e)&&0!==e.length)return this.signal.request(Ki.CONFIGURE,e)}async getGatewayVersion(){return(await this.signal.request(Ki.GATEWAY_INFO)).version}reset(){if(this.inChannelInfo.joinAt&&(this.inChannelInfo.duration=Date.now()-this.inChannelInfo.joinAt,this.inChannelInfo.joinAt=null),this.trafficStatsInterval&&(window.clearInterval(this.trafficStatsInterval),this.trafficStatsInterval=void 0),this.joinInfo){const e=Ho.get(this.joinInfo.cname);e&&e.delete(this.joinInfo.uid)}this.joinInfo=void 0,this.key=void 0,this.networkQualityInterval&&(window.clearInterval(this.networkQualityInterval),this.networkQualityInterval=void 0),this.usingProxy=!1}updateTurnConfigFromSignal(){if(!this.joinInfo)return;const e=function(e){let t;return t=e.startsWith("dc")?e.match(/(dc\:\/\/)?([^:]+):(\d+)/):e.match(/(wss\:\/\/)?([^:]+):(\d+)/),t?{username:ye.username,password:ye.password,turnServerURL:t[2],tcpport:parseInt(t[3])+30,udpport:parseInt(t[3])+30,forceturn:!1}:null}(("disabled"===this.joinInfo.cloudProxyServer?this.signal.url:this.joinInfo.gatewayAddrs[this.signal.currentURLIndex].address)||"");this.joinInfo.turnServer.serversFromGateway=[],e&&"off"!==this.joinInfo.turnServer.mode&&"disabled"===this.joinInfo.cloudProxyServer&&this.joinInfo.turnServer.serversFromGateway.push(ki(ki({},ye),{},{turnServerURL:e.turnServerURL,tcpport:e.tcpport,udpport:e.udpport,username:this.joinInfo.uid.toString(),password:this.joinInfo.token}))}async updateTrafficStats(){if("CONNECTED"!==this.state)return;const e=await this.signal.request(Ki.TRAFFIC_STATS,void 0,!0);e.timestamp=Date.now(),null!=e.ntp_offset&&(this.ntpOffset=e.ntp_offset),e.peer_delay.forEach((e=>{const t=this._statsCollector.trafficStats&&this._statsCollector.trafficStats.peer_delay.find((t=>t.peer_uid===e.peer_uid));t&&t.B_st!==e.B_st&&Ue((()=>{this.emit(an.STREAM_TYPE_CHANGE,e.peer_uid,e.B_st)}))})),this._statsCollector.updateTrafficStats(e)}getJoinMessage(e){var t,i;if(!this.joinInfo||!this.key)throw new j(ne.UNEXPECTED_ERROR,"can not generate join message, no join info");this.store.hasStartJoinChannel=!0,this.store.isABTestSuccess||this.emit(an.UPDATE_GATEWAY_CONFIG),i=this.store.clientId,gi.includes(i)||gi.push(i);return ci(this.store,this.joinInfo,this.spec,{key:this.key,role:this.role,joinGatewayStartTime:this.joinGatewayStartTime,hasChangeBGPAddress:this.hasChangeBGPAddress,isPreallocation:!(null===(t=this.isPreallocation)||void 0===t||!t.call(this)),ortc:e,currentURLIndex:this.signal.currentURLIndex})}getRejoinMessage(){if(!this.joinInfo)throw new j(ne.UNEXPECTED_ERROR,"can not generate rejoin message, no join info");return{session_id:this.joinInfo.sid,channel_name:this.joinInfo.cname,cid:this.joinInfo.cid,uid:this.joinInfo.uid,vid:Number(this.joinInfo.vid)}}handleSignalEvents(){this.signal.on(Hi.WS_RECONNECT_CREATE_CONNECTION,(e=>{this.joinGatewayStartTime=Date.now()})),this.signal.on(Hi.WS_RECONNECTING,(e=>{this.joinInfo&&G.WebSocketQuit(this.joinInfo.sid,{lts:Date.now(),succ:-1,cname:this.joinInfo.cname,uid:this.joinInfo.uid,cid:this.joinInfo.cid,errorCode:e||Ie.NETWORK_ERROR}),this.joinInfo&&(this.state="RECONNECTING",G.sessionInit(this.joinInfo.sid,{lts:(new Date).getTime(),extend:this.isSignalRecover?{recover:!0}:{rejoin:!0},cname:this.joinInfo.cname,appid:this.joinInfo.appId,mode:this.spec.mode,stringUid:this.joinInfo.stringUid,channelProfile:"live"===this.spec.mode?1:0,channelMode:0,lsid:this.joinInfo.sid,clientRole:"audience"===this.role?2:1,buildFormat:3}),this.isSignalRecover=!1,this.joinGatewayStartTime=Date.now())})),this.signal.on(Hi.WS_CLOSED,(e=>{let t;switch(e){case ge.LEAVE:t=Ie.LEAVE;break;case ge.UID_BANNED:case ge.IP_BANNED:case ge.CHANNEL_BANNED:case ge.SERVER_ERROR:t=Ie.SERVER_ERROR;break;case ge.FALLBACK:t=Ie.FALLBACK;break;case ge.LICENSE_MISSING:case ge.LICENSE_EXPIRED:case ge.LICENSE_MINUTES_EXCEEDED:case ge.LICENSE_PERIOD_INVALID:case ge.LICENSE_MULTIPLE_SDK_SERVICE:case ge.LICENSE_ILLEGAL:case ge.TOKEN_EXPIRE:t=e;break;default:t=Ie.NETWORK_ERROR}B.debug("[".concat(this.store.clientId,"] [signal] websocket closed, reason: ").concat(t||"undefined -> "+Ie.NETWORK_ERROR)),this.joinInfo&&G.WebSocketQuit(this.joinInfo.sid,{lts:Date.now(),succ:e===ge.LEAVE?1:-1,cname:this.joinInfo.cname,uid:this.joinInfo.uid,cid:this.joinInfo.cid,errorCode:t}),this._disconnectedReason=e,e!==ge.FALLBACK&&(this.state="DISCONNECTED"),this.reset()})),this.signal.on(Hi.WS_CONNECTED,(()=>{if(this.updateTurnConfigFromSignal(),this.state="CONNECTED",this.joinInfo){if("audience"===this.role){const e=ce("CLIENT_ROLE_OPTIONS")||this._clientRoleOptions;e&&(e.level||e.delay)&&(B.debug("[".concat(this.store.clientId,"] patch to send set client role, role: ").concat(this.role,", mode: ").concat(this.spec.mode,", level: ").concat(e.level,", delay: ").concat(e.delay)),this.setClientRole(this.role,e))}if(G.joinGateway(this.joinInfo.sid,{lts:this.joinGatewayStartTime,succ:!0,ec:null,vid:this.joinInfo.vid,addr:this.signal.url,uid:this.joinInfo.uid,cid:this.joinInfo.cid,firstSuccess:this._isProactiveJoin,isProxy:!!this.joinInfo.proxyServer||this.usingProxy,signalChannel:"DataChannelSignal"===this.signal.__name__?"1":"0",preload:this.joinInfo.preload,isABTestSuccess:this.store.isABTestSuccess}),this._isProactiveJoin=!1,this.joinInfo.useLocalAccessPoint&&1===this.joinInfo.setLocalAPVersion){const e=this.signal.url&&this.signal.url.match(/wss\:\/\/([^:]+):(\d+)/);if(!e)return void B.error("[".concat(this.store.clientId,"] set local access point after joined failed: ").concat(e));Ve("EVENT_REPORT_DOMAIN",e[1]),Ve("EVENT_REPORT_BACKUP_DOMAIN",e[1]),Ve("LOG_UPLOAD_SERVER","".concat(e[1],":6444"))}}})),this.signal.on(qi.ON_UPLINK_STATS,(e=>{this._statsCollector.updateUplinkStats(e)})),this.signal.on(Hi.REQUEST_RECOVER,((e,t,i)=>{if(!this.joinInfo)return i(new j(ne.UNEXPECTED_ERROR,"gateway: can not recover, no join info"));e&&(this.joinInfo.multiIP=e,this.hasChangeBGPAddress=!0),this.isSignalRecover=!0,Ce(this,an.REQUEST_NEW_GATEWAY_LIST).then(t).catch(i)})),this.signal.on(Hi.REQUEST_JOIN_INFO,(async(e,t,i)=>{var n,o,s;if(this.updateTurnConfigFromSignal(),this.store.useP2P)return void e(this.getJoinMessage());const a=Oe(null===(n=this.joinInfo)||void 0===n?void 0:n.turnServer);if(ce("NEW_TURN_MODE")&&a&&"disabled"===(null===(o=this.joinInfo)||void 0===o?void 0:o.cloudProxyServer)){var r;let e=a.servers.map((e=>"turnServerURL"in e&&ce("USE_TURN_IP")?ki(ki({},e),{},{turnServerURL:Xn(e.turnServerURL)}):e)),t=null===(r=a.serversFromGateway)||void 0===r?void 0:r.map((e=>ce("USE_TURN_IP")?ki(ki({},e),{},{turnServerURL:Xn(e.turnServerURL)}):e));const i=this.signal.currentURLIndex;if(e.length>0){e=[e[i%e.length]],a.servers=e}Array.isArray(t)&&t.length>0&&(t=[t[0]],a.serversFromGateway=t),B.debug("[".concat(this.store.clientId,"] use single turn, use turn server index: ").concat(i))}const c=await Ce(this,an.REQUEST_P2P_CONNECTION_PARAMS,{turnServer:a,cloudProxyServer:null===(s=this.joinInfo)||void 0===s?void 0:s.cloudProxyServer}),d=c.iceParameters,l=c.dtlsParameters,h=c.rtpCapabilities;try{e(this.getJoinMessage({iceParameters:d,dtlsParameters:l,rtpCapabilities:h,version:"2"}))}catch(e){t(e)}})),this.signal.on(Hi.REQUEST_JOIN_INFO_WITH_PRE_JOIN_RESPONSE,((e,t)=>{if(this.joinInfo&&this.joinInfo.signalResponse){const t=this.joinInfo.apResponse.addresses[this.signal.currentURLIndex],i=this.joinInfo.signalResponse,n=ce("FINGERPRINT")||t.fingerprint;if(!t.iceUfrag||!t.icePwd||!n)return B.debug("cannot get iceUfrag or icePwd or fingerprint from serverAddress"),void e(void 0);const o=ki(ki({},i),{},{ortc:{dtlsParameters:{role:"client",fingerprints:[{algorithm:"sha-256",fingerprint:ce("FINGERPRINT")||t.fingerprint}]},iceParameters:{candidates:[],iceUfrag:t.iceUfrag,icePwd:t.icePwd},rtpCapabilities:i.rtpCapabilities,cname:"o/i14u9pJrxRKAsu"}});this.joinInfo&&delete this.joinInfo.signalResponse,e(o)}else e(void 0)})),this.signal.on(Hi.REQUEST_REJOIN_INFO,(e=>{e(this.getRejoinMessage())})),this.signal.on(Hi.REPORT_JOIN_GATEWAY,((e,t)=>{if(!this.joinInfo)return;let i,n="";var o;e instanceof j?(i=(null===(o=e.data)||void 0===o?void 0:o.desc)||e.code,n=e.message):i=e;G.joinGateway(this.joinInfo.sid,{lts:this.joinGatewayStartTime,succ:!1,ec:i,errorMsg:n,addr:t,uid:this.joinInfo.uid,cid:this.joinInfo.cid,firstSuccess:this._isProactiveJoin,isProxy:!!this.joinInfo.proxyServer||this.usingProxy,signalChannel:"DataChannelSignal"===this.signal.__name__?"1":"0",preload:this.joinInfo.preload})})),this.signal.on(Hi.IS_P2P_DISCONNECTED,(e=>{e(Ae(this,an.IS_P2P_DISCONNECTED))})),this.signal.on(Hi.DISCONNECT_P2P,(()=>{this.emit(an.DISCONNECT_P2P)})),this.signal.on(Hi.REQUEST_SUCCESS,(()=>{this._signalTimeout=!1})),this.signal.on(Hi.REQUEST_TIMEOUT,(()=>{this._signalTimeout=!0})),this.signal.on(Hi.JOIN_RESPONSE,(e=>{const t=this.getCurrentGatewayAddress();this.emit(an.JOIN_RESPONSE,e,t)})),this.signal.on(Hi.PRE_CONNECT_PC,(async(e,t)=>{if(this.joinInfo){var i,n;this.updateTurnConfigFromSignal();const s=this.getCurrentGatewayAddress(),a=Oe(null===(i=this.joinInfo)||void 0===i?void 0:i.turnServer);if(ce("NEW_TURN_MODE")&&a&&"disabled"===(null===(n=this.joinInfo)||void 0===n?void 0:n.cloudProxyServer)){var o;let e=a.servers.map((e=>"turnServerURL"in e&&ce("USE_TURN_IP")?ki(ki({},e),{},{turnServerURL:Xn(e.turnServerURL)}):e)),t=null===(o=a.serversFromGateway)||void 0===o?void 0:o.map((e=>ce("USE_TURN_IP")?ki(ki({},e),{},{turnServerURL:Xn(e.turnServerURL)}):e));const i=this.signal.currentURLIndex;if(e.length>0){e=[e[i%e.length]],a.servers=e}Array.isArray(t)&&t.length>0&&(t=[t[0]],a.serversFromGateway=t),B.debug("[".concat(this.store.clientId,"] use single turn, use turn server index: ").concat(i,",in pre pc"))}const r=this.joinInfo.apResponse.addresses[this.signal.currentURLIndex],c=ce("FINGERPRINT")||r.fingerprint;if(s&&c){const i=Ro(s);Ce(this,an.PRE_CONNECT_PC,{candidates:i,fingerprint:c,turnServer:a,iceUfrag:r.iceUfrag,icePwd:r.icePwd}).then((t=>{null==e||e(t)})).catch(t||(()=>{}))}}})),this.signal.on(Hi.RECOVER_NOTIFICATION,(e=>{this.joinInfo&&"string"==typeof ce("AP_REQUEST_DETAIL")&&(this.joinInfo.apRequestDetail="".concat(ce("AP_REQUEST_DETAIL"),";").concat(e))})),this.signal.on(Hi.VOS_FALLBACK,(e=>{this.emit(an.VOS_FALLBACK,e)})),this.signal.on(Hi.DATACHANNEL_FAILBACK,(e=>{B.warning("[".concat(this.store.clientId,"] User join datachannel failed")),this.reset(),this.resetSignal(),this.emit(an.DATACHANNEL_FAILBACK)}))}async tryUnsubBeforeResub(e,t){try{await this.signal.request(Ki.UNSUBSCRIBE,{p2p_id:this.store.p2pId,stream_id:e,ortc:[t]},!0)}catch(e){throw B.warning("[".concat(this.store.clientId,"] tryUnsubBeforeResub warning"),e),e}}async tryUnsubDataChannelBeforeResub(e,t){try{await this.signal.request(Ki.UNSUBSCRIBE,{stream_id:t.id},!0)}catch(e){throw B.warning("unsubscribe datachannel warning",e),e}}async tryUnpubBeforeRepub(e,t){try{await this.signal.request(Ki.UNPUBLISH,{stream_id:e,ortc:t},!0)}catch(e){throw B.warning("[".concat(this.store.clientId,"] tryUnpubBeforeRepub warning: "),e),e}}async tryUnpubDataChannelBeforeRepub(e,t){try{await this.signal.request(Ki.UNPUBLISH_DATASTREAM,{channnel_id:t.channelId},!0)}catch(e){throw B.warning("unpublish datastream warning: ",e),e}}async tryMassUnsubBeforeResub(e){const t={users:e.map((e=>({stream_id:e.stream_id,stream_type:e.stream_type})))};try{await this.signal.request(Ki.UNSUBSCRIBE_STREAMS,t,!0)}catch(e){throw B.warning("[".concat(this.store.clientId,"] tryMassUnsubBeforeResub warning"),e),e}}async muteLocal(e,t){const i={action:e.find((e=>e.stream_type===sn.Audio))?"mute_local_audio":"mute_local_video",p2p_id:this.store.p2pId,ortc:e,stream_id:t};try{await this.signal.request(Ki.CONTROL,i,!0,!0)}catch(e){throw B.warning("[".concat(this.store.clientId,"] gateway muteLocal warning: "),e),e}}async unmuteLocal(e,t){const i={action:e.find((e=>e.stream_type===sn.Audio))?"unmute_local_audio":"unmute_local_video",p2p_id:this.store.p2pId,ortc:e,stream_id:t};try{await this.signal.request(Ki.CONTROL,i,!0,!0)}catch(e){throw B.warning("[".concat(this.store.clientId,"] gateway unmuteLocal warning: "),e),e}}async muteRemote(e,t){const i={action:e===Sn.AUDIO?"mute_remote_audio":"mute_remote_video",p2p_id:this.store.p2pId,stream_id:t};try{await this.signal.request(Ki.CONTROL,i,!0,!0)}catch(e){throw B.warning("[".concat(this.store.clientId,"] gateway muteRemote warning: "),e),e}}async unmuteRemote(e,t){const i={action:e===Sn.AUDIO?"unmute_remote_audio":"unmute_remote_video",p2p_id:this.store.p2pId,stream_id:t};try{await this.signal.request(Ki.CONTROL,i,!0,!0)}catch(e){throw B.warning("[".concat(this.store.clientId,"] gateway unmuteRemote warning: "),e),e}}uploadWRTCStats(e){this.signal.uploadWRTCStats(e)}upload(e,t){this.signal.upload(e,t)}getSignalRTT(){return this.signal.rtt}async restartICE(e){const t={p2p_id:this.store.p2pId,stream_id:this.store.uid,ortc:e};try{return await this.signal.request(Ki.RESTART_ICE,t,!0)}catch(e){throw B.warning("[".concat(this.store.clientId,"] P2PChannel.restartICE warning: "),e),e}}reconnect(e,t){"CONNECTED"===this.state&&this.signal.reconnect(e||void 0,t||Ie.P2P_FAILED)}getCurrentGatewayAddress(){var e,t;if(!ce("GATEWAY_WSS_ADDRESS"))return ce("USE_CANDIDATE_FROM_AP_DETAIL")&&null!==(e=this.joinInfo)&&void 0!==e&&e.apGatewayAddress?(B.debug("[".concat(this.store.clientId,"] use candidate from ap detail, ").concat(JSON.stringify(this.joinInfo.apGatewayAddress))),this.joinInfo.apGatewayAddress):null!==(t=this.joinInfo)&&void 0!==t&&t.gatewayAddrs?this.joinInfo.gatewayAddrs[this.signal.currentURLIndex]:void 0}async setPublishAudioFilterEnabled(e){await this.signal.request(Ki.SET_PARAMETER,{enablePublishAudioFilter:e})}downgradeCodec(e){this.signal.downgradeCodec(e)}resetSignal(){this.signal&&(this.signal.removeAllListeners(),this.signal.close(ge.FALLBACK)),this.store.useDcSignal=!1,this.signal=new Yn(ki(ki({},this.spec),{},{retryConfig:this.spec.websocketRetryConfig}),this.store),this.handleSignalEvents(),this.emit(an.RESET_SIGNAL)}}let Yo=function(e){return e.NATIVE_RTC="native_rtc",e.NATIVE_RTM="native_rtm",e.WEB_RTC="web_rtc",e.WEB_RTM="web_rtm",e}({}),qo=0,Jo=0;function Xo(e,t,i,n){return new Promise(((o,s)=>{t.timeout=t.timeout||ce("HTTP_CONNECT_TIMEOUT"),t.responseType=t.responseType||"json",t.data&&!i?(t.data=JSON.stringify(t.data),qo+=xe(t.data)):i&&(t.data.size?qo+=t.data.size:t.data instanceof FormData?qo+=Fe(t.data):qo+=xe(JSON.stringify(t.data))),t.headers=t.headers||{},t.headers["Content-Type"]=t.headers["Content-Type"]||"application/json",t.method="POST",t.url=e,ui.request(t).then((e=>{"string"==typeof e.data?Jo+=xe(e.data):e.data instanceof ArrayBuffer||e.data instanceof Uint8Array?Jo+=e.data.byteLength:Jo+=xe(JSON.stringify(e.data)),n&&o({data:e.data,headers:e.headers}),o(e.data)})).catch((e=>{ui.isCancel(e)?s(new j(ne.OPERATION_ABORTED,"cancel token canceled")):"ECONNABORTED"===e.code?s(new j(ne.NETWORK_TIMEOUT,e.message)):e.response?s(new j(ne.NETWORK_RESPONSE_ERROR,e.response.status)):s(new j(ne.NETWORK_ERROR,e.message))}))}))}const Qo=()=>{const e=ce("AREAS");0===e.length&&e.push(dn.GLOBAL);return e.reduce(((e,t,i)=>{const n=zo(t);return n?0===i?n:"".concat(e,",").concat(n):e}),"")},zo=e=>e===dn.OVERSEA?"".concat(hn.ASIA,",").concat(hn.EUROPE,",").concat(hn.AFRICA,",").concat(hn.NORTH_AMERICA,",").concat(hn.SOUTH_AMERICA,",").concat(hn.OCEANIA):hn[e],Zo=e=>{const t={CODE:"",WEBCS_DOMAIN:[],WEBCS_DOMAIN_BACKUP_LIST:[],PROXY_CS:[],CDS_AP:[],ACCOUNT_REGISTER:[],UAP_AP:[],EVENT_REPORT_DOMAIN:[],EVENT_REPORT_BACKUP_DOMAIN:[],LOG_UPLOAD_SERVER:[],PROXY_SERVER_TYPE3:[]};return e.map((e=>{const i=un[e],n=Object.keys(i);n&&n.map((e=>{"CODE"!==e&&(t[e]=t[e].concat(i[e]))}))})),t},$o={GLOBAL:{ASIA:[dn.CHINA,dn.JAPAN,dn.INDIA,dn.KOREA,dn.HKMC],EUROPE:[],NORTH_AMERICA:[dn.US],SOUTH_AMERICA:[],OCEANIA:[],AFRICA:[]}},es=Object.keys($o[dn.GLOBAL]),ts=[dn.CHINA,dn.NORTH_AMERICA,dn.EUROPE,dn.ASIA,dn.JAPAN,dn.INDIA,dn.OCEANIA,dn.SOUTH_AMERICA,dn.AFRICA,dn.KOREA,dn.HKMC,dn.US],is=function(e,t){let i=[];if(e.includes(dn.GLOBAL)){const s=[dn.GLOBAL,dn.OVERSEA],a=Object.keys(un);if(t===dn.GLOBAL)throw new j(ne.INVALID_PARAMS,"GLOBAL is an invalid excludedArea value");if(t===dn.CHINA)i=[dn.OVERSEA];else if(o=t,es.includes(o)){const e=(n=t,$o[dn.GLOBAL][n]||[]),o=[...s,t,...e];i=a.filter((e=>!o.includes(e)))}else if(function(e){let t=!1;return es.forEach((i=>{$o[dn.GLOBAL][i].includes(e)&&(t=!0)})),t}(t)){const e=function(e){let t;return es.forEach((i=>{$o[dn.GLOBAL][i].includes(e)&&(t=i)})),t}(t),n=[...s,e,t];i=a.filter((e=>!n.includes(e)))}else i=e;i=function(e){const t=[];return ts.forEach((i=>{e.includes(i)&&t.push(i)})),t.concat(e.filter((e=>!ts.includes(e))))}(i)}else i=e;var n,o;return i};function ns(e){if(!e&&ce("AREAS").includes(dn.EXTENSIONS))return B.debug("update area from ap : reset"),void os(Ci,!0);if(!ce("AREAS").includes(dn.GLOBAL)||!e)return;let t=un.EXTENSIONS;t&&(t={CODE:zo(dn.EXTENSIONS),WEBCS_DOMAIN:["ap-web-1-".concat(e,".agora.io")],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-".concat(e,".ap.sd-rtn.com")],PROXY_CS:["proxy-ap-web-".concat(e,".agora.io")],CDS_AP:["cds-ap-web-1-".concat(e,".agora.io"),"cds-ap-web-2-".concat(e,".ap.sd-rtn.com")],ACCOUNT_REGISTER:["sua-ap-web-1-".concat(e,".agora.io"),"sua-ap-web-2-".concat(e,".ap.sd-rtn.com")],UAP_AP:["uap-ap-web-1-".concat(e,".agora.io"),"uap-ap-web-2-".concat(e,".ap.sd-rtn.com")],EVENT_REPORT_DOMAIN:["statscollector-1-".concat(e,".agora.io")],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-".concat(e,".agora.io")],LOG_UPLOAD_SERVER:["logservice-".concat(e,".agora.io")],PROXY_SERVER_TYPE3:["webrtc-cloud-proxy-".concat(e,".agora.io")]},B.debug("update area from ap success: ".concat(e,",config is "),t),Ve("AREAS",[dn.EXTENSIONS],!0),Object.keys(t).map((e=>{if("LOG_UPLOAD_SERVER"===e||"EVENT_REPORT_DOMAIN"===e||"EVENT_REPORT_BACKUP_DOMAIN"===e||"PROXY_SERVER_TYPE3"===e){const i=t[e];Ve(e,i[0])}else Ve(e,t[e])})))}function os(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const i=G.reportApiInvoke(null,{name:Be.SET_AREA,options:e,tag:je.TRACER});try{let n=[];if("string"==typeof e&&(n=[e]),Array.isArray(e)&&(e.forEach((e=>{if(!ln.includes(e))throw new j(ne.INVALID_PARAMS,"invalid area code")})),n=e),"[object Object]"===Object.prototype.toString.call(e)){const t=e,i=t.areaCode,o=t.excludedArea;if(!i)throw new j(ne.INVALID_PARAMS,"area code is needed");let s=i;"string"==typeof i&&(s=[i]),n=o?is(s,o):s}if(!t){if($.AREAS){const e=new j(ne.PROHIBITED_OPERATION,"setArea is prohibited because of config-distribute");return i.onError(e),void B.warning("setArea is prohibited because of config-distribute")}if(n.includes(dn.GLOBAL)&&ce("AREAS")===dn.EXTENSIONS){const e=new j(ne.PROHIBITED_OPERATION,"setArea is prohibited because of ap extensions");return i.onError(e),void B.warning("setArea is prohibited because of ap extensions")}}Ve("AREAS",n,t);const o=Zo(n);Object.keys(o).map((e=>{if("LOG_UPLOAD_SERVER"===e||"EVENT_REPORT_DOMAIN"===e||"EVENT_REPORT_BACKUP_DOMAIN"===e||"PROXY_SERVER_TYPE3"===e){const t=o[e];Ve(e,t[0])}else Ve(e,o[e])})),B.debug("set area success:",n.join(","))}catch(e){throw i.onError(e),e}i.onSuccess()}let ss=1;function as(e,t,i,n,o){ss+=1;const s={sid:i.sid,command:"convergeAllocateEdge",uid:"666",appId:i.appId,ts:Math.floor(Date.now()/1e3),seq:ss,requestId:ss,version:He,cname:i.cname},a={service_name:t,json_body:JSON.stringify(s)};let r,c,d=e[0];return Ge((async()=>{r=Date.now();const e=await Xo(d,{data:a,cancelToken:n,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"}});if(c=Date.now()-r,0!==e.code){const t=new j(W.UNEXPECTED_RESPONSE,"live streaming ap error, code"+e.code,{retry:!0,responseTime:c});throw B.error(t.toString()),t}const i=JSON.parse(e.json_body);if(200!==i.code){const e=new j(W.UNEXPECTED_RESPONSE,"live streaming app center error, code: ".concat(i.code,", reason: ").concat(i.reason),{code:i.code,responseTime:c});throw B.error(e.toString()),e}if(!i.servers||0===i.servers.length){const e=new j(W.UNEXPECTED_RESPONSE,"live streaming app center empty server",{code:i.code,responseTime:c});throw B.error(e.toString()),e}const o=function(e,t){return{addressList:e.servers.map((e=>"wss://".concat(e.address.replace(/\./g,"-"),".").concat(ce("WORKER_DOMAIN"),":").concat(e.wss,"?serviceName=").concat(encodeURIComponent(t)))),workerToken:e.workerToken,vid:e.vid}}(i,t);return ce("LIVE_STREAMING_ADDRESS")&&(o.addressList=ce("LIVE_STREAMING_ADDRESS")instanceof Array?ce("LIVE_STREAMING_ADDRESS"):[ce("LIVE_STREAMING_ADDRESS")]),ki(ki({},o),{},{responseTime:c})}),((n,o)=>(G.apworkerEvent(i.sid,{success:!0,sc:200,serviceName:t,responseDetail:JSON.stringify(n.addressList),firstSuccess:0===o,responseTime:c,serverIp:e[o%e.length]}),!1)),((n,o)=>(G.apworkerEvent(i.sid,{success:!1,sc:n.data&&n.data.code||200,serviceName:t,responseTime:c,serverIp:e[o%e.length]}),!!(n.code!==W.OPERATION_ABORTED&&n.code!==W.UNEXPECTED_RESPONSE||n.data&&n.data.retry)&&(d=e[(o+1)%e.length],!0))),o)}function rs(e,t,i,n,o,s,a){let r=e.url,c=e.areaCode;const d=Date.now();let l;const h=i.role,u=Mi(ps(o,i,n,c,Array.isArray(t)?t:[t]),2),_=u[0],p=u[1];let E=pe.networkState;return Ge((async()=>{E&&pe.networkState===_e.OFFLINE&&pe.onlineWaiter&&await Promise.race([pe.onlineWaiter,fe(a&&a.maxRetryTimeout||Ke.maxRetryTimeout)]),E=pe.networkState;const e=await Xo(r,{data:_,cancelToken:s,responseType:"arraybuffer",headers:{"Content-Type":"text/plain;"}},!0,!0),o=e.data,c=e.headers;let h;l="1"===c.http3?1:-1,G.reportResourceTiming(r,i.sid,i.clientId);const u=(c["content-type"]||c["Content-Type"]||"").includes("application/json");try{h=u?li(o):hi(i,n,o)}catch(e){throw new j(W.PB_ERROR,"sdp enpoint response transformer get unknown res",{retry:!1})}ls(h,r,i,d,Array.isArray(t)?t:[t],l);const p=eo(h,ri.CHOOSE_SERVER);let m;Array.isArray(t)&&t.length>1&&(m=eo(h,"proxy5"===i.cloudProxyServer?ri.CLOUD_PROXY_5:"proxy3"===i.cloudProxyServer||"proxy4"===i.cloudProxyServer?ri.CLOUD_PROXY:ri.CLOUD_PROXY_FALLBACK));const S=performance.getEntriesByName(r),f=S[S.length-1];let C;return f&&(C={name:f.name,protocol:"nextHopProtocol"in f?f.nextHopProtocol:"",dnscost:"domainLookupEnd"in f&&"domainLookupStart"in f&&"number"==typeof f.domainLookupEnd&&"number"==typeof f.domainLookupStart?f.domainLookupEnd-f.domainLookupStart:-1,tcpTlsCost:"connectEnd"in f&&"connectStart"in f&&"number"==typeof f.connectEnd&&"number"==typeof f.connectStart?f.connectEnd-f.connectStart:-1,reqCost:"requestStart"in f&&"number"==typeof f.requestStart&&"responseEnd"in f&&"number"==typeof f.responseEnd?f.responseEnd-f.requestStart:-1,handleCost:"leave_ts"in h&&"enter_ts"in h&&"number"==typeof h.leave_ts&&"number"==typeof h.enter_ts?h.leave_ts-h.enter_ts:-1}),hs(p),Array.isArray(t)?{gatewayInfo:Qn(p,r),proxyInfo:m,url:r,resourceTimingInfo:C}:Qn(p,r)}),(e=>{const n="gatewayInfo"in e?e.gatewayInfo:e,o="proxyInfo"in e?e.proxyInfo:void 0,s="resourceTimingInfo"in e?e.resourceTimingInfo:void 0;return n&&G.joinChooseServer(i.sid,{role:h,lts:d,succ:!0,csAddr:r,serverList:n.gatewayAddrs.map((e=>e.address)),ec:null,opid:p,cid:n.cid.toString(),uid:n.uid.toString(),csIp:n.csIp,unilbsServerIds:t.toString(),isHttp3:l,corssRegionTagReq:i.apRequestDetail,corssRegionTagRes:n.res.detail&&n.res.detail[38],vid:null==n?void 0:n.vid,resourceTimingInfo:s?JSON.stringify(s):void 0}),o&&G.joinWebProxyAP(i.sid,{lts:d,sucess:1,apServerAddr:r,turnServerAddrList:o.addresses.map((e=>e.ip)).join(","),errorCode:null,eventType:i.cloudProxyServer,unilbsServerIds:t.toString()}),!1}),(e=>e.code!==W.PB_ERROR&&(e.code!==W.OPERATION_ABORTED&&(e.code===W.CAN_NOT_GET_GATEWAY_SERVER?e.data.retry:(G.joinWebProxyAP(i.sid,{lts:d,sucess:0,apServerAddr:r,turnServerAddrList:null,errorCode:e.code,eventType:i.cloudProxyServer,unilbsServerIds:t.toString(),extend:JSON.stringify({networkState:E})}),B.warning("[".concat(i.clientId,"] multi unilbs network error, retry"),e),!0)))),a)}function cs(e,t,i,n){let o=e.url,s=e.areaCode;const a=t.clientId,r=t.sid,c=Date.now();let d;const l=t.role,h=Mi(_s(t,s,[ri.CHOOSE_SERVER]),2),u=h[0],_=h[1];let p=pe.networkState;return Ge((async()=>{p&&pe.networkState===_e.OFFLINE&&pe.onlineWaiter&&await Promise.race([pe.onlineWaiter,fe(n&&n.maxRetryTimeout||Ke.maxRetryTimeout)]),p=pe.networkState;const e=await Xo(o,{data:u,cancelToken:i,headers:{"Content-Type":"multipart/form-data;"}},!0,!0),s=e.data,l=e.headers;d="1"===l.http3?1:-1,G.reportResourceTiming(o,r,a),ls(s,o,t,c,[ri.CHOOSE_SERVER],d);const h=eo(s,ri.CHOOSE_SERVER);return hs(h),Qn(h,o)}),(e=>(e&&G.joinChooseServer(r,{role:l,lts:c,succ:!0,csAddr:o,opid:_,serverList:e.gatewayAddrs.map((e=>e.address)),ec:null,cid:e.cid.toString(),uid:e.uid.toString(),csIp:e.csIp,unilbsServerIds:[ri.CHOOSE_SERVER].toString(),isHttp3:d,corssRegionTagReq:t.apRequestDetail,corssRegionTagRes:e.res.detail&&e.res.detail[38],vid:e.vid}),!1)),(e=>e.code!==W.OPERATION_ABORTED&&(e.code===W.CAN_NOT_GET_GATEWAY_SERVER?e.data.retry:(G.joinChooseServer(r,{role:l,lts:c,succ:!1,csAddr:o,serverList:null,opid:_,ec:e.code,csIp:e.data&&e.data.csIp,unilbsServerIds:[ri.CHOOSE_SERVER].toString(),extend:JSON.stringify({networkState:p}),isHttp3:d,corssRegionTagReq:t.apRequestDetail}),B.warning("[".concat(a||"sid-".concat(r.slice(0,6)),"] Choose server network error, retry"),e),!0))),n)}function ds(e,t,i,n){let o,s=e.url,a=e.areaCode,r=e.serviceIds;const c=Date.now(),d=t.role,l=Mi(_s(t,a,r),2),h=l[0],u=l[1];let _;return Ge((async()=>{_&&pe.networkState===_e.OFFLINE&&pe.onlineWaiter&&await Promise.race([pe.onlineWaiter,fe(n&&n.maxRetryTimeout||Ke.maxRetryTimeout)]),_=pe.networkState;const e=await Xo(s,{data:h,cancelToken:i,headers:{"Content-Type":"multipart/form-data;"}},!0,!0),a=e.data,d=e.headers;o="1"===d.http3?1:-1,G.reportResourceTiming(s,t.sid,t.clientId),ls(a,s,t,c,r,o);const l=eo(a,ri.CHOOSE_SERVER),u=eo(a,"proxy5"===t.cloudProxyServer?ri.CLOUD_PROXY_5:"proxy3"===t.cloudProxyServer||"proxy4"===t.cloudProxyServer?ri.CLOUD_PROXY:ri.CLOUD_PROXY_FALLBACK),p=performance.getEntriesByName(s),E=p[p.length-1];let m;return E&&(m={name:E.name,protocol:"nextHopProtocol"in E?E.nextHopProtocol:"",dnscost:"domainLookupEnd"in E&&"domainLookupStart"in E&&"number"==typeof E.domainLookupEnd&&"number"==typeof E.domainLookupStart?E.domainLookupEnd-E.domainLookupStart:-1,tcpTlsCost:"connectEnd"in E&&"connectStart"in E&&"number"==typeof E.connectEnd&&"number"==typeof E.connectStart?E.connectEnd-E.connectStart:-1,reqCost:"requestStart"in E&&"number"==typeof E.requestStart&&"responseEnd"in E&&"number"==typeof E.responseEnd?E.responseEnd-E.requestStart:-1,handleCost:"leave_ts"in a&&"enter_ts"in a&&"number"==typeof a.leave_ts&&"number"==typeof a.enter_ts?a.leave_ts-a.enter_ts:-1}),hs(l),{gatewayInfo:Qn(l,s),proxyInfo:u,url:s,resourceTimingInfo:m}}),(e=>{var i;return e.gatewayInfo&&G.joinChooseServer(t.sid,{role:d,lts:c,succ:!0,csAddr:s,serverList:e.gatewayInfo.gatewayAddrs.map((e=>e.address)),ec:null,opid:u,cid:e.gatewayInfo.cid.toString(),uid:e.gatewayInfo.uid.toString(),csIp:e.gatewayInfo.csIp,unilbsServerIds:r.toString(),isHttp3:o,corssRegionTagReq:t.apRequestDetail,corssRegionTagRes:e.gatewayInfo.res.detail&&e.gatewayInfo.res.detail[38],vid:null===(i=e.gatewayInfo)||void 0===i?void 0:i.vid,resourceTimingInfo:e.resourceTimingInfo?JSON.stringify(e.resourceTimingInfo):void 0}),e.proxyInfo&&G.joinWebProxyAP(t.sid,{lts:c,sucess:1,apServerAddr:s,turnServerAddrList:e.proxyInfo.addresses.map((e=>e.ip)).join(","),errorCode:null,eventType:t.cloudProxyServer,unilbsServerIds:r.toString()}),!1}),(e=>e.code!==W.OPERATION_ABORTED&&(e.code===W.CAN_NOT_GET_GATEWAY_SERVER?e.data.retry:(G.joinWebProxyAP(t.sid,{lts:c,sucess:0,apServerAddr:s,turnServerAddrList:null,errorCode:e.code,eventType:t.cloudProxyServer,unilbsServerIds:r.toString(),extend:JSON.stringify({networkState:_})}),B.warning("[".concat(t.clientId,"] multi unilbs network error, retry"),e),!0))),n)}const ls=(e,t,i,n,o,s)=>{const a=i.sid,r=i.clientId,c=i.cloudProxyServer,d=[],l=r=>{4096===r.flag?G.joinChooseServer(a,{role:i.role,lts:n,succ:!1,csAddr:t,opid:e.opid,serverList:null,ec:r.error.message,csIp:r.error.data&&r.error.data.csIp,unilbsServerIds:o.toString(),isHttp3:s,corssRegionTagReq:i.apRequestDetail}):1048576!==r.flag&&4194304!==r.flag&&4194310!==r.flag||G.joinWebProxyAP(a,{lts:n,sucess:0,apServerAddr:t,turnServerAddrList:null,errorCode:r.error.code,eventType:c,unilbsServerIds:o.toString()})};if(e.response_body.forEach((t=>{const i=t.buffer.code;if(23===t.uri&&0===i&&!t.buffer.edges_services)if(4194310===t.buffer.flag)B.warning("no edge services in ap response of proxy fallback, will not set proxy in iceServers"),t.buffer.edges_services=[];else{const i={error:new j(W.CAN_NOT_GET_GATEWAY_SERVER,"no edge services in ap response",{retry:ce("NO_EDGES_RETRY"),csIp:e.detail[502]}),flag:t.buffer.flag};d.push(i),l(i)}if(0!==i){const n=kn(i),o={error:new j(W.CAN_NOT_GET_GATEWAY_SERVER,n.desc,{desc:n.desc,retry:n.retry,csIp:e.detail[502]}),flag:t.buffer.flag};4194310===t.buffer.flag?B.warning(o.error.toString()):d.push(o),l(o)}})),d.length)throw B.warning("[".concat(r||"sid-".concat(a.slice(0,6)),"] multi unilbs ").concat(t," failed, ").concat(d.map((e=>"flag: ".concat(e.flag,", message: ").concat(e.error.message,", retry: ").concat(e.error.data.retry))).join(" | "))),new j(W.CAN_NOT_GET_GATEWAY_SERVER,d.map((e=>"flag: ".concat(e.flag,", message: ").concat(e.error.message))).join(" | "),{retry:!!d.find((e=>e.error.data.retry)),csIp:e.detail[502],desc:[...new Set(d.map((e=>{var t;return null==e||null===(t=e.error)||void 0===t||null===(t=t.data)||void 0===t?void 0:t.desc})).filter((e=>!!e)))]})},hs=e=>{var t,i,n,o;if(e.addresses&&0===e.addresses.length&&0===e.code)throw new j(W.CAN_NOT_GET_GATEWAY_SERVER,"void gateway address",{retry:!0,csIp:e.detail&&e.detail[502]});ce("AP_AREA")&&(null!==(n=e.detail)&&void 0!==n&&n[23]&&"string"==typeof(null===(o=e.detail)||void 0===o?void 0:o[23])?ns(e.detail[23].toLowerCase()):ns());if(null!==(t=e.detail)&&void 0!==t&&t[19]&&"string"==typeof(null===(i=e.detail)||void 0===i?void 0:i[19])){const t=e.detail[19],i=null==t?void 0:t.split(";");for(let t=0;t<i.length;t++){const n=i[t].trim(),o=e.addresses[t];o&&i&&!o.fingerprint&&(e.addresses[t].fingerprint=n)}}if(ce("GATEWAY_ADDRESS")&&ce("GATEWAY_ADDRESS").length>0){B.debug("assign gateway address to",ce("GATEWAY_ADDRESS"));const t=ce("GATEWAY_ADDRESS").map((t=>{var i,n,o,s;const a=null!==(i=null===(n=e.addresses.find((e=>e.ip===t.ip&&e.port===t.port)))||void 0===n?void 0:n.fingerprint)&&void 0!==i?i:"";return{ip:t.ip,port:t.port,ticket:e.addresses[0]&&e.addresses[0].ticket,fingerprint:a,iceUfrag:null===(o=e.addresses[0])||void 0===o?void 0:o.iceUfrag,icePwd:null===(s=e.addresses[0])||void 0===s?void 0:s.icePwd}}));e.addresses=t}},us=(e,t)=>{if(e.response_body&&e.response_body.length){const t=e.response_body[0];if(0!==t.buffer.code){const e=kn(t.buffer.code);throw new j(W.UPDATE_TICKET_FAILED,"[".concat(t.buffer.code,"]: ").concat(e.desc),{retry:e.retry})}return t.buffer.ticket}throw B.debug("update ticket request received ap response without response body:",t),new j(W.UPDATE_TICKET_FAILED,"cannot find response body from ap response",{retry:!1})},_s=(e,t,i)=>{const n=Math.floor(Math.random()*10**12),o="host"===e.role?"1":"audience"===e.role?"2":void 0,s={appid:e.appId,client_ts:Date.now(),opid:n,sid:e.sid,request_bodies:[{uri:22,buffer:{cname:e.cname,detail:ki(ki(ki({6:e.stringUid,11:t,12:ce("USE_NEW_TOKEN")?"1":void 0},o?{17:o}:{}),{},{22:t},e.apRequestDetail?{33:e.apRequestDetail}:{}),e.apRTM?{26:"RTM2"}:{}),key:e.token,service_ids:i,uid:e.uid||0}}]};s.request_bodies.forEach((t=>{e.multiIP&&e.multiIP.gateway_ip&&(t.buffer.detail[5]=JSON.stringify({vocs_ip:[e.multiIP.uni_lbs_ip],vos_ip:[e.multiIP.gateway_ip]}))}));const a=new FormData;return a.append("request",JSON.stringify(s)),[a,n]},ps=(e,t,i,n,o)=>{const s=Math.floor(Math.random()*10**12);return[di(e,t,n,o,{opid:s,mode:e.mode,codec:e.codec,hasChangeBGPAddress:!1,ortc:i}),s]},Es=(e,t)=>{const i=Math.floor(Math.random()*10**12),n={appid:e.appId,client_ts:Date.now(),opid:i,sid:e.sid,request_bodies:[{uri:28,buffer:{cname:e.cname,detail:{1:"",6:e.stringUid,12:"1"},token:e.token,service_ids:t,uid:e.uid||0,edges_services:e.apResponse.addresses.map((e=>({ip:e.ip,port:e.port})))}}]},o=new FormData;return o.append("request",JSON.stringify(n)),[o,i]};function ms(e){return Promise.all(e.map((e=>e.then((e=>{throw e}),(e=>e))))).then((e=>{throw e}),(e=>e))}const Ss=async e=>{let t=e.fragementLength,i=e.referenceList,n=e.asyncMapHandler,o=e.allFailedhandler,s=e.promisesCollector,a=0;const r=t;let c,d=0;const l=async()=>{const e=(()=>{const e=a*r,t=e+r;return i.slice(e,t).map(n)})();s&&s.push(...e);try{c=await ms(e)}catch(e){if(d+=r,a++,!(d>=i.length))return void await l();o(e)}e.forEach((e=>e.cancel()))};return await l(),c},fs=async e=>{let t=e.referenceList,i=e.asyncMapHandler,n=e.closeFn;const o=t.length;let s=0;const a=async()=>{const e=i(t.shift());try{return await e}catch(e){if(s++,s>=o||null!=n&&n(e))throw e;return a()}};return a()};async function Cs(){if("undefined"==typeof VideoDecoder)return!0;let e;const t=[18,0,10,13,0,0,0,3,180,253,144,6,136,8,8,8,32,50,85,16,66,128,2,8,32,132,0,8,0,180,90,204,169,166,242,109,241,190,143,149,160,133,4,144,43,122,168,159,120,159,205,39,82,131,57,52,87,187,68,23,248,134,204,226,97,17,49,183,55,236,219,249,221,98,208,215,190,59,179,167,213,47,1,246,150,14,194,245,159,83,35,64,103,218,38,21,82,3,135,21,185,84,248,134],i=[18,0,10,13,0,0,0,3,180,253,144,6,136,8,8,8,32,50,87,16,66,128,2,8,32,132,0,8,0,180,90,204,169,166,242,109,241,190,143,148,62,134,140,92,172,141,77,35,94,181,164,65,169,65,156,154,43,221,162,11,252,67,102,113,48,136,137,219,62,43,113,239,23,126,250,186,252,10,138,218,25,193,244,74,68,194,209,107,23,52,206,199,78,72,98,103,151,71,96,62,51,210,158,72,231,158],n=[18,0,10,13,0,0,0,3,180,253,144,6,136,8,8,8,32,50,87,16,66,128,2,8,32,132,0,8,0,180,90,204,169,166,242,109,241,190,143,143,233,163,51,196,98,95,151,224,22,134,33,240,150,248,67,18,34,196,142,81,238,173,140,80,205,232,132,144,67,12,131,157,4,171,243,86,122,35,6,166,184,243,85,126,13,206,103,152,62,168,160,187,2,241,138,52,211,72,121,128,151,63,147,128,19,42],o=[18,0,50,138,1,48,192,64,253,248,65,17,67,192,32,0,16,0,0,0,0,0,0,0,195,12,48,144,64,32,0,209,75,61,9,204,25,115,79,226,115,63,63,208,70,210,220,153,126,241,237,37,107,195,153,1,99,112,230,189,209,169,130,10,11,22,167,215,159,205,197,7,183,162,26,48,254,141,134,103,32,16,235,45,1,15,18,119,169,110,206,251,51,115,202,60,148,1,46,39,109,25,28,86,168,15,77,211,239,2,58,43,146,26,230,184,81,48,140,226,226,250,222,146,171,133,164,13,188,180,64,122,142,146,32,208,238,170,193,35,53,44,225],s=[18,0,50,107,48,0,133,125,248,65,26,195,64,62,32,31,16,0,0,0,0,0,1,4,16,64,144,64,32,0,204,24,122,65,56,165,18,52,206,218,4,187,51,97,9,29,191,90,253,106,185,31,197,155,52,205,245,185,203,131,20,226,25,124,95,113,220,113,141,15,15,104,211,144,152,237,150,157,127,51,143,24,231,218,171,255,176,241,128,229,149,150,148,66,245,228,91,27,182,228,136,61,182,237,133,45,220,24,103,214,152],a=[18,0,50,122,48,1,9,253,248,65,26,67,64,62,32,31,16,0,0,0,0,0,1,4,16,64,144,64,32,0,198,182,231,242,220,235,163,140,12,36,36,166,46,132,210,4,71,23,218,132,27,30,17,45,244,79,31,243,195,136,100,169,76,88,142,85,204,217,121,168,29,163,198,17,251,223,73,12,212,244,139,123,151,179,75,216,96,208,136,40,229,42,59,149,10,116,228,85,99,93,221,108,255,140,248,20,30,167,122,109,206,164,108,197,110,251,23,243,133,160,63,13,207,177,12,128];return await new Promise(((r,c)=>{let d;!async function(){e&&"closed"!==e.state||await async function(){e=new VideoDecoder({output:e=>{e.close(),clearTimeout(d),r(!0)},error:e=>{clearTimeout(d),r(!1)}}),await e.configure({codec:"av01.0.05M.08",width:160,height:90})}();const c=[t,i,n,o,s,a];for(let t=0;t<c.length;t++){const i=new EncodedVideoChunk({type:0==t?"key":"delta",timestamp:33333*t,duration:33333,data:new Uint8Array(c[t])});try{await e.decode(i)}catch(e){return void r(!1)}}}(),d=setTimeout((()=>{r(!1)}),5e3)}))}async function Rs(e,t,i,n){const o=async function(e,t,i,n){let o=null;const s=[],a=async()=>{const o=ce("WEBCS_DOMAIN").slice(0,ce("AJAX_REQUEST_CONCURRENT")).map((t=>({url:e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(t+"/api/v2/transpond/webrtc?v=2"):"https://".concat(t,"/api/v2/transpond/webrtc?v=2"),areaCode:Qo()}))),a=n.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:o.map((e=>e.url))}),r=await Ss({fragementLength:ce("FRAGEMENT_LENGTH"),referenceList:o,asyncMapHandler:n=>(B.debug("[".concat(e.clientId,"] Connect to choose_server:"),n.url),cs(n,e,t,i)),allFailedhandler:e=>{throw n.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},a),e[0]},promisesCollector:s});return n.recordJoinChannelService({endTs:Date.now(),status:"success"},a),r},r=async()=>{if(await fe(1e3),null!==o)return o;const a=ce("WEBCS_DOMAIN_BACKUP_LIST").map((t=>({url:e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(t+"/api/v2/transpond/webrtc?v=2"):"https://".concat(t,"/api/v2/transpond/webrtc?v=2"),areaCode:Qo()}))),r=n.recordJoinChannelService({endTs:void 0,startTs:Date.now(),status:"pending",service:"chooseServer",urls:a.map((e=>e.url))}),c=await Ss({fragementLength:ce("FRAGEMENT_LENGTH"),referenceList:a,asyncMapHandler:n=>(B.debug("[".concat(e.clientId,"] Connect to backup choose_server:"),n.url),cs(n,e,t,i)),allFailedhandler:e=>{throw n.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},r),e[0]},promisesCollector:s});return n.recordJoinChannelService({endTs:Date.now(),status:"success"},r),c};try{return o=await ms([a(),r()]),s.length&&s.forEach((e=>e.cancel&&"function"==typeof e.cancel&&e.cancel())),o}catch(e){throw e[0]}}(e,t,i,n);return{gatewayInfo:await o}}async function Ts(e,t,i,n,o){const s=e.cloudProxyServer;if("disabled"===s){if(!n)return;if(e.useLocalAccessPoint)return await Rs(e,t,i,o);if(ce("JOIN_WITH_FALLBACK_MEDIA_PROXY")){const n=await Ns(e,t,i,o),s=n.gatewayInfo,r=n.proxyInfo;if(e.turnServer&&"auto"!==e.turnServer.mode)return{gatewayInfo:s};const c=r.map((e=>({turnServerURL:e.address,tcpport:e.tcpport||ye.tcpport,udpport:e.udpport||ye.udpport,username:e.username||ye.username,password:e.password||ye.password,forceturn:!1,security:!0})));if(o.useP2P){var a;const t=null!==(a=e.uid)&&void 0!==a?a:s.uid,i="glb:".concat(t.toString()),n=await Ne(i),o=r.map((e=>({turnServerURL:e.address,tcpport:e.tcpport||ye.tcpport,udpport:e.udpport||ye.udpport,username:i,password:n,forceturn:!1,security:!0})));c.push(...o)}return e.turnServer={mode:"manual",servers:c},{gatewayInfo:s}}return await Rs(e,t,i,o)}const r=await Ns(e,t,i,o),c=r.proxyInfo,d=r.gatewayInfo,l={gatewayInfo:d},h=c.map((e=>({turnServerURL:e.address,tcpport:"proxy3"===s?void 0:e.tcpport?e.tcpport:ye.tcpport,udpport:"proxy4"===s?void 0:e.udpport?e.udpport:ye.udpport,username:e.username||ye.username,password:e.password||ye.password,forceturn:"proxy4"!==s,security:"proxy5"===s})));if(o.useP2P){var u;const t=null!==(u=e.uid)&&void 0!==u?u:d.uid,i="glb:".concat(t.toString()),n=await Ne(i),o=c.map((e=>({turnServerURL:e.address,tcpport:"proxy3"===s?void 0:e.tcpport||ye.tcpport,udpport:"proxy4"===s?void 0:e.udpport||ye.udpport,username:i,password:n,forceturn:"proxy4"!==s,security:"proxy5"===s})));h.push(...o)}return e.turnServer={mode:"manual",servers:h},B.debug("[".concat(e.clientId,"] set proxy server: ").concat(e.proxyServer,", mode: ").concat(s)),l}async function gs(e,t,i,n,o){const s=e.cloudProxyServer;if("disabled"===s){if(e.useLocalAccessPoint)return await Rs(e,t,i,n);if(ce("JOIN_WITH_FALLBACK_MEDIA_PROXY")){const s=await Ns(e,t,i,n,o),a=s.gatewayInfo,r=s.proxyInfo;if(e.turnServer&&"auto"!==e.turnServer.mode)return{gatewayInfo:a};const c=r.map((e=>({turnServerURL:e.address,tcpport:e.tcpport||ye.tcpport,udpport:e.udpport||ye.udpport,username:e.username||ye.username,password:e.password||ye.password,forceturn:!1,security:!0})));return e.turnServer={mode:"manual",servers:c},{gatewayInfo:a}}{const s=async function(e,t,i,n,o){let s=null;const a=[],r=async()=>{const s=ce("SDP_ENDPOINT_DOMAIN").slice(0,ce("AJAX_REQUEST_CONCURRENT")).map((t=>({url:e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(t+"/api/v3/transpond/webrtc?v=3"):"https://".concat(t,"/api/v3/transpond/webrtc?v=3"),areaCode:Qo()}))),r=o.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:s.map((e=>e.url))}),c=await Ss({fragementLength:ce("FRAGEMENT_LENGTH"),referenceList:s,asyncMapHandler:s=>(B.debug("[".concat(e.clientId,"] Connect to choose_server:"),s.url),rs(s,ri.CHOOSE_SERVER,e,t,o,i,n)),allFailedhandler:e=>{throw o.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},r),e[0]},promisesCollector:a});return o.recordJoinChannelService({endTs:Date.now(),status:"success"},r),c},c=async()=>{if(await fe(1e3),null!==s)return s;const r=ce("SDP_ENDPOINT_DOMAIN_BACKUP_LIST").map((t=>({url:e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(t+"/api/v3/transpond/webrtc?v=3"):"https://".concat(t,"/api/v3/transpond/webrtc?v=3"),areaCode:Qo()}))),c=o.recordJoinChannelService({endTs:void 0,startTs:Date.now(),status:"pending",service:"chooseServer",urls:r.map((e=>e.url))}),d=await Ss({fragementLength:ce("FRAGEMENT_LENGTH"),referenceList:r,asyncMapHandler:s=>(B.debug("[".concat(e.clientId,"] Connect to backup choose_server:"),s.url),rs(s,ri.CHOOSE_SERVER,e,t,o,i,n)),allFailedhandler:e=>{throw o.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},c),e[0]},promisesCollector:a});return o.recordJoinChannelService({endTs:Date.now(),status:"success"},c),d};try{return s=await ms([r(),c()]),a.length&&a.forEach((e=>e.cancel&&"function"==typeof e.cancel&&e.cancel())),s}catch(e){throw e[0]}}(e,o,t,i,n);return{gatewayInfo:await s}}}const a=await Ns(e,t,i,n),r=a.proxyInfo,c={gatewayInfo:a.gatewayInfo},d=r.map((e=>({turnServerURL:e.address,tcpport:"proxy3"===s?void 0:e.tcpport?e.tcpport:ye.tcpport,udpport:"proxy4"===s?void 0:e.udpport?e.udpport:ye.udpport,username:e.username||ye.username,password:e.password||ye.password,forceturn:"proxy4"!==s,security:"proxy5"===s})));return e.turnServer={mode:"manual",servers:d},B.debug("[".concat(e.clientId,"] set proxy server: ").concat(e.proxyServer,", mode: ").concat(s)),c}async function Is(e,t,i,n,o){const s=ce("ACCOUNT_REGISTER").slice(0,ce("AJAX_REQUEST_CONCURRENT"));let a=[];a=t.proxyServer?s.map((e=>"https://".concat(t.proxyServer,"/ap/?url=").concat(e+"/api/v1"))):s.map((e=>"https://".concat(e,"/api/v1")));const r=null==o?void 0:o.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"stringUID",urls:a});try{const s=await async function(e,t,i,n,o){const s=Date.now(),a={sid:i.sid,opid:10,appid:i.appId,string_uid:t};let r=e[0];const c=await Ge((()=>Xo(r+"".concat(-1===r.indexOf("?")?"?":"&","action=stringuid"),{data:a,cancelToken:n,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":72}})),((i,n)=>{if(0===i.code){if(i.uid<=0||i.uid>=Math.pow(2,32))throw B.error("Invalid Uint Uid ".concat(t," => ").concat(i.uid),i),G.reqUserAccount(a.sid,{lts:s,success:!1,serverAddr:r,stringUid:a.string_uid,uid:i.uid,errorCode:W.INVALID_UINT_UID_FROM_STRING_UID,extend:a}),new j(W.INVALID_UINT_UID_FROM_STRING_UID);return G.reqUserAccount(a.sid,{lts:s,success:!0,serverAddr:r,stringUid:a.string_uid,uid:i.uid,errorCode:null,extend:a}),!1}const o=kn(i.code);return o.retry&&(r=e[(n+1)%e.length]),G.reqUserAccount(a.sid,{lts:s,success:!1,serverAddr:r,stringUid:a.string_uid,uid:i.uid,errorCode:o.desc,extend:a}),o.retry}),((t,i)=>t.code!==W.OPERATION_ABORTED&&(G.reqUserAccount(a.sid,{lts:s,success:!1,serverAddr:r,stringUid:a.string_uid,uid:null,errorCode:t.code,extend:a}),r=e[(i+1)%e.length],!0)),o);if(0!==c.code){const e=kn(c.code);throw new j(W.UNEXPECTED_RESPONSE,e.desc)}return c}(a,e,t,i,n);return null==o||o.recordJoinChannelService({status:"success",endTs:Date.now()},r),s.uid}catch(e){throw null==o||o.recordJoinChannelService({status:"error",endTs:Date.now(),errors:[e]},r),e}}async function vs(e,t,i){const n=ce("ACCOUNT_REGISTER");let o=[];o=t.proxyServer?n.map((e=>"https://".concat(t.proxyServer,"/ap/?url=").concat(e+"/api/v1"))):n.map((e=>"https://".concat(e,"/api/v1")));try{const n=await fs({referenceList:o,asyncMapHandler:n=>async function(e,t,i,n){const o=Date.now(),s={sid:i.sid,opid:10,appid:i.appId,string_uid:t};try{const t=await Xo(e+"".concat(-1===e.indexOf("?")?"?":"&","action=stringuid"),{data:s,cancelToken:n,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":72}});if(0!==t.code){const e=kn(t.code);throw new j(W.UNEXPECTED_RESPONSE,"preload sua error:".concat(e.desc),e)}if(t.uid<=0||t.uid>=Math.pow(2,32))throw new j(W.INVALID_UINT_UID_FROM_STRING_UID);return{requestTime:o,url:e,req:s,uid:t.uid,elapse:Date.now()-o}}catch(e){throw e}}(n,e,t,i),closeFn:e=>e.code===ne.OPERATION_ABORTED||e.code===ne.UNEXPECTED_RESPONSE&&!e.data.retry});return n}catch(e){throw e}}async function As(e,t,i){const n=ce("CDS_AP").slice(0,ce("AJAX_REQUEST_CONCURRENT")).map((t=>e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(t+"/api/v1"):"https://".concat(t,"/api/v1?action=config"))).map((n=>function(e,t,i,n){const o=Pe(),s={flag:64,cipher_method:0,features:ki(ki(ki(ki(ki({install_id:We(),device:o.name,system:o.os,system_general:navigator.userAgent,vendor:t.appId,version:He,cname:t.cname,session_id:t.sid,proxyServer:t.proxyServer,sdk_type:Yo.WEB_RTC,browser_name:o.name,browser_version:o.version,user_agent:navigator.userAgent,channel_name:t.cname},t.stringUid&&{string_uid:t.stringUid}),t.uid&&{uid:t.uid+""}),o.os&&{os_name:o.os}),o.osVersion&&{os_version:o.osVersion}),{},{detail:""})};return Ge((()=>Xo(e,{data:s,timeout:1e3,cancelToken:i,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":54}})),void 0,(e=>e.code!==W.OPERATION_ABORTED),n)}(n,e,t,i)));let o=null,s=null,a={};try{o=await ms(n)}catch(e){if(e.code===ne.OPERATION_ABORTED)throw e;s=e}n.forEach((e=>e.cancel()));if(G.reportApiInvoke(e.sid,{name:Be.REQUEST_CONFIG_DISTRIBUTE,options:{error:s,res:o}}).onSuccess(),o&&o.test_tags)try{a=function(e){if(!e.test_tags)return{};const t=e.test_tags,i=Object.keys(t),n={};return i.forEach((e=>{const i=e.slice(4).trim(),o=JSON.parse(t[e]),s=o[1];n[i]={tag:o[0]||"",value:s}})),n}(o)}catch(e){}return a}async function ys(e,t){const i=ce("WEBCS_DOMAIN").concat(ce("WEBCS_DOMAIN_BACKUP_LIST")).map((e=>({url:"https://".concat(e,"/api/v2/transpond/webrtc?v=2"),areaCode:Qo(),serviceIds:[ri.CHOOSE_SERVER,ri.CLOUD_PROXY_FALLBACK]})));try{const n=await fs({referenceList:i,asyncMapHandler:i=>async function(e,t,i){let n,o=e.url,s=e.areaCode,a=e.serviceIds;const r=Date.now(),c=Mi(_s(t,s,a),2),d=c[0],l=c[1];let h=pe.networkState;try{h&&pe.networkState===_e.OFFLINE&&pe.onlineWaiter&&await Promise.race([pe.onlineWaiter,fe(Ke.maxRetryTimeout)]),h=pe.networkState;const e=await Xo(o,{data:d,cancelToken:i,headers:{"Content-Type":"multipart/form-data;"}},!0,!0),t=e.data;n="1"===e.headers.http3?1:-1,(e=>{const t=[];if(e.response_body.forEach((i=>{const n=i.buffer.code;if(23===i.uri&&0===n&&!i.buffer.edges_services)if(4194310===i.buffer.flag)i.buffer.edges_services=[];else{const n={error:new j(W.CAN_NOT_GET_GATEWAY_SERVER,"no edge services in ap response",{retry:ce("NO_EDGES_RETRY"),csIp:e.detail[502]}),flag:i.buffer.flag};t.push(n)}if(0!==n){const o=kn(n),s={error:new j(W.CAN_NOT_GET_GATEWAY_SERVER,o.desc,{desc:o.desc,retry:o.retry,csIp:e.detail[502]}),flag:i.buffer.flag};4194310===i.buffer.flag?B.warning(s.error.toString()):t.push(s)}})),t.length)throw new j(W.CAN_NOT_GET_GATEWAY_SERVER,t.map((e=>"flag: ".concat(e.flag,", message: ").concat(e.error.message))).join(" | "),{retry:!!t.find((e=>e.error.data.retry)),csIp:e.detail[502],desc:[...new Set(t.map((e=>{var t;return null==e||null===(t=e.error)||void 0===t||null===(t=t.data)||void 0===t?void 0:t.desc})).filter((e=>!!e)))]})})(t);const s=eo(t,ri.CHOOSE_SERVER),a=eo(t,ri.CLOUD_PROXY_FALLBACK);return hs(s),{gatewayInfo:Qn(s,o),proxyInfo:a,opid:l,requestTime:r,url:o,isHttp3:n,elapse:Date.now()-r}}catch(e){throw e}}(i,e,t),closeFn:e=>e.code===ne.OPERATION_ABORTED||e.code===ne.CAN_NOT_GET_GATEWAY_SERVER&&!e.data.retry});return n}catch(e){throw e}}async function Ns(e,t,i,n,o){const s=ce("PROXY_SERVER_TYPE3"),a=(e,t,i)=>{let n=i||s;return Array.isArray(n)&&(n=t%2==0&&s[1]||s[0]),"https://".concat(n,"/ap/?url=").concat(e)};let r=null;const c=[],d=async()=>{const s=ce(o?"SDP_ENDPOINT_DOMAIN":"WEBCS_DOMAIN").slice(0,ce("AJAX_REQUEST_CONCURRENT")).map(((t,i)=>{let n;return n="disabled"===e.cloudProxyServer&&e.proxyServer?a("".concat(t,"/").concat(o?"api/v3/transpond/webrtc?v=3":"api/v2/transpond/webrtc?v=2"),i,e.proxyServer):"disabled"===e.cloudProxyServer||"fallback"===e.cloudProxyServer?"https://".concat(t,"/").concat(o?"api/v3/transpond/webrtc?v=3":"api/v2/transpond/webrtc?v=2"):a("".concat(t,"/").concat(o?"api/v3/transpond/webrtc?v=3":"api/v2/transpond/webrtc?v=2"),i),{url:n,areaCode:Qo(),serviceIds:[ri.CHOOSE_SERVER,"proxy5"===e.cloudProxyServer?ri.CLOUD_PROXY_5:"proxy3"===e.cloudProxyServer||"proxy4"===e.cloudProxyServer?ri.CLOUD_PROXY:ri.CLOUD_PROXY_FALLBACK]}})),r=n.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:s.map((e=>e.url))}),d=await Ss({fragementLength:ce("FRAGEMENT_LENGTH"),referenceList:s,asyncMapHandler:s=>(B.debug("[".concat(e.clientId,"] Connect to choose_server:"),s.url),o?rs(s,s.serviceIds,e,o,n,t,i):ds(s,e,t,i)),allFailedhandler:e=>{throw n.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},r),e[0]},promisesCollector:c});return n.recordJoinChannelService({endTs:Date.now(),status:"success"},r),d},l=async()=>{if(await fe(1e3),null!==r)return r;const s=ce(o?"SDP_ENDPOINT_DOMAIN_BACKUP_LIST":"WEBCS_DOMAIN_BACKUP_LIST").map(((t,i)=>{let n;return n="disabled"===e.cloudProxyServer&&e.proxyServer?a("".concat(t,"/").concat(o?"api/v3/transpond/webrtc?v=3":"api/v2/transpond/webrtc?v=2"),i,e.proxyServer):"disabled"===e.cloudProxyServer||"fallback"===e.cloudProxyServer?"https://".concat(t,"/").concat(o?"api/v3/transpond/webrtc?v=3":"api/v2/transpond/webrtc?v=2"):a("".concat(t,"/").concat(o?"api/v3/transpond/webrtc?v=3":"api/v2/transpond/webrtc?v=2"),i),{url:n,areaCode:Qo(),serviceIds:[ri.CHOOSE_SERVER,"proxy5"===e.cloudProxyServer?ri.CLOUD_PROXY_5:"proxy3"===e.cloudProxyServer||"proxy4"===e.cloudProxyServer?ri.CLOUD_PROXY:ri.CLOUD_PROXY_FALLBACK]}})),d=n.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:s.map((e=>e.url))}),l=await Ss({fragementLength:ce("FRAGEMENT_LENGTH"),referenceList:s,asyncMapHandler:s=>(B.debug("[".concat(e.clientId,"] Connect to backup choose_server:"),s.url),o?rs(s,s.serviceIds,e,o,n,t,i):ds(s,e,t,i)),allFailedhandler:e=>{throw n.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},d),e[0]},promisesCollector:c});return n.recordJoinChannelService({endTs:Date.now(),status:"success"},d),l};let h,u,_;try{var p=await ms([d(),l()]);h=p.gatewayInfo,u=p.proxyInfo,_=p.url}catch(e){throw e[0]}if(c.length&&c.forEach((e=>e.cancel&&"function"==typeof e.cancel&&e.cancel())),!h||!u)throw new j(ne.UNEXPECTED_ERROR,"missing gateway or proxy response").print();if(e.apUrl=_,"disabled"!==e.cloudProxyServer&&Array.isArray(s)&&_){const t=/^https?:\/\/(.+?)(\/.*)?$/.exec(_)[1];s.includes(t)&&(e.proxyServer=t,B.setProxyServer(t),G.setProxyServer(t))}return r={gatewayInfo:h,proxyInfo:await to(u,h.uid)},r}async function ws(e,t,i){let n=null;const o=[],s=async s=>{const a=ce(s?"WEBCS_DOMAIN_BACKUP_LIST":"WEBCS_DOMAIN").map((t=>e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(t+"/api/v2/transpond/webrtc?v=2"):"https://".concat(t,"/api/v2/transpond/webrtc?v=2")));return s&&(await fe(1e3),null!==n)?n:await Ss({fragementLength:ce("FRAGEMENT_LENGTH"),referenceList:a,asyncMapHandler:n=>(B.debug("[".concat(e.clientId,"] update ticket, Connect to ").concat(s?"backup":""," choose_server:"),n),function(e,t,i,n){const o=Mi(Es(t,[ri.CHOOSE_SERVER]),1)[0];let s=pe.networkState;return Ge((async()=>{s&&pe.networkState===_e.OFFLINE&&pe.onlineWaiter&&await Promise.race([pe.onlineWaiter,fe(n&&n.maxRetryTimeout||Ke.maxRetryTimeout)]),s=pe.networkState;const t=await Xo(e,{data:o,cancelToken:i,headers:{"Content-Type":"multipart/form-data;"}},!0);return us(t,e)}),(()=>!1),(e=>e.code!==W.OPERATION_ABORTED&&(e.code===W.UPDATE_TICKET_FAILED?e.data.retry:(B.warning("[".concat(t.clientId,"] update ticket network error, retry"),e),!0))),n)}(n,e,t,i)),allFailedhandler:e=>{throw e[0]},promisesCollector:o})};try{return n=await ms([s(!1),s(!0)]),o.length&&o.forEach((e=>e.cancel&&"function"==typeof e.cancel&&e.cancel())),n}catch(e){throw e[0]}}const bs="/ping",Os="/api/v1?action=stringuid",Ds=JSON.stringify({sid:"",opid:10,appid:"",string_uid:""}),Ps=["oceania","south-america","africa"],Ls=55e3,ks=1e4,Ms=2147483647;function Us(e){const t=Number(e);return!Number.isFinite(t)||t<ks?Ls:Math.min(t,Ms)}let Vs=new class{constructor(){this.hasClient=!1,this.activeJoinClientIds=new Set,this.timer=void 0,this.lastTickAt=void 0,this.pendingOrigins=new Set,this.visibilityListenerAttached=!1,this.onVisibilityChange=()=>{xs((()=>{"visible"===document.visibilityState?this.scheduleNext():this.clearTimer()}))}}onCreateClient(){this.hasClient||(this.hasClient=!0,this.scheduleNext())}syncConfig(){this.scheduleNext()}onJoin(e){this.activeJoinClientIds.has(e)||(this.activeJoinClientIds.add(e),this.clearTimer())}onLeave(e){!this.activeJoinClientIds.delete(e)||this.activeJoinClientIds.size>0||this.scheduleNext()}dispose(){this.clearTimer(),this.pendingOrigins.clear(),this.lastTickAt=void 0,this.hasClient=!1,this.activeJoinClientIds.clear(),this.removeVisibilityListener()}scheduleNext(){this.clearTimer();const e=this.readConfig();if(!e.enabled)return void this.removeVisibilityListener();if(!this.hasClient||this.activeJoinClientIds.size>0)return;if(this.ensureVisibilityListener(),!this.isPageVisible())return;if(void 0!==this.lastTickAt&&!e.keepalive)return void this.removeVisibilityListener();const t=Date.now(),i=void 0===this.lastTickAt?0:Math.max(0,Math.min(this.lastTickAt+e.intervalMs-t,Ms));this.timer=window.setTimeout((()=>{this.timer=void 0,xs((()=>this.runTick()))}),i)}runTick(){const e=this.readConfig();if(!(this.activeJoinClientIds.size>0)&&this.hasClient&&e.enabled&&this.isPageVisible()){this.lastTickAt=Date.now();try{this.buildPlans(e).forEach((e=>this.executePlan(e)))}finally{this.scheduleNext()}}else this.scheduleNext()}executePlan(e){try{if("report"===e.mode)return void this.reportAttempt(e);if(this.pendingOrigins.has(e.origin))return;const t=fetch(e.url,function(e){return e.url!=="".concat(e.origin).concat(bs)?{method:"POST",mode:"cors",credentials:"omit",headers:{"Content-Type":"application/json","X-Packet-Service-Type":"0","X-Packet-URI":"72"},body:Ds}:{method:"HEAD",mode:"no-cors",credentials:"omit",cache:"no-store"}}(e));this.pendingOrigins.add(e.origin),t.then((()=>this.pendingOrigins.delete(e.origin)),(()=>this.pendingOrigins.delete(e.origin))),this.reportAttempt(e)}catch(t){B.debug("createClient preconnect failed",e.origin,t)}}reportAttempt(e){G.reportCreateClientPreconnect({targets:e.targets,mode:e.mode,origin:e.origin})}buildPlans(e){const t=e.mode,i=[{target:"ap",domains:ce("WEBCS_DOMAIN")},{target:"sdpendpoint",domains:ce("SDP_ENDPOINT_DOMAIN")},{target:"sua",domains:ce("ACCOUNT_REGISTER")}],n=new Map;return i.forEach((e=>{let i=e.target;const o=function(e){if(!Array.isArray(e))return;return e.find((e=>"string"==typeof e&&e.length>0))||void 0}(e.domains);if(!o)return;const s=function(e){try{const t=new URL(e.includes("://")?e:"https://".concat(e));return"https:"===t.protocol?t.origin:void 0}catch(e){return}}(o);if(!s)return;if("sua"===i&&Ps.some((e=>s.includes(e))))return;const a=function(e,t){return"sua"===t?"".concat(e).concat(Os):"".concat(e).concat(bs)}(s,i),r=n.get(s);if(r)return r.targets.includes(i)||r.targets.push(i),void("request"===t&&"sua"===i&&(r.url=a));n.set(s,{origin:s,url:a,targets:[i],mode:t})})),Array.from(n.values())}readConfig(){return{enabled:!0===ce("ENABLE_CREATE_CLIENT_PRECONNECT"),mode:(e=ce("CREATE_CLIENT_PRECONNECT_MODE"),"request"===e?"request":"report"),keepalive:!0===ce("CREATE_CLIENT_PRECONNECT_KEEPALIVE"),intervalMs:Us(ce("CREATE_CLIENT_PRECONNECT_INTERVAL_MS"))};var e}isPageVisible(){return"undefined"==typeof document||"visible"===document.visibilityState}ensureVisibilityListener(){this.visibilityListenerAttached||"undefined"==typeof document||(document.addEventListener("visibilitychange",this.onVisibilityChange),this.visibilityListenerAttached=!0)}removeVisibilityListener(){this.visibilityListenerAttached&&"undefined"!=typeof document&&document.removeEventListener("visibilitychange",this.onVisibilityChange),this.visibilityListenerAttached=!1}clearTimer(){void 0!==this.timer&&(window.clearTimeout(this.timer),this.timer=void 0)}};function xs(e){try{e()}catch(e){B.debug("createClient preconnect action failed",e)}}function Fs(e){xs((()=>Vs.onLeave(e)))}function Bs(e){let t=!0;return function(e){xs((()=>Vs.onJoin(e)))}(e),{markJoined:()=>{t=!1},releaseIfNotJoined:()=>{t&&(t=!1,Fs(e))}}}class js extends re{get isSuccess(){return!!this.configs}constructor(e,t){super(),this.configs=void 0,this.store=void 0,this.joinInfo=void 0,this.cancelToken=void 0,this.retryConfig={timeout:3e3,timeoutFactor:1.5,maxRetryCount:1,maxRetryTimeout:1e4},this.interval=void 0,this.mutex=void 0,this.mutableParamsRead=!1,this.configCache={},this.limit_bitrate=void 0,this.mutex=new ue("config-distribute",e),this.store=t}startGetConfigDistribute(e,t){this.joinInfo=e,this.cancelToken=t,this.interval&&this.stopGetConfigDistribute(),ce("ENABLE_CONFIG_DISTRIBUTE")&&(this.updateConfigDistribute(),this.interval=window.setInterval((()=>{this.updateConfigDistribute()}),ce("CONFIG_DISTRIBUTE_INTERVAL")))}stopGetConfigDistribute(){this.interval&&clearInterval(this.interval),this.interval=void 0,this.joinInfo=void 0,this.cancelToken=void 0,this.configs=void 0,this.limit_bitrate=void 0}async awaitConfigDistributeComplete(){if(!this.mutex.isLocked)return;(await this.mutex.lock())()}async updateConfigDistribute(){if(!this.mutableParamsRead){this.mutableParamsRead=!0;G.reportApiInvoke(null,{options:void 0,name:Be.LOAD_CONFIG_FROM_LOCALSTORAGE,tag:je.TRACER}).onSuccess(JSON.stringify($))}if(!this.joinInfo||!this.cancelToken||!this.retryConfig)return void B.debug("[config-distribute] get config distribute interrupted have no joininfo");let e;const t=await this.mutex.lock();try{e=await As(this.joinInfo,this.cancelToken,this.retryConfig),B.debug("[config-distribute] get config distribute",JSON.stringify(e));const i=Gs(e);this.cacheGlobalParameterConfig(i),this.store.hasStartJoinChannel||(this.store.isABTestSuccess=!0),this.configs=i}catch(e){const t=new j(ne.NETWORK_RESPONSE_ERROR,e);B.warning("[config-distribute] ".concat(t.toString()))}finally{t()}}getBitrateLimit(){return this.limit_bitrate||void 0}handleBitrateLimit(e){pn(e)&&(this.limit_bitrate?this.limit_bitrate&&this.limit_bitrate.id!==e.id&&this.emit(_n.UPDATE_BITRATE_LIMIT,e):this.emit(_n.UPDATE_BITRATE_LIMIT,e))}getLowStreamConfigDistribute(){return this.limit_bitrate&&ki({},this.limit_bitrate.low_stream_uplink)}handleABTestConfigDistribute(e){try{const t={},i=Object.keys(e),n=[];i.forEach((i=>{const o=e[i].value;t[i]=o;const s=o.__id;if(s&&this.configCache[i]&&this.configCache[i].__id===s)return;const a=o.__type,r=e[i].value,c=e[i].tag;let d=0;a?a===te.REALTIME&&(d=1):Object.keys(r).some((e=>Object.prototype.hasOwnProperty.call(ie,e)||!vi()&&Object.prototype.hasOwnProperty.call(ee,e)?(d=1,!0):void 0)),n.push({tag:c,isApplied:d,feature:i,params:JSON.stringify(o)})})),n.forEach((e=>{let t=e.tag,i=e.feature,n=e.params,o=e.isApplied;this.store.sessionId&&G.abTest(this.store.sessionId,{intSucc:1,isApplied:o,tag:t,feature:i,params:n,cid:this.store.cid,uid:this.store.intUid})})),this.configCache=t}catch(e){B.debug("handleABTestConfigDistribute error",e)}}cacheGlobalParameterConfig(e){const t=function(e){const t={};return Object.keys(e).forEach((i=>{const n=e[i].value,o=n.__expires,s=n.__type;Object.keys(n).forEach((e=>{"__id"===e||"__type"===e||"__priority"===e||"__expires"===e||Object.prototype.hasOwnProperty.call(t,e)||(t[e]=ki(ki({value:n[e]},o&&{expires:o}),s&&{type:s}))}))})),t}(e);try{var i;const n=null===(i=t.LIMIT_BITRATE)||void 0===i?void 0:i.value;if(delete t.LIMIT_BITRATE,n&&pn(n)&&this.handleBitrateLimit(n),this.limit_bitrate=n,this.handleGlobalParameterConfig(t),this.handleABTestConfigDistribute(e),function(e){try{const t=Date.now();Object.keys(e).forEach((i=>{const n=e[i],o=n.value,s=n.type,a=n.expires;a&&a<=t||((s===te.REALTIME||Object.prototype.hasOwnProperty.call(ie,i))&&($[i]=o,Z[i]=o,B.debug("Update realtime parameters from config distribute",i,o)),s||vi()||!Object.prototype.hasOwnProperty.call(ee,i)||($[i]=o,Z[i]=o,B.debug("Update gateway parameters from config distribute",i,o)))}))}catch(t){B.error("Error update config immediately: ".concat(e),t.message)}}(t),H(t))return B.debug("[warning] [config-distribute] blocked config detected and skipped"),void G.reportAlarm(this.store.sessionId||null,{type:K.CONFIG_DISTRIBUTE,status:Y.RECOVER,message:"Blocked config detected and skipped"});q(t),xs((()=>Vs.syncConfig()));const o=JSON.stringify(t),s=window.btoa(o);window.localStorage.setItem("websdk_ng_global_parameter",s),B.debug("Caching global parameters ".concat(o))}catch(e){B.error("Error caching global parameters:",e.message)}}handleGlobalParameterConfig(e){try{const t=Date.now();Object.keys(e).forEach((i=>{switch(i){case"CLIENT_ROLE_OPTIONS":if(Object.prototype.hasOwnProperty.call(Z,i)){const n=e[i],o=n.value,s=n.expires;if(s&&s<=t)return;Ye(Z[i],o)||($[i]=o,Z[i]=o,this.emit(_n.UPDATE_CLIENT_ROLE_OPTIONS,o),B.debug("Updating client role options: ".concat(JSON.stringify(o))))}break;case"REMOTE_VIDEO_STREAM_TYPE":if(Object.prototype.hasOwnProperty.call(Z,i)){const n=e[i],o=n.value,s=n.expires;if(s&&s<=t)return;"number"==typeof o&&[0,1,4,5,6,7,8,9].includes(o)&&($[i]={value:o},Z[i]=o,this.emit(_n.UPDATE_REMOTE_VIDEO_STREAM_TYPE,o),B.debug("Updating client remote stream type: ".concat(JSON.stringify(o))))}break;case"ENABLE_FORCE_HLS":if(Object.prototype.hasOwnProperty.call(Z,i)){const n=e[i],o=n.value,s=n.expires;if(s&&s<=t)return;Ye(Z[i],o)||($[i]=o,Z[i]=o,this.emit(_n.FALLBACK_TO_HLS,o),B.debug("Updating enable force hls: ".concat(JSON.stringify(o))))}break;case"VOS_CONFIGURE":if(Object.prototype.hasOwnProperty.call(Z,i)){const n=e[i],o=n.value,s=n.expires;if(s&&s<=t)return;Ye(Z[i],o)||($[i]=o,Z[i]=o,this.emit(_n.UPDATE_VOS_CONFIGURE,o),B.debug("Updating vos configure: ".concat(JSON.stringify(o))))}}}))}catch(e){B.error("Error handling global parameter config:",e.message)}}}function Gs(e){const t=Object.keys(e).filter((e=>/^webrtc_ng_global_parameter/.test(e))).sort();for(let i=0;i<t.length;i++)for(let n=t.length-1;n>i;n--){const i=t[n],o=e[i].value;if("number"==typeof o.__priority){const s=o.__priority,a=t[n-1],r=e[a].value;if("number"==typeof r.__priority){if(!(s>r.__priority))continue;{const e=i;t[n]=t[n-1],t[n-1]=e}}else{const e=i;t[n]=t[n-1],t[n-1]=e}}}const i=Date.now(),n={};return t.forEach((t=>{const o=e[t].value.__expires;o&&o<=i||(n[t]=e[t])})),n}async function Ws(e,t,i){let n;try{n=await As(e,t,i),B.debug("[requestConfigDistribute] get config distribute",JSON.stringify(n));return Gs(n)}catch(e){const t=new j(ne.NETWORK_RESPONSE_ERROR,e);B.warning("[requestConfigDistribute] ".concat(t.toString()))}}class Hs extends re{constructor(){super(...arguments),this.resultStorage=new Map}setLocalAudioStats(e,t,i){this.record("AUDIO_INPUT_LEVEL_TOO_LOW",e,this.checkAudioInputLevel(i,t)),this.record("SEND_AUDIO_BITRATE_TOO_LOW",e,this.checkSendAudioBitrate(i,t))}setLocalVideoStats(e,t,i){this.record("SEND_VIDEO_BITRATE_TOO_LOW",e,this.checkSendVideoBitrate(i,t)),this.record("FRAMERATE_INPUT_TOO_LOW",e,this.checkFramerateInput(i,t)),this.record("FRAMERATE_SENT_TOO_LOW",e,this.checkFramerateSent(i)),!t.muted&&this.record("VIDEO_ENCODE_FAILED",e,this.checResolutionSent(i))}setRemoteAudioStats(e,t){const i=e.getUserId();this.record("AUDIO_OUTPUT_LEVEL_TOO_LOW",i,this.checkAudioOutputLevel(t))}setRemoteVideoStats(e,t){const i=e.getUserId();this.record("RECV_VIDEO_DECODE_FAILED",i,this.checkVideoDecode(t))}record(e,t,i){if(ce("STATS_UPDATE_INTERVAL")>500)return;this.resultStorage.has(e)||this.resultStorage.set(e,{result:[],isPrevNormal:!0});const n=this.resultStorage.get(e);if(!n)return;n.result.push(i);const o="VIDEO_ENCODE_FAILED"===e?ce("ENCODE_EXCEPTION_TIMES"):5;if(n.result.length>=o){const i=n.result.includes(!0);n.isPrevNormal&&!i&&this.emit("exception",Ks[e],e,t),!n.isPrevNormal&&i&&this.emit("exception",Ks[e]+2e3,e+"_RECOVER",t),n.isPrevNormal=i,n.result=[]}}checkAudioOutputLevel(e){return!(e.receiveBitrate>0&&0===e.receiveLevel)}checkAudioInputLevel(e,t){return t instanceof a&&!t.isActive||(!!t.muted||0!==e.sendVolumeLevel)}checkFramerateInput(e,t){let i=null;t._encoderConfig&&t._encoderConfig.frameRate&&(i=zn(t._encoderConfig.frameRate));const n=e.captureFrameRate;return!i||!n||!(i>10&&n<5||i<10&&i>=5&&n<=1)}checkFramerateSent(e){return!(e.captureFrameRate&&e.sendFrameRate&&e.captureFrameRate>5&&e.sendFrameRate<=1)}checResolutionSent(e){return!(!e.codecType||ce("ENCODE_EXCEPTION_VALIDATE_CODEC").includes(e.codecType.toLocaleLowerCase()))||(!e.captureFrameRate||0!==e.sendFrameRate||0!==e.sendResolutionWidth||0!==e.sendResolutionHeight)}checkSendVideoBitrate(e,t){return!!t.muted||0!==e.sendBitrate}checkSendAudioBitrate(e,t){return t instanceof a&&!t.isActive||(!!t.muted||0!==e.sendBitrate)}checkVideoDecode(e){return 0===e.receiveBitrate||0!==e.decodeFrameRate}}const Ks={FRAMERATE_INPUT_TOO_LOW:1001,FRAMERATE_SENT_TOO_LOW:1002,SEND_VIDEO_BITRATE_TOO_LOW:1003,RECV_VIDEO_DECODE_FAILED:1005,AUDIO_INPUT_LEVEL_TOO_LOW:2001,AUDIO_OUTPUT_LEVEL_TOO_LOW:2002,SEND_AUDIO_BITRATE_TOO_LOW:2003,VIDEO_ENCODE_FAILED:2004};const Ys=new class{markSubscribeStart(e,t){performance.mark("agora-web-sdk/".concat(e,"/subscribe-").concat(t))}markPublishStart(e,t){performance.mark("agora-web-sdk/".concat(e,"/publish-").concat(t))}measureFromSubscribeStart(e,t){const i=performance.getEntriesByName("agora-web-sdk/".concat(e,"/subscribe-").concat(t));if(i.length>0){const e=i[i.length-1];return Math.round(performance.now()-e.startTime)}return 0}measureFromPublishStart(e,t){const i=performance.getEntriesByName("agora-web-sdk/".concat(e,"/publish-").concat(t));if(i.length>0){const e=i[i.length-1];return Math.round(performance.now()-e.startTime)}return 0}};class qs{constructor(e){this.store=void 0,this.onStatsException=void 0,this.onUploadPublishDuration=void 0,this.onStatsChanged=void 0,this.onVideoCodecChanged=void 0,this.localStats=new Map,this.remoteStats=new Map,this.updateStatsInterval=void 0,this.trafficStats=void 0,this.trafficStatsPeerList=[],this.uplinkStats=void 0,this.exceptionMonitor=void 0,this.p2pChannel=void 0,this.scalabilityMode=we.L1T1,this.updateStats=()=>{this.p2pChannel&&(this.updateRemoteStats(this.p2pChannel),this.updateLocalStats(this.p2pChannel))},this.store=e,this.exceptionMonitor=new Hs,this.exceptionMonitor.on("exception",((e,t,i)=>{this.onStatsException&&this.onStatsException(e,t,i)}))}startUpdateStats(){this.updateStatsInterval||(this.updateStatsInterval=window.setInterval(this.updateStats,1e3))}stopUpdateStats(){this.updateStatsInterval&&(window.clearInterval(this.updateStatsInterval),this.updateStatsInterval=void 0)}reset(){this.localStats=new Map,this.remoteStats=new Map,this.trafficStats=void 0,this.trafficStatsPeerList=[],this.uplinkStats=void 0}getLocalAudioTrackStats(){return this.localStats.get(Tn.LocalAudioTrack)||ki({},r)}getLocalVideoTrackStats(){return this.localStats.get(Tn.LocalVideoTrack)||ki({},c)}getRemoteAudioTrackStats(e){const t=(e,t)=>{if(!this.trafficStats)return t;const i=this.trafficStats.peer_delay.find((t=>t.peer_uid===e));return i&&(t.publishDuration=i.B_ppad+(Date.now()-this.trafficStats.timestamp)),t},i={};if(e){var n;const o=null===(n=this.remoteStats.get(e))||void 0===n?void 0:n.audioStats;o&&(i[e]=t(e,o))}else Array.from(this.remoteStats.entries()).forEach((e=>{let n=Mi(e,2),o=n[0],s=n[1].audioStats;s&&(i[o]=t(o,s))}));return i}getRemoteNetworkQualityStats(e){const t={};if(e){var i;const n=null===(i=this.remoteStats.get(e))||void 0===i?void 0:i.networkStats;n&&(t[e]=n)}else Array.from(this.remoteStats.entries()).forEach((e=>{let i=Mi(e,2),n=i[0],o=i[1].networkStats;o&&(t[n]=o)}));return t}getNetworkQuality(){let e=0,t=0;return this.trafficStats&&(e=$n(this.trafficStats.B_unq),t=$n(this.trafficStats.B_dnq)),{uplinkNetworkQuality:e,downlinkNetworkQuality:t}}getRemoteVideoTrackStats(e){const t=(e,t)=>{if(!this.trafficStats)return t;const i=this.trafficStats.peer_delay.find((t=>t.peer_uid===e));return i&&(t.publishDuration=i.B_ppvd+(Date.now()-this.trafficStats.timestamp)),t},i={};if(e){var n;const o=null===(n=this.remoteStats.get(e))||void 0===n?void 0:n.videoStats;o&&(i[e]=t(e,o))}else Array.from(this.remoteStats.entries()).forEach((e=>{let n=Mi(e,2),o=n[0],s=n[1].videoStats;s&&(i[o]=t(o,s))}));return i}getRTCStats(){let e=0,t=0,i=0,n=0;const o=this.localStats.get(Tn.LocalAudioTrack);o&&(e+=o.sendBytes,t+=o.sendBitrate);const s=this.localStats.get(Tn.LocalVideoTrack);s&&(e+=s.sendBytes,t+=s.sendBitrate);const a=this.localStats.get(Tn.LocalVideoLowTrack);a&&(e+=a.sendBytes,t+=a.sendBitrate),this.remoteStats.forEach((e=>{let t=e.audioStats,o=e.videoStats;t&&(i+=t.receiveBytes,n+=t.receiveBitrate),o&&(i+=o.receiveBytes,n+=o.receiveBitrate)}));let r=1;return this.trafficStats&&(r+=this.trafficStats.peer_delay.length),{Duration:0,UserCount:r,SendBitrate:t,SendBytes:e,RecvBytes:i,RecvBitrate:n,OutgoingAvailableBandwidth:this.uplinkStats?this.uplinkStats.B_uab/1e3:0,RTT:this.trafficStats?2*this.trafficStats.B_acd:0}}addLocalStats(e){this.localStats.set(e,void 0)}removeLocalStats(e){e?this.localStats.delete(e):this.localStats.clear()}addRemoteStats(e){this.remoteStats.set(e,{})}removeRemoteStats(e){e?this.remoteStats.delete(e):this.remoteStats.clear()}addP2PChannel(e){this.p2pChannel=e}updateTrafficStats(e){e.peer_delay=e.peer_delay.filter((e=>void 0!==e.B_ppad||void 0!==e.B_ppvd));e.peer_delay.filter((e=>-1===this.trafficStatsPeerList.indexOf(e.peer_uid))).forEach((e=>{var t;const i=null===(t=this.p2pChannel)||void 0===t?void 0:t.getRemoteMedia(e.peer_uid),n=null!=i&&i.videoSSRC?Ys.measureFromSubscribeStart(this.store.clientId,i.videoSSRC):0,o=null!=i&&i.audioSSRC?Ys.measureFromSubscribeStart(this.store.clientId,i.audioSSRC):0;void 0!==e.B_ppad&&void 0!==e.B_ppvd&&(this.onUploadPublishDuration&&this.onUploadPublishDuration(e.peer_uid,e.B_ppad,e.B_ppvd,n>o?n:o),this.trafficStatsPeerList.push(e.peer_uid))})),this.trafficStats=e}updateUplinkStats(e){this.uplinkStats&&this.uplinkStats.B_fir!==e.B_fir&&B.debug("[".concat(this.store.clientId,"]: Period fir changes to ").concat(e.B_fir)),this.uplinkStats=e}static isRemoteVideoFreeze(e,t,i){if(!e)return!1;const n=!!i&&t.framesDecodeFreezeTime>i.framesDecodeFreezeTime,o=!i||t.framesDecodeCount>i.framesDecodeCount;return n||!o}static isRemoteAudioFreeze(e){return!!e&&e._isFreeze()}isLocalVideoFreeze(e){return!(!e.inputFrame||!e.sentFrame)&&(e.inputFrame.frameRate>5&&e.sentFrame.frameRate<3)}updateLocalStats(e){Array.from(this.localStats.entries()).forEach((t=>{let i=Mi(t,2),n=i[0],o=i[1];switch(n){case Tn.LocalVideoTrack:case Tn.LocalVideoLowTrack:{const t=o,i=ki({},c),r=e.getStats(),d=e.getLocalMedia(n);if(r){const n=r.videoSend.find((e=>e.ssrc===(null==d?void 0:d.ssrcs[0].ssrcId)));if(n){const o=e.getLocalVideoSize(),a=e.getEncoderConfig(Tn.LocalVideoTrack);var s;if("H264"===n.codec||"H265"===n.codec||"VP8"===n.codec||"VP9"===n.codec||"AV1X"===n.codec||"AV1"===n.codec)if(i.codecType=n.codec,(null==t?void 0:t.codecType)!==n.codec)null===(s=this.onVideoCodecChanged)||void 0===s||s.call(this,n.codec.toLocaleLowerCase());i.sendBytes=n.bytes,i.sendBitrate=t?8*Math.max(0,i.sendBytes-t.sendBytes):0,n.inputFrame?(i.captureFrameRate=n.inputFrame.frameRate,i.captureResolutionHeight=n.inputFrame.height,i.captureResolutionWidth=n.inputFrame.width):o&&(i.captureResolutionWidth=o.width,i.captureResolutionHeight=o.height),n.sentFrame?(i.sendFrameRate=n.sentFrame.frameRate,i.sendResolutionHeight=n.sentFrame.height,i.sendResolutionWidth=n.sentFrame.width):o&&(i.sendResolutionWidth=o.width,i.sendResolutionHeight=o.height),n.avgEncodeMs&&(i.encodeDelay=n.avgEncodeMs),a&&a.bitrateMax?i.targetSendBitrate=1e3*a.bitrateMax:n.targetBitrate&&(i.targetSendBitrate=n.targetBitrate),i.sendPackets=n.packets,i.sendPacketsLost=n.packetsLost,i.sendJitterMs=n.jitterMs,i.sendRttMs=n.rttMs,i.totalDuration=t?t.totalDuration+1:1,i.totalFreezeTime=t?t.totalFreezeTime:0,this.isLocalVideoFreeze(n)&&(i.totalFreezeTime+=1),n.scalabilityMode&&this.scalabilityMode!==n.scalabilityMode&&(B.debug("[".concat(this.store.clientId,"]: The scalabilityMode of the video sending stream is ").concat(n.scalabilityMode)),this.scalabilityMode=n.scalabilityMode)}this.trafficStats&&(i.currentPacketLossRate=(this.trafficStats.B_pvlr4||0)/100)}var a;if(this.localStats.set(n,i),(null==t?void 0:t.sendResolutionWidth)!==i.sendResolutionWidth||(null==t?void 0:t.sendResolutionHeight)!==i.sendResolutionHeight)null===(a=this.onStatsChanged)||void 0===a||a.call(this,"resolution",{width:i.sendResolutionWidth,height:i.sendResolutionHeight});i&&d&&this.exceptionMonitor.setLocalVideoStats(this.store.uid,d.track,i);break}case Tn.LocalAudioTrack:{const t=o,i=ki({},r),s=e.getStats(),a=e.getLocalMedia(n);if(s){const n=s.audioSend.find((e=>e.ssrc===(null==a?void 0:a.ssrcs[0].ssrcId)));if(n){if("opus"!==n.codec&&"aac"!==n.codec&&"PCMU"!==n.codec&&"PCMA"!==n.codec&&"G722"!==n.codec||(i.codecType=n.codec),n.inputLevel)i.sendVolumeLevel=Math.round(32767*n.inputLevel);else{const t=e.getLocalAudioVolume();t&&(i.sendVolumeLevel=Math.round(32767*t))}i.sendBytes=n.bytes,i.sendPackets=n.packets,i.sendPacketsLost=n.packetsLost,i.sendJitterMs=n.jitterMs,i.sendRttMs=n.rttMs,i.sendBitrate=t?8*Math.max(0,i.sendBytes-t.sendBytes):0}}this.trafficStats&&(i.currentPacketLossRate=(this.trafficStats.B_palr4||0)/100),this.localStats.set(Tn.LocalAudioTrack,i),i&&a&&this.exceptionMonitor.setLocalAudioStats(this.store.uid,a.track,i);break}}}))}updateRemoteStats(e){Array.from(this.remoteStats.entries()).forEach((t=>{var i,n;let o=Mi(t,2),s=o[0],a=o[1],r=a.videoStats;const c=a.audioStats,u=r,_=a.videoPcStats,p=ki({},d),E=ki({},l),m=ki({},h),S=e.getRemoteMedia(s),f=S.audioTrack,C=S.videoTrack,R=S.audioSSRC,T=S.videoSSRC;let g;g=this.store.useP2P?e.getStats(!0):e.getStats();const I=null===(i=g)||void 0===i?void 0:i.audioRecv.find((e=>e.ssrc===R)),v=null===(n=g)||void 0===n?void 0:n.videoRecv.find((e=>e.ssrc===T)),A=this.trafficStats&&this.trafficStats.peer_delay.find((e=>e.peer_uid===s));if(I&&("opus"!==I.codec&&"aac"!==I.codec&&"PCMU"!==I.codec&&"PCMA"!==I.codec&&"G722"!==I.codec||(p.codecType=I.codec),I.outputLevel?p.receiveLevel=Math.round(32767*I.outputLevel):f&&(p.receiveLevel=Math.round(32767*f.getVolumeLevel())),p.receiveBytes=I.bytes,p.receivePackets=I.packets,p.receivePacketsLost=I.packetsLost,p.receivePacketsDiscarded=I.packetsDiscarded,p.packetLossRate=p.receivePacketsLost/(p.receivePackets+p.receivePacketsLost),p.receiveBitrate=c?8*Math.max(0,p.receiveBytes-c.receiveBytes):0,p.totalDuration=c?c.totalDuration+1:1,p.totalFreezeTime=c?c.totalFreezeTime:0,p.freezeRate=p.totalFreezeTime/p.totalDuration,p.receiveDelay=I.jitterBufferMs,p.totalDuration>10&&qs.isRemoteAudioFreeze(f)&&(p.totalFreezeTime+=1)),v){"H264"!==v.codec&&"H265"!==v.codec&&"VP8"!==v.codec&&"VP9"!==v.codec&&"AV1X"!==v.codec&&"AV1"!==v.codec||(E.codecType=v.codec),E.receiveBytes=v.bytes,E.receiveBitrate=u?8*Math.max(0,E.receiveBytes-u.receiveBytes):0,E.decodeFrameRate=v.decodeFrameRate<0?0:v.decodeFrameRate,E.renderFrameRate=v.decodeFrameRate<0?0:v.decodeFrameRate,v.outputFrame&&(E.renderFrameRate=v.outputFrame.frameRate),v.receivedFrame?(E.receiveFrameRate=v.receivedFrame.frameRate,E.receiveResolutionHeight=v.receivedFrame.height,E.receiveResolutionWidth=v.receivedFrame.width):C&&(E.receiveResolutionHeight=C._videoHeight||0,E.receiveResolutionWidth=C._videoWidth||0),void 0!==v.framesRateFirefox&&(E.receiveFrameRate=Math.round(v.framesRateFirefox)),E.receivePackets=v.packets,E.receivePacketsLost=v.packetsLost,E.packetLossRate=E.receivePacketsLost/(E.receivePackets+E.receivePacketsLost),E.receiveDelay=v.jitterBufferMs||0;const t=!!T&&e.getRemoteVideoIsReady(T),i=u?u.totalFreezeTime:0,n=u?u.totalDuration:0;var y;if(E.totalDuration=u?u.totalDuration+1:1,1===ce("REMOTE_VIDEO_FREEZE_TIME_VERSION"))C&&t&&C._player&&(E.totalFreezeTime=C._player.totalFreezeTime/1e3);else E.totalFreezeTime=null!==(y=v.totalFreezesDuration)&&void 0!==y?y:i||0,void 0===v.totalFreezesDuration&&C&&t&&qs.isRemoteVideoFreeze(C,v,_)&&(E.totalFreezeTime+=1);E.freezeRate=Math.max(0,Math.min((E.totalFreezeTime-i)/(E.totalDuration-n),1))}A&&(p.end2EndDelay=A.B_ad,E.end2EndDelay=A.B_vd,p.transportDelay=A.B_ed,E.transportDelay=A.B_ed,p.currentPacketLossRate=A.B_ealr4/100,E.currentPacketLossRate=A.B_evlr4/100,m.uplinkNetworkQuality=A.B_punq?A.B_punq:0,m.downlinkNetworkQuality=A.B_pdnq?A.B_pdnq:0),this.remoteStats.set(s,{audioStats:p,videoStats:E,videoPcStats:v,networkStats:m}),f&&this.exceptionMonitor.setRemoteAudioStats(f,p),C&&this.exceptionMonitor.setRemoteVideoStats(C,E)}))}}class Js{constructor(){this.destChannelMediaInfos=new Map,this.srcChannelMediaInfo=void 0}setSrcChannelInfo(e){en(e),this.srcChannelMediaInfo=e}addDestChannelInfo(e){en(e),this.destChannelMediaInfos.set(e.channelName,e)}removeDestChannelInfo(e){Qi(e),this.destChannelMediaInfos.delete(e)}getSrcChannelMediaInfo(){return this.srcChannelMediaInfo}getDestChannelMediaInfo(){return this.destChannelMediaInfos}}function Xs(e){if(!(e instanceof Js)){return new j(W.INVALID_PARAMS,"Config should be instance of [ChannelMediaRelayConfiguration]").throw()}const t=e.getSrcChannelMediaInfo(),i=e.getDestChannelMediaInfo();if(!t){return new j(W.INVALID_PARAMS,"srcChannelMediaInfo should not be empty").throw()}if(0===i.size){return new j(W.INVALID_PARAMS,"destChannelMediaInfo should not be empty").throw()}}class Qs{get hasVideo(){return this._video_enabled_&&!this._video_muted_&&this._video_added_}get hasAudio(){return this._audio_enabled_&&!this._audio_muted_&&this._audio_added_}get audioTrack(){if(this.hasAudio||this._audio_pre_subscribed)return this._audioTrack}get videoTrack(){if(this.hasVideo||this._video_pre_subscribed)return this._videoTrack}get dataChannels(){return this._dataChannels}constructor(e,t){this.uid=void 0,this._uintid=void 0,this._trust_in_room_=!0,this._trust_audio_enabled_state_=!0,this._trust_video_enabled_state_=!0,this._trust_audio_mute_state_=!0,this._trust_video_mute_state_=!0,this._audio_muted_=!1,this._video_muted_=!1,this._audio_enabled_=!0,this._video_enabled_=!0,this._audio_added_=!1,this._video_added_=!1,this._is_pre_created=!1,this._video_pre_subscribed=!1,this._audio_pre_subscribed=!1,this._trust_video_stream_added_state_=!0,this._trust_audio_stream_added_state_=!0,this._audioTrack=void 0,this._videoTrack=void 0,this._dataChannels=[],this._audioSSRC=void 0,this._videoSSRC=void 0,this._audioOrtc=void 0,this._videoOrtc=void 0,this._cname=void 0,this._rtxSsrcId=void 0,this._videoMid=void 0,this._audioMid=void 0,this.uid=e,this._uintid=t}}const zs=e=>"v=0\no=- 0 0 IN IP4 127.0.0.1\ns=AgoraGateway\nt=0 0\na=group:BUNDLE 0 1 2\na=msid-semantic: WMS\na=ice-lite".concat(e?"\na=extmap-allow-mixed":"","\nm=video 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendonly\na=rtcp-mux\na=rtcp-rsize\na=mid:0\nm=audio 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendonly\na=rtcp-mux\na=rtcp-rsize\na=mid:1\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\nc=IN IP4 127.0.0.1\na=mid:2\n"),Zs="9",$s=2e4,ea=4e4;class ta{get localCapabilities(){return Oe(this._localCapabilities)}get rtpCapabilities(){return Oe(this._rtpCapabilities)}get candidates(){return Oe(this._candidates)}get iceParameters(){return Oe(this._iceParameters)}get dtlsParameters(){return Oe(this._dtlsParameters)}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];this.sessionDesc=void 0,this._localCapabilities=void 0,this._rtpCapabilities=void 0,this._candidates=void 0,this._originCandidates=void 0,this._iceParameters=void 0,this._isUseExtmapAllowMixed=void 0,this._isUseLocalCodecs=void 0,this._isUseDataChannel=void 0,this._dtlsParameters=void 0,this.setup=void 0,this.currentMidIndex=void 0,this.cname=void 0,this.useLocalCodecsMids=[],this.preloadSsrcs=[],this.firefoxSsrcMidMap=new Map,this._isUseExtmapAllowMixed=t,this._isUseLocalCodecs=i,this._isUseDataChannel=n;const o=e=Oe(e),s=o.iceParameters,a=o.dtlsParameters,r=o.candidates,c=o.rtpCapabilities,d=o.setup,l=o.localCapabilities,h=o.cname;this._rtpCapabilities=c,this._candidates=r,this._originCandidates=Oe(r),this._iceParameters=s,this._dtlsParameters=a,this._localCapabilities=l,this.setup=d,this.cname=h;var u=Mi(this.updateRemoteRTPCapabilities(c),1);this.sessionDesc=u[0],this.currentMidIndex=this.sessionDesc.mediaDescriptions.length-1}checkPreloadSsrcs(e){return e.length===this.preloadSsrcs.length&&e.every((e=>this.preloadSsrcs.includes(e)))}preloadRemoteMedia(e){let t=0;const i=[],n=[];for(;e>0;){const o=[ki({ssrcId:ea+t},ce("USE_SUB_RTX")?{rtx:ea+t+1}:{})],s="".concat(ea+t,"_").concat($s+t),a=To(o,this.cname,ce("SYNC_GROUP")?s:void 0),r=a.ssrcs,c=a.ssrcGroups,d=this.preCreateOrRecycleSendMedia("video",r,c,void 0),l=[{ssrcId:$s+t}],h="".concat(ea+t,"_").concat($s+t),u=To(l,this.cname,ce("SYNC_GROUP")?h:void 0),_=u.ssrcs,p=u.ssrcGroups,E=this.preCreateOrRecycleSendMedia("audio",_,p,void 0);e--,t+=2,i.push(d,E),n.push(r[0].ssrcId,_[0].ssrcId)}return this.useLocalCodecsMids.push(...i),this.preloadSsrcs=n,{mids:i,preSSRCs:n,isAvailable:!0}}preCreateOrRecycleSendMedia(e,t,i,n){const o=this.rtpCapabilities.send.videoCodecs,s=this._isUseLocalCodecs||0===o.length?this.localCapabilities.recv:this.rtpCapabilities.send;B.debug("create or recycle send media without remote rtp capabilities, ssrcs ",t[0].ssrcId);const a=e===Sn.VIDEO?s.videoCodecs:s.audioCodecs,r=e===Sn.VIDEO?s.videoExtensions:s.audioExtensions;this.currentMidIndex+=1;const c="".concat(this.currentMidIndex);let d={media:{mediaType:e,port:Zs,protos:["UDP","TLS","RTP","SAVPF"],fmts:a.map((e=>e.payloadType.toString(10)))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:r,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:i,rtcpFeedbackWildcards:[],payloads:a,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:"sendonly",rtcpMux:!0,rtcpRsize:!0,mid:"".concat(c)}};return d=this.mungSendMediaDesc(d,n),this.sessionDesc.mediaDescriptions.push(d),this.updateBundleMids(),c}toString(){return De(this.sessionDesc)}send(e,t,i,n){const o=To(t,this.cname,ce("SYNC_GROUP")?i:void 0),s=o.ssrcs,a=o.ssrcGroups,r=this.findPreloadMediaDesc(s);if(r){if(he()&&this.firefoxSsrcMidMap.set(s[0].ssrcId,r.attributes.mid),n&&(n.twcc||n.remb)){const e=this.sessionDesc.mediaDescriptions.indexOf(r);return this.sessionDesc.mediaDescriptions[e]=this.mungSendMediaDesc(r,n),{mid:r.attributes.mid,needExchangeSDP:!0}}return{mid:r.attributes.mid,needExchangeSDP:!1}}{const t=this.findAvailableMediaIndex(e,s);let i;return-1===t||1===t&&(qe()||Je()||Xe(143)||Qe(143)||ze()||ce("RESERVE_MID_1_MLINE")||ce("ENABLE_ENCODED_TRANSFORM")&&Ze())||0===t&&!$e(138)&&ce("USE_SUB_RTX")||et()?(i=this.createOrRecycleSendMedia(e,s,a,"sendonly",n),this.updateBundleMids()):(i=Oe(this.sessionDesc.mediaDescriptions[t]),i.attributes.direction="sendonly",i.attributes.ssrcs=s,i.attributes.ssrcGroups=a,this.sessionDesc.mediaDescriptions[t]=this.mungSendMediaDesc(i,n)),he()&&this.firefoxSsrcMidMap.set(s[0].ssrcId,i.attributes.mid),{mid:i.attributes.mid,needExchangeSDP:!0}}}sendDataChannel(){const e=this.createOrRecycleDataChannel(),t=e.mediaDesc,i=e.needExchangeSDP;return this.updateBundleMids(),{mid:t.attributes.mid,needExchangeSDP:i}}batchSend(e){const t=e.map((e=>{let t=e.kind,i=e.ssrcMsg,n=e.mslabel;return this.send(t,i,n)})),i=[];let n=!1;return t.forEach((e=>{let t=e.mid;e.needExchangeSDP&&(n=!0),i.push(t)})),{mids:i,needExchangeSDP:n}}stopSending(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>t.attributes.mid&&-1!==e.indexOf(t.attributes.mid)));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.stopSending.");t.forEach((e=>{"0"===e.attributes.mid||he()||et()?e.attributes.ssrcs=[]:(e.attributes.ssrcs=[],e.attributes.direction="inactive",e.media.port="0")})),this.updateBundleMids()}mute(e){const t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.mute."));t.attributes.direction="inactive"}unmute(e){const t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.unmute."));t.attributes.direction="sendonly"}muteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>e.includes(t.attributes.mid||"")));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");t.forEach((e=>{e.attributes.direction="inactive"}))}unmuteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>e.includes(t.attributes.mid||"")));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");t.forEach((e=>{e.attributes.direction="recvonly"}))}receive(e,t,i,n){e.forEach(((e,o)=>{this.createOrRecycleRecvMedia(e,[],"recvonly",t,i,n[o])})),this.updateBundleMids()}stopReceiving(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>-1!==e.indexOf(t.attributes.mid)));if(t.length!==e.length)throw new Error("MediaDescriptions' length doesn't match mids's length when calling RemoteSDP.receive.");t.forEach((e=>{e.media.port="0",e.attributes.direction="inactive"})),this.updateBundleMids()}updateRemoteRTPCapabilities(e){const t=this.sessionDesc||be((i=this._isUseExtmapAllowMixed,this._isUseDataChannel?zs(i):"v=0\no=- 0 0 IN IP4 127.0.0.1\ns=AgoraGateway\nt=0 0\na=group:BUNDLE 0 1\na=msid-semantic: WMS\na=ice-lite".concat(i?"\na=extmap-allow-mixed":"","\nm=video 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendonly\na=rtcp-mux\na=rtcp-rsize\na=mid:0\nm=audio 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendonly\na=rtcp-mux\na=rtcp-rsize\na=mid:1\n")));var i;this._rtpCapabilities=e;let n=!1;const o=this.rtpCapabilities.send,s=this.localCapabilities.send,a=this.localCapabilities.recv,r=a.videoCodecs,c=a.audioCodecs,d=a.videoExtensions,l=a.audioExtensions;for(const e of t.mediaDescriptions)if("sendonly"!==e.attributes.direction||"string"!=typeof e.attributes.mid||!this.useLocalCodecsMids.includes(e.attributes.mid)){if(n=!0,e.attributes.iceUfrag=this._iceParameters.iceUfrag,e.attributes.icePwd=this._iceParameters.icePwd,e.attributes.fingerprints=this._dtlsParameters.fingerprints,e.attributes.candidates=this._candidates,e.attributes.setup=this.setup,"application"===e.media.mediaType&&(e.attributes.sctpPort="5000"),"video"===e.media.mediaType)if(this._isUseLocalCodecs&&"sendonly"===e.attributes.direction){e.media.fmts=r.map((e=>e.payloadType.toString(10))),e.attributes.payloads=r,e.attributes.extmaps=d;const t=e.attributes.mid;"string"!=typeof t||this.useLocalCodecsMids.includes(t)||this.useLocalCodecsMids.push(t)}else if(0===o.videoCodecs.length){const t=s.videoCodecs.filter((e=>{var t;return null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase().includes("vp8")}));0===t.length&&t.push(s.videoCodecs[0]),e.media.fmts=t.map((e=>e.payloadType.toString(10))),e.attributes.payloads=t,e.attributes.extmaps=[]}else e.media.fmts=o.videoCodecs.map((e=>e.payloadType.toString(10))),e.attributes.payloads=o.videoCodecs,e.attributes.extmaps=o.videoExtensions;if("audio"===e.media.mediaType)if(this._isUseLocalCodecs&&"sendonly"===e.attributes.direction){e.media.fmts=c.map((e=>e.payloadType.toString(10))),e.attributes.payloads=c,e.attributes.extmaps=l;const t=e.attributes.mid;"string"!=typeof t||this.useLocalCodecsMids.includes(t)||this.useLocalCodecsMids.push(t)}else if(0===o.audioCodecs.length){const t=s.audioCodecs.filter((e=>{var t;return null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase().includes("opus")}))||[s.audioCodecs[0]];e.media.fmts=t.map((e=>e.payloadType.toString(10))),e.attributes.payloads=t,e.attributes.extmaps=[]}else e.media.fmts=o.audioCodecs.map((e=>e.payloadType.toString(10))),e.attributes.payloads=o.audioCodecs,e.attributes.extmaps=o.audioExtensions,bo(e)}return this.sessionDesc=t,this.currentMidIndex=t.mediaDescriptions.length-1,[this.sessionDesc,n]}updateCandidates(e){const t=this._originCandidates.filter((e=>"udp"===e.transport)),i=[];if(t.forEach((e=>{i.push(ki(ki({},e),{},{foundation:"tcpcandidate",priority:Number(e.priority)-1+"",transport:"tcp",port:Number(e.port)+90+""}))})),0!==t.length){switch(e){case fn.TCP_RELAY:this._candidates=i;break;case fn.UDP_TCP_RELAY:case fn.RELAY:this._candidates=[...t,...i];break;default:this._candidates=t}for(const e of this.sessionDesc.mediaDescriptions)e.attributes.candidates=this.candidates}}restartICE(e){let t=!1;return e=Oe(e),this._iceParameters=e,this.sessionDesc.mediaDescriptions.forEach((i=>{i.attributes.iceUfrag===e.iceUfrag&&i.attributes.icePwd===e.icePwd||(t=!0),i.attributes.iceUfrag=e.iceUfrag,i.attributes.icePwd=e.icePwd})),t}predictReceivingMids(e){const t=[];for(let i=0;i<e;i++)t.push((this.currentMidIndex+i+1).toString(10));return t}findAvailableMediaIndex(e,t){return this.sessionDesc.mediaDescriptions.findIndex((i=>{const n=i.media.mediaType===e&&"0"!==i.media.port&&("sendonly"===i.attributes.direction||"sendrecv"===i.attributes.direction)&&0===i.attributes.ssrcs.length;if(he()){if(n){const e=this.firefoxSsrcMidMap.get(t[0].ssrcId);return!(e||"0"!==i.attributes.mid&&"1"!==i.attributes.mid)||!(!e||e!==i.attributes.mid)}return!1}return n}))}createOrRecycleDataChannel(){for(const e of this.sessionDesc.mediaDescriptions)if("application"===e.media.mediaType)return{mediaDesc:e,needExchangeSDP:!1};this.currentMidIndex+=1;const e="".concat(this.currentMidIndex),t={media:{mediaType:"application",port:Zs,protos:["UDP","DTLS","SCTP"],fmts:["webrtc-datachannel"]},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:[],fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:[],ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:[],rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,mid:"".concat(e),sctpPort:"5000"}};return this.sessionDesc.mediaDescriptions.push(t),{mediaDesc:t,needExchangeSDP:!0}}createOrRecycleRecvMedia(e,t,i,n,o,s){const a=e._mediaStreamTrack.kind,r=this.rtpCapabilities.recv,c=Oo(a,r,this.localCapabilities.send,a===Sn.VIDEO?n:o),d=a===Sn.VIDEO?r.videoExtensions:r.audioExtensions;this.currentMidIndex+=1;const l="".concat(this.currentMidIndex);let h={media:{mediaType:a,port:Zs,protos:["UDP","TLS","RTP","SAVPF"],fmts:c.map((e=>e.payloadType.toString(10)))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:d,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:c,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:i,rtcpMux:!0,rtcpRsize:!0,mid:"".concat(l)}};h=this.mungRecvMediaDsec(h,e,s);const u=this.findFirstClosedMedia(a);if(u){const e=this.sessionDesc.mediaDescriptions.indexOf(u);this.sessionDesc.mediaDescriptions[e]=h}else this.sessionDesc.mediaDescriptions.push(h);return h}updateRemoteDtlsParameters(e){const t=new Set(this._dtlsParameters.fingerprints.map((e=>e.fingerprint))),i=new Set(e.map((e=>e.fingerprint)));let n=!1;t.size!==i.size&&(n=!0);for(const e of t)i.has(e)||(n=!0);return n}updateRemoteCodec(e,t,i){const n=[...new Set(this._rtpCapabilities.recv.videoCodecs.map((e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"")).filter((e=>Object.keys(tt).includes(e))))],o=new Set(t);if(n.every((e=>o.has(e))))return B.debug("codecs has not changed, no need to updateRemoteCodec, codecs: ".concat(t)),!1;const s=this._rtpCapabilities.recv.videoCodecs.filter((e=>t.some((t=>(e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").includes(t)))));if(0===s.length)return B.debug("updateRemoteCodec failed, because cannot find matched codec, remoteCapabilities codecs: ".concat(n," codecs: ").concat(t)),!1;const a=[...new Set(s.map((e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"")))];let r;if(B.debug("updateRemoteCodec, from ".concat(n," to ").concat(a)),0===e.length)r=this.sessionDesc.mediaDescriptions.filter((e=>"video"===e.media.mediaType&&"recvonly"===e.attributes.direction));else if(r=this.sessionDesc.mediaDescriptions.filter((t=>t.attributes.mid&&"video"===t.media.mediaType&&e.includes(t.attributes.mid)&&"recvonly"===t.attributes.direction)),r.length!==e.length)return B.debug("updateRemoteCodec failed, because cannot find mids, mids: ".concat(e,", codecs: ").concat(t)),!1;if(ce("USE_PUB_RTX")||ce("USE_SUB_RTX")){const e=Do(s,this.rtpCapabilities.recv.videoCodecs);s.push(...e)}this._rtpCapabilities.recv.videoCodecs=s;const c=this.localCapabilities.send,d=this.rtpCapabilities.recv,l=Oo(Sn.VIDEO,d,c,i);return r.forEach((e=>{const t=l.map((e=>e.payloadType.toString(10)));B.debug("updateRemoteCodec mid: ".concat(e.attributes.mid,", from"),e.attributes.payloads,"to",l),e.attributes.payloads=l,e.media.fmts=t})),B.debug("updateRemoteCodec success, mids: ".concat(e,", codecs: ").concat(t,", remote recv: ").concat(this._rtpCapabilities.recv.videoCodecs.length,", remote send: ").concat(this._rtpCapabilities.send.videoCodecs.length)),!0}createOrRecycleSendMedia(e,t,i,n,o){const s=this.rtpCapabilities.send.videoCodecs,a=this._isUseLocalCodecs||0===s.length?this.localCapabilities.recv:this.rtpCapabilities.send,r=e===Sn.VIDEO?a.videoCodecs:a.audioCodecs,c=e===Sn.VIDEO?a.videoExtensions:a.audioExtensions;this.currentMidIndex+=1;const d="".concat(this.currentMidIndex);let l={media:{mediaType:e,port:Zs,protos:["UDP","TLS","RTP","SAVPF"],fmts:r.map((e=>e.payloadType.toString(10)))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:c,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:i,rtcpFeedbackWildcards:[],payloads:r,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:n,rtcpMux:!0,rtcpRsize:!0,mid:"".concat(d)}};l=this.mungSendMediaDesc(l,o);const h=this.findFirstClosedMedia(e);if(h){const e=this.sessionDesc.mediaDescriptions.indexOf(h);this.sessionDesc.mediaDescriptions[e]=l}else this.sessionDesc.mediaDescriptions.push(l);return l}updateBundleMids(){this.sessionDesc.attributes.groups[0].identificationTag=this.sessionDesc.mediaDescriptions.filter((e=>"0"!==e.media.port)).map((e=>e.attributes.mid))}mungRecvMediaDsec(e,t,i){const a=Oe(e);return function(e){const t=e.attributes.unrecognized.findIndex((e=>"x-google-flag"===e.attField&&"conference"===e.attValue));-1!==t&&e.attributes.unrecognized.splice(t,1)}(a),go(a,t),function(e,t){if(e.attributes.payloads.forEach((e=>{var t;"h264"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())&&e.fmtp&&e.fmtp.parameters&&ce("ENABLE_UP_SPS_PPS")&&(e.fmtp.parameters["sps-pps-idr-in-keyframe"]="1")})),!(t instanceof n&&t._encoderConfig&&-1===t._hints.indexOf(s.SCREEN_TRACK)))return;const i=t._encoderConfig;o().supportMinBitrate&&i.bitrateMin&&e.attributes.payloads.forEach((e=>{var t;["h264","h265","vp8","vp9","av1"].includes((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())||"")&&(e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters["x-google-min-bitrate"]="".concat(i.bitrateMin))})),o().supportMinBitrate&&!t._hints.includes(s.LOW_STREAM)&&i.bitrateMax&&e.attributes.payloads.forEach((e=>{var t;["h264","h265","vp8","vp9","av1"].includes((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())||"")&&(e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters["x-google-start-bitrate"]="".concat(ce("X_GOOGLE_START_BITRATE")||Math.floor(i.bitrateMax)))}))}(a,t),function(e){if("video"!==e.media.mediaType)return;const t=Pe();if(t.name!==Le.SAFARI&&t.os!==ke.IOS)return;const i=e.attributes.extmaps.findIndex((e=>/video-orientation/g.test(e.extensionName)));-1!==i&&e.attributes.extmaps.splice(i,1)}(a),Io(a,i,this.localCapabilities.send),a}mungSendMediaDesc(e,t){const i=Oe(e);return i.attributes&&i.attributes.payloads&&Array.isArray(i.attributes.payloads)&&i.attributes.payloads.length>0&&i.attributes.payloads.forEach((e=>{e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase()&&ce("ENABLE_DOWN_SPS_PPS")&&(e.fmtp&&e.fmtp.parameters||(e.fmtp={parameters:{}}),e.fmtp.parameters["sps-pps-idr-in-keyframe"]="1")})),Io(i,t,this.localCapabilities.recv),bo(i),i}updateRecvMedia(e,t){const i=this.sessionDesc.mediaDescriptions.findIndex((t=>t.attributes.mid===e));if(-1!==i){const e=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[i],t);this.sessionDesc.mediaDescriptions[i]=e}}bumpMid(e){this.currentMidIndex+=e}findFirstClosedMedia(e){return this.sessionDesc.mediaDescriptions.find((t=>he()?"0"===t.media.port&&t.media.mediaType===e:"0"===t.media.port))}findPreloadMediaDesc(e){return this.sessionDesc.mediaDescriptions.find((t=>{var i;return(null===(i=t.attributes)||void 0===i||null===(i=i.ssrcs[0])||void 0===i?void 0:i.ssrcId)===e[0].ssrcId}))}getSSRC(e){var t;return null===(t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e)))||void 0===t?void 0:t.attributes.ssrcs}}function ia(e){return!!e&&Boolean("number"==typeof e.minDownscaleWidth&&e.minDownscaleWidth>=1||"number"==typeof e.minDownscaleHeight&&e.minDownscaleHeight>=1)}function na(e){return"vp8"===e||"vp9"===e}function oa(e,t,i,n){if("number"!=typeof n)return Array.from({length:i+1},((i,n)=>e/Math.pow(t,n)));const o=Math.max(e,n),s=o/e;if(s<=1)return Array.from({length:i+1},(()=>e));const a=1/t,r=Math.min(i,Math.max(1,Math.ceil(Math.log(s)/Math.log(a)))),c=Math.pow(s,1/r);return Array.from({length:i+1},((t,i)=>{if(0===i)return e;const n=Math.min(i,r);return Math.min(e*Math.pow(c,n),o)}))}function sa(e,t,i,n){if("number"!=typeof n)return i;const o=Math.max(e,n)/e;if(o<=1)return 0;const s=1/t;return Math.min(i,Math.max(1,Math.ceil(Math.log(o)/Math.log(s))))}var aa=function(e){return e[e.DOWN=0]="DOWN",e[e.UP=1]="UP",e}(aa||{});const ra=new Map;function ca(e,t,i,n){let o=e.scale;if(0===o&&n===aa.UP||o>=t.length-1&&n===aa.DOWN)return e;let s=ki(ki({},e),{},{scale:n===aa.DOWN?++o:--o});switch(i){case"maintain-framerate":s=ki(ki({},s),t[o].motion);break;case"maintain-resolution":s=ki(ki({},s),t[o].detail);break;case"balanced":s=ki(ki({},s),t[o].balanced)}return s}function da(e,t,i){if(t){const n={overUse:0,underUse:0,adaptationList:la(t,i)};ra.set(e,n)}else ra.delete(e)}function la(e,t){const i=ki({},e),n=i.bitrateMax,o=i.frameRate,s=i.scaleResolutionDownBy,a=i.bitrateMin,r=function(e){const t=[];if("number"==typeof e.minDownscaleHeight&&e.minDownscaleHeight>=1&&e.height>0&&t.push(e.height/e.minDownscaleHeight),"number"==typeof e.minDownscaleWidth&&e.minDownscaleWidth>=1&&e.width>0&&t.push(e.width/e.minDownscaleWidth),t.length)return Math.max(e.scaleResolutionDownBy,Math.min(...t))}(i),c=it.MIN_FRAME_RATE,d=it.MAX_THRESHOLD_FRAMERATE,l=it.MAX_SCALE,h=it.BITRATE_MIN_THRESHOLD,u=it.BITRATE_MAX_THRESHOLD,_=it.BWE_SCALE_UP_THRESHOLD,p=it.BWE_SCALE_DOWN_THRESHOLD,E=it.PERF_SCALE_DOWN_THRESHOLD,m=it.PERF_SCALE_UP_THRESHOLD,S=it.BALANCE_BITRATE_FACTOR,f=it.BALANCE_FRAMERATE_FACTOR,C=it.BALANCE_RESOLUTION_FACTOR,R=it.MOTION_RESOLUTION_FACTOR,T=it.MOTION_BITRATE_FACTOR,g=it.DETAIL_FRAMERATE_FACTOR,I=it.DETAIL_BITRATE_FACTOR,v=Math.min(i.frameRate,d);let A=l;"maintain-framerate"===t?A=sa(s,R,l,r):"balanced"===t&&(A=sa(s,C,l,r));const y=oa(s,C,A,r),N=oa(s,R,A,r),w=[{scale:0,threshold:{bwe_down:Math.round(Math.pow(p,1)*n),bwe_up:n,fps_down:Math.round(Math.pow(E,1)*v),fps_up:o},balanced:{scaleResolutionDownBy:1,frameRate:o,bitrateMax:n,bitrateMin:a},motion:{scaleResolutionDownBy:1,frameRate:o,bitrateMax:n,bitrateMin:a},detail:{scaleResolutionDownBy:1,frameRate:o,bitrateMax:n,bitrateMin:a}}];for(let e=1;e<=A;e++){const t={bwe_up:Math.round(Math.pow(_,e)*n),bwe_down:Math.round(Math.pow(p,e+1)*n),fps_up:Math.round(Math.pow(m,e)*v),fps_down:Math.round(Math.pow(E,e+1)*v)},i={scaleResolutionDownBy:y[e],frameRate:Math.max(Math.round(Math.pow(f,e)*o),c),bitrateMax:Math.max(Math.round(Math.pow(S,e)*n),u),bitrateMin:Math.max(Math.round(Math.pow(S,e)*a),h)},s={scaleResolutionDownBy:N[e],frameRate:o,bitrateMax:Math.max(Math.round(Math.pow(T,e)*n),u),bitrateMin:Math.max(Math.round(Math.pow(T,e)*a),h)},r={scaleResolutionDownBy:1,frameRate:Math.max(Math.round(Math.pow(g,e)*o),c),bitrateMax:Math.max(Math.round(Math.pow(I,e)*n),u),bitrateMin:Math.max(Math.round(Math.pow(I,e)*a),h)};w.push({scale:e,threshold:t,balanced:i,motion:s,detail:r})}return w}function ha(e,t,i,n,o,s){const a=ra.get(e)||{overUse:0,underUse:0,adaptationList:la(o,s)},r=a.adaptationList;ra.set(e,a);const c=it.OVERUSE_TIMES_THRESHOLD,d=it.UNDERUSE_TIMES_THRESHOLD,l=n.scale;let h,u;return"number"==typeof t&&t>0&&function(e,t,i,n){if(t>=i.length)return!1;let o=i[t].threshold.fps_down;return ce("FORCE_AG_HIGH_FRAMERATE")&&"maintain-framerate"===n&&(o=i[0].threshold.fps_down),e<o}(t,l,r,s)&&(a.overUse++,u=nt.CPU,a.overUse>c)||"number"==typeof i&&i>0&&function(e,t,i){return!(t>=i.length)&&e<i[t].threshold.bwe_down}(i,l,r)&&(a.overUse++,u=nt.BANDWIDTH,a.overUse>c)?(a.overUse=0,a.underUse=0,h=ca(n,r,s,aa.DOWN),[h,u]):("number"==typeof t&&t>0&&"number"==typeof i&&i>0&&function(e,t,i,n){if(0===t)return;let o=i[t].threshold.fps_up;return ce("FORCE_AG_HIGH_FRAMERATE")&&"maintain-framerate"===n&&(o=i[1].threshold.fps_up),e>o}(t,l,r,s)&&function(e,t,i){if(0===t)return;return e>i[t].threshold.bwe_up}(i,l,r)&&(a.underUse++,a.underUse>d&&(a.overUse=0,a.underUse=0,h=ca(n,r,s,aa.UP),0===h.scale&&(u=nt.NONE))),[h,u])}function ua(e,t){return!!ce("ENABLE_AG_ADAPTATION")&&(!!ia(t)||!!(e instanceof u||e._hints.includes(s.CUSTOM_TRACK))&&(!!ce("FORCE_SUPPORT_AG_ADAPTATION")||!!(ot(14,0,!1)&&st(17,4,!0)||at(14)&&rt(17,4,!0))))}const _a=new Map;function pa(e,t,i,n,o,s){if(Ea(e,i),o(t),"balanced"!==n&&"maintain-framerate"!==n&&"maintain-resolution"!==n)return;let a=-1;da(e,t,n);const r=window.setInterval((()=>{const r=_a.get(e);if(!ce("ENABLE_AG_ADAPTATION")||!r)return Ea(e,i),void o(t);const c=s();if(c.sendPackets>0&&c.OutgoingAvailableBandwidth>0){if(-1===a)return void(a=Date.now());if(Date.now()-a<1e3)return;const s=c.sendFrameRate,d=c.OutgoingAvailableBandwidth,l=Mi(ha(e,s,d,r.adaptationConfig,t,n),2),h=l[0],u=l[1];u&&(i.qualityLimitationReason=u),h&&r.adaptationConfig.scale!==h.scale&&(B.debug("[".concat(e,"] applyAdaptation: ").concat(i.qualityLimitationReason,"\n sendFps ").concat(s,", bwe ").concat(d,", switch from ").concat(r.adaptationConfig.scale," to ").concat(h.scale," ")),r.adaptationConfig=ki(ki({},r.adaptationConfig),h),o(h))}}),ce("CHECK_LOCAL_STATS_INTERVAL")),c=ki({},t);_a.set(e,{timer:r,adaptationConfig:c,originConfig:t,adaptationFunc:o}),B.debug("[".concat(e,"] start adaptation, originConfig: ").concat(JSON.stringify(t),", degradationPreference: ").concat(n))}function Ea(e,t){const i=_a.get(e);if(i){const t=i.timer;window.clearTimeout(t),_a.delete(e)}t.qualityLimitationReason=nt.NONE,da(e)}const ma=["balanced","maintain-framerate","maintain-resolution"];function Sa(e){switch(e){case"motion":return"maintain-framerate";case"detail":return"maintain-resolution";case"balanced":return"balanced";default:return}}function fa(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const i=Sa(e._optimizationMode);if(i)return i;const n=ce("CUSTOM_ADAPTATION_DEFAULT_MODE");return e._hints.includes(s.CUSTOM_TRACK)?function(e){return"string"==typeof e&&ma.includes(e)}(n)?n:t?"maintain-framerate":"":"maintain-framerate"}function Ca(e,t){if(t)return"maintain-resolution";const i=Sa(e._optimizationMode);return i||void 0}function Ra(e,t,i){var n;const o=e.getParameters(),s=null===(n=o.encodings)||void 0===n?void 0:n[0];return s&&Object.assign(s,i),Object.assign(o,t),o}async function Ta(e,t,i){try{return await e.setParameters(Ra(e,t,i)),{classification:"transient"}}catch(n){const o=ki({},i);delete o.scaleResolutionDownBy;try{return await e.setParameters(Ra(e,t,o)),{classification:"unsupported",retryWithScaleError:n}}catch(e){return{classification:"unknown",retryWithScaleError:n,retryWithoutScaleError:e}}}}function ga(e){const t=o();if(e.some((e=>e._bypassWebAudio)))throw new me(ne.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio");if(!t.webAudioMediaStreamDest)throw new me(ne.NOT_SUPPORTED,"cannot publish multiple tracks because your browser does not support audio mixing")}function Ia(e,t){ga(e);const i=t||new a;return e.forEach((e=>i.addAudioTrack(e))),i}const va=!o().supportUnifiedPlan||ce("CHROME_FORCE_PLAN_B")&&ct();function Aa(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(e.useDcSignal)return i={spec:t,store:e},Bo("DataChannelConnection").create(i);var i;const n=va?function(e){return Bo("PlanBConnection").create(e)}({spec:t,store:e}):new ba(t,e);return n}function ya(e){return e&&("disconnected"===e.iceConnectionState||"checking"===e.iceConnectionState||"failed"===e.iceConnectionState)}function Na(e){try{if(e.iceServers)return!1;if(e.turnServer&&"off"!==e.turnServer.mode){if(dt(e.turnServer.servers))return!1;if(ce("FORCE_TURN_TCP")||e.turnServer.servers.concat(e.turnServer.serversFromGateway||[]).some((e=>e.forceturn)))return!0}return!1}catch(e){return!1}}var wa;let ba=(wa=class e extends mn{get currentLocalDescription(){return this.peerConnection.currentLocalDescription}get currentRemoteDescription(){return this.peerConnection.currentRemoteDescription}get peerConnectionState(){return this.peerConnection.connectionState}get iceConnectionState(){return this.peerConnection.iceConnectionState}get dtlsTransportState(){var e,t;return null!==(e=null===(t=this.peerConnection.getReceivers()[0])||void 0===t||null===(t=t.transport)||void 0===t?void 0:t.state)&&void 0!==e?e:null}get localCodecs(){return[...new Set(this.localCapabilities&&this.localCapabilities.send.videoCodecs.map((e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"")).filter((e=>Object.keys(tt).includes(e))))]}constructor(t,i){super(t,i),this.id=ve(5,"connection-"),this.store=void 0,this.peerConnection=void 0,this.forceTurn=!1,this.remoteSDP=void 0,this.initialOffer=void 0,this.transportEventReceiver=void 0,this.statsFilter=void 0,this.extension={useXR:ce("USE_XR")},this.localCapabilities=void 0,this.remoteCodecs=void 0,this.localCandidateCount=0,this.allCandidatesReceived=!1,this.isPreallocation=!1,this.isPreRender=!1,this.preMediaMap=new Map,this.dataStreamChannelMap=new Map,this.establishPromise=void 0,this.recoveredDataChannelIds=[],this.currentDataChannelId=1,this.supportAV1RtpSpec=!1,this.mutex=void 0,this.qualityLimitationReason=nt.NONE,this.unsupportedResolutionFloorTrackIds=new Set,this.isFirstConnected=!1,this.store=i,this.forceTurn=Na(t),this.mutex=new ue("P2PConnection-mutex",i.clientId),this.peerConnection=new RTCPeerConnection(e.resolvePCConfiguration(t),{optional:[{googDscp:!0}]}),this.isFirstConnected=!1,this.statsFilter=lt(this.peerConnection,ce("STATS_UPDATE_INTERVAL"),void 0,he()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1,t.isPreallocation&&(this.isPreallocation=!0),this.establishPromise=this.establish()}getPreMedia(e){return this.preMediaMap.get(e)}isPreSub(){return this.preMediaMap.size>0}async updateRemoteRTPCapabilities(e,t){if(this.remoteCodecs=t,!this.remoteSDP)return void B.debug("[P2PConnection] cannot updateRemoteRTPCapabilities before remote SDP created, local codecs: ".concat(this.localCodecs,", codecs: ").concat(t));if(this.remoteSDP.updateRemoteCodec(e,t,this.store.codec)){const e=await this.peerConnection.createOffer(),t=this.logSDPExchange(e.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(e);const i=this.remoteSDP.toString();null==t||t(i),await this.peerConnection.setRemoteDescription({type:"answer",sdp:i})}else B.debug("[P2PConnection] updateRemoteRTPCapabilities no need to exchange SDP.")}async establish(){try{this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.peerConnection.addTransceiver("audio",{direction:"recvonly"});const t=await this.peerConnection.createOffer();if(!t.sdp)throw new Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");const i=mo(t.sdp),n=await yo({filterRTX:!ce("USE_PUB_RTX")&&!ce("USE_SUB_RTX"),filterVideoFec:ce("FILTER_VIDEO_FEC"),filterAudioFec:ce("FILTER_AUDIO_FEC"),filterVideoCodec:ce("FILTER_VIDEO_CODEC"),unsupportedVideoUplinkCodec:ce("UNSUPPORTED_VIDEO_UPLINK_CODEC"),unsupportedVideoDownlinkCodec:ce("UNSUPPORTED_VIDEO_DOWNLINK_CODEC")},this.extension);if(this.localCapabilities=wo(n),this.initialOffer=t,ce("ENABLE_SVC")&&"av1"==this.store.codec){const t=await Ao();var e;if(t)this.supportAV1RtpSpec=!0,null===(e=n.send)||void 0===e||e.videoExtensions.push(t)}let o;return t.sdp&&Uo(t.sdp)&&(o=Oe(n),co(o)),ki(ki({},i),{},{rtpCapabilities:o||n,offerSDP:t.sdp})}catch(e){throw new me(ne.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString())}}async connect(e){try{if(!this.initialOffer)throw new Error("Cannot establish P2PConnection without initial offer.");if(this.initialOffer.sdp&&Uo(this.initialOffer.sdp)&&lo(e.rtpCapabilities,this.localCapabilities),this.remoteSDP=new ta(ki(ki({},e),{},{localCapabilities:this.localCapabilities}),this.supportAV1RtpSpec,!(!ce("ENABLE_PRE_SUB_WITH_PRE_PC")||!ce("PRE_USE_LOCAL_CODECS"))&&_(this.store)),e.preallocation&&(this.isPreallocation=!0),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0&&this.remoteSDP.updateRemoteCodec([],this.remoteCodecs,this.store.codec),p()&&_(this.store)){var t;const e=(null===(t=this.store.preSubOptions)||void 0===t?void 0:t.length)||0,i=ce("PRE_SUB_NUM")||1,n=e>i?e:i,o=this.remoteSDP.preloadRemoteMedia(n),s=o.mids,a=o.preSSRCs,r=Lo(this.initialOffer.sdp,this.extension),c=this.logSDPExchange(r||"","offer","local","connect");this.store.descriptionStart(),await this.peerConnection.setLocalDescription({type:"offer",sdp:r}),null==c||c(r),new Array(n).fill(0).forEach((()=>{this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.peerConnection.addTransceiver("audio",{direction:"recvonly"})}));const d=await this.peerConnection.createOffer(),l=this.logSDPExchange(d.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(d);const h=this.remoteSDP.toString();null==l||l(h),await this.peerConnection.setRemoteDescription({type:"answer",sdp:h}),B.debug("[".concat(this.store.clientId,"] [P2PConnection] preload media with icc/dtls, add preload ssrcs ").concat(a)),this.presetMedia(s,a);const u=this.peerConnection.getTransceivers()[0];null!=u&&u.receiver&&this.tryBindTransportEvents(u.receiver)}else{const t=this.remoteSDP.toString(),n=Lo(this.initialOffer.sdp,this.extension),o=this.logSDPExchange(n||"","offer","local","connect");this.store.descriptionStart(),await this.peerConnection.setLocalDescription({type:"offer",sdp:n}),null==o||o(t),await this.peerConnection.setRemoteDescription({type:"answer",sdp:t});const s=this.peerConnection.getTransceivers()[0];if(null!=s&&s.receiver&&this.tryBindTransportEvents(s.receiver),_(this.store))if(e.preallocation&&ce("ENABLE_PRE_SUB_WITH_PRE_PC")){var i;const e=(null===(i=this.store.preSubOptions)||void 0===i?void 0:i.length)||0,t=ce("PRE_SUB_NUM")||1,n=e>t?e:t,o=this.remoteSDP.preloadRemoteMedia(n),s=o.mids,a=o.preSSRCs;await Po(this.peerConnection,this.remoteSDP,this.extension),B.debug("[".concat(this.store.clientId,"] [P2PConnection] preload media, in pre pc,add preload ssrcs ").concat(a)),this.presetMedia(s,a)}else{const t=e.preSSRCs,i=void 0===t?[]:t,n=i.map((e=>e.ssrcMsg[0].ssrcId));if(0===i.length)return;const o=this.remoteSDP.batchSend(i.map((e=>Object.assign({},e)))).mids;await Po(this.peerConnection,this.remoteSDP,this.extension),B.debug("[P2PConnection.connect] preload media, after join, add preload ssrcs ".concat(n)),this.presetMedia(o,n)}}}catch(e){throw new me(ne.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(e.toString()))}}presetMedia(e,t){e.forEach(((e,i)=>{this.peerConnection.getTransceivers().forEach((n=>{if(null!=n.mid&&e===n.mid&&n.receiver.track){const a=n.receiver.track;if(ce("PRE_PLAYOUT_DELAY_HINT")){const e=n.receiver;"playoutDelayHint"in e&&(e.playoutDelayHint=ce("PRE_PLAYOUT_DELAY_HINT"),B.debug("[".concat(this.store.clientId,"] [P2PConnection] presetMedia set playoutDelayHint to ").concat(ce("PRE_PLAYOUT_DELAY_HINT"))))}let r,c;if("video"===a.kind&&ce("ENABLE_PRE_RENDER")){var o,s;let e=null===(o=this.store.preSubOptions)||void 0===o||null===(o=o[i])||void 0===o?void 0:o.element;const n=(null===(s=this.store.preSubOptions)||void 0===s||null===(s=s[i])||void 0===s?void 0:s.config)||{};B.debug("try to play pre sub video","string"==typeof e?e:"element","config: ".concat(JSON.stringify(n))),"string"==typeof e&&(e=document.getElementById(e)||void 0),r=e instanceof HTMLVideoElement?new E(ki({trackId:"track-".concat(a.kind,"-unknown-").concat(this.store.clientId,"_").concat(ve(5,"")),element:e},n)):new m(ki({trackId:"track-".concat(a.kind,"-unknown-").concat(this.store.clientId,"_").concat(ve(5,"")),element:e},n),!e),r.updateVideoTrack(a),r.onFirstVideoFrameRender=()=>{var e;r&&(r.onFirstVideoFrameRender=void 0);const n=this.preMediaMap.get(t[i]);n&&(n.firstVideoRender=Date.now()),null===(e=this.onFirstVideoRender)||void 0===e||e.call(this,t[i])},r.onVideoBufferReady=()=>{var e;null===(e=this.onFirstVideoBufferReady)||void 0===e||e.call(this,t[i])},r.play(this.store.sessionId||void 0),this.isPreRender=!0}if("audio"===a.kind&&this.store.autoReceiveAndPlayAudio){c="track-".concat(a.kind,"-unknown-").concat(this.store.clientId,"_").concat(ve(5,""));const e=100;S.play(a,c,e,this.store.sessionId||void 0),B.debug("[".concat(this.store.clientId,"] [P2PConnection] presetMedia start audio playback, trackId: ").concat(c))}this.preMediaMap.set(t[i],{mid:e,track:a,player:r,transceiver:n,audioTrackId:c})}})),this.store.peerReceiver()}))}checkDtlsParameters(e){return!!this.remoteSDP&&(e.length>0&&this.remoteSDP.updateRemoteDtlsParameters(e))}checkIceParameters(e){if(!this.remoteSDP)return!1;return this.remoteSDP.restartICE(e)}async updateRemoteConnect(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.updateRemoteConnect before remote SDP created");let t=!1;const i=e.rtpCapabilities;if(t=Mi(this.remoteSDP.updateRemoteRTPCapabilities(i),2)[1],Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0){const e=this.remoteSDP.updateRemoteCodec([],this.remoteCodecs,this.store.codec);t=t||e}const n=e.preSSRCs,o=void 0===n?[]:n,s=o.map((e=>e.ssrcMsg[0].ssrcId));if(!this.remoteSDP.checkPreloadSsrcs(s)){const e=[],t=[];if(Array.from(this.preMediaMap.entries()).every((i=>{let n=Mi(i,2),o=n[0],s=n[1],a=s.mid,r=s.player,c=(s.track,s.audioTrackId);return e.push(a),t.push(o),this.preMediaMap.delete(o),r&&r.destroy(),c&&S.stop(c),!0})),e.length>0&&(this.remoteSDP.stopSending(e),await Po(this.peerConnection,this.remoteSDP,this.extension),B.warn("[P2PConnection.updateRemoteConnect] preload media, failed, del preload ssrcs ".concat(t)),G.reportApiInvoke(this.store.sessionId,{name:Be.PRELOAD_MEDIA_FAILED,options:[o,t],tag:je.TRACER}).onSuccess()),o.length>0){const e=this.remoteSDP.batchSend(o.map((e=>Object.assign({},e)))).mids;await Po(this.peerConnection,this.remoteSDP,this.extension),B.debug("[P2PConnection.updateRemoteConnect] preload media, after join, add preload ssrcs ".concat(s)),this.presetMedia(e,s)}}t?(await Po(this.peerConnection,this.remoteSDP,this.extension),B.debug("[P2PConnection] updateRemoteConnect by exchanging SDP.")):B.debug("[P2PConnection] updateRemoteConnect no need to exchange SDP, because no need to update remote codecs (use local codecs)")}catch(e){throw new me(ne.EXCHANGE_SDP_FAILED,"P2PConnection.updateRemoteConnect failed; ".concat(e.toString()))}}send(e,t,i){var n=this;return Ui((function*(){const o=yield Di(n.mutex.lock("From P2PConnection.send"));try{if(!n.remoteSDP)throw new Error("Cannot call P2PConnection.send before remote SDP created");const s=[],a=ao();e.forEach((e=>{const t=n.peerConnection.addTransceiver(e._mediaStreamTrack,ki({direction:"sendonly"},"video"===e.trackMediaType&&n.supportAV1RtpSpec&&a?{sendEncodings:[{scalabilityMode:a}]}:{}));s.push(t),e._updateRtpTransceiver(t)})),he()&&!0===ce("SIMULCAST")&&(yield Di(n.applySimulcastForFirefox(s,e)));const r=yield Di(n.peerConnection.createOffer()),c=n.remoteSDP.predictReceivingMids(e.length),d=n.mungSendOfferSDP(r.sdp,e,c),l=be(d),h=c.map((e=>{const t=l.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error("Cannot extract ssrc from mediaDescription.");return So(t,ce("USE_PUB_RTX"))}));let u;try{u=yield h}catch(o){u=[],n.remoteSDP.receive(e,t,i,u);const s=n.remoteSDP.toString();throw yield Di(n.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield Di(n.peerConnection.setRemoteDescription({type:"answer",sdp:s})),yield Di(n.stopSending(c,!0)),o}n.remoteSDP.receive(e,t,i,u);const _=n.remoteSDP.toString(),p=n.logSDPExchange(d,"offer","local","send");return yield Di(n.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield Di(n.applySimulcastEncodings(s,e)),yield Di(n.applySendEncodings(s,e)),null==p||p(_),yield Di(n.peerConnection.setRemoteDescription({type:"answer",sdp:_})),s.map(((e,t)=>{const i=c[t];return{localSSRC:h[t],id:i,transceiver:e}}))}catch(e){throw e instanceof me?e:new me(ne.EXCHANGE_SDP_FAILED,"P2PConnection.send failed; ".concat(e.toString()))}finally{o()}}))()}async createDataChannels(e,t){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.createDataChannels before remote SDP created");let i=this.dataStreamChannelMap.get(e);if(i&&"open"===i.readyState)B.debug("[P2PConnection] Channels are already available and can be reused directly.");else{const t=this.currentDataChannelId<1023?this.currentDataChannelId++:this.recoveredDataChannelIds.shift();if("number"!=typeof t)throw new Error("create DataChannel error, because cannot get dc id");i=this.peerConnection.createDataChannel("datastream-channel",{id:t,negotiated:!0,ordered:!1,maxRetransmits:ce("DATASTREAM_MAX_RETRANSMITS")}),i.binaryType="arraybuffer",this.dataStreamChannelMap.set(e,i)}t.forEach((e=>{e._updateOriginDataChannel(i)}));const n=this.remoteSDP.sendDataChannel();if(n.needExchangeSDP){const e=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:e});const t=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(t),B.debug("[P2PConnection] createDataChannels by exchanging SDP.")}else B.debug("[P2PConnection] createDataChannels no need to exchange SDP.");return}catch(e){throw e instanceof me?e:new me(ne.EXCHANGE_SDP_FAILED,"P2PConnection.createDataChannels failed; ".concat(e.toString()))}}async stopDataChannels(e){try{const t=this.dataStreamChannelMap.get(e);return t&&(t.id&&this.recoveredDataChannelIds.push(t.id),t.close()),void this.dataStreamChannelMap.delete(e)}catch(e){throw e instanceof me?e:new me(ne.DATACHANNEL_FAILED,"P2PConnection.stopDataChannels failed; ".concat(e.toString()))}}async stopSending(e,t){const i=t?void 0:await this.mutex.lock("From P2PConnection.stopSending");try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopSending before remote SDP created");const t=this.peerConnection.getTransceivers().filter((t=>-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length when trying to call P2PConnection.stopSending.");t.map((e=>{var t;Ea(this.id+e.mid,this),e.direction="inactive",null===(t=e.stop)||void 0===t||t.call(e)}));const n=await this.peerConnection.createOffer(),o=this.logSDPExchange(n.sdp||"","offer","local","stopSending");await this.peerConnection.setLocalDescription(n),this.remoteSDP.stopReceiving(e);const s=this.remoteSDP.toString();null==o||o(s),await this.peerConnection.setRemoteDescription({type:"answer",sdp:s})}catch(e){throw new me(ne.EXCHANGE_SDP_FAILED,"P2PConnection.stopSending failed; ".concat(e.toString()))}finally{i&&i()}}async receive(e,t,i,n){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.receive ".concat(e," before remoteSDP created."));const o=this.remoteSDP.send(e,t,i,n),s=o.mid;o.needExchangeSDP&&(await Po(this.peerConnection,this.remoteSDP,this.extension),B.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," by exchanging SDP.")));const a=this.peerConnection.getTransceivers().find((e=>e.mid===s));if(!a)throw new Error("Cannot get transceiver after setLocalDescription.");if(ce("PRE_PLAYOUT_DELAY_HINT")){const t=a.receiver;"playoutDelayHint"in t&&(t.playoutDelayHint=ce("PRE_PLAYOUT_DELAY_HINT"),B.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," set playoutDelayHint to ").concat(ce("PRE_PLAYOUT_DELAY_HINT"))))}return{track:a.receiver.track,id:s,transceiver:a}}catch(e){throw new me(ne.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()))}}async batchReceive(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.batchReceive before remoteSDP created.");const t=this.remoteSDP.batchSend(e),i=t.mids;return t.needExchangeSDP&&(await Po(this.peerConnection,this.remoteSDP,this.extension),B.debug("[".concat(this.store.clientId,"] [P2PConnection] batchReceive by exchanging SDP."))),i.map((e=>{const t=this.peerConnection.getTransceivers().find((t=>t.mid===e));if(!t)throw new Error("Cannot get transceiver after setLocalDescription.");if(ce("PRE_PLAYOUT_DELAY_HINT")){const e=t.receiver;"playoutDelayHint"in e&&(e.playoutDelayHint=ce("PRE_PLAYOUT_DELAY_HINT"),B.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e.track.kind," set playoutDelayHint to ").concat(ce("PRE_PLAYOUT_DELAY_HINT"))))}return{track:t.receiver.track,id:e,transceiver:t}}))}catch(e){throw new me(ne.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()))}}async stopReceiving(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopReceiving before remote SDP created.");e.forEach((e=>{Array.from(this.preMediaMap.entries()).some((t=>{let i=Mi(t,2),n=i[0],o=i[1],s=o.mid,a=o.player,r=o.audioTrackId;if(s===e)return this.preMediaMap.delete(n),a&&a.destroy(),r&&S.stop(r),!0}))})),this.remoteSDP.stopSending(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","stopReceiving");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||""),await this.peerConnection.setLocalDescription(n)}catch(e){throw new me(ne.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(e.toString()))}}async muteRemote(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.muteRemote mid=".concat(e," before remote SDP created."));this.remoteSDP.mute(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","muteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||""),await this.peerConnection.setLocalDescription(n)}catch(e){throw new me(ne.EXCHANGE_SDP_FAILED,"P2PConnection.muteRemote failed; ".concat(e.toString()))}}async unmuteRemote(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.unmuteRemote mid=".concat(e," before remote SDP created."));this.remoteSDP.unmute(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","unmuteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||""),await this.peerConnection.setLocalDescription(n)}catch(e){throw new me(ne.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteRemote failed; ".concat(e.toString()))}}async muteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.muteLocal before remote SDP created.");const t=this.peerConnection.getTransceivers().filter((t=>t.mid&&-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length.");t.map((e=>{e.direction="inactive"}));const i=await this.peerConnection.createOffer(),n=this.logSDPExchange(i.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(i),this.remoteSDP.muteRemote(e);const o=this.remoteSDP.toString();null==n||n(o),await this.peerConnection.setRemoteDescription({type:"answer",sdp:o})}catch(e){throw new me(ne.EXCHANGE_SDP_FAILED,"P2PConnection.muteLocal failed; ".concat(e.toString()))}}async unmuteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.unmuteLocal before remote SDP created.");const t=this.peerConnection.getTransceivers().filter((t=>t.mid&&-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length.");t.map((async(e,t)=>{e.direction="sendonly"}));const i=await this.peerConnection.createOffer(),n=this.logSDPExchange(i.sdp||"","offer","local","unmuteLocal");await this.peerConnection.setLocalDescription(i),this.remoteSDP.unmuteRemote(e),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0&&this.remoteSDP.updateRemoteCodec(e,this.remoteCodecs,this.store.codec);const o=this.remoteSDP.toString();null==n||n(o),await this.peerConnection.setRemoteDescription({type:"answer",sdp:o})}catch(e){throw new me(ne.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteLocal failed; ".concat(e.toString()))}}restartICE(e){var t=this;return Ui((function*(){const i=yield Di(t.mutex.lock("From P2PConnection.restartICE"));try{if(!t.remoteSDP)throw new Error("Cannot restartICE before remoteSDP created.");const n=o().supportPCSetConfiguration,s=ce("FORCE_TURN_TCP")||t.forceTurn;if(e===fn.RELAY&&!n)return;if(n&&!s){const i=e===fn.RELAY?"relay":"all",n=t.peerConnection.getConfiguration();n.iceTransportPolicy!==i&&(B.debug("[".concat(t.store.clientId,"] restartICE change iceTransportPolicy from [").concat(n.iceTransportPolicy,"] to [").concat(i,"]")),n.iceTransportPolicy=i,t.peerConnection.setConfiguration(n))}t.remoteSDP.updateCandidates(e);const a=yield Di(t.peerConnection.createOffer({iceRestart:!0}));if(!a.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const r=mo(a.sdp),c=(yield r.iceParameters).remoteIceParameters;t.remoteSDP.restartICE(c);const d=t.remoteSDP.toString(),l=t.logSDPExchange(a.sdp||"","offer","local","restartICE");t.store.descriptionStart(),yield Di(t.peerConnection.setLocalDescription(a)),null==l||l(d),yield Di(t.peerConnection.setRemoteDescription({type:"answer",sdp:d}))}catch(e){B.warning("[".concat(t.store.clientId,"] restart ICE failed, abort operation"),e)}finally{i()}}))()}async extendCandidate(){if(!this.remoteSDP||this.isFirstConnected)return;const e=await this.mutex.lock("From P2PConnection.extendCandidate");try{this.remoteSDP.updateCandidates(fn.TCP_RELAY),await Po(this.peerConnection,this.remoteSDP,this.extension)}catch(e){B.warning("[".concat(this.store.clientId,"] extend candidate failed, abort operation"),e)}finally{e()}}close(){var e;this.peerConnection.getTransceivers().forEach((e=>{Ea(this.id+e.mid,this)})),this.preMediaMap.forEach((e=>{let t=e.player,i=e.audioTrackId;t&&t.destroy(),i&&S.stop(i)})),this.preMediaMap.clear(),this.peerConnection.close(),null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,"closed"),this.tryUnbindTransportEvents(),this.unbindPCEvents(),this.unbindStatsEvents(),this.removeAllListeners(),this.transportEventReceiver=void 0,this.statsFilter.destroy(),this.dataStreamChannelMap.clear(),this.recoveredDataChannelIds=[],this.currentDataChannelId=1}getStats(){return ki(ki({},this.statsFilter.getStats()),{},{qualityLimitationReason:this.qualityLimitationReason})}getRemoteVideoIsReady(e){return this.statsFilter.getVideoIsReady(e)}async updateEncoderConfig(e,t){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.updateEncoderConfig before remote SDP created.");const i=await this.peerConnection.createOffer(),n=this.mungSendOfferSDP(i.sdp,[t],[e]);this.remoteSDP.updateRecvMedia(e,t);const o=this.remoteSDP.toString(),s=this.logSDPExchange(n,"offer","local","updateEncoderConfig");await this.peerConnection.setLocalDescription({type:"offer",sdp:n}),null==s||s(o),await this.peerConnection.setRemoteDescription({type:"answer",sdp:o})}catch(e){throw new me(ne.EXCHANGE_SDP_FAILED,e.toString())}}async updateSendParameters(e,t){const i=this.peerConnection.getTransceivers().filter((t=>t.mid===e));1===i.length&&(this.isVP8Simulcast(t)?he()||await this.applySimulcastEncodings(i,[t]):await this.applySendEncodings(i,[t]))}setStatsRemoteVideoIsReady(e,t){this.statsFilter.setVideoIsReady2(e,t)}async replaceTrack(e,t){const i=this.peerConnection.getTransceivers().find((e=>e.mid===t));i&&await i.sender.replaceTrack(e._mediaStreamTrack)}async getSelectedCandidatePair(){const e=this.peerConnection.getReceivers();if(e.length>0&&e[0].transport&&e[0].transport.iceTransport&&e[0].transport.iceTransport.getSelectedCandidatePair&&e[0].transport.iceTransport.getSelectedCandidatePair()){const t=e[0].transport.iceTransport.getSelectedCandidatePair(),i=t.local,n=t.remote;return{local:ki(ki({},ht),{},{candidateType:i.type,protocol:i.protocol,address:i.address,port:i.port}),remote:ki(ki({},ht),{},{candidateType:n.type,protocol:n.protocol,address:n.address,port:n.port})}}return this.statsFilter.getSelectedCandidatePair()}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var e;null===(e=this.onICEConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.iceConnectionState)},this.peerConnection.onconnectionstatechange=()=>{var e;"connected"===this.peerConnection.connectionState&&(this.isFirstConnected=!0),null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.connectionState)},this.peerConnection.onicecandidateerror=e=>{if(e&&(e.errorCode||e.errorText)){var t;const i="code: ".concat(e.errorCode,", message: ").concat(e.errorText),n=e.port?"local: ".concat(e.port):"",o=oo(e.url||"");B.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICECandidateError(").concat(i,"), url: ").concat(o||"",", host_candidate:").concat(n)),null===(t=this.onICECandidateError)||void 0===t||t.call(this,i)}},this.peerConnection.onicegatheringstatechange=e=>{e&&e.target&&"iceGatheringState"in e.target&&B.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] RTCPeerConnection.onicegatheringstatechange(").concat(e.target.iceGatheringState,")"))},this.peerConnection.onicecandidate=e=>{e.candidate?this.localCandidateCount+=1:(this.peerConnection.onicecandidate=null,this.allCandidatesReceived=!0,B.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount))},setTimeout((()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,B.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount))}),ce("CANDIDATE_TIMEOUT"))}unbindPCEvents(){this.peerConnection.oniceconnectionstatechange=null,this.peerConnection.onconnectionstatechange=null,this.peerConnection.onsignalingstatechange=null,this.peerConnection.onicecandidateerror=null,this.peerConnection.onicecandidate=null,this.peerConnection.ontrack=null}static resolvePCConfiguration(t){const i={iceServers:[]},n=t.cloudProxyServer||"disabled";return t.iceServers?i.iceServers=t.iceServers:t.turnServer&&(dt(t.turnServer.servers)?i.iceServers=t.turnServer.servers:ce("NEW_TURN_MODE")&&i.iceServers&&"disabled"===n?(ce("USE_TURN_SERVER_OF_GATEWAY")?t.turnServer.serversFromGateway&&i.iceServers.push(...e.newTurnServerConfigToIceServers(t.turnServer.serversFromGateway)):i.iceServers.push(...e.newTurnServerConfigToIceServers(t.turnServer.servers)),ce("NEW_FORCE_TURN")&&(i.iceTransportPolicy="relay")):"off"!==t.turnServer.mode&&(i.iceServers&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers)),ce("USE_TURN_SERVER_OF_GATEWAY")&&i.iceServers&&t.turnServer.serversFromGateway&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway)),ce("FORCE_TURN_TCP")?i.iceTransportPolicy="relay":t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach((e=>{e.forceturn&&(i.iceTransportPolicy="relay")})))),ce("ENABLE_ENCODED_TRANSFORM")&&o().supportWebRTCEncodedTransform&&(i.encodedInsertableStreams=!0),i}static turnServerConfigToIceServers(e){const t=[];return e.forEach((e=>{e.security?e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(Jn(e.turnServerURL),":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&!ce("FORCE_TURN_TCP")&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.udpport,"?transport=udp")}),e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.tcpport,"?transport=tcp")}))})),t}static newTurnServerConfigToIceServers(e){const t=[];return e.forEach((e=>{const i=ce("NEW_TURN_MODE");1===i?t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=udp")}):2===i?t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=tcp")}):3===i?t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(Jn(e.turnServerURL),":443?transport=tcp")}):4===i&&(t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=udp")}),t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=tcp")}),t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(Jn(e.turnServerURL),":443?transport=tcp")}))})),t}tryBindTransportEvents(e){const t=e.transport;if(t){this.transportEventReceiver=e,t.onstatechange=()=>{var e;null!=t&&t.state&&(null===(e=this.onDTLSTransportStateChange)||void 0===e||e.call(this,t.state))},t.onerror=e=>{var t;null===(t=this.onDTLSTransportError)||void 0===t||t.call(this,"error"in e?e.error:e)};const i=t.iceTransport;i&&(i.onstatechange=()=>{const e=null==t?void 0:t.iceTransport.state;var i;e&&(null===(i=this.onICETransportStateChange)||void 0===i||i.call(this,e))},i.getSelectedCandidatePair&&(i.onselectedcandidatepairchange=()=>{if(i.getSelectedCandidatePair()){const e=i.getSelectedCandidatePair()||{},t=e.local,n=e.remote;if(t&&n){const e=t.address+":"+t.port,i=n.address+":"+n.port;B.info("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] selectedcandidatepairchange: local ").concat(JSON.stringify(oo(e)),", remote ").concat(JSON.stringify(oo(i))))}}}))}}tryUnbindTransportEvents(){this.transportEventReceiver&&this.transportEventReceiver.transport&&(this.transportEventReceiver.transport.onstatechange=null,this.transportEventReceiver.transport.onerror=null,this.transportEventReceiver.transport.iceTransport&&(this.transportEventReceiver.transport.iceTransport.onstatechange=null))}async updateRtpSenderEncodings(e,t){var i;if(!t){const i=this.peerConnection.getSenders();t=i.find((t=>t.track===e._mediaStreamTrack))}if(!t)return B.warn("[".concat(e.getTrackId(),"] no rtpSender found}"));if(this.isVP8Simulcast(e))return B.warn("[updateRtpSenderEncodings] Track is VP8 simulcast, please apply simulcast encodings");if(!o().supportSetRtpSenderParameters)return B.warn("[updateRtpSenderEncodings] Browser not support set rtp-sender parameters");const n=f(e),a=!!n&&na(this.store.codec)&&ia(n),r=a&&!this.unsupportedResolutionFloorTrackIds.has(e.getTrackId()),c=!!n&&!(a&&!r)&&ua(e,r?n:void 0),d=r&&c,l=r||["vp8","vp9"].includes(this.store.codec),h={},u={},_=Ca(e,d);_&&(h.degradationPreference=_);const p=so(this.peerConnection,e._mediaStreamTrack);if(c&&p&&t&&n&&this.getLocalVideoStats&&l){const i=this.id+p.mid,o=fa(e,r);pa(i,n,this,o,(n=>{t&&this.updateAdaptation(e,t,n,i,r)}),this.getLocalVideoStats.bind(this))}if(e._encoderConfig){const t=e._encoderConfig,i=t.bitrateMax,n=t.frameRate,o=t.scaleResolutionDownBy;i&&(u.maxBitrate=1e3*i),(e._hints.includes(s.LOW_STREAM)||e.isUseScaleResolutionDownBy)&&(n&&(u.maxFramerate=zn(n)),o&&o>=1&&(u.scaleResolutionDownBy=o))}const E=ce("ENCODER_CONFIG_LIMIT").maxFramerate;if(E&&"number"==typeof E&&(u.maxFramerate=u.maxFramerate?Math.min(u.maxFramerate,E):E),ce("DSCP_TYPE")&&ct()){const e=ce("DSCP_TYPE");["very-low","low","medium","high"].includes(e)&&(u.networkPriority=e)}const m=t.getParameters(),S=null===(i=m.encodings)||void 0===i?void 0:i[0];he()&&!S&&(h.encodings=[u]),S&&Object.assign(S,u),Object.assign(m,h),B.debug("[".concat(e.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(m.encodings))),await t.setParameters(m),await Mo(this.store.codec,t,ce("SVC_MODE"))}async updateAdaptation(e,t,i,n,s){var a;if(!t)return B.debug("[updateAdaptation] no rtpSender found");if(!o().supportSetRtpSenderParameters)return B.debug("[updateAdaptation] Browser not support set rtp-sender parameters");const r={},c={},d=i.bitrateMax,l=i.frameRate,h=i.scaleResolutionDownBy;d&&(c.maxBitrate=1e3*d),l&&(c.maxFramerate=zn(l));let u=!1;"number"==typeof h&&h>=1&&(s||["vp8","vp9"].includes(this.store.codec))&&(c.scaleResolutionDownBy=h,u=h>1);const _=t.getParameters(),p=null===(a=_.encodings)||void 0===a?void 0:a[0];p&&Object.assign(p,c),Object.assign(_,r);try{await t.setParameters(_),B.debug("[updateAdaptation] updateRtpSenderEncodings: ".concat(JSON.stringify(_.encodings)))}catch(i){if(!("transport"in t)||t.transport&&"connected"===t.transport.state)if("connected"!==this.peerConnectionState)B.debug("[updateAdaptation] peerConnection not connected}");else if(s&&u){const o=await Ta(t,r,c);"unsupported"===o.classification?(this.unsupportedResolutionFloorTrackIds.add(e.getTrackId()),Ea(n,this),B.warn("[".concat(e.getTrackId(),"] fallback to browser adaptation because scaleResolutionDownBy adaptation is unsupported"),i,o.retryWithScaleError),this.updateRtpSenderEncodings(e,t).catch((t=>{B.warn("[".concat(e.getTrackId(),"] failed to re-apply browser adaptation after disabling resolution floor"),t)}))):"transient"===o.classification?B.debug("[".concat(e.getTrackId(),"] keep resolution floor enabled after transient setParameters failure"),i):B.debug("[".concat(e.getTrackId(),"] keep resolution floor enabled because setParameters failure is not classified as unsupported"),i,o.retryWithScaleError,o.retryWithoutScaleError)}else B.debug("[updateAdaptation] updateRtpSenderEncodings failed",i);else B.debug("[updateAdaptation] rtpSender transport not connected}")}}async applySendEncodings(e,t){try{if(!o().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let i=0;i<e.length;i++){const o=e[i],s=t[i];s instanceof n&&!this.isVP8Simulcast(s)&&await this.updateRtpSenderEncodings(s,o.sender)}}catch(e){B.debug("[".concat(this.store.clientId,"] Apply RTPSendEncodings failed."))}}mungSendOfferSDP(e,t,i){if(ce("FORBID_MODIFY_LOCAL_OFFER_SDP"))return e;const n=be(e);return t.forEach(((e,t)=>{const o=i[t],s=n.mediaDescriptions.find((e=>e.attributes.mid===o));s&&(go(s,e),vo(s,e,this.store.codec))})),De(n)}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=e=>{var t;null===(t=this.onFirstAudioReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoReceived=e=>{var t;null===(t=this.onFirstVideoReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstAudioDecoded=e=>{var t;null===(t=this.onFirstAudioDecoded)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoDecoded=(e,t,i)=>{var n;null===(n=this.onFirstVideoDecoded)||void 0===n||n.call(this,e,t,i)},this.statsFilter.onSelectedLocalCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedLocalCandidateChanged)||void 0===i||i.call(this,e,t)},this.statsFilter.onSelectedRemoteCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedRemoteCandidateChanged)||void 0===i||i.call(this,e,t)},this.statsFilter.onFirstVideoDecodedTimeout=e=>{var t;null===(t=this.onFirstVideoDecodedTimeout)||void 0===t||t.call(this,e)}}unbindStatsEvents(){this.statsFilter.onFirstAudioReceived=void 0,this.statsFilter.onFirstVideoReceived=void 0,this.statsFilter.onFirstAudioDecoded=void 0,this.statsFilter.onFirstVideoDecoded=void 0,this.statsFilter.onSelectedLocalCandidateChanged=void 0,this.statsFilter.onSelectedRemoteCandidateChanged=void 0,this.statsFilter.onFirstVideoDecodedTimeout=void 0}async applySimulcastForFirefox(e,t){if(e.length===t.length)for(let c=0;c<e.length;c++){var i,o,a,r;const d=e[c],l=t[c];if(l instanceof n&&!l._hints.includes(s.LOW_STREAM)&&null!==(i=l._encoderConfig)&&void 0!==i&&i.bitrateMax&&(null===(o=l._encoderConfig)||void 0===o?void 0:o.bitrateMax)>200&&null!==(a=l._scalabilityMode)&&void 0!==a&&a.numSpatialLayers&&(null===(r=l._scalabilityMode)||void 0===r?void 0:r.numSpatialLayers)>1&&"vp8"===this.store.codec){const e={},t={high:1e3*(l._encoderConfig.bitrateMax-50),medium:5e4};e.encodings=[{rid:"m",active:!0,maxBitrate:t.medium,scaleResolutionDownBy:4},{rid:"h",active:!0,maxBitrate:t.high}];const i=d.sender.getParameters();await d.sender.setParameters(Object.assign(i,e))}}}async applySimulcastEncodings(e,t){if(!he()&&e.length===t.length)for(let i=0;i<e.length;i++){const o=t[i];if(o instanceof n&&this.isVP8Simulcast(o)){const t=e[i],n={},s={high:1e3*(o._encoderConfig.bitrateMax-50),medium:5e4};n.encodings=[{active:!0,adaptivePtime:!1,networkPriority:"high",priority:"high",maxBitrate:s.high},{active:!0,adaptivePtime:!1,networkPriority:"low",priority:"low",maxBitrate:s.medium,scaleResolutionDownBy:4}];const a=t.sender.getParameters();await t.sender.setParameters(Object.assign(a,n))}}}isVP8Simulcast(e){var t,i,o,a;return!!(e instanceof n&&ce("SIMULCAST")&&"vp8"===this.store.codec&&!e._hints.includes(s.LOW_STREAM)&&null!==(t=e._encoderConfig)&&void 0!==t&&t.bitrateMax&&(null===(i=e._encoderConfig)||void 0===i?void 0:i.bitrateMax)>200&&null!==(o=e._scalabilityMode)&&void 0!==o&&o.numSpatialLayers&&(null===(a=e._scalabilityMode)||void 0===a?void 0:a.numSpatialLayers)>1)}logSDPExchange(e,t,i,n){if(ce("SDP_LOGGING"))return B.upload("[".concat(this.store.clientId,"] exchanging ").concat(i," ").concat(t," SDP during P2PConnection.").concat(n,"\n"),e),"offer"===t?e=>{this.logSDPExchange(e,"answer","local"===i?"remote":"local",n)}:void 0}async getRemoteSSRC(e){if(!this.remoteSDP)return;const t=this.remoteSDP.getSSRC(e);return t&&0!==t.length?t[0].ssrcId:void 0}setConfiguration(t){if(o().supportPCSetConfiguration){const i=e.resolvePCConfiguration(t);this.peerConnection.setConfiguration(i)}t.isPreallocation&&(this.isPreallocation=!0)}},yi(wa.prototype,"updateRemoteRTPCapabilities",[Oa],Object.getOwnPropertyDescriptor(wa.prototype,"updateRemoteRTPCapabilities"),wa.prototype),yi(wa.prototype,"connect",[Oa],Object.getOwnPropertyDescriptor(wa.prototype,"connect"),wa.prototype),yi(wa.prototype,"updateRemoteConnect",[Oa],Object.getOwnPropertyDescriptor(wa.prototype,"updateRemoteConnect"),wa.prototype),yi(wa.prototype,"createDataChannels",[Oa],Object.getOwnPropertyDescriptor(wa.prototype,"createDataChannels"),wa.prototype),yi(wa.prototype,"receive",[Oa],Object.getOwnPropertyDescriptor(wa.prototype,"receive"),wa.prototype),yi(wa.prototype,"batchReceive",[Oa],Object.getOwnPropertyDescriptor(wa.prototype,"batchReceive"),wa.prototype),yi(wa.prototype,"stopReceiving",[Oa],Object.getOwnPropertyDescriptor(wa.prototype,"stopReceiving"),wa.prototype),yi(wa.prototype,"muteRemote",[Oa],Object.getOwnPropertyDescriptor(wa.prototype,"muteRemote"),wa.prototype),yi(wa.prototype,"unmuteRemote",[Oa],Object.getOwnPropertyDescriptor(wa.prototype,"unmuteRemote"),wa.prototype),yi(wa.prototype,"muteLocal",[Oa],Object.getOwnPropertyDescriptor(wa.prototype,"muteLocal"),wa.prototype),yi(wa.prototype,"unmuteLocal",[Oa],Object.getOwnPropertyDescriptor(wa.prototype,"unmuteLocal"),wa.prototype),yi(wa.prototype,"close",[Oa],Object.getOwnPropertyDescriptor(wa.prototype,"close"),wa.prototype),yi(wa.prototype,"updateEncoderConfig",[Oa],Object.getOwnPropertyDescriptor(wa.prototype,"updateEncoderConfig"),wa.prototype),yi(wa.prototype,"updateSendParameters",[Oa],Object.getOwnPropertyDescriptor(wa.prototype,"updateSendParameters"),wa.prototype),yi(wa.prototype,"replaceTrack",[Oa],Object.getOwnPropertyDescriptor(wa.prototype,"replaceTrack"),wa.prototype),yi(wa.prototype,"updateAdaptation",[Oa],Object.getOwnPropertyDescriptor(wa.prototype,"updateAdaptation"),wa.prototype),yi(wa.prototype,"getRemoteSSRC",[Oa],Object.getOwnPropertyDescriptor(wa.prototype,"getRemoteSSRC"),wa.prototype),wa);function Oa(e,t,i){const n=e[t];if("function"!=typeof n)throw new Error("Cannot use mutex on object property.");return i.value=async function(){const e=this.mutex,i=await e.lock("From P2PConnection.".concat(t));try{for(var o=arguments.length,s=new Array(o),a=0;a<o;a++)s[a]=arguments[a];return await n.apply(this,s)}finally{i()}},i}function Da(e,t){let i=document.createElement("video"),n=document.createElement("canvas");i.setAttribute("style","display:none"),n.setAttribute("style","display:none"),i.setAttribute("muted",""),i.muted=!0,i.setAttribute("autoplay",""),i.autoplay=!0,i.setAttribute("playsinline",""),n.width=zn(t.width),n.height=zn(t.height);const s=zn(t.framerate||15);document.body.append(i),document.body.append(n);let a=e._mediaStreamTrack;i.srcObject=new MediaStream([a]),i.play().catch(ut);const r=n.getContext("2d");if(!r)throw new j(ne.UNEXPECTED_ERROR,"can not get canvas context");const c=o(),d=n.captureStream(c.supportRequestFrame?0:s).getVideoTracks()[0];d.canvas||(d.canvas=n),n.startCapture=()=>{if(!i)return n.stopCapture&&n.stopCapture();if(i.paused&&i.play(),i.videoHeight>2&&i.videoWidth>2){const e=i.videoWidth,t=i.videoHeight/e,o=n.width*t;Math.abs(o-n.height)>=2&&(B.debug("adjust low stream resolution","".concat(n.width,"x").concat(n.height," -> ").concat(n.width,"x").concat(o)),n.height=o)}r.drawImage(i,0,0,n.width,n.height),d.requestFrame&&d.requestFrame(),a!==e._mediaStreamTrack&&(a=e._mediaStreamTrack,i.srcObject=new MediaStream([a]))},n.stopCapture=C((()=>n.startCapture&&n.startCapture()),s);const l=d.stop;return d.stop=()=>{l.call(d),i&&(i.remove(),i.srcObject=null,i=null),n&&(n.width=0,n.remove(),n.stopCapture&&n.stopCapture(),n.startCapture=void 0,n.stopCapture=void 0,n=null),B.debug("clean low stream renderer")},d}var Pa=function(e){return e[e.Video_Send_Type=190]="Video_Send_Type",e}(Pa||{}),La=function(e){return e[e.Video_Send_Qp_Sum=2143]="Video_Send_Qp_Sum",e[e.Video_Send_Freeze=2082]="Video_Send_Freeze",e[e.Video_Send_Codec=2240]="Video_Send_Codec",e[e.Video_Send_Power_Efficient_Encoder=2241]="Video_Send_Power_Efficient_Encoder",e[e.Video_Recv_Qp_Sum=2144]="Video_Recv_Qp_Sum",e[e.Video_Recv_Freeze=2084]="Video_Recv_Freeze",e[e.Video_Recv_Codec=2242]="Video_Recv_Codec",e[e.Video_Recv_Power_Efficient_Decoder=2243]="Video_Recv_Power_Efficient_Decoder",e[e.Video_Render_Freeze_Time=2109]="Video_Render_Freeze_Time",e[e.Video_Render_Freeze_Time_Render=2147]="Video_Render_Freeze_Time_Render",e[e.Video_Render_Freeze_Time_Render2=2223]="Video_Render_Freeze_Time_Render2",e[e.Audio_Recv_Freeze=2083]="Audio_Recv_Freeze",e}(La||{}),ka=function(e){return e[e.Video_Send_Retransmit=2062]="Video_Send_Retransmit",e[e.Video_Send_Target_Encoded=2064]="Video_Send_Target_Encoded",e[e.Video_Send_Actual_Encoded=2060]="Video_Send_Actual_Encoded",e[e.Video_Send_Transmit=2066]="Video_Send_Transmit",e[e.Video_Send_Bandwidth=2061]="Video_Send_Bandwidth",e[e.Video_Capture_Height=2033]="Video_Capture_Height",e[e.Video_Capture_Width=2035]="Video_Capture_Width",e[e.Video_Capture_Frame_Rate=2034]="Video_Capture_Frame_Rate",e[e.Video_Send_Low_Height=2073]="Video_Send_Low_Height",e[e.Video_Send_Low_Frame_Rate=2075]="Video_Send_Low_Frame_Rate",e[e.Video_Send_Low_Width=2077]="Video_Send_Low_Width",e[e.Video_Send_Low_Bitrate=2069]="Video_Send_Low_Bitrate",e[e.Video_Send_Low_Package_Lost=2070]="Video_Send_Low_Package_Lost",e[e.Video_Send_Low_Package_Rate=2071]="Video_Send_Low_Package_Rate",e[e.Video_Send_Frame_Rate=2002]="Video_Send_Frame_Rate",e[e.Video_Send_Width=2003]="Video_Send_Width",e[e.Video_Send_Height=2004]="Video_Send_Height",e[e.Video_Send_Disabled=2095]="Video_Send_Disabled",e[e.Video_Send_Adaptation=2032]="Video_Send_Adaptation",e[e.Video_Send_Player_Status=2128]="Video_Send_Player_Status",e[e.Video_Send_Nacks=2009]="Video_Send_Nacks",e[e.Video_Send_Plis=2010]="Video_Send_Plis",e[e.Video_Send_Firs=2011]="Video_Send_Firs",e[e.Video_Send_Avg_Encode=2007]="Video_Send_Avg_Encode",e[e.Video_Send_Huge_Frame_Sent=2174]="Video_Send_Huge_Frame_Sent",e[e.Video_Send_Bytes_Retransmit=2173]="Video_Send_Bytes_Retransmit",e[e.Video_Send_Packages_Retransmit=2172]="Video_Send_Packages_Retransmit",e[e.Video_Send_Key_Frames_Encoded=2207]="Video_Send_Key_Frames_Encoded",e[e.Video_Send_Bitrate=2012]="Video_Send_Bitrate",e[e.Video_Send_Package_Rate=2031]="Video_Send_Package_Rate",e[e.Video_Send_Package_Lost=2005]="Video_Send_Package_Lost",e[e.Audio_Capture_PCM_Level=2104]="Audio_Capture_PCM_Level",e[e.Audio_Send_Level=2038]="Audio_Send_Level",e[e.Audio_Send_Bitrate=2039]="Audio_Send_Bitrate",e[e.Audio_Send_Package_Rate=2040]="Audio_Send_Package_Rate",e[e.Audio_Send_AEC_Return_Loss=2041]="Audio_Send_AEC_Return_Loss",e[e.Audio_Send_AEC_Return_Loss_Enhancement=2042]="Audio_Send_AEC_Return_Loss_Enhancement",e[e.Audio_Send_Freeze=2081]="Audio_Send_Freeze",e[e.Audio_Send_Disabled=2096]="Audio_Send_Disabled",e[e.Audio_Send_Bytes_Retransmit=2179]="Audio_Send_Bytes_Retransmit",e[e.Audio_Send_Packages_Retransmit=2180]="Audio_Send_Packages_Retransmit",e[e.Video_Recv_Height=2019]="Video_Recv_Height",e[e.Video_Recv_Width=2018]="Video_Recv_Width",e[e.Video_Recv_Frame_Rate_Output=2155]="Video_Recv_Frame_Rate_Output",e[e.Video_Recv_Jitter_Buffer=2023]="Video_Recv_Jitter_Buffer",e[e.Video_Recv_Current_Delay=2024]="Video_Recv_Current_Delay",e[e.Video_Recv_Nacks=2026]="Video_Recv_Nacks",e[e.Video_Recv_Plis=2027]="Video_Recv_Plis",e[e.Video_Recv_Firs=2028]="Video_Recv_Firs",e[e.Video_Recv_Disabled=2101]="Video_Recv_Disabled",e[e.Video_Recv_Player_Status=2129]="Video_Recv_Player_Status",e[e.Video_Recv_I_Frame_Delay=2149]="Video_Recv_I_Frame_Delay",e[e.Video_Render_Frame_Rate_Render=2022]="Video_Render_Frame_Rate_Render",e[e.Video_Render_Freeze_Duration=2156]="Video_Render_Freeze_Duration",e[e.Audio_Render_Level=2043]="Audio_Render_Level",e[e.Audio_Render_Freeze_Time_80ms=2226]="Audio_Render_Freeze_Time_80ms",e[e.Audio_Render_Freeze_Time_200ms=2227]="Audio_Render_Freeze_Time_200ms",e[e.Audio_Render_Freeze_Samples_80ms=2228]="Audio_Render_Freeze_Samples_80ms",e[e.Audio_Render_Freeze_Samples_200ms=2229]="Audio_Render_Freeze_Samples_200ms",e[e.Audio_Recv_PCM_Level=2105]="Audio_Recv_PCM_Level",e[e.Audio_Recv_Disabled=2102]="Audio_Recv_Disabled",e[e.Audio_Recv_Jitter_Buffer=2054]="Audio_Recv_Jitter_Buffer",e[e.Audio_Recv_Current_Delay=2047]="Audio_Recv_Current_Delay",e[e.Audio_Recv_Player_Status=2130]="Audio_Recv_Player_Status",e[e.Audio_Recv_Bitrate=2044]="Audio_Recv_Bitrate",e[e.Audio_Recv_Concealed_Samples=2148]="Audio_Recv_Concealed_Samples",e[e.Audio_Recv_Total_Samples_Received=2224]="Audio_Recv_Total_Samples_Received",e}(ka||{}),Ma=function(e){return e[e.Video_Render_Frame_Rate_Decode=2021]="Video_Render_Frame_Rate_Decode",e[e.Video_Recv_Frame_Rate=2020]="Video_Recv_Frame_Rate",e[e.Video_Recv_Frame_Dropped=2181]="Video_Recv_Frame_Dropped",e[e.Video_Recv_Bytes_Retransmit=2175]="Video_Recv_Bytes_Retransmit",e[e.Video_Recv_Packages_Retransmit=2176]="Video_Recv_Packages_Retransmit",e[e.Video_Recv_Packages_Discarded=2198]="Video_Recv_Packages_Discarded",e[e.Video_Recv_Avg_Decode=2200]="Video_Recv_Avg_Decode",e[e.Video_Recv_Avg_Processing_Delay=2202]="Video_Recv_Avg_Processing_Delay",e[e.Video_Recv_Avg_Assembly_Time=2203]="Video_Recv_Avg_Assembly_Time",e[e.Video_Recv_Avg_Inter_Frame_Delay=2204]="Video_Recv_Avg_Inter_Frame_Delay",e[e.Video_Recv_Key_Frames_Decoded=2206]="Video_Recv_Key_Frames_Decoded",e[e.Video_Recv_Package_Lost=2014]="Video_Recv_Package_Lost",e[e.Video_Recv_Bitrate=2029]="Video_Recv_Bitrate",e[e.Video_Recv_Package_Rate=2078]="Video_Recv_Package_Rate",e[e.Audio_Recv_Jitter=2055]="Audio_Recv_Jitter",e[e.Audio_Recv_Bytes_Retransmit=2178]="Audio_Recv_Bytes_Retransmit",e[e.Audio_Recv_Packages_Retransmit=2177]="Audio_Recv_Packages_Retransmit",e[e.Audio_Recv_Packages_Discarded=2199]="Audio_Recv_Packages_Discarded",e[e.Audio_Recv_Avg_Processing_Delay=2201]="Audio_Recv_Avg_Processing_Delay",e[e.Audio_Recv_Package_Rate=2046]="Audio_Recv_Package_Rate",e[e.Audio_Recv_Package_Lost=2045]="Audio_Recv_Package_Lost",e[e.Audio_Recv_AV_Sync_TIME=2237]="Audio_Recv_AV_Sync_TIME",e}(Ma||{}),Ua=function(e){return e[e.RTT=2006]="RTT",e[e.CONN_TYPE=801]="CONN_TYPE",e[e.STATS_UPDATE_INTERVAL=2205]="STATS_UPDATE_INTERVAL",e}(Ua||{}),Va=function(e){return e[e.RTC_PEER_CONNECTION_STATE=2219]="RTC_PEER_CONNECTION_STATE",e[e.PAGE_VISIBILITY=2233]="PAGE_VISIBILITY",e}(Va||{}),xa=function(e){return e[e.Transport_Send_Bitrate=2234]="Transport_Send_Bitrate",e[e.Transport_Recv_Bitrate=2235]="Transport_Recv_Bitrate",e}(xa||{});const Fa=1e3,Ba=6,ja=3,Ga=Math.max(Ba,ja,60);function Wa(e){return(e=e.toLowerCase()).includes("vp8")?1:e.includes("h264")?2:e.includes("vp9")?3:e.includes("av1")?4:e.includes("h265")?5:0}function Ha(e,t,i){null!=i&&Number.isFinite(i)&&(e[t]=Math.round(Math.max(0,i)))}function Ka(e){const t={[Ua.CONN_TYPE]:0,[Ua.RTT]:e.rtt,[Ua.STATS_UPDATE_INTERVAL]:e.updateInterval?Math.round(Math.max(0,e.updateInterval)):void 0};switch(e.selectedCandidatePair.localCandidate.candidateType){case"relay":{const i=e.selectedCandidatePair.localCandidate.relayProtocol;"udp"===i&&(t[Ua.CONN_TYPE]=1),"tcp"===i&&(t[Ua.CONN_TYPE]=3),"tls"===i&&(t[Ua.CONN_TYPE]=4);break}case"srflx":t[Ua.CONN_TYPE]=2;break;case"unknown":t[Ua.CONN_TYPE]=5;break;default:t[Ua.CONN_TYPE]=0}return t}function Ya(e){let t=0;switch(e){case"none":t=0;break;case"cpu":t=1;break;case"bandwidth":t=2;break;case"other":t=3}return t}class qa extends re{constructor(e){super(),this.store=void 0,this.uploadWRTCStatsTimer=void 0,this.uploadOutboundDenoiserStatsTimer=void 0,this.uploadExtStatsTimer=void 0,this.uploadExtUsageStatsTimer=void 0,this.uploadInboundExtStatsTimer=void 0,this.requestStats=void 0,this.requestTransportStats=void 0,this.requestLocalMedia=void 0,this.requestRemoteMedia=void 0,this.requestAllTracks=void 0,this.requestVideoIsReady=void 0,this.requestUploadStats=void 0,this.requestUpload=void 0,this.uploadOutboundStarted=!1,this.uploadInboundStarted=!1,this.uploadTransportStarted=!1,this.uploadBaseStatsStarted=!1,this.uploadExtensionUsageStarted=!1,this.lastRecvStats=void 0,this.lastSendStats=void 0,this.lastRefRecvStats=void 0,this.lastRefSendStats=void 0,this.lastNormalRecvStats=void 0,this.lastNormalSendStats=void 0,this.lastExtendStats={},this.needUploadStats={},this.needUploadRenderFreezeTime=!0,this.lastUploadCompensateTime=-1,this.uploadCompensateDeltaTime=0,this.store=e}uploadWRTCStats(e){if(!this.requestStats||!this.requestUploadStats)return;const t=e%ja==0,i=e%Ba==0,n=e%60==0;let o,s;if(this.uploadTransportStarted&&(o=this.requestStats(),this.store.useP2P&&(s=this.requestStats(!0))),!o&&this.uploadOutboundStarted&&(o=this.requestStats()),!s&&this.uploadInboundStarted&&(s=this.requestStats(!0)),o||s){var a;const r={};if(this.uploadTransportStarted&&o){const e=this.getTransportStats(o,t?this.lastRefSendStats:void 0,s,t);e&&(r.misc=[e])}if(this.uploadOutboundStarted&&o){const e=this.getOutboundStats(o,i?this.lastNormalSendStats:void 0,t?this.lastRefSendStats:void 0,this.lastSendStats,n);e&&(r.outbound=[e])}if(this.uploadInboundStarted&&s){this.uploadCompensateStats(e);const n=this.getInboundStats(s,i?this.lastNormalRecvStats:void 0,t?this.lastRefRecvStats:void 0,this.lastRecvStats);n&&(r.inbound=n)}const c=null===(a=this.requestTransportStats)||void 0===a?void 0:a.call(this).connectState;if(c&&(Array.isArray(r.misc)?r.misc[0]&&r.misc[0].addition&&(r.misc[0].addition[Va.RTC_PEER_CONNECTION_STATE]=_t[c]):r.misc=[{addition:{[Va.RTC_PEER_CONNECTION_STATE]:_t[c]}}]),T.needUploadStats.length>0||i){const e=T.needUploadStats.shift()||("visible"===T.visibility?1:0);Array.isArray(r.misc)?r.misc[0]&&r.misc[0].addition&&(r.misc[0].addition[Va.PAGE_VISIBILITY]=e):r.misc=[{addition:{[Va.PAGE_VISIBILITY]:e}}]}this.needUploadStats.sendType&&(Array.isArray(r.outbound)&&r.outbound[0]&&r.outbound[0].high&&(r.outbound[0].high[Pa.Video_Send_Type]=this.needUploadStats.sendType),this.needUploadStats.sendType=void 0),this.requestUploadStats(r)}this.lastRecvStats=s,this.lastSendStats=o,i&&(this.lastNormalRecvStats=s,this.lastNormalSendStats=o),t&&(this.lastRefRecvStats=s,this.lastRefSendStats=o)}startUploadWRTCStats(){if(this.uploadWRTCStatsTimer)return;this.uploadBaseStatsStarted=!0,T.startCollectStats();let e=1;this.uploadWRTCStatsTimer=window.setInterval((()=>{if(!this.uploadTransportStarted&&!this.uploadInboundStarted&&!this.uploadOutboundStarted){if(this.uploadBaseStatsStarted){var t,i;const e=null===(t=this.requestTransportStats)||void 0===t?void 0:t.call(this);return void(e&&(null===(i=this.requestUploadStats)||void 0===i||i.call(this,{misc:[{addition:{[Va.RTC_PEER_CONNECTION_STATE]:_t[e.connectState]}}]})))}return this.stopUploadWRTCStats()}this.uploadWRTCStats(e),++e===Ga+1&&(e=1)}),Fa)}uploadCompensateStats(e){if(!this.requestStats||!this.requestUploadStats||!this.requestRemoteMedia)return;const t=e%ja==0&&this.needUploadRenderFreezeTime;if(!this.uploadInboundStarted||!t)return;if(-1===this.lastUploadCompensateTime)return void(this.lastUploadCompensateTime=Date.now());const i=Math.max(-6e3,Date.now()-this.lastUploadCompensateTime-6e3);if(this.uploadCompensateDeltaTime+=i,this.lastUploadCompensateTime=Date.now(),this.uploadCompensateDeltaTime<6e3)return;const n=Math.min(Math.floor(this.uploadCompensateDeltaTime/6e3),10);this.uploadCompensateDeltaTime-=6e3*n;const s=this.requestStats(!0);new Array(n).fill(0).forEach((()=>{if(!this.requestStats||!this.requestUploadStats||!this.requestRemoteMedia)return;const e={};if(this.uploadInboundStarted&&s){const t=this.requestRemoteMedia()||[],i=[];t.forEach((e=>{let t=Mi(e,2),n=t[0],a=t[1];const r={peer:n.uid};if((n._videoSSRC&&this.requestVideoIsReady&&this.requestVideoIsReady(n._videoSSRC)||!1)&&a.has(Sn.VIDEO)&&n.videoTrack){const e=function(e,t,i){if(!t.videoRecv.find((t=>t.ssrc===e)))return;const n={};if(i&&i._player){const e=i._player,t=e.renderFreezeAccTime2,s=e.videoElementStatus;if("visible"===T.visibility&&s===g.PLAYING&&o().supportRequestVideoFrameCallback){const i=Math.min(6e3,t);e.renderFreezeAccTime2=Math.max(0,t-i),Ha(n,La.Video_Render_Freeze_Time_Render2,i),ce("USE_NEW_RENDER_FREEZE_TIME")&&Ha(n,La.Video_Render_Freeze_Time_Render,i)}}return n}(n._videoSSRC,s,n.videoTrack);e&&(r.video=e)}r.video&&i.push(r)})),i.length>0&&(e.inbound=i,this.requestUploadStats(e))}}))}stopUploadWRTCStats(){window.clearInterval(this.uploadWRTCStatsTimer),this.uploadWRTCStatsTimer=void 0,this.lastSendStats&&(this.lastSendStats.videoSend=[],this.lastSendStats.audioSend=[],this.lastSendStats=void 0),this.lastRecvStats&&(this.lastRecvStats.videoRecv=[],this.lastRecvStats.audioRecv=[],this.lastRecvStats=void 0),this.lastRefSendStats&&(this.lastRefSendStats.videoSend=[],this.lastRefSendStats.audioSend=[],this.lastRefSendStats=void 0),this.lastRefRecvStats&&(this.lastRefRecvStats.videoRecv=[],this.lastRefRecvStats.audioRecv=[],this.lastRefRecvStats=void 0),this.lastNormalSendStats&&(this.lastNormalSendStats.videoSend=[],this.lastNormalSendStats.audioSend=[],this.lastNormalSendStats=void 0),this.lastNormalRecvStats&&(this.lastNormalRecvStats.videoRecv=[],this.lastNormalRecvStats.audioRecv=[],this.lastNormalRecvStats=void 0),this.lastExtendStats={},this.needUploadStats={},this.lastUploadCompensateTime=-1,this.uploadCompensateDeltaTime=0,this.needUploadRenderFreezeTime=!0}getTransportStats(e,t,i,n){if(!this.requestStats)return;if(!n)return null==e.rtt?void 0:{addition:{[Ua.RTT]:e.rtt,[Ua.CONN_TYPE]:void 0,[Ua.STATS_UPDATE_INTERVAL]:e.updateInterval||void 0}};const o=Ka(e);if(this.store.useP2P){if(i){const e=Ka(i);o[Ua.CONN_TYPE]&&e[Ua.CONN_TYPE]&&(o[Ua.CONN_TYPE]+=e[Ua.CONN_TYPE]<<3)}o[Ua.CONN_TYPE]?o[Ua.CONN_TYPE]+=110:o[Ua.CONN_TYPE]=110}else{o[Ua.CONN_TYPE]?o[Ua.CONN_TYPE]+=100:o[Ua.CONN_TYPE]=100;const i=function(e,t){if(t)return[Math.ceil(8*(e.transport.bytesSent-t.transport.bytesSent)/(e.timestamp-t.timestamp)),Math.ceil(8*(e.transport.bytesReceived-t.transport.bytesReceived)/(e.timestamp-t.timestamp))];return[0,0]}(e,t);o[xa.Transport_Send_Bitrate]=i[0],o[xa.Transport_Recv_Bitrate]=i[1]}return{addition:o}}getOutboundStats(e,t,i,n,o){if(!this.requestUploadStats||!this.requestLocalMedia)return;const a=this.requestLocalMedia();if(!a||0===a.length)return;let r,c,d;return a.forEach((n=>{let a=Mi(n,2),l=a[0],h=a[1],u=h.track,_=h.ssrcs;switch(l){case Tn.LocalVideoLowTrack:case Tn.LocalVideoTrack:if(l===Tn.LocalVideoTrack){const n=function(e,t,i,n,o,s){const a=t.videoSend.find((t=>t.ssrc===e));if(!a)return;const r={},c=a.sentFrame,d=a.inputFrame;if(n&&(Ha(r,La.Video_Send_Qp_Sum,a.qpSumPerFrame),a.codec&&Ha(r,La.Video_Send_Codec,Wa(a.codec)),"number"==typeof a.powerEfficientEncoder&&Ha(r,La.Video_Send_Power_Efficient_Encoder,a.powerEfficientEncoder),d&&c)){const e=d.frameRate,t=c.frameRate;r[La.Video_Send_Freeze]=function(e,t){let i=!0;return i=!(e<=5)&&(e<=10?t<3:e<=20?t<4:t<5),i}(e,t)?1:0}if(o){switch(c&&(Ha(r,ka.Video_Send_Height,c.height),Ha(r,ka.Video_Send_Width,c.width),Ha(r,ka.Video_Send_Frame_Rate,c.frameRate)),r[ka.Video_Send_Disabled]=i._originMediaStreamTrack&&!i._originMediaStreamTrack.enabled||i._mediaStreamTrack&&!i._mediaStreamTrack.enabled?1:0,a.adaptionChangeReason){case"none":r[ka.Video_Send_Adaptation]=0;break;case"cpu":r[ka.Video_Send_Adaptation]=1;break;case"bandwidth":r[ka.Video_Send_Adaptation]=2;break;case"other":r[ka.Video_Send_Adaptation]=3}let n=0;a.adaptionChangeReason&&(n+=Ya(a.adaptionChangeReason)),t.qualityLimitationReason&&(n+=Ya(t.qualityLimitationReason)<<3),r[ka.Video_Send_Adaptation]=n,r[ka.Video_Send_Player_Status]=R[i._player?i._player.videoElementStatus:"uninit"],Ha(r,ka.Video_Send_Nacks,a.nacksCount),Ha(r,ka.Video_Send_Plis,a.plisCount),Ha(r,ka.Video_Send_Firs,a.firsCount),Ha(r,ka.Video_Send_Avg_Encode,a.avgEncodeMs),Ha(r,ka.Video_Send_Huge_Frame_Sent,a.hugeFramesSent),Ha(r,ka.Video_Send_Bytes_Retransmit,a.retransmittedBytesSent),Ha(r,ka.Video_Send_Packages_Retransmit,a.retransmittedPacketsSent),Ha(r,ka.Video_Send_Key_Frames_Encoded,a.keyFramesEncoded);const s=o.videoSend.find((t=>t.ssrc===e));if(s){let e=Fa*ja;s.timestamp&&a.timestamp&&(e=a.timestamp-s.timestamp),null!=s.packets&&null!=a.packets&&Ha(r,ka.Video_Send_Package_Rate,1e3*(a.packets-s.packets)/e),null!=a.packetsLost&&null!=s.packetsLost&&Ha(r,ka.Video_Send_Package_Lost,a.packetsLost-s.packetsLost),null!=s.bytes&&null!=a.bytes&&Ha(r,ka.Video_Send_Bitrate,8*(a.bytes-s.bytes)/e)}}return r}(_[0].ssrcId,e,u,t,i),a="CameraVideoTrack"===u.__className__?3:u._hints.includes(s.SCREEN_TRACK)?7:10;(this.lastExtendStats.sendType!==a||o)&&(this.needUploadStats={sendType:a},this.lastExtendStats.sendType=a);const r=u&&function(e,t,i,n){const o=t.videoSend.find((t=>t.ssrc===e));if(!o)return null;const s={};if(n){const e=o.inputFrame,t=e&&e.height||i.videoHeight||0,n=e&&e.width||i.videoWidth||0,a=e&&e.frameRate||0;Ha(s,ka.Video_Capture_Height,t),Ha(s,ka.Video_Capture_Width,n),Ha(s,ka.Video_Capture_Frame_Rate,a)}return s}(_[0].ssrcId,e,u,!!i),d=function(e,t){const i={};return t&&(Ha(i,ka.Video_Send_Retransmit,e.bitrate.retransmit),Ha(i,ka.Video_Send_Target_Encoded,e.bitrate.targetEncoded),Ha(i,ka.Video_Send_Actual_Encoded,e.bitrate.actualEncoded),Ha(i,ka.Video_Send_Transmit,e.bitrate.transmit),Ha(i,ka.Video_Send_Bandwidth,e.sendBandwidth)),i}(e,!!i);c=Object.assign({},n,r,d)}else d=function(e,t,i,n,o){const s=t.videoSend.find((t=>t.ssrc===e));if(!s)return;const a={};if(n){const t=s.sentFrame;t&&(Ha(a,ka.Video_Send_Low_Height,t.height),Ha(a,ka.Video_Send_Low_Width,t.width),Ha(a,ka.Video_Send_Low_Frame_Rate,t.frameRate));const i=n.videoSend.find((t=>t.ssrc===e));if(i){let e=Fa*Ba;i.timestamp&&s.timestamp&&(e=s.timestamp-i.timestamp),null!=i.packets&&null!=s.packets&&Ha(a,ka.Video_Send_Low_Package_Rate,1e3*(s.packets-i.packets)/e),null!=s.packetsLost&&null!=i.packetsLost&&Ha(a,ka.Video_Send_Low_Package_Lost,s.packetsLost-i.packetsLost),null!=i.bytes&&null!=s.bytes&&Ha(a,ka.Video_Send_Low_Bitrate,8*(s.bytes-i.bytes)/e)}}return a}(_[0].ssrcId,e,0,i);break;case Tn.LocalAudioTrack:r=u&&function(e,t,i,n,o,s){const a=t.audioSend.find((t=>t.ssrc===e));if(!a)return;const r={};if(o){r[ka.Audio_Send_Disabled]=i._originMediaStreamTrack&&!i._originMediaStreamTrack.enabled||i._mediaStreamTrack&&!i._mediaStreamTrack.enabled?1:0;const t=100*i._source.getAccurateVolumeLevel(),n=a.inputLevel;if(null!=n){const e=Math.ceil(50*Math.log10(100*n+1));Ha(r,ka.Audio_Send_Level,e)}Ha(r,ka.Audio_Capture_PCM_Level,t),Ha(r,ka.Audio_Send_AEC_Return_Loss,a.aecReturnLoss),Ha(r,ka.Audio_Send_AEC_Return_Loss_Enhancement,a.aecReturnLossEnhancement),Ha(r,ka.Audio_Send_Bytes_Retransmit,a.retransmittedBytesSent),Ha(r,ka.Audio_Send_Packages_Retransmit,a.retransmittedPacketsSent),r[ka.Audio_Send_Freeze]=0;const s=o.audioSend.find((t=>t.ssrc===e));if(s){let e=Fa*Ba;s.timestamp&&a.timestamp&&(e=a.timestamp-s.timestamp),null!=s.bytes&&null!=a.bytes&&Ha(r,ka.Audio_Send_Bitrate,8*(a.bytes-s.bytes)/e),null!=s.packets&&null!=a.packets&&Ha(r,ka.Audio_Send_Package_Rate,1e3*(a.packets-s.packets)/e)}}return r}(_[0].ssrcId,e,u,0,i)}})),{high:c,low:d,audio:r}}getInboundStats(e,t,i,n){if(!this.requestRemoteMedia)return;const s=this.requestRemoteMedia()||[],a=[];return s.forEach((s=>{let r=Mi(s,2),c=r[0],d=r[1];const l={peer:c.uid};let h;if(d.has(Sn.VIDEO)&&c.videoTrack){const s=c._videoSSRC&&this.requestVideoIsReady&&this.requestVideoIsReady(c._videoSSRC)||!1,a=c.videoTrack?function(e,t,i,n,s,a,r,c){const d=t.videoRecv.find((t=>t.ssrc===e));if(!d)return;const l={},h=d.receivedFrame,u=d.outputFrame,_=d.decodeFrameRate;Ha(l,Ma.Video_Render_Frame_Rate_Decode,_),d.framesRateFirefox&&Ha(l,Ma.Video_Recv_Frame_Rate,d.framesRateFirefox),h&&Ha(l,Ma.Video_Recv_Frame_Rate,h.frameRate),Ha(l,Ma.Video_Recv_Frame_Dropped,d.framesDroppedCount),Ha(l,Ma.Video_Recv_Bytes_Retransmit,d.retransmittedBytesReceived),Ha(l,Ma.Video_Recv_Packages_Retransmit,d.retransmittedPacketsReceived),Ha(l,Ma.Video_Recv_Packages_Discarded,d.packetsDiscarded),Ha(l,Ma.Video_Recv_Avg_Decode,d.avgDecodeMs),Ha(l,Ma.Video_Recv_Avg_Processing_Delay,d.avgProcessingDelayMs),Ha(l,Ma.Video_Recv_Avg_Assembly_Time,d.avgFramesAssembledFromMultiplePacketsMs),Ha(l,Ma.Video_Recv_Avg_Inter_Frame_Delay,d.avgInterFrameDelayMs),Ha(l,Ma.Video_Recv_Key_Frames_Decoded,d.keyFramesDecoded);const p=c&&c.videoRecv.find((t=>t.ssrc===e));if(p){const e=t.timestamp-c.timestamp||Fa;null!=d.packetsLost&&null!=p.packetsLost&&Ha(l,Ma.Video_Recv_Package_Lost,d.packetsLost-p.packetsLost),null!=p.bytes&&null!=d.bytes&&Ha(l,Ma.Video_Recv_Bitrate,8*(d.bytes-p.bytes)/e),null!=p.packets&&null!=d.packets&&Ha(l,Ma.Video_Recv_Package_Rate,1e3*(d.packets-p.packets)/e)}const E=a&&a.videoRecv.find((t=>t.ssrc===e));if(E&&(Ha(l,La.Video_Recv_Qp_Sum,d.qpSumPerFrame),d.codec&&Ha(l,La.Video_Recv_Codec,Wa(d.codec)),"number"==typeof d.powerEfficientDecoder&&Ha(l,La.Video_Recv_Power_Efficient_Decoder,d.powerEfficientDecoder),l[La.Video_Recv_Freeze]=n&&qs.isRemoteVideoFreeze(i,d,E)?1:0),r){var m;const t=r.videoRecv.find((t=>t.ssrc===e));h?(Ha(l,ka.Video_Recv_Height,h.height),Ha(l,ka.Video_Recv_Width,h.width)):i&&(Ha(l,ka.Video_Recv_Height,i._videoHeight||0),Ha(l,ka.Video_Recv_Width,i._videoWidth||0)),u&&Ha(l,ka.Video_Recv_Frame_Rate_Output,u.frameRate);const n=null===(m=i._player)||void 0===m?void 0:m.rendFrameRate.toFixed(0);if(n&&Ha(l,ka.Video_Render_Frame_Rate_Render,+n),Ha(l,ka.Video_Recv_Jitter_Buffer,d.jitterBufferMs),Ha(l,ka.Video_Recv_Current_Delay,d.currentDelayMs),Ha(l,ka.Video_Recv_Firs,d.firsCount),Ha(l,ka.Video_Recv_Nacks,d.nacksCount),Ha(l,ka.Video_Recv_Plis,d.plisCount),i){l[ka.Video_Recv_Disabled]=i._originMediaStreamTrack.enabled&&i._mediaStreamTrack.enabled?0:1;const e=i._player;if(e){const i=e.freezeTimeCounterList,n=e.renderFreezeAccTime,a=e.renderFreezeAccTime2,r=e.videoElementStatus;if(i&&i.length>0&&Ha(l,La.Video_Render_Freeze_Time,i.splice(0,1)[0]),s&&"visible"===T.visibility&&r===g.PLAYING&&o().supportRequestVideoFrameCallback){const t=Math.min(6e3,a);e.renderFreezeAccTime2=Math.max(0,a-t),Ha(l,La.Video_Render_Freeze_Time_Render2,t);const i=Math.min(6e3,n);e.renderFreezeAccTime=Math.max(0,n-i),Ha(l,La.Video_Render_Freeze_Time_Render,ce("USE_NEW_RENDER_FREEZE_TIME")?t:i)}if("number"==typeof d.totalFreezesDuration){const e=t&&t.totalFreezesDuration?d.totalFreezesDuration-t.totalFreezesDuration:d.totalFreezesDuration;Ha(l,ka.Video_Render_Freeze_Duration,1e3*e)}}}if(l[ka.Video_Recv_Player_Status]=R[i._player?i._player.videoElementStatus:"uninit"],t&&void 0!==d.totalInterFrameDelay&&void 0!==d.totalSquaredInterFrameDelay&&void 0!==t.totalInterFrameDelay&&void 0!==t.totalSquaredInterFrameDelay){const e=d.totalInterFrameDelay-t.totalInterFrameDelay,i=d.totalSquaredInterFrameDelay-t.totalSquaredInterFrameDelay,n=d.framesDecodeCount-t.framesDecodeCount,o=e/n*1e3,s=Math.round(1e3*Math.sqrt((i-Math.pow(e,2)/n)/n));!isNaN(s)&&o+s>Math.max(3*o,o+150)&&(l[ka.Video_Recv_I_Frame_Delay]=s)}}return l}(c._videoSSRC,e,c.videoTrack,!0===s,this.needUploadRenderFreezeTime,t,i,n):void 0;if(a&&(l.video=a),c.videoTrack){const t=e.videoRecv.find((e=>e.ssrc===c._videoSSRC));t&&t.estimatedPlayoutTimestamp&&(h=t.estimatedPlayoutTimestamp)}}if(d.has(Sn.AUDIO)&&c.audioTrack){const o=!c.hasAudio,s=c.audioTrack?function(e,t,i,n,o,s){let a=arguments.length>6&&void 0!==arguments[6]&&arguments[6];const r=t.audioRecv.find((t=>t.ssrc===e));if(!r)return;const c={};Ha(c,Ma.Audio_Recv_Jitter,r.jitterMs),Ha(c,Ma.Audio_Recv_Bytes_Retransmit,r.retransmittedBytesReceived),Ha(c,Ma.Audio_Recv_Packages_Retransmit,r.retransmittedPacketsReceived),Ha(c,Ma.Audio_Recv_Packages_Discarded,r.packetsDiscarded),Ha(c,Ma.Audio_Recv_Avg_Processing_Delay,r.avgProcessingDelayMs);const d=s&&s.audioRecv.find((t=>t.ssrc===e));if(d){const e=Fa;null!=r.packets&&null!=d.packets&&Ha(c,Ma.Audio_Recv_Package_Rate,1e3*(r.packets-d.packets)/e),null!=r.packetsLost&&null!=d.packetsLost&&Ha(c,Ma.Audio_Recv_Package_Lost,r.packetsLost-d.packetsLost)}if(n){const e=r.receivedFrames,t=r.droppedFrames;null!=e&&null!=t&&(c[La.Audio_Recv_Freeze]=0===(l=e)||100*t/l>20?1:0)}var l;if(o){const t=100*i._source.getAccurateVolumeLevel(),n=r.outputLevel;if(null!=n){const e=Math.ceil(50*Math.log10(100*n+1));Ha(c,ka.Audio_Render_Level,e)}Ha(c,ka.Audio_Recv_PCM_Level,t),i&&(c[ka.Audio_Recv_Disabled]=i._originMediaStreamTrack.enabled&&i._mediaStreamTrack.enabled?0:1),Ha(c,ka.Audio_Recv_Jitter_Buffer,r.jitterBufferMs),Ha(c,ka.Audio_Recv_Current_Delay,r.jitterBufferMs),c[ka.Audio_Recv_Player_Status]=R[S.getPlayerState(i.getTrackId())];const s=o.audioRecv.find((t=>t.ssrc===e));if(s&&(null!=s.bytes&&null!=r.bytes&&Ha(c,ka.Audio_Recv_Bitrate,8*(r.bytes-s.bytes)/(Fa*ja)),!a)){const e=r.concealedSamples-s.concealedSamples;e>0&&Ha(c,ka.Audio_Recv_Concealed_Samples,e);const t=r.totalSamplesReceived-s.totalSamplesReceived;t>0&&Ha(c,ka.Audio_Recv_Total_Samples_Received,t);const i=r.freezeSamples80-s.freezeSamples80;i>0&&Ha(c,ka.Audio_Render_Freeze_Samples_80ms,i);const n=r.freezeSamples200-s.freezeSamples200;n>0&&Ha(c,ka.Audio_Render_Freeze_Samples_200ms,n);const o=r.freezeMs80-s.freezeMs80;Ha(c,ka.Audio_Render_Freeze_Time_80ms,o<0?0:o);const a=r.freezeMs200-s.freezeMs200;Ha(c,ka.Audio_Render_Freeze_Time_200ms,a<0?0:a)}}return c}(c._audioSSRC,e,c.audioTrack,t,i,n,o):void 0;if(s&&(l.audio=s),c.audioTrack&&h){const t=e.audioRecv.find((e=>e.ssrc===c._audioSSRC));if(t&&t.estimatedPlayoutTimestamp){const e=t.estimatedPlayoutTimestamp-h;l.audio?l.audio[Ma.Audio_Recv_AV_Sync_TIME]=e:l.audio={[Ma.Audio_Recv_AV_Sync_TIME]:e}}}}(l.video||l.audio)&&a.push(l)})),this.needUploadRenderFreezeTime=!this.needUploadRenderFreezeTime,a}startUploadTransportStats(){this.uploadTransportStarted=!0,this.uploadWRTCStatsTimer||this.startUploadWRTCStats()}stopUploadTransportStats(){this.uploadTransportStarted=!1}startUploadOutboundStats(){this.uploadOutboundStarted||(this.uploadOutboundStarted=!0,this.uploadWRTCStatsTimer||this.startUploadWRTCStats(),this.uploadOutboundDenoiserStatsTimer&&window.clearInterval(this.uploadOutboundDenoiserStatsTimer),this.uploadOutboundDenoiserStatsTimer=window.setInterval((()=>{if(!this.requestAllTracks||!this.requestUpload)return;const e=(this.requestAllTracks()||[]).find((e=>e instanceof i));if(e&&e._external.getDenoiserStats){const t=e._external.getDenoiserStats();t&&this.requestUpload(Yi.DENOISER_STATS,t)}}),2e3),this.uploadExtStatsTimer&&window.clearInterval(this.uploadExtStatsTimer),this.uploadExtStatsTimer=window.setInterval((()=>{if(!this.requestAllTracks||!this.requestUpload)return;this.requestAllTracks().forEach((e=>{e.getProcessorStats().forEach((e=>{this.requestUpload&&this.requestUpload(e.type,e.stats)}))}))}),2e3))}stopUploadOutboundStats(){this.uploadOutboundStarted&&(this.uploadOutboundStarted=!1,this.lastSendStats&&(this.lastSendStats.videoSend=[],this.lastSendStats.audioSend=[],this.lastSendStats=void 0),this.lastRefSendStats&&(this.lastRefSendStats.videoSend=[],this.lastRefSendStats.audioSend=[],this.lastRefSendStats=void 0),this.lastNormalSendStats&&(this.lastNormalSendStats.videoSend=[],this.lastNormalSendStats.audioSend=[],this.lastNormalSendStats=void 0),this.lastExtendStats={},this.needUploadStats={},this.uploadOutboundDenoiserStatsTimer&&window.clearInterval(this.uploadOutboundDenoiserStatsTimer),this.uploadOutboundDenoiserStatsTimer=void 0,this.uploadExtStatsTimer&&window.clearInterval(this.uploadExtStatsTimer),this.uploadExtStatsTimer=void 0)}startUploadInboundStats(){this.uploadInboundStarted||(this.uploadInboundStarted=!0,this.uploadWRTCStatsTimer||this.startUploadWRTCStats(),this.uploadInboundExtStatsTimer&&window.clearInterval(this.uploadInboundExtStatsTimer),this.uploadInboundExtStatsTimer=window.setInterval((()=>{if(!this.requestUpload||!this.requestRemoteMedia)return;(this.requestRemoteMedia()||[]).forEach((e=>{let t=Mi(e,2),i=t[0],n=t[1];if(n.has(Sn.VIDEO)&&i.videoTrack){i.videoTrack.getProcessorStats().forEach((e=>{this.requestUpload&&this.requestUpload(e.type,e.stats)}))}if(n.has(Sn.AUDIO)&&i.audioTrack){i.audioTrack.getProcessorStats().forEach((e=>{this.requestUpload&&this.requestUpload(e.type,e.stats)}))}}))}),2e3))}stopUploadInboundStats(){this.uploadInboundStarted&&(this.uploadInboundStarted=!1,this.lastRecvStats&&(this.lastRecvStats.videoRecv=[],this.lastRecvStats.audioRecv=[],this.lastRecvStats=void 0),this.lastRefRecvStats&&(this.lastRefRecvStats.videoRecv=[],this.lastRefRecvStats.audioRecv=[],this.lastRefRecvStats=void 0),this.lastNormalRecvStats&&(this.lastNormalRecvStats.videoRecv=[],this.lastNormalRecvStats.audioRecv=[],this.lastNormalRecvStats=void 0),this.lastUploadCompensateTime=-1,this.uploadCompensateDeltaTime=0,this.needUploadRenderFreezeTime=!0,this.uploadInboundExtStatsTimer&&window.clearInterval(this.uploadInboundExtStatsTimer),this.uploadInboundExtStatsTimer=void 0)}startUploadExtensionUsageStats(){if(this.uploadExtensionUsageStarted)return;this.uploadExtensionUsageStarted=!0,this.uploadExtUsageStatsTimer&&window.clearInterval(this.uploadExtUsageStatsTimer);const e=new Map;this.uploadExtUsageStatsTimer=window.setInterval((async()=>{const t=Date.now(),i={connectionInterval:ce("EXTENSION_USAGE_UPLOAD_INTERVAL")/1e3,details:[],lts:t};let n=[];const o=this.requestAllTracks&&this.requestAllTracks()||[];for(const e of o)!e.muted&&e.enabled&&(n=n.concat(await e.getProcessorUsage()));const s=this.requestRemoteMedia&&this.requestRemoteMedia()||[];for(const e of s){var a=Mi(e,2);const t=a[0],i=a[1];i.has(Sn.VIDEO)&&t.videoTrack&&(n=n.concat(await t.videoTrack.getProcessorUsage())),i.has(Sn.AUDIO)&&t.audioTrack&&(n=n.concat(await t.audioTrack.getProcessorUsage()))}if(0===n.length)return;i.details=function(e,t){const i={};for(const a of e){var n;const e=a.id,r=a.value,c=a.level,d=a.direction,l=null!==(n=t.get(e))&&void 0!==n?n:0,h=2===r?l+ce("EXTENSION_USAGE_UPLOAD_INTERVAL")/1e3:l;var o,s;t.set(e,h),i[e]?(2===r&&(i[e].value=r),c>i[e].level&&(i[e].level=c),"remote"===d&&(i[e].remoteUidCount+=1),i[e].totalTs=null!==(o=t.get(e))&&void 0!==o?o:0):i[e]={value:r,level:c,remoteUidCount:"local"===d?0:1,totalTs:null!==(s=t.get(e))&&void 0!==s?s:0}}return Object.keys(i).map((e=>{const t=i[e];return{id:e,level:t.level,value:t.value,totalTs:t.totalTs}}))}(n,e);const r=Date.now(),c=r>t?r:t+1;this.requestUpload&&this.requestUpload(Yi.EXTENSION_USAGE_STATS,{usageStats:i,sendTs:c})}),ce("EXTENSION_USAGE_UPLOAD_INTERVAL"))}stopUploadExtensionUsageStats(){this.uploadExtensionUsageStarted&&(this.uploadExtensionUsageStarted=!1,this.uploadExtUsageStatsTimer&&window.clearInterval(this.uploadExtUsageStatsTimer),this.uploadExtUsageStatsTimer=void 0)}stopUploadBaseStats(){this.uploadBaseStatsStarted=!1,T.stopCollectStats()}}const Ja=ce("ICE_RESTART_INTERVAL");let Xa=new Map,Qa=new Map,za=[fn.UDP_TCP_RELAY,fn.TCP_RELAY,fn.RELAY],Za=ce("JOIN_WITH_FALLBACK_MEDIA_PROXY_FORCE")&&o().supportPCSetConfiguration;function $a(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const i=Xa.get(e.id);i&&(window.clearTimeout(i),Xa.delete(e.id));const n=Qa.get(e.id);t&&n&&n.index===za.length-1&&(B.debug("[".concat(e.id,"] reset ICE restart policy")),Qa.delete(e.id))}function er(e,t,i){if(0===Xa.size&&0===Qa.size&&(Array.isArray(ce("RESTART_SEQUENCE"))&&ce("RESTART_SEQUENCE").length>0&&!pt(za,ce("RESTART_SEQUENCE"))&&(za=ce("RESTART_SEQUENCE").filter((e=>{if(Object.values(fn).includes(e))return!0})),B.debug("use reconnection policy from config distribution, queues: ".concat(za.join(" => ")))),Za=ce("JOIN_WITH_FALLBACK_MEDIA_PROXY_FORCE")&&o().supportPCSetConfiguration),0===za.length)return void i();let n,s=Qa.get(e.id)||{},a=s.index,r=void 0===a?0:a,c=s.type;if(Za&&c===fn.RELAY)return void i();let d=c&&r>=za.length-1;if(Za)c=fn.RELAY;else{if(d)return void i();c?(r++,c=za[r]):(c=za[0],r=0)}B.debug("[".concat(e.id,"] choose ICE restart policy: ").concat(c,", index: ").concat(r)),t(c),Qa.set(e.id,{index:r,type:c}),n=window.setTimeout((()=>er(e,t,i)),Ja),Xa.set(e.id,n)}var tr;let ir=(yi((tr=class extends re{get state(){return this._state}set state(e){const t=this._state;this._state=e,this.emit(In.StateChange,t,this._state)}constructor(e,t){super(),this.isPlanB=void 0,this.store=void 0,this.statsUploader=void 0,this.connection=void 0,this.localTrackMap=new Map,this.remoteUserMap=new Map,this.localDataChannels=[],this.remoteDataChannelMap=new Map,this.pendingLocalTracks=[],this.pendingRemoteTracks=[],this.pendingLocalDataChannels=[],this.pendingRemoteDataChannels=[],this.statsCollector=void 0,this.shouldForwardP2PCreation=void 0,this.iceFailedCount=0,this.dtlsFailedCount=0,this.mutex=void 0,this._state=gn.Disconnected,this._p2pBySDPEndPoint=!1,this._pcStatsUploadType=ce("NEW_ICE_RESTART")?Cn.FIRST_CONNECTION:Cn.OLD_FIRST_CONNECTION,this._isStartRestartIce=!1,this._restartTimer=void 0,this._isTryConnecting=!1,this._iceError=null,this._forceTurn=!1,this._isWaitPcToRePub=!1,this.handleMuteLocalTrack=async(e,t,i)=>{const n=await this.mutex.lock("Locking from P2PChannel.handleMuteLocalTrack");try{if(!this.connection||this.state!==gn.Connected)return void i(new me(ne.INVALID_OPERATION,"Cannot call P2PChannel.handleMuteLocalTrack before connection established."));const o=this.filterTobeMutedTracks(e);if(0===o.length)return void t();const s=o.find((e=>"videoLowTrack"===e[0]));if(s){const e=s[1];this.store.enableInstantMuteRestore?(e.track._originMediaStreamTrack.enabled=!1,B.info("[".concat(this.store.clientId,"] P2PChannel muteLocalLowTrack without close sender because enableInstantMuteRestore is true"))):e.track._originMediaStreamTrack.stop()}this.store.enableInstantMuteRestore?B.info("[".concat(this.store.clientId,"] P2PChannel muteLocalTrack without close sender because enableInstantMuteRestore is true")):await this.connection.muteLocal(o.map((e=>Mi(e,2)[1].id)));const a=this.createMuteMessage(o);await Et(this,In.RequestMuteLocal,a),t()}catch(e){i(e)}finally{n()}},this.handleUnmuteLocalTrack=async(e,t,i)=>{const n=await this.mutex.lock("Locking from P2PChannel.handleUnmuteLocalTrack");try{if(!this.connection||this.state!==gn.Connected)return void i(new me(ne.INVALID_OPERATION,"Cannot call P2PChannel.handleUnmuteLocalTrack before connection established."));const s=this.filterTobeUnmutedTracks(e);if(0===s.length)return void t();const a=s.find((e=>"videoLowTrack"===e[0]));if(a){const t=a[1];if(this.store.enableInstantMuteRestore)t.track._originMediaStreamTrack.enabled=!0,B.info("[".concat(this.store.clientId,"] P2PChannel unmuteLocalLowTrack without close sender because enableInstantMuteRestore is true"));else{if(t.track._originMediaStreamTrack.stop(),!ce("DISABLE_DUAL_STREAM_USE_ENCODING")&&o().supportDualStreamEncoding){const i=e._mediaStreamTrack.clone();t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i}else{const i=Da(e,Ae(this,In.RequestLowStreamParameter));t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i}await new Promise(((e,i)=>{this.handleReplaceTrack(t.track,e,i,!0)}))}}this.store.enableInstantMuteRestore?B.info("[".concat(this.store.clientId,"] P2PChannel unmuteLocalTrack without close sender because enableInstantMuteRestore is true")):await this.connection.unmuteLocal(s.map((e=>Mi(e,2)[1].id)));const r=this.createUnmuteMessage(s);await Et(this,In.RequestUnmuteLocal,r),t()}catch(e){i(e)}finally{n()}},this.handleUpdateVideoEncoder=async(e,t,i,n)=>{let o;n||(o=await this.mutex.lock("Locking from P2PChannel.handleUpdateVideoEncoder"));try{const i=this.localTrackMap.get(Tn.LocalVideoTrack);if(!this.connection||!i||i.track!==e||this.state!==gn.Connected)return void t();const n=i.id,a=i.track;await this.connection.updateSendParameters(n,a),await this.connection.updateEncoderConfig(n,a),this.emit(In.UpdateVideoEncoder,a),t()}catch(e){i(e)}finally{var s;null===(s=o)||void 0===s||s()}},this.handleUpdateVideoSendParameters=async(e,t,i)=>{const n=await this.mutex.lock("Locking from P2PChannel.handleUpdateVideoSendParameters");try{const i=this.localTrackMap.get(Tn.LocalVideoTrack);if(!this.connection||!i||i.track!==e||this.state!==gn.Connected)return void t();const o=i.id,s=i.track;await this.connection.updateSendParameters(o,s),t()}catch(e){i(e)}finally{n()}},this.handleReplaceMixingTrack=async(e,t,i,n)=>{if(!this.connection||this.state!==gn.Connected)return void t();const o=Ia([e]);let s;B.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection will replace audioTrack [").concat(o.getTrackId(),"]")),"boolean"==typeof n&&n||(s=await this.mutex.lock("From P2PChannel.handleReplaceMixingTrack"));try{await this.replaceTrack(e,o),t()}catch(e){i(e)}finally{var a;null===(a=s)||void 0===a||a()}},this.handleReplaceTrack=async(e,t,i,n)=>{let s;B.debug("[".concat(this.store.clientId,"] P2PChannel handleReplaceTrack for [track-id-").concat(e.getTrackId(),"]")),"boolean"==typeof n&&n||(s=await this.mutex.lock("From P2PChannel.handleReplaceTrack"));try{var a;const i=Array.from(this.localTrackMap.entries()).find((t=>{let i=Mi(t,2)[1].track;return e===i}));if(!this.connection||!i||this.state!==gn.Connected)return void t();if(await(null===(a=this.connection)||void 0===a?void 0:a.replaceTrack(e,i[1].id)),this.isPlanB){const t=i[1];t.id=e._mediaStreamTrack.id,this.localTrackMap.set(i[0],t)}if(i[0]===Tn.LocalVideoTrack&&!ce("DISABLE_DUAL_STREAM_USE_ENCODING")&&o().supportDualStreamEncoding){const t=this.localTrackMap.get(Tn.LocalVideoLowTrack);if(t){const i=e._mediaStreamTrack.clone();t.track._originMediaStreamTrack.stop(),t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i,await new Promise(((e,i)=>{this.handleReplaceTrack(t.track,e,i,!0)}))}}t()}catch(e){i(e)}finally{var r;null===(r=s)||void 0===r||r()}},this.handleGetRTCStats=e=>{e(this.statsCollector.getRTCStats())},this.handleGetLocalVideoStats=e=>{e(this.statsCollector.getLocalVideoTrackStats())},this.handleGetLocalAudioStats=e=>{e(this.statsCollector.getLocalAudioTrackStats())},this.handleGetRemoteVideoStats=e=>this.statsCollector.getRemoteVideoTrackStats(e.uid)[e.uid],this.handleGetRemoteAudioStats=e=>this.statsCollector.getRemoteAudioTrackStats(e.uid)[e.uid],this.store=e,this.statsCollector=t,this.statsCollector.addP2PChannel(this),this.statsUploader=new qa(this.store),this.bindStatsUploaderEvents(),this.mutex=new ue("P2PChannel-mutex",this.store.clientId),this.isPlanB=!o().supportUnifiedPlan||ce("CHROME_FORCE_PLAN_B")&&ct(),this.shouldForwardP2PCreation=ce("FORWARD_P2P_CREATION")&&o().supportPCSetConfiguration&&mt(),this.shouldForwardP2PCreation&&this.recreateConnection()}async startP2PConnection(e,t){var i;this.state=gn.New,this._forceTurn=Na(e),B.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] forceTurn: ").concat(this._forceTurn));const n=this.shouldForwardP2PCreation&&"closed"===(null===(i=this.connection)||void 0===i?void 0:i.peerConnectionState);if((!this.shouldForwardP2PCreation||n||t)&&((n||t)&&this.connection&&(B.warning("[".concat(this.store.clientId,"] P2PChannel.startP2PConnection ForwardP2P closed.")),this.resetConnection(this.connection)),this.recreateConnection(e)),!this.connection)throw new me(ne.UNEXPECTED_ERROR,"Cannot P2PChannel.startConnection before P2PConnection initialization .");return this._pcStatsUploadType=ce("NEW_ICE_RESTART")?Cn.FIRST_CONNECTION:Cn.OLD_FIRST_CONNECTION,this._isTryConnecting=!0,this._isStartRestartIce=!1,this._iceError=null,this.connection.setConfiguration(e),this.connection.establishPromise}updateConnectionConfiguration(e){var t;null===(t=this.connection)||void 0===t||t.setConfiguration(e),this._p2pBySDPEndPoint=!0}async connect(e){if(!this.connection)throw new me(ne.UNEXPECTED_ERROR,"Cannot P2PChannel.connect before P2PChannel.startP2PConnection .");if(!this.isPreallocation()||this.state!==gn.Connected){this.store.peerConnectionStart();const t=await this.connection.connect(e);return this.statsUploader.startUploadTransportStats(),this.statsUploader.startUploadExtensionUsageStats(),this.state=gn.Connected,t}if(this.connection instanceof ba||this.connection&&"name"in this.connection&&"DataChannelConnection"===this.connection.name){const t=this.connection.checkDtlsParameters(e.dtlsParameters.fingerprints),i=Wo(e.iceParameters.iceUfrag,e.iceParameters.icePwd);i||B.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] ice parameters mismatch, length: ").concat(e.iceParameters.iceUfrag.length," / ").concat(e.iceParameters.icePwd.length));const n=this.connection.checkIceParameters(e.iceParameters),o=t||!i||n&&!(this.connection instanceof ba);if(o||n){B.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] dtls parameters mismatch, ").concat(o?"try next":"restart ICE"));G.reportApiInvoke(this.store.sessionId,{name:t?Be.MISMATCH_DTLS_PARAMETERS:Be.MISMATCH_ICE_PARAMETERS,options:t?[e.dtlsParameters.fingerprints]:[e.iceParameters],tag:je.TRACER}).onSuccess(),setTimeout((()=>{o?this.emit(In.RequestReconnect):n&&this.emit(In.RequestRestartICE,fn.UDP_RELAY)}))}}await this.connection.updateRemoteConnect(e)}updateRemoteRTPCapabilities(e){const t=Array.from(this.localTrackMap.entries()).filter((e=>{let t=Mi(e,1)[0];return[Tn.LocalVideoLowTrack,Tn.LocalVideoTrack].includes(t)})),i=t.map((e=>Mi(e,2)[1].id)),n=t.map((e=>Mi(e,1)[0]));if(this.connection instanceof ba||this.connection&&"name"in this.connection&&"DataChannelConnection"===this.connection.name){if(G.updateRemoteRTPCapabilities(this.store.sessionId,{trackTypes:JSON.stringify(n),localCodecs:JSON.stringify(this.connection.localCodecs),remoteCodecs:JSON.stringify(e)}),!e.includes(this.store.codec)){const t=["vp9","vp8","h264"].find((t=>e.includes(t)));t&&(this.store.codec=t,B.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId," updateRemoteRTPCapabilities] default codec is not available, hence the fallback to ").concat(t,".")))}this.connection.updateRemoteRTPCapabilities(i,e)}}async getEstablishParams(){return this.connection&&"name"in this.connection&&"DataChannelConnection"===this.connection.name&&"closed"!==this.connection.peerConnectionState||this.connection instanceof ba&&"closed"!==this.connection.peerConnectionState&&[gn.New,gn.Connected].includes(this.state)?this.connection.establishPromise:void 0}async publishDataChannel(e){if(!this.connection||this.state!==gn.Connected){if(this.state===gn.Disconnected)throw new me(ne.UNEXPECTED_ERROR,"PeerConnection already disconnected.");return e.forEach((e=>{this.pendingLocalDataChannels.includes(e)||this.pendingLocalDataChannels.push(e)})),[]}const t=this.filterTobePublishedDataChannels(e);return 0===t.length?[]:(t.forEach((e=>{const t=Date.now();this.store.publish(e.id.toString(),"datachannel",t)})),await this.connection.createDataChannels(this.store.uid,t),t.forEach((e=>{this.localDataChannels.push(e);const t=Date.now();this.store.publish(e.id+"","datachannel",void 0,t)})),e.map((e=>({streamId:e.id,ordered:e.ordered,maxRetransmits:e.maxRetransmits,metadata:e.metadata,channelId:e._originDataChannelId}))))}publish(e,t,i){var n=this;return Ui((function*(){const o=yield Di(n.mutex.lock("From P2PChannel.publish"));try{const s=n.connection&&["disconnected","failed"].includes(n.connection.peerConnectionState);if(!n.connection||n.state!==gn.Connected||s){if(n.state===gn.Disconnected)throw new me(ne.UNEXPECTED_ERROR,"PeerConnection already disconnected.");n.throwIfTrackTypeNotMatch(e);const t=e.filter((e=>-1===n.pendingLocalTracks.indexOf(e)));return n.pendingLocalTracks=n.pendingLocalTracks.concat(t),void(s&&(n._isWaitPcToRePub=!0))}n.store.pubId=n.store.pubId+1,Ys.markPublishStart(n.store.clientId,n.store.pubId);const a=n.filterTobePublishedTracks(e,t,i);if(0===a.length)return void(yield Di(n.tryToUnmuteAudio(e)));yield*wi(bi(n.doPublish(n.connection,a)))}finally{o()}}))()}doPublish(e,t){var i=this;return Ui((function*(){t.forEach((e=>{let t=e.track,n=e.type;const o=Date.now();i.store.publish(t.getTrackId(),n===Tn.LocalAudioTrack?"audio":"video",o)})),i.bindLocalTrackEvents(t);const n=t.map((e=>e.track)),o=yield Di(e.send(n,i.store.codec,i.store.audioCodec)),s=(yield Di(o.next())).value,a=i.createGatewayPublishMessage(t,s);let r;try{r=yield a}catch(e){throw o.throw(e),(null==e?void 0:e.code)===ne.WS_ABORT&&t.forEach((e=>{let t=e.track;-1===i.pendingLocalTracks.indexOf(t)&&i.pendingLocalTracks.push(t)})),i.unbindLocalTrackEvents(t),e}const c=i.mapPubResToRemoteConfig(a,r,n),d=(yield Di(o.next(c))).value;if(i.state===gn.Disconnected)throw new me(ne.UNEXPECTED_ERROR,"PeerConnection already disconnected.");ce("ENABLE_VIDEO_SEI");const l=ce("ENABLE_ENCODED_TRANSFORM"),h=ce("ENABLE_AUDIO_METADATA");n.forEach((async e=>{const t=e.getRTCRtpTransceiver();if(!t||!l)return;const i=Go(),n=i.interceptLocalVideoFrame,o=i.interceptLocalAudioFrame;e.trackMediaType===Sn.VIDEO?await n(t.sender,e):e.trackMediaType===Sn.AUDIO&&await o(t.sender,{metadata:h?()=>{const t=e.metadata.shift();return t&&t.value}:void 0})})),t.forEach((e=>{let t=e.type;i.statsCollector.addLocalStats(t)})),i.assignLocalTracks(t,d),i.statsUploader.startUploadOutboundStats(),t.forEach((e=>{let t=e.track,n=e.type;const o=Date.now();i.store.publish(t.getTrackId(),n===Tn.LocalAudioTrack?"audio":"video",void 0,o)}))}))()}async updateVideoStreamParameter(e,t){const i=this.localTrackMap.get(t);if(!i||!this.connection)return;if(!(i.track instanceof n))return B.warn("[updateVideoStreamParameter]: track is not an instance of LocalVideoTrack");const s=i.track,a=function(e,t){const i={};return e.height&&e.width&&(i.scaleResolutionDownBy=io(e,t)),i.maxFramerate=e.framerate?zn(e.framerate):void 0,i.maxBitrate=e.bitrate?1e3*e.bitrate:void 0,i}(e,s);if(s._encoderConfig||(s._encoderConfig={}),t!==Tn.LocalVideoLowTrack||!ce("DISABLE_DUAL_STREAM_USE_ENCODING")&&o().supportDualStreamEncoding)null!=a.scaleResolutionDownBy&&(s._encoderConfig.scaleResolutionDownBy=a.scaleResolutionDownBy);else{const t=s._originMediaStreamTrack;if(!t.canvas)return B.warn("[".concat(s.getTrackId(),"] no canvas on track"));!function(e,t){const i=e.canvas;t.width&&(i.width=zn(t.width)),t.height&&(i.height=zn(t.height)),t.framerate&&(i.stopCapture&&i.stopCapture(),i.stopCapture=C((()=>{!i.startCapture&&i.stopCapture&&i.stopCapture(),i.startCapture&&i.startCapture()}),zn(t.framerate)))}(t,e)}null!=a.maxBitrate&&(s._encoderConfig.bitrateMax=a.maxBitrate/1e3),null!=a.maxFramerate&&(s._encoderConfig.frameRate&&"object"==typeof s._encoderConfig.frameRate?s._encoderConfig.frameRate.max=a.maxFramerate:s._encoderConfig.frameRate={max:a.maxFramerate}),B.debug("[".concat(s.getTrackId(),"] LowStreamEncoderConfig: , ").concat(JSON.stringify(s._encoderConfig))),await this.connection.updateRtpSenderEncodings(s)}publishLowStream(e){var t=this;return Ui((function*(){if(!t.connection||t.state!==gn.Connected)return;const i=yield Di(t.mutex.lock("Locking from P2PChannel.publishLowStream"));try{const o=t.localTrackMap.get(Tn.LocalVideoTrack);if(!o)throw new me(ne.UNEXPECTED_ERROR,"Could not find high stream");if(t.localTrackMap.has(Tn.LocalVideoLowTrack))throw new me(ne.UNEXPECTED_ERROR,"[".concat(t.store.clientId,"] Can't publish low stream when stream already publish"));const s=[{track:t.getLowVideoTrack(o.track,e),type:Tn.LocalVideoLowTrack}];if(yield*wi(bi(t.doPublish(t.connection,s))),o.track.muted||!o.track.enabled){var n;const e=null===(n=t.localTrackMap.get(Tn.LocalVideoLowTrack))||void 0===n?void 0:n.id;void 0!==e&&(yield Di(t.connection.muteLocal([e])))}}finally{i()}}))()}async republish(){this.pendingLocalTracks.length>0&&(B.debug("[".concat(this.store.clientId,"] Emit P2PChannelEvents.RequestRePublish to republish tracks.")),await Ce(this,In.RequestRePublish,this.pendingLocalTracks),this.emit(In.MediaReconnectEnd,this.store.uid),this.pendingLocalTracks=[]),this.pendingLocalDataChannels.length>0&&(B.debug("Emit P2PChannelEvents.RequestRePublishDataChannel to republish datachannels."),await Ce(this,In.RequestRePublishDataChannel,this.pendingLocalDataChannels),this.pendingLocalDataChannels=[]),this._isWaitPcToRePub=!1}async reSubscribe(e){for(let e=this.pendingRemoteTracks.length-1;e>=0;e--){const t=this.pendingRemoteTracks[e],i=t.user,n=t.kind;(n!==Sn.AUDIO||i._audio_added_&&i._audioSSRC)&&(n!==Sn.VIDEO||i._video_added_&&i._videoSSRC)||this.pendingRemoteTracks.splice(e,1)}if(e)await Ce(this,In.RequestReSubscribe,this.pendingRemoteTracks);else for(const e of this.pendingRemoteTracks){const t=e.user,i=e.kind;await this.subscribe(t,i,i===Sn.VIDEO?t._videoSSRC:t._audioSSRC)}this.pendingRemoteTracks.forEach((e=>{let t=e.user;this.emit(In.MediaReconnectEnd,t.uid)})),this.pendingRemoteTracks=[]}async unpublish(e){if(!this.connection||this.state!==gn.Connected)return void e.forEach((e=>{const t=this.pendingLocalTracks.indexOf(e);-1!==t&&this.pendingLocalTracks.splice(t,1)}));const t=this.filterTobeUnpublishedTracks(e);if(0===t.length)return;const i=t.find((e=>"videoLowTrack"===e[0]));if(i){i[1].track.close()}return this.doUnpublish(this.connection,t)}async unpublishDataChannel(e){if(!this.connection||this.state!==gn.Connected)return void e.forEach((e=>{const t=this.pendingLocalDataChannels.indexOf(e);-1!==t&&this.pendingLocalDataChannels.splice(t,1)}));const t=this.filterTobeUnpublishedDataChannels(e);return 0!==t.length?(t.forEach((e=>{const t=this.localDataChannels.indexOf(e);-1!==t&&this.localDataChannels.splice(t,1)})),0===this.localDataChannels.length&&await this.connection.stopDataChannels(this.store.uid),t.map((e=>e.id))):void 0}async unpublishLowStream(){if(!this.connection||this.state!==gn.Connected)return;const e=this.localTrackMap.get(Tn.LocalVideoLowTrack);if(!e)return;e.track.close();const t=[[Tn.LocalVideoLowTrack,e]];return this.doUnpublish(this.connection,t)}async doUnpublish(e,t){const i=this.createGatewayUnpublishMessage(t);return await e.stopSending(t.map((e=>Mi(e,2)[1].id))),this.withdrawLocalTracks(t),this.unbindLocalTrackEvents(t.map((e=>{let t=Mi(e,2);return{type:t[0],track:t[1].track}}))),t.forEach((e=>{let t=Mi(e,1)[0];this.statsCollector.removeLocalStats(t)})),0===this.localTrackMap.size&&this.statsUploader.stopUploadOutboundStats(),i}async subscribeDataChannel(e,t){if(!this.connection||this.state!==gn.Connected)throw new me(ne.INVALID_OPERATION,"Cannot subscribe remote user when peerConnection disconnected.");const i=t.filter((t=>{var i;return!(null!==(i=this.remoteDataChannelMap.get(e))&&void 0!==i&&i.get(t.id))}));if(0!==i.length)return await this.connection.createDataChannels(e.uid,i),i.forEach((t=>{var i;this.remoteDataChannelMap.has(e)?null===(i=this.remoteDataChannelMap.get(e))||void 0===i||i.set(t.id,t):this.remoteDataChannelMap.set(e,new Map([[t.id,t]]));const n=this.pendingRemoteDataChannels.findIndex((i=>{let n=i.user,o=i.id;return n.uid===e.uid&&o===t.id}));-1!==n&&this.pendingRemoteDataChannels.splice(n,1)})),i.map((e=>e.id))}async subscribe(e,t,i,n,o){var s;if(!this.connection||this.state!==gn.Connected)throw new me(ne.INVALID_OPERATION,"Cannot subscribe remote user when peerConnection disconnected.");if(null!==(s=this.remoteUserMap.get(e))&&void 0!==s&&s.has(t))return;let a,r,c,d,l;const h=this.connection.getPreMedia(i);if(h)B.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] preSSRCMap has ssrcId: ").concat(i,", no need to send sub to gateway.")),c=h.transceiver,a=h.track,r=h.mid,d=h.player,l=h.audioTrackId,h.firstVideoRender&&this.store.firstVideoFrameDecoded(e.uid,{firstPreRender:h.firstVideoRender});else if(o){const i=o.find((e=>e.stream_type===t));if(!i)throw new me(ne.UNEXPECTED_ERROR,"Cannot subscribe to remote ".concat(t," for user: ").concat(e.uid," because subscribe answer from gateway does not contain stream_type: ").concat(t,"."));const n=await this.connection.receive(t,i.ssrcs,String(e._uintid),i.attributes);(this.connection instanceof ba||"name"in this.connection&&"DataChannelConnection"===this.connection.name)&&(c=n.transceiver),a=n.track,r=n.id}else{const o=await this.connection.receive(t,[{ssrcId:i,rtx:n}],String(e._uintid),void 0);(this.connection instanceof ba||"name"in this.connection&&"DataChannelConnection"===this.connection.name)&&(c=o.transceiver),a=o.track,r=o.id}if(t===Sn.AUDIO?(e._audioTrack?e._audioTrack._updateOriginMediaStreamTrack(a):(e._audioTrack=new I(a,e.uid,e._uintid,this.store),B.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote audio track: ").concat(e._audioTrack.getTrackId()))),l&&(e._audioTrack._reusePreAudioElement(l,!0),h&&(h.audioTrackId=void 0)),c&&e._audioTrack._updateRtpTransceiver(c),this.bindRemoteTrackEvents(e,e._audioTrack)):(e._videoTrack?e._videoTrack._updateOriginMediaStreamTrack(a):(e._videoTrack=new v(a,e.uid,e._uintid,this.store,d),B.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote video track: ").concat(e._videoTrack.getTrackId())),e._videoTrack.once(A.PLAY_START,(()=>{this.store.firstVideoFrameDecoded(e.uid,{playStart:Date.now()})})),e._videoTrack.once(A.PLAY_END,(()=>{this.store.firstVideoFrameDecoded(e.uid,{playEnd:Date.now()}),this.reportVideoFirstFrameRender(e)})),d?e._videoTrack.once(A.FIRST_FRAME_RENDER,(()=>{this.store.firstVideoFrameDecoded(e.uid,{firstRender:Date.now()}),this.reportVideoFirstFrameRender(e)})):e._videoTrack.once(A.FIRST_FRAME_DECODED,(()=>{this.store.firstVideoFrameDecoded(e.uid,{firstRender:Date.now()}),this.reportVideoFirstFrameRender(e)}))),c&&e._videoTrack._updateRtpTransceiver(c),this.bindRemoteTrackEvents(e,e._videoTrack)),c&&ce("ENABLE_ENCODED_TRANSFORM")){const i=Go(),n=i.interceptRemoteVideoFrame,o=i.interceptRemoteAudioFrame;t==Sn.VIDEO?await n(c.receiver,{onSei:ce("ENABLE_VIDEO_SEI")&&(t=>{var i;return null===(i=e._videoTrack)||void 0===i?void 0:i._onSei(t)}),onFirstFrame:e=>{const t=Array.from(this.remoteUserMap.keys()).find((t=>t._videoSSRC===e.ssrc));t&&this.store.firstVideoFrameDecoded(t.uid,{firstReceivedEncodedFrame:Date.now(),frameType:e.type,rtpTimestamp:e.rtpTimestamp,framePayloadType:e.payloadType,frameDataLength:e.length,mimeType:e.mimeType})}}):t==Sn.AUDIO&&await o(c.receiver,{enableTopn:!!ce("ENABLE_AUDIO_TOPN"),enableMetadata:!!ce("ENABLE_AUDIO_METADATA"),enablePts:!!ce("ENABLE_AUDIO_PTS"),onMetadata:e=>{this.safeEmit(In.AudioMetadata,e)},onPts:e=>{this.safeEmit(In.AudioPts,e)}})}const u=this.remoteUserMap.get(e);u?u.set(t,r):this.remoteUserMap.set(e,new Map([[t,r]])),this.statsCollector.addRemoteStats(e.uid),this.statsUploader.startUploadInboundStats();const _=this.pendingRemoteTracks.findIndex((i=>{let n=i.user,o=i.kind;return n.uid===e.uid&&t===o}));-1!==_&&(this.pendingRemoteTracks.splice(_,1),this.emit(In.MediaReconnectEnd,e.uid))}async massSubscribe(e){return this.massSubscribeNoLock(e)}async massSubscribeNoLock(e){if(!this.connection||this.state!==gn.Connected)throw new me(ne.INVALID_OPERATION,"Cannot subscribeAll remote users when peerConnection disconnected.");e=e.filter((e=>{var t;let i=e.user,n=e.mediaType;return!(null!==(t=this.remoteUserMap.get(i))&&void 0!==t&&t.has(n))}));const t=[],i=new Map;e.forEach((e=>{if(!this.connection)return;const n=this.connection.getPreMedia(e.ssrcId);if(n){const t=n.track,o=n.mid,s=n.transceiver,a=n.player,r=n.audioTrackId;i.set(e.ssrcId,{track:t,id:o,transceiver:s,player:a,audioTrackId:r})}else t.push(e)}));const n=await this.connection.batchReceive(t.map((e=>{let t=e.user;return{kind:e.mediaType,ssrcMsg:[{ssrcId:e.ssrcId,rtx:e.rtxSsrcId}],mslabel:String(t._uintid)}})));t.forEach(((e,t)=>{i.set(e.ssrcId,n[t])}));for(const t of e){const e=t.user,n=t.mediaType,o=t.ssrcId,s=i.get(o);if(!s)return void B.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] cannot find ").concat(e.uid," subscribe data,").concat(n,", ").concat(o));const a=s.track,r=s.id,c=s.transceiver,d=s.player,l=s.audioTrackId;if(c&&ce("ENABLE_ENCODED_TRANSFORM")){const t=Go(),i=t.interceptRemoteVideoFrame,o=t.interceptRemoteAudioFrame;n==Sn.VIDEO?await i(c.receiver,{onSei:ce("ENABLE_VIDEO_SEI")&&(t=>{var i;return null===(i=e._videoTrack)||void 0===i?void 0:i._onSei(t)}),onFirstFrame:e=>{const t=Array.from(this.remoteUserMap.keys()).find((t=>t._videoSSRC===e.ssrc));t&&this.store.firstVideoFrameDecoded(t.uid,{firstReceivedEncodedFrame:Date.now(),frameType:e.type,rtpTimestamp:e.rtpTimestamp,framePayloadType:e.payloadType,frameDataLength:e.length,mimeType:e.mimeType})}}):n==Sn.AUDIO&&await o(c.receiver,{enableTopn:!!ce("ENABLE_AUDIO_TOPN"),enableMetadata:!!ce("ENABLE_AUDIO_METADATA"),enablePts:!!ce("ENABLE_AUDIO_PTS"),onMetadata:e=>{this.safeEmit(In.AudioMetadata,e)},onPts:e=>{this.safeEmit(In.AudioPts,e)}})}if(n===Sn.AUDIO){if(e._audioTrack?e._audioTrack._updateOriginMediaStreamTrack(a):(e._audioTrack=new I(a,e.uid,e._uintid,this.store),B.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote audio track: ").concat(e._audioTrack.getTrackId()))),l){e._audioTrack._reusePreAudioElement(l,!0);const t=this.connection.getPreMedia(o);t&&(t.audioTrackId=void 0)}c&&e._audioTrack._updateRtpTransceiver(c),this.bindRemoteTrackEvents(e,e._audioTrack)}else e._videoTrack?e._videoTrack._updateOriginMediaStreamTrack(a):(e._videoTrack=new v(a,e.uid,e._uintid,this.store,d),B.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote video track: ").concat(e._videoTrack.getTrackId()))),c&&e._videoTrack._updateRtpTransceiver(c),this.bindRemoteTrackEvents(e,e._videoTrack);if(ce("ENABLE_VIDEO_SEI")&&c){const t=Go(),i=t.interceptRemoteVideoFrame,o=t.interceptRemoteAudioFrame;n==Sn.VIDEO?await i(c.receiver,{onSei:t=>{var i;null===(i=e._videoTrack)||void 0===i||i._onSei(t)},onFirstFrame:e=>{const t=Array.from(this.remoteUserMap.keys()).find((t=>t._videoSSRC===e.ssrc));t&&this.store.firstVideoFrameDecoded(t.uid,{firstReceivedEncodedFrame:Date.now(),frameType:e.type,rtpTimestamp:e.rtpTimestamp,framePayloadType:e.payloadType,frameDataLength:e.length,mimeType:e.mimeType})}}):n==Sn.AUDIO&&await o(c.receiver)}const h=this.remoteUserMap.get(e);h?h.set(n,r):this.remoteUserMap.set(e,new Map([[n,r]])),this.statsCollector.addRemoteStats(e.uid),this.statsUploader.startUploadInboundStats();const u=this.pendingRemoteTracks.findIndex((t=>{let i=t.user,o=t.kind;return i.uid===e.uid&&n===o}));-1!==u&&(this.pendingRemoteTracks.splice(u,1),this.emit(In.MediaReconnectEnd,e.uid))}}async unsubscribe(e,t,i){const n=this.pendingRemoteTracks.filter((i=>{let n=i.user,o=i.kind;return void 0!==t?n.uid===e.uid&&t===o:n.uid===e.uid}));if(n.forEach((e=>{const t=this.pendingRemoteTracks.indexOf(e);this.pendingRemoteTracks.splice(t,1)})),this.connection&&this.state===gn.Connected||i||n.forEach((t=>{let i=t.kind;var n;if(i===Sn.AUDIO)null===(n=e._audioTrack)||void 0===n||n._destroy(),e._audioTrack=void 0;else if(i===Sn.VIDEO){var o;null===(o=e._videoTrack)||void 0===o||o._destroy(),e._videoTrack=void 0}})),!this.connection||this.state!==gn.Connected)return;const o=this.filterTobeUnSubscribedTracks(e,t);if(0===o.length)return;await this.connection.stopReceiving(o.map((e=>Mi(e,2)[1].id)));const s=this.createUnsubscribeMessage(o);return this.withdrawRemoteTracks(o),0===this.remoteUserMap.size&&this.statsUploader.stopUploadInboundStats(),o.forEach((e=>{let t=Mi(e,2),n=t[0],o=t[1].kind;var s,a;o===Sn.VIDEO&&n._videoSSRC&&(null===(s=this.connection)||void 0===s||s.setStatsRemoteVideoIsReady(n._videoSSRC,!1));if(o===Sn.VIDEO)this.unbindRemoteTrackEvents(n._videoTrack),i||(null===(a=n._videoTrack)||void 0===a||a._destroy(),n._videoTrack=void 0);else if(o===Sn.AUDIO){var r;if(this.unbindRemoteTrackEvents(n._audioTrack),!i)null===(r=n._audioTrack)||void 0===r||r._destroy(),n._audioTrack=void 0}})),s}async unsubscribeDataChannel(e,t){if(t.forEach((e=>{const t=this.pendingRemoteDataChannels.findIndex((t=>t.id===e.id));-1!==t&&this.pendingRemoteDataChannels.splice(t,1)})),!this.connection)return;const i=this.filterTobeUnSubscribedDataChannels(e,t);if(0===i.length)return;t.forEach((e=>{e._close()}));const n=this.remoteDataChannelMap.get(e);return i.forEach((e=>{n&&n.delete(e.id)})),n&&0===n.size&&(this.remoteDataChannelMap.delete(e),await this.connection.stopDataChannels(e.uid)),i.map((e=>e.id))}async massUnsubscribe(e){return this.massUnsubscribeNoLock(e)}async massUnsubscribeNoLock(e){let t=[];for(const i of e){const e=i.user,n=i.mediaType,o=this.pendingRemoteTracks.filter((t=>{let i=t.user,o=t.kind;return void 0!==n?i.uid===e.uid&&n===o:i.uid===e.uid}));o.forEach((e=>{const t=this.pendingRemoteTracks.indexOf(e);this.pendingRemoteTracks.splice(t,1)})),t=t.concat(o)}if(!this.connection||this.state!==gn.Connected)return void t.forEach((e=>{let t=e.user,i=e.kind;var n;if(i===Sn.AUDIO)null===(n=t._audioTrack)||void 0===n||n._destroy(),t._audioTrack=void 0;else if(i===Sn.VIDEO){var o;null===(o=t._videoTrack)||void 0===o||o._destroy(),t._videoTrack=void 0}}));const i=e.reduce(((e,t)=>{let i=t.user,n=t.mediaType;const o=this.filterTobeUnSubscribedTracks(i,n);return e.concat(o)}),[]);if(0===i.length)return;await this.connection.stopReceiving(i.map((e=>Mi(e,2)[1].id)));const n=this.createUnsubscribeAllMessage(i);return this.withdrawRemoteTracks(i),0===this.remoteUserMap.size&&this.statsUploader.stopUploadInboundStats(),i.forEach((e=>{let t=Mi(e,2),i=t[0],n=t[1].kind;var o,s;n===Sn.VIDEO&&i._videoSSRC&&(null===(o=this.connection)||void 0===o||o.setStatsRemoteVideoIsReady(i._videoSSRC,!1));if(n===Sn.VIDEO)this.unbindRemoteTrackEvents(i._videoTrack),null===(s=i._videoTrack)||void 0===s||s._destroy(),i._videoTrack=void 0;else if(n===Sn.AUDIO){var a;this.unbindRemoteTrackEvents(i._audioTrack),null===(a=i._audioTrack)||void 0===a||a._destroy(),i._audioTrack=void 0}})),n}isPreSubScribe(e){if(!this.connection||this.state!==gn.Connected)return!1;return!!this.connection.getPreMedia(e)}async muteRemote(e,t){if(!this.connection)return;const i=this.remoteUserMap.get(e);if(!i)return void B.warning("[".concat(this.store.clientId,"] P2PChannel.muteRemote has no remote user ").concat(e.uid,"."));if(!i.get(t))return void B.warning("[".concat(this.store.clientId,"] P2PChannel.muteRemote has no remote user ").concat(e.uid," media type ").concat(t,"."));const n=t===Sn.VIDEO?e._videoSSRC:e._audioSSRC;void 0!==n&&this.connection.setStatsRemoteVideoIsReady(n,!1)}async unmuteRemote(e,t){return this.unmuteRemoteNoLock(e,t)}async unmuteRemoteNoLock(e,t){if(!this.connection)return;const i=this.remoteUserMap.get(e);if(!i)return void B.warning("[".concat(this.store.clientId,"] P2PChannel.unmuteRemote has no remote user ").concat(e.uid,"."));i.get(t)||B.warning("[".concat(this.store.clientId,"] P2PChannel.unmuteRemote has no remote user ").concat(e.uid," media type ").concat(t,"."))}addAudioMetadata(e){const t=this.localTrackMap.get(Tn.LocalAudioTrack),i=t&&t.track;i&&i.metadata.push(e)}getAllTracks(e){const t=this.localTrackMap.get(Tn.LocalAudioTrack);if((null==t?void 0:t.track)instanceof a){const i=t.track;return Array.from(this.localTrackMap.entries()).filter((e=>Mi(e,1)[0]!==Tn.LocalAudioTrack)).filter((t=>{let i=Mi(t,1)[0];return!(e&&i===Tn.LocalVideoLowTrack)})).map((e=>Mi(e,2)[1].track)).concat(i.trackList)}return Array.from(this.localTrackMap.entries()).filter((t=>{let i=Mi(t,1)[0];return!(e&&i===Tn.LocalVideoLowTrack)})).map((e=>Mi(e,2)[1].track))}getAllDataChannels(){return this.localDataChannels}reportPublishEvent(e,i,o,a,r){if(e){const t=this.localTrackMap.get(Tn.LocalAudioTrack),n=a?this.localTrackMap.get(Tn.LocalVideoLowTrack):this.localTrackMap.get(Tn.LocalVideoTrack);G.publish(this.store.sessionId,{eventElapse:Ys.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:e,ec:i,audioName:null==t?void 0:t.track.getTrackLabel(),videoName:null==n?void 0:n.track.getTrackLabel(),screenshare:-1!==(null==n?void 0:n.track._hints.indexOf(s.SCREEN_TRACK)),audio:!!t,video:!!n,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r})}else{var c;o||(o=[]);const d=o.find((e=>e instanceof t)),l=a?null===(c=this.localTrackMap.get(Tn.LocalVideoTrack))||void 0===c?void 0:c.track:o.find((e=>e instanceof n));G.publish(this.store.sessionId,{eventElapse:Ys.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:e,ec:i,audioName:null==d?void 0:d.getTrackLabel(),videoName:null==l?void 0:l.getTrackLabel(),screenshare:-1!==(null==l?void 0:l._hints.indexOf(s.SCREEN_TRACK)),audio:!!d,video:!!l,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r})}}reportSubscribeEvent(e,t,i,n){const o=n===Sn.VIDEO?i._videoSSRC:i._audioSSRC;o&&G.subscribe(this.store.sessionId,{succ:e,ec:t,video:n===Sn.VIDEO,audio:n===Sn.AUDIO,peerid:i.uid,subscribeRequestid:o,p2pid:this.store.p2pId,eventElapse:Ys.measureFromSubscribeStart(this.store.clientId,o),preSsrc:this.isPreSubScribe(o)})}reset(){B.debug("[".concat(this.store.clientId,"] P2PChannel.reset")),this.mutex=new ue("P2PChannel-mutex",this.store.clientId),this.connection&&(this.resetConnection(this.connection),this.connection=void 0),this.shouldForwardP2PCreation&&this.recreateConnection(),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),this.statsUploader.stopUploadExtensionUsageStats(),this.statsUploader.stopUploadBaseStats(),this.unbindLocalTrackEvents(),this.unbindAllRemoteTrackEvents(),this.unbindRtpTransceiver();const e=this.localTrackMap.get(Tn.LocalAudioTrack);if((null==e?void 0:e.track)instanceof a){if(e.track.trackList.length>0){const t=e.track;e.track.trackList.forEach((e=>{t.removeAudioTrack(e)}))}e.track.close()}this.localTrackMap.clear(),this.remoteUserMap.clear(),this.statsCollector.removeRemoteStats(),this.statsCollector.removeLocalStats(),this.iceFailedCount=0,this.dtlsFailedCount=0,this.pendingLocalTracks=[],this.pendingRemoteTracks=[],this.localDataChannels=[],this.remoteDataChannelMap.clear(),this.pendingLocalDataChannels=[],this.pendingRemoteDataChannels=[],this.state=gn.Disconnected}getStats(){var e;return null===(e=this.connection)||void 0===e?void 0:e.getStats()}getRemoteVideoIsReady(e){var t;return(null===(t=this.connection)||void 0===t?void 0:t.getRemoteVideoIsReady(e))||!1}getLocalAudioVolume(){const e=this.localTrackMap.get(Tn.LocalAudioTrack);if(e)return e.track.getVolumeLevel()}getLocalVideoSize(){const e=this.localTrackMap.get(Tn.LocalVideoTrack);if(e)return{width:e.track.videoWidth||0,height:e.track.videoHeight||0}}getEncoderConfig(e){const i=this.localTrackMap.get(e);return i&&i.track instanceof n||i&&i.track instanceof t?i.track._encoderConfig:void 0}getLocalMedia(e){return this.localTrackMap.get(e)}hasLocalMedia(){return this.localTrackMap.size>0}hasRemoteMedia(e,t){if(!e)return this.remoteUserMap.size>0;const i=this.remoteUserMap.get(e);return!!i&&(!t||i.has(t))}async hasRemoteMediaWithLock(e,t){if(!e)return this.remoteUserMap.size>0;const i=this.remoteUserMap.get(e);return!!i&&(!t||i.has(t))}getRemoteMedia(e){const t=Array.from(this.remoteUserMap.keys()).find((t=>t.uid===e));return t?{audioTrack:t.audioTrack,audioSSRC:t._audioSSRC,videoTrack:t.videoTrack,videoSSRC:t._videoSSRC}:{}}getAudioLevels(){let e=Array.from(this.remoteUserMap.entries()).map((e=>{let t=Mi(e,1)[0];return{uid:t.uid,level:t.audioTrack?100*t.audioTrack._source.getAccurateVolumeLevel():0}}));const t=this.localTrackMap.get(Tn.LocalAudioTrack);return t&&e.push({level:100*t.track._source.getAccurateVolumeLevel(),uid:this.store.uid}),e=e.sort(((e,t)=>e.level-t.level)),e}async disconnectForReconnect(){this.connection&&(B.debug("[".concat(this.store.clientId,"] P2PChannel.disconnectForReconnect closing P2PConnection")),this.state=gn.Reconnecting,ce("KEEP_LAST_FRAME")&&0!==this.remoteUserMap.size&&Array.from(this.remoteUserMap.entries()).forEach((e=>{let t=Mi(e,1)[0];var i;t._videoTrack&&t._videoTrack._player&&(null===(i=t._videoTrack._player.getVideoElement())||void 0===i||i.pause(),t._videoTrack._player.isKeepLastFrame=!0,t._videoTrack._originMediaStreamTrack.stop())})),this.resetConnection(this.connection),this.connection=void 0,this.shouldForwardP2PCreation&&this.recreateConnection(),0!==this.localTrackMap.size&&(Array.from(this.localTrackMap.entries()).forEach((e=>{let t=Mi(e,2),i=t[0],n=t[1].track;switch(i){case Tn.LocalVideoTrack:n._hints.includes(s.LOW_STREAM)?n.close():this.pendingLocalTracks.push(n);break;case Tn.LocalAudioTrack:n instanceof a?this.pendingLocalTracks=this.pendingLocalTracks.concat(n.trackList):this.pendingLocalTracks.push(n);case Tn.LocalVideoLowTrack:}})),this.emit(In.MediaReconnectStart,this.store.uid)),this.unbindLocalTrackEvents(),this.localTrackMap.clear(),0!==this.remoteUserMap.size&&Array.from(this.remoteUserMap.entries()).forEach((e=>{let t=Mi(e,2),i=t[0],n=t[1];Array.from(n.keys()).forEach((e=>{this.setPendingRemoteMedia(i,e)})),this.emit(In.MediaReconnectStart,i.uid)})),this.unbindAllRemoteTrackEvents(),this.remoteUserMap.clear(),0!==this.localDataChannels.length&&(this.localDataChannels.forEach((e=>{this.pendingLocalDataChannels.push(e)})),this.localDataChannels.length=0),0!==this.remoteDataChannelMap.size&&(Array.from(this.remoteDataChannelMap.entries()).forEach((e=>{let t=Mi(e,2),i=t[0],n=t[1];Array.from(n.keys()).forEach((e=>{this.setPendingRemoteDataChannel(i,e)}))})),this.remoteDataChannelMap.clear()),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),B.debug("[".concat(this.store.clientId,"] P2PChannel disconnected, waiting to reconnect.")))}hasPendingRemoteDataChannel(e,t){for(const i of this.pendingRemoteDataChannels){const n=i.user,o=i.id;if((e instanceof Qs?e.uid:e)===n.uid&&o===t)return!0}return!1}setPendingRemoteDataChannel(e,t){this.hasPendingRemoteDataChannel(e,t)||this.pendingRemoteDataChannels.push({user:e,id:t})}hasPendingRemoteMedia(e,t){for(const i of this.pendingRemoteTracks){const n=i.user,o=i.kind;if((e instanceof Qs?e.uid:e)===n.uid&&t===o)return!0}return!1}setPendingRemoteMedia(e,t){this.hasPendingRemoteMedia(e,t)||this.pendingRemoteTracks.push({user:e,kind:t})}restartICE(e){var t=this;return Ui((function*(){if(!t.connection||t.state!==gn.Connected)return;const i=yield Di(t.mutex.lock("From P2PChannel.restartICE"));let n;try{n=yield Di(t.connection.restartICE(e));const o=yield Di(n.next());if(o.done)return;const s=o.value,a=yield s;switch(ya(t.connection)&&t.reportPCStats(Date.now(),!1,t._pcStatsUploadType),e){case fn.UDP_TCP_RELAY:t._pcStatsUploadType=Cn.UDP_TCP_RESTART;break;case fn.TCP_RELAY:t._pcStatsUploadType=Cn.TCP_RESTART;break;case fn.RELAY:t._pcStatsUploadType=Cn.RELAY_RESTART;break;default:t._pcStatsUploadType=Cn.OLD_RESTART}t._isTryConnecting=!0,n.next(a)}catch(e){var o;null===(o=n)||void 0===o||o.throw(e)}finally{i()}}))()}getUplinkNetworkQuality(){if(!this.connection)return 0;const e=this.connection.getStats(),t=this.localTrackMap.get(Tn.LocalVideoTrack),i=this.localTrackMap.get(Tn.LocalAudioTrack),n=e.videoSend.find((e=>e.ssrc===(null==t?void 0:t.ssrcs[0].ssrcId))),o=e.audioSend.find((e=>e.ssrc===(null==i?void 0:i.ssrcs[0].ssrcId)));if(!n||!o)return 1;const a=Re(this,In.NeedSignalRTT),r=n?n.rttMs:void 0,c=o?o.rttMs:void 0,d=r&&c?(r+c)/2:r||c,l=(d&&a?(d+a)/2:d||a)||0,h=100*e.sendPacketLossRate*.7/50+.3*l/1500,u=h<.17?1:h<.36?2:h<.59?3:h<.1?4:5,_=null==t?void 0:t.track;if(_&&_._encoderConfig&&-1===_._hints.indexOf(s.SCREEN_TRACK)){const t=_._encoderConfig.bitrateMax,i=e.bitrate.actualEncoded;if(t&&i){const e=(1e3*t-i)/(1e3*t);return Ri[e<.15?0:e<.3?1:e<.45?2:e<.6?3:4][u]}}return u}getDownlinkNetworkQuality(){if(!this.connection)return 0;const e=this.connection.getStats();let t=0;return Array.from(this.remoteUserMap.entries()).forEach((i=>{let n=Mi(i,1)[0];const o=n._audioSSRC,s=n._videoSSRC,a=e.audioRecv.find((e=>e.ssrc===o)),r=e.videoRecv.find((e=>e.ssrc===s));if(!a&&!r)return void(t+=1);const c=Re(this,In.NeedSignalRTT),d=e.rtt,l=(d&&c?(d+c)/2:d||c)||0,h=a?a.jitterMs:void 0,u=e.recvPacketLossRate;let _=.7*u*100/50+.3*l/1500;h&&(_=.6*u*100/50+.2*l/1500+.2*h/400);t+=_<.1?1:_<.17?2:_<.36?3:_<.59?4:5})),this.remoteUserMap.size>0?Math.round(t/this.remoteUserMap.size):t}async muteLocalTrack(e){return new Promise(((t,i)=>{this.handleMuteLocalTrack(e,t,i)}))}async replaceTrack(e,t){var i;if(B.debug("[".concat(this.store.clientId,"] P2PChannel replaceTrack from [").concat(e.getTrackId(),"] to [").concat(t.getTrackId(),"]")),!this.connection||this.state!==gn.Connected)return;const n=Array.from(this.localTrackMap.entries()).find((t=>{let i=Mi(t,2)[1].track;return e===i}));if(!n)return;const s=n[0];if(e!==t&&(this.unbindLocalTrackEvents([{track:e,type:s}]),this.bindLocalTrackEvents([{track:t,type:s}]),n[1].track=t),await(null===(i=this.connection)||void 0===i?void 0:i.replaceTrack(t,n[1].id)),this.isPlanB){const e=n[1];e.id=t._mediaStreamTrack.id,this.localTrackMap.set(s,e)}if(s===Tn.LocalVideoTrack&&!ce("DISABLE_DUAL_STREAM_USE_ENCODING")&&o().supportDualStreamEncoding){const t=this.localTrackMap.get(Tn.LocalVideoLowTrack);if(t){const i=e._mediaStreamTrack.clone();t.track._originMediaStreamTrack.stop(),t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i,await new Promise(((e,i)=>{this.handleReplaceTrack(t.track,e,i,!0)}))}}}filterTobePublishedTracks(e,i,s){const r=[],c=this.getAllTracks();e=e.filter((e=>-1===c.indexOf(e))),e=St(e);let d,l=!1;const h=this.localTrackMap.get(Tn.LocalAudioTrack);for(const c of e){if(c instanceof n&&(this.localTrackMap.has(Tn.LocalVideoTrack)||l?new me(ne.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS).throw():(r.push({track:c,type:Tn.LocalVideoTrack}),l=!0),i)){const e=this.getLowVideoTrack(c,s);r.push({track:e,type:Tn.LocalVideoLowTrack})}if(c instanceof t)if(h){const e=h.track;if(e instanceof a)ga([c]),e.addAudioTrack(c),this.bindLocalAudioTrackEvents(c,!0);else{const t=Ia([e,c]);B.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection will replace audioTrack [").concat(t.getTrackId(),"]")),this.replaceTrack(e,t)}}else if(d instanceof a)ga([c]),d.addAudioTrack(c);else if(d||!c._useAudioElement&&o().webAudioMediaStreamDest&&!c._bypassWebAudio){d=Ia(d?[c,d]:[c])}else d=c}return d&&(B.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection will send audioTrack [").concat(d.getTrackId(),"]")),r.push({track:d,type:Tn.LocalAudioTrack})),r}filterTobeUnpublishedTracks(e){const i=[],o=this.getAllTracks();e=e.filter((e=>-1!==o.indexOf(e))),e=St(e);for(const o of e){if(o instanceof t){const e=this.localTrackMap.get(Tn.LocalAudioTrack);if(!e)continue;e.track instanceof a?(e.track.removeAudioTrack(o),this.unbindLocalAudioTrackEvents(o),0===e.track.trackList.length&&(i.push([Tn.LocalAudioTrack,e]),e.track.close())):i.push([Tn.LocalAudioTrack,e])}if(o instanceof n){const e=this.localTrackMap.get(Tn.LocalVideoTrack);if(!e)continue;i.push([Tn.LocalVideoTrack,e]);const t=this.localTrackMap.get(Tn.LocalVideoLowTrack);t&&i.push([Tn.LocalVideoLowTrack,t])}}return i}filterTobePublishedDataChannels(e){return e=(e=St(e)).filter((e=>-1===this.localDataChannels.findIndex((t=>t.id===e.id))))}filterTobeUnpublishedDataChannels(e){return e=(e=(e=St(e)).filter((e=>-1!==this.localDataChannels.indexOf(e)))).filter((e=>e._originDataChannel))}bindLocalTrackEvents(e){e.forEach((e=>{let t=e.track;switch(e.type){case Tn.LocalVideoTrack:t.addListener(y.GET_STATS,this.handleGetLocalVideoStats),t.addListener(y.GET_RTC_STATS,this.handleGetRTCStats),t.addListener(y.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.addListener(y.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.addListener(y.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.addListener(y.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this.handleUpdateVideoSendParameters),t.addListener(y.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.addListener(y.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.addListener(y.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case Tn.LocalAudioTrack:this.bindLocalAudioTrackEvents(t);case Tn.LocalVideoLowTrack:}}))}bindLocalAudioTrackEvents(e,t){e instanceof a?e.trackList.forEach((e=>{e.addListener(y.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(y.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(y.GET_STATS,this.handleGetLocalAudioStats),e.addListener(y.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(y.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)})):(e.addListener(y.GET_STATS,this.handleGetLocalAudioStats),e.addListener(y.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(y.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(y.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(y.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack),t||(e.addListener(y.NEED_REPLACE_TRACK,this.handleReplaceTrack),e.addListener(y.NEED_REPLACE_MIXING_TRACK,this.handleReplaceMixingTrack)))}unbindLocalTrackEvents(e){e||(e=Array.from(this.localTrackMap.entries()).map((e=>{let t=Mi(e,2),i=t[0];return{track:t[1].track,type:i}}))),e.forEach((e=>{let t=e.track;switch(e.type){case Tn.LocalVideoTrack:t.off(y.GET_STATS,this.handleGetLocalVideoStats),t.off(y.GET_RTC_STATS,this.handleGetRTCStats),t.off(y.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.off(y.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.off(y.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.off(y.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this.handleUpdateVideoSendParameters),t.off(y.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.off(y.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.off(y.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case Tn.LocalAudioTrack:this.unbindLocalAudioTrackEvents(t);case Tn.LocalVideoLowTrack:}}))}unbindLocalAudioTrackEvents(e){e instanceof a?e.trackList.forEach((e=>{e.off(y.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(y.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(y.GET_STATS,this.handleGetLocalAudioStats),e.off(y.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(y.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)})):(e.off(y.GET_STATS,this.handleGetLocalAudioStats),e.off(y.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(y.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(y.NEED_REPLACE_TRACK,this.handleReplaceTrack),e.off(y.NEED_REPLACE_MIXING_TRACK,this.handleReplaceMixingTrack),e.off(y.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(y.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack))}bindRemoteTrackEvents(e,t){t instanceof v&&t.addListener(y.GET_STATS,(t=>{t(this.handleGetRemoteVideoStats(e))})),t instanceof I&&t.addListener(y.GET_STATS,(t=>{t(this.handleGetRemoteAudioStats(e))}))}unbindRemoteTrackEvents(e){e&&e.removeAllListeners(y.GET_STATS)}unbindAllRemoteTrackEvents(){Array.from(this.remoteUserMap.entries()).forEach((e=>{let t=Mi(e,2),i=t[0],n=t[1];n.has(Sn.AUDIO)&&this.unbindRemoteTrackEvents(i._audioTrack),n.has(Sn.VIDEO)&&this.unbindRemoteTrackEvents(i._videoTrack)}))}createGatewayPublishMessage(e,t){return e.map(((e,n)=>{let o,a,r=e.track;switch(e.type){case Tn.LocalAudioTrack:o=sn.Audio,a={dtx:r instanceof i&&r._config.DTX,hq:!1,lq:!1,stereo:!1,speech:!1};break;case Tn.LocalVideoTrack:o=r._hints.includes(s.SCREEN_TRACK)?sn.Screen:sn.High,a=ki(ki({},Zn(r)),{},{codec:this.store.codec,svc_mode:ao()});break;case Tn.LocalVideoLowTrack:o=sn.Low,a=ki(ki({},Zn(r)),{},{codec:this.store.codec,svc_mode:ao()})}return{stream_type:o,attributes:a,ssrcs:t[n]}}))}createGatewayUnpublishMessage(e){return e.map((e=>{let t,i=Mi(e,2),n=i[0],o=i[1],a=o.track,r=o.ssrcs,c=o.id;switch(n){case Tn.LocalVideoTrack:t=a._hints.includes(s.SCREEN_TRACK)?sn.Screen:sn.High;break;case Tn.LocalAudioTrack:t=sn.Audio;break;case Tn.LocalVideoLowTrack:t=sn.Low}return{stream_type:t,ssrcs:r,mid:c}}))}assignLocalTracks(e,t){e.forEach(((e,i)=>{let n=e.track,o=e.type;this.localTrackMap.set(o,{track:n,id:t[i].id,ssrcs:t[i].localSSRC})}))}withdrawLocalTracks(e){e.forEach((e=>{let t=Mi(e,1)[0];this.localTrackMap.delete(t)}))}bindConnectionEvents(e){e.onConnectionStateChange=async t=>{if(B.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onConnectionStateChange(").concat(t,")")),this.emit(In.PeerConnectionStateChange,t),"connecting"===t&&e instanceof ba&&!he()&&ce("FIRST_TCP_CANDIDATE")&&window.setTimeout((()=>{"connecting"===t&&e.extendCandidate()}),ce("FIRST_TCP_CANDIDATE_INTERVAL")),"connected"!==t||this.store.keyMetrics.peerConnectionEnd||this.store.peerConnectionEnd(),"connected"===t){this._restartTimer&&(window.clearTimeout(this._restartTimer),this._restartTimer=void 0),e instanceof ba&&$a(e,!0),this._isTryConnecting&&this.reportPCStats(Date.now(),!0,this._pcStatsUploadType),this._isTryConnecting=!1,this._isStartRestartIce=!1,this._pcStatsUploadType=Cn.DISCONNECTED_OR_FAILED;if("CONNECTED"===Re(this,In.QueryClientConnectionState)&&this._isWaitPcToRePub){const e=this.pendingLocalTracks.map((e=>e.getTrackId())),t=this.pendingLocalDataChannels.map((e=>"dc_".concat(e.id)));G.reportApiInvoke(this.store.sessionId,{name:Be.REPUB_AFTER_PC_CONNECTED,options:e.concat(t),tag:je.TRACER}).onSuccess(),this.republish()}}if(ce("NEW_ICE_RESTART")&&e instanceof ba&&!he()&&!this._forceTurn&&!this.store.useDcSignal){if(Rn.includes(t)){if(this._isStartRestartIce)return;this._isStartRestartIce=!0;const t=t=>{if(ya(e)){B.debug("[".concat(this.store.clientId,"] [P2PChannel] try to restartICE, type is ").concat(t));"CONNECTED"===Re(this,In.QueryClientConnectionState)&&this.emit(In.RequestRestartICE,t)}},i=()=>{ya(e)&&(this.reportPCStats(Date.now(),!1,this._pcStatsUploadType),B.debug("[".concat(this.store.clientId,"] P2PConnection disconnected timeout, force reconnect")),setTimeout((()=>this.emit(In.P2PLost)),0),this.iceFailedCount+=1,this.requestReconnect())};return void(this._restartTimer=window.setTimeout((()=>{er(e,t,i)}),800))}}else{if("disconnected"===t&&"disconnected"===e.iceConnectionState)return setTimeout((()=>{if("disconnected"===e.iceConnectionState&&ce("ICE_RESTART")){"CONNECTED"===Re(this,In.QueryClientConnectionState)&&this.emit(In.RequestRestartICE)}}),800),void setTimeout((()=>{"disconnected"===e.peerConnectionState&&(B.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection disconnected timeout 4000ms, force reconnect")),this.reportPCStats(Date.now(),!1,this._pcStatsUploadType),this._isTryConnecting=!1,setTimeout((()=>this.emit(In.P2PLost)),0),this.iceFailedCount+=1,this.requestReconnect())}),4e3);"failed"===t&&(B.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection state failed, force reconnect")),this.reportPCStats(Date.now(),!1,this._pcStatsUploadType),setTimeout((()=>this.emit(In.P2PLost)),0),this.iceFailedCount+=1,await this.requestReconnect())}},e.onICEConnectionStateChange=e=>{"connected"!==e||this.store.keyMetrics.iceConnectionEnd||this.store.iceConnectionEnd(),B.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICEConnectionStateChange(").concat(e,")")),G.reportApiInvoke(this.store.sessionId,{name:"ICEConnectionStateChange",options:e,tag:je.TRACER}).onSuccess(),this.emit(In.IceConnectionStateChange,e)},e.onICETransportStateChange=e=>{B.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICETransportStateChange(").concat(e,")"))},e.onDTLSTransportStateChange=e=>{B.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportStateChange(").concat(e,")"))},e.onDTLSTransportError=e=>{B.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportError(").concat(e,")"))},e.onFirstAudioDecoded=e=>{const t=Array.from(this.remoteUserMap.keys()).find((t=>t._audioSSRC===e));var i;t&&(this.store.subscribe(t.uid,"audio",void 0,void 0,void 0,Date.now()),null===(i=t.audioTrack)||void 0===i||i.emit(A.FIRST_FRAME_DECODED),G.firstRemoteFrame(this.store.sessionId,J.FIRST_AUDIO_DECODE,X.FIRST_AUDIO_DECODE,{peer:t._uintid,subscribeElapse:Ys.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId}))},e.onFirstAudioReceived=e=>{const t=Array.from(this.remoteUserMap.keys()).find((t=>t._audioSSRC===e));t&&G.firstRemoteFrame(this.store.sessionId,J.FIRST_AUDIO_RECEIVED,X.FIRST_AUDIO_RECEIVED,{peer:t._uintid,subscribeElapse:Ys.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId})},e.onFirstVideoDecoded=(e,t,i)=>{const n=Array.from(this.remoteUserMap.keys()).find((t=>t._videoSSRC===e));n&&this.store.firstVideoFrameDecoded(n.uid,{firstDecoded:Date.now()}),this.reportVideoFirstFrameDecoded(e,t,i)},e.onFirstVideoRender=e=>{const t=Array.from(this.remoteUserMap.keys()).find((t=>t._videoSSRC===e));t&&(this.store.firstVideoFrameDecoded(t.uid,{firstPreRender:Date.now()}),this.reportVideoFirstFrameRender(t),this.emit(In.FirstVideoPreRender,t.uid,e))},e.onFirstVideoReceived=e=>{const t=Array.from(this.remoteUserMap.keys()).find((t=>t._videoSSRC===e));t&&(this.store.firstVideoFrameDecoded(t.uid,{firstReceived:Date.now()}),G.firstRemoteFrame(this.store.sessionId,J.FIRST_VIDEO_RECEIVED,X.FIRST_VIDEO_RECEIVED,{peer:t._uintid,subscribeElapse:Ys.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId}))},e.onFirstVideoBufferReady=e=>{const t=Array.from(this.remoteUserMap.keys()).find((t=>t._videoSSRC===e));t&&this.emit(In.FirstVideoBufferReady,t.uid,e)},e.onSelectedLocalCandidateChanged=(e,t)=>{const i="relay"===e.candidateType,n="relay"===t.candidateType;"unknown"!==t.candidateType&&i===n||this.emit(In.ConnectionTypeChange,i),B.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedLocalCandidateChanged(").concat(JSON.stringify(no(t))," -> ").concat(JSON.stringify(no(e)),")"))},e.onSelectedRemoteCandidateChanged=(e,t)=>{B.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedRemoteCandidateChanged(").concat(JSON.stringify(no(t))," -> ").concat(JSON.stringify(no(e)),")"))},e.onFirstVideoDecodedTimeout=e=>{this.reportVideoFirstFrameDecoded(e,void 0,void 0,!0)},e.getLocalVideoStats=()=>{const e=this.statsCollector.getLocalVideoTrackStats(),t=this.statsCollector.getRTCStats();return ki(ki({},e),t)},e.onICECandidateError=e=>{this._iceError=e}}fallbackConnection(){B.debug("[".concat(this.store.clientId,"] [P2PChannel] try to fallback connection")),this.state===gn.Connected?(B.debug("[".concat(this.store.clientId,"] [P2PChannel] fallback to websocket but P2PChannel state still connected, disconnect first")),this.disconnectForReconnect()):(this.connection&&this.resetConnection(this.connection),this.shouldForwardP2PCreation&&this.recreateConnection())}resetConnection(e){e instanceof ba&&function(e){Qa.delete(e.id),$a(e)}(e),e.close(),this.emit(In.PeerConnectionStateChange,"closed"),function(e){e.onConnectionStateChange=void 0,e.onICEConnectionStateChange=void 0,e.onICETransportStateChange=void 0,e.onDTLSTransportStateChange=void 0,e.onDTLSTransportError=void 0,e.onFirstAudioDecoded=void 0,e.onFirstAudioReceived=void 0,e.onFirstVideoDecoded=void 0,e.onFirstVideoReceived=void 0,e.onSelectedLocalCandidateChanged=void 0,e.onSelectedRemoteCandidateChanged=void 0,e.onFirstVideoDecodedTimeout=void 0,e.getLocalVideoStats=void 0}(e),this._isWaitPcToRePub=!1}recreateConnection(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this._p2pBySDPEndPoint=!1,this.connection=Aa(this.store,e),this.emit(In.PeerConnectionStateChange,this.connection.peerConnectionState),this.bindConnectionEvents(this.connection)}filterTobeMutedTracks(e){const i=[];if(-1===this.getAllTracks().indexOf(e))return i;const n=this.localTrackMap.get(Tn.LocalAudioTrack);if(e instanceof t&&(null==n?void 0:n.track)instanceof a)return n.track.isActive||i.push([Tn.LocalAudioTrack,n]),i;const o=Array.from(this.localTrackMap.entries()).find((t=>{let i=Mi(t,2)[1].track;return e===i}));if(o&&(i.push(o),o[0]===Tn.LocalVideoTrack)){const e=this.localTrackMap.get(Tn.LocalVideoLowTrack);e&&i.push([Tn.LocalVideoLowTrack,e])}return i}filterTobeUnmutedTracks(e){const i=[],n=this.localTrackMap.get(Tn.LocalAudioTrack);if(e instanceof t&&(null==n?void 0:n.track)instanceof a)return n.track.isActive&&i.push([Tn.LocalAudioTrack,n]),i;const o=Array.from(this.localTrackMap.entries()).find((t=>{let i=Mi(t,2)[1].track;return e===i}));if(o)if(o[0]===Tn.LocalVideoTrack){i.push(o);const e=this.localTrackMap.get(Tn.LocalVideoLowTrack);e&&i.push([Tn.LocalVideoLowTrack,e])}else i.push(o);return i}createMuteMessage(e){return e.map((e=>{let t,i=Mi(e,2),n=i[0],o=i[1],a=o.track,r=o.ssrcs,c=o.id;switch(n){case Tn.LocalAudioTrack:t=sn.Audio;break;case Tn.LocalVideoTrack:t=a._hints.includes(s.SCREEN_TRACK)?sn.Screen:sn.High;break;case Tn.LocalVideoLowTrack:t=sn.Low}return{stream_type:t,ssrcs:r,mid:c}}))}createUnmuteMessage(e){return e.map((e=>{let t,i=Mi(e,2),n=i[0],o=i[1],a=o.track,r=o.ssrcs,c=o.id;switch(n){case Tn.LocalAudioTrack:t=sn.Audio;break;case Tn.LocalVideoTrack:t=a._hints.includes(s.SCREEN_TRACK)?sn.Screen:sn.High;break;case Tn.LocalVideoLowTrack:t=sn.Low}return{stream_type:t,ssrcs:r,mid:c}}))}filterTobeUnSubscribedTracks(e,t){const i=[],n=this.remoteUserMap.get(e);if(!n)return i;if(t){const o=n.get(t);if(!o)return i;i.push([e,{kind:t,id:o}])}else Array.from(n.entries()).forEach((t=>{let n=Mi(t,2),o=n[0],s=n[1];i.push([e,{kind:o,id:s}])}));return i}filterTobeUnSubscribedDataChannels(e,t){const i=[];return t.forEach((t=>{var n;null!==(n=this.remoteDataChannelMap.get(e))&&void 0!==n&&n.has(t.id)&&i.push(t)})),i}createUnsubscribeMessage(e){const t=[];return e.forEach((e=>{let i=Mi(e,2),n=i[0],o=i[1],s=o.kind;switch(o.id,s){case Sn.VIDEO:return void(n._videoSSRC&&t.push({stream_type:Sn.VIDEO,ssrcId:n._videoSSRC}));case Sn.AUDIO:return void(n._audioSSRC&&t.push({stream_type:Sn.AUDIO,ssrcId:n._audioSSRC}))}})),t}createUnsubscribeAllMessage(e){const t=new Map;return e.forEach((e=>{let i=Mi(e,2),n=i[0],o=i[1].kind;if(t.has(n)){let e=t.get(n);o===Sn.VIDEO?e|=cn.Video:e|=cn.Audio,t.set(n,e)}else o===Sn.VIDEO?t.set(n,cn.Video):t.set(n,cn.Audio)})),{users:Array.from(t.entries()).map((e=>{let t=Mi(e,2),i=t[0],n=t[1];return{stream_id:i.uid,stream_type:n}}))}}withdrawRemoteTracks(e){e.forEach((e=>{let t=Mi(e,2),i=t[0],n=t[1].kind;const o=this.remoteUserMap.get(i);o&&(o.delete(n),0===Array.from(o.entries()).length&&this.remoteUserMap.delete(i))}))}async updateBitrateLimit(e){const t=this.localTrackMap.get(Tn.LocalVideoTrack),i=this.localTrackMap.get(Tn.LocalVideoLowTrack);t&&(await t.track.setBitrateLimit(e.uplink),await new Promise(((e,i)=>{this.handleUpdateVideoEncoder(t.track,e,i,!0)}))),i&&e.low_stream_uplink&&(await i.track.setBitrateLimit({max_bitrate:e.low_stream_uplink.bitrate,min_bitrate:e.low_stream_uplink.bitrate||0}),await new Promise(((e,t)=>{this.handleUpdateVideoEncoder(i.track,e,t,!0)})))}isP2PDisconnected(){if(this.connection){return"connected"!==this.connection.peerConnectionState}return!0}isPreallocation(){return!(!this.connection||!("name"in this.connection)||"DataChannelConnection"!==this.connection.name||"closed"===this.connection.peerConnectionState)||this.connection instanceof ba&&this.connection.isPreallocation}isPreSub(){return(this.connection&&"name"in this.connection&&"DataChannelConnection"===this.connection.name&&"closed"!==this.connection.peerConnectionState||this.connection instanceof ba)&&this.connection.isPreSub()}isPreRender(){return this.connection instanceof ba&&this.connection.isPreRender}mapPubResToRemoteConfig(e,t,i){return e.map(((e,n)=>{var o;let a=e.stream_type;const r=null===(o=t.find((e=>{let t=e.stream_type;return a===t})))||void 0===o?void 0:o.attributes;if(r&&ce("DISABLE_SCREEN_SHARE_REMB")){const e=i[n]._hints;(e.includes(s.SCREEN_TRACK)||e.includes(s.SCREEN_LOW_TRACK))&&(r.remb=!1,B.debug("disable remb for screen share, hints:",e))}return r}))}async tryToUnmuteAudio(e){for(let n=0;n<e.length;n++)if(e[n]instanceof t){var i;const t=this.filterTobeUnmutedTracks(e[n]);if(0===t.length)continue;await(null===(i=this.connection)||void 0===i?void 0:i.unmuteLocal(t.map((e=>Mi(e,2)[1].id))));const o=this.createUnmuteMessage(t);return void await Et(this,In.RequestUnmuteLocal,o)}}bindStatsUploaderEvents(){this.statsUploader.requestStats=()=>this.getStats(),this.statsUploader.requestLocalMedia=()=>Array.from(this.localTrackMap.entries()),this.statsUploader.requestRemoteMedia=()=>Array.from(this.remoteUserMap.entries()),this.statsUploader.requestVideoIsReady=e=>{var t;return!(null===(t=this.connection)||void 0===t||!t.getRemoteVideoIsReady(e))},this.statsUploader.requestUpload=(e,t)=>this.emit(In.RequestUpload,e,t),this.statsUploader.requestUploadStats=e=>this.emit(In.RequestUploadStats,e),this.statsUploader.requestAllTracks=()=>this.getAllTracks(),this.statsUploader.requestTransportStats=()=>{var e;return{connectState:(null===(e=this.connection)||void 0===e?void 0:e.peerConnectionState)||"closed"}}}unbindStatsUploaderEvents(){this.statsUploader.requestStats=void 0,this.statsUploader.requestLocalMedia=void 0,this.statsUploader.requestRemoteMedia=void 0,this.statsUploader.requestVideoIsReady=void 0}async requestReconnect(){this.dtlsFailedCount+=1,await fe(Se(this.dtlsFailedCount,Ke)),this.emit(In.RequestReconnect)}async reconnectP2P(){const e=Array.from(this.localTrackMap.entries()),t=this.createGatewayUnpublishMessage(e);Array.from(this.remoteUserMap.entries()),t.length>0&&await Ce(this,In.RequestUnpublishForReconnectPC,t),this.disconnectForReconnect(),this.emit(In.RequestReconnectPC)}canPublishLowStream(){return this.localTrackMap.has(Tn.LocalVideoTrack)||this.pendingLocalTracks.some((e=>e instanceof n))}throwIfTrackTypeNotMatch(e){if(e.filter((e=>e instanceof n)).length>1)throw new me(ne.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(e.filter((e=>e instanceof t)).length>1&&(e.some((e=>e instanceof t&&e._bypassWebAudio))||!o().webAudioMediaStreamDest))throw new me(ne.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode");for(const i of e){if(i instanceof n&&this.pendingLocalTracks.some((e=>e instanceof n)))throw new me(ne.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(i instanceof t&&this.pendingLocalTracks.some((e=>e instanceof t))&&(!o().webAudioMediaStreamDest||i._bypassWebAudio||this.pendingLocalTracks.some((e=>e instanceof t&&e._bypassWebAudio))))throw new me(ne.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode")}}getLowVideoTrack(e,t){const i=!ce("DISABLE_DUAL_STREAM_USE_ENCODING")&&o().supportDualStreamEncoding,a=ki(ki({},{width:160,height:120,framerate:15,bitrate:50}),t);let r;r=i?e._mediaStreamTrack.clone():Da(e,a);const c=ve(8,"track-low-"),d=new n(r,ki(ki({},i&&{scaleResolutionDownBy:io(a,e)}),{},{frameRate:a.framerate,bitrateMax:a.bitrate,bitrateMin:a.bitrate}),void 0,void 0,c);return d.on(N.TRANSCEIVER_UPDATED,(t=>{e._updateRtpTransceiver(t,w.LOW_STREAM)})),d._hints.push(s.LOW_STREAM),e._hints.includes(s.SCREEN_TRACK)&&d._hints.push(s.SCREEN_LOW_TRACK),e.on("sei-to-send",(e=>{d.emit("sei-to-send",e)})),e.addListener(y.NEED_CLOSE,(()=>{d.close()})),d}async globalLock(){return this.mutex.lock("From P2PChannel.globalLock")}async reportPCStats(e,t,i){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null;if(this.connection&&this.connection instanceof ba){var o,s,a,r;const c=this.store.keyMetrics.descriptionStart||0,d=this.connection,l=d.iceConnectionState,h=d.dtlsTransportState,u=d.peerConnectionState,_=await this.connection.getSelectedCandidatePair(),p=_.local,E=_.remote;G.pcStats(this.store.sessionId,{startTime:c,eventElapse:e-c||0,iceconnectionsate:l,dtlsstate:h,connectionstate:u,intSucc:t?1:2,error:this._iceError||n||"",selectedLocalCandidateProtocol:null!==(o=null==p?void 0:p.protocol)&&void 0!==o?o:"",selectedLocalCandidateType:null!==(s=p.candidateType)&&void 0!==s?s:"",selectedLocalCandidateAddress:"".concat(p.address,":").concat(p.port),selectedRemoteCandidateProtocol:null!==(a=E.protocol)&&void 0!==a?a:"",selectedRemoteCandidateType:null!==(r=E.candidateType)&&void 0!==r?r:"",selectedRemoteCandidateAddress:"".concat(E.address,":").concat(E.port),restartCnt:i,preallocation:this.connection.isPreallocation,sdpEndPoint:this._p2pBySDPEndPoint?1:0}),this._iceError=null}}reportVideoFirstFrameRender(e){const t=this.store.keyMetrics,i=t.firstVideoFrameDecoded.find((t=>t.userId===e.uid));if(!i)return;const n=i.isInternalUpload,o=i.isExternalUpload;if(n&&o)return;const s=i.subscribeEnd,a=i.firstPreRender,r=i.peerPublishDuration,c=i.peerPubStatusMs;let d=i.firstRender,l=void 0===d?0:d;if(s&&(l||a)&&r&&c){i.isInternalUpload=!0;const n=i.playEnd;n&&(i.isExternalUpload=!0);const o=i.firstPreRender,a=void 0===o?0:o;l=a||l;const d=e.videoTrack,h={peer:e._uintid,width:(null==d?void 0:d._videoWidth)||0,height:(null==d?void 0:d._videoHeight)||0,ssrc:e._videoSSRC||0,p2pid:this.store.p2pId,peerPublishDuration:r,peerPubStatusMs:c,joinChannelStart:t.joinStart||0,preloadStart:t.preloadStart||0,preloadEnd:t.preloadEnd||0,apStart:t.requestAPStart||0,apEnd:t.requestAPEnd||0,suaEnd:t.requestSUAEnd||0,beforeConnect:t.beforeConnect||0,peerReceiver:t.peerReceiver||0,ice:t.iceConnectionEnd||0,pc:t.peerConnectionEnd||0,signalConnected:t.signalConnected||0,joinReq:t.joinReq||0,joinRes:t.joinRep||0,userJoinNotify:i.userJoinNotify||0,videoAddNotify:i.videoAddNotify||0,subscribeStart:i.subscribeStart||0,subscribeEnd:i.subscribeEnd||0,firstReceived:i.firstReceived||0,firstDecoded:i.firstDecoded||0,firstPreRender:a||0,firstRender:n?Math.max(l,n):Math.max(l,s),playStart:i.playStart||0,playEnd:i.playEnd||0,isPreSub:!(!e._videoSSRC||!this.isPreSubScribe(e._videoSSRC)),isPrePc:this.isPreallocation(),isPreInstantVideo:b(this.store),firstReceivedEncodedFrame:i.firstReceivedEncodedFrame||0,frameType:i.frameType||"",rtpTimestamp:i.rtpTimestamp||0,framePayloadType:i.framePayloadType||0,frameDataLength:i.frameDataLength||0,mimeType:i.mimeType||"",sdpEndPoint:this._p2pBySDPEndPoint};G.firstXLAPeerFirstVideoFrame(this.store.sessionId,h)}}reportVideoFirstFrameDecoded(e,t,i,n){const o=Array.from(this.remoteUserMap.keys()).find((t=>t._videoSSRC===e));if(o){n||this.store.subscribe(o.uid,"video",void 0,void 0,void 0,void 0,Date.now());const s=this.store.keyMetrics,a=s.subscribe.find((e=>e.userId===o.uid&&"video"===e.type));G.firstRemoteVideoDecode(this.store.sessionId,J.FIRST_VIDEO_DECODE,X.FIRST_VIDEO_DECODE,{peer:o._uintid,videowidth:t,videoheight:i,subscribeElapse:Ys.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId,apEnd:s.requestAPEnd||0,apStart:s.requestAPStart||0,joinGwEnd:s.joinGatewayEnd||0,joinGwStart:s.joinGatewayStart||0,pcEnd:s.peerConnectionEnd||0,pcStart:s.peerConnectionStart||0,subscriberEnd:(null==a?void 0:a.subscribeEnd)||0,subscriberStart:(null==a?void 0:a.subscribeStart)||0,videoAddNotify:(null==a?void 0:a.streamAdded)||0,state:n?1:0,firstFrame:(null==a?void 0:a.firstFrame)||0})}}async remoteMediaSsrcChanged(e,t,i){if(!this.connection)return!1;const n=this.remoteUserMap.get(e);if(!n)return!1;const o=n.get(t);if(!o)return!1;const s=await this.connection.getRemoteSSRC(o);return void 0!==s&&s!==i}unbindRtpTransceiver(){0!==this.localTrackMap.size&&Array.from(this.localTrackMap.entries()).forEach((e=>{let t=Mi(e,2),i=t[0],n=t[1].track;i===Tn.LocalVideoLowTrack?n._updateRtpTransceiver(void 0,w.LOW_STREAM):n._updateRtpTransceiver(void 0)}))}}).prototype,"startP2PConnection",[nr],Object.getOwnPropertyDescriptor(tr.prototype,"startP2PConnection"),tr.prototype),yi(tr.prototype,"connect",[nr],Object.getOwnPropertyDescriptor(tr.prototype,"connect"),tr.prototype),yi(tr.prototype,"updateRemoteRTPCapabilities",[nr],Object.getOwnPropertyDescriptor(tr.prototype,"updateRemoteRTPCapabilities"),tr.prototype),yi(tr.prototype,"publishDataChannel",[nr],Object.getOwnPropertyDescriptor(tr.prototype,"publishDataChannel"),tr.prototype),yi(tr.prototype,"unpublish",[nr],Object.getOwnPropertyDescriptor(tr.prototype,"unpublish"),tr.prototype),yi(tr.prototype,"unpublishDataChannel",[nr],Object.getOwnPropertyDescriptor(tr.prototype,"unpublishDataChannel"),tr.prototype),yi(tr.prototype,"unpublishLowStream",[nr],Object.getOwnPropertyDescriptor(tr.prototype,"unpublishLowStream"),tr.prototype),yi(tr.prototype,"subscribeDataChannel",[nr],Object.getOwnPropertyDescriptor(tr.prototype,"subscribeDataChannel"),tr.prototype),yi(tr.prototype,"subscribe",[nr],Object.getOwnPropertyDescriptor(tr.prototype,"subscribe"),tr.prototype),yi(tr.prototype,"massSubscribe",[nr],Object.getOwnPropertyDescriptor(tr.prototype,"massSubscribe"),tr.prototype),yi(tr.prototype,"unsubscribe",[nr],Object.getOwnPropertyDescriptor(tr.prototype,"unsubscribe"),tr.prototype),yi(tr.prototype,"unsubscribeDataChannel",[nr],Object.getOwnPropertyDescriptor(tr.prototype,"unsubscribeDataChannel"),tr.prototype),yi(tr.prototype,"massUnsubscribe",[nr],Object.getOwnPropertyDescriptor(tr.prototype,"massUnsubscribe"),tr.prototype),yi(tr.prototype,"muteRemote",[nr],Object.getOwnPropertyDescriptor(tr.prototype,"muteRemote"),tr.prototype),yi(tr.prototype,"unmuteRemote",[nr],Object.getOwnPropertyDescriptor(tr.prototype,"unmuteRemote"),tr.prototype),yi(tr.prototype,"hasRemoteMediaWithLock",[nr],Object.getOwnPropertyDescriptor(tr.prototype,"hasRemoteMediaWithLock"),tr.prototype),yi(tr.prototype,"disconnectForReconnect",[nr],Object.getOwnPropertyDescriptor(tr.prototype,"disconnectForReconnect"),tr.prototype),yi(tr.prototype,"updateBitrateLimit",[nr],Object.getOwnPropertyDescriptor(tr.prototype,"updateBitrateLimit"),tr.prototype),yi(tr.prototype,"remoteMediaSsrcChanged",[nr],Object.getOwnPropertyDescriptor(tr.prototype,"remoteMediaSsrcChanged"),tr.prototype),tr);function nr(e,t,i){const n=e[t];if("function"!=typeof n)throw new Error("Cannot use mutex on object property.");return i.value=async function(){const e=this.mutex,i=await e.lock("From P2PChannel.".concat(t));try{for(var o=arguments.length,s=new Array(o),a=0;a<o;a++)s[a]=arguments[a];return await n.apply(this,s)}finally{i()}},i}const or=Date.now(),sr=20,ar=new Map,rr=new Map;async function cr(e){const t=ar.get(e),i=Array.isArray(t)&&t[t.length-1],n=rr.get(e);if(!i)return void(n.isSyncing=!1);const o={uid:i.uid,payload:i.payload};0===n.firstRecvTs&&(n.firstRecvTs=i.recvTs,n.firstSendTs=i.sendTs);const s=i.sendTs-n.firstSendTs,a=s-(Date.now()-n.firstRecvTs);a>0&&(n.firstRecvTs=Date.now()-s);let r=i.mediaDelay+a;r<=0?(t.pop(),dr(i.context,o),r=0):r=Math.min(r,sr),setTimeout((()=>t.length&&cr(e)),r)}function dr(e,t){e.safeEmit(ft.STREAM_MESSAGE,t.uid,t.payload),e.onStreamMessage&&e.onStreamMessage(t)}function lr(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2?arguments[2]:void 0;if(!e.syncWithAudio)return dr(i,{uid:e.uid,payload:e.payload});const n="".concat(i.id,"-").concat(e.uid),o=ar.get(n)||[],s=o.findIndex((t=>e.sendTs>=t.sendTs)),a=ki(ki({},e),{},{context:i,mediaDelay:t,recvTs:Date.now()});-1===s?o.push(a):o.splice(s,0,a),ar.set(n,o);let r=!1;var c;rr.has(n)?r=!(null===(c=rr.get(n))||void 0===c||!c.isSyncing):rr.set(n,{isSyncing:r,firstRecvTs:0,firstSendTs:0});r||cr(n)}const hr=Pe().name;async function ur(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const i=G.reportApiInvoke(null,{tag:je.TRACER,name:Be.CHECK_VIDEO_TRACK_IS_ACTIVE,options:[t]});if(!(e instanceof n||e instanceof v)){const e=new j(ne.INVALID_TRACK,"the parameter is not a video track");return i.onError(e),e.throw()}t&&t<1e3&&(t=1e3);const o=e instanceof n?e.getTrackLabel():"remote_track",s=e.getMediaStreamTrack(!0),a=document.createElement("video");a.style.width="1px",a.style.height="1px",a.setAttribute("muted",""),a.muted=!0,a.setAttribute("playsinline",""),a.controls=!1,(qe()||Ct())&&(a.style.opacity="0.01",a.style.position="fixed",a.style.left="0",a.style.top="0",document.body.appendChild(a)),a.srcObject=new MediaStream([s]),a.play();const r=document.createElement("canvas");r.width=160,r.height=120;let c=0,d=0;try{const e=Date.now();c=await function(e,t,i,n){let o,s=0,a=null;return new Promise(((r,c)=>{function d(){s>n&&o&&(o(),r(s));const t=i.getContext("2d");if(!t){const e=new j(ne.UNEXPECTED_ERROR,"can not get canvas 2d context.");return B.error(e.toString()),void c(e)}t.drawImage(e,0,0,160,120);const d=t.getImageData(0,0,i.width,i.height),l=Math.floor(d.data.length/3);if(a){for(let e=0;e<l;e+=3)if(d.data[e]!==a[e])return s+=1,void(a=d.data);a=d.data}else a=d.data}setTimeout((()=>{o&&(o(),r(s))}),t),o=C((()=>{d()}),30)}))}(a,t,r,4),d=Date.now()-e}catch(e){throw i.onError(e),e}hr===Le.SAFARI&&(a.pause(),a.remove()),a.srcObject=null;const l=c>4,h={duration:d,changedPicNum:c,deviceLabel:o,result:l};return B.info("[track-".concat(e.getTrackId(),"] check video track active completed. ").concat(JSON.stringify(h))),i.onSuccess(h),l}async function _r(e){let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const n=G.reportApiInvoke(null,{tag:je.TRACER,name:Be.CHECK_AUDIO_TRACK_IS_ACTIVE,options:[i]});if(!(e instanceof t||e instanceof I)){const e=new j(ne.INVALID_TRACK,"the parameter is not a audio track");return n.onError(e),e.throw()}i&&i<1e3&&(i=1e3);const o=e instanceof t?e.getTrackLabel():"remote_track",s=e.getVolumeLevel();let a=s,r=s;const c=Date.now();return new Promise((t=>{const s=setInterval((()=>{const d=e.getVolumeLevel();a=d>a?d:a,r=d<r?d:r;const l=a-r>1e-4,h=Date.now()-c;if(l||h>i){clearInterval(s);const i=l,r={duration:h,deviceLabel:o,maxVolumeLevel:a,result:i};B.info("[track-".concat(e.getTrackId(),"] check audio track active completed. ").concat(JSON.stringify(r))),n.onSuccess(r),t(i)}}),200)}))}const pr="websdk_ng_cache_parameter",Er=ce("MAX_PRELOAD_ASYNC_LENGTH"),mr=1e4,Sr=new Map,fr=[];let Cr=null,Rr=0,Tr=0;const gr=new Map,Ir=new Uint8Array([241,141,127,212,103,139,200,225,251,157,127,139,143,2,22,163]),vr=function(e,t){const i=[];let n=0;const o=async()=>{const e=i.shift();e&&await e(),i.length>0&&n<t?o():n--};return async function(){for(var s=arguments.length,a=new Array(s),r=0;r<s;r++)a[r]=arguments[r];return new Promise((async(s,r)=>{i.push((async()=>{try{const t=await e(...a);s(t)}catch(e){r(e)}})),n<t&&(n++,o())}))}}(br,Er),Ar=ui.CancelToken.source();class yr{constructor(){this._audioContext=null}createMuteAudioTrack(){this._audioContext=new AudioContext;const e=this._audioContext.sampleRate,t=10*e,i=this._audioContext.createBuffer(2,t,e),n=this._audioContext.createBufferSource();n.buffer=i;const o=this._audioContext.createMediaStreamDestination();n.connect(o),n.start();return o.stream.getAudioTracks()[0]}close(){this._audioContext&&(this._audioContext.close(),this._audioContext=null)}}async function Nr(e,t,i,n){return br(e,t,i,n)}async function wr(e,t,i,n){let o={state:"unavailable"};await br(e,t,i,n);const s=await Or({appId:e,cname:t,token:i||e,uid:n,cloudProxyServer:"disabled"});if(!s)return o;await Pr(s);const a=Lc({mode:"rtc",codec:"vp8"});let r;try{r=await a.join(e,t,i,n,{networkQualityProbe:!0})}catch(e){return o}const c=new yr,d=c.createMuteAudioTrack(),l=await O({mediaStreamTrack:d});await a.publish([l]);const h=await new Promise(((e,t)=>{const i=setTimeout((()=>{clearTimeout(i),e([!0,null,"audio"])}),5e3);a.on("user-published",(async(t,n)=>{t.uid===r&&(clearTimeout(i),e([!1,t,n]))}))})),u=Mi(h,3),_=u[0],p=u[1],E=u[2];if(_||!p)return await a.unpublish([l]),await a.leave(),l.close(),c.close(),o;await a.subscribe(p,E),await new Promise(((e,t)=>{const i=setTimeout((()=>{clearTimeout(i),e(null)}),5e3)}));const m=a.getRTCStats(),S=a.getLocalAudioStats(),f=m.RTT,C=S.sendJitterMs,R=S.currentPacketLossRate;return o={state:"complete",rtt:f,packetLossRate:R,jitter:C,networkQuality:((e,t,i)=>{let n=1;if(i>0){let e=Math.log(100*i)/Math.log(2)+1;e=Math.min(5,Math.max(0,e)),n=1-e/5}let o=1;if(e>0){let t=Math.log(e/40)/Math.log(2)+1;t=Math.min(5,Math.max(0,t)),o=1-t/5}let s=1;if(t>0){let e=Math.log(t/10)/Math.log(2.5)+1;e=Math.min(5,Math.max(0,e)),s=1-e/5}const a=.5*n+.3*o+.2*s;let r=0;return r=a>=.8?1:a>=.6?2:a>=.4?3:a>=.2?4:5,r})(f,C,R)},await a.unsubscribe(p),await a.unpublish([l]),await a.leave(),l.close(),c.close(),await Pr(s),o}async function br(e,t,i,n,s,a,r){try{if(!ce("ENABLE_PRELOAD"))return;if(!o().supportWebCrypto)return void Rt((()=>{B.warn("Your browser does not support preloading, this feature be run in a secure environment")}),"preload_webcrypto_not_supported");if(!i&&null!==i)throw new me(ne.INVALID_PARAMS,"Invalid token: ".concat(i,". If you don not use token, set it to null"));i&&se(i,"token",1,2047),se(e,"appid",1,2047),Qi(t),n&&zi(n);const d=Tt();B.debug("preload channel ".concat(t,", uid is ").concat(n));const l={appId:e,cname:t,token:i||e,uid:"string"!=typeof n?n:null,sid:d,proxyServer:s,role:r};let h,u;if("string"==typeof n){l.stringUid=n;var c=Mi(await Promise.all([vs(n,{sid:d,appId:e},Ar.token),ys(ki(ki({},l),{},{token:i||e,uid:0}),Ar.token)]),2);u=c[0],h=c[1],l.uid=u.uid,h.gatewayInfo.uid=l.uid,h.gatewayInfo.res.uid=l.uid}else a&&(l.stringUid=a),h=await ys(l,Ar.token);const _={sid:d,appId:e,cname:t,token:i||e,uid:l.stringUid||n,intUid:l.uid||h.gatewayInfo.uid,stringUid:l.stringUid,ts:Date.now(),sua:u,ap:h};await Pr(_),Rr++}catch(e){throw Tr++,function(e){Cr||(Cr=window.setTimeout((()=>{let t="";gr.forEach(((e,i)=>{t+="".concat(i,": ").concat(e," ;")})),G.reportApiInvoke(null,{name:Be.PRELOAD,options:{success:Rr,failed:Tr,err:t}}).onError(e),Rr=0,Tr=0,gr.clear(),Cr=null}),mr));const t=gr.get(e.code)||0;gr.set(e.code,t+1)}(e),e}}async function Or(e){try{if(ce("AP_REQUEST_DETAIL")||ce("ENABLE_ROLE_SELECT_EDGE")||ce("ENABLE_JOIN_V4"))return;const t=Dr(e);if(!t||"disabled"!==e.cloudProxyServer)return;const i=await async function(e,t){try{const i=await window.crypto.subtle.importKey("raw",It(t),"AES-GCM",!1,["decrypt"]),n=await window.crypto.subtle.decrypt({name:"AES-GCM",iv:Ir},i,vt(e));return JSON.parse(window.atob(At(new Uint8Array(n))))}catch(e){return}}(t,e.token||e.appId);if(!i)return;if(!function(e,t){const i=e.cname===t.cname&&e.appId===t.appId&&e.token===t.token;if(!i)return!1;return t.stringUid?e.stringUid===t.stringUid:"number"==typeof t.uid?e.uid===t.uid:e.uid==t.uid}(i,e))return;if(i&&Date.now()-i.ts<ce("AP_CACHE_LIFETIME"))return i}catch(e){B.warn("Error get preloadInfo",e.message)}}function Dr(e){let t;try{if(t=Ur(pr),!t)return;const i=JSON.parse(t),n=xr(e),o=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1}(i,(e=>n in e));if(-1===o)return;const s=i.splice(o,1)[0];return Vr(pr,JSON.stringify(i)),s[n]}catch(e){B.warn("Error delete preload info: ".concat(t),e.message),Vr(pr,"")}}async function Pr(e){let t;try{e.uid&&Dr({appId:e.appId,cname:e.cname,token:e.token,uid:e.uid,stringUid:e.stringUid});const i=xr(e),n=await async function(e,t){try{const i=await window.crypto.subtle.importKey("raw",It(t),"AES-GCM",!1,["encrypt"]),n=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:Ir},i,vt(window.btoa(JSON.stringify(e))));return At(new Uint8Array(n))}catch(e){return}}(e,e.token||e.appId);if(!n)return;t=Ur(pr);const o=t?JSON.parse(t):[];o.push({[i]:n}),o.length>ce("AP_CACHE_NUM")&&o.shift(),Vr(pr,JSON.stringify(o))}catch(e){B.warn("Error caching server parameters:",e.message),Vr(pr,"")}}function Lr(e){if(e){let t=Sr.get(e);t&&(window.clearTimeout(t),t=null,Sr.delete(e)),fr.includes(e)||"disabled"!==e.cloudProxyServer||fr.push(e)}if(Sr.size<ce("AP_CACHE_NUM")&&fr.length>0){const e=fr.shift();Sr.set(e,window.setTimeout((async()=>{const t=e.appId,i=e.cname,n=e.token,o=e.stringUid,s=e.uid,a=e.proxyServer,r=e.role;try{await vr(t,i,n,s,a,o,r),Sr.has(e)&&Lr(e)}catch(t){B.warn("update preload failed",t.message),kr(e)}}),ce("AP_UPDATE_INTERVAL")))}}function kr(e){const t=fr.indexOf(e);-1!==t&&fr.splice(t,1);let i=Sr.get(e);i&&(window.clearTimeout(i),i=null,Sr.delete(e),Lr())}function Mr(e,t){const i=e.sua,n=e.ap;t&&i&&G.reqUserAccount(e.sid,{lts:i.requestTime,elapse:i.elapse,success:!0,serverAddr:i.url,stringUid:t,uid:e.intUid,errorCode:null,extend:i.req}),G.reportResourceTiming(e.ap.url,e.sid),G.joinWebProxyAP(e.sid,{lts:n.requestTime,elapse:n.elapse,sucess:1,apServerAddr:n.url,turnServerAddrList:n.proxyInfo.addresses.map((e=>e.ip)).join(","),eventType:"disabled",unilbsServerIds:[ri.CHOOSE_SERVER,ri.CLOUD_PROXY_FALLBACK].toString()}),G.joinChooseServer(e.sid,{lts:n.requestTime,elapse:n.elapse,succ:!0,csAddr:n.url,opid:n.opid,serverList:n.gatewayInfo.gatewayAddrs.map((e=>e.address)),ec:null,cid:n.gatewayInfo.cid.toString(),uid:n.gatewayInfo.uid.toString(),csIp:n.gatewayInfo.csIp,unilbsServerIds:[ri.CHOOSE_SERVER].toString(),isHttp3:n.isHttp3})}function Ur(e){return window.atob(window.localStorage.getItem(e)||"")}function Vr(e,t){window.localStorage.setItem(e,window.btoa(t))}function xr(e){let t="".concat(e.appId,"_").concat(e.cname);return"string"==typeof e.uid&&(t+="_s_".concat(e.uid)),"number"==typeof e.uid&&(t+="_".concat(e.uid)),e.token&&(t+="_".concat(e.token)),gt(t)}const Fr={},Br={};function jr(e,t){let i,n,o;return t?(o=0<=(e>>>=0)&&e<256)&&(n=Br[e],n)?n:(i=Gr(e,0,!0),o&&(Br[e]=i),i):(o=-128<=(e|=0)&&e<128)&&(n=Fr[e],n)?n:(i=Gr(e,e<0?-1:0,!1),o&&(Fr[e]=i),i)}function Gr(e,t,i){return{low:0|e,high:0|t,unsigned:!!i}}var Wr,Hr,Kr,Yr,qr,Jr,Xr,Qr,zr,Zr,$r,ec,tc,ic,nc,oc,sc,ac,rc,cc,dc,lc,hc,uc,_c,pc,Ec,mc,Sc,fc,Cc,Rc,Tc,gc,Ic,vc,Ac,yc,Nc,wc,bc,Oc,Dc;jr(0,!0),jr(0),ue.setLogger(B);let Pc=(Wr=Q(),Hr=Q({argsMap:(e,t)=>{if(!Array.isArray(t)){if(!(t instanceof D))return[t];t=[t]}return t.map((e=>e?Object(e).toString():"null"))}}),Kr=Q({argsMap:(e,t)=>(t||(t=[]),Array.isArray(t)||t.trackMediaType!==P.DATA?(Array.isArray(t)||(t=[t]),t.map((e=>e.getTrackId()))):[t.getChannelId()])}),Yr=Q({argsMap:(e,t,i,n)=>["object"==typeof t?t.uid:t,i,n]}),qr=Q({argsMap:(e,t,i)=>[t,i]}),Jr=Q({argsMap:(e,t)=>t.map((e=>{let t=e.user,i=e.mediaType;return[null==t?void 0:t.uid,i]}))}),Xr=Q({argsMap:(e,t,i,n)=>["object"==typeof t?t.uid:t,i,n]}),Qr=Q({argsMap:(e,t)=>t.map((e=>{let t=e.user,i=e.mediaType;return{uid:null==t?void 0:t.uid,mediaType:i}}))}),zr=Q(),Zr=Q(),$r=Q(),ec=Q(),tc=Q(),ic=Q(),nc=Q(),oc=Q(),sc=Q(),ac=Q(),rc=Q(),cc=Q(),dc=Q(),lc=Q(),hc=Q(),uc=Q(),_c=Q({argsMap:(e,t)=>[t]}),pc=Q(),Ec=Q(),mc=Q(),Sc=Q(),fc=Q(),Cc=Q(),Rc=Q(),Tc=Q(),gc=Q({argsMap:(e,t)=>(Array.isArray(t)||(t=[t]),[JSON.stringify(t)])}),Ic=Q(),vc=Q(),Ac=Q(),yc=Q(),Nc=Q(),wc=Q(),bc=Q({reportResult:!0}),Oc=Q(),yi((Dc=class extends re{get connectionState(){return this._gateway.state}get remoteUsers(){return this._users}get localTracks(){return this._p2pChannel.getAllTracks(!0)}get uid(){return this._uid}get channelName(){return this._channelName}get localDataChannels(){return this._p2pChannel.getAllDataChannels()}get mode(){return this._config.mode}get role(){var e;return(null===(e=this._config)||void 0===e?void 0:e.role)||"audience"}get codec(){return this._config.codec}get audioCodec(){return this._config.audioCodec||"opus"}get isStringUID(){return!!this._joinInfo&&!!this._joinInfo.stringUid}get __className__(){return"Client"}constructor(e,t){let i;if(super(),this.store=void 0,this._uid=void 0,this._channelName=void 0,this._uintUid=void 0,this._users=[],this._config=void 0,this._clientId=void 0,this._appId=void 0,this._sessionId=null,this._key=void 0,this._rtmConfig={},this._joinInfo=void 0,this._gateway=void 0,this._statsCollector=void 0,this._configDistribute=void 0,this._leaveMutex=void 0,this._publishMutex=void 0,this._renewTokenMutex=void 0,this._subscribeMutex=void 0,this._encryptionMode="none",this._encryptionSecret=null,this._encryptionSalt=null,this._encryptDataStream=!1,this._encryptDataStreamKey=null,this._encryptDataStreamIv=null,this._proxyServer=void 0,this._turnServer={servers:[],mode:"auto"},this._cloudProxyServerMode="disabled",this._isDualStreamEnabled=!1,this._defaultStreamFallbackType=void 0,this._lowStreamParameter=void 0,this._streamFallbackTypeCacheMap=new Map,this._remoteStreamTypeCacheMap=new Map,this._axiosCancelSource=ui.CancelToken.source(),this._audioVolumeIndicationInterval=void 0,this._networkQualityInterval=void 0,this._userOfflineTimeout=void 0,this._streamRemovedTimeout=void 0,this._rteDetailInterval=void 0,this._liveTranscodeStreamingClient=void 0,this._liveRawStreamingClient=void 0,this._channelMediaRelayClient=void 0,this._networkQualitySensitivity="normal",this._p2pChannel=void 0,this._useLocalAccessPoint=!1,this._setLocalAPVersion=void 0,this._joinAndNotLeaveYet=!1,this._numberOfJoinCount=0,this._joinResponse=null,this._remoteDefaultVideoStreamType=void 0,this._inspect=void 0,this._moderation=void 0,this._license=void 0,this._pendingPublishedUsers=[],this.ntpAlignErrorCount=0,this.remoteInboundOffset=0,this._peerConnectionState=void 0,this._pendingRtpCapabilityChange=void 0,this._fallbackServerInfo=void 0,this._dualStreamMode=void 0,this._handleLocalTrackEnable=(e,t,i)=>{this.publish(e,!1).then(t).catch(i)},this._handleLocalTrackDisable=(e,t,i)=>{this.unpublish(e).then(t).catch(i)},this._handleUserOnline=e=>{if(ce("BLOCK_LOCAL_CLIENT")&&Ii(e.uid,this.channelName))return void B.debug("[".concat(e.uid,"] will be ignored in local"));this.isStringUID&&"string"!=typeof e.uid&&B.error("[".concat(this._clientId,"] StringUID is Mixed with UintUID"));const t=this._users.find((t=>t.uid===e.uid));if(t)t._trust_in_room_=!0,t._is_pre_created&&(t._is_pre_created=!1,this.safeEmit(ft.USER_JOINED,t));else{const t=new Qs(e.uid,e.uint_id||e.uid);this._users.push(t),B.debug("[".concat(this._clientId,"] user online"),e.uid),this.store.firstVideoFrameDecoded(t.uid,{userJoinNotify:Date.now()}),this.safeEmit(ft.USER_JOINED,t)}},this._handleUserOffline=e=>{if(ce("BLOCK_LOCAL_CLIENT")&&Ii(e.uid,this.channelName))return;const t=this._users.find((t=>t.uid===e.uid));t&&(this._handleRemoveStream(e),this._handleRemoveDataChannels(e),t._audio_pre_subscribed||t._video_pre_subscribed?t._is_pre_created=!0:Nt(this._users,t),this._remoteStreamTypeCacheMap.delete(t.uid),this._streamFallbackTypeCacheMap.delete(t.uid),B.debug("[".concat(this._clientId,"] user offline"),e.uid,"reason:",e.reason),this.safeEmit(ft.USER_LEAVED,t,e.reason))},this._handleAddAudioOrVideoStream=(e,t,i,n,o,s,a,r)=>{if(ce("BLOCK_LOCAL_CLIENT")&&Ii(t,this.channelName))return;const c=this._users.find((e=>e.uid===t));if(!c)return void B.error("[".concat(this._clientId,"] can not find target user!(on_add_stream)"));B.debug("[".concat(this._clientId,"] stream added with uid ").concat(t,", type ").concat(e)),this.store.subscribe(c.uid,e,void 0,void 0,void 0,Date.now()),"video"===e&&this.store.firstVideoFrameDecoded(c.uid,{videoAddNotify:Date.now()});const d="audio"===e?c.hasAudio:c.hasVideo;c._uintid||(c._uintid=s||t),"audio"===e?c._trust_audio_stream_added_state_=!0:c._trust_video_stream_added_state_=!0,"audio"===e?(c._audio_added_=!0,void 0!==i&&(c._audioSSRC=i),void 0!==n&&(c._cname=n),a&&(c._audioOrtc=a)):(c._video_added_=!0,void 0!==i&&(c._videoSSRC=i),void 0!==n&&(c._cname=n),void 0!==r&&(c._rtxSsrcId=r),a&&(c._videoOrtc=a)),("audio"===e?c.hasAudio:c.hasVideo)&&!d&&(B.info("[".concat(this._clientId,"] remote user ").concat(c.uid," published ").concat(e)),this.safeEmit(ft.USER_PUBLISHED,c,e)),"video"===e?G.onGatewayStream(this._sessionId,J.ON_ADD_VIDEO_STREAM,X.ON_ADD_VIDEO_STREAM,{peer:s||t,ssrc:c._videoSSRC}):G.onGatewayStream(this._sessionId,J.ON_ADD_AUDIO_STREAM,X.ON_ADD_AUDIO_STREAM,{peer:s||t,ssrc:c._audioSSRC}),this._p2pChannel.remoteMediaSsrcChanged(c,e,i).then((t=>{if(t&&(B.debug("[".concat(this._clientId,"] resubscribe ").concat(e," for user ").concat(c.uid," after rejoin because SSRC id changed.")),this._p2pChannel instanceof ir))return this._p2pChannel.unsubscribe(c,e,!0).then((()=>this._subscribe(c,e,!0).catch((e=>{B.error("[".concat(this._clientId,"] resubscribe error"),e.toString())}))))})),this._p2pChannel.hasPendingRemoteMedia(c,e)&&(B.debug("[".concat(this._clientId,"] resubscribe ").concat(e," for user ").concat(c.uid," after reconnect.")),this._subscribe(c,e,!0).catch((e=>{B.error("[".concat(this._clientId,"] resubscribe error"),e.toString())})));const l=this._getEncodingName(o);"video"===e&&("unknown"===l?this.safeEmit(ft.AV1_DECODABLE_RESULT,!1):qe()||wt()||(null==l?void 0:l.toLocaleLowerCase())!==tt.av1||Cs().then((e=>{ce("FLS_ENABLE_AV1_DECODE_DETECT")&&this.safeEmit(ft.AV1_DECODABLE_RESULT,e),e||this._gateway.downgradeCodec(l)})))},this._handleRemoveStream=e=>{if(ce("BLOCK_LOCAL_CLIENT")&&Ii(e.uid,this.channelName))return;const t=this._users.find((t=>t.uid===e.uid));if(!t)return void B.warning("[".concat(this._clientId,"] can not find target user!(on_remove_stream)"));B.debug("[".concat(this._clientId,"] stream removed with uid ").concat(e.uid));let i=()=>{};t.hasAudio&&t.hasVideo?i=()=>{B.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished audio track")),this.safeEmit(ft.USER_UNPUBLISHED,t,"audio"),B.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished video track")),this.safeEmit(ft.USER_UNPUBLISHED,t,"video")}:t.hasVideo?i=()=>{B.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished video track")),this.safeEmit(ft.USER_UNPUBLISHED,t,"video")}:t.hasAudio&&(i=()=>{B.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished audio track")),this.safeEmit(ft.USER_UNPUBLISHED,t,"audio")}),t._video_pre_subscribed||t._audio_pre_subscribed||(t._trust_audio_stream_added_state_=!0,t._trust_video_stream_added_state_=!0,t._audio_added_=!1,t._video_added_=!1,this._p2pChannel instanceof ir&&this._p2pChannel.unsubscribe(t).then((e=>{if(e)return this._gateway.unsubscribe(e,t.uid)})),t._audioSSRC=void 0,t._videoSSRC=void 0,t._audioOrtc=void 0,t._videoOrtc=void 0,t._rtxSsrcId=void 0),G.onGatewayStream(this._sessionId,J.ON_REMOVE_STREAM,X.ON_REMOVE_STREAM,{peer:e.uint_id||e.uid}),i()},this._handleSetStreamLocalEnable=(e,t,i)=>{if(ce("BLOCK_LOCAL_CLIENT")&&Ii(t,this.channelName))return;const n=this._users.find((e=>e.uid===t));if(!n)return void B.error("[".concat(this._clientId,"] can not find target user!(disable_local)"));B.debug("[".concat(this._clientId,"] local ").concat(e," ").concat(i?"enabled":"disabled"," with uid ").concat(t));const o="audio"===e?n.hasAudio:n.hasVideo;if("audio"===e){n._trust_audio_enabled_state_=!0;const e=n._audio_enabled_;if(n._audio_enabled_=i,n._audio_enabled_===e)return;{const e=n._audio_enabled_?"enable-local-audio":"disable-local-audio";B.debug("[".concat(this._clientId,"] user-info-updated, uid: ").concat(t,", msg: ").concat(e)),this.safeEmit(ft.USER_INFO_UPDATED,t,e)}}else{n._trust_video_enabled_state_=!0;const e=n._video_enabled_;if(n._video_enabled_=i,n._video_enabled_===e)return;{const e=n._video_enabled_?"enable-local-video":"disable-local-video";B.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(t,", msg: ").concat(e)),this.safeEmit(ft.USER_INFO_UPDATED,t,e)}}const s="audio"===e?n.hasAudio:n.hasVideo;return o!==s?!o&&s?(B.info("[".concat(this._clientId,"] remote user ").concat(t," published ").concat(e)),void this.safeEmit(ft.USER_PUBLISHED,n,e)):("video"===e&&n._videoTrack&&n._videoTrack._destroy(),"audio"===e&&n._audioTrack,this._p2pChannel.muteRemote(n,e),B.info("[".concat(this._clientId,"] remote user ").concat(t," unpublished ").concat(e)),void this.safeEmit(ft.USER_UNPUBLISHED,n,e)):void 0},this._handleMuteStream=(e,t,i)=>{if(ce("BLOCK_LOCAL_CLIENT")&&Ii(e,this.channelName))return;B.debug("[".concat(this._clientId,"] receive mute message"),e,t,i);const n=this._users.find((t=>t.uid===e));if(!n)return void B.warning("[".concat(this._clientId,"] can not find remote user, ignore mute event, uid: ").concat(e));const o="audio"===t?n.hasAudio:n.hasVideo;if("audio"===t){n._trust_audio_mute_state_=!0;const t=n._audio_muted_;if(n._audio_muted_=i,n._audio_muted_===t)return;{const t=n._audio_muted_?"mute-audio":"unmute-audio";B.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(e,", msg: ").concat(t)),this.safeEmit(ft.USER_INFO_UPDATED,e,t)}}else{n._trust_video_mute_state_=!0;const t=n._video_muted_;if(n._video_muted_=i,n._video_muted_===t)return;{const t=n._video_muted_?"mute-video":"unmute-video";B.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(e,", msg: ").concat(t)),this.safeEmit(ft.USER_INFO_UPDATED,e,t)}}const s="audio"===t?n.hasAudio:n.hasVideo;if(o!==s){if(!o&&s){return("audio"===t?n._audioSSRC:n._videoSSRC)?(B.info("[".concat(this._clientId,"] remote user ").concat(e," published ").concat(t)),void this.safeEmit(ft.USER_PUBLISHED,n,t)):void B.warning("[".concat(this._clientId,"] remote user ").concat(e," receive ").concat(t," unmute message before add stream message, ").concat(t," SSRC doesn't exist yet."))}"video"===t&&n._videoTrack&&!n._video_pre_subscribed&&n._videoTrack._destroy(),"audio"===t&&n._audioTrack,this._p2pChannel.muteRemote(n,t),B.info("[".concat(this._clientId,"] remote user ").concat(e," unpublished ").concat(t)),this.safeEmit(ft.USER_UNPUBLISHED,n,t)}},this._handleP2PLost=async e=>{B.debug("[".concat(this._clientId,"] receive p2p lost"),e),parseInt(e.p2pid,10)===this.store.p2pId?"isPreallocation"in this._p2pChannel&&this._p2pChannel.isPreallocation()?this._gateway.reconnect("tryNext"):await this._p2pChannel.requestReconnect():B.warning("[".concat(this._clientId,"] P2PLost stream not found"),e)},this._handleTokenWillExpire=()=>{B.debug("[".concat(this._clientId,"] received message onTokenPrivilegeWillExpire")),this.safeEmit(ft.ON_TOKEN_PRIVILEGE_WILL_EXPIRE)},this._handleBeforeUnload=e=>{"beforeunload"===e.type&&void 0!==e.returnValue&&""!==e.returnValue||(this.leave(),B.info("[".concat(this._clientId,"] auto leave onbeforeunload or pagehide")))},this._handleUpdateNetworkQuality=()=>{if("normal"===this._networkQualitySensitivity)return;if(navigator&&void 0!==navigator.onLine&&!navigator.onLine)return void this.safeEmit(ft.NETWORK_QUALITY,{downlinkNetworkQuality:6,uplinkNetworkQuality:6});const e={downlinkNetworkQuality:0,uplinkNetworkQuality:0};e.uplinkNetworkQuality=this._p2pChannel.getUplinkNetworkQuality(),e.downlinkNetworkQuality=this._p2pChannel.getDownlinkNetworkQuality(),this.safeEmit(ft.NETWORK_QUALITY,e)},this._handleP2PAddAudioOrVideoStream=(e,t,i,n)=>{const o=this._users.find((e=>e.uid===t));if(!o)return void B.error("[".concat(this._clientId,"] can not find target user!(on_add_stream)"));B.debug("[".concat(this._clientId,"] stream added with uid ").concat(t,", type ").concat(e)),this.store.subscribe(o.uid,e,void 0,void 0,void 0,Date.now());const s="audio"===e?o.hasAudio:o.hasVideo;"audio"===e?o._trust_audio_stream_added_state_=!0:o._trust_video_stream_added_state_=!0,"audio"===e?(o._audio_added_=!0,void 0!==i&&(o._audioSSRC=i),void 0!==n&&(o._audioMid=n)):(o._video_added_=!0,void 0!==i&&(o._videoSSRC=i),void 0!==n&&(o._videoMid=n)),("audio"===e?o.hasAudio:o.hasVideo)&&!s&&(B.info("[".concat(this._clientId,"] remote user ").concat(o.uid," published ").concat(e)),this.safeEmit(ft.USER_PUBLISHED,o,e)),this._p2pChannel.hasPendingRemoteMedia(o,e)&&(B.debug("[".concat(this._clientId,"] resubscribe ").concat(e," for user ").concat(o.uid," after reconnect.")),this._subscribe(o,e,!0).catch((e=>{B.error("[".concat(this._clientId,"] resubscribe error"),e.toString())})))},this._config=e,this._clientId=t||ve(5,"client-"),this.store=new bt(e.codec,e.audioCodec,e.mode,this._clientId,1===ce("SIGNAL_CHANNEL")),this._leaveMutex=new ue("client-leave",this._clientId),this._publishMutex=new ue("client-publish",this._clientId),this._renewTokenMutex=new ue("client-renewtoken",this._clientId),this._subscribeMutex=new ue("client-subscribe",this._clientId),this.store.clientCreated(),e.proxyServer&&this.setProxyServer(e.proxyServer,!0),e.turnServer&&this.setTurnServer(e.turnServer,!0),B.info("[".concat(this._clientId,"] Initializing AgoraRTC client v").concat(He," build: ").concat(Ot,", mode: ").concat(this.mode,", codec: ").concat(this.codec)),e.clientRoleOptions)try{Dt(e.clientRoleOptions),i=Object.assign({},e.clientRoleOptions)}catch(e){B.warning("[".concat(this._clientId,"] ").concat(e.toString()))}var o;this._statsCollector=new qs(this.store),this._statsCollector.onStatsException=(e,t,i)=>{B.warn("[".concat(this._clientId,"] receive exception msg, code: ").concat(e,", msg: ").concat(t,", uid: ").concat(i)),e===Ks.VIDEO_ENCODE_FAILED&&this.localTracks.forEach((e=>{e instanceof u&&ce("ENABLE_ENCODE_EXCEPTION")&&e.findClosestProfile()})),this.safeEmit(ft.EXCEPTION,{code:e,msg:t,uid:i})},this._statsCollector.onUploadPublishDuration=(e,t,i,n)=>{const o=this._users.find((t=>t.uid===e));if(o){this.store.keyMetrics&&(this.store.firstVideoFrameDecoded(o.uid,{peerPublishDuration:i,peerPubStatusMs:Date.now()}),this._p2pChannel.reportVideoFirstFrameRender(o)),G.peerPublishStatus(this._sessionId,{subscribeElapse:n,audioPublishDuration:t,videoPublishDuration:i,peer:o._uintid})}},this._statsCollector.onVideoCodecChanged=e=>{if(ce("VIDEO_STANDARD_BITRATE_VERSION")&&("av1"===e||"h265"===e||"h264"===e)){const t=this.localTracks.find((e=>e instanceof n));t&&1!==t._saveEncodeBitrateRatio&&t.setSaveEncodeBitrateRatio("h264"===e?ce("BASELINE_MORE_H264_BITRATE_RATIO"):void 0)}},this.store.useP2P="p2p"===e.mode,this._gateway=new Ko(this.store,{clientId:this._clientId,mode:this.mode,codec:this.codec,websocketRetryConfig:e.websocketRetryConfig||Ke,httpRetryConfig:e.httpRetryConfig||Ke,forceWaitGatewayResponse:void 0===e.forceWaitGatewayResponse||e.forceWaitGatewayResponse,statsCollector:this._statsCollector,role:e.role,clientRoleOptions:i}),this._configDistribute=new js(this._clientId,this.store),this.store.useP2P?(this._p2pChannel=(o={store:this.store,statsCollector:this._statsCollector},Bo("P2PChannel").create(o)),this._handleP2PEvents()):this._p2pChannel=new ir(this.store,this._statsCollector),this._handleP2PChannelEvents(),this._handleGatewayEvents(),this._handleGatewaySignalEvents()}async joinMeta(e,t,i,n,o){let s=!(arguments.length>5&&void 0!==arguments[5])||arguments[5],a=arguments.length>6&&void 0!==arguments[6]&&arguments[6];Ve("JOIN_GATEWAY_USE_443PORT_ONLY",s),Ve("JOIN_GATEWAY_USE_DUAL_DOMAIN",a);const r=this._gateway.signal.websocket;return r instanceof Kn&&(r.use443PortOnly=s,r.tryDoubleDomain=a),Pt("client.join",ce("JOIN_MAX_CONCURRENCY"),this.join.bind(this),e,t,i,n,o)}async join(e,t,i,n,s){B.scheduleUploadStart();const a=++this._numberOfJoinCount;this.store.joinStart(),n&&(this.store.uid=n);const r=Lt(),c=kt()?window.isSecureContext:"Browser Not Support";if(!kt()&&!r||!window.isSecureContext){const e="The website must be running in a secure context (About secure context: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts ), otherwise the media collection will be restricted by the browser";B.warning(e)}let d;G.setAppId(e);try{if(!i&&null!==i)throw new j(ne.INVALID_PARAMS,"Invalid token: ".concat(i,". If you don not use token, set it to null"));if(i&&se(i,"token",1,2047),se(e,"appid",1,2047),Qi(t),n&&zi(n),s)if("string"==typeof s)se(s,"optionalInfo",1,256),d=s;else{if("object"!=typeof s)throw new j(ne.INVALID_PARAMS,"Invalid options: options is not a string or object");{const e=s.autoSubscribe,t=s.enableInstantMuteRestore,i=s.networkQualityProbe,n=s.preSubOptions,o=s.autoReceiveAndPlayAudio;e&&(Mt(e,"autoSubscribe"),B.info("[".concat(this._clientId,"] join: autoSubscribe: ").concat(e)),this.store.autoSubscribe=e),void 0!==o&&(Mt(o,"autoReceiveAndPlayAudio"),B.info("[".concat(this._clientId,"] join: autoReceiveAndPlayAudio: ").concat(o)),o&&(this.store.autoSubscribe=!0,this.store.autoReceiveAndPlayAudio=!0)),t&&(Mt(t,"enableInstantMuteRestore"),B.info("[".concat(this._clientId,"] join: enableInstantMuteRestore: ").concat(t)),this.store.enableInstantMuteRestore=t),i&&(Mt(i,"networkQualityProbe"),B.info("[".concat(this._clientId,"] join: networkQualityProbe: ").concat(i)),this.store.networkQualityProbe=i),Array.isArray(n)&&(Ut(n,"preSubOptions"),n.forEach((e=>{zi(e.uid),Vt(e.element,"element")})),B.info("[".concat(this._clientId,"] join: preSubOptions: ").concat(n.map((e=>"".concat(e.uid,": ").concat("string"==typeof e.element?e.element:e.element.id))).join(","))),this.store.preSubOptions=n)}}}catch(o){throw G.reportApiInvoke(Tt(),{clientId:this._clientId,name:Be.JOIN,options:[e,t,i,n],states:{isHttps:r,isSecureContext:c},tag:je.TRACER}).onError(o),o}if(this._leaveMutex.isLocked){B.debug("[".concat(this._clientId,"] join: waiting leave operation"));(await this._leaveMutex.lock())(),B.debug("[".concat(this._clientId,"] join: continue"))}if(this._joinAndNotLeaveYet=!0,"DISCONNECTED"!==this.connectionState){const o=new j(ne.INVALID_OPERATION,"[".concat(this._clientId,"] Client already in connecting/connected state"));throw G.reportApiInvoke(Tt(),{clientId:this._clientId,name:Be.JOIN,options:[e,t,i,n],states:{isHttps:r,isSecureContext:c},tag:je.TRACER}).onError(o),o}const l=Bs(this._clientId);try{this._gateway.state="CONNECTING",this.store.preloadStart();const s=await Or({appId:e,cname:t,uid:n,stringUid:"string"==typeof n?n:void 0,token:i||e,cloudProxyServer:this._cloudProxyServerMode});if(this.store.preloadEnd(),!this._joinAndNotLeaveYet)throw new j(ne.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));const _=(null==s?void 0:s.sid)||Tt();B.info("[".concat(this._clientId,"] start join channel ").concat(t,", join number: ").concat(a)),this._sessionId||(this._sessionId=_,this.store.sessionId=this._sessionId);const p=G.reportApiInvoke(this._sessionId,{id:this._clientId,clientId:this._clientId,name:Be.JOIN,options:[e,t,i,n],states:{isHttps:r,isSecureContext:c},tag:je.TRACER}),E=ki(ki(ki({},this._rtmConfig),{},{role:this.role,clientId:this._clientId,appId:e,sid:this._sessionId,cname:t,uid:"string"!=typeof n?n:null,turnServer:this._turnServer,proxyServer:this._proxyServer,token:i||e,cloudProxyServer:this._cloudProxyServerMode,optionalInfo:d,license:this._license,useLocalAccessPoint:this._useLocalAccessPoint,preload:!!s},void 0!==this._remoteDefaultVideoStreamType&&{defaultVideoStream:this._remoteDefaultVideoStreamType}),{},{apRequestDetail:ce("AP_REQUEST_DETAIL")||void 0});if(this._useLocalAccessPoint&&(E.setLocalAPVersion=this._setLocalAPVersion),"string"==typeof n&&(E.stringUid=n,this._uintUid?(E.uid=this._uintUid,this._uintUid=void 0):E.uid=0),"none"!==this._encryptionMode&&this._encryptionSecret){if(E.aesmode=this._encryptionMode,E.aespassword=await xt(this._encryptionSecret),!this._joinAndNotLeaveYet)throw new j(ne.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));this._encryptionSalt&&(E.aessalt=this._encryptionSalt)}if(this._encryptDataStream&&("aes-128-gcm2"===this._encryptionMode||"aes-256-gcm2"===this._encryptionMode))if(this._encryptionSalt&&this._encryptionSecret)if(window.crypto.subtle){const e=new TextEncoder,t=ce("USE_PURE_ENCRYPTION_MASTER_KEY")?e.encode(E.appId+this._encryptionSecret+this._encryptionSecret):e.encode(E.appId+E.cname+this._encryptionSecret);this._encryptDataStreamIv=await Ft(this._encryptionMode,t,vt(this._encryptionSalt)),this._encryptDataStreamKey=await Bt(this._encryptionMode,t,vt(this._encryptionSalt))}else c?B.warning("[".concat(this._clientId,"] encrypt datastream must be running in a secure context, fallback to plain data stream")):B.warning("[".concat(this._clientId,"] current browser do not support WebCrypto ,fallback to plain data stream")),this._encryptDataStream=!1;else this._encryptDataStream=!1,B.debug("[".concat(this._clientId,"] no salt / secret, cannot support encrypt data stream, fallback to plain data stream"));this._startSession(this._sessionId,{channel:t,appId:e,stringUid:E.stringUid});const m=this._sessionId;setTimeout((()=>{"CONNECTING"===this.connectionState&&m===this._sessionId&&G.joinChannelTimeout(this._sessionId,5)}),5e3);try{let n,a;const r=E.cloudProxyServer;if(["proxy3","proxy4","proxy5"].includes(r)){const e=ce("PROXY_SERVER_TYPE3");Array.isArray(e)?E.proxyServer=e[0]:E.proxyServer=e}if(G.setProxyServer(E.proxyServer),B.setProxyServer(E.proxyServer),this.store.requestAPStart(),ce("ENABLE_JOIN_V4")&&"disabled"===E.cloudProxyServer)try{E.stringUid&&!E.uid&&(E.uid=await Is(E.stringUid,E,this._axiosCancelSource.token,this._config.httpRetryConfig||Ke,this.store).finally((()=>{this.store.requestSUAEnd()})),B.debug("[".concat(this._clientId,"] getUserAccount Success ").concat(E.stringUid," => ").concat(E.uid))),B.debug("[".concat(this._clientId,"] try use best first frame line"));const e=await this._p2pChannel.startP2PConnection({isPreallocation:!0});n=await gs(E,this._axiosCancelSource.token,this._config.httpRetryConfig||Ke,this.store,e),n.gatewayInfo.res.signalResponse&&(a=e.iceParameters),B.debug("[".concat(this._clientId,"] get serverInfo from sdp endpoint")),ce("ENABLE_SDP_ENDPOINT_LOG")&&B.debug("[".concat(this._clientId,"] serverInfo: "),n)}catch(e){n=void 0,B.debug("[".concat(this._clientId,"] join channel with sdp endpoint failed, fallback to normal join ap"),e)}if(n);else if(s){if(B.debug("[".concat(this._clientId,"] get serverInfo Success from Preload Cache ").concat(E.stringUid?", ".concat(E.stringUid," => ").concat(s.intUid):""," ")),E.stringUid&&!E.uid&&(E.uid=s.intUid),n={gatewayInfo:s.ap.gatewayInfo},ce("JOIN_WITH_FALLBACK_MEDIA_PROXY")&&"auto"===E.turnServer.mode)if(0===s.ap.proxyInfo.addresses.length)B.warning("no edge services in ap response of proxy fallback, will not set proxy in iceServers");else{const e=(await to(s.ap.proxyInfo,s.ap.gatewayInfo.uid)).map((e=>({turnServerURL:e.address,tcpport:e.tcpport||ye.tcpport,udpport:e.udpport||ye.udpport,username:e.username||ye.username,password:e.password||ye.password,forceturn:!1,security:!0})));E.turnServer={mode:"manual",servers:e}}Mr(s,E.stringUid)}else if(E.stringUid&&!E.uid){let e;var h=Mi(await Promise.all([Is(E.stringUid,E,this._axiosCancelSource.token,this._config.httpRetryConfig||Ke,this.store).finally((()=>{this.store.requestSUAEnd()})),Ts(E,this._axiosCancelSource.token,this._config.httpRetryConfig||Ke,!0,this.store).finally((()=>{this.store.requestAPEnd()}))]),2);e=h[0],n=h[1],B.debug("[".concat(this._clientId,"] getUserAccount Success ").concat(E.stringUid," => ").concat(e)),E.uid=e,n.gatewayInfo.uid=e,n.gatewayInfo.res.uid=e}else n=await Ts(E,this._axiosCancelSource.token,this._config.httpRetryConfig||Ke,!0,this.store);if(!this._joinAndNotLeaveYet)throw new j(ne.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));this.store.requestAPEnd(),setTimeout((()=>{this._configDistribute.startGetConfigDistribute(E,this._axiosCancelSource.token),this._configDistribute.on(_n.UPDATE_BITRATE_LIMIT,(e=>{this._p2pChannel.updateBitrateLimit(e)})),this._configDistribute.on(_n.UPDATE_CLIENT_ROLE_OPTIONS,(e=>{this._setClientRoleOptions(e)})),this._configDistribute.on(_n.UPDATE_REMOTE_VIDEO_STREAM_TYPE,(e=>{[0,1,4,5,6,7,8,9].includes(e)&&(this.remoteUsers.forEach((t=>{this._remoteStreamTypeCacheMap.get(t.uid)!==e&&this.setRemoteVideoStreamType(t.uid,e)})),this.setRemoteDefaultVideoStreamType(e))})),this._configDistribute.on(_n.FALLBACK_TO_HLS,(e=>{e&&this.safeEmit(ft.FALLBACK_TO_HLS,jt.CONFIG)})),this._configDistribute.on(_n.UPDATE_VOS_CONFIGURE,(e=>{this._gateway.setConfigure(e).catch((e=>{B.debug("[".concat(this._clientId,"] auto set vos config failed"),e)}))}))}),0),this._key=i||e;const c=n.gatewayInfo,d=E.uid?E.uid:c.uid;this._joinInfo=ki(ki({},E),{},{cid:c.cid,uid:d,vid:c.vid,apResponse:c.res,sdpEndpointLocalIceParameters:a,apGatewayAddress:c.apGatewayAddress,uni_lbs_ip:c.uni_lbs_ip,gatewayAddrs:c.gatewayAddrs,signalResponse:c.res.signalResponse}),this.store.intUid=d,this.store.cid=c.cid;const _=await this._joinGateway();if(!this._joinAndNotLeaveYet)throw new j(ne.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));p.onSuccess(_),this._appId=e,this._channelName=E.cname,this._uid=_,this.store.uid=_,setTimeout((()=>{this._networkQualityInterval&&window.clearInterval(this._networkQualityInterval),this._networkQualityInterval=window.setInterval(this._handleUpdateNetworkQuality,2e3),!qe()&&this.store.useDcSignal?(window.addEventListener("beforeunload",this._handleBeforeUnload),window.addEventListener("pagehide",this._handleBeforeUnload)):window.addEventListener(qe()?"beforeunload":"pagehide",this._handleBeforeUnload),this._statsCollector.startUpdateStats()}),0);const m=E.stringUid?"string uid: ".concat(E.stringUid,",uid: ").concat(E.uid):"uid: ".concat(this._uid);return B.info("[".concat(this._clientId,"] Joining channel success: channel: ").concat(t,",").concat(m)),this.store.joinEnd(),u=this,Ti.includes(u)||Ti.push(u),"disabled"===this._cloudProxyServerMode&&o().supportWebCrypto&&ce("ENABLE_PRELOAD")&&Lr(this._joinInfo),this._rteDetailInterval&&(window.clearInterval(this._rteDetailInterval),this._rteDetailInterval=void 0),this._sessionId&&G.reportRteDetail(this._sessionId),this._rteDetailInterval=window.setInterval((()=>{this._sessionId&&G.reportRteDetail(this._sessionId)}),ce("RTE_DETAIL_REPORT_INTERVAL")||6e4),l.markJoined(),_}catch(e){const t=Array.isArray(e)?e[0]:e;throw t&&t.code===ne.OPERATION_ABORTED?B.warning("[".concat(this._clientId,"] join number: ").concat(a,", Joining channel failed, rollback"),t):B.error("[".concat(this._clientId,"] join number: ").concat(a,", Joining channel failed, rollback"),t),t.code!==ne.OPERATION_ABORTED&&this._numberOfJoinCount===a&&(this._gateway.state="DISCONNECTED",this._reset()),p.onError(t),t}}finally{l.releaseIfNotJoined()}var u}async _joinGateway(){if(!this._joinInfo||!this._key)throw new j(ne.INVALID_OPERATION);try{return await this._gateway.join(this._joinInfo,this._key,!("disabled"!==this._joinInfo.cloudProxyServer||this._joinInfo.proxyServer||!ce("JOIN_WITH_FALLBACK_SIGNAL_PROXY")))}catch(e){if(e.code===ne.INIT_DATACHANNEL_TIMEOUT){if(this._gateway.leave(!0,ge.FALLBACK),B.debug("[".concat(this._clientId,"] join by datachannel timeout, fallback to websocket")),!this._joinInfo||!this._key)throw new j(ne.INVALID_OPERATION);return G.reportApiInvoke(this._sessionId,{clientId:this._clientId,name:Be.DATACHANNEL_FAILBACK,options:[this.store.clientId],tag:je.TRACER}).onSuccess(),await this._joinGateway()}throw e}}async leave(){B.info("[".concat(this._clientId,"] Leaving channel"));const e=()=>{!qe()&&this.store.useDcSignal?(window.addEventListener("beforeunload",this._handleBeforeUnload),window.addEventListener("pagehide",this._handleBeforeUnload)):window.addEventListener(qe()?"beforeunload":"pagehide",this._handleBeforeUnload),this._reset(),function(e){const t=Ti.indexOf(e);-1!==t&&Ti.splice(t,1)}(this),this._statsCollector.stopUpdateStats()};this.store.useDcSignal||e();const t=await this._leaveMutex.lock();if("DISCONNECTED"===this.connectionState)return B.info("[".concat(this._clientId,"] Leaving channel repeated, success")),t(),void Fs(this._clientId);await this._gateway.leave("CONNECTED"!==this.connectionState,ge.LEAVE),B.info("[".concat(this._clientId,"] Leaving channel success")),this._joinAndNotLeaveYet=!1,this.store.resetJoinChannelServiceRecords(),t(),this.store.useDcSignal&&e(),Fs(this._clientId)}async publish(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!Array.isArray(e)){if(!(e instanceof D))return this._publishDataChannel(e);e=[e]}if(0===e.length)throw new j(ne.INVALID_PARAMS,"param list is empty");const i=e;if("audience"===this._gateway.role)throw new j(ne.INVALID_OPERATION,"audience can not publish stream");for(const e of i){if(!(e instanceof D))throw new j(ne.INVALID_PARAMS,"parameter is not local track");if(!e._enabled&&t)throw new j(ne.TRACK_IS_DISABLED,"can not publish a disabled track: ".concat(e.getTrackId()))}B.info("[".concat(this._clientId,"] Publishing tracks, id ").concat(i.map((e=>"".concat(e.getTrackId()," ")))));const o=await this._publishMutex.lock();await this._configDistribute.awaitConfigDistributeComplete(),t&&i.forEach((e=>{const t=this._configDistribute.getBitrateLimit();e instanceof n&&t&&e.setBitrateLimit(t.uplink)}));try{await this._publishHighStream(i),B.info("[".concat(this._clientId,"] Publish success, id ").concat(i.map((e=>"".concat(e.getTrackId()," ")))))}catch(e){throw B.error("[".concat(this._clientId,"] publish error"),e.toString()),e}finally{o()}}async _publishDataChannel(e){if(null==e)throw new j(ne.INVALID_PARAMS,"parameter is not local track or datachannel config, config is ".concat(JSON.stringify(e)));yt(e.id,"id",0,65535,!0),Mt(e.ordered,"ordered"),se(e.metadata,"metadata",0,512),B.info("[".concat(this._clientId,"] Publishing datachannels, id ").concat(e.id));const t=await this._publishMutex.lock();try{if(-1!==this._p2pChannel.getAllDataChannels().findIndex((t=>t.id===e.id)))throw new j(ne.INVALID_PARAMS,"Invalid id: ".concat(e.id,". If you want to republish the datachannel, unpublish first"));if(!this._joinInfo||void 0===this._uid)throw new j(ne.INVALID_OPERATION,"Can't publish datachannel, haven't joined yet!");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new j(ne.INVALID_OPERATION,"can not publish datachannel in ".concat(this.connectionState," state"));if("auto"===this._turnServer.mode&&ce("FORCE_TURN")&&!ce("TURN_ENABLE_TCP")&&!ce("TURN_ENABLE_UDP"))throw new j(ne.UNEXPECTED_ERROR,"force TURN With No TURN Configuration");const i=function(e){return jo(e,!1)}(e),n=await this._p2pChannel.publishDataChannel([i]);if(n.length>0){if("number"!=typeof i._originDataChannelId)throw B.error("[".concat(this._clientId,"] can not publish with mediaType datachannel, cannot get RTCDatachannel id")),new j(ne.CREATE_DATACHANNEL_ERROR);try{await Promise.all(n.map((e=>this._uid&&this._gateway.publishDataChannel(this._uid,e,!0)))),await i._waitTillOpen()}catch(e){if(e.code!==ne.DISCONNECT_P2P)throw e}}return B.info("[".concat(this._clientId,"] Publish dataChannels success, id ").concat(i.id)),i}catch(e){throw B.error("[".concat(this._clientId,"] publish datachannels error"),e.toString()),e}finally{t()}}async unpublish(e){if(!this._joinInfo||void 0===this._uid)throw new j(ne.INVALID_OPERATION,"Can't unpublish stream, haven't joined yet!");let t=[];if(e)if(Array.isArray(e))t=e;else{if(!(e instanceof D))return this._unpublishDataChannel([e]);t=[e]}else this.store.useP2P||await this._unpublishDataChannel(),t=this._p2pChannel.getAllTracks(!0);B.info("[".concat(this._clientId,"] Unpublish tracks, tracks ").concat(t.map((e=>"".concat(e.getTrackId()," ")))," "));const i=await this._publishMutex.lock();try{if(this.store.useP2P){const e=await this._p2pChannel.unpublish(t);e&&await this._gateway.sendExtensionMessage(Dn.UNPUBLISH,{unpubMsg:e},!0)}else{const e=await this._p2pChannel.unpublish(t);e&&await this._gateway.unpublish(e,this._uid),B.info("[".concat(this._clientId,"] Unpublish success,tracks ").concat(t.map((e=>"".concat(e.getTrackId())))))}}catch(e){throw B.error("[".concat(this._clientId,"] unpublish error"),e.toString()),e}finally{i&&i()}}async _unpublishDataChannel(e){void 0!==e&&0!==e.length||(e=this._p2pChannel.getAllDataChannels()),B.info("[".concat(this._clientId,"] Unpublish datachannels, datachannels ").concat(e.map((e=>"".concat(e.id," ")))," "));const t=await this._publishMutex.lock();try{const i=await this._p2pChannel.unpublishDataChannel(e);i&&await this._gateway.unpublishDataChannel(i),B.info("[".concat(this._clientId,"] Unpublish dataChannel success, dataChannel ids: ").concat(e.map((e=>"".concat(e.id)))))}catch(e){throw B.error("[".concat(this._clientId,"] unpublish dataChannel error"),e.toString()),e}finally{t&&t()}}async subscribe(e,t,i){if(!(e instanceof Qs)){const t=this.remoteUsers.find((t=>t.uid===e));if(!t)throw new j(ne.INVALID_REMOTE_USER,"user is not in the channel");e=t}return"datachannel"===t?this._subscribeDataChannel(e,i):this._subscribe(e,t)}async presubscribe(e,t){if(Gt(t,"mediaType",["audio","video"]),this.store.useP2P)throw new j(ne.INVALID_OPERATION,"can't presub at p2p mode");if(!this._joinInfo)throw new j(ne.INVALID_OPERATION,"can't presub when not join");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new j(ne.INVALID_OPERATION,"can't presub in ".concat(this.connectionState," state"));const i=t===Sn.AUDIO,n=t===Sn.VIDEO,o=await this._subscribeMutex.lock();try{const s=await this._gateway.presubscribe(e,t,!0),a=s.ssrcId,r=s.ortc,c=s.rtxSsrcId,d=s.cname,l=s.uint_id;if(null==a)throw new j(ne.UNEXPECTED_RESPONSE,"no ssrc id");let h=this._users.find((t=>t.uid===e));h||(h=new Qs(e,l||e),h._is_pre_created=!0,this._users.push(h)),d&&(h._cname=d),h._uintid||(h._uintid=l||e),i&&(h._audioSSRC=a,h._audio_pre_subscribed=!0,r&&(h._audioOrtc=r)),n&&(h._videoSSRC=a,h._video_pre_subscribed=!0,r&&(h._videoOrtc=r),null!=c&&(h._rtxSsrcId=c)),B.info("[".concat(this._clientId,"] presub succeed ssrc: ").concat(a)),await this._p2pChannel.subscribe(h,t,a,c,r);const u=i?h._audioTrack:h._videoTrack;if(!u)throw new j(ne.UNEXPECTED_ERROR,"can not find remote track in user");return i&&(h._trust_audio_stream_added_state_=!0,h._audio_added_=!0),n&&(h._trust_video_stream_added_state_=!0,h._video_added_=!0),u}catch(t){throw B.error("[".concat(this._clientId,"] presub user ").concat(e," error"),t),t}finally{o()}}async _subscribeDataChannel(e,t){var i;if(yt(t,"channelId",0,65535,!0),!this._joinInfo)throw new j(ne.INVALID_OPERATION,"Can't subscribe datachannel, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new j(ne.INVALID_OPERATION,"Can't subscribe datachannel in ".concat(this.connectionState," state"));if(!this._users.find((t=>t===e)))throw B.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", this user is not in the channel")),new j(ne.INVALID_REMOTE_USER,"user is not in the channel");if(!e.hasAudio&&!e.hasVideo&&0===e._dataChannels.length)throw B.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", user is not published")),new j(ne.INVALID_REMOTE_USER,"user is not published");const n=null===(i=e._dataChannels)||void 0===i?void 0:i.find((e=>e.id===t));if(!n)throw B.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid," with mediaType datachannel, remote datachannel is not published")),new j(ne.REMOTE_USER_IS_NOT_PUBLISHED);const o=await this._subscribeMutex.lock();B.info("[".concat(this._clientId,"] subscribe user ").concat(e.uid,", mediaType: datachannel"));try{const t=await this._p2pChannel.subscribeDataChannel(e,[n]);if(t&&t.includes(n.id))try{var s;if("number"!=typeof n._originDataChannelId)throw B.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid," with mediaType datachannel, cannot get RTCDatachannel")),new j(ne.CREATE_DATACHANNEL_ERROR);const t={id:n.id,datachannelId:n._originDataChannelId,ordered:n.ordered,maxRetransmits:n.maxRetransmits,metadata:null!==(s=n.metadata)&&void 0!==s?s:""};await this._gateway.subscribeDataChannel(e.uid,t,!0),await n._waitTillOpen()}catch(t){if((null==t?void 0:t.code)!==ne.WS_ABORT)throw await this._p2pChannel.unsubscribeDataChannel(e,[n]),t;await this._p2pChannel.unsubscribeDataChannel(e,[n]),this._p2pChannel.setPendingRemoteDataChannel(e,n.id)}return B.info("[".concat(this._clientId,"] subscribe success user ").concat(e.uid,", mediaType: datachannel")),n}finally{o()}}async _p2pSubscribe(e,t,i){if(Gt(t,"mediaType",["audio","video"]),!this._joinInfo)throw new j(ne.INVALID_OPERATION,"Can't subscribe stream, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new j(ne.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));if(!this._users.find((t=>t===e))){const t=new j(ne.INVALID_REMOTE_USER,"user is not in the channel");throw B.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", this user is not in the channel")),t}if(!e.hasAudio&&!e.hasVideo){const t=new j(ne.INVALID_REMOTE_USER,"user is not published");throw B.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", user is not published")),t}if(!i&&("audio"===t&&!e.hasAudio||"video"===t&&!e.hasVideo)){const i=new j(ne.REMOTE_USER_IS_NOT_PUBLISHED);throw B.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid," with mediaType ").concat(t,", remote track is not published")),i}const n=await this._subscribeMutex.lock();B.info("[".concat(this._clientId,"] subscribe user ").concat(e.uid,", mediaType: ").concat(t));try{if(await this._p2pChannel.hasRemoteMediaWithLock(e,t))await this._p2pChannel.unmuteRemote(e,t);else try{const i="audio"===t?e._audioSSRC:e._videoSSRC,n="audio"===t?e._audioMid:e._videoMid;this.store.subscribe(e.uid,t,Date.now()),this.store.useP2P&&await this._p2pChannel.subscribe(e,t,i,n)}catch(e){throw e}B.info("[".concat(this._clientId,"] subscribe success user ").concat(e.uid,", mediaType: ").concat(t)),void 0!==this._defaultStreamFallbackType&&this.setStreamFallbackOption(e.uid,this._defaultStreamFallbackType).catch((e=>{B.warning("[".concat(this._clientId,"] auto set fallback failed"),e)}));const i="audio"===t?e._audioTrack:e._videoTrack;if(!i)throw new j(ne.UNEXPECTED_ERROR,"can not find remote track in user object");return i}catch(t){throw B.error("[".concat(this._clientId,"] subscribe user ").concat(e.uid," error"),t),t}finally{n()}}async _subscribe(e,t,i){if(this.store.useP2P)return this._p2pSubscribe(e,t);if(Gt(t,"mediaType",["audio","video"]),!this._joinInfo)throw new j(ne.INVALID_OPERATION,"Can't subscribe stream, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new j(ne.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));if(!this._users.find((t=>t===e))){const t=new j(ne.INVALID_REMOTE_USER,"user is not in the channel");throw B.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", this user is not in the channel")),t}if(!e.hasAudio&&!e.hasVideo){const t=new j(ne.INVALID_REMOTE_USER,"user is not published");throw B.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", user is not published")),t}if(!(i||("audio"!==t||e.hasAudio&&void 0!==e._audioSSRC)&&("video"!==t||e.hasVideo&&void 0!==e._videoSSRC))){const i=new j(ne.REMOTE_USER_IS_NOT_PUBLISHED);throw B.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid," with mediaType ").concat(t,", remote track is not published")),i}let n="audio"===t?e._audioSSRC:e._videoSSRC,o="audio"===t?e._audioOrtc:e._videoOrtc,s="video"===t?e._rtxSsrcId:void 0,a={stream_type:"audio"===t?Sn.AUDIO:Sn.VIDEO,ssrcId:n};"video"===t&&this.store.firstVideoFrameDecoded(e.uid,{subscribeStart:Date.now()});const r=await this._subscribeMutex.lock();B.info("[".concat(this._clientId,"] subscribe user ").concat(e.uid,", mediaType: ").concat(t));try{if(await this._p2pChannel.hasRemoteMediaWithLock(e,t))await this._p2pChannel.unmuteRemote(e,t);else try{const i="audio"===t?e._audioSSRC:e._videoSSRC;void 0!==i&&i!==n&&(n=i,o="audio"===t?e._audioOrtc:e._videoOrtc,s="video"===t?e._rtxSsrcId:void 0,a={stream_type:"audio"===t?Sn.AUDIO:Sn.VIDEO,ssrcId:n}),Ys.markSubscribeStart(this.store.clientId,n),this.store.subscribe(e.uid,t,Date.now()),await this._p2pChannel.subscribe(e,t,n,s,o);try{this._p2pChannel.isPreSubScribe(n)||await this._gateway.subscribe(e.uid,a,!0)}catch(i){if((null==i?void 0:i.code)!==ne.WS_ABORT)throw await this._p2pChannel.unsubscribe(e,t),i;await this._p2pChannel.unsubscribe(e,t,!0),this._p2pChannel.setPendingRemoteMedia(e,t)}this.store.subscribe(e.uid,t,void 0,Date.now()),this._p2pChannel.reportSubscribeEvent(!0,null,e,t)}catch(i){throw this._p2pChannel.reportSubscribeEvent(!1,null==i?void 0:i.code,e,t),i}B.info("[".concat(this._clientId,"] subscribe success user ").concat(e.uid,", mediaType: ").concat(t)),void 0!==this._defaultStreamFallbackType&&this.setStreamFallbackOption(e.uid,this._defaultStreamFallbackType).catch((e=>{B.warning("[".concat(this._clientId,"] auto set fallback failed"),e)}));const i="audio"===t?e._audioTrack:e._videoTrack;if(!i)throw new j(ne.UNEXPECTED_ERROR,"can not find remote track in user object");return"video"===t&&(this.store.firstVideoFrameDecoded(e.uid,{subscribeEnd:Date.now()}),this._p2pChannel.reportVideoFirstFrameRender(e)),i}catch(t){throw B.error("[".concat(this._clientId,"] subscribe user ").concat(e.uid," error"),t),t}finally{r()}}async massSubscribe(e){if(Ut(e,"subscribeList"),!this._joinInfo)throw new j(ne.INVALID_OPERATION,"Can't subscribe stream, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new j(ne.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));const t=Date.now(),i=new Map,n=await this._subscribeMutex.lock();B.info("[".concat(this._clientId,"]start massSubscribe user ").concat(e.map((e=>{let t=e.user,i=e.mediaType;return"user: ".concat(null==t?void 0:t.uid,", mediaType: ").concat(i)})).join("; ")));const o=(e=[...e]).map((e=>({user:e.user,mediaType:e.mediaType}))),s=await this._p2pChannel.globalLock();try{for(let t=e.length-1;t>=0;t--){const n=e[t],s=n.user,a=n.mediaType;if(Gt(a,"mediaType",["audio","video"]),!s){const e=new j(ne.INVALID_PARAMS,"user property does not exist in subscribeList item");throw B.error("[".concat(this._clientId,"] user property does not exist in subscribeList item")),e}if(!this._users.find((e=>e===s))){const i=new j(ne.INVALID_REMOTE_USER,"user is not in the channel");B.error("[".concat(this._clientId,"] can not massSubscribe ").concat(s.uid,", this user is not in the channel")),o[t].error=i,e.splice(t,1);continue}if("audio"===a&&(!s.hasAudio||void 0===s._audioSSRC)||"video"===a&&(!s.hasVideo||void 0===s._videoSSRC)){const i=new j(ne.REMOTE_USER_IS_NOT_PUBLISHED);B.error("[".concat(this._clientId,"] can not subscribe ").concat(s.uid," with mediaType ").concat(a,", remote user is not published")),o[t].error=i,e.splice(t,1);continue}const r=cn.Video|cn.LowVideo,c=i.get(s);if(c){if("video"===a?c&r:c&cn.Audio){e.splice(t,1),B.warning("[".concat(this._clientId,"] repeat massSubscribe user:").concat(s.uid,", mediaType:").concat(a," twice"));continue}i.set(s,c|("video"===a?r:cn.Audio))}else i.set(s,"video"===a?r:cn.Audio)}for(let t=e.length-1;t>=0;t--){const n=e[t],o=n.user,s=n.mediaType,a=cn.Video|cn.LowVideo;if(this._p2pChannel.hasRemoteMedia(o,s)){await this._p2pChannel.unmuteRemoteNoLock(o,s);const n=i.get(o);i.set(o,"video"===s?n^a:n^cn.Audio),e.splice(t,1)}}this.store.massSubscribe(e.map((e=>({userId:e.user.uid,type:e.mediaType}))),t);let a=Array.from(i.entries()).reduce(((e,t)=>{let i=Mi(t,2),n=i[0],o=i[1];if(0===o)return e;const s={stream_id:n.uid,stream_type:o};return o&cn.Audio&&(s.audio_ssrc=n._audioSSRC),o&cn.Video&&(s.video_ssrc=n._videoSSRC),e.push(s),e}),[]);try{e.length>0&&await this._p2pChannel.massSubscribeNoLock(e.map((e=>{let t=e.user,i=e.mediaType;return{user:t,mediaType:i,ssrcId:i===Sn.VIDEO?t._videoSSRC:t._audioSSRC,rtxSsrcId:i===Sn.VIDEO?t._rtxSsrcId:void 0}})));const i=new Map;if(a=a.filter((e=>e.video_ssrc&&!this._p2pChannel.isPreSubScribe(e.video_ssrc)||e.audio_ssrc&&!this._p2pChannel.isPreSubScribe(e.audio_ssrc)||!e.video_ssrc&&!e.audio_ssrc)),a.length>0){const e=await this._gateway.subscribeAll(a,!0);((null==e?void 0:e.users)||[]).forEach((e=>{let t=e.stream_id,n=e.video_error_code,o=e.audio_error_code,s=e.error_code;(n||o||s)&&i.set(t,{video_error_code:n,audio_error_code:o,error_code:s})}))}if(Array.from(i.entries()).length>0){const e=[];Array.from(i.entries()).forEach((t=>{let i=Mi(t,2),n=i[0],o=i[1];const s=this.remoteUsers.find((e=>e.uid===n));if(s){let t;o.error_code||o.video_error_code&&o.audio_error_code?t=void 0:o.video_error_code?t=Sn.VIDEO:o.audio_error_code&&(t=Sn.AUDIO),e.push({user:s,mediaType:t})}})),e.length>0&&await this._p2pChannel.massUnsubscribeNoLock(e)}for(const e of o){const t=i.get(e.user.uid);if(t){const i=t.error_code||"audio"===e.mediaType&&t.audio_error_code||"video"===e.mediaType&&t.video_error_code;if(i){const t=Un(i);B.error("user:".concat(e.user.uid," mediaType:").concat(e.mediaType," has massSubscribe error ").concat(t.desc)),e.error=new j(ne.SUBSCRIBE_FAILED,"code ".concat(i,": ").concat(t.desc))}}e.error||("video"===e.mediaType?e.track=e.user.videoTrack:e.track=e.user.audioTrack)}return this.store.massSubscribe(o.filter((e=>!e.error)).map((e=>({userId:e.user.uid,type:e.mediaType}))),void 0,Date.now()),o.forEach((e=>{var i;G.subscribe(this.store.sessionId,{succ:!!e.error,ec:(null===(i=e.error)||void 0===i?void 0:i.code)||null,video:e.mediaType===Sn.VIDEO,audio:e.mediaType===Sn.AUDIO,peerid:e.user.uid,subscribeRequestid:e.mediaType===Sn.VIDEO?e.user._videoSSRC:e.user._audioSSRC,p2pid:this.store.p2pId,eventElapse:Math.floor(performance.now()-t),preSsrc:this._p2pChannel.isPreSubScribe(e.user._videoSSRC)},!0)})),B.info("[".concat(this._clientId,"] massSubscribe success ").concat(e.map((e=>{let t=e.user,i=e.mediaType;return"user: ".concat(null==t?void 0:t.uid,", mediaType: ").concat(i)})).join("; "))),o}catch(t){throw await this._p2pChannel.massUnsubscribeNoLock(e),t}}finally{s(),n()}}async unsubscribe(e,t,i){if(!(e instanceof Qs)){const t=this.remoteUsers.find((t=>t.uid===e));if(!t)throw new j(ne.INVALID_REMOTE_USER,"user is not in the channel");e=t}if(t||this.store.useP2P){if("datachannel"===t)return this._unsubscribeDataChannel(e,i)}else await this._unsubscribeDataChannel(e,i);if(t&&Gt(t,"mediaType",["audio","video"]),!this._joinInfo)throw new j(ne.INVALID_OPERATION,"Can't unsubscribe stream, haven't joined yet!");if(!this._users.find((t=>t===e))){const t=new j(ne.INVALID_REMOTE_USER,"user is not in the channel");throw B.error("[".concat(this._clientId,"] can not unsubscribe ").concat(e.uid,", user is not in the channel")),t}B.info("[".concat(this._clientId,"] unsubscribe uid: ").concat(e.uid,", mediaType: ").concat(t));const n=await this._subscribeMutex.lock();try{if(this.store.useP2P)await this._p2pChannel.unsubscribe(e,t);else{const i=await this._p2pChannel.unsubscribe(e,t);i&&await this._gateway.unsubscribe(i,e.uid),t&&"audio"!==t||(e._audio_pre_subscribed=!1),t&&"video"!==t||(e._video_pre_subscribed=!1),e._is_pre_created&&Nt(this._users,e),B.info("[".concat(this._clientId,"] unsubscribe success uid: ").concat(e.uid,", mediaType: ").concat(t))}}catch(t){if(t.code===ne.DISCONNECT_P2P)return void B.warning("disconnecting p2p, abort unsubscribe request.");throw B.error("[".concat(this._clientId,"] unsubscribe user ").concat(e.uid," error"),t.toString()),t}finally{n()}}async _unsubscribeDataChannel(e,t){if(t&&yt(t,"id",0,65535,!0),!this._joinInfo)throw new j(ne.INVALID_OPERATION,"Can't unsubscribe datachannel, haven't joined yet!");if(!this._users.find((t=>t===e))){const t=new j(ne.INVALID_REMOTE_USER,"user is not in the channel");throw B.error("[".concat(this._clientId,"] can not unsubscribe ").concat(e.uid,", user is not in the channel")),t}let i;if("number"==typeof t){const n=e._dataChannels.find((e=>e.id===t));n&&(i=[n])}else i=e._dataChannels;if(void 0===i){const i=new j(ne.REMOTE_USER_IS_NOT_PUBLISHED);throw B.error("[".concat(this._clientId,"] can not unsubscribe ").concat(e.uid," with channelId ").concat(t,", remote datachannel is not published")),i}B.info("[".concat(this._clientId,"] unsubscribe uid: ").concat(e.uid,", mediaType: datachannel, ids: ").concat(i.map((e=>e.id))));try{const t=await this._p2pChannel.unsubscribeDataChannel(e,i);t&&await this._gateway.unsubscribeDataChannel(t,e.uid),B.info("[".concat(this._clientId,"] unsubscribe datachannel success uid: ").concat(e.uid,", mediaType: datachannel, ids: ").concat(t))}catch(t){if(t.code===ne.DISCONNECT_P2P)return void B.warning("disconnecting p2p, abort unsubscribe request.");throw B.error("[".concat(this._clientId,"] unsubscribe user ").concat(e.uid," error"),t.toString()),t}}async massUnsubscribe(e){if(Ut(e,"unsubscribeList"),!this._joinInfo)throw new j(ne.INVALID_OPERATION,"Can't unsubscribeAll stream, haven't joined yet!");B.info("[".concat(this._clientId,"] start massUnsubscribe ").concat(e.map((e=>{let t=e.user,i=e.mediaType;return"user: ".concat(null==t?void 0:t.uid,", mediaType: ").concat(i,";")})).join())),e=[...e];const t=new Map;for(let i=e.length-1;i>=0;i--){const n=e[i],o=n.user,s=n.mediaType;if(!o){const e=new j(ne.INVALID_PARAMS,"user property does not exist in unsubscribeList item");throw B.error("[".concat(this._clientId,"] user property does not exist in unsubscribeList item")),e}Gt(s,"mediaType",["video","audio",void 0]);if(!this._users.find((e=>e===o))){B.warning("[".concat(this._clientId,"] can not unsubscribe ").concat(o.uid,", user is not in the channel")),e.splice(i,1);continue}const a=cn.Video|cn.LowVideo;if(t.has(o)){const n=t.get(o);let r;switch(s){case"video":r=n&a;break;case"audio":r=n&cn.Audio;break;default:r=n&(cn.Audio|a)}if(r){B.warning("[".concat(this._clientId,"] repeat massUnsubscribe user:").concat(o.uid,",mediaType:").concat(s," twice.")),e.splice(i,1);continue}s?"audio"===s?t.set(o,n|cn.Audio):"video"===s&&t.set(o,n|a):t.set(o,n|cn.Audio|a)}else s?"audio"===s?t.set(o,cn.Audio):"video"===s&&t.set(o,a):t.set(o,cn.Audio|a)}try{const t=await this._p2pChannel.massUnsubscribe(e);t&&await this._gateway.massUnsubscribe(t),B.info("[".concat(this._clientId,"] massUnsubscribe success ").concat(e.map((e=>{let t=e.user,i=e.mediaType;return"user: ".concat(null==t?void 0:t.uid,", mediaType: ").concat(i,";")})).join()))}catch(e){if(e.code===ne.DISCONNECT_P2P)return void B.warning("[".concat(this._clientId,"] disconnecting p2p, abort unsubscribe request."));throw B.error("[".concat(this._clientId,"] massUnsubscribe error"),e.toString()),e}}async setLowStreamParameter(e){L(e),(!e.width&&e.height||e.width&&!e.height)&&B.warning("[".concat(this._clientId,"] The width and height parameters take effect only when both are set")),B.info("[".concat(this._clientId,"] set low stream parameter to"),JSON.stringify(e));const t=this._configDistribute.getLowStreamConfigDistribute();if(t&&t.bitrate&&e.bitrate&&t.bitrate<e.bitrate&&(e.bitrate=t.bitrate),this._lowStreamParameter=e,this._isDualStreamEnabled)return this._p2pChannel.updateVideoStreamParameter(e,Tn.LocalVideoLowTrack)}async setDualStreamMode(e,t){Gt(e,"mode",[0,1,-1]);try{switch(t&&await this.setLowStreamParameter(t),this._dualStreamMode=e,this._joinInfo?this._gateway.setDualStreamMode(e).catch((e=>{B.warning("[".concat(this._clientId,"] set dual stream mode failed"),e.toString())})):B.debug("[".concat(this._clientId,"] haven't joined yet, cache dual stream mode ").concat(e)),e){case Wt.AUTO_SIMULCAST_STREAM:B.info("[".concat(this._clientId,"] set dual stream mode to ").concat(e));break;case Wt.DISABLE_SIMULCAST_STREM:return this.disableDualStream();case Wt.ENABLE_SIMULCAST_STREAM:return this.enableDualStream()}}catch(e){throw B.error("[".concat(this._clientId,"] set dual stream mode error"),e.toString()),e}}async enableDualStream(){if(!o().supportDualStream)throw G.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!0,succ:!1}),new j(ne.NOT_SUPPORTED,"Your browser is not support dual stream");if(this._isDualStreamEnabled)throw new j(ne.INVALID_OPERATION,"Dual stream is already enabled");if(this._p2pChannel.canPublishLowStream())try{await this._publishLowStream()}catch(e){throw G.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!0,succ:!1}),e}this._isDualStreamEnabled=!0,this._dualStreamMode=Wt.ENABLE_SIMULCAST_STREAM,this._joinInfo&&this._gateway.setDualStreamMode(this._dualStreamMode,!0,!0).catch((e=>{B.debug("[".concat(this._clientId,"] try to inform gateway to set dual stream mode to ").concat(this._dualStreamMode," ,but failed"),e.toString())})),G.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!0,succ:!0}),B.info("[".concat(this._clientId,"] enable dual stream"))}async disableDualStream(){if(this._isDualStreamEnabled){if(!this._joinInfo)return this._isDualStreamEnabled=!1,void B.info("[".concat(this._clientId,"] disable dual stream before join"));if(this._p2pChannel.getLocalMedia(Tn.LocalVideoLowTrack))try{const e=await this._p2pChannel.unpublishLowStream();e&&await this._gateway.unpublish(e,this._joinInfo.stringUid||this._joinInfo.uid)}catch(e){throw G.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!1,succ:!1}),e}this._isDualStreamEnabled=!1,this._dualStreamMode=Wt.DISABLE_SIMULCAST_STREM,this._joinInfo&&this._gateway.setDualStreamMode(this._dualStreamMode,!0,!0).catch((e=>{B.debug("[".concat(this._clientId,"] try to inform gateway to set dual stream mode to ").concat(this._dualStreamMode," ,but failed"),e.toString())})),G.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!1,succ:!0}),B.info("[".concat(this._clientId,"] disable dual stream"))}}async setClientRole(e,t){if(Ht(e),t&&Dt(t),"rtc"===this.mode||"p2p"===this.mode)throw B.warning("[".concat(this._clientId,"]").concat(this.mode," mode can not use setClientRole")),new j(ne.INVALID_OPERATION,"".concat(this.mode," mode can not use setClientRole"));if(t&&t.level&&"host"===e)throw new j(ne.INVALID_OPERATION,"host mode can not set audience latency level");if("audience"===e&&this._p2pChannel.hasLocalMedia())throw new j(ne.INVALID_OPERATION,"can not set client role to audience when publishing stream");const i=this._config.role;if(this._joinInfo&&(this._joinInfo.role=e),e!==i&&ce("ENABLE_ROLE_SELECT_EDGE")?(this._gateway.updateClientRole(e,t),this._config.role=e,this._gateway.reconnect("recover",Ie.REGIONAL_DISTRIBUTION)):(await this._gateway.setClientRole(e,t),this._config.role=e),B.info("[".concat(this._clientId,"] set client role to ").concat(e,", level: ").concat(t&&t.level)),"audience"===i&&"audience"!==e&&this._pendingRtpCapabilityChange&&this._p2pChannel instanceof ir){const e=this._pendingRtpCapabilityChange.video_codec;this._p2pChannel.updateRemoteRTPCapabilities(e.map((e=>e.toLowerCase())).filter((e=>Object.keys(tt).includes(e))))}}async _setClientRoleOptions(e){if("rtc"===this.mode||"p2p"===this.mode)return;if("audience"!==this._config.role||this._p2pChannel.hasLocalMedia())return;let t=!1;try{e&&Dt(e),await this._gateway.setClientRole(this._config.role,e),t=!0}catch(e){}finally{B.info("[".concat(this._clientId,"] set client role options ").concat(t?"succeed":"failed",", options is ").concat(e))}}getRemoteInboundOffset(){var e;const t=null===(e=this._p2pChannel.getStats())||void 0===e?void 0:e.audioSend[0];if(!t||!t.timestamp)return 0;const i=t.timestamp-Date.now();return Math.abs(i)>1e3+t.rttMs+100?this.ntpAlignErrorCount+=1:this.ntpAlignErrorCount=0,this.ntpAlignErrorCount>=3?i:0}getNtpWallTimeInMs(){return"visible"===document.visibilityState&&(this.remoteInboundOffset=this.getRemoteInboundOffset()),this.remoteInboundOffset+Date.now()+this._gateway.ntpOffset}setProxyServer(e,t){if(se(e,"proxyServer"),!t){if("DISCONNECTED"!==this.connectionState)throw new j(ne.INVALID_OPERATION,"Set proxy server before join channel");if("disabled"!==this._cloudProxyServerMode||this._useLocalAccessPoint)throw new j(ne.INVALID_OPERATION,"You have already set the proxy")}this._proxyServer=e,G.setProxyServer(this._proxyServer),B.setProxyServer(this._proxyServer),B.info("[".concat(this._clientId,"] Set proxy server ").concat(t?"by initialize call":""," success."))}setTurnServer(e,t){if(Array.isArray(e)||(e=[e]),!t){if("DISCONNECTED"!==this.connectionState)throw new j(ne.INVALID_OPERATION,"Set turn server before join channel");if("disabled"!==this._cloudProxyServerMode||this._useLocalAccessPoint)throw new j(ne.INVALID_OPERATION,"You have already set the proxy")}if(dt(e))return this._turnServer={servers:e,mode:"original-manual"},void B.info("[".concat(this._clientId,"] Set original turnserver ").concat(t?"by initialize call":""," success: ").concat(e.map((e=>e.urls)).join(","),"."));e.forEach((e=>Kt(e))),this._turnServer={servers:e,mode:"manual"},B.info("[".concat(this._clientId,"] Set turnserver ").concat(t?"by initialize call":""," success."))}setLicense(e){if("DISCONNECTED"!==this.connectionState){throw new j(ne.INVALID_OPERATION,"you should set license before join channel")}if(se(e,"license",32,32),!/^[A-Za-z\d]+$/.test(e))throw new j(ne.INVALID_PARAMS,"license should only contains characters from A-Z a-z 0-9");this._license=e,B.info("[".concat(this._clientId,"] set license success"),e)}startProxyServer(e){if("DISCONNECTED"!==this.connectionState)throw new j(ne.INVALID_OPERATION,"Start proxy server before join channel");if(this._proxyServer||"manual"===this._turnServer.mode||this._useLocalAccessPoint)throw new j(ne.INVALID_OPERATION,"You have already set the proxy");const t=[3,4,5];let i;switch(void 0===e&&(e=3),e){case 1:case 2:throw new j(ne.NOT_SUPPORTED,"proxy mode 1/2 has been deprecated and not supported.");case 3:i="proxy3";break;case 4:i="proxy4";break;case 5:i="proxy5";break;default:throw new j(ne.INVALID_PARAMS,"proxy server mode must be ".concat(t.join("|")))}this._cloudProxyServerMode=i,this.store.cloudProxyServerMode=i,B.info("[".concat(this._clientId,"] set cloud proxy server mode to"),this._cloudProxyServerMode)}stopProxyServer(){if("DISCONNECTED"!==this.connectionState)throw new j(ne.INVALID_OPERATION,"Stop proxy server after leave channel");G.setProxyServer(),B.setProxyServer(),this._cloudProxyServerMode="disabled",this.store.cloudProxyServerMode="disabled",B.info("[".concat(this._clientId,"] set cloud proxy server mode to"),this._cloudProxyServerMode),this._proxyServer=void 0,this._turnServer={mode:"auto",servers:[]}}setLocalAccessPointsV2(e){if(!e.accessPoints)throw new j(ne.INVALID_PARAMS,"accessPoints is required.");Ut(e.accessPoints.serverList,"accessPoints.serverList"),se(e.accessPoints.domain,"accessPoints.domain");const t=(e,t)=>{yt(e,t,0,65535,!0)};let i=443;if(e.accessPoints.port&&(t(e.accessPoints.port,"accessPoints.port"),i=e.accessPoints.port),this._proxyServer||"disabled"!==this._cloudProxyServerMode)throw new j(ne.INVALID_OPERATION,"set local access point failed, You have already set the cloud proxy");ce("CLOSE_AFB_FOR_LOCAL_AP")&&(Ve("JOIN_WITH_FALLBACK_SIGNAL_PROXY",!1),Ve("JOIN_WITH_FALLBACK_MEDIA_PROXY",!1));const n=/^((\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/,o=e.accessPoints.domain,s=e.accessPoints.serverList.map((e=>n.test(e)?"".concat(e.replace(/\./g,"-"),".").concat(o):e)),a=s.map((e=>"".concat(e,":").concat(i)));this._useLocalAccessPoint=!0,this._setLocalAPVersion=2,Ve("WEBCS_DOMAIN",a),Ve("WEBCS_DOMAIN_BACKUP_LIST",a),Ve("GATEWAY_DOMAINS",[o]),e.report&&e.report.hostname&&Array.isArray(e.report.hostname)&&e.report.hostname.length?(Ut(e.report.hostname,"report.hostname"),Ve("EVENT_REPORT_DOMAIN",e.report.hostname[0]),Ve("EVENT_REPORT_BACKUP_DOMAIN",e.report.hostname[1]||e.report.hostname[0])):(Ve("EVENT_REPORT_DOMAIN",s[0]),Ve("EVENT_REPORT_BACKUP_DOMAIN",s[1]||s[0]));let r=6443;e.report&&e.report.port&&(t(e.report.port,"report.port"),r=e.report.port),Ve("STATS_COLLECTOR_PORT",r),e.report?Ve("ENABLE_EVENT_REPORT",!0):Ve("ENABLE_EVENT_REPORT",!1);let c="";e.log&&e.log.hostname&&Array.isArray(e.log.hostname)&&e.log.hostname.length?(Ut(e.log.hostname,"log.hostname"),c=e.log.hostname[0]):c=s[0];let d=6444;e.log&&e.log.port&&(t(e.log.port,"log.port"),d=e.log.port),Ve("LOG_UPLOAD_SERVER","".concat(c,":").concat(d));let l=[];e.cds&&e.cds.hostname&&Array.isArray(e.cds.hostname)&&e.cds.hostname.length?(Ut(e.cds.hostname,"cds.hostname"),l=e.cds.hostname):l=s;let h=443;e.cds&&e.cds.port&&(t(e.cds.port,"cds.port"),h=e.cds.port),Ve("CDS_AP",l.map((e=>"".concat(e,":").concat(h)))),e.cds?Ve("ENABLE_CONFIG_DISTRIBUTE",!0):Ve("ENABLE_CONFIG_DISTRIBUTE",!1),B.info("set local access point v2 success")}setLocalAccessPoints(e,t){if(Ut(e,"serverList"),se(t,"domain"),this._proxyServer||"disabled"!==this._cloudProxyServerMode)throw new j(ne.INVALID_OPERATION,"set local access point failed, You have already set the cloud proxy");const i=/^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;e=e.map((e=>i.test(e)?"".concat(e.replace(/\./g,"-"),".").concat(t):e)),this._useLocalAccessPoint=!0,this._setLocalAPVersion=1,Ve("WEBCS_DOMAIN",e),Ve("WEBCS_DOMAIN_BACKUP_LIST",e),Ve("GATEWAY_DOMAINS",[t]),Ve("EVENT_REPORT_DOMAIN",e[0]),Ve("EVENT_REPORT_BACKUP_DOMAIN",e[1]||e[0]),Ve("LOG_UPLOAD_SERVER","".concat(e[0],":6444")),B.info("[".concat(this._clientId,"] set local access point success"))}async setRemoteDefaultVideoStreamType(e){if(Gt(e,"streamType",[0,1,4,5,6,7,8,9]),this._remoteDefaultVideoStreamType=e,this._joinInfo)try{await this._gateway.setDefaultRemoteVideoStreamType(e),this._joinInfo.defaultVideoStream=this._remoteDefaultVideoStreamType}catch(e){throw B.error("[".concat(this._clientId,"] set default remote video stream type error"),e.toString()),e}else B.debug("[".concat(this._clientId,"] haven't joined yet, cache remoteDefaultVideoStreamType ").concat(e))}async setRemoteVideoStreamType(e,t){Gt(t,"streamType",[0,1,4,5,6,7,8,9]);try{await this._gateway.setRemoteVideoStreamType(e,t),setTimeout((()=>{const t=this._users.find((t=>t.uid===e));t&&t.videoTrack&&t.videoTrack.updateMediaStreamTrackResolution()}),2e3)}catch(e){throw B.error("[".concat(this._clientId,"] set remote video stream type error"),e.toString()),e}B.info("[".concat(this._clientId,"] set remote ").concat(e," video stream type to ").concat(t)),this._remoteStreamTypeCacheMap.set(e,t)}async setStreamFallbackOption(e,t){Gt(t,"fallbackType",[0,1,2,3,4,5,6,7,8]);try{await this._gateway.setStreamFallbackOption(e,t)}catch(e){throw B.error("[".concat(this._clientId,"] set stream fallback option"),e.toString()),e}B.info("[".concat(this._clientId,"] set remote ").concat(e," stream fallback type to ").concat(t)),this._streamFallbackTypeCacheMap.set(e,t)}setEncryptionConfig(e,t,i,n){Yt(e),se(t,"secret");const o=["aes-128-gcm2","aes-256-gcm2"];if(o.includes(e)){if(!i||!(i instanceof Uint8Array&&32===i.length))throw new j(ne.INVALID_PARAMS,"salt must be an Uint8Array and exactly equal to 32 bytes")}else if(i)throw new j(ne.INVALID_PARAMS,"current encrypt mode does not need salt");if(n){if(Mt(n,"encryptDataStream"),!o.includes(e))throw new j(ne.INVALID_PARAMS,"current encrypt mode does not support data stream");this._encryptDataStream=!0}new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*,.<>?/:;'\"|{}\\[\\]])(?=.{8,})").test(t)||B.warning("The secret is not strong:\n The secret must contain at least 1 lowercase alphabetical character,\n The secret must contain at least 1 uppercase alphabetical character,\n The secret must contain at least 1 numeric character,\n The secret must contain at least one special character,\n The secret must be eight characters or longer.\n "),this._encryptionMode=e,this._encryptionSecret=t,i&&(this._encryptionSalt=At(i))}async renewToken(e){if(se(e,"token",1,2047),!this._key||!this._joinInfo)throw new j(ne.INVALID_OPERATION,"renewToken should not be called before user join");const t=this._key;this._key=e,this._joinInfo&&(this._joinInfo.token=e);const i=await this._renewTokenMutex.lock();try{if(ce("USE_NEW_TOKEN")){B.debug("[".concat(this._clientId,"] start renew token with ticket from unilbs"));const t=await ws(this._joinInfo,this._axiosCancelSource.token,this._config.httpRetryConfig||Ke);B.debug("[".concat(this._clientId,"] get ticket from unilbs success")),await this._gateway.renewToken({token:e,ticket:t})}else B.debug("[".concat(this._clientId,"] start renew token without ticket")),await this._gateway.renewToken({token:e});B.debug("[".concat(this._clientId,"] renewToken success"))}catch(e){throw this._key=t,this._joinInfo.token=t,B.error("[".concat(this._clientId,"] renewToken failed"),e.toString()),e}finally{i()}}enableAudioVolumeIndicator(){this._audioVolumeIndicationInterval?B.warning("you have already enabled audio volume indicator!"):this._audioVolumeIndicationInterval=window.setInterval((()=>{const e=this._p2pChannel.getAudioLevels();this.safeEmit(ft.VOLUME_INDICATOR,e)}),ce("AUDIO_VOLUME_INDICATION_INTERVAL")||2e3)}getRTCStats(){const e=this._statsCollector.getRTCStats(),t=this._gateway.getInChannelInfo();return e.Duration=Math.round(t.duration/1e3),e}async startLiveStreaming(e,t){if(!t){if("h264"!==this.codec)throw new j(ne.LIVE_STREAMING_INVALID_RAW_STREAM,"raw streaming is only support h264");if(!this._p2pChannel.hasLocalMedia())throw new j(ne.LIVE_STREAMING_INVALID_RAW_STREAM,"can not find stream to raw streaming")}if(this._liveRawStreamingClient&&this._liveRawStreamingClient.hasUrl(e)||this._liveTranscodeStreamingClient&&this._liveTranscodeStreamingClient.hasUrl(e))throw new j(ne.LIVE_STREAMING_TASK_CONFLICT);const i=t?Zi.TRANSCODE:Zi.RAW;return this._createLiveStreamingClient(i).startLiveStreamingTask(e,i)}setLiveTranscoding(e){return this._createLiveStreamingClient(Zi.TRANSCODE).setTranscodingConfig(e)}async stopLiveStreaming(e){const t=[this._liveRawStreamingClient,this._liveTranscodeStreamingClient].filter((t=>t&&t.hasUrl(e)));if(!t.length)throw new j(ne.INVALID_PARAMS,"can not find live streaming url to stop");await Promise.all(t.map((t=>t&&t.stopLiveStreamingTask(e))))}async startChannelMediaRelay(e){Xs(e);const t=this._createChannelMediaRelayClient();await t.startChannelMediaRelay(e)}async updateChannelMediaRelay(e){Xs(e);const t=this._createChannelMediaRelayClient();await t.updateChannelMediaRelay(e)}async stopChannelMediaRelay(){const e=this._createChannelMediaRelayClient();await e.stopChannelMediaRelay(),this._statsCollector.onStatsChanged&&(this._statsCollector.onStatsChanged=void 0)}sendAudioMetadata(e){this._p2pChannel instanceof ir&&this._p2pChannel.addAudioMetadata(e)}async sendStreamMessage(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!this._joinInfo)throw new j(ne.INVALID_OPERATION,"can not send data stream, not joined");if(("string"==typeof e||e instanceof Uint8Array)&&(e={payload:e}),"string"==typeof e.payload){const t=new TextEncoder;e.payload=t.encode(e.payload)}let i=!1;this._encryptDataStream&&this._encryptDataStreamIv&&this._encryptDataStreamKey&&window.crypto.subtle&&["aes-128-gcm2","aes-256-gcm2"].includes(this._encryptionMode)&&(i=!0,e.payload=await qt(this._encryptDataStreamIv,this._encryptDataStreamKey,e.payload));if(new Blob([e.payload]).size>1024)throw new j(ne.INVALID_PARAMS,i?"encrypted stream message out of range.":"stream message out of range.");return this._gateway.signal.request(Ki.DATA_STREAM,{payload:At(e.payload),syncWithAudio:e.syncWithAudio,sendTs:Date.now()-or},!t)}sendMetadata(e){if(!this._joinInfo)throw new j(ne.INVALID_OPERATION,"can not send metadata, not joined");if(new Blob([e]).size>1024)throw new j(ne.METADATA_OUT_OF_RANGE);return this._gateway.signal.request(Ki.SEND_METADATA,{session_id:this._joinInfo.sid,metadata:At(e)})}async sendCustomReportMessage(e){if(Array.isArray(e)||(e=[e]),e.forEach(z),!this._joinInfo)throw new j(ne.INVALID_OPERATION,"can not send custom report, not joined");await G.sendCustomReportMessage(this._joinInfo.sid,e)}getLocalAudioStats(){return this._statsCollector.getLocalAudioTrackStats()}getRemoteAudioStats(){return this._statsCollector.getRemoteAudioTrackStats()}getLocalVideoStats(){return this._statsCollector.getLocalVideoTrackStats()}getRemoteVideoStats(){return this._statsCollector.getRemoteVideoTrackStats()}getRemoteNetworkQuality(){const e=this._statsCollector.getRemoteNetworkQualityStats();if(ce("DELETE_NEQ_AFTER_USER_LEAVE")){const t=this._users.map((e=>e.uid+""));Object.keys(e).forEach((i=>{t.includes(i)||delete e[i]}))}return e}getNetworkQuality(){return this._statsCollector.getNetworkQuality()}async pickSVCLayer(e,t){Gt(t.spatialLayer,"spatialLayer",[0,1,2,3]),Gt(t.temporalLayer,"temporalLayer",[0,1,2,3]);try{await this._gateway.pickSVCLayer(e,t)}catch(e){throw B.error("[".concat(this._clientId,"] pick SVC layer failed"),e.toString()),e}}async setRTMConfig(e){const t=e.apRTM,i=void 0!==t&&t,n=e.rtmFlag;if(Mt(i,"apRTM"),yt(n,"rtmFlag",0),this._rtmConfig.apRTM=i,this._rtmConfig.rtmFlag=n,B.debug("[".concat(this._clientId,"] setRTMconfig ").concat(JSON.stringify(e)," in ").concat(this.connectionState," state")),("CONNECTED"===this.connectionState||"RECONNECTING"===this.connectionState)&&this._joinInfo)return this._joinInfo.apRTM=i,this._joinInfo.rtmFlag=n,this._gateway.setRTM2Flag(n)}_reset(){if(B.debug("[".concat(this._clientId,"] reset client")),function(e){const t=gi.indexOf(e);-1!==t&&gi.splice(t,1)}(this._clientId),this.store.hasStartJoinChannel=!1,this.store.isABTestSuccess=!1,this.store.autoSubscribe=!1,this.store.autoReceiveAndPlayAudio=!1,this._pendingRtpCapabilityChange=void 0,this._axiosCancelSource.cancel(),this._axiosCancelSource=ui.CancelToken.source(),this._streamFallbackTypeCacheMap=new Map,this._remoteStreamTypeCacheMap=new Map,this._configDistribute.stopGetConfigDistribute(),this._joinInfo&&kr(this._joinInfo),this._rteDetailInterval&&(window.clearInterval(this._rteDetailInterval),this._rteDetailInterval=void 0,this._sessionId&&G.reportRteDetail(this._sessionId)),this._fallbackServerInfo=void 0,this._joinInfo=void 0,this._proxyServer=void 0,this._defaultStreamFallbackType=void 0,this._sessionId&&G.removeSid(this._sessionId),this._sessionId=null,this.store.sessionId=null,this.store.resetFirstVideoFrameDecoded(),this._statsCollector.reset(),this._key=void 0,this._appId=void 0,this._uid=void 0,this.store.uid=void 0,this._channelName=void 0,this._encryptionMode="none",this._encryptionSecret=null,this._encryptionSalt=null,this._encryptDataStreamKey=null,this._encryptDataStreamIv=null,this._pendingPublishedUsers=[],this._users.forEach((e=>{e._audioTrack&&e._audioTrack._destroy(),e._videoTrack&&e._videoTrack._destroy(),e._dataChannels&&(e._dataChannels.forEach((e=>e._close())),e._dataChannels.length=0)})),this._users=[],this._audioVolumeIndicationInterval&&(window.clearInterval(this._audioVolumeIndicationInterval),this._audioVolumeIndicationInterval=void 0),"fallback"===this._cloudProxyServerMode&&(this._cloudProxyServerMode="disabled",this.store.cloudProxyServerMode="disabled"),this._p2pChannel.reset(),this._publishMutex=new ue("client-publish",this._clientId),this._subscribeMutex=new ue("client-subscribe",this._clientId),this._networkQualityInterval&&(window.clearInterval(this._networkQualityInterval),this._networkQualityInterval=void 0),this._liveRawStreamingClient&&(this._liveRawStreamingClient.terminate(),this._liveRawStreamingClient.removeAllListeners(),this._liveRawStreamingClient=void 0),this._liveTranscodeStreamingClient&&(this._liveTranscodeStreamingClient.terminate(),this._liveTranscodeStreamingClient.removeAllListeners(),this._liveTranscodeStreamingClient=void 0),this._channelMediaRelayClient&&(this._channelMediaRelayClient.dispose(),this._channelMediaRelayClient=void 0),this._inspect)try{this._inspect.close(),this._inspect=void 0}catch(e){}if(this._moderation)try{this.setImageModeration(!1)}catch(e){}}_startSession(e,t){var i;const n=e||Tt();e?B.debug("[".concat(this._clientId,"] new Session ").concat(n)):B.debug("[".concat(this._clientId,"] renewSession ").concat(this._sessionId," => ").concat(n));const o=e?"":this._sessionId||"";this._sessionId=n,this.store.sessionId=n,G.addSid(n);const s={lts:(new Date).getTime(),mode:this.mode,buildFormat:3,stringUid:(null==t?void 0:t.stringUid)||(null===(i=this._joinInfo)||void 0===i?void 0:i.stringUid),channelProfile:"live"===this.mode?1:0,channelMode:0,isABTestSuccess:Number(this._configDistribute.isSuccess),lsid:o,clientRole:"audience"===this.role?2:1,rteUrl:this.store.rteUrl,rteSid:this.store.rteSid};G.sessionInit(this._sessionId,ki({cname:t.channel,appid:t.appId},s)),this._joinInfo&&(this._joinInfo.sid=n),this._gateway.joinInfo&&(this._gateway.joinInfo.sid=n)}async _publishHighStream(e){if(!this._joinInfo||void 0===this._uid)throw new j(ne.INVALID_OPERATION,"Can't publish stream, haven't joined yet!");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new j(ne.INVALID_OPERATION,"can not publish stream in ".concat(this.connectionState," state"));if("auto"===this._turnServer.mode&&ce("FORCE_TURN")&&!ce("TURN_ENABLE_TCP")&&!ce("TURN_ENABLE_UDP"))throw new j(ne.UNEXPECTED_ERROR,"force TURN With No TURN Configuration");B.debug("[".concat(this._clientId,"] publish high stream"));try{const i=await this._p2pChannel.publish(e,this._isDualStreamEnabled,this._lowStreamParameter);if(this.store.useP2P){const e=(await i.next()).value;if(e){try{await this._gateway.sendExtensionMessage(Dn.PUBLISH,e,!0)}catch(e){throw i.throw(e),e}await i.next()}this._p2pChannel.reportPublishEvent(!0,null)}else{const o=(await i.next()).value;if(o){var t;let e;try{e=await this._gateway.publish(this._uid,o,!0)}catch(e){if(e.code!==ne.DISCONNECT_P2P)throw i.throw(e),e}await i.next((null===(t=e)||void 0===t?void 0:t.ortc)||[])}this._p2pChannel.reportPublishEvent(!0,null);for(const t of e)t instanceof n&&t._encoderConfig&&this._gateway.setVideoProfile(t._encoderConfig).catch((e=>{B.debug("[".concat(this._clientId,"] stop setVideoProfile, because websocket is closed"))})),!t.muted&&t.enabled||await this._p2pChannel.muteLocalTrack(t)}}catch(t){if(this._p2pChannel.reportPublishEvent(!1,null==t?void 0:t.code,e),(null==t?void 0:t.code)===ne.WS_ABORT)return;throw t}}async _publishLowStream(){if(!this._joinInfo||void 0===this._uid)throw new j(ne.INVALID_OPERATION,"Can't publish stream, haven't joined yet!");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new j(ne.INVALID_OPERATION,"can not publish stream in ".concat(this.connectionState," state"));B.debug("[".concat(this._clientId,"] publish low stream"));const e=this._configDistribute.getLowStreamConfigDistribute();e&&e.bitrate&&(this._lowStreamParameter||(this._lowStreamParameter={width:160,height:120,framerate:15,bitrate:50}),this._lowStreamParameter&&this._lowStreamParameter.bitrate&&e.bitrate<this._lowStreamParameter.bitrate&&(this._lowStreamParameter.bitrate=e.bitrate));try{const e=await this._p2pChannel.publishLowStream(this._lowStreamParameter),i=(await e.next()).value;if(i){var t;let n;try{n=await this._gateway.publish(this._uid,i,!0)}catch(t){if(t.code!==ne.DISCONNECT_P2P)throw e.throw(t),t}e.next((null===(t=n)||void 0===t?void 0:t.ortc)||[]),this._p2pChannel.reportPublishEvent(!0,null,void 0,!0)}}catch(e){if(this._p2pChannel.reportPublishEvent(!1,null==e?void 0:e.code,void 0,!0),(null==e?void 0:e.code)===ne.WS_ABORT)return;throw e}}_createLiveStreamingClient(e){const t=()=>{if(!this._joinInfo||!this._appId){return new j(ne.INVALID_OPERATION,"can not create live streaming client, please join channel first").throw()}const e=(t={joinInfo:this._joinInfo,appId:this._appId,websocketRetryConfig:this._config.websocketRetryConfig,httpRetryConfig:this._config.httpRetryConfig},Bo("LiveStreaming").create(t));var t;return e.onLiveStreamError=(e,t)=>{G.reportApiInvoke(this._sessionId,{clientId:this._clientId,name:Be.ON_LIVE_STREAM_ERROR,options:[e,t],tag:je.TRACER}).onSuccess(),this.safeEmit(ft.LIVE_STREAMING_ERROR,e,t)},e.onLiveStreamWarning=(e,t)=>{G.reportApiInvoke(this._sessionId,{clientId:this._clientId,name:Be.ON_LIVE_STREAM_WARNING,options:[e,t],tag:je.TRACER}).onSuccess(),this.safeEmit(ft.LIVE_STREAMING_WARNING,e,t)},e.on($i.REQUEST_WORKER_MANAGER_LIST,((e,t,i)=>{if(!this._joinInfo)return i(new j(ne.INVALID_OPERATION,"can not find join info to get worker manager"));(async function(e,t,i,n){const o=ce("UAP_AP").slice(0,ce("AJAX_REQUEST_CONCURRENT")).map((e=>t.proxyServer?"https://".concat(t.proxyServer,"/ap/?url=").concat(e+"/api/v1?action=uap"):"https://".concat(e,"/api/v1?action=uap")));return await as(o,e,t,i,n)})(e,this._joinInfo,this._axiosCancelSource.token,Ke).then(t).catch(i)})),e};return e===Zi.RAW?(this._liveRawStreamingClient=this._liveRawStreamingClient||t(),this._liveRawStreamingClient):(this._liveTranscodeStreamingClient=this._liveTranscodeStreamingClient||t(),this._liveTranscodeStreamingClient)}_createChannelMediaRelayClient(){if(!this._joinInfo){return new j(ne.INVALID_OPERATION,"can not create channel media relay client, please join channel first").throw()}if(!this._channelMediaRelayClient){const t=this.getLocalVideoStats(),i=t.sendResolutionWidth,n=t.sendResolutionHeight,o=(e={joinInfo:this._joinInfo,clientId:this._clientId,websocketRetryConfig:this._config.websocketRetryConfig,httpRetryConfig:this._config.httpRetryConfig,resolution:{width:i,height:n}},Bo("ChannelMediaRelay").create(e));o.on("state",(e=>{e===nn.RELAY_STATE_FAILURE&&o&&o.dispose(),this.safeEmit(ft.CHANNEL_MEDIA_RELAY_STATE,e)})),o.on("event",(e=>{this.safeEmit(ft.CHANNEL_MEDIA_RELAY_EVENT,e)})),this._channelMediaRelayClient=o,this._statsCollector.onStatsChanged=(e,t)=>{var i;"resolution"===e&&(null===(i=this._channelMediaRelayClient)||void 0===i||i.setVideoProfile(t))}}var e;return this._channelMediaRelayClient}_handleFullDatachannel(e){const t=[],i=[];this._users.forEach((n=>{const o=n._dataChannels;o.forEach((i=>{e.some((e=>e.uid===n._uintid&&e.stream_id===i.id&&e.metadata===i.metadata))||t.push({uid:n._uintid,stream_id:i.id,ordered:i.ordered,max_retrans_times:i.maxRetransmits,metadata:i.metadata})})),e.filter((e=>e.uid===n._uintid)).forEach((e=>{if(!o.some((t=>n._uintid===e.uid&&t.id===e.stream_id&&t.metadata===e.metadata))){const o=t.findIndex((t=>n._uintid===t.uid&&t.stream_id===e.stream_id));-1!==o&&(i.push(e),t.splice(o,1))}}))})),this._handleDataChannelDeleted(t),this._handleDataChannelUpdated(i),this._handleDataChannelAdded(e,!0),B.debug("[".concat(this._clientId,"] emit full infos, data_channel ids: ").concat(e.map((e=>e.stream_id)))),this.safeEmit(ft.PUBLISHED_USER_LIST,this._pendingPublishedUsers),this._pendingPublishedUsers=[]}_handleDataChannelAdded(e,t){Array.isArray(e)&&e.length>0&&(B.debug("[".concat(this._clientId,"] data_channel ids: ").concat(e.map((e=>e.stream_id))," added")),e.forEach((e=>{const i=e.uid,n=e.stream_id,o=e.ordered,s=e.max_retrans_times,a=e.metadata,r=this._users.find((e=>e._uintid===i));if(!r)return void B.error("[".concat(this._clientId,"] can not find target user!(on_add_data_channel)"));B.debug("[".concat(this._clientId,"] data_channel added with uid ").concat(i)),r._uintid||(r._uintid=i);if(-1!==r._dataChannels.findIndex((t=>t.id===e.stream_id))){const t=r._dataChannels.find((t=>t.id===e.stream_id));null==t||t._updateDataChannelConfig(ki(ki({},null==t?void 0:t.getConfig()),{},{metadata:e.metadata}))}else{const e={id:n,ordered:!!o,maxRetransmits:s,metadata:a},i=function(e){return jo(e,!0)}(e);r._dataChannels.push(i),B.info("[".concat(this._clientId,"] remote user ").concat(r.uid," published datachannel")),t||this.safeEmit(ft.USER_PUBLISHED,r,"datachannel",e)}this._p2pChannel.hasPendingRemoteDataChannel(r,e.stream_id)&&(B.debug("[".concat(this._clientId,"] resubscribe datachannel id: ").concat(e.stream_id," for user ").concat(r.uid," after reconnect.")),this._subscribeDataChannel(r,e.stream_id).catch((e=>{B.error("[".concat(this._clientId,"] resubscribe datachannel error"),e.toString())})))})))}_handleDataChannelUpdated(e){Array.isArray(e)&&e.length>0&&(B.debug("[".concat(this._clientId,"] data_channel ids: ").concat(e.map((e=>e.stream_id))," updated")),e.forEach((e=>{var t;const i=e.uid,n=e.stream_id,o=e.metadata,s=this._users.find((e=>e._uintid===i));if(!s)return void B.error("[".concat(this._clientId,"] can not find target user!(on_update_data_channel)"));const a=s._dataChannels.find((e=>e.id===n));B.debug("[".concat(this._clientId,"] data_channel: ").concat(n," updated with uid ").concat(i,", last metadata: ").concat(null==a||null===(t=a._config)||void 0===t?void 0:t.metadata,", new metadata: ").concat(o)),this.safeEmit(ft.USER_UNPUBLISHED,s,"datachannel",null==a?void 0:a._config),this.safeEmit(ft.USER_PUBLISHED,s,"datachannel",{id:n,ordered:!!e.ordered,maxRetransmits:e.max_retrans_times,metadata:o})})))}_handleDataChannelDeleted(e){Array.isArray(e)&&e.length>0&&(B.debug("[".concat(this._clientId,"] data_channel ids: ").concat(e.map((e=>e.stream_id))," deleted")),e.forEach((e=>{const t=e.uid;e.stream_id;const i=this._users.find((e=>e._uintid===t));if(!i)return void B.error("[".concat(this._clientId,"] can not find target user!(on_delete_data_channel)"));const n=i._dataChannels.find((t=>t.id===e.stream_id));n&&(B.debug("[".concat(this._clientId,"] data_stream delete with uid ").concat(t)),i._dataChannels=i._dataChannels.filter((e=>e.id!==n.id)),this._p2pChannel.unsubscribeDataChannel(i,[n]).then((e=>{if(e)return this._gateway.unsubscribeDataChannel(e,i.uid)})),B.info("[".concat(this._clientId,"] remote user ").concat(t," unpublished datachannel , id:").concat(n.id)),this.safeEmit(ft.USER_UNPUBLISHED,i,"datachannel",n._config))})))}_handleUpdateDataChannel(e){const t=e.added,i=e.deleted;this._handleDataChannelDeleted(null!=i?i:[]),this._handleDataChannelAdded(null!=t?t:[])}_getEncodingName(e){var t,i;if(!this._joinResponse)return;const n=null===(t=this._joinResponse.ortc.rtpCapabilities.sendrecv)||void 0===t?void 0:t.videoCodecs;if(!n)return;for(const t of n){var o;if(t.payloadType===e)return null==t||null===(o=t.rtpMap)||void 0===o?void 0:o.encodingName}const s=null===(i=this._joinResponse.ortc.rtpCapabilities.recv)||void 0===i?void 0:i.videoCodecs;if(s)for(const t of s){var a;if(t.payloadType===e)return null==t||null===(a=t.rtpMap)||void 0===a?void 0:a.encodingName}return 0===e?"unknown":void 0}_handleRemoveDataChannels(e){const t=this._users.find((t=>t.uid===e.uid));if(t){if(void 0!==t._dataChannels&&t._dataChannels.length>0){B.debug("[".concat(this._clientId,"] datachannel removed with uid ").concat(e.uid));const i=()=>{B.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished datachannel")),t._dataChannels.forEach((e=>{this.safeEmit(ft.USER_UNPUBLISHED,t,"datachannel",e._config)}))};this._p2pChannel.unsubscribeDataChannel(t,t._dataChannels).then((e=>{if(e)return this._gateway.unsubscribeDataChannel(e,t.uid)})),i()}}else B.warning("[".concat(this._clientId,"] can not find target user!(on_remove_datachannel)"))}_handleGatewayEvents(){this._gateway.on(an.UPDATE_GATEWAY_CONFIG,(()=>{!function(){let e;try{e=window.localStorage.getItem("websdk_ng_global_parameter")}catch(e){return void B.error("Error loading sdk config",e.message)}if(e)try{const t=JSON.parse(window.atob(e)),i=Date.now();Object.keys(t).forEach((e=>{const n=t[e],o=n.value,s=n.type,a=n.expires;a&&a<=i||s||vi()||!Object.prototype.hasOwnProperty.call(ee,e)||($[e]=o,Z[e]=o,B.debug("Update gateway parameters from config distribute",e,o))}))}catch(e){B.error("Error update config from local cache",e.message)}}()})),this._gateway.on(an.DISCONNECT_P2P,(async()=>{await this._p2pChannel.disconnectForReconnect()})),this._gateway.on(an.CONNECTION_STATE_CHANGE,((e,t,i)=>{var n;if(i===ge.FALLBACK)return;const o=()=>{this.safeEmit(ft.CONNECTION_STATE_CHANGE,e,t,i)};if(G.reportApiInvoke(this._sessionId||(null===(n=this._gateway.joinInfo)||void 0===n?void 0:n.sid)||null,{clientId:this._clientId,name:Be.CONNECTION_STATE_CHANGE,options:[e,t,i],tag:je.TRACER}).onSuccess(JSON.stringify({cur:e,prev:t,reason:i})),B.info("[".concat(this._clientId,"] signal connection state change: ").concat(t," -> ").concat(e)),"DISCONNECTED"===e)return this._reset(),void o();if("RECONNECTING"===e)this._users.forEach((e=>{e._trust_in_room_=!1,e._trust_audio_enabled_state_=!1,e._trust_video_enabled_state_=!1,e._trust_audio_mute_state_=!1,e._trust_video_mute_state_=!1,e._trust_audio_stream_added_state_=!1,e._trust_video_stream_added_state_=!1,e._is_pre_created||(e._audio_pre_subscribed||(e._audioSSRC=void 0,e._audioOrtc=void 0),e._video_pre_subscribed||(e._videoSSRC=void 0,e._videoOrtc=void 0,e._rtxSsrcId=void 0),e._cname=void 0)})),this._userOfflineTimeout&&window.clearTimeout(this._userOfflineTimeout),this._streamRemovedTimeout&&window.clearTimeout(this._streamRemovedTimeout),this._userOfflineTimeout=void 0,this._streamRemovedTimeout=void 0;else if("CONNECTED"===e){var s;this._streamFallbackTypeCacheMap.forEach(((e,t)=>{this._gateway.setStreamFallbackOption(t,e).catch((e=>{B.warning("[".concat(this._clientId,"] auto set stream fallback option failed"),e)}))})),this._remoteStreamTypeCacheMap.forEach(((e,t)=>{this._gateway.setRemoteVideoStreamType(t,e).catch((e=>{B.warning("[".concat(this._clientId,"] auto set remote stream type failed"),e)}))})),ce("VOS_CONFIGURE")&&Array.isArray(ce("VOS_CONFIGURE"))&&ce("VOS_CONFIGURE").length>0&&(this._gateway.setConfigure(ce("VOS_CONFIGURE")).catch((e=>{B.debug("[".concat(this._clientId,"] auto set vos config failed"),e)})),B.debug("[".concat(this._clientId,"] ws connected auto set vos config"))),void 0!==this._remoteDefaultVideoStreamType&&void 0===(null===(s=this._joinInfo)||void 0===s?void 0:s.defaultVideoStream)&&this.setRemoteDefaultVideoStreamType(this._remoteDefaultVideoStreamType).then((()=>{B.debug("[".concat(this._clientId,"] setRemoteDefaultVideoStreamType after gateway connected"))})).catch((e=>{B.error("[".concat(this._clientId,"] setRemoteDefaultVideoStreamType after gateway failed, ").concat(e))})),this._dualStreamMode&&this._gateway.setDualStreamMode(this._dualStreamMode).catch((e=>{B.warning("[".concat(this._clientId,"] auto set dual stream mode failed"),e)})),this.store.useP2P||(this._p2pChannel.republish(),this._userOfflineTimeout=window.setTimeout((()=>{if("CONNECTED"!==this.connectionState)return;this._userOfflineTimeout=void 0;this._users.filter((e=>!e._trust_in_room_)).forEach((e=>{B.debug("[".concat(this._clientId,"] user offline timeout, emit user offline ").concat(e.uid)),this._handleUserOffline({uid:e.uid})}))}),3e3),this._streamRemovedTimeout=window.setTimeout((()=>{"CONNECTED"===this.connectionState&&(this._streamRemovedTimeout=void 0,this._users.forEach((e=>{e._trust_audio_mute_state_||(B.debug("[".concat(this._clientId,"] auto dispatch audio unmute event ").concat(e.uid)),this._handleMuteStream(e.uid,Sn.AUDIO,!1)),e._trust_video_mute_state_||(B.debug("[".concat(this._clientId,"] auto dispatch video unmute event ").concat(e.uid)),this._handleMuteStream(e.uid,Sn.VIDEO,!1)),e._trust_audio_enabled_state_||(B.debug("[".concat(this._clientId,"] auto dispatch enable local audio ").concat(e.uid)),this._handleSetStreamLocalEnable("audio",e.uid,!0)),e._trust_video_enabled_state_||(B.debug("[".concat(this._clientId,"] auto dispatch enable local video ").concat(e.uid)),this._handleSetStreamLocalEnable("video",e.uid,!0)),e._trust_video_stream_added_state_||(B.debug("[".concat(this._clientId,"] auto dispatch reset video stream added ").concat(e.uid)),this._handleResetAddStream(e,"video")),e._trust_audio_stream_added_state_||(B.debug("[".concat(this._clientId,"] auto dispatch reset audio stream added ").concat(e.uid)),this._handleResetAddStream(e,"audio")),e._video_added_||e._audio_added_||(B.debug("[".concat(this._clientId,"] auto dispatch stream remove ").concat(e.uid)),this._handleRemoveStream({uid:e.uid,uint_id:e._uintid}))})))}),1e3))}o()})),this._gateway.on(an.REQUEST_NEW_GATEWAY_LIST,(async(e,t)=>{if(!this._joinInfo)return t(new j(ne.UNEXPECTED_ERROR,"can not recover, no join info"));try{let t;if(this._fallbackServerInfo)t=this._fallbackServerInfo,this._fallbackServerInfo=void 0,this._joinInfo.preload=!1,G.reportApiInvoke(this._sessionId,{clientId:this._clientId,name:Be.VOS_FALLBACK_CN,options:{cur:t.gatewayInfo.gatewayAddrs,prev:this._joinInfo.gatewayAddrs,is_done:!0},tag:je.TRACER}).onSuccess(),B.info("[".concat(this._clientId,"] use fallback cn server info"));else{const e=await Or(ki(ki({},this._joinInfo),{},{uid:this._joinInfo.uid,stringUid:void 0}));e?(t=e.ap,Mr(e),this._joinInfo.preload=!0):(t=await Rs(this._joinInfo,this._axiosCancelSource.token,this._config.httpRetryConfig||Ke,this.store),this._joinInfo.preload=!1)}this._joinInfo&&(this._joinInfo.apResponse=t.gatewayInfo.res,this._joinInfo.gatewayAddrs=t.gatewayInfo.gatewayAddrs,this._joinInfo.uni_lbs_ip=t.gatewayInfo.uni_lbs_ip,delete this._joinInfo.signalResponse);const i=[];t.gatewayInfo.gatewayAddrs.forEach((e=>{const t=Mi(e.address.split(":"),2),n=t[0],o=t[1];this._joinInfo&&this._joinInfo.proxyServer?i.push({proxy:this._joinInfo.proxyServer,host:n,port:o}):i.push({host:n,port:o})})),e(i)}catch(e){t(e)}})),this._gateway.on(an.NETWORK_QUALITY,(e=>{"normal"===this._networkQualitySensitivity&&this.safeEmit(ft.NETWORK_QUALITY,e)})),this._gateway.on(an.STREAM_TYPE_CHANGE,((e,t)=>{this.safeEmit(ft.STREAM_TYPE_CHANGED,e,t);G.reportApiInvoke(this._sessionId,{clientId:this._clientId,name:Be.STREAM_TYPE_CHANGE,options:[e,t],tag:je.TRACER}).onSuccess(JSON.stringify({uid:e,streamType:t}))})),this._gateway.isPreSub=()=>"isPreSub"in this._p2pChannel&&this._p2pChannel.isPreSub(),this._gateway.isPreallocation=()=>"isPreallocation"in this._p2pChannel&&this._p2pChannel.isPreallocation(),this._gateway.on(an.IS_P2P_DISCONNECTED,(e=>{this._p2pChannel.isP2PDisconnected()?e(!0):this._p2pChannel.hasLocalMedia()||this._p2pChannel.hasRemoteMedia()?e(!1):e(!0)})),this._gateway.on(an.REQUEST_P2P_CONNECTION_PARAMS,(async(e,t,i)=>{try{let i=await this._p2pChannel.getEstablishParams();i&&"isPreallocation"in this._p2pChannel&&this._p2pChannel.isPreallocation()||(i=await this._p2pChannel.startP2PConnection(e)),t(i)}catch(e){i(e)}})),this._gateway.on(an.JOIN_RESPONSE,((e,t)=>{if(this.store.useP2P)return;let i;this._joinResponse=e,e.attributes?i=e.attributes.userAttributes.preSubSsrcs:B.debug("no attributes in joinResponse");const n=fo(e.ortc,t,i);this._p2pChannel.connect(n)})),this._gateway.on(an.PRE_CONNECT_PC,(async(e,t,i)=>{const n=e.candidates,o=e.fingerprint,s=e.turnServer;if(this._joinInfo&&n.length>0&&!this._p2pChannel.isPlanB){var a,r;const d=this._joinInfo.apResponse,l=d.cert,h=d.cid,u="".concat(h,"_").concat(l),_=e.iceUfrag||u,p=e.icePwd||u;if(!Wo(_,p))return void B.debug("[".concat(this._clientId,"] ufrag/pwd length is not valid, length: ").concat(_.length," / ").concat(p.length));let E;await this._p2pChannel.getEstablishParams()&&"isPreallocation"in this._p2pChannel&&this._p2pChannel.isPreallocation()?(this._p2pChannel.updateConnectionConfiguration({turnServer:s,cloudProxyServer:this._joinInfo.cloudProxyServer,isPreallocation:!0}),B.debug("pre pc before connect ws/dc, use sdp endpoint")):await this._p2pChannel.startP2PConnection({turnServer:s,cloudProxyServer:this._joinInfo.cloudProxyServer,isPreallocation:!0});const m=null===(a=this._joinInfo.signalResponse)||void 0===a||null===(a=a.attributes)||void 0===a||null===(a=a.userAttributes)||void 0===a?void 0:a.preSubSsrcs;Array.isArray(m)&&m.length>0&&(E=Co(m));const S=null===(r=this._joinInfo.signalResponse)||void 0===r?void 0:r.rtpCapabilities;try{var c;t(await this._p2pChannel.connect(ki({iceParameters:{iceUfrag:_,icePwd:p},dtlsParameters:{fingerprints:[{hashFunction:"sha-256",fingerprint:null!==(c=ce("FINGERPRINT"))&&void 0!==c?c:o}]},candidates:n,rtpCapabilities:S||{send:{audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]},recv:{audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]}},setup:"active",cname:"o/i14u9pJrxRKAsu",preallocation:!0},E?{preSSRCs:E}:{})))}catch(e){e.code&&e.code===ne.EXCHANGE_SDP_FAILED&&(B.debug("try to pre connect pc, but exchange sdp failed, reset p2p connection",e),await this._p2pChannel.startP2PConnection({turnServer:s,cloudProxyServer:this._joinInfo.cloudProxyServer},!0)),i(e)}}})),this._gateway.on(an.VOS_FALLBACK,(e=>{"fallback_hls"===e&&this.safeEmit(ft.FALLBACK_TO_HLS,jt.VOSERROR)})),this._gateway.on(an.RESET_SIGNAL,(()=>{this._p2pChannel instanceof ir&&this._p2pChannel.fallbackConnection(),this._handleGatewaySignalEvents()})),this._gateway.on(an.DATACHANNEL_FAILBACK,(()=>{G.reportApiInvoke(this._sessionId,{clientId:this._clientId,name:Be.DATACHANNEL_FAILBACK,options:{},tag:je.TRACER}).onSuccess(),this._joinGateway()}))}_handleGatewaySignalEvents(){this._gateway.signal.on(qi.ON_USER_ONLINE,this._handleUserOnline),this._gateway.signal.on(qi.ON_USER_OFFLINE,this._handleUserOffline),this._gateway.signal.on(qi.ON_ADD_AUDIO_STREAM,(e=>this._handleAddAudioOrVideoStream("audio",e.uid,e.ssrcId,e.cname,e.pt,e.uint_id,e.ortc))),this._gateway.signal.on(qi.ON_ADD_VIDEO_STREAM,(e=>this._handleAddAudioOrVideoStream("video",e.uid,e.ssrcId,e.cname,e.pt,e.uint_id,e.ortc,e.rtxSsrcId))),this._gateway.signal.on(qi.ON_REMOTE_DATASTREAM_UPDATE,(e=>{this._handleUpdateDataChannel(e)})),this._gateway.signal.on(qi.ON_REMOTE_FULL_DATASTREAM_INFO,(e=>{var t;this._handleFullDatachannel(null!==(t=e.datastreams)&&void 0!==t?t:[])})),this._gateway.signal.on(qi.ON_REMOVE_STREAM,this._handleRemoveStream),this._gateway.signal.on(qi.ON_P2P_LOST,this._handleP2PLost),this._gateway.signal.on(qi.MUTE_AUDIO,(e=>this._handleMuteStream(e.uid,Sn.AUDIO,!0))),this._gateway.signal.on(qi.UNMUTE_AUDIO,(e=>this._handleMuteStream(e.uid,Sn.AUDIO,!1))),this._gateway.signal.on(qi.MUTE_VIDEO,(e=>this._handleMuteStream(e.uid,Sn.VIDEO,!0))),this._gateway.signal.on(qi.UNMUTE_VIDEO,(e=>this._handleMuteStream(e.uid,Sn.VIDEO,!1))),this._gateway.signal.on(qi.RECEIVE_METADATA,(e=>{const t=vt(e.metadata);this.safeEmit(ft.RECEIVE_METADATA,e.uid,t)})),this._gateway.signal.on(qi.ON_DATA_STREAM,(async e=>{if(!e)return;let t=vt(e.payload);if(this._encryptDataStream&&this._encryptDataStreamIv&&this._encryptDataStreamKey&&window.crypto.subtle&&["aes-128-gcm2","aes-256-gcm2"].includes(this._encryptionMode)){if(e.payload.length<Jt)throw new j(ne.UNEXPECTED_RESPONSE,"payload length ".concat(e.payload.length," is less than header length ").concat(Jt));t=await Xt(this._encryptDataStreamIv,this._encryptDataStreamKey,t)}let i=0;if(e.ordered||e.syncWithAudio){const t=this._p2pChannel.getStats(),n=this.remoteUsers.find((t=>t.uid===e.uid)),o=null==t?void 0:t.audioRecv.find((e=>e.ssrc===(null==n?void 0:n._audioSSRC)));i=null==o?void 0:o.jitterBufferMs}(null==i||Number.isNaN(i))&&(i=0),lr(ki(ki({},e),{},{payload:t}),i,{id:this._clientId,onStreamMessage:"function"==typeof this.onStreamMessage?this.onStreamMessage.bind(this):void 0,safeEmit:this.safeEmit.bind(this)})})),this._gateway.signal.on(qi.ON_CRYPT_ERROR,(()=>{Rt((()=>{B.warning("[".concat(this._clientId,"] on crypt error")),this.safeEmit(ft.CRYPT_ERROR)}),this._sessionId)})),this._gateway.signal.on(qi.ON_TOKEN_PRIVILEGE_WILL_EXPIRE,this._handleTokenWillExpire),this._gateway.signal.on(qi.ON_TOKEN_PRIVILEGE_DID_EXPIRE,(()=>{B.warning("[".concat(this._clientId,"] received message onTokenPrivilegeDidExpire, please get new token and join again")),this._gateway.leave(!0,ge.TOKEN_EXPIRE),this.safeEmit(ft.ON_TOKEN_PRIVILEGE_DID_EXPIRE),this._reset()})),this._gateway.signal.on(qi.ON_STREAM_FALLBACK_UPDATE,(e=>{B.debug("[".concat(this._clientId,"] stream fallback peerId: ").concat(e.stream_id,", attr: ").concat(e.stream_type)),this.safeEmit(ft.STREAM_FALLBACK,e.stream_id,1===e.stream_type?"fallback":"recover")})),this._gateway.signal.on(qi.ENABLE_MULTI_STREAM,(e=>{this._dualStreamMode===Wt.AUTO_SIMULCAST_STREAM&&this.enableDualStream().catch((e=>{B.debug("[".concat(this._clientId,"] set dual stream mode error"),e.toString())}))})),this._gateway.signal.on(qi.ON_PUBLISH_STREAM,(e=>{this.uid===this._uid&&(this._p2pChannel.reportPublishEvent(!0,null,void 0,!1,JSON.stringify({proxy:e.proxy})),B.info("[".concat(this._clientId,"] on publish stream, ").concat(JSON.stringify(e))))})),this._gateway.signal.on(qi.ENABLE_LOCAL_VIDEO,(e=>{this._handleSetStreamLocalEnable("video",e.uid,!0)})),this._gateway.signal.on(qi.DISABLE_LOCAL_VIDEO,(e=>{this._handleSetStreamLocalEnable("video",e.uid,!1)})),this._gateway.signal.on(Hi.REQUEST_TIMEOUT,((e,t)=>{if(this._joinInfo)switch(e){case Ki.PUBLISH:{if(!t)return;const e=t.ortc;if(e){var i,n;const o=e.some((e=>e.stream_type===sn.Audio)),s=e.some((e=>e.stream_type!==sn.Audio)),a=e.some((e=>{let t=e.stream_type;return t===sn.Screen||t===sn.ScreenLow}));"offer"===t.state&&G.publish(this._joinInfo.sid,{eventElapse:Ys.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:!1,ec:ne.TIMEOUT,audio:o,video:s,p2pid:t.p2p_id,publishRequestid:this.store.pubId,screenshare:a,audioName:o?null===(i=e.find((e=>e.stream_type===sn.Audio)))||void 0===i||null===(i=i.ssrcs[0])||void 0===i?void 0:i.ssrcId.toString():void 0,videoName:s?null===(n=e.find((e=>e.stream_type!==sn.Audio)))||void 0===n||null===(n=n.ssrcs[0])||void 0===n?void 0:n.ssrcId.toString():void 0})}break}case Ki.SUBSCRIBE:t&&G.subscribe(this._joinInfo.sid,{succ:!1,ec:ne.TIMEOUT,audio:t.stream_type===Sn.AUDIO,video:t.stream_type===Sn.VIDEO,peerid:t.stream_id,subscribeRequestid:t.ssrcId,p2pid:this.store.p2pId,eventElapse:Ys.measureFromSubscribeStart(this.store.clientId,t.ssrcId),preSsrc:this._p2pChannel.isPreSubScribe(t.ssrcId)})}})),this._gateway.signal.on(qi.ON_P2P_OK,(e=>{this.uid,this._uid})),this._gateway.signal.on(qi.ON_PUBLISHED_USER_LIST,(e=>{if(null==e||!e.users)return;let t=e.users;ce("BLOCK_LOCAL_CLIENT")&&(t=t.filter((e=>!Ii(e.string_id||e.stream_id,this.channelName)))),this._handleUserList(t)})),this._gateway.signal.on(qi.ON_USER_LIST,(e=>{if(!e||!Array.isArray(e.users)||0===e.users.length)return;let t=e.users;t=ce("BLOCK_LOCAL_CLIENT")?t.filter((e=>!Ii(e.string_id||e.stream_id,this.channelName))):t,this._handleUserList(t)})),this._gateway.signal.on(qi.ON_RTP_CAPABILITY_CHANGE,(e=>{const t=e.video_codec;if(this._p2pChannel instanceof ir){if("audience"===this.role&&ce("UPDATE_RTP_CAP_IN_HOST"))return this._pendingRtpCapabilityChange=e,void B.debug("[".concat(this._clientId,"] no need to change rtp capability because of audience, params: ").concat(JSON.stringify(e)));this._p2pChannel.updateRemoteRTPCapabilities(t.map((e=>e.toLowerCase())).filter((e=>Object.keys(tt).includes(e))))}})),this._gateway.signal.on(Hi.VOS_FALLBACK_PROMISE,(async(e,t,i)=>{if("FALLBACKCN"===e&&ce("ENABLE_QUALITY_FALLBACK")){if(!this._joinInfo)return i(new j(ne.UNEXPECTED_ERROR,"can not recover, no join info"));B.info("[".concat(this._clientId,"] try fallback to cn, start request new server info"));const o=this._joinInfo.apRequestDetail;try{this._joinInfo.apRequestDetail=e;const n=await Rs(this._joinInfo,this._axiosCancelSource.token,this._config.httpRetryConfig||Ke,this.store);if(ce("QUALITY_FALLBACK_REHEARSAL"))return G.reportApiInvoke(this._sessionId,{clientId:this._clientId,name:Be.VOS_FALLBACK_CN,options:{cur:n.gatewayInfo.gatewayAddrs,prev:this._joinInfo.gatewayAddrs,is_done:!1},tag:je.TRACER}).onSuccess(),this._joinInfo.apRequestDetail=o,void i();this._fallbackServerInfo=n,t()}catch(e){var n;const t=null==e||null===(n=e.data)||void 0===n?void 0:n.desc;ce("QUALITY_FALLBACK_REHEARSAL")?(G.reportApiInvoke(this._sessionId,{clientId:this._clientId,name:Be.VOS_FALLBACK_CN,options:{cur:"failed, errorReason: "+t||"unknown",prev:this._joinInfo.gatewayAddrs,is_done:!1},tag:je.TRACER}).onSuccess(),this._joinInfo.apRequestDetail=o):Array.isArray(t)&&t.includes("request downgrade fallback")&&this.safeEmit(ft.FALLBACK_TO_HLS,jt.AP_ERROR),i(e)}}else i()}))}_handleUserList(e){var t=this;if(0===e.length)return;const i=[],n=[],o=[],s=[],a=[],r=[],c=this.getListeners(ft.USER_LIST).length>0,d=this.getListeners(ft.PUBLISHED_USER_LIST).length>0;for(const t of e){let e=this._users.find((e=>e._uintid===t.stream_id));const c=!!e;e?e._trust_in_room_=!0:(e=new Qs(t.string_id||t.stream_id,t.stream_id),this._users.push(e),this.store.firstVideoFrameDecoded(e.uid,{userJoinNotify:Date.now()}));const d=cn.Audio&t.stream_type,l=(cn.Video|cn.LowVideo)&t.stream_type,h=0!=(65280&t.stream_type),u=d&&e.hasAudio,_=l&&e.hasVideo;l&&(e._trust_video_stream_added_state_=!0,e._video_added_=!0,e._videoSSRC=t.video_ssrc,e._rtxSsrcId=t.video_rtx),d&&(e._trust_audio_stream_added_state_=!0,e._audio_added_=!0,e._audioSSRC=t.audio_ssrc),(d&&!u||l&&!_||h)&&(n.push(e),d&&!u&&o.push(e),l&&!_&&s.push(e)),c||a.push(e),l&&this._p2pChannel.hasPendingRemoteMedia(e,"video")&&r.push({user:e,mediaType:"video"}),d&&this._p2pChannel.hasPendingRemoteMedia(e,"audio")&&r.push({user:e,mediaType:"audio"}),i.push(e)}r.length>0&&(B.debug("[".concat(this._clientId,"] RE massSubscribe after reconnect ").concat(r.map((e=>"user: ".concat(e.user.uid,", mediaType: ").concat(e.mediaType))).join("; ")," ")),this.massSubscribe(r).catch((e=>{B.error("[".concat(this._clientId,"] mass resubscribe error"),e.toString())})));const l=function(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];B.info("[".concat(t._clientId,"] client not emit user-list event case there is no user-list listener...")),e||a.forEach((e=>{B.debug("[".concat(t._clientId,"] user online"),e._uintid),t.safeEmit(ft.USER_JOINED,e)})),n.length>0&&(o.forEach((e=>{B.info("[".concat(t._clientId,"] remote user ").concat(e.uid," published audio")),t.safeEmit(ft.USER_PUBLISHED,e,"audio")})),s.forEach((e=>{B.info("[".concat(t._clientId,"] remote user ").concat(e.uid," published video")),t.safeEmit(ft.USER_PUBLISHED,e,"video")})))};if(ce("ENABLE_USER_LIST"))c?(this.safeEmit(ft.USER_LIST,i),l(!0)):l();else if(d){if(n.length>0){const e=n.reduce(((e,t)=>"".concat(e&&e+", ").concat(t.uid)),"");ce("ENABLE_DATASTREAM_2")?this._pendingPublishedUsers=n:(B.info("[".concat(this._clientId,"] client emit published-user-list, users: ").concat(e)),this.safeEmit(ft.PUBLISHED_USER_LIST,n))}}else l()}_handleP2PEvents(){this._gateway.signal.on(qi.ON_USER_OFFLINE,(()=>{this._p2pChannel.disconnectForReconnect()})),this._gateway.signal.on(Dn.PUBLISH,((e,t,i)=>{const n=e.uid;e.forEach((e=>{const o=e.kind,s=e.ssrcs,a=e.mid,r=e.isMuted;this._handleP2PAddAudioOrVideoStream(o,n,s[0].ssrcId,a);const c=this._users.find((e=>e.uid===n));return c&&this.store.useP2P?this._p2pChannel.mockSubscribe(c,o,s[0].ssrcId,a).then((()=>{t()})).catch(i):t(),this._handleMuteStream(n,o,!!r)}))})),this._gateway.signal.on(Dn.CALL,(async(e,t,i)=>{if(this.store.useP2P)try{var n;t(await this._p2pChannel.startP2P({turnServer:null===(n=this._joinInfo)||void 0===n?void 0:n.turnServer},e))}catch(e){i(e)}})),this._gateway.signal.on(Hi.P2P_CONNECTION,(async e=>{this.store.useP2P&&(await this._p2pChannel).p2pConnect(e)})),this._gateway.signal.on(Dn.UNPUBLISH,(async(e,t,i)=>{if(this.store.useP2P){const n=e.unpubMsg,o=e.uid,s=this._users.find((e=>e.uid===o));if(!s)return B.warning("[".concat(this._clientId,"] can not find remote user, ignore mute event, uid: ").concat(o)),void t();try{n.forEach((async e=>{const t=e.stream_type===sn.Audio?Sn.AUDIO:Sn.VIDEO;await this._p2pChannel.unsubscribe(s,t),this._handleMuteStream(o,t,!0)})),t()}catch(e){i(e)}}})),this._gateway.signal.on(Dn.CONTROL,(async(e,t)=>{switch(e.action){case Pn.MUTE_LOCAL_VIDEO:this._handleMuteStream(t,Sn.VIDEO,!0);break;case Pn.MUTE_LOCAL_AUDIO:this._handleMuteStream(t,Sn.AUDIO,!0);break;case Pn.UNMUTE_LOCAL_VIDEO:this._handleP2PAddAudioOrVideoStream("video",t),this._handleMuteStream(t,Sn.VIDEO,!1);break;case Pn.UNMUTE_LOCAL_AUDIO:this._handleP2PAddAudioOrVideoStream("audio",t),this._handleMuteStream(t,Sn.AUDIO,!1)}})),this._gateway.signal.on(Dn.RESTART_ICE,(async(e,t,i)=>{if(this.store.useP2P)try{const i=e.direction,n=e.iceParameter;if(i!==Ji.SEND_ONLY||n){t(await this._p2pChannel.restartICE(i,n))}else this._p2pChannel.handleDisconnect(i),t()}catch(e){i(e)}})),this._gateway.signal.on(Dn.CANDIDATE,(e=>{if(this.store.useP2P){const t=e.candidate,i=e.direction;this._p2pChannel.addRemoteCandidate(t,i)}})),this._p2pChannel.on(In.RequestP2PRestartICE,(async(e,t,i)=>{try{const i=e.direction;t(await this._gateway.sendExtensionMessage(Dn.RESTART_ICE,e,i===Ji.SEND_ONLY))}catch(e){i(e)}})),this._p2pChannel.on(In.LocalCandidate,(e=>{this._gateway.sendExtensionMessage(Dn.CANDIDATE,JSON.stringify(e),!0)})),this._p2pChannel.on(In.RequestP2PMuteLocal,(async(e,t,i)=>{try{await this._gateway.sendExtensionMessage(Dn.CONTROL,e,!0),t()}catch(e){i(e)}})),this._p2pChannel.on(In.RequestP2PUnmuteRemote,(async(e,t,i)=>{if(this._joinInfo)try{await this._gateway.unmuteRemote(e,this._joinInfo.stringUid||this._joinInfo.uid),t()}catch(e){e.code===ne.DISCONNECT_P2P?t():i(e)}else t()})),this._p2pChannel.on(In.RequestP2PMuteRemote,(async(e,t,i)=>{if(this._joinInfo)try{await this._gateway.muteRemote(e,this._joinInfo.stringUid||this._joinInfo.uid),t()}catch(e){e.code===ne.DISCONNECT_P2P?t():i(e)}else t()})),this._p2pChannel.on(In.StateChange,((e,t)=>{t===gn.Connected&&this._p2pChannel.republish()}))}_handleP2PChannelEvents(){this._p2pChannel.on(In.PeerConnectionStateChange,(e=>{const t=this._peerConnectionState;e!==t&&(this.safeEmit(ft.PEERCONNECTION_STATE_CHANGE,e,t),this._peerConnectionState=e)})),this._p2pChannel.on(In.RequestMuteLocal,(async(e,t,i)=>{if(this._joinInfo)try{await this._gateway.muteLocal(e,this._joinInfo.stringUid||this._joinInfo.uid),t()}catch(e){e.code===ne.DISCONNECT_P2P?t():i(e)}else t()})),this._p2pChannel.on(In.RequestUnmuteLocal,(async(e,t,i)=>{if(this._joinInfo)try{await this._gateway.unmuteLocal(e,this._joinInfo.stringUid||this._joinInfo.uid),t()}catch(e){e.code===ne.DISCONNECT_P2P?t():i(e)}else t()})),this._p2pChannel.on(In.RequestRePublish,((e,t,i)=>{this.publish(e,!1).then(t).catch(i)})),this._p2pChannel.on(In.RequestRePublishDataChannel,((e,t,i)=>{Promise.all(e.map((async e=>{const t=await this._p2pChannel.publishDataChannel([e]);try{t.forEach((e=>{this._uid&&this._gateway.publishDataChannel(this._uid,e,!0)}))}catch(e){if(e.code!==ne.DISCONNECT_P2P)throw e}}))).then(t).catch(i)})),this._p2pChannel.on(In.RequestReSubscribe,(async(e,t,i)=>{try{for(const t of e){const e=t.user;t.kind===Sn.VIDEO?await this.subscribe(e,"video"):await this.subscribe(e,"audio")}t()}catch(e){i(e)}})),this._p2pChannel.on(In.RequestUpload,((e,t)=>{this._gateway.upload(e,t)})),this._p2pChannel.on(In.RequestUploadStats,(e=>{this._gateway.uploadWRTCStats(e)})),this._p2pChannel.on(In.MediaReconnectStart,(e=>{this.safeEmit(ft.MEDIA_RECONNECT_START,e)})),this._p2pChannel.on(In.MediaReconnectEnd,(e=>{this.safeEmit(ft.MEDIA_RECONNECT_END,e)})),this._p2pChannel.on(In.NeedSignalRTT,(e=>{e(this._gateway.getSignalRTT())})),this._p2pChannel.on(In.RequestRestartICE,(async e=>{if(this.store.useP2P)return;const t=await this._p2pChannel.restartICE(e),i=await t.next();if(i.done)return;const n=i.value;let o;try{o=await this._gateway.restartICE({iceParameters:n})}catch(e){return void t.throw(e)}const s=function(e){const t=e.iceParameters;return{iceParameters:{iceUfrag:t.iceUfrag,icePwd:t.icePwd}}}(o).iceParameters;await t.next({remoteIceParameters:s})})),this._p2pChannel.on(In.RequestReconnect,(async()=>{this._gateway.reconnect()})),this._p2pChannel.on(In.RequestReconnectPC,(async()=>{var e;const t=await this._p2pChannel.startP2PConnection({turnServer:null===(e=this._joinInfo)||void 0===e?void 0:e.turnServer}),i=t.iceParameters,n=t.dtlsParameters,o=t.rtpCapabilities,s=await this._gateway.reconnectPC({iceParameters:i,dtlsParameters:n,rtpCapabilities:o}),a=fo(s.gatewayEstablishParams,s.gatewayAddress);await this._p2pChannel.connect(a),await this._p2pChannel.republish(),await this._p2pChannel.reSubscribe()})),this._p2pChannel.on(In.RequestUnpublishForReconnectPC,(async(e,t,i)=>{this._joinInfo&&void 0!==this._uid?(await this._gateway.unpublish(e,this._uid),t()):i()})),this._p2pChannel.on(In.P2PLost,(()=>{this.safeEmit(ft.P2P_LOST,this.store.uid)})),this._p2pChannel.on(In.UpdateVideoEncoder,(e=>{e._encoderConfig&&this._gateway.setVideoProfile(e._encoderConfig)})),this._p2pChannel.on(In.ConnectionTypeChange,(e=>{this.safeEmit(ft.IS_USING_CLOUD_PROXY,e),this._gateway.setUsingProxy(e)})),this._p2pChannel.on(In.FirstVideoBufferReady,((e,t)=>{this.safeEmit(ft.FIRST_VIDEO_BUFFER_READY,e,t)})),this._p2pChannel.on(In.FirstVideoPreRender,((e,t)=>{this.safeEmit(ft.FIRST_VIDEO_PRE_RENDER,e,t)})),this._p2pChannel.on(In.RequestLowStreamParameter,(e=>{e(this._lowStreamParameter||{width:160,height:120,framerate:15,bitrate:50})})),this._p2pChannel.on(In.QueryClientConnectionState,(e=>{e(this.connectionState)})),this._p2pChannel.on(In.AudioMetadata,(e=>{this.safeEmit(ft.AUDIO_METADATA,e)})),this._p2pChannel.on(In.AudioPts,(e=>{this.safeEmit(ft.AUDIO_PTS,Number(e))}))}getKeyMetrics(){return this.store.keyMetrics}async enableContentInspect(e){if(!this._joinInfo||"CONNECTED"!==this.connectionState)throw new j(ne.INVALID_OPERATION,"[".concat(this._clientId,"] can not create content inspect, please join channel first"));if(this._inspect)throw new j(ne.INVALID_OPERATION,"[".concat(this._clientId,"] Inspect content service already in connecting/connected state"));try{const i=(t={config:e},Bo("ContentInspect").create(t));this._inspect=i,this.handleVideoInspectEvents(i);const n=this._joinInfo,o=n.appId,s=n.cname,a=n.sid,r=n.token,c=n.uid,d=n.cid,l=n.vid;await i.init({appId:o,areaCode:"",cname:s,sid:a,token:r,uid:c,cid:d,vid:l?Number(l):0},Ke)}catch(e){throw Array.isArray(e)?e[0]:e}var t}handleVideoInspectEvents(e){e.on(An.CONNECTION_STATE_CHANGE,((t,i)=>{if(this.safeEmit(ft.CONTENT_INSPECT_CONNECTION_STATE_CHANGE,t,i),i===vn.CONNECTED){if("CONNECTED"!==this.connectionState)return void this.safeEmit(ft.CONTENT_INSPECT_ERROR,new j(ne.OPERATION_ABORTED,"Content inspect was cancelled because it left the channel"));e.inspectImage()}})),e.on(An.INSPECT_RESULT,((e,t)=>{var i;if((null==t?void 0:t.code)===ne.INVALID_OPERATION&&"DISCONNECTED"===this.connectionState)return B.debug("Stop inspect content because that has left channel"),null==this||null===(i=this._inspect)||void 0===i||i.close(),void(this._inspect=void 0);this.safeEmit(ft.CONTENT_INSPECT_RESULT,e,t)})),e.on(An.CLIENT_LOCAL_VIDEO_TRACK,(e=>{e(this.localTracks.filter((e=>"video"===e.trackMediaType))[0])}))}async disableContentInspect(){if(!this._inspect)throw new j(ne.INVALID_OPERATION,"[".concat(this._clientId,"] inspectVideoContent not started"));try{this._inspect.close(),this._inspect=void 0}catch(e){throw Array.isArray(e)?e[0]:e}}async setImageModeration(e,t){if(Mt(e,"enabled"),e){if(!t)throw new j(ne.INVALID_PARAMS,"config is required");if(function(e){if(yt(e.interval,"interval",1e3,1/0),e&&e.extraInfo&&e.extraInfo.length>1024)throw new j(W.INVALID_PARAMS,"config.extraInfo length cannot exceed 1024 bytes");if(e&&e.vendor&&e.vendor.length>1024)throw new j(W.INVALID_PARAMS,"config.vendor length cannot exceed 1024 bytes")}(t),!this._joinInfo)throw new j(ne.INVALID_OPERATION,"can not create image moderation, please join channel first");try{if(this._moderation)this._moderation.updateConfig(t);else{const e=(i={config:t},Bo("ImageModeration").create(i));this._moderation=e,this.handleImageModerationEvents(e);const n=this._joinInfo,o=n.appId,s=n.cname,a=n.sid,r=n.token,c=n.uid,d=n.cid,l=n.vid;await e.init({appId:o,areaCode:"",cname:s,sid:a,token:r,uid:c,cid:d,vid:l?Number(l):0},Ke)}}catch(e){throw Array.isArray(e)?e[0]:e}}else{var i;if(!this._moderation)throw new j(ne.INVALID_OPERATION,"[".concat(this._clientId,"] image moderation not started"));try{this._moderation.close(),this._moderation.removeAllListeners(),this._moderation=void 0}catch(e){throw Array.isArray(e)?e[0]:e}}}handleImageModerationEvents(e){e.on(On.CONNECTION_STATE_CHANGE,((t,i)=>{if(this.safeEmit(ft.IMAGE_MODERATION_CONNECTION_STATE_CHANGE,t,i),t===bn.CONNECTED){if("CONNECTED"!==this.connectionState)throw this.setImageModeration(!1),new j(ne.OPERATION_ABORTED,"Image moderation was cancelled because it left the channel");e.inspectImage()}})),e.on(On.CLIENT_LOCAL_VIDEO_TRACK,(e=>{e(this.localTracks.filter((e=>"video"===e.trackMediaType))[0])}))}setP2PTransport(e){if(Qt(e),"p2p"!==this.mode)throw new j(ne.INVALID_OPERATION,"only p2p mode can set p2pTransport");this.store.p2pTransport=e,B.info("[".concat(this._clientId,"] set client p2pTransport to ").concat(e))}getJoinChannelServiceRecords(){return B.debug("getJoinChannelServiceRecords"),this.store.joinChannelServiceRecords}async setPublishAudioFilterEnabled(e){Mt(e,"enabled"),Ve("ENABLE_PUBLISH_AUDIO_FILTER",e),this._joinInfo&&await this._gateway.setPublishAudioFilterEnabled(e)}_setRteInfo(e,t){this.store.rteUrl=e,this.store.rteSid=t}_isPreRender(){return"isPreRender"in this._p2pChannel&&this._p2pChannel.isPreRender()}_handleResetAddStream(e,t){switch(t){case"audio":e._audio_added_=!1,e._trust_audio_stream_added_state_=!0;break;case"video":e._video_added_=!1,e._trust_video_stream_added_state_=!0}}}).prototype,"leave",[Wr],Object.getOwnPropertyDescriptor(Dc.prototype,"leave"),Dc.prototype),yi(Dc.prototype,"publish",[Hr],Object.getOwnPropertyDescriptor(Dc.prototype,"publish"),Dc.prototype),yi(Dc.prototype,"unpublish",[Kr],Object.getOwnPropertyDescriptor(Dc.prototype,"unpublish"),Dc.prototype),yi(Dc.prototype,"subscribe",[Yr],Object.getOwnPropertyDescriptor(Dc.prototype,"subscribe"),Dc.prototype),yi(Dc.prototype,"presubscribe",[qr],Object.getOwnPropertyDescriptor(Dc.prototype,"presubscribe"),Dc.prototype),yi(Dc.prototype,"massSubscribe",[Jr],Object.getOwnPropertyDescriptor(Dc.prototype,"massSubscribe"),Dc.prototype),yi(Dc.prototype,"unsubscribe",[Xr],Object.getOwnPropertyDescriptor(Dc.prototype,"unsubscribe"),Dc.prototype),yi(Dc.prototype,"massUnsubscribe",[Qr],Object.getOwnPropertyDescriptor(Dc.prototype,"massUnsubscribe"),Dc.prototype),yi(Dc.prototype,"setLowStreamParameter",[zr],Object.getOwnPropertyDescriptor(Dc.prototype,"setLowStreamParameter"),Dc.prototype),yi(Dc.prototype,"setDualStreamMode",[Zr],Object.getOwnPropertyDescriptor(Dc.prototype,"setDualStreamMode"),Dc.prototype),yi(Dc.prototype,"enableDualStream",[$r],Object.getOwnPropertyDescriptor(Dc.prototype,"enableDualStream"),Dc.prototype),yi(Dc.prototype,"disableDualStream",[ec],Object.getOwnPropertyDescriptor(Dc.prototype,"disableDualStream"),Dc.prototype),yi(Dc.prototype,"setClientRole",[tc],Object.getOwnPropertyDescriptor(Dc.prototype,"setClientRole"),Dc.prototype),yi(Dc.prototype,"_setClientRoleOptions",[ic],Object.getOwnPropertyDescriptor(Dc.prototype,"_setClientRoleOptions"),Dc.prototype),yi(Dc.prototype,"setProxyServer",[nc],Object.getOwnPropertyDescriptor(Dc.prototype,"setProxyServer"),Dc.prototype),yi(Dc.prototype,"setTurnServer",[oc],Object.getOwnPropertyDescriptor(Dc.prototype,"setTurnServer"),Dc.prototype),yi(Dc.prototype,"setLicense",[sc],Object.getOwnPropertyDescriptor(Dc.prototype,"setLicense"),Dc.prototype),yi(Dc.prototype,"startProxyServer",[ac],Object.getOwnPropertyDescriptor(Dc.prototype,"startProxyServer"),Dc.prototype),yi(Dc.prototype,"stopProxyServer",[rc],Object.getOwnPropertyDescriptor(Dc.prototype,"stopProxyServer"),Dc.prototype),yi(Dc.prototype,"setLocalAccessPointsV2",[cc],Object.getOwnPropertyDescriptor(Dc.prototype,"setLocalAccessPointsV2"),Dc.prototype),yi(Dc.prototype,"setLocalAccessPoints",[dc],Object.getOwnPropertyDescriptor(Dc.prototype,"setLocalAccessPoints"),Dc.prototype),yi(Dc.prototype,"setRemoteDefaultVideoStreamType",[lc],Object.getOwnPropertyDescriptor(Dc.prototype,"setRemoteDefaultVideoStreamType"),Dc.prototype),yi(Dc.prototype,"setRemoteVideoStreamType",[hc],Object.getOwnPropertyDescriptor(Dc.prototype,"setRemoteVideoStreamType"),Dc.prototype),yi(Dc.prototype,"setStreamFallbackOption",[uc],Object.getOwnPropertyDescriptor(Dc.prototype,"setStreamFallbackOption"),Dc.prototype),yi(Dc.prototype,"setEncryptionConfig",[_c],Object.getOwnPropertyDescriptor(Dc.prototype,"setEncryptionConfig"),Dc.prototype),yi(Dc.prototype,"renewToken",[pc],Object.getOwnPropertyDescriptor(Dc.prototype,"renewToken"),Dc.prototype),yi(Dc.prototype,"enableAudioVolumeIndicator",[Ec],Object.getOwnPropertyDescriptor(Dc.prototype,"enableAudioVolumeIndicator"),Dc.prototype),yi(Dc.prototype,"startLiveStreaming",[mc],Object.getOwnPropertyDescriptor(Dc.prototype,"startLiveStreaming"),Dc.prototype),yi(Dc.prototype,"setLiveTranscoding",[Sc],Object.getOwnPropertyDescriptor(Dc.prototype,"setLiveTranscoding"),Dc.prototype),yi(Dc.prototype,"stopLiveStreaming",[fc],Object.getOwnPropertyDescriptor(Dc.prototype,"stopLiveStreaming"),Dc.prototype),yi(Dc.prototype,"startChannelMediaRelay",[Cc],Object.getOwnPropertyDescriptor(Dc.prototype,"startChannelMediaRelay"),Dc.prototype),yi(Dc.prototype,"updateChannelMediaRelay",[Rc],Object.getOwnPropertyDescriptor(Dc.prototype,"updateChannelMediaRelay"),Dc.prototype),yi(Dc.prototype,"stopChannelMediaRelay",[Tc],Object.getOwnPropertyDescriptor(Dc.prototype,"stopChannelMediaRelay"),Dc.prototype),yi(Dc.prototype,"sendCustomReportMessage",[gc],Object.getOwnPropertyDescriptor(Dc.prototype,"sendCustomReportMessage"),Dc.prototype),yi(Dc.prototype,"pickSVCLayer",[Ic],Object.getOwnPropertyDescriptor(Dc.prototype,"pickSVCLayer"),Dc.prototype),yi(Dc.prototype,"setRTMConfig",[vc],Object.getOwnPropertyDescriptor(Dc.prototype,"setRTMConfig"),Dc.prototype),yi(Dc.prototype,"enableContentInspect",[Ac],Object.getOwnPropertyDescriptor(Dc.prototype,"enableContentInspect"),Dc.prototype),yi(Dc.prototype,"disableContentInspect",[yc],Object.getOwnPropertyDescriptor(Dc.prototype,"disableContentInspect"),Dc.prototype),yi(Dc.prototype,"setImageModeration",[Nc],Object.getOwnPropertyDescriptor(Dc.prototype,"setImageModeration"),Dc.prototype),yi(Dc.prototype,"setP2PTransport",[wc],Object.getOwnPropertyDescriptor(Dc.prototype,"setP2PTransport"),Dc.prototype),yi(Dc.prototype,"getJoinChannelServiceRecords",[bc],Object.getOwnPropertyDescriptor(Dc.prototype,"getJoinChannelServiceRecords"),Dc.prototype),yi(Dc.prototype,"setPublishAudioFilterEnabled",[Oc],Object.getOwnPropertyDescriptor(Dc.prototype,"setPublishAudioFilterEnabled"),Dc.prototype),Dc);function Lc(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{codec:"vp8",audioCodec:"opus",mode:"rtc"};const t=ve(5,"client-"),i=G.reportApiInvoke(null,{id:t,clientId:t,name:Be.CREATE_CLIENT,options:[e],tag:je.TRACER});try{zt(e),(st(16,0,!0)||rt(16,0,!0))&&("vp9"===e.codec&&(e.codec="vp8",B.debug("browser not support vp9, force use vp8")),Ve("UNSUPPORTED_VIDEO_CODEC",["vp9"])),void 0===e.audioCodec&&(e.audioCodec="opus");const n=new Pc(ki(ki({forceWaitGatewayResponse:!0},e),{},{role:["rtc","p2p"].includes(e.mode)?"host":e.role||"audience"}),t);return i.onSuccess(),xs((()=>Vs.onCreateClient())),n}catch(e){throw i.onError(e),e}}async function kc(){let e={audio:[],video:[]};try{let t=new RTCPeerConnection;const i=await async function(e){let t;return o().supportUnifiedPlan?(e.addTransceiver("video",{direction:"recvonly"}),e.addTransceiver("audio",{direction:"recvonly"}),t=(await e.createOffer()).sdp):t=(await e.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0})).sdp,t}(t);if(!i)return e;t.close(),t=null,e=function(e){const t={video:[],audio:[]};return e.match(/ VP8/i)&&t.video.push("VP8"),e.match(/ VP9/i)&&t.video.push("VP9"),e.match(/ AV1/i)&&t.video.push("AV1"),e.match(/ H264/i)&&t.video.push("H264"),e.match(/ H265/i)&&t.video.push("H265"),e.match(/ opus/i)&&t.audio.push("OPUS"),e.match(/ PCMU/i)&&t.audio.push("PCMU"),e.match(/ PCMA/i)&&t.audio.push("PCMA"),e.match(/ G722/i)&&t.audio.push("G722"),t}(i)}catch(e){throw new j(ne.CREATE_OFFER_FAILED,e.toString&&e.toString()).print()}return e}function Mc(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];const t=G.reportApiInvoke(null,{name:Be.CHECK_SYSTEM_REQUIREMENTS,options:[],tag:je.TRACER}),i=function(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],t=!1;try{const i=window.RTCPeerConnection,n=navigator.mediaDevices&&navigator.mediaDevices.getUserMedia,o=window.WebSocket;t=!(!i||!o),e&&!n&&(t=!1),t&&Zt()&&$t(75)&&(new i).close()}catch(e){B.error("check system requirement failed: ",e),t=!1}return t}(e),n=function(){let e=!1;const t=Pe();return(t.name===Le.CHROME&&Number(t.version)>=58&&(!ze()||ei())||t.name===Le.FIREFOX&&Number(t.version)>=56||t.name===Le.OPERA&&Number(t.version)>=45||t.name===Le.SAFARI&&Number(t.version)>=11||"WebKit"===t.name&&(wt()||ti())&&t.osVersion&&Number(t.osVersion.split(".")[0])>=11||ii()||ni())&&(e=!0),e}();B.debug("checkSystemRequirements, api:",i,"browser",n);const o=i&&n;return t.onSuccess(o),ce("IGNORE_RTC_DEVICE_CHECK")?i:o}class Uc{constructor(e,t){this.id=0,this.element=void 0,this.peerPair=void 0,this.context=void 0,this.audioPlayerElement=void 0,this.audioTrack=void 0,Uc.count+=1,this.id=Uc.count,this.element=e,this.context=t}initPeers(){this.peerPair=[new RTCPeerConnection,new RTCPeerConnection],this.peerPair[1].ontrack=e=>{const t=document.createElement("audio");t.srcObject=new MediaStream([e.track]),t.play(),this.audioPlayerElement=t}}async switchSdp(){if(!this.peerPair)return;const e=async(e,t)=>{const i="offer"===t?await e.createOffer():await e.createAnswer();return await e.setLocalDescription(i),"complete"===e.iceGatheringState?e.localDescription:new Promise((t=>{e.onicegatheringstatechange=()=>{"complete"===e.iceGatheringState&&t(e.localDescription)}}))},t=async(e,t)=>await e.setRemoteDescription(t);try{const i=await e(this.peerPair[0],"offer");await t(this.peerPair[1],i);const n=await e(this.peerPair[1],"answer");await t(this.peerPair[0],n)}catch(e){throw new j(ne.LOCAL_AEC_ERROR,e.toString()).print()}}async getTracksFromMediaElement(e){if(this.audioTrack)return this.audioTrack;let t;try{e instanceof HTMLVideoElement&&(e.captureStream?e.captureStream():e.mozCaptureStream()),t=this.context.createMediaStreamDestination();this.context.createMediaElementSource(e).connect(t)}catch(e){throw new j(ne.LOCAL_AEC_ERROR,e.toString()).print()}if(!t){throw new j(ne.LOCAL_AEC_ERROR,"no dest node when local aec").print()}const i=t.stream.getAudioTracks()[0];return this.audioTrack=i,i}getElement(){return this.element}async startEchoCancellation(){this.context.resume(),this.peerPair&&this.close(),this.initPeers();const e=this.element,t=await this.getTracksFromMediaElement(e);this.peerPair&&this.peerPair[0].addTrack(t),await this.switchSdp()}close(){B.debug("close echo cancellation unit, id is",this.id),this.audioPlayerElement&&this.audioPlayerElement.pause(),this.peerPair&&this.peerPair.forEach((e=>{e.close()})),this.peerPair=void 0,this.audioPlayerElement=void 0}}var Vc,xc;Uc.count=0;const Fc=window.AudioContext||window.webkitAudioContext;const Bc=new(Vc=Q({report:G}),yi((xc=class{constructor(){this.units=[],this.context=void 0}processExternalMediaAEC(e){if(!this._doesEnvironmentNeedAEC())return B.debug("the system does not need to process local aec"),-1;this.context||(this.context=new Fc);let t=this.units.find((t=>t&&t.getElement()===e));return t||(t=new Uc(e,this.context),this.units.push(t)),t.startEchoCancellation(),B.debug("start processing local audio echo cancellation, id is",t.id),t.id}_doesEnvironmentNeedAEC(){return Pe().name!==Le.SAFARI}}).prototype,"processExternalMediaAEC",[Vc],Object.getOwnPropertyDescriptor(xc.prototype,"processExternalMediaAEC"),xc.prototype),xc);const jc=window||document;function Gc(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(!jc)return;const i=pd._cspEventHandlerPointer;if(i&&t)return void console.error(i,t);const n=e=>{if(!(e&&e.blockedURI&&(pd.onSecurityPolicyViolation||pd.getListeners(wn.SECURITY_POLICY_VIOLATION).length>0)))return;const t=e.blockedURI;ce("CSP_DETECTED_HOSTNAME_LIST").some((e=>t.includes(e)))&&(pd.onSecurityPolicyViolation&&"function"==typeof pd.onSecurityPolicyViolation&&pd.onSecurityPolicyViolation(e),pd.getListeners(wn.SECURITY_POLICY_VIOLATION).length>0&&pd.safeEmit(wn.SECURITY_POLICY_VIOLATION,e))};i&&jc.removeEventListener("securitypolicyviolation",i),(t||e&&"function"==typeof e||pd.getListeners(wn.SECURITY_POLICY_VIOLATION).length>0)&&jc.addEventListener("securitypolicyviolation",n),pd._cspEventHandlerPointer=n}var Wc;let Hc=(Wc=class e extends mn{get currentLocalDescription(){return this.peerConnection.currentLocalDescription}get currentRemoteDescription(){return this.peerConnection.currentRemoteDescription}get peerConnectionState(){return this.peerConnection.connectionState}get iceConnectionState(){return this.peerConnection.iceConnectionState}get dtlsTransportState(){var e,t;return null!==(e=null===(t=this.peerConnection.getReceivers()[0])||void 0===t||null===(t=t.transport)||void 0===t?void 0:t.state)&&void 0!==e?e:null}get localCodecs(){return[...new Set(this.localCapabilities&&this.localCapabilities.send.videoCodecs.map((e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"")).filter((e=>Object.keys(tt).includes(e))))]}constructor(e,t,i){super(e,t),this.id=ve(5,"connection-"),this.store=void 0,this.peerConnection=void 0,this.forceTurn=!1,this.remoteSDP=void 0,this.initialOffer=void 0,this.transportEventReceiver=void 0,this.statsFilter=void 0,this.extension={useXR:ce("USE_XR")},this.localCapabilities=void 0,this.remoteCodecs=void 0,this.localCandidateCount=0,this.allCandidatesReceived=!1,this.isPreallocation=!1,this.preMediaMap=new Map,this.dataStreamChannelMap=new Map,this.establishPromise=void 0,this.recoveredDataChannelIds=[],this.currentDataChannelId=1,this.supportAV1RtpSpec=!1,this.mutex=void 0,this.qualityLimitationReason=nt.NONE,this.unsupportedResolutionFloorTrackIds=new Set,this.isFirstConnected=!1,this.store=t,this.forceTurn=Na(e),this.mutex=new ue("NVConnectionExtension-mutex",t.clientId),this.peerConnection=i,this.isFirstConnected=!1,this.statsFilter=lt(this.peerConnection,ce("STATS_UPDATE_INTERVAL"),void 0,he()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1,e.isPreallocation&&(this.isPreallocation=!0),this.establishPromise=this.establish()}getPreMedia(e){return this.preMediaMap.get(e)}isPreSub(){return this.preMediaMap.size>0}async updateRemoteRTPCapabilities(e,t){if(this.remoteCodecs=t,!this.remoteSDP)return void B.debug("[NVConnectionExtension] cannot updateRemoteRTPCapabilities before remote SDP created, local codecs: ".concat(this.localCodecs,", codecs: ").concat(t));if(this.remoteSDP.updateRemoteCodec(e,t,this.store.codec)){const e=await this.peerConnection.createOffer(),t=this.logSDPExchange(e.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(e);const i=this.remoteSDP.toString();null==t||t(i),await this.peerConnection.setRemoteDescription({type:"answer",sdp:i})}else B.debug("[NVConnectionExtension] updateRemoteRTPCapabilities no need to exchange SDP.")}async establish(){try{this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.peerConnection.addTransceiver("audio",{direction:"recvonly"});const t=await this.peerConnection.createOffer();if(!t.sdp)throw new Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");const i=mo(t.sdp),n=await yo({filterRTX:!ce("USE_PUB_RTX")&&!ce("USE_SUB_RTX"),filterVideoFec:ce("FILTER_VIDEO_FEC"),filterAudioFec:ce("FILTER_AUDIO_FEC"),filterVideoCodec:ce("FILTER_VIDEO_CODEC"),unsupportedVideoUplinkCodec:ce("UNSUPPORTED_VIDEO_UPLINK_CODEC"),unsupportedVideoDownlinkCodec:ce("UNSUPPORTED_VIDEO_DOWNLINK_CODEC")},this.extension);if(this.localCapabilities=wo(n),this.initialOffer=t,ce("ENABLE_SVC")&&"av1"==this.store.codec){const t=await Ao();var e;if(t)this.supportAV1RtpSpec=!0,null===(e=n.send)||void 0===e||e.videoExtensions.push(t)}let o;return t.sdp&&Uo(t.sdp)&&(o=Oe(n),co(o)),ki(ki({},i),{},{rtpCapabilities:o||n,offerSDP:t.sdp})}catch(e){throw new me(ne.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString())}}async connect(e){try{if(!this.initialOffer)throw new Error("Cannot establish NVConnectionExtension without initial offer.");if(this.initialOffer.sdp&&Uo(this.initialOffer.sdp)&&lo(e.rtpCapabilities,this.localCapabilities),this.remoteSDP=new ta(ki(ki({},e),{},{localCapabilities:this.localCapabilities}),this.supportAV1RtpSpec,!(!ce("ENABLE_PRE_SUB_WITH_PRE_PC")||!ce("PRE_USE_LOCAL_CODECS"))&&_(this.store),!0),e.preallocation&&(this.isPreallocation=!0),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0&&this.remoteSDP.updateRemoteCodec([],this.remoteCodecs,this.store.codec),p()){var t;const e=(null===(t=this.store.preSubOptions)||void 0===t?void 0:t.length)||0,i=ce("PRE_SUB_NUM")||1,n=e>i?e:i,o=this.remoteSDP.preloadRemoteMedia(n),s=o.mids,a=o.preSSRCs,r=Lo(this.initialOffer.sdp,this.extension),c=this.logSDPExchange(r||"","offer","local","connect");this.store.descriptionStart(),await this.peerConnection.setLocalDescription({type:"offer",sdp:r}),null==c||c(r),new Array(n).fill(0).forEach((()=>{this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.peerConnection.addTransceiver("audio",{direction:"recvonly"})}));const d=await this.peerConnection.createOffer(),l=this.logSDPExchange(d.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(d);const h=this.remoteSDP.toString();null==l||l(h),await this.peerConnection.setRemoteDescription({type:"answer",sdp:h}),B.debug("[".concat(this.store.clientId,"] [P2PConnection] preload media with icc/dtls, add preload ssrcs ").concat(a)),this.presetMedia(s,a);const u=this.peerConnection.getTransceivers()[0];null!=u&&u.receiver&&this.tryBindTransportEvents(u.receiver)}else{const t=this.remoteSDP.toString(),n=Lo(this.initialOffer.sdp,this.extension),o=this.logSDPExchange(n||"","offer","local","connect");this.store.descriptionStart(),await this.peerConnection.setLocalDescription({type:"offer",sdp:n}),null==o||o(t),await this.peerConnection.setRemoteDescription({type:"answer",sdp:t});const s=this.peerConnection.getTransceivers()[0];if(null!=s&&s.receiver&&this.tryBindTransportEvents(s.receiver),_(this.store))if(e.preallocation&&ce("ENABLE_PRE_SUB_WITH_PRE_PC")){var i;const e=(null===(i=this.store.preSubOptions)||void 0===i?void 0:i.length)||0,t=ce("PRE_SUB_NUM")||1,n=e>t?e:t,o=this.remoteSDP.preloadRemoteMedia(n),s=o.mids,a=o.preSSRCs;await Po(this.peerConnection,this.remoteSDP,this.extension),B.debug("[".concat(this.store.clientId,"] [P2PConnection] preload media, in pre pc,add preload ssrcs ").concat(a)),this.presetMedia(s,a)}else{const t=e.preSSRCs,i=void 0===t?[]:t,n=i.map((e=>e.ssrcMsg[0].ssrcId));if(0===i.length)return;const o=this.remoteSDP.batchSend(i.map((e=>Object.assign({},e)))).mids;await Po(this.peerConnection,this.remoteSDP,this.extension),B.debug("[P2PConnection.connect] preload media, after join, add preload ssrcs ".concat(n)),this.presetMedia(o,n)}}}catch(e){throw new me(ne.EXCHANGE_SDP_FAILED,"NVConnectionExtension.connect failed; ".concat(e.toString()))}}presetMedia(e,t){e.forEach(((e,i)=>{this.peerConnection.getTransceivers().forEach((n=>{if(null!=n.mid&&e===n.mid&&n.receiver.track){const o=n.receiver.track;let s;"video"===o.kind&&ce("ENABLE_PRE_RENDER")&&(s=new m({trackId:"track-".concat(o.kind,"-unknown-").concat(this.store.clientId,"_").concat(ve(5,""))},!0),s.updateVideoTrack(o),s.onFirstVideoFrameRender=()=>{var e;const n=this.preMediaMap.get(t[i]);n&&(n.firstVideoRender=Date.now()),null===(e=this.onFirstVideoRender)||void 0===e||e.call(this,t[i])},s.onVideoBufferReady=()=>{var e;null===(e=this.onFirstVideoBufferReady)||void 0===e||e.call(this,t[i])},s.play(this.store.sessionId||void 0)),this.preMediaMap.set(t[i],{mid:e,track:o,player:s,transceiver:n})}})),this.store.peerReceiver()}))}checkDtlsParameters(e){return!!this.remoteSDP&&(e.length>0&&this.remoteSDP.updateRemoteDtlsParameters(e))}checkIceParameters(e){if(!this.remoteSDP)return!1;return this.remoteSDP.restartICE(e)}async updateRemoteConnect(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.updateRemoteConnect before remote SDP created");let t=!1;const i=e.rtpCapabilities;if(t=Mi(this.remoteSDP.updateRemoteRTPCapabilities(i),2)[1],Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0){const e=this.remoteSDP.updateRemoteCodec([],this.remoteCodecs,this.store.codec);t=t||e}const n=e.preSSRCs,o=void 0===n?[]:n,s=o.map((e=>e.ssrcMsg[0].ssrcId));if(!this.remoteSDP.checkPreloadSsrcs(s)){const e=[],t=[];if(Array.from(this.preMediaMap.entries()).every((i=>{let n=Mi(i,2),o=n[0],s=n[1],a=s.mid,r=s.player;s.track;return e.push(a),t.push(o),this.preMediaMap.delete(o),r&&r.destroy(),!0})),e.length>0&&(this.remoteSDP.stopSending(e),await Po(this.peerConnection,this.remoteSDP,this.extension),B.warn("[NVConnectionExtension.updateRemoteConnect] preload media, failed, del preload ssrcs ".concat(t)),G.reportApiInvoke(this.store.sessionId,{name:Be.PRELOAD_MEDIA_FAILED,options:[o,t],tag:je.TRACER}).onSuccess()),o.length>0){const e=this.remoteSDP.batchSend(o.map((e=>Object.assign({},e)))).mids;await Po(this.peerConnection,this.remoteSDP,this.extension),B.debug("[NVConnectionExtension.updateRemoteConnect] preload media, after join, add preload ssrcs ".concat(s)),this.presetMedia(e,s)}}t?(await Po(this.peerConnection,this.remoteSDP,this.extension),B.debug("[NVConnectionExtension] updateRemoteConnect by exchanging SDP.")):B.debug("[NVConnectionExtension] updateRemoteConnect no need to exchange SDP, because no need to update remote codecs (use local codecs)")}catch(e){throw new me(ne.EXCHANGE_SDP_FAILED,"NVConnectionExtension.updateRemoteConnect failed; ".concat(e.toString()))}}send(e,t,i){var n=this;return Ui((function*(){const o=yield Di(n.mutex.lock("From NVConnectionExtension.send"));try{if(!n.remoteSDP)throw new Error("Cannot call NVConnectionExtension.send before remote SDP created");const s=[],a=ao();e.forEach((e=>{const t=n.peerConnection.addTransceiver(e._mediaStreamTrack,ki({direction:"sendonly"},"video"===e.trackMediaType&&n.supportAV1RtpSpec&&a?{sendEncodings:[{scalabilityMode:a}]}:{}));s.push(t),e._updateRtpTransceiver(t)})),he()&&!0===ce("SIMULCAST")&&(yield Di(n.applySimulcastForFirefox(s,e)));const r=yield Di(n.peerConnection.createOffer()),c=n.remoteSDP.predictReceivingMids(e.length),d=n.mungSendOfferSDP(r.sdp,e,c),l=be(d),h=c.map((e=>{const t=l.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error("Cannot extract ssrc from mediaDescription.");return So(t,ce("USE_PUB_RTX"))}));let u;try{u=yield h}catch(o){u=[],n.remoteSDP.receive(e,t,i,u);const s=n.remoteSDP.toString();throw yield Di(n.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield Di(n.peerConnection.setRemoteDescription({type:"answer",sdp:s})),yield Di(n.stopSending(c,!0)),o}n.remoteSDP.receive(e,t,i,u);const _=n.remoteSDP.toString(),p=n.logSDPExchange(d,"offer","local","send");return yield Di(n.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield Di(n.applySimulcastEncodings(s,e)),yield Di(n.applySendEncodings(s,e)),null==p||p(_),yield Di(n.peerConnection.setRemoteDescription({type:"answer",sdp:_})),s.map(((e,t)=>{const i=c[t];return{localSSRC:h[t],id:i,transceiver:e}}))}catch(e){throw e instanceof me?e:new me(ne.EXCHANGE_SDP_FAILED,"NVConnectionExtension.send failed; ".concat(e.toString()))}finally{o()}}))()}async createDataChannels(e,t){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.createDataChannels before remote SDP created");let i=this.dataStreamChannelMap.get(e);if(i&&"open"===i.readyState)B.debug("[NVConnectionExtension] Channels are already available and can be reused directly.");else{const t=this.currentDataChannelId<1023?this.currentDataChannelId++:this.recoveredDataChannelIds.shift();if("number"!=typeof t)throw new Error("create DataChannel error, because cannot get dc id");i=this.peerConnection.createDataChannel("datastream-channel",{id:t,negotiated:!0,ordered:!1,maxRetransmits:ce("DATASTREAM_MAX_RETRANSMITS")}),i.binaryType="arraybuffer",this.dataStreamChannelMap.set(e,i)}t.forEach((e=>{e._updateOriginDataChannel(i)}));const n=this.remoteSDP.sendDataChannel();if(n.needExchangeSDP){const e=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:e});const t=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(t),B.debug("[NVConnectionExtension] createDataChannels by exchanging SDP.")}else B.debug("[NVConnectionExtension] createDataChannels no need to exchange SDP.");return}catch(e){throw e instanceof me?e:new me(ne.EXCHANGE_SDP_FAILED,"NVConnectionExtension.createDataChannels failed; ".concat(e.toString()))}}async stopDataChannels(e){try{const t=this.dataStreamChannelMap.get(e);return t&&(t.id&&this.recoveredDataChannelIds.push(t.id),t.close()),void this.dataStreamChannelMap.delete(e)}catch(e){throw e instanceof me?e:new me(ne.DATACHANNEL_FAILED,"NVConnectionExtension.stopDataChannels failed; ".concat(e.toString()))}}async stopSending(e,t){const i=t?void 0:await this.mutex.lock("From NVConnectionExtension.stopSending");try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.stopSending before remote SDP created");const t=this.peerConnection.getTransceivers().filter((t=>-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length when trying to call NVConnectionExtension.stopSending.");t.map((e=>{var t;Ea(this.id+e.mid,this),e.direction="inactive",null===(t=e.stop)||void 0===t||t.call(e)}));const n=await this.peerConnection.createOffer(),o=this.logSDPExchange(n.sdp||"","offer","local","stopSending");await this.peerConnection.setLocalDescription(n),this.remoteSDP.stopReceiving(e);const s=this.remoteSDP.toString();null==o||o(s),await this.peerConnection.setRemoteDescription({type:"answer",sdp:s})}catch(e){throw new me(ne.EXCHANGE_SDP_FAILED,"NVConnectionExtension.stopSending failed; ".concat(e.toString()))}finally{i&&i()}}async receive(e,t,i,n){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.receive ".concat(e," before remoteSDP created."));const o=this.remoteSDP.send(e,t,i,n),s=o.mid;o.needExchangeSDP&&(await Po(this.peerConnection,this.remoteSDP,this.extension),B.debug("[".concat(this.store.clientId,"] [NVConnectionExtension] receive ").concat(e," by exchanging SDP.")));const a=this.peerConnection.getTransceivers().find((e=>e.mid===s));if(!a)throw new Error("Cannot get transceiver after setLocalDescription.");return{track:a.receiver.track,id:s,transceiver:a}}catch(e){throw new me(ne.EXCHANGE_SDP_FAILED,"NVConnectionExtension.receive failed; ".concat(e.toString()))}}async batchReceive(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.batchReceive before remoteSDP created.");const t=this.remoteSDP.batchSend(e),i=t.mids;return t.needExchangeSDP&&(await Po(this.peerConnection,this.remoteSDP,this.extension),B.debug("[".concat(this.store.clientId,"] [NVConnectionExtension] batchReceive by exchanging SDP."))),i.map((e=>{const t=this.peerConnection.getTransceivers().find((t=>t.mid===e));if(!t)throw new Error("Cannot get transceiver after setLocalDescription.");return{track:t.receiver.track,id:e,transceiver:t}}))}catch(e){throw new me(ne.EXCHANGE_SDP_FAILED,"NVConnectionExtension.receive failed; ".concat(e.toString()))}}async stopReceiving(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.stopReceiving before remote SDP created.");e.forEach((e=>{Array.from(this.preMediaMap.entries()).some((t=>{let i=Mi(t,2),n=i[0],o=i[1],s=o.mid,a=o.player;if(s===e)return this.preMediaMap.delete(n),a&&a.destroy(),!0}))})),this.remoteSDP.stopSending(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","stopReceiving");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||""),await this.peerConnection.setLocalDescription(n)}catch(e){throw new me(ne.EXCHANGE_SDP_FAILED,"NVConnectionExtension stopReceiving failed; ".concat(e.toString()))}}async muteRemote(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.muteRemote mid=".concat(e," before remote SDP created."));this.remoteSDP.mute(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","muteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||""),await this.peerConnection.setLocalDescription(n)}catch(e){throw new me(ne.EXCHANGE_SDP_FAILED,"NVConnectionExtension.muteRemote failed; ".concat(e.toString()))}}async unmuteRemote(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.unmuteRemote mid=".concat(e," before remote SDP created."));this.remoteSDP.unmute(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","unmuteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||""),await this.peerConnection.setLocalDescription(n)}catch(e){throw new me(ne.EXCHANGE_SDP_FAILED,"NVConnectionExtension.unmuteRemote failed; ".concat(e.toString()))}}async muteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.muteLocal before remote SDP created.");const t=this.peerConnection.getTransceivers().filter((t=>t.mid&&-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length.");t.map((e=>{e.direction="inactive"}));const i=await this.peerConnection.createOffer(),n=this.logSDPExchange(i.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(i),this.remoteSDP.muteRemote(e);const o=this.remoteSDP.toString();null==n||n(o),await this.peerConnection.setRemoteDescription({type:"answer",sdp:o})}catch(e){throw new me(ne.EXCHANGE_SDP_FAILED,"NVConnectionExtension.muteLocal failed; ".concat(e.toString()))}}async unmuteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.unmuteLocal before remote SDP created.");const t=this.peerConnection.getTransceivers().filter((t=>t.mid&&-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length.");t.map((async(e,t)=>{e.direction="sendonly"}));const i=await this.peerConnection.createOffer(),n=this.logSDPExchange(i.sdp||"","offer","local","unmuteLocal");await this.peerConnection.setLocalDescription(i),this.remoteSDP.unmuteRemote(e),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0&&this.remoteSDP.updateRemoteCodec(e,this.remoteCodecs,this.store.codec);const o=this.remoteSDP.toString();null==n||n(o),await this.peerConnection.setRemoteDescription({type:"answer",sdp:o})}catch(e){throw new me(ne.EXCHANGE_SDP_FAILED,"NVConnectionExtension.unmuteLocal failed; ".concat(e.toString()))}}restartICE(e){var t=this;return Ui((function*(){const i=yield Di(t.mutex.lock("From NVConnectionExtension.restartICE"));try{if(!t.remoteSDP)throw new Error("Cannot restartICE before remoteSDP created.");const n=o().supportPCSetConfiguration,s=ce("FORCE_TURN_TCP")||t.forceTurn;if(e===fn.RELAY&&!n)return;if(n&&!s){const i=e===fn.RELAY?"relay":"all",n=t.peerConnection.getConfiguration();n.iceTransportPolicy!==i&&(B.debug("[".concat(t.store.clientId,"] restartICE change iceTransportPolicy from [").concat(n.iceTransportPolicy,"] to [").concat(i,"]")),n.iceTransportPolicy=i,t.peerConnection.setConfiguration(n))}t.remoteSDP.updateCandidates(e);const a=yield Di(t.peerConnection.createOffer({iceRestart:!0}));if(!a.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const r=mo(a.sdp),c=(yield r.iceParameters).remoteIceParameters;t.remoteSDP.restartICE(c);const d=t.remoteSDP.toString(),l=t.logSDPExchange(a.sdp||"","offer","local","restartICE");t.store.descriptionStart(),yield Di(t.peerConnection.setLocalDescription(a)),null==l||l(d),yield Di(t.peerConnection.setRemoteDescription({type:"answer",sdp:d}))}catch(e){B.warning("[".concat(t.store.clientId,"] restart ICE failed, abort operation"),e)}finally{i()}}))()}async extendCandidate(){if(!this.remoteSDP||this.isFirstConnected)return;const e=await this.mutex.lock("From NVConnectionExtension.extendCandidate");try{this.remoteSDP.updateCandidates(fn.TCP_RELAY),await Po(this.peerConnection,this.remoteSDP,this.extension)}catch(e){B.warning("[".concat(this.store.clientId,"] extend candidate failed, abort operation"),e)}finally{e()}}close(){var e;this.peerConnection.getTransceivers().forEach((e=>{Ea(this.id+e.mid,this)})),this.preMediaMap.forEach((e=>{let t=e.player;t&&t.destroy()})),this.preMediaMap.clear(),this.peerConnection.close(),null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,"closed"),this.tryUnbindTransportEvents(),this.unbindPCEvents(),this.unbindStatsEvents(),this.removeAllListeners(),this.transportEventReceiver=void 0,this.statsFilter.destroy(),this.dataStreamChannelMap.clear(),this.recoveredDataChannelIds=[],this.currentDataChannelId=1}getStats(){return ki(ki({},this.statsFilter.getStats()),{},{qualityLimitationReason:this.qualityLimitationReason})}getRemoteVideoIsReady(e){return this.statsFilter.getVideoIsReady(e)}async updateEncoderConfig(e,t){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.updateEncoderConfig before remote SDP created.");const i=await this.peerConnection.createOffer(),n=this.mungSendOfferSDP(i.sdp,[t],[e]);this.remoteSDP.updateRecvMedia(e,t);const o=this.remoteSDP.toString(),s=this.logSDPExchange(n,"offer","local","updateEncoderConfig");await this.peerConnection.setLocalDescription({type:"offer",sdp:n}),null==s||s(o),await this.peerConnection.setRemoteDescription({type:"answer",sdp:o})}catch(e){throw new me(ne.EXCHANGE_SDP_FAILED,e.toString())}}async updateSendParameters(e,t){const i=this.peerConnection.getTransceivers().filter((t=>t.mid===e));1===i.length&&(this.isVP8Simulcast(t)?he()||await this.applySimulcastEncodings(i,[t]):await this.applySendEncodings(i,[t]))}setStatsRemoteVideoIsReady(e,t){this.statsFilter.setVideoIsReady2(e,t)}async replaceTrack(e,t){const i=this.peerConnection.getTransceivers().find((e=>e.mid===t));i&&await i.sender.replaceTrack(e._mediaStreamTrack)}async getSelectedCandidatePair(){const e=this.peerConnection.getReceivers();if(e.length>0&&e[0].transport&&e[0].transport.iceTransport&&e[0].transport.iceTransport.getSelectedCandidatePair&&e[0].transport.iceTransport.getSelectedCandidatePair()){const t=e[0].transport.iceTransport.getSelectedCandidatePair(),i=t.local,n=t.remote;return{local:ki(ki({},ht),{},{candidateType:i.type,protocol:i.protocol,address:i.address,port:i.port}),remote:ki(ki({},ht),{},{candidateType:n.type,protocol:n.protocol,address:n.address,port:n.port})}}return this.statsFilter.getSelectedCandidatePair()}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var e;null===(e=this.onICEConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.iceConnectionState)},this.peerConnection.onconnectionstatechange=()=>{var e;"connected"===this.peerConnection.connectionState&&(this.isFirstConnected=!0),null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.connectionState)},this.peerConnection.onicecandidateerror=e=>{if(e&&(e.errorCode||e.errorText)){var t;const i="code: ".concat(e.errorCode,", message: ").concat(e.errorText),n=e.port?"local: ".concat(e.port):"",o=oo(e.url||"");B.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: NVConnectionExtension.onICECandidateError(").concat(i,"), url: ").concat(o||"",", host_candidate:").concat(n)),null===(t=this.onICECandidateError)||void 0===t||t.call(this,i)}},this.peerConnection.onicegatheringstatechange=e=>{e&&e.target&&"iceGatheringState"in e.target&&B.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] RTCPeerConnection.onicegatheringstatechange(").concat(e.target.iceGatheringState,")"))},this.peerConnection.onicecandidate=e=>{e.candidate?this.localCandidateCount+=1:(this.peerConnection.onicecandidate=null,this.allCandidatesReceived=!0,B.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount))},setTimeout((()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,B.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount))}),ce("CANDIDATE_TIMEOUT"))}unbindPCEvents(){this.peerConnection.oniceconnectionstatechange=null,this.peerConnection.onconnectionstatechange=null,this.peerConnection.onsignalingstatechange=null,this.peerConnection.onicecandidateerror=null,this.peerConnection.onicecandidate=null,this.peerConnection.ontrack=null}static resolvePCConfiguration(t){const i={iceServers:[]},n=t.cloudProxyServer||"disabled";return t.iceServers?i.iceServers=t.iceServers:t.turnServer&&(dt(t.turnServer.servers)?i.iceServers=t.turnServer.servers:ce("NEW_TURN_MODE")&&i.iceServers&&"disabled"===n?(ce("USE_TURN_SERVER_OF_GATEWAY")?t.turnServer.serversFromGateway&&i.iceServers.push(...e.newTurnServerConfigToIceServers(t.turnServer.serversFromGateway)):i.iceServers.push(...e.newTurnServerConfigToIceServers(t.turnServer.servers)),ce("NEW_FORCE_TURN")&&(i.iceTransportPolicy="relay")):"off"!==t.turnServer.mode&&(i.iceServers&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers)),ce("USE_TURN_SERVER_OF_GATEWAY")&&i.iceServers&&t.turnServer.serversFromGateway&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway)),ce("FORCE_TURN_TCP")?i.iceTransportPolicy="relay":t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach((e=>{e.forceturn&&(i.iceTransportPolicy="relay")})))),ce("ENABLE_ENCODED_TRANSFORM")&&o().supportWebRTCEncodedTransform&&(i.encodedInsertableStreams=!0),i}static turnServerConfigToIceServers(e){const t=[];return e.forEach((e=>{e.security?e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(Jn(e.turnServerURL),":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&!ce("FORCE_TURN_TCP")&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.udpport,"?transport=udp")}),e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.tcpport,"?transport=tcp")}))})),t}static newTurnServerConfigToIceServers(e){const t=[];return e.forEach((e=>{const i=ce("NEW_TURN_MODE");1===i?t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=udp")}):2===i?t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=tcp")}):3===i?t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(Jn(e.turnServerURL),":443?transport=tcp")}):4===i&&(t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=udp")}),t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=tcp")}),t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(Jn(e.turnServerURL),":443?transport=tcp")}))})),t}tryBindTransportEvents(e){const t=e.transport;if(t){this.transportEventReceiver=e,t.onstatechange=()=>{var e;null!=t&&t.state&&(null===(e=this.onDTLSTransportStateChange)||void 0===e||e.call(this,t.state))},t.onerror=e=>{var t;null===(t=this.onDTLSTransportError)||void 0===t||t.call(this,"error"in e?e.error:e)};const i=t.iceTransport;i&&(i.onstatechange=()=>{const e=null==t?void 0:t.iceTransport.state;var i;e&&(null===(i=this.onICETransportStateChange)||void 0===i||i.call(this,e))},i.getSelectedCandidatePair&&(i.onselectedcandidatepairchange=()=>{if(i.getSelectedCandidatePair()){const e=i.getSelectedCandidatePair()||{},t=e.local,n=e.remote;if(t&&n){const e=t.address+":"+t.port,i=n.address+":"+n.port;B.info("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] selectedcandidatepairchange: local ").concat(JSON.stringify(oo(e)),", remote ").concat(JSON.stringify(oo(i))))}}}))}}tryUnbindTransportEvents(){this.transportEventReceiver&&this.transportEventReceiver.transport&&(this.transportEventReceiver.transport.onstatechange=null,this.transportEventReceiver.transport.onerror=null,this.transportEventReceiver.transport.iceTransport&&(this.transportEventReceiver.transport.iceTransport.onstatechange=null))}async updateRtpSenderEncodings(e,t){var i;if(!t){const i=this.peerConnection.getSenders();t=i.find((t=>t.track===e._mediaStreamTrack))}if(!t)return B.warn("[".concat(e.getTrackId(),"] no rtpSender found}"));if(this.isVP8Simulcast(e))return B.warn("[updateRtpSenderEncodings] Track is VP8 simulcast, please apply simulcast encodings");if(!o().supportSetRtpSenderParameters)return B.warn("[updateRtpSenderEncodings] Browser not support set rtp-sender parameters");const n=f(e),a=!!n&&na(this.store.codec)&&ia(n),r=a&&!this.unsupportedResolutionFloorTrackIds.has(e.getTrackId()),c=!!n&&!(a&&!r)&&ua(e,r?n:void 0),d=r&&c,l=r||["vp8","vp9"].includes(this.store.codec),h={},u={},_=Ca(e,d);_&&(h.degradationPreference=_);const p=so(this.peerConnection,e._mediaStreamTrack);if(c&&p&&t&&n&&this.getLocalVideoStats&&l){const i=this.id+p.mid,o=fa(e,r);pa(i,n,this,o,(n=>{t&&this.updateAdaptation(e,t,n,i,r)}),this.getLocalVideoStats.bind(this))}if(e._encoderConfig){const t=e._encoderConfig,i=t.bitrateMax,n=t.frameRate,o=t.scaleResolutionDownBy;i&&(u.maxBitrate=1e3*i),(e._hints.includes(s.LOW_STREAM)||e.isUseScaleResolutionDownBy)&&(n&&(u.maxFramerate=zn(n)),o&&o>=1&&(u.scaleResolutionDownBy=o))}const E=ce("ENCODER_CONFIG_LIMIT").maxFramerate;if(E&&"number"==typeof E&&(u.maxFramerate=u.maxFramerate?Math.min(u.maxFramerate,E):E),ce("DSCP_TYPE")&&ct()){const e=ce("DSCP_TYPE");["very-low","low","medium","high"].includes(e)&&(u.networkPriority=e)}const m=t.getParameters(),S=null===(i=m.encodings)||void 0===i?void 0:i[0];he()&&!S&&(h.encodings=[u]),S&&Object.assign(S,u),Object.assign(m,h),B.debug("[".concat(e.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(m.encodings))),await t.setParameters(m),await Mo(this.store.codec,t,ce("SVC_MODE"))}async updateAdaptation(e,t,i,n,s){var a;if(!t)return B.debug("[updateAdaptation] no rtpSender found");if(!o().supportSetRtpSenderParameters)return B.debug("[updateAdaptation] Browser not support set rtp-sender parameters");const r={},c={},d=i.bitrateMax,l=i.frameRate,h=i.scaleResolutionDownBy;d&&(c.maxBitrate=1e3*d),l&&(c.maxFramerate=zn(l));let u=!1;"number"==typeof h&&h>=1&&(s||["vp8","vp9"].includes(this.store.codec))&&(c.scaleResolutionDownBy=h,u=h>1);const _=t.getParameters(),p=null===(a=_.encodings)||void 0===a?void 0:a[0];p&&Object.assign(p,c),Object.assign(_,r);try{await t.setParameters(_),B.debug("[updateAdaptation] updateRtpSenderEncodings: ".concat(JSON.stringify(_.encodings)))}catch(i){if(!("transport"in t)||t.transport&&"connected"===t.transport.state)if("connected"!==this.peerConnectionState)B.debug("[updateAdaptation] peerConnection not connected}");else if(s&&u){const o=await Ta(t,r,c);"unsupported"===o.classification?(this.unsupportedResolutionFloorTrackIds.add(e.getTrackId()),Ea(n,this),B.warn("[".concat(e.getTrackId(),"] fallback to browser adaptation because scaleResolutionDownBy adaptation is unsupported"),i,o.retryWithScaleError),this.updateRtpSenderEncodings(e,t).catch((t=>{B.warn("[".concat(e.getTrackId(),"] failed to re-apply browser adaptation after disabling resolution floor"),t)}))):"transient"===o.classification?B.debug("[".concat(e.getTrackId(),"] keep resolution floor enabled after transient setParameters failure"),i):B.debug("[".concat(e.getTrackId(),"] keep resolution floor enabled because setParameters failure is not classified as unsupported"),i,o.retryWithScaleError,o.retryWithoutScaleError)}else B.debug("[updateAdaptation] updateRtpSenderEncodings failed",i);else B.debug("[updateAdaptation] rtpSender transport not connected}")}}async applySendEncodings(e,t){try{if(!o().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let i=0;i<e.length;i++){const o=e[i],s=t[i];s instanceof n&&!this.isVP8Simulcast(s)&&await this.updateRtpSenderEncodings(s,o.sender)}}catch(e){B.debug("[".concat(this.store.clientId,"] Apply RTPSendEncodings failed."))}}mungSendOfferSDP(e,t,i){const n=be(e);return t.forEach(((e,t)=>{const o=i[t],s=n.mediaDescriptions.find((e=>e.attributes.mid===o));s&&(go(s,e),vo(s,e,this.store.codec))})),De(n)}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=e=>{var t;null===(t=this.onFirstAudioReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoReceived=e=>{var t;null===(t=this.onFirstVideoReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstAudioDecoded=e=>{var t;null===(t=this.onFirstAudioDecoded)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoDecoded=(e,t,i)=>{var n;null===(n=this.onFirstVideoDecoded)||void 0===n||n.call(this,e,t,i)},this.statsFilter.onSelectedLocalCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedLocalCandidateChanged)||void 0===i||i.call(this,e,t)},this.statsFilter.onSelectedRemoteCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedRemoteCandidateChanged)||void 0===i||i.call(this,e,t)},this.statsFilter.onFirstVideoDecodedTimeout=e=>{var t;null===(t=this.onFirstVideoDecodedTimeout)||void 0===t||t.call(this,e)}}unbindStatsEvents(){this.statsFilter.onFirstAudioReceived=void 0,this.statsFilter.onFirstVideoReceived=void 0,this.statsFilter.onFirstAudioDecoded=void 0,this.statsFilter.onFirstVideoDecoded=void 0,this.statsFilter.onSelectedLocalCandidateChanged=void 0,this.statsFilter.onSelectedRemoteCandidateChanged=void 0,this.statsFilter.onFirstVideoDecodedTimeout=void 0}async applySimulcastForFirefox(e,t){if(e.length===t.length)for(let c=0;c<e.length;c++){var i,o,a,r;const d=e[c],l=t[c];if(l instanceof n&&!l._hints.includes(s.LOW_STREAM)&&null!==(i=l._encoderConfig)&&void 0!==i&&i.bitrateMax&&(null===(o=l._encoderConfig)||void 0===o?void 0:o.bitrateMax)>200&&null!==(a=l._scalabilityMode)&&void 0!==a&&a.numSpatialLayers&&(null===(r=l._scalabilityMode)||void 0===r?void 0:r.numSpatialLayers)>1&&"vp8"===this.store.codec){const e={},t={high:1e3*(l._encoderConfig.bitrateMax-50),medium:5e4};e.encodings=[{rid:"m",active:!0,maxBitrate:t.medium,scaleResolutionDownBy:4},{rid:"h",active:!0,maxBitrate:t.high}];const i=d.sender.getParameters();await d.sender.setParameters(Object.assign(i,e))}}}async applySimulcastEncodings(e,t){if(!he()&&e.length===t.length)for(let i=0;i<e.length;i++){const o=t[i];if(o instanceof n&&this.isVP8Simulcast(o)){const t=e[i],n={},s={high:1e3*(o._encoderConfig.bitrateMax-50),medium:5e4};n.encodings=[{active:!0,adaptivePtime:!1,networkPriority:"high",priority:"high",maxBitrate:s.high},{active:!0,adaptivePtime:!1,networkPriority:"low",priority:"low",maxBitrate:s.medium,scaleResolutionDownBy:4}];const a=t.sender.getParameters();await t.sender.setParameters(Object.assign(a,n))}}}isVP8Simulcast(e){var t,i,o,a;return!!(e instanceof n&&ce("SIMULCAST")&&"vp8"===this.store.codec&&!e._hints.includes(s.LOW_STREAM)&&null!==(t=e._encoderConfig)&&void 0!==t&&t.bitrateMax&&(null===(i=e._encoderConfig)||void 0===i?void 0:i.bitrateMax)>200&&null!==(o=e._scalabilityMode)&&void 0!==o&&o.numSpatialLayers&&(null===(a=e._scalabilityMode)||void 0===a?void 0:a.numSpatialLayers)>1)}logSDPExchange(e,t,i,n){if(ce("SDP_LOGGING"))return B.upload("[".concat(this.store.clientId,"] exchanging ").concat(i," ").concat(t," SDP during NVConnectionExtension.").concat(n,"\n"),e),"offer"===t?e=>{this.logSDPExchange(e,"answer","local"===i?"remote":"local",n)}:void 0}async getRemoteSSRC(e){if(!this.remoteSDP)return;const t=this.remoteSDP.getSSRC(e);return t&&0!==t.length?t[0].ssrcId:void 0}setConfiguration(t){if(o().supportPCSetConfiguration){const i=e.resolvePCConfiguration(t);this.peerConnection.setConfiguration(i)}t.isPreallocation&&(this.isPreallocation=!0)}},yi(Wc.prototype,"updateRemoteRTPCapabilities",[Kc],Object.getOwnPropertyDescriptor(Wc.prototype,"updateRemoteRTPCapabilities"),Wc.prototype),yi(Wc.prototype,"connect",[Kc],Object.getOwnPropertyDescriptor(Wc.prototype,"connect"),Wc.prototype),yi(Wc.prototype,"updateRemoteConnect",[Kc],Object.getOwnPropertyDescriptor(Wc.prototype,"updateRemoteConnect"),Wc.prototype),yi(Wc.prototype,"createDataChannels",[Kc],Object.getOwnPropertyDescriptor(Wc.prototype,"createDataChannels"),Wc.prototype),yi(Wc.prototype,"receive",[Kc],Object.getOwnPropertyDescriptor(Wc.prototype,"receive"),Wc.prototype),yi(Wc.prototype,"batchReceive",[Kc],Object.getOwnPropertyDescriptor(Wc.prototype,"batchReceive"),Wc.prototype),yi(Wc.prototype,"stopReceiving",[Kc],Object.getOwnPropertyDescriptor(Wc.prototype,"stopReceiving"),Wc.prototype),yi(Wc.prototype,"muteRemote",[Kc],Object.getOwnPropertyDescriptor(Wc.prototype,"muteRemote"),Wc.prototype),yi(Wc.prototype,"unmuteRemote",[Kc],Object.getOwnPropertyDescriptor(Wc.prototype,"unmuteRemote"),Wc.prototype),yi(Wc.prototype,"muteLocal",[Kc],Object.getOwnPropertyDescriptor(Wc.prototype,"muteLocal"),Wc.prototype),yi(Wc.prototype,"unmuteLocal",[Kc],Object.getOwnPropertyDescriptor(Wc.prototype,"unmuteLocal"),Wc.prototype),yi(Wc.prototype,"close",[Kc],Object.getOwnPropertyDescriptor(Wc.prototype,"close"),Wc.prototype),yi(Wc.prototype,"updateEncoderConfig",[Kc],Object.getOwnPropertyDescriptor(Wc.prototype,"updateEncoderConfig"),Wc.prototype),yi(Wc.prototype,"updateSendParameters",[Kc],Object.getOwnPropertyDescriptor(Wc.prototype,"updateSendParameters"),Wc.prototype),yi(Wc.prototype,"replaceTrack",[Kc],Object.getOwnPropertyDescriptor(Wc.prototype,"replaceTrack"),Wc.prototype),yi(Wc.prototype,"updateAdaptation",[Kc],Object.getOwnPropertyDescriptor(Wc.prototype,"updateAdaptation"),Wc.prototype),yi(Wc.prototype,"getRemoteSSRC",[Kc],Object.getOwnPropertyDescriptor(Wc.prototype,"getRemoteSSRC"),Wc.prototype),Wc);function Kc(e,t,i){const n=e[t];if("function"!=typeof n)throw new Error("Cannot use mutex on object property.");return i.value=async function(){const e=this.mutex,i=await e.lock("From NVConnectionExtension.".concat(t));try{for(var o=arguments.length,s=new Array(o),a=0;a<o;a++)s[a]=arguments[a];return await n.apply(this,s)}finally{i()}},i}var Yc;let qc=(Yc=class e extends mn{get currentLocalDescription(){return this.peerConnection.currentLocalDescription}get currentRemoteDescription(){return this.peerConnection.currentRemoteDescription}get peerConnectionState(){return this.peerConnection.connectionState}get iceConnectionState(){return this.peerConnection.iceConnectionState}get localCodecs(){return this._p2pConnection.localCodecs}constructor(t,i){super(t,i),this.name="DataChannelConnection",this.store=void 0,this.peerConnection=void 0,this.cname=void 0,this.mutex=new ue("DataChannelConnection-mutex"),this.dataChannel=void 0,this._p2pConnection=void 0,this.establishPromise=void 0,this._nvMedia=void 0,this.store=i,this.store.dcId=this.store.dcId+1,this.peerConnection=new RTCPeerConnection(e.resolvePCConfiguration(t),{optional:[{googDscp:!0}]}),this.dataChannel=this.peerConnection.createDataChannel("agora-signal",{ordered:!1,maxPacketLifeTime:50}),this.dataChannel.binaryType="arraybuffer",this._p2pConnection=new Hc(t,i,this.peerConnection),this.bindPCEvents(),this.establishPromise=this._p2pConnection.establishPromise}getPreMedia(e){var t;return null===(t=this._p2pConnection)||void 0===t?void 0:t.getPreMedia(e)}isPreSub(){var e,t;return null!==(e=null===(t=this._p2pConnection)||void 0===t?void 0:t.isPreSub())&&void 0!==e&&e}async establish(){return await this._p2pConnection.establish()}getP2PConnectionParams(){return this._p2pConnection.establishPromise}updateRtpSenderEncodings(e){return this._p2pConnection.updateRtpSenderEncodings(e)}async connect(e){return this.cname=e.cname,await this._p2pConnection.connect(e),await new Promise(((t,i)=>{const n=setTimeout((()=>{this.closeSignal(),i(new j(ne.DATACHANNEL_CONNECTION_TIMEOUT,"Datachannel connection timed out, candidates: ".concat(JSON.stringify(e.candidates))))}),ce("DC_CONNECTION_TIMEOUT"));this.dataChannel.onopen=()=>{if("open"===this.dataChannel.readyState)return clearTimeout(n),void t()},this.dataChannel.onerror=e=>{this.closeSignal(),i(e)},this.dataChannel.addEventListener("close",(()=>{i(new j(ne.DATACHANNEL_CONNECTION_TIMEOUT))}))})),{transmitter:this.dataChannel,close:this.closeSignal.bind(this)}}checkDtlsParameters(e){return this._p2pConnection.checkDtlsParameters(e)}checkIceParameters(e){return this._p2pConnection.checkIceParameters(e)}async updateRemoteRTPCapabilities(e,t){return this._p2pConnection.updateRemoteRTPCapabilities(e,t)}send(e,t,i){var n=this;return Ui((function*(){const o=yield Di(n.mutex.lock("From DataChannelConnection.send"));try{return yield*wi(bi(n._p2pConnection.send(e,t,i)))}finally{o()}}))()}async stopSending(e,t){return this._p2pConnection.stopSending(e,t)}async createDataChannels(e,t){return this._p2pConnection.createDataChannels(e,t)}async stopDataChannels(e){return this._p2pConnection.stopDataChannels(e)}async receive(e,t,i,n){return this._nvMedia?(B.debug("[DataChannelConnection] receive ".concat(e," by DataChannel.")),await this._nvMedia.reveiveByRTCMedia(e,t,this.cname)):(B.debug("[DataChannelConnection] receive ".concat(e," by WebRTC.")),await this._p2pConnection.receive(e,t,i,n))}async batchReceive(e){return[...await this._p2pConnection.batchReceive(e)]}async stopReceiving(e){return await this._p2pConnection.stopReceiving(e)}async muteRemote(e){return await this._p2pConnection.muteRemote(e)}async unmuteRemote(e){return await this._p2pConnection.unmuteRemote(e)}async muteLocal(e){return await this._p2pConnection.muteLocal(e)}async unmuteLocal(e){return await this._p2pConnection.unmuteLocal(e)}restartICE(e){var t=this;return Ui((function*(){return yield*wi(bi(t._p2pConnection.restartICE(e)))}))()}close(){var e;null===(e=this._nvMedia)||void 0===e||e.close(),this._p2pConnection.close(),this.unbindConnectionEvents(this._p2pConnection)}getStats(){return this._p2pConnection.getStats()}getRemoteVideoIsReady(e){return this._p2pConnection.getRemoteVideoIsReady(e)}updateRemoteConnect(e){var t;return null===(t=this._nvMedia)||void 0===t||t.setRemoteRtpCapabilities(e),this._p2pConnection.updateRemoteConnect(e)}async updateEncoderConfig(e,t){return await this._p2pConnection.updateEncoderConfig(e,t)}async updateSendParameters(e,t){return await this._p2pConnection.updateSendParameters(e,t)}setStatsRemoteVideoIsReady(e,t){this._p2pConnection.setStatsRemoteVideoIsReady(e,t)}async replaceTrack(e,t){return await this._p2pConnection.replaceTrack(e,t)}async getRemoteSSRC(e){return this._p2pConnection.getRemoteSSRC(e)}logSDPExchange(e,t,i,n){if(ce("SDP_LOGGING"))return B.upload("exchanging ".concat(i," ").concat(t," SDP during DataChannelConnection.").concat(n,"\n"),e),"offer"===t?e=>{this.logSDPExchange(e,"answer","local"===i?"remote":"local",n)}:void 0}static resolvePCConfiguration(t){const i={iceServers:[]};return t.iceServers?i.iceServers=t.iceServers:t.turnServer&&"off"!==t.turnServer.mode&&(dt(t.turnServer.servers)?i.iceServers=t.turnServer.servers:(i.iceServers&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers)),ce("USE_TURN_SERVER_OF_GATEWAY")&&i.iceServers&&t.turnServer.serversFromGateway&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway)),ce("FORCE_TURN_TCP")?i.iceTransportPolicy="relay":t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach((e=>{e.forceturn&&(i.iceTransportPolicy="relay")})))),ce("ENABLE_ENCODED_TRANSFORM")&&o().supportWebRTCEncodedTransform&&(i.encodedInsertableStreams=!0),i}static turnServerConfigToIceServers(e){const t=[];return e.forEach((e=>{e.security?e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(Jn(e.turnServerURL),":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&!ce("FORCE_TURN_TCP")&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.udpport,"?transport=udp")}),e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.tcpport,"?transport=tcp")}))})),t}bindPCEvents(){this._p2pConnection.onICEConnectionStateChange=e=>{var t;return null===(t=this.onICEConnectionStateChange)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onConnectionStateChange=e=>{var t;return null===(t=this.onConnectionStateChange)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onDTLSTransportStateChange=e=>{var t;return null===(t=this.onDTLSTransportStateChange)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onDTLSTransportError=e=>{var t;return null===(t=this.onDTLSTransportError)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onICETransportStateChange=e=>{var t;return null===(t=this.onICETransportStateChange)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onFirstAudioReceived=e=>{var t;return null===(t=this.onFirstAudioReceived)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onFirstVideoReceived=e=>{var t;return null===(t=this.onFirstVideoReceived)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onFirstAudioDecoded=e=>{var t;return null===(t=this.onFirstAudioDecoded)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onFirstVideoRender=e=>{var t;return null===(t=this.onFirstVideoRender)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onFirstVideoBufferReady=e=>{var t;return null===(t=this.onFirstVideoBufferReady)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onFirstVideoDecoded=(e,t,i)=>{var n;return null===(n=this.onFirstVideoDecoded)||void 0===n?void 0:n.call(this,e,t,i)},this._p2pConnection.onFirstVideoDecodedTimeout=e=>{var t;return null===(t=this.onFirstVideoDecodedTimeout)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onSelectedLocalCandidateChanged=(e,t)=>{var i;return null===(i=this.onSelectedLocalCandidateChanged)||void 0===i?void 0:i.call(this,e,t)},this._p2pConnection.onSelectedRemoteCandidateChanged=(e,t)=>{var i;return null===(i=this.onSelectedRemoteCandidateChanged)||void 0===i?void 0:i.call(this,e,t)}}closeSignal(){this.dataChannel.close(),this.peerConnection.close()}unbindConnectionEvents(e){e.onConnectionStateChange=void 0,e.onICEConnectionStateChange=void 0,e.onICETransportStateChange=void 0,e.onDTLSTransportStateChange=void 0,e.onDTLSTransportError=void 0,e.onFirstAudioDecoded=void 0,e.onFirstAudioReceived=void 0,e.onFirstVideoDecoded=void 0,e.onFirstVideoReceived=void 0,e.onSelectedLocalCandidateChanged=void 0,e.onSelectedRemoteCandidateChanged=void 0,e.onFirstVideoDecodedTimeout=void 0}setConfiguration(e){this._p2pConnection.setConfiguration(e)}},yi(Yc.prototype,"connect",[Jc],Object.getOwnPropertyDescriptor(Yc.prototype,"connect"),Yc.prototype),yi(Yc.prototype,"updateRemoteRTPCapabilities",[Jc],Object.getOwnPropertyDescriptor(Yc.prototype,"updateRemoteRTPCapabilities"),Yc.prototype),yi(Yc.prototype,"createDataChannels",[Jc],Object.getOwnPropertyDescriptor(Yc.prototype,"createDataChannels"),Yc.prototype),yi(Yc.prototype,"receive",[Jc],Object.getOwnPropertyDescriptor(Yc.prototype,"receive"),Yc.prototype),yi(Yc.prototype,"stopReceiving",[Jc],Object.getOwnPropertyDescriptor(Yc.prototype,"stopReceiving"),Yc.prototype),yi(Yc.prototype,"muteRemote",[Jc],Object.getOwnPropertyDescriptor(Yc.prototype,"muteRemote"),Yc.prototype),yi(Yc.prototype,"unmuteRemote",[Jc],Object.getOwnPropertyDescriptor(Yc.prototype,"unmuteRemote"),Yc.prototype),yi(Yc.prototype,"muteLocal",[Jc],Object.getOwnPropertyDescriptor(Yc.prototype,"muteLocal"),Yc.prototype),yi(Yc.prototype,"unmuteLocal",[Jc],Object.getOwnPropertyDescriptor(Yc.prototype,"unmuteLocal"),Yc.prototype),yi(Yc.prototype,"close",[Jc],Object.getOwnPropertyDescriptor(Yc.prototype,"close"),Yc.prototype),yi(Yc.prototype,"updateEncoderConfig",[Jc],Object.getOwnPropertyDescriptor(Yc.prototype,"updateEncoderConfig"),Yc.prototype),yi(Yc.prototype,"updateSendParameters",[Jc],Object.getOwnPropertyDescriptor(Yc.prototype,"updateSendParameters"),Yc.prototype),yi(Yc.prototype,"replaceTrack",[Jc],Object.getOwnPropertyDescriptor(Yc.prototype,"replaceTrack"),Yc.prototype),yi(Yc.prototype,"getRemoteSSRC",[Jc],Object.getOwnPropertyDescriptor(Yc.prototype,"getRemoteSSRC"),Yc.prototype),Yc);function Jc(e,t,i){const n=e[t];if("function"!=typeof n)throw new Error("Cannot use mutex on object property.");return i.value=async function(){const e=this.mutex,i=await e.lock("From DataChannelConnection.".concat(t));try{for(var o=arguments.length,s=new Array(o),a=0;a<o;a++)s[a]=arguments[a];return await n.apply(this,s)}finally{i()}},i}class Xc extends re{get url(){return this._url?this._url:null}get reconnectMode(){return this._reconnectMode}set reconnectMode(e){["tryNext","recover"].includes(e)&&this.resetReconnectCount(e),this._reconnectMode=e}get state(){return this._state}set state(e){e!==this._state&&(this._state=e,"reconnecting"===this._state?this.emit(Nn.RECONNECTING,this.reconnectReason):"connected"===this._state?this.emit(Nn.CONNECTED):"closed"===this._state?this.emit(Nn.CLOSED):"failed"===this._state&&this.emit(Nn.FAILED))}constructor(e,t,i,n){super(),this.connectionID=0,this.currentURLIndex=0,this.reconnectReason=void 0,this._reconnectMode="tryNext",this._initMutex=void 0,this._name=void 0,this._state="closed",this._reconnectInterrupter=void 0,this._url=void 0,this._retryConfig=void 0,this._reconnectCount=0,this._forceCloseTimeout=5e3,this._onlineReconnectListener=void 0,this._closeEstablishingTransmitter=()=>{},this._store=void 0,this._joinChannelServiceRecordIndex=void 0,this._transmitter=void 0,this._useCompress=void 0,this._inflateLength=0,this._deflateLength=0,this._store=n,this._name=e,this._retryConfig=ki({},t),this._useCompress=i}resetReconnectCount(e){B.debug("".concat(this._name," reset reconnect count, reason: ").concat(e)),this._reconnectCount=0}close(e,t){if(this.currentURLIndex=0,this.resetReconnectCount("close"),this._reconnectInterrupter&&this._reconnectInterrupter(),this._transmitter){this._transmitter.onclose=null,this._transmitter.onopen=null,this._transmitter.onmessage=null;const e=this._transmitter;t?setTimeout((()=>e.close()),500):e.close(),this._transmitter=void 0}this.state=e?"failed":"closed",this._closeEstablishingTransmitter&&this._closeEstablishingTransmitter()}reconnect(e,t){if(!this._transmitter)return void B.warning("[".concat(this._name,"] can not reconnect, no websocket"));var i;(void 0!==e&&(this.reconnectMode=e),B.debug("[".concat(this._name,"] reconnect is triggered initiative")),"number"==typeof this._joinChannelServiceRecordIndex)&&(null===(i=this._store)||void 0===i||i.recordJoinChannelService({status:"error",errors:[new Error(t)]},this._joinChannelServiceRecordIndex));const n=this._transmitter.onclose;this._transmitter.onclose=null,this._transmitter.close(),n&&n.bind(this._transmitter)({code:9999,reason:t})}getInflateData(){const e=this._inflateLength,t=this._deflateLength;return this.clearInflateData(),{inflateLength:e,deflateLength:t}}setInflateData(e){this._deflateLength=this._deflateLength+e.originLength,this._inflateLength=this._inflateLength+e.compressedLength}clearInflateData(){this._inflateLength=0,this._deflateLength=0}}let Qc=function(e){return e[e.Default=0]="Default",e[e.Ack=1]="Ack",e}({});class zc{constructor(e,t,i){this.version=1,this.initialRTO=void 0,this.maxBatchAckCount=void 0,this.maxRTO=void 0,this.initialRTT=void 0,this.ID=void 0,this.rtt=void 0,this.packetNumber=1,this.rtoRatioMap=new Map,this.timeoutMap=new Map,this.unorderedPacketQueue=[],this.batchAckPacketQueue=[],this.lastOrderedPacketNumber=0,this.batchAckTimer=void 0,this.sendImpl=void 0,this.receiveImpl=void 0,this.sendImpl=e,this.receiveImpl=t,this.ID=ve(7,"transmitter-"),this.initialRTO=void 0!==(null==i?void 0:i.initialRTO)?i.initialRTO:ce("TRANSMITTER_INITIAL_RTO"),this.initialRTT=void 0!==(null==i?void 0:i.initialRTT)?i.initialRTT:ce("TRANSMITTER_INITIAL_RTT"),this.rtt=void 0!==(null==i?void 0:i.initialRTT)?i.initialRTT:ce("TRANSMITTER_INITIAL_RTT"),this.maxBatchAckCount=void 0!==(null==i?void 0:i.maxBatchAckCount)?i.maxBatchAckCount:ce("TRANSMITTER_MAX_BATCH_ACK_COUNT"),this.maxRTO=void 0!==(null==i?void 0:i.maxRTO)?i.maxRTO:ce("TRANSMITTER_MAX_RTO")}packetize(e,t){return{type:Qc.Default,version:this.version,packetNumber:t,payload:e}}serialize(e){switch(e.type){case Qc.Default:{let t;if("string"==typeof e.payload){t=(new TextEncoder).encode(e.payload)}else t=e.payload;const i=new ArrayBuffer(t.length+15),n=new DataView(i);n.setUint16(0,e.version),n.setUint8(2,e.type),n.setUint32(3,e.packetNumber),oi(n,7,BigInt(e.sendTs));return new Uint8Array(n.buffer).set(t,15),i}case Qc.Ack:{const t=new ArrayBuffer(16),i=new DataView(t);return i.setUint16(0,e.version),i.setUint8(2,e.type),i.setUint32(3,e.maxAckPacketNumber),i.setUint8(7,e.shift),oi(i,8,BigInt(e.ackSendTs)),t}}}deserialize(e){const t=new DataView(e),i=t.getUint16(0),n=t.getUint8(2);switch(n){case Qc.Default:{const o=t.getUint32(3),s=si(t,7),a=e.slice(15),r=new Uint8Array(a);return{version:i,type:n,packetNumber:o,sendTs:Number(s),payload:r}}case Qc.Ack:{const e=t.getUint32(3),o=t.getUint8(7),s=si(t,8);return{version:i,type:n,maxAckPacketNumber:e,shift:o,ackSendTs:Number(s)}}default:throw B.error("[".concat(this.ID,"] Unrecognized packet type ").concat(n)),new Error("Unrecognized packet type ".concat(n))}}sendMessage(e){ce("DC_DEBUG_LOG")&&"string"==typeof e&&B.debug("[".concat(this.ID,"] sending message packet"),JSON.parse(e));const t=this.packetize(e,this.packetNumber);this.packetNumber=4294967295===this.packetNumber?1:this.packetNumber+1;const i=this.calculateRTO(t),n=window.setTimeout((()=>{this.resendMessage(t)}),i);this.timeoutMap.set(t.packetNumber,n),this.sendPacket(t)}onData(e){const t=this.deserialize(e);t.type===Qc.Default?this.ack(t):t.type===Qc.Ack&&(this.updateRTT(t,Math.round(performance.now())),this.clearRTO(t))}close(){this.rtt=this.initialRTT,this.packetNumber=1,Array.from(this.timeoutMap.entries()).forEach((e=>{let t=Mi(e,2);t[0];let i=t[1];window.clearTimeout(i)})),this.timeoutMap=new Map,this.rtoRatioMap=new Map,this.unorderedPacketQueue=[],this.batchAckPacketQueue=[],this.lastOrderedPacketNumber=0,void 0!==this.batchAckTimer&&window.clearTimeout(this.batchAckTimer)}resendMessage(e){const t=this.calculateRTO(e),i=window.setTimeout((()=>{ce("DC_DEBUG_LOG")&&"string"==typeof e.payload&&B.debug("[".concat(this.ID,"] resending message packet"),JSON.parse(e.payload),"timeout: ".concat(t)),this.resendMessage(e)}),t);this.timeoutMap.set(e.packetNumber,i),this.sendPacket(e)}calculateRTO(e){const t=this.rtoRatioMap.get(e.packetNumber);if(void 0===t)return this.rtoRatioMap.set(e.packetNumber,1),this.initialRTO;{const i=9*this.rtt/8*t;return this.rtoRatioMap.set(e.packetNumber,t+1),i>this.maxRTO?this.maxRTO:i}}updateRTT(e,t){const i=e.ackSendTs;this.rtt=this.rtt*(7/8)+(t-i-this.rtt)/8}ack(e){if(e.packetNumber===this.lastOrderedPacketNumber+1)for(this.batchAckPacketQueue.length>=this.maxBatchAckCount&&this.batchAck(),this.batchAckTimer?this.batchAckPacketQueue.push(e):(this.batchAckPacketQueue.push(e),this.batchAckTimer=window.setTimeout((()=>{this.batchAck()}),this.rtt/8)),this.lastOrderedPacketNumber+=1,this.receiveImpl(e.payload);;){const e=this.unorderedPacketQueue[0];if(!e){this.unorderedPacketQueue.shift();break}this.batchAckTimer&&this.batchAck(),this.receiveImpl(e.payload),this.unorderedPacketQueue.shift(),this.lastOrderedPacketNumber+=1}else if(e.packetNumber<=this.lastOrderedPacketNumber){const t={ackSendTs:e.sendTs,maxAckPacketNumber:e.packetNumber,shift:0,type:Qc.Ack,version:this.version};ce("DC_DEBUG_LOG")&&B.debug("[".concat(this.ID,"] sending ack packet"),t,"packetNumber: ".concat(e.packetNumber)),this.sendPacket(t)}else if(e.packetNumber>this.lastOrderedPacketNumber){this.unorderedPacketQueue[e.packetNumber-this.lastOrderedPacketNumber-2]=e;const t={ackSendTs:e.sendTs,maxAckPacketNumber:e.packetNumber,shift:0,type:Qc.Ack,version:this.version};ce("DC_DEBUG_LOG")&&B.debug("[".concat(this.ID,"] sending ack packet"),t,"packetNumber: ".concat(e.packetNumber)),this.sendPacket(t)}}batchAck(){window.clearTimeout(this.batchAckTimer),this.batchAckTimer=void 0;const e={ackSendTs:this.batchAckPacketQueue[this.batchAckPacketQueue.length-1].sendTs,maxAckPacketNumber:this.batchAckPacketQueue[this.batchAckPacketQueue.length-1].packetNumber,shift:this.batchAckPacketQueue.length-1,type:Qc.Ack,version:this.version};ce("DC_DEBUG_LOG")&&B.debug("[".concat(this.ID,"] sending batch ack packet"),e,"shift: ".concat(this.batchAckPacketQueue.length-1)),this.sendPacket(e),this.batchAckPacketQueue=[]}sendPacket(e){e.type===Qc.Default&&(e.sendTs=Math.round(performance.now()));const t=this.serialize(e);this.sendImpl(t)}clearRTO(e){for(let t=e.maxAckPacketNumber-e.shift;t<=e.maxAckPacketNumber;t++){const e=this.timeoutMap.get(t);void 0!==e&&window.clearTimeout(e),this.timeoutMap.delete(t),this.rtoRatioMap.delete(t)}}}class Zc extends Xc{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]&&arguments[2],arguments.length>3?arguments[3]:void 0),this._initMutex=void 0,this._reconnectInterrupter=void 0,this._url=void 0,this._transmitter=void 0,this._addresses=void 0,this._reliableTransmission=void 0,this._textEncoder=void 0,this._textDecoder=void 0,this._textEncoder=new TextEncoder,this._textDecoder=new TextDecoder,this._initMutex=new ue("datachannel");const i=t.timeout,n=t.timeoutFactor,o=Math.max(300,Math.floor(3*i/5)),s=Math.max(1.2,Math.floor(8*n)/10);_e.ONLINE&&(this._retryConfig.timeout=o,this._retryConfig.timeoutFactor=s),pe.on(Ee.NETWORK_STATE_CHANGE,((e,t)=>{e!==t&&(this.resetReconnectCount("network state change: ".concat(t," -> ").concat(e)),e===_e.ONLINE?(this._retryConfig.timeout=o,this._retryConfig.timeoutFactor=s):(this._retryConfig.timeout=i,this._retryConfig.timeoutFactor=n))}))}getConnection(){if(this._reliableTransmission)return this._reliableTransmission}async init(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;this._forceCloseTimeout=t;const i=(t,i)=>{this._addresses=e,this.currentURLIndex=this._addresses.findIndex((e=>e.fingerprint||ce("FINGERPRINT")));const n=this._addresses[this.currentURLIndex];this.state="connecting",this.createTransmitterConnection(n).then(t).catch(i),this.once(Nn.CLOSED,(()=>i(new j(ne.WS_DISCONNECT)))),this.once(Nn.CONNECTED,(()=>t()))};return this._initMutex.lock().then((e=>new Promise(((e,t)=>{i(e,t)})).then((()=>{e()})).catch((()=>{e()}))))}async sendMessage(e){let t=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!this._transmitter||!this._reliableTransmission)throw new j(ne.WS_ABORT,"datachannel is not ready");try{t||(e=JSON.stringify(e));const i=this._textEncoder.encode(e),n=_i(i,{raw:!0});this._reliableTransmission.sendMessage(n)}catch(e){throw new j(ne.WS_ERR,"send datachannel signal message error"+e.toString())}}unbindDcCloseEventListener(){this._transmitter&&(this._transmitter.onclose=null)}sendMessageWithJSON(e){const t=JSON.stringify(e);return{compressed:t,compressedLength:t.length,origin:e}}sendMessageWithUint8Array(e){return{compressed:e,compressedLength:e.byteLength,origin:e}}createTransmitterConnection(e){return this.connectionID+=1,this._joinChannelServiceRecordIndex=void 0,this._url="dc://".concat(e.ip,":").concat(e.port),new Promise(((t,i)=>{var n;const o=()=>{B.debug("[".concat(this._name,"] datachannel opened:"),this._url),this.reconnectMode="recover",this.state="connected",this.resetReconnectCount("opened"),t()},s=async e=>{var n;if(null===(n=this._closeEstablishingTransmitter)||void 0===n||n.call(this),B.debug("[".concat(this._name,"] datachannel close ").concat(this._url,", code: ").concat(e.code,", reason: ").concat(e.reason,", current mode: ").concat(this.reconnectMode)),this._reconnectCount<this._retryConfig.maxRetryCount){"connected"===this.state&&(this.reconnectReason=e.reason,this.state="reconnecting");const n=Re(this,Nn.WILL_RECONNECT,this.reconnectMode)||this.reconnectMode,o=await this.reconnectWithAction(n);if("closed"===this.state)return void B.debug("[".concat(this.connectionID,"] dc is closed, no need to reconnect"));if(!o)return i(new j(ne.WS_DISCONNECT,"datachannel reconnect failed: ".concat(e.code))),void this.close(!0);t()}else i(new j(ne.WS_DISCONNECT,"datachannel close: ".concat(e.code))),this.close()},a=async e=>{try{var t;null===(t=this._reliableTransmission)||void 0===t||t.onData(e.data)}catch(e){console.log(e)}};this._transmitter&&(this._transmitter.onclose=null,this._transmitter.close()),this._reliableTransmission&&(this._reliableTransmission.close(),this._reliableTransmission=void 0),B.debug("[".concat(this._name,"] start connect, address: ").concat(JSON.stringify(e)));const r=null===(n=this._store)||void 0===n?void 0:n.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"gateway"}),c=Date.now();Ce(this,Nn.TO_CONNECT_DATACHANNEL).then((e=>{var t,i;if(!e)throw new Error("transmissonInfo not exist yet");const n=e.transmitter,d=e.close;this._transmitter=n,null===(t=this._store)||void 0===t||t.signalChannelOpen();const l=Date.now()-c;B.debug("[choose dc] dc open cost ".concat(l,"ms"));this._reliableTransmission=new zc((e=>{var t;this._transmitter&&"open"===this._transmitter.readyState&&(null===(t=this._transmitter)||void 0===t||t.send(e))}),(e=>{if("string"==typeof e)this.emit(Nn.ON_MESSAGE,e);else{const t=pi(e,{raw:!0}).buffer,i=this._textDecoder.decode(t);this.emit(Nn.ON_MESSAGE,i)}})),this._closeEstablishingTransmitter=()=>{var e;null===(e=this._reliableTransmission)||void 0===e||e.close(),this._reliableTransmission=void 0,d()},o&&o(),n.onclose=s,n.onmessage=a,null===(i=this._store)||void 0===i||i.recordJoinChannelService({endTs:Date.now(),status:"success"},r),this._joinChannelServiceRecordIndex=r})).catch((e=>{var t;if(null===(t=this._store)||void 0===t||t.recordJoinChannelService({endTs:Date.now(),status:e instanceof j&&e.code===ne.WS_ABORT?"aborted":"error",errors:[e]},r),"closed"!==this.state){if(e instanceof j&&e.code===ne.WS_ERR){const t=new j(ne.WS_ERR,"init datachannel failed! Error: ".concat(e.toString()));return B.error("[".concat(this._name,"]").concat(t)),void i(t)}s&&s(e)}else i(new j(ne.WS_DISCONNECT,"datachannel is closed: ".concat(e.toString())))}))}))}async reconnectWithAction(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(this._reconnectCount>=this._retryConfig.maxRetryCount)return!1;if(!this._addresses)return!1;if("closed"===this.state)return!1;this._onlineReconnectListener||pe.networkState!==_e.OFFLINE||(this._onlineReconnectListener=pe.onlineWaiter&&pe.onlineWaiter.then((()=>{this._onlineReconnectListener=void 0})));let i=!0;if(this._reconnectInterrupter=()=>{i=!1},t){const t=Se(this._reconnectCount,this._retryConfig);B.debug("[".concat(this._name,"] wait ").concat(t,"ms to reconnect datachannel, mode: ").concat(e)),await Promise.race([fe(t),this._onlineReconnectListener||new Promise((()=>{}))])}if("closed"===this.state||!i)return!1;this._reconnectCount+=1;const n=async(e,t)=>{this.emit(Nn.RECONNECT_CREATE_CONNECTION,t),await this.createTransmitterConnection(e)};try{if("retry"===e){const t=this._addresses[this.currentURLIndex];await n(t,e)}else if("tryNext"===e){this.currentURLIndex+=1;for(let e=this.currentURLIndex;e<this._addresses.length;e++){if(this._addresses[e].fingerprint||ce("FINGERPRINT")){this.currentURLIndex=e;break}this.currentURLIndex+=1}if(this.currentURLIndex>=this._addresses.length)return B.debug("[".concat(this._name,"] the available addresses are exhausted, change to recover")),await this.reconnectWithAction("recover",!1);B.debug("[".concat(this._name,"] datachannel url length: ").concat(this._addresses.length," current index: ").concat(this.currentURLIndex));const t=this._addresses[this.currentURLIndex];await n(t,e)}else"recover"===e&&(B.debug("[".concat(this._name,"] start to failback to websocket")),this.resetReconnectCount("recover mode"),this.emit(Nn.FAILBACK));return!0}catch(i){var o;return B.error("[".concat(this._name,"] reconnect failed"),i.toString()),null!=i&&null!==(o=i.data)&&void 0!==o&&o.desc&&Array.isArray(i.data.desc)&&i.data.desc.length&&i.data.desc.includes("dynamic key expired")?(this.emit(Nn.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1):await this.reconnectWithAction(e,t)}}}class $c extends re{get connectionState(){return this._connectionState}set connectionState(e){e!==this._connectionState&&(this._connectionState=e,e===Wi.CONNECTED?this.emit(Hi.WS_CONNECTED):e===Wi.RECONNECTING?this.emit(Hi.WS_RECONNECTING,this._websocketReconnectReason):e===Wi.CLOSED&&this.emit(Hi.WS_CLOSED,this._disconnectedReason))}get currentURLIndex(){return this.websocket.currentURLIndex}get url(){return this.websocket?this.websocket.url:null}get rtt(){return this.rttRolling.mean()}processPendingNotifications(){0!==this.pendingNotifications.length&&(B.debug("[".concat(this.clientId,"] processing ").concat(this.pendingNotifications.length," pending notifications")),this.pendingNotifications.forEach((e=>{let t=e.type,i=e.message;this.emit(t,i),t===qi.ON_NOTIFICATION&&this.handleNotification(i),t===qi.ON_USER_BANNED&&this.handleUserBanned(i)})),this.pendingNotifications=[])}handleUserBanned(e){switch(e.error_code){case 14:this.close(ge.UID_BANNED);break;case 15:this.close(ge.IP_BANNED);break;case 16:this.close(ge.CHANNEL_BANNED)}}constructor(e,t){super(),this.__name__="DataChannelSignal",this._disconnectedReason=void 0,this._websocketReconnectReason=void 0,this._connectionState=Wi.CLOSED,this.reconnectToken=void 0,this.websocket=void 0,this.openConnectionTime=void 0,this.clientId=void 0,this.lastMsgTime=Date.now(),this.uploadCache=[],this.uploadCacheInterval=void 0,this.rttRolling=new Te(5),this.pingpongTimer=void 0,this.inflateDataTimer=void 0,this.pingpongTimeoutCount=0,this.ortc=void 0,this.joinResponse=void 0,this.multiIpOption=void 0,this.initError=void 0,this.spec=void 0,this.store=void 0,this.isJoining=!1,this.pendingNotifications=[],this.onWebsocketMessage=e=>{if(e instanceof ArrayBuffer)return void this.emit(Hi.ON_BINARY_DATA,e);const t=JSON.parse(e);if(ce("DC_DEBUG_LOG")&&B.debug("[datachannel-signal] received packet",t),this.lastMsgTime=Date.now(),Object.prototype.hasOwnProperty.call(t,"_id")){const e="res-@".concat(t._id);this.emit(e,t._result,t._message)}else Object.prototype.hasOwnProperty.call(t,"_type")&&(this.isJoining?t._type===qi.ON_NOTIFICATION||t._type===qi.ON_USER_BANNED?(this.emit(t._type,t._message),t._type===qi.ON_NOTIFICATION&&this.handleNotification(t._message),t._type===qi.ON_USER_BANNED&&this.handleUserBanned(t._message)):(this.pendingNotifications.push({type:t._type,message:t._message}),B.debug("[".concat(this.clientId,"] cached notification during join: ").concat(t._type))):(this.emit(t._type,t._message),t._type===qi.ON_NOTIFICATION&&this.handleNotification(t._message),t._type===qi.ON_USER_BANNED&&this.handleUserBanned(t._message)))},this.clientId=e.clientId,this.spec=e,this.store=t,this.websocket=new Zc("gateway-".concat(this.clientId),this.spec.retryConfig,!0,t),this.handleWebsocketEvents(),window.addEventListener("offline",(()=>{this.connectionState===Wi.CONNECTED&&this.reconnect("retry",yn.OFFLINE)}))}async request(e,t,i,n){const o=ve(6,""),s={_id:o,_type:e,_message:t},a=this.websocket.connectionID,r=()=>new Promise(((t,i)=>{if(this.connectionState===Wi.CONNECTED)return t();const n=()=>{this.off(Hi.WS_CLOSED,o),t()},o=()=>{this.off(Hi.WS_CONNECTED,n),i(new j(ne.WS_ABORT))};this.once(Hi.WS_CONNECTED,n),this.once(Hi.WS_CLOSED,o),e!==Ki.PUBLISH&&e!==Ki.SUBSCRIBE&&e!==Ki.UNSUBSCRIBE&&e!==Ki.UNPUBLISH&&e!==Ki.CONTROL&&e!==Ki.RESTART_ICE||this.once(Hi.DISCONNECT_P2P,(()=>{i(new j(ne.DISCONNECT_P2P))})),e!==Ki.PUBLISH&&e!==Ki.RESTART_ICE||this.once(Hi.ABORT_P2P_EXECUTION,(()=>{i(new j(ne.DISCONNECT_P2P))}))}));if(this.connectionState!==Wi.CONNECTING&&this.connectionState!==Wi.RECONNECTING||e===Ki.JOIN||e===Ki.REJOIN||await r(),e===Ki.LEAVE&&(this.websocket.unbindDcCloseEventListener(),n=!0),ce("DC_DEBUG_LOG")&&B.debug("[datachannel-signal] sendMessage",s),await this.websocket.sendMessage(s,!0,!1),n)return;const c=new Promise(((i,n)=>{let s=!1;const r=(n,o)=>{s=!0,i({isSuccess:"success"===n,message:o||{}}),this.off(Hi.WS_CLOSED,c),this.off(Hi.WS_RECONNECTING,c),this.emit(Hi.REQUEST_SUCCESS,e,t)};this.once("res-@".concat(o),r);const c=()=>{n(new j(ne.WS_ABORT,"type: ".concat(e))),this.off(Hi.WS_CLOSED,c),this.off(Hi.WS_RECONNECTING,c),this.off("res-@".concat(o),r)};this.once(Hi.WS_CLOSED,c),this.once(Hi.WS_RECONNECTING,c),fe(ce("SIGNAL_REQUEST_TIMEOUT")).then((()=>{this.websocket.connectionID!==a||s||(B.warning("dc request timeout, type: ".concat(e)),this.emit(Hi.REQUEST_TIMEOUT,e,t))}))}));let d=null;try{d=await c}catch(n){if(this.connectionState===Wi.CLOSED||e===Ki.LEAVE)throw new j(ne.WS_ABORT);return!this.spec.forceWaitGatewayResponse||i?n.throw():e===Ki.JOIN||e===Ki.REJOIN?null:(await r(),await this.request(e,t))}if(d.isSuccess)return d.message;const l=Number(d.message.error_code||d.message.code),h=Un(l),u=new j(ne.UNEXPECTED_RESPONSE,"".concat(h.desc,": ").concat(d.message.error_str),{code:l,data:d.message});return"success"===h.action?d.message:(B.warning("[".concat(this.websocket.connectionID,"] unexpected response from type ").concat(e,", error_code: ").concat(l,", message: ").concat(h.desc,", action: ").concat(h.action)),l===Gi.ERR_TOO_MANY_BROADCASTERS?e===Ki.JOIN||e===Ki.REJOIN?(this.initError=u,this.close(),u.throw()):u.throw():"failed"===h.action?u.throw():"quit"===h.action?(this.initError=u,this.close(),u.throw()):(l===Gi.ERR_JOIN_BY_MULTI_IP?(this.multiIpOption=d.message.option,B.warning("[".concat(this.clientId,"] detect multi ip, recover")),this.reconnect("recover",yn.MULTI_IP)):this.reconnect(h.action,yn.SERVER_ERROR),e===Ki.JOIN||e===Ki.REJOIN?null:await this.request(e,t)))}waitMessage(e,t){return new Promise((i=>{const n=o=>{(!t||t(o))&&(this.off(e,n),i(o))};this.on(e,n)}))}uploadWRTCStats(e){if(!this.store.sessionId)return void B.warn("[".concat(this.clientId,"] no session id when upload wrtc stats"));const t={lts:Date.now(),sid:this.store.sessionId,uid:this.store.intUid,stats:e};this.upload(Yi.WRTC_STATS,t)}upload(e,t){const i={_type:e,_message:t};try{this.websocket.sendMessage(i)}catch(e){const t=ce("MAX_UPLOAD_CACHE")||50;this.uploadCache.push(i),this.uploadCache.length>t&&this.uploadCache.splice(0,1),this.uploadCache.length>0&&!this.uploadCacheInterval&&(this.uploadCacheInterval=window.setInterval((()=>{if(this.connectionState!==Wi.CONNECTED)return;const e=this.uploadCache.splice(0,1)[0];0===this.uploadCache.length&&(window.clearInterval(this.uploadCacheInterval),this.uploadCacheInterval=void 0),this.upload(e._type,e._message)}),ce("UPLOAD_CACHE_INTERVAL")||2e3))}}async send(e,t){const i={_type:e,_message:t};await this.websocket.sendMessage(i)}init(e){return this.initError=void 0,this.multiIpOption=void 0,this.joinResponse=void 0,this.reconnectToken=void 0,this.openConnectionTime=void 0,new Promise(((t,i)=>{this.once(Hi.WS_CONNECTED,(()=>t(this.joinResponse))),this.once(Hi.WS_CLOSED,(()=>i(this.initError||new j(ne.WS_ABORT)))),this.connectionState=Wi.CONNECTING,this.websocket.init(e).catch(i),this.websocket.once(Nn.FAILBACK,(()=>{i(new j(ne.INIT_DATACHANNEL_TIMEOUT))})),this.inflateDataTimer&&window.clearInterval(this.inflateDataTimer),this.inflateDataTimer=window.setInterval((()=>{this.handleInflateData()}),2e4),setTimeout((()=>{void 0===this.openConnectionTime&&(B.debug("[".concat(this.clientId,"] init datachannel timeout while join with failback to websocket")),i(new j(ne.INIT_DATACHANNEL_TIMEOUT)))}),ce("DC_JOIN_WITH_FAILBACK"))}))}close(e){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.inflateDataTimer&&(this.handleInflateData(),window.clearInterval(this.inflateDataTimer),this.inflateDataTimer=void 0),this.reconnectToken=void 0,this.joinResponse=void 0,this.isJoining=!1,this.pendingNotifications=[],this._disconnectedReason=e||ge.LEAVE,this.connectionState=Wi.CLOSED,B.debug("[".concat(this.clientId,"] ")+"will close datachannel in signal"),this.websocket.close(),e===ge.FALLBACK&&(this.websocket.removeAllListeners(),this.websocket=new Zc("gateway-".concat(this.clientId),this.spec.retryConfig,!0,this.store),this.handleWebsocketEvents())}async join(){if(this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),ce("DC_PINGPONG_INTERVAL")),!this.joinResponse){this.emit(Hi.ABORT_P2P_EXECUTION),this.store.signalConnected();const e=await Ce(this,Hi.REQUEST_JOIN_INFO);this.store.joinReq();let t=await Ce(this,Hi.REQUEST_JOIN_INFO_WITH_PRE_JOIN_RESPONSE);if(this.isJoining=!0,this.pendingNotifications=[],t){B.debug("join response from pre join response");const i=await this.request(Ki.JOIN,e);i&&"ortc"in i&&(t=i)}else B.debug("join response from request join_v3"),t=await this.request(Ki.JOIN,e);if(this.store.joinRep(),this.ortc=null==e?void 0:e.ortc,!t)return this.emit(Hi.REPORT_JOIN_GATEWAY,ne.TIMEOUT,this.url||""),!1;this.joinResponse=t,this.emit(Hi.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token}return this.connectionState=Wi.CONNECTED,this.isJoining=!1,this.processPendingNotifications(),!0}async rejoin(){if(!this.reconnectToken)throw new j(ne.UNEXPECTED_ERROR,"can not rejoin, no rejoin token");const e=Ae(this,Hi.REQUEST_REJOIN_INFO);e.token=this.reconnectToken;const t=await this.request(Ki.REJOIN,e);return!!t&&(this.connectionState=Wi.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),ce("DC_PINGPONG_INTERVAL")),t.peers&&t.peers.forEach((e=>{this.emit(qi.ON_USER_ONLINE,{uid:e.uid}),e.audio&&this.emit(qi.ON_ADD_AUDIO_STREAM,{uid:e.uid,uint_id:e.uint_id,audio:!0,ssrcId:e.audio_ssrc}),e.video&&this.emit(qi.ON_ADD_VIDEO_STREAM,{uid:e.uid,uint_id:e.uint_id,video:!0,ssrcId:e.video_ssrc}),e.audio_mute?this.emit(qi.MUTE_AUDIO,{uid:e.uid}):this.emit(qi.UNMUTE_AUDIO,{uid:e.uid}),e.video_mute?this.emit(qi.MUTE_VIDEO,{uid:e.uid}):this.emit(qi.UNMUTE_VIDEO,{uid:e.uid}),e.audio_enable_local?this.emit(qi.ENABLE_LOCAL_AUDIO,{uid:e.uid}):this.emit(qi.DISABLE_LOCAL_AUDIO,{uid:e.uid}),e.video_enable_local?this.emit(qi.ENABLE_LOCAL_VIDEO,{uid:e.uid}):this.emit(qi.DISABLE_LOCAL_VIDEO,{uid:e.uid}),e.audio||e.video||this.emit(qi.ON_REMOVE_STREAM,{uid:e.uid,uint_id:e.uint_id})})),!0)}reconnect(e,t){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.websocket.reconnect(e,t)}async downgradeCodec(e){if(!this.ortc)return!1;const t={downgrade_codec:e,ortc:this.ortc};return!!await this.request(Ki.DOWNGRADE_CODEC,t)}handleNotification(e){B.debug("[".concat(this.clientId,"] receive notification: "),e);const t=Un(e.code);if("success"!==t.action){if("failed"!==t.action)return"quit"===t.action?("ERR_REPEAT_JOIN_CHANNEL"===t.desc&&this.close(ge.UID_BANNED),void this.close()):void this.reconnect(t.action,yn.SERVER_ERROR);B.error("[".concat(this.clientId,"] ignore error: "),t.desc)}}handlePingPong(){if(!this.websocket||"connected"!==this.websocket.state)return;this.pingpongTimeoutCount>0&&this.rttRolling.add(3e3),this.pingpongTimeoutCount+=1,ce("DC_DEBUG_LOG")&&console.debug("[datachannel-signal] pingpongTimeoutCount: ".concat(this.pingpongTimeoutCount));const e=ce("PING_PONG_TIME_OUT"),t=Date.now();this.pingpongTimeoutCount>=e&&(B.warning("[datachannel-signal] PINGPONG Timeout. Last Socket Message: ".concat(t-this.lastMsgTime,"ms")),t-this.lastMsgTime>ce("WEBSOCKET_TIMEOUT_MIN"))?this.reconnect("recover",yn.FALLBACK):this.request(Ki.PING,void 0,!0).then((()=>{this.pingpongTimeoutCount=0;const e=Date.now()-t;this.rttRolling.add(e),ce("REPORT_STATS")&&this.send(Ki.PING_BACK,{pingpongElapse:e})})).catch((e=>{}))}handleInflateData(){const e=this.websocket.getInflateData(),t=e.inflateLength,i=e.deflateLength;0!==t&&0!==i&&this.upload(Yi.WS_INFLATE_DATA_LENGTH,{ws_deflate_length:i,ws_inflate_length:t})}handleWebsocketEvents(){this.websocket.on(Nn.RECONNECT_CREATE_CONNECTION,(e=>{this.emit(Hi.WS_RECONNECT_CREATE_CONNECTION,e)})),this.websocket.on(Nn.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(Nn.CLOSED,(()=>{this.connectionState=Wi.CLOSED})),this.websocket.on(Nn.FAILED,(()=>{this._disconnectedReason=ge.NETWORK_ERROR,this.connectionState=Wi.CLOSED})),this.websocket.on(Nn.RECONNECTING,(e=>{this._websocketReconnectReason=e,this.joinResponse=void 0,this.connectionState===Wi.CONNECTED?this.connectionState=Wi.RECONNECTING:this.connectionState=Wi.CONNECTING})),this.websocket.on(Nn.WILL_RECONNECT,((e,t)=>{if(Ae(this,Hi.IS_P2P_DISCONNECTED)&&"retry"===e)return B.debug("".concat(this.clientId," reconnect mode is retry, but p2p lost, change to tryNext")),this.reconnectToken=void 0,this.emit(Hi.NEED_RENEW_SESSION),this.emit(Hi.DISCONNECT_P2P),t("tryNext");"retry"!==e&&(B.debug("".concat(this.clientId," websockt will_connect event, renewSession reconnectMode is ").concat(e)),this.reconnectToken=void 0,this.emit(Hi.NEED_RENEW_SESSION),this.emit(Hi.DISCONNECT_P2P)),t(e)})),this.websocket.on(Nn.CONNECTED,(()=>{this.openConnectionTime=Date.now(),this.reconnectToken?this.rejoin().catch((e=>{B.warning("[".concat(this.clientId,"] rejoin failed ").concat(e)),this.reconnect("tryNext",yn.SERVER_ERROR)})):this.join().catch((e=>{if(this.emit(Hi.REPORT_JOIN_GATEWAY,e.message||e.code,this.url||""),e instanceof j&&e.code===ne.UNEXPECTED_RESPONSE&&e.data.code===Gi.ERR_NO_AUTHORIZED)return B.warning("[".concat(this.clientId,"] reconnect no authorized, recover")),void this.reconnect("recover",yn.SERVER_ERROR);B.error("[".concat(this.clientId,"] join gateway request failed"),e.toString()),this.spec.forceWaitGatewayResponse?this.reconnect("tryNext",yn.SERVER_ERROR):(this.initError=e,this.close())}))})),this.websocket.on(Nn.REQUEST_NEW_URLS,((e,t)=>{Ce(this,Hi.REQUEST_RECOVER,this.multiIpOption).then(e).catch(t)})),this.websocket.on(Nn.ON_TOKEN_PRIVILEGE_DID_EXPIRE,(()=>{this.emit(qi.ON_TOKEN_PRIVILEGE_DID_EXPIRE)})),this.websocket.on(Nn.TO_CONNECT_DATACHANNEL,((e,t)=>{Ce(this,Hi.PRE_CONNECT_PC).then(e).catch(t)})),this.websocket.on(Nn.FAILBACK,(()=>{void 0!==this.openConnectionTime&&this.emit(Hi.DATACHANNEL_FAILBACK)}))}}const ed={name:"DataChannelConnection",create:function(e){let t=e.store,i=e.spec;return new qc(i,t)}};const td={name:"DataChannelSignal",create:function(e){let t=e.store,i=e.spec;return new $c(i,t)}};function id(e){return M.enumerateDevices(!0,!0,e)}function nd(e){return M.getRecordingDevices(e)}function od(e){return M.getCamerasDevices(e)}function sd(e){return M.getSpeakers(e)}function ad(){return new Js}function rd(e){if(B.debug("setAppType: ".concat(e)),!(Number.isInteger(e)&&e>=0))throw B.debug("Invalid appType"),new j(ne.INVALID_PARAMS,"invalid app type",e);Ve("APP_TYPE",Math.floor(e))}function cd(e){B.setLogLevel(e)}function dd(){ce("USE_NEW_LOG")?Ve("UPLOAD_LOG",!0):B.enableLogUpload()}function ld(){ce("USE_NEW_LOG")?Ve("UPLOAD_LOG",!1):B.disableLogUpload()}function hd(e){Bc.processExternalMediaAEC(e)}function ud(e){e.forEach((e=>{const t=e;t.__registered__=!0,t.logger.hookLog=B.extLog,t.reporter.hookApiInvoke=G.extApiInvoke,t.parameters&&Object.keys(t.parameters).forEach((e=>{t.parameters[e]=ce(e)}))}))}function _d(){return S.autoResumeAfterInterruption(!0)}We(),Ve("PROCESS_ID",ai()),function(){let e;try{e=window.localStorage.getItem("websdk_ng_global_parameter")}catch(e){return void B.error("Error loading sdk config",e.message)}if(e)try{const t=JSON.parse(window.atob(e)),i=Date.now();B.debug("Loading global parameters from cache",t),Object.keys(t).forEach((e=>{if(Object.prototype.hasOwnProperty.call(Z,e)){const n=t[e],o=n.value,s=n.expires;if(s&&s<=i)return;$[e]=o,Z[e]=o}}))}catch(t){B.error("Error loading mutableParamsCache: ".concat(e),t.message)}}(),Array.isArray($.AREAS)&&$.AREAS.length>0&&os($.AREAS,!0),ce("DC_IN_ESM")&&(Fo(ed),Fo(td));const pd=function(e){const t=new re,i=e,n={getListeners:t.getListeners.bind(t),on:(e,i)=>(function(e,t){e===wn.SECURITY_POLICY_VIOLATION&&Gc(t,!0)}(e,i),t.on.bind(t)(e,i)),addListener:t.addListener.bind(t),once:t.once.bind(t),off:t.off.bind(t),removeAllListeners:t.removeAllListeners.bind(t),emit:t.emit.bind(t),safeEmit:t.safeEmit.bind(t)};return ki(ki({},i),n)}({});function Ed(e){k.onAudioAutoplayFailed=e}function md(e){k.onAutoplayFailed=e}function Sd(e){pd.onSecurityPolicyViolation=e}function fd(e){pd.onCameraChanged=e}function Cd(e){pd.onMicrophoneChanged=e}function Rd(e){pd.onAudioContextStateChanged=e}Object.defineProperties(pd,{onAudioAutoplayFailed:{get:()=>k.onAudioAutoplayFailed,set:Ed},onAutoplayFailed:{get:()=>k.onAutoplayFailed,set:md},_onSecurityPolicyViolation:{value:void 0,writable:!0},_cspEventHandlerPointer:{value:void 0,writable:!0},onSecurityPolicyViolation:{get:()=>pd._onSecurityPolicyViolation,set(e){pd._onSecurityPolicyViolation=e,Gc(e)}},__CLIENT_LIST__:{get:()=>ce("SHOW_GLOBAL_CLIENT_LIST")?Ti:[]}}),pd.use=e=>(Fo(e),pd),M.on(U.CAMERA_DEVICE_CHANGED,(e=>{B.info("camera device changed",JSON.stringify(e)),pd.onCameraChanged&&pd.onCameraChanged(e),pd.safeEmit(wn.CAMERA_CHANGED,e)})),M.on(U.RECORDING_DEVICE_CHANGED,(e=>{B.info("microphone device changed",JSON.stringify(e)),pd.onMicrophoneChanged&&pd.onMicrophoneChanged(e),pd.safeEmit(wn.MICROPHONE_CHANGED,e)})),M.on(U.PLAYOUT_DEVICE_CHANGED,(e=>{B.debug("playout device changed",JSON.stringify(e)),pd.onPlaybackDeviceChanged&&pd.onPlaybackDeviceChanged(e),pd.safeEmit(wn.PLAYBACK_DEVICE_CHANGED,e)})),S.onAutoplayFailed=()=>{B.info("detect audio element autoplay failed"),k.onAudioAutoplayFailed&&k.onAudioAutoplayFailed()},V.on("autoplay-failed",(()=>{B.info("detect webaudio autoplay failed"),k.onAudioAutoplayFailed&&k.onAudioAutoplayFailed(),pd.safeEmit(wn.AUTOPLAY_FAILED)})),V.on(x.STATE_CHANGE,((e,t)=>{B.info("audio context state changed: ".concat(t," => ").concat(e)),pd.onAudioContextStateChanged&&pd.onAudioContextStateChanged(e,t),pd.safeEmit(wn.AUDIO_CONTEXT_STATE_CHANGED,e,t)}));const Td=(e,t,i)=>{B.debug("setParameter key:".concat(e,", value:").concat(JSON.stringify(t))),Ve(e,t,i)};window&&(window.__ARTC__={ESM_BUNDLER:true,ESM:false,UMD:false,DEV:false,AgoraRTC:pd,__TRACK_LIST__:F,setParameter:Td,getParameter:ce}),pe.on(Ee.NETWORK_STATE_CHANGE,((e,t)=>{B.info("[network-indicator] network state changed, ".concat(t," => ").concat(e))}));export{dn as AREAS,pd as AgoraRTC,on as ChannelMediaRelayError,tn as ChannelMediaRelayEvent,nn as ChannelMediaRelayState,fi as DEV,mi as ESM,Ei as ESM_BUNDLER,Si as UMD,Ti as __CLIENT_LIST__,_r as checkAudioTrackIsActive,Mc as checkSystemRequirements,ur as checkVideoTrackIsActive,ad as createChannelMediaRelayConfiguration,Lc as createClient,ld as disableLogUpload,dd as enableLogUpload,od as getCameras,id as getDevices,nd as getMicrophones,sd as getPlaybackDevices,kc as getSupportedCodec,Cs as isAV1Decodable,Ed as onAudioAutoplayFailed,Rd as onAudioContextStateChanged,md as onAutoplayFailed,fd as onCameraChanged,Cd as onMicrophoneChanged,Sd as onSecurityPolicyViolation,Nr as preload,hd as processExternalMediaAEC,ud as registerExtensions,Ws as requestConfigDistribute,_d as resumeAudioContext,rd as setAppType,os as setArea,cd as setLogLevel,Td as setParameter,wr as startLastmileProbeTest};