agora-rtc-sdk-ng
Version:
Agora WebRTC SDK for JavaScript
6 lines • 441 kB
JavaScript
/**
* AgoraWebSDK_N-v4.23.4-0-g17410532-dirty Copyright AgoraInc.
*/
import{LocalAudioTrack as e,MicrophoneAudioTrack as t,LocalVideoTrack as i,getCompatibility as n,TrackHint as o,isPlanB as a,MixingAudioTrack as s,DEFAULT_LOCAL_AUDIO_TRACK_STATS as r,DEFAULT_LOCAL_VIDEO_TRACK_STATS as c,DEFAULT_REMOTE_AUDIO_TRACK_STATS as d,DEFAULT_REMOTE_VIDEO_TRACK_STATS as l,DEFAULT_NETWORK_QUALITY_STATS as h,CameraVideoTrack as u,getOriginSenderConfig as _,audioTimerLoop as p,MediaElementNumStatus as E,visibilityWatcher as S,MediaElementStatus as m,audioElementPlayCenter as R,RemoteAudioTrack as T,RemoteVideoTrack as f,TrackInternalEvent as C,RemoteTrackEvents as I,TrackEvents as A,StreamType as g,LocalTrack as v,TrackMediaType as y,isLowStreamParameter as N,autoPlayGestureEventEmitter as w,deviceManager as O,DeviceManagerEvent as b,audioContextState as D,AUDIO_CONTEXT_EVENT as P,__TRACK_LIST__ as L}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 k,AgoraRTCError as U,report as M,AgoraRTCErrorCode as V,AgoraRTCEvent as x,AgoraRTCEventUploadType as B,apiInvoke as F,isEventCustomReportParams as j}from"@agora-js/report";import{MUTABLE_PARAMS as G,MUTABLE_PARAMS_LOCAL_CACHE as W,MUTABLE_GATEWAY_PARAMS as H,CONFIG_DISTRIBUTE_TYPE as K,MUTABLE_REALTIME_PARAMS as Y,AgoraRTCErrorCode as q,isValidString as X,checkValidString as J,IS_GLOBAL_VERSION as z,EventEmitter as Q,getParameter as Z,createDefer as $,isMacOS as ee,isFirefox as te,PromiseMutex as ie,NETWORK_STATE as ne,networkIndicator as oe,NETWORK_INDICATOR_EVENTS as ae,AgoraRTCError as se,getRetryWaitTime as re,wait as ce,emitAsPromise as de,emitAsInvokerNoResponse as le,Rolling as he,ConnectionDisconnectedReason as ue,WebSocketQuitReason as _e,getRandomString as pe,emitAsInvoker as Ee,DEFAULT_TURN_CONFIG as Se,SHA256 as me,ScalabilityMode as Re,parseSdp as Te,jsonClone as fe,printSdp as Ce,getBrowserInfo as Ie,BrowserName as Ae,BrowserOS as ge,withTimeout as ve,nextTick as ye,isBelowChrome as Ne,isAboveChrome as we,isAboveSafari15_4 as Oe,VERSION as be,isBetweenBrowser as De,setParameter as Pe,getUTF8StringByteLength as Le,getMultiUnilbsFormDataByteLength as ke,AgoraAPIName as Ue,AgoraAPITag as Me,retryable as Ve,DEFAULT_RETRY_CONFIG as xe,loadInstallId as Be,isJsonEqual as Fe,isSafari as je,isChromeBelow90 as Ge,isChrome as We,isBelowIOS14_6 as He,VideoCodec as Ke,QualityLimitationReason as Ye,OVERUSE_DETECTOR_PARAMS as qe,isAboveIOS as Xe,isBelowIOS as Je,isAboveSafari as ze,isBelowSafari as Qe,isChromeKernel as Ze,isRTCIceServerList as $e,createWebRTCStatsFilter as et,DEFAULT_CANDIDATE_STATS as tt,PeerConnectionState as it,compareArray as nt,emitAsPromiseNoResponse as ot,isMobile as at,getUniqueList as st,ClientEvents as rt,isWkWebview as ct,runOnce as dt,generateSessionID as lt,md5 as ht,convertStringToFixedLengthUint8Array as ut,base64ToUint8Array as _t,uint8ArrayToBase64 as pt,checkValidNumber as Et,removeItemFromList as St,SDKStore as mt,BUILD as Rt,isClientRoleOptions as Tt,concurrent as ft,isHttpsEnv as Ct,supportIsSecureContext as It,encryptRSA as At,generateIv as gt,generateKey as vt,checkValidBoolean as yt,checkValidEnum as Nt,checkValidArray as wt,isClientRole as Ot,isTurnServerConfig as bt,isEncryptionMode as Dt,encryptAesGcm as Pt,CRYPTO_HEADER_LENGTH as Lt,decryptAesGcm as kt,isP2PTransport as Ut,isClientConfig as Mt,isWebKit as Vt,isSupportedWkWebview as xt,isIOS as Bt,isIpadOS as Ft,isWechatBrowser as jt,isQQBrowser as Gt,generateProcessID as Wt}from"@agora-js/shared";export{AudienceLatencyLevelType,BUILD,ConnectionDisconnectedReason,VERSION,getParameter}from"@agora-js/shared";import Ht from"axios";import"formdata-polyfill";const Kt=!0,Yt=!1,qt=!1,Xt=!1,Jt=["CHINA","GLOBAL"];const zt=[[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]],Qt=[],Zt=[];function $t(e,t){return!!t&&Qt.some((i=>i.uid===e&&i.channelName===t))}function ei(){return Zt.length>0}function ti(e,t){this.v=e,this.k=t}function ii(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 ni(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 ti(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 oi(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 ai(t.call(e));i="@@asyncIterator",n="@@iterator"}throw new TypeError("Object is not async iterable")}function ai(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 ai=function(e){this.s=e,this.n=e.next},ai.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 ai(e)}function si(e){return new ti(e,0)}function ri(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 ci(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 di(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?ci(Object(i),!0).forEach((function(t){ri(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):ci(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function li(e){return function(){return new hi(e.apply(this,arguments))}}function hi(e){var t,i;function n(t,i){try{var a=e[t](i),s=a.value,r=s instanceof ti;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)}hi.prototype["function"==typeof Symbol&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},hi.prototype.next=function(e){return this._invoke("next",e)},hi.prototype.throw=function(e){return this._invoke("throw",e)},hi.prototype.return=function(e){return this._invoke("return",e)};let ui=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}({}),_i=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}({}),pi=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}({}),Ei=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}({}),Si=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}({}),mi=function(e){return e.CONNECTING="connecting",e.CONNECTED="connected",e.RECONNECTING="reconnecting",e.CLOSED="closed",e}({}),Ri=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}({}),Ti=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}({}),fi=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}({}),Ci=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}({}),Ii=function(e){return e.SEND_ONLY="SEND_ONLY",e.RECEIVE_ONLY="RECEIVE_ONLY",e}({}),Ai=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 gi(e){if("string"!=typeof e||!/^[a-zA-Z0-9 \!\#\$\%\&\(\)\+\-\:\;\<\=\.\>\?\@\[\]\^\_\{\}\|\~\,]{1,64}$/.test(e))throw k.error("Invalid Channel Name ".concat(e)),new U(q.INVALID_PARAMS,"The length must be within 64 bytes. The supported characters: a-z,A-Z,0-9,space,!, #, $, %, &, (, ), +, -, :, ;, <, =, ., >, ?, @, [, ], ^, _, {, }, |, ~, ,")}function vi(e){if(!(t=e,"number"==typeof t&&Math.floor(t)===t&&0<=t&&t<=4294967295||X(e,1,255)))throw new U(q.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&&k.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 yi=function(e){return e.TRANSCODE="mix_streaming",e.RAW="raw_streaming",e}({}),Ni=function(e){return e.REQUEST_WORKER_MANAGER_LIST="@live_req_worker_manager",e}({});function wi(e){if(!e.channelName)throw new U(q.INVALID_PARAMS,"invalid channelName in info");if("number"!=typeof e.uid)throw new U(q.INVALID_PARAMS,"invalid uid in info, uid must be a number");return e.token&&J(e.token,"info.token",1,2047),vi(e.uid),gi(e.channelName),!0}let Oi=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}({}),bi=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}({}),Di=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}({}),Pi=function(e){return e.High="high",e.Low="low",e.Audio="audio",e.Screen="screen",e.ScreenLow="screen_low",e}({}),Li=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}({}),ki=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}({}),Ui=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}({}),Mi=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 Vi=[Mi.AFRICA,Mi.ASIA,Mi.CHINA,Mi.EUROPE,Mi.GLOBAL,Mi.INDIA,Mi.JAPAN,Mi.NORTH_AMERICA,Mi.OCEANIA,Mi.OVERSEA,Mi.SOUTH_AMERICA];let xi=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 Bi={CHINA:{},ASIA:{CODE:xi.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:xi.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:xi.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:xi.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:xi.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:xi.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:xi.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:xi.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:xi.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:xi.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:xi.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:xi.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:xi.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:{}};z&&(Bi.CHINA={CODE:xi.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 Fi=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 Gi extends Q{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.onFirstVideoDecodedTimeout=void 0,this.onSelectedLocalCandidateChanged=void 0,this.onSelectedRemoteCandidateChanged=void 0,this.onICECandidateError=void 0,this.getLocalVideoStats=void 0}}class Wi extends Gi{constructor(e,t){super(e,t),this.establishPromise=void 0}}let Hi=function(e){return e.VIDEO="video",e.AUDIO="audio",e}({}),Ki=function(e){return e.UDP_RELAY="udp_relay",e.UDP_TCP_RELAY="udp_tcp_relay",e.TCP_RELAY="tcp_relay",e.RELAY="relay",e}({}),Yi=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 qi=["disconnected","failed"];let Xi=function(e){return e.LocalVideoTrack="videoTrack",e.LocalAudioTrack="audioTrack",e.LocalVideoLowTrack="videoLowTrack",e}({}),Ji=function(e){return e.New="new",e.Connected="connected",e.Reconnecting="reconnecting",e.Disconnected="disconnected",e}({}),zi=function(e){return e.AudioMetadata="audioMetadata",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}({}),Qi=function(e){return e.CONNECTING="CONNECTING",e.RECONNECTING="RECONNECTING",e.CONNECTED="CONNECTED",e.CLOSED="CLOSED",e}({}),Zi=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}({}),$i=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}({}),en=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}({}),tn=function(e){return e.CONNECTING="CONNECTING",e.RECONNECTING="RECONNECTING",e.CONNECTED="CONNECTED",e.CLOSED="CLOSED",e}({}),nn=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}({}),on=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}({}),an=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 sn={[ui.ACCESS_POINT]:{[Ei.NO_FLAG_SET]:{desc:"flag is zero",retry:!1},[Ei.FLAG_SET_BUT_EMPTY]:{desc:"flag is empty",retry:!1},[Ei.INVALID_FALG_SET]:{desc:"invalid flag",retry:!1},[Ei.FLAG_SET_BUT_NO_RE]:{desc:"flag set unilbs but no request",retry:!1},[Ei.INVALID_SERVICE_ID]:{desc:"invalid service id",retry:!1},[Ei.NO_SERVICE_AVAILABLE]:{desc:"no service available",retry:!0},[Ei.NO_SERVICE_AVAILABLE_P2P]:{desc:"no unilbs p2p service available",retry:!0},[Ei.NO_SERVICE_AVAILABLE_VOICE]:{desc:"no unilbs voice service available",retry:!0},[Ei.NO_SERVICE_AVAILABLE_WEBRTC]:{desc:"no unilbs webrtc service available",retry:!0},[Ei.NO_SERVICE_AVAILABLE_CDS]:{desc:"no cds service available",retry:!0},[Ei.NO_SERVICE_AVAILABLE_CDN]:{desc:"no cdn dispatcher service available",retry:!0},[Ei.NO_SERVICE_AVAILABLE_TDS]:{desc:"no tds service available",retry:!0},[Ei.NO_SERVICE_AVAILABLE_REPORT]:{desc:"no unilbs report service available",retry:!0},[Ei.NO_SERVICE_AVAILABLE_APP_CENTER]:{desc:"no app center service available",retry:!0},[Ei.NO_SERVICE_AVAILABLE_ENV0]:{desc:"no unilbs sig env0 service available",retry:!0},[Ei.NO_SERVICE_AVAILABLE_VOET]:{desc:"no unilbs voet service available",retry:!0},[Ei.NO_SERVICE_AVAILABLE_STRING_UID]:{desc:"no string uid service available",retry:!0},[Ei.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS]:{desc:"no webrtc unilbs service available",retry:!0}},[ui.UNILBS]:{[pi.INVALID_VENDOR_KEY]:{desc:"invalid vendor key, can not find appid",retry:!1},[pi.INVALID_CHANNEL_NAME]:{desc:"invalid channel name",retry:!1},[pi.INTERNAL_ERROR]:{desc:"unilbs internal error",retry:!1},[pi.NO_AUTHORIZED]:{desc:"invalid token, authorized failed",retry:!1},[pi.DYNAMIC_KEY_TIMEOUT]:{desc:"dynamic key or token timeout",retry:!1},[pi.NO_ACTIVE_STATUS]:{desc:"no active status",retry:!1},[pi.DYNAMIC_KEY_EXPIRED]:{desc:"dynamic key expired",retry:!1},[pi.STATIC_USE_DYNAMIC_KEY]:{desc:"static use dynamic key",retry:!1},[pi.DYNAMIC_USE_STATIC_KEY]:{desc:"dynamic use static key",retry:!1},[pi.USER_OVERLOAD]:{desc:"amount of users over load",retry:!1},[pi.FORBIDDEN_REGION]:{desc:"the request is forbidden in this area",retry:!1},[pi.CANNOT_MEET_AREA_DEMAND]:{desc:"unable to allocate services in this area",retry:!1}},[ui.STRING_UID_ALLOCATOR]:{[_i.IIIEGAL_APPID]:{desc:"invalid appid",retry:!1},[_i.IIIEGAL_UID]:{desc:"invalid string uid",retry:!1},[_i.INTERNAL_ERROR]:{desc:"string uid allocator internal error",retry:!0}}};function rn(e){const t=sn[Math.floor(e/1e4)];if(!t)return{desc:"unknown error",retry:!1};const i=t[e%1e4];if(!i){if(Math.floor(e/1e4)===ui.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 cn={[Si.K_TIMESTAMP_EXPIRED]:{desc:"K_TIMESTAMP_EXPIRED",action:"failed"},[Si.K_CHANNEL_PERMISSION_INVALID]:{desc:"K_CHANNEL_PERMISSION_INVALID",action:"failed"},[Si.K_CERTIFICATE_INVALID]:{desc:"K_CERTIFICATE_INVALID",action:"failed"},[Si.K_CHANNEL_NAME_EMPTY]:{desc:"K_CHANNEL_NAME_EMPTY",action:"failed"},[Si.K_CHANNEL_NOT_FOUND]:{desc:"K_CHANNEL_NOT_FOUND",action:"failed"},[Si.K_TICKET_INVALID]:{desc:"K_TICKET_INVALID",action:"failed"},[Si.K_CHANNEL_CONFLICTED]:{desc:"K_CHANNEL_CONFLICTED",action:"failed"},[Si.K_SERVICE_NOT_READY]:{desc:"K_SERVICE_NOT_READY",action:"tryNext"},[Si.K_SERVICE_TOO_HEAVY]:{desc:"K_SERVICE_TOO_HEAVY",action:"tryNext"},[Si.K_UID_BANNED]:{desc:"K_UID_BANNED",action:"failed"},[Si.K_IP_BANNED]:{desc:"K_IP_BANNED",action:"failed"},[Si.DATASTREAM2_NOT_AVAILABLE]:{desc:"DATASTREAM2_NOT_AVAILABLE",action:"quit"},[Si.K_AUTO_REBALANCE]:{desc:"k_AUTO_REBALANCE",action:"recover"},[Si.ERR_INVALID_VENDOR_KEY]:{desc:"ERR_INVALID_VENDOR_KEY",action:"failed"},[Si.ERR_INVALID_CHANNEL_NAME]:{desc:"ERR_INVALID_CHANNEL_NAME",action:"failed"},[Si.WARN_NO_AVAILABLE_CHANNEL]:{desc:"WARN_NO_AVAILABLE_CHANNEL",action:"failed"},[Si.WARN_LOOKUP_CHANNEL_TIMEOUT]:{desc:"WARN_LOOKUP_CHANNEL_TIMEOUT",action:"tryNext"},[Si.WARN_LOOKUP_CHANNEL_REJECTED]:{desc:"WARN_LOOKUP_CHANNEL_REJECTED",action:"failed"},[Si.WARN_OPEN_CHANNEL_TIMEOUT]:{desc:"WARN_OPEN_CHANNEL_TIMEOUT",action:"tryNext"},[Si.WARN_OPEN_CHANNEL_REJECTED]:{desc:"WARN_OPEN_CHANNEL_REJECTED",action:"failed"},[Si.WARN_REQUEST_DEFERRED]:{desc:"WARN_REQUEST_DEFERRED",action:"failed"},[Si.ERR_DYNAMIC_KEY_TIMEOUT]:{desc:"ERR_DYNAMIC_KEY_TIMEOUT",action:"failed"},[Si.ERR_NO_AUTHORIZED]:{desc:"ERR_NO_AUTHORIZED",action:"failed"},[Si.ERR_VOM_SERVICE_UNAVAILABLE]:{desc:"ERR_VOM_SERVICE_UNAVAILABLE",action:"tryNext"},[Si.ERR_NO_CHANNEL_AVAILABLE_CODE]:{desc:"ERR_NO_CHANNEL_AVAILABLE_CODE",action:"failed"},[Si.ERR_MASTER_VOCS_UNAVAILABLE]:{desc:"ERR_MASTER_VOCS_UNAVAILABLE",action:"tryNext"},[Si.ERR_INTERNAL_ERROR]:{desc:"ERR_INTERNAL_ERROR",action:"tryNext"},[Si.ERR_NO_ACTIVE_STATUS]:{desc:"ERR_NO_ACTIVE_STATUS",action:"failed"},[Si.ERR_INVALID_UID]:{desc:"ERR_INVALID_UID",action:"failed"},[Si.ERR_DYNAMIC_KEY_EXPIRED]:{desc:"ERR_DYNAMIC_KEY_EXPIRED",action:"failed"},[Si.ERR_STATIC_USE_DYANMIC_KE]:{desc:"ERR_STATIC_USE_DYANMIC_KE",action:"failed"},[Si.ERR_DYNAMIC_USE_STATIC_KE]:{desc:"ERR_DYNAMIC_USE_STATIC_KE",action:"failed"},[Si.ERR_NO_VOCS_AVAILABLE]:{desc:"ERR_NO_VOCS_AVAILABLE",action:"tryNext"},[Si.ERR_NO_VOS_AVAILABLE]:{desc:"ERR_NO_VOS_AVAILABLE",action:"tryNext"},[Si.ERR_JOIN_CHANNEL_TIMEOUT]:{desc:"ERR_JOIN_CHANNEL_TIMEOUT",action:"tryNext"},[Si.ERR_JOIN_BY_MULTI_IP]:{desc:"ERR_JOIN_BY_MULTI_IP",action:"recover"},[Si.ERR_NOT_JOINED]:{desc:"ERR_NOT_JOINED",action:"failed"},[Si.ERR_REPEAT_JOIN_REQUEST]:{desc:"ERR_REPEAT_JOIN_REQUEST",action:"quit"},[Si.ERR_REPEAT_JOIN_CHANNEL]:{desc:"ERR_REPEAT_JOIN_CHANNEL",action:"quit"},[Si.ERR_INVALID_STRINGUID]:{desc:"ERR_INVALID_STRINGUID",action:"failed"},[Si.ERR_TOO_MANY_USERS]:{desc:"ERR_TOO_MANY_USERS",action:"tryNext"},[Si.ERR_SET_CLIENT_ROLE_TIMEOUT]:{desc:"ERR_SET_CLIENT_ROLE_TIMEOUT",action:"failed"},[Si.ERR_SET_CLIENT_ROLE_NO_PERMISSION]:{desc:"ERR_SET_CLIENT_ROLE_TIMEOUT",action:"failed"},[Si.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE]:{desc:"ERR_SET_CLIENT_ROLE_ALREADY_IN_USE",action:"success"},[Si.ERR_PUBLISH_REQUEST_INVALID]:{desc:"ERR_PUBLISH_REQUEST_INVALID",action:"failed"},[Si.ERR_SUBSCRIBE_REQUEST_INVALID]:{desc:"ERR_SUBSCRIBE_REQUEST_INVALID",action:"failed"},[Si.ERR_NOT_SUPPORTED_MESSAGE]:{desc:"ERR_NOT_SUPPORTED_MESSAGE",action:"failed"},[Si.ERR_ILLEAGAL_PLUGIN]:{desc:"ERR_ILLEAGAL_PLUGIN",action:"failed"},[Si.ILLEGAL_CLIENT_ROLE_LEVEL]:{desc:"ILLEGAL_CLIENT_ROLE_LEVEL",action:"failed"},[Si.ERR_REJOIN_TOKEN_INVALID]:{desc:"ERR_REJOIN_TOKEN_INVALID",action:"failed"},[Si.ERR_REJOIN_USER_NOT_JOINED]:{desc:"ERR_REJOIN_NOT_JOINED",action:"failed"},[Si.ERR_INVALID_OPTIONAL_INFO]:{desc:"ERR_INVALID_OPTIONAL_INFO",action:"quit"},[Si.ERR_TEST_RECOVER]:{desc:"ERR_TEST_RECOVER",action:"recover"},[Si.ERR_TEST_TRYNEXT]:{desc:"ERR_TEST_TRYNEXT",action:"recover"},[Si.ERR_TEST_RETRY]:{desc:"ERR_TEST_RETRY",action:"recover"},[Si.ILLEGAL_AES_PASSWORD]:{desc:"ERR_TEST_RETRY",action:"failed"},[Si.ERR_TOO_MANY_BROADCASTERS]:{desc:"ERR_TOO_MANY_BROADCASTERS",action:"failed"},[Si.ERR_TOO_MANY_SUBSCRIBERS]:{desc:"ERR_TOO_MANY_SUBSCRIBERS",action:"failed"},[Si.ERR_LICENSE_ILLEGAL]:{desc:"ERR_LICENSE_ILLEGAL",action:"quit"},[Si.ERR_LICENSE_MISSING]:{desc:"ERR_LICENSE_MISSING",action:"quit"},[Si.ERR_LICENSE_EXPIRED]:{desc:"ERR_LICENSE_EXPIRED",action:"quit"},[Si.ERR_LICENSE_MINUTES_EXCEEDED]:{desc:"ERR_LICENSE_MINUTES_EXCEEDED",action:"quit"},[Si.ERR_LICENSE_PERIOD_INVALID]:{desc:"ERR_LICENSE_PERIOD_INVALID",action:"quit"},[Si.ERR_LICENSE_MULTIPLE_SDK_SERVICE]:{desc:"ERR_LICENSE_MULTIPLE_SDK_SERVICE",action:"quit"}};function dn(e){const t=cn[e];return t||{desc:"UNKNOWN_ERROR_".concat(e),action:"failed"}}function ln(e,t){if("string"==typeof e)return e;const{proxy:i,host:n,port:o}=e;if(t){const e=Z("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 hn=/wss:\/\/(.+)\/ws\/\?h=(.+)&p=([0-9]+)\/?/,un=/wss:\/\/(.+)\/ws\/\?p=([0-9]+)\/?/,_n=/wss:\/\/(.+):([0-9]+)\/?/,pn=/wss:\/\/(.[^\/]+)\/?/;let En=0;class Sn{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=++En,this.try443PortDuration=Z("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];k.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=Z("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(ln(di(di({},e),{},{host:e.host.replace(s,i)}),t))}));else{const i=di({},e);if(t&&s){const e=n.find((e=>e!==s));e&&(i.host=i.host.replace(s,e))}r.push(ln(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 U(q.WS_ERR,"init websocket failed! Error: ".concat(n.toString()))}const c=$();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:ki.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();ee()&&te()&&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(hn)||[],t||([,i,n]=e.match(un)||[]),i&&n||([,i,n]=e.match(_n)||[]),i&&n||([,i]=e.match(pn)||[]),i||k.warning("un-destructible url: ",e),{proxy:t,host:i,port:n||"443"}}(e)),this.recordIndex=n,this.useProxy=!!e.proxy,i&&this.useProxy&&(k.warn("cannot use 443 only when use proxy"),i=!1),this.createWebSocket(e,!!i,!1).finally((()=>this.clearTimeout()))}}class mn extends Q{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(Ai.RECONNECTING,this.reconnectReason):"connected"===this._state?this.emit(Ai.CONNECTED):"closed"===this._state?this.emit(Ai.CLOSED):"failed"===this._state&&this.emit(Ai.FAILED))}resetReconnectCount(e){k.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=di({},t),this.useCompress=i,this.tryDoubleDomain=n,this.use443PortOnly=o,this._initMutex=new ie("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);ne.ONLINE&&(this.retryConfig.timeout=c,this.retryConfig.timeoutFactor=d),oe.on(ae.NETWORK_STATE_CHANGE,((e,t)=>{e!==t&&(this.resetReconnectCount("network state change: ".concat(t," -> ").concat(e)),e===ne.ONLINE?(this.retryConfig.timeout=c,this.retryConfig.timeoutFactor=d):(this.retryConfig.timeout=s,this.retryConfig.timeoutFactor=r))}))}getConnection(){return this.websocket||void 0}async init(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const i=await this._initMutex.lock();this._reconnectMode="tryNext",this.forceCloseTimeout=t,this.urls=e,this.state="connecting";try{const e=$(),t=this.urls[this.currentURLIndex];Z("ENABLE_PREALLOC_PC")&&this.emit($i.PRE_CONNECT_PC),this.createWebSocketConnection(t).then(e.resolve).catch(e.reject),this.once(Ai.CLOSED,(()=>{e.reject(new se(q.WS_DISCONNECT))})),this.once(Ai.CONNECTED,e.resolve),await e.promise}catch(e){}finally{i()}}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 k.warning("[".concat(this.name,"] can not reconnect, no websocket"));void 0!==e&&(this.reconnectMode=e),k.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 se(q.WS_ABORT,"websocket is not ready");try{t||(e=JSON.stringify(e)),this.websocket.send(e)}catch(e){throw new se(q.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=$();this.connectionID+=1,this.joinGatewayRecordIndex=void 0;const n=e=>{var t;null===(t=this.store)||void 0===t||t.signalChannelOpen(),k.debug("[".concat(this.name,"] websocket opened:"),e),this.reconnectMode="retry",this.state="connected",this.resetReconnectCount("opened"),i.resolve()},o=async e=>{var t;if(k.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 se(q.WS_DISCONNECT,"websocket close: ".concat(e.code))),this.close();else{"connected"===this.state&&(this.reconnectReason=e.reason,this.state="reconnecting");const t=le(this,Ai.WILL_RECONNECT,this.reconnectMode,e.reason)||this.reconnectMode,n=await this.reconnectWithAction(t);if("closed"===this.state)return void k.debug("[".concat(this.connectionID,"] ws is closed, no need to reconnect"));if(!n)return i.reject(new se(q.WS_DISCONNECT,"websocket reconnect failed: ".concat(e.code))),this.close(!0);i.resolve()}},a=e=>{this.emit(Ai.ON_MESSAGE,e)},s=e=>{k.warn("[".concat(this.connectionID,"] ws open error ").concat(e))};this.websocket&&(this.websocket.onclose=null,this.websocket.close()),Z("GATEWAY_WSS_ADDRESS")&&this.name.startsWith("gateway")&&(e=Z("GATEWAY_WSS_ADDRESS")),k.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=ln(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 se,a=n&&e.code===q.WS_ABORT,s=n&&e.code===q.WS_ERR,c=n?e.message:e&&(e.reason||e.toString());k.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 se(q.WS_DISCONNECT,"websocket is closed: ".concat(c)):new se(q.WS_ERR,"init websocket failed: ".concat(c))),s&&k.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;k.warning("[choose-best-ws] action: =>",e),this.onlineReconnectListener||oe.isOnline||!oe.onlineWaiter||(this.onlineReconnectListener=oe.onlineWaiter.then((()=>{this.onlineReconnectListener=void 0})));let i=!0;if(this.reconnectInterrupter=()=>i=!1,t){const t=re(this.reconnectCount,this.retryConfig);k.debug("[".concat(this.name,"] wait ").concat(t,"ms to reconnect websocket, mode: ").concat(e)),await Promise.race([ce(t),this.onlineReconnectListener||new Promise((()=>{}))])}if("closed"===this._state||!i)return!1;this.reconnectCount+=1;const n=async(e,t)=>{this.emit(Ai.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);k.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&&(k.debug("[".concat(this.name,"] request new urls")),this.resetReconnectCount("recover mode"),this.urls=await de(this,Ai.REQUEST_NEW_URLS),this.currentURLIndex=0,await n(this.urls[this.currentURLIndex],e))}catch(i){var o;k.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(Ai.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1):this.reconnectWithAction(e,t)}return!0}}class Rn extends mn{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=$(),n=(o=this.forceCloseTimeout,a=this.store,new Sn(o,a));var o,a;this.closeEstablishingWs=()=>{k.debug("[choose-best-ws] close establishing websockets"),n.closeAllWebsockets(),i.reject(new se(q.WS_ABORT,"choose best websocket aborted"))};const s=Z("GATEWAY_DOMAINS");return k.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 Tn extends Q{get connectionState(){return this._connectionState}set connectionState(e){e!==this._connectionState&&(this._connectionState=e,e===mi.CONNECTED?this.emit(Ri.WS_CONNECTED):e===mi.RECONNECTING?this.emit(Ri.WS_RECONNECTING,this._websocketReconnectReason):e===mi.CLOSED&&this.emit(Ri.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=mi.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 he(5),this.pingpongTimer=void 0,this.wsInflateDataTimer=void 0,this.pingpongTimeoutCount=0,this.joinResponse=void 0,this.multiIpOption=void 0,this.initError=void 0,this.spec=void 0,this.store=void 0,this.onWebsocketMessage=e=>{if(e.data instanceof ArrayBuffer)return void this.emit(Ri.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===Ci.ON_NOTIFICATION&&this.handleNotification(t._message),t._type===Ci.ON_USER_BANNED)switch(t._message.error_code){case 14:this.close(ue.UID_BANNED);break;case 15:this.close(ue.IP_BANNED);break;case 16:this.close(ue.CHANNEL_BANNED)}if(t._type===Ci.ON_USER_LICENSE_BANNED)switch(t._message.error_code){case Si.ERR_LICENSE_MISSING:this.close(ue.LICENSE_MISSING);break;case Si.ERR_LICENSE_EXPIRED:this.close(ue.LICENSE_EXPIRED);break;case Si.ERR_LICENSE_MINUTES_EXCEEDED:this.close(ue.LICENSE_MINUTES_EXCEEDED);break;case Si.ERR_LICENSE_PERIOD_INVALID:this.close(ue.LICENSE_PERIOD_INVALID);break;case Si.ERR_LICENSE_MULTIPLE_SDK_SERVICE:this.close(ue.LICENSE_MULTIPLE_SDK_SERVICE);break;case Si.ERR_LICENSE_ILLEGAL:this.close(ue.LICENSE_ILLEGAL);break;default:this.close()}}},this.clientId=e.clientId,this.spec=e,this.store=t,this.websocket=new Rn("gateway-".concat(this.clientId),this.spec.retryConfig,!0,Z("JOIN_GATEWAY_USE_DUAL_DOMAIN"),Z("JOIN_GATEWAY_USE_443PORT_ONLY"),t),this.handleWebsocketEvents(),window.addEventListener("offline",(()=>{this.connectionState===mi.CONNECTED&&this.reconnect("retry",_e.OFFLINE)}))}async request(e,t,i,n){const o=pe(6,""),a={_id:o,_type:e,_message:t},s=this.websocket.connectionID,r=()=>new Promise(((t,i)=>{if(this.connectionState===mi.CONNECTED)return t();const n=()=>{this.off(Ri.WS_CLOSED,o),t()},o=()=>{this.off(Ri.WS_CONNECTED,n),i(new U(q.WS_ABORT))};this.once(Ri.WS_CONNECTED,n),this.once(Ri.WS_CLOSED,o),e!==Ti.PUBLISH&&e!==Ti.PUBLISH_DATASTREAM&&e!==Ti.SUBSCRIBE&&e!==Ti.SUBSCRIBE_DATASTREAM&&e!==Ti.UNSUBSCRIBE&&e!==Ti.UNSUBSCRIBE_DATASTREAM&&e!==Ti.UNPUBLISH&&e!==Ti.UNPUBLISH_DATASTREAM&&e!==Ti.CONTROL&&e!==Ti.RESTART_ICE||this.once(Ri.DISCONNECT_P2P,(()=>{i(new U(q.DISCONNECT_P2P))})),e!==Ti.PUBLISH&&e!==Ti.RESTART_ICE||this.once(Ri.ABORT_P2P_EXECUTION,(()=>{i(new U(q.DISCONNECT_P2P))}))}));if(this.connectionState!==mi.CONNECTING&&this.connectionState!==mi.RECONNECTING||e===Ti.JOIN||e===Ti.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(Ri.WS_CLOSED,c),this.off(Ri.WS_RECONNECTING,c),this.emit(Ri.REQUEST_SUCCESS,e,t)};this.once("res-@".concat(o),r);const c=()=>{n(new U(q.WS_ABORT,"type: ".concat(e))),this.off(Ri.WS_CLOSED,c),this.off(Ri.WS_RECONNECTING,c),this.off("res-@".concat(o),r)};this.once(Ri.WS_CLOSED,c),this.once(Ri.WS_RECONNECTING,c),ce(Z("SIGNAL_REQUEST_TIMEOUT")).then((()=>{this.websocket.connectionID!==s||a||(k.warning("[".concat(this.clientId,"] ws request timeout, type: ").concat(e)),this.emit(Ri.REQUEST_TIMEOUT,e,t))}))}));let d=null;try{d=await c}catch(n){if(this.connectionState===mi.CLOSED||e===Ti.LEAVE)throw new U(q.WS_ABORT);return!this.spec.forceWaitGatewayResponse||i?n.throw():e===Ti.JOIN||e===Ti.REJOIN?null:(await r(),await this.request(e,t))}if(d.isSuccess)return d.message;const l=Number(d.message.error_code||d.message.code),h=dn(l),u=new U(q.UNEXPECTED_RESPONSE,"".concat(h.desc,": ").concat(d.message.error_str),{code:l,data:d.message,desc:h.desc});return"success"===h.action?d.message:(k.warning("[".concat(this.clientId,"] [").concat(this.websocket.connectionID,"] unexpected response from type ").concat(e,", error_code: ").concat(l,", message: ").concat(h.desc,", action: ").concat(h.action)),l===Si.ERR_TOO_MANY_BROADCASTERS?e===Ti.JOIN||e===Ti.REJOIN?(this.initError=u,this.close(),u.throw()):u.throw():"failed"===h.action?u.throw():"quit"===h.action?(this.initError=u,this.close(),u.throw()):(l===Si.ERR_JOIN_BY_MULTI_IP?(this.multiIpOption=d.message.option,k.warning("[".concat(this.clientId,"] detect multi ip, recover")),this.reconnect("recover",_e.MULTI_IP)):this.reconnect(h.action,_e.SERVER_ERROR),e===Ti.JOIN||e===Ti.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 k.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(fi.WRTC_STATS,t)}upload(e,t){const i={_type:e,_message:t};try{this.websocket.sendMessage(i)}catch(e){const t=Z("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!==mi.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)}),Z("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(Ri.WS_CONNECTED,(()=>t(this.joinResponse))),this.once(Ri.WS_CLOSED,(e=>i(this.initError||new U(q.WS_ABORT,e)))),this.connectionState=mi.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||ue.LEAVE,this.connectionState=mi.CLOSED,k.debug("[".concat(this.clientId,"] ")+"will close websocket in signal"),this.websocket.close()}async join(){if(!this.joinResponse){this.emit(Ri.ABORT_P2P_EXECUTION);const e=await de(this,Ri.REQUEST_JOIN_INFO),t=await this.request(Ti.JOIN,e);if(!t)return this.emit(Ri.REPORT_JOIN_GATEWAY,ki.TIMEOUT,this.url||""),!1;this.joinResponse=t,this.emit(Ri.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token}return this.connectionState=mi.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),!0}async rejoin(){if(!this.reconnectToken)throw new U(q.UNEXPECTED_ERROR,"can not rejoin, no rejoin token");const e=Ee(this,Ri.REQUEST_REJOIN_INFO);e.token=this.reconnectToken;const t=await this.request(Ti.REJOIN,e);return!!t&&(this.connectionState=mi.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),t.peers&&t.peers.forEach((e=>{this.emit(Ci.ON_USER_ONLINE,{uid:e.uid}),e.audio&&this.emit(Ci.ON_ADD_AUDIO_STREAM,{uid:e.uid,uint_id:e.uint_id,audio:!0,ssrcId:e.audio_ssrc}),e.video&&this.emit(Ci.ON_ADD_VIDEO_STREAM,{uid:e.uid,uint_id:e.uint_id,video:!0,ssrcId:e.video_ssrc}),e.audio_mute?this.emit(Ci.MUTE_AUDIO,{uid:e.uid}):this.emit(Ci.UNMUTE_AUDIO,{uid:e.uid}),e.video_mute?this.emit(Ci.MUTE_VIDEO,{uid:e.uid}):this.emit(Ci.UNMUTE_VIDEO,{uid:e.uid}),e.audio_enable_local?this.emit(Ci.ENABLE_LOCAL_AUDIO,{uid:e.uid}):this.emit(Ci.DISABLE_LOCAL_AUDIO,{uid:e.uid}),e.video_enable_local?this.emit(Ci.ENABLE_LOCAL_VIDEO,{uid:e.uid}):this.emit(Ci.DISABLE_LOCAL_VIDEO,{uid:e.uid}),e.audio||e.video||this.emit(Ci.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)}handleNotification(e){k.debug("[".concat(this.clientId,"] receive notification: "),e);const t=dn(e.code);if(28===e.code&&"detail"in e&&(k.info("[".concat(this.clientId,"] receive recover notification: "),e.detail),this.emit(Ri.RECOVER_NOTIFICATION,e.detail)),"success"!==t.action){if("failed"!==t.action)return"quit"===t.action?("ERR_REPEAT_JOIN_CHANNEL"===t.desc&&this.close(ue.UID_BANNED),void this.close()):void this.reconnect(t.action,_e.SERVER_ERROR);k.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=Z("PING_PONG_TIME_OUT"),t=Date.now();this.pingpongTimeoutCount>=e&&(k.warning("[".concat(this.clientId,"] PING-PONG Timeout. Last Socket Message: ").concat(t-this.lastMsgTime,"ms")),t-this.lastMsgTime>Z("WEBSOCKET_TIMEOUT_MIN"))?this.reconnect("retry",_e.TIMEOUT):this.request(Ti.PING,void 0,!0).then((()=>{this.pingpongTimeoutCount=0;const e=Date.now()-t;this.rttRolling.add(e),Z("REPORT_STATS")&&this.send(Ti.PING_BACK,{pingpongElapse:e})})).catch((e=>{}))}handleWsInflateData(){const{wsInflateLength:e,wsDeflateLength:t}=this.websocket.getWsInflateData();0!==e&&0!==t&&this.upload(fi.WS_INFLATE_DATA_LENGTH,{ws_deflate_length:t,ws_inflate_length:e})}handleWebsocketEvents(){this.websocket.on(Ai.RECONNECT_CREATE_CONNECTION,(e=>{this.emit(Ri.WS_RECONNECT_CREATE_CONNECTION,e)})),this.websocket.on(Ai.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(Ai.CLOSED,(()=>{this.connectionState=mi.CLOSED})),this.websocket.on(Ai.FAILED,(()=>{this._disconnectedReason=ue.NETWORK_ERROR,this.connectionState=mi.CLOSED})),this.websocket.on(Ai.RECONNECTING,(e=>{this._websocketReconnectReason=e,this.joinResponse=void 0,this.connectionState===mi.CONNECTED?this.connectionState=mi.RECONNECTING:this.connectionState=mi.CONNECTING})),this.websocket.on(Ai.WILL_RECONNECT,((e,t,i)=>{const n=Ee(this,Ri.IS_P2P_DISCONNECTED),o=n||"retry"!==e;n&&"retry"===e&&(k.debug("".concat(this.clientId," reconnect mode is retry, but p2p lost, change to tryNext")),e="tryNext",t=ki.P2P_DISCONNECTED),o&&(k.debug("".concat(this.clientId," will renewSession, reconnect mode: ").concat(e)),this.emit(Ri.REPORT_JOIN_GATEWAY,t||ki.UNKNOWN_REASON,this.url||""),this.reconnectToken=void 0,this.emit(Ri.DISCONNECT_P2P)),i(e)})),this.websocket.on(Ai.CONNECTED,(()=>{this.openConnectionTime=Date.now(),this.reconnectToken?this.rejoin().catch((e=>{k.warning("[".concat(this.clientId,"] rejoin failed ").concat(e)),this.reconnect("tryNext",_e.SERVER_ERROR)})):this.join().catch((e=>{if(this.emit(Ri.REPORT_JOIN_GATEWAY,e,this.url||""),e instanceof U){if(e.code===q.UNEXPECTED_RESPONSE&&e.data.code===Si.ERR_NO_AUTHORIZED)return this.initError=new U(q.TOKEN_EXPIRE,"dynamic key expired"),void this.close(ue.TOKEN_EXPIRE);k.error("[".concat(this.clientId,"] join gateway request failed"),e.toString()),this.spec.forceWaitGatewayResponse?this.reconnect("tryNext",_e.SERVER_ERROR):(this.initError=e,this.close())}}))})),this.websocket.on(Ai.REQUEST_NEW_URLS,((e,t)=>{de(this,Ri.REQUEST_RECOVER,this.multiIpOption).then(e).catch(t)})),this.websocket.on(Ai.ON_TOKEN_PRIVILEGE_DID_EXPIRE,(()=>{this.emit(Ci.ON_TOKEN_PRIVILEGE_DID_EXPIRE)})),this.websocket.on($i.PRE_CONNECT_PC,(()=>{this.emit(Ri.PRE_CONNECT_PC)}))}}let fn=function(e){return e.NATIVE_RTC="native_rtc",e.NATIVE_RTM="native_rtm",e.WEB_RTC="web_rtc",e.WEB_RTM="web_rtm",e}({}),Cn=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 In(e){return e.match(/^[\.\:\d]+$/)?"".concat(e.replace(/[^\d]/g,"-"),".").concat(Z("TURN_DOMAIN")):(k.debug("Cannot recognized as ip address: ".concat(e,", use as host")),e)}function An(e,t){e.addresses||(e.addresses=[]);const i=function(e,t){if(Z("CONNECT_GATEWAY_WITHOUT_DOMAIN"))return e.map((e=>{let{ip:t,port:i}=e;return{address:"".concat(t,":").concat(i)}}));const i=Z("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||k.debug("Cannot recognized as ip address: ".concat(a,", use as host")),{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 gn(e){return"number"==typeof e?e:e.exact||e.ideal||e.max||e.min||0}function vn(e){const t=e._encoderConfig;if(!t)return{};const i={resolution:t.width&&t.height?"".concat(gn(t.width),"x").concat(gn(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 yn(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 Nn(e,t){let i,n,o;switch(t){case Cn.CHOOSE_SERVER:n=4096,o="choose server";break;case Cn.CLOUD_PROXY:n=1048576,o="proxy";break;case Cn.CLOUD_PROXY_5:n=4194304,o="proxy5";break;case Cn.CLOUD_PROXY_FALLBACK:n=4194310,o="proxy fallback";break;default:throw new U(q.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=>di(di({},e),{},{ticket:t.buffer.cert}))),server_ts:e.enter_ts,uid:t.buffer.uid,cid:t.buffer.cid,cname:t.buffer.cname,detail:di(di({},t.buffer.detail),e.detail),flag:t.buffer.flag,opid:e.opid,cert:t.buffer.cert})})),!i)throw new U(q.MULTI_UNILBS_RESPONSE_ERROR,"cannot parse response ".concat(o," from multi unilbs response"),{csIp:e.detail&&e.detail[502]});return i}async function wn(e,t){return await Promise.all(e.addresses.map((async e=>({address:Z("USE_TURN_IP")?e.ip:In(e.ip),tcpport:e.port,udpport:e.port,username:t&&Z("ENCRYPT_PROXY_USERNAME_AND_PSW")&&window.isSecureContext?t.toString():Se.username,password:t&&Z("ENCRYPT_PROXY_USERNAME_AND_PSW")&&window.isSecureContext?await me(t.toString()):Se.password}))))}function On(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(gn(e.height),gn(e.width)),1):(k.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 Dn(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Z("SVC_MODE");if(Z("ENABLE_SVC"))return function(e){return e in Re}(e)?e:Re.L1T3}const Pn={[Hi.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"}],[Hi.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 Ln(e,t,i){t.forEach((t=>{const n=Pn[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 kn(e,t){t.forEach((t=>{const i=Pn[e].find((e=>{let{key:i}=e;return t.extensionName.includes(i)}));t.extensionName.includes("gdpr_forbidden")&&i&&(t.extensionName=i.extensionName)}))}function Un(e){return"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"===e||e.includes("abs-send-time")}function Mn(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 Vn(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}=t,{useXR:d}=i;let l=[],h=[],u=[],_=[],p=!1,E=!1;if(Te(e).mediaDescriptions.forEach((e=>{n&&n!==e.attributes.direction||("video"!==e.media.mediaType||p||(h=e.attributes.payloads,_=e.attributes.extmaps,p=!0),"audio"!==e.media.mediaType||E||(l=e.attributes.payloads,u=e.attributes.extmaps,E=!0))})),!_||0===h.length)throw new Error("Cannot get video capabilities from SDP.");if(!u||0===l.length)throw new Error("Cannot get audio capabilities from SDP.");if(h.forEach((e=>{var t;null!==(t=e.rtpMap)&&void 0!==t&&t.clockRate&&(e.rtpMap.clockRate=parseInt(e.rtpMap.clockRate)),d&&e.rtcpFeedbacks.push({type:"rrtr"})})),l.forEach((e=>{var t;null!==(t=e.rtpMap)&&void 0!==t&&t.clockRate&&(e.rtpMap.clockRate=parseInt(e.rtpMap.clockRate)),d&&e.rtcpFeedbacks.push({type:"rrtr"})})),o&&(l=l.filter((e=>{var t;return"rtx"!==(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())})),h=h.filter((e=>{var t;return"rtx"!==(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())}))),a&&(h=h.filter((e=>{var t;return!/(red)|(ulpfec)|(flexfec)/i.test((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName)||"")}))),s&&(l=l.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&&(l=l.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=h.filter((e=>{var t;return c.includes((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())||"")}));h=e.concat(o?[]:Jn(e,h))}const S=Z("UNSUPPORTED_VIDEO_CODEC");return S&&S.length>0&&(h=h.filter((e=>!(e.rtpMap&&S.includes(e.rtpMap.encodingName.toLowerCase()))))),{audioCodecs:l,videoCodecs:h,audioExtensions:u,videoExtensions:_}}function xn(e){const t=Te(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 Bn(e,t,i){const{cname:n}=e;let o=[];t&&(o=Fn(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:{}}))),k.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=Yn(e.rtpCapabilities),d=[];return Array.isArray(i)&&i.length>0&&i.forEach((e=>{d.push({kind:Hi.VIDEO,ssrcId:e.v,rtx:e.v_rtx,mslabel:"".concat(e.v,"_").concat(e.a)},{kind:Hi.AUDIO,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 Fn(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:{}}],k.debug("Using remote candidate from AP ".concat(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:{}}),k.debug("Using IPV6 remote candidate from AP ".concat(e.ip6,":").concat(e.port)))),t}function jn(e,t,i){const n=[],o=[];return e.forEach((e=>{let{ssrcId:a,rtx:s}=e;const r=pe(8,"track-"),c={ssrcId:a,attributes:di({label:r,mslabel:i=i||pe(10,""),msid:"".concat(i," ").concat(r)},t&&{cname:t})};if(n.push(c),void 0!==s){const e={ssrcId:s,attributes:di({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 Gn(i,n){n instanceof e&&i.attributes.payloads.forEach((e=>{var i;const o=null===(i=e.rtpMap)||void 0===i?void 0:i.encodingName.toLowerCase();if(!o||-1===["opus","pcmu","pcma","g722"].indexOf(o))return;e.fmtp||(e.fmtp={parameters:{}}),"opus"===o&&"number"==typeof Z("OPUS_PTIME")?e.fmtp.parameters.ptime=Z("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&&!te()&&(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 t&&"opus"===o&&n._config.DTX&&(e.fmtp.parameters.usedtx="1"))}))}function Wn(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=>Mn(e.extensionName)));if(t){const i=t.extensionName;e.attributes.extmaps.find((e=>Mn(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=>Mn(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=>Un(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=>Un(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 Hn(){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=Vn(i,e,t,"sendonly"),o=Vn(i,e,t,"recvonly"),a={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},s={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},r={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]};if(Kn(n,o,"videoExtensions",a,s,r),Kn(n,o,"videoCodecs",a,s,r),Kn(n,o,"audioExtensions",a,s,r),Kn(n,o,"audioCodecs",a,s,r),Z("RAISE_H264_BASELINE_PRIORITY")){const e=[],t=[];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&&eo(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!==Z("FIRST_H264_PROFILE_LEVEL_ID")||Z("FIRST_PACKETIZATION_MODE")&&l!==Z("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&&(k.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=eo(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))}})),s.videoCodecs=s.videoCodecs.filter((e=>{var t,i;return!("h264"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLocaleLowerCase())&&(null===(i=e.fmtp)||void 0===i?void 0:i.parameters["profile-level-id"])!==Z("FIRST_H264_PROFILE_LEVEL_ID"))})),Z("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"])!==Z("FIRST_H264_PROFILE_LEVEL_ID"))}))))}return{send:a,recv:s,sendrecv:r}}(e,t,n);try{i.close()}catch(e){}return{send:o,recv:a,sendrecv:s}}function Kn(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 Yn(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 qn(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 Xn(e,t,i,n){let o=[];if(e===Hi.VIDEO){if(Z("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"]===Z("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"),k.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&&(k.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),Z("USE_PUB_RTX")||Z("USE_SUB_RTX")){const e=Jn(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&&(k.warning("codec ".concat(n," not included in rtpCapabilities, fallback to opus")),o=t.audioCodecs.filter((e=>(e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").includes("opus")))),Z("ENABLE_AUDIO_RED")&&0!==e.length&&(o=[...e,...o])}return o}function Jn(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 zn(e,t,i){const n=t.toString(),o=Zn(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=Qn(s,i||{}),null==o||o(s||""),await e.setLocalDescription({type:"answer",sdp:s})}function Qn(e,t,i){const n=Te(e),{useXR:o}=t;return n.mediaDescriptions.forEach((e=>{e.attributes.mid&&(Array.isArray(i)&&!i.includes(e.attributes.mid)||("audio"===e.media.mediaType&&qn(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"})}))))})),Ce(n)}function Zn(e,t,i,n){if(Z("SDP_LOGGING"))return k.upload("exchanging ".concat(i," ").concat(t," SDP during P2PConnection.").concat(n,"\n"),e),"offer"===t?e=>{Zn(e,"answer","local"===i?"remote":"local",n)}:void 0}function $n(e){const t=Z("COMPATIBLE_SDP_EXTENSION");return!!(Array.isArray(t)&&t.length>0)&&t.some((t=>e.includes(t)))}function eo(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 to(e,t){return typeof Z(e)===t?Z(e):void 0}const io={};function no(e){const t=io[e];if(!t)throw new se(q.INVALID_OPERATION,"".concat(e," not found, please use AgoraRTC.use(").concat(e,"Service) to load it first"));return t}function oo(e,t){return no("DataStream").create(e,t)}function ao(){return no("InterceptFrame").create()}const so=new Map;class ro extends Q{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(Li.CONNECTION_STATE_CHANGE,e,t,this._disconnectedReason):this.emit(Li.CONNECTION_STATE_CHANGE,e,t)}get joinGatewayStartTime(){return this._joinGatewayStartTime}set joinGatewayStartTime(e){k.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.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:di(di({},t),{},{retryConfig:t.websocketRetryConfig}),store:e},null===(n=(o=no("P2PChannel")).createSubmodule)||void 0===n?void 0:n.call(o,i)):new Tn(di(di({},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=so.get(e.cname);if(o||(o=new Map,so.set(e.cname,o)),this._isProactiveJoin=!0,o.has(e.uid)){const t=new U(q.UID_CONFLICT);throw M.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{k.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,k.debug("[".concat(this.store.clientId,"] websocket join uid ").concat(a," cost ").concat(Date.now()-this.joinGatewayStartTime))}catch(t){var r;throw k.error("[".concat(this.store.clientId,"] User join failed"),t.toString()),M.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(),k.debug("[".concat(this.store.clientId,"] Connected to gateway server")),this.trafficStatsInterval=window.setInterval((()=>{this.updateTrafficStats().catch((e=>{k.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(Li.NETWORK_QUALITY,{downlinkNetworkQuality:6,uplinkNetworkQuality:6}):this._signalTimeout?this.emit(Li.NETWORK_QUALITY,{downlinkNetworkQuality:5,uplinkNetworkQuality:5}):"CONNECTED"===this.state&&this._statsCollector.trafficStats?this.emit(Li.NETWORK_QUALITY,{uplinkNetworkQuality:yn(this._statsCollector.trafficStats.B_unq),downlinkNetworkQuality:yn(this._statsCollector.trafficStats.B_dnq)}):this.emit(Li.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!==ue.FALLBACK&&(this.state="DISCONNECTING");try{e||this.signal.connectionState!==mi.CONNECTED||await ve(this.signal.request(Ti.LEAVE,void 0,!0),3e3)}catch(e){k.warning("[".concat(this.store.clientId,"] leave request failed, ignore"),e)}this.signal.close(t),t!==ue.FALLBACK&&(this.state="DISCONNECTED"),this.reset()}}async publish(e,t,i){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new U(q.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:Z("PUB_EXTEND"),twcc:!!Z("PUBLISH_TWCC"),rtx:!!Z("USE_PUB_RTX")};try{return(await this.signal.request(Ti.PUBLISH,n,!0))._message}catch(n){if(i&&n.data&&n.data.code===Si.ERR_PUBLISH_REQUEST_INVALID)return k.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 U(q.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(Ti.PUBLISH_DATASTREAM,o,!0)}catch(n){if(i&&n.data&&n.data.code===Si.ERR_PUBLISH_REQUEST_INVALID)return k.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 U(q.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));await this.signal.request(Ti.UNPUBLISH,{stream_id:t,ortc:e},!0)}catch(e){k.warning("[".concat(this.store.clientId,"] unpublish warning: "),e)}}async unpublishDataChannel(e){try{if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new U(q.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));await Promise.all(e.map((e=>this.signal.request(Ti.UNPUBLISH_DATASTREAM,{channel_id:e},!0))))}catch(e){k.warning("unpublish datachannels warning: ",e)}}async presubscribe(e,t,i){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new U(q.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:!!Z("SUBSCRIBE_TWCC"),rtx:!!Z("USE_SUB_RTX")||void 0,extend:Z("SUB_EXTEND"),svc:Array.isArray(Z("SVC"))&&0!==Z("SVC").length?Z("SVC"):void 0};try{return await this.signal.request(Ti.PRE_SUBSCRIBE,n,!0)}catch(n){if(i&&n.data&&n.data.code===Si.ERR_SUBSCRIBE_REQUEST_INVALID)return k.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 U(q.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:!!Z("SUBSCRIBE_TWCC"),rtx:!!Z("USE_SUB_RTX"),extend:Z("SUB_EXTEND"),ssrcId:t.ssrcId,svc:Array.isArray(Z("SVC"))&&0!==Z("SVC").length?Z("SVC"):void 0};try{return(await this.signal.request(Ti.SUBSCRIBE,n,!0))._message}catch(n){if(i&&n.data&&n.data.code===Si.ERR_SUBSCRIBE_REQUEST_INVALID)return k.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 U(q.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(Ti.SUBSCRIBE_DATASTREAM,n,!0)}catch(n){if(i&&n.data&&n.data.code===Si.ERR_SUBSCRIBE_REQUEST_INVALID)return k.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 U(q.INVALID_OPERATION,"can not massSubscribe when connection state is ".concat(this.state));const i={p2p_id:this.store.p2pId,users:e,dtx:!1,rtx:!!Z("USE_SUB_RTX"),twcc:!!Z("SUBSCRIBE_TWCC"),svc:Array.isArray(Z("SVC"))&&0!==Z("SVC").length?Z("SVC"):void 0};try{return await this.signal.request(Ti.SUBSCRIBE_STREAMS,i,!0)}catch(i){if(t&&i.data&&i.data.code===Si.ERR_SUBSCRIBE_REQUEST_INVALID)return k.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(Ti.SET_VIDEO_PROFILE,t);k.debug("[".concat(this.store.clientId,"] encoder config is not complete, do not report to gateway"))}async unsubscribe(e,t){try{await this.signal.request(Ti.UNSUBSCRIBE,{p2p_id:this.store.p2pId,ortc:e,stream_id:t},!0)}catch(e){k.warning("[".concat(this.store.clientId,"] unsubscribe warning: "),e)}}async unsubscribeDataChannel(e,t){try{if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new U(q.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));await Promise.all(e.map((e=>this.signal.request(Ti.UNSUBSCRIBE_DATASTREAM,{stream_id:e,uid:t},!0))))}catch(e){k.warning("unsubscribeDataChannel warning: ",e)}}async massUnsubscribe(e){try{await this.signal.request(Ti.UNSUBSCRIBE_STREAMS,e,!0)}catch(e){k.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(Ti.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(Ti.GATEWAY_INFO)}async renewToken(e){await this.signal.request(Ti.RENEW_TOKEN,e),this.key=e.token}updateClientRole(e,t){t&&(this._clientRoleOptions=Object.assign({},t)),Z("CLIENT_ROLE_OPTIONS")&&(k.debug("[".concat(this.store.clientId,"] Set roleOptions for ").concat(JSON.stringify(Z("CLIENT_ROLE_OPTIONS"))," instead of ").concat(JSON.stringify(this._clientRoleOptions)," ")),this._clientRoleOptions=Object.assign({},Z("CLIENT_ROLE_OPTIONS"))),this.role=e}async setClientRole(e,t){if(t&&(this._clientRoleOptions=Object.assign({},t)),Z("CLIENT_ROLE_OPTIONS")&&(this._clientRoleOptions=Object.assign({},Z("CLIENT_ROLE_OPTIONS")),k.debug("[".concat(this.store.clientId,"] Set roleOptions for ").concat(JSON.stringify(Z("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,await this.signal.request(Ti.SET_CLIENT_ROLE,{role:e,level:n,delay:i,client_ts:Date.now()}),this.role=e}async setRemoteVideoStreamType(e,t){await this.signal.request(Ti.SWITCH_VIDEO_STREAM,{stream_id:e,stream_type:t})}async setDefaultRemoteVideoStreamType(e){await this.signal.request(Ti.DEFAULT_VIDEO_STREAM,{stream_type:e})}async setStreamFallbackOption(e,t){await this.signal.request(Ti.SET_FALLBACK_OPTION,{stream_id:e,fallback_type:t})}async pickSVCLayer(e,t){await this.signal.request(Ti.PICK_SVC_LAYER,{stream_id:e,spatial_layer:t.spatialLayer,temporal_layer:t.temporalLayer})}async setRTM2Flag(e){await this.signal.request(Ti.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),di({},this.inChannelInfo)}async getGatewayVersion(){return(await this.signal.request(Ti.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=so.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:Se.username,password:Se.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(di(di({},Se),{},{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(Ti.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&&ye((()=>{this.emit(Li.STREAM_TYPE_CHANGE,e.peer_uid,e.B_st)}))})),this._statsCollector.updateTrafficStats(e)}getJoinMessage(e){var t;if(!this.joinInfo||!this.key)throw new U(q.UNEXPECTED_ERROR,"can not generate join message, no join info");const i=Object.assign({},this.joinInfo.apResponse);let n=Z("REPORT_APP_SCENARIO");if("string"!=typeof n)try{n=JSON.stringify(n)}catch(e){n=void 0}var o;n&&n.length>128&&(n=void 0),this.store.hasStartJoinChannel=!0,this.store.isABTestSuccess||this.emit(Li.UPDATE_GATEWAY_CONFIG),o=this.store.clientId,Zt.includes(o)||Zt.push(o);const s=!(te()||Ne(87)||a())&&("boolean"==typeof Z("ENABLE_PRE_SUB")&&Z("ENABLE_PRE_SUB")),r=!a()&&to("ENABLE_PREALLOC_PC","boolean"),c=function(){try{const e=Z("EXPERIMENTS")||{};return"string"==typeof e||Array.isArray(e)?{}:di({},e)}catch(e){return k.debug("handle gateway attributes failed: ",e),{}}}(),d=we(87)||Oe(),l=di({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:be,browser:navigator.userAgent,process_id:Z("PROCESS_ID"),mode:this.store.useP2P?"p2p":this.spec.mode,codec:this.spec.codec,role:this.role,has_changed_gateway:this.hasChangeBGPAddress,ap_response:i,extend:Z("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:n,attributes:{userAttributes:di(di({enableEncodedTransform:!!Z("ENABLE_AUDIO_METADATA")&&d||!!Z("ENABLE_AUDIO_TOPN")&&De(Ae.CHROME,87,116)||void 0,enableAudioMetadata:!!Z("ENABLE_AUDIO_METADATA")&&d,enableAudioPts:!!Z("ENABLE_AUDIO_PTS_METADATA")&&d,topnSmoothLevel:Z("TOPN_SMOOTH_LEVEL"),topnNewSpeakerDelay:Z("TOPN_NEW_SPEAKER_DELAY"),topnSwitchHoldMs:Z("TOPN_SWITCH_HOLD_MS"),topnAudioGain:Z("TOPN_AUDIO_GAIN"),enablePublishedUserList:Z("ENABLE_PUBLISHED_USER_LIST"),maxSubscription:Z("MAX_SUBSCRIPTION"),subscribeAudioFilterTopN:to("SUBSCRIBE_AUDIO_FILTER_TOPN","number"),enablePublishAudioFilter:to("ENABLE_PUBLISH_AUDIO_FILTER","boolean"),enableUserLicenseCheck:to("ENABLE_USER_LICENSE_CHECK","boolean"),enableRTX:!0===Z("USE_PUB_RTX")||!0===Z("USE_SUB_RTX")||void 0,disableFEC:Z("DISABLE_FEC"),enableNTPReport:!!Z("ENABLE_NTP_REPORT")||void 0,enableInstantVideo:!!Z("ENABLE_INSTANT_VIDEO")||void 0,enableFulllinkAvSync:!!Z("ENABLE_FULL_LINK_AV_SYNC")||void 0,enableDataStream2:to("ENABLE_DATASTREAM_2","boolean"),enableAutFeedback:!!Z("ENABLE_AUT_FEEDBACK")||void 0,rtm2Flag:"number"==typeof this.joinInfo.rtmFlag?this.joinInfo.rtmFlag:void 0,enableUserAutoRebalanceCheck:!!Z("ENABLE_USER_AUTO_REBALANCE_CHECK"),enableXR:to("USE_XR","boolean"),enableLossbasedBwe:to("ENABLE_LOSSBASED_BWE","boolean"),enableAutCC:!!Z("ENABLE_AUT_CC")||void 0,enableCCFallback:to("ENABLE_CC_FALLBACK","boolean"),enablePreallocPC:r,preSubNum:s?to("PRE_SUB_NUM","number"):void 0,enablePubTWCC:to("PUBLISH_TWCC","boolean"),enableSubTWCC:to("SUBSCRIBE_TWCC","boolean"),enablePubRTX:to("USE_PUB_RTX","boolean"),enableSubRTX:to("USE_SUB_RTX","boolean"),enableSubSVC:Z("ENABLE_SVC")?Z("ENABLE_SVC_DEFAULT_CODECS"):Array.isArray(Z("SVC"))&&0!==Z("SVC").length?Z("SVC"):void 0,enableSvcExtended:Z("ENABLE_SVC")&&Array.isArray(Z("SVC_EXTENDED"))&&0!==Z("SVC_EXTENDED").length?Z("SVC_EXTENDED"):void 0},c),{},{audioDuplicate:to("ENABLE_AUDIO_RED","boolean")?null!==(t=to("AUDIO_DUPLICATE_NUM","number"))&&void 0!==t?t:2:void 0})},join_ts:this.joinGatewayStartTime},e);return this.joinInfo.stringUid&&(l.string_uid=this.joinInfo.stringUid),this.joinInfo.aesmode&&this.joinInfo.aespassword&&(l.aes_mode=this.joinInfo.aesmode,Z("ENCRYPT_AES")?(l.aes_secret=this.joinInfo.aespassword,l.aes_encrypt=!0):l.aes_secret=this.joinInfo.aespassword,this.joinInfo.aessalt&&(l.aes_salt=this.joinInfo.aessalt)),i.addresses[this.signal.websocket.currentURLIndex]&&(l.ap_response.ticket=i.addresses[this.signal.websocket.currentURLIndex].ticket,delete i.addresses),void 0!==this.joinInfo.defaultVideoStream&&(l.default_video_stream=this.joinInfo.defaultVideoStream),l}getRejoinMessage(){if(!this.joinInfo)throw new U(q.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(Ri.WS_RECONNECT_CREATE_CONNECTION,(e=>{this.joinGatewayStartTime=Date.now()})),this.signal.on(Ri.WS_RECONNECTING,(e=>{this.joinInfo&&M.WebSocketQuit(this.joinInfo.sid,{lts:Date.now(),succ:-1,cname:this.joinInfo.cname,uid:this.joinInfo.uid,cid:this.joinInfo.cid,errorCode:e||_e.NETWORK_ERROR}),this.joinInfo&&(this.state="RECONNECTING",M.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(Ri.WS_CLOSED,(e=>{let t;switch(e){case ue.LEAVE:t=_e.LEAVE;break;case ue.UID_BANNED:case ue.IP_BANNED:case ue.CHANNEL_BANNED:case ue.SERVER_ERROR:t=_e.SERVER_ERROR;break;case ue.FALLBACK:t=_e.FALLBACK;break;case ue.LICENSE_MISSING:case ue.LICENSE_EXPIRED:case ue.LICENSE_MINUTES_EXCEEDED:case ue.LICENSE_PERIOD_INVALID:case ue.LICENSE_MULTIPLE_SDK_SERVICE:case ue.LICENSE_ILLEGAL:case ue.TOKEN_EXPIRE:t=e;break;default:t=_e.NETWORK_ERROR}k.debug("[".concat(this.store.clientId,"] [signal] websocket closed, reason: ").concat(t||"undefined -> "+_e.NETWORK_ERROR)),this.joinInfo&&M.WebSocketQuit(this.joinInfo.sid,{lts:Date.now(),succ:e===ue.LEAVE?1:-1,cname:this.joinInfo.cname,uid:this.joinInfo.uid,cid:this.joinInfo.cid,errorCode:t}),this._disconnectedReason=e,e!==ue.FALLBACK&&(this.state="DISCONNECTED"),this.reset()})),this.signal.on(Ri.WS_CONNECTED,(()=>{if(this.updateTurnConfigFromSignal(),this.state="CONNECTED",this.joinInfo){if("audience"===this.role){const e=Z("CLIENT_ROLE_OPTIONS")||this._clientRoleOptions;e&&(e.level||e.delay)&&(k.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(M.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 k.error("[".concat(this.store.clientId,"] set local access point after joined failed: ").concat(e));Pe("EVENT_REPORT_DOMAIN",e[1]),Pe("EVENT_REPORT_BACKUP_DOMAIN",e[1]),Pe("LOG_UPLOAD_SERVER","".concat(e[1],":6444"))}}})),this.signal.on(Ci.ON_UPLINK_STATS,(e=>{this._statsCollector.updateUplinkStats(e)})),this.signal.on(Ri.REQUEST_RECOVER,((e,t,i)=>{if(!this.joinInfo)return i(new U(q.UNEXPECTED_ERROR,"gateway: can not recover, no join info"));e&&(this.joinInfo.multiIP=e,this.hasChangeBGPAddress=!0),this.isSignalRecover=!0,de(this,Li.REQUEST_NEW_GATEWAY_LIST).then(t).catch(i)})),this.signal.on(Ri.REQUEST_JOIN_INFO,(async(e,t,i)=>{var n;if(this.updateTurnConfigFromSignal(),this.store.useP2P)return void e(this.getJoinMessage({ortc:{}}));const o=fe(null===(n=this.joinInfo)||void 0===n?void 0:n.turnServer);if(Z("NEW_TURN_MODE")&&o){let e=o.servers,t=o.serversFromGateway;const i=this.signal.currentURLIndex;if(e.length>0){e=[e[i%e.length]],o.servers=e}Array.isArray(t)&&t.length>0&&(t=[t[0]],o.serversFromGateway=t),k.debug("[".concat(this.store.clientId,"] use single turn, use turn server index: ").concat(i))}const{iceParameters:a,dtlsParameters:s,rtpCapabilities:r}=await de(this,Li.REQUEST_P2P_CONNECTION_PARAMS,{turnServer:o});try{e(this.getJoinMessage({ortc:{iceParameters:a,dtlsParameters:s,rtpCapabilities:r,version:"2"}}))}catch(e){t(e)}})),this.signal.on(Ri.REQUEST_REJOIN_INFO,(e=>{e(this.getRejoinMessage())})),this.signal.on(Ri.REPORT_JOIN_GATEWAY,((e,t)=>{if(!this.joinInfo)return;let i,n="";var o;e instanceof U?(i=(null===(o=e.data)||void 0===o?void 0:o.desc)||e.code,n=e.message):i=e;M.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(Ri.IS_P2P_DISCONNECTED,(e=>{e(Ee(this,Li.IS_P2P_DISCONNECTED))})),this.signal.on(Ri.DISCONNECT_P2P,(()=>{this.emit(Li.DISCONNECT_P2P)})),this.signal.on(Ri.REQUEST_SUCCESS,(()=>{this._signalTimeout=!1})),this.signal.on(Ri.REQUEST_TIMEOUT,(()=>{this._signalTimeout=!0})),this.signal.on(Ri.JOIN_RESPONSE,(e=>{const t=this.getCurrentGatewayAddress();this.emit(Li.JOIN_RESPONSE,e,t)})),this.signal.on(Ri.PRE_CONNECT_PC,(async()=>{if(this.joinInfo){this.updateTurnConfigFromSignal();const e=this.getCurrentGatewayAddress(),t=Z("FINGERPRINT")||this.joinInfo.apResponse.addresses[this.signal.currentURLIndex].fingerprint;if(e&&t){const i=Fn(e);this.emit(Li.PRE_CONNECT_PC,{candidates:i,fingerprint:t})}}})),this.signal.on(Ri.RECOVER_NOTIFICATION,(e=>{this.joinInfo&&"string"==typeof Z("AP_REQUEST_DETAIL")&&(this.joinInfo.apRequestDetail="".concat(Z("AP_REQUEST_DETAIL"),";").concat(e))}))}async tryUnsubBeforeResub(e,t){try{await this.signal.request(Ti.UNSUBSCRIBE,{p2p_id:this.store.p2pId,stream_id:e,ortc:[t]},!0)}catch(e){throw k.warning("[".concat(this.store.clientId,"] tryUnsubBeforeResub warning"),e),e}}async tryUnsubDataChannelBeforeResub(e,t){try{await this.signal.request(Ti.UNSUBSCRIBE,{stream_id:t.id},!0)}catch(e){throw k.warning("unsubscribe datachannel warning",e),e}}async tryUnpubBeforeRepub(e,t){try{await this.signal.request(Ti.UNPUBLISH,{stream_id:e,ortc:t},!0)}catch(e){throw k.warning("[".concat(this.store.clientId,"] tryUnpubBeforeRepub warning: "),e),e}}async tryUnpubDataChannelBeforeRepub(e,t){try{await this.signal.request(Ti.UNPUBLISH_DATASTREAM,{channnel_id:t.channelId},!0)}catch(e){throw k.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(Ti.UNSUBSCRIBE_STREAMS,t,!0)}catch(e){throw k.warning("[".concat(this.store.clientId,"] tryMassUnsubBeforeResub warning"),e),e}}async muteLocal(e,t){const i={action:e.find((e=>e.stream_type===Pi.Audio))?"mute_local_audio":"mute_local_video",p2p_id:this.store.p2pId,ortc:e,stream_id:t};try{await this.signal.request(Ti.CONTROL,i,!0,!0)}catch(e){throw k.warning("[".concat(this.store.clientId,"] gateway muteLocal warning: "),e),e}}async unmuteLocal(e,t){const i={action:e.find((e=>e.stream_type===Pi.Audio))?"unmute_local_audio":"unmute_local_video",p2p_id:this.store.p2pId,ortc:e,stream_id:t};try{await this.signal.request(Ti.CONTROL,i,!0,!0)}catch(e){throw k.warning("[".concat(this.store.clientId,"] gateway unmuteLocal warning: "),e),e}}async muteRemote(e,t){const i={action:e===Hi.AUDIO?"mute_remote_audio":"mute_remote_video",p2p_id:this.store.p2pId,stream_id:t};try{await this.signal.request(Ti.CONTROL,i,!0,!0)}catch(e){throw k.warning("[".concat(this.store.clientId,"] gateway muteRemote warning: "),e),e}}async unmuteRemote(e,t){const i={action:e===Hi.AUDIO?"unmute_remote_audio":"unmute_remote_video",p2p_id:this.store.p2pId,stream_id:t};try{await this.signal.request(Ti.CONTROL,i,!0,!0)}catch(e){throw k.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(Ti.RESTART_ICE,t,!0)}catch(e){throw k.warning("[".concat(this.store.clientId,"] P2PChannel.restartICE warning: "),e),e}}reconnect(e,t){"CONNECTED"===this.state&&this.signal.reconnect(e||void 0,t||_e.P2P_FAILED)}getCurrentGatewayAddress(){var e,t;if(!Z("GATEWAY_WSS_ADDRESS"))return Z("USE_CANDIDATE_FROM_AP_DETAIL")&&null!==(e=this.joinInfo)&&void 0!==e&&e.apGatewayAddress?(k.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(Ti.SET_PARAMETER,{enablePublishAudioFilter:e})}}let co=0,lo=0;function ho(e,t,i,n){return new Promise(((o,a)=>{t.timeout=t.timeout||Z("HTTP_CONNECT_TIMEOUT"),t.responseType=t.responseType||"json",t.data&&!i?(t.data=JSON.stringify(t.data),co+=Le(t.data)):i&&(t.data.size?co+=t.data.size:t.data instanceof FormData?co+=ke(t.data):co+=Le(JSON.stringify(t.data))),t.headers=t.headers||{},t.headers["Content-Type"]=t.headers["Content-Type"]||"application/json",t.method="POST",t.url=e,Ht.request(t).then((e=>{"string"==typeof e.data?lo+=Le(e.data):e.data instanceof ArrayBuffer||e.data instanceof Uint8Array?lo+=e.data.byteLength:lo+=Le(JSON.stringify(e.data)),n&&o({data:e.data,headers:e.headers}),o(e.data)})).catch((e=>{Ht.isCancel(e)?a(new U(q.OPERATION_ABORTED,"cancel token canceled")):"ECONNABORTED"===e.code?a(new U(q.NETWORK_TIMEOUT,e.message)):e.response?a(new U(q.NETWORK_RESPONSE_ERROR,e.response.status)):a(new U(q.NETWORK_ERROR,e.message))}))}))}const uo=()=>{const e=Z("AREAS");0===e.length&&e.push(Mi.GLOBAL);return e.reduce(((e,t,i)=>{const n=_o(t);return n?0===i?n:"".concat(e,",").concat(n):e}),"")},_o=e=>e===Mi.OVERSEA?"".concat(xi.ASIA,",").concat(xi.EUROPE,",").concat(xi.AFRICA,",").concat(xi.NORTH_AMERICA,",").concat(xi.SOUTH_AMERICA,",").concat(xi.OCEANIA):xi[e],po=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=Bi[e],n=Object.keys(i);n&&n.map((e=>{"CODE"!==e&&(t[e]=t[e].concat(i[e]))}))})),t},Eo={GLOBAL:{ASIA:[Mi.CHINA,Mi.JAPAN,Mi.INDIA,Mi.KOREA,Mi.HKMC],EUROPE:[],NORTH_AMERICA:[Mi.US],SOUTH_AMERICA:[],OCEANIA:[],AFRICA:[]}},So=Object.keys(Eo[Mi.GLOBAL]),mo=[Mi.CHINA,Mi.NORTH_AMERICA,Mi.EUROPE,Mi.ASIA,Mi.JAPAN,Mi.INDIA,Mi.OCEANIA,Mi.SOUTH_AMERICA,Mi.AFRICA,Mi.KOREA,Mi.HKMC,Mi.US],Ro=function(e,t){let i=[];if(e.includes(Mi.GLOBAL)){const a=[Mi.GLOBAL,Mi.OVERSEA],s=Object.keys(Bi);if(t===Mi.GLOBAL)throw new U(q.INVALID_PARAMS,"GLOBAL is an invalid excludedArea value");if(t===Mi.CHINA)i=[Mi.OVERSEA];else if(o=t,So.includes(o)){const e=(n=t,Eo[Mi.GLOBAL][n]||[]),o=[...a,t,...e];i=s.filter((e=>!o.includes(e)))}else if(function(e){let t=!1;return So.forEach((i=>{Eo[Mi.GLOBAL][i].includes(e)&&(t=!0)})),t}(t)){const e=function(e){let t;return So.forEach((i=>{Eo[Mi.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 mo.forEach((i=>{e.includes(i)&&t.push(i)})),t.concat(e.filter((e=>!mo.includes(e))))}(i)}else i=e;var n,o;return i};function To(e){if(!e&&Z("AREAS").includes(Mi.EXTENSIONS))return k.debug("update area from ap : reset"),void fo(Jt,!0);if(!Z("AREAS").includes(Mi.GLOBAL)||!e)return;let t=Bi.EXTENSIONS;t&&(t={CODE:_o(Mi.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")]},k.debug("update area from ap success: ".concat(e,",config is "),t),Pe("AREAS",[Mi.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];Pe(e,i[0])}else Pe(e,t[e])})))}function fo(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const i=M.reportApiInvoke(null,{name:Ue.SET_AREA,options:e,tag:Me.TRACER});try{let n=[];if("string"==typeof e&&(n=[e]),Array.isArray(e)&&(e.forEach((e=>{if(!Vi.includes(e))throw new U(q.INVALID_PARAMS,"invalid area code")})),n=e),"[object Object]"===Object.prototype.toString.call(e)){const{areaCode:t,excludedArea:i}=e;if(!t)throw new U(q.INVALID_PARAMS,"area code is needed");let o=t;"string"==typeof t&&(o=[t]),n=i?Ro(o,i):o}if(!t){if(W.AREAS){const e=new U(q.PROHIBITED_OPERATION,"setArea is prohibited because of config-distribute");return i.onError(e),void k.warning("setArea is prohibited because of config-distribute")}if(n.includes(Mi.GLOBAL)&&Z("AREAS")===Mi.EXTENSIONS){const e=new U(q.PROHIBITED_OPERATION,"setArea is prohibited because of ap extensions");return i.onError(e),void k.warning("setArea is prohibited because of ap extensions")}}Pe("AREAS",n,t);const o=po(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];Pe(e,t[0])}else Pe(e,o[e])})),k.debug("set area success:",n.join(","))}catch(e){throw i.onError(e),e}i.onSuccess()}let Co=1;function Io(e,t,i,n,o){Co+=1;const a={sid:i.sid,command:"convergeAllocateEdge",uid:"666",appId:i.appId,ts:Math.floor(Date.now()/1e3),seq:Co,requestId:Co,version:be,cname:i.cname},s={service_name:t,json_body:JSON.stringify(a)};let r,c,d=e[0];return Ve((async()=>{r=Date.now();const e=await ho(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 U(V.UNEXPECTED_RESPONSE,"live streaming ap error, code"+e.code,{retry:!0,responseTime:c});throw k.error(t.toString()),t}const i=JSON.parse(e.json_body);if(200!==i.code){const e=new U(V.UNEXPECTED_RESPONSE,"live streaming app center error, code: ".concat(i.code,", reason: ").concat(i.reason),{code:i.code,responseTime:c});throw k.error(e.toString()),e}if(!i.servers||0===i.servers.length){const e=new U(V.UNEXPECTED_RESPONSE,"live streaming app center empty server",{code:i.code,responseTime:c});throw k.error(e.toString()),e}const o=function(e,t){return{addressList:e.servers.map((e=>"wss://".concat(e.address.replace(/\./g,"-"),".").concat(Z("WORKER_DOMAIN"),":").concat(e.wss,"?serviceName=").concat(encodeURIComponent(t)))),workerToken:e.workerToken,vid:e.vid}}(i,t);return Z("LIVE_STREAMING_ADDRESS")&&(o.addressList=Z("LIVE_STREAMING_ADDRESS")instanceof Array?Z("LIVE_STREAMING_ADDRESS"):[Z("LIVE_STREAMING_ADDRESS")]),di(di({},o),{},{responseTime:c})}),((n,o)=>(M.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)=>(M.apworkerEvent(i.sid,{success:!1,sc:n.data&&n.data.code||200,serviceName:t,responseTime:c,serverIp:e[o%e.length]}),!!(n.code!==V.OPERATION_ABORTED&&n.code!==V.UNEXPECTED_RESPONSE||n.data&&n.data.retry)&&(d=e[(o+1)%e.length],!0))),o)}function Ao(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,[h,u]=wo(t,a,[Cn.CHOOSE_SERVER]);let _=oe.networkState;return Ve((async()=>{_&&oe.networkState===ne.OFFLINE&&oe.onlineWaiter&&await Promise.race([oe.onlineWaiter,ce(n&&n.maxRetryTimeout||xe.maxRetryTimeout)]),_=oe.networkState;const{data:e,headers:a}=await ho(o,{data:h,cancelToken:i,headers:{"Content-Type":"multipart/form-data;"}},!0,!0);d="1"===a.http3?1:-1,M.reportResourceTiming(o,r),vo(e,o,t,c,[Cn.CHOOSE_SERVER],d);const s=Nn(e,Cn.CHOOSE_SERVER);return yo(s),An(s,o)}),(e=>(e&&M.joinChooseServer(r,{role:l,lts:c,succ:!0,csAddr:o,opid:u,serverList:e.gatewayAddrs.map((e=>e.address)),ec:null,cid:e.cid.toString(),uid:e.uid.toString(),csIp:e.csIp,unilbsServerIds:[Cn.CHOOSE_SERVER].toString(),isHttp3:d,corssRegionTagReq:t.apRequestDetail,corssRegionTagRes:e.res.detail&&e.res.detail[38]}),!1)),(e=>e.code!==V.OPERATION_ABORTED&&(e.code===V.CAN_NOT_GET_GATEWAY_SERVER?e.data.retry:(M.joinChooseServer(r,{role:l,lts:c,succ:!1,csAddr:o,serverList:null,opid:u,ec:e.code,csIp:e.data&&e.data.csIp,unilbsServerIds:[Cn.CHOOSE_SERVER].toString(),extend:JSON.stringify({networkState:_}),isHttp3:d,corssRegionTagReq:t.apRequestDetail}),k.warning("[".concat(s||"sid-".concat(r.slice(0,6)),"] Choose server network error, retry"),e),!0))),n)}function go(e,t,i,n){let o,{url:a,areaCode:s,serviceIds:r}=e;const c=Date.now(),d=t.role,[l,h]=wo(t,s,r);let u;return Ve((async()=>{u&&oe.networkState===ne.OFFLINE&&oe.onlineWaiter&&await Promise.race([oe.onlineWaiter,ce(n&&n.maxRetryTimeout||xe.maxRetryTimeout)]),u=oe.networkState;const{data:e,headers:s}=await ho(a,{data:l,cancelToken:i,headers:{"Content-Type":"multipart/form-data;"}},!0,!0);o="1"===s.http3?1:-1,M.reportResourceTiming(a,t.sid),vo(e,a,t,c,r,o);const d=Nn(e,Cn.CHOOSE_SERVER),h=Nn(e,"proxy5"===t.cloudProxyServer?Cn.CLOUD_PROXY_5:"proxy3"===t.cloudProxyServer||"proxy4"===t.cloudProxyServer?Cn.CLOUD_PROXY:Cn.CLOUD_PROXY_FALLBACK);return yo(d),{gatewayInfo:An(d,a),proxyInfo:h,url:a}}),(e=>(e.gatewayInfo&&M.joinChooseServer(t.sid,{role:d,lts:c,succ:!0,csAddr:a,serverList:e.gatewayInfo.gatewayAddrs.map((e=>e.address)),ec:null,opid:h,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]}),e.proxyInfo&&M.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!==V.OPERATION_ABORTED&&(e.code===V.CAN_NOT_GET_GATEWAY_SERVER?e.data.retry:(M.joinWebProxyAP(t.sid,{lts:c,sucess:0,apServerAddr:a,turnServerAddrList:null,errorCode:e.code,eventType:t.cloudProxyServer,unilbsServerIds:r.toString(),extend:JSON.stringify({networkState:u})}),k.warning("[".concat(t.clientId,"] multi unilbs network error, retry"),e),!0))),n)}const vo=(e,t,i,n,o,a)=>{const{sid:s,clientId:r,cloudProxyServer:c}=i,d=[],l=r=>{4096===r.flag?M.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||M.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)k.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 U(V.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=rn(i),o={error:new U(V.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?k.warning(o.error.toString()):d.push(o),l(o)}})),d.length)throw k.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 U(V.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)))]})},yo=e=>{var t,i,n,o;if(e.addresses&&0===e.addresses.length&&0===e.code)throw new U(V.CAN_NOT_GET_GATEWAY_SERVER,"void gateway address",{retry:!0,csIp:e.detail&&e.detail[502]});Z("AP_AREA")&&(null!==(n=e.detail)&&void 0!==n&&n[23]&&"string"==typeof(null===(o=e.detail)||void 0===o?void 0:o[23])?To(e.detail[23].toLowerCase()):To());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(Z("GATEWAY_ADDRESS")&&Z("GATEWAY_ADDRESS").length>0){k.debug("assign gateway address to",Z("GATEWAY_ADDRESS"));const t=Z("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}},No=(e,t)=>{if(e.response_body&&e.response_body.length){const t=e.response_body[0];if(0!==t.buffer.code){const e=rn(t.buffer.code);throw new U(V.UPDATE_TICKET_FAILED,"[".concat(t.buffer.code,"]: ").concat(e.desc),{retry:e.retry})}return t.buffer.ticket}throw k.debug("update ticket request received ap response without response body:",t),new U(V.UPDATE_TICKET_FAILED,"cannot find response body from ap response",{retry:!1})},wo=(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:di(di(di({6:e.stringUid,11:t,12:Z("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]},Oo=(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 bo(e){return Promise.all(e.map((e=>e.then((e=>{throw e}),(e=>e))))).then((e=>{throw e}),(e=>e))}const Do=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 bo(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},Po=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 Lo(e,t,i,n){const o=async function(e,t,i,n){let o=null;const a=[],s=async()=>{const o=Z("WEBCS_DOMAIN").slice(0,Z("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:uo()}))),s=n.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:o.map((e=>e.url))}),r=await Do({fragementLength:Z("FRAGEMENT_LENGTH"),referenceList:o,asyncMapHandler:n=>(k.debug("[".concat(e.clientId,"] Connect to choose_server:"),n.url),Ao(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 ce(1e3),null!==o)return o;const s=Z("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:uo()}))),r=n.recordJoinChannelService({endTs:void 0,startTs:Date.now(),status:"pending",service:"chooseServer",urls:s.map((e=>e.url))}),c=await Do({fragementLength:Z("FRAGEMENT_LENGTH"),referenceList:s,asyncMapHandler:n=>(k.debug("[".concat(e.clientId,"] Connect to backup choose_server:"),n.url),Ao(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 bo([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 Lo(e,t,i,o);if(Z("JOIN_WITH_FALLBACK_MEDIA_PROXY")){const{gatewayInfo:n,proxyInfo:a}=await Bo(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||Se.tcpport,udpport:e.udpport||Se.udpport,username:e.username||Se.username,password:e.password||Se.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 me(i),c=a.map((e=>({turnServerURL:e.address,tcpport:e.tcpport||Se.tcpport,udpport:e.udpport||Se.udpport,username:i,password:o,forceturn:!1,security:!0})));r.push(...c)}return e.turnServer={mode:"manual",servers:r},{gatewayInfo:n}}return await Lo(e,t,i,o)}const{proxyInfo:r,gatewayInfo:c}=await Bo(e,t,i,o),d={gatewayInfo:c},l=r.map((e=>({turnServerURL:e.address,tcpport:"proxy3"===a?void 0:e.tcpport?e.tcpport:Se.tcpport,udpport:"proxy4"===a?void 0:e.udpport?e.udpport:Se.udpport,username:e.username||Se.username,password:e.password||Se.password,forceturn:"proxy4"!==a,security:"proxy5"===a})));if(o.useP2P){var h;const t=null!==(h=e.uid)&&void 0!==h?h:c.uid,i="glb:".concat(t.toString()),n=await me(i),o=r.map((e=>({turnServerURL:e.address,tcpport:"proxy3"===a?void 0:e.tcpport||Se.tcpport,udpport:"proxy4"===a?void 0:e.udpport||Se.udpport,username:i,password:n,forceturn:"proxy4"!==a,security:"proxy5"===a})));l.push(...o)}return e.turnServer={mode:"manual",servers:l},k.debug("[".concat(e.clientId,"] set proxy server: ").concat(e.proxyServer,", mode: ").concat(a)),d}async function Uo(e,t,i,n,o){const a=Z("ACCOUNT_REGISTER").slice(0,Z("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 Ve((()=>ho(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 k.error("Invalid Uint Uid ".concat(t," => ").concat(i.uid),i),M.reqUserAccount(s.sid,{lts:a,success:!1,serverAddr:r,stringUid:s.string_uid,uid:i.uid,errorCode:V.INVALID_UINT_UID_FROM_STRING_UID,extend:s}),new U(V.INVALID_UINT_UID_FROM_STRING_UID);return M.reqUserAccount(s.sid,{lts:a,success:!0,serverAddr:r,stringUid:s.string_uid,uid:i.uid,errorCode:null,extend:s}),!1}const o=rn(i.code);return o.retry&&(r=e[(n+1)%e.length]),M.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!==V.OPERATION_ABORTED&&(M.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=rn(c.code);throw new U(V.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 Mo(e,t,i){const n=Z("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 Po({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 ho(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=rn(t.code);throw new U(V.UNEXPECTED_RESPONSE,"preload sua error:".concat(e.desc),e)}if(t.uid<=0||t.uid>=Math.pow(2,32))throw new U(V.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===q.OPERATION_ABORTED||e.code===q.UNEXPECTED_RESPONSE&&!e.data.retry});return n}catch(e){throw e}}async function Vo(e,t,i){const n=Z("CDS_AP").slice(0,Z("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=Ie(),a={flag:64,cipher_method:0,features:di(di(di(di(di({install_id:Be(),device:o.name,system:o.os,system_general:navigator.userAgent,vendor:t.appId,version:be,cname:t.cname,session_id:t.sid,proxyServer:t.proxyServer,sdk_type:fn.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 Ve((()=>ho(e,{data:a,timeout:1e3,cancelToken:i,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":54}})),void 0,(e=>e.code!==V.OPERATION_ABORTED),n)}(n,e,t,i)));let o=null,a=null,s={};try{o=await bo(n)}catch(e){if(e.code===q.OPERATION_ABORTED)throw e;a=e}n.forEach((e=>e.cancel()));if(M.reportApiInvoke(e.sid,{name:Ue.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 xo(e,t){const i=Z("WEBCS_DOMAIN").concat(Z("WEBCS_DOMAIN_BACKUP_LIST")).map((e=>({url:"https://".concat(e,"/api/v2/transpond/webrtc?v=2"),areaCode:uo(),serviceIds:[Cn.CHOOSE_SERVER,Cn.CLOUD_PROXY_FALLBACK]})));try{const n=await Po({referenceList:i,asyncMapHandler:i=>async function(e,t,i){let n,{url:o,areaCode:a,serviceIds:s}=e;const r=Date.now(),[c,d]=wo(t,a,s);let l=oe.networkState;try{l&&oe.networkState===ne.OFFLINE&&oe.onlineWaiter&&await Promise.race([oe.onlineWaiter,ce(xe.maxRetryTimeout)]),l=oe.networkState;const{data:e,headers:t}=await ho(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 U(V.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=rn(n),a={error:new U(V.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?k.warning(a.error.toString()):t.push(a)}})),t.length)throw new U(V.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=Nn(e,Cn.CHOOSE_SERVER),s=Nn(e,Cn.CLOUD_PROXY_FALLBACK);return yo(a),{gatewayInfo:An(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===q.OPERATION_ABORTED||e.code===q.CAN_NOT_GET_GATEWAY_SERVER&&!e.data.retry});return n}catch(e){throw e}}async function Bo(e,t,i,n){const o=Z("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=Z("WEBCS_DOMAIN").slice(0,Z("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:uo(),serviceIds:[Cn.CHOOSE_SERVER,"proxy5"===e.cloudProxyServer?Cn.CLOUD_PROXY_5:"proxy3"===e.cloudProxyServer||"proxy4"===e.cloudProxyServer?Cn.CLOUD_PROXY:Cn.CLOUD_PROXY_FALLBACK]}})),s=n.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:o.map((e=>e.url))}),c=await Do({fragementLength:Z("FRAGEMENT_LENGTH"),referenceList:o,asyncMapHandler:n=>(k.debug("[".concat(e.clientId,"] Connect to choose_server:"),n.url),go(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 ce(1e3),null!==s)return s;const o=Z("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:uo(),serviceIds:[Cn.CHOOSE_SERVER,"proxy5"===e.cloudProxyServer?Cn.CLOUD_PROXY_5:"proxy3"===e.cloudProxyServer||"proxy4"===e.cloudProxyServer?Cn.CLOUD_PROXY:Cn.CLOUD_PROXY_FALLBACK]}})),c=n.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:o.map((e=>e.url))}),d=await Do({fragementLength:Z("FRAGEMENT_LENGTH"),referenceList:o,asyncMapHandler:n=>(k.debug("[".concat(e.clientId,"] Connect to backup choose_server:"),n.url),go(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,h,u;try{({gatewayInfo:l,proxyInfo:h,url:u}=await bo([c(),d()]))}catch(e){throw e[0]}if(r.length&&r.forEach((e=>e.cancel&&"function"==typeof e.cancel&&e.cancel())),!l||!h)throw new U(q.UNEXPECTED_ERROR,"missing gateway or proxy response").print();if(e.apUrl=u,"disabled"!==e.cloudProxyServer&&Array.isArray(o)&&u){const t=/^https?:\/\/(.+?)(\/.*)?$/.exec(u)[1];o.includes(t)&&(e.proxyServer=t,k.setProxyServer(t),M.setProxyServer(t))}return s={gatewayInfo:l,proxyInfo:await wn(h,l.uid)},s}async function Fo(e,t,i){let n=null;const o=[],a=async a=>{const s=Z(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 ce(1e3),null!==n)?n:await Do({fragementLength:Z("FRAGEMENT_LENGTH"),referenceList:s,asyncMapHandler:n=>(k.debug("[".concat(e.clientId,"] update ticket, Connect to ").concat(a?"backup":""," choose_server:"),n),function(e,t,i,n){const[o]=Oo(t,[Cn.CHOOSE_SERVER]);let a=oe.networkState;return Ve((async()=>{a&&oe.networkState===ne.OFFLINE&&oe.onlineWaiter&&await Promise.race([oe.onlineWaiter,ce(n&&n.maxRetryTimeout||xe.maxRetryTimeout)]),a=oe.networkState;const t=await ho(e,{data:o,cancelToken:i,headers:{"Content-Type":"multipart/form-data;"}},!0);return No(t,e)}),(()=>!1),(e=>e.code!==V.OPERATION_ABORTED&&(e.code===V.UPDATE_TICKET_FAILED?e.data.retry:(k.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 bo([a(!1),a(!0)]),o.length&&o.forEach((e=>e.cancel&&"function"==typeof e.cancel&&e.cancel())),n}catch(e){throw e[0]}}class jo extends Q{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 ie("config-distribute",e),this.store=t}startGetConfigDistribute(e,t){this.joinInfo=e,this.cancelToken=t,this.interval&&this.stopGetConfigDistribute(),Z("ENABLE_CONFIG_DISTRIBUTE")&&(this.updateConfigDistribute(),this.interval=window.setInterval((()=>{this.updateConfigDistribute()}),Z("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;M.reportApiInvoke(null,{options:void 0,name:Ue.LOAD_CONFIG_FROM_LOCALSTORAGE,tag:Me.TRACER}).onSuccess(JSON.stringify(W))}if(!this.joinInfo||!this.cancelToken||!this.retryConfig)return void k.debug("[config-distribute] get config distribute interrupted have no joininfo");let e;const t=await this.mutex.lock();try{e=await Vo(this.joinInfo,this.cancelToken,this.retryConfig),k.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 U(q.NETWORK_RESPONSE_ERROR,e);k.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(Fi.UPDATE_BITRATE_LIMIT,e):this.emit(Fi.UPDATE_BITRATE_LIMIT,e))}getLowStreamConfigDistribute(){return this.limit_bitrate&&di({},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===K.REALTIME&&(d=1):Object.keys(r).some((e=>Object.prototype.hasOwnProperty.call(Y,e)||!ei()&&Object.prototype.hasOwnProperty.call(H,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&&M.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){k.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]=di(di({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===K.REALTIME||Object.prototype.hasOwnProperty.call(Y,i))&&(W[i]=n,G[i]=n,k.debug("Update realtime parameters from config distribute",i,n)),o||ei()||!Object.prototype.hasOwnProperty.call(H,i)||(W[i]=n,G[i]=n,k.debug("Update gateway parameters from config distribute",i,n)))}))}catch(t){k.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),k.debug("Caching global parameters ".concat(o))}catch(e){k.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(G,i)){const{value:n,expires:o}=e[i];if(o&&o<=t)return;Fe(G[i],n)||(W[i]=n,G[i]=n,this.emit(Fi.UPDATE_CLIENT_ROLE_OPTIONS,n),k.debug("Updating client role options: ".concat(JSON.stringify(n))))}}))}catch(e){k.error("Error handling global parameter config:",e.message)}}}class Go extends Q{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))}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(Z("STATS_UPDATE_INTERVAL")>500)return;this.resultStorage.has(e)||this.resultStorage.set(e,{result:[],isPrevNormal:!0});const n=this.resultStorage.get(e);if(n&&(n.result.push(i),n.result.length>=5)){const i=n.result.includes(!0);n.isPrevNormal&&!i&&this.emit("exception",Wo[e],e,t),!n.isPrevNormal&&i&&this.emit("exception",Wo[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 s&&!t.isActive||(!!t.muted||0!==e.sendVolumeLevel)}checkFramerateInput(e,t){let i=null;t._encoderConfig&&t._encoderConfig.frameRate&&(i=gn(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)}checkSendVideoBitrate(e,t){return!!t.muted||0!==e.sendBitrate}checkSendAudioBitrate(e,t){return t instanceof s&&!t.isActive||(!!t.muted||0!==e.sendBitrate)}checkVideoDecode(e){return 0===e.receiveBitrate||0!==e.decodeFrameRate}}const Wo={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};const Ho=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 Ko{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=Re.L1T1,this.updateStats=()=>{this.p2pChannel&&(this.updateRemoteStats(this.p2pChannel),this.updateLocalStats(this.p2pChannel))},this.store=e,this.exceptionMonitor=new Go,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(Xi.LocalAudioTrack)||di({},r)}getLocalVideoTrackStats(){return this.localStats.get(Xi.LocalVideoTrack)||di({},c)}getRemoteAudioTrackStats(e){const t=(e,t)=>{if(!this.trafficStats)return t;const i=this.trafficStats.peer_delay.find((t=>t.peer_uid===e));return i&&(t.publishDuration=i.B_ppad+(Date.now()-this.trafficStats.timestamp)),t},i={};if(e){var n;const o=null===(n=this.remoteStats.get(e))||void 0===n?void 0:n.audioStats;o&&(i[e]=t(e,o))}else Array.from(this.remoteStats.entries()).forEach((e=>{let[n,{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(Xi.LocalAudioTrack);o&&(e+=o.sendBytes,t+=o.sendBitrate);const a=this.localStats.get(Xi.LocalVideoTrack);a&&(e+=a.sendBytes,t+=a.sendBitrate);const s=this.localStats.get(Xi.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?Ho.measureFromSubscribeStart(this.store.clientId,i.videoSSRC):0,o=null!=i&&i.audioSSRC?Ho.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&&k.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 Xi.LocalVideoTrack:case Xi.LocalVideoLowTrack:{const t=n,s=di({},c),r=e.getStats(),d=e.getLocalMedia(i);if(r){const i=r.videoSend.find((e=>e.ssrc===(null==d?void 0:d.ssrcs[0].ssrcId)));if(i){const n=e.getLocalVideoSize(),a=e.getEncoderConfig(Xi.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&&(k.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&&d&&this.exceptionMonitor.setLocalVideoStats(this.store.uid,d.track,s);break}case Xi.LocalAudioTrack:{const t=n,o=di({},r),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(Xi.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,u=a,_=r,p=di({},d),E=di({},l),S=di({},h),{audioTrack:m,videoTrack:R,audioSSRC:T,videoSSRC:f}=e.getRemoteMedia(o);let C;C=this.store.useP2P?e.getStats(!0):e.getStats();const I=null===(i=C)||void 0===i?void 0:i.audioRecv.find((e=>e.ssrc===T)),A=null===(n=C)||void 0===n?void 0:n.videoRecv.find((e=>e.ssrc===f)),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||(p.codecType=I.codec),I.outputLevel?p.receiveLevel=Math.round(32767*I.outputLevel):m&&(p.receiveLevel=Math.round(32767*m.getVolumeLevel())),p.receiveBytes=I.bytes,p.receivePackets=I.packets,p.receivePacketsLost=I.packetsLost,p.receivePacketsDiscarded=I.packetsDiscarded,p.packetLossRate=p.receivePacketsLost/(p.receivePackets+p.receivePacketsLost),p.receiveBitrate=c?8*Math.max(0,p.receiveBytes-c.receiveBytes):0,p.totalDuration=c?c.totalDuration+1:1,p.totalFreezeTime=c?c.totalFreezeTime:0,p.freezeRate=p.totalFreezeTime/p.totalDuration,p.receiveDelay=I.jitterBufferMs,p.totalDuration>10&&Ko.isRemoteAudioFreeze(m)&&(p.totalFreezeTime+=1)),A){var v;"H264"!==A.codec&&"H265"!==A.codec&&"VP8"!==A.codec&&"VP9"!==A.codec&&"AV1X"!==A.codec&&"AV1"!==A.codec||(E.codecType=A.codec),E.receiveBytes=A.bytes,E.receiveBitrate=u?8*Math.max(0,E.receiveBytes-u.receiveBytes):0,E.decodeFrameRate=A.decodeFrameRate<0?0:A.decodeFrameRate,E.renderFrameRate=A.decodeFrameRate<0?0:A.decodeFrameRate,A.outputFrame&&(E.renderFrameRate=A.outputFrame.frameRate),A.receivedFrame?(E.receiveFrameRate=A.receivedFrame.frameRate,E.receiveResolutionHeight=A.receivedFrame.height,E.receiveResolutionWidth=A.receivedFrame.width):R&&(E.receiveResolutionHeight=R._videoHeight||0,E.receiveResolutionWidth=R._videoWidth||0),void 0!==A.framesRateFirefox&&(E.receiveFrameRate=Math.round(A.framesRateFirefox)),E.receivePackets=A.packets,E.receivePacketsLost=A.packetsLost,E.packetLossRate=E.receivePacketsLost/(E.receivePackets+E.receivePacketsLost);const t=u?u.totalFreezeTime:0,i=u?u.totalDuration:0;E.totalDuration=u?u.totalDuration+1:1,E.totalFreezeTime=null!==(v=A.totalFreezesDuration)&&void 0!==v?v:t||0,E.receiveDelay=A.jitterBufferMs||0;const n=!!f&&e.getRemoteVideoIsReady(f);void 0===A.totalFreezesDuration&&R&&n&&Ko.isRemoteVideoFreeze(R,A,_)&&(E.totalFreezeTime+=1),E.freezeRate=Math.max(0,Math.min((E.totalFreezeTime-t)/(E.totalDuration-i),1))}g&&(p.end2EndDelay=g.B_ad,E.end2EndDelay=g.B_vd,p.transportDelay=g.B_ed,E.transportDelay=g.B_ed,p.currentPacketLossRate=g.B_ealr4/100,E.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:p,videoStats:E,videoPcStats:A,networkStats:S}),m&&this.exceptionMonitor.setRemoteAudioStats(m,p),R&&this.exceptionMonitor.setRemoteVideoStats(R,E)}))}}class Yo{constructor(){this.destChannelMediaInfos=new Map,this.srcChannelMediaInfo=void 0}setSrcChannelInfo(e){wi(e),this.srcChannelMediaInfo=e}addDestChannelInfo(e){wi(e),this.destChannelMediaInfos.set(e.channelName,e)}removeDestChannelInfo(e){gi(e),this.destChannelMediaInfos.delete(e)}getSrcChannelMediaInfo(){return this.srcChannelMediaInfo}getDestChannelMediaInfo(){return this.destChannelMediaInfos}}function qo(e){if(!(e instanceof Yo)){return new U(V.INVALID_PARAMS,"Config should be instance of [ChannelMediaRelayConfiguration]").throw()}const t=e.getSrcChannelMediaInfo(),i=e.getDestChannelMediaInfo();if(!t){return new U(V.INVALID_PARAMS,"srcChannelMediaInfo should not be empty").throw()}if(0===i.size){return new U(V.INVALID_PARAMS,"destChannelMediaInfo should not be empty").throw()}}class Xo{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 Jo="9",zo=4e4;class Qo{get localCapabilities(){return fe(this._localCapabilities)}get rtpCapabilities(){return fe(this._rtpCapabilities)}get candidates(){return fe(this._candidates)}get iceParameters(){return fe(this._iceParameters)}get dtlsParameters(){return fe(this._dtlsParameters)}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];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._dtlsParameters=void 0,this.setup=void 0,this.currentMidIndex=void 0,this.cname=void 0,this.firefoxSsrcMidMap=new Map,this._isUseExtmapAllowMixed=t,e=fe(e);const{iceParameters:i,dtlsParameters:n,candidates:o,rtpCapabilities:a,setup:s,localCapabilities:r,cname:c}=e;this._rtpCapabilities=a,this._candidates=o,this._originCandidates=fe(o),this._iceParameters=i,this._dtlsParameters=n,this._localCapabilities=r,this.setup=s,this.cname=c,this.sessionDesc=this.updateRemoteRTPCapabilities(a),this.currentMidIndex=this.sessionDesc.mediaDescriptions.length-1}preloadRemoteMedia(e){const t=this.candidates,i=this.dtlsParameters,n=this.iceParameters,o=this.rtpCapabilities.send;let a=this.sessionDesc.mediaDescriptions.length-1;for(let s=1;s<e;s++){const e=2*s+2e4,r=2*s+zo,{ssrcs:c,ssrcGroups:d}=jn([{ssrcId:e}],this.cname),{ssrcs:l,ssrcGroups:h}=jn([{ssrcId:r,rtx:Z("USE_SUB_RTX")?r+1:void 0}],this.cname);this.sessionDesc.mediaDescriptions.push({media:{mediaType:"video",port:Jo,protos:["UDP","TLS","RTP","SAVPF"],fmts:o.videoCodecs.map((e=>e.payloadType.toString(10)))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:n.iceUfrag,icePwd:n.icePwd,unrecognized:[],candidates:t,extmaps:o.videoExtensions,fingerprints:i.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:l,ssrcGroups:h,rtcpFeedbackWildcards:[],payloads:o.videoCodecs,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:"sendonly",rtcpMux:!0,rtcpRsize:!0,mid:"".concat(++a)}}),this.sessionDesc.mediaDescriptions.push({media:{mediaType:"audio",port:Jo,protos:["UDP","TLS","RTP","SAVPF"],fmts:o.audioCodecs.map((e=>e.payloadType.toString(10)))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:n.iceUfrag,icePwd:n.icePwd,unrecognized:[],candidates:t,extmaps:o.audioExtensions,fingerprints:i.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:c,ssrcGroups:d,rtcpFeedbackWildcards:[],payloads:o.audioCodecs,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:"sendonly",rtcpMux:!0,rtcpRsize:!0,mid:"".concat(++a)}}),this.currentMidIndex+=2}this.updateBundleMids()}toString(){return Ce(this.sessionDesc)}send(e,t,i,n){const{ssrcs:o,ssrcGroups:a}=jn(t,this.cname,Z("SYNC_GROUP")?i:void 0),s=this.findPreloadMediaDesc(o);if(s){if(te()&&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()||Ge()||Z("ENABLE_ENCODED_TRANSFORM")&&We())||0===t&&Z("USE_SUB_RTX")||He()?(i=this.createOrRecycleSendMedia(e,o,a,"sendonly",n),this.updateBundleMids()):(i=fe(this.sessionDesc.mediaDescriptions[t]),i.attributes.direction="sendonly",i.attributes.ssrcs=o,i.attributes.ssrcGroups=a,this.sessionDesc.mediaDescriptions[t]=this.mungSendMediaDesc(i,n)),te()&&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||te()||He()?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||Te((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;const n=this.rtpCapabilities.send,o=this.localCapabilities.send;for(const e of t.mediaDescriptions){if(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(0===n.videoCodecs.length){const t=o.videoCodecs.filter((e=>{var t;return null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase().includes("vp8")}))||[o.videoCodecs[0]];e.media.fmts=t.map((e=>e.payloadType.toString(10))),e.attributes.payloads=t,e.attributes.extmaps=[]}else if(e.media.fmts=n.videoCodecs.map((e=>e.payloadType.toString(10))),e.attributes.payloads=n.videoCodecs,e.attributes.extmaps=n.videoExtensions,Z("PRELOAD_MEDIA_COUNT")>0){const{ssrcs:t,ssrcGroups:i}=jn([{ssrcId:zo,rtx:Z("USE_SUB_RTX")?40001:void 0}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i}if("audio"===e.media.mediaType)if(0===n.audioCodecs.length){const t=o.audioCodecs.filter((e=>{var t;return null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase().includes("opus")}))||[o.audioCodecs[0]];e.media.fmts=t.map((e=>e.payloadType.toString(10))),e.attributes.payloads=t,e.attributes.extmaps=[]}else if(e.media.fmts=n.audioCodecs.map((e=>e.payloadType.toString(10))),e.attributes.payloads=n.audioCodecs,e.attributes.extmaps=n.audioExtensions,qn(e),Z("PRELOAD_MEDIA_COUNT")>0){const{ssrcs:t,ssrcGroups:i}=jn([{ssrcId:2e4}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i}}return this.sessionDesc=t,this.currentMidIndex=t.mediaDescriptions.length-1,this.sessionDesc}updateCandidates(e){const t=this._originCandidates.filter((e=>"udp"===e.transport)),i=[];if(t.forEach((e=>{i.push(di(di({},e),{},{foundation:"tcpcandidate",priority:Number(e.priority)-1+"",transport:"tcp",port:Number(e.port)+90+""}))})),0!==t.length){switch(e){case Ki.TCP_RELAY:this._candidates=i;break;case Ki.UDP_TCP_RELAY:case Ki.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=fe(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(te()){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:Jo,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=Xn(s,r,this.localCapabilities.send,s===Hi.VIDEO?n:o),d=s===Hi.VIDEO?r.videoExtensions:r.audioExtensions;this.currentMidIndex+=1;const l="".concat(this.currentMidIndex);let h={media:{mediaType:s,port:Jo,protos:["UDP","TLS","RTP","SAVPF"],fmts:c.map((e=>e.payloadType.toString(10)))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:d,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:c,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:i,rtcpMux:!0,rtcpRsize:!0,mid:"".concat(l)}};h=this.mungRecvMediaDsec(h,e,a);const u=this.findFirstClosedMedia(s);if(u){const e=this.sessionDesc.mediaDescriptions.indexOf(u);this.sessionDesc.mediaDescriptions[e]=h}else this.sessionDesc.mediaDescriptions.push(h);return h}updateRemoteCodec(e,t,i){const n=[...new Set(this._rtpCapabilities.recv.videoCodecs.map((e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"")).filter((e=>Object.keys(Ke).includes(e))))],o=new Set(t);if(n.every((e=>o.has(e))))return k.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 k.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(k.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 k.debug("updateRemoteCodec failed, because cannot find mids, mids: ".concat(e,", codecs: ").concat(t)),!1;if(Z("USE_PUB_RTX")||Z("USE_SUB_RTX")){const e=Jn(a,this.rtpCapabilities.recv.videoCodecs);a.push(...e)}this._rtpCapabilities.recv.videoCodecs=a;const c=this.localCapabilities.send,d=this.rtpCapabilities.recv,l=Xn(Hi.VIDEO,d,c,i);return r.forEach((e=>{const t=l.map((e=>e.payloadType.toString(10)));k.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,s=e===Hi.VIDEO?a.videoCodecs:a.audioCodecs,r=e===Hi.VIDEO?a.videoExtensions:a.audioExtensions;this.currentMidIndex+=1;const c="".concat(this.currentMidIndex);let d={media:{mediaType:e,port:Jo,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:n,rtcpMux:!0,rtcpRsize:!0,mid:"".concat(c)}};d=this.mungSendMediaDesc(d,o);const l=this.findFirstClosedMedia(e);if(l){const e=this.sessionDesc.mediaDescriptions.indexOf(l);this.sessionDesc.mediaDescriptions[e]=d}else this.sessionDesc.mediaDescriptions.push(d);return d}updateBundleMids(){this.sessionDesc.attributes.groups[0].identificationTag=this.sessionDesc.mediaDescriptions.filter((e=>"0"!==e.media.port)).map((e=>e.attributes.mid))}mungRecvMediaDsec(e,t,a){const s=fe(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),Gn(s,t),function(e,t){if(!(t instanceof i&&t._encoderConfig&&-1===t._hints.indexOf(o.SCREEN_TRACK)))return;const a=t._encoderConfig;n().supportMinBitrate&&a.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(a.bitrateMin))})),n().supportMinBitrate&&!t._hints.includes(o.LOW_STREAM)&&a.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(Z("X_GOOGLE_START_BITRATE")||Math.floor(a.bitrateMax)))}))}(s,t),function(e){if("video"!==e.media.mediaType)return;const t=Ie();if(t.name!==Ae.SAFARI&&t.os!==ge.IOS)return;const i=e.attributes.extmaps.findIndex((e=>/video-orientation/g.test(e.extensionName)));-1!==i&&e.attributes.extmaps.splice(i,1)}(s),Wn(s,a,this.localCapabilities.send),s}mungSendMediaDesc(e,t){const i=fe(e);return Wn(i,t,this.localCapabilities.recv),qn(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=>te()?"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 Zo=function(e){return e[e.DOWN=0]="DOWN",e[e.UP=1]="UP",e}(Zo||{});const $o=new Map;function ea(e,t,i,n){let{scale:o}=e;if(0===o&&n===Zo.UP||o>=t.length-1&&n===Zo.DOWN)return e;let a=di(di({},e),{},{scale:n===Zo.DOWN?++o:--o});switch(i){case"maintain-framerate":a=di(di({},a),t[o].motion);break;case"maintain-resolution":a=di(di({},a),t[o].detail);break;case"balanced":a=di(di({},a),t[o].balanced)}return a}function ta(e,t){if(t){const i={overUse:0,underUse:0,adaptationList:ia(t)};$o.set(e,i)}else $o.delete(e)}function ia(e){const t=di({},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:h,BWE_SCALE_DOWN_THRESHOLD:u,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:T,DETAIL_FRAMERATE_FACTOR:f,DETAIL_BITRATE_FACTOR:C}=qe,I=Math.min(t.frameRate,r),A=[{scale:0,threshold:{bwe_down:Math.round(Math.pow(u,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(h,e)*i),bwe_down:Math.round(Math.pow(u,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(T,e)*i),l),bitrateMin:Math.max(Math.round(Math.pow(T,e)*a),d)},g={scaleResolutionDownBy:1,frameRate:Math.max(Math.round(Math.pow(f,e)*n),s),bitrateMax:Math.max(Math.round(Math.pow(C,e)*i),l),bitrateMin:Math.max(Math.round(Math.pow(C,e)*a),d)};A.push({scale:e,threshold:t,balanced:r,motion:c,detail:g})}return A}function na(e,t,i,n,o,a){const s=$o.get(e)||{overUse:0,underUse:0,adaptationList:ia(o)},{adaptationList:r}=s;$o.set(e,s);const{OVERUSE_TIMES_THRESHOLD:c,UNDERUSE_TIMES_THRESHOLD:d}=qe,{scale:l}=n;let h,u;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 Z("FORCE_AG_HIGH_FRAMERATE")&&"maintain-framerate"===n&&(o=i[0].threshold.fps_down),e<o}(t,l,r,a)&&(s.overUse++,u=Ye.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++,u=Ye.BANDWIDTH,s.overUse>c)?(s.overUse=0,s.underUse=0,h=ea(n,r,a,Zo.DOWN),[h,u]):("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 Z("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,h=ea(n,r,a,Zo.UP),0===h.scale&&(u=Ye.NONE))),[h,u])}const oa=new Map;function aa(e,t){const i=oa.get(e);if(i){const{timer:t}=i;window.clearTimeout(t),oa.delete(e)}t.qualityLimitationReason=Ye.NONE,ta(e)}function sa(e){const t=n();if(e.some((e=>e._bypassWebAudio)))throw new se(q.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio");if(!t.webAudioMediaStreamDest)throw new se(q.NOT_SUPPORTED,"cannot publish multiple tracks because your browser does not support audio mixing")}function ra(e,t){sa(e);const i=t||new s;return e.forEach((e=>i.addAudioTrack(e))),i}const ca=!n().supportUnifiedPlan||Z("CHROME_FORCE_PLAN_B")&&Ze();function da(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i;return ca?(i={spec:t,store:e},no("PlanBConnection").create(i)):new _a(t,e)}function la(e){return e&&("disconnected"===e.iceConnectionState||"checking"===e.iceConnectionState||"failed"===e.iceConnectionState)}function ha(e){try{if(e.iceServers)return!1;if(e.turnServer&&"off"!==e.turnServer.mode){if($e(e.turnServer.servers))return!1;if(Z("FORCE_TURN_TCP")||e.turnServer.servers.concat(e.turnServer.serversFromGateway||[]).some((e=>e.forceturn)))return!0}return!1}catch(e){return!1}}var ua;let _a=(ua=class e extends Wi{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(Ke).includes(e))))]}constructor(t,i){super(t,i),this.id=pe(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:Z("USE_XR")},this.localCapabilities=void 0,this.remoteCodecs=void 0,this.localCandidateCount=0,this.allCandidatesReceived=!1,this.isPreallocation=!1,this.preSSRCMap=new Map,this.dataStreamChannelMap=new Map,this.establishPromise=void 0,this.recoveredDataChannelIds=[],this.currentDataChannelId=1,this.supportAV1RtpSpec=!1,this.mutex=void 0,this.qualityLimitationReason=Ye.NONE,this.isFirstConnected=!1,this.store=i,this.forceTurn=ha(t),this.mutex=new ie("P2PConnection-mutex",i.clientId),this.peerConnection=new RTCPeerConnection(e.resolvePCConfiguration(t),{optional:[{googDscp:!0}]}),this.isFirstConnected=!1,this.statsFilter=et(this.peerConnection,Z("STATS_UPDATE_INTERVAL"),void 0,te()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1,this.establishPromise=this.establish()}getPreMedia(e){const t=this.preSSRCMap.get(e);if(void 0!==t){const e=this.peerConnection.getTransceivers().find((e=>e.mid===t));if(e)return{transceiver:e,track:e.receiver.track,id:t}}}async updateRemoteRTPCapabilities(e,t){if(this.remoteCodecs=t,!this.remoteSDP)return void k.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 k.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 Hn({filterRTX:!Z("USE_PUB_RTX")&&!Z("USE_SUB_RTX"),filterVideoFec:Z("FILTER_VIDEO_FEC"),filterAudioFec:Z("FILTER_AUDIO_FEC"),filterVideoCodec:Z("FILTER_VIDEO_CODEC")},this.extension);if(this.localCapabilities=Yn(o),this.initialOffer=i,Z("ENABLE_SVC")&&"av1"==this.store.codec){const t=await async function(){try{const e=new RTCPeerConnection;e.addTransceiver("video",{direction:"sendonly",sendEncodings:[{scalabilityMode:Re.L1T3}]});const t=await e.createOffer();if(!t.sdp)return void e.close();const i=Te(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&&$n(i.sdp)&&(a=fe(o),(t=a).send&&(kn(Hi.VIDEO,t.send.videoExtensions),kn(Hi.AUDIO,t.send.audioExtensions)),t.recv&&(kn(Hi.VIDEO,t.recv.videoExtensions),kn(Hi.AUDIO,t.recv.audioExtensions)),t.sendrecv&&(kn(Hi.VIDEO,t.sendrecv.videoExtensions),kn(Hi.AUDIO,t.sendrecv.audioExtensions))),di(di({},n),{},{rtpCapabilities:a||o,offerSDP:i.sdp})}catch(e){throw new se(q.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&&$n(this.initialOffer.sdp)&&(t=e.rtpCapabilities,i=this.localCapabilities,t.send&&(Ln(Hi.VIDEO,t.send.videoExtensions,i.send.videoExtensions),Ln(Hi.AUDIO,t.send.audioExtensions,i.send.audioExtensions)),t.recv&&(Ln(Hi.VIDEO,t.recv.videoExtensions,i.recv.videoExtensions),Ln(Hi.AUDIO,t.recv.audioExtensions,i.recv.audioExtensions))),this.remoteSDP=new Qo(di(di({},e),{},{localCapabilities:this.localCapabilities}),this.supportAV1RtpSpec),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=Qn(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 s=this.peerConnection.getTransceivers()[0];if(null!=s&&s.receiver&&this.tryBindTransportEvents(s.receiver),Z("PRELOAD_MEDIA_COUNT")>0){this.remoteSDP.preloadRemoteMedia(Z("PRELOAD_MEDIA_COUNT"));const e=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:e});const t=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(t)}const{preSSRCs:r}=e;if(Array.isArray(r)&&r.length>0){const{mids:e}=this.remoteSDP.batchSend(r.map((e=>({kind:e.kind,ssrcMsg:[{ssrcId:e.ssrcId,rtx:e.rtx}],mslabel:e.mslabel}))));e.forEach(((e,t)=>{this.preSSRCMap.set(r[t].ssrcId,e)})),await zn(this.peerConnection,this.remoteSDP,this.extension),k.debug("[".concat(this.store.clientId,"] [P2PConnection] pre-batchReceive exchange SDP."))}}catch(e){throw new se(q.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(e.toString()))}var t,i}async updateRemoteConnect(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.updateRemoteConnect before remote SDP created");const{rtpCapabilities:t}=e;this.remoteSDP.updateRemoteRTPCapabilities(t),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0&&this.remoteSDP.updateRemoteCodec([],this.remoteCodecs,this.store.codec);const{preSSRCs:i}=e;if(Array.isArray(i)&&i.length>0){const{mids:e}=this.remoteSDP.batchSend(i.map((e=>Object.assign({},{kind:e.kind,ssrcMsg:[{ssrcId:e.ssrcId,rtx:e.rtx}],mslabel:e.mslabel}))));e.forEach(((e,t)=>{this.preSSRCMap.set(i[t].ssrcId,e)}))}await zn(this.peerConnection,this.remoteSDP,this.extension),k.debug("[P2PConnection] updateRemoteRTPCapabilities by exchanging SDP.")}catch(e){throw new se(q.EXCHANGE_SDP_FAILED,"P2PConnection.updateRemoteConnect failed; ".concat(e.toString()))}}send(e,t,i){var n=this;return li((function*(){const o=yield si(n.mutex.lock("From P2PConnection.send"));try{if(!n.remoteSDP)throw new Error("Cannot call P2PConnection.send before remote SDP created");const a=[],s=Dn();e.forEach((e=>{const t=n.peerConnection.addTransceiver(e._mediaStreamTrack,di({direction:"sendonly"},"video"===e.trackMediaType&&n.supportAV1RtpSpec&&s?{sendEncodings:[{scalabilityMode:s}]}:{}));a.push(t),e._updateRtpTransceiver(t)})),te()&&!0===Z("SIMULCAST")&&(yield si(n.applySimulcastForFirefox(a,e)));const r=yield si(n.peerConnection.createOffer()),c=n.remoteSDP.predictReceivingMids(e.length),d=n.mungSendOfferSDP(r.sdp,e,c),l=Te(d),h=c.map((e=>{const t=l.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error("Cannot extract ssrc from mediaDescription.");return 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,Z("USE_PUB_RTX"))}));let u;try{u=yield h}catch(o){u=[],n.remoteSDP.receive(e,t,i,u);const a=n.remoteSDP.toString();throw yield si(n.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield si(n.peerConnection.setRemoteDescription({type:"answer",sdp:a})),yield si(n.stopSending(c,!0)),o}n.remoteSDP.receive(e,t,i,u);const _=n.remoteSDP.toString(),p=n.logSDPExchange(d,"offer","local","send");return yield si(n.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield si(n.applySimulcastEncodings(a,e)),yield si(n.applySendEncodings(a,e)),null==p||p(_),yield si(n.peerConnection.setRemoteDescription({type:"answer",sdp:_})),a.map(((e,t)=>{const i=c[t];return{localSSRC:h[t],id:i,transceiver:e}}))}catch(e){throw e instanceof se?e:new se(q.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)k.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:Z("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),k.debug("[P2PConnection] createDataChannels by exchanging SDP.")}else k.debug("[P2PConnection] createDataChannels no need to exchange SDP.");return}catch(e){throw e instanceof se?e:new se(q.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 se?e:new se(q.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;aa(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 se(q.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 zn(this.peerConnection,this.remoteSDP,this.extension),k.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 se(q.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 zn(this.peerConnection,this.remoteSDP,this.extension),k.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 se(q.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.preSSRCMap.entries()).some((t=>{let[i,n]=t;if(n===e)return this.preSSRCMap.delete(i),!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 se(q.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 se(q.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 se(q.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 se(q.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 se(q.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteLocal failed; ".concat(e.toString()))}}restartICE(e){var t=this;return li((function*(){const i=yield si(t.mutex.lock("From P2PConnection.restartICE"));try{if(!t.remoteSDP)throw new Error("Cannot restartICE before remoteSDP created.");const o=n().supportPCSetConfiguration,a=Z("FORCE_TURN_TCP")||t.forceTurn;if(e===Ki.RELAY&&!o)return;if(o&&!a){const i=e===Ki.RELAY?"relay":"all",n=t.peerConnection.getConfiguration();n.iceTransportPolicy!==i&&(k.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 si(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 si(t.peerConnection.setLocalDescription(s)),null==l||l(d),yield si(t.peerConnection.setRemoteDescription({type:"answer",sdp:d}))}catch(e){k.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(Ki.TCP_RELAY),await zn(this.peerConnection,this.remoteSDP,this.extension)}catch(e){k.warning("[".concat(this.store.clientId,"] extend candidate failed, abort operation"),e)}finally{e()}}close(){var e;this.peerConnection.getTransceivers().forEach((e=>{aa(this.id+e.mid,this)})),this.preSSRCMap.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 di(di({},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 se(q.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)?te()||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:di(di({},tt),{},{candidateType:i.type,protocol:i.protocol,address:i.address,port:i.port}),remote:di(di({},tt),{},{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):"";k.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICECandidateError(").concat(i,"), url: ").concat(e.url||"",", 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&&k.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,k.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount))},setTimeout((()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,k.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount))}),Z("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:[]};return t.iceServers?i.iceServers=t.iceServers:t.turnServer&&($e(t.turnServer.servers)?i.iceServers=t.turnServer.servers:Z("NEW_TURN_MODE")&&i.iceServers?(Z("USE_TURN_SERVER_OF_GATEWAY")?t.turnServer.serversFromGateway&&i.iceServers.push(...e.newTurnServerConfigToIceServers(t.turnServer.serversFromGateway)):i.iceServers.push(...e.newTurnServerConfigToIceServers(t.turnServer.servers)),Z("NEW_FORCE_TURN")&&(i.iceTransportPolicy="relay")):"off"!==t.turnServer.mode&&(i.iceServers&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers)),Z("USE_TURN_SERVER_OF_GATEWAY")&&i.iceServers&&t.turnServer.serversFromGateway&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway)),Z("FORCE_TURN_TCP")?i.iceTransportPolicy="relay":t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach((e=>{e.forceturn&&(i.iceTransportPolicy="relay")})))),Z("ENABLE_ENCODED_TRANSFORM")&&n().supportWebRTCEncodedTransform&&(i.encodedInsertableStreams=!0),i}static turnServerConfigToIceServers(e){const t=[];return e.forEach((e=>{e.security?e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(In(e.turnServerURL),":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&!Z("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=Z("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(In(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(In(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();k.info("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] selectedcandidatepairchange: local ").concat(JSON.stringify({candidateType:e.type,protocol:e.protocol}),", remote ").concat(JSON.stringify({candidateType:t.type,protocol:t.protocol,address:t.address,port:t.port})," )"))}}))}}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 k.warn("[".concat(e.getTrackId(),"] no rtpSender found}"));if(this.isVP8Simulcast(e))return k.warn("[updateRtpSenderEncodings] Track is VP8 simulcast, please apply simulcast encodings");if(!n().supportSetRtpSenderParameters)return k.warn("[updateRtpSenderEncodings] Browser not support set rtp-sender parameters");const a={},s={};switch(e._optimizationMode){case"motion":a.degradationPreference="maintain-framerate";break;case"detail":a.degradationPreference="maintain-resolution";break;case"balanced":a.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=_(e);if(function(e){return!(!Z("ENABLE_AG_ADAPTATION")||!(e instanceof u||e._hints.includes(o.CUSTOM_TRACK))||!Z("FORCE_SUPPORT_AG_ADAPTATION")&&!(Xe(14)&&Je(17,4,!0)||ze(14)&&Qe(17,4,!0)))}(e)&&r&&t&&c&&this.getLocalVideoStats&&["vp8","vp9"].includes(this.store.codec)){const i=a.degradationPreference||(e._hints.includes(o.CUSTOM_TRACK)?Z("CUSTOM_ADAPTATION_DEFAULT_MODE"):"maintain-framerate");!function(e,t,i,n,o,a){if(aa(e,i),o(t),"balanced"!==n&&"maintain-framerate"!==n&&"maintain-resolution"!==n)return;let s=-1;ta(e,t);const r=window.setInterval((()=>{const r=oa.get(e);if(!Z("ENABLE_AG_ADAPTATION")||!r)return aa(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,h]=na(e,a,d,r.adaptationConfig,t,n);h&&(i.qualityLimitationReason=h),l&&r.adaptationConfig.scale!==l.scale&&(k.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=di(di({},r.adaptationConfig),l),o(l))}}),Z("CHECK_LOCAL_STATS_INTERVAL")),c=di({},t);oa.set(e,{timer:r,adaptationConfig:c,originConfig:t,adaptationFunc:o}),k.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(o.LOW_STREAM)||e.isUseScaleResolutionDownBy)&&(i&&(s.maxFramerate=gn(i)),n&&n>=1&&(s.scaleResolutionDownBy=n))}const{maxFramerate:d}=Z("ENCODER_CONFIG_LIMIT");if(d&&"number"==typeof d&&(s.maxFramerate=s.maxFramerate?Math.min(s.maxFramerate,d):d),Z("DSCP_TYPE")&&Ze()){const e=Z("DSCP_TYPE");["very-low","low","medium","high"].includes(e)&&(s.networkPriority=e)}const l=t.getParameters(),h=null===(i=l.encodings)||void 0===i?void 0:i[0];te()&&!h&&(a.encodings=[s]),h&&Object.assign(h,s),Object.assign(l,a),k.debug("[".concat(e.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(l.encodings))),await t.setParameters(l),await async function(e,t,i){try{var o;if(!n().supportSetRtpSenderParameters)return;if(!function(e){return"vp9"===e||"av1"===e}(e)||!Z("ENABLE_SVC"))return;const a={},s={},r=t.getParameters(),c=null===(o=r.encodings)||void 0===o?void 0:o[0];s.scalabilityMode=Dn(i),c&&Object.assign(c,s),Object.assign(r,a),await t.setParameters(r),k.debug("[updateAdaptation] updateRtpSenderEncodings scalabilityMode success: ".concat(JSON.stringify(r.encodings)))}catch(e){k.debug("[updateAdaptation] updateRtpSenderEncodings scalabilityMode failed",e)}}(this.store.codec,t,Z("SVC_MODE"))}async updateAdaptation(e,t){var i;if(!e)return k.debug("[updateAdaptation] no rtpSender found");if(!n().supportSetRtpSenderParameters)return k.debug("[updateAdaptation] Browser not support set rtp-sender parameters");const o={},{bitrateMax:a,frameRate:s,scaleResolutionDownBy:r}=t;a&&(o.maxBitrate=1e3*a),s&&(o.maxFramerate=gn(s)),r&&r>=1&&["vp8","vp9"].includes(this.store.codec)&&(o.scaleResolutionDownBy=r);const c=e.getParameters(),d=null===(i=c.encodings)||void 0===i?void 0:i[0];d&&Object.assign(d,o),Object.assign(c,{});try{await e.setParameters(c),k.debug("[updateAdaptation] updateRtpSenderEncodings: ".concat(JSON.stringify(c.encodings)))}catch(t){!("transport"in e)||e.transport&&"connected"===e.transport.state?"connected"!==this.peerConnectionState?k.debug("[updateAdaptation] peerConnection not connected}"):k.debug("[updateAdaptation] updateRtpSenderEncodings failed",t):k.debug("[updateAdaptation] rtpSender transport not connected}")}}async applySendEncodings(e,t){try{if(!n().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let n=0;n<e.length;n++){const o=e[n],a=t[n];a instanceof i&&!this.isVP8Simulcast(a)&&await this.updateRtpSenderEncodings(a,o.sender)}}catch(e){k.debug("[".concat(this.store.clientId,"] Apply RTPSendEncodings failed."))}}mungSendOfferSDP(e,t,n){const o=Te(e);return t.forEach(((e,t)=>{const a=n[t],s=o.mediaDescriptions.find((e=>e.attributes.mid===a));s&&(Gn(s,e),function(e,t,n){if(te())return;if("video"!==e.media.mediaType)return;if(!(t instanceof i))return;if("vp9"!==n&&"vp8"!==n)return;if("vp8"===n&&!Z("SIMULCAST"))return;if("vp9"===n&&Z("ENABLE_SVC"))return;if(void 0===t._scalabilityMode||t._scalabilityMode.numSpatialLayers<=1)return;const o="vp8"===n?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:fe(a.attributes)}),r.ssrcIds.push(a.ssrcId+t),s&&(e.attributes.ssrcs.push({ssrcId:s.ssrcIds[1]+t,attributes:fe(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))})),Ce(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 n,a,s,r;const d=e[c],l=t[c];if(l instanceof i&&!l._hints.includes(o.LOW_STREAM)&&null!==(n=l._encoderConfig)&&void 0!==n&&n.bitrateMax&&(null===(a=l._encoderConfig)||void 0===a?void 0:a.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(!te()&&e.length===t.length)for(let n=0;n<e.length;n++){const o=t[n];if(o instanceof i&&this.isVP8Simulcast(o)){const t=e[n],i={},a={high:1e3*(o._encoderConfig.bitrateMax-50),medium:5e4};i.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,i))}}}isVP8Simulcast(e){var t,n,a,s;return!!(e instanceof i&&Z("SIMULCAST")&&"vp8"===this.store.codec&&!e._hints.includes(o.LOW_STREAM)&&null!==(t=e._encoderConfig)&&void 0!==t&&t.bitrateMax&&(null===(n=e._encoderConfig)||void 0===n?void 0:n.bitrateMax)>200&&null!==(a=e._scalabilityMode)&&void 0!==a&&a.numSpatialLayers&&(null===(s=e._scalabilityMode)||void 0===s?void 0:s.numSpatialLayers)>1)}logSDPExchange(e,t,i,n){if(Z("SDP_LOGGING"))return k.upload("[".concat(this.store.clientId,"] exchanging ").concat(i," ").concat(t," SDP during P2PConnection.").concat(n,"\n"),e),"offer"===t?e=>{this.logSDPExchange(e,"answer","local"===i?"remote":"local",n)}:void 0}async getRemoteSSRC(e){if(!this.remoteSDP)return;const t=this.remoteSDP.getSSRC(e);return t&&0!==t.length?t[0].ssrcId:void 0}setConfiguration(t){if(n().supportPCSetConfiguration){const i=e.resolvePCConfiguration(t);this.peerConnection.setConfiguration(i)}}},ii(ua.prototype,"updateRemoteRTPCapabilities",[pa],Object.getOwnPropertyDescriptor(ua.prototype,"updateRemoteRTPCapabilities"),ua.prototype),ii(ua.prototype,"connect",[pa],Object.getOwnPropertyDescriptor(ua.prototype,"connect"),ua.prototype),ii(ua.prototype,"updateRemoteConnect",[pa],Object.getOwnPropertyDescriptor(ua.prototype,"updateRemoteConnect"),ua.prototype),ii(ua.prototype,"createDataChannels",[pa],Object.getOwnPropertyDescriptor(ua.prototype,"createDataChannels"),ua.prototype),ii(ua.prototype,"receive",[pa],Object.getOwnPropertyDescriptor(ua.prototype,"receive"),ua.prototype),ii(ua.prototype,"batchReceive",[pa],Object.getOwnPropertyDescriptor(ua.prototype,"batchReceive"),ua.prototype),ii(ua.prototype,"stopReceiving",[pa],Object.getOwnPropertyDescriptor(ua.prototype,"stopReceiving"),ua.prototype),ii(ua.prototype,"muteRemote",[pa],Object.getOwnPropertyDescriptor(ua.prototype,"muteRemote"),ua.prototype),ii(ua.prototype,"unmuteRemote",[pa],Object.getOwnPropertyDescriptor(ua.prototype,"unmuteRemote"),ua.prototype),ii(ua.prototype,"muteLocal",[pa],Object.getOwnPropertyDescriptor(ua.prototype,"muteLocal"),ua.prototype),ii(ua.prototype,"unmuteLocal",[pa],Object.getOwnPropertyDescriptor(ua.prototype,"unmuteLocal"),ua.prototype),ii(ua.prototype,"close",[pa],Object.getOwnPropertyDescriptor(ua.prototype,"close"),ua.prototype),ii(ua.prototype,"updateEncoderConfig",[pa],Object.getOwnPropertyDescriptor(ua.prototype,"updateEncoderConfig"),ua.prototype),ii(ua.prototype,"updateSendParameters",[pa],Object.getOwnPropertyDescriptor(ua.prototype,"updateSendParameters"),ua.prototype),ii(ua.prototype,"replaceTrack",[pa],Object.getOwnPropertyDescriptor(ua.prototype,"replaceTrack"),ua.prototype),ii(ua.prototype,"updateAdaptation",[pa],Object.getOwnPropertyDescriptor(ua.prototype,"updateAdaptation"),ua.prototype),ii(ua.prototype,"getRemoteSSRC",[pa],Object.getOwnPropertyDescriptor(ua.prototype,"getRemoteSSRC"),ua.prototype),ua);function pa(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 Ea(e,t){let i=document.createElement("video"),o=document.createElement("canvas");i.setAttribute("style","display:none"),o.setAttribute("style","display:none"),i.setAttribute("muted",""),i.muted=!0,i.setAttribute("autoplay",""),i.autoplay=!0,i.setAttribute("playsinline",""),o.width=gn(t.width),o.height=gn(t.height);const a=gn(t.framerate||15);document.body.append(i),document.body.append(o);let s=e._mediaStreamTrack;i.srcObject=new MediaStream([s]),i.play();const r=o.getContext("2d");if(!r)throw new U(q.UNEXPECTED_ERROR,"can not get canvas context");const c=n(),d=o.captureStream(c.supportRequestFrame?0:a).getVideoTracks()[0];d.canvas||(d.canvas=o),o.startCapture=()=>{if(!i)return o.stopCapture&&o.stopCapture();if(i.paused&&i.play(),i.videoHeight>2&&i.videoWidth>2){const e=i.videoWidth,t=i.videoHeight/e,n=o.width*t;Math.abs(n-o.height)>=2&&(k.debug("adjust low stream resolution","".concat(o.width,"x").concat(o.height," -> ").concat(o.width,"x").concat(n)),o.height=n)}r.drawImage(i,0,0,o.width,o.height),d.requestFrame&&d.requestFrame(),s!==e._mediaStreamTrack&&(s=e._mediaStreamTrack,i.srcObject=new MediaStream([s]))},o.stopCapture=p((()=>o.startCapture&&o.startCapture()),a);const l=d.stop;return d.stop=()=>{l.call(d),i&&(i.remove(),i.srcObject=null,i=null),o&&(o.width=0,o.remove(),o.stopCapture&&o.stopCapture(),o.startCapture=void 0,o.stopCapture=void 0,o=null),k.debug("clean low stream renderer")},d}var Sa=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[e.Video_Send_Type=2225]="Video_Send_Type",e}(Sa||{}),ma=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}(ma||{}),Ra=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}(Ra||{}),Ta=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}(Ta||{}),fa=function(e){return e[e.RTC_PEER_CONNECTION_STATE=2219]="RTC_PEER_CONNECTION_STATE",e}(fa||{});const Ca=1e3,Ia=6,Aa=3,ga=Math.max(Ia,Aa);function va(e,t,i){null!=i&&Number.isFinite(i)&&(e[t]=Math.round(Math.max(0,i)))}function ya(e){const t={[Ta.CONN_TYPE]:0,[Ta.RTT]:e.rtt,[Ta.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[Ta.CONN_TYPE]=1),"tcp"===i&&(t[Ta.CONN_TYPE]=3),"tls"===i&&(t[Ta.CONN_TYPE]=4);break}case"srflx":t[Ta.CONN_TYPE]=2;break;case"unknown":t[Ta.CONN_TYPE]=5;break;default:t[Ta.CONN_TYPE]=0}return t}function Na(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 wa extends Q{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.needUploadRenderFreezeTime=!0,this.lastUploadCompensateTime=-1,this.uploadCompensateDeltaTime=0,this.store=e}uploadWRTCStats(e){if(!this.requestStats||!this.requestUploadStats)return;const t=e%Aa==0,i=e%Ia==0;let n,o;if(this.uploadTransportStarted&&(n=this.requestStats(),this.store.useP2P&&(o=this.requestStats(!0))),!n&&this.uploadOutboundStarted&&(n=this.requestStats()),!o&&this.uploadInboundStarted&&(o=this.requestStats(!0)),n||o){var a;const s={};if(this.uploadTransportStarted&&n){const e=this.getTransportStats(n,o,t);e&&(s.misc=[e])}if(this.uploadOutboundStarted&&n){const e=this.getOutboundStats(n,i?this.lastNormalSendStats:void 0,t?this.lastRefSendStats:void 0,this.lastSendStats);e&&(s.outbound=[e])}if(this.uploadInboundStarted&&o){this.uploadCompensateStats(e);const n=this.getInboundStats(o,i?this.lastNormalRecvStats:void 0,t?this.lastRefRecvStats:void 0,this.lastRecvStats);n&&(s.inbound=n)}const r=null===(a=this.requestTransportStats)||void 0===a?void 0:a.call(this).connectState;r&&(Array.isArray(s.misc)?s.misc[0]&&s.misc[0].addition&&(s.misc[0].addition[fa.RTC_PEER_CONNECTION_STATE]=it[r]):s.misc=[{addition:{[fa.RTC_PEER_CONNECTION_STATE]:it[r]}}]),this.requestUploadStats(s)}this.lastRecvStats=o,this.lastSendStats=n,i&&(this.lastNormalRecvStats=o,this.lastNormalSendStats=n),t&&(this.lastRefRecvStats=o,this.lastRefSendStats=n)}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:{[fa.RTC_PEER_CONNECTION_STATE]:it[e.connectState]}}]})))}return this.stopUploadWRTCStats()}this.uploadWRTCStats(e),++e===ga+1&&(e=1)}),Ca)}uploadCompensateStats(e){if(!this.requestStats||!this.requestUploadStats||!this.requestRemoteMedia)return;const t=e%Aa==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 o=Math.min(Math.floor(this.uploadCompensateDeltaTime/6e3),10);this.uploadCompensateDeltaTime-=6e3*o;const a=this.requestStats(!0);new Array(o).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,o]=e;const s={peer:t.uid};if((t._videoSSRC&&this.requestVideoIsReady&&this.requestVideoIsReady(t._videoSSRC)||!1)&&o.has(Hi.VIDEO)&&t.videoTrack){const e=function(e,t,i){if(!t.videoRecv.find((t=>t.ssrc===e)))return;const o={};if(i&&i._player){const e=i._player,{renderFreezeAccTime2:t,videoElementStatus:a}=e;if("visible"===S.visibility&&a===m.PLAYING&&n().supportRequestVideoFrameCallback){const i=Math.min(6e3,t);e.renderFreezeAccTime2=Math.max(0,t-i),va(o,Sa.Video_Render_Freeze_Time_Render2,i),Z("USE_NEW_RENDER_FREEZE_TIME")&&va(o,Sa.Video_Render_Freeze_Time_Render,i)}}return o}(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.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:{[Ta.RTT]:e.rtt,[Ta.CONN_TYPE]:void 0,[Ta.STATS_UPDATE_INTERVAL]:e.updateInterval||void 0}};const n=ya(e);if(this.store.useP2P){if(t){const e=ya(t);n[Ta.CONN_TYPE]+=e[Ta.CONN_TYPE]<<3}n[Ta.CONN_TYPE]+=110}else n[Ta.CONN_TYPE]+=100;return{addition:n}}getOutboundStats(e,t,i,n){if(!this.requestUploadStats||!this.requestLocalMedia)return;const a=this.requestLocalMedia();if(!a||0===a.length)return;let s,r,c;return a.forEach((n=>{let[a,{track:d,ssrcs:l}]=n;switch(a){case Xi.LocalVideoLowTrack:case Xi.LocalVideoTrack:if(a===Xi.LocalVideoTrack){const n=function(e,t,i,n,a,s){const r=t.videoSend.find((t=>t.ssrc===e));if(!r)return;const c={},{sentFrame:d,inputFrame:l}=r;if(n&&(va(c,Sa.Video_Send_Qp_Sum,r.qpSumPerFrame),l&&d)){const e=l.frameRate,t=d.frameRate;c[Sa.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,c[Sa.Video_Send_Type]="CameraVideoTrack"===i.__className__?0:i._hints.includes(o.SCREEN_TRACK)?1:2}if(a){switch(d&&(va(c,ma.Video_Send_Height,d.height),va(c,ma.Video_Send_Width,d.width),va(c,ma.Video_Send_Frame_Rate,d.frameRate)),c[ma.Video_Send_Disabled]=i._originMediaStreamTrack&&!i._originMediaStreamTrack.enabled||i._mediaStreamTrack&&!i._mediaStreamTrack.enabled?1:0,r.adaptionChangeReason){case"none":c[ma.Video_Send_Adaptation]=0;break;case"cpu":c[ma.Video_Send_Adaptation]=1;break;case"bandwidth":c[ma.Video_Send_Adaptation]=2;break;case"other":c[ma.Video_Send_Adaptation]=3}let n=0;r.adaptionChangeReason&&(n+=Na(r.adaptionChangeReason)),t.qualityLimitationReason&&(n+=Na(t.qualityLimitationReason)<<3),c[ma.Video_Send_Adaptation]=n,c[ma.Video_Send_Player_Status]=E[i._player?i._player.videoElementStatus:"uninit"],va(c,ma.Video_Send_Nacks,r.nacksCount),va(c,ma.Video_Send_Plis,r.plisCount),va(c,ma.Video_Send_Firs,r.firsCount),va(c,ma.Video_Send_Avg_Encode,r.avgEncodeMs),va(c,ma.Video_Send_Huge_Frame_Sent,r.hugeFramesSent),va(c,ma.Video_Send_Bytes_Retransmit,r.retransmittedBytesSent),va(c,ma.Video_Send_Packages_Retransmit,r.retransmittedPacketsSent),va(c,ma.Video_Send_Key_Frames_Encoded,r.keyFramesEncoded);const o=a.videoSend.find((t=>t.ssrc===e));if(o){let e=Ca*Aa;o.timestamp&&r.timestamp&&(e=r.timestamp-o.timestamp),null!=o.packets&&null!=r.packets&&va(c,ma.Video_Send_Package_Rate,1e3*(r.packets-o.packets)/e),null!=r.packetsLost&&null!=o.packetsLost&&va(c,ma.Video_Send_Package_Lost,r.packetsLost-o.packetsLost),null!=o.bytes&&null!=r.bytes&&va(c,ma.Video_Send_Bitrate,8*(r.bytes-o.bytes)/e)}}return c}(l[0].ssrcId,e,d,t,i),a=d&&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;va(a,ma.Video_Capture_Height,t),va(a,ma.Video_Capture_Width,n),va(a,ma.Video_Capture_Frame_Rate,s)}return a}(l[0].ssrcId,e,d,!!i),s=function(e,t){const i={};return t&&(va(i,ma.Video_Send_Retransmit,e.bitrate.retransmit),va(i,ma.Video_Send_Target_Encoded,e.bitrate.targetEncoded),va(i,ma.Video_Send_Actual_Encoded,e.bitrate.actualEncoded),va(i,ma.Video_Send_Transmit,e.bitrate.transmit),va(i,ma.Video_Send_Bandwidth,e.sendBandwidth)),i}(e,!!i);r=Object.assign({},n,a,s)}else c=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&&(va(s,ma.Video_Send_Low_Height,t.height),va(s,ma.Video_Send_Low_Width,t.width),va(s,ma.Video_Send_Low_Frame_Rate,t.frameRate));const i=n.videoSend.find((t=>t.ssrc===e));if(i){let e=Ca*Ia;i.timestamp&&a.timestamp&&(e=a.timestamp-i.timestamp),null!=i.packets&&null!=a.packets&&va(s,ma.Video_Send_Low_Package_Rate,1e3*(a.packets-i.packets)/e),null!=a.packetsLost&&null!=i.packetsLost&&va(s,ma.Video_Send_Low_Package_Lost,a.packetsLost-i.packetsLost),null!=i.bytes&&null!=a.bytes&&va(s,ma.Video_Send_Low_Bitrate,8*(a.bytes-i.bytes)/e)}}return s}(l[0].ssrcId,e,0,i);break;case Xi.LocalAudioTrack:s=d&&function(e,t,i,n,o,a){const s=t.audioSend.find((t=>t.ssrc===e));if(!s)return;const r={};if(o){r[ma.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));va(r,ma.Audio_Send_Level,e)}va(r,ma.Audio_Capture_PCM_Level,t),va(r,ma.Audio_Send_AEC_Return_Loss,s.aecReturnLoss),va(r,ma.Audio_Send_AEC_Return_Loss_Enhancement,s.aecReturnLossEnhancement),va(r,ma.Audio_Send_Bytes_Retransmit,s.retransmittedBytesSent),va(r,ma.Audio_Send_Packages_Retransmit,s.retransmittedPacketsSent),r[ma.Audio_Send_Freeze]=0;const a=o.audioSend.find((t=>t.ssrc===e));if(a){let e=Ca*Ia;a.timestamp&&s.timestamp&&(e=s.timestamp-a.timestamp),null!=a.bytes&&null!=s.bytes&&va(r,ma.Audio_Send_Bitrate,8*(s.bytes-a.bytes)/e),null!=a.packets&&null!=s.packets&&va(r,ma.Audio_Send_Package_Rate,1e3*(s.packets-a.packets)/e)}}return r}(l[0].ssrcId,e,d,0,i)}})),{high:r,low:c,audio:s}}getInboundStats(e,t,i,o){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(Hi.VIDEO)&&r.videoTrack){const a=r._videoSSRC&&this.requestVideoIsReady&&this.requestVideoIsReady(r._videoSSRC)||!1,s=r.videoTrack?function(e,t,i,o,a,s,r,c){const d=t.videoRecv.find((t=>t.ssrc===e));if(!d)return;const l={},{receivedFrame:h,outputFrame:u,decodeFrameRate:_}=d;va(l,Ra.Video_Render_Frame_Rate_Decode,_),d.framesRateFirefox&&va(l,Ra.Video_Recv_Frame_Rate,d.framesRateFirefox),h&&va(l,Ra.Video_Recv_Frame_Rate,h.frameRate),va(l,Ra.Video_Recv_Frame_Dropped,d.framesDroppedCount),va(l,Ra.Video_Recv_Bytes_Retransmit,d.retransmittedBytesReceived),va(l,Ra.Video_Recv_Packages_Retransmit,d.retransmittedPacketsReceived),va(l,Ra.Video_Recv_Packages_Discarded,d.packetsDiscarded),va(l,Ra.Video_Recv_Avg_Decode,d.avgDecodeMs),va(l,Ra.Video_Recv_Avg_Processing_Delay,d.avgProcessingDelayMs),va(l,Ra.Video_Recv_Avg_Assembly_Time,d.avgFramesAssembledFromMultiplePacketsMs),va(l,Ra.Video_Recv_Avg_Inter_Frame_Delay,d.avgInterFrameDelayMs),va(l,Ra.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||Ca;null!=d.packetsLost&&null!=p.packetsLost&&va(l,Ra.Video_Recv_Package_Lost,d.packetsLost-p.packetsLost),null!=p.bytes&&null!=d.bytes&&va(l,Ra.Video_Recv_Bitrate,8*(d.bytes-p.bytes)/e),null!=p.packets&&null!=d.packets&&va(l,Ra.Video_Recv_Package_Rate,1e3*(d.packets-p.packets)/e)}const R=s&&s.videoRecv.find((t=>t.ssrc===e));if(R&&(va(l,Sa.Video_Recv_Qp_Sum,d.qpSumPerFrame),l[Sa.Video_Recv_Freeze]=o&&Ko.isRemoteVideoFreeze(i,d,R)?1:0),r){var T;const t=r.videoRecv.find((t=>t.ssrc===e));h?(va(l,ma.Video_Recv_Height,h.height),va(l,ma.Video_Recv_Width,h.width)):i&&(va(l,ma.Video_Recv_Height,i._videoHeight||0),va(l,ma.Video_Recv_Width,i._videoWidth||0)),u&&va(l,ma.Video_Recv_Frame_Rate_Output,u.frameRate);const o=null===(T=i._player)||void 0===T?void 0:T.rendFrameRate.toFixed(0);if(o&&va(l,ma.Video_Render_Frame_Rate_Render,+o),va(l,ma.Video_Recv_Jitter_Buffer,d.jitterBufferMs),va(l,ma.Video_Recv_Current_Delay,d.currentDelayMs),va(l,ma.Video_Recv_Firs,d.firsCount),va(l,ma.Video_Recv_Nacks,d.nacksCount),va(l,ma.Video_Recv_Plis,d.plisCount),i){l[ma.Video_Recv_Disabled]=i._originMediaStreamTrack.enabled&&i._mediaStreamTrack.enabled?0:1;const e=i._player;if(e){const{freezeTimeCounterList:i,renderFreezeAccTime:o,renderFreezeAccTime2:s,videoElementStatus:r}=e;if(i&&i.length>0&&va(l,Sa.Video_Render_Freeze_Time,i.splice(0,1)[0]),a&&"visible"===S.visibility&&r===m.PLAYING&&n().supportRequestVideoFrameCallback){const t=Math.min(6e3,s);e.renderFreezeAccTime2=Math.max(0,s-t),va(l,Sa.Video_Render_Freeze_Time_Render2,t);const i=Math.min(6e3,o);e.renderFreezeAccTime=Math.max(0,o-i),va(l,Sa.Video_Render_Freeze_Time_Render,Z("USE_NEW_RENDER_FREEZE_TIME")?t:i)}if("number"==typeof d.totalFreezesDuration){const e=t&&t.totalFreezesDuration?d.totalFreezesDuration-t.totalFreezesDuration:d.totalFreezesDuration;va(l,ma.Video_Render_Freeze_Duration,1e3*e)}}}if(l[ma.Video_Recv_Player_Status]=E[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[ma.Video_Recv_I_Frame_Delay]=a)}}return l}(r._videoSSRC,e,r.videoTrack,!0===a,this.needUploadRenderFreezeTime,t,i,o):void 0;s&&(d.video=s)}if(c.has(Hi.AUDIO)&&r.audioTrack){const n=r.audioTrack?function(e,t,i,n,o,a){const s=t.audioRecv.find((t=>t.ssrc===e));if(!s)return;const r={};va(r,Ra.Audio_Recv_Jitter,s.jitterMs),va(r,Ra.Audio_Recv_Bytes_Retransmit,s.retransmittedBytesReceived),va(r,Ra.Audio_Recv_Packages_Retransmit,s.retransmittedPacketsReceived),va(r,Ra.Audio_Recv_Packages_Discarded,s.packetsDiscarded),va(r,Ra.Audio_Recv_Avg_Processing_Delay,s.avgProcessingDelayMs);const c=a&&a.audioRecv.find((t=>t.ssrc===e));if(c){const e=Ca;null!=s.packets&&null!=c.packets&&va(r,Ra.Audio_Recv_Package_Rate,1e3*(s.packets-c.packets)/e),null!=s.packetsLost&&null!=c.packetsLost&&va(r,Ra.Audio_Recv_Package_Lost,s.packetsLost-c.packetsLost)}if(n){const{receivedFrames:e,droppedFrames:t}=s;null!=e&&null!=t&&(r[Sa.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));va(r,ma.Audio_Render_Level,e)}va(r,ma.Audio_Recv_PCM_Level,t),i&&(r[ma.Audio_Recv_Disabled]=i._originMediaStreamTrack.enabled&&i._mediaStreamTrack.enabled?0:1),va(r,ma.Audio_Recv_Jitter_Buffer,s.jitterBufferMs),va(r,ma.Audio_Recv_Current_Delay,s.jitterBufferMs),r[ma.Audio_Recv_Player_Status]=E[R.getPlayerState(i.getTrackId())];const a=o.audioRecv.find((t=>t.ssrc===e));if(a){null!=a.bytes&&null!=s.bytes&&va(r,ma.Audio_Recv_Bitrate,8*(s.bytes-a.bytes)/(Ca*Aa));const e=s.concealedSamples-a.concealedSamples;e>0&&va(r,ma.Audio_Recv_Concealed_Samples,e);const t=s.totalSamplesReceived-a.totalSamplesReceived;t>0&&va(r,ma.Audio_Recv_Total_Samples_Received,t);const i=s.freezeSamples80-a.freezeSamples80;i>0&&va(r,ma.Audio_Render_Freeze_Samples_80ms,i);const n=s.freezeSamples200-a.freezeSamples200;n>0&&va(r,ma.Audio_Render_Freeze_Samples_200ms,n);const o=s.freezeMs80-a.freezeMs80;va(r,ma.Audio_Render_Freeze_Time_80ms,o<0?0:o);const c=s.freezeMs200-a.freezeMs200;va(r,ma.Audio_Render_Freeze_Time_200ms,c<0?0:c)}}return r}(r._audioSSRC,e,r.audioTrack,t,i,o):void 0;n&&(d.audio=n)}(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 t));if(e&&e._external.getDenoiserStats){const t=e._external.getDenoiserStats();t&&this.requestUpload(fi.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.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(Hi.VIDEO)&&t.videoTrack){t.videoTrack.getProcessorStats().forEach((e=>{this.requestUpload&&this.requestUpload(e.type,e.stats)}))}if(i.has(Hi.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:Z("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(Hi.VIDEO)&&e.videoTrack&&(n=n.concat(await e.videoTrack.getProcessorUsage())),t.has(Hi.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+Z("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(fi.EXTENSION_USAGE_STATS,{usageStats:i,sendTs:r})}),Z("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 Oa=Z("ICE_RESTART_INTERVAL");let ba=new Map,Da=new Map,Pa=[Ki.UDP_TCP_RELAY,Ki.TCP_RELAY,Ki.RELAY],La=Z("JOIN_WITH_FALLBACK_MEDIA_PROXY_FORCE")&&n().supportPCSetConfiguration;function ka(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const i=ba.get(e.id);i&&(window.clearTimeout(i),ba.delete(e.id));const n=Da.get(e.id);t&&n&&n.index===Pa.length-1&&(k.debug("[".concat(e.id,"] reset ICE restart policy")),Da.delete(e.id))}function Ua(e,t,i){if(0===ba.size&&0===Da.size&&(Array.isArray(Z("RESTART_SEQUENCE"))&&Z("RESTART_SEQUENCE").length>0&&!nt(Pa,Z("RESTART_SEQUENCE"))&&(Pa=Z("RESTART_SEQUENCE").filter((e=>{if(Object.values(Ki).includes(e))return!0})),k.debug("use reconnection policy from config distribution, queues: ".concat(Pa.join(" => ")))),La=Z("JOIN_WITH_FALLBACK_MEDIA_PROXY_FORCE")&&n().supportPCSetConfiguration),0===Pa.length)return void i();let o,{index:a=0,type:s}=Da.get(e.id)||{};if(La&&s===Ki.RELAY)return void i();let r=s&&a>=Pa.length-1;if(La)s=Ki.RELAY;else{if(r)return void i();s?(a++,s=Pa[a]):(s=Pa[0],a=0)}k.debug("[".concat(e.id,"] choose ICE restart policy: ").concat(s,", index: ").concat(a)),t(s),Da.set(e.id,{index:a,type:s}),o=window.setTimeout((()=>Ua(e,t,i)),Oa),ba.set(e.id,o)}var Ma;let Va=(ii((Ma=class extends Q{get state(){return this._state}set state(e){const t=this._state;this._state=e,this.emit(zi.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=Ji.Disconnected,this._pcStatsUploadType=Z("NEW_ICE_RESTART")?Yi.FIRST_CONNECTION:Yi.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!==Ji.Connected)return void i(new se(q.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){a[1].track._originMediaStreamTrack.stop()}await this.connection.muteLocal(o.map((e=>{let[,{id:t}]=e;return t})));const s=this.createMuteMessage(o);await ot(this,zi.RequestMuteLocal,s),t()}catch(e){i(e)}finally{n()}},this.handleUnmuteLocalTrack=async(e,t,i)=>{const o=await this.mutex.lock("Locking from P2PChannel.handleUnmuteLocalTrack");try{if(!this.connection||this.state!==Ji.Connected)return void i(new se(q.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(t.track._originMediaStreamTrack.stop(),!Z("DISABLE_DUAL_STREAM_USE_ENCODING")&&n().supportDualStreamEncoding){const i=e._mediaStreamTrack.clone();t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i}else{const i=Ea(e,Ee(this,zi.RequestLowStreamParameter));t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i}await new Promise(((e,i)=>{this.handleReplaceTrack(t.track,e,i,!0)}))}await this.connection.unmuteLocal(a.map((e=>{let[,{id:t}]=e;return t})));const r=this.createUnmuteMessage(a);await ot(this,zi.RequestUnmuteLocal,r),t()}catch(e){i(e)}finally{o()}},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(Xi.LocalVideoTrack);if(!this.connection||!i||i.track!==e||this.state!==Ji.Connected)return void t();const{id:n,track:s}=i;await this.connection.updateSendParameters(n,s),await this.connection.updateEncoderConfig(n,s),this.emit(zi.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(Xi.LocalVideoTrack);if(!this.connection||!i||i.track!==e||this.state!==Ji.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!==Ji.Connected)return void t();const o=ra([e]);let a;k.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,o)=>{let a;k.debug("[".concat(this.store.clientId,"] P2PChannel handleReplaceTrack for [track-id-").concat(e.getTrackId(),"]")),"boolean"==typeof o&&o||(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!==Ji.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]===Xi.LocalVideoTrack&&!Z("DISABLE_DUAL_STREAM_USE_ENCODING")&&n().supportDualStreamEncoding){const t=this.localTrackMap.get(Xi.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 wa(this.store),this.bindStatsUploaderEvents(),this.mutex=new ie("P2PChannel-mutex",this.store.clientId),this.isPlanB=!n().supportUnifiedPlan||Z("CHROME_FORCE_PLAN_B")&&Ze(),this.shouldForwardP2PCreation=Z("FORWARD_P2P_CREATION")&&n().supportPCSetConfiguration&&at(),this.shouldForwardP2PCreation&&(this.connection=da(this.store),this.emit(zi.PeerConnectionStateChange,this.connection.peerConnectionState),this.bindConnectionEvents(this.connection))}async startP2PConnection(e){var t;this.state=Ji.New,this._forceTurn=ha(e),k.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] forceTurn: ").concat(this._forceTurn));const i=this.shouldForwardP2PCreation&&"closed"===(null===(t=this.connection)||void 0===t?void 0:t.peerConnectionState);if(this.shouldForwardP2PCreation&&!i||(i&&this.connection&&(k.warning("[".concat(this.store.clientId,"] P2PChannel.startP2PConnection ForwardP2P closed.")),this.resetConnection(this.connection)),this.connection=da(this.store,e),this.emit(zi.PeerConnectionStateChange,this.connection.peerConnectionState),this.bindConnectionEvents(this.connection)),!this.connection)throw new se(q.UNEXPECTED_ERROR,"Cannot P2PChannel.startConnection before P2PConnection initialization .");return this._pcStatsUploadType=Z("NEW_ICE_RESTART")?Yi.FIRST_CONNECTION:Yi.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 se(q.UNEXPECTED_ERROR,"Cannot P2PChannel.connect before P2PChannel.startP2PConnection .");Z("ENABLE_PREALLOC_PC")&&this.state===Ji.Connected?await this.connection.updateRemoteConnect(e):(this.store.peerConnectionStart(),await this.connection.connect(e),this.statsUploader.startUploadTransportStats(),this.statsUploader.startUploadExtensionUsageStats(),this.state=Ji.Connected)}updateRemoteRTPCapabilities(e){const t=Array.from(this.localTrackMap.entries()).filter((e=>{let[t]=e;return[Xi.LocalVideoLowTrack,Xi.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 _a){if(M.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,k.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 _a&&"closed"!==this.connection.peerConnectionState&&[Ji.New,Ji.Connected].includes(this.state))return this.connection.establishPromise}async publishDataChannel(e){if(!this.connection||this.state!==Ji.Connected){if(this.state===Ji.Disconnected)throw new se(q.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 li((function*(){const o=yield si(n.mutex.lock("From P2PChannel.publish"));try{const a=n.connection&&["disconnected","failed"].includes(n.connection.peerConnectionState);if(!n.connection||n.state!==Ji.Connected||a){if(n.state===Ji.Disconnected)throw new se(q.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,Ho.markPublishStart(n.store.clientId,n.store.pubId);const s=n.filterTobePublishedTracks(e,t,i);if(0===s.length)return void(yield si(n.tryToUnmuteAudio(e)));yield*ni(oi(n.doPublish(n.connection,s)))}finally{o()}}))()}doPublish(e,t){var i=this;return li((function*(){t.forEach((e=>{let{track:t,type:n}=e;const o=Date.now();i.store.publish(t.getTrackId(),n===Xi.LocalAudioTrack?"audio":"video",o)})),i.bindLocalTrackEvents(t);const n=t.map((e=>{let{track:t}=e;return t})),o=yield si(e.send(n,i.store.codec,i.store.audioCodec)),a=(yield si(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)===q.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 si(o.next(c))).value;if(i.state===Ji.Disconnected)throw new se(q.UNEXPECTED_ERROR,"PeerConnection already disconnected.");Z("ENABLE_VIDEO_SEI");const l=Z("ENABLE_ENCODED_TRANSFORM"),h=Z("ENABLE_AUDIO_METADATA");n.forEach((async e=>{const t=e.getRTCRtpTransceiver();if(!t||!l)return;const{interceptLocalVideoFrame:i,interceptLocalAudioFrame:n}=ao();e.trackMediaType===Hi.VIDEO?await i(t.sender,e):e.trackMediaType===Hi.AUDIO&&await n(t.sender,{metadata:h?()=>{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===Xi.LocalAudioTrack?"audio":"video",void 0,o)}))}))()}async updateVideoStreamParameter(e,t){const o=this.localTrackMap.get(t);if(!o||!this.connection)return;if(!(o.track instanceof i))return k.warn("[updateVideoStreamParameter]: track is not an instance of LocalVideoTrack");const{track:a}=o,s=function(e,t){const i={};return e.height&&e.width&&(i.scaleResolutionDownBy=On(e,t)),i.maxFramerate=e.framerate?gn(e.framerate):void 0,i.maxBitrate=e.bitrate?1e3*e.bitrate:void 0,i}(e,a);if(a._encoderConfig||(a._encoderConfig={}),t!==Xi.LocalVideoLowTrack||!Z("DISABLE_DUAL_STREAM_USE_ENCODING")&&n().supportDualStreamEncoding)null!=s.scaleResolutionDownBy&&(a._encoderConfig.scaleResolutionDownBy=s.scaleResolutionDownBy);else{const t=a._originMediaStreamTrack;if(!t.canvas)return k.warn("[".concat(a.getTrackId(),"] no canvas on track"));!function(e,t){const i=e.canvas;t.width&&(i.width=gn(t.width)),t.height&&(i.height=gn(t.height)),t.framerate&&(i.stopCapture&&i.stopCapture(),i.stopCapture=p((()=>{!i.startCapture&&i.stopCapture&&i.stopCapture(),i.startCapture&&i.startCapture()}),gn(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}),k.debug("[".concat(a.getTrackId(),"] LowStreamEncoderConfig: , ").concat(JSON.stringify(a._encoderConfig))),await this.connection.updateRtpSenderEncodings(a)}publishLowStream(e){var t=this;return li((function*(){if(!t.connection||t.state!==Ji.Connected)return;const i=yield si(t.mutex.lock("Locking from P2PChannel.publishLowStream"));try{const o=t.localTrackMap.get(Xi.LocalVideoTrack);if(!o)throw new se(q.UNEXPECTED_ERROR,"Could not find high stream");if(t.localTrackMap.has(Xi.LocalVideoLowTrack))throw new se(q.UNEXPECTED_ERROR,"[".concat(t.store.clientId,"] Can't publish low stream when stream already publish"));const a=[{track:t.getLowVideoTrack(o.track,e),type:Xi.LocalVideoLowTrack}];if(yield*ni(oi(t.doPublish(t.connection,a))),o.track.muted||!o.track.enabled){var n;const e=null===(n=t.localTrackMap.get(Xi.LocalVideoLowTrack))||void 0===n?void 0:n.id;void 0!==e&&(yield si(t.connection.muteLocal([e])))}}finally{i()}}))()}async republish(){this.pendingLocalTracks.length>0&&(k.debug("[".concat(this.store.clientId,"] Emit P2PChannelEvents.RequestRePublish to republish tracks.")),await de(this,zi.RequestRePublish,this.pendingLocalTracks),this.emit(zi.MediaReconnectEnd,this.store.uid),this.pendingLocalTracks=[]),this.pendingLocalDataChannels.length>0&&(k.debug("Emit P2PChannelEvents.RequestRePublishDataChannel to republish datachannels."),await de(this,zi.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!==Hi.AUDIO||t._audio_added_&&t._audioSSRC)&&(i!==Hi.VIDEO||t._video_added_&&t._videoSSRC)||this.pendingRemoteTracks.splice(e,1)}if(e)await de(this,zi.RequestReSubscribe,this.pendingRemoteTracks);else for(const{user:e,kind:t}of this.pendingRemoteTracks)await this.subscribe(e,t,t===Hi.VIDEO?e._videoSSRC:e._audioSSRC);this.pendingRemoteTracks.forEach((e=>{let{user:t}=e;this.emit(zi.MediaReconnectEnd,t.uid)})),this.pendingRemoteTracks=[]}async unpublish(e){if(!this.connection||this.state!==Ji.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!==Ji.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!==Ji.Connected)return;const e=this.localTrackMap.get(Xi.LocalVideoLowTrack);if(!e)return;e.track.close();const t=[[Xi.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!==Ji.Connected)throw new se(q.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!==Ji.Connected)throw new se(q.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;const d=this.connection.getPreMedia(i);if(d)k.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] preSSRCMap has ssrcId: ").concat(i,", no need to send sub to gateway.")),c=d.transceiver,s=d.track,r=d.id;else if(o){const i=o.find((e=>{let{stream_type:i}=e;return i===t}));if(!i)throw new se(q.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 _a&&(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 _a&&(c=o.transceiver),s=o.track,r=o.id}if(t===Hi.AUDIO?(e._audioTrack?e._audioTrack._updateOriginMediaStreamTrack(s):(e._audioTrack=new T(s,e.uid,e._uintid,this.store),k.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 f(s,e.uid,e._uintid,this.store),k.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote video track: ").concat(e._videoTrack.getTrackId()))),c&&e._videoTrack._updateRtpTransceiver(c),this.bindRemoteTrackEvents(e,e._videoTrack)),c&&Z("ENABLE_ENCODED_TRANSFORM")){const{interceptRemoteVideoFrame:i,interceptRemoteAudioFrame:n}=ao();t==Hi.VIDEO?await i(c.receiver,{onSei:Z("ENABLE_VIDEO_SEI")&&(t=>{var i;return null===(i=e._videoTrack)||void 0===i?void 0:i._onSei(t)})}):t==Hi.AUDIO&&await n(c.receiver,{enableTopn:!!Z("ENABLE_AUDIO_TOPN"),enableMetadata:!!Z("ENABLE_AUDIO_METADATA"),onMetadata:e=>{this.safeEmit(zi.AudioMetadata,e)}})}const l=this.remoteUserMap.get(e);l?l.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(zi.MediaReconnectEnd,e.uid))}async massSubscribe(e){return this.massSubscribeNoLock(e)}async massSubscribeNoLock(e){if(!this.connection||this.state!==Ji.Connected)throw new se(q.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);n?i.set(e.ssrcId,n):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 k.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}=e;if(r&&Z("ENABLE_ENCODED_TRANSFORM")){const{interceptRemoteVideoFrame:e,interceptRemoteAudioFrame:i}=ao();n==Hi.VIDEO?await e(r.receiver,{onSei:Z("ENABLE_VIDEO_SEI")&&(e=>{var i;return null===(i=t._videoTrack)||void 0===i?void 0:i._onSei(e)})}):n==Hi.AUDIO&&await i(r.receiver,{enableTopn:!!Z("ENABLE_AUDIO_TOPN"),enableMetadata:!!Z("ENABLE_AUDIO_METADATA"),onMetadata:e=>{this.safeEmit(zi.AudioMetadata,e)}})}if(n===Hi.AUDIO?(t._audioTrack?t._audioTrack._updateOriginMediaStreamTrack(a):(t._audioTrack=new T(a,t.uid,t._uintid,this.store),k.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 f(a,t.uid,t._uintid,this.store),k.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)),Z("ENABLE_VIDEO_SEI")&&r){const{interceptRemoteVideoFrame:e,interceptRemoteAudioFrame:i}=ao();n==Hi.VIDEO?await e(r.receiver,{onSei:e=>{var i;null===(i=t._videoTrack)||void 0===i||i._onSei(e)}}):n==Hi.AUDIO&&await i(r.receiver)}const c=this.remoteUserMap.get(t);c?c.set(n,s):this.remoteUserMap.set(t,new Map([[n,s]])),this.statsCollector.addRemoteStats(t.uid),this.statsUploader.startUploadInboundStats();const d=this.pendingRemoteTracks.findIndex((e=>{let{user:i,kind:o}=e;return i.uid===t.uid&&n===o}));-1!==d&&(this.pendingRemoteTracks.splice(d,1),this.emit(zi.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===Ji.Connected||i||n.forEach((t=>{let{kind:i}=t;var n;if(i===Hi.AUDIO)null===(n=e._audioTrack)||void 0===n||n._destroy(),e._audioTrack=void 0;else if(i===Hi.VIDEO){var o;null===(o=e._videoTrack)||void 0===o||o._destroy(),e._videoTrack=void 0}})),!this.connection||this.state!==Ji.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===Hi.VIDEO&&t._videoSSRC&&(null===(o=this.connection)||void 0===o||o.setStatsRemoteVideoIsReady(t._videoSSRC,!1));if(n===Hi.VIDEO)this.unbindRemoteTrackEvents(t._videoTrack),i||(null===(a=t._videoTrack)||void 0===a||a._destroy(),t._videoTrack=void 0);else if(n===Hi.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!==Ji.Connected)return void t.forEach((e=>{let{user:t,kind:i}=e;var n;if(i===Hi.AUDIO)null===(n=t._audioTrack)||void 0===n||n._destroy(),t._audioTrack=void 0;else if(i===Hi.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===Hi.VIDEO&&t._videoSSRC&&(null===(n=this.connection)||void 0===n||n.setStatsRemoteVideoIsReady(t._videoSSRC,!1));if(i===Hi.VIDEO)this.unbindRemoteTrackEvents(t._videoTrack),null===(o=t._videoTrack)||void 0===o||o._destroy(),t._videoTrack=void 0;else if(i===Hi.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!==Ji.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 k.warning("[".concat(this.store.clientId,"] P2PChannel.muteRemote has no remote user ").concat(e.uid,"."));if(!i.get(t))return void k.warning("[".concat(this.store.clientId,"] P2PChannel.muteRemote has no remote user ").concat(e.uid," media type ").concat(t,"."));const n=t===Hi.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 k.warning("[".concat(this.store.clientId,"] P2PChannel.unmuteRemote has no remote user ").concat(e.uid,"."));i.get(t)||k.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(Xi.LocalAudioTrack),i=t&&t.track;i&&i.metadata.push(e)}getAllTracks(e){const t=this.localTrackMap.get(Xi.LocalAudioTrack);if((null==t?void 0:t.track)instanceof s){const i=t.track;return Array.from(this.localTrackMap.entries()).filter((e=>{let[t]=e;return t!==Xi.LocalAudioTrack})).filter((t=>{let[i]=t;return!(e&&i===Xi.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===Xi.LocalVideoLowTrack)})).map((e=>{let[,{track:t}]=e;return t}))}getAllDataChannels(){return this.localDataChannels}reportPublishEvent(t,n,a,s,r){if(t){const e=this.localTrackMap.get(Xi.LocalAudioTrack),i=s?this.localTrackMap.get(Xi.LocalVideoLowTrack):this.localTrackMap.get(Xi.LocalVideoTrack);M.publish(this.store.sessionId,{eventElapse:Ho.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:t,ec:n,audioName:null==e?void 0:e.track.getTrackLabel(),videoName:null==i?void 0:i.track.getTrackLabel(),screenshare:-1!==(null==i?void 0:i.track._hints.indexOf(o.SCREEN_TRACK)),audio:!!e,video:!!i,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r})}else{var c;a||(a=[]);const d=a.find((t=>t instanceof e)),l=s?null===(c=this.localTrackMap.get(Xi.LocalVideoTrack))||void 0===c?void 0:c.track:a.find((e=>e instanceof i));M.publish(this.store.sessionId,{eventElapse:Ho.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:t,ec:n,audioName:null==d?void 0:d.getTrackLabel(),videoName:null==l?void 0:l.getTrackLabel(),screenshare:-1!==(null==l?void 0:l._hints.indexOf(o.SCREEN_TRACK)),audio:!!d,video:!!l,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r})}}reportSubscribeEvent(e,t,i,n){const o=n===Hi.VIDEO?i._videoSSRC:i._audioSSRC;o&&M.subscribe(this.store.sessionId,{succ:e,ec:t,video:n===Hi.VIDEO,audio:n===Hi.AUDIO,peerid:i.uid,subscribeRequestid:o,p2pid:this.store.p2pId,eventElapse:Ho.measureFromSubscribeStart(this.store.clientId,o),preSsrc:this.isPreSubScribe(o)})}reset(){k.debug("[".concat(this.store.clientId,"] P2PChannel.reset")),this.mutex=new ie("P2PChannel-mutex",this.store.clientId),this.connection&&(this.resetConnection(this.connection),this.connection=void 0),this.shouldForwardP2PCreation&&(this.connection=da(this.store),this.emit(zi.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(Xi.LocalAudioTrack);if((null==e?void 0:e.track)instanceof s){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=Ji.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(Xi.LocalAudioTrack);if(e)return e.track.getVolumeLevel()}getLocalVideoSize(){const e=this.localTrackMap.get(Xi.LocalVideoTrack);if(e)return{width:e.track.videoWidth||0,height:e.track.videoHeight||0}}getEncoderConfig(t){const n=this.localTrackMap.get(t);return n&&n.track instanceof i||n&&n.track instanceof e?n.track._encoderConfig:void 0}getLocalMedia(e){return this.localTrackMap.get(e)}hasLocalMedia(){return this.localTrackMap.size>0}hasRemoteMedia(e,t){if(!e)return this.remoteUserMap.size>0;const i=this.remoteUserMap.get(e);return!!i&&(!t||i.has(t))}async hasRemoteMediaWithLock(e,t){if(!e)return this.remoteUserMap.size>0;const i=this.remoteUserMap.get(e);return!!i&&(!t||i.has(t))}getRemoteMedia(e){const t=Array.from(this.remoteUserMap.keys()).find((t=>t.uid===e));return t?{audioTrack:t.audioTrack,audioSSRC:t._audioSSRC,videoTrack:t.videoTrack,videoSSRC:t._videoSSRC}:{}}getAudioLevels(){let e=Array.from(this.remoteUserMap.entries()).map((e=>{let[t]=e;return{uid:t.uid,level:t.audioTrack?100*t.audioTrack._source.getAccurateVolumeLevel():0}}));const t=this.localTrackMap.get(Xi.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&&(k.debug("[".concat(this.store.clientId,"] P2PChannel.disconnectForReconnect closing P2PConnection")),this.state=Ji.Reconnecting,Z("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=da(this.store),this.emit(zi.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 Xi.LocalVideoTrack:i._hints.includes(o.LOW_STREAM)?i.close():this.pendingLocalTracks.push(i);break;case Xi.LocalAudioTrack:i instanceof s?this.pendingLocalTracks=this.pendingLocalTracks.concat(i.trackList):this.pendingLocalTracks.push(i);case Xi.LocalVideoLowTrack:}})),this.emit(zi.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(zi.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(),k.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 Xo?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 Xo?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 li((function*(){if(!t.connection||t.state!==Ji.Connected)return;const i=yield si(t.mutex.lock("From P2PChannel.restartICE"));let n;try{n=yield si(t.connection.restartICE(e));const o=yield si(n.next());if(o.done)return;const a=o.value,s=yield a;switch(la(t.connection)&&t.reportPCStats(Date.now(),!1,t._pcStatsUploadType),e){case Ki.UDP_TCP_RELAY:t._pcStatsUploadType=Yi.UDP_TCP_RESTART;break;case Ki.TCP_RELAY:t._pcStatsUploadType=Yi.TCP_RESTART;break;case Ki.RELAY:t._pcStatsUploadType=Yi.RELAY_RESTART;break;default:t._pcStatsUploadType=Yi.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(Xi.LocalVideoTrack),i=this.localTrackMap.get(Xi.LocalAudioTrack),n=e.videoSend.find((e=>e.ssrc===(null==t?void 0:t.ssrcs[0].ssrcId))),a=e.audioSend.find((e=>e.ssrc===(null==i?void 0:i.ssrcs[0].ssrcId)));if(!n||!a)return 1;const s=le(this,zi.NeedSignalRTT),r=n?n.rttMs:void 0,c=a?a.rttMs:void 0,d=r&&c?(r+c)/2:r||c,l=(d&&s?(d+s)/2:d||s)||0,h=100*e.sendPacketLossRate*.7/50+.3*l/1500,u=h<.17?1:h<.36?2:h<.59?3:h<.1?4:5,_=null==t?void 0:t.track;if(_&&_._encoderConfig&&-1===_._hints.indexOf(o.SCREEN_TRACK)){const t=_._encoderConfig.bitrateMax,i=e.bitrate.actualEncoded;if(t&&i){const e=(1e3*t-i)/(1e3*t);return zt[e<.15?0:e<.3?1:e<.45?2:e<.6?3:4][u]}}return u}getDownlinkNetworkQuality(){if(!this.connection)return 0;const e=this.connection.getStats();let t=0;return Array.from(this.remoteUserMap.entries()).forEach((i=>{let[n]=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=le(this,zi.NeedSignalRTT),d=e.rtt,l=(d&&c?(d+c)/2:d||c)||0,h=s?s.jitterMs:void 0,u=e.recvPacketLossRate;let _=.7*u*100/50+.3*l/1500;h&&(_=.6*u*100/50+.2*l/1500+.2*h/400);t+=_<.1?1:_<.17?2:_<.36?3:_<.59?4:5})),this.remoteUserMap.size>0?Math.round(t/this.remoteUserMap.size):t}async muteLocalTrack(e){return new Promise(((t,i)=>{this.handleMuteLocalTrack(e,t,i)}))}async replaceTrack(e,t){var i;if(k.debug("[".concat(this.store.clientId,"] P2PChannel replaceTrack from [").concat(e.getTrackId(),"] to [").concat(t.getTrackId(),"]")),!this.connection||this.state!==Ji.Connected)return;const o=Array.from(this.localTrackMap.entries()).find((t=>{let[,{track:i}]=t;return e===i}));if(!o)return;const a=o[0];if(e!==t&&(this.unbindLocalTrackEvents([{track:e,type:a}]),this.bindLocalTrackEvents([{track:t,type:a}]),o[1].track=t),await(null===(i=this.connection)||void 0===i?void 0:i.replaceTrack(t,o[1].id)),this.isPlanB){const e=o[1];e.id=t._mediaStreamTrack.id,this.localTrackMap.set(a,e)}if(a===Xi.LocalVideoTrack&&!Z("DISABLE_DUAL_STREAM_USE_ENCODING")&&n().supportDualStreamEncoding){const t=this.localTrackMap.get(Xi.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(t,o,a){const r=[],c=this.getAllTracks();t=t.filter((e=>-1===c.indexOf(e))),t=st(t);let d,l=!1;const h=this.localTrackMap.get(Xi.LocalAudioTrack);for(const c of t){if(c instanceof i&&(this.localTrackMap.has(Xi.LocalVideoTrack)||l?new se(q.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS).throw():(r.push({track:c,type:Xi.LocalVideoTrack}),l=!0),o)){const e=this.getLowVideoTrack(c,a);r.push({track:e,type:Xi.LocalVideoLowTrack})}if(c instanceof e)if(h){const e=h.track;if(e instanceof s)sa([c]),e.addAudioTrack(c),this.bindLocalAudioTrackEvents(c,!0);else{const t=ra([e,c]);k.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection will replace audioTrack [").concat(t.getTrackId(),"]")),this.replaceTrack(e,t)}}else if(d instanceof s)sa([c]),d.addAudioTrack(c);else if(d||!c._useAudioElement&&n().webAudioMediaStreamDest&&!c._bypassWebAudio){d=ra(d?[c,d]:[c])}else d=c}return d&&(k.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection will send audioTrack [").concat(d.getTrackId(),"]")),r.push({track:d,type:Xi.LocalAudioTrack})),r}filterTobeUnpublishedTracks(t){const n=[],o=this.getAllTracks();t=t.filter((e=>-1!==o.indexOf(e))),t=st(t);for(const o of t){if(o instanceof e){const e=this.localTrackMap.get(Xi.LocalAudioTrack);if(!e)continue;e.track instanceof s?(e.track.removeAudioTrack(o),this.unbindLocalAudioTrackEvents(o),0===e.track.trackList.length&&(n.push([Xi.LocalAudioTrack,e]),e.track.close())):n.push([Xi.LocalAudioTrack,e])}if(o instanceof i){const e=this.localTrackMap.get(Xi.LocalVideoTrack);if(!e)continue;n.push([Xi.LocalVideoTrack,e]);const t=this.localTrackMap.get(Xi.LocalVideoLowTrack);t&&n.push([Xi.LocalVideoLowTrack,t])}}return n}filterTobePublishedDataChannels(e){return e=(e=st(e)).filter((e=>-1===this.localDataChannels.findIndex((t=>t.id===e.id))))}filterTobeUnpublishedDataChannels(e){return e=(e=(e=st(e)).filter((e=>-1!==this.localDataChannels.indexOf(e)))).filter((e=>e._originDataChannel))}bindLocalTrackEvents(e){e.forEach((e=>{let{track:t,type:i}=e;switch(i){case Xi.LocalVideoTrack:t.addListener(C.GET_STATS,this.handleGetLocalVideoStats),t.addListener(C.GET_RTC_STATS,this.handleGetRTCStats),t.addListener(C.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.addListener(C.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.addListener(C.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.addListener(C.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this.handleUpdateVideoSendParameters),t.addListener(C.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.addListener(C.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.addListener(C.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case Xi.LocalAudioTrack:this.bindLocalAudioTrackEvents(t);case Xi.LocalVideoLowTrack:}}))}bindLocalAudioTrackEvents(e,t){e instanceof s?e.trackList.forEach((e=>{e.addListener(C.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(C.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(C.GET_STATS,this.handleGetLocalAudioStats),e.addListener(C.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(C.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)})):(e.addListener(C.GET_STATS,this.handleGetLocalAudioStats),e.addListener(C.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(C.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(C.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(C.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack),t||(e.addListener(C.NEED_REPLACE_TRACK,this.handleReplaceTrack),e.addListener(C.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 Xi.LocalVideoTrack:t.off(C.GET_STATS,this.handleGetLocalVideoStats),t.off(C.GET_RTC_STATS,this.handleGetRTCStats),t.off(C.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.off(C.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.off(C.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.off(C.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this.handleUpdateVideoSendParameters),t.off(C.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.off(C.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.off(C.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case Xi.LocalAudioTrack:this.unbindLocalAudioTrackEvents(t);case Xi.LocalVideoLowTrack:}}))}unbindLocalAudioTrackEvents(e){e instanceof s?e.trackList.forEach((e=>{e.off(C.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(C.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(C.GET_STATS,this.handleGetLocalAudioStats),e.off(C.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(C.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)})):(e.off(C.GET_STATS,this.handleGetLocalAudioStats),e.off(C.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(C.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(C.NEED_REPLACE_TRACK,this.handleReplaceTrack),e.off(C.NEED_REPLACE_MIXING_TRACK,this.handleReplaceMixingTrack),e.off(C.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(C.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack))}bindRemoteTrackEvents(e,t){t instanceof f&&t.addListener(C.GET_STATS,(t=>{t(this.handleGetRemoteVideoStats(e))})),t instanceof T&&t.addListener(C.GET_STATS,(t=>{t(this.handleGetRemoteAudioStats(e))}))}unbindRemoteTrackEvents(e){e&&e.removeAllListeners(C.GET_STATS)}unbindAllRemoteTrackEvents(){Array.from(this.remoteUserMap.entries()).forEach((e=>{let[t,i]=e;i.has(Hi.AUDIO)&&this.unbindRemoteTrackEvents(t._audioTrack),i.has(Hi.VIDEO)&&this.unbindRemoteTrackEvents(t._videoTrack)}))}createGatewayPublishMessage(e,i){return e.map(((e,n)=>{let a,s,{track:r,type:c}=e;switch(c){case Xi.LocalAudioTrack:a=Pi.Audio,s={dtx:r instanceof t&&r._config.DTX,hq:!1,lq:!1,stereo:!1,speech:!1};break;case Xi.LocalVideoTrack:a=r._hints.includes(o.SCREEN_TRACK)?Pi.Screen:Pi.High,s=di(di({},vn(r)),{},{codec:this.store.codec,svc_mode:Dn()});break;case Xi.LocalVideoLowTrack:a=Pi.Low,s=di(di({},vn(r)),{},{codec:this.store.codec,svc_mode:Dn()})}return{stream_type:a,attributes:s,ssrcs:i[n]}}))}createGatewayUnpublishMessage(e){return e.map((e=>{let t,[i,{track:n,ssrcs:a,id:s}]=e;switch(i){case Xi.LocalVideoTrack:t=n._hints.includes(o.SCREEN_TRACK)?Pi.Screen:Pi.High;break;case Xi.LocalAudioTrack:t=Pi.Audio;break;case Xi.LocalVideoLowTrack:t=Pi.Low}return{stream_type:t,ssrcs:a,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(k.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onConnectionStateChange(").concat(t,")")),this.emit(zi.PeerConnectionStateChange,t),"connecting"===t&&e instanceof _a&&!te()&&Z("FIRST_TCP_CANDIDATE")&&window.setTimeout((()=>{"connecting"===t&&e.extendCandidate()}),Z("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 _a&&ka(e,!0),this._isTryConnecting&&this.reportPCStats(Date.now(),!0,this._pcStatsUploadType),this._isTryConnecting=!1,this._isStartRestartIce=!1,this._pcStatsUploadType=Yi.DISCONNECTED_OR_FAILED;if("CONNECTED"===le(this,zi.QueryClientConnectionState)&&this._isWaitPcToRePub){const e=this.pendingLocalTracks.map((e=>e.getTrackId())),t=this.pendingLocalDataChannels.map((e=>"dc_".concat(e.id)));M.reportApiInvoke(this.store.sessionId,{name:Ue.REPUB_AFTER_PC_CONNECTED,options:e.concat(t),tag:Me.TRACER}).onSuccess(),this.republish()}}if(Z("NEW_ICE_RESTART")&&e instanceof _a&&!te()&&!this._forceTurn){if(qi.includes(t)){if(this._isStartRestartIce)return;this._isStartRestartIce=!0;const t=t=>{if(la(e)){k.debug("[".concat(this.store.clientId,"] [P2PChannel] try to restartICE, type is ").concat(t));"CONNECTED"===le(this,zi.QueryClientConnectionState)&&this.emit(zi.RequestRestartICE,t)}},i=()=>{la(e)&&(this.reportPCStats(Date.now(),!1,this._pcStatsUploadType),k.debug("[".concat(this.store.clientId,"] P2PConnection disconnected timeout, force reconnect")),setTimeout((()=>this.emit(zi.P2PLost)),0),this.iceFailedCount+=1,this.requestReconnect())};return void(this._restartTimer=window.setTimeout((()=>{Ua(e,t,i)}),800))}}else{if("disconnected"===t&&"disconnected"===e.iceConnectionState)return setTimeout((()=>{if("disconnected"===e.iceConnectionState&&Z("ICE_RESTART")){"CONNECTED"===le(this,zi.QueryClientConnectionState)&&this.emit(zi.RequestRestartICE)}}),800),void setTimeout((()=>{"disconnected"===e.peerConnectionState&&(k.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(zi.P2PLost)),0),this.iceFailedCount+=1,this.requestReconnect())}),4e3);"failed"===t&&(k.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(zi.P2PLost)),0),this.iceFailedCount+=1,await this.requestReconnect())}},e.onICEConnectionStateChange=e=>{"connected"!==e||this.store.keyMetrics.iceConnectionEnd||this.store.iceConnectionEnd(),k.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICEConnectionStateChange(").concat(e,")")),M.reportApiInvoke(this.store.sessionId,{name:"ICEConnectionStateChange",options:e,tag:Me.TRACER}).onSuccess(),this.emit(zi.IceConnectionStateChange,e)},e.onICETransportStateChange=e=>{k.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICETransportStateChange(").concat(e,")"))},e.onDTLSTransportStateChange=e=>{k.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportStateChange(").concat(e,")"))},e.onDTLSTransportError=e=>{k.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(I.FIRST_FRAME_DECODED),M.firstRemoteFrame(this.store.sessionId,x.FIRST_AUDIO_DECODE,B.FIRST_AUDIO_DECODE,{peer:t._uintid,subscribeElapse:Ho.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&&M.firstRemoteFrame(this.store.sessionId,x.FIRST_AUDIO_RECEIVED,B.FIRST_AUDIO_RECEIVED,{peer:t._uintid,subscribeElapse:Ho.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId})},e.onFirstVideoDecoded=(e,t,i)=>{this.reportVideoFirstFrameDecoded(e,t,i)},e.onFirstVideoReceived=e=>{const t=Array.from(this.remoteUserMap.keys()).find((t=>t._videoSSRC===e));t&&M.firstRemoteFrame(this.store.sessionId,x.FIRST_VIDEO_RECEIVED,B.FIRST_VIDEO_RECEIVED,{peer:t._uintid,subscribeElapse:Ho.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(zi.ConnectionTypeChange,i),k.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)=>{k.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 di(di({},e),t)},e.onICECandidateError=e=>{this._iceError=e}}resetConnection(e){e instanceof _a&&function(e){Da.delete(e.id),ka(e)}(e),e.close(),this.emit(zi.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(t){const i=[];if(-1===this.getAllTracks().indexOf(t))return i;const n=this.localTrackMap.get(Xi.LocalAudioTrack);if(t instanceof e&&(null==n?void 0:n.track)instanceof s)return n.track.isActive||i.push([Xi.LocalAudioTrack,n]),i;const o=Array.from(this.localTrackMap.entries()).find((e=>{let[,{track:i}]=e;return t===i}));if(o&&(i.push(o),o[0]===Xi.LocalVideoTrack)){const e=this.localTrackMap.get(Xi.LocalVideoLowTrack);e&&i.push([Xi.LocalVideoLowTrack,e])}return i}filterTobeUnmutedTracks(t){const i=[],n=this.localTrackMap.get(Xi.LocalAudioTrack);if(t instanceof e&&(null==n?void 0:n.track)instanceof s)return n.track.isActive&&i.push([Xi.LocalAudioTrack,n]),i;const o=Array.from(this.localTrackMap.entries()).find((e=>{let[,{track:i}]=e;return t===i}));if(o)if(o[0]===Xi.LocalVideoTrack){i.push(o);const e=this.localTrackMap.get(Xi.LocalVideoLowTrack);e&&i.push([Xi.LocalVideoLowTrack,e])}else i.push(o);return i}createMuteMessage(e){return e.map((e=>{let t,[i,{track:n,ssrcs:a,id:s}]=e;switch(i){case Xi.LocalAudioTrack:t=Pi.Audio;break;case Xi.LocalVideoTrack:t=n._hints.includes(o.SCREEN_TRACK)?Pi.Screen:Pi.High;break;case Xi.LocalVideoLowTrack:t=Pi.Low}return{stream_type:t,ssrcs:a,mid:s}}))}createUnmuteMessage(e){return e.map((e=>{let t,[i,{track:n,ssrcs:a,id:s}]=e;switch(i){case Xi.LocalAudioTrack:t=Pi.Audio;break;case Xi.LocalVideoTrack:t=n._hints.includes(o.SCREEN_TRACK)?Pi.Screen:Pi.High;break;case Xi.LocalVideoLowTrack:t=Pi.Low}return{stream_type:t,ssrcs:a,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 Hi.VIDEO:return void(i._videoSSRC&&t.push({stream_type:Hi.VIDEO,ssrcId:i._videoSSRC}));case Hi.AUDIO:return void(i._audioSSRC&&t.push({stream_type:Hi.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===Hi.VIDEO?e|=Ui.Video:e|=Ui.Audio,t.set(i,e)}else n===Hi.VIDEO?t.set(i,Ui.Video):t.set(i,Ui.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(Xi.LocalVideoTrack),i=this.localTrackMap.get(Xi.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}mapPubResToRemoteConfig(e,t,i){return e.map(((e,n)=>{var a;let{stream_type:s}=e;const r=null===(a=t.find((e=>{let{stream_type:t}=e;return s===t})))||void 0===a?void 0:a.attributes;if(r&&Z("DISABLE_SCREEN_SHARE_REMB")){const e=i[n]._hints;(e.includes(o.SCREEN_TRACK)||e.includes(o.SCREEN_LOW_TRACK))&&(r.remb=!1,k.debug("disable remb for screen share, hints:",e))}return r}))}async tryToUnmuteAudio(t){for(let n=0;n<t.length;n++)if(t[n]instanceof e){var i;const e=this.filterTobeUnmutedTracks(t[n]);if(0===e.length)continue;await(null===(i=this.connection)||void 0===i?void 0:i.unmuteLocal(e.map((e=>{let[,{id:t}]=e;return t}))));const o=this.createUnmuteMessage(e);return void await ot(this,zi.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(zi.RequestUpload,e,t),this.statsUploader.requestUploadStats=e=>this.emit(zi.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 ce(re(this.dtlsFailedCount,xe)),this.emit(zi.RequestReconnect)}async reconnectP2P(){const e=Array.from(this.localTrackMap.entries()),t=this.createGatewayUnpublishMessage(e);Array.from(this.remoteUserMap.entries()),t.length>0&&await de(this,zi.RequestUnpublishForReconnectPC,t),this.disconnectForReconnect(),this.emit(zi.RequestReconnectPC)}canPublishLowStream(){return this.localTrackMap.has(Xi.LocalVideoTrack)||this.pendingLocalTracks.some((e=>e instanceof i))}throwIfTrackTypeNotMatch(t){if(t.filter((e=>e instanceof i)).length>1)throw new se(q.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(t.filter((t=>t instanceof e)).length>1&&(t.some((t=>t instanceof e&&t._bypassWebAudio))||!n().webAudioMediaStreamDest))throw new se(q.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode");for(const o of t){if(o instanceof i&&this.pendingLocalTracks.some((e=>e instanceof i)))throw new se(q.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(o instanceof e&&this.pendingLocalTracks.some((t=>t instanceof e))&&(!n().webAudioMediaStreamDest||o._bypassWebAudio||this.pendingLocalTracks.some((t=>t instanceof e&&t._bypassWebAudio))))throw new se(q.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode")}}getLowVideoTrack(e,t){const a=!Z("DISABLE_DUAL_STREAM_USE_ENCODING")&&n().supportDualStreamEncoding,s=di(di({},{width:160,height:120,framerate:15,bitrate:50}),t);let r;r=a?e._mediaStreamTrack.clone():Ea(e,s);const c=pe(8,"track-low-"),d=new i(r,di(di({},a&&{scaleResolutionDownBy:On(s,e)}),{},{frameRate:s.framerate,bitrateMax:s.bitrate,bitrateMin:s.bitrate}),void 0,void 0,c);return d.on(A.TRANSCEIVER_UPDATED,(t=>{e._updateRtpTransceiver(t,g.LOW_STREAM)})),d._hints.push(o.LOW_STREAM),e._hints.includes(o.SCREEN_TRACK)&&d._hints.push(o.SCREEN_LOW_TRACK),e.on("sei-to-send",(e=>{d.emit("sei-to-send",e)})),e.addListener(C.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 _a){var o,a,s,r;const c=this.store.keyMetrics.descriptionStart||0,{iceConnectionState:d,dtlsTransportState:l,peerConnectionState:h}=this.connection,{local:u,remote:_}=await this.connection.getSelectedCandidatePair();M.pcStats(this.store.sessionId,{startTime:c,eventElapse:e-c||0,iceconnectionsate:d,dtlsstate:l,connectionstate:h,intSucc:t?1:2,error:this._iceError||n||"",selectedLocalCandidateProtocol:null!==(o=null==u?void 0:u.protocol)&&void 0!==o?o:"",selectedLocalCandidateType:null!==(a=u.candidateType)&&void 0!==a?a:"",selectedLocalCandidateAddress:"".concat(u.address,":").concat(u.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}}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));M.firstRemoteVideoDecode(this.store.sessionId,x.FIRST_VIDEO_DECODE,B.FIRST_VIDEO_DECODE,{peer:o._uintid,videowidth:t,videoheight:i,subscribeElapse:Ho.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===Xi.LocalVideoLowTrack?i._updateRtpTransceiver(void 0,g.LOW_STREAM):i._updateRtpTransceiver(void 0)}))}}).prototype,"startP2PConnection",[xa],Object.getOwnPropertyDescriptor(Ma.prototype,"startP2PConnection"),Ma.prototype),ii(Ma.prototype,"connect",[xa],Object.getOwnPropertyDescriptor(Ma.prototype,"connect"),Ma.prototype),ii(Ma.prototype,"updateRemoteRTPCapabilities",[xa],Object.getOwnPropertyDescriptor(Ma.prototype,"updateRemoteRTPCapabilities"),Ma.prototype),ii(Ma.prototype,"publishDataChannel",[xa],Object.getOwnPropertyDescriptor(Ma.prototype,"publishDataChannel"),Ma.prototype),ii(Ma.prototype,"unpublish",[xa],Object.getOwnPropertyDescriptor(Ma.prototype,"unpublish"),Ma.prototype),ii(Ma.prototype,"unpublishDataChannel",[xa],Object.getOwnPropertyDescriptor(Ma.prototype,"unpublishDataChannel"),Ma.prototype),ii(Ma.prototype,"unpublishLowStream",[xa],Object.getOwnPropertyDescriptor(Ma.prototype,"unpublishLowStream"),Ma.prototype),ii(Ma.prototype,"subscribeDataChannel",[xa],Object.getOwnPropertyDescriptor(Ma.prototype,"subscribeDataChannel"),Ma.prototype),ii(Ma.prototype,"subscribe",[xa],Object.getOwnPropertyDescriptor(Ma.prototype,"subscribe"),Ma.prototype),ii(Ma.prototype,"massSubscribe",[xa],Object.getOwnPropertyDescriptor(Ma.prototype,"massSubscribe"),Ma.prototype),ii(Ma.prototype,"unsubscribe",[xa],Object.getOwnPropertyDescriptor(Ma.prototype,"unsubscribe"),Ma.prototype),ii(Ma.prototype,"unsubscribeDataChannel",[xa],Object.getOwnPropertyDescriptor(Ma.prototype,"unsubscribeDataChannel"),Ma.prototype),ii(Ma.prototype,"massUnsubscribe",[xa],Object.getOwnPropertyDescriptor(Ma.prototype,"massUnsubscribe"),Ma.prototype),ii(Ma.prototype,"muteRemote",[xa],Object.getOwnPropertyDescriptor(Ma.prototype,"muteRemote"),Ma.prototype),ii(Ma.prototype,"unmuteRemote",[xa],Object.getOwnPropertyDescriptor(Ma.prototype,"unmuteRemote"),Ma.prototype),ii(Ma.prototype,"hasRemoteMediaWithLock",[xa],Object.getOwnPropertyDescriptor(Ma.prototype,"hasRemoteMediaWithLock"),Ma.prototype),ii(Ma.prototype,"disconnectForReconnect",[xa],Object.getOwnPropertyDescriptor(Ma.prototype,"disconnectForReconnect"),Ma.prototype),ii(Ma.prototype,"updateBitrateLimit",[xa],Object.getOwnPropertyDescriptor(Ma.prototype,"updateBitrateLimit"),Ma.prototype),ii(Ma.prototype,"remoteMediaSsrcChanged",[xa],Object.getOwnPropertyDescriptor(Ma.prototype,"remoteMediaSsrcChanged"),Ma.prototype),Ma);function xa(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 Ba=Date.now(),Fa=20,ja=new Map,Ga=new Map;async function Wa(e){const t=ja.get(e),i=Array.isArray(t)&&t[t.length-1],n=Ga.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(),Ha(i.context,o),r=0):r=Math.min(r,Fa),setTimeout((()=>t.length&&Wa(e)),r)}function Ha(e,t){e.safeEmit(rt.STREAM_MESSAGE,t.uid,t.payload),e.onStreamMessage&&e.onStreamMessage(t)}function Ka(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 Ha(i,{uid:e.uid,payload:e.payload});const n="".concat(i.id,"-").concat(e.uid),o=ja.get(n)||[],a=o.findIndex((t=>e.sendTs>=t.sendTs)),s=di(di({},e),{},{context:i,mediaDelay:t,recvTs:Date.now()});-1===a?o.push(s):o.splice(a,0,s),ja.set(n,o);let r=!1;var c;Ga.has(n)?r=!(null===(c=Ga.get(n))||void 0===c||!c.isSyncing):Ga.set(n,{isSyncing:r,firstRecvTs:0,firstSendTs:0});r||Wa(n)}const Ya=Ie().name;async function qa(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const n=M.reportApiInvoke(null,{tag:Me.TRACER,name:Ue.CHECK_VIDEO_TRACK_IS_ACTIVE,options:[t]});if(!(e instanceof i||e instanceof f)){const e=new U(q.INVALID_TRACK,"the parameter is not a video track");return n.onError(e),e.throw()}t&&t<1e3&&(t=1e3);const o=e instanceof i?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()||ct())&&(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 U(q.UNEXPECTED_ERROR,"can not get canvas 2d context.");return k.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=p((()=>{d()}),30)}))}(s,t,r,4),d=Date.now()-e}catch(e){throw n.onError(e),e}Ya===Ae.SAFARI&&(s.pause(),s.remove()),s.srcObject=null;const l=c>4,h={duration:d,changedPicNum:c,deviceLabel:o,result:l};return k.info("[track-".concat(e.getTrackId(),"] check video track active completed. ").concat(JSON.stringify(h))),n.onSuccess(h),l}async function Xa(t){let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const n=M.reportApiInvoke(null,{tag:Me.TRACER,name:Ue.CHECK_AUDIO_TRACK_IS_ACTIVE,options:[i]});if(!(t instanceof e||t instanceof T)){const e=new U(q.INVALID_TRACK,"the parameter is not a audio track");return n.onError(e),e.throw()}i&&i<1e3&&(i=1e3);const o=t instanceof e?t.getTrackLabel():"remote_track",a=t.getVolumeLevel();let s=a,r=a;const c=Date.now();return new Promise((e=>{const a=setInterval((()=>{const d=t.getVolumeLevel();s=d>s?d:s,r=d<r?d:r;const l=s-r>1e-4,h=Date.now()-c;if(l||h>i){clearInterval(a);const i=l,r={duration:h,deviceLabel:o,maxVolumeLevel:s,result:i};k.info("[track-".concat(t.getTrackId(),"] check audio track active completed. ").concat(JSON.stringify(r))),n.onSuccess(r),e(i)}}),200)}))}const Ja="websdk_ng_cache_parameter",za=Z("MAX_PRELOAD_ASYNC_LENGTH"),Qa=1e4,Za=new Map,$a=[];let es=null,ts=0,is=0;const ns=new Map,os=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())}))}}(rs,za),as=Ht.CancelToken.source();async function ss(e,t,i,n){return rs(e,t,i,n)}async function rs(e,t,i,o,a,s){try{if(!Z("ENABLE_PRELOAD"))return;if(!n().supportWebCrypto)return void dt((()=>{k.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 se(q.INVALID_PARAMS,"Invalid token: ".concat(i,". If you don not use token, set it to null"));i&&J(i,"token",1,2047),J(e,"appid",1,2047),gi(t),o&&vi(o);const r=lt();k.debug("preload channel ".concat(t,", uid is ").concat(o));const c={appId:e,cname:t,token:i||e,uid:"string"!=typeof o?o:null,sid:r,proxyServer:a};let d,l;"string"==typeof o?(c.stringUid=o,[l,d]=await Promise.all([Mo(o,{sid:r,appId:e},as.token),xo(di(di({},c),{},{token:i||e,uid:0}),as.token)]),c.uid=l.uid,d.gatewayInfo.uid=c.uid,d.gatewayInfo.res.uid=c.uid):(s&&(c.stringUid=s),d=await xo(c,as.token));const h={sid:r,appId:e,cname:t,token:i||e,uid:c.stringUid||o,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&&ds({appId:e.appId,cname:e.cname,token:e.token,uid:e.uid,stringUid:e.stringUid});const i=Es(e),n=await async function(e,t){try{const i=await window.crypto.subtle.importKey("raw",ut(t),"AES-GCM",!1,["encrypt"]),n=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:new Uint8Array(1)},i,_t(window.btoa(JSON.stringify(e))));return pt(new Uint8Array(n))}catch(e){return}}(e,e.token||e.appId);if(!n)return;t=_s(Ja);const o=t?JSON.parse(t):[];o.push({[i]:n}),o.length>Z("AP_CACHE_NUM")&&o.shift(),ps(Ja,JSON.stringify(o))}catch(e){k.warn("Error caching server parameters:",e.message),ps(Ja,"")}}(h),ts++}catch(e){throw is++,function(e){es||(es=window.setTimeout((()=>{let t="";ns.forEach(((e,i)=>{t+="".concat(i,": ").concat(e," ;")})),M.reportApiInvoke(null,{name:Ue.PRELOAD,options:{success:ts,failed:is,err:t}}).onError(e),ts=0,is=0,ns.clear(),es=null}),Qa));const t=ns.get(e.code)||0;ns.set(e.code,t+1)}(e),e}}async function cs(e){try{if(Z("AP_REQUEST_DETAIL")||Z("ENABLE_ROLE_SELECT_EDGE"))return;const t=ds(e);if(!t||"disabled"!==e.cloudProxyServer)return;const i=await async function(e,t){try{const i=await window.crypto.subtle.importKey("raw",ut(t),"AES-GCM",!1,["decrypt"]),n=await window.crypto.subtle.decrypt({name:"AES-GCM",iv:new Uint8Array(1)},i,_t(e));return JSON.parse(window.atob(pt(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<Z("AP_CACHE_LIFETIME"))return i}catch(e){k.warn("Error get preloadInfo",e.message)}}function ds(e){let t;try{if(t=_s(Ja),!t)return;const i=JSON.parse(t),n=Es(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 ps(Ja,JSON.stringify(i)),a[n]}catch(e){k.warn("Error delete preload info: ".concat(t),e.message),ps(Ja,"")}}function ls(e){if(e){let t=Za.get(e);t&&(window.clearTimeout(t),t=null,Za.delete(e)),$a.includes(e)||"disabled"!==e.cloudProxyServer||$a.push(e)}if(Za.size<Z("AP_CACHE_NUM")&&$a.length>0){const e=$a.shift();Za.set(e,window.setTimeout((async()=>{const{appId:t,cname:i,token:n,stringUid:o,uid:a,proxyServer:s}=e;try{await os(t,i,n,a,s,o),Za.has(e)&&ls(e)}catch(t){k.warn("update preload failed",t.message),hs(e)}}),Z("AP_UPDATE_INTERVAL")))}}function hs(e){const t=$a.indexOf(e);-1!==t&&$a.splice(t,1);let i=Za.get(e);i&&(window.clearTimeout(i),i=null,Za.delete(e),ls())}function us(e,t){const i=e.sua,n=e.ap;t&&i&&M.reqUserAccount(e.sid,{lts:i.requestTime,elapse:i.elapse,success:!0,serverAddr:i.url,stringUid:t,uid:e.intUid,errorCode:null,extend:i.req}),M.reportResourceTiming(e.ap.url,e.sid),M.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:[Cn.CHOOSE_SERVER,Cn.CLOUD_PROXY_FALLBACK].toString()}),M.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:[Cn.CHOOSE_SERVER].toString(),isHttp3:n.isHttp3})}function _s(e){return window.atob(window.localStorage.getItem(e)||"")}function ps(e,t){window.localStorage.setItem(e,window.btoa(t))}function Es(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)),ht(t)}const Ss={},ms={};function Rs(e,t){let i,n,o;return t?(o=0<=(e>>>=0)&&e<256)&&(n=ms[e],n)?n:(i=Ts(e,0,!0),o&&(ms[e]=i),i):(o=-128<=(e|=0)&&e<128)&&(n=Ss[e],n)?n:(i=Ts(e,e<0?-1:0,!1),o&&(Ss[e]=i),i)}function Ts(e,t,i){return{low:0|e,high:0|t,unsigned:!!i}}var fs,Cs,Is,As,gs,vs,ys,Ns,ws,Os,bs,Ds,Ps,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;Rs(0,!0),Rs(0),ie.setLogger(k);let cr=(fs=F(),Cs=F({argsMap:(e,t)=>{if(!Array.isArray(t)){if(!(t instanceof v))return[t];t=[t]}return t.map((e=>e?Object(e).toString():"null"))}}),Is=F({argsMap:(e,t)=>(t||(t=[]),Array.isArray(t)||t.trackMediaType!==y.DATA?(Array.isArray(t)||(t=[t]),t.map((e=>e.getTrackId()))):[t.getChannelId()])}),As=F({argsMap:(e,t,i,n)=>["object"==typeof t?t.uid:t,i,n]}),gs=F({argsMap:(e,t,i)=>[t,i]}),vs=F({argsMap:(e,t)=>t.map((e=>{let{user:t,mediaType:i}=e;return[null==t?void 0:t.uid,i]}))}),ys=F({argsMap:(e,t,i,n)=>["object"==typeof t?t.uid:t,i,n]}),Ns=F({argsMap:(e,t)=>t.map((e=>{let{user:t,mediaType:i}=e;return{uid:null==t?void 0:t.uid,mediaType:i}}))}),ws=F(),Os=F(),bs=F(),Ds=F(),Ps=F(),Ls=F(),ks=F(),Us=F(),Ms=F(),Vs=F(),xs=F(),Bs=F(),Fs=F(),js=F(),Gs=F(),Ws=F({argsMap:(e,t)=>[t]}),Hs=F(),Ks=F(),Ys=F(),qs=F(),Xs=F(),Js=F(),zs=F(),Qs=F(),Zs=F({argsMap:(e,t)=>(Array.isArray(t)||(t=[t]),[JSON.stringify(t)])}),$s=F(),er=F(),tr=F(),ir=F(),nr=F(),or=F(),ar=F({reportResult:!0}),sr=F(),ii((rr=class extends Q{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 n;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=Ht.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._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(Z("BLOCK_LOCAL_CLIENT")&&$t(e.uid,this.channelName))return void k.debug("[".concat(e.uid,"] will be ignored in local"));this.isStringUID&&"string"!=typeof e.uid&&k.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(rt.USER_JOINED,t));else{const t=new Xo(e.uid,e.uint_id||e.uid);this._users.push(t),k.debug("[".concat(this._clientId,"] user online"),e.uid),this.safeEmit(rt.USER_JOINED,t)}},this._handleUserOffline=e=>{if(Z("BLOCK_LOCAL_CLIENT")&&$t(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:St(this._users,t),this._remoteStreamTypeCacheMap.delete(t.uid),this._streamFallbackTypeCacheMap.delete(t.uid),k.debug("[".concat(this._clientId,"] user offline"),e.uid,"reason:",e.reason),this.safeEmit(rt.USER_LEAVED,t,e.reason))},this._handleAddAudioOrVideoStream=(e,t,i,n,o,a,s)=>{if(Z("BLOCK_LOCAL_CLIENT")&&$t(t,this.channelName))return;const r=this._users.find((e=>e.uid===t));if(!r)return void k.error("[".concat(this._clientId,"] can not find target user!(on_add_stream)"));k.debug("[".concat(this._clientId,"] stream added with uid ").concat(t,", type ").concat(e)),this.store.subscribe(r.uid,e,void 0,void 0,void 0,Date.now());const c="audio"===e?r.hasAudio:r.hasVideo;r._uintid||(r._uintid=o||t),"audio"===e?r._trust_audio_stream_added_state_=!0:r._trust_video_stream_added_state_=!0,"audio"===e?(r._audio_added_=!0,void 0!==i&&(r._audioSSRC=i),void 0!==n&&(r._cname=n),a&&(r._audioOrtc=a)):(r._video_added_=!0,void 0!==i&&(r._videoSSRC=i),void 0!==n&&(r._cname=n),void 0!==s&&(r._rtxSsrcId=s),a&&(r._videoOrtc=a)),("audio"===e?r.hasAudio:r.hasVideo)&&!c&&(k.info("[".concat(this._clientId,"] remote user ").concat(r.uid," published ").concat(e)),this.safeEmit(rt.USER_PUBLISHED,r,e)),"video"===e?M.onGatewayStream(this._sessionId,x.ON_ADD_VIDEO_STREAM,B.ON_ADD_VIDEO_STREAM,{peer:o||t,ssrc:r._videoSSRC}):M.onGatewayStream(this._sessionId,x.ON_ADD_AUDIO_STREAM,B.ON_ADD_AUDIO_STREAM,{peer:o||t,ssrc:r._audioSSRC}),this._p2pChannel.remoteMediaSsrcChanged(r,e,i).then((t=>{if(t&&(k.debug("[".concat(this._clientId,"] resubscribe ").concat(e," for user ").concat(r.uid," after rejoin because SSRC id changed.")),this._p2pChannel instanceof Va))return this._p2pChannel.unsubscribe(r,e,!0).then((()=>this._subscribe(r,e,!0).catch((e=>{k.error("[".concat(this._clientId,"] resubscribe error"),e.toString())}))))})),this._p2pChannel.hasPendingRemoteMedia(r,e)&&(k.debug("[".concat(this._clientId,"] resubscribe ").concat(e," for user ").concat(r.uid," after reconnect.")),this._subscribe(r,e,!0).catch((e=>{k.error("[".concat(this._clientId,"] resubscribe error"),e.toString())})))},this._handleRemoveStream=e=>{if(Z("BLOCK_LOCAL_CLIENT")&&$t(e.uid,this.channelName))return;const t=this._users.find((t=>t.uid===e.uid));if(!t)return void k.warning("[".concat(this._clientId,"] can not find target user!(on_remove_stream)"));k.debug("[".concat(this._clientId,"] stream removed with uid ").concat(e.uid));let i=()=>{};t.hasAudio&&t.hasVideo?i=()=>{k.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished audio track")),this.safeEmit(rt.USER_UNPUBLISHED,t,"audio"),k.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished video track")),this.safeEmit(rt.USER_UNPUBLISHED,t,"video")}:t.hasVideo?i=()=>{k.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished video track")),this.safeEmit(rt.USER_UNPUBLISHED,t,"video")}:t.hasAudio&&(i=()=>{k.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished audio track")),this.safeEmit(rt.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 Va&&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),M.onGatewayStream(this._sessionId,x.ON_REMOVE_STREAM,B.ON_REMOVE_STREAM,{peer:e.uint_id||e.uid}),i()},this._handleSetStreamLocalEnable=(e,t,i)=>{if(Z("BLOCK_LOCAL_CLIENT")&&$t(t,this.channelName))return;const n=this._users.find((e=>e.uid===t));if(!n)return void k.error("[".concat(this._clientId,"] can not find target user!(disable_local)"));k.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";k.debug("[".concat(this._clientId,"] user-info-updated, uid: ").concat(t,", msg: ").concat(e)),this.safeEmit(rt.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";k.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(t,", msg: ").concat(e)),this.safeEmit(rt.USER_INFO_UPDATED,t,e)}}const a="audio"===e?n.hasAudio:n.hasVideo;return o!==a?!o&&a?(k.info("[".concat(this._clientId,"] remote user ").concat(t," published ").concat(e)),void this.safeEmit(rt.USER_PUBLISHED,n,e)):("video"===e&&n._videoTrack&&n._videoTrack._destroy(),"audio"===e&&n._audioTrack,this._p2pChannel.muteRemote(n,e),k.info("[".concat(this._clientId,"] remote user ").concat(t," unpublished ").concat(e)),void this.safeEmit(rt.USER_UNPUBLISHED,n,e)):void 0},this._handleMuteStream=(e,t,i)=>{if(Z("BLOCK_LOCAL_CLIENT")&&$t(e,this.channelName))return;k.debug("[".concat(this._clientId,"] receive mute message"),e,t,i);const n=this._users.find((t=>t.uid===e));if(!n)return void k.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";k.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(e,", msg: ").concat(t)),this.safeEmit(rt.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";k.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(e,", msg: ").concat(t)),this.safeEmit(rt.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)?(k.info("[".concat(this._clientId,"] remote user ").concat(e," published ").concat(t)),void this.safeEmit(rt.USER_PUBLISHED,n,t)):void k.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),k.info("[".concat(this._clientId,"] remote user ").concat(e," unpublished ").concat(t)),this.safeEmit(rt.USER_UNPUBLISHED,n,t)}},this._handleP2PLost=async e=>{k.debug("[".concat(this._clientId,"] receive p2p lost"),e),parseInt(e.p2pid,10)===this.store.p2pId?await this._p2pChannel.requestReconnect():k.warning("[".concat(this._clientId,"] P2PLost stream not found"),e)},this._handleTokenWillExpire=()=>{k.debug("[".concat(this._clientId,"] received message onTokenPrivilegeWillExpire")),this.safeEmit(rt.ON_TOKEN_PRIVILEGE_WILL_EXPIRE)},this._handleBeforeUnload=e=>{"beforeunload"===e.type&&void 0!==e.returnValue&&""!==e.returnValue||(this.leave(),k.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(rt.NETWORK_QUALITY,{downlinkNetworkQuality:6,uplinkNetworkQuality:6});const e={downlinkNetworkQuality:0,uplinkNetworkQuality:0};e.uplinkNetworkQuality=this._p2pChannel.getUplinkNetworkQuality(),e.downlinkNetworkQuality=this._p2pChannel.getDownlinkNetworkQuality(),this.safeEmit(rt.NETWORK_QUALITY,e)},this._handleP2PAddAudioOrVideoStream=(e,t,i,n)=>{const o=this._users.find((e=>e.uid===t));if(!o)return void k.error("[".concat(this._clientId,"] can not find target user!(on_add_stream)"));k.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&&(k.info("[".concat(this._clientId,"] remote user ").concat(o.uid," published ").concat(e)),this.safeEmit(rt.USER_PUBLISHED,o,e)),this._p2pChannel.hasPendingRemoteMedia(o,e)&&(k.debug("[".concat(this._clientId,"] resubscribe ").concat(e," for user ").concat(o.uid," after reconnect.")),this._subscribe(o,e,!0).catch((e=>{k.error("[".concat(this._clientId,"] resubscribe error"),e.toString())})))},this._config=e,this._clientId=t||pe(5,"client-"),this.store=new mt(e.codec,e.audioCodec,e.mode,this._clientId),this._leaveMutex=new ie("client-leave",this._clientId),this._publishMutex=new ie("client-publish",this._clientId),this._renewTokenMutex=new ie("client-renewtoken",this._clientId),this._subscribeMutex=new ie("client-subscribe",this._clientId),this.store.clientCreated(),e.proxyServer&&this.setProxyServer(e.proxyServer,!0),e.turnServer&&this.setTurnServer(e.turnServer,!0),k.info("[".concat(this._clientId,"] Initializing AgoraRTC client v").concat(be," build: ").concat(Rt,", mode: ").concat(this.mode,", codec: ").concat(this.codec)),e.clientRoleOptions)try{Tt(e.clientRoleOptions),n=Object.assign({},e.clientRoleOptions)}catch(e){k.warning("[".concat(this._clientId,"] ").concat(e.toString()))}var o;this._statsCollector=new Ko(this.store),this._statsCollector.onStatsException=(e,t,i)=>{k.warn("[".concat(this._clientId,"] receive exception msg, code: ").concat(e,", msg: ").concat(t,", uid: ").concat(i)),this.safeEmit(rt.EXCEPTION,{code:e,msg:t,uid:i})},this._statsCollector.onUploadPublishDuration=(e,t,i,n)=>{const o=this._users.find((t=>t.uid===e));o&&M.peerPublishStatus(this._sessionId,{subscribeElapse:n,audioPublishDuration:t,videoPublishDuration:i,peer:o._uintid})},this._statsCollector.onVideoCodecChanged=e=>{if(Z("VIDEO_STANDARD_BITRATE_VERSION")&&("av1"===e||"h265"===e||"h264"===e)){const t=this.localTracks.find((e=>e instanceof i));t&&1!==t._saveEncodeBitrateRatio&&t.setSaveEncodeBitrateRatio("h264"===e?Z("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||xe,httpRetryConfig:e.httpRetryConfig||xe,forceWaitGatewayResponse:void 0===e.forceWaitGatewayResponse||e.forceWaitGatewayResponse,statsCollector:this._statsCollector,role:e.role,clientRoleOptions:n}),this._configDistribute=new jo(this._clientId,this.store),this.store.useP2P?(this._p2pChannel=(o={store:this.store,statsCollector:this._statsCollector},no("P2PChannel").create(o)),this._handleP2PEvents()):this._p2pChannel=new Va(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];Pe("JOIN_GATEWAY_USE_443PORT_ONLY",a),Pe("JOIN_GATEWAY_USE_DUAL_DOMAIN",s);const r=this._gateway.signal.websocket;return r instanceof Rn&&(r.use443PortOnly=a,r.tryDoubleDomain=s),ft("client.join",Z("JOIN_MAX_CONCURRENCY"),this.join.bind(this),e,t,i,n,o)}async join(e,t,i,o,a){const s=++this._numberOfJoinCount;this.store.joinStart(),o&&(this.store.uid=o);const r=Ct(),c=It()?window.isSecureContext:"Browser Not Support";if(!It()&&!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";k.warning(e)}M.setAppId(e);try{if(!i&&null!==i)throw new U(q.INVALID_PARAMS,"Invalid token: ".concat(i,". If you don not use token, set it to null"));i&&J(i,"token",1,2047),J(e,"appid",1,2047),gi(t),o&&vi(o),a&&J(a,"optionalInfo",1,2047)}catch(n){throw M.reportApiInvoke(lt(),{name:Ue.JOIN,options:[e,t,i,o],states:{isHttps:r,isSecureContext:c},tag:Me.TRACER}).onError(n),n}if(this._leaveMutex.isLocked){k.debug("[".concat(this._clientId,"] join: waiting leave operation"));(await this._leaveMutex.lock())(),k.debug("[".concat(this._clientId,"] join: continue"))}if(this._joinAndNotLeaveYet=!0,"DISCONNECTED"!==this.connectionState){const n=new U(q.INVALID_OPERATION,"[".concat(this._clientId,"] Client already in connecting/connected state"));throw M.reportApiInvoke(lt(),{name:Ue.JOIN,options:[e,t,i,o],states:{isHttps:r,isSecureContext:c},tag:Me.TRACER}).onError(n),n}this._gateway.state="CONNECTING";const d=await cs({appId:e,cname:t,uid:o,stringUid:"string"==typeof o?o:void 0,token:i||e,cloudProxyServer:this._cloudProxyServerMode});if(!this._joinAndNotLeaveYet)throw new U(q.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));const l=(null==d?void 0:d.sid)||lt();k.info("[".concat(this._clientId,"] start join channel ").concat(t,", join number: ").concat(s)),this._sessionId||(this._sessionId=l,this.store.sessionId=this._sessionId);const h=M.reportApiInvoke(l,{id:this._clientId,name:Ue.JOIN,options:[e,t,i,o],states:{isHttps:r,isSecureContext:c},tag:Me.TRACER}),u=di(di(di({},this._rtmConfig),{},{role:this.role,clientId:this._clientId,appId:e,sid:this._sessionId,cname:t,uid:"string"!=typeof o?o:null,turnServer:this._turnServer,proxyServer:this._proxyServer,token:i||e,cloudProxyServer:this._cloudProxyServerMode,optionalInfo:a,license:this._license,useLocalAccessPoint:this._useLocalAccessPoint,preload:!!d},void 0!==this._remoteDefaultVideoStreamType&&{defaultVideoStream:this._remoteDefaultVideoStreamType}),{},{apRequestDetail:Z("AP_REQUEST_DETAIL")||void 0});if(this._useLocalAccessPoint&&(u.setLocalAPVersion=this._setLocalAPVersion),"string"==typeof o&&(u.stringUid=o,this._uintUid?(u.uid=this._uintUid,this._uintUid=void 0):u.uid=0),"none"!==this._encryptionMode&&this._encryptionSecret){if(u.aesmode=this._encryptionMode,u.aespassword=await At(this._encryptionSecret),!this._joinAndNotLeaveYet)throw new U(q.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));this._encryptionSalt&&(u.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=Z("USE_PURE_ENCRYPTION_MASTER_KEY")?e.encode(u.appId+this._encryptionSecret+this._encryptionSecret):e.encode(u.appId+u.cname+this._encryptionSecret);this._encryptDataStreamIv=await gt(this._encryptionMode,t,_t(this._encryptionSalt)),this._encryptDataStreamKey=await vt(this._encryptionMode,t,_t(this._encryptionSalt))}else c?k.warning("[".concat(this._clientId,"] encrypt datastream must be running in a secure context, fallback to plain data stream")):k.warning("[".concat(this._clientId,"] current browser do not support WebCrypto ,fallback to plain data stream")),this._encryptDataStream=!1;else this._encryptDataStream=!1,k.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:u.stringUid});const _=this._sessionId;setTimeout((()=>{"CONNECTING"===this.connectionState&&_===this._sessionId&&M.joinChannelTimeout(this._sessionId,5)}),5e3);try{let o;const a=u.cloudProxyServer;if(["proxy3","proxy4","proxy5"].includes(a)){const e=Z("PROXY_SERVER_TYPE3");Array.isArray(e)?u.proxyServer=e[0]:u.proxyServer=e}if(M.setProxyServer(u.proxyServer),k.setProxyServer(u.proxyServer),this.store.requestAPStart(),d){if(k.debug("[".concat(this._clientId,"] get serverInfo Success from Preload Cache ").concat(u.stringUid?", ".concat(u.stringUid," => ").concat(d.intUid):""," ")),u.stringUid&&!u.uid&&(u.uid=d.intUid),o={gatewayInfo:d.ap.gatewayInfo},Z("JOIN_WITH_FALLBACK_MEDIA_PROXY")&&"auto"===u.turnServer.mode)if(0===d.ap.proxyInfo.addresses.length)k.warning("no edge services in ap response of proxy fallback, will not set proxy in iceServers");else{const e=(await wn(d.ap.proxyInfo,d.ap.gatewayInfo.uid)).map((e=>({turnServerURL:e.address,tcpport:e.tcpport||Se.tcpport,udpport:e.udpport||Se.udpport,username:e.username||Se.username,password:e.password||Se.password,forceturn:!1,security:!0})));u.turnServer={mode:"manual",servers:e}}us(d,u.stringUid)}else{if(u.stringUid&&!u.uid){let e;[e,o]=await Promise.all([Uo(u.stringUid,u,this._axiosCancelSource.token,this._config.httpRetryConfig||xe,this.store),ko(u,this._axiosCancelSource.token,this._config.httpRetryConfig||xe,!0,this.store)]),k.debug("[".concat(this._clientId,"] getUserAccount Success ").concat(u.stringUid," => ").concat(e)),u.uid=e,o.gatewayInfo.uid=e,o.gatewayInfo.res.uid=e}else o=await ko(u,this._axiosCancelSource.token,this._config.httpRetryConfig||xe,!0,this.store);if(!this._joinAndNotLeaveYet)throw new U(q.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"))}this.store.requestAPEnd(),setTimeout((()=>{this._configDistribute.startGetConfigDistribute(u,this._axiosCancelSource.token),this._configDistribute.on(Fi.UPDATE_BITRATE_LIMIT,(e=>{this._p2pChannel.updateBitrateLimit(e)})),this._configDistribute.on(Fi.UPDATE_CLIENT_ROLE_OPTIONS,(e=>{this._setClientRoleOptions(e)}))}),0),this._key=i||e;const s=o.gatewayInfo,r=u.uid?u.uid:s.uid;this._joinInfo=di(di({},u),{},{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 U(q.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));h.onSuccess(c),this._appId=e,this._channelName=u.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 l=u.stringUid?"string uid: ".concat(u.stringUid,",uid: ").concat(u.uid):"uid: ".concat(this._uid);return k.info("[".concat(this._clientId,"] Joining channel success: channel: ").concat(t,",").concat(l)),setTimeout((()=>{k.startUpload()}),5e3),this.store.joinEnd(),p=this,Qt.includes(p)||Qt.push(p),"disabled"===this._cloudProxyServerMode&&n().supportWebCrypto&&Z("ENABLE_PRELOAD")&&ls(this._joinInfo),c}catch(e){const t=Array.isArray(e)?e[0]:e;throw t&&t.code===q.OPERATION_ABORTED?k.warning("[".concat(this._clientId,"] join number: ").concat(s,", Joining channel failed, rollback"),t):k.error("[".concat(this._clientId,"] join number: ").concat(s,", Joining channel failed, rollback"),t),t.code!==q.OPERATION_ABORTED&&this._numberOfJoinCount===s&&(this._gateway.state="DISCONNECTED",this._reset()),h.onError(t),t}var p}_joinGateway(){if(!this._joinInfo||!this._key)throw new U(q.INVALID_OPERATION);return this._gateway.join(this._joinInfo,this._key,!("disabled"!==this._joinInfo.cloudProxyServer||this._joinInfo.proxyServer||!Z("JOIN_WITH_FALLBACK_SIGNAL_PROXY")))}async leave(){k.info("[".concat(this._clientId,"] Leaving channel")),window.removeEventListener(je()?"beforeunload":"pagehide",this._handleBeforeUnload),this._reset(),function(e){const t=Qt.indexOf(e);-1!==t&&Qt.splice(t,1)}(this),this._statsCollector.stopUpdateStats();const e=await this._leaveMutex.lock();if("DISCONNECTED"===this.connectionState)return k.info("[".concat(this._clientId,"] Leaving channel repeated, success")),void e();await this._gateway.leave("CONNECTED"!==this.connectionState,ue.LEAVE),k.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 v))return this._publishDataChannel(e);e=[e]}if(0===e.length)throw new U(q.INVALID_PARAMS,"param list is empty");const n=e;if("audience"===this._gateway.role)throw new U(q.INVALID_OPERATION,"audience can not publish stream");for(const e of n){if(!(e instanceof v))throw new U(q.INVALID_PARAMS,"parameter is not local track");if(!e._enabled&&t)throw new U(q.TRACK_IS_DISABLED,"can not publish a disabled track: ".concat(e.getTrackId()))}k.info("[".concat(this._clientId,"] Publishing tracks, id ").concat(n.map((e=>"".concat(e.getTrackId()," ")))));const o=await this._publishMutex.lock();await this._configDistribute.awaitConfigDistributeComplete(),t&&n.forEach((e=>{const t=this._configDistribute.getBitrateLimit();e instanceof i&&t&&e.setBitrateLimit(t.uplink)}));try{await this._publishHighStream(n),k.info("[".concat(this._clientId,"] Publish success, id ").concat(n.map((e=>"".concat(e.getTrackId()," ")))))}catch(e){throw k.error("[".concat(this._clientId,"] publish error"),e.toString()),e}finally{o()}}async _publishDataChannel(e){Et(e.id,"id",0,65535,!0),yt(e.ordered,"ordered"),J(e.metadata,"metadata",0,512),k.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 U(q.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 U(q.INVALID_OPERATION,"Can't publish datachannel, haven't joined yet!");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new U(q.INVALID_OPERATION,"can not publish datachannel in ".concat(this.connectionState," state"));if("auto"===this._turnServer.mode&&Z("FORCE_TURN")&&!Z("TURN_ENABLE_TCP")&&!Z("TURN_ENABLE_UDP"))throw new U(q.UNEXPECTED_ERROR,"force TURN With No TURN Configuration");const i=function(e){return oo(e,!1)}(e),n=await this._p2pChannel.publishDataChannel([i]);if(n.length>0){if("number"!=typeof i._originDataChannelId)throw k.error("[".concat(this._clientId,"] can not publish with mediaType datachannel, cannot get RTCDatachannel id")),new U(q.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!==q.DISCONNECT_P2P)throw e}}return k.info("[".concat(this._clientId,"] Publish dataChannels success, id ").concat(i.id)),i}catch(e){throw k.error("[".concat(this._clientId,"] publish datachannels error"),e.toString()),e}finally{t()}}async unpublish(e){if(!this._joinInfo||void 0===this._uid)throw new U(q.INVALID_OPERATION,"Can't unpublish stream, haven't joined yet!");let t=[];if(e)if(Array.isArray(e))t=e;else{if(!(e instanceof v))return this._unpublishDataChannel([e]);t=[e]}else this.store.useP2P||await this._unpublishDataChannel(),t=this._p2pChannel.getAllTracks(!0);k.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(on.UNPUBLISH,{unpubMsg:e},!0)}else{const e=await this._p2pChannel.unpublish(t);e&&await this._gateway.unpublish(e,this._uid),k.info("[".concat(this._clientId,"] Unpublish success,tracks ").concat(t.map((e=>"".concat(e.getTrackId())))))}}catch(e){throw k.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()),k.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),k.info("[".concat(this._clientId,"] Unpublish dataChannel success,dataChannel ").concat(e.map((e=>"".concat(e.id)))))}catch(e){throw k.error("[".concat(this._clientId,"] unpublish dataChannel error"),e.toString()),e}finally{t&&t()}}async subscribe(e,t,i){if(!(e instanceof Xo)){const t=this.remoteUsers.find((t=>t.uid===e));if(!t)throw new U(q.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(Nt(t,"mediaType",["audio","video"]),this.store.useP2P)throw new U(q.INVALID_OPERATION,"can't presub at p2p mode");if(!this._joinInfo)throw new U(q.INVALID_OPERATION,"can't presub when not join");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new U(q.INVALID_OPERATION,"can't presub in ".concat(this.connectionState," state"));const i=t===Hi.AUDIO,n=t===Hi.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 U(q.UNEXPECTED_RESPONSE,"no ssrc id");let l=this._users.find((t=>t.uid===e));l||(l=new Xo(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)),k.info("[".concat(this._clientId,"] presub succeed ssrc: ").concat(a)),await this._p2pChannel.subscribe(l,t,a,r,s);const h=i?l._audioTrack:l._videoTrack;if(!h)throw new U(q.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),h}catch(t){throw k.error("[".concat(this._clientId,"] presub user ").concat(e," error"),t),t}finally{o()}}async _subscribeDataChannel(e,t){var i;if(Et(t,"channelId",0,65535,!0),!this._joinInfo)throw new U(q.INVALID_OPERATION,"Can't subscribe datachannel, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new U(q.INVALID_OPERATION,"Can't subscribe datachannel in ".concat(this.connectionState," state"));if(!this._users.find((t=>t===e)))throw k.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", this user is not in the channel")),new U(q.INVALID_REMOTE_USER,"user is not in the channel");if(!e.hasAudio&&!e.hasVideo&&0===e._dataChannels.length)throw k.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", user is not published")),new U(q.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 k.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid," with mediaType datachannel, remote datachannel is not published")),new U(q.REMOTE_USER_IS_NOT_PUBLISHED);const o=await this._subscribeMutex.lock();k.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 k.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid," with mediaType datachannel, cannot get RTCDatachannel")),new U(q.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)!==q.WS_ABORT)throw await this._p2pChannel.unsubscribeDataChannel(e,[n]),t;await this._p2pChannel.unsubscribeDataChannel(e,[n]),this._p2pChannel.setPendingRemoteDataChannel(e,n.id)}return k.info("[".concat(this._clientId,"] subscribe success user ").concat(e.uid,", mediaType: datachannel")),n}finally{o()}}async _p2pSubscribe(e,t,i){if(Nt(t,"mediaType",["audio","video"]),!this._joinInfo)throw new U(q.INVALID_OPERATION,"Can't subscribe stream, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new U(q.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));if(!this._users.find((t=>t===e))){const t=new U(q.INVALID_REMOTE_USER,"user is not in the channel");throw k.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 U(q.INVALID_REMOTE_USER,"user is not published");throw k.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 U(q.REMOTE_USER_IS_NOT_PUBLISHED);throw k.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();k.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}k.info("[".concat(this._clientId,"] subscribe success user ").concat(e.uid,", mediaType: ").concat(t)),this._defaultStreamFallbackType&&this.setStreamFallbackOption(e.uid,this._defaultStreamFallbackType).catch((e=>{k.warning("[".concat(this._clientId,"] auto set fallback failed"),e)}));const i="audio"===t?e._audioTrack:e._videoTrack;if(!i)throw new U(q.UNEXPECTED_ERROR,"can not find remote track in user object");return i}catch(t){throw k.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(Nt(t,"mediaType",["audio","video"]),!this._joinInfo)throw new U(q.INVALID_OPERATION,"Can't subscribe stream, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new U(q.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));if(!this._users.find((t=>t===e))){const t=new U(q.INVALID_REMOTE_USER,"user is not in the channel");throw k.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 U(q.INVALID_REMOTE_USER,"user is not published");throw k.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 U(q.REMOTE_USER_IS_NOT_PUBLISHED);throw k.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?Hi.AUDIO:Hi.VIDEO,ssrcId:n};const r=await this._subscribeMutex.lock();k.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?Hi.AUDIO:Hi.VIDEO,ssrcId:n}),Ho.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)!==q.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}k.info("[".concat(this._clientId,"] subscribe success user ").concat(e.uid,", mediaType: ").concat(t)),this._defaultStreamFallbackType&&this.setStreamFallbackOption(e.uid,this._defaultStreamFallbackType).catch((e=>{k.warning("[".concat(this._clientId,"] auto set fallback failed"),e)}));const i="audio"===t?e._audioTrack:e._videoTrack;if(!i)throw new U(q.UNEXPECTED_ERROR,"can not find remote track in user object");return i}catch(t){throw k.error("[".concat(this._clientId,"] subscribe user ").concat(e.uid," error"),t),t}finally{r()}}async massSubscribe(e){if(wt(e,"subscribeList"),!this._joinInfo)throw new U(q.INVALID_OPERATION,"Can't subscribe stream, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new U(q.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));const t=Date.now(),i=new Map,n=await this._subscribeMutex.lock();k.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(Nt(s,"mediaType",["audio","video"]),!a){const e=new U(q.INVALID_PARAMS,"user property does not exist in subscribeList item");throw k.error("[".concat(this._clientId,"] user property does not exist in subscribeList item")),e}if(!this._users.find((e=>e===a))){const i=new U(q.INVALID_REMOTE_USER,"user is not in the channel");k.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 U(q.REMOTE_USER_IS_NOT_PUBLISHED);k.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=Ui.Video|Ui.LwoVideo,c=i.get(a);if(c){if("video"===s?c&r:c&Ui.Audio){e.splice(t,1),k.warning("[".concat(this._clientId,"] repeat massSubscribe user:").concat(a.uid,", mediaType:").concat(s," twice"));continue}i.set(a,c|("video"===s?r:Ui.Audio))}else i.set(a,"video"===s?r:Ui.Audio)}for(let t=e.length-1;t>=0;t--){const n=e[t],{user:o,mediaType:a}=n,s=Ui.Video|Ui.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^Ui.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&Ui.Audio&&(o.audio_ssrc=i._audioSSRC),n&Ui.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===Hi.VIDEO?t._videoSSRC:t._audioSSRC,rtxSsrcId:i===Hi.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=Hi.VIDEO:n.audio_error_code&&(t=Hi.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=dn(i);k.error("user:".concat(e.user.uid," mediaType:").concat(e.mediaType," has massSubscribe error ").concat(t.desc)),e.error=new U(q.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;M.subscribe(this.store.sessionId,{succ:!!e.error,ec:(null===(i=e.error)||void 0===i?void 0:i.code)||null,video:e.mediaType===Hi.VIDEO,audio:e.mediaType===Hi.AUDIO,peerid:e.user.uid,subscribeRequestid:e.mediaType===Hi.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)})),k.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 Xo)){const t=this.remoteUsers.find((t=>t.uid===e));if(!t)throw new U(q.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&&Nt(t,"mediaType",["audio","video"]),!this._joinInfo)throw new U(q.INVALID_OPERATION,"Can't unsubscribe stream, haven't joined yet!");if(!this._users.find((t=>t===e))){const t=new U(q.INVALID_REMOTE_USER,"user is not in the channel");throw k.error("[".concat(this._clientId,"] can not unsubscribe ").concat(e.uid,", user is not in the channel")),t}k.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&&St(this._users,e),k.info("[".concat(this._clientId,"] unsubscribe success uid: ").concat(e.uid,", mediaType: ").concat(t))}}catch(t){if(t.code===q.DISCONNECT_P2P)return void k.warning("disconnecting p2p, abort unsubscribe request.");throw k.error("[".concat(this._clientId,"] unsubscribe user ").concat(e.uid," error"),t.toString()),t}finally{n()}}async _unsubscribeDataChannel(e,t){if(t&&Et(t,"id",0,65535,!0),!this._joinInfo)throw new U(q.INVALID_OPERATION,"Can't unsubscribe datachannel, haven't joined yet!");if(!this._users.find((t=>t===e))){const t=new U(q.INVALID_REMOTE_USER,"user is not in the channel");throw k.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 U(q.REMOTE_USER_IS_NOT_PUBLISHED);throw k.error("[".concat(this._clientId,"] can not unsubscribe ").concat(e.uid," with channelId ").concat(t,", remote datachannel is not published")),i}k.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),k.info("[".concat(this._clientId,"] unsubscribe datachannel success uid: ").concat(e.uid,", mediaType: datachannel, ids: ").concat(t))}catch(t){if(t.code===q.DISCONNECT_P2P)return void k.warning("disconnecting p2p, abort unsubscribe request.");throw k.error("[".concat(this._clientId,"] unsubscribe user ").concat(e.uid," error"),t.toString()),t}}async massUnsubscribe(e){if(wt(e,"unsubscribeList"),!this._joinInfo)throw new U(q.INVALID_OPERATION,"Can't unsubscribeAll stream, haven't joined yet!");k.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 U(q.INVALID_PARAMS,"user property does not exist in unsubscribeList item");throw k.error("[".concat(this._clientId,"] user property does not exist in unsubscribeList item")),e}Nt(o,"mediaType",["video","audio",void 0]);if(!this._users.find((e=>e===n))){k.warning("[".concat(this._clientId,"] can not unsubscribe ").concat(n.uid,", user is not in the channel")),e.splice(i,1);continue}const a=Ui.Video|Ui.LwoVideo;if(t.has(n)){const s=t.get(n);let r;switch(o){case"video":r=s&a;break;case"audio":r=s&Ui.Audio;break;default:r=s&(Ui.Audio|a)}if(r){k.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|Ui.Audio):"video"===o&&t.set(n,s|a):t.set(n,s|Ui.Audio|a)}else o?"audio"===o?t.set(n,Ui.Audio):"video"===o&&t.set(n,a):t.set(n,Ui.Audio|a)}try{const t=await this._p2pChannel.massUnsubscribe(e);t&&await this._gateway.massUnsubscribe(t),k.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===q.DISCONNECT_P2P)return void k.warning("[".concat(this._clientId,"] disconnecting p2p, abort unsubscribe request."));throw k.error("[".concat(this._clientId,"] massUnsubscribe error"),e.toString()),e}}async setLowStreamParameter(e){N(e),(!e.width&&e.height||e.width&&!e.height)&&k.warning("[".concat(this._clientId,"] The width and height parameters take effect only when both are set")),k.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,Xi.LocalVideoLowTrack)}async enableDualStream(){if(!n().supportDualStream)throw M.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!0,succ:!1}),new U(q.NOT_SUPPORTED,"Your browser is not support dual stream");if(this._isDualStreamEnabled)throw new U(q.INVALID_OPERATION,"Dual stream is already enabled");if(this._p2pChannel.canPublishLowStream())try{await this._publishLowStream()}catch(e){throw M.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!0,succ:!1}),e}this._isDualStreamEnabled=!0,M.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!0,succ:!0}),k.info("[".concat(this._clientId,"] enable dual stream"))}async disableDualStream(){if(this._isDualStreamEnabled){if(!this._joinInfo)throw new U(q.INVALID_OPERATION,"Can't publish stream, haven't joined yet!");if(this._p2pChannel.getLocalMedia(Xi.LocalVideoLowTrack))try{const e=await this._p2pChannel.unpublishLowStream();e&&await this._gateway.unpublish(e,this._joinInfo.stringUid||this._joinInfo.uid)}catch(e){throw M.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!1,succ:!1}),e}this._isDualStreamEnabled=!1,M.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!1,succ:!0}),k.info("[".concat(this._clientId,"] disable dual stream"))}}async setClientRole(e,t){if(Ot(e),t&&Tt(t),"rtc"===this.mode||"p2p"===this.mode)throw k.warning("[".concat(this._clientId,"]").concat(this.mode," mode can not use setClientRole")),new U(q.INVALID_OPERATION,"".concat(this.mode," mode can not use setClientRole"));if(t&&t.level&&"host"===e)throw new U(q.INVALID_OPERATION,"host mode can not set audience latency level");if("audience"===e&&this._p2pChannel.hasLocalMedia())throw new U(q.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&&Z("ENABLE_ROLE_SELECT_EDGE")?(this._gateway.updateClientRole(e,t),this._config.role=e,this._gateway.reconnect("recover",_e.REGIONAL_DISTRIBUTION)):(await this._gateway.setClientRole(e,t),this._config.role=e),k.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&&Tt(e),await this._gateway.setClientRole(this._config.role,e),t=!0}catch(e){}finally{k.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(J(e,"proxyServer"),!t){if("DISCONNECTED"!==this.connectionState)throw new U(q.INVALID_OPERATION,"Set proxy server before join channel");if("disabled"!==this._cloudProxyServerMode||this._useLocalAccessPoint)throw new U(q.INVALID_OPERATION,"You have already set the proxy")}this._proxyServer=e,M.setProxyServer(this._proxyServer),k.setProxyServer(this._proxyServer),k.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 U(q.INVALID_OPERATION,"Set turn server before join channel");if("disabled"!==this._cloudProxyServerMode||this._useLocalAccessPoint)throw new U(q.INVALID_OPERATION,"You have already set the proxy")}if($e(e))return this._turnServer={servers:e,mode:"original-manual"},void k.info("[".concat(this._clientId,"] Set original turnserver ").concat(t?"by initialize call":""," success: ").concat(e.map((e=>e.urls)).join(","),"."));e.forEach((e=>bt(e))),this._turnServer={servers:e,mode:"manual"},k.info("[".concat(this._clientId,"] Set turnserver ").concat(t?"by initialize call":""," success."))}setLicense(e){if("DISCONNECTED"!==this.connectionState){throw new U(q.INVALID_OPERATION,"you should set license before join channel")}if(J(e,"license",32,32),!/^[A-Za-z\d]+$/.test(e))throw new U(q.INVALID_PARAMS,"license should only contains characters from A-Z a-z 0-9");this._license=e,k.info("[".concat(this._clientId,"] set license success"),e)}startProxyServer(e){if("DISCONNECTED"!==this.connectionState)throw new U(q.INVALID_OPERATION,"Start proxy server before join channel");if(this._proxyServer||"manual"===this._turnServer.mode||this._useLocalAccessPoint)throw new U(q.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 U(q.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 U(q.INVALID_PARAMS,"proxy server mode must be ".concat(t.join("|")))}this._cloudProxyServerMode=i,this.store.cloudProxyServerMode=i,k.info("[".concat(this._clientId,"] set cloud proxy server mode to"),this._cloudProxyServerMode)}stopProxyServer(){if("DISCONNECTED"!==this.connectionState)throw new U(q.INVALID_OPERATION,"Stop proxy server after leave channel");M.setProxyServer(),k.setProxyServer(),this._cloudProxyServerMode="disabled",this.store.cloudProxyServerMode="disabled",k.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 U(q.INVALID_PARAMS,"accessPoints is required.");wt(e.accessPoints.serverList,"accessPoints.serverList"),J(e.accessPoints.domain,"accessPoints.domain");const t=(e,t)=>{Et(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 U(q.INVALID_OPERATION,"set local access point failed, You have already set the cloud proxy");Z("CLOSE_AFB_FOR_LOCAL_AP")&&(Pe("JOIN_WITH_FALLBACK_SIGNAL_PROXY",!1),Pe("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,Pe("WEBCS_DOMAIN",s),Pe("WEBCS_DOMAIN_BACKUP_LIST",s),Pe("GATEWAY_DOMAINS",[o]),e.report&&e.report.hostname&&Array.isArray(e.report.hostname)&&e.report.hostname.length?(wt(e.report.hostname,"report.hostname"),Pe("EVENT_REPORT_DOMAIN",e.report.hostname[0]),Pe("EVENT_REPORT_BACKUP_DOMAIN",e.report.hostname[1]||e.report.hostname[0])):(Pe("EVENT_REPORT_DOMAIN",a[0]),Pe("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),Pe("STATS_COLLECTOR_PORT",r),e.report?Pe("ENABLE_EVENT_REPORT",!0):Pe("ENABLE_EVENT_REPORT",!1);let c="";e.log&&e.log.hostname&&Array.isArray(e.log.hostname)&&e.log.hostname.length?(wt(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),Pe("LOG_UPLOAD_SERVER","".concat(c,":").concat(d));let l=[];e.cds&&e.cds.hostname&&Array.isArray(e.cds.hostname)&&e.cds.hostname.length?(wt(e.cds.hostname,"cds.hostname"),l=e.cds.hostname):l=a;let h=443;e.cds&&e.cds.port&&(t(e.cds.port,"cds.port"),h=e.cds.port),Pe("CDS_AP",l.map((e=>"".concat(e,":").concat(h)))),e.cds?Pe("ENABLE_CONFIG_DISTRIBUTE",!0):Pe("ENABLE_CONFIG_DISTRIBUTE",!1),k.info("set local access point v2 success")}setLocalAccessPoints(e,t){if(wt(e,"serverList"),J(t,"domain"),this._proxyServer||"disabled"!==this._cloudProxyServerMode)throw new U(q.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,Pe("WEBCS_DOMAIN",e),Pe("WEBCS_DOMAIN_BACKUP_LIST",e),Pe("GATEWAY_DOMAINS",[t]),Pe("EVENT_REPORT_DOMAIN",e[0]),Pe("EVENT_REPORT_BACKUP_DOMAIN",e[1]||e[0]),Pe("LOG_UPLOAD_SERVER","".concat(e[0],":6444")),k.info("[".concat(this._clientId,"] set local access point success"))}async setRemoteDefaultVideoStreamType(e){if(Nt(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 k.error("[".concat(this._clientId,"] set default remote video stream type error"),e.toString()),e}else k.debug("[".concat(this._clientId,"] haven't joined yet, cache remoteDefaultVideoStreamType ").concat(e))}async setRemoteVideoStreamType(e,t){Nt(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 k.error("[".concat(this._clientId,"] set remote video stream type error"),e.toString()),e}k.info("[".concat(this._clientId,"] set remote ").concat(e," video stream type to ").concat(t)),this._remoteStreamTypeCacheMap.set(e,t)}async setStreamFallbackOption(e,t){Nt(t,"fallbackType",[0,1,2,3,4,5,6,7,8]);try{await this._gateway.setStreamFallbackOption(e,t)}catch(e){throw k.error("[".concat(this._clientId,"] set stream fallback option"),e.toString()),e}k.info("[".concat(this._clientId,"] set remote ").concat(e," stream fallback type to ").concat(t)),this._streamFallbackTypeCacheMap.set(e,t)}setEncryptionConfig(e,t,i,n){Dt(e),J(t,"secret");const o=["aes-128-gcm2","aes-256-gcm2"];if(o.includes(e)){if(!i||!(i instanceof Uint8Array&&32===i.length))throw new U(q.INVALID_PARAMS,"salt must be an Uint8Array and exactly equal to 32 bytes")}else if(i)throw new U(q.INVALID_PARAMS,"current encrypt mode does not need salt");if(n){if(yt(n,"encryptDataStream"),!o.includes(e))throw new U(q.INVALID_PARAMS,"current encrypt mode does not support data stream");this._encryptDataStream=!0}new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*,.<>?/:;'\"|{}\\[\\]])(?=.{8,})").test(t)||k.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=pt(i))}async renewToken(e){if(J(e,"token",1,2047),!this._key||!this._joinInfo)throw new U(q.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(Z("USE_NEW_TOKEN")){k.debug("[".concat(this._clientId,"] start renew token with ticket from unilbs"));const t=await Fo(this._joinInfo,this._axiosCancelSource.token,this._config.httpRetryConfig||xe);k.debug("[".concat(this._clientId,"] get ticket from unilbs success")),await this._gateway.renewToken({token:e,ticket:t})}else k.debug("[".concat(this._clientId,"] start renew token without ticket")),await this._gateway.renewToken({token:e});k.debug("[".concat(this._clientId,"] renewToken success"))}catch(e){throw this._key=t,this._joinInfo.token=t,k.error("[".concat(this._clientId,"] renewToken failed"),e.toString()),e}finally{i()}}enableAudioVolumeIndicator(){this._audioVolumeIndicationInterval?k.warning("you have already enabled audio volume indicator!"):this._audioVolumeIndicationInterval=window.setInterval((()=>{const e=this._p2pChannel.getAudioLevels();this.safeEmit(rt.VOLUME_INDICATOR,e)}),Z("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 U(q.LIVE_STREAMING_INVALID_RAW_STREAM,"raw streaming is only support h264");if(!this._p2pChannel.hasLocalMedia())throw new U(q.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 U(q.LIVE_STREAMING_TASK_CONFLICT);const i=t?yi.TRANSCODE:yi.RAW;return this._createLiveStreamingClient(i).startLiveStreamingTask(e,i)}setLiveTranscoding(e){return this._createLiveStreamingClient(yi.TRANSCODE).setTranscodingConfig(e)}async stopLiveStreaming(e){const t=[this._liveRawStreamingClient,this._liveTranscodeStreamingClient].filter((t=>t&&t.hasUrl(e)));if(!t.length)throw new U(q.INVALID_PARAMS,"can not find live streaming url to stop");await Promise.all(t.map((t=>t&&t.stopLiveStreamingTask(e))))}async startChannelMediaRelay(e){qo(e);const t=this._createChannelMediaRelayClient();await t.startChannelMediaRelay(e)}async updateChannelMediaRelay(e){qo(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 Va&&this._p2pChannel.addAudioMetadata(e)}async sendStreamMessage(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!this._joinInfo)throw new U(q.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 Pt(this._encryptDataStreamIv,this._encryptDataStreamKey,e.payload));if(new Blob([e.payload]).size>1024)throw new U(q.INVALID_PARAMS,i?"encrypted stream message out of range.":"stream message out of range.");return this._gateway.signal.request(Ti.DATA_STREAM,{payload:pt(e.payload),syncWithAudio:e.syncWithAudio,sendTs:Date.now()-Ba},!t)}sendMetadata(e){if(!this._joinInfo)throw new U(q.INVALID_OPERATION,"can not send metadata, not joined");if(new Blob([e]).size>1024)throw new U(q.METADATA_OUT_OF_RANGE);return this._gateway.signal.request(Ti.SEND_METADATA,{session_id:this._joinInfo.sid,metadata:pt(e)})}async sendCustomReportMessage(e){if(Array.isArray(e)||(e=[e]),e.forEach(j),!this._joinInfo)throw new U(q.INVALID_OPERATION,"can not send custom report, not joined");await M.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(){return this._statsCollector.getRemoteNetworkQualityStats()}async pickSVCLayer(e,t){Nt(t.spatialLayer,"spatialLayer",[0,1,2,3]),Nt(t.temporalLayer,"temporalLayer",[0,1,2,3]);try{await this._gateway.pickSVCLayer(e,t)}catch(e){throw k.error("[".concat(this._clientId,"] pick SVC layer failed"),e.toString()),e}}async setRTMConfig(e){const{apRTM:t=!1,rtmFlag:i}=e;if(yt(t,"apRTM"),Et(i,"rtmFlag",0),this._rtmConfig.apRTM=t,this._rtmConfig.rtmFlag=i,k.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(k.debug("[".concat(this._clientId,"] reset client")),function(e){const t=Zt.indexOf(e);-1!==t&&Zt.splice(t,1)}(this._clientId),this.store.hasStartJoinChannel=!1,this.store.isABTestSuccess=!1,this._axiosCancelSource.cancel(),this._axiosCancelSource=Ht.CancelToken.source(),this._streamFallbackTypeCacheMap=new Map,this._remoteStreamTypeCacheMap=new Map,this._configDistribute.stopGetConfigDistribute(),this._joinInfo&&hs(this._joinInfo),this._joinInfo=void 0,this._proxyServer=void 0,this._defaultStreamFallbackType=void 0,this._sessionId&&M.removeSid(this._sessionId),this._sessionId=null,this.store.sessionId=null,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 ie("client-publish",this._clientId),this._subscribeMutex=new ie("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||lt();e?k.debug("[".concat(this._clientId,"] new Session ").concat(n)):k.debug("[".concat(this._clientId,"] renewSession ").concat(this._sessionId," => ").concat(n));const o=e?"":this._sessionId||"";this._sessionId=n,this.store.sessionId=n,M.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};M.sessionInit(this._sessionId,di({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 U(q.INVALID_OPERATION,"Can't publish stream, haven't joined yet!");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new U(q.INVALID_OPERATION,"can not publish stream in ".concat(this.connectionState," state"));if("auto"===this._turnServer.mode&&Z("FORCE_TURN")&&!Z("TURN_ENABLE_TCP")&&!Z("TURN_ENABLE_UDP"))throw new U(q.UNEXPECTED_ERROR,"force TURN With No TURN Configuration");k.debug("[".concat(this._clientId,"] publish high stream"));try{const n=await this._p2pChannel.publish(e,this._isDualStreamEnabled,this._lowStreamParameter);if(this.store.useP2P){const e=(await n.next()).value;if(e){try{await this._gateway.sendExtensionMessage(on.PUBLISH,e,!0)}catch(e){throw n.throw(e),e}await n.next()}this._p2pChannel.reportPublishEvent(!0,null)}else{const o=(await n.next()).value;if(o){var t;let e;try{e=await this._gateway.publish(this._uid,o,!0)}catch(e){if(e.code!==q.DISCONNECT_P2P)throw n.throw(e),e}await n.next((null===(t=e)||void 0===t?void 0:t.ortc)||[])}this._p2pChannel.reportPublishEvent(!0,null);for(const t of e)t instanceof i&&t._encoderConfig&&this._gateway.setVideoProfile(t._encoderConfig).catch((e=>{k.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)===q.WS_ABORT)return;throw t}}async _publishLowStream(){if(!this._joinInfo||void 0===this._uid)throw new U(q.INVALID_OPERATION,"Can't publish stream, haven't joined yet!");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new U(q.INVALID_OPERATION,"can not publish stream in ".concat(this.connectionState," state"));k.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!==q.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)===q.WS_ABORT)return;throw e}}_createLiveStreamingClient(e){const t=()=>{if(!this._joinInfo||!this._appId){return new U(q.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},no("LiveStreaming").create(t));var t;return e.onLiveStreamError=(e,t)=>{M.reportApiInvoke(this._sessionId,{name:Ue.ON_LIVE_STREAM_ERROR,options:[e,t],tag:Me.TRACER}).onSuccess(),this.safeEmit(rt.LIVE_STREAMING_ERROR,e,t)},e.onLiveStreamWarning=(e,t)=>{M.reportApiInvoke(this._sessionId,{name:Ue.ON_LIVE_STREAM_WARNING,options:[e,t],tag:Me.TRACER}).onSuccess(),this.safeEmit(rt.LIVE_STREAMING_WARNING,e,t)},e.on(Ni.REQUEST_WORKER_MANAGER_LIST,((e,t,i)=>{if(!this._joinInfo)return i(new U(q.INVALID_OPERATION,"can not find join info to get worker manager"));(async function(e,t,i,n){const o=Z("UAP_AP").slice(0,Z("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 Io(o,e,t,i,n)})(e,this._joinInfo,this._axiosCancelSource.token,xe).then(t).catch(i)})),e};return e===yi.RAW?(this._liveRawStreamingClient=this._liveRawStreamingClient||t(),this._liveRawStreamingClient):(this._liveTranscodeStreamingClient=this._liveTranscodeStreamingClient||t(),this._liveTranscodeStreamingClient)}_createChannelMediaRelayClient(){if(!this._joinInfo){return new U(q.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}},no("ChannelMediaRelay").create(e));n.on("state",(e=>{e===bi.RELAY_STATE_FAILURE&&n&&n.dispose(),this.safeEmit(rt.CHANNEL_MEDIA_RELAY_STATE,e)})),n.on("event",(e=>{this.safeEmit(rt.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 k.error("[".concat(this._clientId,"] can not find target user!(on_add_data_channel)"));k.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 oo(e,!0)}(e);r._dataChannels.push(i),k.info("[".concat(this._clientId,"] remote user ").concat(r.uid," published datachannel")),t||this.safeEmit(rt.USER_PUBLISHED,r,"datachannel",e)}this._p2pChannel.hasPendingRemoteDataChannel(r,e.stream_id)&&(k.debug("[".concat(this._clientId,"] resubscribe datachannel for user ").concat(r.uid," after reconnect.")),this._subscribeDataChannel(r,e.stream_id).catch((e=>{k.error("[".concat(this._clientId,"] resubscribe datachannel error"),e.toString())})))})),t&&(this.safeEmit(rt.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 k.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&&(k.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)})),k.info("[".concat(this._clientId,"] remote user ").concat(t," unpublished datachannel ,id:").concat(o.id)),this.safeEmit(rt.USER_UNPUBLISHED,n,"datachannel",o._config))}))}_handleRemoveDataChannels(e){const t=this._users.find((t=>t.uid===e.uid));if(t){if(void 0!==t._dataChannels&&t._dataChannels.length>0){k.debug("[".concat(this._clientId,"] datachannel removed with uid ").concat(e.uid));const i=()=>{k.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished datachannel")),t._dataChannels.forEach((e=>{this.safeEmit(rt.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 k.warning("[".concat(this._clientId,"] can not find target user!(on_remove_datachannel)"))}_handleGatewayEvents(){this._gateway.on(Li.UPDATE_GATEWAY_CONFIG,(()=>{!function(){let e;try{e=window.localStorage.getItem("websdk_ng_global_parameter")}catch(e){return void k.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||ei()||!Object.prototype.hasOwnProperty.call(H,e)||(W[e]=n,G[e]=n,k.debug("Update gateway parameters from config distribute",e,n))}))}catch(e){k.error("Error update config from local cache",e.message)}}()})),this._gateway.on(Li.DISCONNECT_P2P,(async()=>{await this._p2pChannel.disconnectForReconnect()})),this._gateway.on(Li.CONNECTION_STATE_CHANGE,((e,t,i)=>{var n;if(i===ue.FALLBACK)return;const o=()=>{this.safeEmit(rt.CONNECTION_STATE_CHANGE,e,t,i)};if(M.reportApiInvoke(this._sessionId||(null===(n=this._gateway.joinInfo)||void 0===n?void 0:n.sid)||null,{name:Ue.CONNECTION_STATE_CHANGE,options:[e,t,i],tag:Me.TRACER}).onSuccess(JSON.stringify({cur:e,prev:t,reason:i})),k.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=>{k.warning("[".concat(this._clientId,"] auto set stream fallback option failed"),e)}))})),this._remoteStreamTypeCacheMap.forEach(((e,t)=>{this._gateway.setRemoteVideoStreamType(t,e).catch((e=>{k.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((()=>{k.debug("[".concat(this._clientId,"] setRemoteDefaultVideoStreamType after gateway connected"))})).catch((e=>{k.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=>{k.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_||(k.debug("[".concat(this._clientId,"] auto dispatch audio unmute event ").concat(e.uid)),this._handleMuteStream(e.uid,Hi.AUDIO,!1)),e._trust_video_mute_state_||(k.debug("[".concat(this._clientId,"] auto dispatch video unmute event ").concat(e.uid)),this._handleMuteStream(e.uid,Hi.VIDEO,!1)),e._trust_audio_enabled_state_||(k.debug("[".concat(this._clientId,"] auto dispatch enable local audio ").concat(e.uid)),this._handleSetStreamLocalEnable("audio",e.uid,!0)),e._trust_video_enabled_state_||(k.debug("[".concat(this._clientId,"] auto dispatch enable local video ").concat(e.uid)),this._handleSetStreamLocalEnable("video",e.uid,!0)),e._trust_video_stream_added_state_||(k.debug("[".concat(this._clientId,"] auto dispatch reset video stream added ").concat(e.uid)),this._handleResetAddStream(e,"video")),e._trust_audio_stream_added_state_||(k.debug("[".concat(this._clientId,"] auto dispatch reset audio stream added ").concat(e.uid)),this._handleResetAddStream(e,"audio")),e._video_added_||e._audio_added_||(k.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(Li.REQUEST_NEW_GATEWAY_LIST,(async(e,t)=>{if(!this._joinInfo)return t(new U(q.UNEXPECTED_ERROR,"can not recover, no join info"));try{let t;const i=await cs(di(di({},this._joinInfo),{},{uid:this._joinInfo.uid,stringUid:void 0}));i?(t=i.ap,us(i),this._joinInfo.preload=!0):(t=await Lo(this._joinInfo,this._axiosCancelSource.token,this._config.httpRetryConfig||xe,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(Li.NETWORK_QUALITY,(e=>{"normal"===this._networkQualitySensitivity&&this.safeEmit(rt.NETWORK_QUALITY,e)})),this._gateway.on(Li.STREAM_TYPE_CHANGE,((e,t)=>{this.safeEmit(rt.STREAM_TYPE_CHANGED,e,t);M.reportApiInvoke(this._sessionId,{name:Ue.STREAM_TYPE_CHANGE,options:[e,t],tag:Me.TRACER}).onSuccess(JSON.stringify({uid:e,streamType:t}))})),this._gateway.on(Li.IS_P2P_DISCONNECTED,(e=>{this._p2pChannel.isP2PDisconnected()?e(!0):this._p2pChannel.hasLocalMedia()||this._p2pChannel.hasRemoteMedia()?e(!1):e(!0)})),this._gateway.on(Li.REQUEST_P2P_CONNECTION_PARAMS,(async(e,t,i)=>{try{let i=await this._p2pChannel.getEstablishParams();Z("ENABLE_PREALLOC_PC")&&i||(i=await this._p2pChannel.startP2PConnection(e)),t(i)}catch(e){i(e)}})),this._gateway.on(Li.JOIN_RESPONSE,((e,t)=>{if(this.store.useP2P)return;let i;e.attributes?i=e.attributes.userAttributes.preSubSsrcs:k.debug("no attributes in joinResponse");const n=Bn(e.ortc,t,i);this._p2pChannel.connect(n)})),this._gateway.on(Li.PRE_CONNECT_PC,(async e=>{const{candidates:t,fingerprint:i}=e;if(this._joinInfo&&t.length>0&&!this._p2pChannel.isPlanB){var n;await this._p2pChannel.startP2PConnection({turnServer:this._joinInfo.turnServer});const{cert:e,cid:o}=this._joinInfo.apResponse;await this._p2pChannel.connect({iceParameters:{iceUfrag:"".concat(o,"_").concat(e),icePwd:"".concat(o,"_").concat(e)},dtlsParameters:{fingerprints:[{hashFunction:"sha-256",fingerprint:null!==(n=Z("FINGERPRINT"))&&void 0!==n?n:i}]},candidates:t,rtpCapabilities:{send:{audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]},recv:{audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]}},setup:"active",cname:"o/i14u9pJrxRKAsu",preallocation:!0})}}))}_handleGatewaySignalEvents(){this._gateway.signal.on(Ci.ON_USER_ONLINE,this._handleUserOnline),this._gateway.signal.on(Ci.ON_USER_OFFLINE,this._handleUserOffline),this._gateway.signal.on(Ci.ON_ADD_AUDIO_STREAM,(e=>this._handleAddAudioOrVideoStream("audio",e.uid,e.ssrcId,e.cname,e.uint_id,e.ortc))),this._gateway.signal.on(Ci.ON_ADD_VIDEO_STREAM,(e=>this._handleAddAudioOrVideoStream("video",e.uid,e.ssrcId,e.cname,e.uint_id,e.ortc,e.rtxSsrcId))),this._gateway.signal.on(Ci.ON_REMOTE_DATASTREAM_UPDATE,(e=>{this._handleUpdateDataChannel(e)})),this._gateway.signal.on(Ci.ON_REMOTE_FULL_DATASTREAM_INFO,(e=>{this._handleUpdateDataChannel({added:e.datastreams||[],deleted:[]},!0)})),this._gateway.signal.on(Ci.ON_REMOVE_STREAM,this._handleRemoveStream),this._gateway.signal.on(Ci.ON_P2P_LOST,this._handleP2PLost),this._gateway.signal.on(Ci.MUTE_AUDIO,(e=>this._handleMuteStream(e.uid,Hi.AUDIO,!0))),this._gateway.signal.on(Ci.UNMUTE_AUDIO,(e=>this._handleMuteStream(e.uid,Hi.AUDIO,!1))),this._gateway.signal.on(Ci.MUTE_VIDEO,(e=>this._handleMuteStream(e.uid,Hi.VIDEO,!0))),this._gateway.signal.on(Ci.UNMUTE_VIDEO,(e=>this._handleMuteStream(e.uid,Hi.VIDEO,!1))),this._gateway.signal.on(Ci.RECEIVE_METADATA,(e=>{const t=_t(e.metadata);this.safeEmit(rt.RECEIVE_METADATA,e.uid,t)})),this._gateway.signal.on(Ci.ON_DATA_STREAM,(async e=>{if(!e)return;let t=_t(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<Lt)throw new U(q.UNEXPECTED_RESPONSE,"payload length ".concat(e.payload.length," is less than header length ").concat(Lt));t=await kt(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),Ka(di(di({},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(Ci.ON_CRYPT_ERROR,(()=>{dt((()=>{k.warning("[".concat(this._clientId,"] on crypt error")),this.safeEmit(rt.CRYPT_ERROR)}),this._sessionId)})),this._gateway.signal.on(Ci.ON_TOKEN_PRIVILEGE_WILL_EXPIRE,this._handleTokenWillExpire),this._gateway.signal.on(Ci.ON_TOKEN_PRIVILEGE_DID_EXPIRE,(()=>{k.warning("[".concat(this._clientId,"] received message onTokenPrivilegeDidExpire, please get new token and join again")),this._gateway.leave(!0,ue.TOKEN_EXPIRE),this.safeEmit(rt.ON_TOKEN_PRIVILEGE_DID_EXPIRE),this._reset()})),this._gateway.signal.on(Ci.ON_STREAM_FALLBACK_UPDATE,(e=>{k.debug("[".concat(this._clientId,"] stream fallback peerId: ").concat(e.stream_id,", attr: ").concat(e.stream_type)),this.safeEmit(rt.STREAM_FALLBACK,e.stream_id,1===e.stream_type?"fallback":"recover")})),this._gateway.signal.on(Ci.ON_PUBLISH_STREAM,(e=>{this.uid===this._uid&&(this._p2pChannel.reportPublishEvent(!0,null,void 0,!1,JSON.stringify({proxy:e.proxy})),k.info("[".concat(this._clientId,"] on publish stream, ").concat(JSON.stringify(e))))})),this._gateway.signal.on(Ci.ENABLE_LOCAL_VIDEO,(e=>{this._handleSetStreamLocalEnable("video",e.uid,!0)})),this._gateway.signal.on(Ci.DISABLE_LOCAL_VIDEO,(e=>{this._handleSetStreamLocalEnable("video",e.uid,!1)})),this._gateway.signal.on(Ri.REQUEST_TIMEOUT,((e,t)=>{if(this._joinInfo)switch(e){case Ti.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===Pi.Audio})),a=e.some((e=>{let{stream_type:t}=e;return t!==Pi.Audio})),s=e.some((e=>{let{stream_type:t}=e;return t===Pi.Screen||t===Pi.ScreenLow}));"offer"===t.state&&M.publish(this._joinInfo.sid,{eventElapse:Ho.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:!1,ec:q.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===Pi.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!==Pi.Audio})))||void 0===n||null===(n=n.ssrcs[0])||void 0===n?void 0:n.ssrcId.toString():void 0})}break}case Ti.SUBSCRIBE:t&&M.subscribe(this._joinInfo.sid,{succ:!1,ec:q.TIMEOUT,audio:t.stream_type===Hi.AUDIO,video:t.stream_type===Hi.VIDEO,peerid:t.stream_id,subscribeRequestid:t.ssrcId,p2pid:this.store.p2pId,eventElapse:Ho.measureFromSubscribeStart(this.store.clientId,t.ssrcId),preSsrc:this._p2pChannel.isPreSubScribe(t.ssrcId)})}})),this._gateway.signal.on(Ci.ON_P2P_OK,(e=>{this.uid,this._uid})),this._gateway.signal.on(Ci.ON_PUBLISHED_USER_LIST,(e=>{if(null==e||!e.users)return;Z("BLOCK_LOCAL_CLIENT")&&(e.users=e.users.filter((e=>!$t(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 Xo(n.string_id||n.stream_id,n.stream_id),this._users.push(e),0===this.getListeners(rt.PUBLISHED_USER_LIST).length&&(k.debug("[".concat(this._clientId,"] user online"),n.stream_id),this.safeEmit(rt.USER_JOINED,e)));const o=Ui.Audio&n.stream_type,a=(Ui.Video|Ui.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(rt.PUBLISHED_USER_LIST).length&&(k.info("[".concat(this._clientId,"] remote user ").concat(e.uid," published audio")),this.safeEmit(rt.USER_PUBLISHED,e,"audio")),a&&!c&&0===this.getListeners(rt.PUBLISHED_USER_LIST).length&&(k.info("[".concat(this._clientId,"] remote user ").concat(e.uid," published video")),this.safeEmit(rt.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&&(k.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=>{k.error("[".concat(this._clientId,"] mass resubscribe error"),e.toString())}))),this.getListeners(rt.PUBLISHED_USER_LIST).length>0?Z("ENABLE_DATASTREAM_2")?this._pendingPublishedUsers=t:(k.info("[".concat(this._clientId,"] client emit user-list event, users: ").concat(t.map((e=>e.uid)).join(", "))),this.safeEmit(rt.PUBLISHED_USER_LIST,t)):k.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(Ci.ON_RTP_CAPABILITY_CHANGE,(e=>{const{video_codec:t}=e;this._p2pChannel instanceof Va&&this._p2pChannel.updateRemoteRTPCapabilities(t.map((e=>e.toLowerCase())).filter((e=>Object.keys(Ke).includes(e))))}))}_handleP2PEvents(){this._gateway.signal.on(Ci.ON_USER_OFFLINE,(()=>{this._p2pChannel.disconnectForReconnect()})),this._gateway.signal.on(on.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(on.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(Ri.P2P_CONNECTION,(async e=>{this.store.useP2P&&(await this._p2pChannel).p2pConnect(e)})),this._gateway.signal.on(on.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 k.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===Pi.Audio?Hi.AUDIO:Hi.VIDEO;await this._p2pChannel.unsubscribe(a,i),this._handleMuteStream(o,i,!0)})),t()}catch(e){i(e)}}})),this._gateway.signal.on(on.CONTROL,(async(e,t)=>{const{action:i}=e;switch(i){case an.MUTE_LOCAL_VIDEO:this._handleMuteStream(t,Hi.VIDEO,!0);break;case an.MUTE_LOCAL_AUDIO:this._handleMuteStream(t,Hi.AUDIO,!0);break;case an.UNMUTE_LOCAL_VIDEO:this._handleP2PAddAudioOrVideoStream("video",t),this._handleMuteStream(t,Hi.VIDEO,!1);break;case an.UNMUTE_LOCAL_AUDIO:this._handleP2PAddAudioOrVideoStream("audio",t),this._handleMuteStream(t,Hi.AUDIO,!1)}})),this._gateway.signal.on(on.RESTART_ICE,(async(e,t,i)=>{if(this.store.useP2P)try{const{direction:i,iceParameter:n}=e;if(i!==Ii.SEND_ONLY||n){t(await this._p2pChannel.restartICE(i,n))}else this._p2pChannel.handleDisconnect(i),t()}catch(e){i(e)}})),this._gateway.signal.on(on.CANDIDATE,(e=>{if(this.store.useP2P){const{candidate:t,direction:i}=e;this._p2pChannel.addRemoteCandidate(t,i)}})),this._p2pChannel.on(zi.RequestP2PRestartICE,(async(e,t,i)=>{try{const{direction:i}=e;t(await this._gateway.sendExtensionMessage(on.RESTART_ICE,e,i===Ii.SEND_ONLY))}catch(e){i(e)}})),this._p2pChannel.on(zi.LocalCandidate,(e=>{this._gateway.sendExtensionMessage(on.CANDIDATE,JSON.stringify(e),!0)})),this._p2pChannel.on(zi.RequestP2PMuteLocal,(async(e,t,i)=>{try{await this._gateway.sendExtensionMessage(on.CONTROL,e,!0),t()}catch(e){i(e)}})),this._p2pChannel.on(zi.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===q.DISCONNECT_P2P?t():i(e)}else t()})),this._p2pChannel.on(zi.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===q.DISCONNECT_P2P?t():i(e)}else t()})),this._p2pChannel.on(zi.StateChange,((e,t)=>{t===Ji.Connected&&this._p2pChannel.republish()}))}_handleP2PChannelEvents(){this._p2pChannel.on(zi.PeerConnectionStateChange,(e=>{const t=this._peerConnectionState;e!==t&&(this.safeEmit(rt.PEERCONNECTION_STATE_CHANGE,e,t),this._peerConnectionState=e)})),this._p2pChannel.on(zi.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===q.DISCONNECT_P2P?t():i(e)}else t()})),this._p2pChannel.on(zi.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===q.DISCONNECT_P2P?t():i(e)}else t()})),this._p2pChannel.on(zi.RequestRePublish,((e,t,i)=>{this.publish(e,!1).then(t).catch(i)})),this._p2pChannel.on(zi.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!==q.DISCONNECT_P2P)throw e}}))).then(t).catch(i)})),this._p2pChannel.on(zi.RequestReSubscribe,(async(e,t,i)=>{try{for(const{user:t,kind:i}of e)i===Hi.VIDEO?await this.subscribe(t,"video"):await this.subscribe(t,"audio");t()}catch(e){i(e)}})),this._p2pChannel.on(zi.RequestUpload,((e,t)=>{this._gateway.upload(e,t)})),this._p2pChannel.on(zi.RequestUploadStats,(e=>{this._gateway.uploadWRTCStats(e)})),this._p2pChannel.on(zi.MediaReconnectStart,(e=>{this.safeEmit(rt.MEDIA_RECONNECT_START,e)})),this._p2pChannel.on(zi.MediaReconnectEnd,(e=>{this.safeEmit(rt.MEDIA_RECONNECT_END,e)})),this._p2pChannel.on(zi.NeedSignalRTT,(e=>{e(this._gateway.getSignalRTT())})),this._p2pChannel.on(zi.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(zi.RequestReconnect,(async()=>{this._gateway.reconnect()})),this._p2pChannel.on(zi.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=Bn(o,a);await this._p2pChannel.connect(s),await this._p2pChannel.republish(),await this._p2pChannel.reSubscribe()})),this._p2pChannel.on(zi.RequestUnpublishForReconnectPC,(async(e,t,i)=>{this._joinInfo&&void 0!==this._uid?(await this._gateway.unpublish(e,this._uid),t()):i()})),this._p2pChannel.on(zi.P2PLost,(()=>{this.safeEmit(rt.P2P_LOST,this.store.uid)})),this._p2pChannel.on(zi.UpdateVideoEncoder,(e=>{e._encoderConfig&&this._gateway.setVideoProfile(e._encoderConfig)})),this._p2pChannel.on(zi.ConnectionTypeChange,(e=>{this.safeEmit(rt.IS_USING_CLOUD_PROXY,e)})),this._p2pChannel.on(zi.RequestLowStreamParameter,(e=>{e(this._lowStreamParameter||{width:160,height:120,framerate:15,bitrate:50})})),this._p2pChannel.on(zi.QueryClientConnectionState,(e=>{e(this.connectionState)})),this._p2pChannel.on(zi.AudioMetadata,(e=>{this.safeEmit(rt.AUDIO_METADATA,e)}))}getKeyMetrics(){return this.store.keyMetrics}async enableContentInspect(e){if(!this._joinInfo||"CONNECTED"!==this.connectionState)throw new U(q.INVALID_OPERATION,"[".concat(this._clientId,"] can not create content inspect, please join channel first"));if(this._inspect)throw new U(q.INVALID_OPERATION,"[".concat(this._clientId,"] Inspect content service already in connecting/connected state"));try{const i=(t={config:e},no("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},xe)}catch(e){throw Array.isArray(e)?e[0]:e}var t}handleVideoInspectEvents(e){e.on(Zi.CONNECTION_STATE_CHANGE,((t,i)=>{if(this.safeEmit(rt.CONTENT_INSPECT_CONNECTION_STATE_CHANGE,t,i),i===Qi.CONNECTED){if("CONNECTED"!==this.connectionState)return void this.safeEmit(rt.CONTENT_INSPECT_ERROR,new U(q.OPERATION_ABORTED,"Content inspect was cancelled because it left the channel"));e.inspectImage()}})),e.on(Zi.INSPECT_RESULT,((e,t)=>{var i;if((null==t?void 0:t.code)===q.INVALID_OPERATION&&"DISCONNECTED"===this.connectionState)return k.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(rt.CONTENT_INSPECT_RESULT,e,t)})),e.on(Zi.CLIENT_LOCAL_VIDEO_TRACK,(e=>{e(this.localTracks.filter((e=>"video"===e.trackMediaType))[0])}))}async disableContentInspect(){if(!this._inspect)throw new U(q.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(yt(e,"enabled"),e){if(!t)throw new U(q.INVALID_PARAMS,"config is required");if(function(e){if(Et(e.interval,"interval",1e3,1/0),e&&e.extraInfo&&e.extraInfo.length>1024)throw new U(V.INVALID_PARAMS,"config.extraInfo length cannot exceed 1024 bytes");if(e&&e.vendor&&e.vendor.length>1024)throw new U(V.INVALID_PARAMS,"config.vendor length cannot exceed 1024 bytes")}(t),!this._joinInfo)throw new U(q.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},no("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},xe)}}catch(e){throw Array.isArray(e)?e[0]:e}}else{var i;if(!this._moderation)throw new U(q.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(nn.CONNECTION_STATE_CHANGE,((t,i)=>{if(this.safeEmit(rt.IMAGE_MODERATION_CONNECTION_STATE_CHANGE,t,i),t===tn.CONNECTED){if("CONNECTED"!==this.connectionState)throw this.setImageModeration(!1),new U(q.OPERATION_ABORTED,"Image moderation was cancelled because it left the channel");e.inspectImage()}})),e.on(nn.CLIENT_LOCAL_VIDEO_TRACK,(e=>{e(this.localTracks.filter((e=>"video"===e.trackMediaType))[0])}))}setP2PTransport(e){if(Ut(e),"p2p"!==this.mode)throw new U(q.INVALID_OPERATION,"only p2p mode can set p2pTransport");this.store.p2pTransport=e,k.info("[".concat(this._clientId,"] set client p2pTransport to ").concat(e))}getJoinChannelServiceRecords(){return k.debug("getJoinChannelServiceRecords"),this.store.joinChannelServiceRecords}async setPublishAudioFilterEnabled(e){yt(e,"enabled"),Pe("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",[fs],Object.getOwnPropertyDescriptor(rr.prototype,"leave"),rr.prototype),ii(rr.prototype,"publish",[Cs],Object.getOwnPropertyDescriptor(rr.prototype,"publish"),rr.prototype),ii(rr.prototype,"unpublish",[Is],Object.getOwnPropertyDescriptor(rr.prototype,"unpublish"),rr.prototype),ii(rr.prototype,"subscribe",[As],Object.getOwnPropertyDescriptor(rr.prototype,"subscribe"),rr.prototype),ii(rr.prototype,"presubscribe",[gs],Object.getOwnPropertyDescriptor(rr.prototype,"presubscribe"),rr.prototype),ii(rr.prototype,"massSubscribe",[vs],Object.getOwnPropertyDescriptor(rr.prototype,"massSubscribe"),rr.prototype),ii(rr.prototype,"unsubscribe",[ys],Object.getOwnPropertyDescriptor(rr.prototype,"unsubscribe"),rr.prototype),ii(rr.prototype,"massUnsubscribe",[Ns],Object.getOwnPropertyDescriptor(rr.prototype,"massUnsubscribe"),rr.prototype),ii(rr.prototype,"setLowStreamParameter",[ws],Object.getOwnPropertyDescriptor(rr.prototype,"setLowStreamParameter"),rr.prototype),ii(rr.prototype,"enableDualStream",[Os],Object.getOwnPropertyDescriptor(rr.prototype,"enableDualStream"),rr.prototype),ii(rr.prototype,"disableDualStream",[bs],Object.getOwnPropertyDescriptor(rr.prototype,"disableDualStream"),rr.prototype),ii(rr.prototype,"setClientRole",[Ds],Object.getOwnPropertyDescriptor(rr.prototype,"setClientRole"),rr.prototype),ii(rr.prototype,"_setClientRoleOptions",[Ps],Object.getOwnPropertyDescriptor(rr.prototype,"_setClientRoleOptions"),rr.prototype),ii(rr.prototype,"setProxyServer",[Ls],Object.getOwnPropertyDescriptor(rr.prototype,"setProxyServer"),rr.prototype),ii(rr.prototype,"setTurnServer",[ks],Object.getOwnPropertyDescriptor(rr.prototype,"setTurnServer"),rr.prototype),ii(rr.prototype,"setLicense",[Us],Object.getOwnPropertyDescriptor(rr.prototype,"setLicense"),rr.prototype),ii(rr.prototype,"startProxyServer",[Ms],Object.getOwnPropertyDescriptor(rr.prototype,"startProxyServer"),rr.prototype),ii(rr.prototype,"stopProxyServer",[Vs],Object.getOwnPropertyDescriptor(rr.prototype,"stopProxyServer"),rr.prototype),ii(rr.prototype,"setLocalAccessPointsV2",[xs],Object.getOwnPropertyDescriptor(rr.prototype,"setLocalAccessPointsV2"),rr.prototype),ii(rr.prototype,"setLocalAccessPoints",[Bs],Object.getOwnPropertyDescriptor(rr.prototype,"setLocalAccessPoints"),rr.prototype),ii(rr.prototype,"setRemoteDefaultVideoStreamType",[Fs],Object.getOwnPropertyDescriptor(rr.prototype,"setRemoteDefaultVideoStreamType"),rr.prototype),ii(rr.prototype,"setRemoteVideoStreamType",[js],Object.getOwnPropertyDescriptor(rr.prototype,"setRemoteVideoStreamType"),rr.prototype),ii(rr.prototype,"setStreamFallbackOption",[Gs],Object.getOwnPropertyDescriptor(rr.prototype,"setStreamFallbackOption"),rr.prototype),ii(rr.prototype,"setEncryptionConfig",[Ws],Object.getOwnPropertyDescriptor(rr.prototype,"setEncryptionConfig"),rr.prototype),ii(rr.prototype,"renewToken",[Hs],Object.getOwnPropertyDescriptor(rr.prototype,"renewToken"),rr.prototype),ii(rr.prototype,"enableAudioVolumeIndicator",[Ks],Object.getOwnPropertyDescriptor(rr.prototype,"enableAudioVolumeIndicator"),rr.prototype),ii(rr.prototype,"startLiveStreaming",[Ys],Object.getOwnPropertyDescriptor(rr.prototype,"startLiveStreaming"),rr.prototype),ii(rr.prototype,"setLiveTranscoding",[qs],Object.getOwnPropertyDescriptor(rr.prototype,"setLiveTranscoding"),rr.prototype),ii(rr.prototype,"stopLiveStreaming",[Xs],Object.getOwnPropertyDescriptor(rr.prototype,"stopLiveStreaming"),rr.prototype),ii(rr.prototype,"startChannelMediaRelay",[Js],Object.getOwnPropertyDescriptor(rr.prototype,"startChannelMediaRelay"),rr.prototype),ii(rr.prototype,"updateChannelMediaRelay",[zs],Object.getOwnPropertyDescriptor(rr.prototype,"updateChannelMediaRelay"),rr.prototype),ii(rr.prototype,"stopChannelMediaRelay",[Qs],Object.getOwnPropertyDescriptor(rr.prototype,"stopChannelMediaRelay"),rr.prototype),ii(rr.prototype,"sendCustomReportMessage",[Zs],Object.getOwnPropertyDescriptor(rr.prototype,"sendCustomReportMessage"),rr.prototype),ii(rr.prototype,"pickSVCLayer",[$s],Object.getOwnPropertyDescriptor(rr.prototype,"pickSVCLayer"),rr.prototype),ii(rr.prototype,"setRTMConfig",[er],Object.getOwnPropertyDescriptor(rr.prototype,"setRTMConfig"),rr.prototype),ii(rr.prototype,"enableContentInspect",[tr],Object.getOwnPropertyDescriptor(rr.prototype,"enableContentInspect"),rr.prototype),ii(rr.prototype,"disableContentInspect",[ir],Object.getOwnPropertyDescriptor(rr.prototype,"disableContentInspect"),rr.prototype),ii(rr.prototype,"setImageModeration",[nr],Object.getOwnPropertyDescriptor(rr.prototype,"setImageModeration"),rr.prototype),ii(rr.prototype,"setP2PTransport",[or],Object.getOwnPropertyDescriptor(rr.prototype,"setP2PTransport"),rr.prototype),ii(rr.prototype,"getJoinChannelServiceRecords",[ar],Object.getOwnPropertyDescriptor(rr.prototype,"getJoinChannelServiceRecords"),rr.prototype),ii(rr.prototype,"setPublishAudioFilterEnabled",[sr],Object.getOwnPropertyDescriptor(rr.prototype,"setPublishAudioFilterEnabled"),rr.prototype),rr);function dr(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{codec:"vp8",audioCodec:"opus",mode:"rtc"};const t=pe(5,"client-"),i=M.reportApiInvoke(null,{id:t,name:Ue.CREATE_CLIENT,options:[e],tag:Me.TRACER});try{Mt(e)}catch(e){throw i.onError(e),e}return(Je(16,0,!0)||Qe(16,0,!0))&&("vp9"===e.codec&&(e.codec="vp8",k.debug("browser not support vp9, force use vp8")),Pe("UNSUPPORTED_VIDEO_CODEC",["vp9"])),void 0===e.audioCodec&&(e.audioCodec="opus"),i.onSuccess(),new cr(di(di({forceWaitGatewayResponse:!0},e),{},{role:["rtc","p2p"].includes(e.mode)?"host":e.role||"audience"}),t)}async function lr(){let e={audio:[],video:[]};try{let t=new RTCPeerConnection;const i=await async function(e){let t;return n().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 U(q.CREATE_OFFER_FAILED,e.toString&&e.toString()).print()}return e}function hr(){const e=M.reportApiInvoke(null,{name:Ue.CHECK_SYSTEM_REQUIREMENTS,options:[],tag:Me.TRACER});let t=!1;try{const e=window.RTCPeerConnection,i=navigator.mediaDevices&&navigator.mediaDevices.getUserMedia,n=window.WebSocket;t=!!(e&&i&&n),t&&at()&&Ne(75)&&(new e).close()}catch(e){return k.error("check system requirement failed: ",e),!1}let i=!1;const n=Ie();n.name===Ae.CHROME&&Number(n.version)>=58&&(!Vt()||xt())&&(i=!0),(n.name===Ae.FIREFOX&&Number(n.version)>=56||n.name===Ae.OPERA&&Number(n.version)>=45||n.name===Ae.SAFARI&&Number(n.version)>=11||"WebKit"===n.name&&(Bt()||Ft())&&n.osVersion&&Number(n.osVersion.split(".")[0])>=11||jt()||Gt())&&(i=!0),k.debug("checkSystemRequirements, api:",t,"browser",i);const o=t&&i;return e.onSuccess(o),o}class ur{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,ur.count+=1,this.id=ur.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 U(q.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 U(q.LOCAL_AEC_ERROR,e.toString()).print()}if(!t){throw new U(q.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(){k.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 _r,pr;ur.count=0;const Er=window.AudioContext||window.webkitAudioContext;const Sr=new(_r=F({report:M}),ii((pr=class{constructor(){this.units=[],this.context=void 0}processExternalMediaAEC(e){if(!this._doesEnvironmentNeedAEC())return k.debug("the system does not need to process local aec"),-1;this.context||(this.context=new Er);let t=this.units.find((t=>t&&t.getElement()===e));return t||(t=new ur(e,this.context),this.units.push(t)),t.startEchoCancellation(),k.debug("start processing local audio echo cancellation, id is",t.id),t.id}_doesEnvironmentNeedAEC(){return Ie().name!==Ae.SAFARI}}).prototype,"processExternalMediaAEC",[_r],Object.getOwnPropertyDescriptor(pr.prototype,"processExternalMediaAEC"),pr.prototype),pr);const mr=window||document;function Rr(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(!mr)return;const i=Dr._cspEventHandlerPointer;if(i&&t)return void console.error(i,t);const n=e=>{if(!(e&&e.blockedURI&&(Dr.onSecurityPolicyViolation||Dr.getListeners(en.SECURITY_POLICY_VIOLATION).length>0)))return;const t=e.blockedURI;Z("CSP_DETECTED_HOSTNAME_LIST").some((e=>t.includes(e)))&&(Dr.onSecurityPolicyViolation&&"function"==typeof Dr.onSecurityPolicyViolation&&Dr.onSecurityPolicyViolation(e),Dr.getListeners(en.SECURITY_POLICY_VIOLATION).length>0&&Dr.safeEmit(en.SECURITY_POLICY_VIOLATION,e))};i&&mr.removeEventListener("securitypolicyviolation",i),(t||e&&"function"==typeof e||Dr.getListeners(en.SECURITY_POLICY_VIOLATION).length>0)&&mr.addEventListener("securitypolicyviolation",n),Dr._cspEventHandlerPointer=n}function Tr(e){return O.enumerateDevices(!0,!0,e)}function fr(e){return O.getRecordingDevices(e)}function Cr(e){return O.getCamerasDevices(e)}function Ir(e){return O.getSpeakers(e)}function Ar(){return new Yo}function gr(e){if(k.debug("setAppType: ".concat(e)),!(Number.isInteger(e)&&e>=0))throw k.debug("Invalid appType"),new U(q.INVALID_PARAMS,"invalid app type",e);Pe("APP_TYPE",Math.floor(e))}function vr(e){k.setLogLevel(e)}function yr(){Z("USE_NEW_LOG")?Pe("UPLOAD_LOG",!0):k.enableLogUpload()}function Nr(){Z("USE_NEW_LOG")?Pe("UPLOAD_LOG",!1):k.disableLogUpload()}function wr(e){Sr.processExternalMediaAEC(e)}function Or(e){e.forEach((e=>{const t=e;t.__registered__=!0,t.logger.hookLog=k.extLog,t.reporter.hookApiInvoke=M.extApiInvoke,t.parameters&&Object.keys(t.parameters).forEach((e=>{t.parameters[e]=Z(e)}))}))}function br(){R.autoResumeAfterInterruption(!0)}Be(),Pe("PROCESS_ID",Wt()),function(){let e;try{e=window.localStorage.getItem("websdk_ng_global_parameter")}catch(e){return void k.error("Error loading sdk config",e.message)}if(e)try{const t=JSON.parse(window.atob(e)),i=Date.now();k.debug("Loading global parameters from cache",t),Object.keys(t).forEach((e=>{if(Object.prototype.hasOwnProperty.call(G,e)){const{value:n,expires:o}=t[e];if(o&&o<=i)return;W[e]=n,G[e]=n}}))}catch(t){k.error("Error loading mutableParamsCache: ".concat(e),t.message)}}(),Array.isArray(W.AREAS)&&W.AREAS.length>0&&fo(W.AREAS,!0);const Dr=function(e){const t=new Q,i=e,n={getListeners:t.getListeners.bind(t),on:(e,i)=>(function(e,t){e===en.SECURITY_POLICY_VIOLATION&&Rr(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 di(di({},i),n)}({});function Pr(e){w.onAudioAutoplayFailed=e}function Lr(e){w.onAutoplayFailed=e}function kr(e){Dr.onSecurityPolicyViolation=e}function Ur(e){Dr.onCameraChanged=e}function Mr(e){Dr.onMicrophoneChanged=e}function Vr(e){Dr.onAudioContextStateChanged=e}Object.defineProperties(Dr,{onAudioAutoplayFailed:{get:()=>w.onAudioAutoplayFailed,set:Pr},onAutoplayFailed:{get:()=>w.onAutoplayFailed,set:Lr},_onSecurityPolicyViolation:{value:void 0,writable:!0},_cspEventHandlerPointer:{value:void 0,writable:!0},onSecurityPolicyViolation:{get:()=>Dr._onSecurityPolicyViolation,set(e){Dr._onSecurityPolicyViolation=e,Rr(e)}},__CLIENT_LIST__:{get:()=>Z("SHOW_GLOBAL_CLIENT_LIST")?Qt:[]}}),Dr.use=e=>(function(e){(!(arguments.length>1&&void 0!==arguments[1])||arguments[1])&&k.debug("install service ".concat(e.name)),io[e.name]=e}(e),Dr),O.on(b.CAMERA_DEVICE_CHANGED,(e=>{k.info("camera device changed",JSON.stringify(e)),Dr.onCameraChanged&&Dr.onCameraChanged(e),Dr.safeEmit(en.CAMERA_CHANGED,e)})),O.on(b.RECORDING_DEVICE_CHANGED,(e=>{k.info("microphone device changed",JSON.stringify(e)),Dr.onMicrophoneChanged&&Dr.onMicrophoneChanged(e),Dr.safeEmit(en.MICROPHONE_CHANGED,e)})),O.on(b.PLAYOUT_DEVICE_CHANGED,(e=>{k.debug("playout device changed",JSON.stringify(e)),Dr.onPlaybackDeviceChanged&&Dr.onPlaybackDeviceChanged(e),Dr.safeEmit(en.PLAYBACK_DEVICE_CHANGED,e)})),R.onAutoplayFailed=()=>{k.info("detect audio element autoplay failed"),w.onAudioAutoplayFailed&&w.onAudioAutoplayFailed()},D.on("autoplay-failed",(()=>{k.info("detect webaudio autoplay failed"),w.onAudioAutoplayFailed&&w.onAudioAutoplayFailed(),Dr.safeEmit(en.AUTOPLAY_FAILED)})),D.on(P.STATE_CHANGE,((e,t)=>{k.info("audio context state changed: ".concat(t," => ").concat(e)),Dr.onAudioContextStateChanged&&Dr.onAudioContextStateChanged(e,t),Dr.safeEmit(en.AUDIO_CONTEXT_STATE_CHANGED,e,t)})),window&&(window.__ARTC__={ESM_BUNDLER:true,ESM:false,UMD:false,DEV:false,AgoraRTC:Dr,__TRACK_LIST__:L}),oe.on(ae.NETWORK_STATE_CHANGE,((e,t)=>{k.info("[network-indicator] network state changed, ".concat(t," => ").concat(e))}));const xr=(e,t,i)=>{k.debug("setParameter key:".concat(e,", value:").concat(JSON.stringify(t))),Pe(e,t,i)};export{Mi as AREAS,Dr as AgoraRTC,Di as ChannelMediaRelayError,Oi as ChannelMediaRelayEvent,bi as ChannelMediaRelayState,Xt as DEV,Yt as ESM,Kt as ESM_BUNDLER,qt as UMD,Qt as __CLIENT_LIST__,Xa as checkAudioTrackIsActive,hr as checkSystemRequirements,qa as checkVideoTrackIsActive,Ar as createChannelMediaRelayConfiguration,dr as createClient,Nr as disableLogUpload,yr as enableLogUpload,Cr as getCameras,Tr as getDevices,fr as getMicrophones,Ir as getPlaybackDevices,lr as getSupportedCodec,Pr as onAudioAutoplayFailed,Vr as onAudioContextStateChanged,Lr as onAutoplayFailed,Ur as onCameraChanged,Mr as onMicrophoneChanged,kr as onSecurityPolicyViolation,ss as preload,wr as processExternalMediaAEC,Or as registerExtensions,br as resumeAudioContext,gr as setAppType,fo as setArea,vr as setLogLevel,xr as setParameter};