agora-rtc-sdk-ng
Version:
Agora WebRTC SDK for JavaScript
6 lines • 192 kB
JavaScript
/**
* AgoraWebSDK_N-v4.24.8-0-gf100be755-dirty Copyright AgoraInc.
*/
import{logger as e,report as t,AgoraRTCError as n}from"@agora-js/report";import{IS_GLOBAL_VERSION as i,EventEmitter as o,getParameter as r,ScalabilityMode as s,parseSdp as a,isFirefox as c,jsonClone as d,printSdp as p,getRandomString as l,getBrowserInfo as h,BrowserName as u,BrowserOS as E,isSafari as _,isChromeBelow90 as C,isAboveChrome as m,isAboveEdge as R,isWebKit as S,isChrome as f,isFirefoxVersion as I,isBelowIOS14_6 as g,VideoCodec as A,OVERUSE_DETECTOR_PARAMS as N,QualityLimitationReason as T,isAboveIOS as v,isBelowIOS as D,isAboveSafari as O,isBelowSafari as P,AgoraRTCError as y,AgoraRTCErrorCode as L,PromiseMutex as w,createWebRTCStatsFilter as b,AgoraAPIName as M,AgoraAPITag as U,DEFAULT_CANDIDATE_STATS as x,isRTCIceServerList as V,isChromeKernel as k,setBigUint64 as F,getBigUint64 as B,NETWORK_STATE as G,networkIndicator as H,NETWORK_INDICATOR_EVENTS as W,emitAsPromise as K,getRetryWaitTime as Y,wait as j,emitAsInvokerNoResponse as J,ConnectionDisconnectedReason as X,Rolling as Q,emitAsInvoker as q}from"@agora-js/shared";import"@agora-js/protocol";import{LocalAudioTrack as z,MicrophoneAudioTrack as Z,LocalVideoTrack as $,getCompatibility as ee,TrackHint as te,CameraVideoTrack as ne,detectSupportPreSub as ie,detectSupportSDPEndpoint as oe,VideoPlayer as re,AgoraRTCPlayer as se,audioElementPlayCenter as ae,getOriginSenderConfig as ce}from"@agora-js/media";import{deflateRaw as de,inflateRaw as pe}from"pako";function le(e,t){this.v=e,this.k=t}function he(e,t,n,i,o){var r={};return Object.keys(i).forEach((function(e){r[e]=i[e]})),r.enumerable=!!r.enumerable,r.configurable=!!r.configurable,("value"in r||r.initializer)&&(r.writable=!0),r=n.slice().reverse().reduce((function(n,i){return i(e,t,n)||n}),r),o&&void 0!==r.initializer&&(r.value=r.initializer?r.initializer.call(o):void 0,r.initializer=void 0),void 0===r.initializer?(Object.defineProperty(e,t,r),null):r}function ue(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n<t;n++)i[n]=e[n];return i}function Ee(e){var t={},n=!1;function i(t,i){return n=!0,i=new Promise((function(n){n(e[t](i))})),{done:!1,value:new le(i,1)}}return t["undefined"!=typeof Symbol&&Symbol.iterator||"@@iterator"]=function(){return this},t.next=function(e){return n?(n=!1,e):i("next",e)},"function"==typeof e.throw&&(t.throw=function(e){if(n)throw n=!1,e;return i("throw",e)}),"function"==typeof e.return&&(t.return=function(e){return n?(n=!1,e):i("return",e)}),t}function _e(e){var t,n,i,o=2;for("undefined"!=typeof Symbol&&(n=Symbol.asyncIterator,i=Symbol.iterator);o--;){if(n&&null!=(t=e[n]))return t.call(e);if(i&&null!=(t=e[i]))return new Ce(t.call(e));n="@@asyncIterator",i="@@iterator"}throw new TypeError("Object is not async iterable")}function Ce(e){function t(e){if(Object(e)!==e)return Promise.reject(new TypeError(e+" is not an object."));var t=e.done;return Promise.resolve(e.value).then((function(e){return{value:e,done:t}}))}return Ce=function(e){this.s=e,this.n=e.next},Ce.prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(e){var n=this.s.return;return void 0===n?Promise.resolve({value:e,done:!0}):t(n.apply(this.s,arguments))},throw:function(e){var n=this.s.return;return void 0===n?Promise.reject(e):t(n.apply(this.s,arguments))}},new Ce(e)}function me(e){return new le(e,0)}function Re(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var i=n.call(e,t||"default");if("object"!=typeof i)return i;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:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Se(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function fe(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?Se(Object(n),!0).forEach((function(t){Re(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Se(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function Ie(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var i,o,r,s,a=[],c=!0,d=!1;try{if(r=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;c=!1}else for(;!(c=(i=r.call(n)).done)&&(a.push(i.value),a.length!==t);c=!0);}catch(e){d=!0,o=e}finally{try{if(!c&&null!=n.return&&(s=n.return(),Object(s)!==s))return}finally{if(d)throw o}}return a}}(e,t)||function(e,t){if(e){if("string"==typeof e)return ue(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?ue(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 ge(e){return function(){return new Ae(e.apply(this,arguments))}}function Ae(e){var t,n;function i(t,n){try{var r=e[t](n),s=r.value,a=s instanceof le;Promise.resolve(a?s.v:s).then((function(n){if(a){var c="return"===t&&s.k?t:"next";if(!s.k||n.done)return i(c,n);n=e[c](n).value}o(!!r.done,n)}),(function(e){i("throw",e)}))}catch(e){o(2,e)}}function o(e,o){2===e?t.reject(o):t.resolve({value:o,done:e}),(t=t.next)?i(t.key,t.arg):n=null}this._invoke=function(e,o){return new Promise((function(r,s){var a={key:e,arg:o,resolve:r,reject:s,next:null};n?n=n.next=a:(t=n=a,i(e,o))}))},"function"!=typeof e.return&&(this.return=void 0)}Ae.prototype["function"==typeof Symbol&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},Ae.prototype.next=function(e){return this._invoke("next",e)},Ae.prototype.throw=function(e){return this._invoke("throw",e)},Ae.prototype.return=function(e){return this._invoke("return",e)};let Ne=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}({}),Te=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}({}),ve=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}({}),De=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}({}),Oe=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}({}),Pe=function(e){return e.CONNECTING="connecting",e.CONNECTED="connected",e.RECONNECTING="reconnecting",e.CLOSED="closed",e}({}),ye=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}({}),Le=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}({}),we=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}({}),be=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}({}),Me=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}({});Me.AFRICA,Me.ASIA,Me.CHINA,Me.EUROPE,Me.GLOBAL,Me.INDIA,Me.JAPAN,Me.NORTH_AMERICA,Me.OCEANIA,Me.OVERSEA,Me.SOUTH_AMERICA;let Ue=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}({});Ue.ASIA,Ue.NORTH_AMERICA,Ue.EUROPE,Ue.JAPAN,Ue.INDIA,Ue.KOREA,Ue.HKMC,Ue.US,Ue.OVERSEA,Ue.GLOBAL,Ue.OCEANIA,Ue.SOUTH_AMERICA,Ue.AFRICA,i&&Ue.CHINA;class xe extends o{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 Ve extends xe{constructor(e,t){super(e,t),this.establishPromise=void 0}}let ke=function(e){return e.VIDEO="video",e.AUDIO="audio",e}({}),Fe=function(e){return e.UDP_RELAY="udp_relay",e.UDP_TCP_RELAY="udp_tcp_relay",e.TCP_RELAY="tcp_relay",e.RELAY="relay",e}({}),Be=function(e){return e.NETWORK_ERROR="NETWORK_ERROR",e.SERVER_ERROR="SERVER_ERROR",e.MULTI_IP="MULTI_IP",e.TIMEOUT="TIMEOUT",e.OFFLINE="OFFLINE",e.LEAVE="LEAVE",e.P2P_FAILED="P2P_FAILED",e.FALLBACK="FALLBACK",e}({}),Ge=function(e){return e.CONNECTED="transmitter:connected",e.RECONNECTING="transmitter:reconnecting",e.WILL_RECONNECT="transmitter:will_reconnect",e.CLOSED="transmitter:closed",e.FAILED="transmitter:failed",e.ON_MESSAGE="transmitter:on_message",e.REQUEST_NEW_URLS="transmitter:request_new_urls",e.RECONNECT_CREATE_CONNECTION="transmitter:reconnect_create_connection",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="transmitter:on_token_privilege_did_expire",e.TO_CONNECT_DATACHANNEL="transmitter:to_connect_datachannel",e.FAILBACK="transmitter:failback",e.PRE_CONNECT_PC="transmitter:pre_connect_pc",e}({}),He=0;function We(t){const n=r("TURN_DOMAINS");He=(He+1)%n.length;const i=n[He]||"edge.agora.io";return t.match(/^[\.\:\d]+$/)?"".concat(t.replace(/[^\d]/g,"-"),".").concat(i):(e.debug("Cannot recognized as ip address: ".concat(t,", use as host2")),t)}function Ke(e){return"number"==typeof e?e:e.exact||e.ideal||e.max||e.min||0}function Ye(e){const t=e.split(":"),n=e.split(/[-.]/),i=e.includes("-")?"-":".";let o=e;return t.length>1?n.length>1?(n[1]="**",o=n[0]+i+"**:"+t[t.length-1]):o=t.length>2?t[0]+i+"**:"+t[t.length-1]:"**:"+t[t.length-1]:n.length>1&&(o=n[0]+i+"**"),o}function je(e,t){return e.getTransceivers().find((e=>e.sender.track===t||e.receiver.track===t))}function Je(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:r("SVC_MODE");if(r("ENABLE_SVC"))return function(e){return e in s}(e)?e:s.L1T3}const Xe={[ke.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"}],[ke.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 Qe(e){e.send&&(Ze(ke.VIDEO,e.send.videoExtensions),Ze(ke.AUDIO,e.send.audioExtensions)),e.recv&&(Ze(ke.VIDEO,e.recv.videoExtensions),Ze(ke.AUDIO,e.recv.audioExtensions)),e.sendrecv&&(Ze(ke.VIDEO,e.sendrecv.videoExtensions),Ze(ke.AUDIO,e.sendrecv.audioExtensions))}function qe(e,t){e.send&&(ze(ke.VIDEO,e.send.videoExtensions,t.send.videoExtensions),ze(ke.AUDIO,e.send.audioExtensions,t.send.audioExtensions)),e.recv&&(ze(ke.VIDEO,e.recv.videoExtensions,t.recv.videoExtensions),ze(ke.AUDIO,e.recv.audioExtensions,t.recv.audioExtensions))}function ze(e,t,n){t.forEach((t=>{const i=Xe[e].find((e=>{let n=e.key;return t.extensionName.includes(n)}));if(!i)return;const o=n.find((e=>e.extensionName.includes(i.key)));o&&o.extensionName.includes("gdpr_forbidden")&&(t.extensionName=o.extensionName)}))}function Ze(e,t){t.forEach((t=>{const n=Xe[e].find((e=>{let n=e.key;return t.extensionName.includes(n)}));t.extensionName.includes("gdpr_forbidden")&&n&&(t.extensionName=n.extensionName)}))}function $e(e){return"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"===e||e.includes("abs-send-time")}function et(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 tt(t){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},o=arguments.length>3?arguments[3]:void 0;const s=n.filterRTX,c=n.filterVideoFec,d=n.filterAudioFec,p=n.filterAudioCodec,l=n.filterVideoCodec,h=n.unsupportedVideoUplinkCodec,u=n.unsupportedVideoDownlinkCodec,E=i.useXR;let _=[],C=[],m=[],R=[],S=!1,f=!1;if(a(t).mediaDescriptions.forEach((e=>{o&&o!==e.attributes.direction||("video"!==e.media.mediaType||S||(C=e.attributes.payloads,R=e.attributes.extmaps,S=!0),"audio"!==e.media.mediaType||f||(_=e.attributes.payloads,m=e.attributes.extmaps,f=!0))})),!R||0===C.length)throw new Error("Cannot get video capabilities from SDP.");if(!m||0===_.length)throw new Error("Cannot get audio capabilities from SDP.");if(C.forEach((e=>{var t;null!==(t=e.rtpMap)&&void 0!==t&&t.clockRate&&(e.rtpMap.clockRate=parseInt(e.rtpMap.clockRate)),E&&e.rtcpFeedbacks.push({type:"rrtr"})})),_.forEach((e=>{var t;null!==(t=e.rtpMap)&&void 0!==t&&t.clockRate&&(e.rtpMap.clockRate=parseInt(e.rtpMap.clockRate)),E&&e.rtcpFeedbacks.push({type:"rrtr"})})),s&&(_=_.filter((e=>{var t;return"rtx"!==(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())})),C=C.filter((e=>{var t;return"rtx"!==(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())}))),c){const e=C.filter((e=>{var t;return/(red)|(ulpfec)|(flexfec)/i.test((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName)||"")})),t=Et(e,C).map((e=>e.payloadType)),n=[...e.map((e=>e.payloadType)),...t];C=C.filter((e=>!n.includes(e.payloadType)))}if(d&&(_=_.filter((e=>{var t;return!/(red)|(ulpfec)|(flexfec)/i.test((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName)||"")}))),p&&(null==p?void 0:p.length)>0&&(_=_.filter((e=>{var t;return p.includes((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())||"")}))),l&&(null==l?void 0:l.length)>0){const e=C.filter((e=>{var t;return l.includes((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())||"")}));C=e.concat(s?[]:Et(e,C))}const I=r("UNSUPPORTED_VIDEO_CODEC");if(I&&I.length>0){const t=C.filter((e=>e.rtpMap&&I.includes(e.rtpMap.encodingName.toLowerCase()))),n=Et(t,C),i=t.concat(n).map((e=>e.payloadType));C=C.filter((e=>!i.includes(e.payloadType))),e.debug("unsupportedVideoCodec: ".concat(I,", toBeRemoved: ").concat(i))}if(h&&h.length>0&&"sendonly"===o){const t=C.filter((e=>e.rtpMap&&h.includes(e.rtpMap.encodingName.toLowerCase()))),n=Et(t,C),i=t.concat(n).map((e=>e.payloadType));C=C.filter((e=>!i.includes(e.payloadType))),e.debug("unsupportedVideoUplinkCodec: ".concat(h,", toBeRemoved: ").concat(i))}if(u&&u.length>0&&"recvonly"===o){const t=C.filter((e=>e.rtpMap&&u.includes(e.rtpMap.encodingName.toLowerCase()))),n=Et(t,C),i=t.concat(n).map((e=>e.payloadType));C=C.filter((e=>!i.includes(e.payloadType))),e.debug("unsupportedVideoDownlinkCodec: ".concat(u,", toBeRemoved: ").concat(i))}return{audioCodecs:_,videoCodecs:C,audioExtensions:m,videoExtensions:R}}function nt(e){const t=a(e);let n,i;for(const e of t.mediaDescriptions){if(!n){const t=e.attributes.iceUfrag,i=e.attributes.icePwd;if(!t||!i)throw new Error("Cannot get iceUfrag or icePwd from SDP.");n={iceUfrag:t,icePwd:i}}if(!i){const t=e.attributes.fingerprints;t.length>0&&(i={fingerprints:t})}}if(!i&&t.attributes.fingerprints.length>0&&(i={fingerprints:t.attributes.fingerprints}),!i||!n)throw new Error("Cannot get iceParameters or dtlsParameters from SDP.");return{iceParameters:n,dtlsParameters:i}}function it(e,t){const n=[],i=e.attributes.ssrcGroups.filter((e=>"FID"===e.semantic)),o=e.attributes.ssrcGroups.find((e=>"SIM"===e.semantic)),r=e.attributes.ssrcs;if(o)o.ssrcIds.forEach((e=>{var o;const r=null===(o=i.find((t=>t.ssrcIds[0]===e)))||void 0===o?void 0:o.ssrcIds[1];n.push({ssrcId:e,rtx:t?r:void 0})}));else if(i.length>0){const e=i[0].ssrcIds[0],o=i[0].ssrcIds[1];n.push({ssrcId:e,rtx:t?o:void 0})}else{if(0===r.length)throw new Error("No ssrcs found on local media description.");n.push({ssrcId:r[0].ssrcId})}return n}function ot(e,t,n){const i=[],o=[];return e.forEach((e=>{let r=e.ssrcId,s=e.rtx;const a=l(8,"track-"),c={ssrcId:r,attributes:fe({label:a,mslabel:n=n||l(10,""),msid:"".concat(n," ").concat(a)},t&&{cname:t})};if(i.push(c),void 0!==s){const e={ssrcId:s,attributes:fe({label:a,mslabel:n,msid:"".concat(n," ").concat(a)},t&&{cname:t})};i.push(e),o.push({semantic:"FID",ssrcIds:[r,s]})}})),e.length>1&&o.push({semantic:"SIM",ssrcIds:e.map((e=>e.ssrcId))}),{ssrcs:i,ssrcGroups:o}}function rt(e,t){t instanceof z&&e.attributes.payloads.forEach((e=>{var n;const i=null===(n=e.rtpMap)||void 0===n?void 0:n.encodingName.toLowerCase();if(!i||-1===["opus","pcmu","pcma","g722"].indexOf(i))return;e.fmtp||(e.fmtp={parameters:{}}),"opus"===i&&"number"==typeof r("OPUS_PTIME")?e.fmtp.parameters.ptime=r("OPUS_PTIME"):e.fmtp.parameters.minptime="10",e.fmtp.parameters.useinbandfec="1";const o=t._encoderConfig;o&&("pcmu"!==i&&"pcma"!==i&&"g722"!==i&&(o.bitrate&&!c()&&(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")),t instanceof Z&&"opus"===i&&t._config.DTX&&(e.fmtp.parameters.usedtx="1"))}))}function st(e,t,n){if(!t)return;let i,o;if("video"===e.media.mediaType?(i=n.videoExtensions,o=n.videoCodecs):(i=n.audioExtensions,o=n.audioCodecs),!0===t.twcc){const t=i.find((e=>et(e.extensionName)));if(t){const n=t.extensionName;e.attributes.extmaps.find((e=>et(e.extensionName)))||e.attributes.extmaps.push({entry:t.entry,extensionName:n});const i=function(e,t){return t.filter((t=>!!e.find((e=>e.payloadType===t.payloadType&&!!e.rtcpFeedbacks.find((e=>"transport-cc"===e.type))))))}(o,e.attributes.payloads);i.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=>et(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=i.find((e=>$e(e.extensionName)));if(t){const n=t.extensionName;e.attributes.extmaps.find((e=>e.extensionName===n))||e.attributes.extmaps.push({entry:t.entry,extensionName:n});const i=function(e,t){return t.filter((t=>!!e.find((e=>e.payloadType===t.payloadType&&!!e.rtcpFeedbacks.find((e=>"goog-remb"===e.type))))))}(o,e.attributes.payloads);i.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=>$e(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 at(e,t,n){if(c())return;if("video"!==e.media.mediaType)return;if(!(t instanceof $))return;if("vp9"!==n&&"vp8"!==n)return;if("vp8"===n&&!r("SIMULCAST"))return;if("vp9"===n&&r("ENABLE_SVC"))return;if(void 0===t._scalabilityMode||t._scalabilityMode.numSpatialLayers<=1)return;const i="vp8"===n?2:t._scalabilityMode.numSpatialLayers,o=e.attributes.ssrcs[0],s=e.attributes.ssrcGroups.find((e=>"FID"===e.semantic&&e.ssrcIds[0]===o.ssrcId)),a={semantic:"SIM",ssrcIds:[o.ssrcId]};for(let t=1;t<i;t++)e.attributes.ssrcs.push({ssrcId:o.ssrcId+t,attributes:d(o.attributes)}),a.ssrcIds.push(o.ssrcId+t),s&&(e.attributes.ssrcs.push({ssrcId:s.ssrcIds[1]+t,attributes:d(o.attributes)}),e.attributes.ssrcGroups.push({semantic:"FID",ssrcIds:[o.ssrcId+t,s.ssrcIds[1]+t]}));e.attributes.ssrcGroups.unshift(a)}async function ct(){try{const e=new RTCPeerConnection;e.addTransceiver("video",{direction:"sendonly",sendEncodings:[{scalabilityMode:s.L1T3}]});const t=await e.createOffer();if(!t.sdp)return void e.close();const n=a(t.sdp).mediaDescriptions[0];if(!n)return;const i=n.attributes.extmaps.find((e=>"https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension"===e.extensionName));return e.close(),i}catch(e){return}}async function dt(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=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 o=function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=arguments.length>2?arguments[2]:void 0;const o=tt(i,t,n,"sendonly"),s=tt(i,t,n,"recvonly"),a={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},c={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},d={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]};if(pt(o,s,"videoExtensions",a,c,d),pt(o,s,"videoCodecs",a,c,d),pt(o,s,"audioExtensions",a,c,d),pt(o,s,"audioCodecs",a,c,d),r("RAISE_H264_BASELINE_PRIORITY")){const t=[],n=[];if(d.videoCodecs.forEach(((e,i)=>{var o;if("h264"===(null===(o=e.rtpMap)||void 0===o?void 0:o.encodingName.toLocaleLowerCase())){var s,a;const o=d.videoCodecs[i+1],c=o&&ft(e,o),p=null===(s=e.fmtp)||void 0===s?void 0:s.parameters["profile-level-id"],l=null===(a=e.fmtp)||void 0===a?void 0:a.parameters["packetization-mode"];!p||p!==r("FIRST_H264_PROFILE_LEVEL_ID")||r("FIRST_PACKETIZATION_MODE")&&l!==r("FIRST_PACKETIZATION_MODE")?c?n.push([e,o]):n.push([e]):c?t.push([e,o]):t.push([e])}})),t.length>0&&n.length>0){e.debug("raising H264 baseline profile priority"),d.videoCodecs.forEach(((e,i)=>{var o;if("h264"===(null===(o=e.rtpMap)||void 0===o?void 0:o.encodingName.toLocaleLowerCase())){const o=ft(e,d.videoCodecs[i+1]),r=t.shift()||n.shift()||[];r.length>0&&(o?d.videoCodecs.splice(i,2,...r):d.videoCodecs.splice(i,1,...r))}}));const i=c.videoCodecs.filter((e=>{var t,n;return"h264"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLocaleLowerCase())&&(null===(n=e.fmtp)||void 0===n?void 0:n.parameters["profile-level-id"])!==r("FIRST_H264_PROFILE_LEVEL_ID")}));if(i.length>0){const e=Et(i,c.videoCodecs).map((e=>e.payloadType)),t=[...i.map((e=>e.payloadType)),...e];c.videoCodecs=c.videoCodecs.filter((e=>!t.includes(e.payloadType)))}r("FILTER_SEND_H264_BASELINE")&&(a.videoCodecs=a.videoCodecs.filter((e=>{var t,n;return!("h264"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLocaleLowerCase())&&(null===(n=e.fmtp)||void 0===n?void 0:n.parameters["profile-level-id"])!==r("FIRST_H264_PROFILE_LEVEL_ID"))})))}return{send:a,recv:c,sendrecv:d}}return{send:a,recv:c,sendrecv:d}}(t,n,(await i.createOffer()).sdp),s=o.send,a=o.recv,c=o.sendrecv;try{i.close()}catch(e){}return{send:s,recv:a,sendrecv:c}}function pt(e,t,n,i,o,r){if("videoExtensions"===n||"audioExtensions"===n){const s=[];return e[n].forEach((e=>{t[n].some(((t,n)=>{if(e.entry===t.entry&&e.extensionName===t.extensionName)return s.push(n),!0}))?r[n].push(e):i[n].push(e)})),void t[n].forEach(((e,t)=>{-1===s.indexOf(t)&&o[n].push(e)}))}if("videoCodecs"===n||"audioCodecs"===n){const s=[];return e[n].forEach((e=>{t[n].some(((t,n)=>{if(e.payloadType===t.payloadType&&JSON.stringify(e)===JSON.stringify(t))return s.push(n),!0}))?r[n].push(e):i[n].push(e)})),void t[n].forEach(((e,t)=>{-1===s.indexOf(t)&&o[n].push(e)}))}}function lt(e){const t=e.send,n=e.recv,i=e.sendrecv;if(!i){if(!t||!n)throw new Error("cannot merge rtp capabilities because one of send or recv is empty!");return{send:t,recv:n}}let o,r;return t?(o={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},o.audioCodecs=[...t.audioCodecs,...i.audioCodecs],o.videoCodecs=[...t.videoCodecs,...i.videoCodecs],o.audioExtensions=[...t.audioExtensions,...i.audioExtensions],o.videoExtensions=[...t.videoExtensions,...i.videoExtensions]):o=d(i),n?(r={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},r.audioCodecs=[...n.audioCodecs,...i.audioCodecs],r.videoCodecs=[...n.videoCodecs,...i.videoCodecs],r.audioExtensions=[...n.audioExtensions,...i.audioExtensions],r.videoExtensions=[...n.videoExtensions,...i.videoExtensions]):r=d(i),{send:o,recv:r}}function ht(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 ut(t,n,i,o){let s=[];if(t===ke.VIDEO){if(r("H264_PROFILE_LEVEL_ID")&&"h264"===o&&(s=n.videoCodecs.filter((e=>(e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").includes(o)&&e&&e.fmtp&&e.fmtp.parameters["profile-level-id"]===r("H264_PROFILE_LEVEL_ID")))),!Array.isArray(s)||0===s.length){let t=[];const r=[],a=[],c=[];if(i.videoCodecs.forEach((e=>{const n=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"";n.includes(o)?t.push(e):n.includes("vp9")?r.push(e):n.includes("vp8")?a.push(e):n.includes("h264")&&c.push(e)})),0===t.length){let n="";0!==r.length?(t=r,n="vp9"):0!==a.length?(t=a,n="vp8"):0!==c.length&&(t=c,n="h264"),e.warning("codec ".concat(o," not included in rtpCapabilities, fallback to default payloads: ").concat(n))}0!==t.length&&(s=n.videoCodecs.filter((e=>t.some((t=>t.payloadType===e.payloadType)))))}if(0===s.length&&(e.warning("codec ".concat(o," not included in rtpCapabilities, fallback to default payloads: ").concat(n.videoCodecs[0].rtpMap&&n.videoCodecs[0].rtpMap.encodingName)),s=n.videoCodecs),r("USE_PUB_RTX")||r("USE_SUB_RTX")){const e=Et(s,n.videoCodecs);s=[...s,...e]}}else{s=n.audioCodecs.filter((e=>(e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").includes(o)));const t=n.audioCodecs.filter((e=>(e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").includes("red")));0===s.length&&(e.warning("codec ".concat(o," not included in rtpCapabilities, fallback to opus")),s=n.audioCodecs.filter((e=>(e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").includes("opus")))),r("ENABLE_AUDIO_RED")&&0!==t.length&&(s=[...t,...s])}return s}function Et(e,t){const n=e.map((e=>e.payloadType.toString()));return t.filter((e=>e.rtpMap&&"rtx"===e.rtpMap.encodingName&&e.fmtp&&e.fmtp.parameters.apt&&n.includes(e.fmtp&&e.fmtp.parameters.apt)))}async function _t(e,t,n){const i=t.toString(),o=mt(i,"offer","remote","exchangeSDP");await e.setRemoteDescription({type:"offer",sdp:i});const r=await e.createAnswer();if(!r.sdp)throw new Error("cannot get answer sdp");let s=r.sdp;s=Ct(s,n||{}),null==o||o(s||""),await e.setLocalDescription({type:"answer",sdp:s})}function Ct(e,t,n){if(r("FORBID_MODIFY_LOCAL_OFFER_SDP"))return e;const i=a(e),o=t.useXR;return i.mediaDescriptions.forEach((e=>{e.attributes.mid&&(Array.isArray(n)&&!n.includes(e.attributes.mid)||("audio"===e.media.mediaType&&ht(e),"video"===e.media.mediaType&&function(e){if("video"!==e.media.mediaType)return;if(!r("ENABLE_DOWN_SPS_PPS"))return;e.attributes.payloads.filter((e=>{var t;return"h264"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())})).forEach((e=>{e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters["sps-pps-idr-in-keyframe"]="1"}))}(e),o&&["audio","video"].includes(e.media.mediaType)&&e.attributes.payloads.forEach((e=>{-1===e.rtcpFeedbacks.findIndex((e=>"rrtr"===e.type))&&e.rtcpFeedbacks.push({type:"rrtr"})}))))})),p(i)}function mt(t,n,i,o){if(r("SDP_LOGGING"))return e.upload("exchanging ".concat(i," ").concat(n," SDP during P2PConnection.").concat(o,"\n"),t),"offer"===n?e=>{mt(e,"answer","local"===i?"remote":"local",o)}:void 0}async function Rt(t,n,i){try{var o;if(!ee().supportSetRtpSenderParameters)return;if(!function(e){return"vp9"===e||"av1"===e}(t)||!r("ENABLE_SVC"))return;const s={},a={},c=n.getParameters(),d=null===(o=c.encodings)||void 0===o?void 0:o[0];a.scalabilityMode=Je(i),d&&Object.assign(d,a),Object.assign(c,s),await n.setParameters(c),e.debug("[updateAdaptation] updateRtpSenderEncodings scalabilityMode success: ".concat(JSON.stringify(c.encodings)))}catch(t){e.debug("[updateAdaptation] updateRtpSenderEncodings scalabilityMode failed",t)}}function St(e){const t=r("COMPATIBLE_SDP_EXTENSION");return!!(Array.isArray(t)&&t.length>0)&&t.some((t=>e.includes(t)))}function ft(e,t){try{var n;return(null===(n=e.fmtp)||void 0===n?void 0:n.parameters.apt)===t.payloadType.toString()}catch(e){return!1}}const It=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"),gt="9",At=2e4,Nt=4e4;class Tt{get localCapabilities(){return d(this._localCapabilities)}get rtpCapabilities(){return d(this._rtpCapabilities)}get candidates(){return d(this._candidates)}get iceParameters(){return d(this._iceParameters)}get remoteIceUfrag(){var e;return null===(e=this._iceParameters)||void 0===e?void 0:e.iceUfrag}get dtlsParameters(){return d(this._dtlsParameters)}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],i=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=n,this._isUseDataChannel=i;const o=e=d(e),r=o.iceParameters,s=o.dtlsParameters,a=o.candidates,c=o.rtpCapabilities,p=o.setup,l=o.localCapabilities,h=o.cname;this._rtpCapabilities=c,this._candidates=a,this._originCandidates=d(a),this._iceParameters=r,this._dtlsParameters=s,this._localCapabilities=l,this.setup=p,this.cname=h;var u=Ie(this.updateRemoteRTPCapabilities(c),1);this.sessionDesc=u[0],this.currentMidIndex=this.sessionDesc.mediaDescriptions.length-1}checkPreloadSsrcs(e){return e.length===this.preloadSsrcs.length&&e.every((e=>this.preloadSsrcs.includes(e)))}preloadRemoteMedia(e){let t=0;const n=[],i=[];for(;e>0;){const o=[fe({ssrcId:Nt+t},r("USE_SUB_RTX")?{rtx:Nt+t+1}:{})],s="".concat(Nt+t,"_").concat(At+t),a=ot(o,this.cname,r("SYNC_GROUP")?s:void 0),c=a.ssrcs,d=a.ssrcGroups,p=this.preCreateOrRecycleSendMedia("video",c,d,void 0),l=[{ssrcId:At+t}],h="".concat(Nt+t,"_").concat(At+t),u=ot(l,this.cname,r("SYNC_GROUP")?h:void 0),E=u.ssrcs,_=u.ssrcGroups,C=this.preCreateOrRecycleSendMedia("audio",E,_,void 0);e--,t+=2,n.push(p,C),i.push(c[0].ssrcId,E[0].ssrcId)}return this.useLocalCodecsMids.push(...n),this.preloadSsrcs=i,{mids:n,preSSRCs:i,isAvailable:!0}}preCreateOrRecycleSendMedia(t,n,i,o){const r=this.rtpCapabilities.send.videoCodecs,s=this._isUseLocalCodecs||0===r.length?this.localCapabilities.recv:this.rtpCapabilities.send;e.debug("create or recycle send media without remote rtp capabilities, ssrcs ",n[0].ssrcId);const a=t===ke.VIDEO?s.videoCodecs:s.audioCodecs,c=t===ke.VIDEO?s.videoExtensions:s.audioExtensions;this.currentMidIndex+=1;const d="".concat(this.currentMidIndex);let p={media:{mediaType:t,port:gt,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:c,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:n,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(d)}};return p=this.mungSendMediaDesc(p,o),this.sessionDesc.mediaDescriptions.push(p),this.updateBundleMids(),d}toString(){return p(this.sessionDesc)}send(e,t,n,i){const o=ot(t,this.cname,r("SYNC_GROUP")?n:void 0),s=o.ssrcs,a=o.ssrcGroups,p=this.findPreloadMediaDesc(s);if(p){if(c()&&this.firefoxSsrcMidMap.set(s[0].ssrcId,p.attributes.mid),i&&(i.twcc||i.remb)){const e=this.sessionDesc.mediaDescriptions.indexOf(p);return this.sessionDesc.mediaDescriptions[e]=this.mungSendMediaDesc(p,i),{mid:p.attributes.mid,needExchangeSDP:!0}}return{mid:p.attributes.mid,needExchangeSDP:!1}}{const t=this.findAvailableMediaIndex(e,s);let n;return-1===t||1===t&&(_()||C()||m(143)||R(143)||S()||r("RESERVE_MID_1_MLINE")||r("ENABLE_ENCODED_TRANSFORM")&&f())||0===t&&!I(138)&&r("USE_SUB_RTX")||g()?(n=this.createOrRecycleSendMedia(e,s,a,"sendonly",i),this.updateBundleMids()):(n=d(this.sessionDesc.mediaDescriptions[t]),n.attributes.direction="sendonly",n.attributes.ssrcs=s,n.attributes.ssrcGroups=a,this.sessionDesc.mediaDescriptions[t]=this.mungSendMediaDesc(n,i)),c()&&this.firefoxSsrcMidMap.set(s[0].ssrcId,n.attributes.mid),{mid:n.attributes.mid,needExchangeSDP:!0}}}sendDataChannel(){const e=this.createOrRecycleDataChannel(),t=e.mediaDesc,n=e.needExchangeSDP;return this.updateBundleMids(),{mid:t.attributes.mid,needExchangeSDP:n}}batchSend(e){const t=e.map((e=>{let t=e.kind,n=e.ssrcMsg,i=e.mslabel;return this.send(t,n,i)})),n=[];let i=!1;return t.forEach((e=>{let t=e.mid;e.needExchangeSDP&&(i=!0),n.push(t)})),{mids:n,needExchangeSDP:i}}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||c()||g()?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,n,i){e.forEach(((e,o)=>{this.createOrRecycleRecvMedia(e,[],"recvonly",t,n,i[o])})),this.updateBundleMids()}stopReceiving(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>-1!==e.indexOf(t.attributes.mid)));if(t.length!==e.length)throw new Error("MediaDescriptions' length doesn't match mids's length when calling RemoteSDP.receive.");t.forEach((e=>{e.media.port="0",e.attributes.direction="inactive"})),this.updateBundleMids()}updateRemoteRTPCapabilities(e){const t=this.sessionDesc||a((n=this._isUseExtmapAllowMixed,this._isUseDataChannel?It(n):"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(n?"\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 n;this._rtpCapabilities=e;let i=!1;const o=this.rtpCapabilities.send,r=this.localCapabilities.send,s=this.localCapabilities.recv,c=s.videoCodecs,d=s.audioCodecs,p=s.videoExtensions,l=s.audioExtensions;for(const e of t.mediaDescriptions)if("sendonly"!==e.attributes.direction||"string"!=typeof e.attributes.mid||!this.useLocalCodecsMids.includes(e.attributes.mid)){if(i=!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=c.map((e=>e.payloadType.toString(10))),e.attributes.payloads=c,e.attributes.extmaps=p;const t=e.attributes.mid;"string"!=typeof t||this.useLocalCodecsMids.includes(t)||this.useLocalCodecsMids.push(t)}else if(0===o.videoCodecs.length){const t=r.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(r.videoCodecs[0]),e.media.fmts=t.map((e=>e.payloadType.toString(10))),e.attributes.payloads=t,e.attributes.extmaps=[]}else e.media.fmts=o.videoCodecs.map((e=>e.payloadType.toString(10))),e.attributes.payloads=o.videoCodecs,e.attributes.extmaps=o.videoExtensions;if("audio"===e.media.mediaType)if(this._isUseLocalCodecs&&"sendonly"===e.attributes.direction){e.media.fmts=d.map((e=>e.payloadType.toString(10))),e.attributes.payloads=d,e.attributes.extmaps=l;const t=e.attributes.mid;"string"!=typeof t||this.useLocalCodecsMids.includes(t)||this.useLocalCodecsMids.push(t)}else if(0===o.audioCodecs.length){const t=r.audioCodecs.filter((e=>{var t;return null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase().includes("opus")}))||[r.audioCodecs[0]];e.media.fmts=t.map((e=>e.payloadType.toString(10))),e.attributes.payloads=t,e.attributes.extmaps=[]}else e.media.fmts=o.audioCodecs.map((e=>e.payloadType.toString(10))),e.attributes.payloads=o.audioCodecs,e.attributes.extmaps=o.audioExtensions,ht(e)}return this.sessionDesc=t,this.currentMidIndex=t.mediaDescriptions.length-1,[this.sessionDesc,i]}updateCandidates(e){const t=this._originCandidates.filter((e=>"udp"===e.transport)),n=[];if(t.forEach((e=>{n.push(fe(fe({},e),{},{foundation:"tcpcandidate",priority:Number(e.priority)-1+"",transport:"tcp",port:Number(e.port)+90+""}))})),0!==t.length){switch(e){case Fe.TCP_RELAY:this._candidates=n;break;case Fe.UDP_TCP_RELAY:case Fe.RELAY:this._candidates=[...t,...n];break;default:this._candidates=t}for(const e of this.sessionDesc.mediaDescriptions)e.attributes.candidates=this.candidates}}restartICE(e){let t=!1;return e=d(e),this._iceParameters=e,this.sessionDesc.mediaDescriptions.forEach((n=>{n.attributes.iceUfrag===e.iceUfrag&&n.attributes.icePwd===e.icePwd||(t=!0),n.attributes.iceUfrag=e.iceUfrag,n.attributes.icePwd=e.icePwd})),t}predictReceivingMids(e){const t=[];for(let n=0;n<e;n++)t.push((this.currentMidIndex+n+1).toString(10));return t}findAvailableMediaIndex(e,t){return this.sessionDesc.mediaDescriptions.findIndex((n=>{const i=n.media.mediaType===e&&"0"!==n.media.port&&("sendonly"===n.attributes.direction||"sendrecv"===n.attributes.direction)&&0===n.attributes.ssrcs.length;if(c()){if(i){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 i}))}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:gt,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,n,i,o,r){const s=e._mediaStreamTrack.kind,a=this.rtpCapabilities.recv,c=ut(s,a,this.localCapabilities.send,s===ke.VIDEO?i:o),d=s===ke.VIDEO?a.videoExtensions:a.audioExtensions;this.currentMidIndex+=1;const p="".concat(this.currentMidIndex);let l={media:{mediaType:s,port:gt,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:n,rtcpMux:!0,rtcpRsize:!0,mid:"".concat(p)}};l=this.mungRecvMediaDsec(l,e,r);const h=this.findFirstClosedMedia(s);if(h){const e=this.sessionDesc.mediaDescriptions.indexOf(h);this.sessionDesc.mediaDescriptions[e]=l}else this.sessionDesc.mediaDescriptions.push(l);return l}updateRemoteDtlsParameters(e){const t=new Set(this._dtlsParameters.fingerprints.map((e=>e.fingerprint))),n=new Set(e.map((e=>e.fingerprint)));let i=!1;t.size!==n.size&&(i=!0);for(const e of t)n.has(e)||(i=!0);return i}updateRemoteCodec(t,n,i){const o=[...new Set(this._rtpCapabilities.recv.videoCodecs.map((e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"")).filter((e=>Object.keys(A).includes(e))))],s=new Set(n);if(o.every((e=>s.has(e))))return e.debug("codecs has not changed, no need to updateRemoteCodec, codecs: ".concat(n)),!1;const a=this._rtpCapabilities.recv.videoCodecs.filter((e=>n.some((t=>(e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").includes(t)))));if(0===a.length)return e.debug("updateRemoteCodec failed, because cannot find matched codec, remoteCapabilities codecs: ".concat(o," codecs: ").concat(n)),!1;const c=[...new Set(a.map((e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"")))];let d;if(e.debug("updateRemoteCodec, from ".concat(o," to ").concat(c)),0===t.length)d=this.sessionDesc.mediaDescriptions.filter((e=>"video"===e.media.mediaType&&"recvonly"===e.attributes.direction));else if(d=this.sessionDesc.mediaDescriptions.filter((e=>e.attributes.mid&&"video"===e.media.mediaType&&t.includes(e.attributes.mid)&&"recvonly"===e.attributes.direction)),d.length!==t.length)return e.debug("updateRemoteCodec failed, because cannot find mids, mids: ".concat(t,", codecs: ").concat(n)),!1;if(r("USE_PUB_RTX")||r("USE_SUB_RTX")){const e=Et(a,this.rtpCapabilities.recv.videoCodecs);a.push(...e)}this._rtpCapabilities.recv.videoCodecs=a;const p=this.localCapabilities.send,l=this.rtpCapabilities.recv,h=ut(ke.VIDEO,l,p,i);return d.forEach((t=>{const n=h.map((e=>e.payloadType.toString(10)));e.debug("updateRemoteCodec mid: ".concat(t.attributes.mid,", from"),t.attributes.payloads,"to",h),t.attributes.payloads=h,t.media.fmts=n})),e.debug("updateRemoteCodec success, mids: ".concat(t,", codecs: ").concat(n,", remote recv: ").concat(this._rtpCapabilities.recv.videoCodecs.length,", remote send: ").concat(this._rtpCapabilities.send.videoCodecs.length)),!0}createOrRecycleSendMedia(e,t,n,i,o){const r=this.rtpCapabilities.send.videoCodecs,s=this._isUseLocalCodecs||0===r.length?this.localCapabilities.recv:this.rtpCapabilities.send,a=e===ke.VIDEO?s.videoCodecs:s.audioCodecs,c=e===ke.VIDEO?s.videoExtensions:s.audioExtensions;this.currentMidIndex+=1;const d="".concat(this.currentMidIndex);let p={media:{mediaType:e,port:gt,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:c,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:n,rtcpFeedbackWildcards:[],payloads:a,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:i,rtcpMux:!0,rtcpRsize:!0,mid:"".concat(d)}};p=this.mungSendMediaDesc(p,o);const l=this.findFirstClosedMedia(e);if(l){const e=this.sessionDesc.mediaDescriptions.indexOf(l);this.sessionDesc.mediaDescriptions[e]=p}else this.sessionDesc.mediaDescriptions.push(p);return p}updateBundleMids(){this.sessionDesc.attributes.groups[0].identificationTag=this.sessionDesc.mediaDescriptions.filter((e=>"0"!==e.media.port)).map((e=>e.attributes.mid))}mungRecvMediaDsec(e,t,n){const i=d(e);return function(e){const t=e.attributes.unrecognized.findIndex((e=>"x-google-flag"===e.attField&&"conference"===e.attValue));-1!==t&&e.attributes.unrecognized.splice(t,1)}(i),rt(i,t),function(e,t){if(e.attributes.payloads.forEach((e=>{var t;"h264"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())&&e.fmtp&&e.fmtp.parameters&&r("ENABLE_UP_SPS_PPS")&&(e.fmtp.parameters["sps-pps-idr-in-keyframe"]="1")})),!(t instanceof $&&t._encoderConfig&&-1===t._hints.indexOf(te.SCREEN_TRACK)))return;const n=t._encoderConfig;ee().supportMinBitrate&&n.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(n.bitrateMin))})),ee().supportMinBitrate&&!t._hints.includes(te.LOW_STREAM)&&n.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(r("X_GOOGLE_START_BITRATE")||Math.floor(n.bitrateMax)))}))}(i,t),function(e){if("video"!==e.media.mediaType)return;const t=h();if(t.name!==u.SAFARI&&t.os!==E.IOS)return;const n=e.attributes.extmaps.findIndex((e=>/video-orientation/g.test(e.extensionName)));-1!==n&&e.attributes.extmaps.splice(n,1)}(i),st(i,n,this.localCapabilities.send),i}mungSendMediaDesc(e,t){const n=d(e);return n.attributes&&n.attributes.payloads&&Array.isArray(n.attributes.payloads)&&n.attributes.payloads.length>0&&n.attributes.payloads.forEach((e=>{e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase()&&r("ENABLE_DOWN_SPS_PPS")&&(e.fmtp&&e.fmtp.parameters||(e.fmtp={parameters:{}}),e.fmtp.parameters["sps-pps-idr-in-keyframe"]="1")})),st(n,t,this.localCapabilities.recv),ht(n),n}updateRecvMedia(e,t){const n=this.sessionDesc.mediaDescriptions.findIndex((t=>t.attributes.mid===e));if(-1!==n){const e=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[n],t);this.sessionDesc.mediaDescriptions[n]=e}}bumpMid(e){this.currentMidIndex+=e}findFirstClosedMedia(e){return this.sessionDesc.mediaDescriptions.find((t=>c()?"0"===t.media.port&&t.media.mediaType===e:"0"===t.media.port))}findPreloadMediaDesc(e){return this.sessionDesc.mediaDescriptions.find((t=>{var n;return(null===(n=t.attributes)||void 0===n||null===(n=n.ssrcs[0])||void 0===n?void 0:n.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 vt(e){return!!e&&Boolean("number"==typeof e.minDownscaleWidth&&e.minDownscaleWidth>=1||"number"==typeof e.minDownscaleHeight&&e.minDownscaleHeight>=1)}function Dt(e){return"vp8"===e||"vp9"===e}function Ot(e,t,n,i){if("number"!=typeof i)return Array.from({length:n+1},((n,i)=>e/Math.pow(t,i)));const o=Math.max(e,i),r=o/e;if(r<=1)return Array.from({length:n+1},(()=>e));const s=1/t,a=Math.min(n,Math.max(1,Math.ceil(Math.log(r)/Math.log(s)))),c=Math.pow(r,1/a);return Array.from({length:n+1},((t,n)=>{if(0===n)return e;const i=Math.min(n,a);return Math.min(e*Math.pow(c,i),o)}))}function Pt(e,t,n,i){if("number"!=typeof i)return n;const o=Math.max(e,i)/e;if(o<=1)return 0;const r=1/t;return Math.min(n,Math.max(1,Math.ceil(Math.log(o)/Math.log(r))))}var yt=function(e){return e[e.DOWN=0]="DOWN",e[e.UP=1]="UP",e}(yt||{});const Lt=new Map;function wt(e,t,n,i){let o=e.scale;if(0===o&&i===yt.UP||o>=t.length-1&&i===yt.DOWN)return e;let r=fe(fe({},e),{},{scale:i===yt.DOWN?++o:--o});switch(n){case"maintain-framerate":r=fe(fe({},r),t[o].motion);break;case"maintain-resolution":r=fe(fe({},r),t[o].detail);break;case"balanced":r=fe(fe({},r),t[o].balanced)}return r}function bt(e,t,n){if(t){const i={overUse:0,underUse:0,adaptationList:Mt(t,n)};Lt.set(e,i)}else Lt.delete(e)}function Mt(e,t){const n=fe({},e),i=n.bitrateMax,o=n.frameRate,r=n.scaleResolutionDownBy,s=n.bitrateMin,a=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))}(n),c=N.MIN_FRAME_RATE,d=N.MAX_THRESHOLD_FRAMERATE,p=N.MAX_SCALE,l=N.BITRATE_MIN_THRESHOLD,h=N.BITRATE_MAX_THRESHOLD,u=N.BWE_SCALE_UP_THRESHOLD,E=N.BWE_SCALE_DOWN_THRESHOLD,_=N.PERF_SCALE_DOWN_THRESHOLD,C=N.PERF_SCALE_UP_THRESHOLD,m=N.BALANCE_BITRATE_FACTOR,R=N.BALANCE_FRAMERATE_FACTOR,S=N.BALANCE_RESOLUTION_FACTOR,f=N.MOTION_RESOLUTION_FACTOR,I=N.MOTION_BITRATE_FACTOR,g=N.DETAIL_FRAMERATE_FACTOR,A=N.DETAIL_BITRATE_FACTOR,T=Math.min(n.frameRate,d);let v=p;"maintain-framerate"===t?v=Pt(r,f,p,a):"balanced"===t&&(v=Pt(r,S,p,a));const D=Ot(r,S,v,a),O=Ot(r,f,v,a),P=[{scale:0,threshold:{bwe_down:Math.round(Math.pow(E,1)*i),bwe_up:i,fps_down:Math.round(Math.pow(_,1)*T),fps_up:o},balanced:{scaleResolutionDownBy:1,frameRate:o,bitrateMax:i,bitrateMin:s},motion:{scaleResolutionDownBy:1,frameRate:o,bitrateMax:i,bitrateMin:s},detail:{scaleResolutionDownBy:1,frameRate:o,bitrateMax:i,bitrateMin:s}}];for(let e=1;e<=v;e++){const t={bwe_up:Math.round(Math.pow(u,e)*i),bwe_down:Math.round(Math.pow(E,e+1)*i),fps_up:Math.round(Math.pow(C,e)*T),fps_down:Math.round(Math.pow(_,e+1)*T)},n={scaleResolutionDownBy:D[e],frameRate:Math.max(Math.round(Math.pow(R,e)*o),c),bitrateMax:Math.max(Math.round(Math.pow(m,e)*i),h),bitrateMin:Math.max(Math.round(Math.pow(m,e)*s),l)},r={scaleResolutionDownBy:O[e],frameRate:o,bitrateMax:Math.max(Math.round(Math.pow(I,e)*i),h),bitrateMin:Math.max(Math.round(Math.pow(I,e)*s),l)},a={scaleResolutionDownBy:1,frameRate:Math.max(Math.round(Math.pow(g,e)*o),c),bitrateMax:Math.max(Math.round(Math.pow(A,e)*i),h),bitrateMin:Math.max(Math.round(Math.pow(A,e)*s),l)};P.push({scale:e,threshold:t,balanced:n,motion:r,detail:a})}return P}function Ut(e,t,n,i,o,s){const a=Lt.get(e)||{overUse:0,underUse:0,adaptationList:Mt(o,s)},c=a.adaptationList;Lt.set(e,a);const d=N.OVERUSE_TIMES_THRESHOLD,p=N.UNDERUSE_TIMES_THRESHOLD,l=i.scale;let h,u;return"number"==typeof t&&t>0&&function(e,t,n,i){if(t>=n.length)return!1;let o=n[t].threshold.fps_down;return r("FORCE_AG_HIGH_FRAMERATE")&&"maintain-framerate"===i&&(o=n[0].threshold.fps_down),e<o}(t,l,c,s)&&(a.overUse++,u=T.CPU,a.overUse>d)||"number"==typeof n&&n>0&&function(e,t,n){return!(t>=n.length)&&e<n[t].threshold.bwe_down}(n,l,c)&&(a.overUse++,u=T.BANDWIDTH,a.overUse>d)?(a.overUse=0,a.underUse=0,h=wt(i,c,s,yt.DOWN),[h,u]):("number"==typeof t&&t>0&&"number"==typeof n&&n>0&&function(e,t,n,i){if(0===t)return;let o=n[t].threshold.fps_up;return r("FORCE_AG_HIGH_FRAMERATE")&&"maintain-framerate"===i&&(o=n[1].threshold.fps_up),e>o}(t,l,c,s)&&function(e,t,n){if(0===t)return;return e>n[t].threshold.bwe_up}(n,l,c)&&(a.underUse++,a.underUse>p&&(a.overUse=0,a.underUse=0,h=wt(i,c,s,yt.UP),0===h.scale&&(u=T.NONE))),[h,u])}function xt(e,t){return!!r("ENABLE_AG_ADAPTATION")&&(!!vt(t)||!!(e instanceof ne||e._hints.includes(te.CUSTOM_TRACK))&&(!!r("FORCE_SUPPORT_AG_ADAPTATION")||!!(v(14,0,!1)&&D(17,4,!0)||O(14)&&P(17,4,!0))))}const Vt=new Map;function kt(t,n,i,o,s,a){if(Ft(t,i),s(n),"balanced"!==o&&"maintain-framerate"!==o&&"maintain-resolution"!==o)return;let c=-1;bt(t,n,o);const d=window.setInterval((()=>{const d=Vt.get(t);if(!r("ENABLE_AG_ADAPTATION")||!d)return Ft(t,i),void s(n);const p=a();if(p.sendPackets>0&&p.OutgoingAvailableBandwidth>0){if(-1===c)return void(c=Date.now());if(Date.now()-c<1e3)return;const r=p.sendFrameRate,a=p.OutgoingAvailableBandwidth,l=Ie(Ut(t,r,a,d.adaptationConfig,n,o),2),h=l[0],u=l[1];u&&(i.qualityLimitationReason=u),h&&d.adaptationConfig.scale!==h.scale&&(e.debug("[".concat(t,"] applyAdaptation: ").concat(i.qualityLimitationReason,"\n sendFps ").concat(r,", bwe ").concat(a,", switch from ").concat(d.adaptationConfig.scale," to ").concat(h.scale," ")),d.adaptationConfig=fe(fe({},d.adaptationConfig),h),s(h))}}),r("CHECK_LOCAL_STATS_INTERVAL")),p=fe({},n);Vt.set(t,{timer:d,adaptationConfig:p,originConfig:n,adaptationFunc:s}),e.debug("[".concat(t,"] start adaptation, originConfig: ").concat(JSON.stringify(n),", degradationPreference: ").concat(o))}function Ft(e,t){const n=Vt.get(e);if(n){const t=n.timer;window.clearTimeout(t),Vt.delete(e)}t.qualityLimitationReason=T.NONE,bt(e)}const Bt=["balanced","maintain-framerate","maintain-resolution"];function Gt(e){switch(e){case"motion":return"maintain-framerate";case"detail":return"maintain-resolution";case"balanced":return"balanced";default:return}}function Ht(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const n=Gt(e._optimizationMode);if(n)return n;const i=r("CUSTOM_ADAPTATION_DEFAULT_MODE");return e._hints.includes(te.CUSTOM_TRACK)?function(e){return"string"==typeof e&&Bt.includes(e)}(i)?i:t?"maintain-framerate":"":"maintain-framerate"}function Wt(e,t){if(t)return"maintain-resolution";const n=Gt(e._optimizationMode);return n||void 0}function Kt(e,t,n){var i;const o=e.getParameters(),r=null===(i=o.encodings)||void 0===i?void 0:i[0];return r&&Object.assign(r,n),Object.assign(o,t),o}async function Yt(e,t,n){try{return await e.setParameters(Kt(e,t,n)),{classification:"transient"}}catch(i){const o=fe({},n);delete o.scaleResolutionDownBy;try{return await e.setParameters(Kt(e,t,o)),{classification:"unsupported",retryWithScaleError:i}}catch(e){return{classification:"unknown",retryWithScaleError:i,retryWithoutScaleError:e}}}}var jt,Jt;const Xt={};function Qt(e){return function(e){const t=Xt[e];if(!t)throw new y(L.INVALID_OPERATION,"".concat(e," not found, please use AgoraRTC.use(").concat(e,"Service) to load it first"));return t}("AiAudioModeExtension").create(e)}var qt;null!==(Jt=(jt=globalThis).__aiClientControllerCallbacks)&&void 0!==Jt||(jt.__aiClientControllerCallbacks={onMute:null,onUnmute:null,onPlay:null,onStop:null});function zt(e,t,n){const i=e[t];if("function"!=typeof i)throw new Error("Cannot use mutex on object property.");return n.value=async function(){const e=this.mutex,n=await e.lock("From P2PConnection.".concat(t));try{for(var o=arguments.length,r=new Array(o),s=0;s<o;s++)r[s]=arguments[s];return await i.apply(this,r)}finally{n()}},n}function Zt(e){try{if(e.iceServers)return!1;if(e.turnServer&&"off"!==e.turnServer.mode){if(V(e.turnServer.servers))return!1;if(r("FORCE_TURN_TCP")||e.turnServer.servers.concat(e.turnServer.serversFromGateway||[]).some((e=>e.forceturn)))return!0}return!1}catch(e){return!1}}var $t;qt=class n extends Ve{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(A).includes(e))))]}constructor(t,i){if(super(t,i),this.id=l(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:r("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=T.NONE,this.unsupportedResolutionFloorTrackIds=new Set,this.isFirstConnected=!1,this.store=i,this.forceTurn=Zt(t),this.mutex=new w("P2PConnection-mutex",i.clientId),this.peerConnection=new RTCPeerConnection(n.resolvePCConfiguration(t),{optional:[{googDscp:!0}]}),this.isFirstConnected=!1,this.statsFilter=b(this.peerConnection,r("STATS_UPDATE_INTERVAL"),void 0,c()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1,t.isPreallocation&&(this.isPreallocation=!0),this.store.aiClientMode){const t=this.peerConnection.createDataChannel("agora-media",{id:this.store.mediaDcId,ordered:!1,negotiated:!0});t.binaryType="arraybuffer";try{this._nvMedia=Qt(t),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)})),e.debug("[".concat(this.store.clientId,"] [P2PConnection] AI Audio Mode initialized"))}catch(t){this._nvMedia=void 0,e.warning("[".concat(this.store.clientId,"] [P2PConnection] AI Audio Mode not available"),t)}}this.establishPromise=this.establish()}getPreMedia(e){return this.preMediaMap.get(e)}isPreSub(){return this.preMediaMap.size>0}async updateRemoteRTPCapabilities(t,n){if(this.remoteCodecs=n,!this.remoteSDP)return void e.debug("[P2PConnection] cannot updateRemoteRTPCapabilities before remote SDP created, local codecs: ".concat(this.localCodecs,", codecs: ").concat(n));if(this.remoteSDP.updateRemoteCodec(t,n,this.store.codec)){const e=await this.peerConnection.createOffer(),t=this.logSDPExchange(e.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(e);const n=this.remoteSDP.toString();null==t||t(n),await this.peerConnection.setRemoteDescription({type:"answer",sdp:n})}else e.debug("[P2PConnection] updateRemoteRTPCapabilities no need to exchange SDP.")}async establish(){try{this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.peerConnection.addTransceiver("audio",{direction:"recvonly"});const t=await this.peerConnection.createOffer();if(!t.sdp)throw new Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");const n=nt(t.sdp),i=await dt({filterRTX:!r("USE_PUB_RTX")&&!r("USE_SUB_RTX"),filterVideoFec:r("FILTER_VIDEO_FEC"),filterAudioFec:r("FILTER_AUDIO_FEC"),filterVideoCodec:r("FILTER_VIDEO_CODEC"),unsupportedVideoUplinkCodec:r("UNSUPPORTED_VIDEO_UPLINK_CODEC"),unsupportedVideoDownlinkCodec:r("UNSUPPORTED_VIDEO_DOWNLINK_CODEC")},this.extension);if(this.localCapabilities=lt(i),this.initialOffer=t,r("ENABLE_SVC")&&"av1"==this.store.codec){const t=await ct();var e;if(t)this.supportAV1RtpSpec=!0,null===(e=i.send)||void 0===e||e.videoExtensions.push(t)}let o;return t.sdp&&St(t.sdp)&&(o=d(i),Qe(o)),fe(fe({},n),{},{rtpCapabilities:o||i,offerSDP:t.sdp})}catch(e){throw new y(L.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString())}}async connect(t){try{if(!this.initialOffer)throw new Error("Cannot establish P2PConnection without initial offer.");if(this.initialOffer.sdp&&St(this.initialOffer.sdp)&&qe(t.rtpCapabilities,this.localCapabilities),this.remoteSDP=new Tt(fe(fe({},t),{},{localCapabilities:this.localCapabilities}),this.supportAV1RtpSpec,!(!r("ENABLE_PRE_SUB_WITH_PRE_PC")||!r("PRE_USE_LOCAL_CODECS"))&&ie(this.store),this.store.aiClientMode),t.preallocation&&(this.isPreallocation=!0),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0&&this.remoteSDP.updateRemoteCodec([],this.remoteCodecs,this.store.codec),oe()&&ie(this.store)){var n;const t=(null===(n=this.store.preSubOptions)||void 0===n?void 0:n.length)||0,i=r("PRE_SUB_NUM")||1,o=t>i?t:i,s=this.remoteSDP.preloadRemoteMedia(o),a=s.mids,c=s.preSSRCs,d=Ct(this.initialOffer.sdp,this.extension),p=this.logSDPExchange(d||"","offer","local","connect");this.store.descriptionStart(),await this.peerConnection.setLocalDescription({type:"offer",sdp:d}),null==p||p(d),new Array(o).fill(0).forEach((()=>{this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.peerConnection.addTransceiver("audio",{direction:"recvonly"})}));const l=await this.peerConnection.createOffer(),h=this.logSDPExchange(l.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(l);const u=this.remoteSDP.toString();null==h||h(u),await this.peerConnection.setRemoteDescription({type:"answer",sdp:u}),e.debug("[".concat(this.store.clientId,"] [P2PConnection] preload media with icc/dtls, add preload ssrcs ").concat(c)),await this.presetMedia(a,c);const E=this.peerConnection.getTransceivers()[0];null!=E&&E.receiver&&this.tryBindTransportEvents(E.receiver)}else{const n=this.remoteSDP.toString(),o=Ct(this.initialOffer.sdp,this.extension),s=this.logSDPExchange(o||"","offer","local","connect");this.store.descriptionStart(),await this.peerConnection.setLocalDescription({type:"offer",sdp:o}),null==s||s(n),await this.peerConnection.setRemoteDescription({type:"answer",sdp:n});const a=this.peerConnection.getTransceivers()[0];if(null!=a&&a.receiver&&this.tryBindTransportEvents(a.receiver),ie(this.store))if(t.preallocation&&r("ENABLE_PRE_SUB_WITH_PRE_PC")){var i;const t=(null===(i=this.store.preSubOptions)||void 0===i?void 0:i.length)||0,n=r("PRE_SUB_NUM")||1,o=t>n?t:n,s=this.remoteSDP.preloadRemoteMedia(o),a=s.mids,c=s.preSSRCs;await _t(this.peerConnection,this.remoteSDP,this.extension),e.debug("[".concat(this.store.clientId,"] [P2PConnection] preload media, in pre pc,add preload ssrcs ").concat(c)),await this.presetMedia(a,c)}else{const n=t.preSSRCs,i=void 0===n?[]:n,o=i.map((e=>e.ssrcMsg[0].ssrcId));if(0===i.length)return;const r=this.remoteSDP.batchSend(i.map((e=>Object.assign({},e)))).mids;await _t(this.peerConnection,this.remoteSDP,this.extension),e.debug("[P2PConnection.connect] preload media, after join, add preload ssrcs ".concat(o)),await this.presetMedia(r,o)}}}catch(e){throw new y(L.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(e.toString()))}}shouldUseAiAudioPreload(){return this.store.aiClientMode&&this.store.autoSubscribe&&!!this._nvMedia}async presetAiAudioMedia(e,t){if(!this._nvMedia)return;const n=await this._nvMedia.receiveByRTCMedia(ke.AUDIO,[{ssrcId:t}],void 0);this.store.autoReceiveAndPlayAudio&&this._nvMedia.play(),this.preMediaMap.set(t,{mid:e,track:n.track,player:void 0,transceiver:void 0,aiAudioMode:!0})}async presetMedia(t,n){for(const a of t.entries()){var i=Ie(a,2);const t=i[0],c=i[1];for(const i of this.peerConnection.getTransceivers())if(null!=i.mid&&c===i.mid&&i.receiver.track){const a=i.receiver.track;if("audio"===a.kind&&this.shouldUseAiAudioPreload()){await this.presetAiAudioMedia(c,n[t]);break}if(r("PRE_PLAYOUT_DELAY_HINT")){const t=i.receiver;"playoutDelayHint"in t&&(t.playoutDelayHint=r("PRE_PLAYOUT_DELAY_HINT"),e.debug("[".concat(this.store.clientId,"] [P2PConnection] presetMedia set playoutDelayHint to ").concat(r("PRE_PLAYOUT_DELAY_HINT"))))}let d,p;if("video"===a.kind&&r("ENABLE_PRE_RENDER")){var o,s;let i=null===(o=this.store.preSubOptions)||void 0===o||null===(o=o[t])||void 0===o?void 0:o.element;const r=(null===(s=this.store.preSubOptions)||void 0===s||null===(s=s[t])||void 0===s?void 0:s.config)||{};e.debug("try to play pre sub video","string"==typeof i?i:"element","config: ".concat(JSON.stringify(r))),"string"==typeof i&&(i=document.getElementById(i)||void 0),d=i instanceof HTMLVideoElement?new re(fe({trackId:"track-".concat(a.kind,"-unknown-").concat(this.store.clientId,"_").concat(l(5,"")),element:i},r)):new se(fe({trackId:"track-".concat(a.kind,"-unknown-").concat(this.store.clientId,"_").concat(l(5,"")),element:i},r),!i),d.updateVideoTrack(a),d.onFirstVideoFrameRender=()=>{var e;d&&(d.onFirstVideoFrameRender=void 0);const i=this.preMediaMap.get(n[t]);i&&(i.firstVideoRender=Date.now()),null===(e=this.onFirstVideoRender)||void 0===e||e.call(this,n[t])},d.onVideoBufferReady=()=>{var e;null===(e=this.onFirstVideoBufferReady)||void 0===e||e.call(this,n[t])},d.play(this.store.sessionId||void 0),this.isPreRender=!0}if("audio"===a.kind&&this.store.autoReceiveAndPlayAudio){p="track-".concat(a.kind,"-unknown-").concat(this.store.clientId,"_").concat(l(5,""));const t=100;ae.play(a,p,t,this.store.sessionId||void 0),e.debug("[".concat(this.store.clientId,"] [P2PConnection] presetMedia start audio playback, trackId: ").concat(p))}this.preMediaMap.set(n[t],{mid:c,track:a,player:d,transceiver:i,audioTrackId:p});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(n){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.updateRemoteConnect before remote SDP created");let o=!1;const r=n.rtpCapabilities;if(o=Ie(this.remoteSDP.updateRemoteRTPCapabilities(r),2)[1],Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0){const e=this.remoteSDP.updateRemoteCodec([],this.remoteCodecs,this.store.codec);o=o||e}const s=n.preSSRCs,a=void 0===s?[]:s,c=a.map((e=>e.ssrcMsg[0].ssrcId));if(!this.remoteSDP.checkPreloadSsrcs(c)){const n=[],o=[];let r=!1;var i;if(Array.from(this.preMediaMap.entries()).every((e=>{let t=Ie(e,2),i=t[0],s=t[1],a=s.mid,c=s.player,d=(s.track,s.audioTrackId),p=s.aiAudioMode;return n.push(a),o.push(i),this.preMediaMap.delete(i),c&&c.destroy(),d&&ae.stop(d),r=r||!!p,!0})),r)null===(i=this._nvMedia)||void 0===i||i.stopReceiving();if(n.length>0&&(this.remoteSDP.stopSending(n),await _t(this.peerConnection,this.remoteSDP,this.extension),e.warn("[P2PConnection.updateRemoteConnect] preload media, failed, del preload ssrcs ".concat(o)),t.reportApiInvoke(this.store.sessionId,{name:M.PRELOAD_MEDIA_FAILED,options:[a,o],tag:U.TRACER}).onSuccess()),a.length>0){const t=this.remoteSDP.batchSend(a.map((e=>Object.assign({},e)))).mids;await _t(this.peerConnection,this.remoteSDP,this.extension),e.debug("[P2PConnection.updateRemoteConnect] preload media, after join, add preload ssrcs ".concat(c)),await this.presetMedia(t,c)}}o?(await _t(this.peerConnection,this.remoteSDP,this.extension),e.debug("[P2PConnection] updateRemoteConnect by exchanging SDP.")):e.debug("[P2PConnection] updateRemoteConnect no need to exchange SDP, because no need to update remote codecs (use local codecs)")}catch(e){throw new y(L.EXCHANGE_SDP_FAILED,"P2PConnection.updateRemoteConnect failed; ".concat(e.toString()))}}send(e,t,n){var i=this;return ge((function*(){const o=yield me(i.mutex.lock("From P2PConnection.send"));try{if(!i.remoteSDP)throw new Error("Cannot call P2PConnection.send before remote SDP created");const s=[],d=Je();e.forEach((e=>{const t=i.peerConnection.addTransceiver(e._mediaStreamTrack,fe({direction:"sendonly"},"video"===e.trackMediaType&&i.supportAV1RtpSpec&&d?{sendEncodings:[{scalabilityMode:d}]}:{}));s.push(t),e._updateRtpTransceiver(t)})),c()&&!0===r("SIMULCAST")&&(yield me(i.applySimulcastForFirefox(s,e)));const p=yield me(i.peerConnection.createOffer()),l=i.remoteSDP.predictReceivingMids(e.length),h=i.mungSendOfferSDP(p.sdp,e,l),u=a(h),E=l.map((e=>{const t=u.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error("Cannot extract ssrc from mediaDescription.");return it(t,r("USE_PUB_RTX"))}));let _;try{_=yield E}catch(o){_=[],i.remoteSDP.receive(e,t,n,_);const r=i.remoteSDP.toString();throw yield me(i.peerConnection.setLocalDescription({type:"offer",sdp:h})),yield me(i.peerConnection.setRemoteDescription({type:"answer",sdp:r})),yield me(i.stopSending(l,!0)),o}i.remoteSDP.receive(e,t,n,_);const C=i.remoteSDP.toString(),m=i.logSDPExchange(h,"offer","local","send");return yield me(i.peerConnection.setLocalDescription({type:"offer",sdp:h})),yield me(i.applySimulcastEncodings(s,e)),yield me(i.applySendEncodings(s,e)),null==m||m(C),yield me(i.peerConnection.setRemoteDescription({type:"answer",sdp:C})),s.map(((e,t)=>{const n=l[t];return{localSSRC:E[t],id:n,transceiver:e}}))}catch(e){throw e instanceof y?e:new y(L.EXCHANGE_SDP_FAILED,"P2PConnection.send failed; ".concat(e.toString()))}finally{o()}}))()}async createDataChannels(t,n){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.createDataChannels before remote SDP created");let i=this.dataStreamChannelMap.get(t);if(i&&"open"===i.readyState)e.debug("[P2PConnection] Channels are already available and can be reused directly.");else{const e=this.currentDataChannelId<1023?this.currentDataChannelId++:this.recoveredDataChannelIds.shift();if("number"!=typeof e)throw new Error("create DataChannel error, because cannot get dc id");i=this.peerConnection.createDataChannel("datastream-channel",{id:e,negotiated:!0,ordered:!1,maxRetransmits:r("DATASTREAM_MAX_RETRANSMITS")}),i.binaryType="arraybuffer",this.dataStreamChannelMap.set(t,i)}n.forEach((e=>{e._updateOriginDataChannel(i)}));const o=this.remoteSDP.sendDataChannel();if(o.needExchangeSDP){const t=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(n),e.debug("[P2PConnection] createDataChannels by exchanging SDP.")}else e.debug("[P2PConnection] createDataChannels no need to exchange SDP.");return}catch(e){throw e instanceof y?e:new y(L.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 y?e:new y(L.DATACHANNEL_FAILED,"P2PConnection.stopDataChannels failed; ".concat(e.toString()))}}async stopSending(e,t){const n=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;Ft(this.id+e.mid,this),e.direction="inactive",null===(t=e.stop)||void 0===t||t.call(e)}));const i=await this.peerConnection.createOffer(),o=this.logSDPExchange(i.sdp||"","offer","local","stopSending");await this.peerConnection.setLocalDescription(i),this.remoteSDP.stopReceiving(e);const r=this.remoteSDP.toString();null==o||o(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new y(L.EXCHANGE_SDP_FAILED,"P2PConnection.stopSending failed; ".concat(e.toString()))}finally{n&&n()}}async receive(t,n,i,o){if(this._nvMedia&&t===ke.AUDIO)return e.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(t," by DataChannel.")),await this._nvMedia.receiveByRTCMedia(t,n,void 0);try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.receive ".concat(t," before remoteSDP created."));const s=this.remoteSDP.send(t,n,i,o),a=s.mid;s.needExchangeSDP&&(await _t(this.peerConnection,this.remoteSDP,this.extension),e.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(t," by exchanging SDP.")));const c=this.peerConnection.getTransceivers().find((e=>e.mid===a));if(!c)throw new Error("Cannot get transceiver after setLocalDescription.");if(r("PRE_PLAYOUT_DELAY_HINT")){const n=c.receiver;"playoutDelayHint"in n&&(n.playoutDelayHint=r("PRE_PLAYOUT_DELAY_HINT"),e.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(t," set playoutDelayHint to ").concat(r("PRE_PLAYOUT_DELAY_HINT"))))}return{track:c.receiver.track,id:a,transceiver:c}}catch(e){throw new y(L.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()))}}async batchReceive(t){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.batchReceive before remoteSDP created.");const n=this.remoteSDP.batchSend(t),i=n.mids;return n.needExchangeSDP&&(await _t(this.peerConnection,this.remoteSDP,this.extension),e.debug("[".concat(this.store.clientId,"] [P2PConnection] batchReceive by exchanging SDP."))),i.map((t=>{const n=this.peerConnection.getTransceivers().find((e=>e.mid===t));if(!n)throw new Error("Cannot get transceiver after setLocalDescription.");if(r("PRE_PLAYOUT_DELAY_HINT")){const t=n.receiver;"playoutDelayHint"in t&&(t.playoutDelayHint=r("PRE_PLAYOUT_DELAY_HINT"),e.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(t.track.kind," set playoutDelayHint to ").concat(r("PRE_PLAYOUT_DELAY_HINT"))))}return{track:n.receiver.track,id:t,transceiver:n}}))}catch(e){throw new y(L.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((n=>{let i=Ie(n,2),o=i[0],r=i[1],s=r.mid,a=r.player,c=r.audioTrackId,d=r.aiAudioMode;if(s===e)return this.preMediaMap.delete(o),a&&a.destroy(),c&&ae.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 n=this.remoteSDP.toString(),i=this.logSDPExchange(n,"offer","remote","stopReceiving");await this.peerConnection.setRemoteDescription({type:"offer",sdp:n});const o=await this.peerConnection.createAnswer();null==i||i(o.sdp||""),await this.peerConnection.setLocalDescription(o)}catch(e){throw new y(L.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(),n=this.logSDPExchange(t,"offer","remote","muteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const i=await this.peerConnection.createAnswer();null==n||n(i.sdp||""),await this.peerConnection.setLocalDescription(i)}catch(e){throw new y(L.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(),n=this.logSDPExchange(t,"offer","remote","unmuteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const i=await this.peerConnection.createAnswer();null==n||n(i.sdp||""),await this.peerConnection.setLocalDescription(i)}catch(e){throw new y(L.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 n=await this.peerConnection.createOffer(),i=this.logSDPExchange(n.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(n),this.remoteSDP.muteRemote(e);const o=this.remoteSDP.toString();null==i||i(o),await this.peerConnection.setRemoteDescription({type:"answer",sdp:o})}catch(e){throw new y(L.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 n=await this.peerConnection.createOffer(),i=this.logSDPExchange(n.sdp||"","offer","local","unmuteLocal");await this.peerConnection.setLocalDescription(n),this.remoteSDP.unmuteRemote(e),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0&&this.remoteSDP.updateRemoteCodec(e,this.remoteCodecs,this.store.codec);const o=this.remoteSDP.toString();null==i||i(o),await this.peerConnection.setRemoteDescription({type:"answer",sdp:o})}catch(e){throw new y(L.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteLocal failed; ".concat(e.toString()))}}restartICE(t){var n=this;return ge((function*(){const i=yield me(n.mutex.lock("From P2PConnection.restartICE"));try{if(!n.remoteSDP)throw new Error("Cannot restartICE before remoteSDP created.");const o=ee().supportPCSetConfiguration,s=r("FORCE_TURN_TCP")||n.forceTurn;if(t===Fe.RELAY&&!o)return;if(o&&!s){const i=t===Fe.RELAY?"relay":"all",o=n.peerConnection.getConfiguration();o.iceTransportPolicy!==i&&(e.debug("[".concat(n.store.clientId,"] restartICE change iceTransportPolicy from [").concat(o.iceTransportPolicy,"] to [").concat(i,"]")),o.iceTransportPolicy=i,n.peerConnection.setConfiguration(o))}n.remoteSDP.updateCandidates(t);const a=yield me(n.peerConnection.createOffer({iceRestart:!0}));if(!a.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const c=nt(a.sdp),d=(yield c.iceParameters).remoteIceParameters;n.remoteSDP.restartICE(d);const p=n.remoteSDP.toString(),l=n.logSDPExchange(a.sdp||"","offer","local","restartICE");n.store.descriptionStart(),yield me(n.peerConnection.setLocalDescription(a)),null==l||l(p),yield me(n.peerConnection.setRemoteDescription({type:"answer",sdp:p}))}catch(t){e.warning("[".concat(n.store.clientId,"] restart ICE failed, abort operation"),t)}finally{i()}}))()}async extendCandidate(){if(!this.remoteSDP||this.isFirstConnected)return;const t=await this.mutex.lock("From P2PConnection.extendCandidate");try{this.remoteSDP.updateCandidates(Fe.TCP_RELAY),await _t(this.peerConnection,this.remoteSDP,this.extension)}catch(t){e.warning("[".concat(this.store.clientId,"] extend candidate failed, abort operation"),t)}finally{t()}}close(){var e,t,n,i;null===(e=this._nvMedia)||void 0===e||e.setAudioMetadataHandler(null),null===(t=this._nvMedia)||void 0===t||t.setAudioPtsHandler(null),null===(n=this._nvMedia)||void 0===n||n.close(),this._nvMedia=void 0,this.peerConnection.getTransceivers().forEach((e=>{Ft(this.id+e.mid,this)})),this.preMediaMap.forEach((e=>{let t=e.player,n=e.audioTrackId;t&&t.destroy(),n&&ae.stop(n)})),this.preMediaMap.clear(),this.peerConnection.close(),null===(i=this.onConnectionStateChange)||void 0===i||i.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=fe(fe({},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 n=await this.peerConnection.createOffer(),i=this.mungSendOfferSDP(n.sdp,[t],[e]);this.remoteSDP.updateRecvMedia(e,t);const o=this.remoteSDP.toString(),r=this.logSDPExchange(i,"offer","local","updateEncoderConfig");await this.peerConnection.setLocalDescription({type:"offer",sdp:i}),null==r||r(o),await this.peerConnection.setRemoteDescription({type:"answer",sdp:o})}catch(e){throw new y(L.EXCHANGE_SDP_FAILED,e.toString())}}async updateSendParameters(e,t){const n=this.peerConnection.getTransceivers().filter((t=>t.mid===e));1===n.length&&(this.isVP8Simulcast(t)?c()||await this.applySimulcastEncodings(n,[t]):await this.applySendEncodings(n,[t]))}setStatsRemoteVideoIsReady(e,t){this.statsFilter.setVideoIsReady2(e,t)}async replaceTrack(e,t){const n=this.peerConnection.getTransceivers().find((e=>e.mid===t));n&&await n.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(),n=t.local,i=t.remote;return{local:fe(fe({},x),{},{candidateType:n.type,protocol:n.protocol,address:n.address,port:n.port}),remote:fe(fe({},x),{},{candidateType:i.type,protocol:i.protocol,address:i.address,port:i.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=t=>{if(t&&(t.errorCode||t.errorText)){var n;const i="code: ".concat(t.errorCode,", message: ").concat(t.errorText),o=t.port?"local: ".concat(t.port):"",r=Ye(t.url||"");e.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICECandidateError(").concat(i,"), url: ").concat(r||"",", host_candidate:").concat(o)),null===(n=this.onICECandidateError)||void 0===n||n.call(this,i)}},this.peerConnection.onicegatheringstatechange=t=>{t&&t.target&&"iceGatheringState"in t.target&&e.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] RTCPeerConnection.onicegatheringstatechange(").concat(t.target.iceGatheringState,")"))},this.peerConnection.onicecandidate=t=>{t.candidate?this.localCandidateCount+=1:(this.peerConnection.onicecandidate=null,this.allCandidatesReceived=!0,e.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount))},setTimeout((()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,e.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount))}),r("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(e){const t={iceServers:[]},i=e.cloudProxyServer||"disabled";return e.iceServers?t.iceServers=e.iceServers:e.turnServer&&(V(e.turnServer.servers)?t.iceServers=e.turnServer.servers:r("NEW_TURN_MODE")&&t.iceServers&&"disabled"===i?(r("USE_TURN_SERVER_OF_GATEWAY")?e.turnServer.serversFromGateway&&t.iceServers.push(...n.newTurnServerConfigToIceServers(e.turnServer.serversFromGateway)):t.iceServers.push(...n.newTurnServerConfigToIceServers(e.turnServer.servers)),r("NEW_FORCE_TURN")&&(t.iceTransportPolicy="relay")):"off"!==e.turnServer.mode&&(t.iceServers&&t.iceServers.push(...n.turnServerConfigToIceServers(e.turnServer.servers)),r("USE_TURN_SERVER_OF_GATEWAY")&&t.iceServers&&e.turnServer.serversFromGateway&&t.iceServers.push(...n.turnServerConfigToIceServers(e.turnServer.serversFromGateway)),r("FORCE_TURN_TCP")?t.iceTransportPolicy="relay":e.turnServer.servers.concat(e.turnServer.serversFromGateway||[]).forEach((e=>{e.forceturn&&(t.iceTransportPolicy="relay")})))),r("ENABLE_ENCODED_TRANSFORM")&&ee().supportWebRTCEncodedTransform&&(t.encodedInsertableStreams=!0),t}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(We(e.turnServerURL),":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&!r("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 n=r("NEW_TURN_MODE");1===n?t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=udp")}):2===n?t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=tcp")}):3===n?t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(We(e.turnServerURL),":443?transport=tcp")}):4===n&&(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(We(e.turnServerURL),":443?transport=tcp")}))})),t}tryBindTransportEvents(t){const n=t.transport;if(n){this.transportEventReceiver=t,n.onstatechange=()=>{var e;null!=n&&n.state&&(null===(e=this.onDTLSTransportStateChange)||void 0===e||e.call(this,n.state))},n.onerror=e=>{var t;null===(t=this.onDTLSTransportError)||void 0===t||t.call(this,"error"in e?e.error:e)};const i=n.iceTransport;i&&(i.onstatechange=()=>{const e=null==n?void 0:n.iceTransport.state;var t;e&&(null===(t=this.onICETransportStateChange)||void 0===t||t.call(this,e))},i.getSelectedCandidatePair&&(i.onselectedcandidatepairchange=()=>{if(i.getSelectedCandidatePair()){const t=i.getSelectedCandidatePair()||{},n=t.local,o=t.remote;if(n&&o){const t=n.address+":"+n.port,i=o.address+":"+o.port;e.info("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] selectedcandidatepairchange: local ").concat(JSON.stringify(Ye(t)),", remote ").concat(JSON.stringify(Ye(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(t,n){var i;if(!n){const e=this.peerConnection.getSenders();n=e.find((e=>e.track===t._mediaStreamTrack))}if(!n)return e.warn("[".concat(t.getTrackId(),"] no rtpSender found}"));if(this.isVP8Simulcast(t))return e.warn("[updateRtpSenderEncodings] Track is VP8 simulcast, please apply simulcast encodings");if(!ee().supportSetRtpSenderParameters)return e.warn("[updateRtpSenderEncodings] Browser not support set rtp-sender parameters");const o=ce(t),s=!!o&&Dt(this.store.codec)&&vt(o),a=s&&!this.unsupportedResolutionFloorTrackIds.has(t.getTrackId()),d=!!o&&!(s&&!a)&&xt(t,a?o:void 0),p=a&&d,l=a||["vp8","vp9"].includes(this.store.codec),h={},u={},E=Wt(t,p);E&&(h.degradationPreference=E);const _=je(this.peerConnection,t._mediaStreamTrack);if(d&&_&&n&&o&&this.getLocalVideoStats&&l){const e=this.id+_.mid,i=Ht(t,a);kt(e,o,this,i,(i=>{n&&this.updateAdaptation(t,n,i,e,a)}),this.getLocalVideoStats.bind(this))}if(t._encoderConfig){const e=t._encoderConfig,n=e.bitrateMax,i=e.frameRate,o=e.scaleResolutionDownBy;n&&(u.maxBitrate=1e3*n),(t._hints.includes(te.LOW_STREAM)||t.isUseScaleResolutionDownBy)&&(i&&(u.maxFramerate=Ke(i)),o&&o>=1&&(u.scaleResolutionDownBy=o))}const C=r("ENCODER_CONFIG_LIMIT").maxFramerate;if(C&&"number"==typeof C&&(u.maxFramerate=u.maxFramerate?Math.min(u.maxFramerate,C):C),r("DSCP_TYPE")&&k()){const e=r("DSCP_TYPE");["very-low","low","medium","high"].includes(e)&&(u.networkPriority=e)}const m=n.getParameters(),R=null===(i=m.encodings)||void 0===i?void 0:i[0];c()&&!R&&(h.encodings=[u]),R&&Object.assign(R,u),Object.assign(m,h),e.debug("[".concat(t.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(m.encodings))),await n.setParameters(m),await Rt(this.store.codec,n,r("SVC_MODE"))}async updateAdaptation(t,n,i,o,r){var s;if(!n)return e.debug("[updateAdaptation] no rtpSender found");if(!ee().supportSetRtpSenderParameters)return e.debug("[updateAdaptation] Browser not support set rtp-sender parameters");const a={},c={},d=i.bitrateMax,p=i.frameRate,l=i.scaleResolutionDownBy;d&&(c.maxBitrate=1e3*d),p&&(c.maxFramerate=Ke(p));let h=!1;"number"==typeof l&&l>=1&&(r||["vp8","vp9"].includes(this.store.codec))&&(c.scaleResolutionDownBy=l,h=l>1);const u=n.getParameters(),E=null===(s=u.encodings)||void 0===s?void 0:s[0];E&&Object.assign(E,c),Object.assign(u,a);try{await n.setParameters(u),e.debug("[updateAdaptation] updateRtpSenderEncodings: ".concat(JSON.stringify(u.encodings)))}catch(i){if(!("transport"in n)||n.transport&&"connected"===n.transport.state)if("connected"!==this.peerConnectionState)e.debug("[updateAdaptation] peerConnection not connected}");else if(r&&h){const r=await Yt(n,a,c);"unsupported"===r.classification?(this.unsupportedResolutionFloorTrackIds.add(t.getTrackId()),Ft(o,this),e.warn("[".concat(t.getTrackId(),"] fallback to browser adaptation because scaleResolutionDownBy adaptation is unsupported"),i,r.retryWithScaleError),this.updateRtpSenderEncodings(t,n).catch((n=>{e.warn("[".concat(t.getTrackId(),"] failed to re-apply browser adaptation after disabling resolution floor"),n)}))):"transient"===r.classification?e.debug("[".concat(t.getTrackId(),"] keep resolution floor enabled after transient setParameters failure"),i):e.debug("[".concat(t.getTrackId(),"] keep resolution floor enabled because setParameters failure is not classified as unsupported"),i,r.retryWithScaleError,r.retryWithoutScaleError)}else e.debug("[updateAdaptation] updateRtpSenderEncodings failed",i);else e.debug("[updateAdaptation] rtpSender transport not connected}")}}async applySendEncodings(t,n){try{if(!ee().supportSetRtpSenderParameters)return;if(t.length!==n.length)return;for(let e=0;e<t.length;e++){const i=t[e],o=n[e];o instanceof $&&!this.isVP8Simulcast(o)&&await this.updateRtpSenderEncodings(o,i.sender)}}catch(t){e.debug("[".concat(this.store.clientId,"] Apply RTPSendEncodings failed."))}}mungSendOfferSDP(e,t,n){if(r("FORBID_MODIFY_LOCAL_OFFER_SDP"))return e;const i=a(e);return t.forEach(((e,t)=>{const o=n[t],r=i.mediaDescriptions.find((e=>e.attributes.mid===o));r&&(rt(r,e),at(r,e,this.store.codec))})),p(i)}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,n)=>{var i;null===(i=this.onFirstVideoDecoded)||void 0===i||i.call(this,e,t,n)},this.statsFilter.onSelectedLocalCandidateChanged=(e,t)=>{var n;null===(n=this.onSelectedLocalCandidateChanged)||void 0===n||n.call(this,e,t)},this.statsFilter.onSelectedRemoteCandidateChanged=(e,t)=>{var n;null===(n=this.onSelectedRemoteCandidateChanged)||void 0===n||n.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 s=0;s<e.length;s++){var n,i,o,r;const a=e[s],c=t[s];if(c instanceof $&&!c._hints.includes(te.LOW_STREAM)&&null!==(n=c._encoderConfig)&&void 0!==n&&n.bitrateMax&&(null===(i=c._encoderConfig)||void 0===i?void 0:i.bitrateMax)>200&&null!==(o=c._scalabilityMode)&&void 0!==o&&o.numSpatialLayers&&(null===(r=c._scalabilityMode)||void 0===r?void 0:r.numSpatialLayers)>1&&"vp8"===this.store.codec){const e={},t={high:1e3*(c._encoderConfig.bitrateMax-50),medium:5e4};e.encodings=[{rid:"m",active:!0,maxBitrate:t.medium,scaleResolutionDownBy:4},{rid:"h",active:!0,maxBitrate:t.high}];const n=a.sender.getParameters();await a.sender.setParameters(Object.assign(n,e))}}}async applySimulcastEncodings(e,t){if(!c()&&e.length===t.length)for(let n=0;n<e.length;n++){const i=t[n];if(i instanceof $&&this.isVP8Simulcast(i)){const t=e[n],o={},r={high:1e3*(i._encoderConfig.bitrateMax-50),medium:5e4};o.encodings=[{active:!0,adaptivePtime:!1,networkPriority:"high",priority:"high",maxBitrate:r.high},{active:!0,adaptivePtime:!1,networkPriority:"low",priority:"low",maxBitrate:r.medium,scaleResolutionDownBy:4}];const s=t.sender.getParameters();await t.sender.setParameters(Object.assign(s,o))}}}isVP8Simulcast(e){var t,n,i,o;return!!(e instanceof $&&r("SIMULCAST")&&"vp8"===this.store.codec&&!e._hints.includes(te.LOW_STREAM)&&null!==(t=e._encoderConfig)&&void 0!==t&&t.bitrateMax&&(null===(n=e._encoderConfig)||void 0===n?void 0:n.bitrateMax)>200&&null!==(i=e._scalabilityMode)&&void 0!==i&&i.numSpatialLayers&&(null===(o=e._scalabilityMode)||void 0===o?void 0:o.numSpatialLayers)>1)}logSDPExchange(t,n,i,o){if(r("SDP_LOGGING"))return e.upload("[".concat(this.store.clientId,"] exchanging ").concat(i," ").concat(n," SDP during P2PConnection.").concat(o,"\n"),t),"offer"===n?e=>{this.logSDPExchange(e,"answer","local"===i?"remote":"local",o)}: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(e){if(ee().supportPCSetConfiguration){const t=n.resolvePCConfiguration(e);this.peerConnection.setConfiguration(t)}e.isPreallocation&&(this.isPreallocation=!0)}},he(qt.prototype,"updateRemoteRTPCapabilities",[zt],Object.getOwnPropertyDescriptor(qt.prototype,"updateRemoteRTPCapabilities"),qt.prototype),he(qt.prototype,"connect",[zt],Object.getOwnPropertyDescriptor(qt.prototype,"connect"),qt.prototype),he(qt.prototype,"updateRemoteConnect",[zt],Object.getOwnPropertyDescriptor(qt.prototype,"updateRemoteConnect"),qt.prototype),he(qt.prototype,"createDataChannels",[zt],Object.getOwnPropertyDescriptor(qt.prototype,"createDataChannels"),qt.prototype),he(qt.prototype,"receive",[zt],Object.getOwnPropertyDescriptor(qt.prototype,"receive"),qt.prototype),he(qt.prototype,"batchReceive",[zt],Object.getOwnPropertyDescriptor(qt.prototype,"batchReceive"),qt.prototype),he(qt.prototype,"stopReceiving",[zt],Object.getOwnPropertyDescriptor(qt.prototype,"stopReceiving"),qt.prototype),he(qt.prototype,"muteRemote",[zt],Object.getOwnPropertyDescriptor(qt.prototype,"muteRemote"),qt.prototype),he(qt.prototype,"unmuteRemote",[zt],Object.getOwnPropertyDescriptor(qt.prototype,"unmuteRemote"),qt.prototype),he(qt.prototype,"muteLocal",[zt],Object.getOwnPropertyDescriptor(qt.prototype,"muteLocal"),qt.prototype),he(qt.prototype,"unmuteLocal",[zt],Object.getOwnPropertyDescriptor(qt.prototype,"unmuteLocal"),qt.prototype),he(qt.prototype,"close",[zt],Object.getOwnPropertyDescriptor(qt.prototype,"close"),qt.prototype),he(qt.prototype,"updateEncoderConfig",[zt],Object.getOwnPropertyDescriptor(qt.prototype,"updateEncoderConfig"),qt.prototype),he(qt.prototype,"updateSendParameters",[zt],Object.getOwnPropertyDescriptor(qt.prototype,"updateSendParameters"),qt.prototype),he(qt.prototype,"replaceTrack",[zt],Object.getOwnPropertyDescriptor(qt.prototype,"replaceTrack"),qt.prototype),he(qt.prototype,"updateAdaptation",[zt],Object.getOwnPropertyDescriptor(qt.prototype,"updateAdaptation"),qt.prototype),he(qt.prototype,"getRemoteSSRC",[zt],Object.getOwnPropertyDescriptor(qt.prototype,"getRemoteSSRC"),qt.prototype),!ee().supportUnifiedPlan||r("CHROME_FORCE_PLAN_B")&&k();let en=($t=class n extends Ve{get currentLocalDescription(){return this.peerConnection.currentLocalDescription}get currentRemoteDescription(){return this.peerConnection.currentRemoteDescription}get peerConnectionState(){return this.peerConnection.connectionState}get iceConnectionState(){return this.peerConnection.iceConnectionState}get dtlsTransportState(){var e,t;return null!==(e=null===(t=this.peerConnection.getReceivers()[0])||void 0===t||null===(t=t.transport)||void 0===t?void 0:t.state)&&void 0!==e?e:null}get localCodecs(){return[...new Set(this.localCapabilities&&this.localCapabilities.send.videoCodecs.map((e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"")).filter((e=>Object.keys(A).includes(e))))]}constructor(e,t,n){super(e,t),this.id=l(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:r("USE_XR")},this.localCapabilities=void 0,this.remoteCodecs=void 0,this.localCandidateCount=0,this.allCandidatesReceived=!1,this.isPreallocation=!1,this.preMediaMap=new Map,this.dataStreamChannelMap=new Map,this.establishPromise=void 0,this.recoveredDataChannelIds=[],this.currentDataChannelId=1,this.supportAV1RtpSpec=!1,this.mutex=void 0,this.qualityLimitationReason=T.NONE,this.unsupportedResolutionFloorTrackIds=new Set,this.isFirstConnected=!1,this.store=t,this.forceTurn=Zt(e),this.mutex=new w("NVConnectionExtension-mutex",t.clientId),this.peerConnection=n,this.isFirstConnected=!1,this.statsFilter=b(this.peerConnection,r("STATS_UPDATE_INTERVAL"),void 0,c()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1,e.isPreallocation&&(this.isPreallocation=!0),this.establishPromise=this.establish()}getPreMedia(e){return this.preMediaMap.get(e)}isPreSub(){return this.preMediaMap.size>0}async updateRemoteRTPCapabilities(t,n){if(this.remoteCodecs=n,!this.remoteSDP)return void e.debug("[NVConnectionExtension] cannot updateRemoteRTPCapabilities before remote SDP created, local codecs: ".concat(this.localCodecs,", codecs: ").concat(n));if(this.remoteSDP.updateRemoteCodec(t,n,this.store.codec)){const e=await this.peerConnection.createOffer(),t=this.logSDPExchange(e.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(e);const n=this.remoteSDP.toString();null==t||t(n),await this.peerConnection.setRemoteDescription({type:"answer",sdp:n})}else e.debug("[NVConnectionExtension] updateRemoteRTPCapabilities no need to exchange SDP.")}async establish(){try{this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.peerConnection.addTransceiver("audio",{direction:"recvonly"});const t=await this.peerConnection.createOffer();if(!t.sdp)throw new Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");const n=nt(t.sdp),i=await dt({filterRTX:!r("USE_PUB_RTX")&&!r("USE_SUB_RTX"),filterVideoFec:r("FILTER_VIDEO_FEC"),filterAudioFec:r("FILTER_AUDIO_FEC"),filterVideoCodec:r("FILTER_VIDEO_CODEC"),unsupportedVideoUplinkCodec:r("UNSUPPORTED_VIDEO_UPLINK_CODEC"),unsupportedVideoDownlinkCodec:r("UNSUPPORTED_VIDEO_DOWNLINK_CODEC")},this.extension);if(this.localCapabilities=lt(i),this.initialOffer=t,r("ENABLE_SVC")&&"av1"==this.store.codec){const t=await ct();var e;if(t)this.supportAV1RtpSpec=!0,null===(e=i.send)||void 0===e||e.videoExtensions.push(t)}let o;return t.sdp&&St(t.sdp)&&(o=d(i),Qe(o)),fe(fe({},n),{},{rtpCapabilities:o||i,offerSDP:t.sdp})}catch(e){throw new y(L.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString())}}async connect(t){try{if(!this.initialOffer)throw new Error("Cannot establish NVConnectionExtension without initial offer.");if(this.initialOffer.sdp&&St(this.initialOffer.sdp)&&qe(t.rtpCapabilities,this.localCapabilities),this.remoteSDP=new Tt(fe(fe({},t),{},{localCapabilities:this.localCapabilities}),this.supportAV1RtpSpec,!(!r("ENABLE_PRE_SUB_WITH_PRE_PC")||!r("PRE_USE_LOCAL_CODECS"))&&ie(this.store),!0),t.preallocation&&(this.isPreallocation=!0),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0&&this.remoteSDP.updateRemoteCodec([],this.remoteCodecs,this.store.codec),oe()){var n;const t=(null===(n=this.store.preSubOptions)||void 0===n?void 0:n.length)||0,i=r("PRE_SUB_NUM")||1,o=t>i?t:i,s=this.remoteSDP.preloadRemoteMedia(o),a=s.mids,c=s.preSSRCs,d=Ct(this.initialOffer.sdp,this.extension),p=this.logSDPExchange(d||"","offer","local","connect");this.store.descriptionStart(),await this.peerConnection.setLocalDescription({type:"offer",sdp:d}),null==p||p(d),new Array(o).fill(0).forEach((()=>{this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.peerConnection.addTransceiver("audio",{direction:"recvonly"})}));const l=await this.peerConnection.createOffer(),h=this.logSDPExchange(l.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(l);const u=this.remoteSDP.toString();null==h||h(u),await this.peerConnection.setRemoteDescription({type:"answer",sdp:u}),e.debug("[".concat(this.store.clientId,"] [P2PConnection] preload media with icc/dtls, add preload ssrcs ").concat(c)),this.presetMedia(a,c);const E=this.peerConnection.getTransceivers()[0];null!=E&&E.receiver&&this.tryBindTransportEvents(E.receiver)}else{const n=this.remoteSDP.toString(),o=Ct(this.initialOffer.sdp,this.extension),s=this.logSDPExchange(o||"","offer","local","connect");this.store.descriptionStart(),await this.peerConnection.setLocalDescription({type:"offer",sdp:o}),null==s||s(n),await this.peerConnection.setRemoteDescription({type:"answer",sdp:n});const a=this.peerConnection.getTransceivers()[0];if(null!=a&&a.receiver&&this.tryBindTransportEvents(a.receiver),ie(this.store))if(t.preallocation&&r("ENABLE_PRE_SUB_WITH_PRE_PC")){var i;const t=(null===(i=this.store.preSubOptions)||void 0===i?void 0:i.length)||0,n=r("PRE_SUB_NUM")||1,o=t>n?t:n,s=this.remoteSDP.preloadRemoteMedia(o),a=s.mids,c=s.preSSRCs;await _t(this.peerConnection,this.remoteSDP,this.extension),e.debug("[".concat(this.store.clientId,"] [P2PConnection] preload media, in pre pc,add preload ssrcs ").concat(c)),this.presetMedia(a,c)}else{const n=t.preSSRCs,i=void 0===n?[]:n,o=i.map((e=>e.ssrcMsg[0].ssrcId));if(0===i.length)return;const r=this.remoteSDP.batchSend(i.map((e=>Object.assign({},e)))).mids;await _t(this.peerConnection,this.remoteSDP,this.extension),e.debug("[P2PConnection.connect] preload media, after join, add preload ssrcs ".concat(o)),this.presetMedia(r,o)}}}catch(e){throw new y(L.EXCHANGE_SDP_FAILED,"NVConnectionExtension.connect failed; ".concat(e.toString()))}}presetMedia(e,t){e.forEach(((e,n)=>{this.peerConnection.getTransceivers().forEach((i=>{if(null!=i.mid&&e===i.mid&&i.receiver.track){const o=i.receiver.track;let s;"video"===o.kind&&r("ENABLE_PRE_RENDER")&&(s=new se({trackId:"track-".concat(o.kind,"-unknown-").concat(this.store.clientId,"_").concat(l(5,""))},!0),s.updateVideoTrack(o),s.onFirstVideoFrameRender=()=>{var e;const i=this.preMediaMap.get(t[n]);i&&(i.firstVideoRender=Date.now()),null===(e=this.onFirstVideoRender)||void 0===e||e.call(this,t[n])},s.onVideoBufferReady=()=>{var e;null===(e=this.onFirstVideoBufferReady)||void 0===e||e.call(this,t[n])},s.play(this.store.sessionId||void 0)),this.preMediaMap.set(t[n],{mid:e,track:o,player:s,transceiver:i})}})),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(n){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.updateRemoteConnect before remote SDP created");let i=!1;const o=n.rtpCapabilities;if(i=Ie(this.remoteSDP.updateRemoteRTPCapabilities(o),2)[1],Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0){const e=this.remoteSDP.updateRemoteCodec([],this.remoteCodecs,this.store.codec);i=i||e}const r=n.preSSRCs,s=void 0===r?[]:r,a=s.map((e=>e.ssrcMsg[0].ssrcId));if(!this.remoteSDP.checkPreloadSsrcs(a)){const n=[],i=[];if(Array.from(this.preMediaMap.entries()).every((e=>{let t=Ie(e,2),o=t[0],r=t[1],s=r.mid,a=r.player;r.track;return n.push(s),i.push(o),this.preMediaMap.delete(o),a&&a.destroy(),!0})),n.length>0&&(this.remoteSDP.stopSending(n),await _t(this.peerConnection,this.remoteSDP,this.extension),e.warn("[NVConnectionExtension.updateRemoteConnect] preload media, failed, del preload ssrcs ".concat(i)),t.reportApiInvoke(this.store.sessionId,{name:M.PRELOAD_MEDIA_FAILED,options:[s,i],tag:U.TRACER}).onSuccess()),s.length>0){const t=this.remoteSDP.batchSend(s.map((e=>Object.assign({},e)))).mids;await _t(this.peerConnection,this.remoteSDP,this.extension),e.debug("[NVConnectionExtension.updateRemoteConnect] preload media, after join, add preload ssrcs ".concat(a)),this.presetMedia(t,a)}}i?(await _t(this.peerConnection,this.remoteSDP,this.extension),e.debug("[NVConnectionExtension] updateRemoteConnect by exchanging SDP.")):e.debug("[NVConnectionExtension] updateRemoteConnect no need to exchange SDP, because no need to update remote codecs (use local codecs)")}catch(e){throw new y(L.EXCHANGE_SDP_FAILED,"NVConnectionExtension.updateRemoteConnect failed; ".concat(e.toString()))}}send(e,t,n){var i=this;return ge((function*(){const o=yield me(i.mutex.lock("From NVConnectionExtension.send"));try{if(!i.remoteSDP)throw new Error("Cannot call NVConnectionExtension.send before remote SDP created");const s=[],d=Je();e.forEach((e=>{const t=i.peerConnection.addTransceiver(e._mediaStreamTrack,fe({direction:"sendonly"},"video"===e.trackMediaType&&i.supportAV1RtpSpec&&d?{sendEncodings:[{scalabilityMode:d}]}:{}));s.push(t),e._updateRtpTransceiver(t)})),c()&&!0===r("SIMULCAST")&&(yield me(i.applySimulcastForFirefox(s,e)));const p=yield me(i.peerConnection.createOffer()),l=i.remoteSDP.predictReceivingMids(e.length),h=i.mungSendOfferSDP(p.sdp,e,l),u=a(h),E=l.map((e=>{const t=u.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error("Cannot extract ssrc from mediaDescription.");return it(t,r("USE_PUB_RTX"))}));let _;try{_=yield E}catch(o){_=[],i.remoteSDP.receive(e,t,n,_);const r=i.remoteSDP.toString();throw yield me(i.peerConnection.setLocalDescription({type:"offer",sdp:h})),yield me(i.peerConnection.setRemoteDescription({type:"answer",sdp:r})),yield me(i.stopSending(l,!0)),o}i.remoteSDP.receive(e,t,n,_);const C=i.remoteSDP.toString(),m=i.logSDPExchange(h,"offer","local","send");return yield me(i.peerConnection.setLocalDescription({type:"offer",sdp:h})),yield me(i.applySimulcastEncodings(s,e)),yield me(i.applySendEncodings(s,e)),null==m||m(C),yield me(i.peerConnection.setRemoteDescription({type:"answer",sdp:C})),s.map(((e,t)=>{const n=l[t];return{localSSRC:E[t],id:n,transceiver:e}}))}catch(e){throw e instanceof y?e:new y(L.EXCHANGE_SDP_FAILED,"NVConnectionExtension.send failed; ".concat(e.toString()))}finally{o()}}))()}async createDataChannels(t,n){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.createDataChannels before remote SDP created");let i=this.dataStreamChannelMap.get(t);if(i&&"open"===i.readyState)e.debug("[NVConnectionExtension] Channels are already available and can be reused directly.");else{const e=this.currentDataChannelId<1023?this.currentDataChannelId++:this.recoveredDataChannelIds.shift();if("number"!=typeof e)throw new Error("create DataChannel error, because cannot get dc id");i=this.peerConnection.createDataChannel("datastream-channel",{id:e,negotiated:!0,ordered:!1,maxRetransmits:r("DATASTREAM_MAX_RETRANSMITS")}),i.binaryType="arraybuffer",this.dataStreamChannelMap.set(t,i)}n.forEach((e=>{e._updateOriginDataChannel(i)}));const o=this.remoteSDP.sendDataChannel();if(o.needExchangeSDP){const t=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(n),e.debug("[NVConnectionExtension] createDataChannels by exchanging SDP.")}else e.debug("[NVConnectionExtension] createDataChannels no need to exchange SDP.");return}catch(e){throw e instanceof y?e:new y(L.EXCHANGE_SDP_FAILED,"NVConnectionExtension.createDataChannels failed; ".concat(e.toString()))}}async stopDataChannels(e){try{const t=this.dataStreamChannelMap.get(e);return t&&(t.id&&this.recoveredDataChannelIds.push(t.id),t.close()),void this.dataStreamChannelMap.delete(e)}catch(e){throw e instanceof y?e:new y(L.DATACHANNEL_FAILED,"NVConnectionExtension.stopDataChannels failed; ".concat(e.toString()))}}async stopSending(e,t){const n=t?void 0:await this.mutex.lock("From NVConnectionExtension.stopSending");try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.stopSending before remote SDP created");const t=this.peerConnection.getTransceivers().filter((t=>-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length when trying to call NVConnectionExtension.stopSending.");t.map((e=>{var t;Ft(this.id+e.mid,this),e.direction="inactive",null===(t=e.stop)||void 0===t||t.call(e)}));const i=await this.peerConnection.createOffer(),o=this.logSDPExchange(i.sdp||"","offer","local","stopSending");await this.peerConnection.setLocalDescription(i),this.remoteSDP.stopReceiving(e);const r=this.remoteSDP.toString();null==o||o(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new y(L.EXCHANGE_SDP_FAILED,"NVConnectionExtension.stopSending failed; ".concat(e.toString()))}finally{n&&n()}}async receive(t,n,i,o){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.receive ".concat(t," before remoteSDP created."));const r=this.remoteSDP.send(t,n,i,o),s=r.mid;r.needExchangeSDP&&(await _t(this.peerConnection,this.remoteSDP,this.extension),e.debug("[".concat(this.store.clientId,"] [NVConnectionExtension] receive ").concat(t," by exchanging SDP.")));const a=this.peerConnection.getTransceivers().find((e=>e.mid===s));if(!a)throw new Error("Cannot get transceiver after setLocalDescription.");return{track:a.receiver.track,id:s,transceiver:a}}catch(e){throw new y(L.EXCHANGE_SDP_FAILED,"NVConnectionExtension.receive failed; ".concat(e.toString()))}}async batchReceive(t){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.batchReceive before remoteSDP created.");const n=this.remoteSDP.batchSend(t),i=n.mids;return n.needExchangeSDP&&(await _t(this.peerConnection,this.remoteSDP,this.extension),e.debug("[".concat(this.store.clientId,"] [NVConnectionExtension] batchReceive by exchanging SDP."))),i.map((e=>{const t=this.peerConnection.getTransceivers().find((t=>t.mid===e));if(!t)throw new Error("Cannot get transceiver after setLocalDescription.");return{track:t.receiver.track,id:e,transceiver:t}}))}catch(e){throw new y(L.EXCHANGE_SDP_FAILED,"NVConnectionExtension.receive failed; ".concat(e.toString()))}}async stopReceiving(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.stopReceiving before remote SDP created.");e.forEach((e=>{Array.from(this.preMediaMap.entries()).some((t=>{let n=Ie(t,2),i=n[0],o=n[1],r=o.mid,s=o.player;if(r===e)return this.preMediaMap.delete(i),s&&s.destroy(),!0}))})),this.remoteSDP.stopSending(e);const t=this.remoteSDP.toString(),n=this.logSDPExchange(t,"offer","remote","stopReceiving");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const i=await this.peerConnection.createAnswer();null==n||n(i.sdp||""),await this.peerConnection.setLocalDescription(i)}catch(e){throw new y(L.EXCHANGE_SDP_FAILED,"NVConnectionExtension stopReceiving failed; ".concat(e.toString()))}}async muteRemote(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.muteRemote mid=".concat(e," before remote SDP created."));this.remoteSDP.mute(e);const t=this.remoteSDP.toString(),n=this.logSDPExchange(t,"offer","remote","muteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const i=await this.peerConnection.createAnswer();null==n||n(i.sdp||""),await this.peerConnection.setLocalDescription(i)}catch(e){throw new y(L.EXCHANGE_SDP_FAILED,"NVConnectionExtension.muteRemote failed; ".concat(e.toString()))}}async unmuteRemote(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.unmuteRemote mid=".concat(e," before remote SDP created."));this.remoteSDP.unmute(e);const t=this.remoteSDP.toString(),n=this.logSDPExchange(t,"offer","remote","unmuteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const i=await this.peerConnection.createAnswer();null==n||n(i.sdp||""),await this.peerConnection.setLocalDescription(i)}catch(e){throw new y(L.EXCHANGE_SDP_FAILED,"NVConnectionExtension.unmuteRemote failed; ".concat(e.toString()))}}async muteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.muteLocal before remote SDP created.");const t=this.peerConnection.getTransceivers().filter((t=>t.mid&&-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length.");t.map((e=>{e.direction="inactive"}));const n=await this.peerConnection.createOffer(),i=this.logSDPExchange(n.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(n),this.remoteSDP.muteRemote(e);const o=this.remoteSDP.toString();null==i||i(o),await this.peerConnection.setRemoteDescription({type:"answer",sdp:o})}catch(e){throw new y(L.EXCHANGE_SDP_FAILED,"NVConnectionExtension.muteLocal failed; ".concat(e.toString()))}}async unmuteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.unmuteLocal before remote SDP created.");const t=this.peerConnection.getTransceivers().filter((t=>t.mid&&-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length.");t.map((async(e,t)=>{e.direction="sendonly"}));const n=await this.peerConnection.createOffer(),i=this.logSDPExchange(n.sdp||"","offer","local","unmuteLocal");await this.peerConnection.setLocalDescription(n),this.remoteSDP.unmuteRemote(e),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0&&this.remoteSDP.updateRemoteCodec(e,this.remoteCodecs,this.store.codec);const o=this.remoteSDP.toString();null==i||i(o),await this.peerConnection.setRemoteDescription({type:"answer",sdp:o})}catch(e){throw new y(L.EXCHANGE_SDP_FAILED,"NVConnectionExtension.unmuteLocal failed; ".concat(e.toString()))}}restartICE(t){var n=this;return ge((function*(){const i=yield me(n.mutex.lock("From NVConnectionExtension.restartICE"));try{if(!n.remoteSDP)throw new Error("Cannot restartICE before remoteSDP created.");const o=ee().supportPCSetConfiguration,s=r("FORCE_TURN_TCP")||n.forceTurn;if(t===Fe.RELAY&&!o)return;if(o&&!s){const i=t===Fe.RELAY?"relay":"all",o=n.peerConnection.getConfiguration();o.iceTransportPolicy!==i&&(e.debug("[".concat(n.store.clientId,"] restartICE change iceTransportPolicy from [").concat(o.iceTransportPolicy,"] to [").concat(i,"]")),o.iceTransportPolicy=i,n.peerConnection.setConfiguration(o))}n.remoteSDP.updateCandidates(t);const a=yield me(n.peerConnection.createOffer({iceRestart:!0}));if(!a.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const c=nt(a.sdp),d=(yield c.iceParameters).remoteIceParameters;n.remoteSDP.restartICE(d);const p=n.remoteSDP.toString(),l=n.logSDPExchange(a.sdp||"","offer","local","restartICE");n.store.descriptionStart(),yield me(n.peerConnection.setLocalDescription(a)),null==l||l(p),yield me(n.peerConnection.setRemoteDescription({type:"answer",sdp:p}))}catch(t){e.warning("[".concat(n.store.clientId,"] restart ICE failed, abort operation"),t)}finally{i()}}))()}async extendCandidate(){if(!this.remoteSDP||this.isFirstConnected)return;const t=await this.mutex.lock("From NVConnectionExtension.extendCandidate");try{this.remoteSDP.updateCandidates(Fe.TCP_RELAY),await _t(this.peerConnection,this.remoteSDP,this.extension)}catch(t){e.warning("[".concat(this.store.clientId,"] extend candidate failed, abort operation"),t)}finally{t()}}close(){var e;this.peerConnection.getTransceivers().forEach((e=>{Ft(this.id+e.mid,this)})),this.preMediaMap.forEach((e=>{let t=e.player;t&&t.destroy()})),this.preMediaMap.clear(),this.peerConnection.close(),null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,"closed"),this.tryUnbindTransportEvents(),this.unbindPCEvents(),this.unbindStatsEvents(),this.removeAllListeners(),this.transportEventReceiver=void 0,this.statsFilter.destroy(),this.dataStreamChannelMap.clear(),this.recoveredDataChannelIds=[],this.currentDataChannelId=1}getStats(){return fe(fe({},this.statsFilter.getStats()),{},{qualityLimitationReason:this.qualityLimitationReason})}getRemoteVideoIsReady(e){return this.statsFilter.getVideoIsReady(e)}async updateEncoderConfig(e,t){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.updateEncoderConfig before remote SDP created.");const n=await this.peerConnection.createOffer(),i=this.mungSendOfferSDP(n.sdp,[t],[e]);this.remoteSDP.updateRecvMedia(e,t);const o=this.remoteSDP.toString(),r=this.logSDPExchange(i,"offer","local","updateEncoderConfig");await this.peerConnection.setLocalDescription({type:"offer",sdp:i}),null==r||r(o),await this.peerConnection.setRemoteDescription({type:"answer",sdp:o})}catch(e){throw new y(L.EXCHANGE_SDP_FAILED,e.toString())}}async updateSendParameters(e,t){const n=this.peerConnection.getTransceivers().filter((t=>t.mid===e));1===n.length&&(this.isVP8Simulcast(t)?c()||await this.applySimulcastEncodings(n,[t]):await this.applySendEncodings(n,[t]))}setStatsRemoteVideoIsReady(e,t){this.statsFilter.setVideoIsReady2(e,t)}async replaceTrack(e,t){const n=this.peerConnection.getTransceivers().find((e=>e.mid===t));n&&await n.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(),n=t.local,i=t.remote;return{local:fe(fe({},x),{},{candidateType:n.type,protocol:n.protocol,address:n.address,port:n.port}),remote:fe(fe({},x),{},{candidateType:i.type,protocol:i.protocol,address:i.address,port:i.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=t=>{if(t&&(t.errorCode||t.errorText)){var n;const i="code: ".concat(t.errorCode,", message: ").concat(t.errorText),o=t.port?"local: ".concat(t.port):"",r=Ye(t.url||"");e.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: NVConnectionExtension.onICECandidateError(").concat(i,"), url: ").concat(r||"",", host_candidate:").concat(o)),null===(n=this.onICECandidateError)||void 0===n||n.call(this,i)}},this.peerConnection.onicegatheringstatechange=t=>{t&&t.target&&"iceGatheringState"in t.target&&e.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] RTCPeerConnection.onicegatheringstatechange(").concat(t.target.iceGatheringState,")"))},this.peerConnection.onicecandidate=t=>{t.candidate?this.localCandidateCount+=1:(this.peerConnection.onicecandidate=null,this.allCandidatesReceived=!0,e.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount))},setTimeout((()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,e.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount))}),r("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(e){const t={iceServers:[]},i=e.cloudProxyServer||"disabled";return e.iceServers?t.iceServers=e.iceServers:e.turnServer&&(V(e.turnServer.servers)?t.iceServers=e.turnServer.servers:r("NEW_TURN_MODE")&&t.iceServers&&"disabled"===i?(r("USE_TURN_SERVER_OF_GATEWAY")?e.turnServer.serversFromGateway&&t.iceServers.push(...n.newTurnServerConfigToIceServers(e.turnServer.serversFromGateway)):t.iceServers.push(...n.newTurnServerConfigToIceServers(e.turnServer.servers)),r("NEW_FORCE_TURN")&&(t.iceTransportPolicy="relay")):"off"!==e.turnServer.mode&&(t.iceServers&&t.iceServers.push(...n.turnServerConfigToIceServers(e.turnServer.servers)),r("USE_TURN_SERVER_OF_GATEWAY")&&t.iceServers&&e.turnServer.serversFromGateway&&t.iceServers.push(...n.turnServerConfigToIceServers(e.turnServer.serversFromGateway)),r("FORCE_TURN_TCP")?t.iceTransportPolicy="relay":e.turnServer.servers.concat(e.turnServer.serversFromGateway||[]).forEach((e=>{e.forceturn&&(t.iceTransportPolicy="relay")})))),r("ENABLE_ENCODED_TRANSFORM")&&ee().supportWebRTCEncodedTransform&&(t.encodedInsertableStreams=!0),t}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(We(e.turnServerURL),":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&!r("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 n=r("NEW_TURN_MODE");1===n?t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=udp")}):2===n?t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=tcp")}):3===n?t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(We(e.turnServerURL),":443?transport=tcp")}):4===n&&(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(We(e.turnServerURL),":443?transport=tcp")}))})),t}tryBindTransportEvents(t){const n=t.transport;if(n){this.transportEventReceiver=t,n.onstatechange=()=>{var e;null!=n&&n.state&&(null===(e=this.onDTLSTransportStateChange)||void 0===e||e.call(this,n.state))},n.onerror=e=>{var t;null===(t=this.onDTLSTransportError)||void 0===t||t.call(this,"error"in e?e.error:e)};const i=n.iceTransport;i&&(i.onstatechange=()=>{const e=null==n?void 0:n.iceTransport.state;var t;e&&(null===(t=this.onICETransportStateChange)||void 0===t||t.call(this,e))},i.getSelectedCandidatePair&&(i.onselectedcandidatepairchange=()=>{if(i.getSelectedCandidatePair()){const t=i.getSelectedCandidatePair()||{},n=t.local,o=t.remote;if(n&&o){const t=n.address+":"+n.port,i=o.address+":"+o.port;e.info("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] selectedcandidatepairchange: local ").concat(JSON.stringify(Ye(t)),", remote ").concat(JSON.stringify(Ye(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(t,n){var i;if(!n){const e=this.peerConnection.getSenders();n=e.find((e=>e.track===t._mediaStreamTrack))}if(!n)return e.warn("[".concat(t.getTrackId(),"] no rtpSender found}"));if(this.isVP8Simulcast(t))return e.warn("[updateRtpSenderEncodings] Track is VP8 simulcast, please apply simulcast encodings");if(!ee().supportSetRtpSenderParameters)return e.warn("[updateRtpSenderEncodings] Browser not support set rtp-sender parameters");const o=ce(t),s=!!o&&Dt(this.store.codec)&&vt(o),a=s&&!this.unsupportedResolutionFloorTrackIds.has(t.getTrackId()),d=!!o&&!(s&&!a)&&xt(t,a?o:void 0),p=a&&d,l=a||["vp8","vp9"].includes(this.store.codec),h={},u={},E=Wt(t,p);E&&(h.degradationPreference=E);const _=je(this.peerConnection,t._mediaStreamTrack);if(d&&_&&n&&o&&this.getLocalVideoStats&&l){const e=this.id+_.mid,i=Ht(t,a);kt(e,o,this,i,(i=>{n&&this.updateAdaptation(t,n,i,e,a)}),this.getLocalVideoStats.bind(this))}if(t._encoderConfig){const e=t._encoderConfig,n=e.bitrateMax,i=e.frameRate,o=e.scaleResolutionDownBy;n&&(u.maxBitrate=1e3*n),(t._hints.includes(te.LOW_STREAM)||t.isUseScaleResolutionDownBy)&&(i&&(u.maxFramerate=Ke(i)),o&&o>=1&&(u.scaleResolutionDownBy=o))}const C=r("ENCODER_CONFIG_LIMIT").maxFramerate;if(C&&"number"==typeof C&&(u.maxFramerate=u.maxFramerate?Math.min(u.maxFramerate,C):C),r("DSCP_TYPE")&&k()){const e=r("DSCP_TYPE");["very-low","low","medium","high"].includes(e)&&(u.networkPriority=e)}const m=n.getParameters(),R=null===(i=m.encodings)||void 0===i?void 0:i[0];c()&&!R&&(h.encodings=[u]),R&&Object.assign(R,u),Object.assign(m,h),e.debug("[".concat(t.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(m.encodings))),await n.setParameters(m),await Rt(this.store.codec,n,r("SVC_MODE"))}async updateAdaptation(t,n,i,o,r){var s;if(!n)return e.debug("[updateAdaptation] no rtpSender found");if(!ee().supportSetRtpSenderParameters)return e.debug("[updateAdaptation] Browser not support set rtp-sender parameters");const a={},c={},d=i.bitrateMax,p=i.frameRate,l=i.scaleResolutionDownBy;d&&(c.maxBitrate=1e3*d),p&&(c.maxFramerate=Ke(p));let h=!1;"number"==typeof l&&l>=1&&(r||["vp8","vp9"].includes(this.store.codec))&&(c.scaleResolutionDownBy=l,h=l>1);const u=n.getParameters(),E=null===(s=u.encodings)||void 0===s?void 0:s[0];E&&Object.assign(E,c),Object.assign(u,a);try{await n.setParameters(u),e.debug("[updateAdaptation] updateRtpSenderEncodings: ".concat(JSON.stringify(u.encodings)))}catch(i){if(!("transport"in n)||n.transport&&"connected"===n.transport.state)if("connected"!==this.peerConnectionState)e.debug("[updateAdaptation] peerConnection not connected}");else if(r&&h){const r=await Yt(n,a,c);"unsupported"===r.classification?(this.unsupportedResolutionFloorTrackIds.add(t.getTrackId()),Ft(o,this),e.warn("[".concat(t.getTrackId(),"] fallback to browser adaptation because scaleResolutionDownBy adaptation is unsupported"),i,r.retryWithScaleError),this.updateRtpSenderEncodings(t,n).catch((n=>{e.warn("[".concat(t.getTrackId(),"] failed to re-apply browser adaptation after disabling resolution floor"),n)}))):"transient"===r.classification?e.debug("[".concat(t.getTrackId(),"] keep resolution floor enabled after transient setParameters failure"),i):e.debug("[".concat(t.getTrackId(),"] keep resolution floor enabled because setParameters failure is not classified as unsupported"),i,r.retryWithScaleError,r.retryWithoutScaleError)}else e.debug("[updateAdaptation] updateRtpSenderEncodings failed",i);else e.debug("[updateAdaptation] rtpSender transport not connected}")}}async applySendEncodings(t,n){try{if(!ee().supportSetRtpSenderParameters)return;if(t.length!==n.length)return;for(let e=0;e<t.length;e++){const i=t[e],o=n[e];o instanceof $&&!this.isVP8Simulcast(o)&&await this.updateRtpSenderEncodings(o,i.sender)}}catch(t){e.debug("[".concat(this.store.clientId,"] Apply RTPSendEncodings failed."))}}mungSendOfferSDP(e,t,n){const i=a(e);return t.forEach(((e,t)=>{const o=n[t],r=i.mediaDescriptions.find((e=>e.attributes.mid===o));r&&(rt(r,e),at(r,e,this.store.codec))})),p(i)}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,n)=>{var i;null===(i=this.onFirstVideoDecoded)||void 0===i||i.call(this,e,t,n)},this.statsFilter.onSelectedLocalCandidateChanged=(e,t)=>{var n;null===(n=this.onSelectedLocalCandidateChanged)||void 0===n||n.call(this,e,t)},this.statsFilter.onSelectedRemoteCandidateChanged=(e,t)=>{var n;null===(n=this.onSelectedRemoteCandidateChanged)||void 0===n||n.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 s=0;s<e.length;s++){var n,i,o,r;const a=e[s],c=t[s];if(c instanceof $&&!c._hints.includes(te.LOW_STREAM)&&null!==(n=c._encoderConfig)&&void 0!==n&&n.bitrateMax&&(null===(i=c._encoderConfig)||void 0===i?void 0:i.bitrateMax)>200&&null!==(o=c._scalabilityMode)&&void 0!==o&&o.numSpatialLayers&&(null===(r=c._scalabilityMode)||void 0===r?void 0:r.numSpatialLayers)>1&&"vp8"===this.store.codec){const e={},t={high:1e3*(c._encoderConfig.bitrateMax-50),medium:5e4};e.encodings=[{rid:"m",active:!0,maxBitrate:t.medium,scaleResolutionDownBy:4},{rid:"h",active:!0,maxBitrate:t.high}];const n=a.sender.getParameters();await a.sender.setParameters(Object.assign(n,e))}}}async applySimulcastEncodings(e,t){if(!c()&&e.length===t.length)for(let n=0;n<e.length;n++){const i=t[n];if(i instanceof $&&this.isVP8Simulcast(i)){const t=e[n],o={},r={high:1e3*(i._encoderConfig.bitrateMax-50),medium:5e4};o.encodings=[{active:!0,adaptivePtime:!1,networkPriority:"high",priority:"high",maxBitrate:r.high},{active:!0,adaptivePtime:!1,networkPriority:"low",priority:"low",maxBitrate:r.medium,scaleResolutionDownBy:4}];const s=t.sender.getParameters();await t.sender.setParameters(Object.assign(s,o))}}}isVP8Simulcast(e){var t,n,i,o;return!!(e instanceof $&&r("SIMULCAST")&&"vp8"===this.store.codec&&!e._hints.includes(te.LOW_STREAM)&&null!==(t=e._encoderConfig)&&void 0!==t&&t.bitrateMax&&(null===(n=e._encoderConfig)||void 0===n?void 0:n.bitrateMax)>200&&null!==(i=e._scalabilityMode)&&void 0!==i&&i.numSpatialLayers&&(null===(o=e._scalabilityMode)||void 0===o?void 0:o.numSpatialLayers)>1)}logSDPExchange(t,n,i,o){if(r("SDP_LOGGING"))return e.upload("[".concat(this.store.clientId,"] exchanging ").concat(i," ").concat(n," SDP during NVConnectionExtension.").concat(o,"\n"),t),"offer"===n?e=>{this.logSDPExchange(e,"answer","local"===i?"remote":"local",o)}: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(e){if(ee().supportPCSetConfiguration){const t=n.resolvePCConfiguration(e);this.peerConnection.setConfiguration(t)}e.isPreallocation&&(this.isPreallocation=!0)}},he($t.prototype,"updateRemoteRTPCapabilities",[tn],Object.getOwnPropertyDescriptor($t.prototype,"updateRemoteRTPCapabilities"),$t.prototype),he($t.prototype,"connect",[tn],Object.getOwnPropertyDescriptor($t.prototype,"connect"),$t.prototype),he($t.prototype,"updateRemoteConnect",[tn],Object.getOwnPropertyDescriptor($t.prototype,"updateRemoteConnect"),$t.prototype),he($t.prototype,"createDataChannels",[tn],Object.getOwnPropertyDescriptor($t.prototype,"createDataChannels"),$t.prototype),he($t.prototype,"receive",[tn],Object.getOwnPropertyDescriptor($t.prototype,"receive"),$t.prototype),he($t.prototype,"batchReceive",[tn],Object.getOwnPropertyDescriptor($t.prototype,"batchReceive"),$t.prototype),he($t.prototype,"stopReceiving",[tn],Object.getOwnPropertyDescriptor($t.prototype,"stopReceiving"),$t.prototype),he($t.prototype,"muteRemote",[tn],Object.getOwnPropertyDescriptor($t.prototype,"muteRemote"),$t.prototype),he($t.prototype,"unmuteRemote",[tn],Object.getOwnPropertyDescriptor($t.prototype,"unmuteRemote"),$t.prototype),he($t.prototype,"muteLocal",[tn],Object.getOwnPropertyDescriptor($t.prototype,"muteLocal"),$t.prototype),he($t.prototype,"unmuteLocal",[tn],Object.getOwnPropertyDescriptor($t.prototype,"unmuteLocal"),$t.prototype),he($t.prototype,"close",[tn],Object.getOwnPropertyDescriptor($t.prototype,"close"),$t.prototype),he($t.prototype,"updateEncoderConfig",[tn],Object.getOwnPropertyDescriptor($t.prototype,"updateEncoderConfig"),$t.prototype),he($t.prototype,"updateSendParameters",[tn],Object.getOwnPropertyDescriptor($t.prototype,"updateSendParameters"),$t.prototype),he($t.prototype,"replaceTrack",[tn],Object.getOwnPropertyDescriptor($t.prototype,"replaceTrack"),$t.prototype),he($t.prototype,"updateAdaptation",[tn],Object.getOwnPropertyDescriptor($t.prototype,"updateAdaptation"),$t.prototype),he($t.prototype,"getRemoteSSRC",[tn],Object.getOwnPropertyDescriptor($t.prototype,"getRemoteSSRC"),$t.prototype),$t);function tn(e,t,n){const i=e[t];if("function"!=typeof i)throw new Error("Cannot use mutex on object property.");return n.value=async function(){const e=this.mutex,n=await e.lock("From NVConnectionExtension.".concat(t));try{for(var o=arguments.length,r=new Array(o),s=0;s<o;s++)r[s]=arguments[s];return await i.apply(this,r)}finally{n()}},n}var nn;let on=(nn=class t extends Ve{get currentLocalDescription(){return this.peerConnection.currentLocalDescription}get currentRemoteDescription(){return this.peerConnection.currentRemoteDescription}get peerConnectionState(){return this.peerConnection.connectionState}get iceConnectionState(){return this.peerConnection.iceConnectionState}get localCodecs(){return this._p2pConnection.localCodecs}constructor(e,n){super(e,n),this.name="DataChannelConnection",this.store=void 0,this.peerConnection=void 0,this.cname=void 0,this.mutex=new w("DataChannelConnection-mutex"),this.dataChannel=void 0,this._p2pConnection=void 0,this.establishPromise=void 0,this.store=n,this.store.dcId=this.store.dcId+1,this.peerConnection=new RTCPeerConnection(t.resolvePCConfiguration(e),{optional:[{googDscp:!0}]}),this.dataChannel=this.peerConnection.createDataChannel("agora-signal",{ordered:!1,maxPacketLifeTime:50}),this.dataChannel.binaryType="arraybuffer",this._p2pConnection=new en(e,n,this.peerConnection),this.bindPCEvents(),this.establishPromise=this._p2pConnection.establishPromise}getPreMedia(e){var t;return null===(t=this._p2pConnection)||void 0===t?void 0:t.getPreMedia(e)}isPreSub(){var e,t;return null!==(e=null===(t=this._p2pConnection)||void 0===t?void 0:t.isPreSub())&&void 0!==e&&e}async establish(){return await this._p2pConnection.establish()}getP2PConnectionParams(){return this._p2pConnection.establishPromise}updateRtpSenderEncodings(e){return this._p2pConnection.updateRtpSenderEncodings(e)}async connect(e){return this.cname=e.cname,await this._p2pConnection.connect(e),await new Promise(((t,i)=>{const o=setTimeout((()=>{this.closeSignal(),i(new n(L.DATACHANNEL_CONNECTION_TIMEOUT,"Datachannel connection timed out, candidates: ".concat(JSON.stringify(e.candidates))))}),r("DC_CONNECTION_TIMEOUT"));this.dataChannel.onopen=()=>{if("open"===this.dataChannel.readyState)return clearTimeout(o),void t()},this.dataChannel.onerror=e=>{this.closeSignal(),i(e)},this.dataChannel.addEventListener("close",(()=>{i(new n(L.DATACHANNEL_CONNECTION_TIMEOUT))}))})),{transmitter:this.dataChannel,close:this.closeSignal.bind(this)}}checkDtlsParameters(e){return this._p2pConnection.checkDtlsParameters(e)}checkIceParameters(e){return this._p2pConnection.checkIceParameters(e)}async updateRemoteRTPCapabilities(e,t){return this._p2pConnection.updateRemoteRTPCapabilities(e,t)}send(e,t,n){var i=this;return ge((function*(){const o=yield me(i.mutex.lock("From DataChannelConnection.send"));try{return yield*Ee(_e(i._p2pConnection.send(e,t,n)))}finally{o()}}))()}async stopSending(e,t){return this._p2pConnection.stopSending(e,t)}async createDataChannels(e,t){return this._p2pConnection.createDataChannels(e,t)}async stopDataChannels(e){return this._p2pConnection.stopDataChannels(e)}async receive(t,n,i,o){return e.debug("[DataChannelConnection] receive ".concat(t," by WebRTC.")),await this._p2pConnection.receive(t,n,i,o)}async batchReceive(e){return[...await this._p2pConnection.batchReceive(e)]}async stopReceiving(e){return await this._p2pConnection.stopReceiving(e)}async muteRemote(e){return await this._p2pConnection.muteRemote(e)}async unmuteRemote(e){return await this._p2pConnection.unmuteRemote(e)}async muteLocal(e){return await this._p2pConnection.muteLocal(e)}async unmuteLocal(e){return await this._p2pConnection.unmuteLocal(e)}restartICE(e){var t=this;return ge((function*(){return yield*Ee(_e(t._p2pConnection.restartICE(e)))}))()}close(){this._p2pConnection.close(),this.unbindConnectionEvents(this._p2pConnection)}getStats(){return this._p2pConnection.getStats()}getRemoteVideoIsReady(e){return this._p2pConnection.getRemoteVideoIsReady(e)}updateRemoteConnect(e){return this._p2pConnection.updateRemoteConnect(e)}async updateEncoderConfig(e,t){return await this._p2pConnection.updateEncoderConfig(e,t)}async updateSendParameters(e,t){return await this._p2pConnection.updateSendParameters(e,t)}setStatsRemoteVideoIsReady(e,t){this._p2pConnection.setStatsRemoteVideoIsReady(e,t)}async replaceTrack(e,t){return await this._p2pConnection.replaceTrack(e,t)}async getRemoteSSRC(e){return this._p2pConnection.getRemoteSSRC(e)}logSDPExchange(t,n,i,o){if(r("SDP_LOGGING"))return e.upload("exchanging ".concat(i," ").concat(n," SDP during DataChannelConnection.").concat(o,"\n"),t),"offer"===n?e=>{this.logSDPExchange(e,"answer","local"===i?"remote":"local",o)}:void 0}static resolvePCConfiguration(e){const n={iceServers:[]};return e.iceServers?n.iceServers=e.iceServers:e.turnServer&&"off"!==e.turnServer.mode&&(V(e.turnServer.servers)?n.iceServers=e.turnServer.servers:(n.iceServers&&n.iceServers.push(...t.turnServerConfigToIceServers(e.turnServer.servers)),r("USE_TURN_SERVER_OF_GATEWAY")&&n.iceServers&&e.turnServer.serversFromGateway&&n.iceServers.push(...t.turnServerConfigToIceServers(e.turnServer.serversFromGateway)),r("FORCE_TURN_TCP")?n.iceTransportPolicy="relay":e.turnServer.servers.concat(e.turnServer.serversFromGateway||[]).forEach((e=>{e.forceturn&&(n.iceTransportPolicy="relay")})))),r("ENABLE_ENCODED_TRANSFORM")&&ee().supportWebRTCEncodedTransform&&(n.encodedInsertableStreams=!0),n}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(We(e.turnServerURL),":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&!r("FORCE_TURN_TCP")&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.udpport,"?transport=udp")}),e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.tcpport,"?transport=tcp")}))})),t}bindPCEvents(){this._p2pConnection.onICEConnectionStateChange=e=>{var t;return null===(t=this.onICEConnectionStateChange)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onConnectionStateChange=e=>{var t;return null===(t=this.onConnectionStateChange)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onDTLSTransportStateChange=e=>{var t;return null===(t=this.onDTLSTransportStateChange)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onDTLSTransportError=e=>{var t;return null===(t=this.onDTLSTransportError)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onICETransportStateChange=e=>{var t;return null===(t=this.onICETransportStateChange)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onFirstAudioReceived=e=>{var t;return null===(t=this.onFirstAudioReceived)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onFirstVideoReceived=e=>{var t;return null===(t=this.onFirstVideoReceived)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onFirstAudioDecoded=e=>{var t;return null===(t=this.onFirstAudioDecoded)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onFirstVideoRender=e=>{var t;return null===(t=this.onFirstVideoRender)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onFirstVideoBufferReady=e=>{var t;return null===(t=this.onFirstVideoBufferReady)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onFirstVideoDecoded=(e,t,n)=>{var i;return null===(i=this.onFirstVideoDecoded)||void 0===i?void 0:i.call(this,e,t,n)},this._p2pConnection.onFirstVideoDecodedTimeout=e=>{var t;return null===(t=this.onFirstVideoDecodedTimeout)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onSelectedLocalCandidateChanged=(e,t)=>{var n;return null===(n=this.onSelectedLocalCandidateChanged)||void 0===n?void 0:n.call(this,e,t)},this._p2pConnection.onSelectedRemoteCandidateChanged=(e,t)=>{var n;return null===(n=this.onSelectedRemoteCandidateChanged)||void 0===n?void 0:n.call(this,e,t)}}closeSignal(){this.dataChannel.close(),this.peerConnection.close()}unbindConnectionEvents(e){e.onConnectionStateChange=void 0,e.onICEConnectionStateChange=void 0,e.onICETransportStateChange=void 0,e.onDTLSTransportStateChange=void 0,e.onDTLSTransportError=void 0,e.onFirstAudioDecoded=void 0,e.onFirstAudioReceived=void 0,e.onFirstVideoDecoded=void 0,e.onFirstVideoReceived=void 0,e.onSelectedLocalCandidateChanged=void 0,e.onSelectedRemoteCandidateChanged=void 0,e.onFirstVideoDecodedTimeout=void 0}setConfiguration(e){this._p2pConnection.setConfiguration(e)}},he(nn.prototype,"connect",[rn],Object.getOwnPropertyDescriptor(nn.prototype,"connect"),nn.prototype),he(nn.prototype,"updateRemoteRTPCapabilities",[rn],Object.getOwnPropertyDescriptor(nn.prototype,"updateRemoteRTPCapabilities"),nn.prototype),he(nn.prototype,"createDataChannels",[rn],Object.getOwnPropertyDescriptor(nn.prototype,"createDataChannels"),nn.prototype),he(nn.prototype,"receive",[rn],Object.getOwnPropertyDescriptor(nn.prototype,"receive"),nn.prototype),he(nn.prototype,"stopReceiving",[rn],Object.getOwnPropertyDescriptor(nn.prototype,"stopReceiving"),nn.prototype),he(nn.prototype,"muteRemote",[rn],Object.getOwnPropertyDescriptor(nn.prototype,"muteRemote"),nn.prototype),he(nn.prototype,"unmuteRemote",[rn],Object.getOwnPropertyDescriptor(nn.prototype,"unmuteRemote"),nn.prototype),he(nn.prototype,"muteLocal",[rn],Object.getOwnPropertyDescriptor(nn.prototype,"muteLocal"),nn.prototype),he(nn.prototype,"unmuteLocal",[rn],Object.getOwnPropertyDescriptor(nn.prototype,"unmuteLocal"),nn.prototype),he(nn.prototype,"close",[rn],Object.getOwnPropertyDescriptor(nn.prototype,"close"),nn.prototype),he(nn.prototype,"updateEncoderConfig",[rn],Object.getOwnPropertyDescriptor(nn.prototype,"updateEncoderConfig"),nn.prototype),he(nn.prototype,"updateSendParameters",[rn],Object.getOwnPropertyDescriptor(nn.prototype,"updateSendParameters"),nn.prototype),he(nn.prototype,"replaceTrack",[rn],Object.getOwnPropertyDescriptor(nn.prototype,"replaceTrack"),nn.prototype),he(nn.prototype,"getRemoteSSRC",[rn],Object.getOwnPropertyDescriptor(nn.prototype,"getRemoteSSRC"),nn.prototype),nn);function rn(e,t,n){const i=e[t];if("function"!=typeof i)throw new Error("Cannot use mutex on object property.");return n.value=async function(){const e=this.mutex,n=await e.lock("From DataChannelConnection.".concat(t));try{for(var o=arguments.length,r=new Array(o),s=0;s<o;s++)r[s]=arguments[s];return await i.apply(this,r)}finally{n()}},n}Ne.ACCESS_POINT,De.NO_FLAG_SET,De.FLAG_SET_BUT_EMPTY,De.INVALID_FALG_SET,De.FLAG_SET_BUT_NO_RE,De.INVALID_SERVICE_ID,De.NO_SERVICE_AVAILABLE,De.NO_SERVICE_AVAILABLE_P2P,De.NO_SERVICE_AVAILABLE_VOICE,De.NO_SERVICE_AVAILABLE_WEBRTC,De.NO_SERVICE_AVAILABLE_CDS,De.NO_SERVICE_AVAILABLE_CDN,De.NO_SERVICE_AVAILABLE_TDS,De.NO_SERVICE_AVAILABLE_REPORT,De.NO_SERVICE_AVAILABLE_APP_CENTER,De.NO_SERVICE_AVAILABLE_ENV0,De.NO_SERVICE_AVAILABLE_VOET,De.NO_SERVICE_AVAILABLE_STRING_UID,De.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS,Ne.UNILBS,ve.INVALID_VENDOR_KEY,ve.INVALID_CHANNEL_NAME,ve.INTERNAL_ERROR,ve.NO_AUTHORIZED,ve.DYNAMIC_KEY_TIMEOUT,ve.NO_ACTIVE_STATUS,ve.DYNAMIC_KEY_EXPIRED,ve.STATIC_USE_DYNAMIC_KEY,ve.DYNAMIC_USE_STATIC_KEY,ve.USER_OVERLOAD,ve.FORBIDDEN_REGION,ve.CANNOT_MEET_AREA_DEMAND,ve.REQ_DOWNGRADE_FALLBACK,Ne.STRING_UID_ALLOCATOR,Te.IIIEGAL_APPID,Te.IIIEGAL_UID,Te.INTERNAL_ERROR;const sn={[Oe.K_TIMESTAMP_EXPIRED]:{desc:"K_TIMESTAMP_EXPIRED",action:"failed"},[Oe.K_CHANNEL_PERMISSION_INVALID]:{desc:"K_CHANNEL_PERMISSION_INVALID",action:"failed"},[Oe.K_CERTIFICATE_INVALID]:{desc:"K_CERTIFICATE_INVALID",action:"failed"},[Oe.K_CHANNEL_NAME_EMPTY]:{desc:"K_CHANNEL_NAME_EMPTY",action:"failed"},[Oe.K_CHANNEL_NOT_FOUND]:{desc:"K_CHANNEL_NOT_FOUND",action:"failed"},[Oe.K_TICKET_INVALID]:{desc:"K_TICKET_INVALID",action:"failed"},[Oe.K_CHANNEL_CONFLICTED]:{desc:"K_CHANNEL_CONFLICTED",action:"failed"},[Oe.K_SERVICE_NOT_READY]:{desc:"K_SERVICE_NOT_READY",action:"tryNext"},[Oe.K_SERVICE_TOO_HEAVY]:{desc:"K_SERVICE_TOO_HEAVY",action:"tryNext"},[Oe.K_UID_BANNED]:{desc:"K_UID_BANNED",action:"failed"},[Oe.K_IP_BANNED]:{desc:"K_IP_BANNED",action:"failed"},[Oe.DATASTREAM2_NOT_AVAILABLE]:{desc:"DATASTREAM2_NOT_AVAILABLE",action:"quit"},[Oe.K_AUTO_REBALANCE]:{desc:"k_AUTO_REBALANCE",action:"recover"},[Oe.K_VOS_FALLBACK]:{desc:"K_VOS_FALLBACK",action:"tryNext"},[Oe.ERR_INVALID_VENDOR_KEY]:{desc:"ERR_INVALID_VENDOR_KEY",action:"failed"},[Oe.ERR_INVALID_CHANNEL_NAME]:{desc:"ERR_INVALID_CHANNEL_NAME",action:"failed"},[Oe.WARN_NO_AVAILABLE_CHANNEL]:{desc:"WARN_NO_AVAILABLE_CHANNEL",action:"failed"},[Oe.WARN_LOOKUP_CHANNEL_TIMEOUT]:{desc:"WARN_LOOKUP_CHANNEL_TIMEOUT",action:"tryNext"},[Oe.WARN_LOOKUP_CHANNEL_REJECTED]:{desc:"WARN_LOOKUP_CHANNEL_REJECTED",action:"failed"},[Oe.WARN_OPEN_CHANNEL_TIMEOUT]:{desc:"WARN_OPEN_CHANNEL_TIMEOUT",action:"tryNext"},[Oe.WARN_OPEN_CHANNEL_REJECTED]:{desc:"WARN_OPEN_CHANNEL_REJECTED",action:"failed"},[Oe.WARN_REQUEST_DEFERRED]:{desc:"WARN_REQUEST_DEFERRED",action:"failed"},[Oe.ERR_DYNAMIC_KEY_TIMEOUT]:{desc:"ERR_DYNAMIC_KEY_TIMEOUT",action:"failed"},[Oe.ERR_NO_AUTHORIZED]:{desc:"ERR_NO_AUTHORIZED",action:"failed"},[Oe.ERR_VOM_SERVICE_UNAVAILABLE]:{desc:"ERR_VOM_SERVICE_UNAVAILABLE",action:"tryNext"},[Oe.ERR_NO_CHANNEL_AVAILABLE_CODE]:{desc:"ERR_NO_CHANNEL_AVAILABLE_CODE",action:"failed"},[Oe.ERR_MASTER_VOCS_UNAVAILABLE]:{desc:"ERR_MASTER_VOCS_UNAVAILABLE",action:"tryNext"},[Oe.ERR_INTERNAL_ERROR]:{desc:"ERR_INTERNAL_ERROR",action:"tryNext"},[Oe.ERR_NO_ACTIVE_STATUS]:{desc:"ERR_NO_ACTIVE_STATUS",action:"failed"},[Oe.ERR_INVALID_UID]:{desc:"ERR_INVALID_UID",action:"failed"},[Oe.ERR_DYNAMIC_KEY_EXPIRED]:{desc:"ERR_DYNAMIC_KEY_EXPIRED",action:"failed"},[Oe.ERR_STATIC_USE_DYANMIC_KE]:{desc:"ERR_STATIC_USE_DYANMIC_KE",action:"failed"},[Oe.ERR_DYNAMIC_USE_STATIC_KE]:{desc:"ERR_DYNAMIC_USE_STATIC_KE",action:"failed"},[Oe.ERR_NO_VOCS_AVAILABLE]:{desc:"ERR_NO_VOCS_AVAILABLE",action:"tryNext"},[Oe.ERR_NO_VOS_AVAILABLE]:{desc:"ERR_NO_VOS_AVAILABLE",action:"tryNext"},[Oe.ERR_JOIN_CHANNEL_TIMEOUT]:{desc:"ERR_JOIN_CHANNEL_TIMEOUT",action:"tryNext"},[Oe.ERR_JOIN_BY_MULTI_IP]:{desc:"ERR_JOIN_BY_MULTI_IP",action:"recover"},[Oe.ERR_NOT_JOINED]:{desc:"ERR_NOT_JOINED",action:"failed"},[Oe.ERR_REPEAT_JOIN_REQUEST]:{desc:"ERR_REPEAT_JOIN_REQUEST",action:"quit"},[Oe.ERR_REPEAT_JOIN_CHANNEL]:{desc:"ERR_REPEAT_JOIN_CHANNEL",action:"quit"},[Oe.ERR_INVALID_STRINGUID]:{desc:"ERR_INVALID_STRINGUID",action:"failed"},[Oe.ERR_TOO_MANY_USERS]:{desc:"ERR_TOO_MANY_USERS",action:"tryNext"},[Oe.ERR_SET_CLIENT_ROLE_TIMEOUT]:{desc:"ERR_SET_CLIENT_ROLE_TIMEOUT",action:"failed"},[Oe.ERR_SET_CLIENT_ROLE_NO_PERMISSION]:{desc:"ERR_SET_CLIENT_ROLE_TIMEOUT",action:"failed"},[Oe.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE]:{desc:"ERR_SET_CLIENT_ROLE_ALREADY_IN_USE",action:"success"},[Oe.ERR_PUBLISH_REQUEST_INVALID]:{desc:"ERR_PUBLISH_REQUEST_INVALID",action:"failed"},[Oe.ERR_SUBSCRIBE_REQUEST_INVALID]:{desc:"ERR_SUBSCRIBE_REQUEST_INVALID",action:"failed"},[Oe.ERR_NOT_SUPPORTED_MESSAGE]:{desc:"ERR_NOT_SUPPORTED_MESSAGE",action:"failed"},[Oe.ERR_ILLEAGAL_PLUGIN]:{desc:"ERR_ILLEAGAL_PLUGIN",action:"failed"},[Oe.ILLEGAL_CLIENT_ROLE_LEVEL]:{desc:"ILLEGAL_CLIENT_ROLE_LEVEL",action:"failed"},[Oe.ERR_REJOIN_TOKEN_INVALID]:{desc:"ERR_REJOIN_TOKEN_INVALID",action:"failed"},[Oe.ERR_REJOIN_USER_NOT_JOINED]:{desc:"ERR_REJOIN_NOT_JOINED",action:"failed"},[Oe.ERR_INVALID_OPTIONAL_INFO]:{desc:"ERR_INVALID_OPTIONAL_INFO",action:"quit"},[Oe.ERR_TEST_RECOVER]:{desc:"ERR_TEST_RECOVER",action:"recover"},[Oe.ERR_TEST_TRYNEXT]:{desc:"ERR_TEST_TRYNEXT",action:"recover"},[Oe.ERR_TEST_RETRY]:{desc:"ERR_TEST_RETRY",action:"recover"},[Oe.ILLEGAL_AES_PASSWORD]:{desc:"ERR_TEST_RETRY",action:"failed"},[Oe.ERR_TOO_MANY_BROADCASTERS]:{desc:"ERR_TOO_MANY_BROADCASTERS",action:"failed"},[Oe.ERR_TOO_MANY_SUBSCRIBERS]:{desc:"ERR_TOO_MANY_SUBSCRIBERS",action:"failed"},[Oe.ERR_TOO_MANY_MESSAGES]:{desc:"ERR_TOO_MANY_MESSAGES",action:"tryNext"},[Oe.ERR_LICENSE_ILLEGAL]:{desc:"ERR_LICENSE_ILLEGAL",action:"quit"},[Oe.ERR_LICENSE_MISSING]:{desc:"ERR_LICENSE_MISSING",action:"quit"},[Oe.ERR_LICENSE_EXPIRED]:{desc:"ERR_LICENSE_EXPIRED",action:"quit"},[Oe.ERR_LICENSE_MINUTES_EXCEEDED]:{desc:"ERR_LICENSE_MINUTES_EXCEEDED",action:"quit"},[Oe.ERR_LICENSE_PERIOD_INVALID]:{desc:"ERR_LICENSE_PERIOD_INVALID",action:"quit"},[Oe.ERR_LICENSE_MULTIPLE_SDK_SERVICE]:{desc:"ERR_LICENSE_MULTIPLE_SDK_SERVICE",action:"quit"}};function an(e){const t=sn[e];return t||{desc:"UNKNOWN_ERROR_".concat(e),action:"failed"}}class cn extends o{get url(){return this._url?this._url:null}get reconnectMode(){return this._reconnectMode}set reconnectMode(e){["tryNext","recover"].includes(e)&&this.resetReconnectCount(e),this._reconnectMode=e}get state(){return this._state}set state(e){e!==this._state&&(this._state=e,"reconnecting"===this._state?this.emit(Ge.RECONNECTING,this.reconnectReason):"connected"===this._state?this.emit(Ge.CONNECTED):"closed"===this._state?this.emit(Ge.CLOSED):"failed"===this._state&&this.emit(Ge.FAILED))}constructor(e,t,n,i){super(),this.connectionID=0,this.currentURLIndex=0,this.reconnectReason=void 0,this._reconnectMode="tryNext",this._initMutex=void 0,this._name=void 0,this._state="closed",this._reconnectInterrupter=void 0,this._url=void 0,this._retryConfig=void 0,this._reconnectCount=0,this._forceCloseTimeout=5e3,this._onlineReconnectListener=void 0,this._closeEstablishingTransmitter=()=>{},this._store=void 0,this._joinChannelServiceRecordIndex=void 0,this._transmitter=void 0,this._useCompress=void 0,this._inflateLength=0,this._deflateLength=0,this._store=i,this._name=e,this._retryConfig=fe({},t),this._useCompress=n}resetReconnectCount(t){e.debug("".concat(this._name," reset reconnect count, reason: ").concat(t)),this._reconnectCount=0}close(e,t){if(this.currentURLIndex=0,this.resetReconnectCount("close"),this._reconnectInterrupter&&this._reconnectInterrupter(),this._transmitter){this._transmitter.onclose=null,this._transmitter.onopen=null,this._transmitter.onmessage=null;const e=this._transmitter;t?setTimeout((()=>e.close()),500):e.close(),this._transmitter=void 0}this.state=e?"failed":"closed",this._closeEstablishingTransmitter&&this._closeEstablishingTransmitter()}reconnect(t,n){if(!this._transmitter)return void e.warning("[".concat(this._name,"] can not reconnect, no websocket"));var i;(void 0!==t&&(this.reconnectMode=t),e.debug("[".concat(this._name,"] reconnect is triggered initiative")),"number"==typeof this._joinChannelServiceRecordIndex)&&(null===(i=this._store)||void 0===i||i.recordJoinChannelService({status:"error",errors:[new Error(n)]},this._joinChannelServiceRecordIndex));const o=this._transmitter.onclose;this._transmitter.onclose=null,this._transmitter.close(),o&&o.bind(this._transmitter)({code:9999,reason:n})}getInflateData(){const e=this._inflateLength,t=this._deflateLength;return this.clearInflateData(),{inflateLength:e,deflateLength:t}}setInflateData(e){this._deflateLength=this._deflateLength+e.originLength,this._inflateLength=this._inflateLength+e.compressedLength}clearInflateData(){this._inflateLength=0,this._deflateLength=0}}let dn=function(e){return e[e.Default=0]="Default",e[e.Ack=1]="Ack",e}({});class pn{constructor(e,t,n){this.version=1,this.initialRTO=void 0,this.maxBatchAckCount=void 0,this.maxRTO=void 0,this.initialRTT=void 0,this.ID=void 0,this.rtt=void 0,this.packetNumber=1,this.rtoRatioMap=new Map,this.timeoutMap=new Map,this.unorderedPacketQueue=[],this.batchAckPacketQueue=[],this.lastOrderedPacketNumber=0,this.batchAckTimer=void 0,this.sendImpl=void 0,this.receiveImpl=void 0,this.sendImpl=e,this.receiveImpl=t,this.ID=l(7,"transmitter-"),this.initialRTO=void 0!==(null==n?void 0:n.initialRTO)?n.initialRTO:r("TRANSMITTER_INITIAL_RTO"),this.initialRTT=void 0!==(null==n?void 0:n.initialRTT)?n.initialRTT:r("TRANSMITTER_INITIAL_RTT"),this.rtt=void 0!==(null==n?void 0:n.initialRTT)?n.initialRTT:r("TRANSMITTER_INITIAL_RTT"),this.maxBatchAckCount=void 0!==(null==n?void 0:n.maxBatchAckCount)?n.maxBatchAckCount:r("TRANSMITTER_MAX_BATCH_ACK_COUNT"),this.maxRTO=void 0!==(null==n?void 0:n.maxRTO)?n.maxRTO:r("TRANSMITTER_MAX_RTO")}packetize(e,t){return{type:dn.Default,version:this.version,packetNumber:t,payload:e}}serialize(e){switch(e.type){case dn.Default:{let t;if("string"==typeof e.payload){t=(new TextEncoder).encode(e.payload)}else t=e.payload;const n=new ArrayBuffer(t.length+15),i=new DataView(n);i.setUint16(0,e.version),i.setUint8(2,e.type),i.setUint32(3,e.packetNumber),F(i,7,BigInt(e.sendTs));return new Uint8Array(i.buffer).set(t,15),n}case dn.Ack:{const t=new ArrayBuffer(16),n=new DataView(t);return n.setUint16(0,e.version),n.setUint8(2,e.type),n.setUint32(3,e.maxAckPacketNumber),n.setUint8(7,e.shift),F(n,8,BigInt(e.ackSendTs)),t}}}deserialize(t){const n=new DataView(t),i=n.getUint16(0),o=n.getUint8(2);switch(o){case dn.Default:{const e=n.getUint32(3),r=B(n,7),s=t.slice(15),a=new Uint8Array(s);return{version:i,type:o,packetNumber:e,sendTs:Number(r),payload:a}}case dn.Ack:{const e=n.getUint32(3),t=n.getUint8(7),r=B(n,8);return{version:i,type:o,maxAckPacketNumber:e,shift:t,ackSendTs:Number(r)}}default:throw e.error("[".concat(this.ID,"] Unrecognized packet type ").concat(o)),new Error("Unrecognized packet type ".concat(o))}}sendMessage(t){r("DC_DEBUG_LOG")&&"string"==typeof t&&e.debug("[".concat(this.ID,"] sending message packet"),JSON.parse(t));const n=this.packetize(t,this.packetNumber);this.packetNumber=4294967295===this.packetNumber?1:this.packetNumber+1;const i=this.calculateRTO(n),o=window.setTimeout((()=>{this.resendMessage(n)}),i);this.timeoutMap.set(n.packetNumber,o),this.sendPacket(n)}onData(e){const t=this.deserialize(e);t.type===dn.Default?this.ack(t):t.type===dn.Ack&&(this.updateRTT(t,Math.round(performance.now())),this.clearRTO(t))}close(){this.rtt=this.initialRTT,this.packetNumber=1,Array.from(this.timeoutMap.entries()).forEach((e=>{let t=Ie(e,2);t[0];let n=t[1];window.clearTimeout(n)})),this.timeoutMap=new Map,this.rtoRatioMap=new Map,this.unorderedPacketQueue=[],this.batchAckPacketQueue=[],this.lastOrderedPacketNumber=0,void 0!==this.batchAckTimer&&window.clearTimeout(this.batchAckTimer)}resendMessage(t){const n=this.calculateRTO(t),i=window.setTimeout((()=>{r("DC_DEBUG_LOG")&&"string"==typeof t.payload&&e.debug("[".concat(this.ID,"] resending message packet"),JSON.parse(t.payload),"timeout: ".concat(n)),this.resendMessage(t)}),n);this.timeoutMap.set(t.packetNumber,i),this.sendPacket(t)}calculateRTO(e){const t=this.rtoRatioMap.get(e.packetNumber);if(void 0===t)return this.rtoRatioMap.set(e.packetNumber,1),this.initialRTO;{const n=9*this.rtt/8*t;return this.rtoRatioMap.set(e.packetNumber,t+1),n>this.maxRTO?this.maxRTO:n}}updateRTT(e,t){const n=e.ackSendTs;this.rtt=this.rtt*(7/8)+(t-n-this.rtt)/8}ack(t){if(t.packetNumber===this.lastOrderedPacketNumber+1)for(this.batchAckPacketQueue.length>=this.maxBatchAckCount&&this.batchAck(),this.batchAckTimer?this.batchAckPacketQueue.push(t):(this.batchAckPacketQueue.push(t),this.batchAckTimer=window.setTimeout((()=>{this.batchAck()}),this.rtt/8)),this.lastOrderedPacketNumber+=1,this.receiveImpl(t.payload);;){const e=this.unorderedPacketQueue[0];if(!e){this.unorderedPacketQueue.shift();break}this.batchAckTimer&&this.batchAck(),this.receiveImpl(e.payload),this.unorderedPacketQueue.shift(),this.lastOrderedPacketNumber+=1}else if(t.packetNumber<=this.lastOrderedPacketNumber){const n={ackSendTs:t.sendTs,maxAckPacketNumber:t.packetNumber,shift:0,type:dn.Ack,version:this.version};r("DC_DEBUG_LOG")&&e.debug("[".concat(this.ID,"] sending ack packet"),n,"packetNumber: ".concat(t.packetNumber)),this.sendPacket(n)}else if(t.packetNumber>this.lastOrderedPacketNumber){this.unorderedPacketQueue[t.packetNumber-this.lastOrderedPacketNumber-2]=t;const n={ackSendTs:t.sendTs,maxAckPacketNumber:t.packetNumber,shift:0,type:dn.Ack,version:this.version};r("DC_DEBUG_LOG")&&e.debug("[".concat(this.ID,"] sending ack packet"),n,"packetNumber: ".concat(t.packetNumber)),this.sendPacket(n)}}batchAck(){window.clearTimeout(this.batchAckTimer),this.batchAckTimer=void 0;const t={ackSendTs:this.batchAckPacketQueue[this.batchAckPacketQueue.length-1].sendTs,maxAckPacketNumber:this.batchAckPacketQueue[this.batchAckPacketQueue.length-1].packetNumber,shift:this.batchAckPacketQueue.length-1,type:dn.Ack,version:this.version};r("DC_DEBUG_LOG")&&e.debug("[".concat(this.ID,"] sending batch ack packet"),t,"shift: ".concat(this.batchAckPacketQueue.length-1)),this.sendPacket(t),this.batchAckPacketQueue=[]}sendPacket(e){e.type===dn.Default&&(e.sendTs=Math.round(performance.now()));const t=this.serialize(e);this.sendImpl(t)}clearRTO(e){for(let t=e.maxAckPacketNumber-e.shift;t<=e.maxAckPacketNumber;t++){const e=this.timeoutMap.get(t);void 0!==e&&window.clearTimeout(e),this.timeoutMap.delete(t),this.rtoRatioMap.delete(t)}}}class ln extends cn{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]&&arguments[2],arguments.length>3?arguments[3]:void 0),this._initMutex=void 0,this._reconnectInterrupter=void 0,this._url=void 0,this._transmitter=void 0,this._addresses=void 0,this._reliableTransmission=void 0,this._textEncoder=void 0,this._textDecoder=void 0,this._textEncoder=new TextEncoder,this._textDecoder=new TextDecoder,this._initMutex=new w("datachannel");const n=t.timeout,i=t.timeoutFactor,o=Math.max(300,Math.floor(3*n/5)),r=Math.max(1.2,Math.floor(8*i)/10);G.ONLINE&&(this._retryConfig.timeout=o,this._retryConfig.timeoutFactor=r),H.on(W.NETWORK_STATE_CHANGE,((e,t)=>{e!==t&&(this.resetReconnectCount("network state change: ".concat(t," -> ").concat(e)),e===G.ONLINE?(this._retryConfig.timeout=o,this._retryConfig.timeoutFactor=r):(this._retryConfig.timeout=n,this._retryConfig.timeoutFactor=i))}))}getConnection(){if(this._reliableTransmission)return this._reliableTransmission}async init(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;this._forceCloseTimeout=t;const i=(t,i)=>{this._addresses=e,this.currentURLIndex=this._addresses.findIndex((e=>e.fingerprint||r("FINGERPRINT")));const o=this._addresses[this.currentURLIndex];this.state="connecting",this.createTransmitterConnection(o).then(t).catch(i),this.once(Ge.CLOSED,(()=>i(new n(L.WS_DISCONNECT)))),this.once(Ge.CONNECTED,(()=>t()))};return this._initMutex.lock().then((e=>new Promise(((e,t)=>{i(e,t)})).then((()=>{e()})).catch((()=>{e()}))))}async sendMessage(e){let t=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!this._transmitter||!this._reliableTransmission)throw new n(L.WS_ABORT,"datachannel is not ready");try{t||(e=JSON.stringify(e));const n=this._textEncoder.encode(e),i=de(n,{raw:!0});this._reliableTransmission.sendMessage(i)}catch(e){throw new n(L.WS_ERR,"send datachannel signal message error"+e.toString())}}unbindDcCloseEventListener(){this._transmitter&&(this._transmitter.onclose=null)}sendMessageWithJSON(e){const t=JSON.stringify(e);return{compressed:t,compressedLength:t.length,origin:e}}sendMessageWithUint8Array(e){return{compressed:e,compressedLength:e.byteLength,origin:e}}createTransmitterConnection(t){return this.connectionID+=1,this._joinChannelServiceRecordIndex=void 0,this._url="dc://".concat(t.ip,":").concat(t.port),new Promise(((i,o)=>{var r;const s=()=>{e.debug("[".concat(this._name,"] datachannel opened:"),this._url),this.reconnectMode="recover",this.state="connected",this.resetReconnectCount("opened"),i()},a=async t=>{var r;if(null===(r=this._closeEstablishingTransmitter)||void 0===r||r.call(this),e.debug("[".concat(this._name,"] datachannel close ").concat(this._url,", code: ").concat(t.code,", reason: ").concat(t.reason,", current mode: ").concat(this.reconnectMode)),this._reconnectCount<this._retryConfig.maxRetryCount){"connected"===this.state&&(this.reconnectReason=t.reason,this.state="reconnecting");const r=J(this,Ge.WILL_RECONNECT,this.reconnectMode)||this.reconnectMode,s=await this.reconnectWithAction(r);if("closed"===this.state)return void e.debug("[".concat(this.connectionID,"] dc is closed, no need to reconnect"));if(!s)return o(new n(L.WS_DISCONNECT,"datachannel reconnect failed: ".concat(t.code))),void this.close(!0);i()}else o(new n(L.WS_DISCONNECT,"datachannel close: ".concat(t.code))),this.close()},c=async e=>{try{var t;null===(t=this._reliableTransmission)||void 0===t||t.onData(e.data)}catch(e){console.log(e)}};this._transmitter&&(this._transmitter.onclose=null,this._transmitter.close()),this._reliableTransmission&&(this._reliableTransmission.close(),this._reliableTransmission=void 0),e.debug("[".concat(this._name,"] start connect, address: ").concat(JSON.stringify(t)));const d=null===(r=this._store)||void 0===r?void 0:r.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"gateway"}),p=Date.now();K(this,Ge.TO_CONNECT_DATACHANNEL).then((t=>{var n,i;if(!t)throw new Error("transmissonInfo not exist yet");const o=t.transmitter,r=t.close;this._transmitter=o,null===(n=this._store)||void 0===n||n.signalChannelOpen();const l=Date.now()-p;e.debug("[choose dc] dc open cost ".concat(l,"ms"));this._reliableTransmission=new pn((e=>{var t;this._transmitter&&"open"===this._transmitter.readyState&&(null===(t=this._transmitter)||void 0===t||t.send(e))}),(e=>{if("string"==typeof e)this.emit(Ge.ON_MESSAGE,e);else{const t=pe(e,{raw:!0}).buffer,n=this._textDecoder.decode(t);this.emit(Ge.ON_MESSAGE,n)}})),this._closeEstablishingTransmitter=()=>{var e;null===(e=this._reliableTransmission)||void 0===e||e.close(),this._reliableTransmission=void 0,r()},s&&s(),o.onclose=a,o.onmessage=c,null===(i=this._store)||void 0===i||i.recordJoinChannelService({endTs:Date.now(),status:"success"},d),this._joinChannelServiceRecordIndex=d})).catch((t=>{var i;if(null===(i=this._store)||void 0===i||i.recordJoinChannelService({endTs:Date.now(),status:t instanceof n&&t.code===L.WS_ABORT?"aborted":"error",errors:[t]},d),"closed"!==this.state){if(t instanceof n&&t.code===L.WS_ERR){const i=new n(L.WS_ERR,"init datachannel failed! Error: ".concat(t.toString()));return e.error("[".concat(this._name,"]").concat(i)),void o(i)}a&&a(t)}else o(new n(L.WS_DISCONNECT,"datachannel is closed: ".concat(t.toString())))}))}))}async reconnectWithAction(t){let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(this._reconnectCount>=this._retryConfig.maxRetryCount)return!1;if(!this._addresses)return!1;if("closed"===this.state)return!1;this._onlineReconnectListener||H.networkState!==G.OFFLINE||(this._onlineReconnectListener=H.onlineWaiter&&H.onlineWaiter.then((()=>{this._onlineReconnectListener=void 0})));let i=!0;if(this._reconnectInterrupter=()=>{i=!1},n){const n=Y(this._reconnectCount,this._retryConfig);e.debug("[".concat(this._name,"] wait ").concat(n,"ms to reconnect datachannel, mode: ").concat(t)),await Promise.race([j(n),this._onlineReconnectListener||new Promise((()=>{}))])}if("closed"===this.state||!i)return!1;this._reconnectCount+=1;const o=async(e,t)=>{this.emit(Ge.RECONNECT_CREATE_CONNECTION,t),await this.createTransmitterConnection(e)};try{if("retry"===t){const e=this._addresses[this.currentURLIndex];await o(e,t)}else if("tryNext"===t){this.currentURLIndex+=1;for(let e=this.currentURLIndex;e<this._addresses.length;e++){if(this._addresses[e].fingerprint||r("FINGERPRINT")){this.currentURLIndex=e;break}this.currentURLIndex+=1}if(this.currentURLIndex>=this._addresses.length)return e.debug("[".concat(this._name,"] the available addresses are exhausted, change to recover")),await this.reconnectWithAction("recover",!1);e.debug("[".concat(this._name,"] datachannel url length: ").concat(this._addresses.length," current index: ").concat(this.currentURLIndex));const n=this._addresses[this.currentURLIndex];await o(n,t)}else"recover"===t&&(e.debug("[".concat(this._name,"] start to failback to websocket")),this.resetReconnectCount("recover mode"),this.emit(Ge.FAILBACK));return!0}catch(i){var s;return e.error("[".concat(this._name,"] reconnect failed"),i.toString()),null!=i&&null!==(s=i.data)&&void 0!==s&&s.desc&&Array.isArray(i.data.desc)&&i.data.desc.length&&i.data.desc.includes("dynamic key expired")?(this.emit(Ge.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1):await this.reconnectWithAction(t,n)}}}class hn extends o{get connectionState(){return this._connectionState}set connectionState(e){e!==this._connectionState&&(this._connectionState=e,e===Pe.CONNECTED?this.emit(ye.WS_CONNECTED):e===Pe.RECONNECTING?this.emit(ye.WS_RECONNECTING,this._websocketReconnectReason):e===Pe.CLOSED&&this.emit(ye.WS_CLOSED,this._disconnectedReason))}get currentURLIndex(){return this.websocket.currentURLIndex}get url(){return this.websocket?this.websocket.url:null}get reportUrl(){return this.url}get rtt(){return this.rttRolling.mean()}processPendingNotifications(){0!==this.pendingNotifications.length&&(e.debug("[".concat(this.clientId,"] processing ").concat(this.pendingNotifications.length," pending notifications")),this.pendingNotifications.forEach((e=>{let t=e.type,n=e.message;this.emit(t,n),t===be.ON_NOTIFICATION&&this.handleNotification(n),t===be.ON_USER_BANNED&&this.handleUserBanned(n)})),this.pendingNotifications=[])}handleUserBanned(e){switch(e.error_code){case 14:this.close(X.UID_BANNED);break;case 15:this.close(X.IP_BANNED);break;case 16:this.close(X.CHANNEL_BANNED)}}constructor(t,n){super(),this.__name__="DataChannelSignal",this._disconnectedReason=void 0,this._websocketReconnectReason=void 0,this._connectionState=Pe.CLOSED,this.reconnectToken=void 0,this.websocket=void 0,this.openConnectionTime=void 0,this.clientId=void 0,this.lastMsgTime=Date.now(),this.uploadCache=[],this.uploadCacheInterval=void 0,this.rttRolling=new Q(5),this.pingpongTimer=void 0,this.inflateDataTimer=void 0,this.pingpongTimeoutCount=0,this.ortc=void 0,this.joinResponse=void 0,this.multiIpOption=void 0,this.initError=void 0,this.spec=void 0,this.store=void 0,this.isJoining=!1,this.pendingNotifications=[],this.onWebsocketMessage=t=>{if(t instanceof ArrayBuffer)return void this.emit(ye.ON_BINARY_DATA,t);const n=JSON.parse(t);if(r("DC_DEBUG_LOG")&&e.debug("[datachannel-signal] received packet",n),this.lastMsgTime=Date.now(),Object.prototype.hasOwnProperty.call(n,"_id")){const e="res-@".concat(n._id);this.emit(e,n._result,n._message)}else Object.prototype.hasOwnProperty.call(n,"_type")&&(this.isJoining?n._type===be.ON_NOTIFICATION||n._type===be.ON_USER_BANNED?(this.emit(n._type,n._message),n._type===be.ON_NOTIFICATION&&this.handleNotification(n._message),n._type===be.ON_USER_BANNED&&this.handleUserBanned(n._message)):(this.pendingNotifications.push({type:n._type,message:n._message}),e.debug("[".concat(this.clientId,"] cached notification during join: ").concat(n._type))):(this.emit(n._type,n._message),n._type===be.ON_NOTIFICATION&&this.handleNotification(n._message),n._type===be.ON_USER_BANNED&&this.handleUserBanned(n._message)))},this.clientId=t.clientId,this.spec=t,this.store=n,this.websocket=new ln("gateway-".concat(this.clientId),this.spec.retryConfig,!0,n),this.handleWebsocketEvents(),window.addEventListener("offline",(()=>{this.connectionState===Pe.CONNECTED&&this.reconnect("retry",Be.OFFLINE)}))}async request(t,i,o,s){const a=l(6,""),c={_id:a,_type:t,_message:i},d=this.websocket.connectionID,p=()=>new Promise(((e,i)=>{if(this.connectionState===Pe.CONNECTED)return e();const o=()=>{this.off(ye.WS_CLOSED,r),e()},r=()=>{this.off(ye.WS_CONNECTED,o),i(new n(L.WS_ABORT))};this.once(ye.WS_CONNECTED,o),this.once(ye.WS_CLOSED,r),t!==Le.PUBLISH&&t!==Le.SUBSCRIBE&&t!==Le.UNSUBSCRIBE&&t!==Le.UNPUBLISH&&t!==Le.CONTROL&&t!==Le.RESTART_ICE||this.once(ye.DISCONNECT_P2P,(()=>{i(new n(L.DISCONNECT_P2P))})),t!==Le.PUBLISH&&t!==Le.RESTART_ICE||this.once(ye.ABORT_P2P_EXECUTION,(()=>{i(new n(L.DISCONNECT_P2P))}))}));if(this.connectionState!==Pe.CONNECTING&&this.connectionState!==Pe.RECONNECTING||t===Le.JOIN||t===Le.REJOIN||await p(),t===Le.LEAVE&&(this.websocket.unbindDcCloseEventListener(),s=!0),r("DC_DEBUG_LOG")&&e.debug("[datachannel-signal] sendMessage",c),await this.websocket.sendMessage(c,!0,!1),s)return;const h=new Promise(((o,s)=>{let c=!1;const p=(e,n)=>{c=!0,o({isSuccess:"success"===e,message:n||{}}),this.off(ye.WS_CLOSED,l),this.off(ye.WS_RECONNECTING,l),this.emit(ye.REQUEST_SUCCESS,t,i)};this.once("res-@".concat(a),p);const l=()=>{s(new n(L.WS_ABORT,"type: ".concat(t))),this.off(ye.WS_CLOSED,l),this.off(ye.WS_RECONNECTING,l),this.off("res-@".concat(a),p)};this.once(ye.WS_CLOSED,l),this.once(ye.WS_RECONNECTING,l),j(r("SIGNAL_REQUEST_TIMEOUT")).then((()=>{this.websocket.connectionID!==d||c||(e.warning("dc request timeout, type: ".concat(t)),this.emit(ye.REQUEST_TIMEOUT,t,i))}))}));let u=null;try{u=await h}catch(e){if(this.connectionState===Pe.CLOSED||t===Le.LEAVE)throw new n(L.WS_ABORT);return!this.spec.forceWaitGatewayResponse||o?e.throw():t===Le.JOIN||t===Le.REJOIN?null:(await p(),await this.request(t,i))}if(u.isSuccess)return u.message;const E=Number(u.message.error_code||u.message.code),_=an(E),C=new n(L.UNEXPECTED_RESPONSE,"".concat(_.desc,": ").concat(u.message.error_str),{code:E,data:u.message});return"success"===_.action?u.message:(e.warning("[".concat(this.websocket.connectionID,"] unexpected response from type ").concat(t,", error_code: ").concat(E,", message: ").concat(_.desc,", action: ").concat(_.action)),E===Oe.ERR_TOO_MANY_BROADCASTERS?t===Le.JOIN||t===Le.REJOIN?(this.initError=C,this.close(),C.throw()):C.throw():"failed"===_.action?C.throw():"quit"===_.action?(this.initError=C,this.close(),C.throw()):(E===Oe.ERR_JOIN_BY_MULTI_IP?(this.multiIpOption=u.message.option,e.warning("[".concat(this.clientId,"] detect multi ip, recover")),this.reconnect("recover",Be.MULTI_IP)):this.reconnect(_.action,Be.SERVER_ERROR),t===Le.JOIN||t===Le.REJOIN?null:await this.request(t,i)))}waitMessage(e,t){return new Promise((n=>{const i=o=>{(!t||t(o))&&(this.off(e,i),n(o))};this.on(e,i)}))}uploadWRTCStats(t){if(!this.store.sessionId)return void e.warn("[".concat(this.clientId,"] no session id when upload wrtc stats"));const n={lts:Date.now(),sid:this.store.sessionId,uid:this.store.intUid,stats:t};this.upload(we.WRTC_STATS,n)}upload(e,t){const n={_type:e,_message:t};try{this.websocket.sendMessage(n)}catch(e){const t=r("MAX_UPLOAD_CACHE")||50;this.uploadCache.push(n),this.uploadCache.length>t&&this.uploadCache.splice(0,1),this.uploadCache.length>0&&!this.uploadCacheInterval&&(this.uploadCacheInterval=window.setInterval((()=>{if(this.connectionState!==Pe.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)}),r("UPLOAD_CACHE_INTERVAL")||2e3))}}async send(e,t){const n={_type:e,_message:t};await this.websocket.sendMessage(n)}init(t){return this.initError=void 0,this.multiIpOption=void 0,this.joinResponse=void 0,this.reconnectToken=void 0,this.openConnectionTime=void 0,new Promise(((i,o)=>{this.once(ye.WS_CONNECTED,(()=>i(this.joinResponse))),this.once(ye.WS_CLOSED,(()=>o(this.initError||new n(L.WS_ABORT)))),this.connectionState=Pe.CONNECTING,this.websocket.init(t).catch(o),this.websocket.once(Ge.FAILBACK,(()=>{o(new n(L.INIT_DATACHANNEL_TIMEOUT))})),this.inflateDataTimer&&window.clearInterval(this.inflateDataTimer),this.inflateDataTimer=window.setInterval((()=>{this.handleInflateData()}),2e4),setTimeout((()=>{void 0===this.openConnectionTime&&(e.debug("[".concat(this.clientId,"] init datachannel timeout while join with failback to websocket")),o(new n(L.INIT_DATACHANNEL_TIMEOUT)))}),r("DC_JOIN_WITH_FAILBACK"))}))}close(t){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.inflateDataTimer&&(this.handleInflateData(),window.clearInterval(this.inflateDataTimer),this.inflateDataTimer=void 0),this.reconnectToken=void 0,this.joinResponse=void 0,this.isJoining=!1,this.pendingNotifications=[],this._disconnectedReason=t||X.LEAVE,this.connectionState=Pe.CLOSED,e.debug("[".concat(this.clientId,"] ")+"will close datachannel in signal"),this.websocket.close(),t===X.FALLBACK&&(this.websocket.removeAllListeners(),this.websocket=new ln("gateway-".concat(this.clientId),this.spec.retryConfig,!0,this.store),this.handleWebsocketEvents())}async join(){if(this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),r("DC_PINGPONG_INTERVAL")),!this.joinResponse){this.emit(ye.ABORT_P2P_EXECUTION),this.store.signalConnected();const e=await K(this,ye.REQUEST_JOIN_INFO);this.store.joinReq(),this.isJoining=!0,this.pendingNotifications=[];const t=await this.request(Le.JOIN,e);if(this.store.joinRep(),this.ortc=null==e?void 0:e.ortc,!t)return this.emit(ye.REPORT_JOIN_GATEWAY,L.TIMEOUT,this.reportUrl||""),!1;this.joinResponse=t,this.emit(ye.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token}return this.connectionState=Pe.CONNECTED,this.isJoining=!1,this.processPendingNotifications(),!0}async rejoin(){if(!this.reconnectToken)throw new n(L.UNEXPECTED_ERROR,"can not rejoin, no rejoin token");const e=q(this,ye.REQUEST_REJOIN_INFO);e.token=this.reconnectToken;const t=await this.request(Le.REJOIN,e);return!!t&&(this.connectionState=Pe.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),r("DC_PINGPONG_INTERVAL")),t.peers&&t.peers.forEach((e=>{this.emit(be.ON_USER_ONLINE,{uid:e.uid}),e.audio&&this.emit(be.ON_ADD_AUDIO_STREAM,{uid:e.uid,uint_id:e.uint_id,audio:!0,ssrcId:e.audio_ssrc}),e.video&&this.emit(be.ON_ADD_VIDEO_STREAM,{uid:e.uid,uint_id:e.uint_id,video:!0,ssrcId:e.video_ssrc}),e.audio_mute?this.emit(be.MUTE_AUDIO,{uid:e.uid}):this.emit(be.UNMUTE_AUDIO,{uid:e.uid}),e.video_mute?this.emit(be.MUTE_VIDEO,{uid:e.uid}):this.emit(be.UNMUTE_VIDEO,{uid:e.uid}),e.audio_enable_local?this.emit(be.ENABLE_LOCAL_AUDIO,{uid:e.uid}):this.emit(be.DISABLE_LOCAL_AUDIO,{uid:e.uid}),e.video_enable_local?this.emit(be.ENABLE_LOCAL_VIDEO,{uid:e.uid}):this.emit(be.DISABLE_LOCAL_VIDEO,{uid:e.uid}),e.audio||e.video||this.emit(be.ON_REMOVE_STREAM,{uid:e.uid,uint_id:e.uint_id})})),!0)}reconnect(e,t){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.websocket.reconnect(e,t)}async downgradeCodec(e){if(!this.ortc)return!1;const t={downgrade_codec:e,ortc:this.ortc};return!!await this.request(Le.DOWNGRADE_CODEC,t)}handleNotification(t){e.debug("[".concat(this.clientId,"] receive notification: "),t);const n=an(t.code);if("success"!==n.action){if("failed"!==n.action)return"quit"===n.action?("ERR_REPEAT_JOIN_CHANNEL"===n.desc&&this.close(X.UID_BANNED),void this.close()):void this.reconnect(n.action,Be.SERVER_ERROR);e.error("[".concat(this.clientId,"] ignore error: "),n.desc)}}handlePingPong(){if(!this.websocket||"connected"!==this.websocket.state)return;this.pingpongTimeoutCount>0&&this.rttRolling.add(3e3),this.pingpongTimeoutCount+=1,r("DC_DEBUG_LOG")&&console.debug("[datachannel-signal] pingpongTimeoutCount: ".concat(this.pingpongTimeoutCount));const t=r("PING_PONG_TIME_OUT"),n=Date.now();this.pingpongTimeoutCount>=t&&(e.warning("[datachannel-signal] PINGPONG Timeout. Last Socket Message: ".concat(n-this.lastMsgTime,"ms")),n-this.lastMsgTime>r("WEBSOCKET_TIMEOUT_MIN"))?this.reconnect("recover",Be.FALLBACK):this.request(Le.PING,void 0,!0).then((()=>{this.pingpongTimeoutCount=0;const e=Date.now()-n;this.rttRolling.add(e),r("REPORT_STATS")&&this.send(Le.PING_BACK,{pingpongElapse:e})})).catch((e=>{}))}handleInflateData(){const e=this.websocket.getInflateData(),t=e.inflateLength,n=e.deflateLength;0!==t&&0!==n&&this.upload(we.WS_INFLATE_DATA_LENGTH,{ws_deflate_length:n,ws_inflate_length:t})}handleWebsocketEvents(){this.websocket.on(Ge.RECONNECT_CREATE_CONNECTION,(e=>{this.emit(ye.WS_RECONNECT_CREATE_CONNECTION,e)})),this.websocket.on(Ge.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(Ge.CLOSED,(()=>{this.connectionState=Pe.CLOSED})),this.websocket.on(Ge.FAILED,(()=>{this._disconnectedReason=X.NETWORK_ERROR,this.connectionState=Pe.CLOSED})),this.websocket.on(Ge.RECONNECTING,(e=>{this._websocketReconnectReason=e,this.joinResponse=void 0,this.connectionState===Pe.CONNECTED?this.connectionState=Pe.RECONNECTING:this.connectionState=Pe.CONNECTING})),this.websocket.on(Ge.WILL_RECONNECT,((t,n)=>{if(q(this,ye.IS_P2P_DISCONNECTED)&&"retry"===t)return e.debug("".concat(this.clientId," reconnect mode is retry, but p2p lost, change to tryNext")),this.reconnectToken=void 0,this.emit(ye.NEED_RENEW_SESSION),this.emit(ye.DISCONNECT_P2P),n("tryNext");"retry"!==t&&(e.debug("".concat(this.clientId," websockt will_connect event, renewSession reconnectMode is ").concat(t)),this.reconnectToken=void 0,this.emit(ye.NEED_RENEW_SESSION),this.emit(ye.DISCONNECT_P2P)),n(t)})),this.websocket.on(Ge.CONNECTED,(()=>{this.openConnectionTime=Date.now(),this.reconnectToken?this.rejoin().catch((t=>{e.warning("[".concat(this.clientId,"] rejoin failed ").concat(t)),this.reconnect("tryNext",Be.SERVER_ERROR)})):this.join().catch((t=>{if(this.emit(ye.REPORT_JOIN_GATEWAY,t.message||t.code,this.reportUrl||""),t instanceof n&&t.code===L.UNEXPECTED_RESPONSE&&t.data.code===Oe.ERR_NO_AUTHORIZED)return e.warning("[".concat(this.clientId,"] reconnect no authorized, recover")),void this.reconnect("recover",Be.SERVER_ERROR);e.error("[".concat(this.clientId,"] join gateway request failed"),t.toString()),this.spec.forceWaitGatewayResponse?this.reconnect("tryNext",Be.SERVER_ERROR):(this.initError=t,this.close())}))})),this.websocket.on(Ge.REQUEST_NEW_URLS,((e,t)=>{K(this,ye.REQUEST_RECOVER,this.multiIpOption).then(e).catch(t)})),this.websocket.on(Ge.ON_TOKEN_PRIVILEGE_DID_EXPIRE,(()=>{this.emit(be.ON_TOKEN_PRIVILEGE_DID_EXPIRE)})),this.websocket.on(Ge.TO_CONNECT_DATACHANNEL,((e,t)=>{K(this,ye.PRE_CONNECT_PC).then(e).catch(t)})),this.websocket.on(Ge.FAILBACK,(()=>{void 0!==this.openConnectionTime&&this.emit(ye.DATACHANNEL_FAILBACK)}))}}const un={name:"DataChannelConnection",create:function(e){let t=e.store,n=e.spec;return new on(n,t)}};const En={name:"DataChannelSignal",create:function(e){let t=e.store,n=e.spec;return new hn(n,t)}};export{un as DataChannelConnectionService,En as DataChannelSignalService};