agora-rtc-sdk-ng
Version:
Agora WebRTC SDK for JavaScript
6 lines • 280 kB
JavaScript
/**
* AgoraWebSDK_N-v4.24.8-0-gf100be755-dirty Copyright AgoraInc.
*/
import{LocalAudioTrack as e,MicrophoneAudioTrack as t,LocalVideoTrack as i,getCompatibility as n,TrackHint as s,audioTimerLoop as o,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 u,MediaElementNumStatus as h,visibilityWatcher as p,MediaElementStatus as _,audioElementPlayCenter as E,CameraVideoTrack as m,detectSupportPreSub as S,detectSupportSDPEndpoint as R,VideoPlayer as C,AgoraRTCPlayer as f,getOriginSenderConfig as v,RemoteAudioTrack as T,RemoteVideoTrack as g,TrackInternalEvent as I,RemoteTrackEvents as A,TrackEvents as D,StreamType as P}from"@agora-js/media";import{logger as N,AgoraRTCError as L,report as y,AgoraRTCEvent as O,AgoraRTCEventUploadType as w}from"@agora-js/report";import{IS_GLOBAL_VERSION as b,EventEmitter as k,getParameter as M,ScalabilityMode as U,parseSdp as V,isFirefox as x,jsonClone as F,printSdp as B,getRandomString as W,getBrowserInfo as G,BrowserName as H,BrowserOS as Y,PromiseMutex as K,createWebRTCStatsFilter as q,AgoraRTCError as j,AgoraRTCErrorCode as z,P2PTransportType as J,DEFAULT_CANDIDATE_STATS as X,isRTCIceServerList as Q,isChromeKernel as Z,noop as $,PeerConnectionState as ee,isSafari as te,isChromeBelow90 as ie,isAboveChrome as ne,isAboveEdge as se,isWebKit as oe,isChrome as ae,isFirefoxVersion as re,isBelowIOS14_6 as ce,VideoCodec as de,OVERUSE_DETECTOR_PARAMS as le,QualityLimitationReason as ue,isAboveIOS as he,isBelowIOS as pe,isAboveSafari as _e,isBelowSafari as Ee,AgoraAPIName as me,AgoraAPITag as Se,emitAsPromiseNoResponse as Re,emitAsPromise as Ce,emitAsInvokerNoResponse as fe,getUniqueList as ve,wait as Te,getRetryWaitTime as ge,DEFAULT_RETRY_CONFIG as Ie,uint8ArrayToBase64 as Ae,createDefer as De,isMacOS as Pe,NETWORK_STATE as Ne,networkIndicator as Le,NETWORK_INDICATOR_EVENTS as ye,Rolling as Oe,ConnectionDisconnectedReason as we,WebSocketQuitReason as be,base64ToUint8Array as ke}from"@agora-js/shared";import"@agora-js/protocol";function Me(e,t){this.v=e,this.k=t}function Ue(e,t,i,n,s){var o={};return Object.keys(n).forEach((function(e){o[e]=n[e]})),o.enumerable=!!o.enumerable,o.configurable=!!o.configurable,("value"in o||o.initializer)&&(o.writable=!0),o=i.slice().reverse().reduce((function(i,n){return n(e,t,i)||i}),o),s&&void 0!==o.initializer&&(o.value=o.initializer?o.initializer.call(s):void 0,o.initializer=void 0),void 0===o.initializer?(Object.defineProperty(e,t,o),null):o}function Ve(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 xe(e){return new Me(e,0)}function Fe(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 Be(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 We(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Be(Object(i),!0).forEach((function(t){Fe(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Be(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function Ge(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,s,o,a,r=[],c=!0,d=!1;try{if(o=(i=i.call(e)).next,0===t){if(Object(i)!==i)return;c=!1}else for(;!(c=(n=o.call(i)).done)&&(r.push(n.value),r.length!==t);c=!0);}catch(e){d=!0,s=e}finally{try{if(!c&&null!=i.return&&(a=i.return(),Object(a)!==a))return}finally{if(d)throw s}}return r}}(e,t)||function(e,t){if(e){if("string"==typeof e)return Ve(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)?Ve(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 He(e){return function(){return new Ye(e.apply(this,arguments))}}function Ye(e){var t,i;function n(t,i){try{var o=e[t](i),a=o.value,r=a instanceof Me;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}s(!!o.done,i)}),(function(e){n("throw",e)}))}catch(e){s(2,e)}}function s(e,s){2===e?t.reject(s):t.resolve({value:s,done:e}),(t=t.next)?n(t.key,t.arg):i=null}this._invoke=function(e,s){return new Promise((function(o,a){var r={key:e,arg:s,resolve:o,reject:a,next:null};i?i=i.next=r:(t=i=r,n(e,s))}))},"function"!=typeof e.return&&(this.return=void 0)}Ye.prototype["function"==typeof Symbol&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},Ye.prototype.next=function(e){return this._invoke("next",e)},Ye.prototype.throw=function(e){return this._invoke("throw",e)},Ye.prototype.return=function(e){return this._invoke("return",e)};let Ke=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}({}),qe=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}({}),je=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}({}),ze=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}({}),Je=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_TOO_MANY_MESSAGES=2033]="ERR_TOO_MANY_MESSAGES",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}({}),Xe=function(e){return e.CONNECTING="connecting",e.CONNECTED="connected",e.RECONNECTING="reconnecting",e.CLOSED="closed",e}({}),Qe=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.SHOULD_ENTER_RECONNECTING="should_enter_reconnecting",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}({}),Ze=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}({}),$e=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}({}),et=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}({}),tt=function(e){return e.SEND_ONLY="SEND_ONLY",e.RECEIVE_ONLY="RECEIVE_ONLY",e}({}),it=function(e){return e.CONNECTED="websocket:connected",e.RECONNECTING="websocket:reconnecting",e.WILL_RECONNECT="websocket:will_reconnect",e.SHOULD_ENTER_RECONNECTING="websocket:should_enter_reconnecting",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}({}),nt=function(e){return e.High="high",e.Low="low",e.Audio="audio",e.Screen="screen",e.ScreenLow="screen_low",e}({}),st=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}({});const ot=[[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]];let at=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}({});at.AFRICA,at.ASIA,at.CHINA,at.EUROPE,at.GLOBAL,at.INDIA,at.JAPAN,at.NORTH_AMERICA,at.OCEANIA,at.OVERSEA,at.SOUTH_AMERICA;let rt=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}({});rt.ASIA,rt.NORTH_AMERICA,rt.EUROPE,rt.JAPAN,rt.INDIA,rt.KOREA,rt.HKMC,rt.US,rt.OVERSEA,rt.GLOBAL,rt.OCEANIA,rt.SOUTH_AMERICA,rt.AFRICA,b&&rt.CHINA;class ct extends k{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.onAudioMetadata=void 0,this.onAudioPts=void 0,this.onSelectedLocalCandidateChanged=void 0,this.onSelectedRemoteCandidateChanged=void 0,this.onICECandidateError=void 0,this.getLocalVideoStats=void 0}}class dt extends ct{constructor(e,t){super(e,t),this.establishPromise=void 0}}let lt=function(e){return e.VIDEO="video",e.AUDIO="audio",e}({}),ut=function(e){return e.UDP_RELAY="udp_relay",e.UDP_TCP_RELAY="udp_tcp_relay",e.TCP_RELAY="tcp_relay",e.RELAY="relay",e}({}),ht=function(e){return e.LocalVideoTrack="videoTrack",e.LocalAudioTrack="audioTrack",e.LocalVideoLowTrack="videoLowTrack",e}({}),pt=function(e){return e.New="new",e.Connected="connected",e.Reconnecting="reconnecting",e.Disconnected="disconnected",e}({}),_t=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}({}),Et=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}({}),mt=function(e){return e.ABORT="abort",e}({}),St=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}({}),Rt=function(e){return e.P2P_TOKEN_TIMEOUT="p2p_token_timeout",e.P2P_TOKEN_CHANGED="p2p_token_changed",e}({}),Ct=0;function ft(e){const t=M("TURN_DOMAINS");Ct=(Ct+1)%t.length;const i=t[Ct]||"edge.agora.io";return e.match(/^[\.\:\d]+$/)?"".concat(e.replace(/[^\d]/g,"-"),".").concat(i):(N.debug("Cannot recognized as ip address: ".concat(e,", use as host2")),e)}function vt(e){return"number"==typeof e?e:e.exact||e.ideal||e.max||e.min||0}function Tt(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 gt(e,t){const i=t.getMediaStreamTrack(!0).getSettings(),n=t.videoHeight||i.height,s=t.videoWidth||i.width;return n&&s?Math.max(Math.min(n,s)/Math.min(vt(e.height),vt(e.width)),1):(N.warning("can't get ori-track's height, default scale down 4 times for low stream"),4)}function It(e){let t=e.candidateType,i=e.relayProtocol,n=e.type,s=e.address,o=e.port;const a={candidateType:t,relayProtocol:i,protocol:e.protocol};if("local-candidate"!==n){const e=s.split(".");e.length>=4&&(e[1]="*",e[2]="*"),a.address=e.join("."),a.port=o}return a}function At(e){const t=e.split(":"),i=e.split(/[-.]/),n=e.includes("-")?"-":".";let s=e;return t.length>1?i.length>1?(i[1]="**",s=i[0]+n+"**:"+t[t.length-1]):s=t.length>2?t[0]+n+"**:"+t[t.length-1]:"**:"+t[t.length-1]:i.length>1&&(s=i[0]+n+"**"),s}function Dt(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:M("SVC_MODE");if(M("ENABLE_SVC"))return function(e){return e in U}(e)?e:U.L1T3}const Pt={[lt.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"}],[lt.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 Nt(e,t,i){t.forEach((t=>{const n=Pt[e].find((e=>{let i=e.key;return t.extensionName.includes(i)}));if(!n)return;const s=i.find((e=>e.extensionName.includes(n.key)));s&&s.extensionName.includes("gdpr_forbidden")&&(t.extensionName=s.extensionName)}))}function Lt(e,t){t.forEach((t=>{const i=Pt[e].find((e=>{let i=e.key;return t.extensionName.includes(i)}));t.extensionName.includes("gdpr_forbidden")&&i&&(t.extensionName=i.extensionName)}))}function yt(e){return"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"===e||e.includes("abs-send-time")}function Ot(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 wt(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 s=t.filterRTX,o=t.filterVideoFec,a=t.filterAudioFec,r=t.filterAudioCodec,c=t.filterVideoCodec,d=t.unsupportedVideoUplinkCodec,l=t.unsupportedVideoDownlinkCodec,u=i.useXR;let h=[],p=[],_=[],E=[],m=!1,S=!1;if(V(e).mediaDescriptions.forEach((e=>{n&&n!==e.attributes.direction||("video"!==e.media.mediaType||m||(p=e.attributes.payloads,E=e.attributes.extmaps,m=!0),"audio"!==e.media.mediaType||S||(h=e.attributes.payloads,_=e.attributes.extmaps,S=!0))})),!E||0===p.length)throw new Error("Cannot get video capabilities from SDP.");if(!_||0===h.length)throw new Error("Cannot get audio capabilities from SDP.");if(p.forEach((e=>{var t;null!==(t=e.rtpMap)&&void 0!==t&&t.clockRate&&(e.rtpMap.clockRate=parseInt(e.rtpMap.clockRate)),u&&e.rtcpFeedbacks.push({type:"rrtr"})})),h.forEach((e=>{var t;null!==(t=e.rtpMap)&&void 0!==t&&t.clockRate&&(e.rtpMap.clockRate=parseInt(e.rtpMap.clockRate)),u&&e.rtcpFeedbacks.push({type:"rrtr"})})),s&&(h=h.filter((e=>{var t;return"rtx"!==(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())})),p=p.filter((e=>{var t;return"rtx"!==(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())}))),o){const e=p.filter((e=>{var t;return/(red)|(ulpfec)|(flexfec)/i.test((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName)||"")})),t=zt(e,p).map((e=>e.payloadType)),i=[...e.map((e=>e.payloadType)),...t];p=p.filter((e=>!i.includes(e.payloadType)))}if(a&&(h=h.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&&(h=h.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=p.filter((e=>{var t;return c.includes((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())||"")}));p=e.concat(s?[]:zt(e,p))}const R=M("UNSUPPORTED_VIDEO_CODEC");if(R&&R.length>0){const e=p.filter((e=>e.rtpMap&&R.includes(e.rtpMap.encodingName.toLowerCase()))),t=zt(e,p),i=e.concat(t).map((e=>e.payloadType));p=p.filter((e=>!i.includes(e.payloadType))),N.debug("unsupportedVideoCodec: ".concat(R,", toBeRemoved: ").concat(i))}if(d&&d.length>0&&"sendonly"===n){const e=p.filter((e=>e.rtpMap&&d.includes(e.rtpMap.encodingName.toLowerCase()))),t=zt(e,p),i=e.concat(t).map((e=>e.payloadType));p=p.filter((e=>!i.includes(e.payloadType))),N.debug("unsupportedVideoUplinkCodec: ".concat(d,", toBeRemoved: ").concat(i))}if(l&&l.length>0&&"recvonly"===n){const e=p.filter((e=>e.rtpMap&&l.includes(e.rtpMap.encodingName.toLowerCase()))),t=zt(e,p),i=e.concat(t).map((e=>e.payloadType));p=p.filter((e=>!i.includes(e.payloadType))),N.debug("unsupportedVideoDownlinkCodec: ".concat(l,", toBeRemoved: ").concat(i))}return{audioCodecs:h,videoCodecs:p,audioExtensions:_,videoExtensions:E}}function bt(e){const t=V(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 kt(e,t){const i=[],n=e.attributes.ssrcGroups.filter((e=>"FID"===e.semantic)),s=e.attributes.ssrcGroups.find((e=>"SIM"===e.semantic)),o=e.attributes.ssrcs;if(s)s.ssrcIds.forEach((e=>{var s;const o=null===(s=n.find((t=>t.ssrcIds[0]===e)))||void 0===s?void 0:s.ssrcIds[1];i.push({ssrcId:e,rtx:t?o:void 0})}));else if(n.length>0){const e=n[0].ssrcIds[0],s=n[0].ssrcIds[1];i.push({ssrcId:e,rtx:t?s:void 0})}else{if(0===o.length)throw new Error("No ssrcs found on local media description.");i.push({ssrcId:o[0].ssrcId})}return i}function Mt(e,t,i){const n=[],s=[];return e.forEach((e=>{let o=e.ssrcId,a=e.rtx;const r=W(8,"track-"),c={ssrcId:o,attributes:We({label:r,mslabel:i=i||W(10,""),msid:"".concat(i," ").concat(r)},t&&{cname:t})};if(n.push(c),void 0!==a){const e={ssrcId:a,attributes:We({label:r,mslabel:i,msid:"".concat(i," ").concat(r)},t&&{cname:t})};n.push(e),s.push({semantic:"FID",ssrcIds:[o,a]})}})),e.length>1&&s.push({semantic:"SIM",ssrcIds:e.map((e=>e.ssrcId))}),{ssrcs:n,ssrcGroups:s}}function Ut(i,n){n instanceof e&&i.attributes.payloads.forEach((e=>{var i;const s=null===(i=e.rtpMap)||void 0===i?void 0:i.encodingName.toLowerCase();if(!s||-1===["opus","pcmu","pcma","g722"].indexOf(s))return;e.fmtp||(e.fmtp={parameters:{}}),"opus"===s&&"number"==typeof M("OPUS_PTIME")?e.fmtp.parameters.ptime=M("OPUS_PTIME"):e.fmtp.parameters.minptime="10",e.fmtp.parameters.useinbandfec="1";const o=n._encoderConfig;o&&("pcmu"!==s&&"pcma"!==s&&"g722"!==s&&(o.bitrate&&!x()&&(e.fmtp.parameters.maxaveragebitrate="".concat(Math.floor(1e3*o.bitrate))),o.sampleRate&&(e.fmtp.parameters.maxplaybackrate="".concat(o.sampleRate),e.fmtp.parameters["sprop-maxcapturerate"]="".concat(o.sampleRate)),o.stereo&&(e.fmtp.parameters.stereo="1",e.fmtp.parameters["sprop-stereo"]="1")),n instanceof t&&"opus"===s&&n._config.DTX&&(e.fmtp.parameters.usedtx="1"))}))}function Vt(e){const t=e.attributes.unrecognized.findIndex((e=>"x-google-flag"===e.attField&&"conference"===e.attValue));-1!==t&&e.attributes.unrecognized.splice(t,1)}function xt(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&&M("ENABLE_UP_SPS_PPS")&&(e.fmtp.parameters["sps-pps-idr-in-keyframe"]="1")})),!(t instanceof i&&t._encoderConfig&&-1===t._hints.indexOf(s.SCREEN_TRACK)))return;const o=t._encoderConfig;n().supportMinBitrate&&o.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(o.bitrateMin))})),n().supportMinBitrate&&!t._hints.includes(s.LOW_STREAM)&&o.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(M("X_GOOGLE_START_BITRATE")||Math.floor(o.bitrateMax)))}))}function Ft(e){if("video"!==e.media.mediaType)return;const t=G();if(t.name!==H.SAFARI&&t.os!==Y.IOS)return;const i=e.attributes.extmaps.findIndex((e=>/video-orientation/g.test(e.extensionName)));-1!==i&&e.attributes.extmaps.splice(i,1)}function Bt(e,t,i){if(!t)return;let n,s;if("video"===e.media.mediaType?(n=i.videoExtensions,s=i.videoCodecs):(n=i.audioExtensions,s=i.audioCodecs),!0===t.twcc){const t=n.find((e=>Ot(e.extensionName)));if(t){const i=t.extensionName;e.attributes.extmaps.find((e=>Ot(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))))))}(s,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=>Ot(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=>yt(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))))))}(s,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=>yt(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 Wt(e,t,n){if(x())return;if("video"!==e.media.mediaType)return;if(!(t instanceof i))return;if("vp9"!==n&&"vp8"!==n)return;if("vp8"===n&&!M("SIMULCAST"))return;if("vp9"===n&&M("ENABLE_SVC"))return;if(void 0===t._scalabilityMode||t._scalabilityMode.numSpatialLayers<=1)return;const s="vp8"===n?2:t._scalabilityMode.numSpatialLayers,o=e.attributes.ssrcs[0],a=e.attributes.ssrcGroups.find((e=>"FID"===e.semantic&&e.ssrcIds[0]===o.ssrcId)),r={semantic:"SIM",ssrcIds:[o.ssrcId]};for(let t=1;t<s;t++)e.attributes.ssrcs.push({ssrcId:o.ssrcId+t,attributes:F(o.attributes)}),r.ssrcIds.push(o.ssrcId+t),a&&(e.attributes.ssrcs.push({ssrcId:a.ssrcIds[1]+t,attributes:F(o.attributes)}),e.attributes.ssrcGroups.push({semantic:"FID",ssrcIds:[o.ssrcId+t,a.ssrcIds[1]+t]}));e.attributes.ssrcGroups.unshift(r)}async function Gt(){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=wt(i,e,t,"sendonly"),s=wt(i,e,t,"recvonly"),o={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},a={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},r={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]};if(Yt(n,s,"videoExtensions",o,a,r),Yt(n,s,"videoCodecs",o,a,r),Yt(n,s,"audioExtensions",o,a,r),Yt(n,s,"audioCodecs",o,a,r),M("RAISE_H264_BASELINE_PRIORITY")){const e=[],t=[];if(r.videoCodecs.forEach(((i,n)=>{var s;if("h264"===(null===(s=i.rtpMap)||void 0===s?void 0:s.encodingName.toLocaleLowerCase())){var o,a;const s=r.videoCodecs[n+1],c=s&&$t(i,s),d=null===(o=i.fmtp)||void 0===o?void 0:o.parameters["profile-level-id"],l=null===(a=i.fmtp)||void 0===a?void 0:a.parameters["packetization-mode"];!d||d!==M("FIRST_H264_PROFILE_LEVEL_ID")||M("FIRST_PACKETIZATION_MODE")&&l!==M("FIRST_PACKETIZATION_MODE")?c?t.push([i,s]):t.push([i]):c?e.push([i,s]):e.push([i])}})),e.length>0&&t.length>0){N.debug("raising H264 baseline profile priority"),r.videoCodecs.forEach(((i,n)=>{var s;if("h264"===(null===(s=i.rtpMap)||void 0===s?void 0:s.encodingName.toLocaleLowerCase())){const s=$t(i,r.videoCodecs[n+1]),o=e.shift()||t.shift()||[];o.length>0&&(s?r.videoCodecs.splice(n,2,...o):r.videoCodecs.splice(n,1,...o))}}));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"])!==M("FIRST_H264_PROFILE_LEVEL_ID")}));if(i.length>0){const e=zt(i,a.videoCodecs).map((e=>e.payloadType)),t=[...i.map((e=>e.payloadType)),...e];a.videoCodecs=a.videoCodecs.filter((e=>!t.includes(e.payloadType)))}M("FILTER_SEND_H264_BASELINE")&&(o.videoCodecs=o.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"])!==M("FIRST_H264_PROFILE_LEVEL_ID"))})))}return{send:o,recv:a,sendrecv:r}}return{send:o,recv:a,sendrecv:r}}(e,t,(await i.createOffer()).sdp),s=n.send,o=n.recv,a=n.sendrecv;try{i.close()}catch(e){}return{send:s,recv:o,sendrecv:a}}function Ht(){const e={audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]},t=wt(arguments.length>2?arguments[2]:void 0,arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},"recvonly"),i={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},n={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},s={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]};if(Yt(e,t,"videoExtensions",i,n,s),Yt(e,t,"videoCodecs",i,n,s),Yt(e,t,"audioExtensions",i,n,s),Yt(e,t,"audioCodecs",i,n,s),M("RAISE_H264_BASELINE_PRIORITY")){const e=s.videoCodecs.findIndex((e=>e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase()&&e.fmtp&&"42001f"===e.fmtp.parameters["profile-level-id"]));if(-1!==e){const t=s.videoCodecs.findIndex((e=>e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase()));if(t<e){N.debug("raising H264 baseline profile priority");const i=s.videoCodecs[e];s.videoCodecs.splice(e,1),s.videoCodecs.splice(t,0,i)}-1!==t&&(n.videoCodecs=n.videoCodecs.filter((e=>!(e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase()&&e.fmtp&&"42001f"!==e.fmtp.parameters["profile-level-id"]))))}}return{send:i,recv:n,sendrecv:s}}function Yt(e,t,i,n,s,o){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}))?o[i].push(e):n[i].push(e)})),void t[i].forEach(((e,t)=>{-1===a.indexOf(t)&&s[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}))?o[i].push(e):n[i].push(e)})),void t[i].forEach(((e,t)=>{-1===a.indexOf(t)&&s[i].push(e)}))}}function Kt(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 s,o;return t?(s={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},s.audioCodecs=[...t.audioCodecs,...n.audioCodecs],s.videoCodecs=[...t.videoCodecs,...n.videoCodecs],s.audioExtensions=[...t.audioExtensions,...n.audioExtensions],s.videoExtensions=[...t.videoExtensions,...n.videoExtensions]):s=F(n),i?(o={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},o.audioCodecs=[...i.audioCodecs,...n.audioCodecs],o.videoCodecs=[...i.videoCodecs,...n.videoCodecs],o.audioExtensions=[...i.audioExtensions,...n.audioExtensions],o.videoExtensions=[...i.videoExtensions,...n.videoExtensions]):o=F(n),{send:s,recv:o}}function qt(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 jt(e,t,i,n){let s=[];if(e===lt.VIDEO){if(M("H264_PROFILE_LEVEL_ID")&&"h264"===n&&(s=t.videoCodecs.filter((e=>(e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").includes(n)&&e&&e.fmtp&&e.fmtp.parameters["profile-level-id"]===M("H264_PROFILE_LEVEL_ID")))),!Array.isArray(s)||0===s.length){let e=[];const o=[],a=[],r=[];if(i.videoCodecs.forEach((t=>{const i=t.rtpMap&&t.rtpMap.encodingName.toLowerCase()||"";i.includes(n)?e.push(t):i.includes("vp9")?o.push(t):i.includes("vp8")?a.push(t):i.includes("h264")&&r.push(t)})),0===e.length){let t="";0!==o.length?(e=o,t="vp9"):0!==a.length?(e=a,t="vp8"):0!==r.length&&(e=r,t="h264"),N.warning("codec ".concat(n," not included in rtpCapabilities, fallback to default payloads: ").concat(t))}0!==e.length&&(s=t.videoCodecs.filter((t=>e.some((e=>e.payloadType===t.payloadType)))))}if(0===s.length&&(N.warning("codec ".concat(n," not included in rtpCapabilities, fallback to default payloads: ").concat(t.videoCodecs[0].rtpMap&&t.videoCodecs[0].rtpMap.encodingName)),s=t.videoCodecs),M("USE_PUB_RTX")||M("USE_SUB_RTX")){const e=zt(s,t.videoCodecs);s=[...s,...e]}}else{s=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===s.length&&(N.warning("codec ".concat(n," not included in rtpCapabilities, fallback to opus")),s=t.audioCodecs.filter((e=>(e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").includes("opus")))),M("ENABLE_AUDIO_RED")&&0!==e.length&&(s=[...e,...s])}return s}function zt(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 Jt(e,t,i){const n=t.toString(),s=Qt(n,"offer","remote","exchangeSDP");await e.setRemoteDescription({type:"offer",sdp:n});const o=await e.createAnswer();if(!o.sdp)throw new Error("cannot get answer sdp");let a=o.sdp;a=Xt(a,i||{}),null==s||s(a||""),await e.setLocalDescription({type:"answer",sdp:a})}function Xt(e,t,i){if(M("FORBID_MODIFY_LOCAL_OFFER_SDP"))return e;const n=V(e),s=t.useXR;return n.mediaDescriptions.forEach((e=>{e.attributes.mid&&(Array.isArray(i)&&!i.includes(e.attributes.mid)||("audio"===e.media.mediaType&&qt(e),"video"===e.media.mediaType&&function(e){if("video"!==e.media.mediaType)return;if(!M("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),s&&["audio","video"].includes(e.media.mediaType)&&e.attributes.payloads.forEach((e=>{-1===e.rtcpFeedbacks.findIndex((e=>"rrtr"===e.type))&&e.rtcpFeedbacks.push({type:"rrtr"})}))))})),B(n)}function Qt(e,t,i,n){if(M("SDP_LOGGING"))return N.upload("exchanging ".concat(i," ").concat(t," SDP during P2PConnection.").concat(n,"\n"),e),"offer"===t?e=>{Qt(e,"answer","local"===i?"remote":"local",n)}:void 0}function Zt(e){const t=M("COMPATIBLE_SDP_EXTENSION");return!!(Array.isArray(t)&&t.length>0)&&t.some((t=>e.includes(t)))}function $t(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}}let ei=class{get localCapabilities(){return F(this._localCapabilities)}get rtpCapabilities(){return F(this._rtpCapabilities)}get candidates(){return F(this._candidates)}get iceParameters(){return F(this._iceParameters)}get dtlsParameters(){return F(this._dtlsParameters)}constructor(e){this.sessionDesc=void 0,this._localCapabilities=void 0,this._rtpCapabilities=void 0,this._candidates=void 0,this._iceParameters=void 0,this._dtlsParameters=void 0,this.setup=void 0,this.currentMidIndex=void 0,this.cname="o/i14u9pJrxRKAsu",this.firefoxSsrcMidMap=new Map;const t=e=F(e),i=t.remoteIceParameters,n=t.remoteDtlsParameters,s=t.candidates,o=t.remoteRTPCapabilities,a=t.localCapabilities,r=t.direction,c=t.setup,d=t.videoCodec,l=t.audioCodec;let u;this.setup=c,u=r===tt.RECEIVE_ONLY?V("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=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"):V("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=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=recvonly\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=recvonly\na=rtcp-mux\na=rtcp-rsize\na=mid:1\n"),this._rtpCapabilities=o,this._candidates=s,this._iceParameters=i,this._dtlsParameters=n,this._localCapabilities=a;const h=r===tt.RECEIVE_ONLY?this.rtpCapabilities.send:this.rtpCapabilities.recv,p=r===tt.RECEIVE_ONLY?this._localCapabilities.recv:this._localCapabilities.send,_=r===tt.RECEIVE_ONLY?o.send.videoCodecs:jt(lt.VIDEO,h,p,d),E=r===tt.RECEIVE_ONLY?o.send.audioCodecs:jt(lt.AUDIO,h,p,l);for(const e of u.mediaDescriptions)e.attributes.iceUfrag=i.iceUfrag,e.attributes.icePwd=i.icePwd,e.attributes.fingerprints=n.fingerprints,e.attributes.candidates=s,e.attributes.setup=this.setup,"application"===e.media.mediaType&&(e.attributes.sctpPort="5000"),"video"===e.media.mediaType&&(e.media.fmts=_.map((e=>e.payloadType.toString(10))),e.attributes.payloads=_,e.attributes.extmaps=h.videoExtensions),"audio"===e.media.mediaType&&(e.media.fmts=E.map((e=>e.payloadType.toString(10))),e.attributes.payloads=E,e.attributes.extmaps=h.audioExtensions,qt(e));this.sessionDesc=u,this.currentMidIndex=u.mediaDescriptions.length-1}toString(){return B(this.sessionDesc)}hasMid(e){return Array.isArray(e)?e.every((e=>this.hasMid(e))):this.sessionDesc.mediaDescriptions.some((t=>t.attributes.mid===e))}send(e,t,i,n,s){i=i.replace(/ /g,"-");const o=Mt(t,this.cname,M("SYNC_GROUP")?i:void 0),a=o.ssrcs,r=o.ssrcGroups,c=this.findPreloadMediaDesc(a);if(c){if(x()&&this.firefoxSsrcMidMap.set(a[0].ssrcId,c.attributes.mid),s&&(s.twcc||s.remb)){const e=this.sessionDesc.mediaDescriptions.indexOf(c);return this.sessionDesc.mediaDescriptions[e]=this.mungSendMediaDesc(c,s),{mid:c.attributes.mid,needExchangeSDP:!0}}return{mid:c.attributes.mid,needExchangeSDP:!1}}{const t=this.findAvailableMediaIndex(e,a,n);let i;return-1===t?(i=this.createOrRecycleSendMedia(e,a,r,"sendonly",n,s),this.updateBundleMids()):(i=F(this.sessionDesc.mediaDescriptions[t]),i.attributes.direction="sendonly",i.attributes.ssrcs=a,i.attributes.ssrcGroups=r,this.sessionDesc.mediaDescriptions[t]=this.mungSendMediaDesc(i,s)),x()&&this.firefoxSsrcMidMap.set(a[0].ssrcId,i.attributes.mid),{needExchangeSDP:!0,mid:i.attributes.mid}}}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=>{e.attributes.ssrcs=[]})),this.updateBundleMids()}receive(e,t,i){const n=[];return e.forEach((e=>{const s=e._mediaStreamTrack.kind,o=this.findAvailableRecvMediaIndex(s);let a,r=!1;-1===o?(r=!0,a=this.createOrRecycleRecvMedia(e,[],"recvonly",t,i),this.updateBundleMids()):(a=F(this.sessionDesc.mediaDescriptions[o]),a.attributes.direction="recvonly"),n.push({mid:a.attributes.mid,needCreateTransceiver:r})})),n}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()}addRemoteCandidate(e){const t=new RTCIceCandidate(e),i=t.foundation,n=t.protocol,s=t.address,o=t.port,a=t.type,r=t.relatedAddress,c=t.relatedPort,d=t.priority,l={foundation:null!=i?i:"",componentId:"1",transport:null!=n?n:"",priority:d?d+"":"",connectionAddress:null!=s?s:"",port:o?o+"":"",type:a?a+"":"",relAddr:null!=r?r:"",relPort:c?c+"":"",extension:{}};this.candidates.some((e=>e.priority===l.priority&&e.connectionAddress===l.connectionAddress&&e.port===l.port))||(this._candidates.push(l),this.sessionDesc.mediaDescriptions.forEach((e=>{e.attributes.candidates=this.candidates})))}clearRemoteCandidate(){this._candidates=[],this.sessionDesc.mediaDescriptions[0].attributes.candidates=this._candidates}createOrRecycleRecvMedia(e,t,i,n,s){const o=e._mediaStreamTrack.kind,a=this.rtpCapabilities.recv,r=jt(o,a,this.localCapabilities.send,o===lt.AUDIO?s:n),c=o===lt.VIDEO?a.videoExtensions:a.audioExtensions,d="".concat(++this.currentMidIndex);let l={media:{mediaType:o,port:"9",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:[],extmaps:c,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:r,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:i,rtcpMux:!0,rtcpRsize:!0,mid:"".concat(d)}};l=this.mungRecvMediaDsec(l,e);const u=this.findFirstClosedMedia(o);if(u){const e=this.sessionDesc.mediaDescriptions.indexOf(u);this.sessionDesc.mediaDescriptions[e]=l}else this.sessionDesc.mediaDescriptions.push(l);return l}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"}))}findAvailableMediaIndex(e,t,i){return this.sessionDesc.mediaDescriptions.findIndex((n=>{const s=n.media.mediaType===e&&"0"!==n.media.port&&("sendonly"===n.attributes.direction||"sendrecv"===n.attributes.direction)&&0===n.attributes.ssrcs.length;if(x()){if(s){const e=this.firefoxSsrcMidMap.get(t[0].ssrcId);return!(e||"0"!==n.attributes.mid&&"1"!==n.attributes.mid)||!(!e||e!==n.attributes.mid)}return!1}return s&&n.attributes.mid===i}))}findAvailableRecvMediaIndex(e){return this.sessionDesc.mediaDescriptions.findIndex((t=>{const i=t.media.mediaType===e&&"0"!==t.media.port&&("recvonly"===t.attributes.direction||"sendrecv"===t.attributes.direction);return"0"!==t.attributes.mid&&"1"!==t.attributes.mid&&i}))}predictReceivingMids(e){const t=[];for(let i=0;i<e;i++)t.push((this.currentMidIndex+i+1).toString(10));return t}restartICE(e){e=F(e),this._iceParameters=e,this.sessionDesc.mediaDescriptions.forEach((t=>{t.attributes.iceUfrag=e.iceUfrag,t.attributes.icePwd=e.icePwd}))}createOrRecycleSendMedia(e,t,i,n,s,o){const a=this.rtpCapabilities.send,r=e===lt.VIDEO?a.videoCodecs:a.audioCodecs,c=e===lt.VIDEO?a.videoExtensions:a.audioExtensions;x()&&(s="".concat(++this.currentMidIndex));let d={media:{mediaType:e,port:"9",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:[],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:s}};d=this.mungSendMediaDesc(d,o);const l=this.findFirstClosedMedia(e);if(l){const e=this.sessionDesc.mediaDescriptions.indexOf(l);this.sessionDesc.mediaDescriptions[e]=d}else this.sessionDesc.mediaDescriptions.push(d);return d}mungRecvMediaDsec(e,t,i){const n=F(e);return Vt(n),Ut(n,t),xt(n,t),Ft(n),Bt(n,i,this.localCapabilities.send),n}mungSendMediaDesc(e,t){const i=F(e);return Bt(i,t,this.localCapabilities.recv),qt(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}}updateBundleMids(){this.sessionDesc.attributes.groups[0].identificationTag=this.sessionDesc.mediaDescriptions.filter((e=>"0"!==e.media.port)).map((e=>e.attributes.mid))}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}))}findFirstClosedMedia(e){return this.sessionDesc.mediaDescriptions.find((t=>x()?"0"===t.media.port&&t.media.mediaType===e:"0"===t.media.port))}};const ti=["sdp"];var ii;let ni=(ii=class e extends ct{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[]}set isInRestartIce(e){this._isInRestartIce=e}get isInRestartIce(){return this._isInRestartIce}constructor(t,i,n){super(t,i),this.direction=void 0,this.name=void 0,this.store=void 0,this.spec=void 0,this.peerConnection=void 0,this.initialOffer=void 0,this.transport=void 0,this.statsFilter=void 0,this.localCandidateCount=0,this._isInRestartIce=!1,this.mutex=void 0,this.onLocalCandidate=void 0,this.remoteSDP=void 0,this.pendingCandidates=[],this.localCapabilities=void 0,this.isReady=!1,this.restartCnt=0,this.curTurnServerIndex=0,this.store=i,this.spec=t,this.mutex=new K("P2PConnection-mutex",i.clientId),this.peerConnection=new RTCPeerConnection(e.resolvePCConfiguration(t,i.p2pTransport),{optional:[{googDscp:!0}]}),this.direction=null!=n?n:tt.SEND_ONLY,this.name=this.direction===tt.SEND_ONLY?"sendP2PConnection":"recvP2PConnection",this.statsFilter=q(this.peerConnection,M("STATS_UPDATE_INTERVAL"),void 0,x()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1}async establish(e){try{const t=await Gt();if(this.localCapabilities=Kt(t),e){const t=e.sdp,i=function(e,t){if(null==e)return{};var i,n,s=function(e,t){if(null==e)return{};var i={};for(var n in e)if({}.hasOwnProperty.call(e,n)){if(-1!==t.indexOf(n))continue;i[n]=e[n]}return i}(e,t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(n=0;n<o.length;n++)i=o[n],-1===t.indexOf(i)&&{}.propertyIsEnumerable.call(e,i)&&(s[i]=e[i])}return s}(e,ti),n=function(){const e={audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]},t=wt(arguments.length>2?arguments[2]:void 0,arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},"sendonly"),i={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},n={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},s={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]};if(Yt(t,e,"videoExtensions",i,n,s),Yt(t,e,"videoCodecs",i,n,s),Yt(t,e,"audioExtensions",i,n,s),Yt(t,e,"audioCodecs",i,n,s),M("RAISE_H264_BASELINE_PRIORITY")){const e=s.videoCodecs.findIndex((e=>e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase()&&e.fmtp&&"42001f"===e.fmtp.parameters["profile-level-id"]));if(-1!==e){const t=s.videoCodecs.findIndex((e=>e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase()));if(t<e){N.debug("raising H264 baseline profile priority");const i=s.videoCodecs[e];s.videoCodecs.splice(e,1),s.videoCodecs.splice(t,0,i)}-1!==t&&M("FILTER_SEND_H264_BASELINE")&&(i.videoCodecs=i.videoCodecs.filter((e=>!(e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase()&&e.fmtp&&"42001f"!==e.fmtp.parameters["profile-level-id"]))))}}return{send:i,recv:n,sendrecv:s}}({},{},t);this.remoteSDP=new ei({remoteIceParameters:i.iceParameters,remoteDtlsParameters:i.dtlsParameters,candidates:[],remoteRTPCapabilities:n,localCapabilities:this.localCapabilities,direction:this.direction,setup:"actpass",videoCodec:this.store.codec,audioCodec:this.store.audioCodec}),await this.setRemoteDescription({type:"offer",sdp:this.remoteSDP.toString()}),this.isReady=!0;const s=await this.peerConnection.createAnswer();if(!s.sdp)throw new Error("Cannot get answer sdp when trying to establish PeerConnection.");const o=bt(s.sdp);await this.peerConnection.setLocalDescription(s);const a=await Ht({},{},s.sdp);this.localCapabilities=Kt(a);const r=this.peerConnection.getTransceivers()[0];return null!=r&&r.receiver&&r.receiver.transport&&this.tryBindTransportEvents(r.receiver.transport),We(We({},o),{},{sdp:s.sdp})}{this.peerConnection.addTransceiver("video",{direction:"sendonly"}),this.peerConnection.addTransceiver("audio",{direction:"sendonly"});const e=await this.peerConnection.createOffer();if(!e.sdp)throw new Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");const t=bt(e.sdp);return this.initialOffer=e,We(We({},t),{},{sdp:e.sdp})}}catch(e){throw new j(z.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString())}}async connect(e){try{if(!this.initialOffer)throw new Error("Cannot establish P2PConnection without initial offer.");await this.peerConnection.setLocalDescription(this.initialOffer);const t=e.sdp,i=e.iceParameters,n=e.dtlsParameters,s=await Ht({},{},t);this.remoteSDP=new ei({remoteIceParameters:i,remoteDtlsParameters:n,candidates:[],remoteRTPCapabilities:s,localCapabilities:this.localCapabilities,direction:this.direction,setup:"active",videoCodec:this.store.codec,audioCodec:this.store.audioCodec}),await this.setRemoteDescription({type:"answer",sdp:this.remoteSDP.toString()});const o=this.peerConnection.getTransceivers()[0];null!=o&&o.sender&&o.sender.transport&&this.tryBindTransportEvents(o.sender.transport)}catch(e){throw new j(z.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(e.toString()))}}async addRemoteCandidate(e){try{e&&this.pendingCandidates.push(e),this.peerConnection.remoteDescription&&this.isReady&&(this.pendingCandidates.forEach((e=>{this.peerConnection.addIceCandidate(e)})),this.pendingCandidates=[])}catch(e){throw new j(z.ADD_CANDIDATE_FAILED,"P2PConnection.addRemoteCandidate failed; ".concat(e.toString()))}}send(e,t,i){var n=this;return He((function*(){const s=yield xe(n.mutex.lock("From P2PConnection.send"));try{if(!n.remoteSDP)throw new Error("Cannot call P2PConnection.send before remote SDP created");const o=[],a=n.remoteSDP.receive(e,t,i);e.forEach(((e,t)=>{if(a[t].needCreateTransceiver){const t=n.peerConnection.addTransceiver(e._mediaStreamTrack,{direction:"sendonly"});o.push(t),e._updateRtpTransceiver(t)}else{const i=n.peerConnection.getTransceivers().find((e=>e.mid===a[t].mid));if(!i)throw new Error("cannot find transceiver when sendPeerconnection send, mid is ".concat(a[t].mid));o.push(i),e._updateRtpTransceiver(i)}})),x()&&!0===M("SIMULCAST")&&(yield xe(n.applySimulcastForFirefox(o,e)));const r=a.map((e=>e.mid)),c=yield xe(n.peerConnection.createOffer()),d=n.mungSendOfferSDP(c.sdp,e,r),l=V(d),u=r.map((e=>{const t=l.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error("Cannot extract ssrc from mediaDescription.");return kt(t,M("USE_PUB_RTX"))})),h=o.map(((e,t)=>{const i=r[t];return{localSSRC:u[t],id:i}}));yield xe(n.peerConnection.setLocalDescription({type:"offer",sdp:d}));try{yield h}catch(e){const t=n.remoteSDP.toString();throw yield xe(n.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield xe(n.peerConnection.setRemoteDescription({type:"answer",sdp:t})),yield xe(n.stopSending(r,!0)),e}yield xe(n.applySimulcastEncodings(o,e)),yield xe(n.applySendEncodings(o,e));const p=n.remoteSDP.toString(),_=n.logSDPExchange(d,"offer","local","send");return null==_||_(p),yield xe(n.setRemoteDescription({type:"answer",sdp:p})),o.map(((e,t)=>{const i=r[t];return{localSSRC:u[t],id:i}}))}catch(e){throw e instanceof j?e:new j(z.EXCHANGE_SDP_FAILED,"P2PConnection.send failed; ".concat(e.toString()))}finally{s()}}))()}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 (".concat(t.length,") doesn't match mids' length (").concat(e.length,") when trying to call P2PConnection.stopSending."));t.map((e=>{var t;e.direction="inactive",null===(t=e.stop)||void 0===t||t.call(e)}));const n=await this.peerConnection.createOffer(),s=this.logSDPExchange(n.sdp||"","offer","local","stopSending");await this.peerConnection.setLocalDescription(n),this.remoteSDP.stopReceiving(e);const o=this.remoteSDP.toString();null==s||s(o),await this.setRemoteDescription({type:"answer",sdp:o})}catch(e){throw new j(z.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 s=this.remoteSDP.send(e,t,i,n),o=s.mid;if(s.needExchangeSDP){const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","receive");await this.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer(),s=this.mungReceiveAnswerSDP(n.sdp,o,e);null==i||i(s||""),await this.peerConnection.setLocalDescription({type:"answer",sdp:s}),N.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," by exchanging SDP."))}else N.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," no need to exchange SDP."));const a=this.peerConnection.getTransceivers().find((e=>e.mid===o));if(!a||null===a.mid)throw new Error("Cannot get transceiver after setLocalDescription.");return{track:a.receiver.track,mid:a.mid,transceiver:a}}catch(e){throw new j(z.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()))}}async mockReceive(e,t,i,n){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.receive ".concat(e," before remoteSDP created."));const s=this.remoteSDP.send(e,t,i,n),o=s.mid;if(s.needExchangeSDP){const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","receive");await this.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer(),s=this.mungReceiveAnswerSDP(n.sdp,o,e);null==i||i(s||""),await this.peerConnection.setLocalDescription({type:"answer",sdp:s}),N.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," by exchanging SDP."))}else N.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," no need to exchange SDP."))}catch(e){throw new j(z.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.");this.remoteSDP.stopSending(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","stopReceiving");await this.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 j(z.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(e.toString()))}}async restartICE(t){try{if(this.store.p2pTransport===J.Auto&&(this.store.p2pTransport=J.SdRtn,n().supportPCSetConfiguration&&this.peerConnection.setConfiguration(e.resolvePCConfiguration(this.spec,this.store.p2pTransport))),this.restartCnt>3&&(this.restartCnt=0,n().supportPCSetConfiguration&&this.peerConnection.setConfiguration(e.resolvePCConfiguration(this.spec,this.store.p2pTransport,++this.curTurnServerIndex))),!t){this.restartCnt++,this.isReady=!1;const e=await this.peerConnection.createOffer({iceRestart:!0});if(!e.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const t=bt(e.sdp).iceParameters;return this.store.descriptionStart(),this.direction===tt.SEND_ONLY&&await this.peerConnection.setLocalDescription(e),t}if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopReceiving before remote SDP created.");if(this.remoteSDP.restartICE(t),this.store.descriptionStart(),this.direction===tt.RECEIVE_ONLY){this.restartCnt++,await this.setRemoteDescription({type:"offer",sdp:this.remoteSDP.toString()});const e=await this.peerConnection.createAnswer();if(!e.sdp)throw new Error("Cannot get answer sdp when trying to iceRestart.");const t=bt(e.sdp).iceParameters;return await this.peerConnection.setLocalDescription(e),t}await this.setRemoteDescription({type:"answer",sdp:this.remoteSDP.toString()}),this.isReady=!0}catch(e){throw new j(z.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(e.toString()))}}close(){var e;this.peerConnection.close(),this.peerConnection.onicecandidate=null,null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,"closed"),this.tryUnbindTransportEvents(),this.unbindPCEvents(),this.unbindStatsEvents(),this.transport=void 0,this.statsFilter.destroy()}getStats(){return this.statsFilter.getStats()}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 s=this.remoteSDP.toString(),o=this.logSDPExchange(n,"offer","local","updateEncoderConfig");await this.peerConnection.setLocalDescription({type:"offer",sdp:n}),null==o||o(s),await this.peerConnection.setRemoteDescription({type:"answer",sdp:s})}catch(e){throw new j(z.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)?x()||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:We(We({},X),{},{candidateType:i.type,protocol:i.protocol,address:i.address,port:i.port}),remote:We(We({},X),{},{candidateType:n.type,protocol:n.protocol,address:n.address,port:n.port})}}return this.statsFilter.getSelectedCandidatePair()}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var e;["connected","completed"].includes(this.peerConnection.iceConnectionState)&&(this.isReady=!1),null===(e=this.onICEConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.iceConnectionState)},this.peerConnection.onconnectionstatechange=()=>{var e;"connected"===this.peerConnection.connectionState&&(this.restartCnt=0),null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.connectionState)},this.startICECandidate()}startICECandidate(){this.peerConnection.onicecandidate||(this.localCandidateCount=0,this.peerConnection.onicecandidate=e=>{if(e.candidate){var t;if(e.candidate.candidate)null===(t=this.onLocalCandidate)||void 0===t||t.call(this,e.candidate.toJSON());this.localCandidateCount+=1}else N.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount)})}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,i){let s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;const o={iceServers:[]};return t.iceServers?o.iceServers=t.iceServers:t.turnServer&&"off"!==t.turnServer.mode&&(Q(t.turnServer.servers)?o.iceServers=t.turnServer.servers:(o.iceServers&&o.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers,i,s)),M("USE_TURN_SERVER_OF_GATEWAY")&&o.iceServers&&t.turnServer.serversFromGateway&&o.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway,i,s)),[J.Relay,J.SdRtn].includes(i)&&(o.iceTransportPolicy="relay"),M("FORCE_TURN_TCP")?o.iceTransportPolicy="relay":t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach((e=>{e.forceturn&&(o.iceTransportPolicy="relay")})))),M("ENABLE_ENCODED_TRANSFORM")&&n().supportWebRTCEncodedTransform&&(o.encodedInsertableStreams=!0),N.debug("P2PConnection p2pTransport is ".concat(i)),o}static turnServerConfigToIceServers(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;const n=[],s=e.filter((e=>e.tcpport));N.debug("P2PConnection turnServers is ".concat(s,", current index is ").concat(i));const o=s.length>i?s[i]:s[0];switch(t){case J.SdRtn:const t=e.filter((e=>e.username.includes("glb:")&&e.turnServerURL==e.turnServerURL)),s=t.length>i?t[i]:t[0];s&&(n.push({username:s.username,credential:s.password,credentialType:"password",urls:"turn:".concat(ft(s.turnServerURL),":").concat(s.tcpport,"?transport=udp")}),n.push({username:s.username,credential:s.password,credentialType:"password",urls:"turns:".concat(ft(s.turnServerURL),":").concat(s.tcpport,"?transport=tcp")}));break;case J.Relay:o&&(n.push({username:o.username,credential:o.password,credentialType:"password",urls:"turn:".concat(o.turnServerURL,":").concat(o.tcpport,"?transport=udp")}),n.push({username:o.username,credential:o.password,credentialType:"password",urls:"turns:".concat(ft(o.turnServerURL),":").concat(o.tcpport,"?transport=tcp")}));break;default:o&&(n.push({username:o.username,credential:o.password,credentialType:"password",urls:"turn:".concat(o.turnServerURL,":").concat(o.tcpport,"?transport=udp")}),n.push({username:o.username,credential:o.password,credentialType:"password",urls:"turns:".concat(ft(o.turnServerURL),":").concat(o.tcpport,"?transport=tcp")}),n.push({username:o.username,credential:o.password,credentialType:"password",urls:"stun:".concat(o.turnServerURL,":").concat(o.tcpport)}))}return n}tryBindTransportEvents(e){if(e){this.transport=e,e.onstatechange=()=>{var t;null!=e&&e.state&&(null===(t=this.onDTLSTransportStateChange)||void 0===t||t.call(this,e.state))},e.onerror=e=>{var t;null===(t=this.onDTLSTransportError)||void 0===t||t.call(this,"error"in e?e.error:e)};const t=e.iceTransport;t&&(t.onstatechange=()=>{const t=null==e?void 0:e.iceTransport.state;var i;t&&(null===(i=this.onICETransportStateChange)||void 0===i||i.call(this,t))},t.getSelectedCandidatePair&&(t.onselectedcandidatepairchange=()=>{if(t.getSelectedCandidatePair()){const e=t.getSelectedCandidatePair()||{},i=e.local,n=e.remote;if(i&&n){const e=i.address+":"+i.port,t=n.address+":"+n.port;N.info("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] selectedcandidatepairchange: local ").concat(JSON.stringify(At(e)),", remote ").concat(JSON.stringify(At(t))))}}}))}}tryUnbindTransportEvents(){this.transport&&(this.transport.onstatechange=null,this.transport.onerror=null,this.transport.iceTransport&&(this.transport.iceTransport.onstatechange=null))}async updateRtpSenderEncodings(e,t){var i;if(!t){t=this.peerConnection.getSenders().find((t=>t.track===e._mediaStreamTrack))}if(!t)return N.warn("[".concat(e.getTrackId(),"] no rtpSender found}"));if(this.isVP8Simulcast(e))return N.warn("[updateRtpSenderEncodings] Track is VP8 simulcast, please apply simulcast encodings");if(!n().supportSetRtpSenderParameters)return N.warn("[updateRtpSenderEncodings] Browser not support set rtp-sender parameters");const o={},a={};switch(e._optimizationMode){case"motion":o.degradationPreference="maintain-framerate";break;case"detail":o.degradationPreference="maintain-resolution";break;default:o.degradationPreference="balanced"}if(e._encoderConfig){const t=e._encoderConfig,i=t.bitrateMax,n=t.frameRate,o=t.scaleResolutionDownBy;i&&(a.maxBitrate=1e3*i),e._hints.includes(s.LOW_STREAM)&&(n&&(a.maxFramerate=vt(n)),o&&o>=1&&(a.scaleResolutionDownBy=o))}if(M("DSCP_TYPE")&&Z()){const e=M("DSCP_TYPE");["very-low","low","medium","high"].includes(e)&&(a.networkPriority=e)}const r=t.getParameters(),c=null===(i=r.encodings)||void 0===i?void 0:i[0];x()&&!c&&(o.encodings=[a]),c&&Object.assign(c,a),Object.assign(r,o),N.debug("[".concat(e.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(r.encodings))),await t.setParameters(r)}async applySendEncodings(e,t){try{if(!n().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let n=0;n<e.length;n++){const s=e[n],o=t[n];o instanceof i&&!this.isVP8Simulcast(o)&&await this.updateRtpSenderEncodings(o,s.sender)}}catch(e){N.debug("[".concat(this.store.clientId,"] Apply RTPSendEncodings failed."))}}mungSendOfferSDP(e,t,i){const n=V(e);return t.forEach(((e,t)=>{const s=i[t],o=n.mediaDescriptions.find((e=>e.attributes.mid===s));o&&(Ut(o,e),Wt(o,e,this.store.codec))})),B(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 n,o,a,r;const d=e[c],l=t[c];if(l instanceof i&&!l._hints.includes(s.LOW_STREAM)&&null!==(n=l._encoderConfig)&&void 0!==n&&n.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(!x()&&e.length===t.length)for(let n=0;n<e.length;n++){const s=t[n];if(s instanceof i&&this.isVP8Simulcast(s)){const t=e[n],i={},o={high:1e3*(s._encoderConfig.bitrateMax-50),medium:5e4};i.encodings=[{active:!0,adaptivePtime:!1,networkPriority:"high",priority:"high",maxBitrate:o.high},{active:!0,adaptivePtime:!1,networkPriority:"low",priority:"low",maxBitrate:o.medium,scaleResolutionDownBy:4}];const a=t.sender.getParameters();await t.sender.setParameters(Object.assign(a,i))}}}isVP8Simulcast(e){var t,n,o,a;return!!(e instanceof i&&M("SIMULCAST")&&"vp8"===this.store.codec&&!e._hints.includes(s.LOW_STREAM)&&null!==(t=e._encoderConfig)&&void 0!==t&&t.bitrateMax&&(null===(n=e._encoderConfig)||void 0===n?void 0:n.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(M("SDP_LOGGING"))return N.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 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 s=this.remoteSDP.toString();null==n||n(s),await this.setRemoteDescription({type:"answer",sdp:s})}catch(e){throw new j(z.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=>{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);const s=this.remoteSDP.toString();null==n||n(s),await this.setRemoteDescription({type:"answer",sdp:s})}catch(e){throw new j(z.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteLocal failed; ".concat(e.toString()))}}async getRemoteSSRC(e,t){var i;if(t=null!=t?t:null===(i=this.currentRemoteDescription)||void 0===i?void 0:i.sdp){var n;const i=null===(n=V(t).mediaDescriptions.find((t=>t.attributes.mid===e)))||void 0===n?void 0:n.attributes.ssrcs;return null==i?void 0:i[0].ssrcId}}async setRemoteDescription(e){await this.peerConnection.setRemoteDescription(e),["connected","completed"].includes(this.peerConnection.iceConnectionState)||(this.isReady=!0,this.addRemoteCandidate())}mungReceiveAnswerSDP(e,t,i){const n=V(e),s=n.mediaDescriptions.find((e=>e.attributes.mid===t));return s&&i===lt.AUDIO&&"audio"===s.media.mediaType&&qt(s),B(n)}},Ue(ii.prototype,"establish",[si],Object.getOwnPropertyDescriptor(ii.prototype,"establish"),ii.prototype),Ue(ii.prototype,"connect",[si],Object.getOwnPropertyDescriptor(ii.prototype,"connect"),ii.prototype),Ue(ii.prototype,"receive",[si],Object.getOwnPropertyDescriptor(ii.prototype,"receive"),ii.prototype),Ue(ii.prototype,"mockReceive",[si],Object.getOwnPropertyDescriptor(ii.prototype,"mockReceive"),ii.prototype),Ue(ii.prototype,"stopReceiving",[si],Object.getOwnPropertyDescriptor(ii.prototype,"stopReceiving"),ii.prototype),Ue(ii.prototype,"restartICE",[si],Object.getOwnPropertyDescriptor(ii.prototype,"restartICE"),ii.prototype),Ue(ii.prototype,"close",[si],Object.getOwnPropertyDescriptor(ii.prototype,"close"),ii.prototype),Ue(ii.prototype,"updateEncoderConfig",[si],Object.getOwnPropertyDescriptor(ii.prototype,"updateEncoderConfig"),ii.prototype),Ue(ii.prototype,"updateSendParameters",[si],Object.getOwnPropertyDescriptor(ii.prototype,"updateSendParameters"),ii.prototype),Ue(ii.prototype,"replaceTrack",[si],Object.getOwnPropertyDescriptor(ii.prototype,"replaceTrack"),ii.prototype),Ue(ii.prototype,"muteLocal",[si],Object.getOwnPropertyDescriptor(ii.prototype,"muteLocal"),ii.prototype),Ue(ii.prototype,"unmuteLocal",[si],Object.getOwnPropertyDescriptor(ii.prototype,"unmuteLocal"),ii.prototype),ii);function si(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 s=arguments.length,o=new Array(s),a=0;a<s;a++)o[a]=arguments[a];return await n.apply(this,o)}finally{i()}},i}const oi=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}};var ai=function(e){return e[e.Video_Send_Type=190]="Video_Send_Type",e}(ai||{}),ri=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}(ri||{}),ci=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}(ci||{}),di=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}(di||{}),li=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}(li||{}),ui=function(e){return e[e.RTC_PEER_CONNECTION_STATE=2219]="RTC_PEER_CONNECTION_STATE",e[e.PAGE_VISIBILITY=2233]="PAGE_VISIBILITY",e}(ui||{}),hi=function(e){return e[e.Transport_Send_Bitrate=2234]="Transport_Send_Bitrate",e[e.Transport_Recv_Bitrate=2235]="Transport_Recv_Bitrate",e}(hi||{});class pi extends k{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(M("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 s="VIDEO_ENCODE_FAILED"===e?M("ENCODE_EXCEPTION_TIMES"):5;if(n.result.length>=s){const i=n.result.includes(!0);n.isPrevNormal&&!i&&this.emit("exception",_i[e],e,t),!n.isPrevNormal&&i&&this.emit("exception",_i[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=vt(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||M("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 _i={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};class Ei{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=U.L1T1,this.updateStats=()=>{this.p2pChannel&&(this.updateRemoteStats(this.p2pChannel),this.updateLocalStats(this.p2pChannel))},this.store=e,this.exceptionMonitor=new pi,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(ht.LocalAudioTrack)||We({},r)}getLocalVideoTrackStats(){return this.localStats.get(ht.LocalVideoTrack)||We({},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 s=null===(n=this.remoteStats.get(e))||void 0===n?void 0:n.audioStats;s&&(i[e]=t(e,s))}else Array.from(this.remoteStats.entries()).forEach((e=>{let n=Ge(e,2),s=n[0],o=n[1].audioStats;o&&(i[s]=t(s,o))}));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=Ge(e,2),n=i[0],s=i[1].networkStats;s&&(t[n]=s)}));return t}getNetworkQuality(){let e=0,t=0;return this.trafficStats&&(e=Tt(this.trafficStats.B_unq),t=Tt(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 s=null===(n=this.remoteStats.get(e))||void 0===n?void 0:n.videoStats;s&&(i[e]=t(e,s))}else Array.from(this.remoteStats.entries()).forEach((e=>{let n=Ge(e,2),s=n[0],o=n[1].videoStats;o&&(i[s]=t(s,o))}));return i}getRTCStats(){let e=0,t=0,i=0,n=0;const s=this.localStats.get(ht.LocalAudioTrack);s&&(e+=s.sendBytes,t+=s.sendBitrate);const o=this.localStats.get(ht.LocalVideoTrack);o&&(e+=o.sendBytes,t+=o.sendBitrate);const a=this.localStats.get(ht.LocalVideoLowTrack);a&&(e+=a.sendBytes,t+=a.sendBitrate),this.remoteStats.forEach((e=>{let t=e.audioStats,s=e.videoStats;t&&(i+=t.receiveBytes,n+=t.receiveBitrate),s&&(i+=s.receiveBytes,n+=s.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?oi.measureFromSubscribeStart(this.store.clientId,i.videoSSRC):0,s=null!=i&&i.audioSSRC?oi.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>s?n:s),this.trafficStatsPeerList.push(e.peer_uid))})),this.trafficStats=e}updateUplinkStats(e){this.uplinkStats&&this.uplinkStats.B_fir!==e.B_fir&&N.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,s=!i||t.framesDecodeCount>i.framesDecodeCount;return n||!s}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=Ge(t,2),n=i[0],s=i[1];switch(n){case ht.LocalVideoTrack:case ht.LocalVideoLowTrack:{const t=s,i=We({},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 s=e.getLocalVideoSize(),a=e.getEncoderConfig(ht.LocalVideoTrack);var o;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===(o=this.onVideoCodecChanged)||void 0===o||o.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):s&&(i.captureResolutionWidth=s.width,i.captureResolutionHeight=s.height),n.sentFrame?(i.sendFrameRate=n.sentFrame.frameRate,i.sendResolutionHeight=n.sentFrame.height,i.sendResolutionWidth=n.sentFrame.width):s&&(i.sendResolutionWidth=s.width,i.sendResolutionHeight=s.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&&(N.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 ht.LocalAudioTrack:{const t=s,i=We({},r),o=e.getStats(),a=e.getLocalMedia(n);if(o){const n=o.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(ht.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 s=Ge(t,2),o=s[0],a=s[1],r=a.videoStats;const c=a.audioStats,h=r,p=a.videoPcStats,_=We({},d),E=We({},l),m=We({},u),S=e.getRemoteMedia(o),R=S.audioTrack,C=S.videoTrack,f=S.audioSSRC,v=S.videoSSRC;let T;T=this.store.useP2P?e.getStats(!0):e.getStats();const g=null===(i=T)||void 0===i?void 0:i.audioRecv.find((e=>e.ssrc===f)),I=null===(n=T)||void 0===n?void 0:n.videoRecv.find((e=>e.ssrc===v)),A=this.trafficStats&&this.trafficStats.peer_delay.find((e=>e.peer_uid===o));if(g&&("opus"!==g.codec&&"aac"!==g.codec&&"PCMU"!==g.codec&&"PCMA"!==g.codec&&"G722"!==g.codec||(_.codecType=g.codec),g.outputLevel?_.receiveLevel=Math.round(32767*g.outputLevel):R&&(_.receiveLevel=Math.round(32767*R.getVolumeLevel())),_.receiveBytes=g.bytes,_.receivePackets=g.packets,_.receivePacketsLost=g.packetsLost,_.receivePacketsDiscarded=g.packetsDiscarded,_.packetLossRate=_.receivePacketsLost/(_.receivePackets+_.receivePacketsLost),_.receiveBitrate=c?8*Math.max(0,_.receiveBytes-c.receiveBytes):0,_.totalDuration=c?c.totalDuration+1:1,_.totalFreezeTime=c?c.totalFreezeTime:0,_.freezeRate=_.totalFreezeTime/_.totalDuration,_.receiveDelay=g.jitterBufferMs,_.totalDuration>10&&Ei.isRemoteAudioFreeze(R)&&(_.totalFreezeTime+=1)),I){"H264"!==I.codec&&"H265"!==I.codec&&"VP8"!==I.codec&&"VP9"!==I.codec&&"AV1X"!==I.codec&&"AV1"!==I.codec||(E.codecType=I.codec),E.receiveBytes=I.bytes,E.receiveBitrate=h?8*Math.max(0,E.receiveBytes-h.receiveBytes):0,E.decodeFrameRate=I.decodeFrameRate<0?0:I.decodeFrameRate,E.renderFrameRate=I.decodeFrameRate<0?0:I.decodeFrameRate,I.outputFrame&&(E.renderFrameRate=I.outputFrame.frameRate),I.receivedFrame?(E.receiveFrameRate=I.receivedFrame.frameRate,E.receiveResolutionHeight=I.receivedFrame.height,E.receiveResolutionWidth=I.receivedFrame.width):C&&(E.receiveResolutionHeight=C._videoHeight||0,E.receiveResolutionWidth=C._videoWidth||0),void 0!==I.framesRateFirefox&&(E.receiveFrameRate=Math.round(I.framesRateFirefox)),E.receivePackets=I.packets,E.receivePacketsLost=I.packetsLost,E.packetLossRate=E.receivePacketsLost/(E.receivePackets+E.receivePacketsLost),E.receiveDelay=I.jitterBufferMs||0;const t=!!v&&e.getRemoteVideoIsReady(v),i=h?h.totalFreezeTime:0,n=h?h.totalDuration:0;var D;if(E.totalDuration=h?h.totalDuration+1:1,1===M("REMOTE_VIDEO_FREEZE_TIME_VERSION"))C&&t&&C._player&&(E.totalFreezeTime=C._player.totalFreezeTime/1e3);else E.totalFreezeTime=null!==(D=I.totalFreezesDuration)&&void 0!==D?D:i||0,void 0===I.totalFreezesDuration&&C&&t&&Ei.isRemoteVideoFreeze(C,I,p)&&(E.totalFreezeTime+=1);E.freezeRate=Math.max(0,Math.min((E.totalFreezeTime-i)/(E.totalDuration-n),1))}A&&(_.end2EndDelay=A.B_ad,E.end2EndDelay=A.B_vd,_.transportDelay=A.B_ed,E.transportDelay=A.B_ed,_.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(o,{audioStats:_,videoStats:E,videoPcStats:I,networkStats:m}),R&&this.exceptionMonitor.setRemoteAudioStats(R,_),C&&this.exceptionMonitor.setRemoteVideoStats(C,E)}))}}const mi=1e3,Si=6,Ri=3,Ci=Math.max(Si,Ri,60);function fi(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 vi(e,t,i){null!=i&&Number.isFinite(i)&&(e[t]=Math.round(Math.max(0,i)))}function Ti(e){const t={[li.CONN_TYPE]:0,[li.RTT]:e.rtt,[li.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[li.CONN_TYPE]=1),"tcp"===i&&(t[li.CONN_TYPE]=3),"tls"===i&&(t[li.CONN_TYPE]=4);break}case"srflx":t[li.CONN_TYPE]=2;break;case"unknown":t[li.CONN_TYPE]=5;break;default:t[li.CONN_TYPE]=0}return t}function gi(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 Ii extends k{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%Ri==0,i=e%Si==0,n=e%60==0;let s,o;if(this.uploadTransportStarted&&(s=this.requestStats(),this.store.useP2P&&(o=this.requestStats(!0))),!s&&this.uploadOutboundStarted&&(s=this.requestStats()),!o&&this.uploadInboundStarted&&(o=this.requestStats(!0)),s||o){var a;const r={};if(this.uploadTransportStarted&&s){const e=this.getTransportStats(s,t?this.lastRefSendStats:void 0,o,t);e&&(r.misc=[e])}if(this.uploadOutboundStarted&&s){const e=this.getOutboundStats(s,i?this.lastNormalSendStats:void 0,t?this.lastRefSendStats:void 0,this.lastSendStats,n);e&&(r.outbound=[e])}if(this.uploadInboundStarted&&o){this.uploadCompensateStats(e);const n=this.getInboundStats(o,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[ui.RTC_PEER_CONNECTION_STATE]=ee[c]):r.misc=[{addition:{[ui.RTC_PEER_CONNECTION_STATE]:ee[c]}}]),p.needUploadStats.length>0||i){const e=p.needUploadStats.shift()||("visible"===p.visibility?1:0);Array.isArray(r.misc)?r.misc[0]&&r.misc[0].addition&&(r.misc[0].addition[ui.PAGE_VISIBILITY]=e):r.misc=[{addition:{[ui.PAGE_VISIBILITY]:e}}]}this.needUploadStats.sendType&&(Array.isArray(r.outbound)&&r.outbound[0]&&r.outbound[0].high&&(r.outbound[0].high[ai.Video_Send_Type]=this.needUploadStats.sendType),this.needUploadStats.sendType=void 0),this.requestUploadStats(r)}this.lastRecvStats=o,this.lastSendStats=s,i&&(this.lastNormalRecvStats=o,this.lastNormalSendStats=s),t&&(this.lastRefRecvStats=o,this.lastRefSendStats=s)}startUploadWRTCStats(){if(this.uploadWRTCStatsTimer)return;this.uploadBaseStatsStarted=!0,p.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:{[ui.RTC_PEER_CONNECTION_STATE]:ee[e.connectState]}}]})))}return this.stopUploadWRTCStats()}this.uploadWRTCStats(e),++e===Ci+1&&(e=1)}),mi)}uploadCompensateStats(e){if(!this.requestStats||!this.requestUploadStats||!this.requestRemoteMedia)return;const t=e%Ri==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 s=Math.min(Math.floor(this.uploadCompensateDeltaTime/6e3),10);this.uploadCompensateDeltaTime-=6e3*s;const o=this.requestStats(!0);new Array(s).fill(0).forEach((()=>{if(!this.requestStats||!this.requestUploadStats||!this.requestRemoteMedia)return;const e={};if(this.uploadInboundStarted&&o){const t=this.requestRemoteMedia()||[],i=[];t.forEach((e=>{let t=Ge(e,2),s=t[0],a=t[1];const r={peer:s.uid};if((s._videoSSRC&&this.requestVideoIsReady&&this.requestVideoIsReady(s._videoSSRC)||!1)&&a.has(lt.VIDEO)&&s.videoTrack){const e=function(e,t,i){if(!t.videoRecv.find((t=>t.ssrc===e)))return;const s={};if(i&&i._player){const e=i._player,t=e.renderFreezeAccTime2,o=e.videoElementStatus;if("visible"===p.visibility&&o===_.PLAYING&&n().supportRequestVideoFrameCallback){const i=Math.min(6e3,t);e.renderFreezeAccTime2=Math.max(0,t-i),vi(s,ri.Video_Render_Freeze_Time_Render2,i),M("USE_NEW_RENDER_FREEZE_TIME")&&vi(s,ri.Video_Render_Freeze_Time_Render,i)}}return s}(s._videoSSRC,o,s.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:{[li.RTT]:e.rtt,[li.CONN_TYPE]:void 0,[li.STATS_UPDATE_INTERVAL]:e.updateInterval||void 0}};const s=Ti(e);if(this.store.useP2P){if(i){const e=Ti(i);s[li.CONN_TYPE]&&e[li.CONN_TYPE]&&(s[li.CONN_TYPE]+=e[li.CONN_TYPE]<<3)}s[li.CONN_TYPE]?s[li.CONN_TYPE]+=110:s[li.CONN_TYPE]=110}else{s[li.CONN_TYPE]?s[li.CONN_TYPE]+=100:s[li.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);s[hi.Transport_Send_Bitrate]=i[0],s[hi.Transport_Recv_Bitrate]=i[1]}return{addition:s}}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=Ge(n,2),l=a[0],u=a[1],p=u.track,_=u.ssrcs;switch(l){case ht.LocalVideoLowTrack:case ht.LocalVideoTrack:if(l===ht.LocalVideoTrack){const n=function(e,t,i,n,s,o){const a=t.videoSend.find((t=>t.ssrc===e));if(!a)return;const r={},c=a.sentFrame,d=a.inputFrame;if(n&&(vi(r,ri.Video_Send_Qp_Sum,a.qpSumPerFrame),a.codec&&vi(r,ri.Video_Send_Codec,fi(a.codec)),"number"==typeof a.powerEfficientEncoder&&vi(r,ri.Video_Send_Power_Efficient_Encoder,a.powerEfficientEncoder),d&&c)){const e=d.frameRate,t=c.frameRate;r[ri.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(s){switch(c&&(vi(r,ci.Video_Send_Height,c.height),vi(r,ci.Video_Send_Width,c.width),vi(r,ci.Video_Send_Frame_Rate,c.frameRate)),r[ci.Video_Send_Disabled]=i._originMediaStreamTrack&&!i._originMediaStreamTrack.enabled||i._mediaStreamTrack&&!i._mediaStreamTrack.enabled?1:0,a.adaptionChangeReason){case"none":r[ci.Video_Send_Adaptation]=0;break;case"cpu":r[ci.Video_Send_Adaptation]=1;break;case"bandwidth":r[ci.Video_Send_Adaptation]=2;break;case"other":r[ci.Video_Send_Adaptation]=3}let n=0;a.adaptionChangeReason&&(n+=gi(a.adaptionChangeReason)),t.qualityLimitationReason&&(n+=gi(t.qualityLimitationReason)<<3),r[ci.Video_Send_Adaptation]=n,r[ci.Video_Send_Player_Status]=h[i._player?i._player.videoElementStatus:"uninit"],vi(r,ci.Video_Send_Nacks,a.nacksCount),vi(r,ci.Video_Send_Plis,a.plisCount),vi(r,ci.Video_Send_Firs,a.firsCount),vi(r,ci.Video_Send_Avg_Encode,a.avgEncodeMs),vi(r,ci.Video_Send_Huge_Frame_Sent,a.hugeFramesSent),vi(r,ci.Video_Send_Bytes_Retransmit,a.retransmittedBytesSent),vi(r,ci.Video_Send_Packages_Retransmit,a.retransmittedPacketsSent),vi(r,ci.Video_Send_Key_Frames_Encoded,a.keyFramesEncoded);const o=s.videoSend.find((t=>t.ssrc===e));if(o){let e=mi*Ri;o.timestamp&&a.timestamp&&(e=a.timestamp-o.timestamp),null!=o.packets&&null!=a.packets&&vi(r,ci.Video_Send_Package_Rate,1e3*(a.packets-o.packets)/e),null!=a.packetsLost&&null!=o.packetsLost&&vi(r,ci.Video_Send_Package_Lost,a.packetsLost-o.packetsLost),null!=o.bytes&&null!=a.bytes&&vi(r,ci.Video_Send_Bitrate,8*(a.bytes-o.bytes)/e)}}return r}(_[0].ssrcId,e,p,t,i),a="CameraVideoTrack"===p.__className__?3:p._hints.includes(s.SCREEN_TRACK)?7:10;(this.lastExtendStats.sendType!==a||o)&&(this.needUploadStats={sendType:a},this.lastExtendStats.sendType=a);const r=p&&function(e,t,i,n){const s=t.videoSend.find((t=>t.ssrc===e));if(!s)return null;const o={};if(n){const e=s.inputFrame,t=e&&e.height||i.videoHeight||0,n=e&&e.width||i.videoWidth||0,a=e&&e.frameRate||0;vi(o,ci.Video_Capture_Height,t),vi(o,ci.Video_Capture_Width,n),vi(o,ci.Video_Capture_Frame_Rate,a)}return o}(_[0].ssrcId,e,p,!!i),d=function(e,t){const i={};return t&&(vi(i,ci.Video_Send_Retransmit,e.bitrate.retransmit),vi(i,ci.Video_Send_Target_Encoded,e.bitrate.targetEncoded),vi(i,ci.Video_Send_Actual_Encoded,e.bitrate.actualEncoded),vi(i,ci.Video_Send_Transmit,e.bitrate.transmit),vi(i,ci.Video_Send_Bandwidth,e.sendBandwidth)),i}(e,!!i);c=Object.assign({},n,r,d)}else d=function(e,t,i,n,s){const o=t.videoSend.find((t=>t.ssrc===e));if(!o)return;const a={};if(n){const t=o.sentFrame;t&&(vi(a,ci.Video_Send_Low_Height,t.height),vi(a,ci.Video_Send_Low_Width,t.width),vi(a,ci.Video_Send_Low_Frame_Rate,t.frameRate));const i=n.videoSend.find((t=>t.ssrc===e));if(i){let e=mi*Si;i.timestamp&&o.timestamp&&(e=o.timestamp-i.timestamp),null!=i.packets&&null!=o.packets&&vi(a,ci.Video_Send_Low_Package_Rate,1e3*(o.packets-i.packets)/e),null!=o.packetsLost&&null!=i.packetsLost&&vi(a,ci.Video_Send_Low_Package_Lost,o.packetsLost-i.packetsLost),null!=i.bytes&&null!=o.bytes&&vi(a,ci.Video_Send_Low_Bitrate,8*(o.bytes-i.bytes)/e)}}return a}(_[0].ssrcId,e,0,i);break;case ht.LocalAudioTrack:r=p&&function(e,t,i,n,s,o){const a=t.audioSend.find((t=>t.ssrc===e));if(!a)return;const r={};if(s){r[ci.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));vi(r,ci.Audio_Send_Level,e)}vi(r,ci.Audio_Capture_PCM_Level,t),vi(r,ci.Audio_Send_AEC_Return_Loss,a.aecReturnLoss),vi(r,ci.Audio_Send_AEC_Return_Loss_Enhancement,a.aecReturnLossEnhancement),vi(r,ci.Audio_Send_Bytes_Retransmit,a.retransmittedBytesSent),vi(r,ci.Audio_Send_Packages_Retransmit,a.retransmittedPacketsSent),r[ci.Audio_Send_Freeze]=0;const o=s.audioSend.find((t=>t.ssrc===e));if(o){let e=mi*Si;o.timestamp&&a.timestamp&&(e=a.timestamp-o.timestamp),null!=o.bytes&&null!=a.bytes&&vi(r,ci.Audio_Send_Bitrate,8*(a.bytes-o.bytes)/e),null!=o.packets&&null!=a.packets&&vi(r,ci.Audio_Send_Package_Rate,1e3*(a.packets-o.packets)/e)}}return r}(_[0].ssrcId,e,p,0,i)}})),{high:c,low:d,audio:r}}getInboundStats(e,t,i,s){if(!this.requestRemoteMedia)return;const o=this.requestRemoteMedia()||[],a=[];return o.forEach((o=>{let r=Ge(o,2),c=r[0],d=r[1];const l={peer:c.uid};let u;if(d.has(lt.VIDEO)&&c.videoTrack){const o=c._videoSSRC&&this.requestVideoIsReady&&this.requestVideoIsReady(c._videoSSRC)||!1,a=c.videoTrack?function(e,t,i,s,o,a,r,c){const d=t.videoRecv.find((t=>t.ssrc===e));if(!d)return;const l={},u=d.receivedFrame,E=d.outputFrame,m=d.decodeFrameRate;vi(l,di.Video_Render_Frame_Rate_Decode,m),d.framesRateFirefox&&vi(l,di.Video_Recv_Frame_Rate,d.framesRateFirefox),u&&vi(l,di.Video_Recv_Frame_Rate,u.frameRate),vi(l,di.Video_Recv_Frame_Dropped,d.framesDroppedCount),vi(l,di.Video_Recv_Bytes_Retransmit,d.retransmittedBytesReceived),vi(l,di.Video_Recv_Packages_Retransmit,d.retransmittedPacketsReceived),vi(l,di.Video_Recv_Packages_Discarded,d.packetsDiscarded),vi(l,di.Video_Recv_Avg_Decode,d.avgDecodeMs),vi(l,di.Video_Recv_Avg_Processing_Delay,d.avgProcessingDelayMs),vi(l,di.Video_Recv_Avg_Assembly_Time,d.avgFramesAssembledFromMultiplePacketsMs),vi(l,di.Video_Recv_Avg_Inter_Frame_Delay,d.avgInterFrameDelayMs),vi(l,di.Video_Recv_Key_Frames_Decoded,d.keyFramesDecoded);const S=c&&c.videoRecv.find((t=>t.ssrc===e));if(S){const e=t.timestamp-c.timestamp||mi;null!=d.packetsLost&&null!=S.packetsLost&&vi(l,di.Video_Recv_Package_Lost,d.packetsLost-S.packetsLost),null!=S.bytes&&null!=d.bytes&&vi(l,di.Video_Recv_Bitrate,8*(d.bytes-S.bytes)/e),null!=S.packets&&null!=d.packets&&vi(l,di.Video_Recv_Package_Rate,1e3*(d.packets-S.packets)/e)}const R=a&&a.videoRecv.find((t=>t.ssrc===e));if(R&&(vi(l,ri.Video_Recv_Qp_Sum,d.qpSumPerFrame),d.codec&&vi(l,ri.Video_Recv_Codec,fi(d.codec)),"number"==typeof d.powerEfficientDecoder&&vi(l,ri.Video_Recv_Power_Efficient_Decoder,d.powerEfficientDecoder),l[ri.Video_Recv_Freeze]=s&&Ei.isRemoteVideoFreeze(i,d,R)?1:0),r){var C;const t=r.videoRecv.find((t=>t.ssrc===e));u?(vi(l,ci.Video_Recv_Height,u.height),vi(l,ci.Video_Recv_Width,u.width)):i&&(vi(l,ci.Video_Recv_Height,i._videoHeight||0),vi(l,ci.Video_Recv_Width,i._videoWidth||0)),E&&vi(l,ci.Video_Recv_Frame_Rate_Output,E.frameRate);const s=null===(C=i._player)||void 0===C?void 0:C.rendFrameRate.toFixed(0);if(s&&vi(l,ci.Video_Render_Frame_Rate_Render,+s),vi(l,ci.Video_Recv_Jitter_Buffer,d.jitterBufferMs),vi(l,ci.Video_Recv_Current_Delay,d.currentDelayMs),vi(l,ci.Video_Recv_Firs,d.firsCount),vi(l,ci.Video_Recv_Nacks,d.nacksCount),vi(l,ci.Video_Recv_Plis,d.plisCount),i){l[ci.Video_Recv_Disabled]=i._originMediaStreamTrack.enabled&&i._mediaStreamTrack.enabled?0:1;const e=i._player;if(e){const i=e.freezeTimeCounterList,s=e.renderFreezeAccTime,a=e.renderFreezeAccTime2,r=e.videoElementStatus;if(i&&i.length>0&&vi(l,ri.Video_Render_Freeze_Time,i.splice(0,1)[0]),o&&"visible"===p.visibility&&r===_.PLAYING&&n().supportRequestVideoFrameCallback){const t=Math.min(6e3,a);e.renderFreezeAccTime2=Math.max(0,a-t),vi(l,ri.Video_Render_Freeze_Time_Render2,t);const i=Math.min(6e3,s);e.renderFreezeAccTime=Math.max(0,s-i),vi(l,ri.Video_Render_Freeze_Time_Render,M("USE_NEW_RENDER_FREEZE_TIME")?t:i)}if("number"==typeof d.totalFreezesDuration){const e=t&&t.totalFreezesDuration?d.totalFreezesDuration-t.totalFreezesDuration:d.totalFreezesDuration;vi(l,ci.Video_Render_Freeze_Duration,1e3*e)}}}if(l[ci.Video_Recv_Player_Status]=h[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,s=e/n*1e3,o=Math.round(1e3*Math.sqrt((i-Math.pow(e,2)/n)/n));!isNaN(o)&&s+o>Math.max(3*s,s+150)&&(l[ci.Video_Recv_I_Frame_Delay]=o)}}return l}(c._videoSSRC,e,c.videoTrack,!0===o,this.needUploadRenderFreezeTime,t,i,s):void 0;if(a&&(l.video=a),c.videoTrack){const t=e.videoRecv.find((e=>e.ssrc===c._videoSSRC));t&&t.estimatedPlayoutTimestamp&&(u=t.estimatedPlayoutTimestamp)}}if(d.has(lt.AUDIO)&&c.audioTrack){const n=!c.hasAudio,o=c.audioTrack?function(e,t,i,n,s,o){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={};vi(c,di.Audio_Recv_Jitter,r.jitterMs),vi(c,di.Audio_Recv_Bytes_Retransmit,r.retransmittedBytesReceived),vi(c,di.Audio_Recv_Packages_Retransmit,r.retransmittedPacketsReceived),vi(c,di.Audio_Recv_Packages_Discarded,r.packetsDiscarded),vi(c,di.Audio_Recv_Avg_Processing_Delay,r.avgProcessingDelayMs);const d=o&&o.audioRecv.find((t=>t.ssrc===e));if(d){const e=mi;null!=r.packets&&null!=d.packets&&vi(c,di.Audio_Recv_Package_Rate,1e3*(r.packets-d.packets)/e),null!=r.packetsLost&&null!=d.packetsLost&&vi(c,di.Audio_Recv_Package_Lost,r.packetsLost-d.packetsLost)}if(n){const e=r.receivedFrames,t=r.droppedFrames;null!=e&&null!=t&&(c[ri.Audio_Recv_Freeze]=0===(l=e)||100*t/l>20?1:0)}var l;if(s){const t=100*i._source.getAccurateVolumeLevel(),n=r.outputLevel;if(null!=n){const e=Math.ceil(50*Math.log10(100*n+1));vi(c,ci.Audio_Render_Level,e)}vi(c,ci.Audio_Recv_PCM_Level,t),i&&(c[ci.Audio_Recv_Disabled]=i._originMediaStreamTrack.enabled&&i._mediaStreamTrack.enabled?0:1),vi(c,ci.Audio_Recv_Jitter_Buffer,r.jitterBufferMs),vi(c,ci.Audio_Recv_Current_Delay,r.jitterBufferMs),c[ci.Audio_Recv_Player_Status]=h[E.getPlayerState(i.getTrackId())];const o=s.audioRecv.find((t=>t.ssrc===e));if(o&&(null!=o.bytes&&null!=r.bytes&&vi(c,ci.Audio_Recv_Bitrate,8*(r.bytes-o.bytes)/(mi*Ri)),!a)){const e=r.concealedSamples-o.concealedSamples;e>0&&vi(c,ci.Audio_Recv_Concealed_Samples,e);const t=r.totalSamplesReceived-o.totalSamplesReceived;t>0&&vi(c,ci.Audio_Recv_Total_Samples_Received,t);const i=r.freezeSamples80-o.freezeSamples80;i>0&&vi(c,ci.Audio_Render_Freeze_Samples_80ms,i);const n=r.freezeSamples200-o.freezeSamples200;n>0&&vi(c,ci.Audio_Render_Freeze_Samples_200ms,n);const s=r.freezeMs80-o.freezeMs80;vi(c,ci.Audio_Render_Freeze_Time_80ms,s<0?0:s);const a=r.freezeMs200-o.freezeMs200;vi(c,ci.Audio_Render_Freeze_Time_200ms,a<0?0:a)}}return c}(c._audioSSRC,e,c.audioTrack,t,i,s,n):void 0;if(o&&(l.audio=o),c.audioTrack&&u){const t=e.audioRecv.find((e=>e.ssrc===c._audioSSRC));if(t&&t.estimatedPlayoutTimestamp){const e=t.estimatedPlayoutTimestamp-u;l.audio?l.audio[di.Audio_Recv_AV_Sync_TIME]=e:l.audio={[di.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 t));if(e&&e._external.getDenoiserStats){const t=e._external.getDenoiserStats();t&&this.requestUpload($e.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=Ge(e,2),i=t[0],n=t[1];if(n.has(lt.VIDEO)&&i.videoTrack){i.videoTrack.getProcessorStats().forEach((e=>{this.requestUpload&&this.requestUpload(e.type,e.stats)}))}if(n.has(lt.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:M("EXTENSION_USAGE_UPLOAD_INTERVAL")/1e3,details:[],lts:t};let n=[];const s=this.requestAllTracks&&this.requestAllTracks()||[];for(const e of s)!e.muted&&e.enabled&&(n=n.concat(await e.getProcessorUsage()));const o=this.requestRemoteMedia&&this.requestRemoteMedia()||[];for(const e of o){var a=Ge(e,2);const t=a[0],i=a[1];i.has(lt.VIDEO)&&t.videoTrack&&(n=n.concat(await t.videoTrack.getProcessorUsage())),i.has(lt.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,u=2===r?l+M("EXTENSION_USAGE_UPLOAD_INTERVAL")/1e3:l;var s,o;t.set(e,u),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!==(s=t.get(e))&&void 0!==s?s:0):i[e]={value:r,level:c,remoteUidCount:"local"===d?0:1,totalTs:null!==(o=t.get(e))&&void 0!==o?o: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($e.EXTENSION_USAGE_STATS,{usageStats:i,sendTs:c})}),M("EXTENSION_USAGE_UPLOAD_INTERVAL"))}stopUploadExtensionUsageStats(){this.uploadExtensionUsageStarted&&(this.uploadExtensionUsageStarted=!1,this.uploadExtUsageStatsTimer&&window.clearInterval(this.uploadExtUsageStatsTimer),this.uploadExtUsageStatsTimer=void 0)}stopUploadBaseStats(){this.uploadBaseStatsStarted=!1,p.stopCollectStats()}}class Ai{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}}let Di=function(e){return e.SEND_ONLY="SEND_ONLY",e.RECEIVE_ONLY="RECEIVE_ONLY",e}({});var Pi,Ni;const Li={};function yi(e){return function(e){const t=Li[e];if(!t)throw new j(z.INVALID_OPERATION,"".concat(e," not found, please use AgoraRTC.use(").concat(e,"Service) to load it first"));return t}("AiAudioModeExtension").create(e)}null!==(Ni=(Pi=globalThis).__aiClientControllerCallbacks)&&void 0!==Ni||(Pi.__aiClientControllerCallbacks={onMute:null,onUnmute:null,onPlay:null,onStop:null});const Oi=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"),wi="9",bi=2e4,ki=4e4;class Mi{get localCapabilities(){return F(this._localCapabilities)}get rtpCapabilities(){return F(this._rtpCapabilities)}get candidates(){return F(this._candidates)}get iceParameters(){return F(this._iceParameters)}get remoteIceUfrag(){var e;return null===(e=this._iceParameters)||void 0===e?void 0:e.iceUfrag}get dtlsParameters(){return F(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 s=e=F(e),o=s.iceParameters,a=s.dtlsParameters,r=s.candidates,c=s.rtpCapabilities,d=s.setup,l=s.localCapabilities,u=s.cname;this._rtpCapabilities=c,this._candidates=r,this._originCandidates=F(r),this._iceParameters=o,this._dtlsParameters=a,this._localCapabilities=l,this.setup=d,this.cname=u;var h=Ge(this.updateRemoteRTPCapabilities(c),1);this.sessionDesc=h[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 s=[We({ssrcId:ki+t},M("USE_SUB_RTX")?{rtx:ki+t+1}:{})],o="".concat(ki+t,"_").concat(bi+t),a=Mt(s,this.cname,M("SYNC_GROUP")?o:void 0),r=a.ssrcs,c=a.ssrcGroups,d=this.preCreateOrRecycleSendMedia("video",r,c,void 0),l=[{ssrcId:bi+t}],u="".concat(ki+t,"_").concat(bi+t),h=Mt(l,this.cname,M("SYNC_GROUP")?u:void 0),p=h.ssrcs,_=h.ssrcGroups,E=this.preCreateOrRecycleSendMedia("audio",p,_,void 0);e--,t+=2,i.push(d,E),n.push(r[0].ssrcId,p[0].ssrcId)}return this.useLocalCodecsMids.push(...i),this.preloadSsrcs=n,{mids:i,preSSRCs:n,isAvailable:!0}}preCreateOrRecycleSendMedia(e,t,i,n){const s=this.rtpCapabilities.send.videoCodecs,o=this._isUseLocalCodecs||0===s.length?this.localCapabilities.recv:this.rtpCapabilities.send;N.debug("create or recycle send media without remote rtp capabilities, ssrcs ",t[0].ssrcId);const a=e===lt.VIDEO?o.videoCodecs:o.audioCodecs,r=e===lt.VIDEO?o.videoExtensions:o.audioExtensions;this.currentMidIndex+=1;const c="".concat(this.currentMidIndex);let d={media:{mediaType:e,port:wi,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 B(this.sessionDesc)}send(e,t,i,n){const s=Mt(t,this.cname,M("SYNC_GROUP")?i:void 0),o=s.ssrcs,a=s.ssrcGroups,r=this.findPreloadMediaDesc(o);if(r){if(x()&&this.firefoxSsrcMidMap.set(o[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,o);let i;return-1===t||1===t&&(te()||ie()||ne(143)||se(143)||oe()||M("RESERVE_MID_1_MLINE")||M("ENABLE_ENCODED_TRANSFORM")&&ae())||0===t&&!re(138)&&M("USE_SUB_RTX")||ce()?(i=this.createOrRecycleSendMedia(e,o,a,"sendonly",n),this.updateBundleMids()):(i=F(this.sessionDesc.mediaDescriptions[t]),i.attributes.direction="sendonly",i.attributes.ssrcs=o,i.attributes.ssrcGroups=a,this.sessionDesc.mediaDescriptions[t]=this.mungSendMediaDesc(i,n)),x()&&this.firefoxSsrcMidMap.set(o[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||x()||ce()?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,s)=>{this.createOrRecycleRecvMedia(e,[],"recvonly",t,i,n[s])})),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||V((i=this._isUseExtmapAllowMixed,this._isUseDataChannel?Oi(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 s=this.rtpCapabilities.send,o=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===s.videoCodecs.length){const t=o.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(o.videoCodecs[0]),e.media.fmts=t.map((e=>e.payloadType.toString(10))),e.attributes.payloads=t,e.attributes.extmaps=[]}else e.media.fmts=s.videoCodecs.map((e=>e.payloadType.toString(10))),e.attributes.payloads=s.videoCodecs,e.attributes.extmaps=s.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===s.audioCodecs.length){const t=o.audioCodecs.filter((e=>{var t;return null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase().includes("opus")}))||[o.audioCodecs[0]];e.media.fmts=t.map((e=>e.payloadType.toString(10))),e.attributes.payloads=t,e.attributes.extmaps=[]}else e.media.fmts=s.audioCodecs.map((e=>e.payloadType.toString(10))),e.attributes.payloads=s.audioCodecs,e.attributes.extmaps=s.audioExtensions,qt(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(We(We({},e),{},{foundation:"tcpcandidate",priority:Number(e.priority)-1+"",transport:"tcp",port:Number(e.port)+90+""}))})),0!==t.length){switch(e){case ut.TCP_RELAY:this._candidates=i;break;case ut.UDP_TCP_RELAY:case ut.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=F(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(x()){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:wi,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,s,o){const a=e._mediaStreamTrack.kind,r=this.rtpCapabilities.recv,c=jt(a,r,this.localCapabilities.send,a===lt.VIDEO?n:s),d=a===lt.VIDEO?r.videoExtensions:r.audioExtensions;this.currentMidIndex+=1;const l="".concat(this.currentMidIndex);let u={media:{mediaType:a,port:wi,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)}};u=this.mungRecvMediaDsec(u,e,o);const h=this.findFirstClosedMedia(a);if(h){const e=this.sessionDesc.mediaDescriptions.indexOf(h);this.sessionDesc.mediaDescriptions[e]=u}else this.sessionDesc.mediaDescriptions.push(u);return u}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(de).includes(e))))],s=new Set(t);if(n.every((e=>s.has(e))))return N.debug("codecs has not changed, no need to updateRemoteCodec, codecs: ".concat(t)),!1;const o=this._rtpCapabilities.recv.videoCodecs.filter((e=>t.some((t=>(e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").includes(t)))));if(0===o.length)return N.debug("updateRemoteCodec failed, because cannot find matched codec, remoteCapabilities codecs: ".concat(n," codecs: ").concat(t)),!1;const a=[...new Set(o.map((e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"")))];let r;if(N.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 N.debug("updateRemoteCodec failed, because cannot find mids, mids: ".concat(e,", codecs: ").concat(t)),!1;if(M("USE_PUB_RTX")||M("USE_SUB_RTX")){const e=zt(o,this.rtpCapabilities.recv.videoCodecs);o.push(...e)}this._rtpCapabilities.recv.videoCodecs=o;const c=this.localCapabilities.send,d=this.rtpCapabilities.recv,l=jt(lt.VIDEO,d,c,i);return r.forEach((e=>{const t=l.map((e=>e.payloadType.toString(10)));N.debug("updateRemoteCodec mid: ".concat(e.attributes.mid,", from"),e.attributes.payloads,"to",l),e.attributes.payloads=l,e.media.fmts=t})),N.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,s){const o=this.rtpCapabilities.send.videoCodecs,a=this._isUseLocalCodecs||0===o.length?this.localCapabilities.recv:this.rtpCapabilities.send,r=e===lt.VIDEO?a.videoCodecs:a.audioCodecs,c=e===lt.VIDEO?a.videoExtensions:a.audioExtensions;this.currentMidIndex+=1;const d="".concat(this.currentMidIndex);let l={media:{mediaType:e,port:wi,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,s);const u=this.findFirstClosedMedia(e);if(u){const e=this.sessionDesc.mediaDescriptions.indexOf(u);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 n=F(e);return Vt(n),Ut(n,t),xt(n,t),Ft(n),Bt(n,i,this.localCapabilities.send),n}mungSendMediaDesc(e,t){const i=F(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()&&M("ENABLE_DOWN_SPS_PPS")&&(e.fmtp&&e.fmtp.parameters||(e.fmtp={parameters:{}}),e.fmtp.parameters["sps-pps-idr-in-keyframe"]="1")})),Bt(i,t,this.localCapabilities.recv),qt(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=>x()?"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 Ui(e){return!!e&&Boolean("number"==typeof e.minDownscaleWidth&&e.minDownscaleWidth>=1||"number"==typeof e.minDownscaleHeight&&e.minDownscaleHeight>=1)}function Vi(e,t,i,n){if("number"!=typeof n)return Array.from({length:i+1},((i,n)=>e/Math.pow(t,n)));const s=Math.max(e,n),o=s/e;if(o<=1)return Array.from({length:i+1},(()=>e));const a=1/t,r=Math.min(i,Math.max(1,Math.ceil(Math.log(o)/Math.log(a)))),c=Math.pow(o,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),s)}))}function xi(e,t,i,n){if("number"!=typeof n)return i;const s=Math.max(e,n)/e;if(s<=1)return 0;const o=1/t;return Math.min(i,Math.max(1,Math.ceil(Math.log(s)/Math.log(o))))}var Fi=function(e){return e[e.DOWN=0]="DOWN",e[e.UP=1]="UP",e}(Fi||{});const Bi=new Map;function Wi(e,t,i,n){let s=e.scale;if(0===s&&n===Fi.UP||s>=t.length-1&&n===Fi.DOWN)return e;let o=We(We({},e),{},{scale:n===Fi.DOWN?++s:--s});switch(i){case"maintain-framerate":o=We(We({},o),t[s].motion);break;case"maintain-resolution":o=We(We({},o),t[s].detail);break;case"balanced":o=We(We({},o),t[s].balanced)}return o}function Gi(e,t,i){if(t){const n={overUse:0,underUse:0,adaptationList:Hi(t,i)};Bi.set(e,n)}else Bi.delete(e)}function Hi(e,t){const i=We({},e),n=i.bitrateMax,s=i.frameRate,o=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=le.MIN_FRAME_RATE,d=le.MAX_THRESHOLD_FRAMERATE,l=le.MAX_SCALE,u=le.BITRATE_MIN_THRESHOLD,h=le.BITRATE_MAX_THRESHOLD,p=le.BWE_SCALE_UP_THRESHOLD,_=le.BWE_SCALE_DOWN_THRESHOLD,E=le.PERF_SCALE_DOWN_THRESHOLD,m=le.PERF_SCALE_UP_THRESHOLD,S=le.BALANCE_BITRATE_FACTOR,R=le.BALANCE_FRAMERATE_FACTOR,C=le.BALANCE_RESOLUTION_FACTOR,f=le.MOTION_RESOLUTION_FACTOR,v=le.MOTION_BITRATE_FACTOR,T=le.DETAIL_FRAMERATE_FACTOR,g=le.DETAIL_BITRATE_FACTOR,I=Math.min(i.frameRate,d);let A=l;"maintain-framerate"===t?A=xi(o,f,l,r):"balanced"===t&&(A=xi(o,C,l,r));const D=Vi(o,C,A,r),P=Vi(o,f,A,r),N=[{scale:0,threshold:{bwe_down:Math.round(Math.pow(_,1)*n),bwe_up:n,fps_down:Math.round(Math.pow(E,1)*I),fps_up:s},balanced:{scaleResolutionDownBy:1,frameRate:s,bitrateMax:n,bitrateMin:a},motion:{scaleResolutionDownBy:1,frameRate:s,bitrateMax:n,bitrateMin:a},detail:{scaleResolutionDownBy:1,frameRate:s,bitrateMax:n,bitrateMin:a}}];for(let e=1;e<=A;e++){const t={bwe_up:Math.round(Math.pow(p,e)*n),bwe_down:Math.round(Math.pow(_,e+1)*n),fps_up:Math.round(Math.pow(m,e)*I),fps_down:Math.round(Math.pow(E,e+1)*I)},i={scaleResolutionDownBy:D[e],frameRate:Math.max(Math.round(Math.pow(R,e)*s),c),bitrateMax:Math.max(Math.round(Math.pow(S,e)*n),h),bitrateMin:Math.max(Math.round(Math.pow(S,e)*a),u)},o={scaleResolutionDownBy:P[e],frameRate:s,bitrateMax:Math.max(Math.round(Math.pow(v,e)*n),h),bitrateMin:Math.max(Math.round(Math.pow(v,e)*a),u)},r={scaleResolutionDownBy:1,frameRate:Math.max(Math.round(Math.pow(T,e)*s),c),bitrateMax:Math.max(Math.round(Math.pow(g,e)*n),h),bitrateMin:Math.max(Math.round(Math.pow(g,e)*a),u)};N.push({scale:e,threshold:t,balanced:i,motion:o,detail:r})}return N}function Yi(e,t,i,n,s,o){const a=Bi.get(e)||{overUse:0,underUse:0,adaptationList:Hi(s,o)},r=a.adaptationList;Bi.set(e,a);const c=le.OVERUSE_TIMES_THRESHOLD,d=le.UNDERUSE_TIMES_THRESHOLD,l=n.scale;let u,h;return"number"==typeof t&&t>0&&function(e,t,i,n){if(t>=i.length)return!1;let s=i[t].threshold.fps_down;return M("FORCE_AG_HIGH_FRAMERATE")&&"maintain-framerate"===n&&(s=i[0].threshold.fps_down),e<s}(t,l,r,o)&&(a.overUse++,h=ue.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++,h=ue.BANDWIDTH,a.overUse>c)?(a.overUse=0,a.underUse=0,u=Wi(n,r,o,Fi.DOWN),[u,h]):("number"==typeof t&&t>0&&"number"==typeof i&&i>0&&function(e,t,i,n){if(0===t)return;let s=i[t].threshold.fps_up;return M("FORCE_AG_HIGH_FRAMERATE")&&"maintain-framerate"===n&&(s=i[1].threshold.fps_up),e>s}(t,l,r,o)&&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,u=Wi(n,r,o,Fi.UP),0===u.scale&&(h=ue.NONE))),[u,h])}const Ki=new Map;function qi(e,t){const i=Ki.get(e);if(i){const t=i.timer;window.clearTimeout(t),Ki.delete(e)}t.qualityLimitationReason=ue.NONE,Gi(e)}const ji=["balanced","maintain-framerate","maintain-resolution"];function zi(e){switch(e){case"motion":return"maintain-framerate";case"detail":return"maintain-resolution";case"balanced":return"balanced";default:return}}function Ji(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const i=zi(e._optimizationMode);if(i)return i;const n=M("CUSTOM_ADAPTATION_DEFAULT_MODE");return e._hints.includes(s.CUSTOM_TRACK)?function(e){return"string"==typeof e&&ji.includes(e)}(n)?n:t?"maintain-framerate":"":"maintain-framerate"}function Xi(e,t,i){var n;const s=e.getParameters(),o=null===(n=s.encodings)||void 0===n?void 0:n[0];return o&&Object.assign(o,i),Object.assign(s,t),s}var Qi;function Zi(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 s=arguments.length,o=new Array(s),a=0;a<s;a++)o[a]=arguments[a];return await n.apply(this,o)}finally{i()}},i}function $i(e,t){let i;switch(t){case ht.LocalAudioTrack:i=nt.Audio;break;case ht.LocalVideoTrack:i=e._hints.includes(s.SCREEN_TRACK)?nt.Screen:nt.High;break;case ht.LocalVideoLowTrack:i=nt.Low}return i}var en,tn,nn,sn,on,an,rn,cn,dn,ln,un,hn;Qi=class e extends dt{get currentLocalDescription(){return this.peerConnection.currentLocalDescription}get currentRemoteDescription(){return this.peerConnection.currentRemoteDescription}get remoteIceUfrag(){var e;return null===(e=this.remoteSDP)||void 0===e?void 0:e.remoteIceUfrag}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(de).includes(e))))]}constructor(t,i){if(super(t,i),this.id=W(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:M("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._nvMedia=void 0,this.mutex=void 0,this.qualityLimitationReason=ue.NONE,this.unsupportedResolutionFloorTrackIds=new Set,this.isFirstConnected=!1,this.store=i,this.forceTurn=function(e){try{if(e.iceServers)return!1;if(e.turnServer&&"off"!==e.turnServer.mode){if(Q(e.turnServer.servers))return!1;if(M("FORCE_TURN_TCP")||e.turnServer.servers.concat(e.turnServer.serversFromGateway||[]).some((e=>e.forceturn)))return!0}return!1}catch(e){return!1}}(t),this.mutex=new K("P2PConnection-mutex",i.clientId),this.peerConnection=new RTCPeerConnection(e.resolvePCConfiguration(t),{optional:[{googDscp:!0}]}),this.isFirstConnected=!1,this.statsFilter=q(this.peerConnection,M("STATS_UPDATE_INTERVAL"),void 0,x()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1,t.isPreallocation&&(this.isPreallocation=!0),this.store.aiClientMode){const e=this.peerConnection.createDataChannel("agora-media",{id:this.store.mediaDcId,ordered:!1,negotiated:!0});e.binaryType="arraybuffer";try{this._nvMedia=yi(e),this._nvMedia.setAudioMetadataHandler((e=>{var t;null===(t=this.onAudioMetadata)||void 0===t||t.call(this,e)})),this._nvMedia.setAudioPtsHandler((e=>{var t;null===(t=this.onAudioPts)||void 0===t||t.call(this,e)})),N.debug("[".concat(this.store.clientId,"] [P2PConnection] AI Audio Mode initialized"))}catch(e){this._nvMedia=void 0,N.warning("[".concat(this.store.clientId,"] [P2PConnection] AI Audio Mode not available"),e)}}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 N.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 N.debug("[P2PConnection] updateRemoteRTPCapabilities no need to exchange SDP.")}async establish(){try{this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.peerConnection.addTransceiver("audio",{direction:"recvonly"});const i=await this.peerConnection.createOffer();if(!i.sdp)throw new Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");const n=bt(i.sdp),s=await Gt({filterRTX:!M("USE_PUB_RTX")&&!M("USE_SUB_RTX"),filterVideoFec:M("FILTER_VIDEO_FEC"),filterAudioFec:M("FILTER_AUDIO_FEC"),filterVideoCodec:M("FILTER_VIDEO_CODEC"),unsupportedVideoUplinkCodec:M("UNSUPPORTED_VIDEO_UPLINK_CODEC"),unsupportedVideoDownlinkCodec:M("UNSUPPORTED_VIDEO_DOWNLINK_CODEC")},this.extension);if(this.localCapabilities=Kt(s),this.initialOffer=i,M("ENABLE_SVC")&&"av1"==this.store.codec){const t=await async function(){try{const e=new RTCPeerConnection;e.addTransceiver("video",{direction:"sendonly",sendEncodings:[{scalabilityMode:U.L1T3}]});const t=await e.createOffer();if(!t.sdp)return void e.close();const i=V(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}}();var e;if(t)this.supportAV1RtpSpec=!0,null===(e=s.send)||void 0===e||e.videoExtensions.push(t)}let o;return i.sdp&&Zt(i.sdp)&&(o=F(s),(t=o).send&&(Lt(lt.VIDEO,t.send.videoExtensions),Lt(lt.AUDIO,t.send.audioExtensions)),t.recv&&(Lt(lt.VIDEO,t.recv.videoExtensions),Lt(lt.AUDIO,t.recv.audioExtensions)),t.sendrecv&&(Lt(lt.VIDEO,t.sendrecv.videoExtensions),Lt(lt.AUDIO,t.sendrecv.audioExtensions))),We(We({},n),{},{rtpCapabilities:o||s,offerSDP:i.sdp})}catch(e){throw new j(z.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString())}var t}async connect(e){try{if(!this.initialOffer)throw new Error("Cannot establish P2PConnection without initial offer.");if(this.initialOffer.sdp&&Zt(this.initialOffer.sdp)&&(n=e.rtpCapabilities,s=this.localCapabilities,n.send&&(Nt(lt.VIDEO,n.send.videoExtensions,s.send.videoExtensions),Nt(lt.AUDIO,n.send.audioExtensions,s.send.audioExtensions)),n.recv&&(Nt(lt.VIDEO,n.recv.videoExtensions,s.recv.videoExtensions),Nt(lt.AUDIO,n.recv.audioExtensions,s.recv.audioExtensions))),this.remoteSDP=new Mi(We(We({},e),{},{localCapabilities:this.localCapabilities}),this.supportAV1RtpSpec,!(!M("ENABLE_PRE_SUB_WITH_PRE_PC")||!M("PRE_USE_LOCAL_CODECS"))&&S(this.store),this.store.aiClientMode),e.preallocation&&(this.isPreallocation=!0),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0&&this.remoteSDP.updateRemoteCodec([],this.remoteCodecs,this.store.codec),R()&&S(this.store)){var t;const e=(null===(t=this.store.preSubOptions)||void 0===t?void 0:t.length)||0,i=M("PRE_SUB_NUM")||1,n=e>i?e:i,s=this.remoteSDP.preloadRemoteMedia(n),o=s.mids,a=s.preSSRCs,r=Xt(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 u=this.remoteSDP.toString();null==l||l(u),await this.peerConnection.setRemoteDescription({type:"answer",sdp:u}),N.debug("[".concat(this.store.clientId,"] [P2PConnection] preload media with icc/dtls, add preload ssrcs ").concat(a)),await this.presetMedia(o,a);const h=this.peerConnection.getTransceivers()[0];null!=h&&h.receiver&&this.tryBindTransportEvents(h.receiver)}else{const t=this.remoteSDP.toString(),n=Xt(this.initialOffer.sdp,this.extension),s=this.logSDPExchange(n||"","offer","local","connect");this.store.descriptionStart(),await this.peerConnection.setLocalDescription({type:"offer",sdp:n}),null==s||s(t),await this.peerConnection.setRemoteDescription({type:"answer",sdp:t});const o=this.peerConnection.getTransceivers()[0];if(null!=o&&o.receiver&&this.tryBindTransportEvents(o.receiver),S(this.store))if(e.preallocation&&M("ENABLE_PRE_SUB_WITH_PRE_PC")){var i;const e=(null===(i=this.store.preSubOptions)||void 0===i?void 0:i.length)||0,t=M("PRE_SUB_NUM")||1,n=e>t?e:t,s=this.remoteSDP.preloadRemoteMedia(n),o=s.mids,a=s.preSSRCs;await Jt(this.peerConnection,this.remoteSDP,this.extension),N.debug("[".concat(this.store.clientId,"] [P2PConnection] preload media, in pre pc,add preload ssrcs ").concat(a)),await this.presetMedia(o,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 s=this.remoteSDP.batchSend(i.map((e=>Object.assign({},e)))).mids;await Jt(this.peerConnection,this.remoteSDP,this.extension),N.debug("[P2PConnection.connect] preload media, after join, add preload ssrcs ".concat(n)),await this.presetMedia(s,n)}}}catch(e){throw new j(z.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(e.toString()))}var n,s}shouldUseAiAudioPreload(){return this.store.aiClientMode&&this.store.autoSubscribe&&!!this._nvMedia}async presetAiAudioMedia(e,t){if(!this._nvMedia)return;const i=await this._nvMedia.receiveByRTCMedia(lt.AUDIO,[{ssrcId:t}],void 0);this.store.autoReceiveAndPlayAudio&&this._nvMedia.play(),this.preMediaMap.set(t,{mid:e,track:i.track,player:void 0,transceiver:void 0,aiAudioMode:!0})}async presetMedia(e,t){for(const o of e.entries()){var i=Ge(o,2);const e=i[0],a=i[1];for(const i of this.peerConnection.getTransceivers())if(null!=i.mid&&a===i.mid&&i.receiver.track){const o=i.receiver.track;if("audio"===o.kind&&this.shouldUseAiAudioPreload()){await this.presetAiAudioMedia(a,t[e]);break}if(M("PRE_PLAYOUT_DELAY_HINT")){const e=i.receiver;"playoutDelayHint"in e&&(e.playoutDelayHint=M("PRE_PLAYOUT_DELAY_HINT"),N.debug("[".concat(this.store.clientId,"] [P2PConnection] presetMedia set playoutDelayHint to ").concat(M("PRE_PLAYOUT_DELAY_HINT"))))}let r,c;if("video"===o.kind&&M("ENABLE_PRE_RENDER")){var n,s;let i=null===(n=this.store.preSubOptions)||void 0===n||null===(n=n[e])||void 0===n?void 0:n.element;const a=(null===(s=this.store.preSubOptions)||void 0===s||null===(s=s[e])||void 0===s?void 0:s.config)||{};N.debug("try to play pre sub video","string"==typeof i?i:"element","config: ".concat(JSON.stringify(a))),"string"==typeof i&&(i=document.getElementById(i)||void 0),r=i instanceof HTMLVideoElement?new C(We({trackId:"track-".concat(o.kind,"-unknown-").concat(this.store.clientId,"_").concat(W(5,"")),element:i},a)):new f(We({trackId:"track-".concat(o.kind,"-unknown-").concat(this.store.clientId,"_").concat(W(5,"")),element:i},a),!i),r.updateVideoTrack(o),r.onFirstVideoFrameRender=()=>{var i;r&&(r.onFirstVideoFrameRender=void 0);const n=this.preMediaMap.get(t[e]);n&&(n.firstVideoRender=Date.now()),null===(i=this.onFirstVideoRender)||void 0===i||i.call(this,t[e])},r.onVideoBufferReady=()=>{var i;null===(i=this.onFirstVideoBufferReady)||void 0===i||i.call(this,t[e])},r.play(this.store.sessionId||void 0),this.isPreRender=!0}if("audio"===o.kind&&this.store.autoReceiveAndPlayAudio){c="track-".concat(o.kind,"-unknown-").concat(this.store.clientId,"_").concat(W(5,""));const e=100;E.play(o,c,e,this.store.sessionId||void 0),N.debug("[".concat(this.store.clientId,"] [P2PConnection] presetMedia start audio playback, trackId: ").concat(c))}this.preMediaMap.set(t[e],{mid:a,track:o,player:r,transceiver:i,audioTrackId:c});break}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 i=!1;const n=e.rtpCapabilities;if(i=Ge(this.remoteSDP.updateRemoteRTPCapabilities(n),2)[1],Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0){const e=this.remoteSDP.updateRemoteCodec([],this.remoteCodecs,this.store.codec);i=i||e}const s=e.preSSRCs,o=void 0===s?[]:s,a=o.map((e=>e.ssrcMsg[0].ssrcId));if(!this.remoteSDP.checkPreloadSsrcs(a)){const e=[],i=[];let n=!1;var t;if(Array.from(this.preMediaMap.entries()).every((t=>{let s=Ge(t,2),o=s[0],a=s[1],r=a.mid,c=a.player,d=(a.track,a.audioTrackId),l=a.aiAudioMode;return e.push(r),i.push(o),this.preMediaMap.delete(o),c&&c.destroy(),d&&E.stop(d),n=n||!!l,!0})),n)null===(t=this._nvMedia)||void 0===t||t.stopReceiving();if(e.length>0&&(this.remoteSDP.stopSending(e),await Jt(this.peerConnection,this.remoteSDP,this.extension),N.warn("[P2PConnection.updateRemoteConnect] preload media, failed, del preload ssrcs ".concat(i)),y.reportApiInvoke(this.store.sessionId,{name:me.PRELOAD_MEDIA_FAILED,options:[o,i],tag:Se.TRACER}).onSuccess()),o.length>0){const e=this.remoteSDP.batchSend(o.map((e=>Object.assign({},e)))).mids;await Jt(this.peerConnection,this.remoteSDP,this.extension),N.debug("[P2PConnection.updateRemoteConnect] preload media, after join, add preload ssrcs ".concat(a)),await this.presetMedia(e,a)}}i?(await Jt(this.peerConnection,this.remoteSDP,this.extension),N.debug("[P2PConnection] updateRemoteConnect by exchanging SDP.")):N.debug("[P2PConnection] updateRemoteConnect no need to exchange SDP, because no need to update remote codecs (use local codecs)")}catch(e){throw new j(z.EXCHANGE_SDP_FAILED,"P2PConnection.updateRemoteConnect failed; ".concat(e.toString()))}}send(e,t,i){var n=this;return He((function*(){const s=yield xe(n.mutex.lock("From P2PConnection.send"));try{if(!n.remoteSDP)throw new Error("Cannot call P2PConnection.send before remote SDP created");const o=[],a=Dt();e.forEach((e=>{const t=n.peerConnection.addTransceiver(e._mediaStreamTrack,We({direction:"sendonly"},"video"===e.trackMediaType&&n.supportAV1RtpSpec&&a?{sendEncodings:[{scalabilityMode:a}]}:{}));o.push(t),e._updateRtpTransceiver(t)})),x()&&!0===M("SIMULCAST")&&(yield xe(n.applySimulcastForFirefox(o,e)));const r=yield xe(n.peerConnection.createOffer()),c=n.remoteSDP.predictReceivingMids(e.length),d=n.mungSendOfferSDP(r.sdp,e,c),l=V(d),u=c.map((e=>{const t=l.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error("Cannot extract ssrc from mediaDescription.");return kt(t,M("USE_PUB_RTX"))}));let h;try{h=yield u}catch(s){h=[],n.remoteSDP.receive(e,t,i,h);const o=n.remoteSDP.toString();throw yield xe(n.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield xe(n.peerConnection.setRemoteDescription({type:"answer",sdp:o})),yield xe(n.stopSending(c,!0)),s}n.remoteSDP.receive(e,t,i,h);const p=n.remoteSDP.toString(),_=n.logSDPExchange(d,"offer","local","send");return yield xe(n.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield xe(n.applySimulcastEncodings(o,e)),yield xe(n.applySendEncodings(o,e)),null==_||_(p),yield xe(n.peerConnection.setRemoteDescription({type:"answer",sdp:p})),o.map(((e,t)=>{const i=c[t];return{localSSRC:u[t],id:i,transceiver:e}}))}catch(e){throw e instanceof j?e:new j(z.EXCHANGE_SDP_FAILED,"P2PConnection.send failed; ".concat(e.toString()))}finally{s()}}))()}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)N.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:M("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),N.debug("[P2PConnection] createDataChannels by exchanging SDP.")}else N.debug("[P2PConnection] createDataChannels no need to exchange SDP.");return}catch(e){throw e instanceof j?e:new j(z.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 j?e:new j(z.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;qi(this.id+e.mid,this),e.direction="inactive",null===(t=e.stop)||void 0===t||t.call(e)}));const n=await this.peerConnection.createOffer(),s=this.logSDPExchange(n.sdp||"","offer","local","stopSending");await this.peerConnection.setLocalDescription(n),this.remoteSDP.stopReceiving(e);const o=this.remoteSDP.toString();null==s||s(o),await this.peerConnection.setRemoteDescription({type:"answer",sdp:o})}catch(e){throw new j(z.EXCHANGE_SDP_FAILED,"P2PConnection.stopSending failed; ".concat(e.toString()))}finally{i&&i()}}async receive(e,t,i,n){if(this._nvMedia&&e===lt.AUDIO)return N.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," by DataChannel.")),await this._nvMedia.receiveByRTCMedia(e,t,void 0);try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.receive ".concat(e," before remoteSDP created."));const s=this.remoteSDP.send(e,t,i,n),o=s.mid;s.needExchangeSDP&&(await Jt(this.peerConnection,this.remoteSDP,this.extension),N.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," by exchanging SDP.")));const a=this.peerConnection.getTransceivers().find((e=>e.mid===o));if(!a)throw new Error("Cannot get transceiver after setLocalDescription.");if(M("PRE_PLAYOUT_DELAY_HINT")){const t=a.receiver;"playoutDelayHint"in t&&(t.playoutDelayHint=M("PRE_PLAYOUT_DELAY_HINT"),N.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," set playoutDelayHint to ").concat(M("PRE_PLAYOUT_DELAY_HINT"))))}return{track:a.receiver.track,id:o,transceiver:a}}catch(e){throw new j(z.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 Jt(this.peerConnection,this.remoteSDP,this.extension),N.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(M("PRE_PLAYOUT_DELAY_HINT")){const e=t.receiver;"playoutDelayHint"in e&&(e.playoutDelayHint=M("PRE_PLAYOUT_DELAY_HINT"),N.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e.track.kind," set playoutDelayHint to ").concat(M("PRE_PLAYOUT_DELAY_HINT"))))}return{track:t.receiver.track,id:e,transceiver:t}}))}catch(e){throw new j(z.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.");let t=!1;e.forEach((e=>{Array.from(this.preMediaMap.entries()).some((i=>{let n=Ge(i,2),s=n[0],o=n[1],a=o.mid,r=o.player,c=o.audioTrackId,d=o.aiAudioMode;if(a===e)return this.preMediaMap.delete(s),r&&r.destroy(),c&&E.stop(c),t=t||!!d,!0}))})),t&&this._nvMedia&&(this._nvMedia.setAudioMetadataHandler(null),this._nvMedia.setAudioPtsHandler(null),this._nvMedia.stopReceiving()),this.remoteSDP.stopSending(e);const i=this.remoteSDP.toString(),n=this.logSDPExchange(i,"offer","remote","stopReceiving");await this.peerConnection.setRemoteDescription({type:"offer",sdp:i});const s=await this.peerConnection.createAnswer();null==n||n(s.sdp||""),await this.peerConnection.setLocalDescription(s)}catch(e){throw new j(z.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 j(z.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 j(z.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 s=this.remoteSDP.toString();null==n||n(s),await this.peerConnection.setRemoteDescription({type:"answer",sdp:s})}catch(e){throw new j(z.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 s=this.remoteSDP.toString();null==n||n(s),await this.peerConnection.setRemoteDescription({type:"answer",sdp:s})}catch(e){throw new j(z.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteLocal failed; ".concat(e.toString()))}}restartICE(e){var t=this;return He((function*(){const i=yield xe(t.mutex.lock("From P2PConnection.restartICE"));try{if(!t.remoteSDP)throw new Error("Cannot restartICE before remoteSDP created.");const s=n().supportPCSetConfiguration,o=M("FORCE_TURN_TCP")||t.forceTurn;if(e===ut.RELAY&&!s)return;if(s&&!o){const i=e===ut.RELAY?"relay":"all",n=t.peerConnection.getConfiguration();n.iceTransportPolicy!==i&&(N.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 xe(t.peerConnection.createOffer({iceRestart:!0}));if(!a.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const r=bt(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 xe(t.peerConnection.setLocalDescription(a)),null==l||l(d),yield xe(t.peerConnection.setRemoteDescription({type:"answer",sdp:d}))}catch(e){N.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(ut.TCP_RELAY),await Jt(this.peerConnection,this.remoteSDP,this.extension)}catch(e){N.warning("[".concat(this.store.clientId,"] extend candidate failed, abort operation"),e)}finally{e()}}close(){var e,t,i,n;null===(e=this._nvMedia)||void 0===e||e.setAudioMetadataHandler(null),null===(t=this._nvMedia)||void 0===t||t.setAudioPtsHandler(null),null===(i=this._nvMedia)||void 0===i||i.close(),this._nvMedia=void 0,this.peerConnection.getTransceivers().forEach((e=>{qi(this.id+e.mid,this)})),this.preMediaMap.forEach((e=>{let t=e.player,i=e.audioTrackId;t&&t.destroy(),i&&E.stop(i)})),this.preMediaMap.clear(),this.peerConnection.close(),null===(n=this.onConnectionStateChange)||void 0===n||n.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(){const e=We(We({},this.statsFilter.getStats()),{},{qualityLimitationReason:this.qualityLimitationReason});if(this._nvMedia){const t=this._nvMedia.getStats();e.audioRecv.push(t)}return e}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 s=this.remoteSDP.toString(),o=this.logSDPExchange(n,"offer","local","updateEncoderConfig");await this.peerConnection.setLocalDescription({type:"offer",sdp:n}),null==o||o(s),await this.peerConnection.setRemoteDescription({type:"answer",sdp:s})}catch(e){throw new j(z.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)?x()||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:We(We({},X),{},{candidateType:i.type,protocol:i.protocol,address:i.address,port:i.port}),remote:We(We({},X),{},{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):"",s=At(e.url||"");N.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICECandidateError(").concat(i,"), url: ").concat(s||"",", 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&&N.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,N.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount))},setTimeout((()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,N.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount))}),M("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:[]},s=t.cloudProxyServer||"disabled";return t.iceServers?i.iceServers=t.iceServers:t.turnServer&&(Q(t.turnServer.servers)?i.iceServers=t.turnServer.servers:M("NEW_TURN_MODE")&&i.iceServers&&"disabled"===s?(M("USE_TURN_SERVER_OF_GATEWAY")?t.turnServer.serversFromGateway&&i.iceServers.push(...e.newTurnServerConfigToIceServers(t.turnServer.serversFromGateway)):i.iceServers.push(...e.newTurnServerConfigToIceServers(t.turnServer.servers)),M("NEW_FORCE_TURN")&&(i.iceTransportPolicy="relay")):"off"!==t.turnServer.mode&&(i.iceServers&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers)),M("USE_TURN_SERVER_OF_GATEWAY")&&i.iceServers&&t.turnServer.serversFromGateway&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway)),M("FORCE_TURN_TCP")?i.iceTransportPolicy="relay":t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach((e=>{e.forceturn&&(i.iceTransportPolicy="relay")})))),M("ENABLE_ENCODED_TRANSFORM")&&n().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(ft(e.turnServerURL),":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&!M("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=M("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(ft(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(ft(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;N.info("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] selectedcandidatepairchange: local ").concat(JSON.stringify(At(e)),", remote ").concat(JSON.stringify(At(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 N.warn("[".concat(e.getTrackId(),"] no rtpSender found}"));if(this.isVP8Simulcast(e))return N.warn("[updateRtpSenderEncodings] Track is VP8 simulcast, please apply simulcast encodings");if(!n().supportSetRtpSenderParameters)return N.warn("[updateRtpSenderEncodings] Browser not support set rtp-sender parameters");const o=v(e),a=!!o&&("vp8"===(r=this.store.codec)||"vp9"===r)&&Ui(o);var r;const c=a&&!this.unsupportedResolutionFloorTrackIds.has(e.getTrackId()),d=!!o&&!(a&&!c)&&function(e,t){return!(!M("ENABLE_AG_ADAPTATION")||!Ui(t)&&(!(e instanceof m||e._hints.includes(s.CUSTOM_TRACK))||!M("FORCE_SUPPORT_AG_ADAPTATION")&&!(he(14,0,!1)&&pe(17,4,!0)||_e(14)&&Ee(17,4,!0))))}(e,c?o:void 0),l=c&&d,u=c||["vp8","vp9"].includes(this.store.codec),h={},p={},_=function(e,t){if(t)return"maintain-resolution";const i=zi(e._optimizationMode);return i||void 0}(e,l);_&&(h.degradationPreference=_);const E=function(e,t){return e.getTransceivers().find((e=>e.sender.track===t||e.receiver.track===t))}(this.peerConnection,e._mediaStreamTrack);if(d&&E&&t&&o&&this.getLocalVideoStats&&u){const i=this.id+E.mid,n=Ji(e,c);!function(e,t,i,n,s,o){if(qi(e,i),s(t),"balanced"!==n&&"maintain-framerate"!==n&&"maintain-resolution"!==n)return;let a=-1;Gi(e,t,n);const r=window.setInterval((()=>{const r=Ki.get(e);if(!M("ENABLE_AG_ADAPTATION")||!r)return qi(e,i),void s(t);const c=o();if(c.sendPackets>0&&c.OutgoingAvailableBandwidth>0){if(-1===a)return void(a=Date.now());if(Date.now()-a<1e3)return;const o=c.sendFrameRate,d=c.OutgoingAvailableBandwidth,l=Ge(Yi(e,o,d,r.adaptationConfig,t,n),2),u=l[0],h=l[1];h&&(i.qualityLimitationReason=h),u&&r.adaptationConfig.scale!==u.scale&&(N.debug("[".concat(e,"] applyAdaptation: ").concat(i.qualityLimitationReason,"\n sendFps ").concat(o,", bwe ").concat(d,", switch from ").concat(r.adaptationConfig.scale," to ").concat(u.scale," ")),r.adaptationConfig=We(We({},r.adaptationConfig),u),s(u))}}),M("CHECK_LOCAL_STATS_INTERVAL")),c=We({},t);Ki.set(e,{timer:r,adaptationConfig:c,originConfig:t,adaptationFunc:s}),N.debug("[".concat(e,"] start adaptation, originConfig: ").concat(JSON.stringify(t),", degradationPreference: ").concat(n))}(i,o,this,n,(n=>{t&&this.updateAdaptation(e,t,n,i,c)}),this.getLocalVideoStats.bind(this))}if(e._encoderConfig){const t=e._encoderConfig,i=t.bitrateMax,n=t.frameRate,o=t.scaleResolutionDownBy;i&&(p.maxBitrate=1e3*i),(e._hints.includes(s.LOW_STREAM)||e.isUseScaleResolutionDownBy)&&(n&&(p.maxFramerate=vt(n)),o&&o>=1&&(p.scaleResolutionDownBy=o))}const S=M("ENCODER_CONFIG_LIMIT").maxFramerate;if(S&&"number"==typeof S&&(p.maxFramerate=p.maxFramerate?Math.min(p.maxFramerate,S):S),M("DSCP_TYPE")&&Z()){const e=M("DSCP_TYPE");["very-low","low","medium","high"].includes(e)&&(p.networkPriority=e)}const R=t.getParameters(),C=null===(i=R.encodings)||void 0===i?void 0:i[0];x()&&!C&&(h.encodings=[p]),C&&Object.assign(C,p),Object.assign(R,h),N.debug("[".concat(e.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(R.encodings))),await t.setParameters(R),await async function(e,t,i){try{var s;if(!n().supportSetRtpSenderParameters)return;if(!function(e){return"vp9"===e||"av1"===e}(e)||!M("ENABLE_SVC"))return;const o={},a={},r=t.getParameters(),c=null===(s=r.encodings)||void 0===s?void 0:s[0];a.scalabilityMode=Dt(i),c&&Object.assign(c,a),Object.assign(r,o),await t.setParameters(r),N.debug("[updateAdaptation] updateRtpSenderEncodings scalabilityMode success: ".concat(JSON.stringify(r.encodings)))}catch(e){N.debug("[updateAdaptation] updateRtpSenderEncodings scalabilityMode failed",e)}}(this.store.codec,t,M("SVC_MODE"))}async updateAdaptation(e,t,i,s,o){var a;if(!t)return N.debug("[updateAdaptation] no rtpSender found");if(!n().supportSetRtpSenderParameters)return N.debug("[updateAdaptation] Browser not support set rtp-sender parameters");const r={},c={},d=i.bitrateMax,l=i.frameRate,u=i.scaleResolutionDownBy;d&&(c.maxBitrate=1e3*d),l&&(c.maxFramerate=vt(l));let h=!1;"number"==typeof u&&u>=1&&(o||["vp8","vp9"].includes(this.store.codec))&&(c.scaleResolutionDownBy=u,h=u>1);const p=t.getParameters(),_=null===(a=p.encodings)||void 0===a?void 0:a[0];_&&Object.assign(_,c),Object.assign(p,r);try{await t.setParameters(p),N.debug("[updateAdaptation] updateRtpSenderEncodings: ".concat(JSON.stringify(p.encodings)))}catch(i){if(!("transport"in t)||t.transport&&"connected"===t.transport.state)if("connected"!==this.peerConnectionState)N.debug("[updateAdaptation] peerConnection not connected}");else if(o&&h){const n=await async function(e,t,i){try{return await e.setParameters(Xi(e,t,i)),{classification:"transient"}}catch(n){const s=We({},i);delete s.scaleResolutionDownBy;try{return await e.setParameters(Xi(e,t,s)),{classification:"unsupported",retryWithScaleError:n}}catch(e){return{classification:"unknown",retryWithScaleError:n,retryWithoutScaleError:e}}}}(t,r,c);"unsupported"===n.classification?(this.unsupportedResolutionFloorTrackIds.add(e.getTrackId()),qi(s,this),N.warn("[".concat(e.getTrackId(),"] fallback to browser adaptation because scaleResolutionDownBy adaptation is unsupported"),i,n.retryWithScaleError),this.updateRtpSenderEncodings(e,t).catch((t=>{N.warn("[".concat(e.getTrackId(),"] failed to re-apply browser adaptation after disabling resolution floor"),t)}))):"transient"===n.classification?N.debug("[".concat(e.getTrackId(),"] keep resolution floor enabled after transient setParameters failure"),i):N.debug("[".concat(e.getTrackId(),"] keep resolution floor enabled because setParameters failure is not classified as unsupported"),i,n.retryWithScaleError,n.retryWithoutScaleError)}else N.debug("[updateAdaptation] updateRtpSenderEncodings failed",i);else N.debug("[updateAdaptation] rtpSender transport not connected}")}}async applySendEncodings(e,t){try{if(!n().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let n=0;n<e.length;n++){const s=e[n],o=t[n];o instanceof i&&!this.isVP8Simulcast(o)&&await this.updateRtpSenderEncodings(o,s.sender)}}catch(e){N.debug("[".concat(this.store.clientId,"] Apply RTPSendEncodings failed."))}}mungSendOfferSDP(e,t,i){if(M("FORBID_MODIFY_LOCAL_OFFER_SDP"))return e;const n=V(e);return t.forEach(((e,t)=>{const s=i[t],o=n.mediaDescriptions.find((e=>e.attributes.mid===s));o&&(Ut(o,e),Wt(o,e,this.store.codec))})),B(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 n,o,a,r;const d=e[c],l=t[c];if(l instanceof i&&!l._hints.includes(s.LOW_STREAM)&&null!==(n=l._encoderConfig)&&void 0!==n&&n.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(!x()&&e.length===t.length)for(let n=0;n<e.length;n++){const s=t[n];if(s instanceof i&&this.isVP8Simulcast(s)){const t=e[n],i={},o={high:1e3*(s._encoderConfig.bitrateMax-50),medium:5e4};i.encodings=[{active:!0,adaptivePtime:!1,networkPriority:"high",priority:"high",maxBitrate:o.high},{active:!0,adaptivePtime:!1,networkPriority:"low",priority:"low",maxBitrate:o.medium,scaleResolutionDownBy:4}];const a=t.sender.getParameters();await t.sender.setParameters(Object.assign(a,i))}}}isVP8Simulcast(e){var t,n,o,a;return!!(e instanceof i&&M("SIMULCAST")&&"vp8"===this.store.codec&&!e._hints.includes(s.LOW_STREAM)&&null!==(t=e._encoderConfig)&&void 0!==t&&t.bitrateMax&&(null===(n=e._encoderConfig)||void 0===n?void 0:n.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(M("SDP_LOGGING"))return N.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(n().supportPCSetConfiguration){const i=e.resolvePCConfiguration(t);this.peerConnection.setConfiguration(i)}t.isPreallocation&&(this.isPreallocation=!0)}},Ue(Qi.prototype,"updateRemoteRTPCapabilities",[Zi],Object.getOwnPropertyDescriptor(Qi.prototype,"updateRemoteRTPCapabilities"),Qi.prototype),Ue(Qi.prototype,"connect",[Zi],Object.getOwnPropertyDescriptor(Qi.prototype,"connect"),Qi.prototype),Ue(Qi.prototype,"updateRemoteConnect",[Zi],Object.getOwnPropertyDescriptor(Qi.prototype,"updateRemoteConnect"),Qi.prototype),Ue(Qi.prototype,"createDataChannels",[Zi],Object.getOwnPropertyDescriptor(Qi.prototype,"createDataChannels"),Qi.prototype),Ue(Qi.prototype,"receive",[Zi],Object.getOwnPropertyDescriptor(Qi.prototype,"receive"),Qi.prototype),Ue(Qi.prototype,"batchReceive",[Zi],Object.getOwnPropertyDescriptor(Qi.prototype,"batchReceive"),Qi.prototype),Ue(Qi.prototype,"stopReceiving",[Zi],Object.getOwnPropertyDescriptor(Qi.prototype,"stopReceiving"),Qi.prototype),Ue(Qi.prototype,"muteRemote",[Zi],Object.getOwnPropertyDescriptor(Qi.prototype,"muteRemote"),Qi.prototype),Ue(Qi.prototype,"unmuteRemote",[Zi],Object.getOwnPropertyDescriptor(Qi.prototype,"unmuteRemote"),Qi.prototype),Ue(Qi.prototype,"muteLocal",[Zi],Object.getOwnPropertyDescriptor(Qi.prototype,"muteLocal"),Qi.prototype),Ue(Qi.prototype,"unmuteLocal",[Zi],Object.getOwnPropertyDescriptor(Qi.prototype,"unmuteLocal"),Qi.prototype),Ue(Qi.prototype,"close",[Zi],Object.getOwnPropertyDescriptor(Qi.prototype,"close"),Qi.prototype),Ue(Qi.prototype,"updateEncoderConfig",[Zi],Object.getOwnPropertyDescriptor(Qi.prototype,"updateEncoderConfig"),Qi.prototype),Ue(Qi.prototype,"updateSendParameters",[Zi],Object.getOwnPropertyDescriptor(Qi.prototype,"updateSendParameters"),Qi.prototype),Ue(Qi.prototype,"replaceTrack",[Zi],Object.getOwnPropertyDescriptor(Qi.prototype,"replaceTrack"),Qi.prototype),Ue(Qi.prototype,"updateAdaptation",[Zi],Object.getOwnPropertyDescriptor(Qi.prototype,"updateAdaptation"),Qi.prototype),Ue(Qi.prototype,"getRemoteSSRC",[Zi],Object.getOwnPropertyDescriptor(Qi.prototype,"getRemoteSSRC"),Qi.prototype),!n().supportUnifiedPlan||M("CHROME_FORCE_PLAN_B")&&Z();let pn=(en=_n(Di.SEND_ONLY),tn=_n(Di.SEND_ONLY),nn=_n(),sn=_n(Di.RECEIVE_ONLY),on=_n(Di.RECEIVE_ONLY),an=_n(Di.RECEIVE_ONLY),rn=_n(Di.RECEIVE_ONLY),cn=_n(Di.RECEIVE_ONLY),dn=_n(Di.RECEIVE_ONLY),ln=_n(),un=_n(Di.RECEIVE_ONLY),hn=class extends k{get state(){return this._state}set state(e){const t=this._state;this._state=e,this.emit(_t.StateChange,t,this._state)}constructor(e,t){super(),this.isPlanB=!1,this.store=void 0,this.statsUploader=void 0,this.sendConnection=void 0,this.recvConnection=void 0,this.localTrackMap=new Map,this.remoteUserMap=new Map,this.localDataChannels=[],this.pendingLocalTracks=[],this.pendingRemoteTracks=[],this.statsCollector=void 0,this.dtlsFailedCount=0,this.sendMutex=void 0,this.recvMutex=void 0,this._state=pt.Disconnected,this._restartStates=["disconnected","failed"],this.reconnectInterval=void 0,this.uploadUnplinkStarted=!1,this.uploadDownlinkStarted=!1,this.uplinkStateUploadInterval=void 0,this.downlinkStatsUploadInterval=void 0,this.handleMuteLocalTrack=async(e,t,i)=>{const n=await this.sendMutex.lock("Locking from P2PChannel2.handleMuteLocalTrack");try{if(!this.sendConnection||this.state!==pt.Connected)return void i(new j(z.INVALID_OPERATION,"Cannot call P2PChannel2.handleMuteLocalTrack before sendConnection established."));const a=this.filterTobeMutedTracks(e);if(0===a.length)return void t();const r=a.find((e=>"videoLowTrack"===e[0]));if(r){r[1].track._originMediaStreamTrack.stop()}await this.sendConnection.muteLocal(a.map((e=>Ge(e,2)[1].id)));let c=!1;var s,o;if("video"===e.trackMediaType)c=!(null===(s=this.localTrackMap.get(ht.LocalAudioTrack))||void 0===s||!s.track._muted);else c=void 0===(null===(o=this.localTrackMap.get(ht.LocalVideoTrack))||void 0===o?void 0:o.id);const d=this.createMuteMessage(a);await Re(this,_t.RequestMuteLocal,d);const l="video"===e.trackMediaType?St.MUTE_LOCAL_VIDEO:St.MUTE_LOCAL_AUDIO;await Re(this,_t.RequestP2PMuteLocal,{action:l,message:d,isMuteAll:c}),t()}catch(e){i(e)}finally{n()}},this.handleUnmuteLocalTrack=async(e,t,i)=>{const n=await this.sendMutex.lock("Locking from P2PChannel2.handleUnmuteLocalTrack");try{if(!this.sendConnection||this.state!==pt.Connected)return void i(new j(z.INVALID_OPERATION,"Cannot call P2PChannel2.handleUnmuteLocalTrack before sendConnection established."));const s=this.filterTobeUnmutedTracks(e);if(0===s.length)return void t();await this.sendConnection.unmuteLocal(s.map((e=>Ge(e,2)[1].id)));const o=this.createUnmuteMessage(s),a="video"===e.trackMediaType?St.UNMUTE_LOCAL_VIDEO:St.UNMUTE_LOCAL_AUDIO;await Re(this,_t.RequestP2PMuteLocal,{action:a,message:o}),t()}catch(e){i(e)}finally{n()}},this.handleUpdateVideoEncoder=async(e,t,i,n)=>{let s;"boolean"==typeof n&&n||(s=await this.sendMutex.lock("Locking from P2PChannel2.handleUpdateVideoEncoder"));try{const i=this.localTrackMap.get(ht.LocalVideoTrack);if(!this.sendConnection||!i||i.track!==e||this.state!==pt.Connected)return void t();const n=i.id,a=i.track;n&&(await this.sendConnection.updateSendParameters(n,a),await this.sendConnection.updateEncoderConfig(n,a),this.emit(_t.UpdateVideoEncoder,a)),t()}catch(e){i(e)}finally{var o;null===(o=s)||void 0===o||o()}},this.handleUpdateVideoSendParameters=async(e,t,i)=>{const n=await this.sendMutex.lock("Locking from P2PChannel2.handleUpdateVideoSendParameters");try{const i=this.localTrackMap.get(ht.LocalVideoTrack);if(!this.sendConnection||!i||i.track!==e||this.state!==pt.Connected)return void t();const s=i.id,o=i.track;s&&await this.sendConnection.updateSendParameters(s,o),t()}catch(e){i(e)}finally{n()}},this.handleReplaceTrack=async(e,t,i,s)=>{let o;N.debug("[".concat(this.store.clientId,"] P2PChannel2 handleReplaceTrack for [track-id-").concat(e.getTrackId(),"]")),"boolean"==typeof s&&s||(o=await this.sendMutex.lock("From P2PChannel2.handleReplaceTrack"));try{var a;const i=Array.from(this.localTrackMap.entries()).find((t=>{let i=Ge(t,2)[1].track;return e===i}));if(!this.sendConnection||!i||void 0===i[1].id||this.state!==pt.Connected)return void t();if(await(null===(a=this.sendConnection)||void 0===a?void 0:a.replaceTrack(e,i[1].id)),i[0]===ht.LocalVideoTrack&&n().supportDualStreamEncoding){const t=this.localTrackMap.get(ht.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=o)||void 0===r||r()}},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 Ii(e),this.bindStatsUploaderEvents(),this.sendMutex=new K("P2PChannel2-send-mutex",e.clientId),this.recvMutex=new K("P2PChannel2-recv-mutex",e.clientId),this.reconnectInterval=window.setInterval((()=>{[this.sendConnection,this.recvConnection].forEach((e=>{e&&("disconnected"!==e.iceConnectionState&&"failed"!==e.iceConnectionState||this.handleDisconnect(e.direction))}))}),M("ICE_RESTART_INTERVAL"))}async startP2PConnection(e,t){throw new j(z.NOT_SUPPORTED,"p2p mode does not support startP2PConnection.")}async connect(e){throw new j(z.NOT_SUPPORTED,"p2p mode does not support connect.")}async startP2P(e,t){let i;try{if(t){this.recvConnection&&(N.warning("[".concat(this.store.clientId,"] P2PChannel.startP2P reset recvConnection.")),this.recvConnection.close(),this.unbindConnectionEvents(this.recvConnection)),i=await this.recvMutex.lock("From P2PChannel.startP2P"),this.recvConnection=new ni(e,this.store,tt.RECEIVE_ONLY),this.bindConnectionEvents(this.recvConnection);const n=await this.recvConnection.establish(t);return{iceParameters:n.iceParameters,dtlsParameters:n.dtlsParameters,sdp:n.sdp}}{this.state=pt.New,this.sendConnection&&(N.warning("[".concat(this.store.clientId,"] P2PChannel.startP2P reset sendConnection.")),this.sendConnection.close(),this.unbindConnectionEvents(this.sendConnection)),i=await this.sendMutex.lock("From P2PChannel.startP2P"),this.sendConnection=new ni(e,this.store),this.store.peerConnectionStart(),this.bindConnectionEvents(this.sendConnection);const t=await this.sendConnection.establish();return{iceParameters:t.iceParameters,dtlsParameters:t.dtlsParameters,sdp:t.sdp}}}finally{i&&i()}}async p2pConnect(e){if(!this.sendConnection)throw new j(z.UNEXPECTED_ERROR,"Cannot P2PChannel2.p2pConnect before P2PChannel2.startP2PConnection .");this.store.peerConnectionStart(),await this.sendConnection.connect(e),this.statsUploader.startUploadTransportStats(),this.statsUploader.startUploadExtensionUsageStats(),this.state=pt.Connected}async addRemoteCandidate(e,t){if(t===tt.RECEIVE_ONLY){if(!this.sendConnection)throw new j(z.UNEXPECTED_ERROR,"Cannot P2PChannel2.connect before P2PChannel2.addRemoteCandidate .");await this.sendConnection.addRemoteCandidate(e)}else{if(!this.recvConnection)throw new j(z.UNEXPECTED_ERROR,"Cannot P2PChannel2.connect before P2PChannel2.addRemoteCandidate .");await this.recvConnection.addRemoteCandidate(e)}}publish(e,t,i){var n=this;return He((function*(){const s=yield xe(n.sendMutex.lock("From P2PChannel.publish"));try{if(!n.sendConnection||n.state!==pt.Connected){n.throwIfTrackTypeNotMatch(e);const t=e.filter((e=>-1===n.pendingLocalTracks.indexOf(e)));return void(n.pendingLocalTracks=n.pendingLocalTracks.concat(t))}n.store.pubId=n.store.pubId+1,oi.markPublishStart(n.store.clientId,n.store.pubId);const o=n.filterTobePublishedTracks(e,t,i);if(0===o.length)return void(yield xe(n.tryToUnmuteAudio(e)));o.forEach((e=>{let t=e.track,i=e.type;const s=Date.now();n.store.publish(t.getTrackId(),i===ht.LocalAudioTrack?"audio":"video",s)})),n.bindLocalTrackEvents(o);const a=yield xe(n.sendConnection.send(o.map((e=>e.track)),n.store.codec,n.store.audioCodec)),r=(yield xe(a.next())).value,c=n.createGatewayPublishMessage(o,r);try{yield c}catch(e){throw a.throw(e),(null==e?void 0:e.code)===z.WS_ABORT&&o.forEach((e=>{let t=e.track;-1===n.pendingLocalTracks.indexOf(t)&&n.pendingLocalTracks.push(t)})),n.unbindLocalTrackEvents(o),e}yield xe(a.next()),o.forEach((e=>{let t=e.type;n.statsCollector.addLocalStats(t)})),n.statsUploader.startUploadOutboundStats(),n.assignLocalTracks(o,r),o.forEach((e=>{let t=e.track,i=e.type;const s=Date.now();n.store.publish(t.getTrackId(),i===ht.LocalAudioTrack?"audio":"video",void 0,s)})),n.startUploadUplinkState()}finally{s()}}))()}async unpublish(e){if(!this.sendConnection||this.state!==pt.Connected)return void(0===e.length?this.pendingLocalTracks.length=0:this.pendingLocalTracks=this.pendingLocalTracks.filter((t=>!e.includes(t))));const t=this.filterTobeUnpublishedTracks(e);if(0===t.length)return;const i=t.find((e=>"videoLowTrack"===e[0]));if(i){i[1].track.close()}const n=this.createGatewayUnpublishMessage(t);if(await this.sendConnection.stopSending(t.map((e=>Ge(e,2)[1].id))),this.withdrawLocalTracks(t),this.unbindLocalTrackEvents(t.map((e=>{let t=Ge(e,2);return{type:t[0],track:t[1].track}}))),t.forEach((e=>{let t=Ge(e,1)[0];this.statsCollector.removeLocalStats(t)})),0===this.localTrackMap.size&&(this.statsUploader.stopUploadOutboundStats(),this.stopUploadUplinkState()),this.sendConnection&&this.state===pt.Connected){if(i){i[1].track.close()}return n}e.forEach((e=>{const t=this.pendingLocalTracks.indexOf(e);-1!==t&&this.pendingLocalTracks.splice(t,1)}))}startUploadUplinkState(){if(this.uploadUnplinkStarted)return;this.uploadUnplinkStarted=!0,this.uplinkStateUploadInterval&&window.clearInterval(this.uplinkStateUploadInterval);const e=()=>{const e=[],t=[];Array.from(this.localTrackMap.entries()).forEach((i=>{let n=Ge(i,2),s=n[0],o=n[1],a=o.track,r=o.ssrcs;const c={stream_type:$i(a,s),ssrcs:r};a._muted||!a._enabled?e.push(c):t.push(c)})),e.length>0&&e.forEach((e=>{Re(this,_t.RequestMuteLocal,[e])})),t.length>0&&t.forEach((e=>{Re(this,_t.RequestUnmuteLocal,[e])}))};e(),this.uplinkStateUploadInterval=window.setInterval((()=>{e()}),3e3)}stopUploadUplinkState(){this.uploadUnplinkStarted&&(this.uploadUnplinkStarted=!1,this.uplinkStateUploadInterval&&window.clearInterval(this.uplinkStateUploadInterval))}publishLowStream(e){return He((function*(){throw new j(z.NOT_SUPPORTED,"p2p mode does not support publishLowStream.")}))()}async republish(){this.pendingLocalTracks.length>0&&(N.debug("[".concat(this.store.clientId,"] Emit P2PChannelEvents.RequestRePublish to republish tracks.")),await Ce(this,_t.RequestRePublish,this.pendingLocalTracks),this.emit(_t.MediaReconnectEnd,this.store.uid),this.pendingLocalTracks=[])}async unpublishLowStream(){throw new j(z.NOT_SUPPORTED,"p2p mode does not support unpublishLowStream.")}async subscribe(e,t,i,n){var s;if(!this.recvConnection)throw new j(z.INVALID_OPERATION,"Cannot subscribe remote user when recvConnection disconnected.");if(null!==(s=this.remoteUserMap.get(e))&&void 0!==s&&s.has(t))return;const o=await this.recvConnection.receive(t,[{ssrcId:i}],String(e.uid),n),a=o.track,r=o.mid,c=o.transceiver;t===lt.AUDIO?(e._audioTrack?e._audioTrack._updateOriginMediaStreamTrack(a):(e._audioTrack=new T(a,e.uid,e._uintid,this.store),N.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote audio track: ").concat(e._audioTrack.getTrackId()))),c&&e._audioTrack._updateRtpTransceiver(c),this.bindRemoteTrackEvents(e,e._audioTrack)):(e._videoSSRC=i,e._videoTrack?e._videoTrack._updateOriginMediaStreamTrack(a):(e._videoTrack=new g(a,e.uid,e._uintid,this.store),N.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));const d=this.remoteUserMap.get(e);d?d.set(t,r):this.remoteUserMap.set(e,new Map([[t,r]])),this.statsCollector.addRemoteStats(e.uid),this.statsUploader.startUploadInboundStats(),this.startUploadDownlinkState();const l=this.pendingRemoteTracks.findIndex((i=>{let n=i.user,s=i.kind;return n.uid===e.uid&&t===s}));-1!==l&&(this.pendingRemoteTracks.splice(l,1),this.emit(_t.MediaReconnectEnd,e.uid))}async mockSubscribe(e,t,i,n){if(!this.recvConnection)throw new j(z.INVALID_OPERATION,"Cannot subscribe remote user when recvConnection disconnected.");await this.recvConnection.mockReceive(t,[{ssrcId:i}],String(e.uid),n)}async unsubscribe(e,t,i){const n=this.pendingRemoteTracks.filter((i=>{let n=i.user,s=i.kind;return void 0!==t?n.uid===e.uid&&t===s:n.uid===e.uid}));if(n.forEach((e=>{const t=this.pendingRemoteTracks.indexOf(e);this.pendingRemoteTracks.splice(t,1)})),this.recvConnection||i||n.forEach((t=>{let i=t.kind;var n;if(i===lt.AUDIO)null===(n=e._audioTrack)||void 0===n||n._destroy(),e._audioTrack=void 0;else if(i===lt.VIDEO){var s;null===(s=e._videoTrack)||void 0===s||s._destroy(),e._videoTrack=void 0}})),!this.recvConnection)return;const s=this.filterTobeUnSubscribedTracks(e,t);0!==s.length&&(await this.recvConnection.stopReceiving(s.map((e=>Ge(e,2)[1].id))),this.withdrawRemoteTracks(s),0===this.remoteUserMap.size&&(this.statsUploader.stopUploadInboundStats(),this.stopUploadDownlinkState()),s.forEach((e=>{let t=Ge(e,2),n=t[0],s=t[1].kind;var o,a;s===lt.VIDEO&&n._videoSSRC&&(null===(o=this.recvConnection)||void 0===o||o.setStatsRemoteVideoIsReady(n._videoSSRC,!1));if(s===lt.VIDEO)this.unbindRemoteTrackEvents(n._videoTrack),i||(null===(a=n._videoTrack)||void 0===a||a._destroy(),n._videoTrack=void 0);else if(s===lt.AUDIO){var r;if(this.unbindRemoteTrackEvents(n._audioTrack),!i)null===(r=n._audioTrack)||void 0===r||r._destroy(),n._audioTrack=void 0}})),s.forEach((e=>{let t=Ge(e,2)[1].kind;Re(this,_t.RequestP2PMuteRemote,t)})))}startUploadDownlinkState(){if(this.uploadDownlinkStarted)return;this.uploadDownlinkStarted=!0,this.downlinkStatsUploadInterval&&window.clearInterval(this.downlinkStatsUploadInterval);const e=()=>Array.from(this.remoteUserMap.entries()).forEach((e=>{let t=Ge(e,2)[1];[lt.VIDEO,lt.AUDIO].forEach((e=>{t.has(e)?Re(this,_t.RequestP2PUnmuteRemote,e):Re(this,_t.RequestP2PMuteRemote,e)}))}));e(),this.downlinkStatsUploadInterval=window.setInterval((()=>{e()}),3e3)}stopUploadDownlinkState(){this.uploadDownlinkStarted&&(this.uploadDownlinkStarted=!1,this.downlinkStatsUploadInterval&&window.clearInterval(this.downlinkStatsUploadInterval))}getAllDataChannels(){return this.localDataChannels}async massSubscribe(e){throw new j(z.NOT_SUPPORTED,"p2p mode does not support massSubscribe.")}async massSubscribeNoLock(e){throw new j(z.NOT_SUPPORTED,"p2p mode does not support massSubscribeNoLock.")}async massUnsubscribe(e){throw new j(z.NOT_SUPPORTED,"p2p mode does not support massUnsubscribe.")}async massUnsubscribeNoLock(e){throw new j(z.NOT_SUPPORTED,"p2p mode does not support massUnsubscribeNoLock.")}async muteRemote(e,t){if(!this.recvConnection)return;const i=this.remoteUserMap.get(e);if(!i)return void N.warning("[".concat(this.store.clientId,"] P2PChannel2.muteRemote has no remote user ").concat(e.uid,"."));if(!i.get(t))return void N.warning("[".concat(this.store.clientId,"] P2PChannel2.muteRemote has no remote user ").concat(e.uid," media type ").concat(t,"."));const n=t===lt.VIDEO?e._videoSSRC:e._audioSSRC;void 0!==n&&this.recvConnection.setStatsRemoteVideoIsReady(n,!1)}async unmuteRemote(e,t){return this.unmuteRemoteNoLock(e,t)}async unmuteRemoteNoLock(e,t){if(!this.recvConnection)return;const i=this.remoteUserMap.get(e);if(!i)return void N.warning("[".concat(this.store.clientId,"] P2PChannel2.unmuteRemote has no remote user ").concat(e.uid,"."));i.get(t)||N.warning("[".concat(this.store.clientId,"] P2PChannel2.unmuteRemote has no remote user ").concat(e.uid," media type ").concat(t,"."))}getAllTracks(e){const t=this.localTrackMap.get(ht.LocalAudioTrack);if((null==t?void 0:t.track)instanceof a){const i=t.track;return Array.from(this.localTrackMap.entries()).filter((e=>Ge(e,1)[0]!==ht.LocalAudioTrack)).filter((t=>{let i=Ge(t,1)[0];return!(e&&i===ht.LocalVideoLowTrack)})).map((e=>Ge(e,2)[1].track)).concat(i.trackList)}return Array.from(this.localTrackMap.entries()).filter((t=>{let i=Ge(t,1)[0];return!(e&&i===ht.LocalVideoLowTrack)})).map((e=>Ge(e,2)[1].track))}reportPublishEvent(t,n,o,a,r){if(t){const e=this.localTrackMap.get(ht.LocalAudioTrack),i=a?this.localTrackMap.get(ht.LocalVideoLowTrack):this.localTrackMap.get(ht.LocalVideoTrack);y.publish(this.store.sessionId,{eventElapse:oi.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:t,ec:n,audioName:null==e?void 0:e.track.getTrackLabel(),videoName:null==i?void 0:i.track.getTrackLabel(),screenshare:-1!==(null==i?void 0:i.track._hints.indexOf(s.SCREEN_TRACK)),audio:!!e,video:!!i,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r})}else{var c;o||(o=[]);const d=o.find((t=>t instanceof e)),l=a?null===(c=this.localTrackMap.get(ht.LocalVideoTrack))||void 0===c?void 0:c.track:o.find((e=>e instanceof i));y.publish(this.store.sessionId,{eventElapse:oi.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:t,ec:n,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 s=n===lt.VIDEO?i._videoSSRC:i._audioSSRC;s&&y.subscribe(this.store.sessionId,{succ:e,ec:t,video:n===lt.VIDEO,audio:n===lt.AUDIO,peerid:i.uid,subscribeRequestid:n===lt.VIDEO?i._videoSSRC:i._audioSSRC,p2pid:this.store.p2pId,eventElapse:oi.measureFromSubscribeStart(this.store.clientId,s)})}reset(){N.debug("[".concat(this.store.clientId,"] P2PChannel2.reset")),this.sendMutex=new K("P2PChannel2-send-mutex",this.store.clientId),this.sendMutex=new K("P2PChannel2-recv-mutex",this.store.clientId),this.sendConnection&&(this.sendConnection.close(),this.unbindConnectionEvents(this.sendConnection),this.sendConnection=void 0),this.recvConnection&&(this.recvConnection.close(),this.unbindConnectionEvents(this.recvConnection),this.recvConnection=void 0),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),this.statsUploader.stopUploadExtensionUsageStats(),this.stopUploadUplinkState(),this.stopUploadDownlinkState(),this.unbindLocalTrackEvents(),this.unbindAllRemoteTrackEvents(),this.unbindRtpTransceiver();const e=this.localTrackMap.get(ht.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.dtlsFailedCount=0,this.pendingLocalTracks=[],this.pendingRemoteTracks=[],this.reconnectInterval&&(window.clearInterval(this.reconnectInterval),this.reconnectInterval=void 0),this.state=pt.Disconnected}getStats(e){var t,i;return e?null===(i=this.recvConnection)||void 0===i?void 0:i.getStats():null===(t=this.sendConnection)||void 0===t?void 0:t.getStats()}getRemoteVideoIsReady(e){var t;return(null===(t=this.recvConnection)||void 0===t?void 0:t.getRemoteVideoIsReady(e))||!1}getLocalAudioVolume(){const e=this.localTrackMap.get(ht.LocalAudioTrack);if(e)return e.track.getVolumeLevel()}getLocalVideoSize(){const e=this.localTrackMap.get(ht.LocalVideoTrack);if(e)return{width:e.track.videoWidth||0,height:e.track.videoHeight||0}}getEncoderConfig(t){const n=this.localTrackMap.get(t);return n&&n.track instanceof i||n&&n.track instanceof e?n.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=Ge(e,1)[0];return{uid:t.uid,level:t.audioTrack?100*t.audioTrack._source.getAccurateVolumeLevel():0}}));const t=this.localTrackMap.get(ht.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.sendConnection&&this.recvConnection&&(N.debug("[".concat(this.store.clientId,"] P2PChannel2.disconnectForReconnect closing P2PConnection")),this.state=pt.Reconnecting,M("KEEP_LAST_FRAME")&&0!==this.remoteUserMap.size&&Array.from(this.remoteUserMap.entries()).forEach((e=>{let t=Ge(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.sendConnection.close(),this.unbindConnectionEvents(this.sendConnection),this.sendConnection=void 0,this.recvConnection.close(),this.unbindConnectionEvents(this.recvConnection),this.recvConnection=void 0,0!==this.localTrackMap.size&&(Array.from(this.localTrackMap.entries()).forEach((e=>{let t=Ge(e,2),i=t[0],n=t[1].track;switch(i){case ht.LocalVideoTrack:n._hints.includes(s.LOW_STREAM)?n.close():this.pendingLocalTracks.push(n);break;case ht.LocalAudioTrack:n instanceof a?this.pendingLocalTracks=this.pendingLocalTracks.concat(n.trackList):this.pendingLocalTracks.push(n);case ht.LocalVideoLowTrack:}})),this.emit(_t.MediaReconnectStart,this.store.uid)),this.unbindLocalTrackEvents(),this.localTrackMap.clear(),0!==this.remoteUserMap.size&&Array.from(this.remoteUserMap.entries()).forEach((e=>{let t=Ge(e,2),i=t[0],n=t[1];Array.from(n.keys()).forEach((e=>{this.setPendingRemoteMedia(i,e)})),this.emit(_t.MediaReconnectStart,i.uid)})),this.unbindAllRemoteTrackEvents(),this.remoteUserMap.clear(),this.stopUploadUplinkState(),this.stopUploadDownlinkState(),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),N.debug("[".concat(this.store.clientId,"] P2PChannel2 disconnected, waiting to reconnect.")))}hasPendingRemoteMedia(e,t){for(const i of this.pendingRemoteTracks){const n=i.user,s=i.kind;if((e instanceof Ai?e.uid:e)===n.uid&&t===s)return!0}return!1}setPendingRemoteMedia(e,t){this.hasPendingRemoteMedia(e,t)||this.pendingRemoteTracks.push({user:e,kind:t})}async restartICE(e,t){let i,n;if(e===tt.SEND_ONLY){if(!this.sendConnection)throw new j(z.INVALID_OPERATION,"Cannot call P2PChannel2.handleMuteLocalTrack before sendConnection established.");i=await this.sendMutex.lock("From P2PChannel.restartICE"),n=this.sendConnection}else{if(!this.recvConnection)throw new j(z.INVALID_OPERATION,"Cannot call P2PChannel2.handleMuteLocalTrack before recvConnection established.");i=await this.recvMutex.lock("From P2PChannel.restartICE"),n=this.recvConnection}try{if(t){const e=await n.restartICE(t);return n.isInRestartIce=!1,e}{const e=await n.restartICE();if(e){const t=await Ce(this,_t.RequestP2PRestartICE,{direction:tt.RECEIVE_ONLY,iceParameter:e});await n.restartICE(t),n.isInRestartIce=!1}}}finally{i()}}getUplinkNetworkQuality(){if(!this.sendConnection)return 0;const e=this.sendConnection.getStats(),t=this.localTrackMap.get(ht.LocalVideoTrack),i=this.localTrackMap.get(ht.LocalAudioTrack),n=e.videoSend.find((e=>{var i;return e.ssrc===(null==t||null===(i=t.ssrcs)||void 0===i?void 0:i[0].ssrcId)})),o=e.audioSend.find((e=>{var t;return e.ssrc===(null==i||null===(t=i.ssrcs)||void 0===t?void 0:t[0].ssrcId)}));if(!n||!o)return 1;const a=fe(this,_t.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,u=100*e.sendPacketLossRate*.7/50+.3*l/1500,h=u<.17?1:u<.36?2:u<.59?3:u<.1?4:5,p=null==t?void 0:t.track;if(p&&p._encoderConfig&&-1===p._hints.indexOf(s.SCREEN_TRACK)){const t=p._encoderConfig.bitrateMax,i=e.bitrate.actualEncoded;if(t&&i){const e=(1e3*t-i)/(1e3*t);return ot[e<.15?0:e<.3?1:e<.45?2:e<.6?3:4][h]}}return h}getDownlinkNetworkQuality(){if(!this.recvConnection)return 0;const e=this.recvConnection.getStats();let t=0;return Array.from(this.remoteUserMap.entries()).forEach((i=>{let n=Ge(i,1)[0];const s=n._audioSSRC,o=n._videoSSRC,a=e.audioRecv.find((e=>e.ssrc===s)),r=e.videoRecv.find((e=>e.ssrc===o));if(!a&&!r)return void(t+=1);const c=fe(this,_t.NeedSignalRTT),d=e.rtt,l=(d&&c?(d+c)/2:d||c)||0,u=a?a.jitterMs:void 0,h=e.recvPacketLossRate;let p=.7*h*100/50+.3*l/1500;u&&(p=.6*h*100/50+.2*l/1500+.2*u/400);t+=p<.1?1:p<.17?2:p<.36?3:p<.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)}))}filterTobePublishedTracks(t,s,o){const r=[],c=n(),d=this.getAllTracks();t=t.filter((e=>-1===d.indexOf(e))),t=ve(t);let l=!1,u=!1;for(const n of t){if(n instanceof i&&(this.localTrackMap.has(ht.LocalVideoTrack)||l?new j(z.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS).throw():(r.push({track:n,type:ht.LocalVideoTrack}),l=!0),s)){const e=this.getLowVideoTrack(n,o);r.push({track:e,type:ht.LocalVideoLowTrack})}if(n instanceof e){const e=this.localTrackMap.get(ht.LocalAudioTrack);if(e){if(!(e.track instanceof a))throw new j(z.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser does not support audio mixing");if(n._bypassWebAudio)throw new j(z.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio");e.track.addAudioTrack(n),this.bindLocalAudioTrackEvents(n,!0)}else if(u){const e=r.find((e=>e.type===ht.LocalAudioTrack));if(!(e.track instanceof a))throw new j(z.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser does not support audio mixing");if(n._bypassWebAudio)throw new j(z.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio");e.track.addAudioTrack(n)}else{if(!c.webAudioMediaStreamDest||n instanceof a||n._bypassWebAudio)r.push({track:n,type:ht.LocalAudioTrack});else{const e=new a;e.addAudioTrack(n),r.push({track:e,type:ht.LocalAudioTrack})}u=!0}}}return r}filterTobeUnpublishedTracks(t){const n=[],s=this.getAllTracks();t=t.filter((e=>-1!==s.indexOf(e))),t=ve(t);for(const s of t){if(s instanceof e){const e=this.localTrackMap.get(ht.LocalAudioTrack);if(!e)continue;e.track instanceof a?(e.track.removeAudioTrack(s),this.unbindLocalAudioTrackEvents(s),0===e.track.trackList.length&&(n.push([ht.LocalAudioTrack,e]),e.track.close())):n.push([ht.LocalAudioTrack,e])}if(s instanceof i){const e=this.localTrackMap.get(ht.LocalVideoTrack);if(!e)continue;n.push([ht.LocalVideoTrack,e]);const t=this.localTrackMap.get(ht.LocalVideoLowTrack);t&&n.push([ht.LocalVideoLowTrack,t])}}return n}bindLocalTrackEvents(e){e.forEach((e=>{let t=e.track;switch(e.type){case ht.LocalVideoTrack:t.addListener(I.GET_STATS,this.handleGetLocalVideoStats),t.addListener(I.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.addListener(I.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.addListener(I.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.addListener(I.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this.handleUpdateVideoSendParameters),t.addListener(I.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.addListener(I.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.addListener(I.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case ht.LocalAudioTrack:this.bindLocalAudioTrackEvents(t);case ht.LocalVideoLowTrack:}}))}bindLocalAudioTrackEvents(e,t){e instanceof a?e.trackList.forEach((e=>{e.addListener(I.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(I.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(I.GET_STATS,this.handleGetLocalAudioStats),e.addListener(I.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(I.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)})):(e.addListener(I.GET_STATS,this.handleGetLocalAudioStats),e.addListener(I.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(I.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(I.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(I.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack),t||e.addListener(I.NEED_REPLACE_TRACK,this.handleReplaceTrack))}unbindLocalTrackEvents(e){e||(e=Array.from(this.localTrackMap.entries()).map((e=>{let t=Ge(e,2),i=t[0];return{track:t[1].track,type:i}}))),e.forEach((e=>{let t=e.track;switch(e.type){case ht.LocalVideoTrack:t.off(I.GET_STATS,this.handleGetLocalVideoStats),t.off(I.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.off(I.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.off(I.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.off(I.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this.handleUpdateVideoSendParameters),t.off(I.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.off(I.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.off(I.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case ht.LocalAudioTrack:this.unbindLocalAudioTrackEvents(t);case ht.LocalVideoLowTrack:}}))}unbindLocalAudioTrackEvents(e){e instanceof a?e.trackList.forEach((e=>{e.off(I.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(I.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(I.GET_STATS,this.handleGetLocalAudioStats),e.off(I.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(I.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)})):(e.off(I.GET_STATS,this.handleGetLocalAudioStats),e.off(I.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(I.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(I.NEED_REPLACE_TRACK,this.handleReplaceTrack),e.off(I.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(I.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack))}bindRemoteTrackEvents(e,t){t instanceof g&&t.addListener(I.GET_STATS,(t=>{t(this.handleGetRemoteVideoStats(e))})),t instanceof T&&t.addListener(I.GET_STATS,(t=>{t(this.handleGetRemoteAudioStats(e))}))}unbindRemoteTrackEvents(e){e&&e.removeAllListeners(I.GET_STATS)}unbindAllRemoteTrackEvents(){Array.from(this.remoteUserMap.entries()).forEach((e=>{let t=Ge(e,2),i=t[0],n=t[1];n.has(lt.AUDIO)&&this.unbindRemoteTrackEvents(i._audioTrack),n.has(lt.VIDEO)&&this.unbindRemoteTrackEvents(i._videoTrack)}))}createGatewayPublishMessage(e,t){return e.map(((e,i)=>{let n,o=e.track,a=e.type;switch(a){case ht.LocalAudioTrack:n=nt.Audio;break;case ht.LocalVideoTrack:n=o._hints.includes(s.SCREEN_TRACK)?nt.Screen:nt.High;break;case ht.LocalVideoLowTrack:n=nt.Low}return{kind:a===ht.LocalAudioTrack?lt.AUDIO:lt.VIDEO,stream_type:n,mid:t[i].id,ssrcs:t[i].localSSRC,isMuted:o.muted||!o.enabled}}))}createGatewayUnpublishMessage(e){return e.map((e=>{let t,i=Ge(e,2),n=i[0],o=i[1],a=o.track,r=o.ssrcs,c=o.id;switch(n){case ht.LocalVideoTrack:t=a._hints.includes(s.SCREEN_TRACK)?nt.Screen:nt.High;break;case ht.LocalAudioTrack:t=nt.Audio;break;case ht.LocalVideoLowTrack:t=nt.Low}return{stream_type:t,ssrcs:r,mid:c}}))}assignLocalTracks(e,t){e.forEach(((e,i)=>{let n=e.track,s=e.type;this.localTrackMap.set(s,{track:n,id:t[i].id,ssrcs:t[i].localSSRC})}))}withdrawLocalTracks(e){e.forEach((e=>{let t=Ge(e,1)[0];this.localTrackMap.delete(t)}))}bindConnectionEvents(e){e.onConnectionStateChange=async t=>{N.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: ").concat(e.name,".onConnectionStateChange(").concat(t,")")),this.emit(_t.PeerConnectionStateChange,t),"connected"!==t||this.store.keyMetrics.peerConnectionEnd||this.store.peerConnectionEnd(),"connected"===t&&(e.isInRestartIce=!1),this._restartStates.includes(t)&&!e.isInRestartIce&&("disconnected"===t&&await Te(800),"disconnected"!==e.iceConnectionState&&"failed"!==e.iceConnectionState||this.handleDisconnect(e.direction))},e.onICEConnectionStateChange=e=>{"connected"!==e||this.store.keyMetrics.iceConnectionEnd||this.store.iceConnectionEnd(),N.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICEConnectionStateChange(").concat(e,")")),y.reportApiInvoke(this.store.sessionId,{name:"ICEConnectionStateChange",options:e,tag:Se.TRACER}).onSuccess(),this.emit(_t.IceConnectionStateChange,e)},e.onICETransportStateChange=e=>{N.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICETransportStateChange(").concat(e,")"))},e.onDTLSTransportStateChange=e=>{N.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportStateChange(").concat(e,")"))},e.onDTLSTransportError=e=>{N.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),y.firstRemoteFrame(this.store.sessionId,O.FIRST_AUDIO_DECODE,w.FIRST_AUDIO_DECODE,{peer:t._uintid,subscribeElapse:oi.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&&y.firstRemoteFrame(this.store.sessionId,O.FIRST_AUDIO_RECEIVED,w.FIRST_AUDIO_RECEIVED,{peer:t._uintid,subscribeElapse:oi.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId})},e.onFirstVideoDecoded=(e,t,i)=>{this.reportVideoFirstFrameDecoded(e,t,i)},e.onFirstVideoReceived=e=>{const t=Array.from(this.remoteUserMap.keys()).find((t=>t._videoSSRC===e));t&&y.firstRemoteFrame(this.store.sessionId,O.FIRST_VIDEO_RECEIVED,w.FIRST_VIDEO_RECEIVED,{peer:t._uintid,subscribeElapse:oi.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId})},e.onSelectedLocalCandidateChanged=(e,t)=>{const i="relay"===e.candidateType,n="relay"===t.candidateType;"unknown"!==t.candidateType&&i===n||this.emit(_t.ConnectionTypeChange,i),N.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedLocalCandidateChanged(").concat(JSON.stringify(It(t))," -> ").concat(JSON.stringify(It(e)),")"))},e.onSelectedRemoteCandidateChanged=(e,t)=>{N.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedRemoteCandidateChanged(").concat(JSON.stringify(It(t))," -> ").concat(JSON.stringify(It(e)),")"))},e.onFirstVideoDecodedTimeout=e=>{this.reportVideoFirstFrameDecoded(e,void 0,void 0,!0)},e.onLocalCandidate=t=>{this.emit(_t.LocalCandidate,{candidate:t,direction:e.direction})}}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,e.onLocalCandidate=void 0}async handleDisconnect(e){const t=e===tt.SEND_ONLY?this.sendConnection:this.recvConnection;t&&!t.isInRestartIce&&(t.isInRestartIce=!0,N.debug("[".concat(this.store.clientId,"] [P2PChannel-").concat(t.name,"] start use restartICE")),e===tt.SEND_ONLY?this.restartICE(e):Ce(this,_t.RequestP2PRestartICE,{direction:tt.SEND_ONLY}))}filterTobeMutedTracks(t){const i=[];if(-1===this.getAllTracks().indexOf(t))return i;const n=this.localTrackMap.get(ht.LocalAudioTrack);if(t instanceof e&&(null==n?void 0:n.track)instanceof a)return n.track.isActive||i.push([ht.LocalAudioTrack,n]),i;const s=Array.from(this.localTrackMap.entries()).find((e=>{let i=Ge(e,2)[1].track;return t===i}));if(s&&(i.push(s),s[0]===ht.LocalVideoTrack)){const e=this.localTrackMap.get(ht.LocalVideoLowTrack);e&&i.push([ht.LocalVideoLowTrack,e])}return i}filterTobeUnmutedTracks(t){const i=[],n=this.localTrackMap.get(ht.LocalAudioTrack);if(t instanceof e&&(null==n?void 0:n.track)instanceof a)return n.track.isActive&&i.push([ht.LocalAudioTrack,n]),i;const s=Array.from(this.localTrackMap.entries()).find((e=>{let i=Ge(e,2)[1].track;return t===i}));if(s)if(s[0]===ht.LocalVideoTrack){i.push(s);const e=this.localTrackMap.get(ht.LocalVideoLowTrack);e&&i.push([ht.LocalVideoLowTrack,e])}else i.push(s);return i}createMuteMessage(e){return e.map((e=>{let t,i=Ge(e,2),n=i[0],o=i[1],a=o.track,r=o.ssrcs,c=o.id;switch(n){case ht.LocalAudioTrack:t=nt.Audio;break;case ht.LocalVideoTrack:t=a._hints.includes(s.SCREEN_TRACK)?nt.Screen:nt.High;break;case ht.LocalVideoLowTrack:t=nt.Low}return{stream_type:t,ssrcs:r,mid:c}}))}createUnmuteMessage(e){return e.map((e=>{let t,i=Ge(e,2),n=i[0],o=i[1],a=o.track,r=o.ssrcs,c=o.id;switch(n){case ht.LocalAudioTrack:t=nt.Audio;break;case ht.LocalVideoTrack:t=a._hints.includes(s.SCREEN_TRACK)?nt.Screen:nt.High;break;case ht.LocalVideoLowTrack:t=nt.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 s=n.get(t);if(!s)return i;i.push([e,{kind:t,id:s}])}else Array.from(n.entries()).forEach((t=>{let n=Ge(t,2),s=n[0],o=n[1];i.push([e,{kind:s,id:o}])}));return i}createUnsubscribeMessage(e){const t=[];return e.forEach((e=>{let i=Ge(e,2),n=i[0],s=i[1],o=s.kind;switch(s.id,o){case lt.VIDEO:return void(n._videoSSRC&&t.push({stream_type:lt.VIDEO,ssrcId:n._videoSSRC}));case lt.AUDIO:return void(n._audioSSRC&&t.push({stream_type:lt.AUDIO,ssrcId:n._audioSSRC}))}})),t}withdrawRemoteTracks(e){e.forEach((e=>{let t=Ge(e,2),i=t[0],n=t[1].kind;const s=this.remoteUserMap.get(i);s&&(s.delete(n),0===Array.from(s.entries()).length&&this.remoteUserMap.delete(i))}))}async updateBitrateLimit(e){const t=this.localTrackMap.get(ht.LocalVideoTrack),i=this.localTrackMap.get(ht.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.sendConnection&&this.recvConnection){const e=this.sendConnection.peerConnectionState,t=this.recvConnection.peerConnectionState;return"connected"!==e&&"connected"!==t}return!0}async tryToUnmuteAudio(t){for(let i=0;i<t.length;i++)if(t[i]instanceof e){const e=this.filterTobeUnmutedTracks(t[i]);if(0===e.length)continue;const n=this.createUnmuteMessage(e);return void await Re(this,_t.RequestUnmuteLocal,n)}}bindStatsUploaderEvents(){this.statsUploader.requestStats=e=>this.getStats(e),this.statsUploader.requestLocalMedia=()=>Array.from(this.localTrackMap.entries()).filter((e=>!!Ge(e,2)[1].ssrcs)),this.statsUploader.requestRemoteMedia=()=>Array.from(this.remoteUserMap.entries()),this.statsUploader.requestVideoIsReady=e=>{var t;return!(null===(t=this.recvConnection)||void 0===t||!t.getRemoteVideoIsReady(e))},this.statsUploader.requestUpload=(e,t)=>this.emit(_t.RequestUpload,e,t),this.statsUploader.requestUploadStats=e=>this.emit(_t.RequestUploadStats,e),this.statsUploader.requestAllTracks=()=>this.getAllTracks()}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 Te(ge(this.dtlsFailedCount,Ie)),this.emit(_t.RequestReconnect)}async reconnectP2P(){}canPublishLowStream(){return this.localTrackMap.has(ht.LocalVideoTrack)||this.pendingLocalTracks.some((e=>e instanceof i))}throwIfTrackTypeNotMatch(t){if(t.filter((e=>e instanceof i)).length>1)throw new j(z.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(t.filter((t=>t instanceof e)).length>1&&(t.some((t=>t instanceof e&&t._bypassWebAudio))||!n().webAudioMediaStreamDest))throw new j(z.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode");for(const s of t){if(s instanceof i&&this.pendingLocalTracks.some((e=>e instanceof i)))throw new j(z.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(s instanceof e&&this.pendingLocalTracks.some((t=>t instanceof e))&&(!n().webAudioMediaStreamDest||s._bypassWebAudio||this.pendingLocalTracks.some((t=>t instanceof e&&t._bypassWebAudio))))throw new j(z.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode")}}getLowVideoTrack(e,t){const a=!M("DISABLE_DUAL_STREAM_USE_ENCODING")&&n().supportDualStreamEncoding,r=We(We({},{width:160,height:120,framerate:15,bitrate:50}),t);let c;c=a?e._mediaStreamTrack.clone():function(e,t){let i=document.createElement("video"),s=document.createElement("canvas");i.setAttribute("style","display:none"),s.setAttribute("style","display:none"),i.setAttribute("muted",""),i.muted=!0,i.setAttribute("autoplay",""),i.autoplay=!0,i.setAttribute("playsinline",""),s.width=vt(t.width),s.height=vt(t.height);const a=vt(t.framerate||15);document.body.append(i),document.body.append(s);let r=e._mediaStreamTrack;i.srcObject=new MediaStream([r]),i.play().catch($);const c=s.getContext("2d");if(!c)throw new L(z.UNEXPECTED_ERROR,"can not get canvas context");const d=n(),l=s.captureStream(d.supportRequestFrame?0:a).getVideoTracks()[0];l.canvas||(l.canvas=s),s.startCapture=()=>{if(!i)return s.stopCapture&&s.stopCapture();if(i.paused&&i.play(),i.videoHeight>2&&i.videoWidth>2){const e=i.videoWidth,t=i.videoHeight/e,n=s.width*t;Math.abs(n-s.height)>=2&&(N.debug("adjust low stream resolution","".concat(s.width,"x").concat(s.height," -> ").concat(s.width,"x").concat(n)),s.height=n)}c.drawImage(i,0,0,s.width,s.height),l.requestFrame&&l.requestFrame(),r!==e._mediaStreamTrack&&(r=e._mediaStreamTrack,i.srcObject=new MediaStream([r]))},s.stopCapture=o((()=>s.startCapture&&s.startCapture()),a);const u=l.stop;return l.stop=()=>{u.call(l),i&&(i.remove(),i.srcObject=null,i=null),s&&(s.width=0,s.remove(),s.stopCapture&&s.stopCapture(),s.startCapture=void 0,s.stopCapture=void 0,s=null),N.debug("clean low stream renderer")},l}(e,r);const d=W(8,"track-low-"),l=new i(c,We(We({},a&&{scaleResolutionDownBy:gt(r,e)}),{},{frameRate:r.framerate,bitrateMax:r.bitrate,bitrateMin:r.bitrate}),void 0,void 0,d);return l.on(D.TRANSCEIVER_UPDATED,(t=>{e._updateRtpTransceiver(t,P.LOW_STREAM)})),l._hints.push(s.LOW_STREAM),e.addListener(I.NEED_CLOSE,(()=>{l.close()})),l}async globalLock(){return this.recvMutex.lock("From P2PChannel2.globalLock")}reportVideoFirstFrameDecoded(e,t,i,n){const s=Array.from(this.remoteUserMap.keys()).find((t=>t._videoSSRC===e));if(s){n||this.store.subscribe(s.uid,"video",void 0,void 0,void 0,void 0,Date.now());const o=this.store.keyMetrics,a=o.subscribe.find((e=>e.userId===s.uid&&"video"===e.type));y.firstRemoteVideoDecode(this.store.sessionId,O.FIRST_VIDEO_DECODE,w.FIRST_VIDEO_DECODE,{peer:s._uintid,videowidth:t,videoheight:i,subscribeElapse:oi.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId,apEnd:o.requestAPEnd||0,apStart:o.requestAPStart||0,joinGwEnd:o.joinGatewayEnd||0,joinGwStart:o.joinGatewayStart||0,pcEnd:o.peerConnectionEnd||0,pcStart:o.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})}}async remoteMediaSsrcChanged(e,t,i){if(!this.recvConnection)return!1;const n=this.remoteUserMap.get(e);if(!n)return!1;const s=n.get(t);if(!s)return!1;const o=await this.recvConnection.getRemoteSSRC(s);return void 0!==o&&o!==i}isPreSubScribe(e){return!1}async publishDataChannel(e){throw new j(z.NOT_SUPPORTED)}async unpublishDataChannel(e){throw new j(z.NOT_SUPPORTED)}async subscribeDataChannel(e,t){throw new j(z.NOT_SUPPORTED)}async unsubscribeDataChannel(e,t){throw new j(z.NOT_SUPPORTED)}hasPendingRemoteDataChannel(e,t){throw new j(z.NOT_SUPPORTED)}setPendingRemoteDataChannel(e,t){throw new j(z.NOT_SUPPORTED)}async preConnect(e){throw new j(z.NOT_SUPPORTED)}getEstablishParams(){throw new j(z.NOT_SUPPORTED)}async reSubscribe(e){throw new j(z.NOT_SUPPORTED)}reportVideoFirstFrameRender(e){}async updateVideoStreamParameter(e,t){throw new j(z.NOT_SUPPORTED)}unbindRtpTransceiver(){0!==this.localTrackMap.size&&Array.from(this.localTrackMap.entries()).forEach((e=>{let t=Ge(e,2),i=t[0],n=t[1].track;i===ht.LocalVideoLowTrack?n._updateRtpTransceiver(void 0,P.LOW_STREAM):n._updateRtpTransceiver(void 0)}))}},Ue(hn.prototype,"p2pConnect",[en],Object.getOwnPropertyDescriptor(hn.prototype,"p2pConnect"),hn.prototype),Ue(hn.prototype,"unpublish",[tn],Object.getOwnPropertyDescriptor(hn.prototype,"unpublish"),hn.prototype),Ue(hn.prototype,"unpublishLowStream",[nn],Object.getOwnPropertyDescriptor(hn.prototype,"unpublishLowStream"),hn.prototype),Ue(hn.prototype,"subscribe",[sn],Object.getOwnPropertyDescriptor(hn.prototype,"subscribe"),hn.prototype),Ue(hn.prototype,"mockSubscribe",[on],Object.getOwnPropertyDescriptor(hn.prototype,"mockSubscribe"),hn.prototype),Ue(hn.prototype,"unsubscribe",[an],Object.getOwnPropertyDescriptor(hn.prototype,"unsubscribe"),hn.prototype),Ue(hn.prototype,"muteRemote",[rn],Object.getOwnPropertyDescriptor(hn.prototype,"muteRemote"),hn.prototype),Ue(hn.prototype,"unmuteRemote",[cn],Object.getOwnPropertyDescriptor(hn.prototype,"unmuteRemote"),hn.prototype),Ue(hn.prototype,"hasRemoteMediaWithLock",[dn],Object.getOwnPropertyDescriptor(hn.prototype,"hasRemoteMediaWithLock"),hn.prototype),Ue(hn.prototype,"disconnectForReconnect",[ln],Object.getOwnPropertyDescriptor(hn.prototype,"disconnectForReconnect"),hn.prototype),Ue(hn.prototype,"remoteMediaSsrcChanged",[un],Object.getOwnPropertyDescriptor(hn.prototype,"remoteMediaSsrcChanged"),hn.prototype),hn);function _n(e){return function(t,i,n){const s=t[i];if("function"!=typeof s)throw new Error("Cannot use mutex on object property.");return n.value=async function(){for(var t=arguments.length,n=new Array(t),o=0;o<t;o++)n[o]=arguments[o];switch(e){case Di.SEND_ONLY:{const e=await this.sendMutex.lock("From P2PChannel2.".concat(i));try{return await s.apply(this,n)}finally{e()}}case Di.RECEIVE_ONLY:{const e=await this.recvMutex.lock("From P2PChannel2.".concat(i));try{return await s.apply(this,n)}finally{e()}}default:{const e=await this.sendMutex.lock("From P2PChannel2.".concat(i)),t=await this.recvMutex.lock("From P2PChannel2.".concat(i));try{return await s.apply(this,n)}finally{e(),t()}}}},n}}Ke.ACCESS_POINT,ze.NO_FLAG_SET,ze.FLAG_SET_BUT_EMPTY,ze.INVALID_FALG_SET,ze.FLAG_SET_BUT_NO_RE,ze.INVALID_SERVICE_ID,ze.NO_SERVICE_AVAILABLE,ze.NO_SERVICE_AVAILABLE_P2P,ze.NO_SERVICE_AVAILABLE_VOICE,ze.NO_SERVICE_AVAILABLE_WEBRTC,ze.NO_SERVICE_AVAILABLE_CDS,ze.NO_SERVICE_AVAILABLE_CDN,ze.NO_SERVICE_AVAILABLE_TDS,ze.NO_SERVICE_AVAILABLE_REPORT,ze.NO_SERVICE_AVAILABLE_APP_CENTER,ze.NO_SERVICE_AVAILABLE_ENV0,ze.NO_SERVICE_AVAILABLE_VOET,ze.NO_SERVICE_AVAILABLE_STRING_UID,ze.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS,Ke.UNILBS,je.INVALID_VENDOR_KEY,je.INVALID_CHANNEL_NAME,je.INTERNAL_ERROR,je.NO_AUTHORIZED,je.DYNAMIC_KEY_TIMEOUT,je.NO_ACTIVE_STATUS,je.DYNAMIC_KEY_EXPIRED,je.STATIC_USE_DYNAMIC_KEY,je.DYNAMIC_USE_STATIC_KEY,je.USER_OVERLOAD,je.FORBIDDEN_REGION,je.CANNOT_MEET_AREA_DEMAND,je.REQ_DOWNGRADE_FALLBACK,Ke.STRING_UID_ALLOCATOR,qe.IIIEGAL_APPID,qe.IIIEGAL_UID,qe.INTERNAL_ERROR;const En={[Je.K_TIMESTAMP_EXPIRED]:{desc:"K_TIMESTAMP_EXPIRED",action:"failed"},[Je.K_CHANNEL_PERMISSION_INVALID]:{desc:"K_CHANNEL_PERMISSION_INVALID",action:"failed"},[Je.K_CERTIFICATE_INVALID]:{desc:"K_CERTIFICATE_INVALID",action:"failed"},[Je.K_CHANNEL_NAME_EMPTY]:{desc:"K_CHANNEL_NAME_EMPTY",action:"failed"},[Je.K_CHANNEL_NOT_FOUND]:{desc:"K_CHANNEL_NOT_FOUND",action:"failed"},[Je.K_TICKET_INVALID]:{desc:"K_TICKET_INVALID",action:"failed"},[Je.K_CHANNEL_CONFLICTED]:{desc:"K_CHANNEL_CONFLICTED",action:"failed"},[Je.K_SERVICE_NOT_READY]:{desc:"K_SERVICE_NOT_READY",action:"tryNext"},[Je.K_SERVICE_TOO_HEAVY]:{desc:"K_SERVICE_TOO_HEAVY",action:"tryNext"},[Je.K_UID_BANNED]:{desc:"K_UID_BANNED",action:"failed"},[Je.K_IP_BANNED]:{desc:"K_IP_BANNED",action:"failed"},[Je.DATASTREAM2_NOT_AVAILABLE]:{desc:"DATASTREAM2_NOT_AVAILABLE",action:"quit"},[Je.K_AUTO_REBALANCE]:{desc:"k_AUTO_REBALANCE",action:"recover"},[Je.K_VOS_FALLBACK]:{desc:"K_VOS_FALLBACK",action:"tryNext"},[Je.ERR_INVALID_VENDOR_KEY]:{desc:"ERR_INVALID_VENDOR_KEY",action:"failed"},[Je.ERR_INVALID_CHANNEL_NAME]:{desc:"ERR_INVALID_CHANNEL_NAME",action:"failed"},[Je.WARN_NO_AVAILABLE_CHANNEL]:{desc:"WARN_NO_AVAILABLE_CHANNEL",action:"failed"},[Je.WARN_LOOKUP_CHANNEL_TIMEOUT]:{desc:"WARN_LOOKUP_CHANNEL_TIMEOUT",action:"tryNext"},[Je.WARN_LOOKUP_CHANNEL_REJECTED]:{desc:"WARN_LOOKUP_CHANNEL_REJECTED",action:"failed"},[Je.WARN_OPEN_CHANNEL_TIMEOUT]:{desc:"WARN_OPEN_CHANNEL_TIMEOUT",action:"tryNext"},[Je.WARN_OPEN_CHANNEL_REJECTED]:{desc:"WARN_OPEN_CHANNEL_REJECTED",action:"failed"},[Je.WARN_REQUEST_DEFERRED]:{desc:"WARN_REQUEST_DEFERRED",action:"failed"},[Je.ERR_DYNAMIC_KEY_TIMEOUT]:{desc:"ERR_DYNAMIC_KEY_TIMEOUT",action:"failed"},[Je.ERR_NO_AUTHORIZED]:{desc:"ERR_NO_AUTHORIZED",action:"failed"},[Je.ERR_VOM_SERVICE_UNAVAILABLE]:{desc:"ERR_VOM_SERVICE_UNAVAILABLE",action:"tryNext"},[Je.ERR_NO_CHANNEL_AVAILABLE_CODE]:{desc:"ERR_NO_CHANNEL_AVAILABLE_CODE",action:"failed"},[Je.ERR_MASTER_VOCS_UNAVAILABLE]:{desc:"ERR_MASTER_VOCS_UNAVAILABLE",action:"tryNext"},[Je.ERR_INTERNAL_ERROR]:{desc:"ERR_INTERNAL_ERROR",action:"tryNext"},[Je.ERR_NO_ACTIVE_STATUS]:{desc:"ERR_NO_ACTIVE_STATUS",action:"failed"},[Je.ERR_INVALID_UID]:{desc:"ERR_INVALID_UID",action:"failed"},[Je.ERR_DYNAMIC_KEY_EXPIRED]:{desc:"ERR_DYNAMIC_KEY_EXPIRED",action:"failed"},[Je.ERR_STATIC_USE_DYANMIC_KE]:{desc:"ERR_STATIC_USE_DYANMIC_KE",action:"failed"},[Je.ERR_DYNAMIC_USE_STATIC_KE]:{desc:"ERR_DYNAMIC_USE_STATIC_KE",action:"failed"},[Je.ERR_NO_VOCS_AVAILABLE]:{desc:"ERR_NO_VOCS_AVAILABLE",action:"tryNext"},[Je.ERR_NO_VOS_AVAILABLE]:{desc:"ERR_NO_VOS_AVAILABLE",action:"tryNext"},[Je.ERR_JOIN_CHANNEL_TIMEOUT]:{desc:"ERR_JOIN_CHANNEL_TIMEOUT",action:"tryNext"},[Je.ERR_JOIN_BY_MULTI_IP]:{desc:"ERR_JOIN_BY_MULTI_IP",action:"recover"},[Je.ERR_NOT_JOINED]:{desc:"ERR_NOT_JOINED",action:"failed"},[Je.ERR_REPEAT_JOIN_REQUEST]:{desc:"ERR_REPEAT_JOIN_REQUEST",action:"quit"},[Je.ERR_REPEAT_JOIN_CHANNEL]:{desc:"ERR_REPEAT_JOIN_CHANNEL",action:"quit"},[Je.ERR_INVALID_STRINGUID]:{desc:"ERR_INVALID_STRINGUID",action:"failed"},[Je.ERR_TOO_MANY_USERS]:{desc:"ERR_TOO_MANY_USERS",action:"tryNext"},[Je.ERR_SET_CLIENT_ROLE_TIMEOUT]:{desc:"ERR_SET_CLIENT_ROLE_TIMEOUT",action:"failed"},[Je.ERR_SET_CLIENT_ROLE_NO_PERMISSION]:{desc:"ERR_SET_CLIENT_ROLE_TIMEOUT",action:"failed"},[Je.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE]:{desc:"ERR_SET_CLIENT_ROLE_ALREADY_IN_USE",action:"success"},[Je.ERR_PUBLISH_REQUEST_INVALID]:{desc:"ERR_PUBLISH_REQUEST_INVALID",action:"failed"},[Je.ERR_SUBSCRIBE_REQUEST_INVALID]:{desc:"ERR_SUBSCRIBE_REQUEST_INVALID",action:"failed"},[Je.ERR_NOT_SUPPORTED_MESSAGE]:{desc:"ERR_NOT_SUPPORTED_MESSAGE",action:"failed"},[Je.ERR_ILLEAGAL_PLUGIN]:{desc:"ERR_ILLEAGAL_PLUGIN",action:"failed"},[Je.ILLEGAL_CLIENT_ROLE_LEVEL]:{desc:"ILLEGAL_CLIENT_ROLE_LEVEL",action:"failed"},[Je.ERR_REJOIN_TOKEN_INVALID]:{desc:"ERR_REJOIN_TOKEN_INVALID",action:"failed"},[Je.ERR_REJOIN_USER_NOT_JOINED]:{desc:"ERR_REJOIN_NOT_JOINED",action:"failed"},[Je.ERR_INVALID_OPTIONAL_INFO]:{desc:"ERR_INVALID_OPTIONAL_INFO",action:"quit"},[Je.ERR_TEST_RECOVER]:{desc:"ERR_TEST_RECOVER",action:"recover"},[Je.ERR_TEST_TRYNEXT]:{desc:"ERR_TEST_TRYNEXT",action:"recover"},[Je.ERR_TEST_RETRY]:{desc:"ERR_TEST_RETRY",action:"recover"},[Je.ILLEGAL_AES_PASSWORD]:{desc:"ERR_TEST_RETRY",action:"failed"},[Je.ERR_TOO_MANY_BROADCASTERS]:{desc:"ERR_TOO_MANY_BROADCASTERS",action:"failed"},[Je.ERR_TOO_MANY_SUBSCRIBERS]:{desc:"ERR_TOO_MANY_SUBSCRIBERS",action:"failed"},[Je.ERR_TOO_MANY_MESSAGES]:{desc:"ERR_TOO_MANY_MESSAGES",action:"tryNext"},[Je.ERR_LICENSE_ILLEGAL]:{desc:"ERR_LICENSE_ILLEGAL",action:"quit"},[Je.ERR_LICENSE_MISSING]:{desc:"ERR_LICENSE_MISSING",action:"quit"},[Je.ERR_LICENSE_EXPIRED]:{desc:"ERR_LICENSE_EXPIRED",action:"quit"},[Je.ERR_LICENSE_MINUTES_EXCEEDED]:{desc:"ERR_LICENSE_MINUTES_EXCEEDED",action:"quit"},[Je.ERR_LICENSE_PERIOD_INVALID]:{desc:"ERR_LICENSE_PERIOD_INVALID",action:"quit"},[Je.ERR_LICENSE_MULTIPLE_SDK_SERVICE]:{desc:"ERR_LICENSE_MULTIPLE_SDK_SERVICE",action:"quit"}};function mn(e){const t=En[e];return t||{desc:"UNKNOWN_ERROR_".concat(e),action:"failed"}}class Sn extends k{constructor(e,t){super(),this.signal=void 0,this.token=void 0,this.tokenTimeout=void 0,this.tokenInterval=void 0,this._sequence=0,this.userMap=new Map,this.encoder=new TextEncoder,this.signal=e,this.token=t;const i=()=>{this.signal.connectionState===Xe.CONNECTED&&this.check(),0===this.userMap.size?this.tokenInterval=window.setTimeout(i,1e3):this.tokenInterval=window.setTimeout(i,3*M("P2P_TOKEN_INTERVAL"))};i()}async send(e,t,i,n,s){if(0===this.userMap.size)return;const o=Array.from(this.userMap.values())[0].token;"string"!=typeof t&&(t=JSON.stringify(t)),n=null!=n?n:W(6,""),s=null!=s?s:this._sequence++;const a={_id:n,_type:e,_seq:s,_message:t,token:"".concat(this.token,"_").concat(o)};M("SHOW_P2P_LOG")&&N.debug("send message",a,"noNeedResponse : ".concat(i));this.splitMessage(JSON.stringify(a)).forEach((e=>{this.signal.request(Ze.DATA_STREAM,{payload:Ae(this.encoder.encode(e))})}));const r=new Promise(((t,s)=>{const o=window.setTimeout((()=>{this.off("res-@".concat(n,"_ack"),r),this.off("res-@".concat(n),d),this.off(mt.ABORT,c),N.debug("[external-signal] request timeout, type: ".concat(e,", requestId: ").concat(n)),0===this.userMap.size?s(new j(z.INVALID_REMOTE_USER)):s(new j(z.TIMEOUT))}),M("EXTERNAL_SIGNAL_REQUEST_TIMEOUT")),r=()=>{o&&window.clearTimeout(o),this.off(mt.ABORT,c),i&&t()},c=()=>{o&&window.clearTimeout(o),this.off("res-@".concat(n,"_ack"),r),this.off("res-@".concat(n),d),s(new j(z.EXTERNAL_SIGNAL_ABORT,"type: ".concat(e,", requestId: ").concat(n)))};this.once(mt.ABORT,c),this.once("res-@".concat(n,"_ack"),r);const d=(i,a)=>{l=!0,o&&window.clearTimeout(o),this.off("res-@".concat(n,"_ack"),r),this.off(mt.ABORT,c),"success"===i?t(a):s(new j(z.P2P_MESSAGE_FAILED,"request ".concat(e," failed, requestId: ").concat(n)))};let l=!1;i||(this.once("res-@".concat(n),d),Te(M("SIGNAL_REQUEST_TIMEOUT")).then((()=>{l||N.warning("external_signal request timeout, type: ".concat(e,", requestId: ").concat(n,", ").concat(a))})))}));try{return await r}catch(o){if(o.code===z.TIMEOUT)return await this.send(e,t,i,n,s);throw o}}onMessage(e){const t=e._uid;let i,n=this.userMap.get(t);if(n)i=n.splitMessageMap;else{if(this.userMap.size>0||!("_type"in e)||e._type!==Et.CHECK)return;const s=e.token;i=new Map,n={uid:t,isStart:!0,token:s,splitMessageMap:i,nextExpectedSequenceNumber:0,receivedMessagesMap:new Map},this.userMap.set(t,n),this.signal.emit(et.ON_USER_ONLINE,{uid:t}),this.handleUserOnline()}if("id"in e&&"total"in e){var s;const n=e,o=n.id,a=n.total,r=null!==(s=i.get(o))&&void 0!==s?s:[];if(r.push(e),i.has(o)||i.set(o,r),r.length!==a)return;{const n=r.sort(((e,t)=>e.index-t.index)).map((e=>e.payload)).join("");i.delete(o),(e=JSON.parse(n))._uid=t}}const o=e,a=o._type,r=o.token;if([Et.ACK,Et.CHECK].includes(a))return a===Et.CHECK&&this.handleCheckToken(n,r),void this.receiveMessage(e);r==="".concat(n.token,"_").concat(this.token)?this.handleReceivedMessage(e):N.debug('Receive unexpected message", '.concat(r,", cur_token: ").concat(n.token,"_").concat(this.token),e)}check(){const e={_id:W(6,""),token:this.token,_type:Et.CHECK};M("SHOW_P2P_LOG")&&N.debug("send message",e),this.signal.request(Ze.DATA_STREAM,{payload:Ae(this.encoder.encode(JSON.stringify(e)))})}ack(e){const t={_id:e,_type:Et.ACK,token:this.token};M("SHOW_P2P_LOG")&&N.debug("send message",t),this.signal.request(Ze.DATA_STREAM,{payload:Ae(this.encoder.encode(JSON.stringify(t)))})}response(e,t,i){this.send(Et.RESPONSE,JSON.stringify({success:!i,message:t}),!0,e)}handleReceivedMessage(e){const t=()=>{this.userMap.forEach((e=>{const t=e.receivedMessagesMap,i=e.nextExpectedSequenceNumber;for(;t.has(i);){const n=t.get(i);t.delete(i),this.receiveMessage(n),e.nextExpectedSequenceNumber++}}))};if(!e)return void t();const i=e,n=i._uid,s=i._seq,o=this.userMap.get(n),a=o.receivedMessagesMap,r=o.isStart,c=o.nextExpectedSequenceNumber;if(s<c)return this.ack(e._id),void N.debug("[external-signal] receive old message, seq: ".concat(s,", ").concat(e._message));a.set(s,e),r&&s===c&&(this.receiveMessage(e),a.delete(c),o.nextExpectedSequenceNumber++,t())}receiveMessage(e){const t=e._id,i=e._type,n=e._message,s=e._uid;if(M("SHOW_P2P_LOG")&&N.debug("receive message",e),t){let o;switch(e._type!==Et.ACK&&(n&&(o=JSON.parse(n)),this.ack(e._id)),e._type){case Et.CANDIDATE:case Et.CONTROL:this.signal.emit(i,o,s);break;case Et.PUBLISH:case Et.UNPUBLISH:case Et.RESTART_ICE:case Et.CALL:o.uid=s,Ce(this.signal,i,o).then((t=>{this.response(e._id,t)})).catch((()=>{this.response(e._id,void 0,!0)}));break;case Et.ACK:this.getListeners("res-@".concat(t,"_ack")).length>0&&this.emit("res-@".concat(t,"_ack"));break;case Et.RESPONSE:{const e=o,i=e.success,n=e.message;this.emit("res-@".concat(t),i?"success":"failed",n);break}}}}splitMessage(e){if(e.length<Sn.MAX_MESSAGE_SIZE)return[e];const t=[],i=JSON.parse(e).remoteToken,n=W(6,"");let s=0,o=800;const a=Math.ceil(e.length/o);for(;e.length>0;){s++;const r={id:n,index:s,total:a,payload:e.slice(0,o),token:"".concat(this.token,"_").concat(i)};JSON.stringify(r).length>Sn.MAX_MESSAGE_SIZE?o-=50:(t.push(r),e=e.slice(o))}return t.map((e=>JSON.stringify(e)))}handleCheckToken(e,t){return e.token!==t?(N.debug("token changed, from ".concat(e.token," to ").concat(t)),this.reset(e.uid,t),!1):(this.tokenTimeout&&(window.clearTimeout(this.tokenTimeout),this.tokenTimeout=void 0),this.tokenTimeout=window.setTimeout((()=>{N.debug("token timeout, ".concat(t)),this.reset(e.uid)}),M("MAX_P2P_TIMEOUT")),!0)}async handleUserOnline(){const e=await Ce(this.signal,Et.CALL,void 0),t=await this.send(Et.CALL,e);this.signal.emit(Qe.P2P_CONNECTION,t,!0)}async reset(e,t){const i=this.userMap.get(e);i&&(this.emit(mt.ABORT),this.signal.emit(et.ON_USER_OFFLINE,{uid:i.uid,reason:Rt.P2P_TOKEN_CHANGED}),this._sequence=0,this.userMap.clear(),t||(N.debug("change local token from ".concat(t," to ").concat(t)),this.token=W(6,"")))}clear(){this._sequence=0,this.userMap.clear(),this.tokenInterval&&window.clearTimeout(this.tokenInterval),this.tokenInterval=void 0,this.tokenTimeout&&window.clearTimeout(this.tokenTimeout),this.tokenTimeout=void 0,this.emit(mt.ABORT)}}function Rn(e,t){if("string"==typeof e)return e;const i=e.proxy,n=e.host,s=e.port;if(t){const e=M("JOIN_GATEWAY_FALLBACK_PORT")||443;return 443===e?"wss://".concat(n,"/ws/?p=").concat(Number(s)+150):"wss://".concat(n,":").concat(e,"/ws/?p=").concat(Number(s)+150)}return i?"wss://".concat(i,"/ws/?h=").concat(n,"&p=").concat(s):"wss://".concat(n,":").concat(s)}Sn.MAX_SIZE=1,Sn.MAX_MESSAGE_SIZE=1024;const Cn=/wss:\/\/(.+)\/ws\/\?h=(.+)&p=([0-9]+)\/?/,fn=/wss:\/\/(.+)\/ws\/\?p=([0-9]+)\/?/,vn=/wss:\/\/(.+):([0-9]+)\/?/,Tn=/wss:\/\/(.[^\/]+)\/?/;let gn=0;class In{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=M("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),s=0;s<i;s++)n[s]=arguments[s];N.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=M("GATEWAY_DOMAINS"),s=Date.now(),o=[],a=n.find((t=>e.host.includes(t)));a||(this.useDoubleDomain=!1);const r=[];if(this.useDoubleDomain)n.forEach((i=>{r.push(Rn(We(We({},e),{},{host:e.host.replace(a,i)}),t))}));else{const i=We({},e);if(t&&a){const e=n.find((e=>e!==a));e&&(i.host=i.host.replace(a,e))}r.push(Rn(i,t))}try{r.forEach((e=>{const t=new WebSocket(e);t.binaryType="arraybuffer",o.push(t),this.logger("ws is connecting:",t.url)}))}catch(n){if(this.logger("ws create failed"),o.forEach((e=>e.close())),o.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 L(z.WS_ERR,"init websocket failed! Error: ".concat(n.toString()))}const c=De();this.store&&this.store.recordJoinChannelService({urls:o.map((e=>e.url)),service:"gateway"},this.recordIndex),o.forEach((e=>{e.onopen=()=>{this.logger("onopen: ws ".concat(e.url," open cost ").concat(Date.now()-s,"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()-s,"ms state: ").concat(e.readyState));const n=o.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:st.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(...o);const d=()=>{this.websockets.forEach((e=>e.readyState!==WebSocket.OPEN&&e.close()))},l=()=>{if(c.isResolved)return d();Pe()&&x()&&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 s=Ge(e.match(Cn)||[],4);if(t=s[1],i=s[2],n=s[3],!t){var o=Ge(e.match(fn)||[],3);i=o[1],n=o[2]}if(!i||!n){var a=Ge(e.match(vn)||[],3);i=a[1],n=a[2]}return i&&n||(i=Ge(e.match(Tn)||[],2)[1]),i||N.warning("un-destructible url: ",e),{proxy:t,host:i,port:n||"443"}}(e)),this.recordIndex=n,this.useProxy=!!e.proxy,i&&this.useProxy&&(N.warn("cannot use 443 only when use proxy"),i=!1),this.createWebSocket(e,!!i,!1).finally((()=>this.clearTimeout()))}}class An extends k{get url(){return this.websocket&&this.websocket.url||this._websocketUrl}get reportUrl(){return"connected"===this._state&&this.websocket?this.websocket.url:this._lastAttemptedUrl}get reconnectMode(){return this._reconnectMode}set reconnectMode(e){["tryNext","recover"].includes(e)&&this.resetReconnectCount(e),this._reconnectMode=e}get isFirstJoin(){return this.queryReconnectingWhenConnecting}get state(){return this._state}set state(e){e!==this._state&&(this._state=e,"reconnecting"===this._state?this.emit(it.RECONNECTING,this.reconnectReason):"connected"===this._state?this.emit(it.CONNECTED):"closed"===this._state?this.emit(it.CLOSED):"failed"===this._state&&this.emit(it.FAILED))}resetReconnectCount(e){N.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],s=arguments.length>4&&void 0!==arguments[4]&&arguments[4],o=arguments.length>5?arguments[5]:void 0;super(),this._websocketUrl=null,this._lastAttemptedUrl=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.queryReconnectingWhenConnecting=!1,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=o,this.name=e,this.retryConfig=We({},t),this.useCompress=i,this.tryDoubleDomain=n,this.use443PortOnly=s,this._initMutex=new K("websocket",o?o.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);Ne.ONLINE&&(this.retryConfig.timeout=c,this.retryConfig.timeoutFactor=d),Le.on(ye.NETWORK_STATE_CHANGE,((e,t)=>{e!==t&&(this.resetReconnectCount("network state change: ".concat(t," -> ").concat(e)),e===Ne.ONLINE?(this.retryConfig.timeout=c,this.retryConfig.timeoutFactor=d):(this.retryConfig.timeout=a,this.retryConfig.timeoutFactor=r))}))}getConnection(){return this.websocket||void 0}disableQueryReconnectingWhenConnecting(){this.queryReconnectingWhenConnecting=!1}async init(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const n=await this._initMutex.lock();this._lastAttemptedUrl=null,this._reconnectMode="tryNext",this.forceCloseTimeout=t,this.queryReconnectingWhenConnecting=!0===i.queryReconnectingWhenConnecting,this.urls=e,this.state="connecting";try{var s;const e=De(),t=this.urls[this.currentURLIndex];null===(s=this.store)||void 0===s||s.beforeConnect(),this.createWebSocketConnection(t).then(e.resolve).catch(e.reject),this.once(it.CLOSED,(()=>{e.reject(new j(z.WS_DISCONNECT))})),this.once(it.CONNECTED,e.resolve),await e.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 N.warning("[".concat(this.name,"] can not reconnect, no websocket"));void 0!==e&&(this.reconnectMode=e),N.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 j(z.WS_ABORT,"websocket is not ready");try{t||(e=JSON.stringify(e)),this.websocket.send(e)}catch(e){throw new j(z.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(),N.debug("[".concat(this.name,"] websocket opened:"),e),this.reconnectMode="retry",this.state="connected",this.resetReconnectCount("opened"),i.resolve()},s=async e=>{var t;if(N.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 j(z.WS_DISCONNECT,"websocket close: ".concat(e.code))),this.close();else{const t=this.queryReconnectingWhenConnecting;this.disableQueryReconnectingWhenConnecting();const n=t&&("connecting"===this.state||"connected"===this.state)&&!0===fe(this,it.SHOULD_ENTER_RECONNECTING,e.reason);("connected"===this.state||n)&&(this.reconnectReason=e.reason,this.state="reconnecting");const s=fe(this,it.WILL_RECONNECT,this.reconnectMode,e.reason)||this.reconnectMode,o=await this.reconnectWithAction(s);if("closed"===this.state)return void N.debug("[".concat(this.connectionID,"] ws is closed, no need to reconnect"));if(!o)return i.reject(new j(z.WS_DISCONNECT,"websocket reconnect failed: ".concat(e.code))),this.close(!0);i.resolve()}},o=e=>{this.emit(it.ON_MESSAGE,e)},a=e=>{N.warn("[".concat(this.connectionID,"] ws open error ").concat(e))};this.websocket&&(this.websocket.onclose=null,this.websocket.close()),M("GATEWAY_WSS_ADDRESS")&&this.name.startsWith("gateway")&&(e=M("GATEWAY_WSS_ADDRESS")),N.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;const t=Rn(e);this._websocketUrl=t,this._lastAttemptedUrl=t;const i=await this.chooseBestWebsocketConnection(e);this.websocket=i,n&&n(this.websocket.url),this.websocket.onclose=s,this.websocket.onmessage=o,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 j,o=n&&e.code===z.WS_ABORT,a=n&&e.code===z.WS_ERR,c=n?e.message:e&&(e.reason||e.toString());N.warning("[choose-best-ws] chooseBestWebsocket error: ".concat(c)),this.store&&this.store.recordJoinChannelService({endTs:Date.now(),status:o?"aborted":"error",errors:[e]},r),t||a?(i.reject(t?new j(z.WS_DISCONNECT,"websocket is closed: ".concat(c)):new j(z.WS_ERR,"init websocket failed: ".concat(c))),a&&N.error("[".concat(this.name,"] init websocket failed: ").concat(c))):s&&s(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;N.warning("[choose-best-ws] action: =>",e),this.onlineReconnectListener||Le.isOnline||!Le.onlineWaiter||(this.onlineReconnectListener=Le.onlineWaiter.then((()=>{this.onlineReconnectListener=void 0})));let i=!0;if(this.reconnectInterrupter=()=>i=!1,t){const t=ge(this.reconnectCount,this.retryConfig);N.debug("[".concat(this.name,"] wait ").concat(t,"ms to reconnect websocket, mode: ").concat(e)),await Promise.race([Te(t),this.onlineReconnectListener||new Promise((()=>{}))])}if("closed"===this._state||!i)return!1;this.reconnectCount+=1;const n=async(e,t)=>{this.emit(it.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);N.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&&(N.debug("[".concat(this.name,"] request new urls")),this.resetReconnectCount("recover mode"),this.urls=await Ce(this,it.REQUEST_NEW_URLS),this.currentURLIndex=0,await n(this.urls[this.currentURLIndex],e))}catch(i){var s;N.error("[".concat(this.name,"] reconnect failed ").concat(i&&i.toString()));const n=null==i||null===(s=i.data)||void 0===s?void 0:s.desc;if(Array.isArray(n)){if(n.includes("dynamic key expired"))return this.emit(it.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1;if(n.includes("request downgrade fallback"))return this.emit(it.ON_FALLBACK),!1}return this.reconnectWithAction(e,t)}return!0}}class Dn extends An{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=(s=this.forceCloseTimeout,o=this.store,new In(s,o));var s,o;this.closeEstablishingWs=()=>{N.debug("[choose-best-ws] close establishing websockets"),n.closeAllWebsockets(),i.reject(new j(z.WS_ABORT,"choose best websocket aborted"))};const a=M("GATEWAY_DOMAINS");return N.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 Pn extends k{get connectionState(){return this._connectionState}set connectionState(e){e!==this._connectionState&&(this._connectionState=e,e===Xe.CONNECTED?this.emit(Qe.WS_CONNECTED):e===Xe.RECONNECTING?this.emit(Qe.WS_RECONNECTING,this._websocketReconnectReason):e===Xe.CLOSED&&this.emit(Qe.WS_CLOSED,this._disconnectedReason))}get currentURLIndex(){return this.websocket.currentURLIndex}get url(){return this.websocket&&this.websocket.url||null}get reportUrl(){return this.websocket&&this.websocket.reportUrl||null}get rtt(){return this.rttRolling.mean()}constructor(e,t){super(),this.__name__="P2PSignal",this._disconnectedReason=void 0,this._websocketReconnectReason=void 0,this._connectionState=Xe.CLOSED,this.reconnectToken=void 0,this.p2pToken=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 Oe(5),this.pingpongTimer=void 0,this.pingpongTimeoutCount=0,this.joinResponse=void 0,this.multiIpOption=void 0,this.initError=void 0,this.spec=void 0,this.store=void 0,this._external_signal=void 0,this.onWebsocketMessage=e=>{if(e.data instanceof ArrayBuffer)return void this.emit(Qe.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")){switch(t._type){case et.ON_DATA_STREAM:return void this.handleDataStream(t._message);case et.MUTE_AUDIO:case et.MUTE_VIDEO:case et.ON_P2P_LOST:case et.ON_USER_ONLINE:return;case et.ON_USER_OFFLINE:const e=t._message.uid;return N.debug("[".concat(this.clientId,"] user-offline uid: ").concat(e)),void this._external_signal.reset(e)}if(this.emit(t._type,t._message),t._type===et.ON_NOTIFICATION&&this.handleNotification(t._message),t._type===et.ON_USER_BANNED)switch(t._message.error_code){case 14:this.close(we.UID_BANNED);break;case 15:this.close(we.IP_BANNED);break;case 16:this.close(we.CHANNEL_BANNED)}if(t._type===et.ON_USER_LICENSE_BANNED)switch(t._message.error_code){case Je.ERR_LICENSE_MISSING:this.close(we.LICENSE_MISSING);break;case Je.ERR_LICENSE_EXPIRED:this.close(we.LICENSE_EXPIRED);break;case Je.ERR_LICENSE_MINUTES_EXCEEDED:this.close(we.LICENSE_MINUTES_EXCEEDED);break;case Je.ERR_LICENSE_PERIOD_INVALID:this.close(we.LICENSE_PERIOD_INVALID);break;case Je.ERR_LICENSE_MULTIPLE_SDK_SERVICE:this.close(we.LICENSE_MULTIPLE_SDK_SERVICE);break;case Je.ERR_LICENSE_ILLEGAL:this.close(we.LICENSE_ILLEGAL);break;default:this.close()}}},this.clientId=e.clientId,this.spec=e,this.store=t,this.websocket=new Dn("gateway-".concat(this.clientId),this.spec.retryConfig,!0,M("JOIN_GATEWAY_USE_DUAL_DOMAIN"),M("JOIN_GATEWAY_USE_443PORT_ONLY"),t),this.handleWebsocketEvents(),window.addEventListener("offline",(()=>{this.connectionState===Xe.CONNECTED&&this.reconnect("retry",be.OFFLINE)})),this.p2pToken=W(6,""),this._external_signal=new Sn(this,this.p2pToken)}async request(e,t,i,n){const s=W(6,""),o={_id:s,_type:e,_message:t},a=this.websocket.connectionID,r=()=>new Promise(((e,t)=>{if(this.connectionState===Xe.CONNECTED)return e();const i=()=>{this.off(Qe.WS_CLOSED,n),e()},n=()=>{this.off(Qe.WS_CONNECTED,i),t(new j(z.WS_ABORT))};this.once(Qe.WS_CONNECTED,i),this.once(Qe.WS_CLOSED,n)}));if(this.connectionState!==Xe.CONNECTING&&this.connectionState!==Xe.RECONNECTING||e===Ze.JOIN||e===Ze.REJOIN||await r(),this.websocket.sendMessage(o,!0),n)return;const c=new Promise(((i,n)=>{let o=!1;const r=(n,s)=>{o=!0,i({isSuccess:"success"===n,message:s||{}}),this.off(Qe.WS_CLOSED,c),this.off(Qe.WS_RECONNECTING,c),this.emit(Qe.REQUEST_SUCCESS,e,t)};this.once("res-@".concat(s),r);const c=()=>{n(new j(z.WS_ABORT,"type: ".concat(e))),this.off(Qe.WS_CLOSED,c),this.off(Qe.WS_RECONNECTING,c),this.off("res-@".concat(s),r)};this.once(Qe.WS_CLOSED,c),this.once(Qe.WS_RECONNECTING,c),Te(M("SIGNAL_REQUEST_TIMEOUT")).then((()=>{this.websocket.connectionID!==a||o||(N.warning("[".concat(this.clientId,"] ws request timeout, type: ").concat(e)),this.emit(Qe.REQUEST_TIMEOUT,e,t))}))}));let d=null;try{d=await c}catch(n){if(this.connectionState===Xe.CLOSED||e===Ze.LEAVE)throw new j(z.WS_ABORT);return!this.spec.forceWaitGatewayResponse||i?n.throw():e===Ze.JOIN||e===Ze.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),u=mn(l),h=new j(z.UNEXPECTED_RESPONSE,"".concat(u.desc,": ").concat(d.message.error_str),{code:l,data:d.message,desc:u.desc});return"success"===u.action?d.message:(N.warning("[".concat(this.clientId,"] [").concat(this.websocket.connectionID,"] unexpected response from type ").concat(e,", error_code: ").concat(l,", message: ").concat(u.desc,", action: ").concat(u.action)),l===Je.ERR_TOO_MANY_BROADCASTERS?e===Ze.JOIN||e===Ze.REJOIN?(this.initError=h,this.close(),h.throw()):h.throw():"failed"===u.action?h.throw():"quit"===u.action?(this.initError=h,this.close(),h.throw()):(l===Je.ERR_JOIN_BY_MULTI_IP?(this.multiIpOption=d.message.option,N.warning("[".concat(this.clientId,"] detect multi ip, recover")),this.reconnect("recover",be.MULTI_IP)):this.reconnect(u.action,be.SERVER_ERROR),e===Ze.JOIN||e===Ze.REJOIN?null:await this.request(e,t)))}waitMessage(e,t){return new Promise((i=>{const n=s=>{(!t||t(s))&&(this.off(e,n),i(s))};this.on(e,n)}))}uploadWRTCStats(e){if(!this.store.sessionId)return void N.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($e.WRTC_STATS,t)}upload(e,t){const i={_type:e,_message:t};try{this.websocket.sendMessage(i)}catch(e){const t=M("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!==Xe.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)}),M("UPLOAD_CACHE_INTERVAL")||2e3))}}send(e,t){const i={_type:e,_message:t};this.websocket.sendMessage(i)}async sendExtensionMessage(e,t,i){return await this._external_signal.send(e,t,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(Qe.WS_CONNECTED,(()=>t(this.joinResponse))),this.once(Qe.WS_CLOSED,(()=>i(this.initError||new j(z.WS_ABORT)))),this.connectionState=Xe.CONNECTING,this.websocket.init(e).catch(i)}))}close(e){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.reconnectToken=void 0,this.joinResponse=void 0,this._external_signal.clear(),this._disconnectedReason=e||we.LEAVE,this.connectionState=Xe.CLOSED,N.debug("[".concat(this.clientId,"] ")+"will close websocket in signal"),this.websocket.close(),this.p2pToken=W(6,""),this._external_signal.clear(),this._external_signal=new Sn(this,this.p2pToken)}async join(){if(!this.joinResponse){this.emit(Qe.ABORT_P2P_EXECUTION);const e=await Ce(this,Qe.REQUEST_JOIN_INFO),t=await this.request(Ze.JOIN,e);if(!t)return this.emit(Qe.REPORT_JOIN_GATEWAY,z.TIMEOUT,this.reportUrl||""),!1;this.joinResponse=t,this.emit(Qe.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token}return this.connectionState=Xe.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),!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){return!1}handleDataStream(e){try{const t=ke(e.payload),i=(new TextDecoder).decode(t),n=JSON.parse(i);"total"in n&&"id"in n||Object.values(Et).includes(n._type)?(n._uid=e.uid,this._external_signal.onMessage(n)):this.emit(et.ON_DATA_STREAM,e)}catch(t){this.emit(et.ON_DATA_STREAM,e)}}handleNotification(e){N.debug("[".concat(this.clientId,"] receive notification: "),e);const t=mn(e.code);if("success"!==t.action){if("failed"!==t.action)return"quit"===t.action?e.code===Je.ERR_REPEAT_JOIN_CHANNEL&&M("IGNORE_UID_CHECK")?void this.close(we.UID_CONFLICT):("ERR_REPEAT_JOIN_CHANNEL"===t.desc&&this.close(we.UID_BANNED),void this.close()):void this.reconnect(t.action,be.SERVER_ERROR);N.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=M("PING_PONG_TIME_OUT"),t=Date.now();this.pingpongTimeoutCount>=e&&(N.warning("[".concat(this.clientId,"] PINGPONG Timeout. Last Socket Message: ").concat(t-this.lastMsgTime,"ms")),t-this.lastMsgTime>M("WEBSOCKET_TIMEOUT_MIN"))?this.reconnect("retry",be.TIMEOUT):this.request(Ze.PING,void 0,!0).then((()=>{this.pingpongTimeoutCount=0;const e=Date.now()-t;this.rttRolling.add(e),M("REPORT_STATS")&&this.send(Ze.PING_BACK,{pingpongElapse:e})})).catch((e=>{}))}handleWebsocketEvents(){this.websocket.on(it.RECONNECT_CREATE_CONNECTION,(e=>{this.emit(Qe.WS_RECONNECT_CREATE_CONNECTION,e)})),this.websocket.on(it.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(it.CLOSED,(()=>{this.connectionState=Xe.CLOSED})),this.websocket.on(it.FAILED,(()=>{this._disconnectedReason=we.NETWORK_ERROR,this.connectionState=Xe.CLOSED})),this.websocket.on(it.RECONNECTING,(e=>{this._websocketReconnectReason=e,this.joinResponse=void 0,this.connectionState===Xe.CONNECTED?this.connectionState=Xe.RECONNECTING:this.connectionState=Xe.CONNECTING})),this.websocket.on(it.WILL_RECONNECT,((e,t,i)=>{"retry"!==e?(N.debug("".concat(this.clientId," websocket will_connect event, renewSession reconnectMode is ").concat(e)),this.reconnectToken=void 0):N.debug("".concat(this.clientId," reconnect mode is retry, no need to renew session")),i(e)})),this.websocket.on(it.CONNECTED,(()=>{this.openConnectionTime=Date.now(),this.join().catch((e=>{if(this.emit(Qe.REPORT_JOIN_GATEWAY,e,this.reportUrl||""),e instanceof j&&e.code===z.UNEXPECTED_RESPONSE&&e.data.code===Je.ERR_NO_AUTHORIZED)return N.warning("[".concat(this.clientId,"] reconnect no authorized, recover")),void this.reconnect("recover",be.SERVER_ERROR);N.error("[".concat(this.clientId,"] join gateway request failed"),e.toString()),this.spec.forceWaitGatewayResponse?this.reconnect("tryNext",be.SERVER_ERROR):(this.initError=e,this.close())}))})),this.websocket.on(it.REQUEST_NEW_URLS,((e,t)=>{Ce(this,Qe.REQUEST_RECOVER,this.multiIpOption).then(e).catch(t)})),this.websocket.on(it.ON_TOKEN_PRIVILEGE_DID_EXPIRE,(()=>{this.emit(et.ON_TOKEN_PRIVILEGE_DID_EXPIRE)}))}}const Nn={name:"P2PChannel",create:function(e){let t=e.store,i=e.statsCollector;return new pn(t,i)},createSubmodule:function(e){let t=e.store,i=e.spec;return new Pn(i,t)}};export{Nn as P2PChannelService};