agora-rtc-sdk-ng
Version:
Agora WebRTC SDK for JavaScript
6 lines • 459 kB
JavaScript
/**
* AgoraWebSDK_N-v4.24.0-0-gf2267710-dirty Copyright AgoraInc.
*/
import{detectSupportPrePc as e,LocalAudioTrack as t,MicrophoneAudioTrack as i,LocalVideoTrack as n,getCompatibility as o,TrackHint as a,detectSupportPreSub as s,detectSupportInstantVideo as r,detectSupportAutCCFeedback as c,detectSupportAutCC as d,MixingAudioTrack as l,DEFAULT_LOCAL_AUDIO_TRACK_STATS as u,DEFAULT_LOCAL_VIDEO_TRACK_STATS as h,DEFAULT_REMOTE_AUDIO_TRACK_STATS as _,DEFAULT_REMOTE_VIDEO_TRACK_STATS as p,DEFAULT_NETWORK_QUALITY_STATS as E,CameraVideoTrack as S,AgoraRTCPlayer as m,getOriginSenderConfig as R,audioTimerLoop as f,MediaElementNumStatus as C,visibilityWatcher as T,MediaElementStatus as I,audioElementPlayCenter as A,RemoteAudioTrack as g,RemoteVideoTrack as v,RemoteTrackEvents as y,TrackInternalEvent as N,TrackEvents as b,StreamType as w,LocalTrack as O,TrackMediaType as D,isLowStreamParameter as P,autoPlayGestureEventEmitter as L,deviceManager as k,DeviceManagerEvent as U,audioContextState as M,AUDIO_CONTEXT_EVENT as V,__TRACK_LIST__ as x}from"@agora-js/media";export{RemoteStreamFallbackType,RemoteStreamType,__TRACK_LIST__,audioElementPlayCenter,createBufferSourceAudioTrack,createCameraVideoTrack,createCustomAudioTrack,createCustomVideoTrack,createMicrophoneAndCameraTracks,createMicrophoneAudioTrack,createScreenVideoTrack,getElectronScreenSources}from"@agora-js/media";import{logger as B,AgoraRTCError as F,report as j,AgoraRTCErrorCode as G,AgoraRTCEvent as W,AgoraRTCEventUploadType as H,apiInvoke as K,isEventCustomReportParams as Y}from"@agora-js/report";import{MUTABLE_PARAMS as q,MUTABLE_PARAMS_LOCAL_CACHE as X,MUTABLE_GATEWAY_PARAMS as J,CONFIG_DISTRIBUTE_TYPE as z,MUTABLE_REALTIME_PARAMS as Q,AgoraRTCErrorCode as Z,isValidString as $,checkValidString as ee,IS_GLOBAL_VERSION as te,EventEmitter as ie,getParameter as ne,createDefer as oe,isMacOS as ae,isFirefox as se,PromiseMutex as re,NETWORK_STATE as ce,networkIndicator as de,NETWORK_INDICATOR_EVENTS as le,AgoraRTCError as ue,getRetryWaitTime as he,wait as _e,emitAsPromise as pe,emitAsInvokerNoResponse as Ee,Rolling as Se,ConnectionDisconnectedReason as me,WebSocketQuitReason as Re,getRandomString as fe,emitAsInvoker as Ce,DEFAULT_TURN_CONFIG as Te,SHA256 as Ie,ScalabilityMode as Ae,parseSdp as ge,jsonClone as ve,printSdp as ye,getBrowserInfo as Ne,BrowserName as be,BrowserOS as we,withTimeout as Oe,nextTick as De,isAboveChrome as Pe,isAboveSafari15_4 as Le,isAboveFirefox as ke,isAboveSafari18_4 as Ue,isAboveIOS as Me,isBelowSafari as Ve,VERSION as xe,isBetweenBrowser as Be,setParameter as Fe,getUTF8StringByteLength as je,getMultiUnilbsFormDataByteLength as Ge,AgoraAPIName as We,AgoraAPITag as He,retryable as Ke,DEFAULT_RETRY_CONFIG as Ye,loadInstallId as qe,isJsonEqual as Xe,isSafari as Je,isChromeBelow90 as ze,isChrome as Qe,isFirefoxVersion as Ze,isBelowIOS14_6 as $e,VideoCodec as et,QualityLimitationReason as tt,OVERUSE_DETECTOR_PARAMS as it,isBelowIOS as nt,isAboveSafari as ot,isChromeKernel as at,isRTCIceServerList as st,createWebRTCStatsFilter as rt,DEFAULT_CANDIDATE_STATS as ct,PeerConnectionState as dt,compareArray as lt,emitAsPromiseNoResponse as ut,isMobile as ht,getUniqueList as _t,ClientEvents as pt,isWkWebview as Et,runOnce as St,generateSessionID as mt,md5 as Rt,convertStringToFixedLengthUint8Array as ft,base64ToUint8Array as Ct,uint8ArrayToBase64 as Tt,checkValidNumber as It,removeItemFromList as At,isIOS as gt,SDKStore as vt,BUILD as yt,isClientRoleOptions as Nt,concurrent as bt,isHttpsEnv as wt,supportIsSecureContext as Ot,checkValidBoolean as Dt,encryptRSA as Pt,generateIv as Lt,generateKey as kt,checkValidEnum as Ut,checkValidArray as Mt,isClientRole as Vt,isTurnServerConfig as xt,isEncryptionMode as Bt,encryptAesGcm as Ft,CRYPTO_HEADER_LENGTH as jt,decryptAesGcm as Gt,isP2PTransport as Wt,isClientConfig as Ht,isBelowChrome as Kt,isWebKit as Yt,isSupportedWkWebview as qt,isIpadOS as Xt,isWechatBrowser as Jt,isQQBrowser as zt,generateProcessID as Qt}from"@agora-js/shared";export{AudienceLatencyLevelType,BUILD,ConnectionDisconnectedReason,VERSION,getParameter}from"@agora-js/shared";import Zt from"axios";import"formdata-polyfill";const $t=!0,ei=!1,ti=!1,ii=!1,ni=["CHINA","GLOBAL"];const oi=[[0,1,2,3,4,5,5],[0,2,2,3,4,5,5],[0,3,3,3,4,5,5],[0,4,4,4,4,5,5],[0,5,5,5,5,5,5]],ai=[],si=[];function ri(e,t){return!!t&&ai.some((i=>i.uid===e&&i.channelName===t))}function ci(){return si.length>0}function di(e,t){this.v=e,this.k=t}function li(e,t,i,n,o){var a={};return Object.keys(n).forEach((function(e){a[e]=n[e]})),a.enumerable=!!a.enumerable,a.configurable=!!a.configurable,("value"in a||a.initializer)&&(a.writable=!0),a=i.slice().reverse().reduce((function(i,n){return n(e,t,i)||i}),a),o&&void 0!==a.initializer&&(a.value=a.initializer?a.initializer.call(o):void 0,a.initializer=void 0),void 0===a.initializer?(Object.defineProperty(e,t,a),null):a}function ui(e){var t={},i=!1;function n(t,n){return i=!0,n=new Promise((function(i){i(e[t](n))})),{done:!1,value:new di(n,1)}}return t["undefined"!=typeof Symbol&&Symbol.iterator||"@@iterator"]=function(){return this},t.next=function(e){return i?(i=!1,e):n("next",e)},"function"==typeof e.throw&&(t.throw=function(e){if(i)throw i=!1,e;return n("throw",e)}),"function"==typeof e.return&&(t.return=function(e){return i?(i=!1,e):n("return",e)}),t}function hi(e){var t,i,n,o=2;for("undefined"!=typeof Symbol&&(i=Symbol.asyncIterator,n=Symbol.iterator);o--;){if(i&&null!=(t=e[i]))return t.call(e);if(n&&null!=(t=e[n]))return new _i(t.call(e));i="@@asyncIterator",n="@@iterator"}throw new TypeError("Object is not async iterable")}function _i(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 _i=function(e){this.s=e,this.n=e.next},_i.prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(e){var i=this.s.return;return void 0===i?Promise.resolve({value:e,done:!0}):t(i.apply(this.s,arguments))},throw:function(e){var i=this.s.return;return void 0===i?Promise.reject(e):t(i.apply(this.s,arguments))}},new _i(e)}function pi(e){return new di(e,0)}function Ei(e,t,i){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var n=i.call(e,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function Si(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function mi(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Si(Object(i),!0).forEach((function(t){Ei(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Si(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function Ri(e){return function(){return new fi(e.apply(this,arguments))}}function fi(e){var t,i;function n(t,i){try{var a=e[t](i),s=a.value,r=s instanceof di;Promise.resolve(r?s.v:s).then((function(i){if(r){var c="return"===t?"return":"next";if(!s.k||i.done)return n(c,i);i=e[c](i).value}o(a.done?"return":"normal",i)}),(function(e){n("throw",e)}))}catch(e){o("throw",e)}}function o(e,o){switch(e){case"return":t.resolve({value:o,done:!0});break;case"throw":t.reject(o);break;default:t.resolve({value:o,done:!1})}(t=t.next)?n(t.key,t.arg):i=null}this._invoke=function(e,o){return new Promise((function(a,s){var r={key:e,arg:o,resolve:a,reject:s,next:null};i?i=i.next=r:(t=i=r,n(e,o))}))},"function"!=typeof e.return&&(this.return=void 0)}fi.prototype["function"==typeof Symbol&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},fi.prototype.next=function(e){return this._invoke("next",e)},fi.prototype.throw=function(e){return this._invoke("throw",e)},fi.prototype.return=function(e){return this._invoke("return",e)};let Ci=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}({}),Ti=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}({}),Ii=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}({}),Ai=function(e){return e[e.NO_FLAG_SET=100]="NO_FLAG_SET",e[e.FLAG_SET_BUT_EMPTY=101]="FLAG_SET_BUT_EMPTY",e[e.INVALID_FALG_SET=102]="INVALID_FALG_SET",e[e.FLAG_SET_BUT_NO_RE=103]="FLAG_SET_BUT_NO_RE",e[e.INVALID_SERVICE_ID=104]="INVALID_SERVICE_ID",e[e.NO_SERVICE_AVAILABLE=200]="NO_SERVICE_AVAILABLE",e[e.NO_SERVICE_AVAILABLE_P2P=201]="NO_SERVICE_AVAILABLE_P2P",e[e.NO_SERVICE_AVAILABLE_VOICE=202]="NO_SERVICE_AVAILABLE_VOICE",e[e.NO_SERVICE_AVAILABLE_WEBRTC=203]="NO_SERVICE_AVAILABLE_WEBRTC",e[e.NO_SERVICE_AVAILABLE_CDS=204]="NO_SERVICE_AVAILABLE_CDS",e[e.NO_SERVICE_AVAILABLE_CDN=205]="NO_SERVICE_AVAILABLE_CDN",e[e.NO_SERVICE_AVAILABLE_TDS=206]="NO_SERVICE_AVAILABLE_TDS",e[e.NO_SERVICE_AVAILABLE_REPORT=207]="NO_SERVICE_AVAILABLE_REPORT",e[e.NO_SERVICE_AVAILABLE_APP_CENTER=208]="NO_SERVICE_AVAILABLE_APP_CENTER",e[e.NO_SERVICE_AVAILABLE_ENV0=209]="NO_SERVICE_AVAILABLE_ENV0",e[e.NO_SERVICE_AVAILABLE_VOET=210]="NO_SERVICE_AVAILABLE_VOET",e[e.NO_SERVICE_AVAILABLE_STRING_UID=211]="NO_SERVICE_AVAILABLE_STRING_UID",e[e.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS=212]="NO_SERVICE_AVAILABLE_WEBRTC_UNILBS",e[e.NO_SERVICE_AVAILABLE_UNILBS_FLV=213]="NO_SERVICE_AVAILABLE_UNILBS_FLV",e}({}),gi=function(e){return e[e.K_TIMESTAMP_EXPIRED=2]="K_TIMESTAMP_EXPIRED",e[e.K_CHANNEL_PERMISSION_INVALID=3]="K_CHANNEL_PERMISSION_INVALID",e[e.K_CERTIFICATE_INVALID=4]="K_CERTIFICATE_INVALID",e[e.K_CHANNEL_NAME_EMPTY=5]="K_CHANNEL_NAME_EMPTY",e[e.K_CHANNEL_NOT_FOUND=6]="K_CHANNEL_NOT_FOUND",e[e.K_TICKET_INVALID=7]="K_TICKET_INVALID",e[e.K_CHANNEL_CONFLICTED=8]="K_CHANNEL_CONFLICTED",e[e.K_SERVICE_NOT_READY=9]="K_SERVICE_NOT_READY",e[e.K_SERVICE_TOO_HEAVY=10]="K_SERVICE_TOO_HEAVY",e[e.K_UID_BANNED=14]="K_UID_BANNED",e[e.K_IP_BANNED=15]="K_IP_BANNED",e[e.K_CHANNEL_BANNED=16]="K_CHANNEL_BANNED",e[e.DATASTREAM2_NOT_AVAILABLE=27]="DATASTREAM2_NOT_AVAILABLE",e[e.K_AUTO_REBALANCE=28]="K_AUTO_REBALANCE",e[e.WARN_NO_AVAILABLE_CHANNEL=103]="WARN_NO_AVAILABLE_CHANNEL",e[e.WARN_LOOKUP_CHANNEL_TIMEOUT=104]="WARN_LOOKUP_CHANNEL_TIMEOUT",e[e.WARN_LOOKUP_CHANNEL_REJECTED=105]="WARN_LOOKUP_CHANNEL_REJECTED",e[e.WARN_OPEN_CHANNEL_TIMEOUT=106]="WARN_OPEN_CHANNEL_TIMEOUT",e[e.WARN_OPEN_CHANNEL_REJECTED=107]="WARN_OPEN_CHANNEL_REJECTED",e[e.WARN_REQUEST_DEFERRED=108]="WARN_REQUEST_DEFERRED",e[e.ERR_DYNAMIC_KEY_TIMEOUT=109]="ERR_DYNAMIC_KEY_TIMEOUT",e[e.ERR_NO_AUTHORIZED=110]="ERR_NO_AUTHORIZED",e[e.ERR_VOM_SERVICE_UNAVAILABLE=111]="ERR_VOM_SERVICE_UNAVAILABLE",e[e.ERR_NO_CHANNEL_AVAILABLE_CODE=112]="ERR_NO_CHANNEL_AVAILABLE_CODE",e[e.ERR_MASTER_VOCS_UNAVAILABLE=114]="ERR_MASTER_VOCS_UNAVAILABLE",e[e.ERR_INTERNAL_ERROR=115]="ERR_INTERNAL_ERROR",e[e.ERR_NO_ACTIVE_STATUS=116]="ERR_NO_ACTIVE_STATUS",e[e.ERR_INVALID_UID=117]="ERR_INVALID_UID",e[e.ERR_DYNAMIC_KEY_EXPIRED=118]="ERR_DYNAMIC_KEY_EXPIRED",e[e.ERR_STATIC_USE_DYANMIC_KE=119]="ERR_STATIC_USE_DYANMIC_KE",e[e.ERR_DYNAMIC_USE_STATIC_KE=120]="ERR_DYNAMIC_USE_STATIC_KE",e[e.ERR_NO_VOCS_AVAILABLE=2e3]="ERR_NO_VOCS_AVAILABLE",e[e.ERR_NO_VOS_AVAILABLE=2001]="ERR_NO_VOS_AVAILABLE",e[e.ERR_JOIN_CHANNEL_TIMEOUT=2002]="ERR_JOIN_CHANNEL_TIMEOUT",e[e.ERR_REPEAT_JOIN_CHANNEL=2003]="ERR_REPEAT_JOIN_CHANNEL",e[e.ERR_JOIN_BY_MULTI_IP=2004]="ERR_JOIN_BY_MULTI_IP",e[e.ERR_NOT_JOINED=2011]="ERR_NOT_JOINED",e[e.ERR_REPEAT_JOIN_REQUEST=2012]="ERR_REPEAT_JOIN_REQUEST",e[e.ERR_INVALID_VENDOR_KEY=2013]="ERR_INVALID_VENDOR_KEY",e[e.ERR_INVALID_CHANNEL_NAME=2014]="ERR_INVALID_CHANNEL_NAME",e[e.ERR_INVALID_STRINGUID=2015]="ERR_INVALID_STRINGUID",e[e.ERR_TOO_MANY_USERS=2016]="ERR_TOO_MANY_USERS",e[e.ERR_SET_CLIENT_ROLE_TIMEOUT=2017]="ERR_SET_CLIENT_ROLE_TIMEOUT",e[e.ERR_SET_CLIENT_ROLE_NO_PERMISSION=2018]="ERR_SET_CLIENT_ROLE_NO_PERMISSION",e[e.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE=2019]="ERR_SET_CLIENT_ROLE_ALREADY_IN_USE",e[e.ERR_PUBLISH_REQUEST_INVALID=2020]="ERR_PUBLISH_REQUEST_INVALID",e[e.ERR_SUBSCRIBE_REQUEST_INVALID=2021]="ERR_SUBSCRIBE_REQUEST_INVALID",e[e.ERR_NOT_SUPPORTED_MESSAGE=2022]="ERR_NOT_SUPPORTED_MESSAGE",e[e.ERR_ILLEAGAL_PLUGIN=2023]="ERR_ILLEAGAL_PLUGIN",e[e.ERR_REJOIN_TOKEN_INVALID=2024]="ERR_REJOIN_TOKEN_INVALID",e[e.ERR_REJOIN_USER_NOT_JOINED=2025]="ERR_REJOIN_USER_NOT_JOINED",e[e.ERR_INVALID_OPTIONAL_INFO=2027]="ERR_INVALID_OPTIONAL_INFO",e[e.ILLEGAL_AES_PASSWORD=2028]="ILLEGAL_AES_PASSWORD",e[e.ILLEGAL_CLIENT_ROLE_LEVEL=2029]="ILLEGAL_CLIENT_ROLE_LEVEL",e[e.ERR_TOO_MANY_BROADCASTERS=2031]="ERR_TOO_MANY_BROADCASTERS",e[e.ERR_TOO_MANY_SUBSCRIBERS=2032]="ERR_TOO_MANY_SUBSCRIBERS",e[e.ERR_LICENSE_MISSING=32769]="ERR_LICENSE_MISSING",e[e.ERR_LICENSE_EXPIRED=32771]="ERR_LICENSE_EXPIRED",e[e.ERR_LICENSE_MINUTES_EXCEEDED=32773]="ERR_LICENSE_MINUTES_EXCEEDED",e[e.ERR_LICENSE_PERIOD_INVALID=32774]="ERR_LICENSE_PERIOD_INVALID",e[e.ERR_LICENSE_MULTIPLE_SDK_SERVICE=32778]="ERR_LICENSE_MULTIPLE_SDK_SERVICE",e[e.ERR_LICENSE_ILLEGAL=32783]="ERR_LICENSE_ILLEGAL",e[e.ERR_TEST_RECOVER=9e3]="ERR_TEST_RECOVER",e[e.ERR_TEST_TRYNEXT=9001]="ERR_TEST_TRYNEXT",e[e.ERR_TEST_RETRY=9002]="ERR_TEST_RETRY",e}({}),vi=function(e){return e.CONNECTING="connecting",e.CONNECTED="connected",e.RECONNECTING="reconnecting",e.CLOSED="closed",e}({}),yi=function(e){return e.WS_CONNECTED="ws_connected",e.WS_RECONNECTING="ws_reconnecting",e.WS_CLOSED="ws_closed",e.WS_RECONNECT_CREATE_CONNECTION="ws_reconnect_create_connection",e.ON_BINARY_DATA="on_binary_data",e.REQUEST_RECOVER="request_recover",e.REQUEST_JOIN_INFO="request_join_info",e.REQUEST_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.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}({}),Ni=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.SWITCH_VIDEO_STREAM="switch_video_stream",e.DEFAULT_VIDEO_STREAM="default_video_stream",e.SET_FALLBACK_OPTION="set_fallback_option",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}({}),bi=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}({}),wi=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}({}),Oi=function(e){return e.SEND_ONLY="SEND_ONLY",e.RECEIVE_ONLY="RECEIVE_ONLY",e}({}),Di=function(e){return e.CONNECTED="websocket:connected",e.RECONNECTING="websocket:reconnecting",e.WILL_RECONNECT="websocket:will_reconnect",e.CLOSED="websocket:closed",e.FAILED="websocket:failed",e.ON_MESSAGE="websocket:on_message",e.REQUEST_NEW_URLS="websocket:request_new_urls",e.RECONNECT_CREATE_CONNECTION="websocket:reconnect_create_connection",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="websocket:on_token_privilege_did_expire",e}({});function Pi(e){if("string"!=typeof e||!/^[a-zA-Z0-9 \!\#\$\%\&\(\)\+\-\:\;\<\=\.\>\?\@\[\]\^\_\{\}\|\~\,]{1,64}$/.test(e))throw B.error("Invalid Channel Name ".concat(e)),new F(Z.INVALID_PARAMS,"The length must be within 64 bytes. The supported characters: a-z,A-Z,0-9,space,!, #, $, %, &, (, ), +, -, :, ;, <, =, ., >, ?, @, [, ], ^, _, {, }, |, ~, ,")}function Li(e){if(!(t=e,"number"==typeof t&&Math.floor(t)===t&&0<=t&&t<=4294967295||$(e,1,255)))throw new F(Z.INVALID_PARAMS,"[String uid] Length of the string: [1,255]. ASCII characters only. [Number uid] The value range is [0,10000]");var t;"string"==typeof e&&B.warn("You input a string as the user ID, to ensure better end-user experience, Agora highly suggests not using a string as the user ID.")}let ki=function(e){return e.TRANSCODE="mix_streaming",e.RAW="raw_streaming",e}({}),Ui=function(e){return e.REQUEST_WORKER_MANAGER_LIST="@live_req_worker_manager",e}({});function Mi(e){if(!e.channelName)throw new F(Z.INVALID_PARAMS,"invalid channelName in info");if("number"!=typeof e.uid)throw new F(Z.INVALID_PARAMS,"invalid uid in info, uid must be a number");return e.token&&ee(e.token,"info.token",1,2047),Li(e.uid),Pi(e.channelName),!0}let Vi=function(e){return e.NETWORK_DISCONNECTED="NETWORK_DISCONNECTED",e.NETWORK_CONNECTED="NETWORK_CONNECTED",e.PACKET_JOINED_SRC_CHANNEL="PACKET_JOINED_SRC_CHANNEL",e.PACKET_JOINED_DEST_CHANNEL="PACKET_JOINED_DEST_CHANNEL",e.PACKET_SENT_TO_DEST_CHANNEL="PACKET_SENT_TO_DEST_CHANNEL",e.PACKET_RECEIVED_VIDEO_FROM_SRC="PACKET_RECEIVED_VIDEO_FROM_SRC",e.PACKET_RECEIVED_AUDIO_FROM_SRC="PACKET_RECEIVED_AUDIO_FROM_SRC",e.PACKET_UPDATE_DEST_CHANNEL="PACKET_UPDATE_DEST_CHANNEL",e.PACKET_UPDATE_DEST_CHANNEL_REFUSED="PACKET_UPDATE_DEST_CHANNEL_REFUSED",e.PACKET_UPDATE_DEST_CHANNEL_NOT_CHANGE="PACKET_UPDATE_DEST_CHANNEL_NOT_CHANGE",e}({}),xi=function(e){return e.RELAY_STATE_IDLE="RELAY_STATE_IDLE",e.RELAY_STATE_CONNECTING="RELAY_STATE_CONNECTING",e.RELAY_STATE_RUNNING="RELAY_STATE_RUNNING",e.RELAY_STATE_FAILURE="RELAY_STATE_FAILURE",e}({}),Bi=function(e){return e.RELAY_OK="RELAY_OK",e.SERVER_CONNECTION_LOST="SERVER_CONNECTION_LOST",e.SRC_TOKEN_EXPIRED="SRC_TOKEN_EXPIRED",e.DEST_TOKEN_EXPIRED="DEST_TOKEN_EXPIRED",e}({}),Fi=function(e){return e.High="high",e.Low="low",e.Audio="audio",e.Screen="screen",e.ScreenLow="screen_low",e}({}),ji=function(e){return e.DISCONNECT="disconnect",e.CONNECTION_STATE_CHANGE="connection-state-change",e.NETWORK_QUALITY="network-quality",e.STREAM_TYPE_CHANGE="stream-type-change",e.IS_P2P_DISCONNECTED="is-p2p-dis",e.DISCONNECT_P2P="dis-p2p",e.REQUEST_NEW_GATEWAY_LIST="req-gate-url",e.NEED_RENEW_SESSION="need-sid",e.REQUEST_P2P_CONNECTION_PARAMS="request-p2p-connection-params",e.JOIN_RESPONSE="join-response",e.RESET_CONNECTION_EVENTS="reset-connection-events",e.PRE_CONNECT_PC="pre-connect_pc",e.UPDATE_GATEWAY_CONFIG="update-gateway-config",e}({}),Gi=function(e){return e.P2P_DISCONNECTED="P2P_DISCONNECTED",e.A_ROUND_WS_FAILED="A_ROUND_WS_FAILED",e.TIMEOUT="TIMEOUT",e.UNKNOWN_REASON="UNKNOWN_REASON",e}({}),Wi=function(e){return e[e.Nothing=0]="Nothing",e[e.Audio=1]="Audio",e[e.LwoVideo=2]="LwoVideo",e[e.Video=4]="Video",e[e.Data=8]="Data",e[e.DataStream0=256]="DataStream0",e[e.DataStream1=512]="DataStream1",e[e.DataStream2=1024]="DataStream2",e[e.DataStream3=2048]="DataStream3",e[e.DataStream4=4096]="DataStream4",e[e.DataStream5=8192]="DataStream5",e[e.DataStream6=16384]="DataStream6",e[e.DataStream7=32768]="DataStream7",e}({}),Hi=function(e){return e.CHINA="CHINA",e.ASIA="ASIA",e.NORTH_AMERICA="NORTH_AMERICA",e.EUROPE="EUROPE",e.JAPAN="JAPAN",e.INDIA="INDIA",e.KOREA="KOREA",e.HKMC="HKMC",e.US="US",e.OCEANIA="OCEANIA",e.SOUTH_AMERICA="SOUTH_AMERICA",e.AFRICA="AFRICA",e.OVERSEA="OVERSEA",e.GLOBAL="GLOBAL",e.EXTENSIONS="EXTENSIONS",e}({});const Ki=[Hi.AFRICA,Hi.ASIA,Hi.CHINA,Hi.EUROPE,Hi.GLOBAL,Hi.INDIA,Hi.JAPAN,Hi.NORTH_AMERICA,Hi.OCEANIA,Hi.OVERSEA,Hi.SOUTH_AMERICA];let Yi=function(e){return e.CHINA="CN",e.ASIA="AS",e.NORTH_AMERICA="NA",e.EUROPE="EU",e.JAPAN="JP",e.INDIA="IN",e.KOREA="KR",e.HKMC="HK",e.US="US",e.OCEANIA="OC",e.SOUTH_AMERICA="SA",e.AFRICA="AF",e.OVERSEA="OVERSEA",e.GLOBAL="GLOBAL",e.EXTENSIONS="GLOBAL",e}({});const qi={CHINA:{},ASIA:{CODE:Yi.ASIA,WEBCS_DOMAIN:["ap-web-1-asia.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-asia.agora.io"],PROXY_CS:["proxy-ap-web-asia.agora.io"],CDS_AP:["cds-ap-web-asia.agora.io","cds-ap-web-asia2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-asia.agora.io","sua-ap-web-asia2.agora.io"],UAP_AP:["uap-ap-web-asia.agora.io","uap-ap-web-asia2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-asia.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-asia.agora.io"],LOG_UPLOAD_SERVER:["logservice-asia.agora.io"],PROXY_SERVER_TYPE3:["southeast-asia.webrtc-cloud-proxy.sd-rtn.com"]},NORTH_AMERICA:{CODE:Yi.NORTH_AMERICA,WEBCS_DOMAIN:["ap-web-1-north-america.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-north-america.agora.io"],PROXY_CS:["proxy-ap-web-america.agora.io"],CDS_AP:["cds-ap-web-america.agora.io","cds-ap-web-america2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-america.agora.io","sua-ap-web-america2.agora.io"],UAP_AP:["uap-ap-web-america.agora.io","uap-ap-web-america2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-north-america.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-north-america.agora.io"],LOG_UPLOAD_SERVER:["logservice-north-america.agora.io"],PROXY_SERVER_TYPE3:["east-usa.webrtc-cloud-proxy.sd-rtn.com"]},EUROPE:{CODE:Yi.EUROPE,WEBCS_DOMAIN:["ap-web-1-europe.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-europe.agora.io"],PROXY_CS:["proxy-ap-web-europe.agora.io"],CDS_AP:["cds-ap-web-europe.agora.io","cds-ap-web-europe2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-europe.agora.io","sua-ap-web-europe.agora.io"],UAP_AP:["uap-ap-web-europe.agora.io","uap-ap-web-europe2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-europe.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-europe.agora.io"],LOG_UPLOAD_SERVER:["logservice-europe.agora.io"],PROXY_SERVER_TYPE3:["europe.webrtc-cloud-proxy.sd-rtn.com"]},JAPAN:{CODE:Yi.JAPAN,WEBCS_DOMAIN:["ap-web-1-japan.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-japan.agora.io"],PROXY_CS:["proxy-ap-web-japan.agora.io"],CDS_AP:["cds-ap-web-japan.agora.io","cds-ap-web-japan2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-japan.agora.io","sua-ap-web-japan2.agora.io"],UAP_AP:["uap-ap-web-japan.agora.io","uap-ap-web-japan2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-japan.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-japan.agora.io"],LOG_UPLOAD_SERVER:["logservice-japan.agora.io"],PROXY_SERVER_TYPE3:["japan.webrtc-cloud-proxy.sd-rtn.com"]},INDIA:{CODE:Yi.INDIA,WEBCS_DOMAIN:["ap-web-1-india.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-india.agora.io"],PROXY_CS:["proxy-ap-web-india.agora.io"],CDS_AP:["cds-ap-web-india.agora.io","cds-ap-web-india2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-india.agora.io","sua-ap-web-india2.agora.io"],UAP_AP:["uap-ap-web-india.agora.io","uap-ap-web-india2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-india.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-india.agora.io"],LOG_UPLOAD_SERVER:["logservice-india.agora.io"],PROXY_SERVER_TYPE3:["india.webrtc-cloud-proxy.sd-rtn.com"]},KOREA:{CODE:Yi.KOREA,WEBCS_DOMAIN:["ap-web-1-korea.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-korea.agora.io"],PROXY_CS:["proxy-ap-web-korea.agora.io"],CDS_AP:["cds-ap-web-korea.agora.io","cds-ap-web-korea2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-korea.agora.io","sua-ap-web-korea2.agora.io"],UAP_AP:["uap-ap-web-korea.agora.io","uap-ap-web-korea2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-korea.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-korea.agora.io"],LOG_UPLOAD_SERVER:["logservice-korea.agora.io"],PROXY_SERVER_TYPE3:["korea.webrtc-cloud-proxy.sd-rtn.com"]},HKMC:{CODE:Yi.HKMC,WEBCS_DOMAIN:["ap-web-1-hkmc.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-hkmc.agora.io"],PROXY_CS:["proxy-ap-web-hkmc.agora.io"],CDS_AP:["cds-ap-web-hkmc.agora.io","cds-ap-web-hkmc2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-hkmc.agora.io","sua-ap-web-hkmc2.agora.io"],UAP_AP:["uap-ap-web-hkmc.agora.io","uap-ap-web-hkmc2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-hkmc.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-hkmc.agora.io"],LOG_UPLOAD_SERVER:["logservice-hkmc.agora.io"],PROXY_SERVER_TYPE3:["hkmc.webrtc-cloud-proxy.sd-rtn.com"]},US:{CODE:Yi.US,WEBCS_DOMAIN:["ap-web-1-us.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-us.agora.io"],PROXY_CS:["proxy-ap-web-us.agora.io"],CDS_AP:["cds-ap-web-us.agora.io","cds-ap-web-us2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-us.agora.io","sua-ap-web-us2.agora.io"],UAP_AP:["uap-ap-web-us.agora.io","uap-ap-web-us2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-us.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-us.agora.io"],LOG_UPLOAD_SERVER:["logservice-us.agora.io"],PROXY_SERVER_TYPE3:["us.webrtc-cloud-proxy.sd-rtn.com"]},OVERSEA:{CODE:Yi.OVERSEA,WEBCS_DOMAIN:["ap-web-1-oversea.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-oversea.agora.io"],PROXY_CS:["proxy-ap-web-oversea.agora.io"],CDS_AP:["cds-ap-web-oversea.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-oversea.agora.io"],UAP_AP:["uap-ap-web-oversea.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-oversea.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-oversea.agora.io"],LOG_UPLOAD_SERVER:["logservice-oversea.agora.io"],PROXY_SERVER_TYPE3:["webrtc-cloud-proxy.agora.io"]},GLOBAL:{CODE:Yi.GLOBAL,WEBCS_DOMAIN:["webrtc2-ap-web-1.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["webrtc2-ap-web-3.agora.io"],PROXY_CS:["ap-proxy-1.agora.io","ap-proxy-2.agora.io"],CDS_AP:["cds-ap-web-1.agora.io","cds-ap-web-3.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-1.agora.io","sua-ap-web-3.agora.io"],UAP_AP:["uap-ap-web-1.agora.io","uap-ap-web-3.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2.agora.io"],LOG_UPLOAD_SERVER:["logservice.agora.io"],PROXY_SERVER_TYPE3:["webrtc-cloud-proxy.sd-rtn.com"]},OCEANIA:{CODE:Yi.OCEANIA,WEBCS_DOMAIN:["ap-web-1-oceania.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-oceania.agora.io"],PROXY_CS:["proxy-ap-web-oceania.agora.io"],CDS_AP:["cds-ap-web-oceania.agora.io","cds-ap-web-oceania2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-oceania.agora.io","sua-ap-web-oceania2.agora.io"],UAP_AP:["uap-ap-web-oceania.agora.io","uap-ap-web-oceania2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-oceania.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-oceania.agora.io"],LOG_UPLOAD_SERVER:["logservice-oceania.agora.io"],PROXY_SERVER_TYPE3:["oceania.webrtc-cloud-proxy.sd-rtn.com"]},SOUTH_AMERICA:{CODE:Yi.SOUTH_AMERICA,WEBCS_DOMAIN:["ap-web-1-south-america.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-south-america.agora.io"],PROXY_CS:["proxy-ap-web-south-america.agora.io"],CDS_AP:["cds-ap-web-south-america.agora.io","cds-ap-web-south-america2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-south-america.agora.io","sua-ap-web-south-america2.agora.io"],UAP_AP:["uap-ap-web-south-america.agora.io","uap-ap-web-south-america2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-south-america.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-south-america.agora.io"],LOG_UPLOAD_SERVER:["logservice-south-america.agora.io"],PROXY_SERVER_TYPE3:["south-america.webrtc-cloud-proxy.sd-rtn.com"]},AFRICA:{CODE:Yi.AFRICA,WEBCS_DOMAIN:["ap-web-1-africa.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-africa.agora.io"],PROXY_CS:["proxy-ap-web-africa.agora.io"],CDS_AP:["cds-ap-web-africa.agora.io","cds-ap-web-africa2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-africa.agora.io","sua-ap-web-africa2.agora.io"],UAP_AP:["uap-ap-web-africa.agora.io","uap-ap-web-africa2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-africa.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-africa.agora.io"],LOG_UPLOAD_SERVER:["logservice-south-africa.agora.io"],PROXY_SERVER_TYPE3:["africa.webrtc-cloud-proxy.sd-rtn.com"]},EXTENSIONS:{}};te&&(qi.CHINA={CODE:Yi.CHINA,WEBCS_DOMAIN:["webrtc2-2.ap.sd-rtn.com"],WEBCS_DOMAIN_BACKUP_LIST:["webrtc2-4.ap.sd-rtn.com"],PROXY_CS:["proxy-web.ap.sd-rtn.com"],CDS_AP:["cds-web-2.ap.sd-rtn.com","cds-web-4.ap.sd-rtn.com"],ACCOUNT_REGISTER:["sua-web-2.ap.sd-rtn.com","sua-web-4.ap.sd-rtn.com"],UAP_AP:["uap-web-2.ap.sd-rtn.com","uap-web-4.ap.sd-rtn.com"],EVENT_REPORT_DOMAIN:["web-3.statscollector.sd-rtn.com"],EVENT_REPORT_BACKUP_DOMAIN:["web-4.statscollector.sd-rtn.com"],LOG_UPLOAD_SERVER:["logservice-china.agora.io"],PROXY_SERVER_TYPE3:["east-cn.webrtc-cloud-proxy.sd-rtn.com"]});let Xi=function(e){return e.UPDATE_BITRATE_LIMIT="update_bitrate_limit",e.UPDATE_CLIENT_ROLE_OPTIONS="update_client_role_options",e}({});function Ji(e){return!!e&&(!(!e.uplink||!e.id)&&(void 0!==e.uplink.max_bitrate&&void 0!==e.uplink.min_bitrate))}class zi extends ie{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.onFirstVideoDecodedTimeout=void 0,this.onSelectedLocalCandidateChanged=void 0,this.onSelectedRemoteCandidateChanged=void 0,this.onICECandidateError=void 0,this.getLocalVideoStats=void 0}}class Qi extends zi{constructor(e,t){super(e,t),this.establishPromise=void 0}}let Zi=function(e){return e.VIDEO="video",e.AUDIO="audio",e}({}),$i=function(e){return e.UDP_RELAY="udp_relay",e.UDP_TCP_RELAY="udp_tcp_relay",e.TCP_RELAY="tcp_relay",e.RELAY="relay",e}({}),en=function(e){return e[e.FIRST_CONNECTION=0]="FIRST_CONNECTION",e[e.UDP_TCP_RESTART=1]="UDP_TCP_RESTART",e[e.RELAY_RESTART=2]="RELAY_RESTART",e[e.TCP_RESTART=3]="TCP_RESTART",e[e.OLD_FIRST_CONNECTION=10]="OLD_FIRST_CONNECTION",e[e.OLD_RESTART=11]="OLD_RESTART",e[e.DISCONNECTED_OR_FAILED=20]="DISCONNECTED_OR_FAILED",e}({});const tn=["disconnected","failed"];let nn=function(e){return e.LocalVideoTrack="videoTrack",e.LocalAudioTrack="audioTrack",e.LocalVideoLowTrack="videoLowTrack",e}({}),on=function(e){return e.New="new",e.Connected="connected",e.Reconnecting="reconnecting",e.Disconnected="disconnected",e}({}),an=function(e){return e.AudioMetadata="audioMetadata",e.AudioPts="audioPts",e.StateChange="stateChange",e.IceConnectionStateChange="iceConnectionStateChange",e.RequestMuteLocal="requestMuteLocal",e.RequestUnmuteLocal="requestUnmuteLocal",e.RequestRePublish="requestRePublish",e.RequestRePublishDataChannel="requestRePublishDataChannel",e.RequestReSubscribe="requestReSubscribe",e.RequestUploadStats="requestUploadStats",e.RequestUpload="requestUpload",e.MediaReconnectStart="MediaReconnectStart",e.MediaReconnectEnd="MediaReconnectEnd",e.NeedSignalRTT="NeedSignalRTT",e.RequestRestartICE="RequestRestartIce",e.PeerConnectionStateChange="PeerConnectionStateChange",e.RequestReconnect="RequestReconnect",e.RequestReconnectPC="RequestReconnectPC",e.RequestUnpublishForReconnectPC="RequestUnpublishForReconnectPC",e.P2PLost="P2PLost",e.UpdateVideoEncoder="UpdateVideoEncoder",e.ConnectionTypeChange="ConnectionTypeChange",e.RequestLowStreamParameter="RequestLowStreamParameter",e.QueryClientConnectionState="QueryClientConnectionState",e.LocalCandidate="LocalCandidate",e.RequestP2PMuteLocal="requestP2PMuteLocal",e.RequestP2PUnPublish="RequestP2PUnPublish",e.RequestP2PUnmuteRemote="RequestP2PUnmuteRemote",e.RequestP2PMuteRemote="RequestP2PMuteRemote",e.RequestP2PRestartICE="RequestP2PRestartICE",e}({}),sn=function(e){return e.CONNECTING="CONNECTING",e.RECONNECTING="RECONNECTING",e.CONNECTED="CONNECTED",e.CLOSED="CLOSED",e}({}),rn=function(e){return e.CONNECTION_STATE_CHANGE="connection-state-change",e.STATE_CHANGE="state-change",e.INSPECT_RESULT="inspect-result",e.CLIENT_LOCAL_VIDEO_TRACK="client-local-video-track",e.REQUEST_NEW_WORKER_URL="request-new-worker-url",e}({}),cn=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}({}),dn=function(e){return e.CAMERA_CHANGED="camera-changed",e.MICROPHONE_CHANGED="microphone-changed",e.PLAYBACK_DEVICE_CHANGED="playback-device-changed",e.AUDIO_AUTOPLAY_FAILED="audio-autoplay-failed",e.AUTOPLAY_FAILED="autoplay-failed",e.AUDIO_CONTEXT_STATE_CHANGED="audio-context-state-changed",e.SECURITY_POLICY_VIOLATION="security-policy-violation",e}({}),ln=function(e){return e.CONNECTING="CONNECTING",e.RECONNECTING="RECONNECTING",e.CONNECTED="CONNECTED",e.CLOSED="CLOSED",e}({}),un=function(e){return e.CONNECTION_STATE_CHANGE="connection-state-change",e.STATE_CHANGE="state-change",e.INSPECT_RESULT="inspect-result",e.CLIENT_LOCAL_VIDEO_TRACK="client-local-video-track",e.REQUEST_NEW_WORKER_URL="request-new-worker-url",e}({}),hn=function(e){return e.CALL="call",e.CANDIDATE="candidate",e.PUBLISH="publish",e.UNPUBLISH="unpublish",e.CONTROL="control",e.RESTART_ICE="restart_ice",e.ACK="ack",e.RESPONSE="response",e.JOIN="join",e.CHECK="check",e}({}),_n=function(e){return e.MUTE_LOCAL_AUDIO="mute_local_audio",e.MUTE_LOCAL_VIDEO="mute_local_video",e.UNMUTE_LOCAL_AUDIO="unmute_local_audio",e.UNMUTE_LOCAL_VIDEO="unmute_local_video",e}({});const pn={[Ci.ACCESS_POINT]:{[Ai.NO_FLAG_SET]:{desc:"flag is zero",retry:!1},[Ai.FLAG_SET_BUT_EMPTY]:{desc:"flag is empty",retry:!1},[Ai.INVALID_FALG_SET]:{desc:"invalid flag",retry:!1},[Ai.FLAG_SET_BUT_NO_RE]:{desc:"flag set unilbs but no request",retry:!1},[Ai.INVALID_SERVICE_ID]:{desc:"invalid service id",retry:!1},[Ai.NO_SERVICE_AVAILABLE]:{desc:"no service available",retry:!0},[Ai.NO_SERVICE_AVAILABLE_P2P]:{desc:"no unilbs p2p service available",retry:!0},[Ai.NO_SERVICE_AVAILABLE_VOICE]:{desc:"no unilbs voice service available",retry:!0},[Ai.NO_SERVICE_AVAILABLE_WEBRTC]:{desc:"no unilbs webrtc service available",retry:!0},[Ai.NO_SERVICE_AVAILABLE_CDS]:{desc:"no cds service available",retry:!0},[Ai.NO_SERVICE_AVAILABLE_CDN]:{desc:"no cdn dispatcher service available",retry:!0},[Ai.NO_SERVICE_AVAILABLE_TDS]:{desc:"no tds service available",retry:!0},[Ai.NO_SERVICE_AVAILABLE_REPORT]:{desc:"no unilbs report service available",retry:!0},[Ai.NO_SERVICE_AVAILABLE_APP_CENTER]:{desc:"no app center service available",retry:!0},[Ai.NO_SERVICE_AVAILABLE_ENV0]:{desc:"no unilbs sig env0 service available",retry:!0},[Ai.NO_SERVICE_AVAILABLE_VOET]:{desc:"no unilbs voet service available",retry:!0},[Ai.NO_SERVICE_AVAILABLE_STRING_UID]:{desc:"no string uid service available",retry:!0},[Ai.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS]:{desc:"no webrtc unilbs service available",retry:!0}},[Ci.UNILBS]:{[Ii.INVALID_VENDOR_KEY]:{desc:"invalid vendor key, can not find appid",retry:!1},[Ii.INVALID_CHANNEL_NAME]:{desc:"invalid channel name",retry:!1},[Ii.INTERNAL_ERROR]:{desc:"unilbs internal error",retry:!1},[Ii.NO_AUTHORIZED]:{desc:"invalid token, authorized failed",retry:!1},[Ii.DYNAMIC_KEY_TIMEOUT]:{desc:"dynamic key or token timeout",retry:!1},[Ii.NO_ACTIVE_STATUS]:{desc:"no active status",retry:!1},[Ii.DYNAMIC_KEY_EXPIRED]:{desc:"dynamic key expired",retry:!1},[Ii.STATIC_USE_DYNAMIC_KEY]:{desc:"static use dynamic key",retry:!1},[Ii.DYNAMIC_USE_STATIC_KEY]:{desc:"dynamic use static key",retry:!1},[Ii.USER_OVERLOAD]:{desc:"amount of users over load",retry:!1},[Ii.FORBIDDEN_REGION]:{desc:"the request is forbidden in this area",retry:!1},[Ii.CANNOT_MEET_AREA_DEMAND]:{desc:"unable to allocate services in this area",retry:!1}},[Ci.STRING_UID_ALLOCATOR]:{[Ti.IIIEGAL_APPID]:{desc:"invalid appid",retry:!1},[Ti.IIIEGAL_UID]:{desc:"invalid string uid",retry:!1},[Ti.INTERNAL_ERROR]:{desc:"string uid allocator internal error",retry:!0}}};function En(e){const t=pn[Math.floor(e/1e4)];if(!t)return{desc:"unknown error",retry:!1};const i=t[e%1e4];if(!i){if(Math.floor(e/1e4)===Ci.ACCESS_POINT){const t=e%1e4;if("1"===t.toString()[0])return{desc:e.toString(),retry:!1};if("2"===t.toString()[0])return{desc:e.toString(),retry:!0}}return{desc:"unknown error",retry:!1}}return i}const Sn={[gi.K_TIMESTAMP_EXPIRED]:{desc:"K_TIMESTAMP_EXPIRED",action:"failed"},[gi.K_CHANNEL_PERMISSION_INVALID]:{desc:"K_CHANNEL_PERMISSION_INVALID",action:"failed"},[gi.K_CERTIFICATE_INVALID]:{desc:"K_CERTIFICATE_INVALID",action:"failed"},[gi.K_CHANNEL_NAME_EMPTY]:{desc:"K_CHANNEL_NAME_EMPTY",action:"failed"},[gi.K_CHANNEL_NOT_FOUND]:{desc:"K_CHANNEL_NOT_FOUND",action:"failed"},[gi.K_TICKET_INVALID]:{desc:"K_TICKET_INVALID",action:"failed"},[gi.K_CHANNEL_CONFLICTED]:{desc:"K_CHANNEL_CONFLICTED",action:"failed"},[gi.K_SERVICE_NOT_READY]:{desc:"K_SERVICE_NOT_READY",action:"tryNext"},[gi.K_SERVICE_TOO_HEAVY]:{desc:"K_SERVICE_TOO_HEAVY",action:"tryNext"},[gi.K_UID_BANNED]:{desc:"K_UID_BANNED",action:"failed"},[gi.K_IP_BANNED]:{desc:"K_IP_BANNED",action:"failed"},[gi.DATASTREAM2_NOT_AVAILABLE]:{desc:"DATASTREAM2_NOT_AVAILABLE",action:"quit"},[gi.K_AUTO_REBALANCE]:{desc:"k_AUTO_REBALANCE",action:"recover"},[gi.ERR_INVALID_VENDOR_KEY]:{desc:"ERR_INVALID_VENDOR_KEY",action:"failed"},[gi.ERR_INVALID_CHANNEL_NAME]:{desc:"ERR_INVALID_CHANNEL_NAME",action:"failed"},[gi.WARN_NO_AVAILABLE_CHANNEL]:{desc:"WARN_NO_AVAILABLE_CHANNEL",action:"failed"},[gi.WARN_LOOKUP_CHANNEL_TIMEOUT]:{desc:"WARN_LOOKUP_CHANNEL_TIMEOUT",action:"tryNext"},[gi.WARN_LOOKUP_CHANNEL_REJECTED]:{desc:"WARN_LOOKUP_CHANNEL_REJECTED",action:"failed"},[gi.WARN_OPEN_CHANNEL_TIMEOUT]:{desc:"WARN_OPEN_CHANNEL_TIMEOUT",action:"tryNext"},[gi.WARN_OPEN_CHANNEL_REJECTED]:{desc:"WARN_OPEN_CHANNEL_REJECTED",action:"failed"},[gi.WARN_REQUEST_DEFERRED]:{desc:"WARN_REQUEST_DEFERRED",action:"failed"},[gi.ERR_DYNAMIC_KEY_TIMEOUT]:{desc:"ERR_DYNAMIC_KEY_TIMEOUT",action:"failed"},[gi.ERR_NO_AUTHORIZED]:{desc:"ERR_NO_AUTHORIZED",action:"failed"},[gi.ERR_VOM_SERVICE_UNAVAILABLE]:{desc:"ERR_VOM_SERVICE_UNAVAILABLE",action:"tryNext"},[gi.ERR_NO_CHANNEL_AVAILABLE_CODE]:{desc:"ERR_NO_CHANNEL_AVAILABLE_CODE",action:"failed"},[gi.ERR_MASTER_VOCS_UNAVAILABLE]:{desc:"ERR_MASTER_VOCS_UNAVAILABLE",action:"tryNext"},[gi.ERR_INTERNAL_ERROR]:{desc:"ERR_INTERNAL_ERROR",action:"tryNext"},[gi.ERR_NO_ACTIVE_STATUS]:{desc:"ERR_NO_ACTIVE_STATUS",action:"failed"},[gi.ERR_INVALID_UID]:{desc:"ERR_INVALID_UID",action:"failed"},[gi.ERR_DYNAMIC_KEY_EXPIRED]:{desc:"ERR_DYNAMIC_KEY_EXPIRED",action:"failed"},[gi.ERR_STATIC_USE_DYANMIC_KE]:{desc:"ERR_STATIC_USE_DYANMIC_KE",action:"failed"},[gi.ERR_DYNAMIC_USE_STATIC_KE]:{desc:"ERR_DYNAMIC_USE_STATIC_KE",action:"failed"},[gi.ERR_NO_VOCS_AVAILABLE]:{desc:"ERR_NO_VOCS_AVAILABLE",action:"tryNext"},[gi.ERR_NO_VOS_AVAILABLE]:{desc:"ERR_NO_VOS_AVAILABLE",action:"tryNext"},[gi.ERR_JOIN_CHANNEL_TIMEOUT]:{desc:"ERR_JOIN_CHANNEL_TIMEOUT",action:"tryNext"},[gi.ERR_JOIN_BY_MULTI_IP]:{desc:"ERR_JOIN_BY_MULTI_IP",action:"recover"},[gi.ERR_NOT_JOINED]:{desc:"ERR_NOT_JOINED",action:"failed"},[gi.ERR_REPEAT_JOIN_REQUEST]:{desc:"ERR_REPEAT_JOIN_REQUEST",action:"quit"},[gi.ERR_REPEAT_JOIN_CHANNEL]:{desc:"ERR_REPEAT_JOIN_CHANNEL",action:"quit"},[gi.ERR_INVALID_STRINGUID]:{desc:"ERR_INVALID_STRINGUID",action:"failed"},[gi.ERR_TOO_MANY_USERS]:{desc:"ERR_TOO_MANY_USERS",action:"tryNext"},[gi.ERR_SET_CLIENT_ROLE_TIMEOUT]:{desc:"ERR_SET_CLIENT_ROLE_TIMEOUT",action:"failed"},[gi.ERR_SET_CLIENT_ROLE_NO_PERMISSION]:{desc:"ERR_SET_CLIENT_ROLE_TIMEOUT",action:"failed"},[gi.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE]:{desc:"ERR_SET_CLIENT_ROLE_ALREADY_IN_USE",action:"success"},[gi.ERR_PUBLISH_REQUEST_INVALID]:{desc:"ERR_PUBLISH_REQUEST_INVALID",action:"failed"},[gi.ERR_SUBSCRIBE_REQUEST_INVALID]:{desc:"ERR_SUBSCRIBE_REQUEST_INVALID",action:"failed"},[gi.ERR_NOT_SUPPORTED_MESSAGE]:{desc:"ERR_NOT_SUPPORTED_MESSAGE",action:"failed"},[gi.ERR_ILLEAGAL_PLUGIN]:{desc:"ERR_ILLEAGAL_PLUGIN",action:"failed"},[gi.ILLEGAL_CLIENT_ROLE_LEVEL]:{desc:"ILLEGAL_CLIENT_ROLE_LEVEL",action:"failed"},[gi.ERR_REJOIN_TOKEN_INVALID]:{desc:"ERR_REJOIN_TOKEN_INVALID",action:"failed"},[gi.ERR_REJOIN_USER_NOT_JOINED]:{desc:"ERR_REJOIN_NOT_JOINED",action:"failed"},[gi.ERR_INVALID_OPTIONAL_INFO]:{desc:"ERR_INVALID_OPTIONAL_INFO",action:"quit"},[gi.ERR_TEST_RECOVER]:{desc:"ERR_TEST_RECOVER",action:"recover"},[gi.ERR_TEST_TRYNEXT]:{desc:"ERR_TEST_TRYNEXT",action:"recover"},[gi.ERR_TEST_RETRY]:{desc:"ERR_TEST_RETRY",action:"recover"},[gi.ILLEGAL_AES_PASSWORD]:{desc:"ERR_TEST_RETRY",action:"failed"},[gi.ERR_TOO_MANY_BROADCASTERS]:{desc:"ERR_TOO_MANY_BROADCASTERS",action:"failed"},[gi.ERR_TOO_MANY_SUBSCRIBERS]:{desc:"ERR_TOO_MANY_SUBSCRIBERS",action:"failed"},[gi.ERR_LICENSE_ILLEGAL]:{desc:"ERR_LICENSE_ILLEGAL",action:"quit"},[gi.ERR_LICENSE_MISSING]:{desc:"ERR_LICENSE_MISSING",action:"quit"},[gi.ERR_LICENSE_EXPIRED]:{desc:"ERR_LICENSE_EXPIRED",action:"quit"},[gi.ERR_LICENSE_MINUTES_EXCEEDED]:{desc:"ERR_LICENSE_MINUTES_EXCEEDED",action:"quit"},[gi.ERR_LICENSE_PERIOD_INVALID]:{desc:"ERR_LICENSE_PERIOD_INVALID",action:"quit"},[gi.ERR_LICENSE_MULTIPLE_SDK_SERVICE]:{desc:"ERR_LICENSE_MULTIPLE_SDK_SERVICE",action:"quit"}};function mn(e){const t=Sn[e];return t||{desc:"UNKNOWN_ERROR_".concat(e),action:"failed"}}function Rn(e,t){if("string"==typeof e)return e;const{proxy:i,host:n,port:o}=e;if(t){const e=ne("JOIN_GATEWAY_FALLBACK_PORT")||443;return 443===e?"wss://".concat(n,"/ws/?p=").concat(Number(o)+150):"wss://".concat(n,":").concat(e,"/ws/?p=").concat(Number(o)+150)}return i?"wss://".concat(i,"/ws/?h=").concat(n,"&p=").concat(o):"wss://".concat(n,":").concat(o)}const fn=/wss:\/\/(.+)\/ws\/\?h=(.+)&p=([0-9]+)\/?/,Cn=/wss:\/\/(.+)\/ws\/\?p=([0-9]+)\/?/,Tn=/wss:\/\/(.+):([0-9]+)\/?/,In=/wss:\/\/(.[^\/]+)\/?/;let An=0;class gn{constructor(e,t){this.id=0,this.store=void 0,this.recordIndex=void 0,this.websockets=[],this.try443PortDuration=2e3,this.forceCloseWSDuration=5e3,this.try443PortTimeout=null,this.forceCloseTimeout=null,this.isTry443PortFailed=!1,this.isNormalPortFailed=!1,this.useDoubleDomain=!1,this.useProxy=!1,this.startTime=Date.now(),this.id=++An,this.try443PortDuration=ne("JOIN_GATEWAY_TRY_443PORT_DURATION")||2e3,this.forceCloseWSDuration=e||5e3,this.store=t}closeAllWebsockets(){this.websockets.forEach((e=>{e.onopen=null,e.onclose=null,e.onmessage=null,e.close()})),this.websockets.length=0}clearTimeout(){this.forceCloseTimeout&&clearTimeout(this.forceCloseTimeout),this.try443PortTimeout&&clearTimeout(this.try443PortTimeout),this.forceCloseTimeout=null,this.try443PortTimeout=null}logger(){var e;const t=Date.now()-this.startTime;for(var i=arguments.length,n=new Array(i),o=0;o<i;o++)n[o]=arguments[o];B.debug("[choose-best-ws ".concat(null===(e=this.store)||void 0===e?void 0:e.clientId," ").concat(this.id,"] ").concat(t,"ms:"),...n)}createWebSocket(e,t,i){this.logger("createWebSocket:",e,{isTry443Port:t,hasTimeoutDetection:i});const n=ne("GATEWAY_DOMAINS"),o=Date.now(),a=[],s=n.find((t=>e.host.includes(t)));s||(this.useDoubleDomain=!1);const r=[];if(this.useDoubleDomain)n.forEach((i=>{r.push(Rn(mi(mi({},e),{},{host:e.host.replace(s,i)}),t))}));else{const i=mi({},e);if(t&&s){const e=n.find((e=>e!==s));e&&(i.host=i.host.replace(s,e))}r.push(Rn(i,t))}try{r.forEach((e=>{const t=new WebSocket(e);t.binaryType="arraybuffer",a.push(t),this.logger("ws is connecting:",t.url)}))}catch(n){if(this.logger("ws create failed"),a.forEach((e=>e.close())),a.length=0,this.useDoubleDomain)return this.useDoubleDomain=!1,this.createWebSocket(e,t,i);if(!t&&443!==Number(e.port))return this.createWebSocket(e,!0,i);throw new F(Z.WS_ERR,"init websocket failed! Error: ".concat(n.toString()))}const c=oe();this.store&&this.store.recordJoinChannelService({urls:a.map((e=>e.url)),service:"gateway"},this.recordIndex),a.forEach((e=>{e.onopen=()=>{this.logger("onopen: ws ".concat(e.url," open cost ").concat(Date.now()-o,"ms")),this.websockets.forEach((t=>{t!==e&&(t.onopen=null,t.onclose=null,t.onmessage=null,t.close(),this.logger("close backup websocket: ".concat(t.url)))})),this.websockets.length=0,c.resolve(e)},e.onclose=i=>{this.logger("onclose: ws ".concat(e.url," closed cost ").concat(Date.now()-o,"ms state: ").concat(e.readyState));const n=a.every((e=>e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING));this.logger("".concat(t?"443":"47xx"," websocket closed, all failed: ").concat(n)),n&&(t||this.isTry443PortFailed||this.useProxy)?(this.logger("onclose: all websocket is closed, ".concat(i.reason)),c.reject({code:i.code,reason:Gi.A_ROUND_WS_FAILED})):!t&&n&&!this.isNormalPortFailed&&this.try443PortTimeout&&(this.logger("all 47xx websocket is closed, try 443 port"),this.clearTimeout(),l()),t?this.isTry443PortFailed=n:this.isNormalPortFailed=n},e.onmessage=t=>this.logger("".concat(e.url," onmessage: ").concat(t.data))})),this.websockets.push(...a);const d=()=>{this.websockets.forEach((e=>e.readyState!==WebSocket.OPEN&&e.close()))},l=()=>{if(c.isResolved)return d();ae()&&se()&&d(),this.createWebSocket(e,!0,!0).then((e=>{c.resolve(e)})).catch((e=>{this.isNormalPortFailed&&c.reject(e),this.logger("try 443 port to create ws failed")})),this.forceCloseTimeout=window.setTimeout((()=>{this.logger("5s timeout close un-opens, isWebsocket created: ",c.isResolved),this.forceCloseTimeout=null,d()}),this.forceCloseWSDuration)};return i||(()=>{if(t||this.useProxy)return this.logger("add 5s timeout at ".concat(t?"try-443":"proxy"," condition")),this.forceCloseTimeout=window.setTimeout((()=>{this.forceCloseTimeout=null,d()}),this.forceCloseWSDuration);this.try443PortTimeout=window.setTimeout((()=>{this.logger("2s timeout, isWebsocket created: ",c.isResolved),this.try443PortTimeout=null,l()}),this.try443PortDuration)})(),c.promise}chooseBestWebsocket(e,t,i,n){return this.useDoubleDomain=!!t,"string"==typeof e&&(e=function(e){let t,i,n;return[,t,i,n]=e.match(fn)||[],t||([,i,n]=e.match(Cn)||[]),i&&n||([,i,n]=e.match(Tn)||[]),i&&n||([,i]=e.match(In)||[]),i||B.warning("un-destructible url: ",e),{proxy:t,host:i,port:n||"443"}}(e)),this.recordIndex=n,this.useProxy=!!e.proxy,i&&this.useProxy&&(B.warn("cannot use 443 only when use proxy"),i=!1),this.createWebSocket(e,!!i,!1).finally((()=>this.clearTimeout()))}}class vn extends ie{get url(){return this.websocket&&this.websocket.url||this._websocketUrl}get reconnectMode(){return this._reconnectMode}set reconnectMode(e){["tryNext","recover"].includes(e)&&this.resetReconnectCount(e),this._reconnectMode=e}get state(){return this._state}set state(e){e!==this._state&&(this._state=e,"reconnecting"===this._state?this.emit(Di.RECONNECTING,this.reconnectReason):"connected"===this._state?this.emit(Di.CONNECTED):"closed"===this._state?this.emit(Di.CLOSED):"failed"===this._state&&this.emit(Di.FAILED))}resetReconnectCount(e){B.debug("websocket reset reconnect count, reason: "+e),this.reconnectCount=0}constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3],o=arguments.length>4&&void 0!==arguments[4]&&arguments[4],a=arguments.length>5?arguments[5]:void 0;super(),this._websocketUrl=null,this.connectionID=0,this.currentURLIndex=0,this.urls=[],this._reconnectMode="tryNext",this.reconnectReason=void 0,this._initMutex=void 0,this.name=void 0,this._state="closed",this.reconnectInterrupter=void 0,this.websocket=void 0,this.retryConfig=void 0,this.reconnectCount=0,this.forceCloseTimeout=5e3,this.onlineReconnectListener=void 0,this.useCompress=void 0,this.tryDoubleDomain=!1,this.use443PortOnly=!1,this.wsInflateLength=0,this.wsDeflateLength=0,this.closeEstablishingWs=()=>{},this.store=void 0,this.joinGatewayRecordIndex=void 0,this.store=a,this.name=e,this.retryConfig=mi({},t),this.useCompress=i,this.tryDoubleDomain=n,this.use443PortOnly=o,this._initMutex=new re("websocket",a?a.clientId:void 0);const{timeout:s,timeoutFactor:r}=t,c=Math.max(300,Math.floor(3*s/5)),d=Math.max(1.2,Math.floor(8*r)/10);ce.ONLINE&&(this.retryConfig.timeout=c,this.retryConfig.timeoutFactor=d),de.on(le.NETWORK_STATE_CHANGE,((e,t)=>{e!==t&&(this.resetReconnectCount("network state change: ".concat(t," -> ").concat(e)),e===ce.ONLINE?(this.retryConfig.timeout=c,this.retryConfig.timeoutFactor=d):(this.retryConfig.timeout=s,this.retryConfig.timeoutFactor=r))}))}getConnection(){return this.websocket||void 0}async init(t){let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const n=await this._initMutex.lock();this._reconnectMode="tryNext",this.forceCloseTimeout=i,this.urls=t,this.state="connecting";try{var o;const t=oe(),i=this.urls[this.currentURLIndex];null===(o=this.store)||void 0===o||o.beforeConnect(),e(this.store)&&this.emit(cn.PRE_CONNECT_PC),this.createWebSocketConnection(i).then(t.resolve).catch(t.reject),this.once(Di.CLOSED,(()=>{t.reject(new ue(Z.WS_DISCONNECT))})),this.once(Di.CONNECTED,t.resolve),await t.promise}catch(e){}finally{n()}}close(e,t){if(this.currentURLIndex=0,this.resetReconnectCount("close"),this.reconnectInterrupter&&this.reconnectInterrupter(),this.websocket){this.websocket.onclose=null,this.websocket.onopen=null,this.websocket.onmessage=null;const e=this.websocket;t?setTimeout((()=>e.close()),500):e.close(),this.websocket=void 0,this._websocketUrl=null}this.state=e?"failed":"closed",this.closeEstablishingWs&&this.closeEstablishingWs()}reconnect(e,t){if(!this.websocket)return void B.warning("[".concat(this.name,"] can not reconnect, no websocket"));void 0!==e&&(this.reconnectMode=e),B.debug("[".concat(this.name,"] reconnect is triggered initiative")),"number"==typeof this.joinGatewayRecordIndex&&this.store&&this.store.recordJoinChannelService({status:"error",errors:[new Error(t)]},this.joinGatewayRecordIndex);const i=this.websocket.onclose;this.websocket.onclose=null,this.websocket.close(),i&&i.bind(this.websocket)({code:9999,reason:t})}sendMessage(e){let t=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw new ue(Z.WS_ABORT,"websocket is not ready");try{t||(e=JSON.stringify(e)),this.websocket.send(e)}catch(e){throw new ue(Z.WS_ERR,"send websocket message error"+e.toString())}}setWsInflateData(e){this.wsDeflateLength=this.wsDeflateLength+e.originLength,this.wsInflateLength=this.wsInflateLength+e.compressedLength}getWsInflateData(){const e=this.wsInflateLength,t=this.wsDeflateLength;return this.clearWsInflateData(),{wsInflateLength:e,wsDeflateLength:t}}clearWsInflateData(){this.wsInflateLength=0,this.wsDeflateLength=0}async createWebSocketConnection(e){var t;const i=oe();this.connectionID+=1,this.joinGatewayRecordIndex=void 0;const n=e=>{var t;null===(t=this.store)||void 0===t||t.signalChannelOpen(),B.debug("[".concat(this.name,"] websocket opened:"),e),this.reconnectMode="retry",this.state="connected",this.resetReconnectCount("opened"),i.resolve()},o=async e=>{var t;if(B.debug("[".concat(this.name,"] websocket close ").concat(null===(t=this.websocket)||void 0===t?void 0:t.url,", code: ").concat(e.code,", reason: ").concat(e.reason,", current mode: ").concat(this.reconnectMode)),this.reconnectCount>=this.retryConfig.maxRetryCount)i.reject(new ue(Z.WS_DISCONNECT,"websocket close: ".concat(e.code))),this.close();else{"connected"===this.state&&(this.reconnectReason=e.reason,this.state="reconnecting");const t=Ee(this,Di.WILL_RECONNECT,this.reconnectMode,e.reason)||this.reconnectMode,n=await this.reconnectWithAction(t);if("closed"===this.state)return void B.debug("[".concat(this.connectionID,"] ws is closed, no need to reconnect"));if(!n)return i.reject(new ue(Z.WS_DISCONNECT,"websocket reconnect failed: ".concat(e.code))),this.close(!0);i.resolve()}},a=e=>{this.emit(Di.ON_MESSAGE,e)},s=e=>{B.warn("[".concat(this.connectionID,"] ws open error ").concat(e))};this.websocket&&(this.websocket.onclose=null,this.websocket.close()),ne("GATEWAY_WSS_ADDRESS")&&this.name.startsWith("gateway")&&(e=ne("GATEWAY_WSS_ADDRESS")),B.debug("[".concat(this.name,"] start connect, url:"),e);const r=null===(t=this.store)||void 0===t?void 0:t.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"gateway"});try{var c;this._websocketUrl=Rn(e);const t=await this.chooseBestWebsocketConnection(e);this.websocket=t,n&&n(this.websocket.url),this.websocket.onclose=o,this.websocket.onmessage=a,this.websocket.onerror=s,null===(c=this.store)||void 0===c||c.recordJoinChannelService({endTs:Date.now(),status:"success"},r),this.joinGatewayRecordIndex=r}catch(e){const t="closed"===this.state,n=e instanceof ue,a=n&&e.code===Z.WS_ABORT,s=n&&e.code===Z.WS_ERR,c=n?e.message:e&&(e.reason||e.toString());B.warning("[choose-best-ws] chooseBestWebsocket error: ".concat(c)),this.store&&this.store.recordJoinChannelService({endTs:Date.now(),status:a?"aborted":"error",errors:[e]},r),t||s?(i.reject(t?new ue(Z.WS_DISCONNECT,"websocket is closed: ".concat(c)):new ue(Z.WS_ERR,"init websocket failed: ".concat(c))),s&&B.error("[".concat(this.name,"] init websocket failed: ").concat(c))):o&&o(e)}return i.promise}async reconnectWithAction(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(this.reconnectCount>=this.retryConfig.maxRetryCount)return!1;if(0===this.urls.length)return!1;if("closed"===this.state)return!1;B.warning("[choose-best-ws] action: =>",e),this.onlineReconnectListener||de.isOnline||!de.onlineWaiter||(this.onlineReconnectListener=de.onlineWaiter.then((()=>{this.onlineReconnectListener=void 0})));let i=!0;if(this.reconnectInterrupter=()=>i=!1,t){const t=he(this.reconnectCount,this.retryConfig);B.debug("[".concat(this.name,"] wait ").concat(t,"ms to reconnect websocket, mode: ").concat(e)),await Promise.race([_e(t),this.onlineReconnectListener||new Promise((()=>{}))])}if("closed"===this._state||!i)return!1;this.reconnectCount+=1;const n=async(e,t)=>{this.emit(Di.RECONNECT_CREATE_CONNECTION,t),await this.createWebSocketConnection(e)};try{if("retry"===e)await n(this.urls[this.currentURLIndex],e);else if("tryNext"===e){if(this.currentURLIndex+=1,this.currentURLIndex>=this.urls.length)return this.reconnectWithAction("recover",!1);B.debug("[".concat(this.name,"] websocket url length: ").concat(this.urls.length," current index: ").concat(this.currentURLIndex)),await n(this.urls[this.currentURLIndex],e)}else"recover"===e&&(B.debug("[".concat(this.name,"] request new urls")),this.resetReconnectCount("recover mode"),this.urls=await pe(this,Di.REQUEST_NEW_URLS),this.currentURLIndex=0,await n(this.urls[this.currentURLIndex],e))}catch(i){var o;B.error("[".concat(this.name,"] reconnect failed ").concat(i&&i.toString()));const n=null==i||null===(o=i.data)||void 0===o?void 0:o.desc;return Array.isArray(n)&&n.includes("dynamic key expired")?(this.emit(Di.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1):this.reconnectWithAction(e,t)}return!0}}class yn extends vn{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]&&arguments[2],arguments.length>3&&void 0!==arguments[3]&&arguments[3],arguments.length>4&&void 0!==arguments[4]&&arguments[4],arguments.length>5?arguments[5]:void 0)}async chooseBestWebsocketConnection(e,t){const i=oe(),n=(o=this.forceCloseTimeout,a=this.store,new gn(o,a));var o,a;this.closeEstablishingWs=()=>{B.debug("[choose-best-ws] close establishing websockets"),n.closeAllWebsockets(),i.reject(new ue(Z.WS_ABORT,"choose best websocket aborted"))};const s=ne("GATEWAY_DOMAINS");return B.debug("[choose-best-ws] currentDomain: ",e,", domains: ",s,"total: ".concat(this.urls.length),"current: ".concat(this.currentURLIndex+1)),n.chooseBestWebsocket(e,this.tryDoubleDomain,this.use443PortOnly,t).then(i.resolve).catch(i.reject),i.promise.finally((()=>{this.closeEstablishingWs=void 0}))}}class Nn extends ie{get connectionState(){return this._connectionState}set connectionState(e){e!==this._connectionState&&(this._connectionState=e,e===vi.CONNECTED?this.emit(yi.WS_CONNECTED):e===vi.RECONNECTING?this.emit(yi.WS_RECONNECTING,this._websocketReconnectReason):e===vi.CLOSED&&this.emit(yi.WS_CLOSED,this._disconnectedReason))}get currentURLIndex(){return this.websocket.currentURLIndex}get url(){return this.websocket&&this.websocket.url||null}get rtt(){return this.rttRolling.mean()}constructor(e,t){super(),this._disconnectedReason=void 0,this._websocketReconnectReason=void 0,this._connectionState=vi.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 Se(5),this.pingpongTimer=void 0,this.wsInflateDataTimer=void 0,this.pingpongTimeoutCount=0,this.ortc=void 0,this.joinResponse=void 0,this.multiIpOption=void 0,this.initError=void 0,this.spec=void 0,this.store=void 0,this.onWebsocketMessage=e=>{if(e.data instanceof ArrayBuffer)return void this.emit(yi.ON_BINARY_DATA,e.data);const t=JSON.parse(e.data);if(this.lastMsgTime=Date.now(),Object.prototype.hasOwnProperty.call(t,"_id")){const e="res-@".concat(t._id);this.emit(e,t._result,t._message)}else if(Object.prototype.hasOwnProperty.call(t,"_type")){if(this.emit(t._type,t._message),t._type===wi.ON_NOTIFICATION&&this.handleNotification(t._message),t._type===wi.ON_USER_BANNED)switch(t._message.error_code){case 14:this.close(me.UID_BANNED);break;case 15:this.close(me.IP_BANNED);break;case 16:this.close(me.CHANNEL_BANNED)}if(t._type===wi.ON_USER_LICENSE_BANNED)switch(t._message.error_code){case gi.ERR_LICENSE_MISSING:this.close(me.LICENSE_MISSING);break;case gi.ERR_LICENSE_EXPIRED:this.close(me.LICENSE_EXPIRED);break;case gi.ERR_LICENSE_MINUTES_EXCEEDED:this.close(me.LICENSE_MINUTES_EXCEEDED);break;case gi.ERR_LICENSE_PERIOD_INVALID:this.close(me.LICENSE_PERIOD_INVALID);break;case gi.ERR_LICENSE_MULTIPLE_SDK_SERVICE:this.close(me.LICENSE_MULTIPLE_SDK_SERVICE);break;case gi.ERR_LICENSE_ILLEGAL:this.close(me.LICENSE_ILLEGAL);break;default:this.close()}}},this.clientId=e.clientId,this.spec=e,this.store=t,this.websocket=new yn("gateway-".concat(this.clientId),this.spec.retryConfig,!0,ne("JOIN_GATEWAY_USE_DUAL_DOMAIN"),ne("JOIN_GATEWAY_USE_443PORT_ONLY"),t),this.handleWebsocketEvents(),window.addEventListener("offline",(()=>{this.connectionState===vi.CONNECTED&&this.reconnect("retry",Re.OFFLINE)}))}async request(e,t,i,n){const o=fe(6,""),a={_id:o,_type:e,_message:t},s=this.websocket.connectionID,r=()=>new Promise(((t,i)=>{if(this.connectionState===vi.CONNECTED)return t();const n=()=>{this.off(yi.WS_CLOSED,o),t()},o=()=>{this.off(yi.WS_CONNECTED,n),i(new F(Z.WS_ABORT))};this.once(yi.WS_CONNECTED,n),this.once(yi.WS_CLOSED,o),e!==Ni.PUBLISH&&e!==Ni.PUBLISH_DATASTREAM&&e!==Ni.SUBSCRIBE&&e!==Ni.SUBSCRIBE_DATASTREAM&&e!==Ni.UNSUBSCRIBE&&e!==Ni.UNSUBSCRIBE_DATASTREAM&&e!==Ni.UNPUBLISH&&e!==Ni.UNPUBLISH_DATASTREAM&&e!==Ni.CONTROL&&e!==Ni.RESTART_ICE||this.once(yi.DISCONNECT_P2P,(()=>{i(new F(Z.DISCONNECT_P2P))})),e!==Ni.PUBLISH&&e!==Ni.RESTART_ICE||this.once(yi.ABORT_P2P_EXECUTION,(()=>{i(new F(Z.DISCONNECT_P2P))}))}));if(this.connectionState!==vi.CONNECTING&&this.connectionState!==vi.RECONNECTING||e===Ni.JOIN||e===Ni.REJOIN||await r(),this.websocket.sendMessage(a,!0),n)return;const c=new Promise(((i,n)=>{let a=!1;const r=(n,o)=>{a=!0,i({isSuccess:"success"===n,message:o||{}}),this.off(yi.WS_CLOSED,c),this.off(yi.WS_RECONNECTING,c),this.emit(yi.REQUEST_SUCCESS,e,t)};this.once("res-@".concat(o),r);const c=()=>{n(new F(Z.WS_ABORT,"type: ".concat(e))),this.off(yi.WS_CLOSED,c),this.off(yi.WS_RECONNECTING,c),this.off("res-@".concat(o),r)};this.once(yi.WS_CLOSED,c),this.once(yi.WS_RECONNECTING,c),_e(ne("SIGNAL_REQUEST_TIMEOUT")).then((()=>{this.websocket.connectionID!==s||a||(B.warning("[".concat(this.clientId,"] ws request timeout, type: ").concat(e)),this.emit(yi.REQUEST_TIMEOUT,e,t))}))}));let d=null;try{d=await c}catch(n){if(this.connectionState===vi.CLOSED||e===Ni.LEAVE)throw new F(Z.WS_ABORT);return!this.spec.forceWaitGatewayResponse||i?n.throw():e===Ni.JOIN||e===Ni.REJOIN?null:(await r(),await this.request(e,t))}if(d.isSuccess)return d.message;const l=Number(d.message.error_code||d.message.code),u=mn(l),h=new F(Z.UNEXPECTED_RESPONSE,"".concat(u.desc,": ").concat(d.message.error_str),{code:l,data:d.message,desc:u.desc});return"success"===u.action?d.message:(B.warning("[".concat(this.clientId,"] [").concat(this.websocket.connectionID,"] unexpected response from type ").concat(e,", error_code: ").concat(l,", message: ").concat(u.desc,", action: ").concat(u.action)),l===gi.ERR_TOO_MANY_BROADCASTERS?e===Ni.JOIN||e===Ni.REJOIN?(this.initError=h,this.close(),h.throw()):h.throw():"failed"===u.action?h.throw():"quit"===u.action?(this.initError=h,this.close(),h.throw()):(l===gi.ERR_JOIN_BY_MULTI_IP?(this.multiIpOption=d.message.option,B.warning("[".concat(this.clientId,"] detect multi ip, recover")),this.reconnect("recover",Re.MULTI_IP)):this.reconnect(u.action,Re.SERVER_ERROR),e===Ni.JOIN||e===Ni.REJOIN?null:await this.request(e,t)))}waitMessage(e,t){return new Promise((i=>{const n=o=>{(!t||t(o))&&(this.off(e,n),i(o))};this.on(e,n)}))}uploadWRTCStats(e){if(!this.store.sessionId)return void B.warn("[".concat(this.clientId,"] no session id when upload wrtc stats"));const t={lts:Date.now(),sid:this.store.sessionId,uid:this.store.intUid,stats:e};this.upload(bi.WRTC_STATS,t)}upload(e,t){const i={_type:e,_message:t};try{this.websocket.sendMessage(i)}catch(e){const t=ne("MAX_UPLOAD_CACHE")||50;this.uploadCache.push(i),this.uploadCache.length>t&&this.uploadCache.splice(0,1),this.uploadCache.length>0&&!this.uploadCacheInterval&&(this.uploadCacheInterval=window.setInterval((()=>{if(this.connectionState!==vi.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)}),ne("UPLOAD_CACHE_INTERVAL")||2e3))}}send(e,t){const i={_type:e,_message:t};this.websocket.sendMessage(i)}init(e){return this.initError=void 0,this.multiIpOption=void 0,this.joinResponse=void 0,this.reconnectToken=void 0,this.openConnectionTime=void 0,new Promise(((t,i)=>{this.once(yi.WS_CONNECTED,(()=>t(this.joinResponse))),this.once(yi.WS_CLOSED,(e=>i(this.initError||new F(Z.WS_ABORT,e)))),this.connectionState=vi.CONNECTING,this.websocket.init(e).catch(i),this.wsInflateDataTimer&&window.clearInterval(this.wsInflateDataTimer),this.wsInflateDataTimer=window.setInterval((()=>{this.handleWsInflateData()}),2e4)}))}close(e){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.wsInflateDataTimer&&(this.handleWsInflateData(),window.clearInterval(this.wsInflateDataTimer),this.wsInflateDataTimer=void 0),this.reconnectToken=void 0,this.joinResponse=void 0,this._disconnectedReason=e||me.LEAVE,this.connectionState=vi.CLOSED,B.debug("[".concat(this.clientId,"] ")+"will close websocket in signal"),this.websocket.close()}async join(){if(!this.joinResponse){this.emit(yi.ABORT_P2P_EXECUTION),this.store.signalConnected();const e=await pe(this,yi.REQUEST_JOIN_INFO);this.store.joinReq();const t=await this.request(Ni.JOIN,e);if(this.ortc=null==e?void 0:e.ortc,this.store.joinRep(),!t)return this.emit(yi.REPORT_JOIN_GATEWAY,Gi.TIMEOUT,this.url||""),!1;this.joinResponse=t,this.emit(yi.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token}return this.connectionState=vi.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),!0}async rejoin(){if(!this.reconnectToken)throw new F(Z.UNEXPECTED_ERROR,"can not rejoin, no rejoin token");const e=Ce(this,yi.REQUEST_REJOIN_INFO);e.token=this.reconnectToken;const t=await this.request(Ni.REJOIN,e);return!!t&&(this.connectionState=vi.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),t.peers&&t.peers.forEach((e=>{this.emit(wi.ON_USER_ONLINE,{uid:e.uid}),e.audio&&this.emit(wi.ON_ADD_AUDIO_STREAM,{uid:e.uid,uint_id:e.uint_id,audio:!0,ssrcId:e.audio_ssrc}),e.video&&this.emit(wi.ON_ADD_VIDEO_STREAM,{uid:e.uid,uint_id:e.uint_id,video:!0,ssrcId:e.video_ssrc}),e.audio_mute?this.emit(wi.MUTE_AUDIO,{uid:e.uid}):this.emit(wi.UNMUTE_AUDIO,{uid:e.uid}),e.video_mute?this.emit(wi.MUTE_VIDEO,{uid:e.uid}):this.emit(wi.UNMUTE_VIDEO,{uid:e.uid}),e.audio_enable_local?this.emit(wi.ENABLE_LOCAL_AUDIO,{uid:e.uid}):this.emit(wi.DISABLE_LOCAL_AUDIO,{uid:e.uid}),e.video_enable_local?this.emit(wi.ENABLE_LOCAL_VIDEO,{uid:e.uid}):this.emit(wi.DISABLE_LOCAL_VIDEO,{uid:e.uid}),e.audio||e.video||this.emit(wi.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(Ni.DOWNGRADE_CODEC,t)}handleNotification(e){B.debug("[".concat(this.clientId,"] receive notification: "),e);const t=mn(e.code);if(28===e.code&&"detail"in e&&(B.info("[".concat(this.clientId,"] receive recover notification: "),e.detail),this.emit(yi.RECOVER_NOTIFICATION,e.detail)),"success"!==t.action){if("failed"!==t.action)return"quit"===t.action?("ERR_REPEAT_JOIN_CHANNEL"===t.desc&&this.close(me.UID_BANNED),void this.close()):void this.reconnect(t.action,Re.SERVER_ERROR);B.error("[".concat(this.clientId,"] ignore error: "),t.desc)}}handlePingPong(){if(!this.websocket||"connected"!==this.websocket.state)return;this.pingpongTimeoutCount>0&&this.rttRolling.add(3e3),this.pingpongTimeoutCount+=1;const e=ne("PING_PONG_TIME_OUT"),t=Date.now();this.pingpongTimeoutCount>=e&&(B.warning("[".concat(this.clientId,"] PING-PONG Timeout. Last Socket Message: ").concat(t-this.lastMsgTime,"ms")),t-this.lastMsgTime>ne("WEBSOCKET_TIMEOUT_MIN"))?this.reconnect("retry",Re.TIMEOUT):this.request(Ni.PING,void 0,!0).then((()=>{this.pingpongTimeoutCount=0;const e=Date.now()-t;this.rttRolling.add(e),ne("REPORT_STATS")&&this.send(Ni.PING_BACK,{pingpongElapse:e})})).catch((e=>{}))}handleWsInflateData(){const{wsInflateLength:e,wsDeflateLength:t}=this.websocket.getWsInflateData();0!==e&&0!==t&&this.upload(bi.WS_INFLATE_DATA_LENGTH,{ws_deflate_length:t,ws_inflate_length:e})}handleWebsocketEvents(){this.websocket.on(Di.RECONNECT_CREATE_CONNECTION,(e=>{this.emit(yi.WS_RECONNECT_CREATE_CONNECTION,e)})),this.websocket.on(Di.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(Di.CLOSED,(()=>{this.connectionState=vi.CLOSED})),this.websocket.on(Di.FAILED,(()=>{this._disconnectedReason=me.NETWORK_ERROR,this.connectionState=vi.CLOSED})),this.websocket.on(Di.RECONNECTING,(e=>{this._websocketReconnectReason=e,this.joinResponse=void 0,this.connectionState===vi.CONNECTED?this.connectionState=vi.RECONNECTING:this.connectionState=vi.CONNECTING})),this.websocket.on(Di.WILL_RECONNECT,((e,t,i)=>{const n=Ce(this,yi.IS_P2P_DISCONNECTED),o=n||"retry"!==e;n&&"retry"===e&&(B.debug("".concat(this.clientId," reconnect mode is retry, but p2p lost, change to tryNext")),e="tryNext",t=Gi.P2P_DISCONNECTED),o&&(B.debug("".concat(this.clientId," will renewSession, reconnect mode: ").concat(e)),this.emit(yi.REPORT_JOIN_GATEWAY,t||Gi.UNKNOWN_REASON,this.url||""),this.reconnectToken=void 0,this.emit(yi.DISCONNECT_P2P)),i(e)})),this.websocket.on(Di.CONNECTED,(()=>{this.openConnectionTime=Date.now(),this.reconnectToken?this.rejoin().catch((e=>{B.warning("[".concat(this.clientId,"] rejoin failed ").concat(e)),this.reconnect("tryNext",Re.SERVER_ERROR)})):this.join().catch((e=>{if(this.emit(yi.REPORT_JOIN_GATEWAY,e,this.url||""),e instanceof F){if(e.code===Z.UNEXPECTED_RESPONSE&&e.data.code===gi.ERR_NO_AUTHORIZED)return this.initError=new F(Z.TOKEN_EXPIRE,"dynamic key expired"),void this.close(me.TOKEN_EXPIRE);B.error("[".concat(this.clientId,"] join gateway request failed"),e.toString()),this.spec.forceWaitGatewayResponse?this.reconnect("tryNext",Re.SERVER_ERROR):(this.initError=e,this.close())}}))})),this.websocket.on(Di.REQUEST_NEW_URLS,((e,t)=>{pe(this,yi.REQUEST_RECOVER,this.multiIpOption).then(e).catch(t)})),this.websocket.on(Di.ON_TOKEN_PRIVILEGE_DID_EXPIRE,(()=>{this.emit(wi.ON_TOKEN_PRIVILEGE_DID_EXPIRE)})),this.websocket.on(cn.PRE_CONNECT_PC,(()=>{this.emit(yi.PRE_CONNECT_PC)}))}}let bn=function(e){return e.NATIVE_RTC="native_rtc",e.NATIVE_RTM="native_rtm",e.WEB_RTC="web_rtc",e.WEB_RTM="web_rtm",e}({}),wn=function(e){return e[e.CHOOSE_SERVER=11]="CHOOSE_SERVER",e[e.CLOUD_PROXY=18]="CLOUD_PROXY",e[e.CLOUD_PROXY_5=20]="CLOUD_PROXY_5",e[e.CLOUD_PROXY_FALLBACK=26]="CLOUD_PROXY_FALLBACK",e}({});function On(e){return e.match(/^[\.\:\d]+$/)?"".concat(e.replace(/[^\d]/g,"-"),".").concat(ne("TURN_DOMAIN")):(B.debug("Cannot recognized as ip address: ".concat(e,", use as host2")),e)}function Dn(e){try{const t=ne("GATEWAY_DOMAINS").concat(ne("TURN_DOMAIN")).find((t=>e.includes(t)));if(t){return e.split(".".concat(t))[0].replace(/-/g,".")}return e}catch(t){return B.debug("serverUrlToIp error, fallback to url",e),e}}function Pn(e,t){e.addresses||(e.addresses=[]);const i=function(e,t){if(ne("CONNECT_GATEWAY_WITHOUT_DOMAIN"))return e.map((e=>{let{ip:t,port:i}=e;return{address:"".concat(t,":").concat(i)}}));const i=ne("GATEWAY_DOMAINS");let n=i[1]&&t.includes(i[1])?1:0;return e.map((e=>{let{domain_prefix:t,port:o,ip:a}=e;if(t)return{address:"".concat(t,".").concat(i[n++%i.length],":").concat(o)};const s=/^[\.\:\d]+$/.test(a),r=s?"".concat(a.replace(/[^\d]/g,"-"),".").concat(i[n++%i.length],":").concat(o):"".concat(a,":").concat(o);return s||B.debug("Cannot recognized as ip address: ".concat(a,", use as host3")),{ip:a,port:o,address:r}}))}(e.addresses,t),n=Array.isArray(e.detail)&&e.detail[18];if(n&&"string"==typeof n){const e=n.split(";");for(let t=0;t<e.length;t++){const n=e[t].trim();i[t]&&n&&(i[t].ip6=n)}}const o=e.detail&&e.detail.candidate;let a;if(o){const[e,t]=o.split(":");e&&t&&(a={port:Number(t),ip:e,address:"".concat(e,":").concat(t)})}return{gatewayAddrs:i,apGatewayAddress:a,uid:e.uid,cid:e.cid,cert:e.cert,vid:e.detail&&e.detail[8],uni_lbs_ip:e.detail&&e.detail[1],res:e,csIp:e.detail&&e.detail[502]}}function Ln(e){return"number"==typeof e?e:e.exact||e.ideal||e.max||e.min||0}function kn(e){const t=e._encoderConfig;if(!t)return{};const i={resolution:t.width&&t.height?"".concat(Ln(t.width),"x").concat(Ln(t.height)):void 0,maxVideoBW:t.bitrateMax,minVideoBW:t.bitrateMin};return"number"==typeof t.frameRate?(i.maxFrameRate=t.frameRate,i.minFrameRate=t.frameRate):t.frameRate&&(i.maxFrameRate=t.frameRate.max||t.frameRate.ideal||t.frameRate.exact||t.frameRate.min,i.minFrameRate=t.frameRate.min||t.frameRate.ideal||t.frameRate.exact||t.frameRate.max),i}function Un(e){return e>=0&&e<.17?1:e>=.17&&e<.36?2:e>=.36&&e<.59?3:e>=.59&&e<=1?4:e>1?5:0}function Mn(e,t){let i,n,o;switch(t){case wn.CHOOSE_SERVER:n=4096,o="choose server";break;case wn.CLOUD_PROXY:n=1048576,o="proxy";break;case wn.CLOUD_PROXY_5:n=4194304,o="proxy5";break;case wn.CLOUD_PROXY_FALLBACK:n=4194310,o="proxy fallback";break;default:throw new F(Z.UNEXPECTED_ERROR,"multi unlibs response transformer get unknown service id",{csIp:e.detail&&e.detail[502],retry:!1})}if(e.response_body.forEach((t=>{t.buffer&&t.buffer.flag===n&&(i={code:t.buffer.code,addresses:(t.buffer.edges_services||[]).map((e=>mi(mi({},e),{},{ticket:t.buffer.cert}))),server_ts:e.enter_ts,uid:t.buffer.uid,cid:t.buffer.cid,cname:t.buffer.cname,detail:mi(mi({},t.buffer.detail),e.detail),flag:t.buffer.flag,opid:e.opid,cert:t.buffer.cert})})),!i)throw new F(Z.MULTI_UNILBS_RESPONSE_ERROR,"cannot parse response ".concat(o," from multi unilbs response"),{csIp:e.detail&&e.detail[502]});return i}async function Vn(e,t){return await Promise.all(e.addresses.map((async e=>({address:On(e.ip),tcpport:e.port,udpport:e.port,username:t&&ne("ENCRYPT_PROXY_USERNAME_AND_PSW")&&window.isSecureContext?t.toString():Te.username,password:t&&ne("ENCRYPT_PROXY_USERNAME_AND_PSW")&&window.isSecureContext?await Ie(t.toString()):Te.password}))))}function xn(e,t){const i=t.getMediaStreamTrack(!0).getSettings(),n=t.videoHeight||i.height,o=t.videoWidth||i.width;return n&&o?Math.max(Math.min(n,o)/Math.min(Ln(e.height),Ln(e.width)),1):(B.warning("can't get ori-track's height, default scale down 4 times for low stream"),4)}function Bn(e){let{candidateType:t,relayProtocol:i,type:n,address:o,port:a,protocol:s}=e;const r={candidateType:t,relayProtocol:i,protocol:s};if("local-candidate"!==n){const e=o.split(".");e.length>=4&&(e[1]="*",e[2]="*"),r.address=e.join("."),r.port=a}return r}function Fn(e){const t=e.split(":"),i=e.split(/[-.]/),n=e.includes("-")?"-":".";let o=e;return t.length>1?i.length>1?(i[1]="**",o=i[0]+n+"**:"+t[t.length-1]):o=t.length>2?t[0]+n+"**:"+t[t.length-1]:"**:"+t[t.length-1]:i.length>1&&(o=i[0]+n+"**"),o}function jn(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ne("SVC_MODE");if(ne("ENABLE_SVC"))return function(e){return e in Ae}(e)?e:Ae.L1T3}const Gn={[Zi.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"}],[Zi.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 Wn(e,t,i){t.forEach((t=>{const n=Gn[e].find((e=>{let{key:i}=e;return t.extensionName.includes(i)}));if(!n)return;const o=i.find((e=>{let{extensionName:t}=e;return t.includes(n.key)}));o&&o.extensionName.includes("gdpr_forbidden")&&(t.extensionName=o.extensionName)}))}function Hn(e,t){t.forEach((t=>{const i=Gn[e].find((e=>{let{key:i}=e;return t.extensionName.includes(i)}));t.extensionName.includes("gdpr_forbidden")&&i&&(t.extensionName=i.extensionName)}))}function Kn(e){return"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"===e||e.includes("abs-send-time")}function Yn(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 qn(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=arguments.length>3?arguments[3]:void 0;const{filterRTX:o,filterVideoFec:a,filterAudioFec:s,filterAudioCodec:r,filterVideoCodec:c,unsupportedVideoUplinkCodec:d,unsupportedVideoDownlinkCodec:l}=t,{useXR:u}=i;let h=[],_=[],p=[],E=[],S=!1,m=!1;if(ge(e).mediaDescriptions.forEach((e=>{n&&n!==e.attributes.direction||("video"!==e.media.mediaType||S||(_=e.attributes.payloads,E=e.attributes.extmaps,S=!0),"audio"!==e.media.mediaType||m||(h=e.attributes.payloads,p=e.attributes.extmaps,m=!0))})),!E||0===_.length)throw new Error("Cannot get video capabilities from SDP.");if(!p||0===h.length)throw new Error("Cannot get audio capabilities from SDP.");if(_.forEach((e=>{var t;null!==(t=e.rtpMap)&&void 0!==t&&t.clockRate&&(e.rtpMap.clockRate=parseInt(e.rtpMap.clockRate)),u&&e.rtcpFeedbacks.push({type:"rrtr"})})),h.forEach((e=>{var t;null!==(t=e.rtpMap)&&void 0!==t&&t.clockRate&&(e.rtpMap.clockRate=parseInt(e.rtpMap.clockRate)),u&&e.rtcpFeedbacks.push({type:"rrtr"})})),o&&(h=h.filter((e=>{var t;return"rtx"!==(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())})),_=_.filter((e=>{var t;return"rtx"!==(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())}))),a){const e=_.filter((e=>{var t;return/(red)|(ulpfec)|(flexfec)/i.test((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName)||"")})),t=ao(e,_).map((e=>e.payloadType)),i=[...e.map((e=>e.payloadType)),...t];_=_.filter((e=>!i.includes(e.payloadType)))}if(s&&(h=h.filter((e=>{var t;return!/(red)|(ulpfec)|(flexfec)/i.test((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName)||"")}))),r&&(null==r?void 0:r.length)>0&&(h=h.filter((e=>{var t;return r.includes((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())||"")}))),c&&(null==c?void 0:c.length)>0){const e=_.filter((e=>{var t;return c.includes((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())||"")}));_=e.concat(o?[]:ao(e,_))}const R=ne("UNSUPPORTED_VIDEO_CODEC");if(R&&R.length>0){const e=_.filter((e=>e.rtpMap&&R.includes(e.rtpMap.encodingName.toLowerCase()))),t=ao(e,_),i=e.concat(t).map((e=>e.payloadType));_=_.filter((e=>!i.includes(e.payloadType))),B.debug("unsupportedVideoCodec: ".concat(R,", toBeRemoved: ").concat(i))}if(d&&d.length>0&&"sendonly"===n){const e=_.filter((e=>e.rtpMap&&d.includes(e.rtpMap.encodingName.toLowerCase()))),t=ao(e,_),i=e.concat(t).map((e=>e.payloadType));_=_.filter((e=>!i.includes(e.payloadType))),B.debug("unsupportedVideoUplinkCodec: ".concat(d,", toBeRemoved: ").concat(i))}if(l&&l.length>0&&"recvonly"===n){const e=_.filter((e=>e.rtpMap&&l.includes(e.rtpMap.encodingName.toLowerCase()))),t=ao(e,_),i=e.concat(t).map((e=>e.payloadType));_=_.filter((e=>!i.includes(e.payloadType))),B.debug("unsupportedVideoDownlinkCodec: ".concat(l,", toBeRemoved: ").concat(i))}return{audioCodecs:h,videoCodecs:_,audioExtensions:p,videoExtensions:E}}function Xn(e){const t=ge(e);let i,n;for(const e of t.mediaDescriptions){if(!i){const t=e.attributes.iceUfrag,n=e.attributes.icePwd;if(!t||!n)throw new Error("Cannot get iceUfrag or icePwd from SDP.");i={iceUfrag:t,icePwd:n}}if(!n){const t=e.attributes.fingerprints;t.length>0&&(n={fingerprints:t})}}if(!n&&t.attributes.fingerprints.length>0&&(n={fingerprints:t.attributes.fingerprints}),!n||!i)throw new Error("Cannot get iceParameters or dtlsParameters from SDP.");return{iceParameters:i,dtlsParameters:n}}function Jn(e,t,i){const{cname:n}=e;let o=[];t&&(o=zn(t)),0===o.length&&(o=e.iceParameters.candidates.map((e=>({foundation:e.foundation,componentId:"1",transport:e.protocol,priority:e.priority.toString(),connectionAddress:e.ip,port:e.port.toString(),type:e.type,extension:{}}))),B.debug("Using candidates from gateway."));const a={fingerprints:e.dtlsParameters.fingerprints.map((e=>({hashFunction:e.algorithm,fingerprint:e.fingerprint})))},s={iceUfrag:e.iceParameters.iceUfrag,icePwd:e.iceParameters.icePwd};let r;switch(e.dtlsParameters.role){case"server":r="passive";break;case"client":r="active";break;case"auto":r="actpass"}const c=io(e.rtpCapabilities),d=[];return Array.isArray(i)&&i.length>0&&i.forEach((e=>{d.push({kind:Zi.VIDEO,ssrcMsg:[{ssrcId:e.v,rtx:e.v_rtx}],mslabel:"".concat(e.v,"_").concat(e.a)},{kind:Zi.AUDIO,ssrcMsg:[{ssrcId:e.a}],mslabel:"".concat(e.v,"_").concat(e.a)})})),{dtlsParameters:a,iceParameters:s,candidates:o,rtpCapabilities:c,setup:r,cname:n,preSSRCs:d}}function zn(e){let t=[];return e.ip&&"number"==typeof e.port&&(t=[{foundation:"udpcandidate",componentId:"1",transport:"udp",priority:"2103266323",connectionAddress:e.ip,port:e.port.toString(),type:"host",extension:{}}],B.debug("Using remote candidate from AP ".concat(Fn(e.ip),":").concat(e.port)),e.ip6&&(t.push({foundation:"udpcandidate",componentId:"1",transport:"udp",priority:"2103266323",connectionAddress:e.ip6,port:e.port.toString(),type:"host",extension:{}}),B.debug("Using IPV6 remote candidate from AP ".concat(Fn(e.ip6),":").concat(e.port)))),t}function Qn(e,t,i){const n=[],o=[];return e.forEach((e=>{let{ssrcId:a,rtx:s}=e;const r=fe(8,"track-"),c={ssrcId:a,attributes:mi({label:r,mslabel:i=i||fe(10,""),msid:"".concat(i," ").concat(r)},t&&{cname:t})};if(n.push(c),void 0!==s){const e={ssrcId:s,attributes:mi({label:r,mslabel:i,msid:"".concat(i," ").concat(r)},t&&{cname:t})};n.push(e),o.push({semantic:"FID",ssrcIds:[a,s]})}})),e.length>1&&o.push({semantic:"SIM",ssrcIds:e.map((e=>{let{ssrcId:t}=e;return t}))}),{ssrcs:n,ssrcGroups:o}}function Zn(e,n){n instanceof t&&e.attributes.payloads.forEach((e=>{var t;const o=null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase();if(!o||-1===["opus","pcmu","pcma","g722"].indexOf(o))return;e.fmtp||(e.fmtp={parameters:{}}),"opus"===o&&"number"==typeof ne("OPUS_PTIME")?e.fmtp.parameters.ptime=ne("OPUS_PTIME"):e.fmtp.parameters.minptime="10",e.fmtp.parameters.useinbandfec="1";const a=n._encoderConfig;a&&("pcmu"!==o&&"pcma"!==o&&"g722"!==o&&(a.bitrate&&!se()&&(e.fmtp.parameters.maxaveragebitrate="".concat(Math.floor(1e3*a.bitrate))),a.sampleRate&&(e.fmtp.parameters.maxplaybackrate="".concat(a.sampleRate),e.fmtp.parameters["sprop-maxcapturerate"]="".concat(a.sampleRate)),a.stereo&&(e.fmtp.parameters.stereo="1",e.fmtp.parameters["sprop-stereo"]="1")),n instanceof i&&"opus"===o&&n._config.DTX&&(e.fmtp.parameters.usedtx="1"))}))}function $n(e,t,i){if(!t)return;let n,o;if("video"===e.media.mediaType?(n=i.videoExtensions,o=i.videoCodecs):(n=i.audioExtensions,o=i.audioCodecs),!0===t.twcc){const t=n.find((e=>Yn(e.extensionName)));if(t){const i=t.extensionName;e.attributes.extmaps.find((e=>Yn(e.extensionName)))||e.attributes.extmaps.push({entry:t.entry,extensionName:i});const n=function(e,t){return t.filter((t=>!!e.find((e=>e.payloadType===t.payloadType&&!!e.rtcpFeedbacks.find((e=>"transport-cc"===e.type))))))}(o,e.attributes.payloads);n.forEach((e=>{e.rtcpFeedbacks.find((e=>"transport-cc"===e.type))||e.rtcpFeedbacks.push({type:"transport-cc"})}))}}else if(!1===t.twcc){const t=e.attributes.extmaps.findIndex((e=>Yn(e.extensionName)));-1!==t&&e.attributes.extmaps.splice(t,1),e.attributes.payloads.forEach((e=>{const t=e.rtcpFeedbacks.findIndex((e=>"transport-cc"===e.type));-1!==t&&e.rtcpFeedbacks.splice(t,1)}))}if(!0===t.remb){const t=n.find((e=>Kn(e.extensionName)));if(t){const i=t.extensionName;e.attributes.extmaps.find((e=>e.extensionName===i))||e.attributes.extmaps.push({entry:t.entry,extensionName:i});const n=function(e,t){return t.filter((t=>!!e.find((e=>e.payloadType===t.payloadType&&!!e.rtcpFeedbacks.find((e=>"goog-remb"===e.type))))))}(o,e.attributes.payloads);n.forEach((e=>{e.rtcpFeedbacks.find((e=>"goog-remb"===e.type))||e.rtcpFeedbacks.push({type:"goog-remb"})}))}}else if(!1===t.remb){const t=e.attributes.extmaps.findIndex((e=>Kn(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)}))}}async function eo(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=new RTCPeerConnection;i.addTransceiver("video",{direction:"sendonly"}),i.addTransceiver("audio",{direction:"sendonly"}),i.addTransceiver("video",{direction:"recvonly"}),i.addTransceiver("audio",{direction:"recvonly"});const n=(await i.createOffer()).sdp,{send:o,recv:a,sendrecv:s}=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=arguments.length>2?arguments[2]:void 0;const n=qn(i,e,t,"sendonly"),o=qn(i,e,t,"recvonly"),a={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},s={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},r={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]};if(to(n,o,"videoExtensions",a,s,r),to(n,o,"videoCodecs",a,s,r),to(n,o,"audioExtensions",a,s,r),to(n,o,"audioCodecs",a,s,r),ne("RAISE_H264_BASELINE_PRIORITY")){const e=[],t=[];if(r.videoCodecs.forEach(((i,n)=>{var o;if("h264"===(null===(o=i.rtpMap)||void 0===o?void 0:o.encodingName.toLocaleLowerCase())){var a,s;const o=r.videoCodecs[n+1],c=o&&uo(i,o),d=null===(a=i.fmtp)||void 0===a?void 0:a.parameters["profile-level-id"],l=null===(s=i.fmtp)||void 0===s?void 0:s.parameters["packetization-mode"];!d||d!==ne("FIRST_H264_PROFILE_LEVEL_ID")||ne("FIRST_PACKETIZATION_MODE")&&l!==ne("FIRST_PACKETIZATION_MODE")?c?t.push([i,o]):t.push([i]):c?e.push([i,o]):e.push([i])}})),e.length>0&&t.length>0){B.debug("raising H264 baseline profile priority"),r.videoCodecs.forEach(((i,n)=>{var o;if("h264"===(null===(o=i.rtpMap)||void 0===o?void 0:o.encodingName.toLocaleLowerCase())){const o=uo(i,r.videoCodecs[n+1]),a=e.shift()||t.shift()||[];a.length>0&&(o?r.videoCodecs.splice(n,2,...a):r.videoCodecs.splice(n,1,...a))}}));const i=s.videoCodecs.filter((e=>{var t,i;return"h264"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLocaleLowerCase())&&(null===(i=e.fmtp)||void 0===i?void 0:i.parameters["profile-level-id"])!==ne("FIRST_H264_PROFILE_LEVEL_ID")}));if(i.length>0){const e=ao(i,s.videoCodecs).map((e=>e.payloadType)),t=[...i.map((e=>e.payloadType)),...e];s.videoCodecs=s.videoCodecs.filter((e=>!t.includes(e.payloadType)))}ne("FILTER_SEND_H264_BASELINE")&&(a.videoCodecs=a.videoCodecs.filter((e=>{var t,i;return!("h264"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLocaleLowerCase())&&(null===(i=e.fmtp)||void 0===i?void 0:i.parameters["profile-level-id"])!==ne("FIRST_H264_PROFILE_LEVEL_ID"))})))}return{send:a,recv:s,sendrecv:r}}return{send:a,recv:s,sendrecv:r}}(e,t,n);try{i.close()}catch(e){}return{send:o,recv:a,sendrecv:s}}function to(e,t,i,n,o,a){if("videoExtensions"===i||"audioExtensions"===i){const s=[];return e[i].forEach((e=>{t[i].some(((t,i)=>{if(e.entry===t.entry&&e.extensionName===t.extensionName)return s.push(i),!0}))?a[i].push(e):n[i].push(e)})),void t[i].forEach(((e,t)=>{-1===s.indexOf(t)&&o[i].push(e)}))}if("videoCodecs"===i||"audioCodecs"===i){const s=[];return e[i].forEach((e=>{t[i].some(((t,i)=>{if(e.payloadType===t.payloadType&&JSON.stringify(e)===JSON.stringify(t))return s.push(i),!0}))?a[i].push(e):n[i].push(e)})),void t[i].forEach(((e,t)=>{-1===s.indexOf(t)&&o[i].push(e)}))}}function io(e){const{send:t,recv:i,sendrecv:n}=e;if(!n){if(!t||!i)throw new Error("cannot merge rtp capabilities because one of send or recv is empty!");return{send:t,recv:i}}let o,a;return t?(o={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},o.audioCodecs=[...t.audioCodecs,...n.audioCodecs],o.videoCodecs=[...t.videoCodecs,...n.videoCodecs],o.audioExtensions=[...t.audioExtensions,...n.audioExtensions],o.videoExtensions=[...t.videoExtensions,...n.videoExtensions]):o=n,i?(a={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},a.audioCodecs=[...i.audioCodecs,...n.audioCodecs],a.videoCodecs=[...i.videoCodecs,...n.videoCodecs],a.audioExtensions=[...i.audioExtensions,...n.audioExtensions],a.videoExtensions=[...i.videoExtensions,...n.videoExtensions]):a=n,{send:o,recv:a}}function no(e){if("audio"!==e.media.mediaType)return;e.attributes.payloads.filter((e=>{var t;return"opus"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())})).forEach((e=>{e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters.stereo="1",e.fmtp.parameters["sprop-stereo"]="1"}))}function oo(e,t,i,n){let o=[];if(e===Zi.VIDEO){if(ne("H264_PROFILE_LEVEL_ID")&&"h264"===n&&(o=t.videoCodecs.filter((e=>(e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").includes(n)&&e&&e.fmtp&&e.fmtp.parameters["profile-level-id"]===ne("H264_PROFILE_LEVEL_ID")))),!Array.isArray(o)||0===o.length){let e=[];const a=[],s=[],r=[];if(i.videoCodecs.forEach((t=>{const i=t.rtpMap&&t.rtpMap.encodingName.toLowerCase()||"";i.includes(n)?e.push(t):i.includes("vp9")?a.push(t):i.includes("vp8")?s.push(t):i.includes("h264")&&r.push(t)})),0===e.length){let t="";0!==a.length?(e=a,t="vp9"):0!==s.length?(e=s,t="vp8"):0!==r.length&&(e=r,t="h264"),B.warning("codec ".concat(n," not included in rtpCapabilities, fallback to default payloads: ").concat(t))}0!==e.length&&(o=t.videoCodecs.filter((t=>e.some((e=>e.payloadType===t.payloadType)))))}if(0===o.length&&(B.warning("codec ".concat(n," not included in rtpCapabilities, fallback to default payloads: ").concat(t.videoCodecs[0].rtpMap&&t.videoCodecs[0].rtpMap.encodingName)),o=t.videoCodecs),ne("USE_PUB_RTX")||ne("USE_SUB_RTX")){const e=ao(o,t.videoCodecs);o=[...o,...e]}}else{o=t.audioCodecs.filter((e=>(e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").includes(n)));const e=t.audioCodecs.filter((e=>(e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").includes("red")));0===o.length&&(B.warning("codec ".concat(n," not included in rtpCapabilities, fallback to opus")),o=t.audioCodecs.filter((e=>(e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").includes("opus")))),ne("ENABLE_AUDIO_RED")&&0!==e.length&&(o=[...e,...o])}return o}function ao(e,t){const i=e.map((e=>e.payloadType.toString()));return t.filter((e=>e.rtpMap&&"rtx"===e.rtpMap.encodingName&&e.fmtp&&e.fmtp.parameters.apt&&i.includes(e.fmtp&&e.fmtp.parameters.apt)))}async function so(e,t,i){const n=t.toString(),o=co(n,"offer","remote","exchangeSDP");await e.setRemoteDescription({type:"offer",sdp:n});const a=await e.createAnswer();if(!a.sdp)throw new Error("cannot get answer sdp");let s=a.sdp;s=ro(s,i||{}),null==o||o(s||""),await e.setLocalDescription({type:"answer",sdp:s})}function ro(e,t,i){const n=ge(e),{useXR:o}=t;return n.mediaDescriptions.forEach((e=>{e.attributes.mid&&(Array.isArray(i)&&!i.includes(e.attributes.mid)||("audio"===e.media.mediaType&&no(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"})}))))})),ye(n)}function co(e,t,i,n){if(ne("SDP_LOGGING"))return B.upload("exchanging ".concat(i," ").concat(t," SDP during P2PConnection.").concat(n,"\n"),e),"offer"===t?e=>{co(e,"answer","local"===i?"remote":"local",n)}:void 0}function lo(e){const t=ne("COMPATIBLE_SDP_EXTENSION");return!!(Array.isArray(t)&&t.length>0)&&t.some((t=>e.includes(t)))}function uo(e,t){try{var i;return(null===(i=e.fmtp)||void 0===i?void 0:i.parameters.apt)===t.payloadType.toString()}catch(e){return!1}}function ho(e,t){return typeof ne(e)===t?ne(e):void 0}const _o={};function po(e){const t=_o[e];if(!t)throw new ue(Z.INVALID_OPERATION,"".concat(e," not found, please use AgoraRTC.use(").concat(e,"Service) to load it first"));return t}function Eo(e,t){return po("DataStream").create(e,t)}function So(){return po("InterceptFrame").create()}const mo=new Map;class Ro extends ie{get state(){return this._state}set state(e){if(e===this._state)return;const t=this._state;this._state=e,"DISCONNECTED"===e&&this._disconnectedReason?this.emit(ji.CONNECTION_STATE_CHANGE,e,t,this._disconnectedReason):this.emit(ji.CONNECTION_STATE_CHANGE,e,t)}get joinGatewayStartTime(){return this._joinGatewayStartTime}set joinGatewayStartTime(e){B.debug("[".concat(this.store.clientId,"] set joinGatewayStartTime at ").concat(e)),this._joinGatewayStartTime=e}constructor(e,t){var i,n,o;super(),this.store=void 0,this.joinInfo=void 0,this.key=void 0,this.ntpOffset=0,this.signal=void 0,this.role=void 0,this.isPreallocation=void 0,this.isPreSub=void 0,this.inChannelInfo={joinAt:null,duration:0},this.spec=void 0,this._state="DISCONNECTED",this._statsCollector=void 0,this._disconnectedReason=void 0,this.isSignalRecover=!1,this.hasChangeBGPAddress=!1,this.trafficStatsInterval=void 0,this.networkQualityInterval=void 0,this._joinGatewayStartTime=0,this._signalTimeout=!1,this._clientRoleOptions=void 0,this._isProactiveJoin=!1,this.store=e,this.spec=t,this.signal=this.store.useP2P?(i={spec:mi(mi({},t),{},{retryConfig:t.websocketRetryConfig}),store:e},null===(n=(o=po("P2PChannel")).createSubmodule)||void 0===n?void 0:n.call(o,i)):new Nn(mi(mi({},t),{},{retryConfig:t.websocketRetryConfig}),e),this._statsCollector=t.statsCollector,this.role=t.role||"audience",this._clientRoleOptions=t.clientRoleOptions,this.handleSignalEvents()}async join(e,t,i){this.store.joinGatewayStart(),"disabled"!==e.cloudProxyServer&&(this.hasChangeBGPAddress=!0);const n=Date.now();let o=mo.get(e.cname);if(o||(o=new Map,mo.set(e.cname,o)),this._isProactiveJoin=!0,o.has(e.uid)){const t=new F(Z.UID_CONFLICT);throw j.joinGateway(e.sid,{lts:n,succ:!1,ec:t.code,addr:null,uid:e.uid,cid:e.cid,firstSuccess:this._isProactiveJoin,isProxy:!!e.proxyServer,signalChannel:"0",preload:e.preload}),t}o.set(e.uid,!0),this.joinInfo=e,this.key=t;let a=0;this.joinGatewayStartTime=n;const s=e.proxyServer;try{B.debug("[".concat(this.store.clientId,"] use websocket join uid ").concat(a));const t=e.gatewayAddrs.map((t=>{let{address:i}=t;const[n,o]=i.split(":"),a={host:n,port:o};return e.proxyServer&&(a.proxy=e.proxyServer),a}));a=(await this.signal.init(t)).uid,B.debug("[".concat(this.store.clientId,"] websocket join uid ").concat(a," cost ").concat(Date.now()-this.joinGatewayStartTime))}catch(t){var r;throw B.error("[".concat(this.store.clientId,"] User join failed"),t.toString()),j.joinGateway(e.sid,{lts:n,succ:!1,ec:(null===(r=t.data)||void 0===r?void 0:r.desc)||t.code,errorMsg:t.message,addr:this.signal.url,uid:e.uid,cid:e.cid,firstSuccess:this._isProactiveJoin,isProxy:!!s,signalChannel:"0",preload:e.preload}),o.delete(e.uid),this.signal.close(),t}return this.state="CONNECTED",this.inChannelInfo.joinAt=Date.now(),B.debug("[".concat(this.store.clientId,"] Connected to gateway server")),this.trafficStatsInterval=window.setInterval((()=>{this.updateTrafficStats().catch((e=>{B.warning("[".concat(this.store.clientId,"] get traffic stats error"),e.toString())}))}),3e3),this.networkQualityInterval=window.setInterval((()=>{navigator&&void 0!==navigator.onLine&&!navigator.onLine?this.emit(ji.NETWORK_QUALITY,{downlinkNetworkQuality:6,uplinkNetworkQuality:6}):this._signalTimeout?this.emit(ji.NETWORK_QUALITY,{downlinkNetworkQuality:5,uplinkNetworkQuality:5}):"CONNECTED"===this.state&&this._statsCollector.trafficStats?this.emit(ji.NETWORK_QUALITY,{uplinkNetworkQuality:Un(this._statsCollector.trafficStats.B_unq),downlinkNetworkQuality:Un(this._statsCollector.trafficStats.B_dnq)}):this.emit(ji.NETWORK_QUALITY,{uplinkNetworkQuality:0,downlinkNetworkQuality:0})}),2e3),this.store.joinGatewayEnd(),a}async leave(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=arguments.length>1?arguments[1]:void 0;if("DISCONNECTED"!==this.state){t!==me.FALLBACK&&(this.state="DISCONNECTING");try{e||this.signal.connectionState!==vi.CONNECTED||await Oe(this.signal.request(Ni.LEAVE,void 0,!0),3e3)}catch(e){B.warning("[".concat(this.store.clientId,"] leave request failed, ignore"),e)}this.signal.close(t),t!==me.FALLBACK&&(this.state="DISCONNECTED"),this.reset()}}async publish(e,t,i){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new F(Z.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));const n={state:"offer",p2p_id:this.store.p2pId,ortc:t,mode:this.spec.mode,extend:ne("PUB_EXTEND"),twcc:!!ne("PUBLISH_TWCC"),rtx:!!ne("USE_PUB_RTX")};try{return(await this.signal.request(Ni.PUBLISH,n,!0))._message}catch(n){if(i&&n.data&&n.data.code===gi.ERR_PUBLISH_REQUEST_INVALID)return B.warning("[".concat(this.store.clientId,"] receive publish error code, retry"),n.toString()),await this.tryUnpubBeforeRepub(e,t),this.publish(e,t,!1);throw n}}async publishDataChannel(e,t,i){var n;if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new F(Z.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));const o={stream_id:t.streamId,ordered:t.ordered?1:0,max_retrans_times:null!==(n=t.maxRetransmits)&&void 0!==n?n:10,channel_id:t.channelId,metadata:t.metadata};try{await this.signal.request(Ni.PUBLISH_DATASTREAM,o,!0)}catch(n){if(i&&n.data&&n.data.code===gi.ERR_PUBLISH_REQUEST_INVALID)return B.warning("[".concat(this.store.clientId,"] receive publish datachannels error code, retry"),n.toString()),await this.tryUnpubDataChannelBeforeRepub(e,t),this.publishDataChannel(e,t,!1);throw n}}async unpublish(e,t){try{if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new F(Z.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));await this.signal.request(Ni.UNPUBLISH,{stream_id:t,ortc:e},!0)}catch(e){B.warning("[".concat(this.store.clientId,"] unpublish warning: "),e)}}async unpublishDataChannel(e){try{if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new F(Z.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));await Promise.all(e.map((e=>this.signal.request(Ni.UNPUBLISH_DATASTREAM,{channel_id:e},!0))))}catch(e){B.warning("unpublish datachannels warning: ",e)}}async presubscribe(e,t,i){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new F(Z.INVALID_OPERATION,"can not presubscribe when connection state is ".concat(this.state));const n={stream_id:e,stream_type:t,mode:this.spec.mode,codec:this.spec.codec,p2p_id:this.store.p2pId,twcc:!!ne("SUBSCRIBE_TWCC"),rtx:!!ne("USE_SUB_RTX")||void 0,extend:ne("SUB_EXTEND"),svc:Array.isArray(ne("SVC"))&&0!==ne("SVC").length?ne("SVC"):void 0};try{return await this.signal.request(Ni.PRE_SUBSCRIBE,n,!0)}catch(n){if(i&&n.data&&n.data.code===gi.ERR_SUBSCRIBE_REQUEST_INVALID)return B.warning("[".concat(this.store.clientId,"] pre-subscribe error, retry"),n.toString()),this.presubscribe(e,t,!1);throw n}}async subscribe(e,t,i){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new F(Z.INVALID_OPERATION,"can not subscribe when connection state is ".concat(this.state));const n={stream_id:e,stream_type:t.stream_type,mode:this.spec.mode,codec:this.spec.codec,p2p_id:this.store.p2pId,twcc:!!ne("SUBSCRIBE_TWCC"),rtx:!!ne("USE_SUB_RTX"),extend:ne("SUB_EXTEND"),ssrcId:t.ssrcId,svc:Array.isArray(ne("SVC"))&&0!==ne("SVC").length?ne("SVC"):void 0};try{return(await this.signal.request(Ni.SUBSCRIBE,n,!0))._message}catch(n){if(i&&n.data&&n.data.code===gi.ERR_SUBSCRIBE_REQUEST_INVALID)return B.warning("[".concat(this.store.clientId,"] receiver subscribe error code, retry"),n.toString()),await this.tryUnsubBeforeResub(e,t),await this.subscribe(e,t,!1);throw n}}async subscribeDataChannel(e,t,i){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new F(Z.INVALID_OPERATION,"can not subscribe datachannel when connection state is ".concat(this.state));const n={uid:e,stream_id:t.id,channel_id:t.datachannelId};try{return void await this.signal.request(Ni.SUBSCRIBE_DATASTREAM,n,!0)}catch(n){if(i&&n.data&&n.data.code===gi.ERR_SUBSCRIBE_REQUEST_INVALID)return B.warning("[".concat(this.store.clientId,"] receiver subscribe datachannel error code, retry"),n.toString()),await this.tryUnsubDataChannelBeforeResub(e,t),await this.subscribeDataChannel(e,t,!1);throw n}}async subscribeAll(e,t){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new F(Z.INVALID_OPERATION,"can not massSubscribe when connection state is ".concat(this.state));const i={p2p_id:this.store.p2pId,users:e,dtx:!1,rtx:!!ne("USE_SUB_RTX"),twcc:!!ne("SUBSCRIBE_TWCC"),svc:Array.isArray(ne("SVC"))&&0!==ne("SVC").length?ne("SVC"):void 0};try{return await this.signal.request(Ni.SUBSCRIBE_STREAMS,i,!0)}catch(i){if(t&&i.data&&i.data.code===gi.ERR_SUBSCRIBE_REQUEST_INVALID)return B.warning("[".concat(this.store.clientId,"] receiver massSubscribe error code, retry"),i.toString()),await this.tryMassUnsubBeforeResub(e),await this.subscribeAll(e,!1);throw i}}async setVideoProfile(e){const t=function(e){if(!(e.bitrateMax&&e.bitrateMin&&e.frameRate&&e.height&&e.width))return;let t=e.frameRate,i=e.width,n=e.height,o=!0;return"number"!=typeof t&&(t=t.exact||t.ideal||t.max||t.min||0,t||(o=!1)),"number"!=typeof i&&(i=i.exact||i.ideal||i.max||i.min||0,i||(o=!1)),"number"!=typeof n&&(n=n.exact||n.ideal||n.max||n.min||0,t||(o=!1)),o?{stream_type:0,width:i,height:n,fps:t,start_bps:1e3*e.bitrateMax,min_bps:1e3*e.bitrateMin,target_bps:1e3*e.bitrateMax}:void 0}(e);if(t)return this.signal.request(Ni.SET_VIDEO_PROFILE,t);B.debug("[".concat(this.store.clientId,"] encoder config is not complete, do not report to gateway"))}async unsubscribe(e,t){try{await this.signal.request(Ni.UNSUBSCRIBE,{p2p_id:this.store.p2pId,ortc:e,stream_id:t},!0)}catch(e){B.warning("[".concat(this.store.clientId,"] unsubscribe warning: "),e)}}async unsubscribeDataChannel(e,t){try{if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new F(Z.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));await Promise.all(e.map((e=>this.signal.request(Ni.UNSUBSCRIBE_DATASTREAM,{stream_id:e,uid:t},!0))))}catch(e){B.warning("unsubscribeDataChannel warning: ",e)}}async massUnsubscribe(e){try{await this.signal.request(Ni.UNSUBSCRIBE_STREAMS,e,!0)}catch(e){B.warning("[".concat(this.store.clientId,"] massUnsubscribeAll warning: "),e)}}async reconnectPC(e){const{iceParameters:t,dtlsParameters:i,rtpCapabilities:n}=e;return{gatewayEstablishParams:await this.signal.request(Ni.CONNECT_PC,{p2p_id:this.store.p2pId,stream_id:this.store.uid,ortc:{iceParameters:t,dtlsParameters:i,rtpCapabilities:n}},!0),gatewayAddress:this.getCurrentGatewayAddress()}}getGatewayInfo(){return this.signal.request(Ni.GATEWAY_INFO)}async renewToken(e){await this.signal.request(Ni.RENEW_TOKEN,e),this.key=e.token}updateClientRole(e,t){t&&(this._clientRoleOptions=Object.assign({},t)),ne("CLIENT_ROLE_OPTIONS")&&(B.debug("[".concat(this.store.clientId,"] Set roleOptions for ").concat(JSON.stringify(ne("CLIENT_ROLE_OPTIONS"))," instead of ").concat(JSON.stringify(this._clientRoleOptions)," ")),this._clientRoleOptions=Object.assign({},ne("CLIENT_ROLE_OPTIONS"))),this.role=e}async setClientRole(e,t){if(t&&(this._clientRoleOptions=Object.assign({},t)),ne("CLIENT_ROLE_OPTIONS")&&(this._clientRoleOptions=Object.assign({},ne("CLIENT_ROLE_OPTIONS")),B.debug("[".concat(this.store.clientId,"] Set roleOptions for ").concat(JSON.stringify(ne("CLIENT_ROLE_OPTIONS"))," instead of ").concat(JSON.stringify(this._clientRoleOptions)," "))),"CONNECTED"!==this.state)return void(this.role=e);let i,n=0;"audience"===e?this._clientRoleOptions&&this._clientRoleOptions.delay?(i=this._clientRoleOptions.delay,n=1):n=this._clientRoleOptions&&this._clientRoleOptions.level?this._clientRoleOptions.level:2:n=0;const o=Object.assign({},t);delete o.delay,delete o.level,await this.signal.request(Ni.SET_CLIENT_ROLE,mi(mi({role:e,level:n,delay:i},o),{},{client_ts:Date.now()})),this.role=e}async setRemoteVideoStreamType(e,t){await this.signal.request(Ni.SWITCH_VIDEO_STREAM,{stream_id:e,stream_type:t})}async setDefaultRemoteVideoStreamType(e){await this.signal.request(Ni.DEFAULT_VIDEO_STREAM,{stream_type:e})}async setStreamFallbackOption(e,t){await this.signal.request(Ni.SET_FALLBACK_OPTION,{stream_id:e,fallback_type:t})}async pickSVCLayer(e,t){await this.signal.request(Ni.PICK_SVC_LAYER,{stream_id:e,spatial_layer:t.spatialLayer,temporal_layer:t.temporalLayer})}async setRTM2Flag(e){await this.signal.request(Ni.SET_RTM2_FLAG,{rtm2_flag:e})}async sendExtensionMessage(e,t,i){if(this.store.useP2P)return this.signal.sendExtensionMessage(e,t,i)}getInChannelInfo(){return this.inChannelInfo.joinAt&&(this.inChannelInfo.duration=Date.now()-this.inChannelInfo.joinAt),mi({},this.inChannelInfo)}async getGatewayVersion(){return(await this.signal.request(Ni.GATEWAY_INFO)).version}reset(){if(this.inChannelInfo.joinAt&&(this.inChannelInfo.duration=Date.now()-this.inChannelInfo.joinAt,this.inChannelInfo.joinAt=null),this.trafficStatsInterval&&(window.clearInterval(this.trafficStatsInterval),this.trafficStatsInterval=void 0),this.joinInfo){const e=mo.get(this.joinInfo.cname);e&&e.delete(this.joinInfo.uid)}this.joinInfo=void 0,this.key=void 0,this.networkQualityInterval&&(window.clearInterval(this.networkQualityInterval),this.networkQualityInterval=void 0)}updateTurnConfigFromSignal(){if(!this.joinInfo)return;const e=function(e){let t;return t=e.startsWith("dc")?e.match(/(dc\:\/\/)?([^:]+):(\d+)/):e.match(/(wss\:\/\/)?([^:]+):(\d+)/),t?{username:Te.username,password:Te.password,turnServerURL:t[2],tcpport:parseInt(t[3])+30,udpport:parseInt(t[3])+30,forceturn:!1}:null}(("disabled"===this.joinInfo.cloudProxyServer?this.signal.url:this.joinInfo.gatewayAddrs[this.signal.currentURLIndex].address)||"");this.joinInfo.turnServer.serversFromGateway=[],e&&"off"!==this.joinInfo.turnServer.mode&&"disabled"===this.joinInfo.cloudProxyServer&&this.joinInfo.turnServer.serversFromGateway.push(mi(mi({},Te),{},{turnServerURL:e.turnServerURL,tcpport:e.tcpport,udpport:e.udpport,username:this.joinInfo.uid.toString(),password:this.joinInfo.token}))}async updateTrafficStats(){if("CONNECTED"!==this.state)return;const e=await this.signal.request(Ni.TRAFFIC_STATS,void 0,!0);e.timestamp=Date.now(),null!=e.ntp_offset&&(this.ntpOffset=e.ntp_offset),e.peer_delay.forEach((e=>{const t=this._statsCollector.trafficStats&&this._statsCollector.trafficStats.peer_delay.find((t=>t.peer_uid===e.peer_uid));t&&t.B_st!==e.B_st&&De((()=>{this.emit(ji.STREAM_TYPE_CHANGE,e.peer_uid,e.B_st)}))})),this._statsCollector.updateTrafficStats(e)}getJoinMessage(e){var t,i;if(!this.joinInfo||!this.key)throw new F(Z.UNEXPECTED_ERROR,"can not generate join message, no join info");const n=Object.assign({},this.joinInfo.apResponse);let o=ne("REPORT_APP_SCENARIO");if("string"!=typeof o)try{o=JSON.stringify(o)}catch(e){o=void 0}var a;o&&o.length>128&&(o=void 0),this.store.hasStartJoinChannel=!0,this.store.isABTestSuccess||this.emit(ji.UPDATE_GATEWAY_CONFIG),a=this.store.clientId,si.includes(a)||si.push(a);const l=s(this.store),u=!(null===(t=this.isPreallocation)||void 0===t||!t.call(this)),h=r(this.store),_=function(){try{const e=ne("EXPERIMENTS")||{};return"string"==typeof e||Array.isArray(e)?{}:mi({},e)}catch(e){return B.debug("handle gateway attributes failed: ",e),{}}}(),p=Pe(87)||Le()||ke(117),E=(Ue()||Me(18,4,!1))&&Ve(18,6,!0)&&"h264"===this.spec.codec&&ne("ENABLE_ABSSENDTIME_AS_SENTTS"),S=mi({license:this.joinInfo.license,p2p_id:this.store.p2pId,session_id:this.joinInfo.sid,app_id:this.joinInfo.appId,channel_key:this.key,channel_name:this.joinInfo.cname,sdk_version:xe,browser:navigator.userAgent,process_id:ne("PROCESS_ID"),mode:this.store.useP2P?"p2p":this.spec.mode,codec:this.spec.codec,role:this.role,has_changed_gateway:this.hasChangeBGPAddress,ap_response:n,extend:ne("JOIN_EXTEND"),details:{6:this.joinInfo.stringUid,cservice_map:"proxy3"===this.joinInfo.cloudProxyServer?"1":"proxy5"===this.joinInfo.cloudProxyServer?"2":void 0},features:{rejoin:!0},optionalInfo:this.joinInfo.optionalInfo,appScenario:o,attributes:{userAttributes:mi(mi({enableEncodedTransform:(!!ne("ENABLE_AUDIO_METADATA")||!!ne("ENABLE_AUDIO_PTS"))&&p||!!ne("ENABLE_AUDIO_TOPN")&&Be(be.CHROME,87,116)||void 0,enableAudioMetadata:!!ne("ENABLE_AUDIO_METADATA")&&p,enableAudioPts:!!ne("ENABLE_AUDIO_PTS")&&p,topnSmoothLevel:ne("TOPN_SMOOTH_LEVEL"),topnNewSpeakerDelay:ne("TOPN_NEW_SPEAKER_DELAY"),topnSwitchHoldMs:ne("TOPN_SWITCH_HOLD_MS"),topnAudioGain:ne("TOPN_AUDIO_GAIN"),enablePublishedUserList:ne("ENABLE_PUBLISHED_USER_LIST"),maxSubscription:ne("MAX_SUBSCRIPTION"),subscribeAudioFilterTopN:ho("SUBSCRIBE_AUDIO_FILTER_TOPN","number"),enablePublishAudioFilter:ho("ENABLE_PUBLISH_AUDIO_FILTER","boolean"),enableUserLicenseCheck:ho("ENABLE_USER_LICENSE_CHECK","boolean"),enableRTX:!0===ne("USE_PUB_RTX")||!0===ne("USE_SUB_RTX")||void 0,disableFEC:ne("DISABLE_FEC"),enableNTPReport:!!ne("ENABLE_NTP_REPORT")||void 0,enableInstantVideo:h,enableFulllinkAvSync:!!ne("ENABLE_FULL_LINK_AV_SYNC")||void 0,enableDataStream2:ho("ENABLE_DATASTREAM_2","boolean"),enableAutFeedback:c(),rtm2Flag:"number"==typeof this.joinInfo.rtmFlag?this.joinInfo.rtmFlag:void 0,enableUserAutoRebalanceCheck:!!ne("ENABLE_USER_AUTO_REBALANCE_CHECK"),enableXR:ho("USE_XR","boolean"),enableLossbasedBwe:ho("ENABLE_LOSSBASED_BWE","boolean"),enableAutCC:d(),enableCCFallback:ho("ENABLE_CC_FALLBACK","boolean"),enablePreallocPC:u,preSubNum:l?ho("PRE_SUB_NUM","number"):void 0,enablePubTWCC:ho("PUBLISH_TWCC","boolean"),enableSubTWCC:ho("SUBSCRIBE_TWCC","boolean"),enablePubRTX:ho("USE_PUB_RTX","boolean"),enableSubRTX:ho("USE_SUB_RTX","boolean"),enableSubSVC:ne("ENABLE_SVC")?ne("ENABLE_SVC_DEFAULT_CODECS"):Array.isArray(ne("SVC"))&&0!==ne("SVC").length?ne("SVC"):void 0,enableSvcExtended:ne("ENABLE_SVC")&&Array.isArray(ne("SVC_EXTENDED"))&&0!==ne("SVC_EXTENDED").length?ne("SVC_EXTENDED"):void 0},_),{},{audioDuplicate:ho("ENABLE_AUDIO_RED","boolean")?null!==(i=ho("AUDIO_DUPLICATE_NUM","number"))&&void 0!==i?i:2:void 0,senttsUsesAbsSendTime:!!E||void 0})},join_ts:this.joinGatewayStartTime},e);return this.joinInfo.stringUid&&(S.string_uid=this.joinInfo.stringUid),this.joinInfo.aesmode&&this.joinInfo.aespassword&&(S.aes_mode=this.joinInfo.aesmode,ne("ENCRYPT_AES")?(S.aes_secret=this.joinInfo.aespassword,S.aes_encrypt=!0):S.aes_secret=this.joinInfo.aespassword,this.joinInfo.aessalt&&(S.aes_salt=this.joinInfo.aessalt)),n.addresses[this.signal.websocket.currentURLIndex]&&(S.ap_response.ticket=n.addresses[this.signal.websocket.currentURLIndex].ticket,delete n.addresses),void 0!==this.joinInfo.defaultVideoStream&&(S.default_video_stream=this.joinInfo.defaultVideoStream),S}getRejoinMessage(){if(!this.joinInfo)throw new F(Z.UNEXPECTED_ERROR,"can not generate rejoin message, no join info");return{session_id:this.joinInfo.sid,channel_name:this.joinInfo.cname,cid:this.joinInfo.cid,uid:this.joinInfo.uid,vid:Number(this.joinInfo.vid)}}handleSignalEvents(){this.signal.on(yi.WS_RECONNECT_CREATE_CONNECTION,(e=>{this.joinGatewayStartTime=Date.now()})),this.signal.on(yi.WS_RECONNECTING,(e=>{this.joinInfo&&j.WebSocketQuit(this.joinInfo.sid,{lts:Date.now(),succ:-1,cname:this.joinInfo.cname,uid:this.joinInfo.uid,cid:this.joinInfo.cid,errorCode:e||Re.NETWORK_ERROR}),this.joinInfo&&(this.state="RECONNECTING",j.sessionInit(this.joinInfo.sid,{lts:(new Date).getTime(),extend:this.isSignalRecover?{recover:!0}:{rejoin:!0},cname:this.joinInfo.cname,appid:this.joinInfo.appId,mode:this.spec.mode,stringUid:this.joinInfo.stringUid,channelProfile:"live"===this.spec.mode?1:0,channelMode:0,lsid:this.joinInfo.sid,clientRole:"audience"===this.role?2:1,buildFormat:3}),this.isSignalRecover=!1,this.joinGatewayStartTime=Date.now())})),this.signal.on(yi.WS_CLOSED,(e=>{let t;switch(e){case me.LEAVE:t=Re.LEAVE;break;case me.UID_BANNED:case me.IP_BANNED:case me.CHANNEL_BANNED:case me.SERVER_ERROR:t=Re.SERVER_ERROR;break;case me.FALLBACK:t=Re.FALLBACK;break;case me.LICENSE_MISSING:case me.LICENSE_EXPIRED:case me.LICENSE_MINUTES_EXCEEDED:case me.LICENSE_PERIOD_INVALID:case me.LICENSE_MULTIPLE_SDK_SERVICE:case me.LICENSE_ILLEGAL:case me.TOKEN_EXPIRE:t=e;break;default:t=Re.NETWORK_ERROR}B.debug("[".concat(this.store.clientId,"] [signal] websocket closed, reason: ").concat(t||"undefined -> "+Re.NETWORK_ERROR)),this.joinInfo&&j.WebSocketQuit(this.joinInfo.sid,{lts:Date.now(),succ:e===me.LEAVE?1:-1,cname:this.joinInfo.cname,uid:this.joinInfo.uid,cid:this.joinInfo.cid,errorCode:t}),this._disconnectedReason=e,e!==me.FALLBACK&&(this.state="DISCONNECTED"),this.reset()})),this.signal.on(yi.WS_CONNECTED,(()=>{if(this.updateTurnConfigFromSignal(),this.state="CONNECTED",this.joinInfo){if("audience"===this.role){const e=ne("CLIENT_ROLE_OPTIONS")||this._clientRoleOptions;e&&(e.level||e.delay)&&(B.debug("[".concat(this.store.clientId,"] patch to send set client role, role: ").concat(this.role,", mode: ").concat(this.spec.mode,", level: ").concat(e.level,", delay: ").concat(e.delay)),this.setClientRole(this.role,e))}if(j.joinGateway(this.joinInfo.sid,{lts:this.joinGatewayStartTime,succ:!0,ec:null,vid:this.joinInfo.vid,addr:this.signal.url,uid:this.joinInfo.uid,cid:this.joinInfo.cid,firstSuccess:this._isProactiveJoin,isProxy:!!this.joinInfo.proxyServer,signalChannel:"0",preload:this.joinInfo.preload,isABTestSuccess:this.store.isABTestSuccess}),this._isProactiveJoin=!1,this.joinInfo.useLocalAccessPoint&&1===this.joinInfo.setLocalAPVersion){const e=this.signal.url&&this.signal.url.match(/wss\:\/\/([^:]+):(\d+)/);if(!e)return void B.error("[".concat(this.store.clientId,"] set local access point after joined failed: ").concat(e));Fe("EVENT_REPORT_DOMAIN",e[1]),Fe("EVENT_REPORT_BACKUP_DOMAIN",e[1]),Fe("LOG_UPLOAD_SERVER","".concat(e[1],":6444"))}}})),this.signal.on(wi.ON_UPLINK_STATS,(e=>{this._statsCollector.updateUplinkStats(e)})),this.signal.on(yi.REQUEST_RECOVER,((e,t,i)=>{if(!this.joinInfo)return i(new F(Z.UNEXPECTED_ERROR,"gateway: can not recover, no join info"));e&&(this.joinInfo.multiIP=e,this.hasChangeBGPAddress=!0),this.isSignalRecover=!0,pe(this,ji.REQUEST_NEW_GATEWAY_LIST).then(t).catch(i)})),this.signal.on(yi.REQUEST_JOIN_INFO,(async(e,t,i)=>{var n,o,a;if(this.updateTurnConfigFromSignal(),this.store.useP2P)return void e(this.getJoinMessage({ortc:{}}));const s=ve(null===(n=this.joinInfo)||void 0===n?void 0:n.turnServer);if(ne("NEW_TURN_MODE")&&s&&"disabled"===(null===(o=this.joinInfo)||void 0===o?void 0:o.cloudProxyServer)){var r;let e=s.servers.map((e=>"turnServerURL"in e&&ne("USE_TURN_IP")?mi(mi({},e),{},{turnServerURL:Dn(e.turnServerURL)}):e)),t=null===(r=s.serversFromGateway)||void 0===r?void 0:r.map((e=>ne("USE_TURN_IP")?mi(mi({},e),{},{turnServerURL:Dn(e.turnServerURL)}):e));const i=this.signal.currentURLIndex;if(e.length>0){e=[e[i%e.length]],s.servers=e}Array.isArray(t)&&t.length>0&&(t=[t[0]],s.serversFromGateway=t),B.debug("[".concat(this.store.clientId,"] use single turn, use turn server index: ").concat(i))}const{iceParameters:c,dtlsParameters:d,rtpCapabilities:l}=await pe(this,ji.REQUEST_P2P_CONNECTION_PARAMS,{turnServer:s,cloudProxyServer:null===(a=this.joinInfo)||void 0===a?void 0:a.cloudProxyServer});try{e(this.getJoinMessage({ortc:{iceParameters:c,dtlsParameters:d,rtpCapabilities:l,version:"2"}}))}catch(e){t(e)}})),this.signal.on(yi.REQUEST_REJOIN_INFO,(e=>{e(this.getRejoinMessage())})),this.signal.on(yi.REPORT_JOIN_GATEWAY,((e,t)=>{if(!this.joinInfo)return;let i,n="";var o;e instanceof F?(i=(null===(o=e.data)||void 0===o?void 0:o.desc)||e.code,n=e.message):i=e;j.joinGateway(this.joinInfo.sid,{lts:this.joinGatewayStartTime,succ:!1,ec:i,errorMsg:n,addr:t,uid:this.joinInfo.uid,cid:this.joinInfo.cid,firstSuccess:this._isProactiveJoin,isProxy:!!this.joinInfo.proxyServer,signalChannel:"0",preload:this.joinInfo.preload})})),this.signal.on(yi.IS_P2P_DISCONNECTED,(e=>{e(Ce(this,ji.IS_P2P_DISCONNECTED))})),this.signal.on(yi.DISCONNECT_P2P,(()=>{this.emit(ji.DISCONNECT_P2P)})),this.signal.on(yi.REQUEST_SUCCESS,(()=>{this._signalTimeout=!1})),this.signal.on(yi.REQUEST_TIMEOUT,(()=>{this._signalTimeout=!0})),this.signal.on(yi.JOIN_RESPONSE,(e=>{const t=this.getCurrentGatewayAddress();this.emit(ji.JOIN_RESPONSE,e,t)})),this.signal.on(yi.PRE_CONNECT_PC,(async()=>{if(this.joinInfo){var e,t;this.updateTurnConfigFromSignal();const n=this.getCurrentGatewayAddress(),o=ve(null===(e=this.joinInfo)||void 0===e?void 0:e.turnServer);if(ne("NEW_TURN_MODE")&&o&&"disabled"===(null===(t=this.joinInfo)||void 0===t?void 0:t.cloudProxyServer)){var i;let e=o.servers.map((e=>"turnServerURL"in e&&ne("USE_TURN_IP")?mi(mi({},e),{},{turnServerURL:Dn(e.turnServerURL)}):e)),t=null===(i=o.serversFromGateway)||void 0===i?void 0:i.map((e=>ne("USE_TURN_IP")?mi(mi({},e),{},{turnServerURL:Dn(e.turnServerURL)}):e));const n=this.signal.currentURLIndex;if(e.length>0){e=[e[n%e.length]],o.servers=e}Array.isArray(t)&&t.length>0&&(t=[t[0]],o.serversFromGateway=t),B.debug("[".concat(this.store.clientId,"] use single turn, use turn server index: ").concat(n,",in pre pc"))}const a=ne("FINGERPRINT")||this.joinInfo.apResponse.addresses[this.signal.currentURLIndex].fingerprint;if(n&&a){const e=zn(n);this.emit(ji.PRE_CONNECT_PC,{candidates:e,fingerprint:a,turnServer:o})}}})),this.signal.on(yi.RECOVER_NOTIFICATION,(e=>{this.joinInfo&&"string"==typeof ne("AP_REQUEST_DETAIL")&&(this.joinInfo.apRequestDetail="".concat(ne("AP_REQUEST_DETAIL"),";").concat(e))}))}async tryUnsubBeforeResub(e,t){try{await this.signal.request(Ni.UNSUBSCRIBE,{p2p_id:this.store.p2pId,stream_id:e,ortc:[t]},!0)}catch(e){throw B.warning("[".concat(this.store.clientId,"] tryUnsubBeforeResub warning"),e),e}}async tryUnsubDataChannelBeforeResub(e,t){try{await this.signal.request(Ni.UNSUBSCRIBE,{stream_id:t.id},!0)}catch(e){throw B.warning("unsubscribe datachannel warning",e),e}}async tryUnpubBeforeRepub(e,t){try{await this.signal.request(Ni.UNPUBLISH,{stream_id:e,ortc:t},!0)}catch(e){throw B.warning("[".concat(this.store.clientId,"] tryUnpubBeforeRepub warning: "),e),e}}async tryUnpubDataChannelBeforeRepub(e,t){try{await this.signal.request(Ni.UNPUBLISH_DATASTREAM,{channnel_id:t.channelId},!0)}catch(e){throw B.warning("unpublish datastream warning: ",e),e}}async tryMassUnsubBeforeResub(e){const t={users:e.map((e=>({stream_id:e.stream_id,stream_type:e.stream_type})))};try{await this.signal.request(Ni.UNSUBSCRIBE_STREAMS,t,!0)}catch(e){throw B.warning("[".concat(this.store.clientId,"] tryMassUnsubBeforeResub warning"),e),e}}async muteLocal(e,t){const i={action:e.find((e=>e.stream_type===Fi.Audio))?"mute_local_audio":"mute_local_video",p2p_id:this.store.p2pId,ortc:e,stream_id:t};try{await this.signal.request(Ni.CONTROL,i,!0,!0)}catch(e){throw B.warning("[".concat(this.store.clientId,"] gateway muteLocal warning: "),e),e}}async unmuteLocal(e,t){const i={action:e.find((e=>e.stream_type===Fi.Audio))?"unmute_local_audio":"unmute_local_video",p2p_id:this.store.p2pId,ortc:e,stream_id:t};try{await this.signal.request(Ni.CONTROL,i,!0,!0)}catch(e){throw B.warning("[".concat(this.store.clientId,"] gateway unmuteLocal warning: "),e),e}}async muteRemote(e,t){const i={action:e===Zi.AUDIO?"mute_remote_audio":"mute_remote_video",p2p_id:this.store.p2pId,stream_id:t};try{await this.signal.request(Ni.CONTROL,i,!0,!0)}catch(e){throw B.warning("[".concat(this.store.clientId,"] gateway muteRemote warning: "),e),e}}async unmuteRemote(e,t){const i={action:e===Zi.AUDIO?"unmute_remote_audio":"unmute_remote_video",p2p_id:this.store.p2pId,stream_id:t};try{await this.signal.request(Ni.CONTROL,i,!0,!0)}catch(e){throw B.warning("[".concat(this.store.clientId,"] gateway unmuteRemote warning: "),e),e}}uploadWRTCStats(e){this.signal.uploadWRTCStats(e)}upload(e,t){this.signal.upload(e,t)}getSignalRTT(){return this.signal.rtt}async restartICE(e){const t={p2p_id:this.store.p2pId,stream_id:this.store.uid,ortc:e};try{return await this.signal.request(Ni.RESTART_ICE,t,!0)}catch(e){throw B.warning("[".concat(this.store.clientId,"] P2PChannel.restartICE warning: "),e),e}}reconnect(e,t){"CONNECTED"===this.state&&this.signal.reconnect(e||void 0,t||Re.P2P_FAILED)}getCurrentGatewayAddress(){var e,t;if(!ne("GATEWAY_WSS_ADDRESS"))return ne("USE_CANDIDATE_FROM_AP_DETAIL")&&null!==(e=this.joinInfo)&&void 0!==e&&e.apGatewayAddress?(B.debug("[".concat(this.store.clientId,"] use candidate from ap detail, ").concat(JSON.stringify(this.joinInfo.apGatewayAddress))),this.joinInfo.apGatewayAddress):null!==(t=this.joinInfo)&&void 0!==t&&t.gatewayAddrs?this.joinInfo.gatewayAddrs[this.signal.currentURLIndex]:void 0}async setPublishAudioFilterEnabled(e){await this.signal.request(Ni.SET_PARAMETER,{enablePublishAudioFilter:e})}downgradeCodec(e){this.signal.downgradeCodec(e)}}let fo=0,Co=0;function To(e,t,i,n){return new Promise(((o,a)=>{t.timeout=t.timeout||ne("HTTP_CONNECT_TIMEOUT"),t.responseType=t.responseType||"json",t.data&&!i?(t.data=JSON.stringify(t.data),fo+=je(t.data)):i&&(t.data.size?fo+=t.data.size:t.data instanceof FormData?fo+=Ge(t.data):fo+=je(JSON.stringify(t.data))),t.headers=t.headers||{},t.headers["Content-Type"]=t.headers["Content-Type"]||"application/json",t.method="POST",t.url=e,Zt.request(t).then((e=>{"string"==typeof e.data?Co+=je(e.data):e.data instanceof ArrayBuffer||e.data instanceof Uint8Array?Co+=e.data.byteLength:Co+=je(JSON.stringify(e.data)),n&&o({data:e.data,headers:e.headers}),o(e.data)})).catch((e=>{Zt.isCancel(e)?a(new F(Z.OPERATION_ABORTED,"cancel token canceled")):"ECONNABORTED"===e.code?a(new F(Z.NETWORK_TIMEOUT,e.message)):e.response?a(new F(Z.NETWORK_RESPONSE_ERROR,e.response.status)):a(new F(Z.NETWORK_ERROR,e.message))}))}))}const Io=()=>{const e=ne("AREAS");0===e.length&&e.push(Hi.GLOBAL);return e.reduce(((e,t,i)=>{const n=Ao(t);return n?0===i?n:"".concat(e,",").concat(n):e}),"")},Ao=e=>e===Hi.OVERSEA?"".concat(Yi.ASIA,",").concat(Yi.EUROPE,",").concat(Yi.AFRICA,",").concat(Yi.NORTH_AMERICA,",").concat(Yi.SOUTH_AMERICA,",").concat(Yi.OCEANIA):Yi[e],go=e=>{const t={CODE:"",WEBCS_DOMAIN:[],WEBCS_DOMAIN_BACKUP_LIST:[],PROXY_CS:[],CDS_AP:[],ACCOUNT_REGISTER:[],UAP_AP:[],EVENT_REPORT_DOMAIN:[],EVENT_REPORT_BACKUP_DOMAIN:[],LOG_UPLOAD_SERVER:[],PROXY_SERVER_TYPE3:[]};return e.map((e=>{const i=qi[e],n=Object.keys(i);n&&n.map((e=>{"CODE"!==e&&(t[e]=t[e].concat(i[e]))}))})),t},vo={GLOBAL:{ASIA:[Hi.CHINA,Hi.JAPAN,Hi.INDIA,Hi.KOREA,Hi.HKMC],EUROPE:[],NORTH_AMERICA:[Hi.US],SOUTH_AMERICA:[],OCEANIA:[],AFRICA:[]}},yo=Object.keys(vo[Hi.GLOBAL]),No=[Hi.CHINA,Hi.NORTH_AMERICA,Hi.EUROPE,Hi.ASIA,Hi.JAPAN,Hi.INDIA,Hi.OCEANIA,Hi.SOUTH_AMERICA,Hi.AFRICA,Hi.KOREA,Hi.HKMC,Hi.US],bo=function(e,t){let i=[];if(e.includes(Hi.GLOBAL)){const a=[Hi.GLOBAL,Hi.OVERSEA],s=Object.keys(qi);if(t===Hi.GLOBAL)throw new F(Z.INVALID_PARAMS,"GLOBAL is an invalid excludedArea value");if(t===Hi.CHINA)i=[Hi.OVERSEA];else if(o=t,yo.includes(o)){const e=(n=t,vo[Hi.GLOBAL][n]||[]),o=[...a,t,...e];i=s.filter((e=>!o.includes(e)))}else if(function(e){let t=!1;return yo.forEach((i=>{vo[Hi.GLOBAL][i].includes(e)&&(t=!0)})),t}(t)){const e=function(e){let t;return yo.forEach((i=>{vo[Hi.GLOBAL][i].includes(e)&&(t=i)})),t}(t),n=[...a,e,t];i=s.filter((e=>!n.includes(e)))}else i=e;i=function(e){const t=[];return No.forEach((i=>{e.includes(i)&&t.push(i)})),t.concat(e.filter((e=>!No.includes(e))))}(i)}else i=e;var n,o;return i};function wo(e){if(!e&&ne("AREAS").includes(Hi.EXTENSIONS))return B.debug("update area from ap : reset"),void Oo(ni,!0);if(!ne("AREAS").includes(Hi.GLOBAL)||!e)return;let t=qi.EXTENSIONS;t&&(t={CODE:Ao(Hi.EXTENSIONS),WEBCS_DOMAIN:["ap-web-1-".concat(e,".agora.io")],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-".concat(e,".ap.sd-rtn.com")],PROXY_CS:["proxy-ap-web-".concat(e,".agora.io")],CDS_AP:["cds-ap-web-1-".concat(e,".agora.io"),"cds-ap-web-2-".concat(e,".ap.sd-rtn.com")],ACCOUNT_REGISTER:["sua-ap-web-1-".concat(e,".agora.io"),"sua-ap-web-2-".concat(e,".ap.sd-rtn.com")],UAP_AP:["uap-ap-web-1-".concat(e,".agora.io"),"uap-ap-web-2-".concat(e,".ap.sd-rtn.com")],EVENT_REPORT_DOMAIN:["statscollector-1-".concat(e,".agora.io")],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-".concat(e,".agora.io")],LOG_UPLOAD_SERVER:["logservice-".concat(e,".agora.io")],PROXY_SERVER_TYPE3:["webrtc-cloud-proxy-".concat(e,".agora.io")]},B.debug("update area from ap success: ".concat(e,",config is "),t),Fe("AREAS",[Hi.EXTENSIONS],!0),Object.keys(t).map((e=>{if("LOG_UPLOAD_SERVER"===e||"EVENT_REPORT_DOMAIN"===e||"EVENT_REPORT_BACKUP_DOMAIN"===e||"PROXY_SERVER_TYPE3"===e){const i=t[e];Fe(e,i[0])}else Fe(e,t[e])})))}function Oo(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const i=j.reportApiInvoke(null,{name:We.SET_AREA,options:e,tag:He.TRACER});try{let n=[];if("string"==typeof e&&(n=[e]),Array.isArray(e)&&(e.forEach((e=>{if(!Ki.includes(e))throw new F(Z.INVALID_PARAMS,"invalid area code")})),n=e),"[object Object]"===Object.prototype.toString.call(e)){const{areaCode:t,excludedArea:i}=e;if(!t)throw new F(Z.INVALID_PARAMS,"area code is needed");let o=t;"string"==typeof t&&(o=[t]),n=i?bo(o,i):o}if(!t){if(X.AREAS){const e=new F(Z.PROHIBITED_OPERATION,"setArea is prohibited because of config-distribute");return i.onError(e),void B.warning("setArea is prohibited because of config-distribute")}if(n.includes(Hi.GLOBAL)&&ne("AREAS")===Hi.EXTENSIONS){const e=new F(Z.PROHIBITED_OPERATION,"setArea is prohibited because of ap extensions");return i.onError(e),void B.warning("setArea is prohibited because of ap extensions")}}Fe("AREAS",n,t);const o=go(n);Object.keys(o).map((e=>{if("LOG_UPLOAD_SERVER"===e||"EVENT_REPORT_DOMAIN"===e||"EVENT_REPORT_BACKUP_DOMAIN"===e||"PROXY_SERVER_TYPE3"===e){const t=o[e];Fe(e,t[0])}else Fe(e,o[e])})),B.debug("set area success:",n.join(","))}catch(e){throw i.onError(e),e}i.onSuccess()}let Do=1;function Po(e,t,i,n,o){Do+=1;const a={sid:i.sid,command:"convergeAllocateEdge",uid:"666",appId:i.appId,ts:Math.floor(Date.now()/1e3),seq:Do,requestId:Do,version:xe,cname:i.cname},s={service_name:t,json_body:JSON.stringify(a)};let r,c,d=e[0];return Ke((async()=>{r=Date.now();const e=await To(d,{data:s,cancelToken:n,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"}});if(c=Date.now()-r,0!==e.code){const t=new F(G.UNEXPECTED_RESPONSE,"live streaming ap error, code"+e.code,{retry:!0,responseTime:c});throw B.error(t.toString()),t}const i=JSON.parse(e.json_body);if(200!==i.code){const e=new F(G.UNEXPECTED_RESPONSE,"live streaming app center error, code: ".concat(i.code,", reason: ").concat(i.reason),{code:i.code,responseTime:c});throw B.error(e.toString()),e}if(!i.servers||0===i.servers.length){const e=new F(G.UNEXPECTED_RESPONSE,"live streaming app center empty server",{code:i.code,responseTime:c});throw B.error(e.toString()),e}const o=function(e,t){return{addressList:e.servers.map((e=>"wss://".concat(e.address.replace(/\./g,"-"),".").concat(ne("WORKER_DOMAIN"),":").concat(e.wss,"?serviceName=").concat(encodeURIComponent(t)))),workerToken:e.workerToken,vid:e.vid}}(i,t);return ne("LIVE_STREAMING_ADDRESS")&&(o.addressList=ne("LIVE_STREAMING_ADDRESS")instanceof Array?ne("LIVE_STREAMING_ADDRESS"):[ne("LIVE_STREAMING_ADDRESS")]),mi(mi({},o),{},{responseTime:c})}),((n,o)=>(j.apworkerEvent(i.sid,{success:!0,sc:200,serviceName:t,responseDetail:JSON.stringify(n.addressList),firstSuccess:0===o,responseTime:c,serverIp:e[o%e.length]}),!1)),((n,o)=>(j.apworkerEvent(i.sid,{success:!1,sc:n.data&&n.data.code||200,serviceName:t,responseTime:c,serverIp:e[o%e.length]}),!!(n.code!==G.OPERATION_ABORTED&&n.code!==G.UNEXPECTED_RESPONSE||n.data&&n.data.retry)&&(d=e[(o+1)%e.length],!0))),o)}function Lo(e,t,i,n){let{url:o,areaCode:a}=e;const{clientId:s,sid:r}=t,c=Date.now();let d;const l=t.role,[u,h]=xo(t,a,[wn.CHOOSE_SERVER]);let _=de.networkState;return Ke((async()=>{_&&de.networkState===ce.OFFLINE&&de.onlineWaiter&&await Promise.race([de.onlineWaiter,_e(n&&n.maxRetryTimeout||Ye.maxRetryTimeout)]),_=de.networkState;const{data:e,headers:a}=await To(o,{data:u,cancelToken:i,headers:{"Content-Type":"multipart/form-data;"}},!0,!0);d="1"===a.http3?1:-1,j.reportResourceTiming(o,r),Uo(e,o,t,c,[wn.CHOOSE_SERVER],d);const s=Mn(e,wn.CHOOSE_SERVER);return Mo(s),Pn(s,o)}),(e=>(e&&j.joinChooseServer(r,{role:l,lts:c,succ:!0,csAddr:o,opid:h,serverList:e.gatewayAddrs.map((e=>e.address)),ec:null,cid:e.cid.toString(),uid:e.uid.toString(),csIp:e.csIp,unilbsServerIds:[wn.CHOOSE_SERVER].toString(),isHttp3:d,corssRegionTagReq:t.apRequestDetail,corssRegionTagRes:e.res.detail&&e.res.detail[38]}),!1)),(e=>e.code!==G.OPERATION_ABORTED&&(e.code===G.CAN_NOT_GET_GATEWAY_SERVER?e.data.retry:(j.joinChooseServer(r,{role:l,lts:c,succ:!1,csAddr:o,serverList:null,opid:h,ec:e.code,csIp:e.data&&e.data.csIp,unilbsServerIds:[wn.CHOOSE_SERVER].toString(),extend:JSON.stringify({networkState:_}),isHttp3:d,corssRegionTagReq:t.apRequestDetail}),B.warning("[".concat(s||"sid-".concat(r.slice(0,6)),"] Choose server network error, retry"),e),!0))),n)}function ko(e,t,i,n){let o,{url:a,areaCode:s,serviceIds:r}=e;const c=Date.now(),d=t.role,[l,u]=xo(t,s,r);let h;return Ke((async()=>{h&&de.networkState===ce.OFFLINE&&de.onlineWaiter&&await Promise.race([de.onlineWaiter,_e(n&&n.maxRetryTimeout||Ye.maxRetryTimeout)]),h=de.networkState;const{data:e,headers:s}=await To(a,{data:l,cancelToken:i,headers:{"Content-Type":"multipart/form-data;"}},!0,!0);o="1"===s.http3?1:-1,j.reportResourceTiming(a,t.sid),Uo(e,a,t,c,r,o);const d=Mn(e,wn.CHOOSE_SERVER),u=Mn(e,"proxy5"===t.cloudProxyServer?wn.CLOUD_PROXY_5:"proxy3"===t.cloudProxyServer||"proxy4"===t.cloudProxyServer?wn.CLOUD_PROXY:wn.CLOUD_PROXY_FALLBACK),_=performance.getEntriesByName(a),p=_[_.length-1];let E;return p&&(E={name:p.name,protocol:"nextHopProtocol"in p?p.nextHopProtocol:"",dnscost:"domainLookupEnd"in p&&"domainLookupStart"in p&&"number"==typeof p.domainLookupEnd&&"number"==typeof p.domainLookupStart?p.domainLookupEnd-p.domainLookupStart:-1,tcpTlsCost:"connectEnd"in p&&"connectStart"in p&&"number"==typeof p.connectEnd&&"number"==typeof p.connectStart?p.connectEnd-p.connectStart:-1,reqCost:"requestStart"in p&&"number"==typeof p.requestStart&&"responseEnd"in p&&"number"==typeof p.responseEnd?p.responseEnd-p.requestStart:-1,handleCost:"leave_ts"in e&&"enter_ts"in e&&"number"==typeof e.leave_ts&&"number"==typeof e.enter_ts?e.leave_ts-e.enter_ts:-1}),Mo(d),{gatewayInfo:Pn(d,a),proxyInfo:u,url:a,resourceTimingInfo:E}}),(e=>(e.gatewayInfo&&j.joinChooseServer(t.sid,{role:d,lts:c,succ:!0,csAddr:a,serverList:e.gatewayInfo.gatewayAddrs.map((e=>e.address)),ec:null,opid:u,cid:e.gatewayInfo.cid.toString(),uid:e.gatewayInfo.uid.toString(),csIp:e.gatewayInfo.csIp,unilbsServerIds:r.toString(),isHttp3:o,corssRegionTagReq:t.apRequestDetail,corssRegionTagRes:e.gatewayInfo.res.detail&&e.gatewayInfo.res.detail[38],resourceTimingInfo:e.resourceTimingInfo?JSON.stringify(e.resourceTimingInfo):void 0}),e.proxyInfo&&j.joinWebProxyAP(t.sid,{lts:c,sucess:1,apServerAddr:a,turnServerAddrList:e.proxyInfo.addresses.map((e=>e.ip)).join(","),errorCode:null,eventType:t.cloudProxyServer,unilbsServerIds:r.toString()}),!1)),(e=>e.code!==G.OPERATION_ABORTED&&(e.code===G.CAN_NOT_GET_GATEWAY_SERVER?e.data.retry:(j.joinWebProxyAP(t.sid,{lts:c,sucess:0,apServerAddr:a,turnServerAddrList:null,errorCode:e.code,eventType:t.cloudProxyServer,unilbsServerIds:r.toString(),extend:JSON.stringify({networkState:h})}),B.warning("[".concat(t.clientId,"] multi unilbs network error, retry"),e),!0))),n)}const Uo=(e,t,i,n,o,a)=>{const{sid:s,clientId:r,cloudProxyServer:c}=i,d=[],l=r=>{4096===r.flag?j.joinChooseServer(s,{role:i.role,lts:n,succ:!1,csAddr:t,opid:e.opid,serverList:null,ec:r.error.message,csIp:r.error.data&&r.error.data.csIp,unilbsServerIds:o.toString(),isHttp3:a,corssRegionTagReq:i.apRequestDetail}):1048576!==r.flag&&4194304!==r.flag&&4194310!==r.flag||j.joinWebProxyAP(s,{lts:n,sucess:0,apServerAddr:t,turnServerAddrList:null,errorCode:r.error.code,eventType:c,unilbsServerIds:o.toString()})};if(e.response_body.forEach((t=>{const i=t.buffer.code;if(23===t.uri&&0===i&&!t.buffer.edges_services)if(4194310===t.buffer.flag)B.warning("no edge services in ap response of proxy fallback, will not set proxy in iceServers"),t.buffer.edges_services=[];else{const i={error:new F(G.CAN_NOT_GET_GATEWAY_SERVER,"no edge services in ap response",{retry:!0,csIp:e.detail[502]}),flag:t.buffer.flag};d.push(i),l(i)}if(0!==i){const n=En(i),o={error:new F(G.CAN_NOT_GET_GATEWAY_SERVER,n.desc,{desc:n.desc,retry:n.retry,csIp:e.detail[502]}),flag:t.buffer.flag};4194310===t.buffer.flag?B.warning(o.error.toString()):d.push(o),l(o)}})),d.length)throw B.warning("[".concat(r||"sid-".concat(s.slice(0,6)),"] multi unilbs ").concat(t," failed, ").concat(d.map((e=>"flag: ".concat(e.flag,", message: ").concat(e.error.message,", retry: ").concat(e.error.data.retry))).join(" | "))),new F(G.CAN_NOT_GET_GATEWAY_SERVER,d.map((e=>"flag: ".concat(e.flag,", message: ").concat(e.error.message))).join(" | "),{retry:!!d.find((e=>e.error.data.retry)),csIp:e.detail[502],desc:[...new Set(d.map((e=>{var t;return null==e||null===(t=e.error)||void 0===t||null===(t=t.data)||void 0===t?void 0:t.desc})).filter((e=>!!e)))]})},Mo=e=>{var t,i,n,o;if(e.addresses&&0===e.addresses.length&&0===e.code)throw new F(G.CAN_NOT_GET_GATEWAY_SERVER,"void gateway address",{retry:!0,csIp:e.detail&&e.detail[502]});ne("AP_AREA")&&(null!==(n=e.detail)&&void 0!==n&&n[23]&&"string"==typeof(null===(o=e.detail)||void 0===o?void 0:o[23])?wo(e.detail[23].toLowerCase()):wo());if(null!==(t=e.detail)&&void 0!==t&&t[19]&&"string"==typeof(null===(i=e.detail)||void 0===i?void 0:i[19])){const t=e.detail[19],i=null==t?void 0:t.split(";");for(let t=0;t<i.length;t++){const n=i[t].trim();e.addresses[t]&&i&&(e.addresses[t].fingerprint=n)}}if(ne("GATEWAY_ADDRESS")&&ne("GATEWAY_ADDRESS").length>0){B.debug("assign gateway address to",ne("GATEWAY_ADDRESS"));const t=ne("GATEWAY_ADDRESS").map((t=>{var i,n;const o=null!==(i=null===(n=e.addresses.find((e=>e.ip===t.ip&&e.port===t.port)))||void 0===n?void 0:n.fingerprint)&&void 0!==i?i:"";return{ip:t.ip,port:t.port,ticket:e.addresses[0]&&e.addresses[0].ticket,fingerprint:o}}));e.addresses=t}},Vo=(e,t)=>{if(e.response_body&&e.response_body.length){const t=e.response_body[0];if(0!==t.buffer.code){const e=En(t.buffer.code);throw new F(G.UPDATE_TICKET_FAILED,"[".concat(t.buffer.code,"]: ").concat(e.desc),{retry:e.retry})}return t.buffer.ticket}throw B.debug("update ticket request received ap response without response body:",t),new F(G.UPDATE_TICKET_FAILED,"cannot find response body from ap response",{retry:!1})},xo=(e,t,i)=>{const n=Math.floor(Math.random()*10**12),o="host"===e.role?"1":"audience"===e.role?"2":void 0,a={appid:e.appId,client_ts:Date.now(),opid:n,sid:e.sid,request_bodies:[{uri:22,buffer:{cname:e.cname,detail:mi(mi(mi({6:e.stringUid,11:t,12:ne("USE_NEW_TOKEN")?"1":void 0},o?{17:o}:{}),{},{22:t},e.apRequestDetail?{33:e.apRequestDetail}:{}),e.apRTM?{26:"RTM2"}:{}),key:e.token,service_ids:i,uid:e.uid||0}}]};a.request_bodies.forEach((t=>{e.multiIP&&e.multiIP.gateway_ip&&(t.buffer.detail[5]=JSON.stringify({vocs_ip:[e.multiIP.uni_lbs_ip],vos_ip:[e.multiIP.gateway_ip]}))}));const s=new FormData;return s.append("request",JSON.stringify(a)),[s,n]},Bo=(e,t)=>{const i=Math.floor(Math.random()*10**12),n={appid:e.appId,client_ts:Date.now(),opid:i,sid:e.sid,request_bodies:[{uri:28,buffer:{cname:e.cname,detail:{1:"",6:e.stringUid,12:"1"},token:e.token,service_ids:t,uid:e.uid||0,edges_services:e.apResponse.addresses.map((e=>({ip:e.ip,port:e.port})))}}]},o=new FormData;return o.append("request",JSON.stringify(n)),[o,i]};function Fo(e){return Promise.all(e.map((e=>e.then((e=>{throw e}),(e=>e))))).then((e=>{throw e}),(e=>e))}const jo=async e=>{let{fragementLength:t,referenceList:i,asyncMapHandler:n,allFailedhandler:o,promisesCollector:a}=e,s=0;const r=t;let c,d=0;const l=async()=>{const e=(()=>{const e=s*r,t=e+r;return i.slice(e,t).map(n)})();a&&a.push(...e);try{c=await Fo(e)}catch(e){if(d+=r,s++,!(d>=i.length))return void await l();o(e)}e.forEach((e=>e.cancel()))};return await l(),c},Go=async e=>{let{referenceList:t,asyncMapHandler:i,closeFn:n}=e;const o=t.length;let a=0;const s=async()=>{const e=i(t.shift());try{return await e}catch(e){if(a++,a>=o||null!=n&&n(e))throw e;return s()}};return s()};async function Wo(){if("undefined"==typeof VideoDecoder)return!0;let e;const t=[18,0,10,13,0,0,0,3,180,253,144,6,136,8,8,8,32,50,85,16,66,128,2,8,32,132,0,8,0,180,90,204,169,166,242,109,241,190,143,149,160,133,4,144,43,122,168,159,120,159,205,39,82,131,57,52,87,187,68,23,248,134,204,226,97,17,49,183,55,236,219,249,221,98,208,215,190,59,179,167,213,47,1,246,150,14,194,245,159,83,35,64,103,218,38,21,82,3,135,21,185,84,248,134],i=[18,0,10,13,0,0,0,3,180,253,144,6,136,8,8,8,32,50,87,16,66,128,2,8,32,132,0,8,0,180,90,204,169,166,242,109,241,190,143,148,62,134,140,92,172,141,77,35,94,181,164,65,169,65,156,154,43,221,162,11,252,67,102,113,48,136,137,219,62,43,113,239,23,126,250,186,252,10,138,218,25,193,244,74,68,194,209,107,23,52,206,199,78,72,98,103,151,71,96,62,51,210,158,72,231,158],n=[18,0,10,13,0,0,0,3,180,253,144,6,136,8,8,8,32,50,87,16,66,128,2,8,32,132,0,8,0,180,90,204,169,166,242,109,241,190,143,143,233,163,51,196,98,95,151,224,22,134,33,240,150,248,67,18,34,196,142,81,238,173,140,80,205,232,132,144,67,12,131,157,4,171,243,86,122,35,6,166,184,243,85,126,13,206,103,152,62,168,160,187,2,241,138,52,211,72,121,128,151,63,147,128,19,42],o=[18,0,50,138,1,48,192,64,253,248,65,17,67,192,32,0,16,0,0,0,0,0,0,0,195,12,48,144,64,32,0,209,75,61,9,204,25,115,79,226,115,63,63,208,70,210,220,153,126,241,237,37,107,195,153,1,99,112,230,189,209,169,130,10,11,22,167,215,159,205,197,7,183,162,26,48,254,141,134,103,32,16,235,45,1,15,18,119,169,110,206,251,51,115,202,60,148,1,46,39,109,25,28,86,168,15,77,211,239,2,58,43,146,26,230,184,81,48,140,226,226,250,222,146,171,133,164,13,188,180,64,122,142,146,32,208,238,170,193,35,53,44,225],a=[18,0,50,107,48,0,133,125,248,65,26,195,64,62,32,31,16,0,0,0,0,0,1,4,16,64,144,64,32,0,204,24,122,65,56,165,18,52,206,218,4,187,51,97,9,29,191,90,253,106,185,31,197,155,52,205,245,185,203,131,20,226,25,124,95,113,220,113,141,15,15,104,211,144,152,237,150,157,127,51,143,24,231,218,171,255,176,241,128,229,149,150,148,66,245,228,91,27,182,228,136,61,182,237,133,45,220,24,103,214,152],s=[18,0,50,122,48,1,9,253,248,65,26,67,64,62,32,31,16,0,0,0,0,0,1,4,16,64,144,64,32,0,198,182,231,242,220,235,163,140,12,36,36,166,46,132,210,4,71,23,218,132,27,30,17,45,244,79,31,243,195,136,100,169,76,88,142,85,204,217,121,168,29,163,198,17,251,223,73,12,212,244,139,123,151,179,75,216,96,208,136,40,229,42,59,149,10,116,228,85,99,93,221,108,255,140,248,20,30,167,122,109,206,164,108,197,110,251,23,243,133,160,63,13,207,177,12,128];return await new Promise(((r,c)=>{let d;!async function(){e&&"closed"!==e.state||await async function(){e=new VideoDecoder({output:e=>{e.close(),clearTimeout(d),r(!0)},error:e=>{clearTimeout(d),r(!1)}}),await e.configure({codec:"av01.0.05M.08",width:160,height:90})}();const c=[t,i,n,o,a,s];for(let t=0;t<c.length;t++){const i=new EncodedVideoChunk({type:0==t?"key":"delta",timestamp:33333*t,duration:33333,data:new Uint8Array(c[t])});try{await e.decode(i)}catch(e){return void r(!1)}}}(),d=setTimeout((()=>{r(!1)}),5e3)}))}async function Ho(e,t,i,n){const o=async function(e,t,i,n){let o=null;const a=[],s=async()=>{const o=ne("WEBCS_DOMAIN").slice(0,ne("AJAX_REQUEST_CONCURRENT")).map((t=>({url:e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(t+"/api/v2/transpond/webrtc?v=2"):"https://".concat(t,"/api/v2/transpond/webrtc?v=2"),areaCode:Io()}))),s=n.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:o.map((e=>e.url))}),r=await jo({fragementLength:ne("FRAGEMENT_LENGTH"),referenceList:o,asyncMapHandler:n=>(B.debug("[".concat(e.clientId,"] Connect to choose_server:"),n.url),Lo(n,e,t,i)),allFailedhandler:e=>{throw n.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},s),e[0]},promisesCollector:a});return n.recordJoinChannelService({endTs:Date.now(),status:"success"},s),r},r=async()=>{if(await _e(1e3),null!==o)return o;const s=ne("WEBCS_DOMAIN_BACKUP_LIST").map((t=>({url:e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(t+"/api/v2/transpond/webrtc?v=2"):"https://".concat(t,"/api/v2/transpond/webrtc?v=2"),areaCode:Io()}))),r=n.recordJoinChannelService({endTs:void 0,startTs:Date.now(),status:"pending",service:"chooseServer",urls:s.map((e=>e.url))}),c=await jo({fragementLength:ne("FRAGEMENT_LENGTH"),referenceList:s,asyncMapHandler:n=>(B.debug("[".concat(e.clientId,"] Connect to backup choose_server:"),n.url),Lo(n,e,t,i)),allFailedhandler:e=>{throw n.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},r),e[0]},promisesCollector:a});return n.recordJoinChannelService({endTs:Date.now(),status:"success"},r),c};try{return o=await Fo([s(),r()]),a.length&&a.forEach((e=>e.cancel&&"function"==typeof e.cancel&&e.cancel())),o}catch(e){throw e[0]}}(e,t,i,n);return{gatewayInfo:await o}}async function Ko(e,t,i,n,o){const a=e.cloudProxyServer;if("disabled"===a){if(!n)return;if(e.useLocalAccessPoint)return await Ho(e,t,i,o);if(ne("JOIN_WITH_FALLBACK_MEDIA_PROXY")){const{gatewayInfo:n,proxyInfo:a}=await zo(e,t,i,o);if(e.turnServer&&"auto"!==e.turnServer.mode)return{gatewayInfo:n};const r=a.map((e=>({turnServerURL:e.address,tcpport:e.tcpport||Te.tcpport,udpport:e.udpport||Te.udpport,username:e.username||Te.username,password:e.password||Te.password,forceturn:!1,security:!0})));if(o.useP2P){var s;const t=null!==(s=e.uid)&&void 0!==s?s:n.uid,i="glb:".concat(t.toString()),o=await Ie(i),c=a.map((e=>({turnServerURL:e.address,tcpport:e.tcpport||Te.tcpport,udpport:e.udpport||Te.udpport,username:i,password:o,forceturn:!1,security:!0})));r.push(...c)}return e.turnServer={mode:"manual",servers:r},{gatewayInfo:n}}return await Ho(e,t,i,o)}const{proxyInfo:r,gatewayInfo:c}=await zo(e,t,i,o),d={gatewayInfo:c},l=r.map((e=>({turnServerURL:e.address,tcpport:"proxy3"===a?void 0:e.tcpport?e.tcpport:Te.tcpport,udpport:"proxy4"===a?void 0:e.udpport?e.udpport:Te.udpport,username:e.username||Te.username,password:e.password||Te.password,forceturn:"proxy4"!==a,security:"proxy5"===a})));if(o.useP2P){var u;const t=null!==(u=e.uid)&&void 0!==u?u:c.uid,i="glb:".concat(t.toString()),n=await Ie(i),o=r.map((e=>({turnServerURL:e.address,tcpport:"proxy3"===a?void 0:e.tcpport||Te.tcpport,udpport:"proxy4"===a?void 0:e.udpport||Te.udpport,username:i,password:n,forceturn:"proxy4"!==a,security:"proxy5"===a})));l.push(...o)}return e.turnServer={mode:"manual",servers:l},B.debug("[".concat(e.clientId,"] set proxy server: ").concat(e.proxyServer,", mode: ").concat(a)),d}async function Yo(e,t,i,n,o){const a=ne("ACCOUNT_REGISTER").slice(0,ne("AJAX_REQUEST_CONCURRENT"));let s=[];s=t.proxyServer?a.map((e=>"https://".concat(t.proxyServer,"/ap/?url=").concat(e+"/api/v1"))):a.map((e=>"https://".concat(e,"/api/v1")));const r=null==o?void 0:o.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"stringUID",urls:s});try{const a=await async function(e,t,i,n,o){const a=Date.now(),s={sid:i.sid,opid:10,appid:i.appId,string_uid:t};let r=e[0];const c=await Ke((()=>To(r+"".concat(-1===r.indexOf("?")?"?":"&","action=stringuid"),{data:s,cancelToken:n,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":72}})),((i,n)=>{if(0===i.code){if(i.uid<=0||i.uid>=Math.pow(2,32))throw B.error("Invalid Uint Uid ".concat(t," => ").concat(i.uid),i),j.reqUserAccount(s.sid,{lts:a,success:!1,serverAddr:r,stringUid:s.string_uid,uid:i.uid,errorCode:G.INVALID_UINT_UID_FROM_STRING_UID,extend:s}),new F(G.INVALID_UINT_UID_FROM_STRING_UID);return j.reqUserAccount(s.sid,{lts:a,success:!0,serverAddr:r,stringUid:s.string_uid,uid:i.uid,errorCode:null,extend:s}),!1}const o=En(i.code);return o.retry&&(r=e[(n+1)%e.length]),j.reqUserAccount(s.sid,{lts:a,success:!1,serverAddr:r,stringUid:s.string_uid,uid:i.uid,errorCode:o.desc,extend:s}),o.retry}),((t,i)=>t.code!==G.OPERATION_ABORTED&&(j.reqUserAccount(s.sid,{lts:a,success:!1,serverAddr:r,stringUid:s.string_uid,uid:null,errorCode:t.code,extend:s}),r=e[(i+1)%e.length],!0)),o);if(0!==c.code){const e=En(c.code);throw new F(G.UNEXPECTED_RESPONSE,e.desc)}return c}(s,e,t,i,n);return null==o||o.recordJoinChannelService({status:"success",endTs:Date.now()},r),a.uid}catch(e){throw null==o||o.recordJoinChannelService({status:"error",endTs:Date.now(),errors:[e]},r),e}}async function qo(e,t,i){const n=ne("ACCOUNT_REGISTER");let o=[];o=t.proxyServer?n.map((e=>"https://".concat(t.proxyServer,"/ap/?url=").concat(e+"/api/v1"))):n.map((e=>"https://".concat(e,"/api/v1")));try{const n=await Go({referenceList:o,asyncMapHandler:n=>async function(e,t,i,n){const o=Date.now(),a={sid:i.sid,opid:10,appid:i.appId,string_uid:t};try{const t=await To(e+"".concat(-1===e.indexOf("?")?"?":"&","action=stringuid"),{data:a,cancelToken:n,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":72}});if(0!==t.code){const e=En(t.code);throw new F(G.UNEXPECTED_RESPONSE,"preload sua error:".concat(e.desc),e)}if(t.uid<=0||t.uid>=Math.pow(2,32))throw new F(G.INVALID_UINT_UID_FROM_STRING_UID);return{requestTime:o,url:e,req:a,uid:t.uid,elapse:Date.now()-o}}catch(e){throw e}}(n,e,t,i),closeFn:e=>e.code===Z.OPERATION_ABORTED||e.code===Z.UNEXPECTED_RESPONSE&&!e.data.retry});return n}catch(e){throw e}}async function Xo(e,t,i){const n=ne("CDS_AP").slice(0,ne("AJAX_REQUEST_CONCURRENT")).map((t=>e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(t+"/api/v1"):"https://".concat(t,"/api/v1?action=config"))).map((n=>function(e,t,i,n){const o=Ne(),a={flag:64,cipher_method:0,features:mi(mi(mi(mi(mi({install_id:qe(),device:o.name,system:o.os,system_general:navigator.userAgent,vendor:t.appId,version:xe,cname:t.cname,session_id:t.sid,proxyServer:t.proxyServer,sdk_type:bn.WEB_RTC,browser_name:o.name,browser_version:o.version,user_agent:navigator.userAgent,channel_name:t.cname},t.stringUid&&{string_uid:t.stringUid}),t.uid&&{uid:t.uid+""}),o.os&&{os_name:o.os}),o.osVersion&&{os_version:o.osVersion}),{},{detail:""})};return Ke((()=>To(e,{data:a,timeout:1e3,cancelToken:i,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":54}})),void 0,(e=>e.code!==G.OPERATION_ABORTED),n)}(n,e,t,i)));let o=null,a=null,s={};try{o=await Fo(n)}catch(e){if(e.code===Z.OPERATION_ABORTED)throw e;a=e}n.forEach((e=>e.cancel()));if(j.reportApiInvoke(e.sid,{name:We.REQUEST_CONFIG_DISTRIBUTE,options:{error:a,res:o}}).onSuccess(),o&&o.test_tags)try{s=function(e){if(!e.test_tags)return{};const t=e.test_tags,i=Object.keys(t),n={};return i.forEach((e=>{const i=e.slice(4).trim(),o=JSON.parse(t[e]),a=o[1];n[i]={tag:o[0]||"",value:a}})),n}(o)}catch(e){}return s}async function Jo(e,t){const i=ne("WEBCS_DOMAIN").concat(ne("WEBCS_DOMAIN_BACKUP_LIST")).map((e=>({url:"https://".concat(e,"/api/v2/transpond/webrtc?v=2"),areaCode:Io(),serviceIds:[wn.CHOOSE_SERVER,wn.CLOUD_PROXY_FALLBACK]})));try{const n=await Go({referenceList:i,asyncMapHandler:i=>async function(e,t,i){let n,{url:o,areaCode:a,serviceIds:s}=e;const r=Date.now(),[c,d]=xo(t,a,s);let l=de.networkState;try{l&&de.networkState===ce.OFFLINE&&de.onlineWaiter&&await Promise.race([de.onlineWaiter,_e(Ye.maxRetryTimeout)]),l=de.networkState;const{data:e,headers:t}=await To(o,{data:c,cancelToken:i,headers:{"Content-Type":"multipart/form-data;"}},!0,!0);n="1"===t.http3?1:-1,(e=>{const t=[];if(e.response_body.forEach((i=>{const n=i.buffer.code;if(23===i.uri&&0===n&&!i.buffer.edges_services)if(4194310===i.buffer.flag)i.buffer.edges_services=[];else{const n={error:new F(G.CAN_NOT_GET_GATEWAY_SERVER,"no edge services in ap response",{retry:!0,csIp:e.detail[502]}),flag:i.buffer.flag};t.push(n)}if(0!==n){const o=En(n),a={error:new F(G.CAN_NOT_GET_GATEWAY_SERVER,o.desc,{desc:o.desc,retry:o.retry,csIp:e.detail[502]}),flag:i.buffer.flag};4194310===i.buffer.flag?B.warning(a.error.toString()):t.push(a)}})),t.length)throw new F(G.CAN_NOT_GET_GATEWAY_SERVER,t.map((e=>"flag: ".concat(e.flag,", message: ").concat(e.error.message))).join(" | "),{retry:!!t.find((e=>e.error.data.retry)),csIp:e.detail[502],desc:[...new Set(t.map((e=>{var t;return null==e||null===(t=e.error)||void 0===t||null===(t=t.data)||void 0===t?void 0:t.desc})).filter((e=>!!e)))]})})(e);const a=Mn(e,wn.CHOOSE_SERVER),s=Mn(e,wn.CLOUD_PROXY_FALLBACK);return Mo(a),{gatewayInfo:Pn(a,o),proxyInfo:s,opid:d,requestTime:r,url:o,isHttp3:n,elapse:Date.now()-r}}catch(e){throw e}}(i,e,t),closeFn:e=>e.code===Z.OPERATION_ABORTED||e.code===Z.CAN_NOT_GET_GATEWAY_SERVER&&!e.data.retry});return n}catch(e){throw e}}async function zo(e,t,i,n){const o=ne("PROXY_SERVER_TYPE3"),a=(e,t,i)=>{let n=i||o;return Array.isArray(n)&&(n=t%2==0&&o[1]||o[0]),"https://".concat(n,"/ap/?url=").concat(e)};let s=null;const r=[],c=async()=>{const o=ne("WEBCS_DOMAIN").slice(0,ne("AJAX_REQUEST_CONCURRENT")).map(((t,i)=>{let n;return n="disabled"===e.cloudProxyServer&&e.proxyServer?a("".concat(t,"/api/v2/transpond/webrtc?v=2"),i,e.proxyServer):"disabled"===e.cloudProxyServer||"fallback"===e.cloudProxyServer?"https://".concat(t,"/api/v2/transpond/webrtc?v=2"):a("".concat(t,"/api/v2/transpond/webrtc?v=2"),i),{url:n,areaCode:Io(),serviceIds:[wn.CHOOSE_SERVER,"proxy5"===e.cloudProxyServer?wn.CLOUD_PROXY_5:"proxy3"===e.cloudProxyServer||"proxy4"===e.cloudProxyServer?wn.CLOUD_PROXY:wn.CLOUD_PROXY_FALLBACK]}})),s=n.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:o.map((e=>e.url))}),c=await jo({fragementLength:ne("FRAGEMENT_LENGTH"),referenceList:o,asyncMapHandler:n=>(B.debug("[".concat(e.clientId,"] Connect to choose_server:"),n.url),ko(n,e,t,i)),allFailedhandler:e=>{throw n.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},s),e[0]},promisesCollector:r});return n.recordJoinChannelService({endTs:Date.now(),status:"success"},s),c},d=async()=>{if(await _e(1e3),null!==s)return s;const o=ne("WEBCS_DOMAIN_BACKUP_LIST").map(((t,i)=>{let n;return n="disabled"===e.cloudProxyServer&&e.proxyServer?a("".concat(t,"/api/v2/transpond/webrtc?v=2"),i,e.proxyServer):"disabled"===e.cloudProxyServer||"fallback"===e.cloudProxyServer?"https://".concat(t,"/api/v2/transpond/webrtc?v=2"):a("".concat(t,"/api/v2/transpond/webrtc?v=2"),i),{url:n,areaCode:Io(),serviceIds:[wn.CHOOSE_SERVER,"proxy5"===e.cloudProxyServer?wn.CLOUD_PROXY_5:"proxy3"===e.cloudProxyServer||"proxy4"===e.cloudProxyServer?wn.CLOUD_PROXY:wn.CLOUD_PROXY_FALLBACK]}})),c=n.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:o.map((e=>e.url))}),d=await jo({fragementLength:ne("FRAGEMENT_LENGTH"),referenceList:o,asyncMapHandler:n=>(B.debug("[".concat(e.clientId,"] Connect to backup choose_server:"),n.url),ko(n,e,t,i)),allFailedhandler:e=>{throw n.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},c),e[0]},promisesCollector:r});return n.recordJoinChannelService({endTs:Date.now(),status:"success"},c),d};let l,u,h;try{({gatewayInfo:l,proxyInfo:u,url:h}=await Fo([c(),d()]))}catch(e){throw e[0]}if(r.length&&r.forEach((e=>e.cancel&&"function"==typeof e.cancel&&e.cancel())),!l||!u)throw new F(Z.UNEXPECTED_ERROR,"missing gateway or proxy response").print();if(e.apUrl=h,"disabled"!==e.cloudProxyServer&&Array.isArray(o)&&h){const t=/^https?:\/\/(.+?)(\/.*)?$/.exec(h)[1];o.includes(t)&&(e.proxyServer=t,B.setProxyServer(t),j.setProxyServer(t))}return s={gatewayInfo:l,proxyInfo:await Vn(u,l.uid)},s}async function Qo(e,t,i){let n=null;const o=[],a=async a=>{const s=ne(a?"WEBCS_DOMAIN_BACKUP_LIST":"WEBCS_DOMAIN").map((t=>e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(t+"/api/v2/transpond/webrtc?v=2"):"https://".concat(t,"/api/v2/transpond/webrtc?v=2")));return a&&(await _e(1e3),null!==n)?n:await jo({fragementLength:ne("FRAGEMENT_LENGTH"),referenceList:s,asyncMapHandler:n=>(B.debug("[".concat(e.clientId,"] update ticket, Connect to ").concat(a?"backup":""," choose_server:"),n),function(e,t,i,n){const[o]=Bo(t,[wn.CHOOSE_SERVER]);let a=de.networkState;return Ke((async()=>{a&&de.networkState===ce.OFFLINE&&de.onlineWaiter&&await Promise.race([de.onlineWaiter,_e(n&&n.maxRetryTimeout||Ye.maxRetryTimeout)]),a=de.networkState;const t=await To(e,{data:o,cancelToken:i,headers:{"Content-Type":"multipart/form-data;"}},!0);return Vo(t,e)}),(()=>!1),(e=>e.code!==G.OPERATION_ABORTED&&(e.code===G.UPDATE_TICKET_FAILED?e.data.retry:(B.warning("[".concat(t.clientId,"] update ticket network error, retry"),e),!0))),n)}(n,e,t,i)),allFailedhandler:e=>{throw e[0]},promisesCollector:o})};try{return n=await Fo([a(!1),a(!0)]),o.length&&o.forEach((e=>e.cancel&&"function"==typeof e.cancel&&e.cancel())),n}catch(e){throw e[0]}}class Zo extends ie{get isSuccess(){return!!this.configs}constructor(e,t){super(),this.configs=void 0,this.store=void 0,this.joinInfo=void 0,this.cancelToken=void 0,this.retryConfig={timeout:3e3,timeoutFactor:1.5,maxRetryCount:1,maxRetryTimeout:1e4},this.interval=void 0,this.mutex=void 0,this.mutableParamsRead=!1,this.configCache={},this.limit_bitrate=void 0,this.mutex=new re("config-distribute",e),this.store=t}startGetConfigDistribute(e,t){this.joinInfo=e,this.cancelToken=t,this.interval&&this.stopGetConfigDistribute(),ne("ENABLE_CONFIG_DISTRIBUTE")&&(this.updateConfigDistribute(),this.interval=window.setInterval((()=>{this.updateConfigDistribute()}),ne("CONFIG_DISTRIBUTE_INTERVAL")))}stopGetConfigDistribute(){this.interval&&clearInterval(this.interval),this.interval=void 0,this.joinInfo=void 0,this.cancelToken=void 0,this.configs=void 0,this.limit_bitrate=void 0}async awaitConfigDistributeComplete(){if(!this.mutex.isLocked)return;(await this.mutex.lock())()}async updateConfigDistribute(){if(!this.mutableParamsRead){this.mutableParamsRead=!0;j.reportApiInvoke(null,{options:void 0,name:We.LOAD_CONFIG_FROM_LOCALSTORAGE,tag:He.TRACER}).onSuccess(JSON.stringify(X))}if(!this.joinInfo||!this.cancelToken||!this.retryConfig)return void B.debug("[config-distribute] get config distribute interrupted have no joininfo");let e;const t=await this.mutex.lock();try{e=await Xo(this.joinInfo,this.cancelToken,this.retryConfig),B.debug("[config-distribute] get config distribute",JSON.stringify(e));const i=function(e){const t=Object.keys(e).filter((e=>/^webrtc_ng_global_parameter/.test(e))).sort();for(let i=0;i<t.length;i++)for(let n=t.length-1;n>i;n--){const i=t[n],o=e[i].value;if("number"==typeof o.__priority){const a=o.__priority,s=t[n-1],r=e[s].value;if("number"==typeof r.__priority){if(!(a>r.__priority))continue;{const e=i;t[n]=t[n-1],t[n-1]=e}}else{const e=i;t[n]=t[n-1],t[n-1]=e}}}const i=Date.now();let n={};return t.forEach((t=>{const o=e[t].value.__expires;o&&o<=i||(n[t]=e[t])})),n}(e);this.cacheGlobalParameterConfig(i),this.store.hasStartJoinChannel||(this.store.isABTestSuccess=!0),this.configs=i}catch(e){const t=new F(Z.NETWORK_RESPONSE_ERROR,e);B.warning("[config-distribute] ".concat(t.toString()))}finally{t()}}getBitrateLimit(){return this.limit_bitrate||void 0}handleBitrateLimit(e){Ji(e)&&(this.limit_bitrate?this.limit_bitrate&&this.limit_bitrate.id!==e.id&&this.emit(Xi.UPDATE_BITRATE_LIMIT,e):this.emit(Xi.UPDATE_BITRATE_LIMIT,e))}getLowStreamConfigDistribute(){return this.limit_bitrate&&mi({},this.limit_bitrate.low_stream_uplink)}handleABTestConfigDistribute(e){try{const t={},i=Object.keys(e),n=[];i.forEach((i=>{const o=e[i].value;t[i]=o;const a=o.__id;if(a&&this.configCache[i]&&this.configCache[i].__id===a)return;const s=o.__type,r=e[i].value,c=e[i].tag;let d=0;s?s===z.REALTIME&&(d=1):Object.keys(r).some((e=>Object.prototype.hasOwnProperty.call(Q,e)||!ci()&&Object.prototype.hasOwnProperty.call(J,e)?(d=1,!0):void 0)),n.push({tag:c,isApplied:d,feature:i,params:JSON.stringify(o)})})),n.forEach((e=>{let{tag:t,feature:i,params:n,isApplied:o}=e;this.store.sessionId&&j.abTest(this.store.sessionId,{intSucc:1,isApplied:o,tag:t,feature:i,params:n,cid:this.store.cid,uid:this.store.intUid})})),this.configCache=t}catch(e){B.debug("handleABTestConfigDistribute error",e)}}cacheGlobalParameterConfig(e){const t=function(e){const t={};return Object.keys(e).forEach((i=>{const n=e[i].value,o=n.__expires,a=n.__type;Object.keys(n).forEach((e=>{"__id"===e||"__type"===e||"__priority"===e||"__expires"===e||Object.prototype.hasOwnProperty.call(t,e)||(t[e]=mi(mi({value:n[e]},o&&{expires:o}),a&&{type:a}))}))})),t}(e);try{var i;const n=null===(i=t.LIMIT_BITRATE)||void 0===i?void 0:i.value;delete t.LIMIT_BITRATE,n&&Ji(n)&&this.handleBitrateLimit(n),this.limit_bitrate=n,this.handleGlobalParameterConfig(t),this.handleABTestConfigDistribute(e),function(e){try{const t=Date.now();Object.keys(e).forEach((i=>{const{value:n,type:o,expires:a}=e[i];a&&a<=t||((o===z.REALTIME||Object.prototype.hasOwnProperty.call(Q,i))&&(X[i]=n,q[i]=n,B.debug("Update realtime parameters from config distribute",i,n)),o||ci()||!Object.prototype.hasOwnProperty.call(J,i)||(X[i]=n,q[i]=n,B.debug("Update gateway parameters from config distribute",i,n)))}))}catch(t){B.error("Error update config immediately: ".concat(e),t.message)}}(t);const o=JSON.stringify(t),a=window.btoa(o);window.localStorage.setItem("websdk_ng_global_parameter",a),B.debug("Caching global parameters ".concat(o))}catch(e){B.error("Error caching global parameters:",e.message)}}handleGlobalParameterConfig(e){try{const t=Date.now();Object.keys(e).forEach((i=>{if("CLIENT_ROLE_OPTIONS"===i)if(Object.prototype.hasOwnProperty.call(q,i)){const{value:n,expires:o}=e[i];if(o&&o<=t)return;Xe(q[i],n)||(X[i]=n,q[i]=n,this.emit(Xi.UPDATE_CLIENT_ROLE_OPTIONS,n),B.debug("Updating client role options: ".concat(JSON.stringify(n))))}}))}catch(e){B.error("Error handling global parameter config:",e.message)}}}class $o extends ie{constructor(){super(...arguments),this.resultStorage=new Map}setLocalAudioStats(e,t,i){this.record("AUDIO_INPUT_LEVEL_TOO_LOW",e,this.checkAudioInputLevel(i,t)),this.record("SEND_AUDIO_BITRATE_TOO_LOW",e,this.checkSendAudioBitrate(i,t))}setLocalVideoStats(e,t,i){this.record("SEND_VIDEO_BITRATE_TOO_LOW",e,this.checkSendVideoBitrate(i,t)),this.record("FRAMERATE_INPUT_TOO_LOW",e,this.checkFramerateInput(i,t)),this.record("FRAMERATE_SENT_TOO_LOW",e,this.checkFramerateSent(i)),!t.muted&&this.record("VIDEO_ENCODE_FAILED",e,this.checResolutionSent(i))}setRemoteAudioStats(e,t){const i=e.getUserId();this.record("AUDIO_OUTPUT_LEVEL_TOO_LOW",i,this.checkAudioOutputLevel(t))}setRemoteVideoStats(e,t){const i=e.getUserId();this.record("RECV_VIDEO_DECODE_FAILED",i,this.checkVideoDecode(t))}record(e,t,i){if(ne("STATS_UPDATE_INTERVAL")>500)return;this.resultStorage.has(e)||this.resultStorage.set(e,{result:[],isPrevNormal:!0});const n=this.resultStorage.get(e);if(!n)return;n.result.push(i);const o="VIDEO_ENCODE_FAILED"===e?ne("ENCODE_EXCEPTION_TIMES"):5;if(n.result.length>=o){const i=n.result.includes(!0);n.isPrevNormal&&!i&&this.emit("exception",ea[e],e,t),!n.isPrevNormal&&i&&this.emit("exception",ea[e]+2e3,e+"_RECOVER",t),n.isPrevNormal=i,n.result=[]}}checkAudioOutputLevel(e){return!(e.receiveBitrate>0&&0===e.receiveLevel)}checkAudioInputLevel(e,t){return t instanceof l&&!t.isActive||(!!t.muted||0!==e.sendVolumeLevel)}checkFramerateInput(e,t){let i=null;t._encoderConfig&&t._encoderConfig.frameRate&&(i=Ln(t._encoderConfig.frameRate));const n=e.captureFrameRate;return!i||!n||!(i>10&&n<5||i<10&&i>=5&&n<=1)}checkFramerateSent(e){return!(e.captureFrameRate&&e.sendFrameRate&&e.captureFrameRate>5&&e.sendFrameRate<=1)}checResolutionSent(e){return!(!e.codecType||ne("ENCODE_EXCEPTION_VALIDATE_CODEC").includes(e.codecType.toLocaleLowerCase()))||(!e.captureFrameRate||0!==e.sendFrameRate||0!==e.sendResolutionWidth||0!==e.sendResolutionHeight)}checkSendVideoBitrate(e,t){return!!t.muted||0!==e.sendBitrate}checkSendAudioBitrate(e,t){return t instanceof l&&!t.isActive||(!!t.muted||0!==e.sendBitrate)}checkVideoDecode(e){return 0===e.receiveBitrate||0!==e.decodeFrameRate}}const ea={FRAMERATE_INPUT_TOO_LOW:1001,FRAMERATE_SENT_TOO_LOW:1002,SEND_VIDEO_BITRATE_TOO_LOW:1003,RECV_VIDEO_DECODE_FAILED:1005,AUDIO_INPUT_LEVEL_TOO_LOW:2001,AUDIO_OUTPUT_LEVEL_TOO_LOW:2002,SEND_AUDIO_BITRATE_TOO_LOW:2003,VIDEO_ENCODE_FAILED:2004};const ta=new class{markSubscribeStart(e,t){performance.mark("agora-web-sdk/".concat(e,"/subscribe-").concat(t))}markPublishStart(e,t){performance.mark("agora-web-sdk/".concat(e,"/publish-").concat(t))}measureFromSubscribeStart(e,t){const i=performance.getEntriesByName("agora-web-sdk/".concat(e,"/subscribe-").concat(t));if(i.length>0){const e=i[i.length-1];return Math.round(performance.now()-e.startTime)}return 0}measureFromPublishStart(e,t){const i=performance.getEntriesByName("agora-web-sdk/".concat(e,"/publish-").concat(t));if(i.length>0){const e=i[i.length-1];return Math.round(performance.now()-e.startTime)}return 0}};class ia{constructor(e){this.store=void 0,this.onStatsException=void 0,this.onUploadPublishDuration=void 0,this.onStatsChanged=void 0,this.onVideoCodecChanged=void 0,this.localStats=new Map,this.remoteStats=new Map,this.updateStatsInterval=void 0,this.trafficStats=void 0,this.trafficStatsPeerList=[],this.uplinkStats=void 0,this.exceptionMonitor=void 0,this.p2pChannel=void 0,this.scalabilityMode=Ae.L1T1,this.updateStats=()=>{this.p2pChannel&&(this.updateRemoteStats(this.p2pChannel),this.updateLocalStats(this.p2pChannel))},this.store=e,this.exceptionMonitor=new $o,this.exceptionMonitor.on("exception",((e,t,i)=>{this.onStatsException&&this.onStatsException(e,t,i)}))}startUpdateStats(){this.updateStatsInterval||(this.updateStatsInterval=window.setInterval(this.updateStats,1e3))}stopUpdateStats(){this.updateStatsInterval&&(window.clearInterval(this.updateStatsInterval),this.updateStatsInterval=void 0)}reset(){this.localStats=new Map,this.remoteStats=new Map,this.trafficStats=void 0,this.trafficStatsPeerList=[],this.uplinkStats=void 0}getLocalAudioTrackStats(){return this.localStats.get(nn.LocalAudioTrack)||mi({},u)}getLocalVideoTrackStats(){return this.localStats.get(nn.LocalVideoTrack)||mi({},h)}getRemoteAudioTrackStats(e){const t=(e,t)=>{if(!this.trafficStats)return t;const i=this.trafficStats.peer_delay.find((t=>t.peer_uid===e));return i&&(t.publishDuration=i.B_ppad+(Date.now()-this.trafficStats.timestamp)),t},i={};if(e){var n;const o=null===(n=this.remoteStats.get(e))||void 0===n?void 0:n.audioStats;o&&(i[e]=t(e,o))}else Array.from(this.remoteStats.entries()).forEach((e=>{let[n,{audioStats:o}]=e;o&&(i[n]=t(n,o))}));return i}getRemoteNetworkQualityStats(e){const t={};if(e){var i;const n=null===(i=this.remoteStats.get(e))||void 0===i?void 0:i.networkStats;n&&(t[e]=n)}else Array.from(this.remoteStats.entries()).forEach((e=>{let[i,{networkStats:n}]=e;n&&(t[i]=n)}));return t}getRemoteVideoTrackStats(e){const t=(e,t)=>{if(!this.trafficStats)return t;const i=this.trafficStats.peer_delay.find((t=>t.peer_uid===e));return i&&(t.publishDuration=i.B_ppvd+(Date.now()-this.trafficStats.timestamp)),t},i={};if(e){var n;const o=null===(n=this.remoteStats.get(e))||void 0===n?void 0:n.videoStats;o&&(i[e]=t(e,o))}else Array.from(this.remoteStats.entries()).forEach((e=>{let[n,{videoStats:o}]=e;o&&(i[n]=t(n,o))}));return i}getRTCStats(){let e=0,t=0,i=0,n=0;const o=this.localStats.get(nn.LocalAudioTrack);o&&(e+=o.sendBytes,t+=o.sendBitrate);const a=this.localStats.get(nn.LocalVideoTrack);a&&(e+=a.sendBytes,t+=a.sendBitrate);const s=this.localStats.get(nn.LocalVideoLowTrack);s&&(e+=s.sendBytes,t+=s.sendBitrate),this.remoteStats.forEach((e=>{let{audioStats:t,videoStats:o}=e;t&&(i+=t.receiveBytes,n+=t.receiveBitrate),o&&(i+=o.receiveBytes,n+=o.receiveBitrate)}));let r=1;return this.trafficStats&&(r+=this.trafficStats.peer_delay.length),{Duration:0,UserCount:r,SendBitrate:t,SendBytes:e,RecvBytes:i,RecvBitrate:n,OutgoingAvailableBandwidth:this.uplinkStats?this.uplinkStats.B_uab/1e3:0,RTT:this.trafficStats?2*this.trafficStats.B_acd:0}}addLocalStats(e){this.localStats.set(e,void 0)}removeLocalStats(e){e?this.localStats.delete(e):this.localStats.clear()}addRemoteStats(e){this.remoteStats.set(e,{})}removeRemoteStats(e){e?this.remoteStats.delete(e):this.remoteStats.clear()}addP2PChannel(e){this.p2pChannel=e}updateTrafficStats(e){e.peer_delay=e.peer_delay.filter((e=>void 0!==e.B_ppad||void 0!==e.B_ppvd));e.peer_delay.filter((e=>-1===this.trafficStatsPeerList.indexOf(e.peer_uid))).forEach((e=>{var t;const i=null===(t=this.p2pChannel)||void 0===t?void 0:t.getRemoteMedia(e.peer_uid),n=null!=i&&i.videoSSRC?ta.measureFromSubscribeStart(this.store.clientId,i.videoSSRC):0,o=null!=i&&i.audioSSRC?ta.measureFromSubscribeStart(this.store.clientId,i.audioSSRC):0;void 0!==e.B_ppad&&void 0!==e.B_ppvd&&(this.onUploadPublishDuration&&this.onUploadPublishDuration(e.peer_uid,e.B_ppad,e.B_ppvd,n>o?n:o),this.trafficStatsPeerList.push(e.peer_uid))})),this.trafficStats=e}updateUplinkStats(e){this.uplinkStats&&this.uplinkStats.B_fir!==e.B_fir&&B.debug("[".concat(this.store.clientId,"]: Period fir changes to ").concat(e.B_fir)),this.uplinkStats=e}static isRemoteVideoFreeze(e,t,i){if(!e)return!1;const n=!!i&&t.framesDecodeFreezeTime>i.framesDecodeFreezeTime,o=!i||t.framesDecodeCount>i.framesDecodeCount;return n||!o}static isRemoteAudioFreeze(e){return!!e&&e._isFreeze()}isLocalVideoFreeze(e){return!(!e.inputFrame||!e.sentFrame)&&(e.inputFrame.frameRate>5&&e.sentFrame.frameRate<3)}updateLocalStats(e){Array.from(this.localStats.entries()).forEach((t=>{let[i,n]=t;switch(i){case nn.LocalVideoTrack:case nn.LocalVideoLowTrack:{const t=n,s=mi({},h),r=e.getStats(),c=e.getLocalMedia(i);if(r){const i=r.videoSend.find((e=>e.ssrc===(null==c?void 0:c.ssrcs[0].ssrcId)));if(i){const n=e.getLocalVideoSize(),a=e.getEncoderConfig(nn.LocalVideoTrack);var o;if("H264"===i.codec||"H265"===i.codec||"VP8"===i.codec||"VP9"===i.codec||"AV1X"===i.codec||"AV1"===i.codec)if(s.codecType=i.codec,(null==t?void 0:t.codecType)!==i.codec)null===(o=this.onVideoCodecChanged)||void 0===o||o.call(this,i.codec.toLocaleLowerCase());s.sendBytes=i.bytes,s.sendBitrate=t?8*Math.max(0,s.sendBytes-t.sendBytes):0,i.inputFrame?(s.captureFrameRate=i.inputFrame.frameRate,s.captureResolutionHeight=i.inputFrame.height,s.captureResolutionWidth=i.inputFrame.width):n&&(s.captureResolutionWidth=n.width,s.captureResolutionHeight=n.height),i.sentFrame?(s.sendFrameRate=i.sentFrame.frameRate,s.sendResolutionHeight=i.sentFrame.height,s.sendResolutionWidth=i.sentFrame.width):n&&(s.sendResolutionWidth=n.width,s.sendResolutionHeight=n.height),i.avgEncodeMs&&(s.encodeDelay=i.avgEncodeMs),a&&a.bitrateMax?s.targetSendBitrate=1e3*a.bitrateMax:i.targetBitrate&&(s.targetSendBitrate=i.targetBitrate),s.sendPackets=i.packets,s.sendPacketsLost=i.packetsLost,s.sendJitterMs=i.jitterMs,s.sendRttMs=i.rttMs,s.totalDuration=t?t.totalDuration+1:1,s.totalFreezeTime=t?t.totalFreezeTime:0,this.isLocalVideoFreeze(i)&&(s.totalFreezeTime+=1),i.scalabilityMode&&this.scalabilityMode!==i.scalabilityMode&&(B.debug("[".concat(this.store.clientId,"]: The scalabilityMode of the video sending stream is ").concat(i.scalabilityMode)),this.scalabilityMode=i.scalabilityMode)}this.trafficStats&&(s.currentPacketLossRate=(this.trafficStats.B_pvlr4||0)/100)}var a;if(this.localStats.set(i,s),(null==t?void 0:t.sendResolutionWidth)!==s.sendResolutionWidth||(null==t?void 0:t.sendResolutionHeight)!==s.sendResolutionHeight)null===(a=this.onStatsChanged)||void 0===a||a.call(this,"resolution",{width:s.sendResolutionWidth,height:s.sendResolutionHeight});s&&c&&this.exceptionMonitor.setLocalVideoStats(this.store.uid,c.track,s);break}case nn.LocalAudioTrack:{const t=n,o=mi({},u),a=e.getStats(),s=e.getLocalMedia(i);if(a){const i=a.audioSend.find((e=>e.ssrc===(null==s?void 0:s.ssrcs[0].ssrcId)));if(i){if("opus"!==i.codec&&"aac"!==i.codec&&"PCMU"!==i.codec&&"PCMA"!==i.codec&&"G722"!==i.codec||(o.codecType=i.codec),i.inputLevel)o.sendVolumeLevel=Math.round(32767*i.inputLevel);else{const t=e.getLocalAudioVolume();t&&(o.sendVolumeLevel=Math.round(32767*t))}o.sendBytes=i.bytes,o.sendPackets=i.packets,o.sendPacketsLost=i.packetsLost,o.sendJitterMs=i.jitterMs,o.sendRttMs=i.rttMs,o.sendBitrate=t?8*Math.max(0,o.sendBytes-t.sendBytes):0}}this.trafficStats&&(o.currentPacketLossRate=(this.trafficStats.B_palr4||0)/100),this.localStats.set(nn.LocalAudioTrack,o),o&&s&&this.exceptionMonitor.setLocalAudioStats(this.store.uid,s.track,o);break}}}))}updateRemoteStats(e){Array.from(this.remoteStats.entries()).forEach((t=>{var i,n;let[o,{videoStats:a,audioStats:s,videoPcStats:r}]=t;const c=s,d=a,l=r,u=mi({},_),h=mi({},p),S=mi({},E),{audioTrack:m,videoTrack:R,audioSSRC:f,videoSSRC:C}=e.getRemoteMedia(o);let T;T=this.store.useP2P?e.getStats(!0):e.getStats();const I=null===(i=T)||void 0===i?void 0:i.audioRecv.find((e=>e.ssrc===f)),A=null===(n=T)||void 0===n?void 0:n.videoRecv.find((e=>e.ssrc===C)),g=this.trafficStats&&this.trafficStats.peer_delay.find((e=>e.peer_uid===o));if(I&&("opus"!==I.codec&&"aac"!==I.codec&&"PCMU"!==I.codec&&"PCMA"!==I.codec&&"G722"!==I.codec||(u.codecType=I.codec),I.outputLevel?u.receiveLevel=Math.round(32767*I.outputLevel):m&&(u.receiveLevel=Math.round(32767*m.getVolumeLevel())),u.receiveBytes=I.bytes,u.receivePackets=I.packets,u.receivePacketsLost=I.packetsLost,u.receivePacketsDiscarded=I.packetsDiscarded,u.packetLossRate=u.receivePacketsLost/(u.receivePackets+u.receivePacketsLost),u.receiveBitrate=c?8*Math.max(0,u.receiveBytes-c.receiveBytes):0,u.totalDuration=c?c.totalDuration+1:1,u.totalFreezeTime=c?c.totalFreezeTime:0,u.freezeRate=u.totalFreezeTime/u.totalDuration,u.receiveDelay=I.jitterBufferMs,u.totalDuration>10&&ia.isRemoteAudioFreeze(m)&&(u.totalFreezeTime+=1)),A){var v;"H264"!==A.codec&&"H265"!==A.codec&&"VP8"!==A.codec&&"VP9"!==A.codec&&"AV1X"!==A.codec&&"AV1"!==A.codec||(h.codecType=A.codec),h.receiveBytes=A.bytes,h.receiveBitrate=d?8*Math.max(0,h.receiveBytes-d.receiveBytes):0,h.decodeFrameRate=A.decodeFrameRate<0?0:A.decodeFrameRate,h.renderFrameRate=A.decodeFrameRate<0?0:A.decodeFrameRate,A.outputFrame&&(h.renderFrameRate=A.outputFrame.frameRate),A.receivedFrame?(h.receiveFrameRate=A.receivedFrame.frameRate,h.receiveResolutionHeight=A.receivedFrame.height,h.receiveResolutionWidth=A.receivedFrame.width):R&&(h.receiveResolutionHeight=R._videoHeight||0,h.receiveResolutionWidth=R._videoWidth||0),void 0!==A.framesRateFirefox&&(h.receiveFrameRate=Math.round(A.framesRateFirefox)),h.receivePackets=A.packets,h.receivePacketsLost=A.packetsLost,h.packetLossRate=h.receivePacketsLost/(h.receivePackets+h.receivePacketsLost);const t=d?d.totalFreezeTime:0,i=d?d.totalDuration:0;h.totalDuration=d?d.totalDuration+1:1,h.totalFreezeTime=null!==(v=A.totalFreezesDuration)&&void 0!==v?v:t||0,h.receiveDelay=A.jitterBufferMs||0;const n=!!C&&e.getRemoteVideoIsReady(C);void 0===A.totalFreezesDuration&&R&&n&&ia.isRemoteVideoFreeze(R,A,l)&&(h.totalFreezeTime+=1),h.freezeRate=Math.max(0,Math.min((h.totalFreezeTime-t)/(h.totalDuration-i),1))}g&&(u.end2EndDelay=g.B_ad,h.end2EndDelay=g.B_vd,u.transportDelay=g.B_ed,h.transportDelay=g.B_ed,u.currentPacketLossRate=g.B_ealr4/100,h.currentPacketLossRate=g.B_evlr4/100,S.uplinkNetworkQuality=g.B_punq?g.B_punq:0,S.downlinkNetworkQuality=g.B_pdnq?g.B_pdnq:0),this.remoteStats.set(o,{audioStats:u,videoStats:h,videoPcStats:A,networkStats:S}),m&&this.exceptionMonitor.setRemoteAudioStats(m,u),R&&this.exceptionMonitor.setRemoteVideoStats(R,h)}))}}class na{constructor(){this.destChannelMediaInfos=new Map,this.srcChannelMediaInfo=void 0}setSrcChannelInfo(e){Mi(e),this.srcChannelMediaInfo=e}addDestChannelInfo(e){Mi(e),this.destChannelMediaInfos.set(e.channelName,e)}removeDestChannelInfo(e){Pi(e),this.destChannelMediaInfos.delete(e)}getSrcChannelMediaInfo(){return this.srcChannelMediaInfo}getDestChannelMediaInfo(){return this.destChannelMediaInfos}}function oa(e){if(!(e instanceof na)){return new F(G.INVALID_PARAMS,"Config should be instance of [ChannelMediaRelayConfiguration]").throw()}const t=e.getSrcChannelMediaInfo(),i=e.getDestChannelMediaInfo();if(!t){return new F(G.INVALID_PARAMS,"srcChannelMediaInfo should not be empty").throw()}if(0===i.size){return new F(G.INVALID_PARAMS,"destChannelMediaInfo should not be empty").throw()}}class aa{get hasVideo(){return this._video_enabled_&&!this._video_muted_&&this._video_added_}get hasAudio(){return this._audio_enabled_&&!this._audio_muted_&&this._audio_added_}get audioTrack(){if(this.hasAudio||this._audio_pre_subscribed)return this._audioTrack}get videoTrack(){if(this.hasVideo||this._video_pre_subscribed)return this._videoTrack}get dataChannels(){return this._dataChannels}constructor(e,t){this.uid=void 0,this._uintid=void 0,this._trust_in_room_=!0,this._trust_audio_enabled_state_=!0,this._trust_video_enabled_state_=!0,this._trust_audio_mute_state_=!0,this._trust_video_mute_state_=!0,this._audio_muted_=!1,this._video_muted_=!1,this._audio_enabled_=!0,this._video_enabled_=!0,this._audio_added_=!1,this._video_added_=!1,this._is_pre_created=!1,this._video_pre_subscribed=!1,this._audio_pre_subscribed=!1,this._trust_video_stream_added_state_=!0,this._trust_audio_stream_added_state_=!0,this._audioTrack=void 0,this._videoTrack=void 0,this._dataChannels=[],this._audioSSRC=void 0,this._videoSSRC=void 0,this._audioOrtc=void 0,this._videoOrtc=void 0,this._cname=void 0,this._rtxSsrcId=void 0,this._videoMid=void 0,this._audioMid=void 0,this.uid=e,this._uintid=t}}const sa="9",ra=2e4,ca=4e4;class da{get localCapabilities(){return ve(this._localCapabilities)}get rtpCapabilities(){return ve(this._rtpCapabilities)}get candidates(){return ve(this._candidates)}get iceParameters(){return ve(this._iceParameters)}get dtlsParameters(){return ve(this._dtlsParameters)}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];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._dtlsParameters=void 0,this.setup=void 0,this.currentMidIndex=void 0,this.cname=void 0,this.useLocalCodecsMids=[],this.preloadSsrcs=[],this.firefoxSsrcMidMap=new Map,this._isUseExtmapAllowMixed=t,this._isUseLocalCodecs=i,e=ve(e);const{iceParameters:n,dtlsParameters:o,candidates:a,rtpCapabilities:s,setup:r,localCapabilities:c,cname:d}=e;this._rtpCapabilities=s,this._candidates=a,this._originCandidates=ve(a),this._iceParameters=n,this._dtlsParameters=o,this._localCapabilities=c,this.setup=r,this.cname=d,[this.sessionDesc]=this.updateRemoteRTPCapabilities(s),this.currentMidIndex=this.sessionDesc.mediaDescriptions.length-1}checkPreloadSsrcs(e){return e.length===this.preloadSsrcs.length&&e.every((e=>this.preloadSsrcs.includes(e)))}preloadRemoteMedia(e){let t=0;const i=[],n=[];for(;e>0;){const o=[mi({ssrcId:ca+t},ne("USE_SUB_RTX")?{rtx:ca+t+1}:{})],a="".concat(ca+t,"_").concat(ra+t),{ssrcs:s,ssrcGroups:r}=Qn(o,this.cname,ne("SYNC_GROUP")?a:void 0),c=this.preCreateOrRecycleSendMedia("video",s,r,void 0),d=[{ssrcId:ra+t}],l="".concat(ca+t,"_").concat(ra+t),{ssrcs:u,ssrcGroups:h}=Qn(d,this.cname,ne("SYNC_GROUP")?l:void 0),_=this.preCreateOrRecycleSendMedia("audio",u,h,void 0);e--,t+=2,i.push(c,_),n.push(s[0].ssrcId,u[0].ssrcId)}return this.useLocalCodecsMids.push(...i),this.preloadSsrcs=n,{mids:i,preSSRCs:n,isAvailable:!0}}preCreateOrRecycleSendMedia(e,t,i,n){const o=this.rtpCapabilities.send.videoCodecs,a=this._isUseLocalCodecs||0===o.length?this.localCapabilities.recv:this.rtpCapabilities.send;B.debug("create or recycle send media without remote rtp capabilities, ssrcs ",t[0].ssrcId);const s=e===Zi.VIDEO?a.videoCodecs:a.audioCodecs,r=e===Zi.VIDEO?a.videoExtensions:a.audioExtensions;this.currentMidIndex+=1;const c="".concat(this.currentMidIndex);let d={media:{mediaType:e,port:sa,protos:["UDP","TLS","RTP","SAVPF"],fmts:s.map((e=>e.payloadType.toString(10)))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:r,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:i,rtcpFeedbackWildcards:[],payloads:s,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:"sendonly",rtcpMux:!0,rtcpRsize:!0,mid:"".concat(c)}};return d=this.mungSendMediaDesc(d,n),this.sessionDesc.mediaDescriptions.push(d),this.updateBundleMids(),c}toString(){return ye(this.sessionDesc)}send(e,t,i,n){const{ssrcs:o,ssrcGroups:a}=Qn(t,this.cname,ne("SYNC_GROUP")?i:void 0),s=this.findPreloadMediaDesc(o);if(s){if(se()&&this.firefoxSsrcMidMap.set(o[0].ssrcId,s.attributes.mid),n&&(n.twcc||n.remb)){const e=this.sessionDesc.mediaDescriptions.indexOf(s);return this.sessionDesc.mediaDescriptions[e]=this.mungSendMediaDesc(s,n),{mid:s.attributes.mid,needExchangeSDP:!0}}return{mid:s.attributes.mid,needExchangeSDP:!1}}{const t=this.findAvailableMediaIndex(e,o);let i;return-1===t||1===t&&(Je()||ze()||ne("ENABLE_ENCODED_TRANSFORM")&&Qe())||0===t&&!Ze(138)&&ne("USE_SUB_RTX")||$e()?(i=this.createOrRecycleSendMedia(e,o,a,"sendonly",n),this.updateBundleMids()):(i=ve(this.sessionDesc.mediaDescriptions[t]),i.attributes.direction="sendonly",i.attributes.ssrcs=o,i.attributes.ssrcGroups=a,this.sessionDesc.mediaDescriptions[t]=this.mungSendMediaDesc(i,n)),se()&&this.firefoxSsrcMidMap.set(o[0].ssrcId,i.attributes.mid),{mid:i.attributes.mid,needExchangeSDP:!0}}}sendDataChannel(){const{mediaDesc:e,needExchangeSDP:t}=this.createOrRecycleDataChannel();return this.updateBundleMids(),{mid:e.attributes.mid,needExchangeSDP:t}}batchSend(e){const t=e.map((e=>{let{kind:t,ssrcMsg:i,mslabel:n}=e;return this.send(t,i,n)})),i=[];let n=!1;return t.forEach((e=>{let{mid:t,needExchangeSDP:o}=e;o&&(n=!0),i.push(t)})),{mids:i,needExchangeSDP:n}}stopSending(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>t.attributes.mid&&-1!==e.indexOf(t.attributes.mid)));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.stopSending.");t.forEach((e=>{"0"===e.attributes.mid||se()||$e()?e.attributes.ssrcs=[]:(e.attributes.ssrcs=[],e.attributes.direction="inactive",e.media.port="0")})),this.updateBundleMids()}mute(e){const t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.mute."));t.attributes.direction="inactive"}unmute(e){const t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.unmute."));t.attributes.direction="sendonly"}muteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>e.includes(t.attributes.mid||"")));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");t.forEach((e=>{e.attributes.direction="inactive"}))}unmuteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>e.includes(t.attributes.mid||"")));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");t.forEach((e=>{e.attributes.direction="recvonly"}))}receive(e,t,i,n){e.forEach(((e,o)=>{this.createOrRecycleRecvMedia(e,[],"recvonly",t,i,n[o])})),this.updateBundleMids()}stopReceiving(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>-1!==e.indexOf(t.attributes.mid)));if(t.length!==e.length)throw new Error("MediaDescriptions' length doesn't match mids's length when calling RemoteSDP.receive.");t.forEach((e=>{e.media.port="0",e.attributes.direction="inactive"})),this.updateBundleMids()}updateRemoteRTPCapabilities(e){const t=this.sessionDesc||ge((i=this._isUseExtmapAllowMixed,"v=0\no=- 0 0 IN IP4 127.0.0.1\ns=AgoraGateway\nt=0 0\na=group:BUNDLE 0 1\na=msid-semantic: WMS\na=ice-lite".concat(i?"\na=extmap-allow-mixed":"","\nm=video 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendonly\na=rtcp-mux\na=rtcp-rsize\na=mid:0\nm=audio 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendonly\na=rtcp-mux\na=rtcp-rsize\na=mid:1\n")));var i;this._rtpCapabilities=e;let n=!1;const o=this.rtpCapabilities.send,a=this.localCapabilities.send,s=this.localCapabilities.recv,r=s.videoCodecs,c=s.audioCodecs,d=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(n=!0,e.attributes.iceUfrag=this._iceParameters.iceUfrag,e.attributes.icePwd=this._iceParameters.icePwd,e.attributes.fingerprints=this._dtlsParameters.fingerprints,e.attributes.candidates=this._candidates,e.attributes.setup=this.setup,"application"===e.media.mediaType&&(e.attributes.sctpPort="5000"),"video"===e.media.mediaType)if(this._isUseLocalCodecs&&"sendonly"===e.attributes.direction){e.media.fmts=r.map((e=>e.payloadType.toString(10))),e.attributes.payloads=r,e.attributes.extmaps=d;const t=e.attributes.mid;"string"!=typeof t||this.useLocalCodecsMids.includes(t)||this.useLocalCodecsMids.push(t)}else if(0===o.videoCodecs.length){const t=a.videoCodecs.filter((e=>{var t;return null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase().includes("vp8")}))||[a.videoCodecs[0]];e.media.fmts=t.map((e=>e.payloadType.toString(10))),e.attributes.payloads=t,e.attributes.extmaps=[]}else e.media.fmts=o.videoCodecs.map((e=>e.payloadType.toString(10))),e.attributes.payloads=o.videoCodecs,e.attributes.extmaps=o.videoExtensions;if("audio"===e.media.mediaType)if(this._isUseLocalCodecs&&"sendonly"===e.attributes.direction){e.media.fmts=c.map((e=>e.payloadType.toString(10))),e.attributes.payloads=c,e.attributes.extmaps=l;const t=e.attributes.mid;"string"!=typeof t||this.useLocalCodecsMids.includes(t)||this.useLocalCodecsMids.push(t)}else if(0===o.audioCodecs.length){const t=a.audioCodecs.filter((e=>{var t;return null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase().includes("opus")}))||[a.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,no(e)}return this.sessionDesc=t,this.currentMidIndex=t.mediaDescriptions.length-1,[this.sessionDesc,n]}updateCandidates(e){const t=this._originCandidates.filter((e=>"udp"===e.transport)),i=[];if(t.forEach((e=>{i.push(mi(mi({},e),{},{foundation:"tcpcandidate",priority:Number(e.priority)-1+"",transport:"tcp",port:Number(e.port)+90+""}))})),0!==t.length){switch(e){case $i.TCP_RELAY:this._candidates=i;break;case $i.UDP_TCP_RELAY:case $i.RELAY:this._candidates=[...t,...i];break;default:this._candidates=t}for(const e of this.sessionDesc.mediaDescriptions)e.attributes.candidates=this.candidates}}restartICE(e){e=ve(e),this._iceParameters=e,this.sessionDesc.mediaDescriptions.forEach((t=>{t.attributes.iceUfrag=e.iceUfrag,t.attributes.icePwd=e.icePwd}))}predictReceivingMids(e){const t=[];for(let i=0;i<e;i++)t.push((this.currentMidIndex+i+1).toString(10));return t}findAvailableMediaIndex(e,t){return this.sessionDesc.mediaDescriptions.findIndex((i=>{const n=i.media.mediaType===e&&"0"!==i.media.port&&("sendonly"===i.attributes.direction||"sendrecv"===i.attributes.direction)&&0===i.attributes.ssrcs.length;if(se()){if(n){const e=this.firefoxSsrcMidMap.get(t[0].ssrcId);return!(e||"0"!==i.attributes.mid&&"1"!==i.attributes.mid)||!(!e||e!==i.attributes.mid)}return!1}return n}))}createOrRecycleDataChannel(){for(const e of this.sessionDesc.mediaDescriptions)if("application"===e.media.mediaType)return{mediaDesc:e,needExchangeSDP:!1};this.currentMidIndex+=1;const e="".concat(this.currentMidIndex),t={media:{mediaType:"application",port:sa,protos:["UDP","DTLS","SCTP"],fmts:["webrtc-datachannel"]},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:[],fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:[],ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:[],rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,mid:"".concat(e),sctpPort:"5000"}};return this.sessionDesc.mediaDescriptions.push(t),{mediaDesc:t,needExchangeSDP:!0}}createOrRecycleRecvMedia(e,t,i,n,o,a){const s=e._mediaStreamTrack.kind,r=this.rtpCapabilities.recv,c=oo(s,r,this.localCapabilities.send,s===Zi.VIDEO?n:o),d=s===Zi.VIDEO?r.videoExtensions:r.audioExtensions;this.currentMidIndex+=1;const l="".concat(this.currentMidIndex);let u={media:{mediaType:s,port:sa,protos:["UDP","TLS","RTP","SAVPF"],fmts:c.map((e=>e.payloadType.toString(10)))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:d,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:c,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:i,rtcpMux:!0,rtcpRsize:!0,mid:"".concat(l)}};u=this.mungRecvMediaDsec(u,e,a);const h=this.findFirstClosedMedia(s);if(h){const e=this.sessionDesc.mediaDescriptions.indexOf(h);this.sessionDesc.mediaDescriptions[e]=u}else this.sessionDesc.mediaDescriptions.push(u);return u}updateRemoteDtlsParameters(e){const t=new Set(this._dtlsParameters.fingerprints.map((e=>e.fingerprint))),i=new Set(e.map((e=>e.fingerprint)));let n=!1;t.size!==i.size&&(n=!0);for(const e of t)i.has(e)||(n=!0);return n}updateRemoteCodec(e,t,i){const n=[...new Set(this._rtpCapabilities.recv.videoCodecs.map((e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"")).filter((e=>Object.keys(et).includes(e))))],o=new Set(t);if(n.every((e=>o.has(e))))return B.debug("codecs has not changed, no need to updateRemoteCodec, codecs: ".concat(t)),!1;const a=this._rtpCapabilities.recv.videoCodecs.filter((e=>t.some((t=>(e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").includes(t)))));if(0===a.length)return B.debug("updateRemoteCodec failed, because cannot find matched codec, remoteCapabilities codecs: ".concat(n," codecs: ").concat(t)),!1;const s=[...new Set(a.map((e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"")))];let r;if(B.debug("updateRemoteCodec, from ".concat(n," to ").concat(s)),0===e.length)r=this.sessionDesc.mediaDescriptions.filter((e=>"video"===e.media.mediaType&&"recvonly"===e.attributes.direction));else if(r=this.sessionDesc.mediaDescriptions.filter((t=>t.attributes.mid&&"video"===t.media.mediaType&&e.includes(t.attributes.mid)&&"recvonly"===t.attributes.direction)),r.length!==e.length)return B.debug("updateRemoteCodec failed, because cannot find mids, mids: ".concat(e,", codecs: ").concat(t)),!1;if(ne("USE_PUB_RTX")||ne("USE_SUB_RTX")){const e=ao(a,this.rtpCapabilities.recv.videoCodecs);a.push(...e)}this._rtpCapabilities.recv.videoCodecs=a;const c=this.localCapabilities.send,d=this.rtpCapabilities.recv,l=oo(Zi.VIDEO,d,c,i);return r.forEach((e=>{const t=l.map((e=>e.payloadType.toString(10)));B.debug("updateRemoteCodec mid: ".concat(e.attributes.mid,", from"),e.attributes.payloads,"to",l),e.attributes.payloads=l,e.media.fmts=t})),!0}createOrRecycleSendMedia(e,t,i,n,o){const a=this.rtpCapabilities.send.videoCodecs,s=this._isUseLocalCodecs||0===a.length?this.localCapabilities.recv:this.rtpCapabilities.send,r=e===Zi.VIDEO?s.videoCodecs:s.audioCodecs,c=e===Zi.VIDEO?s.videoExtensions:s.audioExtensions;this.currentMidIndex+=1;const d="".concat(this.currentMidIndex);let l={media:{mediaType:e,port:sa,protos:["UDP","TLS","RTP","SAVPF"],fmts:r.map((e=>e.payloadType.toString(10)))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:c,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:i,rtcpFeedbackWildcards:[],payloads:r,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:n,rtcpMux:!0,rtcpRsize:!0,mid:"".concat(d)}};l=this.mungSendMediaDesc(l,o);const u=this.findFirstClosedMedia(e);if(u){const e=this.sessionDesc.mediaDescriptions.indexOf(u);this.sessionDesc.mediaDescriptions[e]=l}else this.sessionDesc.mediaDescriptions.push(l);return l}updateBundleMids(){this.sessionDesc.attributes.groups[0].identificationTag=this.sessionDesc.mediaDescriptions.filter((e=>"0"!==e.media.port)).map((e=>e.attributes.mid))}mungRecvMediaDsec(e,t,i){const s=ve(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)}(s),Zn(s,t),function(e,t){if(!(t instanceof n&&t._encoderConfig&&-1===t._hints.indexOf(a.SCREEN_TRACK)))return;const i=t._encoderConfig;o().supportMinBitrate&&i.bitrateMin&&e.attributes.payloads.forEach((e=>{var t;["h264","h265","vp8","vp9","av1"].includes((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())||"")&&(e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters["x-google-min-bitrate"]="".concat(i.bitrateMin))})),o().supportMinBitrate&&!t._hints.includes(a.LOW_STREAM)&&i.bitrateMax&&e.attributes.payloads.forEach((e=>{var t;["h264","h265","vp8","vp9","av1"].includes((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())||"")&&(e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters["x-google-start-bitrate"]="".concat(ne("X_GOOGLE_START_BITRATE")||Math.floor(i.bitrateMax)))}))}(s,t),function(e){if("video"!==e.media.mediaType)return;const t=Ne();if(t.name!==be.SAFARI&&t.os!==we.IOS)return;const i=e.attributes.extmaps.findIndex((e=>/video-orientation/g.test(e.extensionName)));-1!==i&&e.attributes.extmaps.splice(i,1)}(s),$n(s,i,this.localCapabilities.send),s}mungSendMediaDesc(e,t){const i=ve(e);return $n(i,t,this.localCapabilities.recv),no(i),i}updateRecvMedia(e,t){const i=this.sessionDesc.mediaDescriptions.findIndex((t=>t.attributes.mid===e));if(-1!==i){const e=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[i],t);this.sessionDesc.mediaDescriptions[i]=e}}bumpMid(e){this.currentMidIndex+=e}findFirstClosedMedia(e){return this.sessionDesc.mediaDescriptions.find((t=>se()?"0"===t.media.port&&t.media.mediaType===e:"0"===t.media.port))}findPreloadMediaDesc(e){return this.sessionDesc.mediaDescriptions.find((t=>{var i;return(null===(i=t.attributes)||void 0===i||null===(i=i.ssrcs[0])||void 0===i?void 0:i.ssrcId)===e[0].ssrcId}))}getSSRC(e){var t;return null===(t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e)))||void 0===t?void 0:t.attributes.ssrcs}}var la=function(e){return e[e.DOWN=0]="DOWN",e[e.UP=1]="UP",e}(la||{});const ua=new Map;function ha(e,t,i,n){let{scale:o}=e;if(0===o&&n===la.UP||o>=t.length-1&&n===la.DOWN)return e;let a=mi(mi({},e),{},{scale:n===la.DOWN?++o:--o});switch(i){case"maintain-framerate":a=mi(mi({},a),t[o].motion);break;case"maintain-resolution":a=mi(mi({},a),t[o].detail);break;case"balanced":a=mi(mi({},a),t[o].balanced)}return a}function _a(e,t){if(t){const i={overUse:0,underUse:0,adaptationList:pa(t)};ua.set(e,i)}else ua.delete(e)}function pa(e){const t=mi({},e),{bitrateMax:i,frameRate:n,scaleResolutionDownBy:o,bitrateMin:a}=t,{MIN_FRAME_RATE:s,MAX_THRESHOLD_FRAMERATE:r,MAX_SCALE:c,BITRATE_MIN_THRESHOLD:d,BITRATE_MAX_THRESHOLD:l,BWE_SCALE_UP_THRESHOLD:u,BWE_SCALE_DOWN_THRESHOLD:h,PERF_SCALE_DOWN_THRESHOLD:_,PERF_SCALE_UP_THRESHOLD:p,BALANCE_BITRATE_FACTOR:E,BALANCE_FRAMERATE_FACTOR:S,BALANCE_RESOLUTION_FACTOR:m,MOTION_RESOLUTION_FACTOR:R,MOTION_BITRATE_FACTOR:f,DETAIL_FRAMERATE_FACTOR:C,DETAIL_BITRATE_FACTOR:T}=it,I=Math.min(t.frameRate,r),A=[{scale:0,threshold:{bwe_down:Math.round(Math.pow(h,1)*i),bwe_up:i,fps_down:Math.round(Math.pow(_,1)*I),fps_up:n},balanced:{scaleResolutionDownBy:1,frameRate:n,bitrateMax:i,bitrateMin:a},motion:{scaleResolutionDownBy:1,frameRate:n,bitrateMax:i,bitrateMin:a},detail:{scaleResolutionDownBy:1,frameRate:n,bitrateMax:i,bitrateMin:a}}];for(let e=1;e<=c;e++){const t={bwe_up:Math.round(Math.pow(u,e)*i),bwe_down:Math.round(Math.pow(h,e+1)*i),fps_up:Math.round(Math.pow(p,e)*I),fps_down:Math.round(Math.pow(_,e+1)*I)},r={scaleResolutionDownBy:o/Math.pow(m,e),frameRate:Math.max(Math.round(Math.pow(S,e)*n),s),bitrateMax:Math.max(Math.round(Math.pow(E,e)*i),l),bitrateMin:Math.max(Math.round(Math.pow(E,e)*a),d)},c={scaleResolutionDownBy:o/Math.pow(R,e),frameRate:n,bitrateMax:Math.max(Math.round(Math.pow(f,e)*i),l),bitrateMin:Math.max(Math.round(Math.pow(f,e)*a),d)},g={scaleResolutionDownBy:1,frameRate:Math.max(Math.round(Math.pow(C,e)*n),s),bitrateMax:Math.max(Math.round(Math.pow(T,e)*i),l),bitrateMin:Math.max(Math.round(Math.pow(T,e)*a),d)};A.push({scale:e,threshold:t,balanced:r,motion:c,detail:g})}return A}function Ea(e,t,i,n,o,a){const s=ua.get(e)||{overUse:0,underUse:0,adaptationList:pa(o)},{adaptationList:r}=s;ua.set(e,s);const{OVERUSE_TIMES_THRESHOLD:c,UNDERUSE_TIMES_THRESHOLD:d}=it,{scale:l}=n;let u,h;return"number"==typeof t&&t>0&&function(e,t,i,n){if(t>=i.length)return!1;let{threshold:{fps_down:o}}=i[t];return ne("FORCE_AG_HIGH_FRAMERATE")&&"maintain-framerate"===n&&(o=i[0].threshold.fps_down),e<o}(t,l,r,a)&&(s.overUse++,h=tt.CPU,s.overUse>c)||"number"==typeof i&&i>0&&function(e,t,i){if(t>=i.length)return!1;const{threshold:{bwe_down:n}}=i[t];return e<n}(i,l,r)&&(s.overUse++,h=tt.BANDWIDTH,s.overUse>c)?(s.overUse=0,s.underUse=0,u=ha(n,r,a,la.DOWN),[u,h]):("number"==typeof t&&t>0&&"number"==typeof i&&i>0&&function(e,t,i,n){if(0===t)return;let{threshold:{fps_up:o}}=i[t];return ne("FORCE_AG_HIGH_FRAMERATE")&&"maintain-framerate"===n&&(o=i[1].threshold.fps_up),e>o}(t,l,r,a)&&function(e,t,i){if(0===t)return;const{threshold:{bwe_up:n}}=i[t];return e>n}(i,l,r)&&(s.underUse++,s.underUse>d&&(s.overUse=0,s.underUse=0,u=ha(n,r,a,la.UP),0===u.scale&&(h=tt.NONE))),[u,h])}const Sa=new Map;function ma(e,t){const i=Sa.get(e);if(i){const{timer:t}=i;window.clearTimeout(t),Sa.delete(e)}t.qualityLimitationReason=tt.NONE,_a(e)}function Ra(e){const t=o();if(e.some((e=>e._bypassWebAudio)))throw new ue(Z.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio");if(!t.webAudioMediaStreamDest)throw new ue(Z.NOT_SUPPORTED,"cannot publish multiple tracks because your browser does not support audio mixing")}function fa(e,t){Ra(e);const i=t||new l;return e.forEach((e=>i.addAudioTrack(e))),i}const Ca=!o().supportUnifiedPlan||ne("CHROME_FORCE_PLAN_B")&&at();function Ta(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i;return Ca?(i={spec:t,store:e},po("PlanBConnection").create(i)):new va(t,e)}function Ia(e){return e&&("disconnected"===e.iceConnectionState||"checking"===e.iceConnectionState||"failed"===e.iceConnectionState)}function Aa(e){try{if(e.iceServers)return!1;if(e.turnServer&&"off"!==e.turnServer.mode){if(st(e.turnServer.servers))return!1;if(ne("FORCE_TURN_TCP")||e.turnServer.servers.concat(e.turnServer.serversFromGateway||[]).some((e=>e.forceturn)))return!0}return!1}catch(e){return!1}}var ga;let va=(ga=class e extends Qi{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(et).includes(e))))]}constructor(t,i){super(t,i),this.id=fe(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:ne("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=tt.NONE,this.isFirstConnected=!1,this.store=i,this.forceTurn=Aa(t),this.mutex=new re("P2PConnection-mutex",i.clientId),this.peerConnection=new RTCPeerConnection(e.resolvePCConfiguration(t),{optional:[{googDscp:!0}]}),this.isFirstConnected=!1,this.statsFilter=rt(this.peerConnection,ne("STATS_UPDATE_INTERVAL"),void 0,se()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1,t.isPreallocation&&(this.isPreallocation=!0),this.establishPromise=this.establish()}getPreMedia(e){return this.preMediaMap.get(e)}isPreSub(){return this.preMediaMap.size>0}async updateRemoteRTPCapabilities(e,t){if(this.remoteCodecs=t,!this.remoteSDP)return void B.debug("[P2PConnection] cannot updateRemoteRTPCapabilities before remote SDP created, local codecs: ".concat(this.localCodecs,", codecs: ").concat(t));if(this.remoteSDP.updateRemoteCodec(e,t,this.store.codec)){const e=await this.peerConnection.createOffer(),t=this.logSDPExchange(e.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(e);const i=this.remoteSDP.toString();null==t||t(i),await this.peerConnection.setRemoteDescription({type:"answer",sdp:i})}else B.debug("[P2PConnection] updateRemoteRTPCapabilities no need to exchange SDP.")}async establish(){try{this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.peerConnection.addTransceiver("audio",{direction:"recvonly"});const i=await this.peerConnection.createOffer();if(!i.sdp)throw new Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");const n=Xn(i.sdp),o=await eo({filterRTX:!ne("USE_PUB_RTX")&&!ne("USE_SUB_RTX"),filterVideoFec:ne("FILTER_VIDEO_FEC"),filterAudioFec:ne("FILTER_AUDIO_FEC"),filterVideoCodec:ne("FILTER_VIDEO_CODEC"),unsupportedVideoUplinkCodec:ne("UNSUPPORTED_VIDEO_UPLINK_CODEC"),unsupportedVideoDownlinkCodec:ne("UNSUPPORTED_VIDEO_DOWNLINK_CODEC")},this.extension);if(this.localCapabilities=io(o),this.initialOffer=i,ne("ENABLE_SVC")&&"av1"==this.store.codec){const t=await async function(){try{const e=new RTCPeerConnection;e.addTransceiver("video",{direction:"sendonly",sendEncodings:[{scalabilityMode:Ae.L1T3}]});const t=await e.createOffer();if(!t.sdp)return void e.close();const i=ge(t.sdp).mediaDescriptions[0];if(!i)return;const n=i.attributes.extmaps.find((e=>"https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension"===e.extensionName));return e.close(),n}catch(e){return}}();var e;if(t)this.supportAV1RtpSpec=!0,null===(e=o.send)||void 0===e||e.videoExtensions.push(t)}let a;return i.sdp&&lo(i.sdp)&&(a=ve(o),(t=a).send&&(Hn(Zi.VIDEO,t.send.videoExtensions),Hn(Zi.AUDIO,t.send.audioExtensions)),t.recv&&(Hn(Zi.VIDEO,t.recv.videoExtensions),Hn(Zi.AUDIO,t.recv.audioExtensions)),t.sendrecv&&(Hn(Zi.VIDEO,t.sendrecv.videoExtensions),Hn(Zi.AUDIO,t.sendrecv.audioExtensions))),mi(mi({},n),{},{rtpCapabilities:a||o,offerSDP:i.sdp})}catch(e){throw new ue(Z.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString())}var t}async connect(e){try{if(!this.initialOffer)throw new Error("Cannot establish P2PConnection without initial offer.");this.initialOffer.sdp&&lo(this.initialOffer.sdp)&&(t=e.rtpCapabilities,i=this.localCapabilities,t.send&&(Wn(Zi.VIDEO,t.send.videoExtensions,i.send.videoExtensions),Wn(Zi.AUDIO,t.send.audioExtensions,i.send.audioExtensions)),t.recv&&(Wn(Zi.VIDEO,t.recv.videoExtensions,i.recv.videoExtensions),Wn(Zi.AUDIO,t.recv.audioExtensions,i.recv.audioExtensions))),this.remoteSDP=new da(mi(mi({},e),{},{localCapabilities:this.localCapabilities}),this.supportAV1RtpSpec,!(!ne("ENABLE_PRE_SUB_WITH_PRE_PC")||!ne("PRE_USE_LOCAL_CODECS"))&&s(this.store)),e.preallocation&&(this.isPreallocation=!0),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0&&this.remoteSDP.updateRemoteCodec([],this.remoteCodecs,this.store.codec);const n=this.remoteSDP.toString(),o=ro(this.initialOffer.sdp,this.extension),a=this.logSDPExchange(o||"","offer","local","connect");this.store.descriptionStart(),await this.peerConnection.setLocalDescription({type:"offer",sdp:o}),null==a||a(n),await this.peerConnection.setRemoteDescription({type:"answer",sdp:n});const r=this.peerConnection.getTransceivers()[0];if(null!=r&&r.receiver&&this.tryBindTransportEvents(r.receiver),s(this.store))if(e.preallocation&&ne("ENABLE_PRE_SUB_WITH_PRE_PC")){const e=ne("PRE_SUB_NUM"),{mids:t,preSSRCs:i}=this.remoteSDP.preloadRemoteMedia(e);await so(this.peerConnection,this.remoteSDP,this.extension),B.debug("[".concat(this.store.clientId,"] [P2PConnection] preload media, in pre pc,add preload ssrcs ").concat(i)),this.presetMedia(t,i)}else{const{preSSRCs:t=[]}=e,i=t.map((e=>e.ssrcMsg[0].ssrcId));if(0===t.length)return;const{mids:n}=this.remoteSDP.batchSend(t.map((e=>Object.assign({},e))));await so(this.peerConnection,this.remoteSDP,this.extension),B.debug("[P2PConnection.connect] preload media, after join, add preload ssrcs ".concat(i)),this.presetMedia(n,i)}}catch(e){throw new ue(Z.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(e.toString()))}var t,i}presetMedia(e,t){e.forEach(((e,i)=>{this.peerConnection.getTransceivers().forEach((n=>{if(null!=n.mid&&e===n.mid&&n.receiver.track){const o=n.receiver.track;let a;"video"===o.kind&&ne("ENABLE_PRE_RENDER")&&(a=new m({trackId:"track-".concat(o.kind,"-unknown-").concat(this.store.clientId,"_").concat(fe(5,""))},!0),a.updateVideoTrack(o),a.onFirstVideoFrameRender=()=>{var e;const n=this.preMediaMap.get(t[i]);n&&(n.firstVideoRender=Date.now()),null===(e=this.onFirstVideoRender)||void 0===e||e.call(this,t[i])},a.play(this.store.sessionId||void 0)),this.preMediaMap.set(t[i],{mid:e,track:o,player:a,transceiver:n})}})),this.store.peerReceiver()}))}checkDtlsParameters(e){return!!this.remoteSDP&&(e.length>0&&this.remoteSDP.updateRemoteDtlsParameters(e))}async updateRemoteConnect(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.updateRemoteConnect before remote SDP created");let t=!1;const{rtpCapabilities:i}=e;if([,t]=this.remoteSDP.updateRemoteRTPCapabilities(i),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0){const e=this.remoteSDP.updateRemoteCodec([],this.remoteCodecs,this.store.codec);t=t||e}const{preSSRCs:n=[]}=e,o=n.map((e=>e.ssrcMsg[0].ssrcId));if(!this.remoteSDP.checkPreloadSsrcs(o)){const e=[],t=[];if(Array.from(this.preMediaMap.entries()).every((i=>{let[n,{mid:o,player:a,track:s}]=i;return e.push(o),t.push(n),this.preMediaMap.delete(n),a&&a.destroy(),!0})),e.length>0&&(this.remoteSDP.stopSending(e),await so(this.peerConnection,this.remoteSDP,this.extension),B.warn("[P2PConnection.updateRemoteConnect] preload media, failed, del preload ssrcs ".concat(t)),j.reportApiInvoke(this.store.sessionId,{name:We.PRELOAD_MEDIA_FAILED,options:[n,t],tag:He.TRACER}).onSuccess()),n.length>0){const{mids:e}=this.remoteSDP.batchSend(n.map((e=>Object.assign({},e))));await so(this.peerConnection,this.remoteSDP,this.extension),B.debug("[P2PConnection.updateRemoteConnect] preload media, after join, add preload ssrcs ".concat(o)),this.presetMedia(e,o)}}t?(await so(this.peerConnection,this.remoteSDP,this.extension),B.debug("[P2PConnection] updateRemoteConnect by exchanging SDP.")):B.debug("[P2PConnection] updateRemoteConnect no need to exchange SDP, because no need to update remote codecs (use local codecs)")}catch(e){throw new ue(Z.EXCHANGE_SDP_FAILED,"P2PConnection.updateRemoteConnect failed; ".concat(e.toString()))}}send(e,t,i){var n=this;return Ri((function*(){const o=yield pi(n.mutex.lock("From P2PConnection.send"));try{if(!n.remoteSDP)throw new Error("Cannot call P2PConnection.send before remote SDP created");const a=[],s=jn();e.forEach((e=>{const t=n.peerConnection.addTransceiver(e._mediaStreamTrack,mi({direction:"sendonly"},"video"===e.trackMediaType&&n.supportAV1RtpSpec&&s?{sendEncodings:[{scalabilityMode:s}]}:{}));a.push(t),e._updateRtpTransceiver(t)})),se()&&!0===ne("SIMULCAST")&&(yield pi(n.applySimulcastForFirefox(a,e)));const r=yield pi(n.peerConnection.createOffer()),c=n.remoteSDP.predictReceivingMids(e.length),d=n.mungSendOfferSDP(r.sdp,e,c),l=ge(d),u=c.map((e=>{const t=l.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error("Cannot extract ssrc from mediaDescription.");return function(e,t){const i=[],n=e.attributes.ssrcGroups.filter((e=>"FID"===e.semantic)),o=e.attributes.ssrcGroups.find((e=>"SIM"===e.semantic)),a=e.attributes.ssrcs;if(o)o.ssrcIds.forEach((e=>{var o;const a=null===(o=n.find((t=>t.ssrcIds[0]===e)))||void 0===o?void 0:o.ssrcIds[1];i.push({ssrcId:e,rtx:t?a:void 0})}));else if(n.length>0){const e=n[0].ssrcIds[0],o=n[0].ssrcIds[1];i.push({ssrcId:e,rtx:t?o:void 0})}else{if(0===a.length)throw new Error("No ssrcs found on local media description.");i.push({ssrcId:a[0].ssrcId})}return i}(t,ne("USE_PUB_RTX"))}));let h;try{h=yield u}catch(o){h=[],n.remoteSDP.receive(e,t,i,h);const a=n.remoteSDP.toString();throw yield pi(n.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield pi(n.peerConnection.setRemoteDescription({type:"answer",sdp:a})),yield pi(n.stopSending(c,!0)),o}n.remoteSDP.receive(e,t,i,h);const _=n.remoteSDP.toString(),p=n.logSDPExchange(d,"offer","local","send");return yield pi(n.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield pi(n.applySimulcastEncodings(a,e)),yield pi(n.applySendEncodings(a,e)),null==p||p(_),yield pi(n.peerConnection.setRemoteDescription({type:"answer",sdp:_})),a.map(((e,t)=>{const i=c[t];return{localSSRC:u[t],id:i,transceiver:e}}))}catch(e){throw e instanceof ue?e:new ue(Z.EXCHANGE_SDP_FAILED,"P2PConnection.send failed; ".concat(e.toString()))}finally{o()}}))()}async createDataChannels(e,t){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.createDataChannels before remote SDP created");let i=this.dataStreamChannelMap.get(e);if(i&&"open"===i.readyState)B.debug("[P2PConnection] Channels are already available and can be reused directly.");else{const t=this.currentDataChannelId<1023?this.currentDataChannelId++:this.recoveredDataChannelIds.shift();if("number"!=typeof t)throw new Error("create DataChannel error, because cannot get dc id");i=this.peerConnection.createDataChannel("datastream-channel",{id:t,negotiated:!0,ordered:!1,maxRetransmits:ne("DATASTREAM_MAX_RETRANSMITS")}),i.binaryType="arraybuffer",this.dataStreamChannelMap.set(e,i)}t.forEach((e=>{e._updateOriginDataChannel(i)}));const{needExchangeSDP:n}=this.remoteSDP.sendDataChannel();if(n){const e=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:e});const t=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(t),B.debug("[P2PConnection] createDataChannels by exchanging SDP.")}else B.debug("[P2PConnection] createDataChannels no need to exchange SDP.");return}catch(e){throw e instanceof ue?e:new ue(Z.EXCHANGE_SDP_FAILED,"P2PConnection.createDataChannels failed; ".concat(e.toString()))}}async stopDataChannels(e){try{const t=this.dataStreamChannelMap.get(e);return t&&(t.id&&this.recoveredDataChannelIds.push(t.id),t.close()),void this.dataStreamChannelMap.delete(e)}catch(e){throw e instanceof ue?e:new ue(Z.DATACHANNEL_FAILED,"P2PConnection.stopDataChannels failed; ".concat(e.toString()))}}async stopSending(e,t){const i=t?void 0:await this.mutex.lock("From P2PConnection.stopSending");try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopSending before remote SDP created");const t=this.peerConnection.getTransceivers().filter((t=>-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length when trying to call P2PConnection.stopSending.");t.map((e=>{var t;ma(this.id+e.mid,this),e.direction="inactive",null===(t=e.stop)||void 0===t||t.call(e)}));const n=await this.peerConnection.createOffer(),o=this.logSDPExchange(n.sdp||"","offer","local","stopSending");await this.peerConnection.setLocalDescription(n),this.remoteSDP.stopReceiving(e);const a=this.remoteSDP.toString();null==o||o(a),await this.peerConnection.setRemoteDescription({type:"answer",sdp:a})}catch(e){throw new ue(Z.EXCHANGE_SDP_FAILED,"P2PConnection.stopSending failed; ".concat(e.toString()))}finally{i&&i()}}async receive(e,t,i,n){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.receive ".concat(e," before remoteSDP created."));const{mid:o,needExchangeSDP:a}=this.remoteSDP.send(e,t,i,n);a&&(await so(this.peerConnection,this.remoteSDP,this.extension),B.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," by exchanging SDP.")));const s=this.peerConnection.getTransceivers().find((e=>e.mid===o));if(!s)throw new Error("Cannot get transceiver after setLocalDescription.");return{track:s.receiver.track,id:o,transceiver:s}}catch(e){throw new ue(Z.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()))}}async batchReceive(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.batchReceive before remoteSDP created.");const{mids:t,needExchangeSDP:i}=this.remoteSDP.batchSend(e);return i&&(await so(this.peerConnection,this.remoteSDP,this.extension),B.debug("[".concat(this.store.clientId,"] [P2PConnection] batchReceive by exchanging SDP."))),t.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 ue(Z.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()))}}async stopReceiving(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopReceiving before remote SDP created.");e.forEach((e=>{Array.from(this.preMediaMap.entries()).some((t=>{let[i,{mid:n,player:o}]=t;if(n===e)return this.preMediaMap.delete(i),o&&o.destroy(),!0}))})),this.remoteSDP.stopSending(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","stopReceiving");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||""),await this.peerConnection.setLocalDescription(n)}catch(e){throw new ue(Z.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(e.toString()))}}async muteRemote(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.muteRemote mid=".concat(e," before remote SDP created."));this.remoteSDP.mute(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","muteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||""),await this.peerConnection.setLocalDescription(n)}catch(e){throw new ue(Z.EXCHANGE_SDP_FAILED,"P2PConnection.muteRemote failed; ".concat(e.toString()))}}async unmuteRemote(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.unmuteRemote mid=".concat(e," before remote SDP created."));this.remoteSDP.unmute(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","unmuteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||""),await this.peerConnection.setLocalDescription(n)}catch(e){throw new ue(Z.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteRemote failed; ".concat(e.toString()))}}async muteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.muteLocal before remote SDP created.");const t=this.peerConnection.getTransceivers().filter((t=>t.mid&&-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length.");t.map((e=>{e.direction="inactive"}));const i=await this.peerConnection.createOffer(),n=this.logSDPExchange(i.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(i),this.remoteSDP.muteRemote(e);const o=this.remoteSDP.toString();null==n||n(o),await this.peerConnection.setRemoteDescription({type:"answer",sdp:o})}catch(e){throw new ue(Z.EXCHANGE_SDP_FAILED,"P2PConnection.muteLocal failed; ".concat(e.toString()))}}async unmuteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.unmuteLocal before remote SDP created.");const t=this.peerConnection.getTransceivers().filter((t=>t.mid&&-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length.");t.map((async(e,t)=>{e.direction="sendonly"}));const i=await this.peerConnection.createOffer(),n=this.logSDPExchange(i.sdp||"","offer","local","unmuteLocal");await this.peerConnection.setLocalDescription(i),this.remoteSDP.unmuteRemote(e),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0&&this.remoteSDP.updateRemoteCodec(e,this.remoteCodecs,this.store.codec);const o=this.remoteSDP.toString();null==n||n(o),await this.peerConnection.setRemoteDescription({type:"answer",sdp:o})}catch(e){throw new ue(Z.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteLocal failed; ".concat(e.toString()))}}restartICE(e){var t=this;return Ri((function*(){const i=yield pi(t.mutex.lock("From P2PConnection.restartICE"));try{if(!t.remoteSDP)throw new Error("Cannot restartICE before remoteSDP created.");const n=o().supportPCSetConfiguration,a=ne("FORCE_TURN_TCP")||t.forceTurn;if(e===$i.RELAY&&!n)return;if(n&&!a){const i=e===$i.RELAY?"relay":"all",n=t.peerConnection.getConfiguration();n.iceTransportPolicy!==i&&(B.debug("[".concat(t.store.clientId,"] restartICE change iceTransportPolicy from [").concat(n.iceTransportPolicy,"] to [").concat(i,"]")),n.iceTransportPolicy=i,t.peerConnection.setConfiguration(n))}t.remoteSDP.updateCandidates(e);const s=yield pi(t.peerConnection.createOffer({iceRestart:!0}));if(!s.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const r=Xn(s.sdp),{remoteIceParameters:c}=yield r.iceParameters;t.remoteSDP.restartICE(c);const d=t.remoteSDP.toString(),l=t.logSDPExchange(s.sdp||"","offer","local","restartICE");t.store.descriptionStart(),yield pi(t.peerConnection.setLocalDescription(s)),null==l||l(d),yield pi(t.peerConnection.setRemoteDescription({type:"answer",sdp:d}))}catch(e){B.warning("[".concat(t.store.clientId,"] restart ICE failed, abort operation"),e)}finally{i()}}))()}async extendCandidate(){if(!this.remoteSDP||this.isFirstConnected)return;const e=await this.mutex.lock("From P2PConnection.extendCandidate");try{this.remoteSDP.updateCandidates($i.TCP_RELAY),await so(this.peerConnection,this.remoteSDP,this.extension)}catch(e){B.warning("[".concat(this.store.clientId,"] extend candidate failed, abort operation"),e)}finally{e()}}close(){var e;this.peerConnection.getTransceivers().forEach((e=>{ma(this.id+e.mid,this)})),this.preMediaMap.forEach((e=>{let{player:t}=e;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 mi(mi({},this.statsFilter.getStats()),{},{qualityLimitationReason:this.qualityLimitationReason})}getRemoteVideoIsReady(e){return this.statsFilter.getVideoIsReady(e)}async updateEncoderConfig(e,t){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.updateEncoderConfig before remote SDP created.");const i=await this.peerConnection.createOffer(),n=this.mungSendOfferSDP(i.sdp,[t],[e]);this.remoteSDP.updateRecvMedia(e,t);const o=this.remoteSDP.toString(),a=this.logSDPExchange(n,"offer","local","updateEncoderConfig");await this.peerConnection.setLocalDescription({type:"offer",sdp:n}),null==a||a(o),await this.peerConnection.setRemoteDescription({type:"answer",sdp:o})}catch(e){throw new ue(Z.EXCHANGE_SDP_FAILED,e.toString())}}async updateSendParameters(e,t){const i=this.peerConnection.getTransceivers().filter((t=>t.mid===e));1===i.length&&(this.isVP8Simulcast(t)?se()||await this.applySimulcastEncodings(i,[t]):await this.applySendEncodings(i,[t]))}setStatsRemoteVideoIsReady(e,t){this.statsFilter.setVideoIsReady2(e,t)}async replaceTrack(e,t){const i=this.peerConnection.getTransceivers().find((e=>e.mid===t));i&&await i.sender.replaceTrack(e._mediaStreamTrack)}async getSelectedCandidatePair(){const e=this.peerConnection.getReceivers();if(e.length>0&&e[0].transport&&e[0].transport.iceTransport&&e[0].transport.iceTransport.getSelectedCandidatePair&&e[0].transport.iceTransport.getSelectedCandidatePair()){const t=e[0].transport.iceTransport,{local:i,remote:n}=t.getSelectedCandidatePair();return{local:mi(mi({},ct),{},{candidateType:i.type,protocol:i.protocol,address:i.address,port:i.port}),remote:mi(mi({},ct),{},{candidateType:n.type,protocol:n.protocol,address:n.address,port:n.port})}}return this.statsFilter.getSelectedCandidatePair()}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var e;null===(e=this.onICEConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.iceConnectionState)},this.peerConnection.onconnectionstatechange=()=>{var e;"connected"===this.peerConnection.connectionState&&(this.isFirstConnected=!0),null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.connectionState)},this.peerConnection.onicecandidateerror=e=>{if(e&&(e.errorCode||e.errorText)){var t;const i="code: ".concat(e.errorCode,", message: ").concat(e.errorText),n=e.port?"local: ".concat(e.port):"",o=Fn(e.url||"");B.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICECandidateError(").concat(i,"), url: ").concat(o||"",", host_candidate:").concat(n)),null===(t=this.onICECandidateError)||void 0===t||t.call(this,i)}},this.peerConnection.onicegatheringstatechange=e=>{e&&e.target&&"iceGatheringState"in e.target&&B.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] RTCPeerConnection.onicegatheringstatechange(").concat(e.target.iceGatheringState,")"))},this.peerConnection.onicecandidate=e=>{e.candidate?this.localCandidateCount+=1:(this.peerConnection.onicecandidate=null,this.allCandidatesReceived=!0,B.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount))},setTimeout((()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,B.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount))}),ne("CANDIDATE_TIMEOUT"))}unbindPCEvents(){this.peerConnection.oniceconnectionstatechange=null,this.peerConnection.onconnectionstatechange=null,this.peerConnection.onsignalingstatechange=null,this.peerConnection.onicecandidateerror=null,this.peerConnection.onicecandidate=null,this.peerConnection.ontrack=null}static resolvePCConfiguration(t){const i={iceServers:[]},n=t.cloudProxyServer||"disabled";return t.iceServers?i.iceServers=t.iceServers:t.turnServer&&(st(t.turnServer.servers)?i.iceServers=t.turnServer.servers:ne("NEW_TURN_MODE")&&i.iceServers&&"disabled"===n?(ne("USE_TURN_SERVER_OF_GATEWAY")?t.turnServer.serversFromGateway&&i.iceServers.push(...e.newTurnServerConfigToIceServers(t.turnServer.serversFromGateway)):i.iceServers.push(...e.newTurnServerConfigToIceServers(t.turnServer.servers)),ne("NEW_FORCE_TURN")&&(i.iceTransportPolicy="relay")):"off"!==t.turnServer.mode&&(i.iceServers&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers)),ne("USE_TURN_SERVER_OF_GATEWAY")&&i.iceServers&&t.turnServer.serversFromGateway&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway)),ne("FORCE_TURN_TCP")?i.iceTransportPolicy="relay":t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach((e=>{e.forceturn&&(i.iceTransportPolicy="relay")})))),ne("ENABLE_ENCODED_TRANSFORM")&&o().supportWebRTCEncodedTransform&&(i.encodedInsertableStreams=!0),i}static turnServerConfigToIceServers(e){const t=[];return e.forEach((e=>{e.security?e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(On(e.turnServerURL),":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&!ne("FORCE_TURN_TCP")&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.udpport,"?transport=udp")}),e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.tcpport,"?transport=tcp")}))})),t}static newTurnServerConfigToIceServers(e){const t=[];return e.forEach((e=>{const i=ne("NEW_TURN_MODE");1===i?t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=udp")}):2===i?t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=tcp")}):3===i?t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(On(e.turnServerURL),":443?transport=tcp")}):4===i&&(t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=udp")}),t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=tcp")}),t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(On(e.turnServerURL),":443?transport=tcp")}))})),t}tryBindTransportEvents(e){const t=e.transport;if(t){this.transportEventReceiver=e,t.onstatechange=()=>{var e;null!=t&&t.state&&(null===(e=this.onDTLSTransportStateChange)||void 0===e||e.call(this,t.state))},t.onerror=e=>{var t;null===(t=this.onDTLSTransportError)||void 0===t||t.call(this,"error"in e?e.error:e)};const i=t.iceTransport;i&&(i.onstatechange=()=>{const e=null==t?void 0:t.iceTransport.state;var i;e&&(null===(i=this.onICETransportStateChange)||void 0===i||i.call(this,e))},i.getSelectedCandidatePair&&(i.onselectedcandidatepairchange=()=>{if(i.getSelectedCandidatePair()){const{local:e,remote:t}=i.getSelectedCandidatePair()||{};if(e&&t){const i=e.address+":"+e.port,n=t.address+":"+t.port;B.info("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] selectedcandidatepairchange: local ").concat(JSON.stringify(Fn(i)),", remote ").concat(JSON.stringify(Fn(n))))}}}))}}tryUnbindTransportEvents(){this.transportEventReceiver&&this.transportEventReceiver.transport&&(this.transportEventReceiver.transport.onstatechange=null,this.transportEventReceiver.transport.onerror=null,this.transportEventReceiver.transport.iceTransport&&(this.transportEventReceiver.transport.iceTransport.onstatechange=null))}async updateRtpSenderEncodings(e,t){var i;if(!t){const i=this.peerConnection.getSenders();t=i.find((t=>t.track===e._mediaStreamTrack))}if(!t)return B.warn("[".concat(e.getTrackId(),"] no rtpSender found}"));if(this.isVP8Simulcast(e))return B.warn("[updateRtpSenderEncodings] Track is VP8 simulcast, please apply simulcast encodings");if(!o().supportSetRtpSenderParameters)return B.warn("[updateRtpSenderEncodings] Browser not support set rtp-sender parameters");const n={},s={};switch(e._optimizationMode){case"motion":n.degradationPreference="maintain-framerate";break;case"detail":n.degradationPreference="maintain-resolution";break;case"balanced":n.degradationPreference="balanced"}const r=function(e,t){return e.getTransceivers().find((e=>e.sender.track===t||e.receiver.track===t))}(this.peerConnection,e._mediaStreamTrack),c=R(e);if(function(e){return!(!ne("ENABLE_AG_ADAPTATION")||!(e instanceof S||e._hints.includes(a.CUSTOM_TRACK))||!ne("FORCE_SUPPORT_AG_ADAPTATION")&&!(Me(14,0,!1)&&nt(17,4,!0)||ot(14)&&Ve(17,4,!0)))}(e)&&r&&t&&c&&this.getLocalVideoStats&&["vp8","vp9"].includes(this.store.codec)){const i=n.degradationPreference||(e._hints.includes(a.CUSTOM_TRACK)?ne("CUSTOM_ADAPTATION_DEFAULT_MODE"):"maintain-framerate");!function(e,t,i,n,o,a){if(ma(e,i),o(t),"balanced"!==n&&"maintain-framerate"!==n&&"maintain-resolution"!==n)return;let s=-1;_a(e,t);const r=window.setInterval((()=>{const r=Sa.get(e);if(!ne("ENABLE_AG_ADAPTATION")||!r)return ma(e,i),void o(t);const c=a();if(c.sendPackets>0&&c.OutgoingAvailableBandwidth>0){if(-1===s)return void(s=Date.now());if(Date.now()-s<1e3)return;const a=c.sendFrameRate,d=c.OutgoingAvailableBandwidth,[l,u]=Ea(e,a,d,r.adaptationConfig,t,n);u&&(i.qualityLimitationReason=u),l&&r.adaptationConfig.scale!==l.scale&&(B.debug("[".concat(e,"] applyAdaptation: ").concat(i.qualityLimitationReason,"\n sendFps ").concat(a,", bwe ").concat(d,", switch from ").concat(r.adaptationConfig.scale," to ").concat(l.scale," ")),r.adaptationConfig=mi(mi({},r.adaptationConfig),l),o(l))}}),ne("CHECK_LOCAL_STATS_INTERVAL")),c=mi({},t);Sa.set(e,{timer:r,adaptationConfig:c,originConfig:t,adaptationFunc:o}),B.debug("[".concat(e,"] start adaptation, originConfig: ").concat(JSON.stringify(t),", degradationPreference: ").concat(n))}(this.id+r.mid,c,this,i,(e=>{t&&this.updateAdaptation(t,e)}),this.getLocalVideoStats.bind(this))}if(e._encoderConfig){const{bitrateMax:t,frameRate:i,scaleResolutionDownBy:n}=e._encoderConfig;t&&(s.maxBitrate=1e3*t),(e._hints.includes(a.LOW_STREAM)||e.isUseScaleResolutionDownBy)&&(i&&(s.maxFramerate=Ln(i)),n&&n>=1&&(s.scaleResolutionDownBy=n))}const{maxFramerate:d}=ne("ENCODER_CONFIG_LIMIT");if(d&&"number"==typeof d&&(s.maxFramerate=s.maxFramerate?Math.min(s.maxFramerate,d):d),ne("DSCP_TYPE")&&at()){const e=ne("DSCP_TYPE");["very-low","low","medium","high"].includes(e)&&(s.networkPriority=e)}const l=t.getParameters(),u=null===(i=l.encodings)||void 0===i?void 0:i[0];se()&&!u&&(n.encodings=[s]),u&&Object.assign(u,s),Object.assign(l,n),B.debug("[".concat(e.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(l.encodings))),await t.setParameters(l),await async function(e,t,i){try{var n;if(!o().supportSetRtpSenderParameters)return;if(!function(e){return"vp9"===e||"av1"===e}(e)||!ne("ENABLE_SVC"))return;const a={},s={},r=t.getParameters(),c=null===(n=r.encodings)||void 0===n?void 0:n[0];s.scalabilityMode=jn(i),c&&Object.assign(c,s),Object.assign(r,a),await t.setParameters(r),B.debug("[updateAdaptation] updateRtpSenderEncodings scalabilityMode success: ".concat(JSON.stringify(r.encodings)))}catch(e){B.debug("[updateAdaptation] updateRtpSenderEncodings scalabilityMode failed",e)}}(this.store.codec,t,ne("SVC_MODE"))}async updateAdaptation(e,t){var i;if(!e)return B.debug("[updateAdaptation] no rtpSender found");if(!o().supportSetRtpSenderParameters)return B.debug("[updateAdaptation] Browser not support set rtp-sender parameters");const n={},{bitrateMax:a,frameRate:s,scaleResolutionDownBy:r}=t;a&&(n.maxBitrate=1e3*a),s&&(n.maxFramerate=Ln(s)),r&&r>=1&&["vp8","vp9"].includes(this.store.codec)&&(n.scaleResolutionDownBy=r);const c=e.getParameters(),d=null===(i=c.encodings)||void 0===i?void 0:i[0];d&&Object.assign(d,n),Object.assign(c,{});try{await e.setParameters(c),B.debug("[updateAdaptation] updateRtpSenderEncodings: ".concat(JSON.stringify(c.encodings)))}catch(t){!("transport"in e)||e.transport&&"connected"===e.transport.state?"connected"!==this.peerConnectionState?B.debug("[updateAdaptation] peerConnection not connected}"):B.debug("[updateAdaptation] updateRtpSenderEncodings failed",t):B.debug("[updateAdaptation] rtpSender transport not connected}")}}async applySendEncodings(e,t){try{if(!o().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let i=0;i<e.length;i++){const o=e[i],a=t[i];a instanceof n&&!this.isVP8Simulcast(a)&&await this.updateRtpSenderEncodings(a,o.sender)}}catch(e){B.debug("[".concat(this.store.clientId,"] Apply RTPSendEncodings failed."))}}mungSendOfferSDP(e,t,i){const o=ge(e);return t.forEach(((e,t)=>{const a=i[t],s=o.mediaDescriptions.find((e=>e.attributes.mid===a));s&&(Zn(s,e),function(e,t,i){if(se())return;if("video"!==e.media.mediaType)return;if(!(t instanceof n))return;if("vp9"!==i&&"vp8"!==i)return;if("vp8"===i&&!ne("SIMULCAST"))return;if("vp9"===i&&ne("ENABLE_SVC"))return;if(void 0===t._scalabilityMode||t._scalabilityMode.numSpatialLayers<=1)return;const o="vp8"===i?2:t._scalabilityMode.numSpatialLayers,a=e.attributes.ssrcs[0],s=e.attributes.ssrcGroups.find((e=>"FID"===e.semantic&&e.ssrcIds[0]===a.ssrcId)),r={semantic:"SIM",ssrcIds:[a.ssrcId]};for(let t=1;t<o;t++)e.attributes.ssrcs.push({ssrcId:a.ssrcId+t,attributes:ve(a.attributes)}),r.ssrcIds.push(a.ssrcId+t),s&&(e.attributes.ssrcs.push({ssrcId:s.ssrcIds[1]+t,attributes:ve(a.attributes)}),e.attributes.ssrcGroups.push({semantic:"FID",ssrcIds:[a.ssrcId+t,s.ssrcIds[1]+t]}));e.attributes.ssrcGroups.unshift(r)}(s,e,this.store.codec))})),ye(o)}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=e=>{var t;null===(t=this.onFirstAudioReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoReceived=e=>{var t;null===(t=this.onFirstVideoReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstAudioDecoded=e=>{var t;null===(t=this.onFirstAudioDecoded)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoDecoded=(e,t,i)=>{var n;null===(n=this.onFirstVideoDecoded)||void 0===n||n.call(this,e,t,i)},this.statsFilter.onSelectedLocalCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedLocalCandidateChanged)||void 0===i||i.call(this,e,t)},this.statsFilter.onSelectedRemoteCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedRemoteCandidateChanged)||void 0===i||i.call(this,e,t)},this.statsFilter.onFirstVideoDecodedTimeout=e=>{var t;null===(t=this.onFirstVideoDecodedTimeout)||void 0===t||t.call(this,e)}}unbindStatsEvents(){this.statsFilter.onFirstAudioReceived=void 0,this.statsFilter.onFirstVideoReceived=void 0,this.statsFilter.onFirstAudioDecoded=void 0,this.statsFilter.onFirstVideoDecoded=void 0,this.statsFilter.onSelectedLocalCandidateChanged=void 0,this.statsFilter.onSelectedRemoteCandidateChanged=void 0,this.statsFilter.onFirstVideoDecodedTimeout=void 0}async applySimulcastForFirefox(e,t){if(e.length===t.length)for(let c=0;c<e.length;c++){var i,o,s,r;const d=e[c],l=t[c];if(l instanceof n&&!l._hints.includes(a.LOW_STREAM)&&null!==(i=l._encoderConfig)&&void 0!==i&&i.bitrateMax&&(null===(o=l._encoderConfig)||void 0===o?void 0:o.bitrateMax)>200&&null!==(s=l._scalabilityMode)&&void 0!==s&&s.numSpatialLayers&&(null===(r=l._scalabilityMode)||void 0===r?void 0:r.numSpatialLayers)>1&&"vp8"===this.store.codec){const e={},t={high:1e3*(l._encoderConfig.bitrateMax-50),medium:5e4};e.encodings=[{rid:"m",active:!0,maxBitrate:t.medium,scaleResolutionDownBy:4},{rid:"h",active:!0,maxBitrate:t.high}];const i=d.sender.getParameters();await d.sender.setParameters(Object.assign(i,e))}}}async applySimulcastEncodings(e,t){if(!se()&&e.length===t.length)for(let i=0;i<e.length;i++){const o=t[i];if(o instanceof n&&this.isVP8Simulcast(o)){const t=e[i],n={},a={high:1e3*(o._encoderConfig.bitrateMax-50),medium:5e4};n.encodings=[{active:!0,adaptivePtime:!1,networkPriority:"high",priority:"high",maxBitrate:a.high},{active:!0,adaptivePtime:!1,networkPriority:"low",priority:"low",maxBitrate:a.medium,scaleResolutionDownBy:4}];const s=t.sender.getParameters();await t.sender.setParameters(Object.assign(s,n))}}}isVP8Simulcast(e){var t,i,o,s;return!!(e instanceof n&&ne("SIMULCAST")&&"vp8"===this.store.codec&&!e._hints.includes(a.LOW_STREAM)&&null!==(t=e._encoderConfig)&&void 0!==t&&t.bitrateMax&&(null===(i=e._encoderConfig)||void 0===i?void 0:i.bitrateMax)>200&&null!==(o=e._scalabilityMode)&&void 0!==o&&o.numSpatialLayers&&(null===(s=e._scalabilityMode)||void 0===s?void 0:s.numSpatialLayers)>1)}logSDPExchange(e,t,i,n){if(ne("SDP_LOGGING"))return B.upload("[".concat(this.store.clientId,"] exchanging ").concat(i," ").concat(t," SDP during P2PConnection.").concat(n,"\n"),e),"offer"===t?e=>{this.logSDPExchange(e,"answer","local"===i?"remote":"local",n)}:void 0}async getRemoteSSRC(e){if(!this.remoteSDP)return;const t=this.remoteSDP.getSSRC(e);return t&&0!==t.length?t[0].ssrcId:void 0}setConfiguration(t){if(o().supportPCSetConfiguration){const i=e.resolvePCConfiguration(t);this.peerConnection.setConfiguration(i)}t.isPreallocation&&(this.isPreallocation=!0)}},li(ga.prototype,"updateRemoteRTPCapabilities",[ya],Object.getOwnPropertyDescriptor(ga.prototype,"updateRemoteRTPCapabilities"),ga.prototype),li(ga.prototype,"connect",[ya],Object.getOwnPropertyDescriptor(ga.prototype,"connect"),ga.prototype),li(ga.prototype,"updateRemoteConnect",[ya],Object.getOwnPropertyDescriptor(ga.prototype,"updateRemoteConnect"),ga.prototype),li(ga.prototype,"createDataChannels",[ya],Object.getOwnPropertyDescriptor(ga.prototype,"createDataChannels"),ga.prototype),li(ga.prototype,"receive",[ya],Object.getOwnPropertyDescriptor(ga.prototype,"receive"),ga.prototype),li(ga.prototype,"batchReceive",[ya],Object.getOwnPropertyDescriptor(ga.prototype,"batchReceive"),ga.prototype),li(ga.prototype,"stopReceiving",[ya],Object.getOwnPropertyDescriptor(ga.prototype,"stopReceiving"),ga.prototype),li(ga.prototype,"muteRemote",[ya],Object.getOwnPropertyDescriptor(ga.prototype,"muteRemote"),ga.prototype),li(ga.prototype,"unmuteRemote",[ya],Object.getOwnPropertyDescriptor(ga.prototype,"unmuteRemote"),ga.prototype),li(ga.prototype,"muteLocal",[ya],Object.getOwnPropertyDescriptor(ga.prototype,"muteLocal"),ga.prototype),li(ga.prototype,"unmuteLocal",[ya],Object.getOwnPropertyDescriptor(ga.prototype,"unmuteLocal"),ga.prototype),li(ga.prototype,"close",[ya],Object.getOwnPropertyDescriptor(ga.prototype,"close"),ga.prototype),li(ga.prototype,"updateEncoderConfig",[ya],Object.getOwnPropertyDescriptor(ga.prototype,"updateEncoderConfig"),ga.prototype),li(ga.prototype,"updateSendParameters",[ya],Object.getOwnPropertyDescriptor(ga.prototype,"updateSendParameters"),ga.prototype),li(ga.prototype,"replaceTrack",[ya],Object.getOwnPropertyDescriptor(ga.prototype,"replaceTrack"),ga.prototype),li(ga.prototype,"updateAdaptation",[ya],Object.getOwnPropertyDescriptor(ga.prototype,"updateAdaptation"),ga.prototype),li(ga.prototype,"getRemoteSSRC",[ya],Object.getOwnPropertyDescriptor(ga.prototype,"getRemoteSSRC"),ga.prototype),ga);function ya(e,t,i){const n=e[t];if("function"!=typeof n)throw new Error("Cannot use mutex on object property.");return i.value=async function(){const e=this.mutex,i=await e.lock("From P2PConnection.".concat(t));try{for(var o=arguments.length,a=new Array(o),s=0;s<o;s++)a[s]=arguments[s];return await n.apply(this,a)}finally{i()}},i}function Na(e,t){let i=document.createElement("video"),n=document.createElement("canvas");i.setAttribute("style","display:none"),n.setAttribute("style","display:none"),i.setAttribute("muted",""),i.muted=!0,i.setAttribute("autoplay",""),i.autoplay=!0,i.setAttribute("playsinline",""),n.width=Ln(t.width),n.height=Ln(t.height);const a=Ln(t.framerate||15);document.body.append(i),document.body.append(n);let s=e._mediaStreamTrack;i.srcObject=new MediaStream([s]),i.play();const r=n.getContext("2d");if(!r)throw new F(Z.UNEXPECTED_ERROR,"can not get canvas context");const c=o(),d=n.captureStream(c.supportRequestFrame?0:a).getVideoTracks()[0];d.canvas||(d.canvas=n),n.startCapture=()=>{if(!i)return n.stopCapture&&n.stopCapture();if(i.paused&&i.play(),i.videoHeight>2&&i.videoWidth>2){const e=i.videoWidth,t=i.videoHeight/e,o=n.width*t;Math.abs(o-n.height)>=2&&(B.debug("adjust low stream resolution","".concat(n.width,"x").concat(n.height," -> ").concat(n.width,"x").concat(o)),n.height=o)}r.drawImage(i,0,0,n.width,n.height),d.requestFrame&&d.requestFrame(),s!==e._mediaStreamTrack&&(s=e._mediaStreamTrack,i.srcObject=new MediaStream([s]))},n.stopCapture=f((()=>n.startCapture&&n.startCapture()),a);const l=d.stop;return d.stop=()=>{l.call(d),i&&(i.remove(),i.srcObject=null,i=null),n&&(n.width=0,n.remove(),n.stopCapture&&n.stopCapture(),n.startCapture=void 0,n.stopCapture=void 0,n=null),B.debug("clean low stream renderer")},d}var ba=function(e){return e[e.Video_Send_Type=190]="Video_Send_Type",e}(ba||{}),wa=function(e){return e[e.Video_Send_Qp_Sum=2143]="Video_Send_Qp_Sum",e[e.Video_Send_Freeze=2082]="Video_Send_Freeze",e[e.Video_Recv_Qp_Sum=2144]="Video_Recv_Qp_Sum",e[e.Video_Recv_Freeze=2084]="Video_Recv_Freeze",e[e.Video_Render_Freeze_Time=2109]="Video_Render_Freeze_Time",e[e.Video_Render_Freeze_Time_Render=2147]="Video_Render_Freeze_Time_Render",e[e.Video_Render_Freeze_Time_Render2=2223]="Video_Render_Freeze_Time_Render2",e[e.Audio_Recv_Freeze=2083]="Audio_Recv_Freeze",e}(wa||{}),Oa=function(e){return e[e.Video_Send_Retransmit=2062]="Video_Send_Retransmit",e[e.Video_Send_Target_Encoded=2064]="Video_Send_Target_Encoded",e[e.Video_Send_Actual_Encoded=2060]="Video_Send_Actual_Encoded",e[e.Video_Send_Transmit=2066]="Video_Send_Transmit",e[e.Video_Send_Bandwidth=2061]="Video_Send_Bandwidth",e[e.Video_Capture_Height=2033]="Video_Capture_Height",e[e.Video_Capture_Width=2035]="Video_Capture_Width",e[e.Video_Capture_Frame_Rate=2034]="Video_Capture_Frame_Rate",e[e.Video_Send_Low_Height=2073]="Video_Send_Low_Height",e[e.Video_Send_Low_Frame_Rate=2075]="Video_Send_Low_Frame_Rate",e[e.Video_Send_Low_Width=2077]="Video_Send_Low_Width",e[e.Video_Send_Low_Bitrate=2069]="Video_Send_Low_Bitrate",e[e.Video_Send_Low_Package_Lost=2070]="Video_Send_Low_Package_Lost",e[e.Video_Send_Low_Package_Rate=2071]="Video_Send_Low_Package_Rate",e[e.Video_Send_Frame_Rate=2002]="Video_Send_Frame_Rate",e[e.Video_Send_Width=2003]="Video_Send_Width",e[e.Video_Send_Height=2004]="Video_Send_Height",e[e.Video_Send_Disabled=2095]="Video_Send_Disabled",e[e.Video_Send_Adaptation=2032]="Video_Send_Adaptation",e[e.Video_Send_Player_Status=2128]="Video_Send_Player_Status",e[e.Video_Send_Nacks=2009]="Video_Send_Nacks",e[e.Video_Send_Plis=2010]="Video_Send_Plis",e[e.Video_Send_Firs=2011]="Video_Send_Firs",e[e.Video_Send_Avg_Encode=2007]="Video_Send_Avg_Encode",e[e.Video_Send_Huge_Frame_Sent=2174]="Video_Send_Huge_Frame_Sent",e[e.Video_Send_Bytes_Retransmit=2173]="Video_Send_Bytes_Retransmit",e[e.Video_Send_Packages_Retransmit=2172]="Video_Send_Packages_Retransmit",e[e.Video_Send_Key_Frames_Encoded=2207]="Video_Send_Key_Frames_Encoded",e[e.Video_Send_Bitrate=2012]="Video_Send_Bitrate",e[e.Video_Send_Package_Rate=2031]="Video_Send_Package_Rate",e[e.Video_Send_Package_Lost=2005]="Video_Send_Package_Lost",e[e.Audio_Capture_PCM_Level=2104]="Audio_Capture_PCM_Level",e[e.Audio_Send_Level=2038]="Audio_Send_Level",e[e.Audio_Send_Bitrate=2039]="Audio_Send_Bitrate",e[e.Audio_Send_Package_Rate=2040]="Audio_Send_Package_Rate",e[e.Audio_Send_AEC_Return_Loss=2041]="Audio_Send_AEC_Return_Loss",e[e.Audio_Send_AEC_Return_Loss_Enhancement=2042]="Audio_Send_AEC_Return_Loss_Enhancement",e[e.Audio_Send_Freeze=2081]="Audio_Send_Freeze",e[e.Audio_Send_Disabled=2096]="Audio_Send_Disabled",e[e.Audio_Send_Bytes_Retransmit=2179]="Audio_Send_Bytes_Retransmit",e[e.Audio_Send_Packages_Retransmit=2180]="Audio_Send_Packages_Retransmit",e[e.Video_Recv_Height=2019]="Video_Recv_Height",e[e.Video_Recv_Width=2018]="Video_Recv_Width",e[e.Video_Recv_Frame_Rate_Output=2155]="Video_Recv_Frame_Rate_Output",e[e.Video_Recv_Jitter_Buffer=2023]="Video_Recv_Jitter_Buffer",e[e.Video_Recv_Current_Delay=2024]="Video_Recv_Current_Delay",e[e.Video_Recv_Nacks=2026]="Video_Recv_Nacks",e[e.Video_Recv_Plis=2027]="Video_Recv_Plis",e[e.Video_Recv_Firs=2028]="Video_Recv_Firs",e[e.Video_Recv_Disabled=2101]="Video_Recv_Disabled",e[e.Video_Recv_Player_Status=2129]="Video_Recv_Player_Status",e[e.Video_Recv_I_Frame_Delay=2149]="Video_Recv_I_Frame_Delay",e[e.Video_Render_Frame_Rate_Render=2022]="Video_Render_Frame_Rate_Render",e[e.Video_Render_Freeze_Duration=2156]="Video_Render_Freeze_Duration",e[e.Audio_Render_Level=2043]="Audio_Render_Level",e[e.Audio_Render_Freeze_Time_80ms=2226]="Audio_Render_Freeze_Time_80ms",e[e.Audio_Render_Freeze_Time_200ms=2227]="Audio_Render_Freeze_Time_200ms",e[e.Audio_Render_Freeze_Samples_80ms=2228]="Audio_Render_Freeze_Samples_80ms",e[e.Audio_Render_Freeze_Samples_200ms=2229]="Audio_Render_Freeze_Samples_200ms",e[e.Audio_Recv_PCM_Level=2105]="Audio_Recv_PCM_Level",e[e.Audio_Recv_Disabled=2102]="Audio_Recv_Disabled",e[e.Audio_Recv_Jitter_Buffer=2054]="Audio_Recv_Jitter_Buffer",e[e.Audio_Recv_Current_Delay=2047]="Audio_Recv_Current_Delay",e[e.Audio_Recv_Player_Status=2130]="Audio_Recv_Player_Status",e[e.Audio_Recv_Bitrate=2044]="Audio_Recv_Bitrate",e[e.Audio_Recv_Concealed_Samples=2148]="Audio_Recv_Concealed_Samples",e[e.Audio_Recv_Total_Samples_Received=2224]="Audio_Recv_Total_Samples_Received",e}(Oa||{}),Da=function(e){return e[e.Video_Render_Frame_Rate_Decode=2021]="Video_Render_Frame_Rate_Decode",e[e.Video_Recv_Frame_Rate=2020]="Video_Recv_Frame_Rate",e[e.Video_Recv_Frame_Dropped=2181]="Video_Recv_Frame_Dropped",e[e.Video_Recv_Bytes_Retransmit=2175]="Video_Recv_Bytes_Retransmit",e[e.Video_Recv_Packages_Retransmit=2176]="Video_Recv_Packages_Retransmit",e[e.Video_Recv_Packages_Discarded=2198]="Video_Recv_Packages_Discarded",e[e.Video_Recv_Avg_Decode=2200]="Video_Recv_Avg_Decode",e[e.Video_Recv_Avg_Processing_Delay=2202]="Video_Recv_Avg_Processing_Delay",e[e.Video_Recv_Avg_Assembly_Time=2203]="Video_Recv_Avg_Assembly_Time",e[e.Video_Recv_Avg_Inter_Frame_Delay=2204]="Video_Recv_Avg_Inter_Frame_Delay",e[e.Video_Recv_Key_Frames_Decoded=2206]="Video_Recv_Key_Frames_Decoded",e[e.Video_Recv_Package_Lost=2014]="Video_Recv_Package_Lost",e[e.Video_Recv_Bitrate=2029]="Video_Recv_Bitrate",e[e.Video_Recv_Package_Rate=2078]="Video_Recv_Package_Rate",e[e.Audio_Recv_Jitter=2055]="Audio_Recv_Jitter",e[e.Audio_Recv_Bytes_Retransmit=2178]="Audio_Recv_Bytes_Retransmit",e[e.Audio_Recv_Packages_Retransmit=2177]="Audio_Recv_Packages_Retransmit",e[e.Audio_Recv_Packages_Discarded=2199]="Audio_Recv_Packages_Discarded",e[e.Audio_Recv_Avg_Processing_Delay=2201]="Audio_Recv_Avg_Processing_Delay",e[e.Audio_Recv_Package_Rate=2046]="Audio_Recv_Package_Rate",e[e.Audio_Recv_Package_Lost=2045]="Audio_Recv_Package_Lost",e}(Da||{}),Pa=function(e){return e[e.RTT=2006]="RTT",e[e.CONN_TYPE=801]="CONN_TYPE",e[e.STATS_UPDATE_INTERVAL=2205]="STATS_UPDATE_INTERVAL",e}(Pa||{}),La=function(e){return e[e.RTC_PEER_CONNECTION_STATE=2219]="RTC_PEER_CONNECTION_STATE",e}(La||{});const ka=1e3,Ua=6,Ma=3,Va=Math.max(Ua,Ma,60);function xa(e,t,i){null!=i&&Number.isFinite(i)&&(e[t]=Math.round(Math.max(0,i)))}function Ba(e){const t={[Pa.CONN_TYPE]:0,[Pa.RTT]:e.rtt,[Pa.STATS_UPDATE_INTERVAL]:e.updateInterval?Math.round(Math.max(0,e.updateInterval)):void 0};switch(e.selectedCandidatePair.localCandidate.candidateType){case"relay":{const i=e.selectedCandidatePair.localCandidate.relayProtocol;"udp"===i&&(t[Pa.CONN_TYPE]=1),"tcp"===i&&(t[Pa.CONN_TYPE]=3),"tls"===i&&(t[Pa.CONN_TYPE]=4);break}case"srflx":t[Pa.CONN_TYPE]=2;break;case"unknown":t[Pa.CONN_TYPE]=5;break;default:t[Pa.CONN_TYPE]=0}return t}function Fa(e){let t=0;switch(e){case"none":t=0;break;case"cpu":t=1;break;case"bandwidth":t=2;break;case"other":t=3}return t}class ja extends ie{constructor(e){super(),this.store=void 0,this.uploadWRTCStatsTimer=void 0,this.uploadOutboundDenoiserStatsTimer=void 0,this.uploadExtStatsTimer=void 0,this.uploadExtUsageStatsTimer=void 0,this.uploadInboundExtStatsTimer=void 0,this.requestStats=void 0,this.requestTransportStats=void 0,this.requestLocalMedia=void 0,this.requestRemoteMedia=void 0,this.requestAllTracks=void 0,this.requestVideoIsReady=void 0,this.requestUploadStats=void 0,this.requestUpload=void 0,this.uploadOutboundStarted=!1,this.uploadInboundStarted=!1,this.uploadTransportStarted=!1,this.uploadBaseStatsStarted=!1,this.uploadExtensionUsageStarted=!1,this.lastRecvStats=void 0,this.lastSendStats=void 0,this.lastRefRecvStats=void 0,this.lastRefSendStats=void 0,this.lastNormalRecvStats=void 0,this.lastNormalSendStats=void 0,this.lastExtendStats={},this.needUploadStats={},this.needUploadRenderFreezeTime=!0,this.lastUploadCompensateTime=-1,this.uploadCompensateDeltaTime=0,this.store=e}uploadWRTCStats(e){if(!this.requestStats||!this.requestUploadStats)return;const t=e%Ma==0,i=e%Ua==0,n=e%60==0;let o,a;if(this.uploadTransportStarted&&(o=this.requestStats(),this.store.useP2P&&(a=this.requestStats(!0))),!o&&this.uploadOutboundStarted&&(o=this.requestStats()),!a&&this.uploadInboundStarted&&(a=this.requestStats(!0)),o||a){var s;const r={};if(this.uploadTransportStarted&&o){const e=this.getTransportStats(o,a,t);e&&(r.misc=[e])}if(this.uploadOutboundStarted&&o){const e=this.getOutboundStats(o,i?this.lastNormalSendStats:void 0,t?this.lastRefSendStats:void 0,this.lastSendStats,n);e&&(r.outbound=[e])}if(this.uploadInboundStarted&&a){this.uploadCompensateStats(e);const n=this.getInboundStats(a,i?this.lastNormalRecvStats:void 0,t?this.lastRefRecvStats:void 0,this.lastRecvStats);n&&(r.inbound=n)}const c=null===(s=this.requestTransportStats)||void 0===s?void 0:s.call(this).connectState;c&&(Array.isArray(r.misc)?r.misc[0]&&r.misc[0].addition&&(r.misc[0].addition[La.RTC_PEER_CONNECTION_STATE]=dt[c]):r.misc=[{addition:{[La.RTC_PEER_CONNECTION_STATE]:dt[c]}}]),this.needUploadStats.sendType&&(Array.isArray(r.outbound)&&r.outbound[0]&&r.outbound[0].high&&(r.outbound[0].high[ba.Video_Send_Type]=this.needUploadStats.sendType),this.needUploadStats.sendType=void 0),this.requestUploadStats(r)}this.lastRecvStats=a,this.lastSendStats=o,i&&(this.lastNormalRecvStats=a,this.lastNormalSendStats=o),t&&(this.lastRefRecvStats=a,this.lastRefSendStats=o)}startUploadWRTCStats(){if(this.uploadWRTCStatsTimer)return;this.uploadBaseStatsStarted=!0;let e=1;this.uploadWRTCStatsTimer=window.setInterval((()=>{if(!this.uploadTransportStarted&&!this.uploadInboundStarted&&!this.uploadOutboundStarted){if(this.uploadBaseStatsStarted){var t,i;const e=null===(t=this.requestTransportStats)||void 0===t?void 0:t.call(this);return void(e&&(null===(i=this.requestUploadStats)||void 0===i||i.call(this,{misc:[{addition:{[La.RTC_PEER_CONNECTION_STATE]:dt[e.connectState]}}]})))}return this.stopUploadWRTCStats()}this.uploadWRTCStats(e),++e===Va+1&&(e=1)}),ka)}uploadCompensateStats(e){if(!this.requestStats||!this.requestUploadStats||!this.requestRemoteMedia)return;const t=e%Ma==0&&this.needUploadRenderFreezeTime;if(!this.uploadInboundStarted||!t)return;if(-1===this.lastUploadCompensateTime)return void(this.lastUploadCompensateTime=Date.now());const i=Math.max(-6e3,Date.now()-this.lastUploadCompensateTime-6e3);if(this.uploadCompensateDeltaTime+=i,this.lastUploadCompensateTime=Date.now(),this.uploadCompensateDeltaTime<6e3)return;const n=Math.min(Math.floor(this.uploadCompensateDeltaTime/6e3),10);this.uploadCompensateDeltaTime-=6e3*n;const a=this.requestStats(!0);new Array(n).fill(0).forEach((()=>{if(!this.requestStats||!this.requestUploadStats||!this.requestRemoteMedia)return;const e={};if(this.uploadInboundStarted&&a){const t=this.requestRemoteMedia()||[],i=[];t.forEach((e=>{let[t,n]=e;const s={peer:t.uid};if((t._videoSSRC&&this.requestVideoIsReady&&this.requestVideoIsReady(t._videoSSRC)||!1)&&n.has(Zi.VIDEO)&&t.videoTrack){const e=function(e,t,i){if(!t.videoRecv.find((t=>t.ssrc===e)))return;const n={};if(i&&i._player){const e=i._player,{renderFreezeAccTime2:t,videoElementStatus:a}=e;if("visible"===T.visibility&&a===I.PLAYING&&o().supportRequestVideoFrameCallback){const i=Math.min(6e3,t);e.renderFreezeAccTime2=Math.max(0,t-i),xa(n,wa.Video_Render_Freeze_Time_Render2,i),ne("USE_NEW_RENDER_FREEZE_TIME")&&xa(n,wa.Video_Render_Freeze_Time_Render,i)}}return n}(t._videoSSRC,a,t.videoTrack);e&&(s.video=e)}s.video&&i.push(s)})),i.length>0&&(e.inbound=i,this.requestUploadStats(e))}}))}stopUploadWRTCStats(){window.clearInterval(this.uploadWRTCStatsTimer),this.uploadWRTCStatsTimer=void 0,this.lastSendStats&&(this.lastSendStats.videoSend=[],this.lastSendStats.audioSend=[],this.lastSendStats=void 0),this.lastRecvStats&&(this.lastRecvStats.videoRecv=[],this.lastRecvStats.audioRecv=[],this.lastRecvStats=void 0),this.lastRefSendStats&&(this.lastRefSendStats.videoSend=[],this.lastRefSendStats.audioSend=[],this.lastRefSendStats=void 0),this.lastRefRecvStats&&(this.lastRefRecvStats.videoRecv=[],this.lastRefRecvStats.audioRecv=[],this.lastRefRecvStats=void 0),this.lastNormalSendStats&&(this.lastNormalSendStats.videoSend=[],this.lastNormalSendStats.audioSend=[],this.lastNormalSendStats=void 0),this.lastNormalRecvStats&&(this.lastNormalRecvStats.videoRecv=[],this.lastNormalRecvStats.audioRecv=[],this.lastNormalRecvStats=void 0),this.lastExtendStats={},this.needUploadStats={},this.lastUploadCompensateTime=-1,this.uploadCompensateDeltaTime=0,this.needUploadRenderFreezeTime=!0}getTransportStats(e,t,i){if(!this.requestStats)return;if(!i)return null==e.rtt?void 0:{addition:{[Pa.RTT]:e.rtt,[Pa.CONN_TYPE]:void 0,[Pa.STATS_UPDATE_INTERVAL]:e.updateInterval||void 0}};const n=Ba(e);if(this.store.useP2P){if(t){const e=Ba(t);n[Pa.CONN_TYPE]+=e[Pa.CONN_TYPE]<<3}n[Pa.CONN_TYPE]+=110}else n[Pa.CONN_TYPE]+=100;return{addition:n}}getOutboundStats(e,t,i,n,o){if(!this.requestUploadStats||!this.requestLocalMedia)return;const s=this.requestLocalMedia();if(!s||0===s.length)return;let r,c,d;return s.forEach((n=>{let[s,{track:l,ssrcs:u}]=n;switch(s){case nn.LocalVideoLowTrack:case nn.LocalVideoTrack:if(s===nn.LocalVideoTrack){const n=function(e,t,i,n,o,a){const s=t.videoSend.find((t=>t.ssrc===e));if(!s)return;const r={},{sentFrame:c,inputFrame:d}=s;if(n&&(xa(r,wa.Video_Send_Qp_Sum,s.qpSumPerFrame),d&&c)){const e=d.frameRate,t=c.frameRate;r[wa.Video_Send_Freeze]=function(e,t){let i=!0;return i=!(e<=5)&&(e<=10?t<3:e<=20?t<4:t<5),i}(e,t)?1:0}if(o){switch(c&&(xa(r,Oa.Video_Send_Height,c.height),xa(r,Oa.Video_Send_Width,c.width),xa(r,Oa.Video_Send_Frame_Rate,c.frameRate)),r[Oa.Video_Send_Disabled]=i._originMediaStreamTrack&&!i._originMediaStreamTrack.enabled||i._mediaStreamTrack&&!i._mediaStreamTrack.enabled?1:0,s.adaptionChangeReason){case"none":r[Oa.Video_Send_Adaptation]=0;break;case"cpu":r[Oa.Video_Send_Adaptation]=1;break;case"bandwidth":r[Oa.Video_Send_Adaptation]=2;break;case"other":r[Oa.Video_Send_Adaptation]=3}let n=0;s.adaptionChangeReason&&(n+=Fa(s.adaptionChangeReason)),t.qualityLimitationReason&&(n+=Fa(t.qualityLimitationReason)<<3),r[Oa.Video_Send_Adaptation]=n,r[Oa.Video_Send_Player_Status]=C[i._player?i._player.videoElementStatus:"uninit"],xa(r,Oa.Video_Send_Nacks,s.nacksCount),xa(r,Oa.Video_Send_Plis,s.plisCount),xa(r,Oa.Video_Send_Firs,s.firsCount),xa(r,Oa.Video_Send_Avg_Encode,s.avgEncodeMs),xa(r,Oa.Video_Send_Huge_Frame_Sent,s.hugeFramesSent),xa(r,Oa.Video_Send_Bytes_Retransmit,s.retransmittedBytesSent),xa(r,Oa.Video_Send_Packages_Retransmit,s.retransmittedPacketsSent),xa(r,Oa.Video_Send_Key_Frames_Encoded,s.keyFramesEncoded);const a=o.videoSend.find((t=>t.ssrc===e));if(a){let e=ka*Ma;a.timestamp&&s.timestamp&&(e=s.timestamp-a.timestamp),null!=a.packets&&null!=s.packets&&xa(r,Oa.Video_Send_Package_Rate,1e3*(s.packets-a.packets)/e),null!=s.packetsLost&&null!=a.packetsLost&&xa(r,Oa.Video_Send_Package_Lost,s.packetsLost-a.packetsLost),null!=a.bytes&&null!=s.bytes&&xa(r,Oa.Video_Send_Bitrate,8*(s.bytes-a.bytes)/e)}}return r}(u[0].ssrcId,e,l,t,i),s="CameraVideoTrack"===l.__className__?3:l._hints.includes(a.SCREEN_TRACK)?7:10;(this.lastExtendStats.sendType!==s||o)&&(this.needUploadStats={sendType:s},this.lastExtendStats.sendType=s);const r=l&&function(e,t,i,n){const o=t.videoSend.find((t=>t.ssrc===e));if(!o)return null;const a={};if(n){const e=o.inputFrame,t=e&&e.height||i.videoHeight||0,n=e&&e.width||i.videoWidth||0,s=e&&e.frameRate||0;xa(a,Oa.Video_Capture_Height,t),xa(a,Oa.Video_Capture_Width,n),xa(a,Oa.Video_Capture_Frame_Rate,s)}return a}(u[0].ssrcId,e,l,!!i),d=function(e,t){const i={};return t&&(xa(i,Oa.Video_Send_Retransmit,e.bitrate.retransmit),xa(i,Oa.Video_Send_Target_Encoded,e.bitrate.targetEncoded),xa(i,Oa.Video_Send_Actual_Encoded,e.bitrate.actualEncoded),xa(i,Oa.Video_Send_Transmit,e.bitrate.transmit),xa(i,Oa.Video_Send_Bandwidth,e.sendBandwidth)),i}(e,!!i);c=Object.assign({},n,r,d)}else d=function(e,t,i,n,o){const a=t.videoSend.find((t=>t.ssrc===e));if(!a)return;const s={};if(n){const t=a.sentFrame;t&&(xa(s,Oa.Video_Send_Low_Height,t.height),xa(s,Oa.Video_Send_Low_Width,t.width),xa(s,Oa.Video_Send_Low_Frame_Rate,t.frameRate));const i=n.videoSend.find((t=>t.ssrc===e));if(i){let e=ka*Ua;i.timestamp&&a.timestamp&&(e=a.timestamp-i.timestamp),null!=i.packets&&null!=a.packets&&xa(s,Oa.Video_Send_Low_Package_Rate,1e3*(a.packets-i.packets)/e),null!=a.packetsLost&&null!=i.packetsLost&&xa(s,Oa.Video_Send_Low_Package_Lost,a.packetsLost-i.packetsLost),null!=i.bytes&&null!=a.bytes&&xa(s,Oa.Video_Send_Low_Bitrate,8*(a.bytes-i.bytes)/e)}}return s}(u[0].ssrcId,e,0,i);break;case nn.LocalAudioTrack:r=l&&function(e,t,i,n,o,a){const s=t.audioSend.find((t=>t.ssrc===e));if(!s)return;const r={};if(o){r[Oa.Audio_Send_Disabled]=i._originMediaStreamTrack&&!i._originMediaStreamTrack.enabled||i._mediaStreamTrack&&!i._mediaStreamTrack.enabled?1:0;const t=100*i._source.getAccurateVolumeLevel(),n=s.inputLevel;if(null!=n){const e=Math.ceil(50*Math.log10(100*n+1));xa(r,Oa.Audio_Send_Level,e)}xa(r,Oa.Audio_Capture_PCM_Level,t),xa(r,Oa.Audio_Send_AEC_Return_Loss,s.aecReturnLoss),xa(r,Oa.Audio_Send_AEC_Return_Loss_Enhancement,s.aecReturnLossEnhancement),xa(r,Oa.Audio_Send_Bytes_Retransmit,s.retransmittedBytesSent),xa(r,Oa.Audio_Send_Packages_Retransmit,s.retransmittedPacketsSent),r[Oa.Audio_Send_Freeze]=0;const a=o.audioSend.find((t=>t.ssrc===e));if(a){let e=ka*Ua;a.timestamp&&s.timestamp&&(e=s.timestamp-a.timestamp),null!=a.bytes&&null!=s.bytes&&xa(r,Oa.Audio_Send_Bitrate,8*(s.bytes-a.bytes)/e),null!=a.packets&&null!=s.packets&&xa(r,Oa.Audio_Send_Package_Rate,1e3*(s.packets-a.packets)/e)}}return r}(u[0].ssrcId,e,l,0,i)}})),{high:c,low:d,audio:r}}getInboundStats(e,t,i,n){if(!this.requestRemoteMedia)return;const a=this.requestRemoteMedia()||[],s=[];return a.forEach((a=>{let[r,c]=a;const d={peer:r.uid};if(c.has(Zi.VIDEO)&&r.videoTrack){const a=r._videoSSRC&&this.requestVideoIsReady&&this.requestVideoIsReady(r._videoSSRC)||!1,s=r.videoTrack?function(e,t,i,n,a,s,r,c){const d=t.videoRecv.find((t=>t.ssrc===e));if(!d)return;const l={},{receivedFrame:u,outputFrame:h,decodeFrameRate:_}=d;xa(l,Da.Video_Render_Frame_Rate_Decode,_),d.framesRateFirefox&&xa(l,Da.Video_Recv_Frame_Rate,d.framesRateFirefox),u&&xa(l,Da.Video_Recv_Frame_Rate,u.frameRate),xa(l,Da.Video_Recv_Frame_Dropped,d.framesDroppedCount),xa(l,Da.Video_Recv_Bytes_Retransmit,d.retransmittedBytesReceived),xa(l,Da.Video_Recv_Packages_Retransmit,d.retransmittedPacketsReceived),xa(l,Da.Video_Recv_Packages_Discarded,d.packetsDiscarded),xa(l,Da.Video_Recv_Avg_Decode,d.avgDecodeMs),xa(l,Da.Video_Recv_Avg_Processing_Delay,d.avgProcessingDelayMs),xa(l,Da.Video_Recv_Avg_Assembly_Time,d.avgFramesAssembledFromMultiplePacketsMs),xa(l,Da.Video_Recv_Avg_Inter_Frame_Delay,d.avgInterFrameDelayMs),xa(l,Da.Video_Recv_Key_Frames_Decoded,d.keyFramesDecoded);const p=c&&c.videoRecv.find((t=>t.ssrc===e));if(p){const e=t.timestamp-c.timestamp||ka;null!=d.packetsLost&&null!=p.packetsLost&&xa(l,Da.Video_Recv_Package_Lost,d.packetsLost-p.packetsLost),null!=p.bytes&&null!=d.bytes&&xa(l,Da.Video_Recv_Bitrate,8*(d.bytes-p.bytes)/e),null!=p.packets&&null!=d.packets&&xa(l,Da.Video_Recv_Package_Rate,1e3*(d.packets-p.packets)/e)}const E=s&&s.videoRecv.find((t=>t.ssrc===e));if(E&&(xa(l,wa.Video_Recv_Qp_Sum,d.qpSumPerFrame),l[wa.Video_Recv_Freeze]=n&&ia.isRemoteVideoFreeze(i,d,E)?1:0),r){var S;const t=r.videoRecv.find((t=>t.ssrc===e));u?(xa(l,Oa.Video_Recv_Height,u.height),xa(l,Oa.Video_Recv_Width,u.width)):i&&(xa(l,Oa.Video_Recv_Height,i._videoHeight||0),xa(l,Oa.Video_Recv_Width,i._videoWidth||0)),h&&xa(l,Oa.Video_Recv_Frame_Rate_Output,h.frameRate);const n=null===(S=i._player)||void 0===S?void 0:S.rendFrameRate.toFixed(0);if(n&&xa(l,Oa.Video_Render_Frame_Rate_Render,+n),xa(l,Oa.Video_Recv_Jitter_Buffer,d.jitterBufferMs),xa(l,Oa.Video_Recv_Current_Delay,d.currentDelayMs),xa(l,Oa.Video_Recv_Firs,d.firsCount),xa(l,Oa.Video_Recv_Nacks,d.nacksCount),xa(l,Oa.Video_Recv_Plis,d.plisCount),i){l[Oa.Video_Recv_Disabled]=i._originMediaStreamTrack.enabled&&i._mediaStreamTrack.enabled?0:1;const e=i._player;if(e){const{freezeTimeCounterList:i,renderFreezeAccTime:n,renderFreezeAccTime2:s,videoElementStatus:r}=e;if(i&&i.length>0&&xa(l,wa.Video_Render_Freeze_Time,i.splice(0,1)[0]),a&&"visible"===T.visibility&&r===I.PLAYING&&o().supportRequestVideoFrameCallback){const t=Math.min(6e3,s);e.renderFreezeAccTime2=Math.max(0,s-t),xa(l,wa.Video_Render_Freeze_Time_Render2,t);const i=Math.min(6e3,n);e.renderFreezeAccTime=Math.max(0,n-i),xa(l,wa.Video_Render_Freeze_Time_Render,ne("USE_NEW_RENDER_FREEZE_TIME")?t:i)}if("number"==typeof d.totalFreezesDuration){const e=t&&t.totalFreezesDuration?d.totalFreezesDuration-t.totalFreezesDuration:d.totalFreezesDuration;xa(l,Oa.Video_Render_Freeze_Duration,1e3*e)}}}if(l[Oa.Video_Recv_Player_Status]=C[i._player?i._player.videoElementStatus:"uninit"],t&&void 0!==d.totalInterFrameDelay&&void 0!==d.totalSquaredInterFrameDelay&&void 0!==t.totalInterFrameDelay&&void 0!==t.totalSquaredInterFrameDelay){const e=d.totalInterFrameDelay-t.totalInterFrameDelay,i=d.totalSquaredInterFrameDelay-t.totalSquaredInterFrameDelay,n=d.framesDecodeCount-t.framesDecodeCount,o=e/n*1e3,a=Math.round(1e3*Math.sqrt((i-Math.pow(e,2)/n)/n));!isNaN(a)&&o+a>Math.max(3*o,o+150)&&(l[Oa.Video_Recv_I_Frame_Delay]=a)}}return l}(r._videoSSRC,e,r.videoTrack,!0===a,this.needUploadRenderFreezeTime,t,i,n):void 0;s&&(d.video=s)}if(c.has(Zi.AUDIO)&&r.audioTrack){const o=r.audioTrack?function(e,t,i,n,o,a){const s=t.audioRecv.find((t=>t.ssrc===e));if(!s)return;const r={};xa(r,Da.Audio_Recv_Jitter,s.jitterMs),xa(r,Da.Audio_Recv_Bytes_Retransmit,s.retransmittedBytesReceived),xa(r,Da.Audio_Recv_Packages_Retransmit,s.retransmittedPacketsReceived),xa(r,Da.Audio_Recv_Packages_Discarded,s.packetsDiscarded),xa(r,Da.Audio_Recv_Avg_Processing_Delay,s.avgProcessingDelayMs);const c=a&&a.audioRecv.find((t=>t.ssrc===e));if(c){const e=ka;null!=s.packets&&null!=c.packets&&xa(r,Da.Audio_Recv_Package_Rate,1e3*(s.packets-c.packets)/e),null!=s.packetsLost&&null!=c.packetsLost&&xa(r,Da.Audio_Recv_Package_Lost,s.packetsLost-c.packetsLost)}if(n){const{receivedFrames:e,droppedFrames:t}=s;null!=e&&null!=t&&(r[wa.Audio_Recv_Freeze]=0===(d=e)||100*t/d>20?1:0)}var d;if(o){const t=100*i._source.getAccurateVolumeLevel(),n=s.outputLevel;if(null!=n){const e=Math.ceil(50*Math.log10(100*n+1));xa(r,Oa.Audio_Render_Level,e)}xa(r,Oa.Audio_Recv_PCM_Level,t),i&&(r[Oa.Audio_Recv_Disabled]=i._originMediaStreamTrack.enabled&&i._mediaStreamTrack.enabled?0:1),xa(r,Oa.Audio_Recv_Jitter_Buffer,s.jitterBufferMs),xa(r,Oa.Audio_Recv_Current_Delay,s.jitterBufferMs),r[Oa.Audio_Recv_Player_Status]=C[A.getPlayerState(i.getTrackId())];const a=o.audioRecv.find((t=>t.ssrc===e));if(a){null!=a.bytes&&null!=s.bytes&&xa(r,Oa.Audio_Recv_Bitrate,8*(s.bytes-a.bytes)/(ka*Ma));const e=s.concealedSamples-a.concealedSamples;e>0&&xa(r,Oa.Audio_Recv_Concealed_Samples,e);const t=s.totalSamplesReceived-a.totalSamplesReceived;t>0&&xa(r,Oa.Audio_Recv_Total_Samples_Received,t);const i=s.freezeSamples80-a.freezeSamples80;i>0&&xa(r,Oa.Audio_Render_Freeze_Samples_80ms,i);const n=s.freezeSamples200-a.freezeSamples200;n>0&&xa(r,Oa.Audio_Render_Freeze_Samples_200ms,n);const o=s.freezeMs80-a.freezeMs80;xa(r,Oa.Audio_Render_Freeze_Time_80ms,o<0?0:o);const c=s.freezeMs200-a.freezeMs200;xa(r,Oa.Audio_Render_Freeze_Time_200ms,c<0?0:c)}}return r}(r._audioSSRC,e,r.audioTrack,t,i,n):void 0;o&&(d.audio=o)}(d.video||d.audio)&&s.push(d)})),this.needUploadRenderFreezeTime=!this.needUploadRenderFreezeTime,s}startUploadTransportStats(){this.uploadTransportStarted=!0,this.uploadWRTCStatsTimer||this.startUploadWRTCStats()}stopUploadTransportStats(){this.uploadTransportStarted=!1}startUploadOutboundStats(){this.uploadOutboundStarted||(this.uploadOutboundStarted=!0,this.uploadWRTCStatsTimer||this.startUploadWRTCStats(),this.uploadOutboundDenoiserStatsTimer&&window.clearInterval(this.uploadOutboundDenoiserStatsTimer),this.uploadOutboundDenoiserStatsTimer=window.setInterval((()=>{if(!this.requestAllTracks||!this.requestUpload)return;const e=(this.requestAllTracks()||[]).find((e=>e instanceof i));if(e&&e._external.getDenoiserStats){const t=e._external.getDenoiserStats();t&&this.requestUpload(bi.DENOISER_STATS,t)}}),2e3),this.uploadExtStatsTimer&&window.clearInterval(this.uploadExtStatsTimer),this.uploadExtStatsTimer=window.setInterval((()=>{if(!this.requestAllTracks||!this.requestUpload)return;this.requestAllTracks().forEach((e=>{e.getProcessorStats().forEach((e=>{this.requestUpload&&this.requestUpload(e.type,e.stats)}))}))}),2e3))}stopUploadOutboundStats(){this.uploadOutboundStarted&&(this.uploadOutboundStarted=!1,this.lastSendStats&&(this.lastSendStats.videoSend=[],this.lastSendStats.audioSend=[],this.lastSendStats=void 0),this.lastRefSendStats&&(this.lastRefSendStats.videoSend=[],this.lastRefSendStats.audioSend=[],this.lastRefSendStats=void 0),this.lastNormalSendStats&&(this.lastNormalSendStats.videoSend=[],this.lastNormalSendStats.audioSend=[],this.lastNormalSendStats=void 0),this.lastExtendStats={},this.needUploadStats={},this.uploadOutboundDenoiserStatsTimer&&window.clearInterval(this.uploadOutboundDenoiserStatsTimer),this.uploadOutboundDenoiserStatsTimer=void 0,this.uploadExtStatsTimer&&window.clearInterval(this.uploadExtStatsTimer),this.uploadExtStatsTimer=void 0)}startUploadInboundStats(){this.uploadInboundStarted||(this.uploadInboundStarted=!0,this.uploadWRTCStatsTimer||this.startUploadWRTCStats(),this.uploadInboundExtStatsTimer&&window.clearInterval(this.uploadInboundExtStatsTimer),this.uploadInboundExtStatsTimer=window.setInterval((()=>{if(!this.requestUpload||!this.requestRemoteMedia)return;(this.requestRemoteMedia()||[]).forEach((e=>{let[t,i]=e;if(i.has(Zi.VIDEO)&&t.videoTrack){t.videoTrack.getProcessorStats().forEach((e=>{this.requestUpload&&this.requestUpload(e.type,e.stats)}))}if(i.has(Zi.AUDIO)&&t.audioTrack){t.audioTrack.getProcessorStats().forEach((e=>{this.requestUpload&&this.requestUpload(e.type,e.stats)}))}}))}),2e3))}stopUploadInboundStats(){this.uploadInboundStarted&&(this.uploadInboundStarted=!1,this.lastRecvStats&&(this.lastRecvStats.videoRecv=[],this.lastRecvStats.audioRecv=[],this.lastRecvStats=void 0),this.lastRefRecvStats&&(this.lastRefRecvStats.videoRecv=[],this.lastRefRecvStats.audioRecv=[],this.lastRefRecvStats=void 0),this.lastNormalRecvStats&&(this.lastNormalRecvStats.videoRecv=[],this.lastNormalRecvStats.audioRecv=[],this.lastNormalRecvStats=void 0),this.lastUploadCompensateTime=-1,this.uploadCompensateDeltaTime=0,this.needUploadRenderFreezeTime=!0,this.uploadInboundExtStatsTimer&&window.clearInterval(this.uploadInboundExtStatsTimer),this.uploadInboundExtStatsTimer=void 0)}startUploadExtensionUsageStats(){if(this.uploadExtensionUsageStarted)return;this.uploadExtensionUsageStarted=!0,this.uploadExtUsageStatsTimer&&window.clearInterval(this.uploadExtUsageStatsTimer);const e=new Map;this.uploadExtUsageStatsTimer=window.setInterval((async()=>{const t=Date.now(),i={connectionInterval:ne("EXTENSION_USAGE_UPLOAD_INTERVAL")/1e3,details:[],lts:t};let n=[];const o=this.requestAllTracks&&this.requestAllTracks()||[];for(const e of o)!e.muted&&e.enabled&&(n=n.concat(await e.getProcessorUsage()));const a=this.requestRemoteMedia&&this.requestRemoteMedia()||[];for(const[e,t]of a)t.has(Zi.VIDEO)&&e.videoTrack&&(n=n.concat(await e.videoTrack.getProcessorUsage())),t.has(Zi.AUDIO)&&e.audioTrack&&(n=n.concat(await e.audioTrack.getProcessorUsage()));if(0===n.length)return;i.details=function(e,t){const i={};for(const{id:s,value:r,level:c,direction:d}of e){var n;const e=null!==(n=t.get(s))&&void 0!==n?n:0,l=2===r?e+ne("EXTENSION_USAGE_UPLOAD_INTERVAL")/1e3:e;var o,a;t.set(s,l),i[s]?(2===r&&(i[s].value=r),c>i[s].level&&(i[s].level=c),"remote"===d&&(i[s].remoteUidCount+=1),i[s].totalTs=null!==(o=t.get(s))&&void 0!==o?o:0):i[s]={value:r,level:c,remoteUidCount:"local"===d?0:1,totalTs:null!==(a=t.get(s))&&void 0!==a?a:0}}return Object.keys(i).map((e=>{const{level:t,value:n,totalTs:o}=i[e];return{id:e,level:t,value:n,totalTs:o}}))}(n,e);const s=Date.now(),r=s>t?s:t+1;this.requestUpload&&this.requestUpload(bi.EXTENSION_USAGE_STATS,{usageStats:i,sendTs:r})}),ne("EXTENSION_USAGE_UPLOAD_INTERVAL"))}stopUploadExtensionUsageStats(){this.uploadExtensionUsageStarted&&(this.uploadExtensionUsageStarted=!1,this.uploadExtUsageStatsTimer&&window.clearInterval(this.uploadExtUsageStatsTimer),this.uploadExtUsageStatsTimer=void 0)}stopUploadBaseStats(){this.uploadBaseStatsStarted=!1}}const Ga=ne("ICE_RESTART_INTERVAL");let Wa=new Map,Ha=new Map,Ka=[$i.UDP_TCP_RELAY,$i.TCP_RELAY,$i.RELAY],Ya=ne("JOIN_WITH_FALLBACK_MEDIA_PROXY_FORCE")&&o().supportPCSetConfiguration;function qa(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const i=Wa.get(e.id);i&&(window.clearTimeout(i),Wa.delete(e.id));const n=Ha.get(e.id);t&&n&&n.index===Ka.length-1&&(B.debug("[".concat(e.id,"] reset ICE restart policy")),Ha.delete(e.id))}function Xa(e,t,i){if(0===Wa.size&&0===Ha.size&&(Array.isArray(ne("RESTART_SEQUENCE"))&&ne("RESTART_SEQUENCE").length>0&&!lt(Ka,ne("RESTART_SEQUENCE"))&&(Ka=ne("RESTART_SEQUENCE").filter((e=>{if(Object.values($i).includes(e))return!0})),B.debug("use reconnection policy from config distribution, queues: ".concat(Ka.join(" => ")))),Ya=ne("JOIN_WITH_FALLBACK_MEDIA_PROXY_FORCE")&&o().supportPCSetConfiguration),0===Ka.length)return void i();let n,{index:a=0,type:s}=Ha.get(e.id)||{};if(Ya&&s===$i.RELAY)return void i();let r=s&&a>=Ka.length-1;if(Ya)s=$i.RELAY;else{if(r)return void i();s?(a++,s=Ka[a]):(s=Ka[0],a=0)}B.debug("[".concat(e.id,"] choose ICE restart policy: ").concat(s,", index: ").concat(a)),t(s),Ha.set(e.id,{index:a,type:s}),n=window.setTimeout((()=>Xa(e,t,i)),Ga),Wa.set(e.id,n)}var Ja;let za=(li((Ja=class extends ie{get state(){return this._state}set state(e){const t=this._state;this._state=e,this.emit(an.StateChange,t,this._state)}constructor(e,t){super(),this.isPlanB=void 0,this.store=void 0,this.statsUploader=void 0,this.connection=void 0,this.localTrackMap=new Map,this.remoteUserMap=new Map,this.localDataChannels=[],this.remoteDataChannelMap=new Map,this.pendingLocalTracks=[],this.pendingRemoteTracks=[],this.pendingLocalDataChannels=[],this.pendingRemoteDataChannels=[],this.statsCollector=void 0,this.shouldForwardP2PCreation=void 0,this.iceFailedCount=0,this.dtlsFailedCount=0,this.mutex=void 0,this._state=on.Disconnected,this._pcStatsUploadType=ne("NEW_ICE_RESTART")?en.FIRST_CONNECTION:en.OLD_FIRST_CONNECTION,this._isStartRestartIce=!1,this._restartTimer=void 0,this._isTryConnecting=!1,this._iceError=null,this._forceTurn=!1,this._isWaitPcToRePub=!1,this.handleMuteLocalTrack=async(e,t,i)=>{const n=await this.mutex.lock("Locking from P2PChannel.handleMuteLocalTrack");try{if(!this.connection||this.state!==on.Connected)return void i(new ue(Z.INVALID_OPERATION,"Cannot call P2PChannel.handleMuteLocalTrack before connection established."));const o=this.filterTobeMutedTracks(e);if(0===o.length)return void t();const a=o.find((e=>"videoLowTrack"===e[0]));if(a){const e=a[1];this.store.enableInstantMuteRestore?(e.track._originMediaStreamTrack.enabled=!1,B.info("[".concat(this.store.clientId,"] P2PChannel muteLocalLowTrack without close sender because enableInstantMuteRestore is true"))):e.track._originMediaStreamTrack.stop()}this.store.enableInstantMuteRestore?B.info("[".concat(this.store.clientId,"] P2PChannel muteLocalTrack without close sender because enableInstantMuteRestore is true")):await this.connection.muteLocal(o.map((e=>{let[,{id:t}]=e;return t})));const s=this.createMuteMessage(o);await ut(this,an.RequestMuteLocal,s),t()}catch(e){i(e)}finally{n()}},this.handleUnmuteLocalTrack=async(e,t,i)=>{const n=await this.mutex.lock("Locking from P2PChannel.handleUnmuteLocalTrack");try{if(!this.connection||this.state!==on.Connected)return void i(new ue(Z.INVALID_OPERATION,"Cannot call P2PChannel.handleUnmuteLocalTrack before connection established."));const a=this.filterTobeUnmutedTracks(e);if(0===a.length)return void t();const s=a.find((e=>"videoLowTrack"===e[0]));if(s){const t=s[1];if(this.store.enableInstantMuteRestore)t.track._originMediaStreamTrack.enabled=!0,B.info("[".concat(this.store.clientId,"] P2PChannel unmuteLocalLowTrack without close sender because enableInstantMuteRestore is true"));else{if(t.track._originMediaStreamTrack.stop(),!ne("DISABLE_DUAL_STREAM_USE_ENCODING")&&o().supportDualStreamEncoding){const i=e._mediaStreamTrack.clone();t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i}else{const i=Na(e,Ce(this,an.RequestLowStreamParameter));t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i}await new Promise(((e,i)=>{this.handleReplaceTrack(t.track,e,i,!0)}))}}this.store.enableInstantMuteRestore?B.info("[".concat(this.store.clientId,"] P2PChannel unmuteLocalTrack without close sender because enableInstantMuteRestore is true")):await this.connection.unmuteLocal(a.map((e=>{let[,{id:t}]=e;return t})));const r=this.createUnmuteMessage(a);await ut(this,an.RequestUnmuteLocal,r),t()}catch(e){i(e)}finally{n()}},this.handleUpdateVideoEncoder=async(e,t,i,n)=>{let o;n||(o=await this.mutex.lock("Locking from P2PChannel.handleUpdateVideoEncoder"));try{const i=this.localTrackMap.get(nn.LocalVideoTrack);if(!this.connection||!i||i.track!==e||this.state!==on.Connected)return void t();const{id:n,track:s}=i;await this.connection.updateSendParameters(n,s),await this.connection.updateEncoderConfig(n,s),this.emit(an.UpdateVideoEncoder,s),t()}catch(e){i(e)}finally{var a;null===(a=o)||void 0===a||a()}},this.handleUpdateVideoSendParameters=async(e,t,i)=>{const n=await this.mutex.lock("Locking from P2PChannel.handleUpdateVideoSendParameters");try{const i=this.localTrackMap.get(nn.LocalVideoTrack);if(!this.connection||!i||i.track!==e||this.state!==on.Connected)return void t();const{id:o,track:a}=i;await this.connection.updateSendParameters(o,a),t()}catch(e){i(e)}finally{n()}},this.handleReplaceMixingTrack=async(e,t,i,n)=>{if(!this.connection||this.state!==on.Connected)return void t();const o=fa([e]);let a;B.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection will replace audioTrack [").concat(o.getTrackId(),"]")),"boolean"==typeof n&&n||(a=await this.mutex.lock("From P2PChannel.handleReplaceMixingTrack"));try{await this.replaceTrack(e,o),t()}catch(e){i(e)}finally{var s;null===(s=a)||void 0===s||s()}},this.handleReplaceTrack=async(e,t,i,n)=>{let a;B.debug("[".concat(this.store.clientId,"] P2PChannel handleReplaceTrack for [track-id-").concat(e.getTrackId(),"]")),"boolean"==typeof n&&n||(a=await this.mutex.lock("From P2PChannel.handleReplaceTrack"));try{var s;const i=Array.from(this.localTrackMap.entries()).find((t=>{let[,{track:i}]=t;return e===i}));if(!this.connection||!i||this.state!==on.Connected)return void t();if(await(null===(s=this.connection)||void 0===s?void 0:s.replaceTrack(e,i[1].id)),this.isPlanB){const t=i[1];t.id=e._mediaStreamTrack.id,this.localTrackMap.set(i[0],t)}if(i[0]===nn.LocalVideoTrack&&!ne("DISABLE_DUAL_STREAM_USE_ENCODING")&&o().supportDualStreamEncoding){const t=this.localTrackMap.get(nn.LocalVideoLowTrack);if(t){const i=e._mediaStreamTrack.clone();t.track._originMediaStreamTrack.stop(),t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i,await new Promise(((e,i)=>{this.handleReplaceTrack(t.track,e,i,!0)}))}}t()}catch(e){i(e)}finally{var r;null===(r=a)||void 0===r||r()}},this.handleGetRTCStats=e=>{e(this.statsCollector.getRTCStats())},this.handleGetLocalVideoStats=e=>{e(this.statsCollector.getLocalVideoTrackStats())},this.handleGetLocalAudioStats=e=>{e(this.statsCollector.getLocalAudioTrackStats())},this.handleGetRemoteVideoStats=e=>this.statsCollector.getRemoteVideoTrackStats(e.uid)[e.uid],this.handleGetRemoteAudioStats=e=>this.statsCollector.getRemoteAudioTrackStats(e.uid)[e.uid],this.store=e,this.statsCollector=t,this.statsCollector.addP2PChannel(this),this.statsUploader=new ja(this.store),this.bindStatsUploaderEvents(),this.mutex=new re("P2PChannel-mutex",this.store.clientId),this.isPlanB=!o().supportUnifiedPlan||ne("CHROME_FORCE_PLAN_B")&&at(),this.shouldForwardP2PCreation=ne("FORWARD_P2P_CREATION")&&o().supportPCSetConfiguration&&ht(),this.shouldForwardP2PCreation&&(this.connection=Ta(this.store),this.emit(an.PeerConnectionStateChange,this.connection.peerConnectionState),this.bindConnectionEvents(this.connection))}async startP2PConnection(e,t){var i;this.state=on.New,this._forceTurn=Aa(e),B.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] forceTurn: ").concat(this._forceTurn));const n=this.shouldForwardP2PCreation&&"closed"===(null===(i=this.connection)||void 0===i?void 0:i.peerConnectionState);if((!this.shouldForwardP2PCreation||n||t)&&((n||t)&&this.connection&&(B.warning("[".concat(this.store.clientId,"] P2PChannel.startP2PConnection ForwardP2P closed.")),this.resetConnection(this.connection)),this.connection=Ta(this.store,e),this.emit(an.PeerConnectionStateChange,this.connection.peerConnectionState),this.bindConnectionEvents(this.connection)),!this.connection)throw new ue(Z.UNEXPECTED_ERROR,"Cannot P2PChannel.startConnection before P2PConnection initialization .");return this._pcStatsUploadType=ne("NEW_ICE_RESTART")?en.FIRST_CONNECTION:en.OLD_FIRST_CONNECTION,this._isTryConnecting=!0,this._isStartRestartIce=!1,this._iceError=null,this.connection.setConfiguration(e),this.connection.establishPromise}async connect(e){if(!this.connection)throw new ue(Z.UNEXPECTED_ERROR,"Cannot P2PChannel.connect before P2PChannel.startP2PConnection .");if(this.isPreallocation()&&this.state===on.Connected){if(this.connection instanceof va){if(this.connection.checkDtlsParameters(e.dtlsParameters.fingerprints)){B.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] dtls parameters mismatch, try next."));return j.reportApiInvoke(this.store.sessionId,{name:We.MISMATCH_DTLS_PARAMETERS,options:[e.dtlsParameters.fingerprints],tag:He.TRACER}).onSuccess(),void setTimeout((()=>{this.emit(an.RequestReconnect)}))}}await this.connection.updateRemoteConnect(e)}else this.store.peerConnectionStart(),await this.connection.connect(e),this.statsUploader.startUploadTransportStats(),this.statsUploader.startUploadExtensionUsageStats(),this.state=on.Connected}updateRemoteRTPCapabilities(e){const t=Array.from(this.localTrackMap.entries()).filter((e=>{let[t]=e;return[nn.LocalVideoLowTrack,nn.LocalVideoTrack].includes(t)})),i=t.map((e=>{let[,{id:t}]=e;return t})),n=t.map((e=>{let[t]=e;return t}));if(this.connection instanceof va){if(j.updateRemoteRTPCapabilities(this.store.sessionId,{trackTypes:JSON.stringify(n),localCodecs:JSON.stringify(this.connection.localCodecs),remoteCodecs:JSON.stringify(e)}),!e.includes(this.store.codec)){const t=["vp9","vp8","h264"].find((t=>e.includes(t)));t&&(this.store.codec=t,B.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId," updateRemoteRTPCapabilities] default codec is not available, hence the fallback to ").concat(t,".")))}this.connection.updateRemoteRTPCapabilities(i,e)}}async getEstablishParams(){if(this.connection instanceof va&&"closed"!==this.connection.peerConnectionState&&[on.New,on.Connected].includes(this.state))return this.connection.establishPromise}async publishDataChannel(e){if(!this.connection||this.state!==on.Connected){if(this.state===on.Disconnected)throw new ue(Z.UNEXPECTED_ERROR,"PeerConnection already disconnected.");return e.forEach((e=>{this.pendingLocalDataChannels.includes(e)||this.pendingLocalDataChannels.push(e)})),[]}const t=this.filterTobePublishedDataChannels(e);return 0===t.length?[]:(t.forEach((e=>{const t=Date.now();this.store.publish(e.id.toString(),"datachannel",t)})),await this.connection.createDataChannels(this.store.uid,t),t.forEach((e=>{this.localDataChannels.push(e);const t=Date.now();this.store.publish(e.id+"","datachannel",void 0,t)})),e.map((e=>({streamId:e.id,ordered:e.ordered,maxRetransmits:e.maxRetransmits,metadata:e.metadata,channelId:e._originDataChannelId}))))}publish(e,t,i){var n=this;return Ri((function*(){const o=yield pi(n.mutex.lock("From P2PChannel.publish"));try{const a=n.connection&&["disconnected","failed"].includes(n.connection.peerConnectionState);if(!n.connection||n.state!==on.Connected||a){if(n.state===on.Disconnected)throw new ue(Z.UNEXPECTED_ERROR,"PeerConnection already disconnected.");n.throwIfTrackTypeNotMatch(e);const t=e.filter((e=>-1===n.pendingLocalTracks.indexOf(e)));return n.pendingLocalTracks=n.pendingLocalTracks.concat(t),void(a&&(n._isWaitPcToRePub=!0))}n.store.pubId=n.store.pubId+1,ta.markPublishStart(n.store.clientId,n.store.pubId);const s=n.filterTobePublishedTracks(e,t,i);if(0===s.length)return void(yield pi(n.tryToUnmuteAudio(e)));yield*ui(hi(n.doPublish(n.connection,s)))}finally{o()}}))()}doPublish(e,t){var i=this;return Ri((function*(){t.forEach((e=>{let{track:t,type:n}=e;const o=Date.now();i.store.publish(t.getTrackId(),n===nn.LocalAudioTrack?"audio":"video",o)})),i.bindLocalTrackEvents(t);const n=t.map((e=>{let{track:t}=e;return t})),o=yield pi(e.send(n,i.store.codec,i.store.audioCodec)),a=(yield pi(o.next())).value,s=i.createGatewayPublishMessage(t,a);let r;try{r=yield s}catch(e){throw o.throw(e),(null==e?void 0:e.code)===Z.WS_ABORT&&t.forEach((e=>{let{track:t}=e;-1===i.pendingLocalTracks.indexOf(t)&&i.pendingLocalTracks.push(t)})),i.unbindLocalTrackEvents(t),e}const c=i.mapPubResToRemoteConfig(s,r,n),d=(yield pi(o.next(c))).value;if(i.state===on.Disconnected)throw new ue(Z.UNEXPECTED_ERROR,"PeerConnection already disconnected.");ne("ENABLE_VIDEO_SEI");const l=ne("ENABLE_ENCODED_TRANSFORM"),u=ne("ENABLE_AUDIO_METADATA");n.forEach((async e=>{const t=e.getRTCRtpTransceiver();if(!t||!l)return;const{interceptLocalVideoFrame:i,interceptLocalAudioFrame:n}=So();e.trackMediaType===Zi.VIDEO?await i(t.sender,e):e.trackMediaType===Zi.AUDIO&&await n(t.sender,{metadata:u?()=>{const t=e.metadata.shift();return t&&t.value}:void 0})})),t.forEach((e=>{let{type:t}=e;i.statsCollector.addLocalStats(t)})),i.assignLocalTracks(t,d),i.statsUploader.startUploadOutboundStats(),t.forEach((e=>{let{track:t,type:n}=e;const o=Date.now();i.store.publish(t.getTrackId(),n===nn.LocalAudioTrack?"audio":"video",void 0,o)}))}))()}async updateVideoStreamParameter(e,t){const i=this.localTrackMap.get(t);if(!i||!this.connection)return;if(!(i.track instanceof n))return B.warn("[updateVideoStreamParameter]: track is not an instance of LocalVideoTrack");const{track:a}=i,s=function(e,t){const i={};return e.height&&e.width&&(i.scaleResolutionDownBy=xn(e,t)),i.maxFramerate=e.framerate?Ln(e.framerate):void 0,i.maxBitrate=e.bitrate?1e3*e.bitrate:void 0,i}(e,a);if(a._encoderConfig||(a._encoderConfig={}),t!==nn.LocalVideoLowTrack||!ne("DISABLE_DUAL_STREAM_USE_ENCODING")&&o().supportDualStreamEncoding)null!=s.scaleResolutionDownBy&&(a._encoderConfig.scaleResolutionDownBy=s.scaleResolutionDownBy);else{const t=a._originMediaStreamTrack;if(!t.canvas)return B.warn("[".concat(a.getTrackId(),"] no canvas on track"));!function(e,t){const i=e.canvas;t.width&&(i.width=Ln(t.width)),t.height&&(i.height=Ln(t.height)),t.framerate&&(i.stopCapture&&i.stopCapture(),i.stopCapture=f((()=>{!i.startCapture&&i.stopCapture&&i.stopCapture(),i.startCapture&&i.startCapture()}),Ln(t.framerate)))}(t,e)}null!=s.maxBitrate&&(a._encoderConfig.bitrateMax=s.maxBitrate/1e3),null!=s.maxFramerate&&(a._encoderConfig.frameRate&&"object"==typeof a._encoderConfig.frameRate?a._encoderConfig.frameRate.max=s.maxFramerate:a._encoderConfig.frameRate={max:s.maxFramerate}),B.debug("[".concat(a.getTrackId(),"] LowStreamEncoderConfig: , ").concat(JSON.stringify(a._encoderConfig))),await this.connection.updateRtpSenderEncodings(a)}publishLowStream(e){var t=this;return Ri((function*(){if(!t.connection||t.state!==on.Connected)return;const i=yield pi(t.mutex.lock("Locking from P2PChannel.publishLowStream"));try{const o=t.localTrackMap.get(nn.LocalVideoTrack);if(!o)throw new ue(Z.UNEXPECTED_ERROR,"Could not find high stream");if(t.localTrackMap.has(nn.LocalVideoLowTrack))throw new ue(Z.UNEXPECTED_ERROR,"[".concat(t.store.clientId,"] Can't publish low stream when stream already publish"));const a=[{track:t.getLowVideoTrack(o.track,e),type:nn.LocalVideoLowTrack}];if(yield*ui(hi(t.doPublish(t.connection,a))),o.track.muted||!o.track.enabled){var n;const e=null===(n=t.localTrackMap.get(nn.LocalVideoLowTrack))||void 0===n?void 0:n.id;void 0!==e&&(yield pi(t.connection.muteLocal([e])))}}finally{i()}}))()}async republish(){this.pendingLocalTracks.length>0&&(B.debug("[".concat(this.store.clientId,"] Emit P2PChannelEvents.RequestRePublish to republish tracks.")),await pe(this,an.RequestRePublish,this.pendingLocalTracks),this.emit(an.MediaReconnectEnd,this.store.uid),this.pendingLocalTracks=[]),this.pendingLocalDataChannels.length>0&&(B.debug("Emit P2PChannelEvents.RequestRePublishDataChannel to republish datachannels."),await pe(this,an.RequestRePublishDataChannel,this.pendingLocalDataChannels),this.pendingLocalDataChannels=[]),this._isWaitPcToRePub=!1}async reSubscribe(e){for(let e=this.pendingRemoteTracks.length-1;e>=0;e--){const{user:t,kind:i}=this.pendingRemoteTracks[e];(i!==Zi.AUDIO||t._audio_added_&&t._audioSSRC)&&(i!==Zi.VIDEO||t._video_added_&&t._videoSSRC)||this.pendingRemoteTracks.splice(e,1)}if(e)await pe(this,an.RequestReSubscribe,this.pendingRemoteTracks);else for(const{user:e,kind:t}of this.pendingRemoteTracks)await this.subscribe(e,t,t===Zi.VIDEO?e._videoSSRC:e._audioSSRC);this.pendingRemoteTracks.forEach((e=>{let{user:t}=e;this.emit(an.MediaReconnectEnd,t.uid)})),this.pendingRemoteTracks=[]}async unpublish(e){if(!this.connection||this.state!==on.Connected)return void e.forEach((e=>{const t=this.pendingLocalTracks.indexOf(e);-1!==t&&this.pendingLocalTracks.splice(t,1)}));const t=this.filterTobeUnpublishedTracks(e);if(0===t.length)return;const i=t.find((e=>"videoLowTrack"===e[0]));if(i){i[1].track.close()}return this.doUnpublish(this.connection,t)}async unpublishDataChannel(e){if(!this.connection||this.state!==on.Connected)return void e.forEach((e=>{const t=this.pendingLocalDataChannels.indexOf(e);-1!==t&&this.pendingLocalDataChannels.splice(t,1)}));const t=this.filterTobeUnpublishedDataChannels(e);return 0!==t.length?(t.forEach((e=>{const t=this.localDataChannels.indexOf(e);-1!==t&&this.localDataChannels.splice(t,1)})),0===this.localDataChannels.length&&await this.connection.stopDataChannels(this.store.uid),t.map((e=>e.id))):void 0}async unpublishLowStream(){if(!this.connection||this.state!==on.Connected)return;const e=this.localTrackMap.get(nn.LocalVideoLowTrack);if(!e)return;e.track.close();const t=[[nn.LocalVideoLowTrack,e]];return this.doUnpublish(this.connection,t)}async doUnpublish(e,t){const i=this.createGatewayUnpublishMessage(t);return await e.stopSending(t.map((e=>{let[,{id:t}]=e;return t}))),this.withdrawLocalTracks(t),this.unbindLocalTrackEvents(t.map((e=>{let[t,{track:i}]=e;return{type:t,track:i}}))),t.forEach((e=>{let[t]=e;this.statsCollector.removeLocalStats(t)})),0===this.localTrackMap.size&&this.statsUploader.stopUploadOutboundStats(),i}async subscribeDataChannel(e,t){if(!this.connection||this.state!==on.Connected)throw new ue(Z.INVALID_OPERATION,"Cannot subscribe remote user when peerConnection disconnected.");const i=t.filter((t=>{var i;return!(null!==(i=this.remoteDataChannelMap.get(e))&&void 0!==i&&i.get(t.id))}));if(0!==i.length)return await this.connection.createDataChannels(e.uid,i),i.forEach((t=>{var i;this.remoteDataChannelMap.has(e)?null===(i=this.remoteDataChannelMap.get(e))||void 0===i||i.set(t.id,t):this.remoteDataChannelMap.set(e,new Map([[t.id,t]]));const n=this.pendingRemoteDataChannels.findIndex((i=>{let{user:n,id:o}=i;return n.uid===e.uid&&o===t.id}));-1!==n&&this.pendingRemoteDataChannels.splice(n,1)})),i.map((e=>e.id))}async subscribe(e,t,i,n,o){var a;if(!this.connection||this.state!==on.Connected)throw new ue(Z.INVALID_OPERATION,"Cannot subscribe remote user when peerConnection disconnected.");if(null!==(a=this.remoteUserMap.get(e))&&void 0!==a&&a.has(t))return;let s,r,c,d;const l=this.connection.getPreMedia(i);if(l)B.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] preSSRCMap has ssrcId: ").concat(i,", no need to send sub to gateway.")),c=l.transceiver,s=l.track,r=l.mid,d=l.player,l.firstVideoRender&&this.store.firstVideoFrameDecoded(e.uid,{firstPreRender:l.firstVideoRender});else if(o){const i=o.find((e=>{let{stream_type:i}=e;return i===t}));if(!i)throw new ue(Z.UNEXPECTED_ERROR,"Cannot subscribe to remote ".concat(t," for user: ").concat(e.uid," because subscribe answer from gateway does not contain stream_type: ").concat(t,"."));const n=await this.connection.receive(t,i.ssrcs,String(e._uintid),i.attributes);this.connection instanceof va&&(c=n.transceiver),s=n.track,r=n.id}else{const o=await this.connection.receive(t,[{ssrcId:i,rtx:n}],String(e._uintid),void 0);this.connection instanceof va&&(c=o.transceiver),s=o.track,r=o.id}if(t===Zi.AUDIO?(e._audioTrack?e._audioTrack._updateOriginMediaStreamTrack(s):(e._audioTrack=new g(s,e.uid,e._uintid,this.store),B.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote audio track: ").concat(e._audioTrack.getTrackId()))),c&&e._audioTrack._updateRtpTransceiver(c),this.bindRemoteTrackEvents(e,e._audioTrack)):(e._videoTrack?e._videoTrack._updateOriginMediaStreamTrack(s):(e._videoTrack=new v(s,e.uid,e._uintid,this.store,d),B.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote video track: ").concat(e._videoTrack.getTrackId())),e._videoTrack.once(y.PLAY_START,(()=>{this.store.firstVideoFrameDecoded(e.uid,{playStart:Date.now()})})),e._videoTrack.once(y.PLAY_END,(()=>{this.store.firstVideoFrameDecoded(e.uid,{playEnd:Date.now()}),this.reportVideoFirstFrameRender(e)})),d?e._videoTrack.once(y.FIRST_FRAME_RENDER,(()=>{this.store.firstVideoFrameDecoded(e.uid,{firstRender:Date.now()}),this.reportVideoFirstFrameRender(e)})):e._videoTrack.once(y.FIRST_FRAME_DECODED,(()=>{this.store.firstVideoFrameDecoded(e.uid,{firstRender:Date.now()}),this.reportVideoFirstFrameRender(e)}))),c&&e._videoTrack._updateRtpTransceiver(c),this.bindRemoteTrackEvents(e,e._videoTrack)),c&&ne("ENABLE_ENCODED_TRANSFORM")){const{interceptRemoteVideoFrame:i,interceptRemoteAudioFrame:n}=So();t==Zi.VIDEO?await i(c.receiver,{onSei:ne("ENABLE_VIDEO_SEI")&&(t=>{var i;return null===(i=e._videoTrack)||void 0===i?void 0:i._onSei(t)})}):t==Zi.AUDIO&&await n(c.receiver,{enableTopn:!!ne("ENABLE_AUDIO_TOPN"),enableMetadata:!!ne("ENABLE_AUDIO_METADATA"),enablePts:!!ne("ENABLE_AUDIO_PTS"),onMetadata:e=>{this.safeEmit(an.AudioMetadata,e)},onPts:e=>{this.safeEmit(an.AudioPts,e)}})}const u=this.remoteUserMap.get(e);u?u.set(t,r):this.remoteUserMap.set(e,new Map([[t,r]])),this.statsCollector.addRemoteStats(e.uid),this.statsUploader.startUploadInboundStats();const h=this.pendingRemoteTracks.findIndex((i=>{let{user:n,kind:o}=i;return n.uid===e.uid&&t===o}));-1!==h&&(this.pendingRemoteTracks.splice(h,1),this.emit(an.MediaReconnectEnd,e.uid))}async massSubscribe(e){return this.massSubscribeNoLock(e)}async massSubscribeNoLock(e){if(!this.connection||this.state!==on.Connected)throw new ue(Z.INVALID_OPERATION,"Cannot subscribeAll remote users when peerConnection disconnected.");e=e.filter((e=>{var t;let{user:i,mediaType:n}=e;return!(null!==(t=this.remoteUserMap.get(i))&&void 0!==t&&t.has(n))}));const t=[],i=new Map;e.forEach((e=>{if(!this.connection)return;const n=this.connection.getPreMedia(e.ssrcId);if(n){const{track:t,mid:o,transceiver:a,player:s}=n;i.set(e.ssrcId,{track:t,id:o,transceiver:a,player:s})}else t.push(e)}));const n=await this.connection.batchReceive(t.map((e=>{let{user:t,mediaType:i,ssrcId:n,rtxSsrcId:o}=e;return{kind:i,ssrcMsg:[{ssrcId:n,rtx:o}],mslabel:String(t._uintid)}})));t.forEach(((e,t)=>{i.set(e.ssrcId,n[t])}));for(const{user:t,mediaType:n,ssrcId:o}of e){const e=i.get(o);if(!e)return void B.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] cannot find ").concat(t.uid," subscribe data,").concat(n,", ").concat(o));const{track:a,id:s,transceiver:r,player:c}=e;if(r&&ne("ENABLE_ENCODED_TRANSFORM")){const{interceptRemoteVideoFrame:e,interceptRemoteAudioFrame:i}=So();n==Zi.VIDEO?await e(r.receiver,{onSei:ne("ENABLE_VIDEO_SEI")&&(e=>{var i;return null===(i=t._videoTrack)||void 0===i?void 0:i._onSei(e)})}):n==Zi.AUDIO&&await i(r.receiver,{enableTopn:!!ne("ENABLE_AUDIO_TOPN"),enableMetadata:!!ne("ENABLE_AUDIO_METADATA"),enablePts:!!ne("ENABLE_AUDIO_PTS"),onMetadata:e=>{this.safeEmit(an.AudioMetadata,e)},onPts:e=>{this.safeEmit(an.AudioPts,e)}})}if(n===Zi.AUDIO?(t._audioTrack?t._audioTrack._updateOriginMediaStreamTrack(a):(t._audioTrack=new g(a,t.uid,t._uintid,this.store),B.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote audio track: ").concat(t._audioTrack.getTrackId()))),r&&t._audioTrack._updateRtpTransceiver(r),this.bindRemoteTrackEvents(t,t._audioTrack)):(t._videoTrack?t._videoTrack._updateOriginMediaStreamTrack(a):(t._videoTrack=new v(a,t.uid,t._uintid,this.store,c),B.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote video track: ").concat(t._videoTrack.getTrackId()))),r&&t._videoTrack._updateRtpTransceiver(r),this.bindRemoteTrackEvents(t,t._videoTrack)),ne("ENABLE_VIDEO_SEI")&&r){const{interceptRemoteVideoFrame:e,interceptRemoteAudioFrame:i}=So();n==Zi.VIDEO?await e(r.receiver,{onSei:e=>{var i;null===(i=t._videoTrack)||void 0===i||i._onSei(e)}}):n==Zi.AUDIO&&await i(r.receiver)}const d=this.remoteUserMap.get(t);d?d.set(n,s):this.remoteUserMap.set(t,new Map([[n,s]])),this.statsCollector.addRemoteStats(t.uid),this.statsUploader.startUploadInboundStats();const l=this.pendingRemoteTracks.findIndex((e=>{let{user:i,kind:o}=e;return i.uid===t.uid&&n===o}));-1!==l&&(this.pendingRemoteTracks.splice(l,1),this.emit(an.MediaReconnectEnd,t.uid))}}async unsubscribe(e,t,i){const n=this.pendingRemoteTracks.filter((i=>{let{user:n,kind:o}=i;return void 0!==t?n.uid===e.uid&&t===o:n.uid===e.uid}));if(n.forEach((e=>{const t=this.pendingRemoteTracks.indexOf(e);this.pendingRemoteTracks.splice(t,1)})),this.connection&&this.state===on.Connected||i||n.forEach((t=>{let{kind:i}=t;var n;if(i===Zi.AUDIO)null===(n=e._audioTrack)||void 0===n||n._destroy(),e._audioTrack=void 0;else if(i===Zi.VIDEO){var o;null===(o=e._videoTrack)||void 0===o||o._destroy(),e._videoTrack=void 0}})),!this.connection||this.state!==on.Connected)return;const o=this.filterTobeUnSubscribedTracks(e,t);if(0===o.length)return;await this.connection.stopReceiving(o.map((e=>{let[,{id:t}]=e;return t})));const a=this.createUnsubscribeMessage(o);return this.withdrawRemoteTracks(o),0===this.remoteUserMap.size&&this.statsUploader.stopUploadInboundStats(),o.forEach((e=>{let[t,{kind:n}]=e;var o,a;n===Zi.VIDEO&&t._videoSSRC&&(null===(o=this.connection)||void 0===o||o.setStatsRemoteVideoIsReady(t._videoSSRC,!1));if(n===Zi.VIDEO)this.unbindRemoteTrackEvents(t._videoTrack),i||(null===(a=t._videoTrack)||void 0===a||a._destroy(),t._videoTrack=void 0);else if(n===Zi.AUDIO){var s;if(this.unbindRemoteTrackEvents(t._audioTrack),!i)null===(s=t._audioTrack)||void 0===s||s._destroy(),t._audioTrack=void 0}})),a}async unsubscribeDataChannel(e,t){if(t.forEach((e=>{const t=this.pendingRemoteDataChannels.findIndex((t=>t.id===e.id));-1!==t&&this.pendingRemoteDataChannels.splice(t,1)})),!this.connection)return;const i=this.filterTobeUnSubscribedDataChannels(e,t);if(0===i.length)return;t.forEach((e=>{e._close()}));const n=this.remoteDataChannelMap.get(e);return i.forEach((e=>{n&&n.delete(e.id)})),n&&0===n.size&&(this.remoteDataChannelMap.delete(e),await this.connection.stopDataChannels(e.uid)),i.map((e=>e.id))}async massUnsubscribe(e){return this.massUnsubscribeNoLock(e)}async massUnsubscribeNoLock(e){let t=[];for(const{user:i,mediaType:n}of e){const e=this.pendingRemoteTracks.filter((e=>{let{user:t,kind:o}=e;return void 0!==n?t.uid===i.uid&&n===o:t.uid===i.uid}));e.forEach((e=>{const t=this.pendingRemoteTracks.indexOf(e);this.pendingRemoteTracks.splice(t,1)})),t=t.concat(e)}if(!this.connection||this.state!==on.Connected)return void t.forEach((e=>{let{user:t,kind:i}=e;var n;if(i===Zi.AUDIO)null===(n=t._audioTrack)||void 0===n||n._destroy(),t._audioTrack=void 0;else if(i===Zi.VIDEO){var o;null===(o=t._videoTrack)||void 0===o||o._destroy(),t._videoTrack=void 0}}));const i=e.reduce(((e,t)=>{let{user:i,mediaType:n}=t;const o=this.filterTobeUnSubscribedTracks(i,n);return e.concat(o)}),[]);if(0===i.length)return;await this.connection.stopReceiving(i.map((e=>{let[,{id:t}]=e;return t})));const n=this.createUnsubscribeAllMessage(i);return this.withdrawRemoteTracks(i),0===this.remoteUserMap.size&&this.statsUploader.stopUploadInboundStats(),i.forEach((e=>{let[t,{kind:i}]=e;var n,o;i===Zi.VIDEO&&t._videoSSRC&&(null===(n=this.connection)||void 0===n||n.setStatsRemoteVideoIsReady(t._videoSSRC,!1));if(i===Zi.VIDEO)this.unbindRemoteTrackEvents(t._videoTrack),null===(o=t._videoTrack)||void 0===o||o._destroy(),t._videoTrack=void 0;else if(i===Zi.AUDIO){var a;this.unbindRemoteTrackEvents(t._audioTrack),null===(a=t._audioTrack)||void 0===a||a._destroy(),t._audioTrack=void 0}})),n}isPreSubScribe(e){if(!this.connection||this.state!==on.Connected)return!1;return!!this.connection.getPreMedia(e)}async muteRemote(e,t){if(!this.connection)return;const i=this.remoteUserMap.get(e);if(!i)return void B.warning("[".concat(this.store.clientId,"] P2PChannel.muteRemote has no remote user ").concat(e.uid,"."));if(!i.get(t))return void B.warning("[".concat(this.store.clientId,"] P2PChannel.muteRemote has no remote user ").concat(e.uid," media type ").concat(t,"."));const n=t===Zi.VIDEO?e._videoSSRC:e._audioSSRC;void 0!==n&&this.connection.setStatsRemoteVideoIsReady(n,!1)}async unmuteRemote(e,t){return this.unmuteRemoteNoLock(e,t)}async unmuteRemoteNoLock(e,t){if(!this.connection)return;const i=this.remoteUserMap.get(e);if(!i)return void B.warning("[".concat(this.store.clientId,"] P2PChannel.unmuteRemote has no remote user ").concat(e.uid,"."));i.get(t)||B.warning("[".concat(this.store.clientId,"] P2PChannel.unmuteRemote has no remote user ").concat(e.uid," media type ").concat(t,"."))}addAudioMetadata(e){const t=this.localTrackMap.get(nn.LocalAudioTrack),i=t&&t.track;i&&i.metadata.push(e)}getAllTracks(e){const t=this.localTrackMap.get(nn.LocalAudioTrack);if((null==t?void 0:t.track)instanceof l){const i=t.track;return Array.from(this.localTrackMap.entries()).filter((e=>{let[t]=e;return t!==nn.LocalAudioTrack})).filter((t=>{let[i]=t;return!(e&&i===nn.LocalVideoLowTrack)})).map((e=>{let[,{track:t}]=e;return t})).concat(i.trackList)}return Array.from(this.localTrackMap.entries()).filter((t=>{let[i]=t;return!(e&&i===nn.LocalVideoLowTrack)})).map((e=>{let[,{track:t}]=e;return t}))}getAllDataChannels(){return this.localDataChannels}reportPublishEvent(e,i,o,s,r){if(e){const t=this.localTrackMap.get(nn.LocalAudioTrack),n=s?this.localTrackMap.get(nn.LocalVideoLowTrack):this.localTrackMap.get(nn.LocalVideoTrack);j.publish(this.store.sessionId,{eventElapse:ta.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:e,ec:i,audioName:null==t?void 0:t.track.getTrackLabel(),videoName:null==n?void 0:n.track.getTrackLabel(),screenshare:-1!==(null==n?void 0:n.track._hints.indexOf(a.SCREEN_TRACK)),audio:!!t,video:!!n,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r})}else{var c;o||(o=[]);const d=o.find((e=>e instanceof t)),l=s?null===(c=this.localTrackMap.get(nn.LocalVideoTrack))||void 0===c?void 0:c.track:o.find((e=>e instanceof n));j.publish(this.store.sessionId,{eventElapse:ta.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:e,ec:i,audioName:null==d?void 0:d.getTrackLabel(),videoName:null==l?void 0:l.getTrackLabel(),screenshare:-1!==(null==l?void 0:l._hints.indexOf(a.SCREEN_TRACK)),audio:!!d,video:!!l,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r})}}reportSubscribeEvent(e,t,i,n){const o=n===Zi.VIDEO?i._videoSSRC:i._audioSSRC;o&&j.subscribe(this.store.sessionId,{succ:e,ec:t,video:n===Zi.VIDEO,audio:n===Zi.AUDIO,peerid:i.uid,subscribeRequestid:o,p2pid:this.store.p2pId,eventElapse:ta.measureFromSubscribeStart(this.store.clientId,o),preSsrc:this.isPreSubScribe(o)})}reset(){B.debug("[".concat(this.store.clientId,"] P2PChannel.reset")),this.mutex=new re("P2PChannel-mutex",this.store.clientId),this.connection&&(this.resetConnection(this.connection),this.connection=void 0),this.shouldForwardP2PCreation&&(this.connection=Ta(this.store),this.emit(an.PeerConnectionStateChange,this.connection.peerConnectionState),this.bindConnectionEvents(this.connection)),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),this.statsUploader.stopUploadExtensionUsageStats(),this.statsUploader.stopUploadBaseStats(),this.unbindLocalTrackEvents(),this.unbindAllRemoteTrackEvents(),this.unbindRtpTransceiver();const e=this.localTrackMap.get(nn.LocalAudioTrack);if((null==e?void 0:e.track)instanceof l){if(e.track.trackList.length>0){const t=e.track;e.track.trackList.forEach((e=>{t.removeAudioTrack(e)}))}e.track.close()}this.localTrackMap.clear(),this.remoteUserMap.clear(),this.statsCollector.removeRemoteStats(),this.statsCollector.removeLocalStats(),this.iceFailedCount=0,this.dtlsFailedCount=0,this.pendingLocalTracks=[],this.pendingRemoteTracks=[],this.localDataChannels=[],this.remoteDataChannelMap.clear(),this.pendingLocalDataChannels=[],this.pendingRemoteDataChannels=[],this.state=on.Disconnected}getStats(){var e;return null===(e=this.connection)||void 0===e?void 0:e.getStats()}getRemoteVideoIsReady(e){var t;return(null===(t=this.connection)||void 0===t?void 0:t.getRemoteVideoIsReady(e))||!1}getLocalAudioVolume(){const e=this.localTrackMap.get(nn.LocalAudioTrack);if(e)return e.track.getVolumeLevel()}getLocalVideoSize(){const e=this.localTrackMap.get(nn.LocalVideoTrack);if(e)return{width:e.track.videoWidth||0,height:e.track.videoHeight||0}}getEncoderConfig(e){const i=this.localTrackMap.get(e);return i&&i.track instanceof n||i&&i.track instanceof t?i.track._encoderConfig:void 0}getLocalMedia(e){return this.localTrackMap.get(e)}hasLocalMedia(){return this.localTrackMap.size>0}hasRemoteMedia(e,t){if(!e)return this.remoteUserMap.size>0;const i=this.remoteUserMap.get(e);return!!i&&(!t||i.has(t))}async hasRemoteMediaWithLock(e,t){if(!e)return this.remoteUserMap.size>0;const i=this.remoteUserMap.get(e);return!!i&&(!t||i.has(t))}getRemoteMedia(e){const t=Array.from(this.remoteUserMap.keys()).find((t=>t.uid===e));return t?{audioTrack:t.audioTrack,audioSSRC:t._audioSSRC,videoTrack:t.videoTrack,videoSSRC:t._videoSSRC}:{}}getAudioLevels(){let e=Array.from(this.remoteUserMap.entries()).map((e=>{let[t]=e;return{uid:t.uid,level:t.audioTrack?100*t.audioTrack._source.getAccurateVolumeLevel():0}}));const t=this.localTrackMap.get(nn.LocalAudioTrack);return t&&e.push({level:100*t.track._source.getAccurateVolumeLevel(),uid:this.store.uid}),e=e.sort(((e,t)=>e.level-t.level)),e}async disconnectForReconnect(){this.connection&&(B.debug("[".concat(this.store.clientId,"] P2PChannel.disconnectForReconnect closing P2PConnection")),this.state=on.Reconnecting,ne("KEEP_LAST_FRAME")&&0!==this.remoteUserMap.size&&Array.from(this.remoteUserMap.entries()).forEach((e=>{let[t]=e;var i;t._videoTrack&&t._videoTrack._player&&(null===(i=t._videoTrack._player.getVideoElement())||void 0===i||i.pause(),t._videoTrack._player.isKeepLastFrame=!0,t._videoTrack._originMediaStreamTrack.stop())})),this.resetConnection(this.connection),this.connection=void 0,this.shouldForwardP2PCreation&&(this.connection=Ta(this.store),this.emit(an.PeerConnectionStateChange,this.connection.peerConnectionState),this.bindConnectionEvents(this.connection)),0!==this.localTrackMap.size&&(Array.from(this.localTrackMap.entries()).forEach((e=>{let[t,{track:i}]=e;switch(t){case nn.LocalVideoTrack:i._hints.includes(a.LOW_STREAM)?i.close():this.pendingLocalTracks.push(i);break;case nn.LocalAudioTrack:i instanceof l?this.pendingLocalTracks=this.pendingLocalTracks.concat(i.trackList):this.pendingLocalTracks.push(i);case nn.LocalVideoLowTrack:}})),this.emit(an.MediaReconnectStart,this.store.uid)),this.unbindLocalTrackEvents(),this.localTrackMap.clear(),0!==this.remoteUserMap.size&&Array.from(this.remoteUserMap.entries()).forEach((e=>{let[t,i]=e;Array.from(i.keys()).forEach((e=>{this.setPendingRemoteMedia(t,e)})),this.emit(an.MediaReconnectStart,t.uid)})),this.unbindAllRemoteTrackEvents(),this.remoteUserMap.clear(),0!==this.localDataChannels.length&&(this.localDataChannels.forEach((e=>{this.pendingLocalDataChannels.push(e)})),this.localDataChannels.length=0),0!==this.remoteDataChannelMap.size&&(Array.from(this.remoteDataChannelMap.entries()).forEach((e=>{let[t,i]=e;Array.from(i.keys()).forEach((e=>{this.setPendingRemoteDataChannel(t,e)}))})),this.remoteDataChannelMap.clear()),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),B.debug("[".concat(this.store.clientId,"] P2PChannel disconnected, waiting to reconnect.")))}hasPendingRemoteDataChannel(e,t){for(const i of this.pendingRemoteDataChannels){const{user:n,id:o}=i;if((e instanceof aa?e.uid:e)===n.uid&&o===t)return!0}return!1}setPendingRemoteDataChannel(e,t){this.hasPendingRemoteDataChannel(e,t)||this.pendingRemoteDataChannels.push({user:e,id:t})}hasPendingRemoteMedia(e,t){for(const i of this.pendingRemoteTracks){const{user:n,kind:o}=i;if((e instanceof aa?e.uid:e)===n.uid&&t===o)return!0}return!1}setPendingRemoteMedia(e,t){this.hasPendingRemoteMedia(e,t)||this.pendingRemoteTracks.push({user:e,kind:t})}restartICE(e){var t=this;return Ri((function*(){if(!t.connection||t.state!==on.Connected)return;const i=yield pi(t.mutex.lock("From P2PChannel.restartICE"));let n;try{n=yield pi(t.connection.restartICE(e));const o=yield pi(n.next());if(o.done)return;const a=o.value,s=yield a;switch(Ia(t.connection)&&t.reportPCStats(Date.now(),!1,t._pcStatsUploadType),e){case $i.UDP_TCP_RELAY:t._pcStatsUploadType=en.UDP_TCP_RESTART;break;case $i.TCP_RELAY:t._pcStatsUploadType=en.TCP_RESTART;break;case $i.RELAY:t._pcStatsUploadType=en.RELAY_RESTART;break;default:t._pcStatsUploadType=en.OLD_RESTART}t._isTryConnecting=!0,n.next(s)}catch(e){var o;null===(o=n)||void 0===o||o.throw(e)}finally{i()}}))()}getUplinkNetworkQuality(){if(!this.connection)return 0;const e=this.connection.getStats(),t=this.localTrackMap.get(nn.LocalVideoTrack),i=this.localTrackMap.get(nn.LocalAudioTrack),n=e.videoSend.find((e=>e.ssrc===(null==t?void 0:t.ssrcs[0].ssrcId))),o=e.audioSend.find((e=>e.ssrc===(null==i?void 0:i.ssrcs[0].ssrcId)));if(!n||!o)return 1;const s=Ee(this,an.NeedSignalRTT),r=n?n.rttMs:void 0,c=o?o.rttMs:void 0,d=r&&c?(r+c)/2:r||c,l=(d&&s?(d+s)/2:d||s)||0,u=100*e.sendPacketLossRate*.7/50+.3*l/1500,h=u<.17?1:u<.36?2:u<.59?3:u<.1?4:5,_=null==t?void 0:t.track;if(_&&_._encoderConfig&&-1===_._hints.indexOf(a.SCREEN_TRACK)){const t=_._encoderConfig.bitrateMax,i=e.bitrate.actualEncoded;if(t&&i){const e=(1e3*t-i)/(1e3*t);return oi[e<.15?0:e<.3?1:e<.45?2:e<.6?3:4][h]}}return h}getDownlinkNetworkQuality(){if(!this.connection)return 0;const e=this.connection.getStats();let t=0;return Array.from(this.remoteUserMap.entries()).forEach((i=>{let[n]=i;const o=n._audioSSRC,a=n._videoSSRC,s=e.audioRecv.find((e=>e.ssrc===o)),r=e.videoRecv.find((e=>e.ssrc===a));if(!s&&!r)return void(t+=1);const c=Ee(this,an.NeedSignalRTT),d=e.rtt,l=(d&&c?(d+c)/2:d||c)||0,u=s?s.jitterMs:void 0,h=e.recvPacketLossRate;let _=.7*h*100/50+.3*l/1500;u&&(_=.6*h*100/50+.2*l/1500+.2*u/400);t+=_<.1?1:_<.17?2:_<.36?3:_<.59?4:5})),this.remoteUserMap.size>0?Math.round(t/this.remoteUserMap.size):t}async muteLocalTrack(e){return new Promise(((t,i)=>{this.handleMuteLocalTrack(e,t,i)}))}async replaceTrack(e,t){var i;if(B.debug("[".concat(this.store.clientId,"] P2PChannel replaceTrack from [").concat(e.getTrackId(),"] to [").concat(t.getTrackId(),"]")),!this.connection||this.state!==on.Connected)return;const n=Array.from(this.localTrackMap.entries()).find((t=>{let[,{track:i}]=t;return e===i}));if(!n)return;const a=n[0];if(e!==t&&(this.unbindLocalTrackEvents([{track:e,type:a}]),this.bindLocalTrackEvents([{track:t,type:a}]),n[1].track=t),await(null===(i=this.connection)||void 0===i?void 0:i.replaceTrack(t,n[1].id)),this.isPlanB){const e=n[1];e.id=t._mediaStreamTrack.id,this.localTrackMap.set(a,e)}if(a===nn.LocalVideoTrack&&!ne("DISABLE_DUAL_STREAM_USE_ENCODING")&&o().supportDualStreamEncoding){const t=this.localTrackMap.get(nn.LocalVideoLowTrack);if(t){const i=e._mediaStreamTrack.clone();t.track._originMediaStreamTrack.stop(),t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i,await new Promise(((e,i)=>{this.handleReplaceTrack(t.track,e,i,!0)}))}}}filterTobePublishedTracks(e,i,a){const s=[],r=this.getAllTracks();e=e.filter((e=>-1===r.indexOf(e))),e=_t(e);let c,d=!1;const u=this.localTrackMap.get(nn.LocalAudioTrack);for(const r of e){if(r instanceof n&&(this.localTrackMap.has(nn.LocalVideoTrack)||d?new ue(Z.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS).throw():(s.push({track:r,type:nn.LocalVideoTrack}),d=!0),i)){const e=this.getLowVideoTrack(r,a);s.push({track:e,type:nn.LocalVideoLowTrack})}if(r instanceof t)if(u){const e=u.track;if(e instanceof l)Ra([r]),e.addAudioTrack(r),this.bindLocalAudioTrackEvents(r,!0);else{const t=fa([e,r]);B.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection will replace audioTrack [").concat(t.getTrackId(),"]")),this.replaceTrack(e,t)}}else if(c instanceof l)Ra([r]),c.addAudioTrack(r);else if(c||!r._useAudioElement&&o().webAudioMediaStreamDest&&!r._bypassWebAudio){c=fa(c?[r,c]:[r])}else c=r}return c&&(B.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection will send audioTrack [").concat(c.getTrackId(),"]")),s.push({track:c,type:nn.LocalAudioTrack})),s}filterTobeUnpublishedTracks(e){const i=[],o=this.getAllTracks();e=e.filter((e=>-1!==o.indexOf(e))),e=_t(e);for(const o of e){if(o instanceof t){const e=this.localTrackMap.get(nn.LocalAudioTrack);if(!e)continue;e.track instanceof l?(e.track.removeAudioTrack(o),this.unbindLocalAudioTrackEvents(o),0===e.track.trackList.length&&(i.push([nn.LocalAudioTrack,e]),e.track.close())):i.push([nn.LocalAudioTrack,e])}if(o instanceof n){const e=this.localTrackMap.get(nn.LocalVideoTrack);if(!e)continue;i.push([nn.LocalVideoTrack,e]);const t=this.localTrackMap.get(nn.LocalVideoLowTrack);t&&i.push([nn.LocalVideoLowTrack,t])}}return i}filterTobePublishedDataChannels(e){return e=(e=_t(e)).filter((e=>-1===this.localDataChannels.findIndex((t=>t.id===e.id))))}filterTobeUnpublishedDataChannels(e){return e=(e=(e=_t(e)).filter((e=>-1!==this.localDataChannels.indexOf(e)))).filter((e=>e._originDataChannel))}bindLocalTrackEvents(e){e.forEach((e=>{let{track:t,type:i}=e;switch(i){case nn.LocalVideoTrack:t.addListener(N.GET_STATS,this.handleGetLocalVideoStats),t.addListener(N.GET_RTC_STATS,this.handleGetRTCStats),t.addListener(N.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.addListener(N.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.addListener(N.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.addListener(N.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this.handleUpdateVideoSendParameters),t.addListener(N.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.addListener(N.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.addListener(N.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case nn.LocalAudioTrack:this.bindLocalAudioTrackEvents(t);case nn.LocalVideoLowTrack:}}))}bindLocalAudioTrackEvents(e,t){e instanceof l?e.trackList.forEach((e=>{e.addListener(N.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(N.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(N.GET_STATS,this.handleGetLocalAudioStats),e.addListener(N.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(N.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)})):(e.addListener(N.GET_STATS,this.handleGetLocalAudioStats),e.addListener(N.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(N.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(N.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(N.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack),t||(e.addListener(N.NEED_REPLACE_TRACK,this.handleReplaceTrack),e.addListener(N.NEED_REPLACE_MIXING_TRACK,this.handleReplaceMixingTrack)))}unbindLocalTrackEvents(e){e||(e=Array.from(this.localTrackMap.entries()).map((e=>{let[t,{track:i}]=e;return{track:i,type:t}}))),e.forEach((e=>{let{track:t,type:i}=e;switch(i){case nn.LocalVideoTrack:t.off(N.GET_STATS,this.handleGetLocalVideoStats),t.off(N.GET_RTC_STATS,this.handleGetRTCStats),t.off(N.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.off(N.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.off(N.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.off(N.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this.handleUpdateVideoSendParameters),t.off(N.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.off(N.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.off(N.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case nn.LocalAudioTrack:this.unbindLocalAudioTrackEvents(t);case nn.LocalVideoLowTrack:}}))}unbindLocalAudioTrackEvents(e){e instanceof l?e.trackList.forEach((e=>{e.off(N.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(N.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(N.GET_STATS,this.handleGetLocalAudioStats),e.off(N.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(N.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)})):(e.off(N.GET_STATS,this.handleGetLocalAudioStats),e.off(N.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(N.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(N.NEED_REPLACE_TRACK,this.handleReplaceTrack),e.off(N.NEED_REPLACE_MIXING_TRACK,this.handleReplaceMixingTrack),e.off(N.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(N.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack))}bindRemoteTrackEvents(e,t){t instanceof v&&t.addListener(N.GET_STATS,(t=>{t(this.handleGetRemoteVideoStats(e))})),t instanceof g&&t.addListener(N.GET_STATS,(t=>{t(this.handleGetRemoteAudioStats(e))}))}unbindRemoteTrackEvents(e){e&&e.removeAllListeners(N.GET_STATS)}unbindAllRemoteTrackEvents(){Array.from(this.remoteUserMap.entries()).forEach((e=>{let[t,i]=e;i.has(Zi.AUDIO)&&this.unbindRemoteTrackEvents(t._audioTrack),i.has(Zi.VIDEO)&&this.unbindRemoteTrackEvents(t._videoTrack)}))}createGatewayPublishMessage(e,t){return e.map(((e,n)=>{let o,s,{track:r,type:c}=e;switch(c){case nn.LocalAudioTrack:o=Fi.Audio,s={dtx:r instanceof i&&r._config.DTX,hq:!1,lq:!1,stereo:!1,speech:!1};break;case nn.LocalVideoTrack:o=r._hints.includes(a.SCREEN_TRACK)?Fi.Screen:Fi.High,s=mi(mi({},kn(r)),{},{codec:this.store.codec,svc_mode:jn()});break;case nn.LocalVideoLowTrack:o=Fi.Low,s=mi(mi({},kn(r)),{},{codec:this.store.codec,svc_mode:jn()})}return{stream_type:o,attributes:s,ssrcs:t[n]}}))}createGatewayUnpublishMessage(e){return e.map((e=>{let t,[i,{track:n,ssrcs:o,id:s}]=e;switch(i){case nn.LocalVideoTrack:t=n._hints.includes(a.SCREEN_TRACK)?Fi.Screen:Fi.High;break;case nn.LocalAudioTrack:t=Fi.Audio;break;case nn.LocalVideoLowTrack:t=Fi.Low}return{stream_type:t,ssrcs:o,mid:s}}))}assignLocalTracks(e,t){e.forEach(((e,i)=>{let{track:n,type:o}=e;this.localTrackMap.set(o,{track:n,id:t[i].id,ssrcs:t[i].localSSRC})}))}withdrawLocalTracks(e){e.forEach((e=>{let[t]=e;this.localTrackMap.delete(t)}))}bindConnectionEvents(e){e.onConnectionStateChange=async t=>{if(B.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onConnectionStateChange(").concat(t,")")),this.emit(an.PeerConnectionStateChange,t),"connecting"===t&&e instanceof va&&!se()&&ne("FIRST_TCP_CANDIDATE")&&window.setTimeout((()=>{"connecting"===t&&e.extendCandidate()}),ne("FIRST_TCP_CANDIDATE_INTERVAL")),"connected"!==t||this.store.keyMetrics.peerConnectionEnd||this.store.peerConnectionEnd(),"connected"===t){this._restartTimer&&(window.clearTimeout(this._restartTimer),this._restartTimer=void 0),e instanceof va&&qa(e,!0),this._isTryConnecting&&this.reportPCStats(Date.now(),!0,this._pcStatsUploadType),this._isTryConnecting=!1,this._isStartRestartIce=!1,this._pcStatsUploadType=en.DISCONNECTED_OR_FAILED;if("CONNECTED"===Ee(this,an.QueryClientConnectionState)&&this._isWaitPcToRePub){const e=this.pendingLocalTracks.map((e=>e.getTrackId())),t=this.pendingLocalDataChannels.map((e=>"dc_".concat(e.id)));j.reportApiInvoke(this.store.sessionId,{name:We.REPUB_AFTER_PC_CONNECTED,options:e.concat(t),tag:He.TRACER}).onSuccess(),this.republish()}}if(ne("NEW_ICE_RESTART")&&e instanceof va&&!se()&&!this._forceTurn){if(tn.includes(t)){if(this._isStartRestartIce)return;this._isStartRestartIce=!0;const t=t=>{if(Ia(e)){B.debug("[".concat(this.store.clientId,"] [P2PChannel] try to restartICE, type is ").concat(t));"CONNECTED"===Ee(this,an.QueryClientConnectionState)&&this.emit(an.RequestRestartICE,t)}},i=()=>{Ia(e)&&(this.reportPCStats(Date.now(),!1,this._pcStatsUploadType),B.debug("[".concat(this.store.clientId,"] P2PConnection disconnected timeout, force reconnect")),setTimeout((()=>this.emit(an.P2PLost)),0),this.iceFailedCount+=1,this.requestReconnect())};return void(this._restartTimer=window.setTimeout((()=>{Xa(e,t,i)}),800))}}else{if("disconnected"===t&&"disconnected"===e.iceConnectionState)return setTimeout((()=>{if("disconnected"===e.iceConnectionState&&ne("ICE_RESTART")){"CONNECTED"===Ee(this,an.QueryClientConnectionState)&&this.emit(an.RequestRestartICE)}}),800),void setTimeout((()=>{"disconnected"===e.peerConnectionState&&(B.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection disconnected timeout 4000ms, force reconnect")),this.reportPCStats(Date.now(),!1,this._pcStatsUploadType),this._isTryConnecting=!1,setTimeout((()=>this.emit(an.P2PLost)),0),this.iceFailedCount+=1,this.requestReconnect())}),4e3);"failed"===t&&(B.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection state failed, force reconnect")),this.reportPCStats(Date.now(),!1,this._pcStatsUploadType),setTimeout((()=>this.emit(an.P2PLost)),0),this.iceFailedCount+=1,await this.requestReconnect())}},e.onICEConnectionStateChange=e=>{"connected"!==e||this.store.keyMetrics.iceConnectionEnd||this.store.iceConnectionEnd(),B.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICEConnectionStateChange(").concat(e,")")),j.reportApiInvoke(this.store.sessionId,{name:"ICEConnectionStateChange",options:e,tag:He.TRACER}).onSuccess(),this.emit(an.IceConnectionStateChange,e)},e.onICETransportStateChange=e=>{B.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICETransportStateChange(").concat(e,")"))},e.onDTLSTransportStateChange=e=>{B.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportStateChange(").concat(e,")"))},e.onDTLSTransportError=e=>{B.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportError(").concat(e,")"))},e.onFirstAudioDecoded=e=>{const t=Array.from(this.remoteUserMap.keys()).find((t=>t._audioSSRC===e));var i;t&&(this.store.subscribe(t.uid,"audio",void 0,void 0,void 0,Date.now()),null===(i=t.audioTrack)||void 0===i||i.emit(y.FIRST_FRAME_DECODED),j.firstRemoteFrame(this.store.sessionId,W.FIRST_AUDIO_DECODE,H.FIRST_AUDIO_DECODE,{peer:t._uintid,subscribeElapse:ta.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId}))},e.onFirstAudioReceived=e=>{const t=Array.from(this.remoteUserMap.keys()).find((t=>t._audioSSRC===e));t&&j.firstRemoteFrame(this.store.sessionId,W.FIRST_AUDIO_RECEIVED,H.FIRST_AUDIO_RECEIVED,{peer:t._uintid,subscribeElapse:ta.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId})},e.onFirstVideoDecoded=(e,t,i)=>{const n=Array.from(this.remoteUserMap.keys()).find((t=>t._videoSSRC===e));n&&this.store.firstVideoFrameDecoded(n.uid,{firstDecoded:Date.now()}),this.reportVideoFirstFrameDecoded(e,t,i)},e.onFirstVideoRender=e=>{const t=Array.from(this.remoteUserMap.keys()).find((t=>t._videoSSRC===e));t&&(this.store.firstVideoFrameDecoded(t.uid,{firstPreRender:Date.now()}),this.reportVideoFirstFrameRender(t))},e.onFirstVideoReceived=e=>{const t=Array.from(this.remoteUserMap.keys()).find((t=>t._videoSSRC===e));t&&(this.store.firstVideoFrameDecoded(t.uid,{firstReceived:Date.now()}),j.firstRemoteFrame(this.store.sessionId,W.FIRST_VIDEO_RECEIVED,H.FIRST_VIDEO_RECEIVED,{peer:t._uintid,subscribeElapse:ta.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId}))},e.onSelectedLocalCandidateChanged=(e,t)=>{const i="relay"===e.candidateType,n="relay"===t.candidateType;"unknown"!==t.candidateType&&i===n||this.emit(an.ConnectionTypeChange,i),B.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedLocalCandidateChanged(").concat(JSON.stringify(Bn(t))," -> ").concat(JSON.stringify(Bn(e)),")"))},e.onSelectedRemoteCandidateChanged=(e,t)=>{B.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedRemoteCandidateChanged(").concat(JSON.stringify(Bn(t))," -> ").concat(JSON.stringify(Bn(e)),")"))},e.onFirstVideoDecodedTimeout=e=>{this.reportVideoFirstFrameDecoded(e,void 0,void 0,!0)},e.getLocalVideoStats=()=>{const e=this.statsCollector.getLocalVideoTrackStats(),t=this.statsCollector.getRTCStats();return mi(mi({},e),t)},e.onICECandidateError=e=>{this._iceError=e}}resetConnection(e){e instanceof va&&function(e){Ha.delete(e.id),qa(e)}(e),e.close(),this.emit(an.PeerConnectionStateChange,"closed"),function(e){e.onConnectionStateChange=void 0,e.onICEConnectionStateChange=void 0,e.onICETransportStateChange=void 0,e.onDTLSTransportStateChange=void 0,e.onDTLSTransportError=void 0,e.onFirstAudioDecoded=void 0,e.onFirstAudioReceived=void 0,e.onFirstVideoDecoded=void 0,e.onFirstVideoReceived=void 0,e.onSelectedLocalCandidateChanged=void 0,e.onSelectedRemoteCandidateChanged=void 0,e.onFirstVideoDecodedTimeout=void 0,e.getLocalVideoStats=void 0}(e),this._isWaitPcToRePub=!1}filterTobeMutedTracks(e){const i=[];if(-1===this.getAllTracks().indexOf(e))return i;const n=this.localTrackMap.get(nn.LocalAudioTrack);if(e instanceof t&&(null==n?void 0:n.track)instanceof l)return n.track.isActive||i.push([nn.LocalAudioTrack,n]),i;const o=Array.from(this.localTrackMap.entries()).find((t=>{let[,{track:i}]=t;return e===i}));if(o&&(i.push(o),o[0]===nn.LocalVideoTrack)){const e=this.localTrackMap.get(nn.LocalVideoLowTrack);e&&i.push([nn.LocalVideoLowTrack,e])}return i}filterTobeUnmutedTracks(e){const i=[],n=this.localTrackMap.get(nn.LocalAudioTrack);if(e instanceof t&&(null==n?void 0:n.track)instanceof l)return n.track.isActive&&i.push([nn.LocalAudioTrack,n]),i;const o=Array.from(this.localTrackMap.entries()).find((t=>{let[,{track:i}]=t;return e===i}));if(o)if(o[0]===nn.LocalVideoTrack){i.push(o);const e=this.localTrackMap.get(nn.LocalVideoLowTrack);e&&i.push([nn.LocalVideoLowTrack,e])}else i.push(o);return i}createMuteMessage(e){return e.map((e=>{let t,[i,{track:n,ssrcs:o,id:s}]=e;switch(i){case nn.LocalAudioTrack:t=Fi.Audio;break;case nn.LocalVideoTrack:t=n._hints.includes(a.SCREEN_TRACK)?Fi.Screen:Fi.High;break;case nn.LocalVideoLowTrack:t=Fi.Low}return{stream_type:t,ssrcs:o,mid:s}}))}createUnmuteMessage(e){return e.map((e=>{let t,[i,{track:n,ssrcs:o,id:s}]=e;switch(i){case nn.LocalAudioTrack:t=Fi.Audio;break;case nn.LocalVideoTrack:t=n._hints.includes(a.SCREEN_TRACK)?Fi.Screen:Fi.High;break;case nn.LocalVideoLowTrack:t=Fi.Low}return{stream_type:t,ssrcs:o,mid:s}}))}filterTobeUnSubscribedTracks(e,t){const i=[],n=this.remoteUserMap.get(e);if(!n)return i;if(t){const o=n.get(t);if(!o)return i;i.push([e,{kind:t,id:o}])}else Array.from(n.entries()).forEach((t=>{let[n,o]=t;i.push([e,{kind:n,id:o}])}));return i}filterTobeUnSubscribedDataChannels(e,t){const i=[];return t.forEach((t=>{var n;null!==(n=this.remoteDataChannelMap.get(e))&&void 0!==n&&n.has(t.id)&&i.push(t)})),i}createUnsubscribeMessage(e){const t=[];return e.forEach((e=>{let[i,{kind:n,id:o}]=e;switch(n){case Zi.VIDEO:return void(i._videoSSRC&&t.push({stream_type:Zi.VIDEO,ssrcId:i._videoSSRC}));case Zi.AUDIO:return void(i._audioSSRC&&t.push({stream_type:Zi.AUDIO,ssrcId:i._audioSSRC}))}})),t}createUnsubscribeAllMessage(e){const t=new Map;return e.forEach((e=>{let[i,{kind:n}]=e;if(t.has(i)){let e=t.get(i);n===Zi.VIDEO?e|=Wi.Video:e|=Wi.Audio,t.set(i,e)}else n===Zi.VIDEO?t.set(i,Wi.Video):t.set(i,Wi.Audio)})),{users:Array.from(t.entries()).map((e=>{let[t,i]=e;return{stream_id:t.uid,stream_type:i}}))}}withdrawRemoteTracks(e){e.forEach((e=>{let[t,{kind:i}]=e;const n=this.remoteUserMap.get(t);n&&(n.delete(i),0===Array.from(n.entries()).length&&this.remoteUserMap.delete(t))}))}async updateBitrateLimit(e){const t=this.localTrackMap.get(nn.LocalVideoTrack),i=this.localTrackMap.get(nn.LocalVideoLowTrack);t&&(await t.track.setBitrateLimit(e.uplink),await new Promise(((e,i)=>{this.handleUpdateVideoEncoder(t.track,e,i,!0)}))),i&&e.low_stream_uplink&&(await i.track.setBitrateLimit({max_bitrate:e.low_stream_uplink.bitrate,min_bitrate:e.low_stream_uplink.bitrate||0}),await new Promise(((e,t)=>{this.handleUpdateVideoEncoder(i.track,e,t,!0)})))}isP2PDisconnected(){if(this.connection){return"connected"!==this.connection.peerConnectionState}return!0}isPreallocation(){return this.connection instanceof va&&this.connection.isPreallocation}isPreSub(){return this.connection instanceof va&&this.connection.isPreSub()}mapPubResToRemoteConfig(e,t,i){return e.map(((e,n)=>{var o;let{stream_type:s}=e;const r=null===(o=t.find((e=>{let{stream_type:t}=e;return s===t})))||void 0===o?void 0:o.attributes;if(r&&ne("DISABLE_SCREEN_SHARE_REMB")){const e=i[n]._hints;(e.includes(a.SCREEN_TRACK)||e.includes(a.SCREEN_LOW_TRACK))&&(r.remb=!1,B.debug("disable remb for screen share, hints:",e))}return r}))}async tryToUnmuteAudio(e){for(let n=0;n<e.length;n++)if(e[n]instanceof t){var i;const t=this.filterTobeUnmutedTracks(e[n]);if(0===t.length)continue;await(null===(i=this.connection)||void 0===i?void 0:i.unmuteLocal(t.map((e=>{let[,{id:t}]=e;return t}))));const o=this.createUnmuteMessage(t);return void await ut(this,an.RequestUnmuteLocal,o)}}bindStatsUploaderEvents(){this.statsUploader.requestStats=()=>this.getStats(),this.statsUploader.requestLocalMedia=()=>Array.from(this.localTrackMap.entries()),this.statsUploader.requestRemoteMedia=()=>Array.from(this.remoteUserMap.entries()),this.statsUploader.requestVideoIsReady=e=>{var t;return!(null===(t=this.connection)||void 0===t||!t.getRemoteVideoIsReady(e))},this.statsUploader.requestUpload=(e,t)=>this.emit(an.RequestUpload,e,t),this.statsUploader.requestUploadStats=e=>this.emit(an.RequestUploadStats,e),this.statsUploader.requestAllTracks=()=>this.getAllTracks(),this.statsUploader.requestTransportStats=()=>{var e;return{connectState:(null===(e=this.connection)||void 0===e?void 0:e.peerConnectionState)||"closed"}}}unbindStatsUploaderEvents(){this.statsUploader.requestStats=void 0,this.statsUploader.requestLocalMedia=void 0,this.statsUploader.requestRemoteMedia=void 0,this.statsUploader.requestVideoIsReady=void 0}async requestReconnect(){this.dtlsFailedCount+=1,await _e(he(this.dtlsFailedCount,Ye)),this.emit(an.RequestReconnect)}async reconnectP2P(){const e=Array.from(this.localTrackMap.entries()),t=this.createGatewayUnpublishMessage(e);Array.from(this.remoteUserMap.entries()),t.length>0&&await pe(this,an.RequestUnpublishForReconnectPC,t),this.disconnectForReconnect(),this.emit(an.RequestReconnectPC)}canPublishLowStream(){return this.localTrackMap.has(nn.LocalVideoTrack)||this.pendingLocalTracks.some((e=>e instanceof n))}throwIfTrackTypeNotMatch(e){if(e.filter((e=>e instanceof n)).length>1)throw new ue(Z.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(e.filter((e=>e instanceof t)).length>1&&(e.some((e=>e instanceof t&&e._bypassWebAudio))||!o().webAudioMediaStreamDest))throw new ue(Z.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode");for(const i of e){if(i instanceof n&&this.pendingLocalTracks.some((e=>e instanceof n)))throw new ue(Z.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(i instanceof t&&this.pendingLocalTracks.some((e=>e instanceof t))&&(!o().webAudioMediaStreamDest||i._bypassWebAudio||this.pendingLocalTracks.some((e=>e instanceof t&&e._bypassWebAudio))))throw new ue(Z.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode")}}getLowVideoTrack(e,t){const i=!ne("DISABLE_DUAL_STREAM_USE_ENCODING")&&o().supportDualStreamEncoding,s=mi(mi({},{width:160,height:120,framerate:15,bitrate:50}),t);let r;r=i?e._mediaStreamTrack.clone():Na(e,s);const c=fe(8,"track-low-"),d=new n(r,mi(mi({},i&&{scaleResolutionDownBy:xn(s,e)}),{},{frameRate:s.framerate,bitrateMax:s.bitrate,bitrateMin:s.bitrate}),void 0,void 0,c);return d.on(b.TRANSCEIVER_UPDATED,(t=>{e._updateRtpTransceiver(t,w.LOW_STREAM)})),d._hints.push(a.LOW_STREAM),e._hints.includes(a.SCREEN_TRACK)&&d._hints.push(a.SCREEN_LOW_TRACK),e.on("sei-to-send",(e=>{d.emit("sei-to-send",e)})),e.addListener(N.NEED_CLOSE,(()=>{d.close()})),d}async globalLock(){return this.mutex.lock("From P2PChannel.globalLock")}async reportPCStats(e,t,i){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null;if(this.connection&&this.connection instanceof va){var o,a,s,r;const c=this.store.keyMetrics.descriptionStart||0,{iceConnectionState:d,dtlsTransportState:l,peerConnectionState:u}=this.connection,{local:h,remote:_}=await this.connection.getSelectedCandidatePair();j.pcStats(this.store.sessionId,{startTime:c,eventElapse:e-c||0,iceconnectionsate:d,dtlsstate:l,connectionstate:u,intSucc:t?1:2,error:this._iceError||n||"",selectedLocalCandidateProtocol:null!==(o=null==h?void 0:h.protocol)&&void 0!==o?o:"",selectedLocalCandidateType:null!==(a=h.candidateType)&&void 0!==a?a:"",selectedLocalCandidateAddress:"".concat(h.address,":").concat(h.port),selectedRemoteCandidateProtocol:null!==(s=_.protocol)&&void 0!==s?s:"",selectedRemoteCandidateType:null!==(r=_.candidateType)&&void 0!==r?r:"",selectedRemoteCandidateAddress:"".concat(_.address,":").concat(_.port),restartCnt:i,preallocation:this.connection.isPreallocation}),this._iceError=null}}reportVideoFirstFrameRender(e){const t=this.store.keyMetrics,i=t.firstVideoFrameDecoded.find((t=>t.userId===e.uid));if(!i)return;const{isInternalUpload:n,isExternalUpload:o}=i;if(n&&o)return;const{subscribeEnd:a,firstPreRender:s,peerPublishDuration:c,peerPubStatusMs:d}=i;let{firstRender:l=0}=i;if(a&&(l||s)&&c&&d){i.isInternalUpload=!0;const{playEnd:n}=i;n&&(i.isExternalUpload=!0);const{firstPreRender:o=0}=i;l=o||l;const s=e.videoTrack,u={peer:e._uintid,width:(null==s?void 0:s._videoWidth)||0,height:(null==s?void 0:s._videoHeight)||0,ssrc:e._videoSSRC||0,p2pid:this.store.p2pId,peerPublishDuration:c,peerPubStatusMs:d,joinChannelStart:t.joinStart||0,preloadStart:t.preloadStart||0,preloadEnd:t.preloadEnd||0,apStart:t.requestAPStart||0,apEnd:t.requestAPEnd||0,suaEnd:t.requestSUAEnd||0,beforeConnect:t.beforeConnect||0,peerReceiver:t.peerReceiver||0,ice:t.iceConnectionEnd||0,pc:t.peerConnectionEnd||0,signalConnected:t.signalConnected||0,joinReq:t.joinReq||0,joinRes:t.joinRep||0,userJoinNotify:i.userJoinNotify||0,videoAddNotify:i.videoAddNotify||0,subscribeStart:i.subscribeStart||0,subscribeEnd:i.subscribeEnd||0,firstReceived:i.firstReceived||0,firstDecoded:i.firstDecoded||0,firstPreRender:o||0,firstRender:n?Math.max(l,n):Math.max(l,a),playStart:i.playStart||0,playEnd:i.playEnd||0,isPreSub:!(!e._videoSSRC||!this.isPreSubScribe(e._videoSSRC)),isPrePc:this.isPreallocation(),isPreInstantVideo:r(this.store)};j.firstXLAPeerFirstVideoFrame(this.store.sessionId,u)}}reportVideoFirstFrameDecoded(e,t,i,n){const o=Array.from(this.remoteUserMap.keys()).find((t=>t._videoSSRC===e));if(o){n||this.store.subscribe(o.uid,"video",void 0,void 0,void 0,void 0,Date.now());const a=this.store.keyMetrics,s=a.subscribe.find((e=>e.userId===o.uid&&"video"===e.type));j.firstRemoteVideoDecode(this.store.sessionId,W.FIRST_VIDEO_DECODE,H.FIRST_VIDEO_DECODE,{peer:o._uintid,videowidth:t,videoheight:i,subscribeElapse:ta.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId,apEnd:a.requestAPEnd||0,apStart:a.requestAPStart||0,joinGwEnd:a.joinGatewayEnd||0,joinGwStart:a.joinGatewayStart||0,pcEnd:a.peerConnectionEnd||0,pcStart:a.peerConnectionStart||0,subscriberEnd:(null==s?void 0:s.subscribeEnd)||0,subscriberStart:(null==s?void 0:s.subscribeStart)||0,videoAddNotify:(null==s?void 0:s.streamAdded)||0,state:n?1:0,firstFrame:(null==s?void 0:s.firstFrame)||0})}}async remoteMediaSsrcChanged(e,t,i){if(!this.connection)return!1;const n=this.remoteUserMap.get(e);if(!n)return!1;const o=n.get(t);if(!o)return!1;const a=await this.connection.getRemoteSSRC(o);return void 0!==a&&a!==i}unbindRtpTransceiver(){0!==this.localTrackMap.size&&Array.from(this.localTrackMap.entries()).forEach((e=>{let[t,{track:i}]=e;t===nn.LocalVideoLowTrack?i._updateRtpTransceiver(void 0,w.LOW_STREAM):i._updateRtpTransceiver(void 0)}))}}).prototype,"startP2PConnection",[Qa],Object.getOwnPropertyDescriptor(Ja.prototype,"startP2PConnection"),Ja.prototype),li(Ja.prototype,"connect",[Qa],Object.getOwnPropertyDescriptor(Ja.prototype,"connect"),Ja.prototype),li(Ja.prototype,"updateRemoteRTPCapabilities",[Qa],Object.getOwnPropertyDescriptor(Ja.prototype,"updateRemoteRTPCapabilities"),Ja.prototype),li(Ja.prototype,"publishDataChannel",[Qa],Object.getOwnPropertyDescriptor(Ja.prototype,"publishDataChannel"),Ja.prototype),li(Ja.prototype,"unpublish",[Qa],Object.getOwnPropertyDescriptor(Ja.prototype,"unpublish"),Ja.prototype),li(Ja.prototype,"unpublishDataChannel",[Qa],Object.getOwnPropertyDescriptor(Ja.prototype,"unpublishDataChannel"),Ja.prototype),li(Ja.prototype,"unpublishLowStream",[Qa],Object.getOwnPropertyDescriptor(Ja.prototype,"unpublishLowStream"),Ja.prototype),li(Ja.prototype,"subscribeDataChannel",[Qa],Object.getOwnPropertyDescriptor(Ja.prototype,"subscribeDataChannel"),Ja.prototype),li(Ja.prototype,"subscribe",[Qa],Object.getOwnPropertyDescriptor(Ja.prototype,"subscribe"),Ja.prototype),li(Ja.prototype,"massSubscribe",[Qa],Object.getOwnPropertyDescriptor(Ja.prototype,"massSubscribe"),Ja.prototype),li(Ja.prototype,"unsubscribe",[Qa],Object.getOwnPropertyDescriptor(Ja.prototype,"unsubscribe"),Ja.prototype),li(Ja.prototype,"unsubscribeDataChannel",[Qa],Object.getOwnPropertyDescriptor(Ja.prototype,"unsubscribeDataChannel"),Ja.prototype),li(Ja.prototype,"massUnsubscribe",[Qa],Object.getOwnPropertyDescriptor(Ja.prototype,"massUnsubscribe"),Ja.prototype),li(Ja.prototype,"muteRemote",[Qa],Object.getOwnPropertyDescriptor(Ja.prototype,"muteRemote"),Ja.prototype),li(Ja.prototype,"unmuteRemote",[Qa],Object.getOwnPropertyDescriptor(Ja.prototype,"unmuteRemote"),Ja.prototype),li(Ja.prototype,"hasRemoteMediaWithLock",[Qa],Object.getOwnPropertyDescriptor(Ja.prototype,"hasRemoteMediaWithLock"),Ja.prototype),li(Ja.prototype,"disconnectForReconnect",[Qa],Object.getOwnPropertyDescriptor(Ja.prototype,"disconnectForReconnect"),Ja.prototype),li(Ja.prototype,"updateBitrateLimit",[Qa],Object.getOwnPropertyDescriptor(Ja.prototype,"updateBitrateLimit"),Ja.prototype),li(Ja.prototype,"remoteMediaSsrcChanged",[Qa],Object.getOwnPropertyDescriptor(Ja.prototype,"remoteMediaSsrcChanged"),Ja.prototype),Ja);function Qa(e,t,i){const n=e[t];if("function"!=typeof n)throw new Error("Cannot use mutex on object property.");return i.value=async function(){const e=this.mutex,i=await e.lock("From P2PChannel.".concat(t));try{for(var o=arguments.length,a=new Array(o),s=0;s<o;s++)a[s]=arguments[s];return await n.apply(this,a)}finally{i()}},i}const Za=Date.now(),$a=20,es=new Map,ts=new Map;async function is(e){const t=es.get(e),i=Array.isArray(t)&&t[t.length-1],n=ts.get(e);if(!i)return void(n.isSyncing=!1);const o={uid:i.uid,payload:i.payload};0===n.firstRecvTs&&(n.firstRecvTs=i.recvTs,n.firstSendTs=i.sendTs);const a=i.sendTs-n.firstSendTs,s=a-(Date.now()-n.firstRecvTs);s>0&&(n.firstRecvTs=Date.now()-a);let r=i.mediaDelay+s;r<=0?(t.pop(),ns(i.context,o),r=0):r=Math.min(r,$a),setTimeout((()=>t.length&&is(e)),r)}function ns(e,t){e.safeEmit(pt.STREAM_MESSAGE,t.uid,t.payload),e.onStreamMessage&&e.onStreamMessage(t)}function os(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2?arguments[2]:void 0;if(!e.syncWithAudio)return ns(i,{uid:e.uid,payload:e.payload});const n="".concat(i.id,"-").concat(e.uid),o=es.get(n)||[],a=o.findIndex((t=>e.sendTs>=t.sendTs)),s=mi(mi({},e),{},{context:i,mediaDelay:t,recvTs:Date.now()});-1===a?o.push(s):o.splice(a,0,s),es.set(n,o);let r=!1;var c;ts.has(n)?r=!(null===(c=ts.get(n))||void 0===c||!c.isSyncing):ts.set(n,{isSyncing:r,firstRecvTs:0,firstSendTs:0});r||is(n)}const as=Ne().name;async function ss(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const i=j.reportApiInvoke(null,{tag:He.TRACER,name:We.CHECK_VIDEO_TRACK_IS_ACTIVE,options:[t]});if(!(e instanceof n||e instanceof v)){const e=new F(Z.INVALID_TRACK,"the parameter is not a video track");return i.onError(e),e.throw()}t&&t<1e3&&(t=1e3);const o=e instanceof n?e.getTrackLabel():"remote_track",a=e.getMediaStreamTrack(!0),s=document.createElement("video");s.style.width="1px",s.style.height="1px",s.setAttribute("muted",""),s.muted=!0,s.setAttribute("playsinline",""),s.controls=!1,(Je()||Et())&&(s.style.opacity="0.01",s.style.position="fixed",s.style.left="0",s.style.top="0",document.body.appendChild(s)),s.srcObject=new MediaStream([a]),s.play();const r=document.createElement("canvas");r.width=160,r.height=120;let c=0,d=0;try{const e=Date.now();c=await function(e,t,i,n){let o,a=0,s=null;return new Promise(((r,c)=>{function d(){a>n&&o&&(o(),r(a));const t=i.getContext("2d");if(!t){const e=new F(Z.UNEXPECTED_ERROR,"can not get canvas 2d context.");return B.error(e.toString()),void c(e)}t.drawImage(e,0,0,160,120);const d=t.getImageData(0,0,i.width,i.height),l=Math.floor(d.data.length/3);if(s){for(let e=0;e<l;e+=3)if(d.data[e]!==s[e])return a+=1,void(s=d.data);s=d.data}else s=d.data}setTimeout((()=>{o&&(o(),r(a))}),t),o=f((()=>{d()}),30)}))}(s,t,r,4),d=Date.now()-e}catch(e){throw i.onError(e),e}as===be.SAFARI&&(s.pause(),s.remove()),s.srcObject=null;const l=c>4,u={duration:d,changedPicNum:c,deviceLabel:o,result:l};return B.info("[track-".concat(e.getTrackId(),"] check video track active completed. ").concat(JSON.stringify(u))),i.onSuccess(u),l}async function rs(e){let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const n=j.reportApiInvoke(null,{tag:He.TRACER,name:We.CHECK_AUDIO_TRACK_IS_ACTIVE,options:[i]});if(!(e instanceof t||e instanceof g)){const e=new F(Z.INVALID_TRACK,"the parameter is not a audio track");return n.onError(e),e.throw()}i&&i<1e3&&(i=1e3);const o=e instanceof t?e.getTrackLabel():"remote_track",a=e.getVolumeLevel();let s=a,r=a;const c=Date.now();return new Promise((t=>{const a=setInterval((()=>{const d=e.getVolumeLevel();s=d>s?d:s,r=d<r?d:r;const l=s-r>1e-4,u=Date.now()-c;if(l||u>i){clearInterval(a);const i=l,r={duration:u,deviceLabel:o,maxVolumeLevel:s,result:i};B.info("[track-".concat(e.getTrackId(),"] check audio track active completed. ").concat(JSON.stringify(r))),n.onSuccess(r),t(i)}}),200)}))}const cs="websdk_ng_cache_parameter",ds=ne("MAX_PRELOAD_ASYNC_LENGTH"),ls=1e4,us=new Map,hs=[];let _s=null,ps=0,Es=0;const Ss=new Map,ms=function(e,t){const i=[];let n=0;const o=async()=>{const e=i.shift();e&&await e(),i.length>0&&n<t?o():n--};return async function(){for(var a=arguments.length,s=new Array(a),r=0;r<a;r++)s[r]=arguments[r];return new Promise((async(a,r)=>{i.push((async()=>{try{const t=await e(...s);a(t)}catch(e){r(e)}})),n<t&&(n++,o())}))}}(Cs,ds),Rs=Zt.CancelToken.source();async function fs(e,t,i,n){return Cs(e,t,i,n)}async function Cs(e,t,i,n,a,s){try{if(!ne("ENABLE_PRELOAD"))return;if(!o().supportWebCrypto)return void St((()=>{B.warn("Your browser does not support preloading, this feature be run in a secure environment")}),"preload_webcrypto_not_supported");if(!i&&null!==i)throw new ue(Z.INVALID_PARAMS,"Invalid token: ".concat(i,". If you don not use token, set it to null"));i&&ee(i,"token",1,2047),ee(e,"appid",1,2047),Pi(t),n&&Li(n);const r=mt();B.debug("preload channel ".concat(t,", uid is ").concat(n));const c={appId:e,cname:t,token:i||e,uid:"string"!=typeof n?n:null,sid:r,proxyServer:a};let d,l;"string"==typeof n?(c.stringUid=n,[l,d]=await Promise.all([qo(n,{sid:r,appId:e},Rs.token),Jo(mi(mi({},c),{},{token:i||e,uid:0}),Rs.token)]),c.uid=l.uid,d.gatewayInfo.uid=c.uid,d.gatewayInfo.res.uid=c.uid):(s&&(c.stringUid=s),d=await Jo(c,Rs.token));const u={sid:r,appId:e,cname:t,token:i||e,uid:c.stringUid||n,intUid:c.uid||d.gatewayInfo.uid,stringUid:c.stringUid,ts:Date.now(),sua:l,ap:d};await async function(e){let t;try{e.uid&&Is({appId:e.appId,cname:e.cname,token:e.token,uid:e.uid,stringUid:e.stringUid});const i=bs(e),n=await async function(e,t){try{const i=await window.crypto.subtle.importKey("raw",ft(t),"AES-GCM",!1,["encrypt"]),n=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:new Uint8Array(1)},i,Ct(window.btoa(JSON.stringify(e))));return Tt(new Uint8Array(n))}catch(e){return}}(e,e.token||e.appId);if(!n)return;t=ys(cs);const o=t?JSON.parse(t):[];o.push({[i]:n}),o.length>ne("AP_CACHE_NUM")&&o.shift(),Ns(cs,JSON.stringify(o))}catch(e){B.warn("Error caching server parameters:",e.message),Ns(cs,"")}}(u),ps++}catch(e){throw Es++,function(e){_s||(_s=window.setTimeout((()=>{let t="";Ss.forEach(((e,i)=>{t+="".concat(i,": ").concat(e," ;")})),j.reportApiInvoke(null,{name:We.PRELOAD,options:{success:ps,failed:Es,err:t}}).onError(e),ps=0,Es=0,Ss.clear(),_s=null}),ls));const t=Ss.get(e.code)||0;Ss.set(e.code,t+1)}(e),e}}async function Ts(e){try{if(ne("AP_REQUEST_DETAIL")||ne("ENABLE_ROLE_SELECT_EDGE"))return;const t=Is(e);if(!t||"disabled"!==e.cloudProxyServer)return;const i=await async function(e,t){try{const i=await window.crypto.subtle.importKey("raw",ft(t),"AES-GCM",!1,["decrypt"]),n=await window.crypto.subtle.decrypt({name:"AES-GCM",iv:new Uint8Array(1)},i,Ct(e));return JSON.parse(window.atob(Tt(new Uint8Array(n))))}catch(e){return}}(t,e.token||e.appId);if(!i)return;if(!function(e,t){const i=e.cname===t.cname&&e.appId===t.appId&&e.token===t.token;if(!i)return!1;return t.stringUid?e.stringUid===t.stringUid:"number"==typeof t.uid?e.uid===t.uid:e.uid==t.uid}(i,e))return;if(i&&Date.now()-i.ts<ne("AP_CACHE_LIFETIME"))return i}catch(e){B.warn("Error get preloadInfo",e.message)}}function Is(e){let t;try{if(t=ys(cs),!t)return;const i=JSON.parse(t),n=bs(e),o=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1}(i,(e=>n in e));if(-1===o)return;const a=i.splice(o,1)[0];return Ns(cs,JSON.stringify(i)),a[n]}catch(e){B.warn("Error delete preload info: ".concat(t),e.message),Ns(cs,"")}}function As(e){if(e){let t=us.get(e);t&&(window.clearTimeout(t),t=null,us.delete(e)),hs.includes(e)||"disabled"!==e.cloudProxyServer||hs.push(e)}if(us.size<ne("AP_CACHE_NUM")&&hs.length>0){const e=hs.shift();us.set(e,window.setTimeout((async()=>{const{appId:t,cname:i,token:n,stringUid:o,uid:a,proxyServer:s}=e;try{await ms(t,i,n,a,s,o),us.has(e)&&As(e)}catch(t){B.warn("update preload failed",t.message),gs(e)}}),ne("AP_UPDATE_INTERVAL")))}}function gs(e){const t=hs.indexOf(e);-1!==t&&hs.splice(t,1);let i=us.get(e);i&&(window.clearTimeout(i),i=null,us.delete(e),As())}function vs(e,t){const i=e.sua,n=e.ap;t&&i&&j.reqUserAccount(e.sid,{lts:i.requestTime,elapse:i.elapse,success:!0,serverAddr:i.url,stringUid:t,uid:e.intUid,errorCode:null,extend:i.req}),j.reportResourceTiming(e.ap.url,e.sid),j.joinWebProxyAP(e.sid,{lts:n.requestTime,elapse:n.elapse,sucess:1,apServerAddr:n.url,turnServerAddrList:n.proxyInfo.addresses.map((e=>e.ip)).join(","),eventType:"disabled",unilbsServerIds:[wn.CHOOSE_SERVER,wn.CLOUD_PROXY_FALLBACK].toString()}),j.joinChooseServer(e.sid,{lts:n.requestTime,elapse:n.elapse,succ:!0,csAddr:n.url,opid:n.opid,serverList:n.gatewayInfo.gatewayAddrs.map((e=>e.address)),ec:null,cid:n.gatewayInfo.cid.toString(),uid:n.gatewayInfo.uid.toString(),csIp:n.gatewayInfo.csIp,unilbsServerIds:[wn.CHOOSE_SERVER].toString(),isHttp3:n.isHttp3})}function ys(e){return window.atob(window.localStorage.getItem(e)||"")}function Ns(e,t){window.localStorage.setItem(e,window.btoa(t))}function bs(e){let t="".concat(e.appId,"_").concat(e.cname);return"string"==typeof e.uid&&(t+="_s_".concat(e.uid)),"number"==typeof e.uid&&(t+="_".concat(e.uid)),e.token&&(t+="_".concat(e.token)),Rt(t)}const ws={},Os={};function Ds(e,t){let i,n,o;return t?(o=0<=(e>>>=0)&&e<256)&&(n=Os[e],n)?n:(i=Ps(e,0,!0),o&&(Os[e]=i),i):(o=-128<=(e|=0)&&e<128)&&(n=ws[e],n)?n:(i=Ps(e,e<0?-1:0,!1),o&&(ws[e]=i),i)}function Ps(e,t,i){return{low:0|e,high:0|t,unsigned:!!i}}var Ls,ks,Us,Ms,Vs,xs,Bs,Fs,js,Gs,Ws,Hs,Ks,Ys,qs,Xs,Js,zs,Qs,Zs,$s,er,tr,ir,nr,or,ar,sr,rr,cr,dr,lr,ur,hr,_r,pr,Er,Sr,mr,Rr,fr,Cr;Ds(0,!0),Ds(0),re.setLogger(B);let Tr=(Ls=K(),ks=K({argsMap:(e,t)=>{if(!Array.isArray(t)){if(!(t instanceof O))return[t];t=[t]}return t.map((e=>e?Object(e).toString():"null"))}}),Us=K({argsMap:(e,t)=>(t||(t=[]),Array.isArray(t)||t.trackMediaType!==D.DATA?(Array.isArray(t)||(t=[t]),t.map((e=>e.getTrackId()))):[t.getChannelId()])}),Ms=K({argsMap:(e,t,i,n)=>["object"==typeof t?t.uid:t,i,n]}),Vs=K({argsMap:(e,t,i)=>[t,i]}),xs=K({argsMap:(e,t)=>t.map((e=>{let{user:t,mediaType:i}=e;return[null==t?void 0:t.uid,i]}))}),Bs=K({argsMap:(e,t,i,n)=>["object"==typeof t?t.uid:t,i,n]}),Fs=K({argsMap:(e,t)=>t.map((e=>{let{user:t,mediaType:i}=e;return{uid:null==t?void 0:t.uid,mediaType:i}}))}),js=K(),Gs=K(),Ws=K(),Hs=K(),Ks=K(),Ys=K(),qs=K(),Xs=K(),Js=K(),zs=K(),Qs=K(),Zs=K(),$s=K(),er=K(),tr=K(),ir=K({argsMap:(e,t)=>[t]}),nr=K(),or=K(),ar=K(),sr=K(),rr=K(),cr=K(),dr=K(),lr=K(),ur=K({argsMap:(e,t)=>(Array.isArray(t)||(t=[t]),[JSON.stringify(t)])}),hr=K(),_r=K(),pr=K(),Er=K(),Sr=K(),mr=K(),Rr=K({reportResult:!0}),fr=K(),li((Cr=class extends ie{get connectionState(){return this._gateway.state}get remoteUsers(){return this._users}get localTracks(){return this._p2pChannel.getAllTracks(!0)}get uid(){return this._uid}get channelName(){return this._channelName}get localDataChannels(){return this._p2pChannel.getAllDataChannels()}get mode(){return this._config.mode}get role(){var e;return(null===(e=this._config)||void 0===e?void 0:e.role)||"audience"}get codec(){return this._config.codec}get audioCodec(){return this._config.audioCodec||"opus"}get isStringUID(){return!!this._joinInfo&&!!this._joinInfo.stringUid}get __className__(){return"Client"}constructor(e,t){let i;if(super(),this.store=void 0,this._uid=void 0,this._channelName=void 0,this._uintUid=void 0,this._users=[],this._config=void 0,this._clientId=void 0,this._appId=void 0,this._sessionId=null,this._key=void 0,this._rtmConfig={},this._joinInfo=void 0,this._gateway=void 0,this._statsCollector=void 0,this._configDistribute=void 0,this._leaveMutex=void 0,this._publishMutex=void 0,this._renewTokenMutex=void 0,this._subscribeMutex=void 0,this._encryptionMode="none",this._encryptionSecret=null,this._encryptionSalt=null,this._encryptDataStream=!1,this._encryptDataStreamKey=null,this._encryptDataStreamIv=null,this._proxyServer=void 0,this._turnServer={servers:[],mode:"auto"},this._cloudProxyServerMode="disabled",this._isDualStreamEnabled=!1,this._defaultStreamFallbackType=void 0,this._lowStreamParameter=void 0,this._streamFallbackTypeCacheMap=new Map,this._remoteStreamTypeCacheMap=new Map,this._axiosCancelSource=Zt.CancelToken.source(),this._audioVolumeIndicationInterval=void 0,this._networkQualityInterval=void 0,this._userOfflineTimeout=void 0,this._streamRemovedTimeout=void 0,this._liveTranscodeStreamingClient=void 0,this._liveRawStreamingClient=void 0,this._channelMediaRelayClient=void 0,this._networkQualitySensitivity="normal",this._p2pChannel=void 0,this._useLocalAccessPoint=!1,this._setLocalAPVersion=void 0,this._joinAndNotLeaveYet=!1,this._numberOfJoinCount=0,this._joinResponse=null,this._remoteDefaultVideoStreamType=void 0,this._inspect=void 0,this._moderation=void 0,this._license=void 0,this._pendingPublishedUsers=[],this.ntpAlignErrorCount=0,this.remoteInboundOffset=0,this._peerConnectionState=void 0,this._handleLocalTrackEnable=(e,t,i)=>{this.publish(e,!1).then(t).catch(i)},this._handleLocalTrackDisable=(e,t,i)=>{this.unpublish(e).then(t).catch(i)},this._handleUserOnline=e=>{if(ne("BLOCK_LOCAL_CLIENT")&&ri(e.uid,this.channelName))return void B.debug("[".concat(e.uid,"] will be ignored in local"));this.isStringUID&&"string"!=typeof e.uid&&B.error("[".concat(this._clientId,"] StringUID is Mixed with UintUID"));const t=this._users.find((t=>t.uid===e.uid));if(t)t._trust_in_room_=!0,t._is_pre_created&&(t._is_pre_created=!1,this.safeEmit(pt.USER_JOINED,t));else{const t=new aa(e.uid,e.uint_id||e.uid);this._users.push(t),B.debug("[".concat(this._clientId,"] user online"),e.uid),this.store.firstVideoFrameDecoded(t.uid,{userJoinNotify:Date.now()}),this.safeEmit(pt.USER_JOINED,t)}},this._handleUserOffline=e=>{if(ne("BLOCK_LOCAL_CLIENT")&&ri(e.uid,this.channelName))return;const t=this._users.find((t=>t.uid===e.uid));t&&(this._handleRemoveStream(e),this._handleRemoveDataChannels(e),t._audio_pre_subscribed||t._video_pre_subscribed?t._is_pre_created=!0:At(this._users,t),this._remoteStreamTypeCacheMap.delete(t.uid),this._streamFallbackTypeCacheMap.delete(t.uid),B.debug("[".concat(this._clientId,"] user offline"),e.uid,"reason:",e.reason),this.safeEmit(pt.USER_LEAVED,t,e.reason))},this._handleAddAudioOrVideoStream=(e,t,i,n,o,a,s,r)=>{if(ne("BLOCK_LOCAL_CLIENT")&&ri(t,this.channelName))return;const c=this._users.find((e=>e.uid===t));if(!c)return void B.error("[".concat(this._clientId,"] can not find target user!(on_add_stream)"));B.debug("[".concat(this._clientId,"] stream added with uid ").concat(t,", type ").concat(e)),this.store.subscribe(c.uid,e,void 0,void 0,void 0,Date.now()),"video"===e&&this.store.firstVideoFrameDecoded(c.uid,{videoAddNotify:Date.now()});const d="audio"===e?c.hasAudio:c.hasVideo;if(c._uintid||(c._uintid=a||t),"audio"===e?c._trust_audio_stream_added_state_=!0:c._trust_video_stream_added_state_=!0,"audio"===e?(c._audio_added_=!0,void 0!==i&&(c._audioSSRC=i),void 0!==n&&(c._cname=n),s&&(c._audioOrtc=s)):(c._video_added_=!0,void 0!==i&&(c._videoSSRC=i),void 0!==n&&(c._cname=n),void 0!==r&&(c._rtxSsrcId=r),s&&(c._videoOrtc=s)),("audio"===e?c.hasAudio:c.hasVideo)&&!d&&(B.info("[".concat(this._clientId,"] remote user ").concat(c.uid," published ").concat(e)),this.safeEmit(pt.USER_PUBLISHED,c,e)),"video"===e?j.onGatewayStream(this._sessionId,W.ON_ADD_VIDEO_STREAM,H.ON_ADD_VIDEO_STREAM,{peer:a||t,ssrc:c._videoSSRC}):j.onGatewayStream(this._sessionId,W.ON_ADD_AUDIO_STREAM,H.ON_ADD_AUDIO_STREAM,{peer:a||t,ssrc:c._audioSSRC}),this._p2pChannel.remoteMediaSsrcChanged(c,e,i).then((t=>{if(t&&(B.debug("[".concat(this._clientId,"] resubscribe ").concat(e," for user ").concat(c.uid," after rejoin because SSRC id changed.")),this._p2pChannel instanceof za))return this._p2pChannel.unsubscribe(c,e,!0).then((()=>this._subscribe(c,e,!0).catch((e=>{B.error("[".concat(this._clientId,"] resubscribe error"),e.toString())}))))})),this._p2pChannel.hasPendingRemoteMedia(c,e)&&(B.debug("[".concat(this._clientId,"] resubscribe ").concat(e," for user ").concat(c.uid," after reconnect.")),this._subscribe(c,e,!0).catch((e=>{B.error("[".concat(this._clientId,"] resubscribe error"),e.toString())}))),"video"===e&&!Je()&&!gt()){const e=this._getEncodingName(o);(null==e?void 0:e.toLocaleLowerCase())==et.av1&&Wo().then((t=>{t||this._gateway.downgradeCodec(e)}))}},this._handleRemoveStream=e=>{if(ne("BLOCK_LOCAL_CLIENT")&&ri(e.uid,this.channelName))return;const t=this._users.find((t=>t.uid===e.uid));if(!t)return void B.warning("[".concat(this._clientId,"] can not find target user!(on_remove_stream)"));B.debug("[".concat(this._clientId,"] stream removed with uid ").concat(e.uid));let i=()=>{};t.hasAudio&&t.hasVideo?i=()=>{B.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished audio track")),this.safeEmit(pt.USER_UNPUBLISHED,t,"audio"),B.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished video track")),this.safeEmit(pt.USER_UNPUBLISHED,t,"video")}:t.hasVideo?i=()=>{B.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished video track")),this.safeEmit(pt.USER_UNPUBLISHED,t,"video")}:t.hasAudio&&(i=()=>{B.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished audio track")),this.safeEmit(pt.USER_UNPUBLISHED,t,"audio")}),t._video_pre_subscribed||t._audio_pre_subscribed||(t._trust_audio_stream_added_state_=!0,t._trust_video_stream_added_state_=!0,t._audio_added_=!1,t._video_added_=!1,this._p2pChannel instanceof za&&this._p2pChannel.unsubscribe(t).then((e=>{if(e)return this._gateway.unsubscribe(e,t.uid)})),t._audioSSRC=void 0,t._videoSSRC=void 0,t._audioOrtc=void 0,t._videoOrtc=void 0,t._rtxSsrcId=void 0),j.onGatewayStream(this._sessionId,W.ON_REMOVE_STREAM,H.ON_REMOVE_STREAM,{peer:e.uint_id||e.uid}),i()},this._handleSetStreamLocalEnable=(e,t,i)=>{if(ne("BLOCK_LOCAL_CLIENT")&&ri(t,this.channelName))return;const n=this._users.find((e=>e.uid===t));if(!n)return void B.error("[".concat(this._clientId,"] can not find target user!(disable_local)"));B.debug("[".concat(this._clientId,"] local ").concat(e," ").concat(i?"enabled":"disabled"," with uid ").concat(t));const o="audio"===e?n.hasAudio:n.hasVideo;if("audio"===e){n._trust_audio_enabled_state_=!0;const e=n._audio_enabled_;if(n._audio_enabled_=i,n._audio_enabled_===e)return;{const e=n._audio_enabled_?"enable-local-audio":"disable-local-audio";B.debug("[".concat(this._clientId,"] user-info-updated, uid: ").concat(t,", msg: ").concat(e)),this.safeEmit(pt.USER_INFO_UPDATED,t,e)}}else{n._trust_video_enabled_state_=!0;const e=n._video_enabled_;if(n._video_enabled_=i,n._video_enabled_===e)return;{const e=n._video_enabled_?"enable-local-video":"disable-local-video";B.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(t,", msg: ").concat(e)),this.safeEmit(pt.USER_INFO_UPDATED,t,e)}}const a="audio"===e?n.hasAudio:n.hasVideo;return o!==a?!o&&a?(B.info("[".concat(this._clientId,"] remote user ").concat(t," published ").concat(e)),void this.safeEmit(pt.USER_PUBLISHED,n,e)):("video"===e&&n._videoTrack&&n._videoTrack._destroy(),"audio"===e&&n._audioTrack,this._p2pChannel.muteRemote(n,e),B.info("[".concat(this._clientId,"] remote user ").concat(t," unpublished ").concat(e)),void this.safeEmit(pt.USER_UNPUBLISHED,n,e)):void 0},this._handleMuteStream=(e,t,i)=>{if(ne("BLOCK_LOCAL_CLIENT")&&ri(e,this.channelName))return;B.debug("[".concat(this._clientId,"] receive mute message"),e,t,i);const n=this._users.find((t=>t.uid===e));if(!n)return void B.warning("[".concat(this._clientId,"] can not find remote user, ignore mute event, uid: ").concat(e));const o="audio"===t?n.hasAudio:n.hasVideo;if("audio"===t){n._trust_audio_mute_state_=!0;const t=n._audio_muted_;if(n._audio_muted_=i,n._audio_muted_===t)return;{const t=n._audio_muted_?"mute-audio":"unmute-audio";B.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(e,", msg: ").concat(t)),this.safeEmit(pt.USER_INFO_UPDATED,e,t)}}else{n._trust_video_mute_state_=!0;const t=n._video_muted_;if(n._video_muted_=i,n._video_muted_===t)return;{const t=n._video_muted_?"mute-video":"unmute-video";B.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(e,", msg: ").concat(t)),this.safeEmit(pt.USER_INFO_UPDATED,e,t)}}const a="audio"===t?n.hasAudio:n.hasVideo;if(o!==a){if(!o&&a){return("audio"===t?n._audioSSRC:n._videoSSRC)?(B.info("[".concat(this._clientId,"] remote user ").concat(e," published ").concat(t)),void this.safeEmit(pt.USER_PUBLISHED,n,t)):void B.warning("[".concat(this._clientId,"] remote user ").concat(e," receive ").concat(t," unmute message before add stream message, ").concat(t," SSRC doesn't exist yet."))}"video"===t&&n._videoTrack&&!n._video_pre_subscribed&&n._videoTrack._destroy(),"audio"===t&&n._audioTrack,this._p2pChannel.muteRemote(n,t),B.info("[".concat(this._clientId,"] remote user ").concat(e," unpublished ").concat(t)),this.safeEmit(pt.USER_UNPUBLISHED,n,t)}},this._handleP2PLost=async e=>{B.debug("[".concat(this._clientId,"] receive p2p lost"),e),parseInt(e.p2pid,10)===this.store.p2pId?await this._p2pChannel.requestReconnect():B.warning("[".concat(this._clientId,"] P2PLost stream not found"),e)},this._handleTokenWillExpire=()=>{B.debug("[".concat(this._clientId,"] received message onTokenPrivilegeWillExpire")),this.safeEmit(pt.ON_TOKEN_PRIVILEGE_WILL_EXPIRE)},this._handleBeforeUnload=e=>{"beforeunload"===e.type&&void 0!==e.returnValue&&""!==e.returnValue||(this.leave(),B.info("[".concat(this._clientId,"] auto leave onbeforeunload or pagehide")))},this._handleUpdateNetworkQuality=()=>{if("normal"===this._networkQualitySensitivity)return;if(navigator&&void 0!==navigator.onLine&&!navigator.onLine)return void this.safeEmit(pt.NETWORK_QUALITY,{downlinkNetworkQuality:6,uplinkNetworkQuality:6});const e={downlinkNetworkQuality:0,uplinkNetworkQuality:0};e.uplinkNetworkQuality=this._p2pChannel.getUplinkNetworkQuality(),e.downlinkNetworkQuality=this._p2pChannel.getDownlinkNetworkQuality(),this.safeEmit(pt.NETWORK_QUALITY,e)},this._handleP2PAddAudioOrVideoStream=(e,t,i,n)=>{const o=this._users.find((e=>e.uid===t));if(!o)return void B.error("[".concat(this._clientId,"] can not find target user!(on_add_stream)"));B.debug("[".concat(this._clientId,"] stream added with uid ").concat(t,", type ").concat(e)),this.store.subscribe(o.uid,e,void 0,void 0,void 0,Date.now());const a="audio"===e?o.hasAudio:o.hasVideo;"audio"===e?o._trust_audio_stream_added_state_=!0:o._trust_video_stream_added_state_=!0,"audio"===e?(o._audio_added_=!0,void 0!==i&&(o._audioSSRC=i),void 0!==n&&(o._audioMid=n)):(o._video_added_=!0,void 0!==i&&(o._videoSSRC=i),void 0!==n&&(o._videoMid=n)),("audio"===e?o.hasAudio:o.hasVideo)&&!a&&(B.info("[".concat(this._clientId,"] remote user ").concat(o.uid," published ").concat(e)),this.safeEmit(pt.USER_PUBLISHED,o,e)),this._p2pChannel.hasPendingRemoteMedia(o,e)&&(B.debug("[".concat(this._clientId,"] resubscribe ").concat(e," for user ").concat(o.uid," after reconnect.")),this._subscribe(o,e,!0).catch((e=>{B.error("[".concat(this._clientId,"] resubscribe error"),e.toString())})))},this._config=e,this._clientId=t||fe(5,"client-"),this.store=new vt(e.codec,e.audioCodec,e.mode,this._clientId),this._leaveMutex=new re("client-leave",this._clientId),this._publishMutex=new re("client-publish",this._clientId),this._renewTokenMutex=new re("client-renewtoken",this._clientId),this._subscribeMutex=new re("client-subscribe",this._clientId),this.store.clientCreated(),e.proxyServer&&this.setProxyServer(e.proxyServer,!0),e.turnServer&&this.setTurnServer(e.turnServer,!0),B.info("[".concat(this._clientId,"] Initializing AgoraRTC client v").concat(xe," build: ").concat(yt,", mode: ").concat(this.mode,", codec: ").concat(this.codec)),e.clientRoleOptions)try{Nt(e.clientRoleOptions),i=Object.assign({},e.clientRoleOptions)}catch(e){B.warning("[".concat(this._clientId,"] ").concat(e.toString()))}var o;this._statsCollector=new ia(this.store),this._statsCollector.onStatsException=(e,t,i)=>{B.warn("[".concat(this._clientId,"] receive exception msg, code: ").concat(e,", msg: ").concat(t,", uid: ").concat(i)),e===ea.VIDEO_ENCODE_FAILED&&this.localTracks.forEach((e=>{e instanceof S&&ne("ENABLE_ENCODE_EXCEPTION")&&e.findClosestProfile()})),this.safeEmit(pt.EXCEPTION,{code:e,msg:t,uid:i})},this._statsCollector.onUploadPublishDuration=(e,t,i,n)=>{const o=this._users.find((t=>t.uid===e));if(o){this.store.keyMetrics&&(this.store.firstVideoFrameDecoded(o._uintid,{peerPublishDuration:i,peerPubStatusMs:Date.now()}),this._p2pChannel.reportVideoFirstFrameRender(o)),j.peerPublishStatus(this._sessionId,{subscribeElapse:n,audioPublishDuration:t,videoPublishDuration:i,peer:o._uintid})}},this._statsCollector.onVideoCodecChanged=e=>{if(ne("VIDEO_STANDARD_BITRATE_VERSION")&&("av1"===e||"h265"===e||"h264"===e)){const t=this.localTracks.find((e=>e instanceof n));t&&1!==t._saveEncodeBitrateRatio&&t.setSaveEncodeBitrateRatio("h264"===e?ne("BASELINE_MORE_H264_BITRATE_RATIO"):void 0)}},this.store.useP2P="p2p"===e.mode,this._gateway=new Ro(this.store,{clientId:this._clientId,mode:this.mode,codec:this.codec,websocketRetryConfig:e.websocketRetryConfig||Ye,httpRetryConfig:e.httpRetryConfig||Ye,forceWaitGatewayResponse:void 0===e.forceWaitGatewayResponse||e.forceWaitGatewayResponse,statsCollector:this._statsCollector,role:e.role,clientRoleOptions:i}),this._configDistribute=new Zo(this._clientId,this.store),this.store.useP2P?(this._p2pChannel=(o={store:this.store,statsCollector:this._statsCollector},po("P2PChannel").create(o)),this._handleP2PEvents()):this._p2pChannel=new za(this.store,this._statsCollector),this._handleP2PChannelEvents(),this._handleGatewayEvents(),this._handleGatewaySignalEvents()}async joinMeta(e,t,i,n,o){let a=!(arguments.length>5&&void 0!==arguments[5])||arguments[5],s=arguments.length>6&&void 0!==arguments[6]&&arguments[6];Fe("JOIN_GATEWAY_USE_443PORT_ONLY",a),Fe("JOIN_GATEWAY_USE_DUAL_DOMAIN",s);const r=this._gateway.signal.websocket;return r instanceof yn&&(r.use443PortOnly=a,r.tryDoubleDomain=s),bt("client.join",ne("JOIN_MAX_CONCURRENCY"),this.join.bind(this),e,t,i,n,o)}async join(e,t,i,n,a){const s=++this._numberOfJoinCount;this.store.joinStart(),n&&(this.store.uid=n);const r=wt(),c=Ot()?window.isSecureContext:"Browser Not Support";if(!Ot()&&!r||!window.isSecureContext){const e="The website must be running in a secure context (About secure context: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts ), otherwise the media collection will be restricted by the browser";B.warning(e)}let d;j.setAppId(e);try{if(!i&&null!==i)throw new F(Z.INVALID_PARAMS,"Invalid token: ".concat(i,". If you don not use token, set it to null"));if(i&&ee(i,"token",1,2047),ee(e,"appid",1,2047),Pi(t),n&&Li(n),a)if("string"==typeof a)ee(a,"optionalInfo",1,256),d=a;else{if("object"!=typeof a)throw new F(Z.INVALID_PARAMS,"Invalid options: options is not a string or object");{const{autoSubscribe:e,enableInstantMuteRestore:t}=a;e&&(Dt(e,"autoSubscribe"),B.info("[".concat(this._clientId,"] join: autoSubscribe: ").concat(e)),this.store.autoSubscribe=e),t&&(Dt(t,"enableInstantMuteRestore"),B.info("[".concat(this._clientId,"] join: enableInstantMuteRestore: ").concat(t)),this.store.enableInstantMuteRestore=t)}}}catch(o){throw j.reportApiInvoke(mt(),{name:We.JOIN,options:[e,t,i,n],states:{isHttps:r,isSecureContext:c},tag:He.TRACER}).onError(o),o}if(this._leaveMutex.isLocked){B.debug("[".concat(this._clientId,"] join: waiting leave operation"));(await this._leaveMutex.lock())(),B.debug("[".concat(this._clientId,"] join: continue"))}if(this._joinAndNotLeaveYet=!0,"DISCONNECTED"!==this.connectionState){const o=new F(Z.INVALID_OPERATION,"[".concat(this._clientId,"] Client already in connecting/connected state"));throw j.reportApiInvoke(mt(),{name:We.JOIN,options:[e,t,i,n],states:{isHttps:r,isSecureContext:c},tag:He.TRACER}).onError(o),o}this._gateway.state="CONNECTING",this.store.preloadStart();const l=await Ts({appId:e,cname:t,uid:n,stringUid:"string"==typeof n?n:void 0,token:i||e,cloudProxyServer:this._cloudProxyServerMode});if(this.store.preloadEnd(),!this._joinAndNotLeaveYet)throw new F(Z.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));const u=(null==l?void 0:l.sid)||mt();B.info("[".concat(this._clientId,"] start join channel ").concat(t,", join number: ").concat(s)),this._sessionId||(this._sessionId=u,this.store.sessionId=this._sessionId);const h=j.reportApiInvoke(u,{id:this._clientId,name:We.JOIN,options:[e,t,i,n],states:{isHttps:r,isSecureContext:c},tag:He.TRACER}),_=mi(mi(mi({},this._rtmConfig),{},{role:this.role,clientId:this._clientId,appId:e,sid:this._sessionId,cname:t,uid:"string"!=typeof n?n:null,turnServer:this._turnServer,proxyServer:this._proxyServer,token:i||e,cloudProxyServer:this._cloudProxyServerMode,optionalInfo:d,license:this._license,useLocalAccessPoint:this._useLocalAccessPoint,preload:!!l},void 0!==this._remoteDefaultVideoStreamType&&{defaultVideoStream:this._remoteDefaultVideoStreamType}),{},{apRequestDetail:ne("AP_REQUEST_DETAIL")||void 0});if(this._useLocalAccessPoint&&(_.setLocalAPVersion=this._setLocalAPVersion),"string"==typeof n&&(_.stringUid=n,this._uintUid?(_.uid=this._uintUid,this._uintUid=void 0):_.uid=0),"none"!==this._encryptionMode&&this._encryptionSecret){if(_.aesmode=this._encryptionMode,_.aespassword=await Pt(this._encryptionSecret),!this._joinAndNotLeaveYet)throw new F(Z.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));this._encryptionSalt&&(_.aessalt=this._encryptionSalt)}if(this._encryptDataStream&&("aes-128-gcm2"===this._encryptionMode||"aes-256-gcm2"===this._encryptionMode))if(this._encryptionSalt&&this._encryptionSecret)if(window.crypto.subtle){const e=new TextEncoder,t=ne("USE_PURE_ENCRYPTION_MASTER_KEY")?e.encode(_.appId+this._encryptionSecret+this._encryptionSecret):e.encode(_.appId+_.cname+this._encryptionSecret);this._encryptDataStreamIv=await Lt(this._encryptionMode,t,Ct(this._encryptionSalt)),this._encryptDataStreamKey=await kt(this._encryptionMode,t,Ct(this._encryptionSalt))}else c?B.warning("[".concat(this._clientId,"] encrypt datastream must be running in a secure context, fallback to plain data stream")):B.warning("[".concat(this._clientId,"] current browser do not support WebCrypto ,fallback to plain data stream")),this._encryptDataStream=!1;else this._encryptDataStream=!1,B.debug("[".concat(this._clientId,"] no salt / secret, cannot support encrypt data stream, fallback to plain data stream"));this._startSession(this._sessionId,{channel:t,appId:e,stringUid:_.stringUid});const p=this._sessionId;setTimeout((()=>{"CONNECTING"===this.connectionState&&p===this._sessionId&&j.joinChannelTimeout(this._sessionId,5)}),5e3);try{let n;const a=_.cloudProxyServer;if(["proxy3","proxy4","proxy5"].includes(a)){const e=ne("PROXY_SERVER_TYPE3");Array.isArray(e)?_.proxyServer=e[0]:_.proxyServer=e}if(j.setProxyServer(_.proxyServer),B.setProxyServer(_.proxyServer),this.store.requestAPStart(),l){if(B.debug("[".concat(this._clientId,"] get serverInfo Success from Preload Cache ").concat(_.stringUid?", ".concat(_.stringUid," => ").concat(l.intUid):""," ")),_.stringUid&&!_.uid&&(_.uid=l.intUid),n={gatewayInfo:l.ap.gatewayInfo},ne("JOIN_WITH_FALLBACK_MEDIA_PROXY")&&"auto"===_.turnServer.mode)if(0===l.ap.proxyInfo.addresses.length)B.warning("no edge services in ap response of proxy fallback, will not set proxy in iceServers");else{const e=(await Vn(l.ap.proxyInfo,l.ap.gatewayInfo.uid)).map((e=>({turnServerURL:e.address,tcpport:e.tcpport||Te.tcpport,udpport:e.udpport||Te.udpport,username:e.username||Te.username,password:e.password||Te.password,forceturn:!1,security:!0})));_.turnServer={mode:"manual",servers:e}}vs(l,_.stringUid)}else{if(_.stringUid&&!_.uid){let e;[e,n]=await Promise.all([Yo(_.stringUid,_,this._axiosCancelSource.token,this._config.httpRetryConfig||Ye,this.store).finally((()=>{this.store.requestSUAEnd()})),Ko(_,this._axiosCancelSource.token,this._config.httpRetryConfig||Ye,!0,this.store).finally((()=>{this.store.requestAPEnd()}))]),B.debug("[".concat(this._clientId,"] getUserAccount Success ").concat(_.stringUid," => ").concat(e)),_.uid=e,n.gatewayInfo.uid=e,n.gatewayInfo.res.uid=e}else n=await Ko(_,this._axiosCancelSource.token,this._config.httpRetryConfig||Ye,!0,this.store);if(!this._joinAndNotLeaveYet)throw new F(Z.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"))}this.store.requestAPEnd(),setTimeout((()=>{this._configDistribute.startGetConfigDistribute(_,this._axiosCancelSource.token),this._configDistribute.on(Xi.UPDATE_BITRATE_LIMIT,(e=>{this._p2pChannel.updateBitrateLimit(e)})),this._configDistribute.on(Xi.UPDATE_CLIENT_ROLE_OPTIONS,(e=>{this._setClientRoleOptions(e)}))}),0),this._key=i||e;const s=n.gatewayInfo,r=_.uid?_.uid:s.uid;this._joinInfo=mi(mi({},_),{},{cid:s.cid,uid:r,vid:s.vid,apResponse:s.res,apGatewayAddress:s.apGatewayAddress,uni_lbs_ip:s.uni_lbs_ip,gatewayAddrs:s.gatewayAddrs}),this.store.intUid=r,this.store.cid=s.cid;const c=await this._joinGateway();if(!this._joinAndNotLeaveYet)throw new F(Z.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));h.onSuccess(c),this._appId=e,this._channelName=_.cname,this._uid=c,this.store.uid=c,setTimeout((()=>{this._networkQualityInterval&&window.clearInterval(this._networkQualityInterval),this._networkQualityInterval=window.setInterval(this._handleUpdateNetworkQuality,2e3),window.addEventListener(Je()?"beforeunload":"pagehide",this._handleBeforeUnload),this._statsCollector.startUpdateStats()}),0);const d=_.stringUid?"string uid: ".concat(_.stringUid,",uid: ").concat(_.uid):"uid: ".concat(this._uid);return B.info("[".concat(this._clientId,"] Joining channel success: channel: ").concat(t,",").concat(d)),setTimeout((()=>{B.startUpload()}),5e3),this.store.joinEnd(),E=this,ai.includes(E)||ai.push(E),"disabled"===this._cloudProxyServerMode&&o().supportWebCrypto&&ne("ENABLE_PRELOAD")&&As(this._joinInfo),c}catch(e){const t=Array.isArray(e)?e[0]:e;throw t&&t.code===Z.OPERATION_ABORTED?B.warning("[".concat(this._clientId,"] join number: ").concat(s,", Joining channel failed, rollback"),t):B.error("[".concat(this._clientId,"] join number: ").concat(s,", Joining channel failed, rollback"),t),t.code!==Z.OPERATION_ABORTED&&this._numberOfJoinCount===s&&(this._gateway.state="DISCONNECTED",this._reset()),h.onError(t),t}var E}_joinGateway(){if(!this._joinInfo||!this._key)throw new F(Z.INVALID_OPERATION);return this._gateway.join(this._joinInfo,this._key,!("disabled"!==this._joinInfo.cloudProxyServer||this._joinInfo.proxyServer||!ne("JOIN_WITH_FALLBACK_SIGNAL_PROXY")))}async leave(){B.info("[".concat(this._clientId,"] Leaving channel")),window.removeEventListener(Je()?"beforeunload":"pagehide",this._handleBeforeUnload),this._reset(),function(e){const t=ai.indexOf(e);-1!==t&&ai.splice(t,1)}(this),this._statsCollector.stopUpdateStats();const e=await this._leaveMutex.lock();if("DISCONNECTED"===this.connectionState)return B.info("[".concat(this._clientId,"] Leaving channel repeated, success")),void e();await this._gateway.leave("CONNECTED"!==this.connectionState,me.LEAVE),B.info("[".concat(this._clientId,"] Leaving channel success")),this._joinAndNotLeaveYet=!1,this.store.resetJoinChannelServiceRecords(),e()}async publish(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!Array.isArray(e)){if(!(e instanceof O))return this._publishDataChannel(e);e=[e]}if(0===e.length)throw new F(Z.INVALID_PARAMS,"param list is empty");const i=e;if("audience"===this._gateway.role)throw new F(Z.INVALID_OPERATION,"audience can not publish stream");for(const e of i){if(!(e instanceof O))throw new F(Z.INVALID_PARAMS,"parameter is not local track");if(!e._enabled&&t)throw new F(Z.TRACK_IS_DISABLED,"can not publish a disabled track: ".concat(e.getTrackId()))}B.info("[".concat(this._clientId,"] Publishing tracks, id ").concat(i.map((e=>"".concat(e.getTrackId()," ")))));const o=await this._publishMutex.lock();await this._configDistribute.awaitConfigDistributeComplete(),t&&i.forEach((e=>{const t=this._configDistribute.getBitrateLimit();e instanceof n&&t&&e.setBitrateLimit(t.uplink)}));try{await this._publishHighStream(i),B.info("[".concat(this._clientId,"] Publish success, id ").concat(i.map((e=>"".concat(e.getTrackId()," ")))))}catch(e){throw B.error("[".concat(this._clientId,"] publish error"),e.toString()),e}finally{o()}}async _publishDataChannel(e){if(null==e)throw new F(Z.INVALID_PARAMS,"parameter is not local track or datachannel config, config is ".concat(JSON.stringify(e)));It(e.id,"id",0,65535,!0),Dt(e.ordered,"ordered"),ee(e.metadata,"metadata",0,512),B.info("[".concat(this._clientId,"] Publishing datachannels, id ").concat(e.id));const t=await this._publishMutex.lock();try{if(-1!==this._p2pChannel.getAllDataChannels().findIndex((t=>t.id===e.id)))throw new F(Z.INVALID_PARAMS,"Invalid id: ".concat(e.id,". If you want to republish the datachannel, unpublish first"));if(!this._joinInfo||void 0===this._uid)throw new F(Z.INVALID_OPERATION,"Can't publish datachannel, haven't joined yet!");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new F(Z.INVALID_OPERATION,"can not publish datachannel in ".concat(this.connectionState," state"));if("auto"===this._turnServer.mode&&ne("FORCE_TURN")&&!ne("TURN_ENABLE_TCP")&&!ne("TURN_ENABLE_UDP"))throw new F(Z.UNEXPECTED_ERROR,"force TURN With No TURN Configuration");const i=function(e){return Eo(e,!1)}(e),n=await this._p2pChannel.publishDataChannel([i]);if(n.length>0){if("number"!=typeof i._originDataChannelId)throw B.error("[".concat(this._clientId,"] can not publish with mediaType datachannel, cannot get RTCDatachannel id")),new F(Z.CREATE_DATACHANNEL_ERROR);try{await Promise.all(n.map((e=>this._uid&&this._gateway.publishDataChannel(this._uid,e,!0)))),await i._waitTillOpen()}catch(e){if(e.code!==Z.DISCONNECT_P2P)throw e}}return B.info("[".concat(this._clientId,"] Publish dataChannels success, id ").concat(i.id)),i}catch(e){throw B.error("[".concat(this._clientId,"] publish datachannels error"),e.toString()),e}finally{t()}}async unpublish(e){if(!this._joinInfo||void 0===this._uid)throw new F(Z.INVALID_OPERATION,"Can't unpublish stream, haven't joined yet!");let t=[];if(e)if(Array.isArray(e))t=e;else{if(!(e instanceof O))return this._unpublishDataChannel([e]);t=[e]}else this.store.useP2P||await this._unpublishDataChannel(),t=this._p2pChannel.getAllTracks(!0);B.info("[".concat(this._clientId,"] Unpublish tracks, tracks ").concat(t.map((e=>"".concat(e.getTrackId()," ")))," "));const i=await this._publishMutex.lock();try{if(this.store.useP2P){const e=await this._p2pChannel.unpublish(t);e&&await this._gateway.sendExtensionMessage(hn.UNPUBLISH,{unpubMsg:e},!0)}else{const e=await this._p2pChannel.unpublish(t);e&&await this._gateway.unpublish(e,this._uid),B.info("[".concat(this._clientId,"] Unpublish success,tracks ").concat(t.map((e=>"".concat(e.getTrackId())))))}}catch(e){throw B.error("[".concat(this._clientId,"] unpublish error"),e.toString()),e}finally{i&&i()}}async _unpublishDataChannel(e){void 0!==e&&0!==e.length||(e=this._p2pChannel.getAllDataChannels()),B.info("[".concat(this._clientId,"] Unpublish datachannels, datachannels ").concat(e.map((e=>"".concat(e.id," ")))," "));const t=await this._publishMutex.lock();try{const i=await this._p2pChannel.unpublishDataChannel(e);i&&await this._gateway.unpublishDataChannel(i),B.info("[".concat(this._clientId,"] Unpublish dataChannel success,dataChannel ").concat(e.map((e=>"".concat(e.id)))))}catch(e){throw B.error("[".concat(this._clientId,"] unpublish dataChannel error"),e.toString()),e}finally{t&&t()}}async subscribe(e,t,i){if(!(e instanceof aa)){const t=this.remoteUsers.find((t=>t.uid===e));if(!t)throw new F(Z.INVALID_REMOTE_USER,"user is not in the channel");e=t}return"datachannel"===t?this._subscribeDataChannel(e,i):this._subscribe(e,t)}async presubscribe(e,t){if(Ut(t,"mediaType",["audio","video"]),this.store.useP2P)throw new F(Z.INVALID_OPERATION,"can't presub at p2p mode");if(!this._joinInfo)throw new F(Z.INVALID_OPERATION,"can't presub when not join");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new F(Z.INVALID_OPERATION,"can't presub in ".concat(this.connectionState," state"));const i=t===Zi.AUDIO,n=t===Zi.VIDEO,o=await this._subscribeMutex.lock();try{const{ssrcId:a,ortc:s,rtxSsrcId:r,cname:c,uint_id:d}=await this._gateway.presubscribe(e,t,!0);if(null==a)throw new F(Z.UNEXPECTED_RESPONSE,"no ssrc id");let l=this._users.find((t=>t.uid===e));l||(l=new aa(e,d||e),l._is_pre_created=!0,this._users.push(l)),c&&(l._cname=c),l._uintid||(l._uintid=d||e),i&&(l._audioSSRC=a,l._audio_pre_subscribed=!0,s&&(l._audioOrtc=s)),n&&(l._videoSSRC=a,l._video_pre_subscribed=!0,s&&(l._videoOrtc=s),null!=r&&(l._rtxSsrcId=r)),B.info("[".concat(this._clientId,"] presub succeed ssrc: ").concat(a)),await this._p2pChannel.subscribe(l,t,a,r,s);const u=i?l._audioTrack:l._videoTrack;if(!u)throw new F(Z.UNEXPECTED_ERROR,"can not find remote track in user");return i&&(l._trust_audio_stream_added_state_=!0,l._audio_added_=!0),n&&(l._trust_video_stream_added_state_=!0,l._video_added_=!0),u}catch(t){throw B.error("[".concat(this._clientId,"] presub user ").concat(e," error"),t),t}finally{o()}}async _subscribeDataChannel(e,t){var i;if(It(t,"channelId",0,65535,!0),!this._joinInfo)throw new F(Z.INVALID_OPERATION,"Can't subscribe datachannel, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new F(Z.INVALID_OPERATION,"Can't subscribe datachannel in ".concat(this.connectionState," state"));if(!this._users.find((t=>t===e)))throw B.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", this user is not in the channel")),new F(Z.INVALID_REMOTE_USER,"user is not in the channel");if(!e.hasAudio&&!e.hasVideo&&0===e._dataChannels.length)throw B.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", user is not published")),new F(Z.INVALID_REMOTE_USER,"user is not published");const n=null===(i=e._dataChannels)||void 0===i?void 0:i.find((e=>e.id===t));if(!n)throw B.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid," with mediaType datachannel, remote datachannel is not published")),new F(Z.REMOTE_USER_IS_NOT_PUBLISHED);const o=await this._subscribeMutex.lock();B.info("[".concat(this._clientId,"] subscribe user ").concat(e.uid,", mediaType: datachannel"));try{const t=await this._p2pChannel.subscribeDataChannel(e,[n]);if(t&&t.includes(n.id))try{var a;if("number"!=typeof n._originDataChannelId)throw B.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid," with mediaType datachannel, cannot get RTCDatachannel")),new F(Z.CREATE_DATACHANNEL_ERROR);const t={id:n.id,datachannelId:n._originDataChannelId,ordered:n.ordered,maxRetransmits:n.maxRetransmits,metadata:null!==(a=n.metadata)&&void 0!==a?a:""};await this._gateway.subscribeDataChannel(e.uid,t,!0),await n._waitTillOpen()}catch(t){if((null==t?void 0:t.code)!==Z.WS_ABORT)throw await this._p2pChannel.unsubscribeDataChannel(e,[n]),t;await this._p2pChannel.unsubscribeDataChannel(e,[n]),this._p2pChannel.setPendingRemoteDataChannel(e,n.id)}return B.info("[".concat(this._clientId,"] subscribe success user ").concat(e.uid,", mediaType: datachannel")),n}finally{o()}}async _p2pSubscribe(e,t,i){if(Ut(t,"mediaType",["audio","video"]),!this._joinInfo)throw new F(Z.INVALID_OPERATION,"Can't subscribe stream, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new F(Z.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));if(!this._users.find((t=>t===e))){const t=new F(Z.INVALID_REMOTE_USER,"user is not in the channel");throw B.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", this user is not in the channel")),t}if(!e.hasAudio&&!e.hasVideo){const t=new F(Z.INVALID_REMOTE_USER,"user is not published");throw B.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", user is not published")),t}if(!i&&("audio"===t&&!e.hasAudio||"video"===t&&!e.hasVideo)){const i=new F(Z.REMOTE_USER_IS_NOT_PUBLISHED);throw B.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid," with mediaType ").concat(t,", remote track is not published")),i}const n=await this._subscribeMutex.lock();B.info("[".concat(this._clientId,"] subscribe user ").concat(e.uid,", mediaType: ").concat(t));try{if(await this._p2pChannel.hasRemoteMediaWithLock(e,t))await this._p2pChannel.unmuteRemote(e,t);else try{const i="audio"===t?e._audioSSRC:e._videoSSRC,n="audio"===t?e._audioMid:e._videoMid;this.store.subscribe(e.uid,t,Date.now()),this.store.useP2P&&await this._p2pChannel.subscribe(e,t,i,n)}catch(e){throw e}B.info("[".concat(this._clientId,"] subscribe success user ").concat(e.uid,", mediaType: ").concat(t)),this._defaultStreamFallbackType&&this.setStreamFallbackOption(e.uid,this._defaultStreamFallbackType).catch((e=>{B.warning("[".concat(this._clientId,"] auto set fallback failed"),e)}));const i="audio"===t?e._audioTrack:e._videoTrack;if(!i)throw new F(Z.UNEXPECTED_ERROR,"can not find remote track in user object");return i}catch(t){throw B.error("[".concat(this._clientId,"] subscribe user ").concat(e.uid," error"),t),t}finally{n()}}async _subscribe(e,t,i){if(this.store.useP2P)return this._p2pSubscribe(e,t);if(Ut(t,"mediaType",["audio","video"]),!this._joinInfo)throw new F(Z.INVALID_OPERATION,"Can't subscribe stream, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new F(Z.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));if(!this._users.find((t=>t===e))){const t=new F(Z.INVALID_REMOTE_USER,"user is not in the channel");throw B.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", this user is not in the channel")),t}if(!e.hasAudio&&!e.hasVideo){const t=new F(Z.INVALID_REMOTE_USER,"user is not published");throw B.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", user is not published")),t}if(!(i||("audio"!==t||e.hasAudio&&void 0!==e._audioSSRC)&&("video"!==t||e.hasVideo&&void 0!==e._videoSSRC))){const i=new F(Z.REMOTE_USER_IS_NOT_PUBLISHED);throw B.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid," with mediaType ").concat(t,", remote track is not published")),i}let n="audio"===t?e._audioSSRC:e._videoSSRC,o="audio"===t?e._audioOrtc:e._videoOrtc,a="video"===t?e._rtxSsrcId:void 0,s={stream_type:"audio"===t?Zi.AUDIO:Zi.VIDEO,ssrcId:n};"video"===t&&this.store.firstVideoFrameDecoded(e.uid,{subscribeStart:Date.now()});const r=await this._subscribeMutex.lock();B.info("[".concat(this._clientId,"] subscribe user ").concat(e.uid,", mediaType: ").concat(t));try{if(await this._p2pChannel.hasRemoteMediaWithLock(e,t))await this._p2pChannel.unmuteRemote(e,t);else try{const i="audio"===t?e._audioSSRC:e._videoSSRC;void 0!==i&&i!==n&&(n=i,o="audio"===t?e._audioOrtc:e._videoOrtc,a="video"===t?e._rtxSsrcId:void 0,s={stream_type:"audio"===t?Zi.AUDIO:Zi.VIDEO,ssrcId:n}),ta.markSubscribeStart(this.store.clientId,n),this.store.subscribe(e.uid,t,Date.now()),await this._p2pChannel.subscribe(e,t,n,a,o);try{this._p2pChannel.isPreSubScribe(n)||await this._gateway.subscribe(e.uid,s,!0)}catch(i){if((null==i?void 0:i.code)!==Z.WS_ABORT)throw await this._p2pChannel.unsubscribe(e,t),i;await this._p2pChannel.unsubscribe(e,t,!0),this._p2pChannel.setPendingRemoteMedia(e,t)}this.store.subscribe(e.uid,t,void 0,Date.now()),this._p2pChannel.reportSubscribeEvent(!0,null,e,t)}catch(i){throw this._p2pChannel.reportSubscribeEvent(!1,null==i?void 0:i.code,e,t),i}B.info("[".concat(this._clientId,"] subscribe success user ").concat(e.uid,", mediaType: ").concat(t)),this._defaultStreamFallbackType&&this.setStreamFallbackOption(e.uid,this._defaultStreamFallbackType).catch((e=>{B.warning("[".concat(this._clientId,"] auto set fallback failed"),e)}));const i="audio"===t?e._audioTrack:e._videoTrack;if(!i)throw new F(Z.UNEXPECTED_ERROR,"can not find remote track in user object");return"video"===t&&(this.store.firstVideoFrameDecoded(e.uid,{subscribeEnd:Date.now()}),this._p2pChannel.reportVideoFirstFrameRender(e)),i}catch(t){throw B.error("[".concat(this._clientId,"] subscribe user ").concat(e.uid," error"),t),t}finally{r()}}async massSubscribe(e){if(Mt(e,"subscribeList"),!this._joinInfo)throw new F(Z.INVALID_OPERATION,"Can't subscribe stream, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new F(Z.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));const t=Date.now(),i=new Map,n=await this._subscribeMutex.lock();B.info("[".concat(this._clientId,"]start massSubscribe user ").concat(e.map((e=>{let{user:t,mediaType:i}=e;return"user: ".concat(null==t?void 0:t.uid,", mediaType: ").concat(i)})).join("; ")));const o=(e=[...e]).map((e=>{let{user:t,mediaType:i}=e;return{user:t,mediaType:i}})),a=await this._p2pChannel.globalLock();try{for(let t=e.length-1;t>=0;t--){const n=e[t],{user:a,mediaType:s}=n;if(Ut(s,"mediaType",["audio","video"]),!a){const e=new F(Z.INVALID_PARAMS,"user property does not exist in subscribeList item");throw B.error("[".concat(this._clientId,"] user property does not exist in subscribeList item")),e}if(!this._users.find((e=>e===a))){const i=new F(Z.INVALID_REMOTE_USER,"user is not in the channel");B.error("[".concat(this._clientId,"] can not massSubscribe ").concat(a.uid,", this user is not in the channel")),o[t].error=i,e.splice(t,1);continue}if("audio"===s&&(!a.hasAudio||void 0===a._audioSSRC)||"video"===s&&(!a.hasVideo||void 0===a._videoSSRC)){const i=new F(Z.REMOTE_USER_IS_NOT_PUBLISHED);B.error("[".concat(this._clientId,"] can not subscribe ").concat(a.uid," with mediaType ").concat(s,", remote user is not published")),o[t].error=i,e.splice(t,1);continue}const r=Wi.Video|Wi.LwoVideo,c=i.get(a);if(c){if("video"===s?c&r:c&Wi.Audio){e.splice(t,1),B.warning("[".concat(this._clientId,"] repeat massSubscribe user:").concat(a.uid,", mediaType:").concat(s," twice"));continue}i.set(a,c|("video"===s?r:Wi.Audio))}else i.set(a,"video"===s?r:Wi.Audio)}for(let t=e.length-1;t>=0;t--){const n=e[t],{user:o,mediaType:a}=n,s=Wi.Video|Wi.LwoVideo;if(this._p2pChannel.hasRemoteMedia(o,a)){await this._p2pChannel.unmuteRemoteNoLock(o,a);const n=i.get(o);i.set(o,"video"===a?n^s:n^Wi.Audio),e.splice(t,1)}}this.store.massSubscribe(e.map((e=>({userId:e.user.uid,type:e.mediaType}))),t);let s=Array.from(i.entries()).reduce(((e,t)=>{let[i,n]=t;if(0===n)return e;const o={stream_id:i.uid,stream_type:n};return n&Wi.Audio&&(o.audio_ssrc=i._audioSSRC),n&Wi.Video&&(o.video_ssrc=i._videoSSRC),e.push(o),e}),[]);try{e.length>0&&await this._p2pChannel.massSubscribeNoLock(e.map((e=>{let{user:t,mediaType:i}=e;return{user:t,mediaType:i,ssrcId:i===Zi.VIDEO?t._videoSSRC:t._audioSSRC,rtxSsrcId:i===Zi.VIDEO?t._rtxSsrcId:void 0}})));const i=new Map;if(s=s.filter((e=>e.video_ssrc&&!this._p2pChannel.isPreSubScribe(e.video_ssrc)||e.audio_ssrc&&!this._p2pChannel.isPreSubScribe(e.audio_ssrc)||!e.video_ssrc&&!e.audio_ssrc)),s.length>0){const e=await this._gateway.subscribeAll(s,!0);((null==e?void 0:e.users)||[]).forEach((e=>{let{stream_id:t,video_error_code:n,audio_error_code:o,error_code:a}=e;(n||o||a)&&i.set(t,{video_error_code:n,audio_error_code:o,error_code:a})}))}if(Array.from(i.entries()).length>0){const e=[];Array.from(i.entries()).forEach((t=>{let[i,n]=t;const o=this.remoteUsers.find((e=>e.uid===i));if(o){let t;n.error_code||n.video_error_code&&n.audio_error_code?t=void 0:n.video_error_code?t=Zi.VIDEO:n.audio_error_code&&(t=Zi.AUDIO),e.push({user:o,mediaType:t})}})),e.length>0&&await this._p2pChannel.massUnsubscribeNoLock(e)}for(const e of o){const t=i.get(e.user.uid);if(t){const i=t.error_code||"audio"===e.mediaType&&t.audio_error_code||"video"===e.mediaType&&t.video_error_code;if(i){const t=mn(i);B.error("user:".concat(e.user.uid," mediaType:").concat(e.mediaType," has massSubscribe error ").concat(t.desc)),e.error=new F(Z.SUBSCRIBE_FAILED,"code ".concat(i,": ").concat(t.desc))}}e.error||("video"===e.mediaType?e.track=e.user.videoTrack:e.track=e.user.audioTrack)}return this.store.massSubscribe(o.filter((e=>!e.error)).map((e=>({userId:e.user.uid,type:e.mediaType}))),void 0,Date.now()),o.forEach((e=>{var i;j.subscribe(this.store.sessionId,{succ:!!e.error,ec:(null===(i=e.error)||void 0===i?void 0:i.code)||null,video:e.mediaType===Zi.VIDEO,audio:e.mediaType===Zi.AUDIO,peerid:e.user.uid,subscribeRequestid:e.mediaType===Zi.VIDEO?e.user._videoSSRC:e.user._audioSSRC,p2pid:this.store.p2pId,eventElapse:Math.floor(performance.now()-t),preSsrc:this._p2pChannel.isPreSubScribe(e.user._videoSSRC)},!0)})),B.info("[".concat(this._clientId,"] massSubscribe success ").concat(e.map((e=>{let{user:t,mediaType:i}=e;return"user: ".concat(null==t?void 0:t.uid,", mediaType: ").concat(i)})).join("; "))),o}catch(t){throw await this._p2pChannel.massUnsubscribeNoLock(e),t}}finally{a(),n()}}async unsubscribe(e,t,i){if(!(e instanceof aa)){const t=this.remoteUsers.find((t=>t.uid===e));if(!t)throw new F(Z.INVALID_REMOTE_USER,"user is not in the channel");e=t}if(t||this.store.useP2P){if("datachannel"===t)return this._unsubscribeDataChannel(e,i)}else await this._unsubscribeDataChannel(e,i);if(t&&Ut(t,"mediaType",["audio","video"]),!this._joinInfo)throw new F(Z.INVALID_OPERATION,"Can't unsubscribe stream, haven't joined yet!");if(!this._users.find((t=>t===e))){const t=new F(Z.INVALID_REMOTE_USER,"user is not in the channel");throw B.error("[".concat(this._clientId,"] can not unsubscribe ").concat(e.uid,", user is not in the channel")),t}B.info("[".concat(this._clientId,"] unsubscribe uid: ").concat(e.uid,", mediaType: ").concat(t));const n=await this._subscribeMutex.lock();try{if(this.store.useP2P)await this._p2pChannel.unsubscribe(e,t);else{const i=await this._p2pChannel.unsubscribe(e,t);i&&await this._gateway.unsubscribe(i,e.uid),t&&"audio"!==t||(e._audio_pre_subscribed=!1),t&&"video"!==t||(e._video_pre_subscribed=!1),e._is_pre_created&&At(this._users,e),B.info("[".concat(this._clientId,"] unsubscribe success uid: ").concat(e.uid,", mediaType: ").concat(t))}}catch(t){if(t.code===Z.DISCONNECT_P2P)return void B.warning("disconnecting p2p, abort unsubscribe request.");throw B.error("[".concat(this._clientId,"] unsubscribe user ").concat(e.uid," error"),t.toString()),t}finally{n()}}async _unsubscribeDataChannel(e,t){if(t&&It(t,"id",0,65535,!0),!this._joinInfo)throw new F(Z.INVALID_OPERATION,"Can't unsubscribe datachannel, haven't joined yet!");if(!this._users.find((t=>t===e))){const t=new F(Z.INVALID_REMOTE_USER,"user is not in the channel");throw B.error("[".concat(this._clientId,"] can not unsubscribe ").concat(e.uid,", user is not in the channel")),t}let i;if("number"==typeof t){const n=e._dataChannels.find((e=>e.id===t));n&&(i=[n])}else i=e._dataChannels;if(void 0===i){const i=new F(Z.REMOTE_USER_IS_NOT_PUBLISHED);throw B.error("[".concat(this._clientId,"] can not unsubscribe ").concat(e.uid," with channelId ").concat(t,", remote datachannel is not published")),i}B.info("[".concat(this._clientId,"] unsubscribe uid: ").concat(e.uid,", mediaType: datachannel, ids: ").concat(i.map((e=>e.id))));try{const t=await this._p2pChannel.unsubscribeDataChannel(e,i);t&&await this._gateway.unsubscribeDataChannel(t,e.uid),B.info("[".concat(this._clientId,"] unsubscribe datachannel success uid: ").concat(e.uid,", mediaType: datachannel, ids: ").concat(t))}catch(t){if(t.code===Z.DISCONNECT_P2P)return void B.warning("disconnecting p2p, abort unsubscribe request.");throw B.error("[".concat(this._clientId,"] unsubscribe user ").concat(e.uid," error"),t.toString()),t}}async massUnsubscribe(e){if(Mt(e,"unsubscribeList"),!this._joinInfo)throw new F(Z.INVALID_OPERATION,"Can't unsubscribeAll stream, haven't joined yet!");B.info("[".concat(this._clientId,"] start massUnsubscribe ").concat(e.map((e=>{let{user:t,mediaType:i}=e;return"user: ".concat(null==t?void 0:t.uid,", mediaType: ").concat(i,";")})).join())),e=[...e];const t=new Map;for(let i=e.length-1;i>=0;i--){const{user:n,mediaType:o}=e[i];if(!n){const e=new F(Z.INVALID_PARAMS,"user property does not exist in unsubscribeList item");throw B.error("[".concat(this._clientId,"] user property does not exist in unsubscribeList item")),e}Ut(o,"mediaType",["video","audio",void 0]);if(!this._users.find((e=>e===n))){B.warning("[".concat(this._clientId,"] can not unsubscribe ").concat(n.uid,", user is not in the channel")),e.splice(i,1);continue}const a=Wi.Video|Wi.LwoVideo;if(t.has(n)){const s=t.get(n);let r;switch(o){case"video":r=s&a;break;case"audio":r=s&Wi.Audio;break;default:r=s&(Wi.Audio|a)}if(r){B.warning("[".concat(this._clientId,"] repeat massUnsubscribe user:").concat(n.uid,",mediaType:").concat(o," twice.")),e.splice(i,1);continue}o?"audio"===o?t.set(n,s|Wi.Audio):"video"===o&&t.set(n,s|a):t.set(n,s|Wi.Audio|a)}else o?"audio"===o?t.set(n,Wi.Audio):"video"===o&&t.set(n,a):t.set(n,Wi.Audio|a)}try{const t=await this._p2pChannel.massUnsubscribe(e);t&&await this._gateway.massUnsubscribe(t),B.info("[".concat(this._clientId,"] massUnsubscribe success ").concat(e.map((e=>{let{user:t,mediaType:i}=e;return"user: ".concat(null==t?void 0:t.uid,", mediaType: ").concat(i,";")})).join()))}catch(e){if(e.code===Z.DISCONNECT_P2P)return void B.warning("[".concat(this._clientId,"] disconnecting p2p, abort unsubscribe request."));throw B.error("[".concat(this._clientId,"] massUnsubscribe error"),e.toString()),e}}async setLowStreamParameter(e){P(e),(!e.width&&e.height||e.width&&!e.height)&&B.warning("[".concat(this._clientId,"] The width and height parameters take effect only when both are set")),B.info("[".concat(this._clientId,"] set low stream parameter to"),JSON.stringify(e));const t=this._configDistribute.getLowStreamConfigDistribute();if(t&&t.bitrate&&e.bitrate&&t.bitrate<e.bitrate&&(e.bitrate=t.bitrate),this._lowStreamParameter=e,this._isDualStreamEnabled)return this._p2pChannel.updateVideoStreamParameter(e,nn.LocalVideoLowTrack)}async enableDualStream(){if(!o().supportDualStream)throw j.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!0,succ:!1}),new F(Z.NOT_SUPPORTED,"Your browser is not support dual stream");if(this._isDualStreamEnabled)throw new F(Z.INVALID_OPERATION,"Dual stream is already enabled");if(this._p2pChannel.canPublishLowStream())try{await this._publishLowStream()}catch(e){throw j.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!0,succ:!1}),e}this._isDualStreamEnabled=!0,j.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!0,succ:!0}),B.info("[".concat(this._clientId,"] enable dual stream"))}async disableDualStream(){if(this._isDualStreamEnabled){if(!this._joinInfo)throw new F(Z.INVALID_OPERATION,"Can't publish stream, haven't joined yet!");if(this._p2pChannel.getLocalMedia(nn.LocalVideoLowTrack))try{const e=await this._p2pChannel.unpublishLowStream();e&&await this._gateway.unpublish(e,this._joinInfo.stringUid||this._joinInfo.uid)}catch(e){throw j.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!1,succ:!1}),e}this._isDualStreamEnabled=!1,j.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!1,succ:!0}),B.info("[".concat(this._clientId,"] disable dual stream"))}}async setClientRole(e,t){if(Vt(e),t&&Nt(t),"rtc"===this.mode||"p2p"===this.mode)throw B.warning("[".concat(this._clientId,"]").concat(this.mode," mode can not use setClientRole")),new F(Z.INVALID_OPERATION,"".concat(this.mode," mode can not use setClientRole"));if(t&&t.level&&"host"===e)throw new F(Z.INVALID_OPERATION,"host mode can not set audience latency level");if("audience"===e&&this._p2pChannel.hasLocalMedia())throw new F(Z.INVALID_OPERATION,"can not set client role to audience when publishing stream");const i=this._config.role;this._joinInfo&&(this._joinInfo.role=e),e!==i&&ne("ENABLE_ROLE_SELECT_EDGE")?(this._gateway.updateClientRole(e,t),this._config.role=e,this._gateway.reconnect("recover",Re.REGIONAL_DISTRIBUTION)):(await this._gateway.setClientRole(e,t),this._config.role=e),B.info("[".concat(this._clientId,"] set client role to ").concat(e,", level: ").concat(t&&t.level))}async _setClientRoleOptions(e){if("rtc"===this.mode||"p2p"===this.mode)return;if("audience"!==this._config.role||this._p2pChannel.hasLocalMedia())return;let t=!1;try{e&&Nt(e),await this._gateway.setClientRole(this._config.role,e),t=!0}catch(e){}finally{B.info("[".concat(this._clientId,"] set client role options ").concat(t?"succeed":"failed",", options is ").concat(e))}}getRemoteInboundOffset(){var e;const t=null===(e=this._p2pChannel.getStats())||void 0===e?void 0:e.audioSend[0];if(!t||!t.timestamp)return 0;const i=t.timestamp-Date.now();return Math.abs(i)>1e3+t.rttMs+100?this.ntpAlignErrorCount+=1:this.ntpAlignErrorCount=0,this.ntpAlignErrorCount>=3?i:0}getNtpWallTimeInMs(){return"visible"===document.visibilityState&&(this.remoteInboundOffset=this.getRemoteInboundOffset()),this.remoteInboundOffset+Date.now()+this._gateway.ntpOffset}setProxyServer(e,t){if(ee(e,"proxyServer"),!t){if("DISCONNECTED"!==this.connectionState)throw new F(Z.INVALID_OPERATION,"Set proxy server before join channel");if("disabled"!==this._cloudProxyServerMode||this._useLocalAccessPoint)throw new F(Z.INVALID_OPERATION,"You have already set the proxy")}this._proxyServer=e,j.setProxyServer(this._proxyServer),B.setProxyServer(this._proxyServer),B.info("[".concat(this._clientId,"] Set proxy server ").concat(t?"by initialize call":""," success."))}setTurnServer(e,t){if(Array.isArray(e)||(e=[e]),!t){if("DISCONNECTED"!==this.connectionState)throw new F(Z.INVALID_OPERATION,"Set turn server before join channel");if("disabled"!==this._cloudProxyServerMode||this._useLocalAccessPoint)throw new F(Z.INVALID_OPERATION,"You have already set the proxy")}if(st(e))return this._turnServer={servers:e,mode:"original-manual"},void B.info("[".concat(this._clientId,"] Set original turnserver ").concat(t?"by initialize call":""," success: ").concat(e.map((e=>e.urls)).join(","),"."));e.forEach((e=>xt(e))),this._turnServer={servers:e,mode:"manual"},B.info("[".concat(this._clientId,"] Set turnserver ").concat(t?"by initialize call":""," success."))}setLicense(e){if("DISCONNECTED"!==this.connectionState){throw new F(Z.INVALID_OPERATION,"you should set license before join channel")}if(ee(e,"license",32,32),!/^[A-Za-z\d]+$/.test(e))throw new F(Z.INVALID_PARAMS,"license should only contains characters from A-Z a-z 0-9");this._license=e,B.info("[".concat(this._clientId,"] set license success"),e)}startProxyServer(e){if("DISCONNECTED"!==this.connectionState)throw new F(Z.INVALID_OPERATION,"Start proxy server before join channel");if(this._proxyServer||"manual"===this._turnServer.mode||this._useLocalAccessPoint)throw new F(Z.INVALID_OPERATION,"You have already set the proxy");const t=[3,4,5];let i;switch(void 0===e&&(e=3),e){case 1:case 2:throw new F(Z.NOT_SUPPORTED,"proxy mode 1/2 has been deprecated and not supported.");case 3:i="proxy3";break;case 4:i="proxy4";break;case 5:i="proxy5";break;default:throw new F(Z.INVALID_PARAMS,"proxy server mode must be ".concat(t.join("|")))}this._cloudProxyServerMode=i,this.store.cloudProxyServerMode=i,B.info("[".concat(this._clientId,"] set cloud proxy server mode to"),this._cloudProxyServerMode)}stopProxyServer(){if("DISCONNECTED"!==this.connectionState)throw new F(Z.INVALID_OPERATION,"Stop proxy server after leave channel");j.setProxyServer(),B.setProxyServer(),this._cloudProxyServerMode="disabled",this.store.cloudProxyServerMode="disabled",B.info("[".concat(this._clientId,"] set cloud proxy server mode to"),this._cloudProxyServerMode),this._proxyServer=void 0,this._turnServer={mode:"auto",servers:[]}}setLocalAccessPointsV2(e){if(!e.accessPoints)throw new F(Z.INVALID_PARAMS,"accessPoints is required.");Mt(e.accessPoints.serverList,"accessPoints.serverList"),ee(e.accessPoints.domain,"accessPoints.domain");const t=(e,t)=>{It(e,t,0,65535,!0)};let i=443;if(e.accessPoints.port&&(t(e.accessPoints.port,"accessPoints.port"),i=e.accessPoints.port),this._proxyServer||"disabled"!==this._cloudProxyServerMode)throw new F(Z.INVALID_OPERATION,"set local access point failed, You have already set the cloud proxy");ne("CLOSE_AFB_FOR_LOCAL_AP")&&(Fe("JOIN_WITH_FALLBACK_SIGNAL_PROXY",!1),Fe("JOIN_WITH_FALLBACK_MEDIA_PROXY",!1));const n=/^((\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/,o=e.accessPoints.domain,a=e.accessPoints.serverList.map((e=>n.test(e)?"".concat(e.replace(/\./g,"-"),".").concat(o):e)),s=a.map((e=>"".concat(e,":").concat(i)));this._useLocalAccessPoint=!0,this._setLocalAPVersion=2,Fe("WEBCS_DOMAIN",s),Fe("WEBCS_DOMAIN_BACKUP_LIST",s),Fe("GATEWAY_DOMAINS",[o]),e.report&&e.report.hostname&&Array.isArray(e.report.hostname)&&e.report.hostname.length?(Mt(e.report.hostname,"report.hostname"),Fe("EVENT_REPORT_DOMAIN",e.report.hostname[0]),Fe("EVENT_REPORT_BACKUP_DOMAIN",e.report.hostname[1]||e.report.hostname[0])):(Fe("EVENT_REPORT_DOMAIN",a[0]),Fe("EVENT_REPORT_BACKUP_DOMAIN",a[1]||a[0]));let r=6443;e.report&&e.report.port&&(t(e.report.port,"report.port"),r=e.report.port),Fe("STATS_COLLECTOR_PORT",r),e.report?Fe("ENABLE_EVENT_REPORT",!0):Fe("ENABLE_EVENT_REPORT",!1);let c="";e.log&&e.log.hostname&&Array.isArray(e.log.hostname)&&e.log.hostname.length?(Mt(e.log.hostname,"log.hostname"),c=e.log.hostname[0]):c=a[0];let d=6444;e.log&&e.log.port&&(t(e.log.port,"log.port"),d=e.log.port),Fe("LOG_UPLOAD_SERVER","".concat(c,":").concat(d));let l=[];e.cds&&e.cds.hostname&&Array.isArray(e.cds.hostname)&&e.cds.hostname.length?(Mt(e.cds.hostname,"cds.hostname"),l=e.cds.hostname):l=a;let u=443;e.cds&&e.cds.port&&(t(e.cds.port,"cds.port"),u=e.cds.port),Fe("CDS_AP",l.map((e=>"".concat(e,":").concat(u)))),e.cds?Fe("ENABLE_CONFIG_DISTRIBUTE",!0):Fe("ENABLE_CONFIG_DISTRIBUTE",!1),B.info("set local access point v2 success")}setLocalAccessPoints(e,t){if(Mt(e,"serverList"),ee(t,"domain"),this._proxyServer||"disabled"!==this._cloudProxyServerMode)throw new F(Z.INVALID_OPERATION,"set local access point failed, You have already set the cloud proxy");const i=/^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;e=e.map((e=>i.test(e)?"".concat(e.replace(/\./g,"-"),".").concat(t):e)),this._useLocalAccessPoint=!0,this._setLocalAPVersion=1,Fe("WEBCS_DOMAIN",e),Fe("WEBCS_DOMAIN_BACKUP_LIST",e),Fe("GATEWAY_DOMAINS",[t]),Fe("EVENT_REPORT_DOMAIN",e[0]),Fe("EVENT_REPORT_BACKUP_DOMAIN",e[1]||e[0]),Fe("LOG_UPLOAD_SERVER","".concat(e[0],":6444")),B.info("[".concat(this._clientId,"] set local access point success"))}async setRemoteDefaultVideoStreamType(e){if(Ut(e,"streamType",[0,1,4,5,6,7,8,9]),this._remoteDefaultVideoStreamType=e,this._joinInfo)try{await this._gateway.setDefaultRemoteVideoStreamType(e),this._joinInfo.defaultVideoStream=this._remoteDefaultVideoStreamType}catch(e){throw B.error("[".concat(this._clientId,"] set default remote video stream type error"),e.toString()),e}else B.debug("[".concat(this._clientId,"] haven't joined yet, cache remoteDefaultVideoStreamType ").concat(e))}async setRemoteVideoStreamType(e,t){Ut(t,"streamType",[0,1,4,5,6,7,8,9]);try{await this._gateway.setRemoteVideoStreamType(e,t),setTimeout((()=>{const t=this._users.find((t=>t.uid===e));t&&t.videoTrack&&t.videoTrack.updateMediaStreamTrackResolution()}),2e3)}catch(e){throw B.error("[".concat(this._clientId,"] set remote video stream type error"),e.toString()),e}B.info("[".concat(this._clientId,"] set remote ").concat(e," video stream type to ").concat(t)),this._remoteStreamTypeCacheMap.set(e,t)}async setStreamFallbackOption(e,t){Ut(t,"fallbackType",[0,1,2,3,4,5,6,7,8]);try{await this._gateway.setStreamFallbackOption(e,t)}catch(e){throw B.error("[".concat(this._clientId,"] set stream fallback option"),e.toString()),e}B.info("[".concat(this._clientId,"] set remote ").concat(e," stream fallback type to ").concat(t)),this._streamFallbackTypeCacheMap.set(e,t)}setEncryptionConfig(e,t,i,n){Bt(e),ee(t,"secret");const o=["aes-128-gcm2","aes-256-gcm2"];if(o.includes(e)){if(!i||!(i instanceof Uint8Array&&32===i.length))throw new F(Z.INVALID_PARAMS,"salt must be an Uint8Array and exactly equal to 32 bytes")}else if(i)throw new F(Z.INVALID_PARAMS,"current encrypt mode does not need salt");if(n){if(Dt(n,"encryptDataStream"),!o.includes(e))throw new F(Z.INVALID_PARAMS,"current encrypt mode does not support data stream");this._encryptDataStream=!0}new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*,.<>?/:;'\"|{}\\[\\]])(?=.{8,})").test(t)||B.warning("The secret is not strong:\n The secret must contain at least 1 lowercase alphabetical character,\n The secret must contain at least 1 uppercase alphabetical character,\n The secret must contain at least 1 numeric character,\n The secret must contain at least one special character,\n The secret must be eight characters or longer.\n "),this._encryptionMode=e,this._encryptionSecret=t,i&&(this._encryptionSalt=Tt(i))}async renewToken(e){if(ee(e,"token",1,2047),!this._key||!this._joinInfo)throw new F(Z.INVALID_OPERATION,"renewToken should not be called before user join");const t=this._key;this._key=e,this._joinInfo&&(this._joinInfo.token=e);const i=await this._renewTokenMutex.lock();try{if(ne("USE_NEW_TOKEN")){B.debug("[".concat(this._clientId,"] start renew token with ticket from unilbs"));const t=await Qo(this._joinInfo,this._axiosCancelSource.token,this._config.httpRetryConfig||Ye);B.debug("[".concat(this._clientId,"] get ticket from unilbs success")),await this._gateway.renewToken({token:e,ticket:t})}else B.debug("[".concat(this._clientId,"] start renew token without ticket")),await this._gateway.renewToken({token:e});B.debug("[".concat(this._clientId,"] renewToken success"))}catch(e){throw this._key=t,this._joinInfo.token=t,B.error("[".concat(this._clientId,"] renewToken failed"),e.toString()),e}finally{i()}}enableAudioVolumeIndicator(){this._audioVolumeIndicationInterval?B.warning("you have already enabled audio volume indicator!"):this._audioVolumeIndicationInterval=window.setInterval((()=>{const e=this._p2pChannel.getAudioLevels();this.safeEmit(pt.VOLUME_INDICATOR,e)}),ne("AUDIO_VOLUME_INDICATION_INTERVAL")||2e3)}getRTCStats(){const e=this._statsCollector.getRTCStats(),t=this._gateway.getInChannelInfo();return e.Duration=Math.round(t.duration/1e3),e}async startLiveStreaming(e,t){if(!t){if("h264"!==this.codec)throw new F(Z.LIVE_STREAMING_INVALID_RAW_STREAM,"raw streaming is only support h264");if(!this._p2pChannel.hasLocalMedia())throw new F(Z.LIVE_STREAMING_INVALID_RAW_STREAM,"can not find stream to raw streaming")}if(this._liveRawStreamingClient&&this._liveRawStreamingClient.hasUrl(e)||this._liveTranscodeStreamingClient&&this._liveTranscodeStreamingClient.hasUrl(e))throw new F(Z.LIVE_STREAMING_TASK_CONFLICT);const i=t?ki.TRANSCODE:ki.RAW;return this._createLiveStreamingClient(i).startLiveStreamingTask(e,i)}setLiveTranscoding(e){return this._createLiveStreamingClient(ki.TRANSCODE).setTranscodingConfig(e)}async stopLiveStreaming(e){const t=[this._liveRawStreamingClient,this._liveTranscodeStreamingClient].filter((t=>t&&t.hasUrl(e)));if(!t.length)throw new F(Z.INVALID_PARAMS,"can not find live streaming url to stop");await Promise.all(t.map((t=>t&&t.stopLiveStreamingTask(e))))}async startChannelMediaRelay(e){oa(e);const t=this._createChannelMediaRelayClient();await t.startChannelMediaRelay(e)}async updateChannelMediaRelay(e){oa(e);const t=this._createChannelMediaRelayClient();await t.updateChannelMediaRelay(e)}async stopChannelMediaRelay(){const e=this._createChannelMediaRelayClient();await e.stopChannelMediaRelay(),this._statsCollector.onStatsChanged&&(this._statsCollector.onStatsChanged=void 0)}sendAudioMetadata(e){this._p2pChannel instanceof za&&this._p2pChannel.addAudioMetadata(e)}async sendStreamMessage(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!this._joinInfo)throw new F(Z.INVALID_OPERATION,"can not send data stream, not joined");if(("string"==typeof e||e instanceof Uint8Array)&&(e={payload:e}),"string"==typeof e.payload){const t=new TextEncoder;e.payload=t.encode(e.payload)}let i=!1;this._encryptDataStream&&this._encryptDataStreamIv&&this._encryptDataStreamKey&&window.crypto.subtle&&["aes-128-gcm2","aes-256-gcm2"].includes(this._encryptionMode)&&(i=!0,e.payload=await Ft(this._encryptDataStreamIv,this._encryptDataStreamKey,e.payload));if(new Blob([e.payload]).size>1024)throw new F(Z.INVALID_PARAMS,i?"encrypted stream message out of range.":"stream message out of range.");return this._gateway.signal.request(Ni.DATA_STREAM,{payload:Tt(e.payload),syncWithAudio:e.syncWithAudio,sendTs:Date.now()-Za},!t)}sendMetadata(e){if(!this._joinInfo)throw new F(Z.INVALID_OPERATION,"can not send metadata, not joined");if(new Blob([e]).size>1024)throw new F(Z.METADATA_OUT_OF_RANGE);return this._gateway.signal.request(Ni.SEND_METADATA,{session_id:this._joinInfo.sid,metadata:Tt(e)})}async sendCustomReportMessage(e){if(Array.isArray(e)||(e=[e]),e.forEach(Y),!this._joinInfo)throw new F(Z.INVALID_OPERATION,"can not send custom report, not joined");await j.sendCustomReportMessage(this._joinInfo.sid,e)}getLocalAudioStats(){return this._statsCollector.getLocalAudioTrackStats()}getRemoteAudioStats(){return this._statsCollector.getRemoteAudioTrackStats()}getLocalVideoStats(){return this._statsCollector.getLocalVideoTrackStats()}getRemoteVideoStats(){return this._statsCollector.getRemoteVideoTrackStats()}getRemoteNetworkQuality(){const e=this._statsCollector.getRemoteNetworkQualityStats();if(ne("DELETE_NEQ_AFTER_USER_LEAVE")){const t=this._users.map((e=>e.uid+""));Object.keys(e).forEach((i=>{t.includes(i)||delete e[i]}))}return e}async pickSVCLayer(e,t){Ut(t.spatialLayer,"spatialLayer",[0,1,2,3]),Ut(t.temporalLayer,"temporalLayer",[0,1,2,3]);try{await this._gateway.pickSVCLayer(e,t)}catch(e){throw B.error("[".concat(this._clientId,"] pick SVC layer failed"),e.toString()),e}}async setRTMConfig(e){const{apRTM:t=!1,rtmFlag:i}=e;if(Dt(t,"apRTM"),It(i,"rtmFlag",0),this._rtmConfig.apRTM=t,this._rtmConfig.rtmFlag=i,B.debug("[".concat(this._clientId,"] setRTMconfig ").concat(JSON.stringify(e)," in ").concat(this.connectionState," state")),("CONNECTED"===this.connectionState||"RECONNECTING"===this.connectionState)&&this._joinInfo)return this._joinInfo.apRTM=t,this._joinInfo.rtmFlag=i,this._gateway.setRTM2Flag(i)}_reset(){if(B.debug("[".concat(this._clientId,"] reset client")),function(e){const t=si.indexOf(e);-1!==t&&si.splice(t,1)}(this._clientId),this.store.hasStartJoinChannel=!1,this.store.isABTestSuccess=!1,this.store.autoSubscribe=!1,this._axiosCancelSource.cancel(),this._axiosCancelSource=Zt.CancelToken.source(),this._streamFallbackTypeCacheMap=new Map,this._remoteStreamTypeCacheMap=new Map,this._configDistribute.stopGetConfigDistribute(),this._joinInfo&&gs(this._joinInfo),this._joinInfo=void 0,this._proxyServer=void 0,this._defaultStreamFallbackType=void 0,this._sessionId&&j.removeSid(this._sessionId),this._sessionId=null,this.store.sessionId=null,this.store.resetFirstVideoFrameDecoded(),this._statsCollector.reset(),this._key=void 0,this._appId=void 0,this._uid=void 0,this.store.uid=void 0,this._channelName=void 0,this._encryptionMode="none",this._encryptionSecret=null,this._encryptionSalt=null,this._encryptDataStreamKey=null,this._encryptDataStreamIv=null,this._pendingPublishedUsers=[],this._users.forEach((e=>{e._audioTrack&&e._audioTrack._destroy(),e._videoTrack&&e._videoTrack._destroy(),e._dataChannels&&(e._dataChannels.forEach((e=>e._close())),e._dataChannels.length=0)})),this._users=[],this._audioVolumeIndicationInterval&&(window.clearInterval(this._audioVolumeIndicationInterval),this._audioVolumeIndicationInterval=void 0),"fallback"===this._cloudProxyServerMode&&(this._cloudProxyServerMode="disabled",this.store.cloudProxyServerMode="disabled"),this._p2pChannel.reset(),this._publishMutex=new re("client-publish",this._clientId),this._subscribeMutex=new re("client-subscribe",this._clientId),this._networkQualityInterval&&(window.clearInterval(this._networkQualityInterval),this._networkQualityInterval=void 0),this._liveRawStreamingClient&&(this._liveRawStreamingClient.terminate(),this._liveRawStreamingClient.removeAllListeners(),this._liveRawStreamingClient=void 0),this._liveTranscodeStreamingClient&&(this._liveTranscodeStreamingClient.terminate(),this._liveTranscodeStreamingClient.removeAllListeners(),this._liveTranscodeStreamingClient=void 0),this._channelMediaRelayClient&&(this._channelMediaRelayClient.dispose(),this._channelMediaRelayClient=void 0),this._inspect)try{this._inspect.close(),this._inspect=void 0}catch(e){}if(this._moderation)try{this.setImageModeration(!1)}catch(e){}}_startSession(e,t){var i;const n=e||mt();e?B.debug("[".concat(this._clientId,"] new Session ").concat(n)):B.debug("[".concat(this._clientId,"] renewSession ").concat(this._sessionId," => ").concat(n));const o=e?"":this._sessionId||"";this._sessionId=n,this.store.sessionId=n,j.addSid(n);const a={lts:(new Date).getTime(),mode:this.mode,buildFormat:3,stringUid:(null==t?void 0:t.stringUid)||(null===(i=this._joinInfo)||void 0===i?void 0:i.stringUid),channelProfile:"live"===this.mode?1:0,channelMode:0,isABTestSuccess:Number(this._configDistribute.isSuccess),lsid:o,clientRole:"audience"===this.role?2:1};j.sessionInit(this._sessionId,mi({cname:t.channel,appid:t.appId},a)),this._joinInfo&&(this._joinInfo.sid=n),this._gateway.joinInfo&&(this._gateway.joinInfo.sid=n)}async _publishHighStream(e){if(!this._joinInfo||void 0===this._uid)throw new F(Z.INVALID_OPERATION,"Can't publish stream, haven't joined yet!");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new F(Z.INVALID_OPERATION,"can not publish stream in ".concat(this.connectionState," state"));if("auto"===this._turnServer.mode&&ne("FORCE_TURN")&&!ne("TURN_ENABLE_TCP")&&!ne("TURN_ENABLE_UDP"))throw new F(Z.UNEXPECTED_ERROR,"force TURN With No TURN Configuration");B.debug("[".concat(this._clientId,"] publish high stream"));try{const i=await this._p2pChannel.publish(e,this._isDualStreamEnabled,this._lowStreamParameter);if(this.store.useP2P){const e=(await i.next()).value;if(e){try{await this._gateway.sendExtensionMessage(hn.PUBLISH,e,!0)}catch(e){throw i.throw(e),e}await i.next()}this._p2pChannel.reportPublishEvent(!0,null)}else{const o=(await i.next()).value;if(o){var t;let e;try{e=await this._gateway.publish(this._uid,o,!0)}catch(e){if(e.code!==Z.DISCONNECT_P2P)throw i.throw(e),e}await i.next((null===(t=e)||void 0===t?void 0:t.ortc)||[])}this._p2pChannel.reportPublishEvent(!0,null);for(const t of e)t instanceof n&&t._encoderConfig&&this._gateway.setVideoProfile(t._encoderConfig).catch((e=>{B.debug("[".concat(this._clientId,"] stop setVideoProfile, because websocket is closed"))})),!t.muted&&t.enabled||await this._p2pChannel.muteLocalTrack(t)}}catch(t){if(this._p2pChannel.reportPublishEvent(!1,null==t?void 0:t.code,e),(null==t?void 0:t.code)===Z.WS_ABORT)return;throw t}}async _publishLowStream(){if(!this._joinInfo||void 0===this._uid)throw new F(Z.INVALID_OPERATION,"Can't publish stream, haven't joined yet!");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new F(Z.INVALID_OPERATION,"can not publish stream in ".concat(this.connectionState," state"));B.debug("[".concat(this._clientId,"] publish low stream"));const e=this._configDistribute.getLowStreamConfigDistribute();e&&e.bitrate&&(this._lowStreamParameter||(this._lowStreamParameter={width:160,height:120,framerate:15,bitrate:50}),this._lowStreamParameter&&this._lowStreamParameter.bitrate&&e.bitrate<this._lowStreamParameter.bitrate&&(this._lowStreamParameter.bitrate=e.bitrate));try{const e=await this._p2pChannel.publishLowStream(this._lowStreamParameter),i=(await e.next()).value;if(i){var t;let n;try{n=await this._gateway.publish(this._uid,i,!0)}catch(t){if(t.code!==Z.DISCONNECT_P2P)throw e.throw(t),t}e.next((null===(t=n)||void 0===t?void 0:t.ortc)||[]),this._p2pChannel.reportPublishEvent(!0,null,void 0,!0)}}catch(e){if(this._p2pChannel.reportPublishEvent(!1,null==e?void 0:e.code,void 0,!0),(null==e?void 0:e.code)===Z.WS_ABORT)return;throw e}}_createLiveStreamingClient(e){const t=()=>{if(!this._joinInfo||!this._appId){return new F(Z.INVALID_OPERATION,"can not create live streaming client, please join channel first").throw()}const e=(t={joinInfo:this._joinInfo,appId:this._appId,websocketRetryConfig:this._config.websocketRetryConfig,httpRetryConfig:this._config.httpRetryConfig},po("LiveStreaming").create(t));var t;return e.onLiveStreamError=(e,t)=>{j.reportApiInvoke(this._sessionId,{name:We.ON_LIVE_STREAM_ERROR,options:[e,t],tag:He.TRACER}).onSuccess(),this.safeEmit(pt.LIVE_STREAMING_ERROR,e,t)},e.onLiveStreamWarning=(e,t)=>{j.reportApiInvoke(this._sessionId,{name:We.ON_LIVE_STREAM_WARNING,options:[e,t],tag:He.TRACER}).onSuccess(),this.safeEmit(pt.LIVE_STREAMING_WARNING,e,t)},e.on(Ui.REQUEST_WORKER_MANAGER_LIST,((e,t,i)=>{if(!this._joinInfo)return i(new F(Z.INVALID_OPERATION,"can not find join info to get worker manager"));(async function(e,t,i,n){const o=ne("UAP_AP").slice(0,ne("AJAX_REQUEST_CONCURRENT")).map((e=>t.proxyServer?"https://".concat(t.proxyServer,"/ap/?url=").concat(e+"/api/v1?action=uap"):"https://".concat(e,"/api/v1?action=uap")));return await Po(o,e,t,i,n)})(e,this._joinInfo,this._axiosCancelSource.token,Ye).then(t).catch(i)})),e};return e===ki.RAW?(this._liveRawStreamingClient=this._liveRawStreamingClient||t(),this._liveRawStreamingClient):(this._liveTranscodeStreamingClient=this._liveTranscodeStreamingClient||t(),this._liveTranscodeStreamingClient)}_createChannelMediaRelayClient(){if(!this._joinInfo){return new F(Z.INVALID_OPERATION,"can not create channel media relay client, please join channel first").throw()}if(!this._channelMediaRelayClient){const{sendResolutionWidth:t,sendResolutionHeight:i}=this.getLocalVideoStats(),n=(e={joinInfo:this._joinInfo,clientId:this._clientId,websocketRetryConfig:this._config.websocketRetryConfig,httpRetryConfig:this._config.httpRetryConfig,resolution:{width:t,height:i}},po("ChannelMediaRelay").create(e));n.on("state",(e=>{e===xi.RELAY_STATE_FAILURE&&n&&n.dispose(),this.safeEmit(pt.CHANNEL_MEDIA_RELAY_STATE,e)})),n.on("event",(e=>{this.safeEmit(pt.CHANNEL_MEDIA_RELAY_EVENT,e)})),this._channelMediaRelayClient=n,this._statsCollector.onStatsChanged=(e,t)=>{var i;"resolution"===e&&(null===(i=this._channelMediaRelayClient)||void 0===i||i.setVideoProfile(t))}}var e;return this._channelMediaRelayClient}_handleUpdateDataChannel(e,t){const{added:i,deleted:n}=e;if(t){const e=[];this._users.forEach((t=>{t._dataChannels.forEach((n=>{i.every((e=>e.uid!==t._uintid||e.stream_id!==n.id))&&e.push({uid:t._uintid,stream_id:n.id,ordered:n.ordered,max_retrans_times:n.maxRetransmits,metadata:n.metadata})}))})),e.length>0&&this._handleUpdateDataChannel({added:[],deleted:e})}Array.isArray(i)&&i.length>0&&i.forEach((e=>{const{uid:i,stream_id:n,ordered:o,max_retrans_times:a,metadata:s}=e,r=this._users.find((e=>e._uintid===i));if(!r)return void B.error("[".concat(this._clientId,"] can not find target user!(on_add_data_channel)"));B.debug("[".concat(this._clientId,"] data_channel added with uid ").concat(i)),r._uintid||(r._uintid=i);if(!(-1!==r._dataChannels.findIndex((t=>t.id===e.stream_id)))){const e={id:n,ordered:!!o,maxRetransmits:a,metadata:s},i=function(e){return Eo(e,!0)}(e);r._dataChannels.push(i),B.info("[".concat(this._clientId,"] remote user ").concat(r.uid," published datachannel")),t||this.safeEmit(pt.USER_PUBLISHED,r,"datachannel",e)}this._p2pChannel.hasPendingRemoteDataChannel(r,e.stream_id)&&(B.debug("[".concat(this._clientId,"] resubscribe datachannel for user ").concat(r.uid," after reconnect.")),this._subscribeDataChannel(r,e.stream_id).catch((e=>{B.error("[".concat(this._clientId,"] resubscribe datachannel error"),e.toString())})))})),t&&(this.safeEmit(pt.PUBLISHED_USER_LIST,this._pendingPublishedUsers),this._pendingPublishedUsers=[]),Array.isArray(n)&&n.length>0&&n.forEach((e=>{const{uid:t,stream_id:i}=e,n=this._users.find((e=>e._uintid===t));if(!n)return void B.error("[".concat(this._clientId,"] can not find target user!(on_delete_data_channel)"));const o=n._dataChannels.find((t=>t.id===e.stream_id));o&&(B.debug("[".concat(this._clientId,"] data_stream delete with uid ").concat(t)),this._p2pChannel.unsubscribeDataChannel(n,[o]).then((e=>{if(n._dataChannels=n._dataChannels.filter((e=>e!==o)),e)return this._gateway.unsubscribeDataChannel(e,n.uid)})),B.info("[".concat(this._clientId,"] remote user ").concat(t," unpublished datachannel ,id:").concat(o.id)),this.safeEmit(pt.USER_UNPUBLISHED,n,"datachannel",o._config))}))}_getEncodingName(e){var t;if(!this._joinResponse)return;const i=null===(t=this._joinResponse.ortc.rtpCapabilities.sendrecv)||void 0===t?void 0:t.videoCodecs;if(i)for(const t of i){var n;if(t.payloadType===e)return null==t||null===(n=t.rtpMap)||void 0===n?void 0:n.encodingName}}_handleRemoveDataChannels(e){const t=this._users.find((t=>t.uid===e.uid));if(t){if(void 0!==t._dataChannels&&t._dataChannels.length>0){B.debug("[".concat(this._clientId,"] datachannel removed with uid ").concat(e.uid));const i=()=>{B.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished datachannel")),t._dataChannels.forEach((e=>{this.safeEmit(pt.USER_UNPUBLISHED,t,"datachannel",e._config)}))};this._p2pChannel.unsubscribeDataChannel(t,t._dataChannels).then((e=>{if(e)return this._gateway.unsubscribeDataChannel(e,t.uid)})),i()}}else B.warning("[".concat(this._clientId,"] can not find target user!(on_remove_datachannel)"))}_handleGatewayEvents(){this._gateway.on(ji.UPDATE_GATEWAY_CONFIG,(()=>{!function(){let e;try{e=window.localStorage.getItem("websdk_ng_global_parameter")}catch(e){return void B.error("Error loading sdk config",e.message)}if(e)try{const t=JSON.parse(window.atob(e)),i=Date.now();Object.keys(t).forEach((e=>{const{value:n,type:o,expires:a}=t[e];a&&a<=i||o||ci()||!Object.prototype.hasOwnProperty.call(J,e)||(X[e]=n,q[e]=n,B.debug("Update gateway parameters from config distribute",e,n))}))}catch(e){B.error("Error update config from local cache",e.message)}}()})),this._gateway.on(ji.DISCONNECT_P2P,(async()=>{await this._p2pChannel.disconnectForReconnect()})),this._gateway.on(ji.CONNECTION_STATE_CHANGE,((e,t,i)=>{var n;if(i===me.FALLBACK)return;const o=()=>{this.safeEmit(pt.CONNECTION_STATE_CHANGE,e,t,i)};if(j.reportApiInvoke(this._sessionId||(null===(n=this._gateway.joinInfo)||void 0===n?void 0:n.sid)||null,{name:We.CONNECTION_STATE_CHANGE,options:[e,t,i],tag:He.TRACER}).onSuccess(JSON.stringify({cur:e,prev:t,reason:i})),B.info("[".concat(this._clientId,"] signal connection state change: ").concat(t," -> ").concat(e)),"DISCONNECTED"===e)return this._reset(),void o();if("RECONNECTING"===e)this._users.forEach((e=>{e._trust_in_room_=!1,e._trust_audio_enabled_state_=!1,e._trust_video_enabled_state_=!1,e._trust_audio_mute_state_=!1,e._trust_video_mute_state_=!1,e._trust_audio_stream_added_state_=!1,e._trust_video_stream_added_state_=!1,e._is_pre_created||(e._audio_pre_subscribed||(e._audioSSRC=void 0,e._audioOrtc=void 0),e._video_pre_subscribed||(e._videoSSRC=void 0,e._videoOrtc=void 0,e._rtxSsrcId=void 0),e._cname=void 0)})),this._userOfflineTimeout&&window.clearTimeout(this._userOfflineTimeout),this._streamRemovedTimeout&&window.clearTimeout(this._streamRemovedTimeout),this._userOfflineTimeout=void 0,this._streamRemovedTimeout=void 0;else if("CONNECTED"===e){var a;this._streamFallbackTypeCacheMap.forEach(((e,t)=>{this._gateway.setStreamFallbackOption(t,e).catch((e=>{B.warning("[".concat(this._clientId,"] auto set stream fallback option failed"),e)}))})),this._remoteStreamTypeCacheMap.forEach(((e,t)=>{this._gateway.setRemoteVideoStreamType(t,e).catch((e=>{B.warning("[".concat(this._clientId,"] auto set remote stream type failed"),e)}))})),void 0!==this._remoteDefaultVideoStreamType&&void 0===(null===(a=this._joinInfo)||void 0===a?void 0:a.defaultVideoStream)&&this.setRemoteDefaultVideoStreamType(this._remoteDefaultVideoStreamType).then((()=>{B.debug("[".concat(this._clientId,"] setRemoteDefaultVideoStreamType after gateway connected"))})).catch((e=>{B.error("[".concat(this._clientId,"] setRemoteDefaultVideoStreamType after gateway failed, ").concat(e))})),this.store.useP2P||(this._p2pChannel.republish(),this._userOfflineTimeout=window.setTimeout((()=>{if("CONNECTED"!==this.connectionState)return;this._userOfflineTimeout=void 0;this._users.filter((e=>!e._trust_in_room_)).forEach((e=>{B.debug("[".concat(this._clientId,"] user offline timeout, emit user offline ").concat(e.uid)),this._handleUserOffline({uid:e.uid})}))}),3e3),this._streamRemovedTimeout=window.setTimeout((()=>{"CONNECTED"===this.connectionState&&(this._streamRemovedTimeout=void 0,this._users.forEach((e=>{e._trust_audio_mute_state_||(B.debug("[".concat(this._clientId,"] auto dispatch audio unmute event ").concat(e.uid)),this._handleMuteStream(e.uid,Zi.AUDIO,!1)),e._trust_video_mute_state_||(B.debug("[".concat(this._clientId,"] auto dispatch video unmute event ").concat(e.uid)),this._handleMuteStream(e.uid,Zi.VIDEO,!1)),e._trust_audio_enabled_state_||(B.debug("[".concat(this._clientId,"] auto dispatch enable local audio ").concat(e.uid)),this._handleSetStreamLocalEnable("audio",e.uid,!0)),e._trust_video_enabled_state_||(B.debug("[".concat(this._clientId,"] auto dispatch enable local video ").concat(e.uid)),this._handleSetStreamLocalEnable("video",e.uid,!0)),e._trust_video_stream_added_state_||(B.debug("[".concat(this._clientId,"] auto dispatch reset video stream added ").concat(e.uid)),this._handleResetAddStream(e,"video")),e._trust_audio_stream_added_state_||(B.debug("[".concat(this._clientId,"] auto dispatch reset audio stream added ").concat(e.uid)),this._handleResetAddStream(e,"audio")),e._video_added_||e._audio_added_||(B.debug("[".concat(this._clientId,"] auto dispatch stream remove ").concat(e.uid)),this._handleRemoveStream({uid:e.uid,uint_id:e._uintid}))})))}),1e3))}o()})),this._gateway.on(ji.REQUEST_NEW_GATEWAY_LIST,(async(e,t)=>{if(!this._joinInfo)return t(new F(Z.UNEXPECTED_ERROR,"can not recover, no join info"));try{let t;const i=await Ts(mi(mi({},this._joinInfo),{},{uid:this._joinInfo.uid,stringUid:void 0}));i?(t=i.ap,vs(i),this._joinInfo.preload=!0):(t=await Ho(this._joinInfo,this._axiosCancelSource.token,this._config.httpRetryConfig||Ye,this.store),this._joinInfo.preload=!1),this._joinInfo&&(this._joinInfo.apResponse=t.gatewayInfo.res,this._joinInfo.gatewayAddrs=t.gatewayInfo.gatewayAddrs,this._joinInfo.uni_lbs_ip=t.gatewayInfo.uni_lbs_ip);const n=[];t.gatewayInfo.gatewayAddrs.forEach((e=>{let{address:t}=e;const[i,o]=t.split(":");this._joinInfo&&this._joinInfo.proxyServer?n.push({proxy:this._joinInfo.proxyServer,host:i,port:o}):n.push({host:i,port:o})})),e(n)}catch(e){t(e)}})),this._gateway.on(ji.NETWORK_QUALITY,(e=>{"normal"===this._networkQualitySensitivity&&this.safeEmit(pt.NETWORK_QUALITY,e)})),this._gateway.on(ji.STREAM_TYPE_CHANGE,((e,t)=>{this.safeEmit(pt.STREAM_TYPE_CHANGED,e,t);j.reportApiInvoke(this._sessionId,{name:We.STREAM_TYPE_CHANGE,options:[e,t],tag:He.TRACER}).onSuccess(JSON.stringify({uid:e,streamType:t}))})),this._gateway.isPreSub=()=>"isPreSub"in this._p2pChannel&&this._p2pChannel.isPreSub(),this._gateway.isPreallocation=()=>"isPreallocation"in this._p2pChannel&&this._p2pChannel.isPreallocation(),this._gateway.on(ji.IS_P2P_DISCONNECTED,(e=>{this._p2pChannel.isP2PDisconnected()?e(!0):this._p2pChannel.hasLocalMedia()||this._p2pChannel.hasRemoteMedia()?e(!1):e(!0)})),this._gateway.on(ji.REQUEST_P2P_CONNECTION_PARAMS,(async(e,t,i)=>{try{let i=await this._p2pChannel.getEstablishParams();i&&"isPreallocation"in this._p2pChannel&&this._p2pChannel.isPreallocation()||(i=await this._p2pChannel.startP2PConnection(e)),t(i)}catch(e){i(e)}})),this._gateway.on(ji.JOIN_RESPONSE,((e,t)=>{if(this.store.useP2P)return;let i;this._joinResponse=e,e.attributes?i=e.attributes.userAttributes.preSubSsrcs:B.debug("no attributes in joinResponse");const n=Jn(e.ortc,t,i);this._p2pChannel.connect(n)})),this._gateway.on(ji.PRE_CONNECT_PC,(async e=>{const{candidates:t,fingerprint:i,turnServer:n}=e;if(this._joinInfo&&t.length>0&&!this._p2pChannel.isPlanB){const{cert:e,cid:a}=this._joinInfo.apResponse,s="".concat(a,"_").concat(e);if(s.length<4||s.length>256)return;await this._p2pChannel.startP2PConnection({turnServer:n,cloudProxyServer:this._joinInfo.cloudProxyServer,isPreallocation:!0});try{var o;await this._p2pChannel.connect({iceParameters:{iceUfrag:"".concat(a,"_").concat(e),icePwd:"".concat(a,"_").concat(e)},dtlsParameters:{fingerprints:[{hashFunction:"sha-256",fingerprint:null!==(o=ne("FINGERPRINT"))&&void 0!==o?o:i}]},candidates:t,rtpCapabilities:{send:{audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]},recv:{audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]}},setup:"active",cname:"o/i14u9pJrxRKAsu",preallocation:!0})}catch(e){e.code&&e.code===Z.EXCHANGE_SDP_FAILED&&await this._p2pChannel.startP2PConnection({turnServer:n,cloudProxyServer:this._joinInfo.cloudProxyServer},!0)}}}))}_handleGatewaySignalEvents(){this._gateway.signal.on(wi.ON_USER_ONLINE,this._handleUserOnline),this._gateway.signal.on(wi.ON_USER_OFFLINE,this._handleUserOffline),this._gateway.signal.on(wi.ON_ADD_AUDIO_STREAM,(e=>this._handleAddAudioOrVideoStream("audio",e.uid,e.ssrcId,e.cname,e.pt,e.uint_id,e.ortc))),this._gateway.signal.on(wi.ON_ADD_VIDEO_STREAM,(e=>this._handleAddAudioOrVideoStream("video",e.uid,e.ssrcId,e.cname,e.pt,e.uint_id,e.ortc,e.rtxSsrcId))),this._gateway.signal.on(wi.ON_REMOTE_DATASTREAM_UPDATE,(e=>{this._handleUpdateDataChannel(e)})),this._gateway.signal.on(wi.ON_REMOTE_FULL_DATASTREAM_INFO,(e=>{this._handleUpdateDataChannel({added:e.datastreams||[],deleted:[]},!0)})),this._gateway.signal.on(wi.ON_REMOVE_STREAM,this._handleRemoveStream),this._gateway.signal.on(wi.ON_P2P_LOST,this._handleP2PLost),this._gateway.signal.on(wi.MUTE_AUDIO,(e=>this._handleMuteStream(e.uid,Zi.AUDIO,!0))),this._gateway.signal.on(wi.UNMUTE_AUDIO,(e=>this._handleMuteStream(e.uid,Zi.AUDIO,!1))),this._gateway.signal.on(wi.MUTE_VIDEO,(e=>this._handleMuteStream(e.uid,Zi.VIDEO,!0))),this._gateway.signal.on(wi.UNMUTE_VIDEO,(e=>this._handleMuteStream(e.uid,Zi.VIDEO,!1))),this._gateway.signal.on(wi.RECEIVE_METADATA,(e=>{const t=Ct(e.metadata);this.safeEmit(pt.RECEIVE_METADATA,e.uid,t)})),this._gateway.signal.on(wi.ON_DATA_STREAM,(async e=>{if(!e)return;let t=Ct(e.payload);if(this._encryptDataStream&&this._encryptDataStreamIv&&this._encryptDataStreamKey&&window.crypto.subtle&&["aes-128-gcm2","aes-256-gcm2"].includes(this._encryptionMode)){if(e.payload.length<jt)throw new F(Z.UNEXPECTED_RESPONSE,"payload length ".concat(e.payload.length," is less than header length ").concat(jt));t=await Gt(this._encryptDataStreamIv,this._encryptDataStreamKey,t)}let i=0;if(e.ordered||e.syncWithAudio){const t=this._p2pChannel.getStats(),n=this.remoteUsers.find((t=>t.uid===e.uid)),o=null==t?void 0:t.audioRecv.find((e=>e.ssrc===(null==n?void 0:n._audioSSRC)));i=null==o?void 0:o.jitterBufferMs}(null==i||Number.isNaN(i))&&(i=0),os(mi(mi({},e),{},{payload:t}),i,{id:this._clientId,onStreamMessage:"function"==typeof this.onStreamMessage?this.onStreamMessage.bind(this):void 0,safeEmit:this.safeEmit.bind(this)})})),this._gateway.signal.on(wi.ON_CRYPT_ERROR,(()=>{St((()=>{B.warning("[".concat(this._clientId,"] on crypt error")),this.safeEmit(pt.CRYPT_ERROR)}),this._sessionId)})),this._gateway.signal.on(wi.ON_TOKEN_PRIVILEGE_WILL_EXPIRE,this._handleTokenWillExpire),this._gateway.signal.on(wi.ON_TOKEN_PRIVILEGE_DID_EXPIRE,(()=>{B.warning("[".concat(this._clientId,"] received message onTokenPrivilegeDidExpire, please get new token and join again")),this._gateway.leave(!0,me.TOKEN_EXPIRE),this.safeEmit(pt.ON_TOKEN_PRIVILEGE_DID_EXPIRE),this._reset()})),this._gateway.signal.on(wi.ON_STREAM_FALLBACK_UPDATE,(e=>{B.debug("[".concat(this._clientId,"] stream fallback peerId: ").concat(e.stream_id,", attr: ").concat(e.stream_type)),this.safeEmit(pt.STREAM_FALLBACK,e.stream_id,1===e.stream_type?"fallback":"recover")})),this._gateway.signal.on(wi.ON_PUBLISH_STREAM,(e=>{this.uid===this._uid&&(this._p2pChannel.reportPublishEvent(!0,null,void 0,!1,JSON.stringify({proxy:e.proxy})),B.info("[".concat(this._clientId,"] on publish stream, ").concat(JSON.stringify(e))))})),this._gateway.signal.on(wi.ENABLE_LOCAL_VIDEO,(e=>{this._handleSetStreamLocalEnable("video",e.uid,!0)})),this._gateway.signal.on(wi.DISABLE_LOCAL_VIDEO,(e=>{this._handleSetStreamLocalEnable("video",e.uid,!1)})),this._gateway.signal.on(yi.REQUEST_TIMEOUT,((e,t)=>{if(this._joinInfo)switch(e){case Ni.PUBLISH:{if(!t)return;const e=t.ortc;if(e){var i,n;const o=e.some((e=>{let{stream_type:t}=e;return t===Fi.Audio})),a=e.some((e=>{let{stream_type:t}=e;return t!==Fi.Audio})),s=e.some((e=>{let{stream_type:t}=e;return t===Fi.Screen||t===Fi.ScreenLow}));"offer"===t.state&&j.publish(this._joinInfo.sid,{eventElapse:ta.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:!1,ec:Z.TIMEOUT,audio:o,video:a,p2pid:t.p2p_id,publishRequestid:this.store.pubId,screenshare:s,audioName:o?null===(i=e.find((e=>{let{stream_type:t}=e;return t===Fi.Audio})))||void 0===i||null===(i=i.ssrcs[0])||void 0===i?void 0:i.ssrcId.toString():void 0,videoName:a?null===(n=e.find((e=>{let{stream_type:t}=e;return t!==Fi.Audio})))||void 0===n||null===(n=n.ssrcs[0])||void 0===n?void 0:n.ssrcId.toString():void 0})}break}case Ni.SUBSCRIBE:t&&j.subscribe(this._joinInfo.sid,{succ:!1,ec:Z.TIMEOUT,audio:t.stream_type===Zi.AUDIO,video:t.stream_type===Zi.VIDEO,peerid:t.stream_id,subscribeRequestid:t.ssrcId,p2pid:this.store.p2pId,eventElapse:ta.measureFromSubscribeStart(this.store.clientId,t.ssrcId),preSsrc:this._p2pChannel.isPreSubScribe(t.ssrcId)})}})),this._gateway.signal.on(wi.ON_P2P_OK,(e=>{this.uid,this._uid})),this._gateway.signal.on(wi.ON_PUBLISHED_USER_LIST,(e=>{if(null==e||!e.users)return;ne("BLOCK_LOCAL_CLIENT")&&(e.users=e.users.filter((e=>!ri(e.string_id||e.stream_id,this.channelName))));const t=[],i=[];for(const n of e.users){let e=this._users.find((e=>e._uintid===n.stream_id));e?e._trust_in_room_=!0:(e=new aa(n.string_id||n.stream_id,n.stream_id),this._users.push(e),this.store.firstVideoFrameDecoded(e.uid,{userJoinNotify:Date.now()}),0===this.getListeners(pt.PUBLISHED_USER_LIST).length&&(B.debug("[".concat(this._clientId,"] user online"),n.stream_id),this.safeEmit(pt.USER_JOINED,e)));const o=Wi.Audio&n.stream_type,a=(Wi.Video|Wi.LwoVideo)&n.stream_type,s=0!=(65280&n.stream_type),r=o&&e.hasAudio,c=a&&e.hasVideo;a&&(e._trust_video_stream_added_state_=!0,e._video_added_=!0,e._videoSSRC=n.video_ssrc,e._rtxSsrcId=n.video_rtx),o&&(e._trust_audio_stream_added_state_=!0,e._audio_added_=!0,e._audioSSRC=n.audio_ssrc),o&&!r&&0===this.getListeners(pt.PUBLISHED_USER_LIST).length&&(B.info("[".concat(this._clientId,"] remote user ").concat(e.uid," published audio")),this.safeEmit(pt.USER_PUBLISHED,e,"audio")),a&&!c&&0===this.getListeners(pt.PUBLISHED_USER_LIST).length&&(B.info("[".concat(this._clientId,"] remote user ").concat(e.uid," published video")),this.safeEmit(pt.USER_PUBLISHED,e,"video")),(o&&!r||a&&!c||s)&&t.push(e),a&&this._p2pChannel.hasPendingRemoteMedia(e,"video")&&i.push({user:e,mediaType:"video"}),o&&this._p2pChannel.hasPendingRemoteMedia(e,"audio")&&i.push({user:e,mediaType:"audio"})}i.length>0&&(B.debug("[".concat(this._clientId,"] RE massSubscribe after reconnect ").concat(i.map((e=>"user: ".concat(e.user.uid,", mediaType: ").concat(e.mediaType))).join("; ")," ")),this.massSubscribe(i).catch((e=>{B.error("[".concat(this._clientId,"] mass resubscribe error"),e.toString())}))),this.getListeners(pt.PUBLISHED_USER_LIST).length>0?ne("ENABLE_DATASTREAM_2")?this._pendingPublishedUsers=t:(B.info("[".concat(this._clientId,"] client emit user-list event, users: ").concat(t.map((e=>e.uid)).join(", "))),this.safeEmit(pt.PUBLISHED_USER_LIST,t)):B.info("[".concat(this._clientId,"] client not emit user-list event case there is no user-list listener, users: ").concat(t.map((e=>e.uid)).join(", ")))})),this._gateway.signal.on(wi.ON_RTP_CAPABILITY_CHANGE,(e=>{const{video_codec:t}=e;this._p2pChannel instanceof za&&this._p2pChannel.updateRemoteRTPCapabilities(t.map((e=>e.toLowerCase())).filter((e=>Object.keys(et).includes(e))))}))}_handleP2PEvents(){this._gateway.signal.on(wi.ON_USER_OFFLINE,(()=>{this._p2pChannel.disconnectForReconnect()})),this._gateway.signal.on(hn.PUBLISH,((e,t,i)=>{const{uid:n}=e;e.forEach((e=>{const{kind:o,ssrcs:a,mid:s,isMuted:r}=e;this._handleP2PAddAudioOrVideoStream(o,n,a[0].ssrcId,s);const c=this._users.find((e=>e.uid===n));return c&&this.store.useP2P?this._p2pChannel.mockSubscribe(c,o,a[0].ssrcId,s).then((()=>{t()})).catch(i):t(),this._handleMuteStream(n,o,!!r)}))})),this._gateway.signal.on(hn.CALL,(async(e,t,i)=>{if(this.store.useP2P)try{var n;t(await this._p2pChannel.startP2P({turnServer:null===(n=this._joinInfo)||void 0===n?void 0:n.turnServer},e))}catch(e){i(e)}})),this._gateway.signal.on(yi.P2P_CONNECTION,(async e=>{this.store.useP2P&&(await this._p2pChannel).p2pConnect(e)})),this._gateway.signal.on(hn.UNPUBLISH,(async(e,t,i)=>{if(this.store.useP2P){const{unpubMsg:n,uid:o}=e,a=this._users.find((e=>e.uid===o));if(!a)return B.warning("[".concat(this._clientId,"] can not find remote user, ignore mute event, uid: ").concat(o)),void t();try{n.forEach((async e=>{let{stream_type:t}=e;const i=t===Fi.Audio?Zi.AUDIO:Zi.VIDEO;await this._p2pChannel.unsubscribe(a,i),this._handleMuteStream(o,i,!0)})),t()}catch(e){i(e)}}})),this._gateway.signal.on(hn.CONTROL,(async(e,t)=>{const{action:i}=e;switch(i){case _n.MUTE_LOCAL_VIDEO:this._handleMuteStream(t,Zi.VIDEO,!0);break;case _n.MUTE_LOCAL_AUDIO:this._handleMuteStream(t,Zi.AUDIO,!0);break;case _n.UNMUTE_LOCAL_VIDEO:this._handleP2PAddAudioOrVideoStream("video",t),this._handleMuteStream(t,Zi.VIDEO,!1);break;case _n.UNMUTE_LOCAL_AUDIO:this._handleP2PAddAudioOrVideoStream("audio",t),this._handleMuteStream(t,Zi.AUDIO,!1)}})),this._gateway.signal.on(hn.RESTART_ICE,(async(e,t,i)=>{if(this.store.useP2P)try{const{direction:i,iceParameter:n}=e;if(i!==Oi.SEND_ONLY||n){t(await this._p2pChannel.restartICE(i,n))}else this._p2pChannel.handleDisconnect(i),t()}catch(e){i(e)}})),this._gateway.signal.on(hn.CANDIDATE,(e=>{if(this.store.useP2P){const{candidate:t,direction:i}=e;this._p2pChannel.addRemoteCandidate(t,i)}})),this._p2pChannel.on(an.RequestP2PRestartICE,(async(e,t,i)=>{try{const{direction:i}=e;t(await this._gateway.sendExtensionMessage(hn.RESTART_ICE,e,i===Oi.SEND_ONLY))}catch(e){i(e)}})),this._p2pChannel.on(an.LocalCandidate,(e=>{this._gateway.sendExtensionMessage(hn.CANDIDATE,JSON.stringify(e),!0)})),this._p2pChannel.on(an.RequestP2PMuteLocal,(async(e,t,i)=>{try{await this._gateway.sendExtensionMessage(hn.CONTROL,e,!0),t()}catch(e){i(e)}})),this._p2pChannel.on(an.RequestP2PUnmuteRemote,(async(e,t,i)=>{if(this._joinInfo)try{await this._gateway.unmuteRemote(e,this._joinInfo.stringUid||this._joinInfo.uid),t()}catch(e){e.code===Z.DISCONNECT_P2P?t():i(e)}else t()})),this._p2pChannel.on(an.RequestP2PMuteRemote,(async(e,t,i)=>{if(this._joinInfo)try{await this._gateway.muteRemote(e,this._joinInfo.stringUid||this._joinInfo.uid),t()}catch(e){e.code===Z.DISCONNECT_P2P?t():i(e)}else t()})),this._p2pChannel.on(an.StateChange,((e,t)=>{t===on.Connected&&this._p2pChannel.republish()}))}_handleP2PChannelEvents(){this._p2pChannel.on(an.PeerConnectionStateChange,(e=>{const t=this._peerConnectionState;e!==t&&(this.safeEmit(pt.PEERCONNECTION_STATE_CHANGE,e,t),this._peerConnectionState=e)})),this._p2pChannel.on(an.RequestMuteLocal,(async(e,t,i)=>{if(this._joinInfo)try{await this._gateway.muteLocal(e,this._joinInfo.stringUid||this._joinInfo.uid),t()}catch(e){e.code===Z.DISCONNECT_P2P?t():i(e)}else t()})),this._p2pChannel.on(an.RequestUnmuteLocal,(async(e,t,i)=>{if(this._joinInfo)try{await this._gateway.unmuteLocal(e,this._joinInfo.stringUid||this._joinInfo.uid),t()}catch(e){e.code===Z.DISCONNECT_P2P?t():i(e)}else t()})),this._p2pChannel.on(an.RequestRePublish,((e,t,i)=>{this.publish(e,!1).then(t).catch(i)})),this._p2pChannel.on(an.RequestRePublishDataChannel,((e,t,i)=>{Promise.all(e.map((async e=>{const t=await this._p2pChannel.publishDataChannel([e]);try{t.forEach((e=>{this._uid&&this._gateway.publishDataChannel(this._uid,e,!0)}))}catch(e){if(e.code!==Z.DISCONNECT_P2P)throw e}}))).then(t).catch(i)})),this._p2pChannel.on(an.RequestReSubscribe,(async(e,t,i)=>{try{for(const{user:t,kind:i}of e)i===Zi.VIDEO?await this.subscribe(t,"video"):await this.subscribe(t,"audio");t()}catch(e){i(e)}})),this._p2pChannel.on(an.RequestUpload,((e,t)=>{this._gateway.upload(e,t)})),this._p2pChannel.on(an.RequestUploadStats,(e=>{this._gateway.uploadWRTCStats(e)})),this._p2pChannel.on(an.MediaReconnectStart,(e=>{this.safeEmit(pt.MEDIA_RECONNECT_START,e)})),this._p2pChannel.on(an.MediaReconnectEnd,(e=>{this.safeEmit(pt.MEDIA_RECONNECT_END,e)})),this._p2pChannel.on(an.NeedSignalRTT,(e=>{e(this._gateway.getSignalRTT())})),this._p2pChannel.on(an.RequestRestartICE,(async e=>{if(this.store.useP2P)return;const t=await this._p2pChannel.restartICE(e),i=await t.next();if(i.done)return;const n=i.value;let o;try{o=await this._gateway.restartICE({iceParameters:n})}catch(e){return void t.throw(e)}const{iceParameters:a}=function(e){const t=e.iceParameters;return{iceParameters:{iceUfrag:t.iceUfrag,icePwd:t.icePwd}}}(o);await t.next({remoteIceParameters:a})})),this._p2pChannel.on(an.RequestReconnect,(async()=>{this._gateway.reconnect()})),this._p2pChannel.on(an.RequestReconnectPC,(async()=>{var e;const{iceParameters:t,dtlsParameters:i,rtpCapabilities:n}=await this._p2pChannel.startP2PConnection({turnServer:null===(e=this._joinInfo)||void 0===e?void 0:e.turnServer}),{gatewayEstablishParams:o,gatewayAddress:a}=await this._gateway.reconnectPC({iceParameters:t,dtlsParameters:i,rtpCapabilities:n}),s=Jn(o,a);await this._p2pChannel.connect(s),await this._p2pChannel.republish(),await this._p2pChannel.reSubscribe()})),this._p2pChannel.on(an.RequestUnpublishForReconnectPC,(async(e,t,i)=>{this._joinInfo&&void 0!==this._uid?(await this._gateway.unpublish(e,this._uid),t()):i()})),this._p2pChannel.on(an.P2PLost,(()=>{this.safeEmit(pt.P2P_LOST,this.store.uid)})),this._p2pChannel.on(an.UpdateVideoEncoder,(e=>{e._encoderConfig&&this._gateway.setVideoProfile(e._encoderConfig)})),this._p2pChannel.on(an.ConnectionTypeChange,(e=>{this.safeEmit(pt.IS_USING_CLOUD_PROXY,e)})),this._p2pChannel.on(an.RequestLowStreamParameter,(e=>{e(this._lowStreamParameter||{width:160,height:120,framerate:15,bitrate:50})})),this._p2pChannel.on(an.QueryClientConnectionState,(e=>{e(this.connectionState)})),this._p2pChannel.on(an.AudioMetadata,(e=>{this.safeEmit(pt.AUDIO_METADATA,e)})),this._p2pChannel.on(an.AudioPts,(e=>{this.safeEmit(pt.AUDIO_PTS,Number(e))}))}getKeyMetrics(){return this.store.keyMetrics}async enableContentInspect(e){if(!this._joinInfo||"CONNECTED"!==this.connectionState)throw new F(Z.INVALID_OPERATION,"[".concat(this._clientId,"] can not create content inspect, please join channel first"));if(this._inspect)throw new F(Z.INVALID_OPERATION,"[".concat(this._clientId,"] Inspect content service already in connecting/connected state"));try{const i=(t={config:e},po("ContentInspect").create(t));this._inspect=i,this.handleVideoInspectEvents(i);const{appId:n,cname:o,sid:a,token:s,uid:r,cid:c,vid:d}=this._joinInfo;await i.init({appId:n,areaCode:"",cname:o,sid:a,token:s,uid:r,cid:c,vid:d?Number(d):0},Ye)}catch(e){throw Array.isArray(e)?e[0]:e}var t}handleVideoInspectEvents(e){e.on(rn.CONNECTION_STATE_CHANGE,((t,i)=>{if(this.safeEmit(pt.CONTENT_INSPECT_CONNECTION_STATE_CHANGE,t,i),i===sn.CONNECTED){if("CONNECTED"!==this.connectionState)return void this.safeEmit(pt.CONTENT_INSPECT_ERROR,new F(Z.OPERATION_ABORTED,"Content inspect was cancelled because it left the channel"));e.inspectImage()}})),e.on(rn.INSPECT_RESULT,((e,t)=>{var i;if((null==t?void 0:t.code)===Z.INVALID_OPERATION&&"DISCONNECTED"===this.connectionState)return B.debug("Stop inspect content because that has left channel"),null==this||null===(i=this._inspect)||void 0===i||i.close(),void(this._inspect=void 0);this.safeEmit(pt.CONTENT_INSPECT_RESULT,e,t)})),e.on(rn.CLIENT_LOCAL_VIDEO_TRACK,(e=>{e(this.localTracks.filter((e=>"video"===e.trackMediaType))[0])}))}async disableContentInspect(){if(!this._inspect)throw new F(Z.INVALID_OPERATION,"[".concat(this._clientId,"] inspectVideoContent not started"));try{this._inspect.close(),this._inspect=void 0}catch(e){throw Array.isArray(e)?e[0]:e}}async setImageModeration(e,t){if(Dt(e,"enabled"),e){if(!t)throw new F(Z.INVALID_PARAMS,"config is required");if(function(e){if(It(e.interval,"interval",1e3,1/0),e&&e.extraInfo&&e.extraInfo.length>1024)throw new F(G.INVALID_PARAMS,"config.extraInfo length cannot exceed 1024 bytes");if(e&&e.vendor&&e.vendor.length>1024)throw new F(G.INVALID_PARAMS,"config.vendor length cannot exceed 1024 bytes")}(t),!this._joinInfo)throw new F(Z.INVALID_OPERATION,"can not create image moderation, please join channel first");try{if(this._moderation)this._moderation.updateConfig(t);else{const e=(i={config:t},po("ImageModeration").create(i));this._moderation=e,this.handleImageModerationEvents(e);const{appId:n,cname:o,sid:a,token:s,uid:r,cid:c,vid:d}=this._joinInfo;await e.init({appId:n,areaCode:"",cname:o,sid:a,token:s,uid:r,cid:c,vid:d?Number(d):0},Ye)}}catch(e){throw Array.isArray(e)?e[0]:e}}else{var i;if(!this._moderation)throw new F(Z.INVALID_OPERATION,"[".concat(this._clientId,"] image moderation not started"));try{this._moderation.close(),this._moderation.removeAllListeners(),this._moderation=void 0}catch(e){throw Array.isArray(e)?e[0]:e}}}handleImageModerationEvents(e){e.on(un.CONNECTION_STATE_CHANGE,((t,i)=>{if(this.safeEmit(pt.IMAGE_MODERATION_CONNECTION_STATE_CHANGE,t,i),t===ln.CONNECTED){if("CONNECTED"!==this.connectionState)throw this.setImageModeration(!1),new F(Z.OPERATION_ABORTED,"Image moderation was cancelled because it left the channel");e.inspectImage()}})),e.on(un.CLIENT_LOCAL_VIDEO_TRACK,(e=>{e(this.localTracks.filter((e=>"video"===e.trackMediaType))[0])}))}setP2PTransport(e){if(Wt(e),"p2p"!==this.mode)throw new F(Z.INVALID_OPERATION,"only p2p mode can set p2pTransport");this.store.p2pTransport=e,B.info("[".concat(this._clientId,"] set client p2pTransport to ").concat(e))}getJoinChannelServiceRecords(){return B.debug("getJoinChannelServiceRecords"),this.store.joinChannelServiceRecords}async setPublishAudioFilterEnabled(e){Dt(e,"enabled"),Fe("ENABLE_PUBLISH_AUDIO_FILTER",e),this._joinInfo&&await this._gateway.setPublishAudioFilterEnabled(e)}_handleResetAddStream(e,t){switch(t){case"audio":e._audio_added_=!1,e._trust_audio_stream_added_state_=!0;break;case"video":e._video_added_=!1,e._trust_video_stream_added_state_=!0}}}).prototype,"leave",[Ls],Object.getOwnPropertyDescriptor(Cr.prototype,"leave"),Cr.prototype),li(Cr.prototype,"publish",[ks],Object.getOwnPropertyDescriptor(Cr.prototype,"publish"),Cr.prototype),li(Cr.prototype,"unpublish",[Us],Object.getOwnPropertyDescriptor(Cr.prototype,"unpublish"),Cr.prototype),li(Cr.prototype,"subscribe",[Ms],Object.getOwnPropertyDescriptor(Cr.prototype,"subscribe"),Cr.prototype),li(Cr.prototype,"presubscribe",[Vs],Object.getOwnPropertyDescriptor(Cr.prototype,"presubscribe"),Cr.prototype),li(Cr.prototype,"massSubscribe",[xs],Object.getOwnPropertyDescriptor(Cr.prototype,"massSubscribe"),Cr.prototype),li(Cr.prototype,"unsubscribe",[Bs],Object.getOwnPropertyDescriptor(Cr.prototype,"unsubscribe"),Cr.prototype),li(Cr.prototype,"massUnsubscribe",[Fs],Object.getOwnPropertyDescriptor(Cr.prototype,"massUnsubscribe"),Cr.prototype),li(Cr.prototype,"setLowStreamParameter",[js],Object.getOwnPropertyDescriptor(Cr.prototype,"setLowStreamParameter"),Cr.prototype),li(Cr.prototype,"enableDualStream",[Gs],Object.getOwnPropertyDescriptor(Cr.prototype,"enableDualStream"),Cr.prototype),li(Cr.prototype,"disableDualStream",[Ws],Object.getOwnPropertyDescriptor(Cr.prototype,"disableDualStream"),Cr.prototype),li(Cr.prototype,"setClientRole",[Hs],Object.getOwnPropertyDescriptor(Cr.prototype,"setClientRole"),Cr.prototype),li(Cr.prototype,"_setClientRoleOptions",[Ks],Object.getOwnPropertyDescriptor(Cr.prototype,"_setClientRoleOptions"),Cr.prototype),li(Cr.prototype,"setProxyServer",[Ys],Object.getOwnPropertyDescriptor(Cr.prototype,"setProxyServer"),Cr.prototype),li(Cr.prototype,"setTurnServer",[qs],Object.getOwnPropertyDescriptor(Cr.prototype,"setTurnServer"),Cr.prototype),li(Cr.prototype,"setLicense",[Xs],Object.getOwnPropertyDescriptor(Cr.prototype,"setLicense"),Cr.prototype),li(Cr.prototype,"startProxyServer",[Js],Object.getOwnPropertyDescriptor(Cr.prototype,"startProxyServer"),Cr.prototype),li(Cr.prototype,"stopProxyServer",[zs],Object.getOwnPropertyDescriptor(Cr.prototype,"stopProxyServer"),Cr.prototype),li(Cr.prototype,"setLocalAccessPointsV2",[Qs],Object.getOwnPropertyDescriptor(Cr.prototype,"setLocalAccessPointsV2"),Cr.prototype),li(Cr.prototype,"setLocalAccessPoints",[Zs],Object.getOwnPropertyDescriptor(Cr.prototype,"setLocalAccessPoints"),Cr.prototype),li(Cr.prototype,"setRemoteDefaultVideoStreamType",[$s],Object.getOwnPropertyDescriptor(Cr.prototype,"setRemoteDefaultVideoStreamType"),Cr.prototype),li(Cr.prototype,"setRemoteVideoStreamType",[er],Object.getOwnPropertyDescriptor(Cr.prototype,"setRemoteVideoStreamType"),Cr.prototype),li(Cr.prototype,"setStreamFallbackOption",[tr],Object.getOwnPropertyDescriptor(Cr.prototype,"setStreamFallbackOption"),Cr.prototype),li(Cr.prototype,"setEncryptionConfig",[ir],Object.getOwnPropertyDescriptor(Cr.prototype,"setEncryptionConfig"),Cr.prototype),li(Cr.prototype,"renewToken",[nr],Object.getOwnPropertyDescriptor(Cr.prototype,"renewToken"),Cr.prototype),li(Cr.prototype,"enableAudioVolumeIndicator",[or],Object.getOwnPropertyDescriptor(Cr.prototype,"enableAudioVolumeIndicator"),Cr.prototype),li(Cr.prototype,"startLiveStreaming",[ar],Object.getOwnPropertyDescriptor(Cr.prototype,"startLiveStreaming"),Cr.prototype),li(Cr.prototype,"setLiveTranscoding",[sr],Object.getOwnPropertyDescriptor(Cr.prototype,"setLiveTranscoding"),Cr.prototype),li(Cr.prototype,"stopLiveStreaming",[rr],Object.getOwnPropertyDescriptor(Cr.prototype,"stopLiveStreaming"),Cr.prototype),li(Cr.prototype,"startChannelMediaRelay",[cr],Object.getOwnPropertyDescriptor(Cr.prototype,"startChannelMediaRelay"),Cr.prototype),li(Cr.prototype,"updateChannelMediaRelay",[dr],Object.getOwnPropertyDescriptor(Cr.prototype,"updateChannelMediaRelay"),Cr.prototype),li(Cr.prototype,"stopChannelMediaRelay",[lr],Object.getOwnPropertyDescriptor(Cr.prototype,"stopChannelMediaRelay"),Cr.prototype),li(Cr.prototype,"sendCustomReportMessage",[ur],Object.getOwnPropertyDescriptor(Cr.prototype,"sendCustomReportMessage"),Cr.prototype),li(Cr.prototype,"pickSVCLayer",[hr],Object.getOwnPropertyDescriptor(Cr.prototype,"pickSVCLayer"),Cr.prototype),li(Cr.prototype,"setRTMConfig",[_r],Object.getOwnPropertyDescriptor(Cr.prototype,"setRTMConfig"),Cr.prototype),li(Cr.prototype,"enableContentInspect",[pr],Object.getOwnPropertyDescriptor(Cr.prototype,"enableContentInspect"),Cr.prototype),li(Cr.prototype,"disableContentInspect",[Er],Object.getOwnPropertyDescriptor(Cr.prototype,"disableContentInspect"),Cr.prototype),li(Cr.prototype,"setImageModeration",[Sr],Object.getOwnPropertyDescriptor(Cr.prototype,"setImageModeration"),Cr.prototype),li(Cr.prototype,"setP2PTransport",[mr],Object.getOwnPropertyDescriptor(Cr.prototype,"setP2PTransport"),Cr.prototype),li(Cr.prototype,"getJoinChannelServiceRecords",[Rr],Object.getOwnPropertyDescriptor(Cr.prototype,"getJoinChannelServiceRecords"),Cr.prototype),li(Cr.prototype,"setPublishAudioFilterEnabled",[fr],Object.getOwnPropertyDescriptor(Cr.prototype,"setPublishAudioFilterEnabled"),Cr.prototype),Cr);function Ir(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{codec:"vp8",audioCodec:"opus",mode:"rtc"};const t=fe(5,"client-"),i=j.reportApiInvoke(null,{id:t,name:We.CREATE_CLIENT,options:[e],tag:He.TRACER});try{Ht(e)}catch(e){throw i.onError(e),e}return(nt(16,0,!0)||Ve(16,0,!0))&&("vp9"===e.codec&&(e.codec="vp8",B.debug("browser not support vp9, force use vp8")),Fe("UNSUPPORTED_VIDEO_CODEC",["vp9"])),void 0===e.audioCodec&&(e.audioCodec="opus"),i.onSuccess(),new Tr(mi(mi({forceWaitGatewayResponse:!0},e),{},{role:["rtc","p2p"].includes(e.mode)?"host":e.role||"audience"}),t)}async function Ar(){let e={audio:[],video:[]};try{let t=new RTCPeerConnection;const i=await async function(e){let t;return o().supportUnifiedPlan?(e.addTransceiver("video",{direction:"recvonly"}),e.addTransceiver("audio",{direction:"recvonly"}),t=(await e.createOffer()).sdp):t=(await e.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0})).sdp,t}(t);if(!i)return e;t.close(),t=null,e=function(e){const t={video:[],audio:[]};return e.match(/ VP8/i)&&t.video.push("VP8"),e.match(/ VP9/i)&&t.video.push("VP9"),e.match(/ AV1/i)&&t.video.push("AV1"),e.match(/ H264/i)&&t.video.push("H264"),e.match(/ H265/i)&&t.video.push("H265"),e.match(/ opus/i)&&t.audio.push("OPUS"),e.match(/ PCMU/i)&&t.audio.push("PCMU"),e.match(/ PCMA/i)&&t.audio.push("PCMA"),e.match(/ G722/i)&&t.audio.push("G722"),t}(i)}catch(e){throw new F(Z.CREATE_OFFER_FAILED,e.toString&&e.toString()).print()}return e}function gr(){const e=j.reportApiInvoke(null,{name:We.CHECK_SYSTEM_REQUIREMENTS,options:[],tag:He.TRACER});let t=!1;try{const e=window.RTCPeerConnection,i=navigator.mediaDevices&&navigator.mediaDevices.getUserMedia,n=window.WebSocket;t=!!(e&&i&&n),t&&ht()&&Kt(75)&&(new e).close()}catch(e){return B.error("check system requirement failed: ",e),!1}let i=!1;const n=Ne();n.name===be.CHROME&&Number(n.version)>=58&&(!Yt()||qt())&&(i=!0),(n.name===be.FIREFOX&&Number(n.version)>=56||n.name===be.OPERA&&Number(n.version)>=45||n.name===be.SAFARI&&Number(n.version)>=11||"WebKit"===n.name&&(gt()||Xt())&&n.osVersion&&Number(n.osVersion.split(".")[0])>=11||Jt()||zt())&&(i=!0),B.debug("checkSystemRequirements, api:",t,"browser",i);const o=t&&i;return e.onSuccess(o),o}class vr{constructor(e,t){this.id=0,this.element=void 0,this.peerPair=void 0,this.context=void 0,this.audioPlayerElement=void 0,this.audioTrack=void 0,vr.count+=1,this.id=vr.count,this.element=e,this.context=t}initPeers(){this.peerPair=[new RTCPeerConnection,new RTCPeerConnection],this.peerPair[1].ontrack=e=>{const t=document.createElement("audio");t.srcObject=new MediaStream([e.track]),t.play(),this.audioPlayerElement=t}}async switchSdp(){if(!this.peerPair)return;const e=async(e,t)=>{const i="offer"===t?await e.createOffer():await e.createAnswer();return await e.setLocalDescription(i),"complete"===e.iceGatheringState?e.localDescription:new Promise((t=>{e.onicegatheringstatechange=()=>{"complete"===e.iceGatheringState&&t(e.localDescription)}}))},t=async(e,t)=>await e.setRemoteDescription(t);try{const i=await e(this.peerPair[0],"offer");await t(this.peerPair[1],i);const n=await e(this.peerPair[1],"answer");await t(this.peerPair[0],n)}catch(e){throw new F(Z.LOCAL_AEC_ERROR,e.toString()).print()}}async getTracksFromMediaElement(e){if(this.audioTrack)return this.audioTrack;let t;try{e instanceof HTMLVideoElement&&(e.captureStream?e.captureStream():e.mozCaptureStream()),t=this.context.createMediaStreamDestination();this.context.createMediaElementSource(e).connect(t)}catch(e){throw new F(Z.LOCAL_AEC_ERROR,e.toString()).print()}if(!t){throw new F(Z.LOCAL_AEC_ERROR,"no dest node when local aec").print()}const i=t.stream.getAudioTracks()[0];return this.audioTrack=i,i}getElement(){return this.element}async startEchoCancellation(){this.context.resume(),this.peerPair&&this.close(),this.initPeers();const e=this.element,t=await this.getTracksFromMediaElement(e);this.peerPair&&this.peerPair[0].addTrack(t),await this.switchSdp()}close(){B.debug("close echo cancellation unit, id is",this.id),this.audioPlayerElement&&this.audioPlayerElement.pause(),this.peerPair&&this.peerPair.forEach((e=>{e.close()})),this.peerPair=void 0,this.audioPlayerElement=void 0}}var yr,Nr;vr.count=0;const br=window.AudioContext||window.webkitAudioContext;const wr=new(yr=K({report:j}),li((Nr=class{constructor(){this.units=[],this.context=void 0}processExternalMediaAEC(e){if(!this._doesEnvironmentNeedAEC())return B.debug("the system does not need to process local aec"),-1;this.context||(this.context=new br);let t=this.units.find((t=>t&&t.getElement()===e));return t||(t=new vr(e,this.context),this.units.push(t)),t.startEchoCancellation(),B.debug("start processing local audio echo cancellation, id is",t.id),t.id}_doesEnvironmentNeedAEC(){return Ne().name!==be.SAFARI}}).prototype,"processExternalMediaAEC",[yr],Object.getOwnPropertyDescriptor(Nr.prototype,"processExternalMediaAEC"),Nr.prototype),Nr);const Or=window||document;function Dr(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(!Or)return;const i=Hr._cspEventHandlerPointer;if(i&&t)return void console.error(i,t);const n=e=>{if(!(e&&e.blockedURI&&(Hr.onSecurityPolicyViolation||Hr.getListeners(dn.SECURITY_POLICY_VIOLATION).length>0)))return;const t=e.blockedURI;ne("CSP_DETECTED_HOSTNAME_LIST").some((e=>t.includes(e)))&&(Hr.onSecurityPolicyViolation&&"function"==typeof Hr.onSecurityPolicyViolation&&Hr.onSecurityPolicyViolation(e),Hr.getListeners(dn.SECURITY_POLICY_VIOLATION).length>0&&Hr.safeEmit(dn.SECURITY_POLICY_VIOLATION,e))};i&&Or.removeEventListener("securitypolicyviolation",i),(t||e&&"function"==typeof e||Hr.getListeners(dn.SECURITY_POLICY_VIOLATION).length>0)&&Or.addEventListener("securitypolicyviolation",n),Hr._cspEventHandlerPointer=n}function Pr(e){return k.enumerateDevices(!0,!0,e)}function Lr(e){return k.getRecordingDevices(e)}function kr(e){return k.getCamerasDevices(e)}function Ur(e){return k.getSpeakers(e)}function Mr(){return new na}function Vr(e){if(B.debug("setAppType: ".concat(e)),!(Number.isInteger(e)&&e>=0))throw B.debug("Invalid appType"),new F(Z.INVALID_PARAMS,"invalid app type",e);Fe("APP_TYPE",Math.floor(e))}function xr(e){B.setLogLevel(e)}function Br(){ne("USE_NEW_LOG")?Fe("UPLOAD_LOG",!0):B.enableLogUpload()}function Fr(){ne("USE_NEW_LOG")?Fe("UPLOAD_LOG",!1):B.disableLogUpload()}function jr(e){wr.processExternalMediaAEC(e)}function Gr(e){e.forEach((e=>{const t=e;t.__registered__=!0,t.logger.hookLog=B.extLog,t.reporter.hookApiInvoke=j.extApiInvoke,t.parameters&&Object.keys(t.parameters).forEach((e=>{t.parameters[e]=ne(e)}))}))}function Wr(){A.autoResumeAfterInterruption(!0)}qe(),Fe("PROCESS_ID",Qt()),function(){let e;try{e=window.localStorage.getItem("websdk_ng_global_parameter")}catch(e){return void B.error("Error loading sdk config",e.message)}if(e)try{const t=JSON.parse(window.atob(e)),i=Date.now();B.debug("Loading global parameters from cache",t),Object.keys(t).forEach((e=>{if(Object.prototype.hasOwnProperty.call(q,e)){const{value:n,expires:o}=t[e];if(o&&o<=i)return;X[e]=n,q[e]=n}}))}catch(t){B.error("Error loading mutableParamsCache: ".concat(e),t.message)}}(),Array.isArray(X.AREAS)&&X.AREAS.length>0&&Oo(X.AREAS,!0);const Hr=function(e){const t=new ie,i=e,n={getListeners:t.getListeners.bind(t),on:(e,i)=>(function(e,t){e===dn.SECURITY_POLICY_VIOLATION&&Dr(t,!0)}(e,i),t.on.bind(t)(e,i)),addListener:t.addListener.bind(t),once:t.once.bind(t),off:t.off.bind(t),removeAllListeners:t.removeAllListeners.bind(t),emit:t.emit.bind(t),safeEmit:t.safeEmit.bind(t)};return mi(mi({},i),n)}({});function Kr(e){L.onAudioAutoplayFailed=e}function Yr(e){L.onAutoplayFailed=e}function qr(e){Hr.onSecurityPolicyViolation=e}function Xr(e){Hr.onCameraChanged=e}function Jr(e){Hr.onMicrophoneChanged=e}function zr(e){Hr.onAudioContextStateChanged=e}Object.defineProperties(Hr,{onAudioAutoplayFailed:{get:()=>L.onAudioAutoplayFailed,set:Kr},onAutoplayFailed:{get:()=>L.onAutoplayFailed,set:Yr},_onSecurityPolicyViolation:{value:void 0,writable:!0},_cspEventHandlerPointer:{value:void 0,writable:!0},onSecurityPolicyViolation:{get:()=>Hr._onSecurityPolicyViolation,set(e){Hr._onSecurityPolicyViolation=e,Dr(e)}},__CLIENT_LIST__:{get:()=>ne("SHOW_GLOBAL_CLIENT_LIST")?ai:[]}}),Hr.use=e=>(function(e){(!(arguments.length>1&&void 0!==arguments[1])||arguments[1])&&B.debug("install service ".concat(e.name)),_o[e.name]=e}(e),Hr),k.on(U.CAMERA_DEVICE_CHANGED,(e=>{B.info("camera device changed",JSON.stringify(e)),Hr.onCameraChanged&&Hr.onCameraChanged(e),Hr.safeEmit(dn.CAMERA_CHANGED,e)})),k.on(U.RECORDING_DEVICE_CHANGED,(e=>{B.info("microphone device changed",JSON.stringify(e)),Hr.onMicrophoneChanged&&Hr.onMicrophoneChanged(e),Hr.safeEmit(dn.MICROPHONE_CHANGED,e)})),k.on(U.PLAYOUT_DEVICE_CHANGED,(e=>{B.debug("playout device changed",JSON.stringify(e)),Hr.onPlaybackDeviceChanged&&Hr.onPlaybackDeviceChanged(e),Hr.safeEmit(dn.PLAYBACK_DEVICE_CHANGED,e)})),A.onAutoplayFailed=()=>{B.info("detect audio element autoplay failed"),L.onAudioAutoplayFailed&&L.onAudioAutoplayFailed()},M.on("autoplay-failed",(()=>{B.info("detect webaudio autoplay failed"),L.onAudioAutoplayFailed&&L.onAudioAutoplayFailed(),Hr.safeEmit(dn.AUTOPLAY_FAILED)})),M.on(V.STATE_CHANGE,((e,t)=>{B.info("audio context state changed: ".concat(t," => ").concat(e)),Hr.onAudioContextStateChanged&&Hr.onAudioContextStateChanged(e,t),Hr.safeEmit(dn.AUDIO_CONTEXT_STATE_CHANGED,e,t)})),window&&(window.__ARTC__={ESM_BUNDLER:true,ESM:false,UMD:false,DEV:false,AgoraRTC:Hr,__TRACK_LIST__:x}),de.on(le.NETWORK_STATE_CHANGE,((e,t)=>{B.info("[network-indicator] network state changed, ".concat(t," => ").concat(e))}));const Qr=(e,t,i)=>{B.debug("setParameter key:".concat(e,", value:").concat(JSON.stringify(t))),Fe(e,t,i)};export{Hi as AREAS,Hr as AgoraRTC,Bi as ChannelMediaRelayError,Vi as ChannelMediaRelayEvent,xi as ChannelMediaRelayState,ii as DEV,ei as ESM,$t as ESM_BUNDLER,ti as UMD,ai as __CLIENT_LIST__,rs as checkAudioTrackIsActive,gr as checkSystemRequirements,ss as checkVideoTrackIsActive,Mr as createChannelMediaRelayConfiguration,Ir as createClient,Fr as disableLogUpload,Br as enableLogUpload,kr as getCameras,Pr as getDevices,Lr as getMicrophones,Ur as getPlaybackDevices,Ar as getSupportedCodec,Kr as onAudioAutoplayFailed,zr as onAudioContextStateChanged,Yr as onAutoplayFailed,Xr as onCameraChanged,Jr as onMicrophoneChanged,qr as onSecurityPolicyViolation,fs as preload,jr as processExternalMediaAEC,Gr as registerExtensions,Wr as resumeAudioContext,Vr as setAppType,Oo as setArea,xr as setLogLevel,Qr as setParameter};