aliyun-rtc-sdk 7.2.9 → 7.2.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
- (function(z,J){typeof exports=="object"&&typeof module!="undefined"?J(exports,require("aliyun-rts-sdk"),require("eventemitter3")):typeof define=="function"&&define.amd?define(["exports","aliyun-rts-sdk","eventemitter3"],J):J((z=typeof globalThis!="undefined"?globalThis:z||self).AliRtcEngine={},z.AliyunRts,z.EventEmitter)})(this,function(z,J,oe){var re,bt,ui,se,Yt,Zt,rt,F,Zn;"use strict";var at=(a=>(a.EnableNonOnePcDefaultJoinMode="h5_enable_non_one_pc_default_join_mode",a))(at||{});function Vt(){}let pi=0,mi=!1;const di=class di{static getInstance(){var r;return di.instance||(di.instance=new AudioContext),(r=di.instance.resume())==null||r.then(Vt,Vt).catch(Vt),di.instance}};m(di,"instance");let yt=di;const nt=()=>{var r;const a=yt.getInstance();a.state!=="running"&&a.state!=="closed"&&((r=a.resume())==null||r.then(Vt,Vt).catch(Vt)),window.removeEventListener("mousedown",nt),window.removeEventListener("touchstart",nt)};var Rt=(a=>(a.prod="rs.rtn.aliyuncs.com",a.pre="prs.rtn.aliyuncs.com",a))(Rt||{}),It=(a=>(a.pre="pre",a.prod="prod",a))(It||{}),Ut=(a=>(a.AliRtcSdkCommunication="communication",a.AliRtcSdkInteractiveLive="interactive_live",a.AliRtcSdkInteractiveWithLowLatencyLive="cdn_live",a))(Ut||{}),zt=(a=>(a.AliRtcSdkInteractive="interactive",a.AliRtcSdkLive="live",a))(zt||{}),kt=(a=>(a[a.AliEngineLocalDeviceTypeUnknown=0]="AliEngineLocalDeviceTypeUnknown",a[a.AliEngineLocalDeviceTypeMic=1]="AliEngineLocalDeviceTypeMic",a[a.AliEngineLocalDeviceTypeSpeaker=2]="AliEngineLocalDeviceTypeSpeaker",a[a.AliEngineLocalDeviceTypeAudioDevice=3]="AliEngineLocalDeviceTypeAudioDevice",a[a.AliEngineLocalDeviceTypeCamera=4]="AliEngineLocalDeviceTypeCamera",a[a.AliEngineLocalDeviceTypeDisplay=5]="AliEngineLocalDeviceTypeDisplay",a[a.AliEngineLocalDeviceTypeVideoDevice=6]="AliEngineLocalDeviceTypeVideoDevice",a))(kt||{}),je=(a=>(a[a.AliEngineLocalDeviceExceptionTypeUnknown=0]="AliEngineLocalDeviceExceptionTypeUnknown",a[a.AliEngineLocalDeviceExceptionTypeMicOpenFail=1]="AliEngineLocalDeviceExceptionTypeMicOpenFail",a[a.AliEngineLocalDeviceExceptionTypeMicInterrupt=2]="AliEngineLocalDeviceExceptionTypeMicInterrupt",a[a.AliEngineLocalDeviceExceptionTypeMicAuthFail=3]="AliEngineLocalDeviceExceptionTypeMicAuthFail",a[a.AliEngineLocalDeviceExceptionTypeMicNotAvailable=4]="AliEngineLocalDeviceExceptionTypeMicNotAvailable",a[a.AliEngineLocalDeviceExceptionTypeSpeakerOpenFail=5]="AliEngineLocalDeviceExceptionTypeSpeakerOpenFail",a[a.AliEngineLocalDeviceExceptionTypeSpeakerInterrupt=6]="AliEngineLocalDeviceExceptionTypeSpeakerInterrupt",a[a.AliEngineLocalDeviceExceptionTypeSpeakerNotAvailable=7]="AliEngineLocalDeviceExceptionTypeSpeakerNotAvailable",a[a.AliEngineLocalDeviceExceptionTypeAudioDeviceException=8]="AliEngineLocalDeviceExceptionTypeAudioDeviceException",a[a.AliEngineLocalDeviceExceptionTypeCameraOpenFail=9]="AliEngineLocalDeviceExceptionTypeCameraOpenFail",a[a.AliEngineLocalDeviceExceptionTypeCameraInterrupt=10]="AliEngineLocalDeviceExceptionTypeCameraInterrupt",a[a.AliEngineLocalDeviceExceptionTypeCameraAuthFail=11]="AliEngineLocalDeviceExceptionTypeCameraAuthFail",a[a.AliEngineLocalDeviceExceptionTypeDisplayException=12]="AliEngineLocalDeviceExceptionTypeDisplayException",a[a.AliEngineLocalDeviceExceptionTypeVideoDeviceException=13]="AliEngineLocalDeviceExceptionTypeVideoDeviceException",a))(je||{}),ae=(a=>(a[a.AliRtcConnectionStatusInit=0]="AliRtcConnectionStatusInit",a[a.AliRtcConnectionStatusDisconnected=1]="AliRtcConnectionStatusDisconnected",a[a.AliRtcConnectionStatusConnecting=2]="AliRtcConnectionStatusConnecting",a[a.AliRtcConnectionStatusConnected=3]="AliRtcConnectionStatusConnected",a[a.AliRtcConnectionStatusReconnecting=4]="AliRtcConnectionStatusReconnecting",a[a.AliRtcConnectionStatusFailed=5]="AliRtcConnectionStatusFailed",a))(ae||{}),Pt=(a=>(a[a.AliRtcConnectionChangedDummyReason=0]="AliRtcConnectionChangedDummyReason",a[a.AliRtcConnectionMediaPathChanged=1]="AliRtcConnectionMediaPathChanged",a[a.AliRtcConnectionSignalingHeartbeatTimeout=2]="AliRtcConnectionSignalingHeartbeatTimeout",a[a.AliRtcConnectionSignalingHeartbeatAlive=3]="AliRtcConnectionSignalingHeartbeatAlive",a[a.AliRtcConnectionSignalingHttpDnsResolved=4]="AliRtcConnectionSignalingHttpDnsResolved",a[a.AliRtcConnectionSignalingHttpDnsFailure=5]="AliRtcConnectionSignalingHttpDnsFailure",a[a.AliRtcConnectionSignalingGslbFailure=6]="AliRtcConnectionSignalingGslbFailure",a[a.AliRtcConnectionSignalingGslbSuccess=7]="AliRtcConnectionSignalingGslbSuccess",a[a.AliRtcConnectionSignalingJoinRoomFailure=8]="AliRtcConnectionSignalingJoinRoomFailure",a[a.AliRtcConnectionSignalingJoinRoomSuccess=9]="AliRtcConnectionSignalingJoinRoomSuccess",a[a.AliRtcConnectionSignalingLeaveRoom=10]="AliRtcConnectionSignalingLeaveRoom",a[a.AliRtcConnectionSignalingConnecting=11]="AliRtcConnectionSignalingConnecting",a[a.AliRtcConnectionChangedNetworkInterrupted=12]="AliRtcConnectionChangedNetworkInterrupted",a))(Pt||{}),ns=(a=>(a[a.AliRtcUserOfflineQuit=0]="AliRtcUserOfflineQuit",a[a.AliRtcUserOfflineDropped=1]="AliRtcUserOfflineDropped",a[a.AliRtcUserOfflineBecomeAudience=2]="AliRtcUserOfflineBecomeAudience",a))(ns||{}),ti=(a=>(a[a.AliRtcAudioTrackNo=0]="AliRtcAudioTrackNo",a[a.AliRtcAudioTrackMic=1]="AliRtcAudioTrackMic",a[a.AliRtcAudioTrackDual=2]="AliRtcAudioTrackDual",a))(ti||{}),ue=(a=>(a[a.AliRtcVideoTrackNo=0]="AliRtcVideoTrackNo",a[a.AliRtcVideoTrackCamera=1]="AliRtcVideoTrackCamera",a[a.AliRtcVideoTrackScreen=2]="AliRtcVideoTrackScreen",a[a.AliRtcVideoTrackBoth=3]="AliRtcVideoTrackBoth",a))(ue||{}),ee=(a=>(a[a.AliRtcStatePublishIdle=0]="AliRtcStatePublishIdle",a[a.AliRtcStateNoPublish=1]="AliRtcStateNoPublish",a[a.AliRtcStatePublishing=2]="AliRtcStatePublishing",a[a.AliRtcStatePublished=3]="AliRtcStatePublished",a[a.AliRtcStateReconnecting=4]="AliRtcStateReconnecting",a))(ee||{}),ce=(a=>(a[a.AliRtcStateSubscribeIdle=0]="AliRtcStateSubscribeIdle",a[a.AliRtcStateNoSubscribe=1]="AliRtcStateNoSubscribe",a[a.AliRtcStateSubscribing=2]="AliRtcStateSubscribing",a[a.AliRtcStateSubscribed=3]="AliRtcStateSubscribed",a[a.AliRtcStateReconnecting=4]="AliRtcStateReconnecting",a))(ce||{}),Ge=(a=>(a[a.AliRtcVideoStreamTypeNone=0]="AliRtcVideoStreamTypeNone",a[a.AliRtcVideoStreamTypeHigh=1]="AliRtcVideoStreamTypeHigh",a[a.AliRtcVideoStreamTypeLow=2]="AliRtcVideoStreamTypeLow",a))(Ge||{}),Ai=(a=>(a[a.CAMERA_INVALID=-1]="CAMERA_INVALID",a[a.CAMERA_REAR=0]="CAMERA_REAR",a[a.CAMERA_FRONT=1]="CAMERA_FRONT",a))(Ai||{}),tt=(a=>(a[a.AliRtcNetworkExcellent=0]="AliRtcNetworkExcellent",a[a.AliRtcNetworkGood=1]="AliRtcNetworkGood",a[a.AliRtcNetworkPoor=2]="AliRtcNetworkPoor",a[a.AliRtcNetworkBad=3]="AliRtcNetworkBad",a[a.AliRtcNetworkVeryBad=4]="AliRtcNetworkVeryBad",a[a.AliRtcNetworkDisconnected=5]="AliRtcNetworkDisconnected",a[a.AliRtcNetworkUnknown=6]="AliRtcNetworkUnknown",a))(tt||{}),Me=(a=>(a.PullStreamStats="remoteStat",a.RtsSubscribeExceeds="rtsSubscribeExceeds",a.UserJoined="userJoined",a.UserLeft="userLeft",a.Bye="bye",a.MuteAudio="muteAudio",a.UnmuteAudio="unmuteAudio",a.MuteVideo="muteVideo",a.UnmuteVideo="unmuteVideo",a.MuteScreen="muteScreen",a.UnmuteScreen="unmuteScreen",a.Error="error",a))(Me||{}),ot=(a=>(a.Local="local-device-status-change",a.Remote="remote-device-status-change",a))(ot||{}),D=(a=>(a.Audio="sophon_audio",a.VideoLarge="sophon_video_camera_large",a.VideoSmall="sophon_video_camera_small",a.Screen="sophon_video_screen_share",a.Data="sophon_data",a))(D||{}),os=(a=>(a.Audio="rts audio",a.VideoLarge="rts video",a))(os||{}),Bt=(a=>(a.Add="add",a.Delete="delete",a.Replace="replace",a.Stop="stop",a.UnPublish="unpublish",a))(Bt||{}),wi=(a=>(a[a.Camera=0]="Camera",a[a.Screen=1]="Screen",a[a.Image=2]="Image",a))(wi||{}),Hi=(a=>(a[a.Microphone=0]="Microphone",a[a.Screen=1]="Screen",a[a.Mixed=2]="Mixed",a))(Hi||{}),ge=(a=>(a.InRoom="inRoom",a.Join="join",a.Publish="publish",a.User="user",a.Resume="resume",a.Retry="retry",a.Reconnect="reconnect",a))(ge||{}),Dt=(a=>(a[a.MANUAL=0]="MANUAL",a[a.JOIN_CHANNEL=1]="JOIN_CHANNEL",a[a.ROLE_CHANGE=2]="ROLE_CHANGE",a[a.RECONNECT=3]="RECONNECT",a))(Dt||{}),B=(a=>(a[a.ERR_JOIN_ALREADY_JOINED=16843521]="ERR_JOIN_ALREADY_JOINED",a[a.ERR_JOIN_BAD_APPID=33620481]="ERR_JOIN_BAD_APPID",a[a.ERR_JOIN_INVALID_APPID=33620482]="ERR_JOIN_INVALID_APPID",a[a.ERR_JOIN_BAD_CHANNEL=33620484]="ERR_JOIN_BAD_CHANNEL",a[a.ERR_JOIN_INVALID_CHANNEL=33620483]="ERR_JOIN_INVALID_CHANNEL",a[a.ERR_JOIN_BAD_TOKEN=33620485]="ERR_JOIN_BAD_TOKEN",a[a.ERR_JOIN_TIMEOUT=16908804]="ERR_JOIN_TIMEOUT",a[a.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD=16974081]="ERR_JOIN_ERR_JOIN_BAD_PARAMBAD",a[a.ERR_JOIN_CHANNEL_FAILED=16974338]="ERR_JOIN_CHANNEL_FAILED",a[a.ERR_LOG_ALREADY_INIT=16974085]="ERR_LOG_ALREADY_INIT",a[a.ERR_LOG_ROOT_PATH_ERROR=16974086]="ERR_LOG_ROOT_PATH_ERROR",a[a.ERR_MIC_OPEN_FAIL=17040388]="ERR_MIC_OPEN_FAIL",a[a.ERR_SPEAKER_OPEN_FAIL=17040389]="ERR_SPEAKER_OPEN_FAIL",a[a.ERR_MIC_INTERRUPT=17040390]="ERR_MIC_INTERRUPT",a[a.ERR_SPEAKER_INTERRUPT=17040391]="ERR_SPEAKER_INTERRUPT",a[a.ERR_MIC_AUTH_FAIL=17040392]="ERR_MIC_AUTH_FAIL",a[a.ERR_MIC_NOT_AVAILABLE=17040393]="ERR_MIC_NOT_AVAILABLE",a[a.ERR_SPEAKER_NOT_AVAILABLE=17040400]="ERR_SPEAKER_NOT_AVAILABLE",a[a.ERR_CAMERA_OPEN_FAIL=17039620]="ERR_CAMERA_OPEN_FAIL",a[a.ERR_CAMERA_AUTH_FAIL=17039621]="ERR_CAMERA_AUTH_FAIL",a[a.ERR_CAMERA_INTERRUPT=17039622]="ERR_CAMERA_INTERRUPT",a[a.ERR_CAMERA_NOT_AVAILABLE=17039623]="ERR_CAMERA_NOT_AVAILABLE",a[a.ERR_VIDEO_DISPLAY_OPEN_FAIL=17039873]="ERR_VIDEO_DISPLAY_OPEN_FAIL",a[a.ERR_VIDEO_DISPLAY_INTERRUPT=1064992]="ERR_VIDEO_DISPLAY_INTERRUPT",a[a.ERR_ICE_CONNECTION_CONNECT_FAIL=17105409]="ERR_ICE_CONNECTION_CONNECT_FAIL",a[a.ERR_ICE_CONNECTION_RECONNECT_FAI=17105410]="ERR_ICE_CONNECTION_RECONNECT_FAI",a[a.ERR_ICE_CONNECTION_MOBILITY_FAIL=17105411]="ERR_ICE_CONNECTION_MOBILITY_FAIL",a[a.ERR_ICE_CONNECTION_HEARTBEAT_TIMEOUT=16908812]="ERR_ICE_CONNECTION_HEARTBEAT_TIMEOUT",a[a.ERR_LATENCY_LIVE_COMMUNICATION_FAILED=17235971]="ERR_LATENCY_LIVE_COMMUNICATION_FAILED",a[a.ERR_LATENCY_LIVE_MEIDASETTING_FAILED=17235972]="ERR_LATENCY_LIVE_MEIDASETTING_FAILED",a[a.ERR_LATENCY_LIVE_NONE_BROADCASTER=17235973]="ERR_LATENCY_LIVE_NONE_BROADCASTER",a[a.ERR_LATENCY_LIVE_NEED_RESTART=17235974]="ERR_LATENCY_LIVE_NEED_RESTART",a[a.ERR_LATENCY_LIVE_NEED_RESTART_AGAIN_LATER=17235975]="ERR_LATENCY_LIVE_NEED_RESTART_AGAIN_LATER",a[a.ERR_LATENCY_LIVE_SERVICE_UNAVAILABLE=17235976]="ERR_LATENCY_LIVE_SERVICE_UNAVAILABLE",a[a.ERR_LATENCY_LIVE_MEDIACONNECTION_INTERRUPTION=17235977]="ERR_LATENCY_LIVE_MEDIACONNECTION_INTERRUPTION",a[a.ERR_SDK_PUBLISH_INVAILD=16974597]="ERR_SDK_PUBLISH_INVAILD",a[a.ERR_SDK_PUBLISH_NOT_JOIN_CHANNEL=16843782]="ERR_SDK_PUBLISH_NOT_JOIN_CHANNEL",a[a.ERR_SDK_PUBLISH_AUDIO_STREAM_FAILED=16843856]="ERR_SDK_PUBLISH_AUDIO_STREAM_FAILED",a[a.ERR_SDK_PUBLISH_VIDEO_STREAM_FAILED=16843857]="ERR_SDK_PUBLISH_VIDEO_STREAM_FAILED",a[a.ERR_SDK_PUBLISH_DUAL_STREAM_FAILED=16843858]="ERR_SDK_PUBLISH_DUAL_STREAM_FAILED",a[a.ERR_SDK_PUBLISH_SCEEN_SHARE_FAILED=16843859]="ERR_SDK_PUBLISH_SCEEN_SHARE_FAILED",a[a.ERR_SDK_PUBLISH_SCREEN_SHARE_CONFIG_ERROR=16843860]="ERR_SDK_PUBLISH_SCREEN_SHARE_CONFIG_ERROR",a[a.ERR_SDK_SUBSCRIBE_INVAILD=16974852]="ERR_SDK_SUBSCRIBE_INVAILD",a[a.ERR_SDK_SUBSCRIBE_NOT_JOIN_CHANNEL=16844112]="ERR_SDK_SUBSCRIBE_NOT_JOIN_CHANNEL",a[a.ERR_SDK_SUBSCRIBE_AUDIO_STREAM_FAILED=16844113]="ERR_SDK_SUBSCRIBE_AUDIO_STREAM_FAILED",a[a.ERR_SDK_SUBSCRIBE_VIDEO_STREAM_FAILED=16844114]="ERR_SDK_SUBSCRIBE_VIDEO_STREAM_FAILED",a[a.ERR_SDK_SUBSCRIBE_DUAL_STREAM_FAILED=16844115]="ERR_SDK_SUBSCRIBE_DUAL_STREAM_FAILED",a[a.ERR_SDK_SUBSCRIBE_SCREEN_SHARE_FAILED=16844116]="ERR_SDK_SUBSCRIBE_SCREEN_SHARE_FAILED",a[a.ERR_SDK_SUBSCRIBE_DATA_FAILED=16844117]="ERR_SDK_SUBSCRIBE_DATA_FAILED",a[a.ERR_SDK_SUBSCRIBE_DATA_ERROR=16844118]="ERR_SDK_SUBSCRIBE_DATA_ERROR",a[a.ERR_SDK_INVALID_STATE=16974340]="ERR_SDK_INVALID_STATE",a[a.ERR_INVALID_ARGUMENTS=16974083]="ERR_INVALID_ARGUMENTS",a[a.ERR_SESSION_REMOVED=33620229]="ERR_SESSION_REMOVED",a[a.ERR_SDK_UPDATE_ROLE_CHANNEL=16908801]="ERR_SDK_UPDATE_ROLE_CHANNEL",a[a.ERR_INNER=-1]="ERR_INNER",a[a.ERR_SDK_MPU_TASK_PUBLISH_OK=0]="ERR_SDK_MPU_TASK_PUBLISH_OK",a[a.ERR_SDK_MPU_TASK_STREAM_NOT_FOUND=17825793]="ERR_SDK_MPU_TASK_STREAM_NOT_FOUND",a[a.ERR_SDK_MPU_TASK_STREAM_ALREADY_EXIST=17825794]="ERR_SDK_MPU_TASK_STREAM_ALREADY_EXIST",a[a.ERR_SDK_MPU_TASK_INVALID_PARAM=17825795]="ERR_SDK_MPU_TASK_INVALID_PARAM",a[a.ERR_SDK_MPU_TASK_INTERNAL_ERROR=17825796]="ERR_SDK_MPU_TASK_INTERNAL_ERROR",a[a.ERR_SDK_MPU_TASK_RTMP_SERVER_ERROR=17825797]="ERR_SDK_MPU_TASK_RTMP_SERVER_ERROR",a[a.ERR_SDK_MPU_TASK_RTMP_STREAM_URL_ERROR=17825798]="ERR_SDK_MPU_TASK_RTMP_STREAM_URL_ERROR",a[a.ERR_SDK_MPU_TASK_PUBLISH_TIMEOUT=17825799]="ERR_SDK_MPU_TASK_PUBLISH_TIMEOUT",a[a.ERR_SDK_MPU_TASK_NOT_AUTHORIZED=17825800]="ERR_SDK_MPU_TASK_NOT_AUTHORIZED",a[a.ERR_SDK_CHANNEL_RELAY_STATE_ERROR=18874369]="ERR_SDK_CHANNEL_RELAY_STATE_ERROR",a[a.ERR_SDK_CHANNEL_RELAY_SRC_NOT_ALLOW=18874370]="ERR_SDK_CHANNEL_RELAY_SRC_NOT_ALLOW",a[a.ERR_SDK_CHANNEL_RELAY_JOIN_DEST_FAILED=18874371]="ERR_SDK_CHANNEL_RELAY_JOIN_DEST_FAILED",a[a.ERR_SDK_CHANNEL_RELAY_TOKEN_INVALID=18874372]="ERR_SDK_CHANNEL_RELAY_TOKEN_INVALID",a[a.ERR_SDK_CHANNEL_RELAY_ROLE_ERROR=18874373]="ERR_SDK_CHANNEL_RELAY_ROLE_ERROR",a[a.ERR_SDK_CHANNEL_RELAY_INVALID_PARAM=18874374]="ERR_SDK_CHANNEL_RELAY_INVALID_PARAM",a[a.ERR_SDK_CHANNEL_RELAY_TO_SELF_ERROR=18874375]="ERR_SDK_CHANNEL_RELAY_TO_SELF_ERROR",a))(B||{});class U extends Error{constructor(e,t,i){super(t);m(this,"_code");m(this,"_extra");this._code=e,this._extra=i}static fromRtsError(e){return e instanceof U?e:new U((e==null?void 0:e.errorCode)||-1,(e==null?void 0:e.message)||(e==null?void 0:e.errorCodeName)||"rts error",e)}static fromError(e,t=-1,i=""){return new U(t,(e==null?void 0:e.message)||(e==null?void 0:e.reason)||i||"error",e)}get code(){return this._code}set code(e){this._code=e}get reason(){return this.message}get extra(){return this._extra}}function hr(a){var r;if(((r=a==null?void 0:a.nodeName)==null?void 0:r.toLowerCase())==="video")return a.setAttribute("playsinline",""),a;if(typeof a=="string"){let e=document.getElementById(a);if(e){if(e.nodeName.toLocaleLowerCase()==="video")return e.setAttribute("playsinline",""),e;throw new U(B.ERR_INVALID_ARGUMENTS,"element should be HtmlVideoElement")}throw new U(B.ERR_INVALID_ARGUMENTS,"element not founded")}throw new U(B.ERR_INVALID_ARGUMENTS,"element id should be string")}function cs(a){var e;const r=[];if(Array.isArray(a))a.forEach(t=>{try{r.push(hr(t))}catch(i){}});else if(typeof a=="string"||((e=a==null?void 0:a.nodeName)==null?void 0:e.toLowerCase())==="video")try{r.push(hr(a))}catch(t){}return r}function Ht(a){return new Promise(r=>setTimeout(r,a))}function pr(a,r,e=1e3,t=i=>!0){return I(this,null,function*(){let i=0;for(;i<r;)try{return yield a(i)}catch(s){if(i++,i>=r||!t(s))throw s||void 0;yield new Promise(n=>setTimeout(n,e))}})}function ls(a,r){let e=r;return typeof window.__ali_prefer_media_server=="string"&&window.__ali_prefer_media_server!==""&&(e=window.__ali_prefer_media_server),e?`${a}&ali_prefer_media_server=${e}`:a}function ii(a,r){var e;try{const{archCfgs:t}=a;if(!t||!Array.isArray(t))return;const i=t.find(s=>s.arch==="grtn");return i?(e=i.user_specified)==null?void 0:e[r]:void 0}catch(t){return}}function gi(a,r){try{const{config:e}=a;return e?e==null?void 0:e[r]:void 0}catch(e){return}}function lo(a){const r=a.replace(/(a=rtpmap:(\d+).*\r\n)/g,`$1a=rtcp-fb:$2 rrtr\r
1
+ (function(z,J){typeof exports=="object"&&typeof module!="undefined"?J(exports,require("aliyun-rts-live-sdk"),require("eventemitter3")):typeof define=="function"&&define.amd?define(["exports","aliyun-rts-live-sdk","eventemitter3"],J):J((z=typeof globalThis!="undefined"?globalThis:z||self).AliRtcEngine={},z.AliyunRts,z.EventEmitter)})(this,function(z,J,oe){var re,bt,ui,se,Yt,Zt,rt,F,Zn;"use strict";var at=(a=>(a.EnableNonOnePcDefaultJoinMode="h5_enable_non_one_pc_default_join_mode",a))(at||{});function Vt(){}let pi=0,mi=!1;const di=class di{static getInstance(){var r;return di.instance||(di.instance=new AudioContext),(r=di.instance.resume())==null||r.then(Vt,Vt).catch(Vt),di.instance}};m(di,"instance");let yt=di;const nt=()=>{var r;const a=yt.getInstance();a.state!=="running"&&a.state!=="closed"&&((r=a.resume())==null||r.then(Vt,Vt).catch(Vt)),window.removeEventListener("mousedown",nt),window.removeEventListener("touchstart",nt)};var Rt=(a=>(a.prod="rs.rtn.aliyuncs.com",a.pre="prs.rtn.aliyuncs.com",a))(Rt||{}),It=(a=>(a.pre="pre",a.prod="prod",a))(It||{}),Ut=(a=>(a.AliRtcSdkCommunication="communication",a.AliRtcSdkInteractiveLive="interactive_live",a.AliRtcSdkInteractiveWithLowLatencyLive="cdn_live",a))(Ut||{}),zt=(a=>(a.AliRtcSdkInteractive="interactive",a.AliRtcSdkLive="live",a))(zt||{}),kt=(a=>(a[a.AliEngineLocalDeviceTypeUnknown=0]="AliEngineLocalDeviceTypeUnknown",a[a.AliEngineLocalDeviceTypeMic=1]="AliEngineLocalDeviceTypeMic",a[a.AliEngineLocalDeviceTypeSpeaker=2]="AliEngineLocalDeviceTypeSpeaker",a[a.AliEngineLocalDeviceTypeAudioDevice=3]="AliEngineLocalDeviceTypeAudioDevice",a[a.AliEngineLocalDeviceTypeCamera=4]="AliEngineLocalDeviceTypeCamera",a[a.AliEngineLocalDeviceTypeDisplay=5]="AliEngineLocalDeviceTypeDisplay",a[a.AliEngineLocalDeviceTypeVideoDevice=6]="AliEngineLocalDeviceTypeVideoDevice",a))(kt||{}),je=(a=>(a[a.AliEngineLocalDeviceExceptionTypeUnknown=0]="AliEngineLocalDeviceExceptionTypeUnknown",a[a.AliEngineLocalDeviceExceptionTypeMicOpenFail=1]="AliEngineLocalDeviceExceptionTypeMicOpenFail",a[a.AliEngineLocalDeviceExceptionTypeMicInterrupt=2]="AliEngineLocalDeviceExceptionTypeMicInterrupt",a[a.AliEngineLocalDeviceExceptionTypeMicAuthFail=3]="AliEngineLocalDeviceExceptionTypeMicAuthFail",a[a.AliEngineLocalDeviceExceptionTypeMicNotAvailable=4]="AliEngineLocalDeviceExceptionTypeMicNotAvailable",a[a.AliEngineLocalDeviceExceptionTypeSpeakerOpenFail=5]="AliEngineLocalDeviceExceptionTypeSpeakerOpenFail",a[a.AliEngineLocalDeviceExceptionTypeSpeakerInterrupt=6]="AliEngineLocalDeviceExceptionTypeSpeakerInterrupt",a[a.AliEngineLocalDeviceExceptionTypeSpeakerNotAvailable=7]="AliEngineLocalDeviceExceptionTypeSpeakerNotAvailable",a[a.AliEngineLocalDeviceExceptionTypeAudioDeviceException=8]="AliEngineLocalDeviceExceptionTypeAudioDeviceException",a[a.AliEngineLocalDeviceExceptionTypeCameraOpenFail=9]="AliEngineLocalDeviceExceptionTypeCameraOpenFail",a[a.AliEngineLocalDeviceExceptionTypeCameraInterrupt=10]="AliEngineLocalDeviceExceptionTypeCameraInterrupt",a[a.AliEngineLocalDeviceExceptionTypeCameraAuthFail=11]="AliEngineLocalDeviceExceptionTypeCameraAuthFail",a[a.AliEngineLocalDeviceExceptionTypeDisplayException=12]="AliEngineLocalDeviceExceptionTypeDisplayException",a[a.AliEngineLocalDeviceExceptionTypeVideoDeviceException=13]="AliEngineLocalDeviceExceptionTypeVideoDeviceException",a))(je||{}),ae=(a=>(a[a.AliRtcConnectionStatusInit=0]="AliRtcConnectionStatusInit",a[a.AliRtcConnectionStatusDisconnected=1]="AliRtcConnectionStatusDisconnected",a[a.AliRtcConnectionStatusConnecting=2]="AliRtcConnectionStatusConnecting",a[a.AliRtcConnectionStatusConnected=3]="AliRtcConnectionStatusConnected",a[a.AliRtcConnectionStatusReconnecting=4]="AliRtcConnectionStatusReconnecting",a[a.AliRtcConnectionStatusFailed=5]="AliRtcConnectionStatusFailed",a))(ae||{}),Pt=(a=>(a[a.AliRtcConnectionChangedDummyReason=0]="AliRtcConnectionChangedDummyReason",a[a.AliRtcConnectionMediaPathChanged=1]="AliRtcConnectionMediaPathChanged",a[a.AliRtcConnectionSignalingHeartbeatTimeout=2]="AliRtcConnectionSignalingHeartbeatTimeout",a[a.AliRtcConnectionSignalingHeartbeatAlive=3]="AliRtcConnectionSignalingHeartbeatAlive",a[a.AliRtcConnectionSignalingHttpDnsResolved=4]="AliRtcConnectionSignalingHttpDnsResolved",a[a.AliRtcConnectionSignalingHttpDnsFailure=5]="AliRtcConnectionSignalingHttpDnsFailure",a[a.AliRtcConnectionSignalingGslbFailure=6]="AliRtcConnectionSignalingGslbFailure",a[a.AliRtcConnectionSignalingGslbSuccess=7]="AliRtcConnectionSignalingGslbSuccess",a[a.AliRtcConnectionSignalingJoinRoomFailure=8]="AliRtcConnectionSignalingJoinRoomFailure",a[a.AliRtcConnectionSignalingJoinRoomSuccess=9]="AliRtcConnectionSignalingJoinRoomSuccess",a[a.AliRtcConnectionSignalingLeaveRoom=10]="AliRtcConnectionSignalingLeaveRoom",a[a.AliRtcConnectionSignalingConnecting=11]="AliRtcConnectionSignalingConnecting",a[a.AliRtcConnectionChangedNetworkInterrupted=12]="AliRtcConnectionChangedNetworkInterrupted",a))(Pt||{}),ns=(a=>(a[a.AliRtcUserOfflineQuit=0]="AliRtcUserOfflineQuit",a[a.AliRtcUserOfflineDropped=1]="AliRtcUserOfflineDropped",a[a.AliRtcUserOfflineBecomeAudience=2]="AliRtcUserOfflineBecomeAudience",a))(ns||{}),ti=(a=>(a[a.AliRtcAudioTrackNo=0]="AliRtcAudioTrackNo",a[a.AliRtcAudioTrackMic=1]="AliRtcAudioTrackMic",a[a.AliRtcAudioTrackDual=2]="AliRtcAudioTrackDual",a))(ti||{}),ue=(a=>(a[a.AliRtcVideoTrackNo=0]="AliRtcVideoTrackNo",a[a.AliRtcVideoTrackCamera=1]="AliRtcVideoTrackCamera",a[a.AliRtcVideoTrackScreen=2]="AliRtcVideoTrackScreen",a[a.AliRtcVideoTrackBoth=3]="AliRtcVideoTrackBoth",a))(ue||{}),ee=(a=>(a[a.AliRtcStatePublishIdle=0]="AliRtcStatePublishIdle",a[a.AliRtcStateNoPublish=1]="AliRtcStateNoPublish",a[a.AliRtcStatePublishing=2]="AliRtcStatePublishing",a[a.AliRtcStatePublished=3]="AliRtcStatePublished",a[a.AliRtcStateReconnecting=4]="AliRtcStateReconnecting",a))(ee||{}),ce=(a=>(a[a.AliRtcStateSubscribeIdle=0]="AliRtcStateSubscribeIdle",a[a.AliRtcStateNoSubscribe=1]="AliRtcStateNoSubscribe",a[a.AliRtcStateSubscribing=2]="AliRtcStateSubscribing",a[a.AliRtcStateSubscribed=3]="AliRtcStateSubscribed",a[a.AliRtcStateReconnecting=4]="AliRtcStateReconnecting",a))(ce||{}),Ge=(a=>(a[a.AliRtcVideoStreamTypeNone=0]="AliRtcVideoStreamTypeNone",a[a.AliRtcVideoStreamTypeHigh=1]="AliRtcVideoStreamTypeHigh",a[a.AliRtcVideoStreamTypeLow=2]="AliRtcVideoStreamTypeLow",a))(Ge||{}),Ai=(a=>(a[a.CAMERA_INVALID=-1]="CAMERA_INVALID",a[a.CAMERA_REAR=0]="CAMERA_REAR",a[a.CAMERA_FRONT=1]="CAMERA_FRONT",a))(Ai||{}),tt=(a=>(a[a.AliRtcNetworkExcellent=0]="AliRtcNetworkExcellent",a[a.AliRtcNetworkGood=1]="AliRtcNetworkGood",a[a.AliRtcNetworkPoor=2]="AliRtcNetworkPoor",a[a.AliRtcNetworkBad=3]="AliRtcNetworkBad",a[a.AliRtcNetworkVeryBad=4]="AliRtcNetworkVeryBad",a[a.AliRtcNetworkDisconnected=5]="AliRtcNetworkDisconnected",a[a.AliRtcNetworkUnknown=6]="AliRtcNetworkUnknown",a))(tt||{}),Me=(a=>(a.PullStreamStats="remoteStat",a.RtsSubscribeExceeds="rtsSubscribeExceeds",a.UserJoined="userJoined",a.UserLeft="userLeft",a.Bye="bye",a.MuteAudio="muteAudio",a.UnmuteAudio="unmuteAudio",a.MuteVideo="muteVideo",a.UnmuteVideo="unmuteVideo",a.MuteScreen="muteScreen",a.UnmuteScreen="unmuteScreen",a.Error="error",a))(Me||{}),ot=(a=>(a.Local="local-device-status-change",a.Remote="remote-device-status-change",a))(ot||{}),D=(a=>(a.Audio="sophon_audio",a.VideoLarge="sophon_video_camera_large",a.VideoSmall="sophon_video_camera_small",a.Screen="sophon_video_screen_share",a.Data="sophon_data",a))(D||{}),os=(a=>(a.Audio="rts audio",a.VideoLarge="rts video",a))(os||{}),Bt=(a=>(a.Add="add",a.Delete="delete",a.Replace="replace",a.Stop="stop",a.UnPublish="unpublish",a))(Bt||{}),wi=(a=>(a[a.Camera=0]="Camera",a[a.Screen=1]="Screen",a[a.Image=2]="Image",a))(wi||{}),Hi=(a=>(a[a.Microphone=0]="Microphone",a[a.Screen=1]="Screen",a[a.Mixed=2]="Mixed",a))(Hi||{}),ge=(a=>(a.InRoom="inRoom",a.Join="join",a.Publish="publish",a.User="user",a.Resume="resume",a.Retry="retry",a.Reconnect="reconnect",a))(ge||{}),Dt=(a=>(a[a.MANUAL=0]="MANUAL",a[a.JOIN_CHANNEL=1]="JOIN_CHANNEL",a[a.ROLE_CHANGE=2]="ROLE_CHANGE",a[a.RECONNECT=3]="RECONNECT",a))(Dt||{}),B=(a=>(a[a.ERR_JOIN_ALREADY_JOINED=16843521]="ERR_JOIN_ALREADY_JOINED",a[a.ERR_JOIN_BAD_APPID=33620481]="ERR_JOIN_BAD_APPID",a[a.ERR_JOIN_INVALID_APPID=33620482]="ERR_JOIN_INVALID_APPID",a[a.ERR_JOIN_BAD_CHANNEL=33620484]="ERR_JOIN_BAD_CHANNEL",a[a.ERR_JOIN_INVALID_CHANNEL=33620483]="ERR_JOIN_INVALID_CHANNEL",a[a.ERR_JOIN_BAD_TOKEN=33620485]="ERR_JOIN_BAD_TOKEN",a[a.ERR_JOIN_TIMEOUT=16908804]="ERR_JOIN_TIMEOUT",a[a.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD=16974081]="ERR_JOIN_ERR_JOIN_BAD_PARAMBAD",a[a.ERR_JOIN_CHANNEL_FAILED=16974338]="ERR_JOIN_CHANNEL_FAILED",a[a.ERR_LOG_ALREADY_INIT=16974085]="ERR_LOG_ALREADY_INIT",a[a.ERR_LOG_ROOT_PATH_ERROR=16974086]="ERR_LOG_ROOT_PATH_ERROR",a[a.ERR_MIC_OPEN_FAIL=17040388]="ERR_MIC_OPEN_FAIL",a[a.ERR_SPEAKER_OPEN_FAIL=17040389]="ERR_SPEAKER_OPEN_FAIL",a[a.ERR_MIC_INTERRUPT=17040390]="ERR_MIC_INTERRUPT",a[a.ERR_SPEAKER_INTERRUPT=17040391]="ERR_SPEAKER_INTERRUPT",a[a.ERR_MIC_AUTH_FAIL=17040392]="ERR_MIC_AUTH_FAIL",a[a.ERR_MIC_NOT_AVAILABLE=17040393]="ERR_MIC_NOT_AVAILABLE",a[a.ERR_SPEAKER_NOT_AVAILABLE=17040400]="ERR_SPEAKER_NOT_AVAILABLE",a[a.ERR_CAMERA_OPEN_FAIL=17039620]="ERR_CAMERA_OPEN_FAIL",a[a.ERR_CAMERA_AUTH_FAIL=17039621]="ERR_CAMERA_AUTH_FAIL",a[a.ERR_CAMERA_INTERRUPT=17039622]="ERR_CAMERA_INTERRUPT",a[a.ERR_CAMERA_NOT_AVAILABLE=17039623]="ERR_CAMERA_NOT_AVAILABLE",a[a.ERR_VIDEO_DISPLAY_OPEN_FAIL=17039873]="ERR_VIDEO_DISPLAY_OPEN_FAIL",a[a.ERR_VIDEO_DISPLAY_INTERRUPT=1064992]="ERR_VIDEO_DISPLAY_INTERRUPT",a[a.ERR_ICE_CONNECTION_CONNECT_FAIL=17105409]="ERR_ICE_CONNECTION_CONNECT_FAIL",a[a.ERR_ICE_CONNECTION_RECONNECT_FAI=17105410]="ERR_ICE_CONNECTION_RECONNECT_FAI",a[a.ERR_ICE_CONNECTION_MOBILITY_FAIL=17105411]="ERR_ICE_CONNECTION_MOBILITY_FAIL",a[a.ERR_ICE_CONNECTION_HEARTBEAT_TIMEOUT=16908812]="ERR_ICE_CONNECTION_HEARTBEAT_TIMEOUT",a[a.ERR_LATENCY_LIVE_COMMUNICATION_FAILED=17235971]="ERR_LATENCY_LIVE_COMMUNICATION_FAILED",a[a.ERR_LATENCY_LIVE_MEIDASETTING_FAILED=17235972]="ERR_LATENCY_LIVE_MEIDASETTING_FAILED",a[a.ERR_LATENCY_LIVE_NONE_BROADCASTER=17235973]="ERR_LATENCY_LIVE_NONE_BROADCASTER",a[a.ERR_LATENCY_LIVE_NEED_RESTART=17235974]="ERR_LATENCY_LIVE_NEED_RESTART",a[a.ERR_LATENCY_LIVE_NEED_RESTART_AGAIN_LATER=17235975]="ERR_LATENCY_LIVE_NEED_RESTART_AGAIN_LATER",a[a.ERR_LATENCY_LIVE_SERVICE_UNAVAILABLE=17235976]="ERR_LATENCY_LIVE_SERVICE_UNAVAILABLE",a[a.ERR_LATENCY_LIVE_MEDIACONNECTION_INTERRUPTION=17235977]="ERR_LATENCY_LIVE_MEDIACONNECTION_INTERRUPTION",a[a.ERR_SDK_PUBLISH_INVAILD=16974597]="ERR_SDK_PUBLISH_INVAILD",a[a.ERR_SDK_PUBLISH_NOT_JOIN_CHANNEL=16843782]="ERR_SDK_PUBLISH_NOT_JOIN_CHANNEL",a[a.ERR_SDK_PUBLISH_AUDIO_STREAM_FAILED=16843856]="ERR_SDK_PUBLISH_AUDIO_STREAM_FAILED",a[a.ERR_SDK_PUBLISH_VIDEO_STREAM_FAILED=16843857]="ERR_SDK_PUBLISH_VIDEO_STREAM_FAILED",a[a.ERR_SDK_PUBLISH_DUAL_STREAM_FAILED=16843858]="ERR_SDK_PUBLISH_DUAL_STREAM_FAILED",a[a.ERR_SDK_PUBLISH_SCEEN_SHARE_FAILED=16843859]="ERR_SDK_PUBLISH_SCEEN_SHARE_FAILED",a[a.ERR_SDK_PUBLISH_SCREEN_SHARE_CONFIG_ERROR=16843860]="ERR_SDK_PUBLISH_SCREEN_SHARE_CONFIG_ERROR",a[a.ERR_SDK_SUBSCRIBE_INVAILD=16974852]="ERR_SDK_SUBSCRIBE_INVAILD",a[a.ERR_SDK_SUBSCRIBE_NOT_JOIN_CHANNEL=16844112]="ERR_SDK_SUBSCRIBE_NOT_JOIN_CHANNEL",a[a.ERR_SDK_SUBSCRIBE_AUDIO_STREAM_FAILED=16844113]="ERR_SDK_SUBSCRIBE_AUDIO_STREAM_FAILED",a[a.ERR_SDK_SUBSCRIBE_VIDEO_STREAM_FAILED=16844114]="ERR_SDK_SUBSCRIBE_VIDEO_STREAM_FAILED",a[a.ERR_SDK_SUBSCRIBE_DUAL_STREAM_FAILED=16844115]="ERR_SDK_SUBSCRIBE_DUAL_STREAM_FAILED",a[a.ERR_SDK_SUBSCRIBE_SCREEN_SHARE_FAILED=16844116]="ERR_SDK_SUBSCRIBE_SCREEN_SHARE_FAILED",a[a.ERR_SDK_SUBSCRIBE_DATA_FAILED=16844117]="ERR_SDK_SUBSCRIBE_DATA_FAILED",a[a.ERR_SDK_SUBSCRIBE_DATA_ERROR=16844118]="ERR_SDK_SUBSCRIBE_DATA_ERROR",a[a.ERR_SDK_INVALID_STATE=16974340]="ERR_SDK_INVALID_STATE",a[a.ERR_INVALID_ARGUMENTS=16974083]="ERR_INVALID_ARGUMENTS",a[a.ERR_SESSION_REMOVED=33620229]="ERR_SESSION_REMOVED",a[a.ERR_SDK_UPDATE_ROLE_CHANNEL=16908801]="ERR_SDK_UPDATE_ROLE_CHANNEL",a[a.ERR_INNER=-1]="ERR_INNER",a[a.ERR_SDK_MPU_TASK_PUBLISH_OK=0]="ERR_SDK_MPU_TASK_PUBLISH_OK",a[a.ERR_SDK_MPU_TASK_STREAM_NOT_FOUND=17825793]="ERR_SDK_MPU_TASK_STREAM_NOT_FOUND",a[a.ERR_SDK_MPU_TASK_STREAM_ALREADY_EXIST=17825794]="ERR_SDK_MPU_TASK_STREAM_ALREADY_EXIST",a[a.ERR_SDK_MPU_TASK_INVALID_PARAM=17825795]="ERR_SDK_MPU_TASK_INVALID_PARAM",a[a.ERR_SDK_MPU_TASK_INTERNAL_ERROR=17825796]="ERR_SDK_MPU_TASK_INTERNAL_ERROR",a[a.ERR_SDK_MPU_TASK_RTMP_SERVER_ERROR=17825797]="ERR_SDK_MPU_TASK_RTMP_SERVER_ERROR",a[a.ERR_SDK_MPU_TASK_RTMP_STREAM_URL_ERROR=17825798]="ERR_SDK_MPU_TASK_RTMP_STREAM_URL_ERROR",a[a.ERR_SDK_MPU_TASK_PUBLISH_TIMEOUT=17825799]="ERR_SDK_MPU_TASK_PUBLISH_TIMEOUT",a[a.ERR_SDK_MPU_TASK_NOT_AUTHORIZED=17825800]="ERR_SDK_MPU_TASK_NOT_AUTHORIZED",a[a.ERR_SDK_CHANNEL_RELAY_STATE_ERROR=18874369]="ERR_SDK_CHANNEL_RELAY_STATE_ERROR",a[a.ERR_SDK_CHANNEL_RELAY_SRC_NOT_ALLOW=18874370]="ERR_SDK_CHANNEL_RELAY_SRC_NOT_ALLOW",a[a.ERR_SDK_CHANNEL_RELAY_JOIN_DEST_FAILED=18874371]="ERR_SDK_CHANNEL_RELAY_JOIN_DEST_FAILED",a[a.ERR_SDK_CHANNEL_RELAY_TOKEN_INVALID=18874372]="ERR_SDK_CHANNEL_RELAY_TOKEN_INVALID",a[a.ERR_SDK_CHANNEL_RELAY_ROLE_ERROR=18874373]="ERR_SDK_CHANNEL_RELAY_ROLE_ERROR",a[a.ERR_SDK_CHANNEL_RELAY_INVALID_PARAM=18874374]="ERR_SDK_CHANNEL_RELAY_INVALID_PARAM",a[a.ERR_SDK_CHANNEL_RELAY_TO_SELF_ERROR=18874375]="ERR_SDK_CHANNEL_RELAY_TO_SELF_ERROR",a))(B||{});class U extends Error{constructor(e,t,i){super(t);m(this,"_code");m(this,"_extra");this._code=e,this._extra=i}static fromRtsError(e){return e instanceof U?e:new U((e==null?void 0:e.errorCode)||-1,(e==null?void 0:e.message)||(e==null?void 0:e.errorCodeName)||"rts error",e)}static fromError(e,t=-1,i=""){return new U(t,(e==null?void 0:e.message)||(e==null?void 0:e.reason)||i||"error",e)}get code(){return this._code}set code(e){this._code=e}get reason(){return this.message}get extra(){return this._extra}}function hr(a){var r;if(((r=a==null?void 0:a.nodeName)==null?void 0:r.toLowerCase())==="video")return a.setAttribute("playsinline",""),a;if(typeof a=="string"){let e=document.getElementById(a);if(e){if(e.nodeName.toLocaleLowerCase()==="video")return e.setAttribute("playsinline",""),e;throw new U(B.ERR_INVALID_ARGUMENTS,"element should be HtmlVideoElement")}throw new U(B.ERR_INVALID_ARGUMENTS,"element not founded")}throw new U(B.ERR_INVALID_ARGUMENTS,"element id should be string")}function cs(a){var e;const r=[];if(Array.isArray(a))a.forEach(t=>{try{r.push(hr(t))}catch(i){}});else if(typeof a=="string"||((e=a==null?void 0:a.nodeName)==null?void 0:e.toLowerCase())==="video")try{r.push(hr(a))}catch(t){}return r}function Ht(a){return new Promise(r=>setTimeout(r,a))}function pr(a,r,e=1e3,t=i=>!0){return I(this,null,function*(){let i=0;for(;i<r;)try{return yield a(i)}catch(s){if(i++,i>=r||!t(s))throw s||void 0;yield new Promise(n=>setTimeout(n,e))}})}function ls(a,r){let e=r;return typeof window.__ali_prefer_media_server=="string"&&window.__ali_prefer_media_server!==""&&(e=window.__ali_prefer_media_server),e?`${a}&ali_prefer_media_server=${e}`:a}function ii(a,r){var e;try{const{archCfgs:t}=a;if(!t||!Array.isArray(t))return;const i=t.find(s=>s.arch==="grtn");return i?(e=i.user_specified)==null?void 0:e[r]:void 0}catch(t){return}}function gi(a,r){try{const{config:e}=a;return e?e==null?void 0:e[r]:void 0}catch(e){return}}function lo(a){const r=a.replace(/(a=rtpmap:(\d+).*\r\n)/g,`$1a=rtcp-fb:$2 rrtr\r
2
2
  `);return r.includes(`a=rtcp-rsize\r
3
3
  `)?r:r.replace(/(m=(video|audio).*\r\n)/g,`$1a=rtcp-rsize\r
4
- `)}function ds(a,r){return a>50||r>500?tt.AliRtcNetworkVeryBad:a>30||r>350?tt.AliRtcNetworkBad:a>20||r>200?tt.AliRtcNetworkPoor:a>10||r>100?tt.AliRtcNetworkGood:a>=0||r>=0?tt.AliRtcNetworkExcellent:tt.AliRtcNetworkUnknown}function mr(a){return!!a&&[D.VideoLarge,D.VideoSmall,D.Screen].includes(a)}function gr(a){return a===D.Audio}for(var us,Qe=[],hs=0;hs<256;++hs)Qe.push((hs+256).toString(16).slice(1));var uo=new Uint8Array(16);function ho(){if(!us&&!(us=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return us(uo)}const fr={randomUUID:typeof crypto!="undefined"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function mt(a,r,e){if(fr.randomUUID&&!r&&!a)return fr.randomUUID();var t=(a=a||{}).random||(a.rng||ho)();if(t[6]=15&t[6]|64,t[8]=63&t[8]|128,r){e=e||0;for(var i=0;i<16;++i)r[e+i]=t[i];return r}return function(s,n=0){return(Qe[s[n+0]]+Qe[s[n+1]]+Qe[s[n+2]]+Qe[s[n+3]]+"-"+Qe[s[n+4]]+Qe[s[n+5]]+"-"+Qe[s[n+6]]+Qe[s[n+7]]+"-"+Qe[s[n+8]]+Qe[s[n+9]]+"-"+Qe[s[n+10]]+Qe[s[n+11]]+Qe[s[n+12]]+Qe[s[n+13]]+Qe[s[n+14]]+Qe[s[n+15]]).toLowerCase()}(t)}const _i="7.2.9";class Le{static getVersionNumber(){let r=_i.split("."),e="";return r.forEach(t=>{t.length===1?e+="0"+t:e+=t}),parseInt(e)}static queryingParam(r){let e=[];if(r)for(let t in r)e.push(t+"="+r[t]);return e.join("&")}static getQueryParams(r){const e=window.location.search.substring(1).split("&");for(let t=0;t<e.length;t++){const i=e[t].split("=");if(decodeURIComponent(i[0])===r)return decodeURIComponent(i[1])}}static createCallid(r=""){const e=mt();return r&&e&&e.length>r.length?`${r}${e.substring(r.length)}`:e}static checkSubOptionsValid(r){if(r){const{audio:e,video:t,screen:i}=r;if(e===!1&&t===!1&&i===!1)return!1}return!0}static isNetworkAvailable(){return I(this,null,function*(){const r=Rt.prod,{onLine:e}=navigator;if(!e)return!1;try{return yield fetch(`https://${r}/roomserver/v1/ws/version`),!0}catch(t){return!1}})}static toString(r){let e;if(r instanceof Error)e=r.message;else if(typeof r=="string")e=r;else try{e=JSON.stringify(r)}catch(t){e="undefined"}return e}static paramArrayToString(r){let e="";for(let t=0;t<r.length;t++)e!==""&&(e+=" "),e+=Le.toString(r[t]);return e}static removeQueryString(r){if(!r)return r;let e=r.indexOf("?");return e>0?r.substring(0,e):r}}function br(a,r,e){Object.defineProperty(a,r,{writable:!0,enumerable:!0,configurable:!0,value:e})}function Sr(a,r,e,t){t?t(()=>{br(a,r,e)}):br(a,r,e)}Array(32);var Fi=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function po(a){return a&&a.__esModule&&Object.prototype.hasOwnProperty.call(a,"default")?a.default:a}function mo(a){if(a.__esModule)return a;var r=a.default;if(typeof r=="function"){var e=function t(){return this instanceof t?Reflect.construct(r,arguments,this.constructor):r.apply(this,arguments)};e.prototype=r.prototype}else e={};return Object.defineProperty(e,"__esModule",{value:!0}),Object.keys(a).forEach(function(t){var i=Object.getOwnPropertyDescriptor(a,t);Object.defineProperty(e,t,i.get?i:{enumerable:!0,get:function(){return a[t]}})}),e}var vr={exports:{}},yr={exports:{}};const go=mo(Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})));var Rr;function fe(){return Rr||(Rr=1,function(a){a.exports=function(){var r=r||function(e,t){var i;if(typeof window!="undefined"&&window.crypto&&(i=window.crypto),typeof self!="undefined"&&self.crypto&&(i=self.crypto),typeof globalThis!="undefined"&&globalThis.crypto&&(i=globalThis.crypto),!i&&typeof window!="undefined"&&window.msCrypto&&(i=window.msCrypto),!i&&Fi!==void 0&&Fi.crypto&&(i=Fi.crypto),!i)try{i=go}catch(S){}var s=function(){if(i){if(typeof i.getRandomValues=="function")try{return i.getRandomValues(new Uint32Array(1))[0]}catch(S){}if(typeof i.randomBytes=="function")try{return i.randomBytes(4).readInt32LE()}catch(S){}}throw new Error("Native crypto module could not be used to get secure random number.")},n=Object.create||function(){function S(){}return function(v){var R;return S.prototype=v,R=new S,S.prototype=null,R}}(),c={},o=c.lib={},l=o.Base={extend:function(S){var v=n(this);return S&&v.mixIn(S),v.hasOwnProperty("init")&&this.init!==v.init||(v.init=function(){v.$super.init.apply(this,arguments)}),v.init.prototype=v,v.$super=this,v},create:function(){var S=this.extend();return S.init.apply(S,arguments),S},init:function(){},mixIn:function(S){for(var v in S)S.hasOwnProperty(v)&&(this[v]=S[v]);S.hasOwnProperty("toString")&&(this.toString=S.toString)},clone:function(){return this.init.prototype.extend(this)}},d=o.WordArray=l.extend({init:function(S,v){S=this.words=S||[],this.sigBytes=v!=t?v:4*S.length},toString:function(S){return(S||p).stringify(this)},concat:function(S){var v=this.words,R=S.words,_=this.sigBytes,y=S.sigBytes;if(this.clamp(),_%4)for(var w=0;w<y;w++){var A=R[w>>>2]>>>24-w%4*8&255;v[_+w>>>2]|=A<<24-(_+w)%4*8}else for(var E=0;E<y;E+=4)v[_+E>>>2]=R[E>>>2];return this.sigBytes+=y,this},clamp:function(){var S=this.words,v=this.sigBytes;S[v>>>2]&=4294967295<<32-v%4*8,S.length=e.ceil(v/4)},clone:function(){var S=l.clone.call(this);return S.words=this.words.slice(0),S},random:function(S){for(var v=[],R=0;R<S;R+=4)v.push(s());return new d.init(v,S)}}),u=c.enc={},p=u.Hex={stringify:function(S){for(var v=S.words,R=S.sigBytes,_=[],y=0;y<R;y++){var w=v[y>>>2]>>>24-y%4*8&255;_.push((w>>>4).toString(16)),_.push((15&w).toString(16))}return _.join("")},parse:function(S){for(var v=S.length,R=[],_=0;_<v;_+=2)R[_>>>3]|=parseInt(S.substr(_,2),16)<<24-_%8*4;return new d.init(R,v/2)}},h=u.Latin1={stringify:function(S){for(var v=S.words,R=S.sigBytes,_=[],y=0;y<R;y++){var w=v[y>>>2]>>>24-y%4*8&255;_.push(String.fromCharCode(w))}return _.join("")},parse:function(S){for(var v=S.length,R=[],_=0;_<v;_++)R[_>>>2]|=(255&S.charCodeAt(_))<<24-_%4*8;return new d.init(R,v)}},f=u.Utf8={stringify:function(S){try{return decodeURIComponent(escape(h.stringify(S)))}catch(v){throw new Error("Malformed UTF-8 data")}},parse:function(S){return h.parse(unescape(encodeURIComponent(S)))}},g=o.BufferedBlockAlgorithm=l.extend({reset:function(){this._data=new d.init,this._nDataBytes=0},_append:function(S){typeof S=="string"&&(S=f.parse(S)),this._data.concat(S),this._nDataBytes+=S.sigBytes},_process:function(S){var v,R=this._data,_=R.words,y=R.sigBytes,w=this.blockSize,A=y/(4*w),E=(A=S?e.ceil(A):e.max((0|A)-this._minBufferSize,0))*w,C=e.min(4*E,y);if(E){for(var P=0;P<E;P+=w)this._doProcessBlock(_,P);v=_.splice(0,E),R.sigBytes-=C}return new d.init(v,C)},clone:function(){var S=l.clone.call(this);return S._data=this._data.clone(),S},_minBufferSize:0});o.Hasher=g.extend({cfg:l.extend(),init:function(S){this.cfg=this.cfg.extend(S),this.reset()},reset:function(){g.reset.call(this),this._doReset()},update:function(S){return this._append(S),this._process(),this},finalize:function(S){return S&&this._append(S),this._doFinalize()},blockSize:16,_createHelper:function(S){return function(v,R){return new S.init(R).finalize(v)}},_createHmacHelper:function(S){return function(v,R){return new b.HMAC.init(S,R).finalize(v)}}});var b=c.algo={};return c}(Math);return r}()}(yr)),yr.exports}var Ar,wr={exports:{}};function ji(){return Ar||(Ar=1,function(a){a.exports=function(r){return i=(t=r).lib,s=i.Base,n=i.WordArray,(c=t.x64={}).Word=s.extend({init:function(o,l){this.high=o,this.low=l}}),c.WordArray=s.extend({init:function(o,l){o=this.words=o||[],this.sigBytes=l!=e?l:8*o.length},toX32:function(){for(var o=this.words,l=o.length,d=[],u=0;u<l;u++){var p=o[u];d.push(p.high),d.push(p.low)}return n.create(d,this.sigBytes)},clone:function(){for(var o=s.clone.call(this),l=o.words=this.words.slice(0),d=l.length,u=0;u<d;u++)l[u]=l[u].clone();return o}}),r;var e,t,i,s,n,c}(fe())}(wr)),wr.exports}var _r,Ir={exports:{}};function fo(){return _r||(_r=1,function(a){a.exports=function(r){return function(){if(typeof ArrayBuffer=="function"){var e=r.lib.WordArray,t=e.init,i=e.init=function(s){if(s instanceof ArrayBuffer&&(s=new Uint8Array(s)),(s instanceof Int8Array||typeof Uint8ClampedArray!="undefined"&&s instanceof Uint8ClampedArray||s instanceof Int16Array||s instanceof Uint16Array||s instanceof Int32Array||s instanceof Uint32Array||s instanceof Float32Array||s instanceof Float64Array)&&(s=new Uint8Array(s.buffer,s.byteOffset,s.byteLength)),s instanceof Uint8Array){for(var n=s.byteLength,c=[],o=0;o<n;o++)c[o>>>2]|=s[o]<<24-o%4*8;t.call(this,c,n)}else t.apply(this,arguments)};i.prototype=e}}(),r.lib.WordArray}(fe())}(Ir)),Ir.exports}var Er,Tr={exports:{}};function bo(){return Er||(Er=1,function(a){a.exports=function(r){return function(){var e=r,t=e.lib.WordArray,i=e.enc;function s(n){return n<<8&4278255360|n>>>8&16711935}i.Utf16=i.Utf16BE={stringify:function(n){for(var c=n.words,o=n.sigBytes,l=[],d=0;d<o;d+=2){var u=c[d>>>2]>>>16-d%4*8&65535;l.push(String.fromCharCode(u))}return l.join("")},parse:function(n){for(var c=n.length,o=[],l=0;l<c;l++)o[l>>>1]|=n.charCodeAt(l)<<16-l%2*16;return t.create(o,2*c)}},i.Utf16LE={stringify:function(n){for(var c=n.words,o=n.sigBytes,l=[],d=0;d<o;d+=2){var u=s(c[d>>>2]>>>16-d%4*8&65535);l.push(String.fromCharCode(u))}return l.join("")},parse:function(n){for(var c=n.length,o=[],l=0;l<c;l++)o[l>>>1]|=s(n.charCodeAt(l)<<16-l%2*16);return t.create(o,2*c)}}}(),r.enc.Utf16}(fe())}(Tr)),Tr.exports}var Cr,kr={exports:{}};function si(){return Cr||(Cr=1,function(a){a.exports=function(r){return function(){var e=r,t=e.lib.WordArray;function i(s,n,c){for(var o=[],l=0,d=0;d<n;d++)if(d%4){var u=c[s.charCodeAt(d-1)]<<d%4*2|c[s.charCodeAt(d)]>>>6-d%4*2;o[l>>>2]|=u<<24-l%4*8,l++}return t.create(o,l)}e.enc.Base64={stringify:function(s){var n=s.words,c=s.sigBytes,o=this._map;s.clamp();for(var l=[],d=0;d<c;d+=3)for(var u=(n[d>>>2]>>>24-d%4*8&255)<<16|(n[d+1>>>2]>>>24-(d+1)%4*8&255)<<8|n[d+2>>>2]>>>24-(d+2)%4*8&255,p=0;p<4&&d+.75*p<c;p++)l.push(o.charAt(u>>>6*(3-p)&63));var h=o.charAt(64);if(h)for(;l.length%4;)l.push(h);return l.join("")},parse:function(s){var n=s.length,c=this._map,o=this._reverseMap;if(!o){o=this._reverseMap=[];for(var l=0;l<c.length;l++)o[c.charCodeAt(l)]=l}var d=c.charAt(64);if(d){var u=s.indexOf(d);u!==-1&&(n=u)}return i(s,n,o)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}}(),r.enc.Base64}(fe())}(kr)),kr.exports}var Pr,Dr={exports:{}};function So(){return Pr||(Pr=1,function(a){a.exports=function(r){return function(){var e=r,t=e.lib.WordArray;function i(s,n,c){for(var o=[],l=0,d=0;d<n;d++)if(d%4){var u=c[s.charCodeAt(d-1)]<<d%4*2|c[s.charCodeAt(d)]>>>6-d%4*2;o[l>>>2]|=u<<24-l%4*8,l++}return t.create(o,l)}e.enc.Base64url={stringify:function(s,n){n===void 0&&(n=!0);var c=s.words,o=s.sigBytes,l=n?this._safe_map:this._map;s.clamp();for(var d=[],u=0;u<o;u+=3)for(var p=(c[u>>>2]>>>24-u%4*8&255)<<16|(c[u+1>>>2]>>>24-(u+1)%4*8&255)<<8|c[u+2>>>2]>>>24-(u+2)%4*8&255,h=0;h<4&&u+.75*h<o;h++)d.push(l.charAt(p>>>6*(3-h)&63));var f=l.charAt(64);if(f)for(;d.length%4;)d.push(f);return d.join("")},parse:function(s,n){n===void 0&&(n=!0);var c=s.length,o=n?this._safe_map:this._map,l=this._reverseMap;if(!l){l=this._reverseMap=[];for(var d=0;d<o.length;d++)l[o.charCodeAt(d)]=d}var u=o.charAt(64);if(u){var p=s.indexOf(u);p!==-1&&(c=p)}return i(s,c,l)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",_safe_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"}}(),r.enc.Base64url}(fe())}(Dr)),Dr.exports}var Mr,Lr={exports:{}};function ri(){return Mr||(Mr=1,function(a){a.exports=function(r){return function(e){var t=r,i=t.lib,s=i.WordArray,n=i.Hasher,c=t.algo,o=[];(function(){for(var f=0;f<64;f++)o[f]=4294967296*e.abs(e.sin(f+1))|0})();var l=c.MD5=n.extend({_doReset:function(){this._hash=new s.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(f,g){for(var b=0;b<16;b++){var S=g+b,v=f[S];f[S]=16711935&(v<<8|v>>>24)|4278255360&(v<<24|v>>>8)}var R=this._hash.words,_=f[g+0],y=f[g+1],w=f[g+2],A=f[g+3],E=f[g+4],C=f[g+5],P=f[g+6],M=f[g+7],x=f[g+8],K=f[g+9],Q=f[g+10],G=f[g+11],W=f[g+12],Z=f[g+13],te=f[g+14],Se=f[g+15],L=R[0],O=R[1],N=R[2],V=R[3];L=d(L,O,N,V,_,7,o[0]),V=d(V,L,O,N,y,12,o[1]),N=d(N,V,L,O,w,17,o[2]),O=d(O,N,V,L,A,22,o[3]),L=d(L,O,N,V,E,7,o[4]),V=d(V,L,O,N,C,12,o[5]),N=d(N,V,L,O,P,17,o[6]),O=d(O,N,V,L,M,22,o[7]),L=d(L,O,N,V,x,7,o[8]),V=d(V,L,O,N,K,12,o[9]),N=d(N,V,L,O,Q,17,o[10]),O=d(O,N,V,L,G,22,o[11]),L=d(L,O,N,V,W,7,o[12]),V=d(V,L,O,N,Z,12,o[13]),N=d(N,V,L,O,te,17,o[14]),L=u(L,O=d(O,N,V,L,Se,22,o[15]),N,V,y,5,o[16]),V=u(V,L,O,N,P,9,o[17]),N=u(N,V,L,O,G,14,o[18]),O=u(O,N,V,L,_,20,o[19]),L=u(L,O,N,V,C,5,o[20]),V=u(V,L,O,N,Q,9,o[21]),N=u(N,V,L,O,Se,14,o[22]),O=u(O,N,V,L,E,20,o[23]),L=u(L,O,N,V,K,5,o[24]),V=u(V,L,O,N,te,9,o[25]),N=u(N,V,L,O,A,14,o[26]),O=u(O,N,V,L,x,20,o[27]),L=u(L,O,N,V,Z,5,o[28]),V=u(V,L,O,N,w,9,o[29]),N=u(N,V,L,O,M,14,o[30]),L=p(L,O=u(O,N,V,L,W,20,o[31]),N,V,C,4,o[32]),V=p(V,L,O,N,x,11,o[33]),N=p(N,V,L,O,G,16,o[34]),O=p(O,N,V,L,te,23,o[35]),L=p(L,O,N,V,y,4,o[36]),V=p(V,L,O,N,E,11,o[37]),N=p(N,V,L,O,M,16,o[38]),O=p(O,N,V,L,Q,23,o[39]),L=p(L,O,N,V,Z,4,o[40]),V=p(V,L,O,N,_,11,o[41]),N=p(N,V,L,O,A,16,o[42]),O=p(O,N,V,L,P,23,o[43]),L=p(L,O,N,V,K,4,o[44]),V=p(V,L,O,N,W,11,o[45]),N=p(N,V,L,O,Se,16,o[46]),L=h(L,O=p(O,N,V,L,w,23,o[47]),N,V,_,6,o[48]),V=h(V,L,O,N,M,10,o[49]),N=h(N,V,L,O,te,15,o[50]),O=h(O,N,V,L,C,21,o[51]),L=h(L,O,N,V,W,6,o[52]),V=h(V,L,O,N,A,10,o[53]),N=h(N,V,L,O,Q,15,o[54]),O=h(O,N,V,L,y,21,o[55]),L=h(L,O,N,V,x,6,o[56]),V=h(V,L,O,N,Se,10,o[57]),N=h(N,V,L,O,P,15,o[58]),O=h(O,N,V,L,Z,21,o[59]),L=h(L,O,N,V,E,6,o[60]),V=h(V,L,O,N,G,10,o[61]),N=h(N,V,L,O,w,15,o[62]),O=h(O,N,V,L,K,21,o[63]),R[0]=R[0]+L|0,R[1]=R[1]+O|0,R[2]=R[2]+N|0,R[3]=R[3]+V|0},_doFinalize:function(){var f=this._data,g=f.words,b=8*this._nDataBytes,S=8*f.sigBytes;g[S>>>5]|=128<<24-S%32;var v=e.floor(b/4294967296),R=b;g[15+(S+64>>>9<<4)]=16711935&(v<<8|v>>>24)|4278255360&(v<<24|v>>>8),g[14+(S+64>>>9<<4)]=16711935&(R<<8|R>>>24)|4278255360&(R<<24|R>>>8),f.sigBytes=4*(g.length+1),this._process();for(var _=this._hash,y=_.words,w=0;w<4;w++){var A=y[w];y[w]=16711935&(A<<8|A>>>24)|4278255360&(A<<24|A>>>8)}return _},clone:function(){var f=n.clone.call(this);return f._hash=this._hash.clone(),f}});function d(f,g,b,S,v,R,_){var y=f+(g&b|~g&S)+v+_;return(y<<R|y>>>32-R)+g}function u(f,g,b,S,v,R,_){var y=f+(g&S|b&~S)+v+_;return(y<<R|y>>>32-R)+g}function p(f,g,b,S,v,R,_){var y=f+(g^b^S)+v+_;return(y<<R|y>>>32-R)+g}function h(f,g,b,S,v,R,_){var y=f+(b^(g|~S))+v+_;return(y<<R|y>>>32-R)+g}t.MD5=n._createHelper(l),t.HmacMD5=n._createHmacHelper(l)}(Math),r.MD5}(fe())}(Lr)),Lr.exports}var Nr,xr={exports:{}};function Or(){return Nr||(Nr=1,function(a){a.exports=function(r){return t=(e=r).lib,i=t.WordArray,s=t.Hasher,n=e.algo,c=[],o=n.SHA1=s.extend({_doReset:function(){this._hash=new i.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(l,d){for(var u=this._hash.words,p=u[0],h=u[1],f=u[2],g=u[3],b=u[4],S=0;S<80;S++){if(S<16)c[S]=0|l[d+S];else{var v=c[S-3]^c[S-8]^c[S-14]^c[S-16];c[S]=v<<1|v>>>31}var R=(p<<5|p>>>27)+b+c[S];R+=S<20?1518500249+(h&f|~h&g):S<40?1859775393+(h^f^g):S<60?(h&f|h&g|f&g)-1894007588:(h^f^g)-899497514,b=g,g=f,f=h<<30|h>>>2,h=p,p=R}u[0]=u[0]+p|0,u[1]=u[1]+h|0,u[2]=u[2]+f|0,u[3]=u[3]+g|0,u[4]=u[4]+b|0},_doFinalize:function(){var l=this._data,d=l.words,u=8*this._nDataBytes,p=8*l.sigBytes;return d[p>>>5]|=128<<24-p%32,d[14+(p+64>>>9<<4)]=Math.floor(u/4294967296),d[15+(p+64>>>9<<4)]=u,l.sigBytes=4*d.length,this._process(),this._hash},clone:function(){var l=s.clone.call(this);return l._hash=this._hash.clone(),l}}),e.SHA1=s._createHelper(o),e.HmacSHA1=s._createHmacHelper(o),r.SHA1;var e,t,i,s,n,c,o}(fe())}(xr)),xr.exports}var Vr,Ur={exports:{}};function ps(){return Vr||(Vr=1,function(a){a.exports=function(r){return function(e){var t=r,i=t.lib,s=i.WordArray,n=i.Hasher,c=t.algo,o=[],l=[];(function(){function p(b){for(var S=e.sqrt(b),v=2;v<=S;v++)if(!(b%v))return!1;return!0}function h(b){return 4294967296*(b-(0|b))|0}for(var f=2,g=0;g<64;)p(f)&&(g<8&&(o[g]=h(e.pow(f,.5))),l[g]=h(e.pow(f,1/3)),g++),f++})();var d=[],u=c.SHA256=n.extend({_doReset:function(){this._hash=new s.init(o.slice(0))},_doProcessBlock:function(p,h){for(var f=this._hash.words,g=f[0],b=f[1],S=f[2],v=f[3],R=f[4],_=f[5],y=f[6],w=f[7],A=0;A<64;A++){if(A<16)d[A]=0|p[h+A];else{var E=d[A-15],C=(E<<25|E>>>7)^(E<<14|E>>>18)^E>>>3,P=d[A-2],M=(P<<15|P>>>17)^(P<<13|P>>>19)^P>>>10;d[A]=C+d[A-7]+M+d[A-16]}var x=g&b^g&S^b&S,K=(g<<30|g>>>2)^(g<<19|g>>>13)^(g<<10|g>>>22),Q=w+((R<<26|R>>>6)^(R<<21|R>>>11)^(R<<7|R>>>25))+(R&_^~R&y)+l[A]+d[A];w=y,y=_,_=R,R=v+Q|0,v=S,S=b,b=g,g=Q+(K+x)|0}f[0]=f[0]+g|0,f[1]=f[1]+b|0,f[2]=f[2]+S|0,f[3]=f[3]+v|0,f[4]=f[4]+R|0,f[5]=f[5]+_|0,f[6]=f[6]+y|0,f[7]=f[7]+w|0},_doFinalize:function(){var p=this._data,h=p.words,f=8*this._nDataBytes,g=8*p.sigBytes;return h[g>>>5]|=128<<24-g%32,h[14+(g+64>>>9<<4)]=e.floor(f/4294967296),h[15+(g+64>>>9<<4)]=f,p.sigBytes=4*h.length,this._process(),this._hash},clone:function(){var p=n.clone.call(this);return p._hash=this._hash.clone(),p}});t.SHA256=n._createHelper(u),t.HmacSHA256=n._createHmacHelper(u)}(Math),r.SHA256}(fe())}(Ur)),Ur.exports}var Br,vo={exports:{}},Hr,Fr={exports:{}};function jr(){return Hr||(Hr=1,function(a){a.exports=function(r){return function(){var e=r,t=e.lib.Hasher,i=e.x64,s=i.Word,n=i.WordArray,c=e.algo;function o(){return s.create.apply(s,arguments)}var l=[o(1116352408,3609767458),o(1899447441,602891725),o(3049323471,3964484399),o(3921009573,2173295548),o(961987163,4081628472),o(1508970993,3053834265),o(2453635748,2937671579),o(2870763221,3664609560),o(3624381080,2734883394),o(310598401,1164996542),o(607225278,1323610764),o(1426881987,3590304994),o(1925078388,4068182383),o(2162078206,991336113),o(2614888103,633803317),o(3248222580,3479774868),o(3835390401,2666613458),o(4022224774,944711139),o(264347078,2341262773),o(604807628,2007800933),o(770255983,1495990901),o(1249150122,1856431235),o(1555081692,3175218132),o(1996064986,2198950837),o(2554220882,3999719339),o(2821834349,766784016),o(2952996808,2566594879),o(3210313671,3203337956),o(3336571891,1034457026),o(3584528711,2466948901),o(113926993,3758326383),o(338241895,168717936),o(666307205,1188179964),o(773529912,1546045734),o(1294757372,1522805485),o(1396182291,2643833823),o(1695183700,2343527390),o(1986661051,1014477480),o(2177026350,1206759142),o(2456956037,344077627),o(2730485921,1290863460),o(2820302411,3158454273),o(3259730800,3505952657),o(3345764771,106217008),o(3516065817,3606008344),o(3600352804,1432725776),o(4094571909,1467031594),o(275423344,851169720),o(430227734,3100823752),o(506948616,1363258195),o(659060556,3750685593),o(883997877,3785050280),o(958139571,3318307427),o(1322822218,3812723403),o(1537002063,2003034995),o(1747873779,3602036899),o(1955562222,1575990012),o(2024104815,1125592928),o(2227730452,2716904306),o(2361852424,442776044),o(2428436474,593698344),o(2756734187,3733110249),o(3204031479,2999351573),o(3329325298,3815920427),o(3391569614,3928383900),o(3515267271,566280711),o(3940187606,3454069534),o(4118630271,4000239992),o(116418474,1914138554),o(174292421,2731055270),o(289380356,3203993006),o(460393269,320620315),o(685471733,587496836),o(852142971,1086792851),o(1017036298,365543100),o(1126000580,2618297676),o(1288033470,3409855158),o(1501505948,4234509866),o(1607167915,987167468),o(1816402316,1246189591)],d=[];(function(){for(var p=0;p<80;p++)d[p]=o()})();var u=c.SHA512=t.extend({_doReset:function(){this._hash=new n.init([new s.init(1779033703,4089235720),new s.init(3144134277,2227873595),new s.init(1013904242,4271175723),new s.init(2773480762,1595750129),new s.init(1359893119,2917565137),new s.init(2600822924,725511199),new s.init(528734635,4215389547),new s.init(1541459225,327033209)])},_doProcessBlock:function(p,h){for(var f=this._hash.words,g=f[0],b=f[1],S=f[2],v=f[3],R=f[4],_=f[5],y=f[6],w=f[7],A=g.high,E=g.low,C=b.high,P=b.low,M=S.high,x=S.low,K=v.high,Q=v.low,G=R.high,W=R.low,Z=_.high,te=_.low,Se=y.high,L=y.low,O=w.high,N=w.low,V=A,he=E,xe=C,q=P,Re=M,Ve=x,Ee=K,Ne=Q,ve=G,we=W,pe=Z,Oe=te,Te=Se,Ye=L,ht=O,le=N,ne=0;ne<80;ne++){var ie,Ae,Fe=d[ne];if(ne<16)Ae=Fe.high=0|p[h+2*ne],ie=Fe.low=0|p[h+2*ne+1];else{var me=d[ne-15],qe=me.high,Y=me.low,Ue=(qe>>>1|Y<<31)^(qe>>>8|Y<<24)^qe>>>7,pt=(Y>>>1|qe<<31)^(Y>>>8|qe<<24)^(Y>>>7|qe<<25),Be=d[ne-2],Tt=Be.high,Ot=Be.low,Ct=(Tt>>>19|Ot<<13)^(Tt<<3|Ot>>>29)^Tt>>>6,ei=(Ot>>>19|Tt<<13)^(Ot<<3|Tt>>>29)^(Ot>>>6|Tt<<26),Ui=d[ne-7],rs=Ui.high,yl=Ui.low,eo=d[ne-16],Rl=eo.high,to=eo.low;Ae=(Ae=(Ae=Ue+rs+((ie=pt+yl)>>>0<pt>>>0?1:0))+Ct+((ie+=ei)>>>0<ei>>>0?1:0))+Rl+((ie+=to)>>>0<to>>>0?1:0),Fe.high=Ae,Fe.low=ie}var hi,Al=ve&pe^~ve&Te,io=we&Oe^~we&Ye,wl=V&xe^V&Re^xe&Re,_l=he&q^he&Ve^q&Ve,Il=(V>>>28|he<<4)^(V<<30|he>>>2)^(V<<25|he>>>7),so=(he>>>28|V<<4)^(he<<30|V>>>2)^(he<<25|V>>>7),El=(ve>>>14|we<<18)^(ve>>>18|we<<14)^(ve<<23|we>>>9),Tl=(we>>>14|ve<<18)^(we>>>18|ve<<14)^(we<<23|ve>>>9),ro=l[ne],Cl=ro.high,ao=ro.low,Bi=ht+El+((hi=le+Tl)>>>0<le>>>0?1:0),no=so+_l;ht=Te,le=Ye,Te=pe,Ye=Oe,pe=ve,Oe=we,ve=Ee+(Bi=(Bi=(Bi=Bi+Al+((hi+=io)>>>0<io>>>0?1:0))+Cl+((hi+=ao)>>>0<ao>>>0?1:0))+Ae+((hi+=ie)>>>0<ie>>>0?1:0))+((we=Ne+hi|0)>>>0<Ne>>>0?1:0)|0,Ee=Re,Ne=Ve,Re=xe,Ve=q,xe=V,q=he,V=Bi+(Il+wl+(no>>>0<so>>>0?1:0))+((he=hi+no|0)>>>0<hi>>>0?1:0)|0}E=g.low=E+he,g.high=A+V+(E>>>0<he>>>0?1:0),P=b.low=P+q,b.high=C+xe+(P>>>0<q>>>0?1:0),x=S.low=x+Ve,S.high=M+Re+(x>>>0<Ve>>>0?1:0),Q=v.low=Q+Ne,v.high=K+Ee+(Q>>>0<Ne>>>0?1:0),W=R.low=W+we,R.high=G+ve+(W>>>0<we>>>0?1:0),te=_.low=te+Oe,_.high=Z+pe+(te>>>0<Oe>>>0?1:0),L=y.low=L+Ye,y.high=Se+Te+(L>>>0<Ye>>>0?1:0),N=w.low=N+le,w.high=O+ht+(N>>>0<le>>>0?1:0)},_doFinalize:function(){var p=this._data,h=p.words,f=8*this._nDataBytes,g=8*p.sigBytes;return h[g>>>5]|=128<<24-g%32,h[30+(g+128>>>10<<5)]=Math.floor(f/4294967296),h[31+(g+128>>>10<<5)]=f,p.sigBytes=4*h.length,this._process(),this._hash.toX32()},clone:function(){var p=t.clone.call(this);return p._hash=this._hash.clone(),p},blockSize:32});e.SHA512=t._createHelper(u),e.HmacSHA512=t._createHmacHelper(u)}(),r.SHA512}(fe(),ji())}(Fr)),Fr.exports}var $r,yo={exports:{}},Wr,zr={exports:{}};function Ro(){return Wr||(Wr=1,function(a){a.exports=function(r){return function(e){var t=r,i=t.lib,s=i.WordArray,n=i.Hasher,c=t.x64.Word,o=t.algo,l=[],d=[],u=[];(function(){for(var f=1,g=0,b=0;b<24;b++){l[f+5*g]=(b+1)*(b+2)/2%64;var S=(2*f+3*g)%5;f=g%5,g=S}for(f=0;f<5;f++)for(g=0;g<5;g++)d[f+5*g]=g+(2*f+3*g)%5*5;for(var v=1,R=0;R<24;R++){for(var _=0,y=0,w=0;w<7;w++){if(1&v){var A=(1<<w)-1;A<32?y^=1<<A:_^=1<<A-32}128&v?v=v<<1^113:v<<=1}u[R]=c.create(_,y)}})();var p=[];(function(){for(var f=0;f<25;f++)p[f]=c.create()})();var h=o.SHA3=n.extend({cfg:n.cfg.extend({outputLength:512}),_doReset:function(){for(var f=this._state=[],g=0;g<25;g++)f[g]=new c.init;this.blockSize=(1600-2*this.cfg.outputLength)/32},_doProcessBlock:function(f,g){for(var b=this._state,S=this.blockSize/2,v=0;v<S;v++){var R=f[g+2*v],_=f[g+2*v+1];R=16711935&(R<<8|R>>>24)|4278255360&(R<<24|R>>>8),_=16711935&(_<<8|_>>>24)|4278255360&(_<<24|_>>>8),(N=b[v]).high^=_,N.low^=R}for(var y=0;y<24;y++){for(var w=0;w<5;w++){for(var A=0,E=0,C=0;C<5;C++)A^=(N=b[w+5*C]).high,E^=N.low;var P=p[w];P.high=A,P.low=E}for(w=0;w<5;w++){var M=p[(w+4)%5],x=p[(w+1)%5],K=x.high,Q=x.low;for(A=M.high^(K<<1|Q>>>31),E=M.low^(Q<<1|K>>>31),C=0;C<5;C++)(N=b[w+5*C]).high^=A,N.low^=E}for(var G=1;G<25;G++){var W=(N=b[G]).high,Z=N.low,te=l[G];te<32?(A=W<<te|Z>>>32-te,E=Z<<te|W>>>32-te):(A=Z<<te-32|W>>>64-te,E=W<<te-32|Z>>>64-te);var Se=p[d[G]];Se.high=A,Se.low=E}var L=p[0],O=b[0];for(L.high=O.high,L.low=O.low,w=0;w<5;w++)for(C=0;C<5;C++){var N=b[G=w+5*C],V=p[G],he=p[(w+1)%5+5*C],xe=p[(w+2)%5+5*C];N.high=V.high^~he.high&xe.high,N.low=V.low^~he.low&xe.low}N=b[0];var q=u[y];N.high^=q.high,N.low^=q.low}},_doFinalize:function(){var f=this._data,g=f.words;this._nDataBytes;var b=8*f.sigBytes,S=32*this.blockSize;g[b>>>5]|=1<<24-b%32,g[(e.ceil((b+1)/S)*S>>>5)-1]|=128,f.sigBytes=4*g.length,this._process();for(var v=this._state,R=this.cfg.outputLength/8,_=R/8,y=[],w=0;w<_;w++){var A=v[w],E=A.high,C=A.low;E=16711935&(E<<8|E>>>24)|4278255360&(E<<24|E>>>8),C=16711935&(C<<8|C>>>24)|4278255360&(C<<24|C>>>8),y.push(C),y.push(E)}return new s.init(y,R)},clone:function(){for(var f=n.clone.call(this),g=f._state=this._state.slice(0),b=0;b<25;b++)g[b]=g[b].clone();return f}});t.SHA3=n._createHelper(h),t.HmacSHA3=n._createHmacHelper(h)}(Math),r.SHA3}(fe(),ji())}(zr)),zr.exports}var Kr,Ao={exports:{}},Jr,qr={exports:{}};function ms(){return Jr||(Jr=1,function(a){a.exports=function(r){var e,t,i;t=(e=r).lib.Base,i=e.enc.Utf8,e.algo.HMAC=t.extend({init:function(s,n){s=this._hasher=new s.init,typeof n=="string"&&(n=i.parse(n));var c=s.blockSize,o=4*c;n.sigBytes>o&&(n=s.finalize(n)),n.clamp();for(var l=this._oKey=n.clone(),d=this._iKey=n.clone(),u=l.words,p=d.words,h=0;h<c;h++)u[h]^=1549556828,p[h]^=909522486;l.sigBytes=d.sigBytes=o,this.reset()},reset:function(){var s=this._hasher;s.reset(),s.update(this._iKey)},update:function(s){return this._hasher.update(s),this},finalize:function(s){var n=this._hasher,c=n.finalize(s);return n.reset(),n.finalize(this._oKey.clone().concat(c))}})}(fe())}(qr)),qr.exports}var Gr,wo={exports:{}},Xr,Qr={exports:{}};function Kt(){return Xr||(Xr=1,function(a){a.exports=function(r){return t=(e=r).lib,i=t.Base,s=t.WordArray,n=e.algo,c=n.MD5,o=n.EvpKDF=i.extend({cfg:i.extend({keySize:4,hasher:c,iterations:1}),init:function(l){this.cfg=this.cfg.extend(l)},compute:function(l,d){for(var u,p=this.cfg,h=p.hasher.create(),f=s.create(),g=f.words,b=p.keySize,S=p.iterations;g.length<b;){u&&h.update(u),u=h.update(l).finalize(d),h.reset();for(var v=1;v<S;v++)u=h.finalize(u),h.reset();f.concat(u)}return f.sigBytes=4*b,f}}),e.EvpKDF=function(l,d,u){return o.create(u).compute(l,d)},r.EvpKDF;var e,t,i,s,n,c,o}(fe(),Or(),ms())}(Qr)),Qr.exports}var Yr,Zr={exports:{}};function Xe(){return Yr||(Yr=1,function(a){a.exports=function(r){r.lib.Cipher||function(e){var t=r,i=t.lib,s=i.Base,n=i.WordArray,c=i.BufferedBlockAlgorithm,o=t.enc;o.Utf8;var l=o.Base64,d=t.algo.EvpKDF,u=i.Cipher=c.extend({cfg:s.extend(),createEncryptor:function(y,w){return this.create(this._ENC_XFORM_MODE,y,w)},createDecryptor:function(y,w){return this.create(this._DEC_XFORM_MODE,y,w)},init:function(y,w,A){this.cfg=this.cfg.extend(A),this._xformMode=y,this._key=w,this.reset()},reset:function(){c.reset.call(this),this._doReset()},process:function(y){return this._append(y),this._process()},finalize:function(y){return y&&this._append(y),this._doFinalize()},keySize:4,ivSize:4,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,_createHelper:function(){function y(w){return typeof w=="string"?_:v}return function(w){return{encrypt:function(A,E,C){return y(E).encrypt(w,A,E,C)},decrypt:function(A,E,C){return y(E).decrypt(w,A,E,C)}}}}()});i.StreamCipher=u.extend({_doFinalize:function(){return this._process(!0)},blockSize:1});var p=t.mode={},h=i.BlockCipherMode=s.extend({createEncryptor:function(y,w){return this.Encryptor.create(y,w)},createDecryptor:function(y,w){return this.Decryptor.create(y,w)},init:function(y,w){this._cipher=y,this._iv=w}}),f=p.CBC=function(){var y=h.extend();function w(A,E,C){var P,M=this._iv;M?(P=M,this._iv=e):P=this._prevBlock;for(var x=0;x<C;x++)A[E+x]^=P[x]}return y.Encryptor=y.extend({processBlock:function(A,E){var C=this._cipher,P=C.blockSize;w.call(this,A,E,P),C.encryptBlock(A,E),this._prevBlock=A.slice(E,E+P)}}),y.Decryptor=y.extend({processBlock:function(A,E){var C=this._cipher,P=C.blockSize,M=A.slice(E,E+P);C.decryptBlock(A,E),w.call(this,A,E,P),this._prevBlock=M}}),y}(),g=(t.pad={}).Pkcs7={pad:function(y,w){for(var A=4*w,E=A-y.sigBytes%A,C=E<<24|E<<16|E<<8|E,P=[],M=0;M<E;M+=4)P.push(C);var x=n.create(P,E);y.concat(x)},unpad:function(y){var w=255&y.words[y.sigBytes-1>>>2];y.sigBytes-=w}};i.BlockCipher=u.extend({cfg:u.cfg.extend({mode:f,padding:g}),reset:function(){var y;u.reset.call(this);var w=this.cfg,A=w.iv,E=w.mode;this._xformMode==this._ENC_XFORM_MODE?y=E.createEncryptor:(y=E.createDecryptor,this._minBufferSize=1),this._mode&&this._mode.__creator==y?this._mode.init(this,A&&A.words):(this._mode=y.call(E,this,A&&A.words),this._mode.__creator=y)},_doProcessBlock:function(y,w){this._mode.processBlock(y,w)},_doFinalize:function(){var y,w=this.cfg.padding;return this._xformMode==this._ENC_XFORM_MODE?(w.pad(this._data,this.blockSize),y=this._process(!0)):(y=this._process(!0),w.unpad(y)),y},blockSize:4});var b=i.CipherParams=s.extend({init:function(y){this.mixIn(y)},toString:function(y){return(y||this.formatter).stringify(this)}}),S=(t.format={}).OpenSSL={stringify:function(y){var w=y.ciphertext,A=y.salt;return(A?n.create([1398893684,1701076831]).concat(A).concat(w):w).toString(l)},parse:function(y){var w,A=l.parse(y),E=A.words;return E[0]==1398893684&&E[1]==1701076831&&(w=n.create(E.slice(2,4)),E.splice(0,4),A.sigBytes-=16),b.create({ciphertext:A,salt:w})}},v=i.SerializableCipher=s.extend({cfg:s.extend({format:S}),encrypt:function(y,w,A,E){E=this.cfg.extend(E);var C=y.createEncryptor(A,E),P=C.finalize(w),M=C.cfg;return b.create({ciphertext:P,key:A,iv:M.iv,algorithm:y,mode:M.mode,padding:M.padding,blockSize:y.blockSize,formatter:E.format})},decrypt:function(y,w,A,E){return E=this.cfg.extend(E),w=this._parse(w,E.format),y.createDecryptor(A,E).finalize(w.ciphertext)},_parse:function(y,w){return typeof y=="string"?w.parse(y,this):y}}),R=(t.kdf={}).OpenSSL={execute:function(y,w,A,E,C){if(E||(E=n.random(8)),C)P=d.create({keySize:w+A,hasher:C}).compute(y,E);else var P=d.create({keySize:w+A}).compute(y,E);var M=n.create(P.words.slice(w),4*A);return P.sigBytes=4*w,b.create({key:P,iv:M,salt:E})}},_=i.PasswordBasedCipher=v.extend({cfg:v.cfg.extend({kdf:R}),encrypt:function(y,w,A,E){var C=(E=this.cfg.extend(E)).kdf.execute(A,y.keySize,y.ivSize,E.salt,E.hasher);E.iv=C.iv;var P=v.encrypt.call(this,y,w,C.key,E);return P.mixIn(C),P},decrypt:function(y,w,A,E){E=this.cfg.extend(E),w=this._parse(w,E.format);var C=E.kdf.execute(A,y.keySize,y.ivSize,w.salt,E.hasher);return E.iv=C.iv,v.decrypt.call(this,y,w,C.key,E)}})}()}(fe(),Kt())}(Zr)),Zr.exports}var ea,ta={exports:{}};function _o(){return ea||(ea=1,function(a){a.exports=function(r){return r.mode.CFB=function(){var e=r.lib.BlockCipherMode.extend();function t(i,s,n,c){var o,l=this._iv;l?(o=l.slice(0),this._iv=void 0):o=this._prevBlock,c.encryptBlock(o,0);for(var d=0;d<n;d++)i[s+d]^=o[d]}return e.Encryptor=e.extend({processBlock:function(i,s){var n=this._cipher,c=n.blockSize;t.call(this,i,s,c,n),this._prevBlock=i.slice(s,s+c)}}),e.Decryptor=e.extend({processBlock:function(i,s){var n=this._cipher,c=n.blockSize,o=i.slice(s,s+c);t.call(this,i,s,c,n),this._prevBlock=o}}),e}(),r.mode.CFB}(fe(),Xe())}(ta)),ta.exports}var ia,sa={exports:{}};function Io(){return ia||(ia=1,function(a){a.exports=function(r){return r.mode.CTR=(e=r.lib.BlockCipherMode.extend(),t=e.Encryptor=e.extend({processBlock:function(i,s){var n=this._cipher,c=n.blockSize,o=this._iv,l=this._counter;o&&(l=this._counter=o.slice(0),this._iv=void 0);var d=l.slice(0);n.encryptBlock(d,0),l[c-1]=l[c-1]+1|0;for(var u=0;u<c;u++)i[s+u]^=d[u]}}),e.Decryptor=t,e),r.mode.CTR;var e,t}(fe(),Xe())}(sa)),sa.exports}var ra,aa={exports:{}};function Eo(){return ra||(ra=1,function(a){a.exports=function(r){return r.mode.CTRGladman=function(){var e=r.lib.BlockCipherMode.extend();function t(n){if(255&~(n>>24))n+=1<<24;else{var c=n>>16&255,o=n>>8&255,l=255&n;c===255?(c=0,o===255?(o=0,l===255?l=0:++l):++o):++c,n=0,n+=c<<16,n+=o<<8,n+=l}return n}function i(n){return(n[0]=t(n[0]))===0&&(n[1]=t(n[1])),n}var s=e.Encryptor=e.extend({processBlock:function(n,c){var o=this._cipher,l=o.blockSize,d=this._iv,u=this._counter;d&&(u=this._counter=d.slice(0),this._iv=void 0),i(u);var p=u.slice(0);o.encryptBlock(p,0);for(var h=0;h<l;h++)n[c+h]^=p[h]}});return e.Decryptor=s,e}(),r.mode.CTRGladman}(fe(),Xe())}(aa)),aa.exports}var na,oa={exports:{}};function To(){return na||(na=1,function(a){a.exports=function(r){return r.mode.OFB=(e=r.lib.BlockCipherMode.extend(),t=e.Encryptor=e.extend({processBlock:function(i,s){var n=this._cipher,c=n.blockSize,o=this._iv,l=this._keystream;o&&(l=this._keystream=o.slice(0),this._iv=void 0),n.encryptBlock(l,0);for(var d=0;d<c;d++)i[s+d]^=l[d]}}),e.Decryptor=t,e),r.mode.OFB;var e,t}(fe(),Xe())}(oa)),oa.exports}var ca,Co={exports:{}},la,ko={exports:{}},da,Po={exports:{}},ua,Do={exports:{}},ha,Mo={exports:{}},pa,Lo={exports:{}},ma,No={exports:{}},ga,xo={exports:{}},fa,ba={exports:{}};function Oo(){return fa||(fa=1,function(a){a.exports=function(r){return function(){var e=r,t=e.lib,i=t.WordArray,s=t.BlockCipher,n=e.algo,c=[57,49,41,33,25,17,9,1,58,50,42,34,26,18,10,2,59,51,43,35,27,19,11,3,60,52,44,36,63,55,47,39,31,23,15,7,62,54,46,38,30,22,14,6,61,53,45,37,29,21,13,5,28,20,12,4],o=[14,17,11,24,1,5,3,28,15,6,21,10,23,19,12,4,26,8,16,7,27,20,13,2,41,52,31,37,47,55,30,40,51,45,33,48,44,49,39,56,34,53,46,42,50,36,29,32],l=[1,2,4,6,8,10,12,14,15,17,19,21,23,25,27,28],d=[{0:8421888,268435456:32768,536870912:8421378,805306368:2,1073741824:512,1342177280:8421890,1610612736:8389122,1879048192:8388608,2147483648:514,2415919104:8389120,2684354560:33280,2952790016:8421376,3221225472:32770,3489660928:8388610,3758096384:0,4026531840:33282,134217728:0,402653184:8421890,671088640:33282,939524096:32768,1207959552:8421888,1476395008:512,1744830464:8421378,2013265920:2,2281701376:8389120,2550136832:33280,2818572288:8421376,3087007744:8389122,3355443200:8388610,3623878656:32770,3892314112:514,4160749568:8388608,1:32768,268435457:2,536870913:8421888,805306369:8388608,1073741825:8421378,1342177281:33280,1610612737:512,1879048193:8389122,2147483649:8421890,2415919105:8421376,2684354561:8388610,2952790017:33282,3221225473:514,3489660929:8389120,3758096385:32770,4026531841:0,134217729:8421890,402653185:8421376,671088641:8388608,939524097:512,1207959553:32768,1476395009:8388610,1744830465:2,2013265921:33282,2281701377:32770,2550136833:8389122,2818572289:514,3087007745:8421888,3355443201:8389120,3623878657:0,3892314113:33280,4160749569:8421378},{0:1074282512,16777216:16384,33554432:524288,50331648:1074266128,67108864:1073741840,83886080:1074282496,100663296:1073758208,117440512:16,134217728:540672,150994944:1073758224,167772160:1073741824,184549376:540688,201326592:524304,218103808:0,234881024:16400,251658240:1074266112,8388608:1073758208,25165824:540688,41943040:16,58720256:1073758224,75497472:1074282512,92274688:1073741824,109051904:524288,125829120:1074266128,142606336:524304,159383552:0,176160768:16384,192937984:1074266112,209715200:1073741840,226492416:540672,243269632:1074282496,260046848:16400,268435456:0,285212672:1074266128,301989888:1073758224,318767104:1074282496,335544320:1074266112,352321536:16,369098752:540688,385875968:16384,402653184:16400,419430400:524288,436207616:524304,452984832:1073741840,469762048:540672,486539264:1073758208,503316480:1073741824,520093696:1074282512,276824064:540688,293601280:524288,310378496:1074266112,327155712:16384,343932928:1073758208,360710144:1074282512,377487360:16,394264576:1073741824,411041792:1074282496,427819008:1073741840,444596224:1073758224,461373440:524304,478150656:0,494927872:16400,511705088:1074266128,528482304:540672},{0:260,1048576:0,2097152:67109120,3145728:65796,4194304:65540,5242880:67108868,6291456:67174660,7340032:67174400,8388608:67108864,9437184:67174656,10485760:65792,11534336:67174404,12582912:67109124,13631488:65536,14680064:4,15728640:256,524288:67174656,1572864:67174404,2621440:0,3670016:67109120,4718592:67108868,5767168:65536,6815744:65540,7864320:260,8912896:4,9961472:256,11010048:67174400,12058624:65796,13107200:65792,14155776:67109124,15204352:67174660,16252928:67108864,16777216:67174656,17825792:65540,18874368:65536,19922944:67109120,20971520:256,22020096:67174660,23068672:67108868,24117248:0,25165824:67109124,26214400:67108864,27262976:4,28311552:65792,29360128:67174400,30408704:260,31457280:65796,32505856:67174404,17301504:67108864,18350080:260,19398656:67174656,20447232:0,21495808:65540,22544384:67109120,23592960:256,24641536:67174404,25690112:65536,26738688:67174660,27787264:65796,28835840:67108868,29884416:67109124,30932992:67174400,31981568:4,33030144:65792},{0:2151682048,65536:2147487808,131072:4198464,196608:2151677952,262144:0,327680:4198400,393216:2147483712,458752:4194368,524288:2147483648,589824:4194304,655360:64,720896:2147487744,786432:2151678016,851968:4160,917504:4096,983040:2151682112,32768:2147487808,98304:64,163840:2151678016,229376:2147487744,294912:4198400,360448:2151682112,425984:0,491520:2151677952,557056:4096,622592:2151682048,688128:4194304,753664:4160,819200:2147483648,884736:4194368,950272:4198464,1015808:2147483712,1048576:4194368,1114112:4198400,1179648:2147483712,1245184:0,1310720:4160,1376256:2151678016,1441792:2151682048,1507328:2147487808,1572864:2151682112,1638400:2147483648,1703936:2151677952,1769472:4198464,1835008:2147487744,1900544:4194304,1966080:64,2031616:4096,1081344:2151677952,1146880:2151682112,1212416:0,1277952:4198400,1343488:4194368,1409024:2147483648,1474560:2147487808,1540096:64,1605632:2147483712,1671168:4096,1736704:2147487744,1802240:2151678016,1867776:4160,1933312:2151682048,1998848:4194304,2064384:4198464},{0:128,4096:17039360,8192:262144,12288:536870912,16384:537133184,20480:16777344,24576:553648256,28672:262272,32768:16777216,36864:537133056,40960:536871040,45056:553910400,49152:553910272,53248:0,57344:17039488,61440:553648128,2048:17039488,6144:553648256,10240:128,14336:17039360,18432:262144,22528:537133184,26624:553910272,30720:536870912,34816:537133056,38912:0,43008:553910400,47104:16777344,51200:536871040,55296:553648128,59392:16777216,63488:262272,65536:262144,69632:128,73728:536870912,77824:553648256,81920:16777344,86016:553910272,90112:537133184,94208:16777216,98304:553910400,102400:553648128,106496:17039360,110592:537133056,114688:262272,118784:536871040,122880:0,126976:17039488,67584:553648256,71680:16777216,75776:17039360,79872:537133184,83968:536870912,88064:17039488,92160:128,96256:553910272,100352:262272,104448:553910400,108544:0,112640:553648128,116736:16777344,120832:262144,124928:537133056,129024:536871040},{0:268435464,256:8192,512:270532608,768:270540808,1024:268443648,1280:2097152,1536:2097160,1792:268435456,2048:0,2304:268443656,2560:2105344,2816:8,3072:270532616,3328:2105352,3584:8200,3840:270540800,128:270532608,384:270540808,640:8,896:2097152,1152:2105352,1408:268435464,1664:268443648,1920:8200,2176:2097160,2432:8192,2688:268443656,2944:270532616,3200:0,3456:270540800,3712:2105344,3968:268435456,4096:268443648,4352:270532616,4608:270540808,4864:8200,5120:2097152,5376:268435456,5632:268435464,5888:2105344,6144:2105352,6400:0,6656:8,6912:270532608,7168:8192,7424:268443656,7680:270540800,7936:2097160,4224:8,4480:2105344,4736:2097152,4992:268435464,5248:268443648,5504:8200,5760:270540808,6016:270532608,6272:270540800,6528:270532616,6784:8192,7040:2105352,7296:2097160,7552:0,7808:268435456,8064:268443656},{0:1048576,16:33555457,32:1024,48:1049601,64:34604033,80:0,96:1,112:34603009,128:33555456,144:1048577,160:33554433,176:34604032,192:34603008,208:1025,224:1049600,240:33554432,8:34603009,24:0,40:33555457,56:34604032,72:1048576,88:33554433,104:33554432,120:1025,136:1049601,152:33555456,168:34603008,184:1048577,200:1024,216:34604033,232:1,248:1049600,256:33554432,272:1048576,288:33555457,304:34603009,320:1048577,336:33555456,352:34604032,368:1049601,384:1025,400:34604033,416:1049600,432:1,448:0,464:34603008,480:33554433,496:1024,264:1049600,280:33555457,296:34603009,312:1,328:33554432,344:1048576,360:1025,376:34604032,392:33554433,408:34603008,424:0,440:34604033,456:1049601,472:1024,488:33555456,504:1048577},{0:134219808,1:131072,2:134217728,3:32,4:131104,5:134350880,6:134350848,7:2048,8:134348800,9:134219776,10:133120,11:134348832,12:2080,13:0,14:134217760,15:133152,2147483648:2048,2147483649:134350880,2147483650:134219808,2147483651:134217728,2147483652:134348800,2147483653:133120,2147483654:133152,2147483655:32,2147483656:134217760,2147483657:2080,2147483658:131104,2147483659:134350848,2147483660:0,2147483661:134348832,2147483662:134219776,2147483663:131072,16:133152,17:134350848,18:32,19:2048,20:134219776,21:134217760,22:134348832,23:131072,24:0,25:131104,26:134348800,27:134219808,28:134350880,29:133120,30:2080,31:134217728,2147483664:131072,2147483665:2048,2147483666:134348832,2147483667:133152,2147483668:32,2147483669:134348800,2147483670:134217728,2147483671:134219808,2147483672:134350880,2147483673:134217760,2147483674:134219776,2147483675:0,2147483676:133120,2147483677:2080,2147483678:131104,2147483679:134350848}],u=[4160749569,528482304,33030144,2064384,129024,8064,504,2147483679],p=n.DES=s.extend({_doReset:function(){for(var b=this._key.words,S=[],v=0;v<56;v++){var R=c[v]-1;S[v]=b[R>>>5]>>>31-R%32&1}for(var _=this._subKeys=[],y=0;y<16;y++){var w=_[y]=[],A=l[y];for(v=0;v<24;v++)w[v/6|0]|=S[(o[v]-1+A)%28]<<31-v%6,w[4+(v/6|0)]|=S[28+(o[v+24]-1+A)%28]<<31-v%6;for(w[0]=w[0]<<1|w[0]>>>31,v=1;v<7;v++)w[v]=w[v]>>>4*(v-1)+3;w[7]=w[7]<<5|w[7]>>>27}var E=this._invSubKeys=[];for(v=0;v<16;v++)E[v]=_[15-v]},encryptBlock:function(b,S){this._doCryptBlock(b,S,this._subKeys)},decryptBlock:function(b,S){this._doCryptBlock(b,S,this._invSubKeys)},_doCryptBlock:function(b,S,v){this._lBlock=b[S],this._rBlock=b[S+1],h.call(this,4,252645135),h.call(this,16,65535),f.call(this,2,858993459),f.call(this,8,16711935),h.call(this,1,1431655765);for(var R=0;R<16;R++){for(var _=v[R],y=this._lBlock,w=this._rBlock,A=0,E=0;E<8;E++)A|=d[E][((w^_[E])&u[E])>>>0];this._lBlock=w,this._rBlock=y^A}var C=this._lBlock;this._lBlock=this._rBlock,this._rBlock=C,h.call(this,1,1431655765),f.call(this,8,16711935),f.call(this,2,858993459),h.call(this,16,65535),h.call(this,4,252645135),b[S]=this._lBlock,b[S+1]=this._rBlock},keySize:2,ivSize:2,blockSize:2});function h(b,S){var v=(this._lBlock>>>b^this._rBlock)&S;this._rBlock^=v,this._lBlock^=v<<b}function f(b,S){var v=(this._rBlock>>>b^this._lBlock)&S;this._lBlock^=v,this._rBlock^=v<<b}e.DES=s._createHelper(p);var g=n.TripleDES=s.extend({_doReset:function(){var b=this._key.words;if(b.length!==2&&b.length!==4&&b.length<6)throw new Error("Invalid key length - 3DES requires the key length to be 64, 128, 192 or >192.");var S=b.slice(0,2),v=b.length<4?b.slice(0,2):b.slice(2,4),R=b.length<6?b.slice(0,2):b.slice(4,6);this._des1=p.createEncryptor(i.create(S)),this._des2=p.createEncryptor(i.create(v)),this._des3=p.createEncryptor(i.create(R))},encryptBlock:function(b,S){this._des1.encryptBlock(b,S),this._des2.decryptBlock(b,S),this._des3.encryptBlock(b,S)},decryptBlock:function(b,S){this._des3.decryptBlock(b,S),this._des2.encryptBlock(b,S),this._des1.decryptBlock(b,S)},keySize:6,ivSize:2,blockSize:2});e.TripleDES=s._createHelper(g)}(),r.TripleDES}(fe(),si(),ri(),Kt(),Xe())}(ba)),ba.exports}var Sa,Vo={exports:{}},va,Uo={exports:{}},ya,Bo={exports:{}},Ra,Aa={exports:{}};function Ho(){return Ra||(Ra=1,function(a){a.exports=function(r){return function(){var e=r,t=e.lib.BlockCipher,i=e.algo;const s=16,n=[608135816,2242054355,320440878,57701188,2752067618,698298832,137296536,3964562569,1160258022,953160567,3193202383,887688300,3232508343,3380367581,1065670069,3041331479,2450970073,2306472731],c=[[3509652390,2564797868,805139163,3491422135,3101798381,1780907670,3128725573,4046225305,614570311,3012652279,134345442,2240740374,1667834072,1901547113,2757295779,4103290238,227898511,1921955416,1904987480,2182433518,2069144605,3260701109,2620446009,720527379,3318853667,677414384,3393288472,3101374703,2390351024,1614419982,1822297739,2954791486,3608508353,3174124327,2024746970,1432378464,3864339955,2857741204,1464375394,1676153920,1439316330,715854006,3033291828,289532110,2706671279,2087905683,3018724369,1668267050,732546397,1947742710,3462151702,2609353502,2950085171,1814351708,2050118529,680887927,999245976,1800124847,3300911131,1713906067,1641548236,4213287313,1216130144,1575780402,4018429277,3917837745,3693486850,3949271944,596196993,3549867205,258830323,2213823033,772490370,2760122372,1774776394,2652871518,566650946,4142492826,1728879713,2882767088,1783734482,3629395816,2517608232,2874225571,1861159788,326777828,3124490320,2130389656,2716951837,967770486,1724537150,2185432712,2364442137,1164943284,2105845187,998989502,3765401048,2244026483,1075463327,1455516326,1322494562,910128902,469688178,1117454909,936433444,3490320968,3675253459,1240580251,122909385,2157517691,634681816,4142456567,3825094682,3061402683,2540495037,79693498,3249098678,1084186820,1583128258,426386531,1761308591,1047286709,322548459,995290223,1845252383,2603652396,3431023940,2942221577,3202600964,3727903485,1712269319,422464435,3234572375,1170764815,3523960633,3117677531,1434042557,442511882,3600875718,1076654713,1738483198,4213154764,2393238008,3677496056,1014306527,4251020053,793779912,2902807211,842905082,4246964064,1395751752,1040244610,2656851899,3396308128,445077038,3742853595,3577915638,679411651,2892444358,2354009459,1767581616,3150600392,3791627101,3102740896,284835224,4246832056,1258075500,768725851,2589189241,3069724005,3532540348,1274779536,3789419226,2764799539,1660621633,3471099624,4011903706,913787905,3497959166,737222580,2514213453,2928710040,3937242737,1804850592,3499020752,2949064160,2386320175,2390070455,2415321851,4061277028,2290661394,2416832540,1336762016,1754252060,3520065937,3014181293,791618072,3188594551,3933548030,2332172193,3852520463,3043980520,413987798,3465142937,3030929376,4245938359,2093235073,3534596313,375366246,2157278981,2479649556,555357303,3870105701,2008414854,3344188149,4221384143,3956125452,2067696032,3594591187,2921233993,2428461,544322398,577241275,1471733935,610547355,4027169054,1432588573,1507829418,2025931657,3646575487,545086370,48609733,2200306550,1653985193,298326376,1316178497,3007786442,2064951626,458293330,2589141269,3591329599,3164325604,727753846,2179363840,146436021,1461446943,4069977195,705550613,3059967265,3887724982,4281599278,3313849956,1404054877,2845806497,146425753,1854211946],[1266315497,3048417604,3681880366,3289982499,290971e4,1235738493,2632868024,2414719590,3970600049,1771706367,1449415276,3266420449,422970021,1963543593,2690192192,3826793022,1062508698,1531092325,1804592342,2583117782,2714934279,4024971509,1294809318,4028980673,1289560198,2221992742,1669523910,35572830,157838143,1052438473,1016535060,1802137761,1753167236,1386275462,3080475397,2857371447,1040679964,2145300060,2390574316,1461121720,2956646967,4031777805,4028374788,33600511,2920084762,1018524850,629373528,3691585981,3515945977,2091462646,2486323059,586499841,988145025,935516892,3367335476,2599673255,2839830854,265290510,3972581182,2759138881,3795373465,1005194799,847297441,406762289,1314163512,1332590856,1866599683,4127851711,750260880,613907577,1450815602,3165620655,3734664991,3650291728,3012275730,3704569646,1427272223,778793252,1343938022,2676280711,2052605720,1946737175,3164576444,3914038668,3967478842,3682934266,1661551462,3294938066,4011595847,840292616,3712170807,616741398,312560963,711312465,1351876610,322626781,1910503582,271666773,2175563734,1594956187,70604529,3617834859,1007753275,1495573769,4069517037,2549218298,2663038764,504708206,2263041392,3941167025,2249088522,1514023603,1998579484,1312622330,694541497,2582060303,2151582166,1382467621,776784248,2618340202,3323268794,2497899128,2784771155,503983604,4076293799,907881277,423175695,432175456,1378068232,4145222326,3954048622,3938656102,3820766613,2793130115,2977904593,26017576,3274890735,3194772133,1700274565,1756076034,4006520079,3677328699,720338349,1533947780,354530856,688349552,3973924725,1637815568,332179504,3949051286,53804574,2852348879,3044236432,1282449977,3583942155,3416972820,4006381244,1617046695,2628476075,3002303598,1686838959,431878346,2686675385,1700445008,1080580658,1009431731,832498133,3223435511,2605976345,2271191193,2516031870,1648197032,4164389018,2548247927,300782431,375919233,238389289,3353747414,2531188641,2019080857,1475708069,455242339,2609103871,448939670,3451063019,1395535956,2413381860,1841049896,1491858159,885456874,4264095073,4001119347,1565136089,3898914787,1108368660,540939232,1173283510,2745871338,3681308437,4207628240,3343053890,4016749493,1699691293,1103962373,3625875870,2256883143,3830138730,1031889488,3479347698,1535977030,4236805024,3251091107,2132092099,1774941330,1199868427,1452454533,157007616,2904115357,342012276,595725824,1480756522,206960106,497939518,591360097,863170706,2375253569,3596610801,1814182875,2094937945,3421402208,1082520231,3463918190,2785509508,435703966,3908032597,1641649973,2842273706,3305899714,1510255612,2148256476,2655287854,3276092548,4258621189,236887753,3681803219,274041037,1734335097,3815195456,3317970021,1899903192,1026095262,4050517792,356393447,2410691914,3873677099,3682840055],[3913112168,2491498743,4132185628,2489919796,1091903735,1979897079,3170134830,3567386728,3557303409,857797738,1136121015,1342202287,507115054,2535736646,337727348,3213592640,1301675037,2528481711,1895095763,1721773893,3216771564,62756741,2142006736,835421444,2531993523,1442658625,3659876326,2882144922,676362277,1392781812,170690266,3921047035,1759253602,3611846912,1745797284,664899054,1329594018,3901205900,3045908486,2062866102,2865634940,3543621612,3464012697,1080764994,553557557,3656615353,3996768171,991055499,499776247,1265440854,648242737,3940784050,980351604,3713745714,1749149687,3396870395,4211799374,3640570775,1161844396,3125318951,1431517754,545492359,4268468663,3499529547,1437099964,2702547544,3433638243,2581715763,2787789398,1060185593,1593081372,2418618748,4260947970,69676912,2159744348,86519011,2512459080,3838209314,1220612927,3339683548,133810670,1090789135,1078426020,1569222167,845107691,3583754449,4072456591,1091646820,628848692,1613405280,3757631651,526609435,236106946,48312990,2942717905,3402727701,1797494240,859738849,992217954,4005476642,2243076622,3870952857,3732016268,765654824,3490871365,2511836413,1685915746,3888969200,1414112111,2273134842,3281911079,4080962846,172450625,2569994100,980381355,4109958455,2819808352,2716589560,2568741196,3681446669,3329971472,1835478071,660984891,3704678404,4045999559,3422617507,3040415634,1762651403,1719377915,3470491036,2693910283,3642056355,3138596744,1364962596,2073328063,1983633131,926494387,3423689081,2150032023,4096667949,1749200295,3328846651,309677260,2016342300,1779581495,3079819751,111262694,1274766160,443224088,298511866,1025883608,3806446537,1145181785,168956806,3641502830,3584813610,1689216846,3666258015,3200248200,1692713982,2646376535,4042768518,1618508792,1610833997,3523052358,4130873264,2001055236,3610705100,2202168115,4028541809,2961195399,1006657119,2006996926,3186142756,1430667929,3210227297,1314452623,4074634658,4101304120,2273951170,1399257539,3367210612,3027628629,1190975929,2062231137,2333990788,2221543033,2438960610,1181637006,548689776,2362791313,3372408396,3104550113,3145860560,296247880,1970579870,3078560182,3769228297,1714227617,3291629107,3898220290,166772364,1251581989,493813264,448347421,195405023,2709975567,677966185,3703036547,1463355134,2715995803,1338867538,1343315457,2802222074,2684532164,233230375,2599980071,2000651841,3277868038,1638401717,4028070440,3237316320,6314154,819756386,300326615,590932579,1405279636,3267499572,3150704214,2428286686,3959192993,3461946742,1862657033,1266418056,963775037,2089974820,2263052895,1917689273,448879540,3550394620,3981727096,150775221,3627908307,1303187396,508620638,2975983352,2726630617,1817252668,1876281319,1457606340,908771278,3720792119,3617206836,2455994898,1729034894,1080033504],[976866871,3556439503,2881648439,1522871579,1555064734,1336096578,3548522304,2579274686,3574697629,3205460757,3593280638,3338716283,3079412587,564236357,2993598910,1781952180,1464380207,3163844217,3332601554,1699332808,1393555694,1183702653,3581086237,1288719814,691649499,2847557200,2895455976,3193889540,2717570544,1781354906,1676643554,2592534050,3230253752,1126444790,2770207658,2633158820,2210423226,2615765581,2414155088,3127139286,673620729,2805611233,1269405062,4015350505,3341807571,4149409754,1057255273,2012875353,2162469141,2276492801,2601117357,993977747,3918593370,2654263191,753973209,36408145,2530585658,25011837,3520020182,2088578344,530523599,2918365339,1524020338,1518925132,3760827505,3759777254,1202760957,3985898139,3906192525,674977740,4174734889,2031300136,2019492241,3983892565,4153806404,3822280332,352677332,2297720250,60907813,90501309,3286998549,1016092578,2535922412,2839152426,457141659,509813237,4120667899,652014361,1966332200,2975202805,55981186,2327461051,676427537,3255491064,2882294119,3433927263,1307055953,942726286,933058658,2468411793,3933900994,4215176142,1361170020,2001714738,2830558078,3274259782,1222529897,1679025792,2729314320,3714953764,1770335741,151462246,3013232138,1682292957,1483529935,471910574,1539241949,458788160,3436315007,1807016891,3718408830,978976581,1043663428,3165965781,1927990952,4200891579,2372276910,3208408903,3533431907,1412390302,2931980059,4132332400,1947078029,3881505623,4168226417,2941484381,1077988104,1320477388,886195818,18198404,3786409e3,2509781533,112762804,3463356488,1866414978,891333506,18488651,661792760,1628790961,3885187036,3141171499,876946877,2693282273,1372485963,791857591,2686433993,3759982718,3167212022,3472953795,2716379847,445679433,3561995674,3504004811,3574258232,54117162,3331405415,2381918588,3769707343,4154350007,1140177722,4074052095,668550556,3214352940,367459370,261225585,2610173221,4209349473,3468074219,3265815641,314222801,3066103646,3808782860,282218597,3406013506,3773591054,379116347,1285071038,846784868,2669647154,3771962079,3550491691,2305946142,453669953,1268987020,3317592352,3279303384,3744833421,2610507566,3859509063,266596637,3847019092,517658769,3462560207,3443424879,370717030,4247526661,2224018117,4143653529,4112773975,2788324899,2477274417,1456262402,2901442914,1517677493,1846949527,2295493580,3734397586,2176403920,1280348187,1908823572,3871786941,846861322,1172426758,3287448474,3383383037,1655181056,3139813346,901632758,1897031941,2986607138,3066810236,3447102507,1393639104,373351379,950779232,625454576,3124240540,4148612726,2007998917,544563296,2244738638,2330496472,2058025392,1291430526,424198748,50039436,29584100,3605783033,2429876329,2791104160,1057563949,3255363231,3075367218,3463963227,1469046755,985887462]];var o={pbox:[],sbox:[]};function l(f,g){let b=g>>24&255,S=g>>16&255,v=g>>8&255,R=255&g,_=f.sbox[0][b]+f.sbox[1][S];return _^=f.sbox[2][v],_+=f.sbox[3][R],_}function d(f,g,b){let S,v=g,R=b;for(let _=0;_<s;++_)v^=f.pbox[_],R=l(f,v)^R,S=v,v=R,R=S;return S=v,v=R,R=S,R^=f.pbox[s],v^=f.pbox[s+1],{left:v,right:R}}function u(f,g,b){let S,v=g,R=b;for(let _=s+1;_>1;--_)v^=f.pbox[_],R=l(f,v)^R,S=v,v=R,R=S;return S=v,v=R,R=S,R^=f.pbox[1],v^=f.pbox[0],{left:v,right:R}}function p(f,g,b){for(let y=0;y<4;y++){f.sbox[y]=[];for(let w=0;w<256;w++)f.sbox[y][w]=c[y][w]}let S=0;for(let y=0;y<s+2;y++)f.pbox[y]=n[y]^g[S],S++,S>=b&&(S=0);let v=0,R=0,_=0;for(let y=0;y<s+2;y+=2)_=d(f,v,R),v=_.left,R=_.right,f.pbox[y]=v,f.pbox[y+1]=R;for(let y=0;y<4;y++)for(let w=0;w<256;w+=2)_=d(f,v,R),v=_.left,R=_.right,f.sbox[y][w]=v,f.sbox[y][w+1]=R;return!0}var h=i.Blowfish=t.extend({_doReset:function(){if(this._keyPriorReset!==this._key){var f=this._keyPriorReset=this._key,g=f.words,b=f.sigBytes/4;p(o,g,b)}},encryptBlock:function(f,g){var b=d(o,f[g],f[g+1]);f[g]=b.left,f[g+1]=b.right},decryptBlock:function(f,g){var b=u(o,f[g],f[g+1]);f[g]=b.left,f[g+1]=b.right},blockSize:2,keySize:4,ivSize:2});e.Blowfish=t._createHelper(h)}(),r.Blowfish}(fe(),si(),ri(),Kt(),Xe())}(Aa)),Aa.exports}(function(a){a.exports=function(r){return r}(fe(),ji(),fo(),bo(),si(),So(),ri(),Or(),ps(),Br||(Br=1,function(r){r.exports=function(e){return i=(t=e).lib.WordArray,s=t.algo,n=s.SHA256,c=s.SHA224=n.extend({_doReset:function(){this._hash=new i.init([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428])},_doFinalize:function(){var o=n._doFinalize.call(this);return o.sigBytes-=4,o}}),t.SHA224=n._createHelper(c),t.HmacSHA224=n._createHmacHelper(c),e.SHA224;var t,i,s,n,c}(fe(),ps())}(vo)),jr(),$r||($r=1,function(r){r.exports=function(e){return i=(t=e).x64,s=i.Word,n=i.WordArray,c=t.algo,o=c.SHA512,l=c.SHA384=o.extend({_doReset:function(){this._hash=new n.init([new s.init(3418070365,3238371032),new s.init(1654270250,914150663),new s.init(2438529370,812702999),new s.init(355462360,4144912697),new s.init(1731405415,4290775857),new s.init(2394180231,1750603025),new s.init(3675008525,1694076839),new s.init(1203062813,3204075428)])},_doFinalize:function(){var d=o._doFinalize.call(this);return d.sigBytes-=16,d}}),t.SHA384=o._createHelper(l),t.HmacSHA384=o._createHmacHelper(l),e.SHA384;var t,i,s,n,c,o,l}(fe(),ji(),jr())}(yo)),Ro(),Kr||(Kr=1,function(r){r.exports=function(e){return function(){var t=e,i=t.lib,s=i.WordArray,n=i.Hasher,c=t.algo,o=s.create([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13]),l=s.create([5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11]),d=s.create([11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6]),u=s.create([8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]),p=s.create([0,1518500249,1859775393,2400959708,2840853838]),h=s.create([1352829926,1548603684,1836072691,2053994217,0]),f=c.RIPEMD160=n.extend({_doReset:function(){this._hash=s.create([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(y,w){for(var A=0;A<16;A++){var E=w+A,C=y[E];y[E]=16711935&(C<<8|C>>>24)|4278255360&(C<<24|C>>>8)}var P,M,x,K,Q,G,W,Z,te,Se,L,O=this._hash.words,N=p.words,V=h.words,he=o.words,xe=l.words,q=d.words,Re=u.words;for(G=P=O[0],W=M=O[1],Z=x=O[2],te=K=O[3],Se=Q=O[4],A=0;A<80;A+=1)L=P+y[w+he[A]]|0,L+=A<16?g(M,x,K)+N[0]:A<32?b(M,x,K)+N[1]:A<48?S(M,x,K)+N[2]:A<64?v(M,x,K)+N[3]:R(M,x,K)+N[4],L=(L=_(L|=0,q[A]))+Q|0,P=Q,Q=K,K=_(x,10),x=M,M=L,L=G+y[w+xe[A]]|0,L+=A<16?R(W,Z,te)+V[0]:A<32?v(W,Z,te)+V[1]:A<48?S(W,Z,te)+V[2]:A<64?b(W,Z,te)+V[3]:g(W,Z,te)+V[4],L=(L=_(L|=0,Re[A]))+Se|0,G=Se,Se=te,te=_(Z,10),Z=W,W=L;L=O[1]+x+te|0,O[1]=O[2]+K+Se|0,O[2]=O[3]+Q+G|0,O[3]=O[4]+P+W|0,O[4]=O[0]+M+Z|0,O[0]=L},_doFinalize:function(){var y=this._data,w=y.words,A=8*this._nDataBytes,E=8*y.sigBytes;w[E>>>5]|=128<<24-E%32,w[14+(E+64>>>9<<4)]=16711935&(A<<8|A>>>24)|4278255360&(A<<24|A>>>8),y.sigBytes=4*(w.length+1),this._process();for(var C=this._hash,P=C.words,M=0;M<5;M++){var x=P[M];P[M]=16711935&(x<<8|x>>>24)|4278255360&(x<<24|x>>>8)}return C},clone:function(){var y=n.clone.call(this);return y._hash=this._hash.clone(),y}});function g(y,w,A){return y^w^A}function b(y,w,A){return y&w|~y&A}function S(y,w,A){return(y|~w)^A}function v(y,w,A){return y&A|w&~A}function R(y,w,A){return y^(w|~A)}function _(y,w){return y<<w|y>>>32-w}t.RIPEMD160=n._createHelper(f),t.HmacRIPEMD160=n._createHmacHelper(f)}(),e.RIPEMD160}(fe())}(Ao)),ms(),Gr||(Gr=1,function(r){r.exports=function(e){return s=(i=(t=e).lib).Base,n=i.WordArray,o=(c=t.algo).SHA256,l=c.HMAC,d=c.PBKDF2=s.extend({cfg:s.extend({keySize:4,hasher:o,iterations:25e4}),init:function(u){this.cfg=this.cfg.extend(u)},compute:function(u,p){for(var h=this.cfg,f=l.create(h.hasher,u),g=n.create(),b=n.create([1]),S=g.words,v=b.words,R=h.keySize,_=h.iterations;S.length<R;){var y=f.update(p).finalize(b);f.reset();for(var w=y.words,A=w.length,E=y,C=1;C<_;C++){E=f.finalize(E),f.reset();for(var P=E.words,M=0;M<A;M++)w[M]^=P[M]}g.concat(y),v[0]++}return g.sigBytes=4*R,g}}),t.PBKDF2=function(u,p,h){return d.create(h).compute(u,p)},e.PBKDF2;var t,i,s,n,c,o,l,d}(fe(),ps(),ms())}(wo)),Kt(),Xe(),_o(),Io(),Eo(),To(),ca||(ca=1,function(r){r.exports=function(e){return e.mode.ECB=((t=e.lib.BlockCipherMode.extend()).Encryptor=t.extend({processBlock:function(i,s){this._cipher.encryptBlock(i,s)}}),t.Decryptor=t.extend({processBlock:function(i,s){this._cipher.decryptBlock(i,s)}}),t),e.mode.ECB;var t}(fe(),Xe())}(Co)),la||(la=1,function(r){r.exports=function(e){return e.pad.AnsiX923={pad:function(t,i){var s=t.sigBytes,n=4*i,c=n-s%n,o=s+c-1;t.clamp(),t.words[o>>>2]|=c<<24-o%4*8,t.sigBytes+=c},unpad:function(t){var i=255&t.words[t.sigBytes-1>>>2];t.sigBytes-=i}},e.pad.Ansix923}(fe(),Xe())}(ko)),da||(da=1,function(r){r.exports=function(e){return e.pad.Iso10126={pad:function(t,i){var s=4*i,n=s-t.sigBytes%s;t.concat(e.lib.WordArray.random(n-1)).concat(e.lib.WordArray.create([n<<24],1))},unpad:function(t){var i=255&t.words[t.sigBytes-1>>>2];t.sigBytes-=i}},e.pad.Iso10126}(fe(),Xe())}(Po)),ua||(ua=1,function(r){r.exports=function(e){return e.pad.Iso97971={pad:function(t,i){t.concat(e.lib.WordArray.create([2147483648],1)),e.pad.ZeroPadding.pad(t,i)},unpad:function(t){e.pad.ZeroPadding.unpad(t),t.sigBytes--}},e.pad.Iso97971}(fe(),Xe())}(Do)),ha||(ha=1,function(r){r.exports=function(e){return e.pad.ZeroPadding={pad:function(t,i){var s=4*i;t.clamp(),t.sigBytes+=s-(t.sigBytes%s||s)},unpad:function(t){var i=t.words,s=t.sigBytes-1;for(s=t.sigBytes-1;s>=0;s--)if(i[s>>>2]>>>24-s%4*8&255){t.sigBytes=s+1;break}}},e.pad.ZeroPadding}(fe(),Xe())}(Mo)),pa||(pa=1,function(r){r.exports=function(e){return e.pad.NoPadding={pad:function(){},unpad:function(){}},e.pad.NoPadding}(fe(),Xe())}(Lo)),ma||(ma=1,function(r){r.exports=function(e){return i=(t=e).lib.CipherParams,s=t.enc.Hex,t.format.Hex={stringify:function(n){return n.ciphertext.toString(s)},parse:function(n){var c=s.parse(n);return i.create({ciphertext:c})}},e.format.Hex;var t,i,s}(fe(),Xe())}(No)),ga||(ga=1,function(r){r.exports=function(e){return function(){var t=e,i=t.lib.BlockCipher,s=t.algo,n=[],c=[],o=[],l=[],d=[],u=[],p=[],h=[],f=[],g=[];(function(){for(var v=[],R=0;R<256;R++)v[R]=R<128?R<<1:R<<1^283;var _=0,y=0;for(R=0;R<256;R++){var w=y^y<<1^y<<2^y<<3^y<<4;w=w>>>8^255&w^99,n[_]=w,c[w]=_;var A=v[_],E=v[A],C=v[E],P=257*v[w]^16843008*w;o[_]=P<<24|P>>>8,l[_]=P<<16|P>>>16,d[_]=P<<8|P>>>24,u[_]=P,P=16843009*C^65537*E^257*A^16843008*_,p[w]=P<<24|P>>>8,h[w]=P<<16|P>>>16,f[w]=P<<8|P>>>24,g[w]=P,_?(_=A^v[v[v[C^A]]],y^=v[v[y]]):_=y=1}})();var b=[0,1,2,4,8,16,32,64,128,27,54],S=s.AES=i.extend({_doReset:function(){if(!this._nRounds||this._keyPriorReset!==this._key){for(var v=this._keyPriorReset=this._key,R=v.words,_=v.sigBytes/4,y=4*((this._nRounds=_+6)+1),w=this._keySchedule=[],A=0;A<y;A++)A<_?w[A]=R[A]:(P=w[A-1],A%_?_>6&&A%_==4&&(P=n[P>>>24]<<24|n[P>>>16&255]<<16|n[P>>>8&255]<<8|n[255&P]):(P=n[(P=P<<8|P>>>24)>>>24]<<24|n[P>>>16&255]<<16|n[P>>>8&255]<<8|n[255&P],P^=b[A/_|0]<<24),w[A]=w[A-_]^P);for(var E=this._invKeySchedule=[],C=0;C<y;C++){if(A=y-C,C%4)var P=w[A];else P=w[A-4];E[C]=C<4||A<=4?P:p[n[P>>>24]]^h[n[P>>>16&255]]^f[n[P>>>8&255]]^g[n[255&P]]}}},encryptBlock:function(v,R){this._doCryptBlock(v,R,this._keySchedule,o,l,d,u,n)},decryptBlock:function(v,R){var _=v[R+1];v[R+1]=v[R+3],v[R+3]=_,this._doCryptBlock(v,R,this._invKeySchedule,p,h,f,g,c),_=v[R+1],v[R+1]=v[R+3],v[R+3]=_},_doCryptBlock:function(v,R,_,y,w,A,E,C){for(var P=this._nRounds,M=v[R]^_[0],x=v[R+1]^_[1],K=v[R+2]^_[2],Q=v[R+3]^_[3],G=4,W=1;W<P;W++){var Z=y[M>>>24]^w[x>>>16&255]^A[K>>>8&255]^E[255&Q]^_[G++],te=y[x>>>24]^w[K>>>16&255]^A[Q>>>8&255]^E[255&M]^_[G++],Se=y[K>>>24]^w[Q>>>16&255]^A[M>>>8&255]^E[255&x]^_[G++],L=y[Q>>>24]^w[M>>>16&255]^A[x>>>8&255]^E[255&K]^_[G++];M=Z,x=te,K=Se,Q=L}Z=(C[M>>>24]<<24|C[x>>>16&255]<<16|C[K>>>8&255]<<8|C[255&Q])^_[G++],te=(C[x>>>24]<<24|C[K>>>16&255]<<16|C[Q>>>8&255]<<8|C[255&M])^_[G++],Se=(C[K>>>24]<<24|C[Q>>>16&255]<<16|C[M>>>8&255]<<8|C[255&x])^_[G++],L=(C[Q>>>24]<<24|C[M>>>16&255]<<16|C[x>>>8&255]<<8|C[255&K])^_[G++],v[R]=Z,v[R+1]=te,v[R+2]=Se,v[R+3]=L},keySize:8});t.AES=i._createHelper(S)}(),e.AES}(fe(),si(),ri(),Kt(),Xe())}(xo)),Oo(),Sa||(Sa=1,function(r){r.exports=function(e){return function(){var t=e,i=t.lib.StreamCipher,s=t.algo,n=s.RC4=i.extend({_doReset:function(){for(var l=this._key,d=l.words,u=l.sigBytes,p=this._S=[],h=0;h<256;h++)p[h]=h;h=0;for(var f=0;h<256;h++){var g=h%u,b=d[g>>>2]>>>24-g%4*8&255;f=(f+p[h]+b)%256;var S=p[h];p[h]=p[f],p[f]=S}this._i=this._j=0},_doProcessBlock:function(l,d){l[d]^=c.call(this)},keySize:8,ivSize:0});function c(){for(var l=this._S,d=this._i,u=this._j,p=0,h=0;h<4;h++){u=(u+l[d=(d+1)%256])%256;var f=l[d];l[d]=l[u],l[u]=f,p|=l[(l[d]+l[u])%256]<<24-8*h}return this._i=d,this._j=u,p}t.RC4=i._createHelper(n);var o=s.RC4Drop=n.extend({cfg:n.cfg.extend({drop:192}),_doReset:function(){n._doReset.call(this);for(var l=this.cfg.drop;l>0;l--)c.call(this)}});t.RC4Drop=i._createHelper(o)}(),e.RC4}(fe(),si(),ri(),Kt(),Xe())}(Vo)),va||(va=1,function(r){r.exports=function(e){return function(){var t=e,i=t.lib.StreamCipher,s=t.algo,n=[],c=[],o=[],l=s.Rabbit=i.extend({_doReset:function(){for(var u=this._key.words,p=this.cfg.iv,h=0;h<4;h++)u[h]=16711935&(u[h]<<8|u[h]>>>24)|4278255360&(u[h]<<24|u[h]>>>8);var f=this._X=[u[0],u[3]<<16|u[2]>>>16,u[1],u[0]<<16|u[3]>>>16,u[2],u[1]<<16|u[0]>>>16,u[3],u[2]<<16|u[1]>>>16],g=this._C=[u[2]<<16|u[2]>>>16,4294901760&u[0]|65535&u[1],u[3]<<16|u[3]>>>16,4294901760&u[1]|65535&u[2],u[0]<<16|u[0]>>>16,4294901760&u[2]|65535&u[3],u[1]<<16|u[1]>>>16,4294901760&u[3]|65535&u[0]];for(this._b=0,h=0;h<4;h++)d.call(this);for(h=0;h<8;h++)g[h]^=f[h+4&7];if(p){var b=p.words,S=b[0],v=b[1],R=16711935&(S<<8|S>>>24)|4278255360&(S<<24|S>>>8),_=16711935&(v<<8|v>>>24)|4278255360&(v<<24|v>>>8),y=R>>>16|4294901760&_,w=_<<16|65535&R;for(g[0]^=R,g[1]^=y,g[2]^=_,g[3]^=w,g[4]^=R,g[5]^=y,g[6]^=_,g[7]^=w,h=0;h<4;h++)d.call(this)}},_doProcessBlock:function(u,p){var h=this._X;d.call(this),n[0]=h[0]^h[5]>>>16^h[3]<<16,n[1]=h[2]^h[7]>>>16^h[5]<<16,n[2]=h[4]^h[1]>>>16^h[7]<<16,n[3]=h[6]^h[3]>>>16^h[1]<<16;for(var f=0;f<4;f++)n[f]=16711935&(n[f]<<8|n[f]>>>24)|4278255360&(n[f]<<24|n[f]>>>8),u[p+f]^=n[f]},blockSize:4,ivSize:2});function d(){for(var u=this._X,p=this._C,h=0;h<8;h++)c[h]=p[h];for(p[0]=p[0]+1295307597+this._b|0,p[1]=p[1]+3545052371+(p[0]>>>0<c[0]>>>0?1:0)|0,p[2]=p[2]+886263092+(p[1]>>>0<c[1]>>>0?1:0)|0,p[3]=p[3]+1295307597+(p[2]>>>0<c[2]>>>0?1:0)|0,p[4]=p[4]+3545052371+(p[3]>>>0<c[3]>>>0?1:0)|0,p[5]=p[5]+886263092+(p[4]>>>0<c[4]>>>0?1:0)|0,p[6]=p[6]+1295307597+(p[5]>>>0<c[5]>>>0?1:0)|0,p[7]=p[7]+3545052371+(p[6]>>>0<c[6]>>>0?1:0)|0,this._b=p[7]>>>0<c[7]>>>0?1:0,h=0;h<8;h++){var f=u[h]+p[h],g=65535&f,b=f>>>16,S=((g*g>>>17)+g*b>>>15)+b*b,v=((4294901760&f)*f|0)+((65535&f)*f|0);o[h]=S^v}u[0]=o[0]+(o[7]<<16|o[7]>>>16)+(o[6]<<16|o[6]>>>16)|0,u[1]=o[1]+(o[0]<<8|o[0]>>>24)+o[7]|0,u[2]=o[2]+(o[1]<<16|o[1]>>>16)+(o[0]<<16|o[0]>>>16)|0,u[3]=o[3]+(o[2]<<8|o[2]>>>24)+o[1]|0,u[4]=o[4]+(o[3]<<16|o[3]>>>16)+(o[2]<<16|o[2]>>>16)|0,u[5]=o[5]+(o[4]<<8|o[4]>>>24)+o[3]|0,u[6]=o[6]+(o[5]<<16|o[5]>>>16)+(o[4]<<16|o[4]>>>16)|0,u[7]=o[7]+(o[6]<<8|o[6]>>>24)+o[5]|0}t.Rabbit=i._createHelper(l)}(),e.Rabbit}(fe(),si(),ri(),Kt(),Xe())}(Uo)),ya||(ya=1,function(r){r.exports=function(e){return function(){var t=e,i=t.lib.StreamCipher,s=t.algo,n=[],c=[],o=[],l=s.RabbitLegacy=i.extend({_doReset:function(){var u=this._key.words,p=this.cfg.iv,h=this._X=[u[0],u[3]<<16|u[2]>>>16,u[1],u[0]<<16|u[3]>>>16,u[2],u[1]<<16|u[0]>>>16,u[3],u[2]<<16|u[1]>>>16],f=this._C=[u[2]<<16|u[2]>>>16,4294901760&u[0]|65535&u[1],u[3]<<16|u[3]>>>16,4294901760&u[1]|65535&u[2],u[0]<<16|u[0]>>>16,4294901760&u[2]|65535&u[3],u[1]<<16|u[1]>>>16,4294901760&u[3]|65535&u[0]];this._b=0;for(var g=0;g<4;g++)d.call(this);for(g=0;g<8;g++)f[g]^=h[g+4&7];if(p){var b=p.words,S=b[0],v=b[1],R=16711935&(S<<8|S>>>24)|4278255360&(S<<24|S>>>8),_=16711935&(v<<8|v>>>24)|4278255360&(v<<24|v>>>8),y=R>>>16|4294901760&_,w=_<<16|65535&R;for(f[0]^=R,f[1]^=y,f[2]^=_,f[3]^=w,f[4]^=R,f[5]^=y,f[6]^=_,f[7]^=w,g=0;g<4;g++)d.call(this)}},_doProcessBlock:function(u,p){var h=this._X;d.call(this),n[0]=h[0]^h[5]>>>16^h[3]<<16,n[1]=h[2]^h[7]>>>16^h[5]<<16,n[2]=h[4]^h[1]>>>16^h[7]<<16,n[3]=h[6]^h[3]>>>16^h[1]<<16;for(var f=0;f<4;f++)n[f]=16711935&(n[f]<<8|n[f]>>>24)|4278255360&(n[f]<<24|n[f]>>>8),u[p+f]^=n[f]},blockSize:4,ivSize:2});function d(){for(var u=this._X,p=this._C,h=0;h<8;h++)c[h]=p[h];for(p[0]=p[0]+1295307597+this._b|0,p[1]=p[1]+3545052371+(p[0]>>>0<c[0]>>>0?1:0)|0,p[2]=p[2]+886263092+(p[1]>>>0<c[1]>>>0?1:0)|0,p[3]=p[3]+1295307597+(p[2]>>>0<c[2]>>>0?1:0)|0,p[4]=p[4]+3545052371+(p[3]>>>0<c[3]>>>0?1:0)|0,p[5]=p[5]+886263092+(p[4]>>>0<c[4]>>>0?1:0)|0,p[6]=p[6]+1295307597+(p[5]>>>0<c[5]>>>0?1:0)|0,p[7]=p[7]+3545052371+(p[6]>>>0<c[6]>>>0?1:0)|0,this._b=p[7]>>>0<c[7]>>>0?1:0,h=0;h<8;h++){var f=u[h]+p[h],g=65535&f,b=f>>>16,S=((g*g>>>17)+g*b>>>15)+b*b,v=((4294901760&f)*f|0)+((65535&f)*f|0);o[h]=S^v}u[0]=o[0]+(o[7]<<16|o[7]>>>16)+(o[6]<<16|o[6]>>>16)|0,u[1]=o[1]+(o[0]<<8|o[0]>>>24)+o[7]|0,u[2]=o[2]+(o[1]<<16|o[1]>>>16)+(o[0]<<16|o[0]>>>16)|0,u[3]=o[3]+(o[2]<<8|o[2]>>>24)+o[1]|0,u[4]=o[4]+(o[3]<<16|o[3]>>>16)+(o[2]<<16|o[2]>>>16)|0,u[5]=o[5]+(o[4]<<8|o[4]>>>24)+o[3]|0,u[6]=o[6]+(o[5]<<16|o[5]>>>16)+(o[4]<<16|o[4]>>>16)|0,u[7]=o[7]+(o[6]<<8|o[6]>>>24)+o[5]|0}t.RabbitLegacy=i._createHelper(l)}(),e.RabbitLegacy}(fe(),si(),ri(),Kt(),Xe())}(Bo)),Ho())})(vr);const ai=po(vr.exports);function Fo(a){return r=this,e=null,t=function*(){const i=new Date;if(a.refreshSTSTokenInterval||(a.refreshSTSTokenInterval=3e5),!a.stsTokenFreshTime||+i-a.stsTokenFreshTime>=a.refreshSTSTokenInterval){a.stsTokenFreshTime=i;try{yield a.refreshSTSToken()}catch(s){typeof console.error=="function"&&console.error(`Some error occured during excuting refreshSTSToken, see:
4
+ `)}function ds(a,r){return a>50||r>500?tt.AliRtcNetworkVeryBad:a>30||r>350?tt.AliRtcNetworkBad:a>20||r>200?tt.AliRtcNetworkPoor:a>10||r>100?tt.AliRtcNetworkGood:a>=0||r>=0?tt.AliRtcNetworkExcellent:tt.AliRtcNetworkUnknown}function mr(a){return!!a&&[D.VideoLarge,D.VideoSmall,D.Screen].includes(a)}function gr(a){return a===D.Audio}for(var us,Qe=[],hs=0;hs<256;++hs)Qe.push((hs+256).toString(16).slice(1));var uo=new Uint8Array(16);function ho(){if(!us&&!(us=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return us(uo)}const fr={randomUUID:typeof crypto!="undefined"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function mt(a,r,e){if(fr.randomUUID&&!r&&!a)return fr.randomUUID();var t=(a=a||{}).random||(a.rng||ho)();if(t[6]=15&t[6]|64,t[8]=63&t[8]|128,r){e=e||0;for(var i=0;i<16;++i)r[e+i]=t[i];return r}return function(s,n=0){return(Qe[s[n+0]]+Qe[s[n+1]]+Qe[s[n+2]]+Qe[s[n+3]]+"-"+Qe[s[n+4]]+Qe[s[n+5]]+"-"+Qe[s[n+6]]+Qe[s[n+7]]+"-"+Qe[s[n+8]]+Qe[s[n+9]]+"-"+Qe[s[n+10]]+Qe[s[n+11]]+Qe[s[n+12]]+Qe[s[n+13]]+Qe[s[n+14]]+Qe[s[n+15]]).toLowerCase()}(t)}const _i="7.2.10";class Le{static getVersionNumber(){let r=_i.split("."),e="";return r.forEach(t=>{t.length===1?e+="0"+t:e+=t}),parseInt(e)}static queryingParam(r){let e=[];if(r)for(let t in r)e.push(t+"="+r[t]);return e.join("&")}static getQueryParams(r){const e=window.location.search.substring(1).split("&");for(let t=0;t<e.length;t++){const i=e[t].split("=");if(decodeURIComponent(i[0])===r)return decodeURIComponent(i[1])}}static createCallid(r=""){const e=mt();return r&&e&&e.length>r.length?`${r}${e.substring(r.length)}`:e}static checkSubOptionsValid(r){if(r){const{audio:e,video:t,screen:i}=r;if(e===!1&&t===!1&&i===!1)return!1}return!0}static isNetworkAvailable(){return I(this,null,function*(){const r=Rt.prod,{onLine:e}=navigator;if(!e)return!1;try{return yield fetch(`https://${r}/roomserver/v1/ws/version`),!0}catch(t){return!1}})}static toString(r){let e;if(r instanceof Error)e=r.message;else if(typeof r=="string")e=r;else try{e=JSON.stringify(r)}catch(t){e="undefined"}return e}static paramArrayToString(r){let e="";for(let t=0;t<r.length;t++)e!==""&&(e+=" "),e+=Le.toString(r[t]);return e}static removeQueryString(r){if(!r)return r;let e=r.indexOf("?");return e>0?r.substring(0,e):r}}function br(a,r,e){Object.defineProperty(a,r,{writable:!0,enumerable:!0,configurable:!0,value:e})}function Sr(a,r,e,t){t?t(()=>{br(a,r,e)}):br(a,r,e)}Array(32);var Fi=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function po(a){return a&&a.__esModule&&Object.prototype.hasOwnProperty.call(a,"default")?a.default:a}function mo(a){if(a.__esModule)return a;var r=a.default;if(typeof r=="function"){var e=function t(){return this instanceof t?Reflect.construct(r,arguments,this.constructor):r.apply(this,arguments)};e.prototype=r.prototype}else e={};return Object.defineProperty(e,"__esModule",{value:!0}),Object.keys(a).forEach(function(t){var i=Object.getOwnPropertyDescriptor(a,t);Object.defineProperty(e,t,i.get?i:{enumerable:!0,get:function(){return a[t]}})}),e}var vr={exports:{}},yr={exports:{}};const go=mo(Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})));var Rr;function fe(){return Rr||(Rr=1,function(a){a.exports=function(){var r=r||function(e,t){var i;if(typeof window!="undefined"&&window.crypto&&(i=window.crypto),typeof self!="undefined"&&self.crypto&&(i=self.crypto),typeof globalThis!="undefined"&&globalThis.crypto&&(i=globalThis.crypto),!i&&typeof window!="undefined"&&window.msCrypto&&(i=window.msCrypto),!i&&Fi!==void 0&&Fi.crypto&&(i=Fi.crypto),!i)try{i=go}catch(S){}var s=function(){if(i){if(typeof i.getRandomValues=="function")try{return i.getRandomValues(new Uint32Array(1))[0]}catch(S){}if(typeof i.randomBytes=="function")try{return i.randomBytes(4).readInt32LE()}catch(S){}}throw new Error("Native crypto module could not be used to get secure random number.")},n=Object.create||function(){function S(){}return function(v){var R;return S.prototype=v,R=new S,S.prototype=null,R}}(),c={},o=c.lib={},l=o.Base={extend:function(S){var v=n(this);return S&&v.mixIn(S),v.hasOwnProperty("init")&&this.init!==v.init||(v.init=function(){v.$super.init.apply(this,arguments)}),v.init.prototype=v,v.$super=this,v},create:function(){var S=this.extend();return S.init.apply(S,arguments),S},init:function(){},mixIn:function(S){for(var v in S)S.hasOwnProperty(v)&&(this[v]=S[v]);S.hasOwnProperty("toString")&&(this.toString=S.toString)},clone:function(){return this.init.prototype.extend(this)}},d=o.WordArray=l.extend({init:function(S,v){S=this.words=S||[],this.sigBytes=v!=t?v:4*S.length},toString:function(S){return(S||p).stringify(this)},concat:function(S){var v=this.words,R=S.words,_=this.sigBytes,y=S.sigBytes;if(this.clamp(),_%4)for(var w=0;w<y;w++){var A=R[w>>>2]>>>24-w%4*8&255;v[_+w>>>2]|=A<<24-(_+w)%4*8}else for(var E=0;E<y;E+=4)v[_+E>>>2]=R[E>>>2];return this.sigBytes+=y,this},clamp:function(){var S=this.words,v=this.sigBytes;S[v>>>2]&=4294967295<<32-v%4*8,S.length=e.ceil(v/4)},clone:function(){var S=l.clone.call(this);return S.words=this.words.slice(0),S},random:function(S){for(var v=[],R=0;R<S;R+=4)v.push(s());return new d.init(v,S)}}),u=c.enc={},p=u.Hex={stringify:function(S){for(var v=S.words,R=S.sigBytes,_=[],y=0;y<R;y++){var w=v[y>>>2]>>>24-y%4*8&255;_.push((w>>>4).toString(16)),_.push((15&w).toString(16))}return _.join("")},parse:function(S){for(var v=S.length,R=[],_=0;_<v;_+=2)R[_>>>3]|=parseInt(S.substr(_,2),16)<<24-_%8*4;return new d.init(R,v/2)}},h=u.Latin1={stringify:function(S){for(var v=S.words,R=S.sigBytes,_=[],y=0;y<R;y++){var w=v[y>>>2]>>>24-y%4*8&255;_.push(String.fromCharCode(w))}return _.join("")},parse:function(S){for(var v=S.length,R=[],_=0;_<v;_++)R[_>>>2]|=(255&S.charCodeAt(_))<<24-_%4*8;return new d.init(R,v)}},f=u.Utf8={stringify:function(S){try{return decodeURIComponent(escape(h.stringify(S)))}catch(v){throw new Error("Malformed UTF-8 data")}},parse:function(S){return h.parse(unescape(encodeURIComponent(S)))}},g=o.BufferedBlockAlgorithm=l.extend({reset:function(){this._data=new d.init,this._nDataBytes=0},_append:function(S){typeof S=="string"&&(S=f.parse(S)),this._data.concat(S),this._nDataBytes+=S.sigBytes},_process:function(S){var v,R=this._data,_=R.words,y=R.sigBytes,w=this.blockSize,A=y/(4*w),E=(A=S?e.ceil(A):e.max((0|A)-this._minBufferSize,0))*w,C=e.min(4*E,y);if(E){for(var P=0;P<E;P+=w)this._doProcessBlock(_,P);v=_.splice(0,E),R.sigBytes-=C}return new d.init(v,C)},clone:function(){var S=l.clone.call(this);return S._data=this._data.clone(),S},_minBufferSize:0});o.Hasher=g.extend({cfg:l.extend(),init:function(S){this.cfg=this.cfg.extend(S),this.reset()},reset:function(){g.reset.call(this),this._doReset()},update:function(S){return this._append(S),this._process(),this},finalize:function(S){return S&&this._append(S),this._doFinalize()},blockSize:16,_createHelper:function(S){return function(v,R){return new S.init(R).finalize(v)}},_createHmacHelper:function(S){return function(v,R){return new b.HMAC.init(S,R).finalize(v)}}});var b=c.algo={};return c}(Math);return r}()}(yr)),yr.exports}var Ar,wr={exports:{}};function ji(){return Ar||(Ar=1,function(a){a.exports=function(r){return i=(t=r).lib,s=i.Base,n=i.WordArray,(c=t.x64={}).Word=s.extend({init:function(o,l){this.high=o,this.low=l}}),c.WordArray=s.extend({init:function(o,l){o=this.words=o||[],this.sigBytes=l!=e?l:8*o.length},toX32:function(){for(var o=this.words,l=o.length,d=[],u=0;u<l;u++){var p=o[u];d.push(p.high),d.push(p.low)}return n.create(d,this.sigBytes)},clone:function(){for(var o=s.clone.call(this),l=o.words=this.words.slice(0),d=l.length,u=0;u<d;u++)l[u]=l[u].clone();return o}}),r;var e,t,i,s,n,c}(fe())}(wr)),wr.exports}var _r,Ir={exports:{}};function fo(){return _r||(_r=1,function(a){a.exports=function(r){return function(){if(typeof ArrayBuffer=="function"){var e=r.lib.WordArray,t=e.init,i=e.init=function(s){if(s instanceof ArrayBuffer&&(s=new Uint8Array(s)),(s instanceof Int8Array||typeof Uint8ClampedArray!="undefined"&&s instanceof Uint8ClampedArray||s instanceof Int16Array||s instanceof Uint16Array||s instanceof Int32Array||s instanceof Uint32Array||s instanceof Float32Array||s instanceof Float64Array)&&(s=new Uint8Array(s.buffer,s.byteOffset,s.byteLength)),s instanceof Uint8Array){for(var n=s.byteLength,c=[],o=0;o<n;o++)c[o>>>2]|=s[o]<<24-o%4*8;t.call(this,c,n)}else t.apply(this,arguments)};i.prototype=e}}(),r.lib.WordArray}(fe())}(Ir)),Ir.exports}var Er,Tr={exports:{}};function bo(){return Er||(Er=1,function(a){a.exports=function(r){return function(){var e=r,t=e.lib.WordArray,i=e.enc;function s(n){return n<<8&4278255360|n>>>8&16711935}i.Utf16=i.Utf16BE={stringify:function(n){for(var c=n.words,o=n.sigBytes,l=[],d=0;d<o;d+=2){var u=c[d>>>2]>>>16-d%4*8&65535;l.push(String.fromCharCode(u))}return l.join("")},parse:function(n){for(var c=n.length,o=[],l=0;l<c;l++)o[l>>>1]|=n.charCodeAt(l)<<16-l%2*16;return t.create(o,2*c)}},i.Utf16LE={stringify:function(n){for(var c=n.words,o=n.sigBytes,l=[],d=0;d<o;d+=2){var u=s(c[d>>>2]>>>16-d%4*8&65535);l.push(String.fromCharCode(u))}return l.join("")},parse:function(n){for(var c=n.length,o=[],l=0;l<c;l++)o[l>>>1]|=s(n.charCodeAt(l)<<16-l%2*16);return t.create(o,2*c)}}}(),r.enc.Utf16}(fe())}(Tr)),Tr.exports}var Cr,kr={exports:{}};function si(){return Cr||(Cr=1,function(a){a.exports=function(r){return function(){var e=r,t=e.lib.WordArray;function i(s,n,c){for(var o=[],l=0,d=0;d<n;d++)if(d%4){var u=c[s.charCodeAt(d-1)]<<d%4*2|c[s.charCodeAt(d)]>>>6-d%4*2;o[l>>>2]|=u<<24-l%4*8,l++}return t.create(o,l)}e.enc.Base64={stringify:function(s){var n=s.words,c=s.sigBytes,o=this._map;s.clamp();for(var l=[],d=0;d<c;d+=3)for(var u=(n[d>>>2]>>>24-d%4*8&255)<<16|(n[d+1>>>2]>>>24-(d+1)%4*8&255)<<8|n[d+2>>>2]>>>24-(d+2)%4*8&255,p=0;p<4&&d+.75*p<c;p++)l.push(o.charAt(u>>>6*(3-p)&63));var h=o.charAt(64);if(h)for(;l.length%4;)l.push(h);return l.join("")},parse:function(s){var n=s.length,c=this._map,o=this._reverseMap;if(!o){o=this._reverseMap=[];for(var l=0;l<c.length;l++)o[c.charCodeAt(l)]=l}var d=c.charAt(64);if(d){var u=s.indexOf(d);u!==-1&&(n=u)}return i(s,n,o)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}}(),r.enc.Base64}(fe())}(kr)),kr.exports}var Pr,Dr={exports:{}};function So(){return Pr||(Pr=1,function(a){a.exports=function(r){return function(){var e=r,t=e.lib.WordArray;function i(s,n,c){for(var o=[],l=0,d=0;d<n;d++)if(d%4){var u=c[s.charCodeAt(d-1)]<<d%4*2|c[s.charCodeAt(d)]>>>6-d%4*2;o[l>>>2]|=u<<24-l%4*8,l++}return t.create(o,l)}e.enc.Base64url={stringify:function(s,n){n===void 0&&(n=!0);var c=s.words,o=s.sigBytes,l=n?this._safe_map:this._map;s.clamp();for(var d=[],u=0;u<o;u+=3)for(var p=(c[u>>>2]>>>24-u%4*8&255)<<16|(c[u+1>>>2]>>>24-(u+1)%4*8&255)<<8|c[u+2>>>2]>>>24-(u+2)%4*8&255,h=0;h<4&&u+.75*h<o;h++)d.push(l.charAt(p>>>6*(3-h)&63));var f=l.charAt(64);if(f)for(;d.length%4;)d.push(f);return d.join("")},parse:function(s,n){n===void 0&&(n=!0);var c=s.length,o=n?this._safe_map:this._map,l=this._reverseMap;if(!l){l=this._reverseMap=[];for(var d=0;d<o.length;d++)l[o.charCodeAt(d)]=d}var u=o.charAt(64);if(u){var p=s.indexOf(u);p!==-1&&(c=p)}return i(s,c,l)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",_safe_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"}}(),r.enc.Base64url}(fe())}(Dr)),Dr.exports}var Mr,Lr={exports:{}};function ri(){return Mr||(Mr=1,function(a){a.exports=function(r){return function(e){var t=r,i=t.lib,s=i.WordArray,n=i.Hasher,c=t.algo,o=[];(function(){for(var f=0;f<64;f++)o[f]=4294967296*e.abs(e.sin(f+1))|0})();var l=c.MD5=n.extend({_doReset:function(){this._hash=new s.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(f,g){for(var b=0;b<16;b++){var S=g+b,v=f[S];f[S]=16711935&(v<<8|v>>>24)|4278255360&(v<<24|v>>>8)}var R=this._hash.words,_=f[g+0],y=f[g+1],w=f[g+2],A=f[g+3],E=f[g+4],C=f[g+5],P=f[g+6],M=f[g+7],x=f[g+8],K=f[g+9],Q=f[g+10],G=f[g+11],W=f[g+12],Z=f[g+13],te=f[g+14],Se=f[g+15],L=R[0],O=R[1],N=R[2],V=R[3];L=d(L,O,N,V,_,7,o[0]),V=d(V,L,O,N,y,12,o[1]),N=d(N,V,L,O,w,17,o[2]),O=d(O,N,V,L,A,22,o[3]),L=d(L,O,N,V,E,7,o[4]),V=d(V,L,O,N,C,12,o[5]),N=d(N,V,L,O,P,17,o[6]),O=d(O,N,V,L,M,22,o[7]),L=d(L,O,N,V,x,7,o[8]),V=d(V,L,O,N,K,12,o[9]),N=d(N,V,L,O,Q,17,o[10]),O=d(O,N,V,L,G,22,o[11]),L=d(L,O,N,V,W,7,o[12]),V=d(V,L,O,N,Z,12,o[13]),N=d(N,V,L,O,te,17,o[14]),L=u(L,O=d(O,N,V,L,Se,22,o[15]),N,V,y,5,o[16]),V=u(V,L,O,N,P,9,o[17]),N=u(N,V,L,O,G,14,o[18]),O=u(O,N,V,L,_,20,o[19]),L=u(L,O,N,V,C,5,o[20]),V=u(V,L,O,N,Q,9,o[21]),N=u(N,V,L,O,Se,14,o[22]),O=u(O,N,V,L,E,20,o[23]),L=u(L,O,N,V,K,5,o[24]),V=u(V,L,O,N,te,9,o[25]),N=u(N,V,L,O,A,14,o[26]),O=u(O,N,V,L,x,20,o[27]),L=u(L,O,N,V,Z,5,o[28]),V=u(V,L,O,N,w,9,o[29]),N=u(N,V,L,O,M,14,o[30]),L=p(L,O=u(O,N,V,L,W,20,o[31]),N,V,C,4,o[32]),V=p(V,L,O,N,x,11,o[33]),N=p(N,V,L,O,G,16,o[34]),O=p(O,N,V,L,te,23,o[35]),L=p(L,O,N,V,y,4,o[36]),V=p(V,L,O,N,E,11,o[37]),N=p(N,V,L,O,M,16,o[38]),O=p(O,N,V,L,Q,23,o[39]),L=p(L,O,N,V,Z,4,o[40]),V=p(V,L,O,N,_,11,o[41]),N=p(N,V,L,O,A,16,o[42]),O=p(O,N,V,L,P,23,o[43]),L=p(L,O,N,V,K,4,o[44]),V=p(V,L,O,N,W,11,o[45]),N=p(N,V,L,O,Se,16,o[46]),L=h(L,O=p(O,N,V,L,w,23,o[47]),N,V,_,6,o[48]),V=h(V,L,O,N,M,10,o[49]),N=h(N,V,L,O,te,15,o[50]),O=h(O,N,V,L,C,21,o[51]),L=h(L,O,N,V,W,6,o[52]),V=h(V,L,O,N,A,10,o[53]),N=h(N,V,L,O,Q,15,o[54]),O=h(O,N,V,L,y,21,o[55]),L=h(L,O,N,V,x,6,o[56]),V=h(V,L,O,N,Se,10,o[57]),N=h(N,V,L,O,P,15,o[58]),O=h(O,N,V,L,Z,21,o[59]),L=h(L,O,N,V,E,6,o[60]),V=h(V,L,O,N,G,10,o[61]),N=h(N,V,L,O,w,15,o[62]),O=h(O,N,V,L,K,21,o[63]),R[0]=R[0]+L|0,R[1]=R[1]+O|0,R[2]=R[2]+N|0,R[3]=R[3]+V|0},_doFinalize:function(){var f=this._data,g=f.words,b=8*this._nDataBytes,S=8*f.sigBytes;g[S>>>5]|=128<<24-S%32;var v=e.floor(b/4294967296),R=b;g[15+(S+64>>>9<<4)]=16711935&(v<<8|v>>>24)|4278255360&(v<<24|v>>>8),g[14+(S+64>>>9<<4)]=16711935&(R<<8|R>>>24)|4278255360&(R<<24|R>>>8),f.sigBytes=4*(g.length+1),this._process();for(var _=this._hash,y=_.words,w=0;w<4;w++){var A=y[w];y[w]=16711935&(A<<8|A>>>24)|4278255360&(A<<24|A>>>8)}return _},clone:function(){var f=n.clone.call(this);return f._hash=this._hash.clone(),f}});function d(f,g,b,S,v,R,_){var y=f+(g&b|~g&S)+v+_;return(y<<R|y>>>32-R)+g}function u(f,g,b,S,v,R,_){var y=f+(g&S|b&~S)+v+_;return(y<<R|y>>>32-R)+g}function p(f,g,b,S,v,R,_){var y=f+(g^b^S)+v+_;return(y<<R|y>>>32-R)+g}function h(f,g,b,S,v,R,_){var y=f+(b^(g|~S))+v+_;return(y<<R|y>>>32-R)+g}t.MD5=n._createHelper(l),t.HmacMD5=n._createHmacHelper(l)}(Math),r.MD5}(fe())}(Lr)),Lr.exports}var Nr,xr={exports:{}};function Or(){return Nr||(Nr=1,function(a){a.exports=function(r){return t=(e=r).lib,i=t.WordArray,s=t.Hasher,n=e.algo,c=[],o=n.SHA1=s.extend({_doReset:function(){this._hash=new i.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(l,d){for(var u=this._hash.words,p=u[0],h=u[1],f=u[2],g=u[3],b=u[4],S=0;S<80;S++){if(S<16)c[S]=0|l[d+S];else{var v=c[S-3]^c[S-8]^c[S-14]^c[S-16];c[S]=v<<1|v>>>31}var R=(p<<5|p>>>27)+b+c[S];R+=S<20?1518500249+(h&f|~h&g):S<40?1859775393+(h^f^g):S<60?(h&f|h&g|f&g)-1894007588:(h^f^g)-899497514,b=g,g=f,f=h<<30|h>>>2,h=p,p=R}u[0]=u[0]+p|0,u[1]=u[1]+h|0,u[2]=u[2]+f|0,u[3]=u[3]+g|0,u[4]=u[4]+b|0},_doFinalize:function(){var l=this._data,d=l.words,u=8*this._nDataBytes,p=8*l.sigBytes;return d[p>>>5]|=128<<24-p%32,d[14+(p+64>>>9<<4)]=Math.floor(u/4294967296),d[15+(p+64>>>9<<4)]=u,l.sigBytes=4*d.length,this._process(),this._hash},clone:function(){var l=s.clone.call(this);return l._hash=this._hash.clone(),l}}),e.SHA1=s._createHelper(o),e.HmacSHA1=s._createHmacHelper(o),r.SHA1;var e,t,i,s,n,c,o}(fe())}(xr)),xr.exports}var Vr,Ur={exports:{}};function ps(){return Vr||(Vr=1,function(a){a.exports=function(r){return function(e){var t=r,i=t.lib,s=i.WordArray,n=i.Hasher,c=t.algo,o=[],l=[];(function(){function p(b){for(var S=e.sqrt(b),v=2;v<=S;v++)if(!(b%v))return!1;return!0}function h(b){return 4294967296*(b-(0|b))|0}for(var f=2,g=0;g<64;)p(f)&&(g<8&&(o[g]=h(e.pow(f,.5))),l[g]=h(e.pow(f,1/3)),g++),f++})();var d=[],u=c.SHA256=n.extend({_doReset:function(){this._hash=new s.init(o.slice(0))},_doProcessBlock:function(p,h){for(var f=this._hash.words,g=f[0],b=f[1],S=f[2],v=f[3],R=f[4],_=f[5],y=f[6],w=f[7],A=0;A<64;A++){if(A<16)d[A]=0|p[h+A];else{var E=d[A-15],C=(E<<25|E>>>7)^(E<<14|E>>>18)^E>>>3,P=d[A-2],M=(P<<15|P>>>17)^(P<<13|P>>>19)^P>>>10;d[A]=C+d[A-7]+M+d[A-16]}var x=g&b^g&S^b&S,K=(g<<30|g>>>2)^(g<<19|g>>>13)^(g<<10|g>>>22),Q=w+((R<<26|R>>>6)^(R<<21|R>>>11)^(R<<7|R>>>25))+(R&_^~R&y)+l[A]+d[A];w=y,y=_,_=R,R=v+Q|0,v=S,S=b,b=g,g=Q+(K+x)|0}f[0]=f[0]+g|0,f[1]=f[1]+b|0,f[2]=f[2]+S|0,f[3]=f[3]+v|0,f[4]=f[4]+R|0,f[5]=f[5]+_|0,f[6]=f[6]+y|0,f[7]=f[7]+w|0},_doFinalize:function(){var p=this._data,h=p.words,f=8*this._nDataBytes,g=8*p.sigBytes;return h[g>>>5]|=128<<24-g%32,h[14+(g+64>>>9<<4)]=e.floor(f/4294967296),h[15+(g+64>>>9<<4)]=f,p.sigBytes=4*h.length,this._process(),this._hash},clone:function(){var p=n.clone.call(this);return p._hash=this._hash.clone(),p}});t.SHA256=n._createHelper(u),t.HmacSHA256=n._createHmacHelper(u)}(Math),r.SHA256}(fe())}(Ur)),Ur.exports}var Br,vo={exports:{}},Hr,Fr={exports:{}};function jr(){return Hr||(Hr=1,function(a){a.exports=function(r){return function(){var e=r,t=e.lib.Hasher,i=e.x64,s=i.Word,n=i.WordArray,c=e.algo;function o(){return s.create.apply(s,arguments)}var l=[o(1116352408,3609767458),o(1899447441,602891725),o(3049323471,3964484399),o(3921009573,2173295548),o(961987163,4081628472),o(1508970993,3053834265),o(2453635748,2937671579),o(2870763221,3664609560),o(3624381080,2734883394),o(310598401,1164996542),o(607225278,1323610764),o(1426881987,3590304994),o(1925078388,4068182383),o(2162078206,991336113),o(2614888103,633803317),o(3248222580,3479774868),o(3835390401,2666613458),o(4022224774,944711139),o(264347078,2341262773),o(604807628,2007800933),o(770255983,1495990901),o(1249150122,1856431235),o(1555081692,3175218132),o(1996064986,2198950837),o(2554220882,3999719339),o(2821834349,766784016),o(2952996808,2566594879),o(3210313671,3203337956),o(3336571891,1034457026),o(3584528711,2466948901),o(113926993,3758326383),o(338241895,168717936),o(666307205,1188179964),o(773529912,1546045734),o(1294757372,1522805485),o(1396182291,2643833823),o(1695183700,2343527390),o(1986661051,1014477480),o(2177026350,1206759142),o(2456956037,344077627),o(2730485921,1290863460),o(2820302411,3158454273),o(3259730800,3505952657),o(3345764771,106217008),o(3516065817,3606008344),o(3600352804,1432725776),o(4094571909,1467031594),o(275423344,851169720),o(430227734,3100823752),o(506948616,1363258195),o(659060556,3750685593),o(883997877,3785050280),o(958139571,3318307427),o(1322822218,3812723403),o(1537002063,2003034995),o(1747873779,3602036899),o(1955562222,1575990012),o(2024104815,1125592928),o(2227730452,2716904306),o(2361852424,442776044),o(2428436474,593698344),o(2756734187,3733110249),o(3204031479,2999351573),o(3329325298,3815920427),o(3391569614,3928383900),o(3515267271,566280711),o(3940187606,3454069534),o(4118630271,4000239992),o(116418474,1914138554),o(174292421,2731055270),o(289380356,3203993006),o(460393269,320620315),o(685471733,587496836),o(852142971,1086792851),o(1017036298,365543100),o(1126000580,2618297676),o(1288033470,3409855158),o(1501505948,4234509866),o(1607167915,987167468),o(1816402316,1246189591)],d=[];(function(){for(var p=0;p<80;p++)d[p]=o()})();var u=c.SHA512=t.extend({_doReset:function(){this._hash=new n.init([new s.init(1779033703,4089235720),new s.init(3144134277,2227873595),new s.init(1013904242,4271175723),new s.init(2773480762,1595750129),new s.init(1359893119,2917565137),new s.init(2600822924,725511199),new s.init(528734635,4215389547),new s.init(1541459225,327033209)])},_doProcessBlock:function(p,h){for(var f=this._hash.words,g=f[0],b=f[1],S=f[2],v=f[3],R=f[4],_=f[5],y=f[6],w=f[7],A=g.high,E=g.low,C=b.high,P=b.low,M=S.high,x=S.low,K=v.high,Q=v.low,G=R.high,W=R.low,Z=_.high,te=_.low,Se=y.high,L=y.low,O=w.high,N=w.low,V=A,he=E,xe=C,q=P,Re=M,Ve=x,Ee=K,Ne=Q,ve=G,we=W,pe=Z,Oe=te,Te=Se,Ye=L,ht=O,le=N,ne=0;ne<80;ne++){var ie,Ae,Fe=d[ne];if(ne<16)Ae=Fe.high=0|p[h+2*ne],ie=Fe.low=0|p[h+2*ne+1];else{var me=d[ne-15],qe=me.high,Y=me.low,Ue=(qe>>>1|Y<<31)^(qe>>>8|Y<<24)^qe>>>7,pt=(Y>>>1|qe<<31)^(Y>>>8|qe<<24)^(Y>>>7|qe<<25),Be=d[ne-2],Tt=Be.high,Ot=Be.low,Ct=(Tt>>>19|Ot<<13)^(Tt<<3|Ot>>>29)^Tt>>>6,ei=(Ot>>>19|Tt<<13)^(Ot<<3|Tt>>>29)^(Ot>>>6|Tt<<26),Ui=d[ne-7],rs=Ui.high,yl=Ui.low,eo=d[ne-16],Rl=eo.high,to=eo.low;Ae=(Ae=(Ae=Ue+rs+((ie=pt+yl)>>>0<pt>>>0?1:0))+Ct+((ie+=ei)>>>0<ei>>>0?1:0))+Rl+((ie+=to)>>>0<to>>>0?1:0),Fe.high=Ae,Fe.low=ie}var hi,Al=ve&pe^~ve&Te,io=we&Oe^~we&Ye,wl=V&xe^V&Re^xe&Re,_l=he&q^he&Ve^q&Ve,Il=(V>>>28|he<<4)^(V<<30|he>>>2)^(V<<25|he>>>7),so=(he>>>28|V<<4)^(he<<30|V>>>2)^(he<<25|V>>>7),El=(ve>>>14|we<<18)^(ve>>>18|we<<14)^(ve<<23|we>>>9),Tl=(we>>>14|ve<<18)^(we>>>18|ve<<14)^(we<<23|ve>>>9),ro=l[ne],Cl=ro.high,ao=ro.low,Bi=ht+El+((hi=le+Tl)>>>0<le>>>0?1:0),no=so+_l;ht=Te,le=Ye,Te=pe,Ye=Oe,pe=ve,Oe=we,ve=Ee+(Bi=(Bi=(Bi=Bi+Al+((hi+=io)>>>0<io>>>0?1:0))+Cl+((hi+=ao)>>>0<ao>>>0?1:0))+Ae+((hi+=ie)>>>0<ie>>>0?1:0))+((we=Ne+hi|0)>>>0<Ne>>>0?1:0)|0,Ee=Re,Ne=Ve,Re=xe,Ve=q,xe=V,q=he,V=Bi+(Il+wl+(no>>>0<so>>>0?1:0))+((he=hi+no|0)>>>0<hi>>>0?1:0)|0}E=g.low=E+he,g.high=A+V+(E>>>0<he>>>0?1:0),P=b.low=P+q,b.high=C+xe+(P>>>0<q>>>0?1:0),x=S.low=x+Ve,S.high=M+Re+(x>>>0<Ve>>>0?1:0),Q=v.low=Q+Ne,v.high=K+Ee+(Q>>>0<Ne>>>0?1:0),W=R.low=W+we,R.high=G+ve+(W>>>0<we>>>0?1:0),te=_.low=te+Oe,_.high=Z+pe+(te>>>0<Oe>>>0?1:0),L=y.low=L+Ye,y.high=Se+Te+(L>>>0<Ye>>>0?1:0),N=w.low=N+le,w.high=O+ht+(N>>>0<le>>>0?1:0)},_doFinalize:function(){var p=this._data,h=p.words,f=8*this._nDataBytes,g=8*p.sigBytes;return h[g>>>5]|=128<<24-g%32,h[30+(g+128>>>10<<5)]=Math.floor(f/4294967296),h[31+(g+128>>>10<<5)]=f,p.sigBytes=4*h.length,this._process(),this._hash.toX32()},clone:function(){var p=t.clone.call(this);return p._hash=this._hash.clone(),p},blockSize:32});e.SHA512=t._createHelper(u),e.HmacSHA512=t._createHmacHelper(u)}(),r.SHA512}(fe(),ji())}(Fr)),Fr.exports}var $r,yo={exports:{}},Wr,zr={exports:{}};function Ro(){return Wr||(Wr=1,function(a){a.exports=function(r){return function(e){var t=r,i=t.lib,s=i.WordArray,n=i.Hasher,c=t.x64.Word,o=t.algo,l=[],d=[],u=[];(function(){for(var f=1,g=0,b=0;b<24;b++){l[f+5*g]=(b+1)*(b+2)/2%64;var S=(2*f+3*g)%5;f=g%5,g=S}for(f=0;f<5;f++)for(g=0;g<5;g++)d[f+5*g]=g+(2*f+3*g)%5*5;for(var v=1,R=0;R<24;R++){for(var _=0,y=0,w=0;w<7;w++){if(1&v){var A=(1<<w)-1;A<32?y^=1<<A:_^=1<<A-32}128&v?v=v<<1^113:v<<=1}u[R]=c.create(_,y)}})();var p=[];(function(){for(var f=0;f<25;f++)p[f]=c.create()})();var h=o.SHA3=n.extend({cfg:n.cfg.extend({outputLength:512}),_doReset:function(){for(var f=this._state=[],g=0;g<25;g++)f[g]=new c.init;this.blockSize=(1600-2*this.cfg.outputLength)/32},_doProcessBlock:function(f,g){for(var b=this._state,S=this.blockSize/2,v=0;v<S;v++){var R=f[g+2*v],_=f[g+2*v+1];R=16711935&(R<<8|R>>>24)|4278255360&(R<<24|R>>>8),_=16711935&(_<<8|_>>>24)|4278255360&(_<<24|_>>>8),(N=b[v]).high^=_,N.low^=R}for(var y=0;y<24;y++){for(var w=0;w<5;w++){for(var A=0,E=0,C=0;C<5;C++)A^=(N=b[w+5*C]).high,E^=N.low;var P=p[w];P.high=A,P.low=E}for(w=0;w<5;w++){var M=p[(w+4)%5],x=p[(w+1)%5],K=x.high,Q=x.low;for(A=M.high^(K<<1|Q>>>31),E=M.low^(Q<<1|K>>>31),C=0;C<5;C++)(N=b[w+5*C]).high^=A,N.low^=E}for(var G=1;G<25;G++){var W=(N=b[G]).high,Z=N.low,te=l[G];te<32?(A=W<<te|Z>>>32-te,E=Z<<te|W>>>32-te):(A=Z<<te-32|W>>>64-te,E=W<<te-32|Z>>>64-te);var Se=p[d[G]];Se.high=A,Se.low=E}var L=p[0],O=b[0];for(L.high=O.high,L.low=O.low,w=0;w<5;w++)for(C=0;C<5;C++){var N=b[G=w+5*C],V=p[G],he=p[(w+1)%5+5*C],xe=p[(w+2)%5+5*C];N.high=V.high^~he.high&xe.high,N.low=V.low^~he.low&xe.low}N=b[0];var q=u[y];N.high^=q.high,N.low^=q.low}},_doFinalize:function(){var f=this._data,g=f.words;this._nDataBytes;var b=8*f.sigBytes,S=32*this.blockSize;g[b>>>5]|=1<<24-b%32,g[(e.ceil((b+1)/S)*S>>>5)-1]|=128,f.sigBytes=4*g.length,this._process();for(var v=this._state,R=this.cfg.outputLength/8,_=R/8,y=[],w=0;w<_;w++){var A=v[w],E=A.high,C=A.low;E=16711935&(E<<8|E>>>24)|4278255360&(E<<24|E>>>8),C=16711935&(C<<8|C>>>24)|4278255360&(C<<24|C>>>8),y.push(C),y.push(E)}return new s.init(y,R)},clone:function(){for(var f=n.clone.call(this),g=f._state=this._state.slice(0),b=0;b<25;b++)g[b]=g[b].clone();return f}});t.SHA3=n._createHelper(h),t.HmacSHA3=n._createHmacHelper(h)}(Math),r.SHA3}(fe(),ji())}(zr)),zr.exports}var Kr,Ao={exports:{}},Jr,qr={exports:{}};function ms(){return Jr||(Jr=1,function(a){a.exports=function(r){var e,t,i;t=(e=r).lib.Base,i=e.enc.Utf8,e.algo.HMAC=t.extend({init:function(s,n){s=this._hasher=new s.init,typeof n=="string"&&(n=i.parse(n));var c=s.blockSize,o=4*c;n.sigBytes>o&&(n=s.finalize(n)),n.clamp();for(var l=this._oKey=n.clone(),d=this._iKey=n.clone(),u=l.words,p=d.words,h=0;h<c;h++)u[h]^=1549556828,p[h]^=909522486;l.sigBytes=d.sigBytes=o,this.reset()},reset:function(){var s=this._hasher;s.reset(),s.update(this._iKey)},update:function(s){return this._hasher.update(s),this},finalize:function(s){var n=this._hasher,c=n.finalize(s);return n.reset(),n.finalize(this._oKey.clone().concat(c))}})}(fe())}(qr)),qr.exports}var Gr,wo={exports:{}},Xr,Qr={exports:{}};function Kt(){return Xr||(Xr=1,function(a){a.exports=function(r){return t=(e=r).lib,i=t.Base,s=t.WordArray,n=e.algo,c=n.MD5,o=n.EvpKDF=i.extend({cfg:i.extend({keySize:4,hasher:c,iterations:1}),init:function(l){this.cfg=this.cfg.extend(l)},compute:function(l,d){for(var u,p=this.cfg,h=p.hasher.create(),f=s.create(),g=f.words,b=p.keySize,S=p.iterations;g.length<b;){u&&h.update(u),u=h.update(l).finalize(d),h.reset();for(var v=1;v<S;v++)u=h.finalize(u),h.reset();f.concat(u)}return f.sigBytes=4*b,f}}),e.EvpKDF=function(l,d,u){return o.create(u).compute(l,d)},r.EvpKDF;var e,t,i,s,n,c,o}(fe(),Or(),ms())}(Qr)),Qr.exports}var Yr,Zr={exports:{}};function Xe(){return Yr||(Yr=1,function(a){a.exports=function(r){r.lib.Cipher||function(e){var t=r,i=t.lib,s=i.Base,n=i.WordArray,c=i.BufferedBlockAlgorithm,o=t.enc;o.Utf8;var l=o.Base64,d=t.algo.EvpKDF,u=i.Cipher=c.extend({cfg:s.extend(),createEncryptor:function(y,w){return this.create(this._ENC_XFORM_MODE,y,w)},createDecryptor:function(y,w){return this.create(this._DEC_XFORM_MODE,y,w)},init:function(y,w,A){this.cfg=this.cfg.extend(A),this._xformMode=y,this._key=w,this.reset()},reset:function(){c.reset.call(this),this._doReset()},process:function(y){return this._append(y),this._process()},finalize:function(y){return y&&this._append(y),this._doFinalize()},keySize:4,ivSize:4,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,_createHelper:function(){function y(w){return typeof w=="string"?_:v}return function(w){return{encrypt:function(A,E,C){return y(E).encrypt(w,A,E,C)},decrypt:function(A,E,C){return y(E).decrypt(w,A,E,C)}}}}()});i.StreamCipher=u.extend({_doFinalize:function(){return this._process(!0)},blockSize:1});var p=t.mode={},h=i.BlockCipherMode=s.extend({createEncryptor:function(y,w){return this.Encryptor.create(y,w)},createDecryptor:function(y,w){return this.Decryptor.create(y,w)},init:function(y,w){this._cipher=y,this._iv=w}}),f=p.CBC=function(){var y=h.extend();function w(A,E,C){var P,M=this._iv;M?(P=M,this._iv=e):P=this._prevBlock;for(var x=0;x<C;x++)A[E+x]^=P[x]}return y.Encryptor=y.extend({processBlock:function(A,E){var C=this._cipher,P=C.blockSize;w.call(this,A,E,P),C.encryptBlock(A,E),this._prevBlock=A.slice(E,E+P)}}),y.Decryptor=y.extend({processBlock:function(A,E){var C=this._cipher,P=C.blockSize,M=A.slice(E,E+P);C.decryptBlock(A,E),w.call(this,A,E,P),this._prevBlock=M}}),y}(),g=(t.pad={}).Pkcs7={pad:function(y,w){for(var A=4*w,E=A-y.sigBytes%A,C=E<<24|E<<16|E<<8|E,P=[],M=0;M<E;M+=4)P.push(C);var x=n.create(P,E);y.concat(x)},unpad:function(y){var w=255&y.words[y.sigBytes-1>>>2];y.sigBytes-=w}};i.BlockCipher=u.extend({cfg:u.cfg.extend({mode:f,padding:g}),reset:function(){var y;u.reset.call(this);var w=this.cfg,A=w.iv,E=w.mode;this._xformMode==this._ENC_XFORM_MODE?y=E.createEncryptor:(y=E.createDecryptor,this._minBufferSize=1),this._mode&&this._mode.__creator==y?this._mode.init(this,A&&A.words):(this._mode=y.call(E,this,A&&A.words),this._mode.__creator=y)},_doProcessBlock:function(y,w){this._mode.processBlock(y,w)},_doFinalize:function(){var y,w=this.cfg.padding;return this._xformMode==this._ENC_XFORM_MODE?(w.pad(this._data,this.blockSize),y=this._process(!0)):(y=this._process(!0),w.unpad(y)),y},blockSize:4});var b=i.CipherParams=s.extend({init:function(y){this.mixIn(y)},toString:function(y){return(y||this.formatter).stringify(this)}}),S=(t.format={}).OpenSSL={stringify:function(y){var w=y.ciphertext,A=y.salt;return(A?n.create([1398893684,1701076831]).concat(A).concat(w):w).toString(l)},parse:function(y){var w,A=l.parse(y),E=A.words;return E[0]==1398893684&&E[1]==1701076831&&(w=n.create(E.slice(2,4)),E.splice(0,4),A.sigBytes-=16),b.create({ciphertext:A,salt:w})}},v=i.SerializableCipher=s.extend({cfg:s.extend({format:S}),encrypt:function(y,w,A,E){E=this.cfg.extend(E);var C=y.createEncryptor(A,E),P=C.finalize(w),M=C.cfg;return b.create({ciphertext:P,key:A,iv:M.iv,algorithm:y,mode:M.mode,padding:M.padding,blockSize:y.blockSize,formatter:E.format})},decrypt:function(y,w,A,E){return E=this.cfg.extend(E),w=this._parse(w,E.format),y.createDecryptor(A,E).finalize(w.ciphertext)},_parse:function(y,w){return typeof y=="string"?w.parse(y,this):y}}),R=(t.kdf={}).OpenSSL={execute:function(y,w,A,E,C){if(E||(E=n.random(8)),C)P=d.create({keySize:w+A,hasher:C}).compute(y,E);else var P=d.create({keySize:w+A}).compute(y,E);var M=n.create(P.words.slice(w),4*A);return P.sigBytes=4*w,b.create({key:P,iv:M,salt:E})}},_=i.PasswordBasedCipher=v.extend({cfg:v.cfg.extend({kdf:R}),encrypt:function(y,w,A,E){var C=(E=this.cfg.extend(E)).kdf.execute(A,y.keySize,y.ivSize,E.salt,E.hasher);E.iv=C.iv;var P=v.encrypt.call(this,y,w,C.key,E);return P.mixIn(C),P},decrypt:function(y,w,A,E){E=this.cfg.extend(E),w=this._parse(w,E.format);var C=E.kdf.execute(A,y.keySize,y.ivSize,w.salt,E.hasher);return E.iv=C.iv,v.decrypt.call(this,y,w,C.key,E)}})}()}(fe(),Kt())}(Zr)),Zr.exports}var ea,ta={exports:{}};function _o(){return ea||(ea=1,function(a){a.exports=function(r){return r.mode.CFB=function(){var e=r.lib.BlockCipherMode.extend();function t(i,s,n,c){var o,l=this._iv;l?(o=l.slice(0),this._iv=void 0):o=this._prevBlock,c.encryptBlock(o,0);for(var d=0;d<n;d++)i[s+d]^=o[d]}return e.Encryptor=e.extend({processBlock:function(i,s){var n=this._cipher,c=n.blockSize;t.call(this,i,s,c,n),this._prevBlock=i.slice(s,s+c)}}),e.Decryptor=e.extend({processBlock:function(i,s){var n=this._cipher,c=n.blockSize,o=i.slice(s,s+c);t.call(this,i,s,c,n),this._prevBlock=o}}),e}(),r.mode.CFB}(fe(),Xe())}(ta)),ta.exports}var ia,sa={exports:{}};function Io(){return ia||(ia=1,function(a){a.exports=function(r){return r.mode.CTR=(e=r.lib.BlockCipherMode.extend(),t=e.Encryptor=e.extend({processBlock:function(i,s){var n=this._cipher,c=n.blockSize,o=this._iv,l=this._counter;o&&(l=this._counter=o.slice(0),this._iv=void 0);var d=l.slice(0);n.encryptBlock(d,0),l[c-1]=l[c-1]+1|0;for(var u=0;u<c;u++)i[s+u]^=d[u]}}),e.Decryptor=t,e),r.mode.CTR;var e,t}(fe(),Xe())}(sa)),sa.exports}var ra,aa={exports:{}};function Eo(){return ra||(ra=1,function(a){a.exports=function(r){return r.mode.CTRGladman=function(){var e=r.lib.BlockCipherMode.extend();function t(n){if(255&~(n>>24))n+=1<<24;else{var c=n>>16&255,o=n>>8&255,l=255&n;c===255?(c=0,o===255?(o=0,l===255?l=0:++l):++o):++c,n=0,n+=c<<16,n+=o<<8,n+=l}return n}function i(n){return(n[0]=t(n[0]))===0&&(n[1]=t(n[1])),n}var s=e.Encryptor=e.extend({processBlock:function(n,c){var o=this._cipher,l=o.blockSize,d=this._iv,u=this._counter;d&&(u=this._counter=d.slice(0),this._iv=void 0),i(u);var p=u.slice(0);o.encryptBlock(p,0);for(var h=0;h<l;h++)n[c+h]^=p[h]}});return e.Decryptor=s,e}(),r.mode.CTRGladman}(fe(),Xe())}(aa)),aa.exports}var na,oa={exports:{}};function To(){return na||(na=1,function(a){a.exports=function(r){return r.mode.OFB=(e=r.lib.BlockCipherMode.extend(),t=e.Encryptor=e.extend({processBlock:function(i,s){var n=this._cipher,c=n.blockSize,o=this._iv,l=this._keystream;o&&(l=this._keystream=o.slice(0),this._iv=void 0),n.encryptBlock(l,0);for(var d=0;d<c;d++)i[s+d]^=l[d]}}),e.Decryptor=t,e),r.mode.OFB;var e,t}(fe(),Xe())}(oa)),oa.exports}var ca,Co={exports:{}},la,ko={exports:{}},da,Po={exports:{}},ua,Do={exports:{}},ha,Mo={exports:{}},pa,Lo={exports:{}},ma,No={exports:{}},ga,xo={exports:{}},fa,ba={exports:{}};function Oo(){return fa||(fa=1,function(a){a.exports=function(r){return function(){var e=r,t=e.lib,i=t.WordArray,s=t.BlockCipher,n=e.algo,c=[57,49,41,33,25,17,9,1,58,50,42,34,26,18,10,2,59,51,43,35,27,19,11,3,60,52,44,36,63,55,47,39,31,23,15,7,62,54,46,38,30,22,14,6,61,53,45,37,29,21,13,5,28,20,12,4],o=[14,17,11,24,1,5,3,28,15,6,21,10,23,19,12,4,26,8,16,7,27,20,13,2,41,52,31,37,47,55,30,40,51,45,33,48,44,49,39,56,34,53,46,42,50,36,29,32],l=[1,2,4,6,8,10,12,14,15,17,19,21,23,25,27,28],d=[{0:8421888,268435456:32768,536870912:8421378,805306368:2,1073741824:512,1342177280:8421890,1610612736:8389122,1879048192:8388608,2147483648:514,2415919104:8389120,2684354560:33280,2952790016:8421376,3221225472:32770,3489660928:8388610,3758096384:0,4026531840:33282,134217728:0,402653184:8421890,671088640:33282,939524096:32768,1207959552:8421888,1476395008:512,1744830464:8421378,2013265920:2,2281701376:8389120,2550136832:33280,2818572288:8421376,3087007744:8389122,3355443200:8388610,3623878656:32770,3892314112:514,4160749568:8388608,1:32768,268435457:2,536870913:8421888,805306369:8388608,1073741825:8421378,1342177281:33280,1610612737:512,1879048193:8389122,2147483649:8421890,2415919105:8421376,2684354561:8388610,2952790017:33282,3221225473:514,3489660929:8389120,3758096385:32770,4026531841:0,134217729:8421890,402653185:8421376,671088641:8388608,939524097:512,1207959553:32768,1476395009:8388610,1744830465:2,2013265921:33282,2281701377:32770,2550136833:8389122,2818572289:514,3087007745:8421888,3355443201:8389120,3623878657:0,3892314113:33280,4160749569:8421378},{0:1074282512,16777216:16384,33554432:524288,50331648:1074266128,67108864:1073741840,83886080:1074282496,100663296:1073758208,117440512:16,134217728:540672,150994944:1073758224,167772160:1073741824,184549376:540688,201326592:524304,218103808:0,234881024:16400,251658240:1074266112,8388608:1073758208,25165824:540688,41943040:16,58720256:1073758224,75497472:1074282512,92274688:1073741824,109051904:524288,125829120:1074266128,142606336:524304,159383552:0,176160768:16384,192937984:1074266112,209715200:1073741840,226492416:540672,243269632:1074282496,260046848:16400,268435456:0,285212672:1074266128,301989888:1073758224,318767104:1074282496,335544320:1074266112,352321536:16,369098752:540688,385875968:16384,402653184:16400,419430400:524288,436207616:524304,452984832:1073741840,469762048:540672,486539264:1073758208,503316480:1073741824,520093696:1074282512,276824064:540688,293601280:524288,310378496:1074266112,327155712:16384,343932928:1073758208,360710144:1074282512,377487360:16,394264576:1073741824,411041792:1074282496,427819008:1073741840,444596224:1073758224,461373440:524304,478150656:0,494927872:16400,511705088:1074266128,528482304:540672},{0:260,1048576:0,2097152:67109120,3145728:65796,4194304:65540,5242880:67108868,6291456:67174660,7340032:67174400,8388608:67108864,9437184:67174656,10485760:65792,11534336:67174404,12582912:67109124,13631488:65536,14680064:4,15728640:256,524288:67174656,1572864:67174404,2621440:0,3670016:67109120,4718592:67108868,5767168:65536,6815744:65540,7864320:260,8912896:4,9961472:256,11010048:67174400,12058624:65796,13107200:65792,14155776:67109124,15204352:67174660,16252928:67108864,16777216:67174656,17825792:65540,18874368:65536,19922944:67109120,20971520:256,22020096:67174660,23068672:67108868,24117248:0,25165824:67109124,26214400:67108864,27262976:4,28311552:65792,29360128:67174400,30408704:260,31457280:65796,32505856:67174404,17301504:67108864,18350080:260,19398656:67174656,20447232:0,21495808:65540,22544384:67109120,23592960:256,24641536:67174404,25690112:65536,26738688:67174660,27787264:65796,28835840:67108868,29884416:67109124,30932992:67174400,31981568:4,33030144:65792},{0:2151682048,65536:2147487808,131072:4198464,196608:2151677952,262144:0,327680:4198400,393216:2147483712,458752:4194368,524288:2147483648,589824:4194304,655360:64,720896:2147487744,786432:2151678016,851968:4160,917504:4096,983040:2151682112,32768:2147487808,98304:64,163840:2151678016,229376:2147487744,294912:4198400,360448:2151682112,425984:0,491520:2151677952,557056:4096,622592:2151682048,688128:4194304,753664:4160,819200:2147483648,884736:4194368,950272:4198464,1015808:2147483712,1048576:4194368,1114112:4198400,1179648:2147483712,1245184:0,1310720:4160,1376256:2151678016,1441792:2151682048,1507328:2147487808,1572864:2151682112,1638400:2147483648,1703936:2151677952,1769472:4198464,1835008:2147487744,1900544:4194304,1966080:64,2031616:4096,1081344:2151677952,1146880:2151682112,1212416:0,1277952:4198400,1343488:4194368,1409024:2147483648,1474560:2147487808,1540096:64,1605632:2147483712,1671168:4096,1736704:2147487744,1802240:2151678016,1867776:4160,1933312:2151682048,1998848:4194304,2064384:4198464},{0:128,4096:17039360,8192:262144,12288:536870912,16384:537133184,20480:16777344,24576:553648256,28672:262272,32768:16777216,36864:537133056,40960:536871040,45056:553910400,49152:553910272,53248:0,57344:17039488,61440:553648128,2048:17039488,6144:553648256,10240:128,14336:17039360,18432:262144,22528:537133184,26624:553910272,30720:536870912,34816:537133056,38912:0,43008:553910400,47104:16777344,51200:536871040,55296:553648128,59392:16777216,63488:262272,65536:262144,69632:128,73728:536870912,77824:553648256,81920:16777344,86016:553910272,90112:537133184,94208:16777216,98304:553910400,102400:553648128,106496:17039360,110592:537133056,114688:262272,118784:536871040,122880:0,126976:17039488,67584:553648256,71680:16777216,75776:17039360,79872:537133184,83968:536870912,88064:17039488,92160:128,96256:553910272,100352:262272,104448:553910400,108544:0,112640:553648128,116736:16777344,120832:262144,124928:537133056,129024:536871040},{0:268435464,256:8192,512:270532608,768:270540808,1024:268443648,1280:2097152,1536:2097160,1792:268435456,2048:0,2304:268443656,2560:2105344,2816:8,3072:270532616,3328:2105352,3584:8200,3840:270540800,128:270532608,384:270540808,640:8,896:2097152,1152:2105352,1408:268435464,1664:268443648,1920:8200,2176:2097160,2432:8192,2688:268443656,2944:270532616,3200:0,3456:270540800,3712:2105344,3968:268435456,4096:268443648,4352:270532616,4608:270540808,4864:8200,5120:2097152,5376:268435456,5632:268435464,5888:2105344,6144:2105352,6400:0,6656:8,6912:270532608,7168:8192,7424:268443656,7680:270540800,7936:2097160,4224:8,4480:2105344,4736:2097152,4992:268435464,5248:268443648,5504:8200,5760:270540808,6016:270532608,6272:270540800,6528:270532616,6784:8192,7040:2105352,7296:2097160,7552:0,7808:268435456,8064:268443656},{0:1048576,16:33555457,32:1024,48:1049601,64:34604033,80:0,96:1,112:34603009,128:33555456,144:1048577,160:33554433,176:34604032,192:34603008,208:1025,224:1049600,240:33554432,8:34603009,24:0,40:33555457,56:34604032,72:1048576,88:33554433,104:33554432,120:1025,136:1049601,152:33555456,168:34603008,184:1048577,200:1024,216:34604033,232:1,248:1049600,256:33554432,272:1048576,288:33555457,304:34603009,320:1048577,336:33555456,352:34604032,368:1049601,384:1025,400:34604033,416:1049600,432:1,448:0,464:34603008,480:33554433,496:1024,264:1049600,280:33555457,296:34603009,312:1,328:33554432,344:1048576,360:1025,376:34604032,392:33554433,408:34603008,424:0,440:34604033,456:1049601,472:1024,488:33555456,504:1048577},{0:134219808,1:131072,2:134217728,3:32,4:131104,5:134350880,6:134350848,7:2048,8:134348800,9:134219776,10:133120,11:134348832,12:2080,13:0,14:134217760,15:133152,2147483648:2048,2147483649:134350880,2147483650:134219808,2147483651:134217728,2147483652:134348800,2147483653:133120,2147483654:133152,2147483655:32,2147483656:134217760,2147483657:2080,2147483658:131104,2147483659:134350848,2147483660:0,2147483661:134348832,2147483662:134219776,2147483663:131072,16:133152,17:134350848,18:32,19:2048,20:134219776,21:134217760,22:134348832,23:131072,24:0,25:131104,26:134348800,27:134219808,28:134350880,29:133120,30:2080,31:134217728,2147483664:131072,2147483665:2048,2147483666:134348832,2147483667:133152,2147483668:32,2147483669:134348800,2147483670:134217728,2147483671:134219808,2147483672:134350880,2147483673:134217760,2147483674:134219776,2147483675:0,2147483676:133120,2147483677:2080,2147483678:131104,2147483679:134350848}],u=[4160749569,528482304,33030144,2064384,129024,8064,504,2147483679],p=n.DES=s.extend({_doReset:function(){for(var b=this._key.words,S=[],v=0;v<56;v++){var R=c[v]-1;S[v]=b[R>>>5]>>>31-R%32&1}for(var _=this._subKeys=[],y=0;y<16;y++){var w=_[y]=[],A=l[y];for(v=0;v<24;v++)w[v/6|0]|=S[(o[v]-1+A)%28]<<31-v%6,w[4+(v/6|0)]|=S[28+(o[v+24]-1+A)%28]<<31-v%6;for(w[0]=w[0]<<1|w[0]>>>31,v=1;v<7;v++)w[v]=w[v]>>>4*(v-1)+3;w[7]=w[7]<<5|w[7]>>>27}var E=this._invSubKeys=[];for(v=0;v<16;v++)E[v]=_[15-v]},encryptBlock:function(b,S){this._doCryptBlock(b,S,this._subKeys)},decryptBlock:function(b,S){this._doCryptBlock(b,S,this._invSubKeys)},_doCryptBlock:function(b,S,v){this._lBlock=b[S],this._rBlock=b[S+1],h.call(this,4,252645135),h.call(this,16,65535),f.call(this,2,858993459),f.call(this,8,16711935),h.call(this,1,1431655765);for(var R=0;R<16;R++){for(var _=v[R],y=this._lBlock,w=this._rBlock,A=0,E=0;E<8;E++)A|=d[E][((w^_[E])&u[E])>>>0];this._lBlock=w,this._rBlock=y^A}var C=this._lBlock;this._lBlock=this._rBlock,this._rBlock=C,h.call(this,1,1431655765),f.call(this,8,16711935),f.call(this,2,858993459),h.call(this,16,65535),h.call(this,4,252645135),b[S]=this._lBlock,b[S+1]=this._rBlock},keySize:2,ivSize:2,blockSize:2});function h(b,S){var v=(this._lBlock>>>b^this._rBlock)&S;this._rBlock^=v,this._lBlock^=v<<b}function f(b,S){var v=(this._rBlock>>>b^this._lBlock)&S;this._lBlock^=v,this._rBlock^=v<<b}e.DES=s._createHelper(p);var g=n.TripleDES=s.extend({_doReset:function(){var b=this._key.words;if(b.length!==2&&b.length!==4&&b.length<6)throw new Error("Invalid key length - 3DES requires the key length to be 64, 128, 192 or >192.");var S=b.slice(0,2),v=b.length<4?b.slice(0,2):b.slice(2,4),R=b.length<6?b.slice(0,2):b.slice(4,6);this._des1=p.createEncryptor(i.create(S)),this._des2=p.createEncryptor(i.create(v)),this._des3=p.createEncryptor(i.create(R))},encryptBlock:function(b,S){this._des1.encryptBlock(b,S),this._des2.decryptBlock(b,S),this._des3.encryptBlock(b,S)},decryptBlock:function(b,S){this._des3.decryptBlock(b,S),this._des2.encryptBlock(b,S),this._des1.decryptBlock(b,S)},keySize:6,ivSize:2,blockSize:2});e.TripleDES=s._createHelper(g)}(),r.TripleDES}(fe(),si(),ri(),Kt(),Xe())}(ba)),ba.exports}var Sa,Vo={exports:{}},va,Uo={exports:{}},ya,Bo={exports:{}},Ra,Aa={exports:{}};function Ho(){return Ra||(Ra=1,function(a){a.exports=function(r){return function(){var e=r,t=e.lib.BlockCipher,i=e.algo;const s=16,n=[608135816,2242054355,320440878,57701188,2752067618,698298832,137296536,3964562569,1160258022,953160567,3193202383,887688300,3232508343,3380367581,1065670069,3041331479,2450970073,2306472731],c=[[3509652390,2564797868,805139163,3491422135,3101798381,1780907670,3128725573,4046225305,614570311,3012652279,134345442,2240740374,1667834072,1901547113,2757295779,4103290238,227898511,1921955416,1904987480,2182433518,2069144605,3260701109,2620446009,720527379,3318853667,677414384,3393288472,3101374703,2390351024,1614419982,1822297739,2954791486,3608508353,3174124327,2024746970,1432378464,3864339955,2857741204,1464375394,1676153920,1439316330,715854006,3033291828,289532110,2706671279,2087905683,3018724369,1668267050,732546397,1947742710,3462151702,2609353502,2950085171,1814351708,2050118529,680887927,999245976,1800124847,3300911131,1713906067,1641548236,4213287313,1216130144,1575780402,4018429277,3917837745,3693486850,3949271944,596196993,3549867205,258830323,2213823033,772490370,2760122372,1774776394,2652871518,566650946,4142492826,1728879713,2882767088,1783734482,3629395816,2517608232,2874225571,1861159788,326777828,3124490320,2130389656,2716951837,967770486,1724537150,2185432712,2364442137,1164943284,2105845187,998989502,3765401048,2244026483,1075463327,1455516326,1322494562,910128902,469688178,1117454909,936433444,3490320968,3675253459,1240580251,122909385,2157517691,634681816,4142456567,3825094682,3061402683,2540495037,79693498,3249098678,1084186820,1583128258,426386531,1761308591,1047286709,322548459,995290223,1845252383,2603652396,3431023940,2942221577,3202600964,3727903485,1712269319,422464435,3234572375,1170764815,3523960633,3117677531,1434042557,442511882,3600875718,1076654713,1738483198,4213154764,2393238008,3677496056,1014306527,4251020053,793779912,2902807211,842905082,4246964064,1395751752,1040244610,2656851899,3396308128,445077038,3742853595,3577915638,679411651,2892444358,2354009459,1767581616,3150600392,3791627101,3102740896,284835224,4246832056,1258075500,768725851,2589189241,3069724005,3532540348,1274779536,3789419226,2764799539,1660621633,3471099624,4011903706,913787905,3497959166,737222580,2514213453,2928710040,3937242737,1804850592,3499020752,2949064160,2386320175,2390070455,2415321851,4061277028,2290661394,2416832540,1336762016,1754252060,3520065937,3014181293,791618072,3188594551,3933548030,2332172193,3852520463,3043980520,413987798,3465142937,3030929376,4245938359,2093235073,3534596313,375366246,2157278981,2479649556,555357303,3870105701,2008414854,3344188149,4221384143,3956125452,2067696032,3594591187,2921233993,2428461,544322398,577241275,1471733935,610547355,4027169054,1432588573,1507829418,2025931657,3646575487,545086370,48609733,2200306550,1653985193,298326376,1316178497,3007786442,2064951626,458293330,2589141269,3591329599,3164325604,727753846,2179363840,146436021,1461446943,4069977195,705550613,3059967265,3887724982,4281599278,3313849956,1404054877,2845806497,146425753,1854211946],[1266315497,3048417604,3681880366,3289982499,290971e4,1235738493,2632868024,2414719590,3970600049,1771706367,1449415276,3266420449,422970021,1963543593,2690192192,3826793022,1062508698,1531092325,1804592342,2583117782,2714934279,4024971509,1294809318,4028980673,1289560198,2221992742,1669523910,35572830,157838143,1052438473,1016535060,1802137761,1753167236,1386275462,3080475397,2857371447,1040679964,2145300060,2390574316,1461121720,2956646967,4031777805,4028374788,33600511,2920084762,1018524850,629373528,3691585981,3515945977,2091462646,2486323059,586499841,988145025,935516892,3367335476,2599673255,2839830854,265290510,3972581182,2759138881,3795373465,1005194799,847297441,406762289,1314163512,1332590856,1866599683,4127851711,750260880,613907577,1450815602,3165620655,3734664991,3650291728,3012275730,3704569646,1427272223,778793252,1343938022,2676280711,2052605720,1946737175,3164576444,3914038668,3967478842,3682934266,1661551462,3294938066,4011595847,840292616,3712170807,616741398,312560963,711312465,1351876610,322626781,1910503582,271666773,2175563734,1594956187,70604529,3617834859,1007753275,1495573769,4069517037,2549218298,2663038764,504708206,2263041392,3941167025,2249088522,1514023603,1998579484,1312622330,694541497,2582060303,2151582166,1382467621,776784248,2618340202,3323268794,2497899128,2784771155,503983604,4076293799,907881277,423175695,432175456,1378068232,4145222326,3954048622,3938656102,3820766613,2793130115,2977904593,26017576,3274890735,3194772133,1700274565,1756076034,4006520079,3677328699,720338349,1533947780,354530856,688349552,3973924725,1637815568,332179504,3949051286,53804574,2852348879,3044236432,1282449977,3583942155,3416972820,4006381244,1617046695,2628476075,3002303598,1686838959,431878346,2686675385,1700445008,1080580658,1009431731,832498133,3223435511,2605976345,2271191193,2516031870,1648197032,4164389018,2548247927,300782431,375919233,238389289,3353747414,2531188641,2019080857,1475708069,455242339,2609103871,448939670,3451063019,1395535956,2413381860,1841049896,1491858159,885456874,4264095073,4001119347,1565136089,3898914787,1108368660,540939232,1173283510,2745871338,3681308437,4207628240,3343053890,4016749493,1699691293,1103962373,3625875870,2256883143,3830138730,1031889488,3479347698,1535977030,4236805024,3251091107,2132092099,1774941330,1199868427,1452454533,157007616,2904115357,342012276,595725824,1480756522,206960106,497939518,591360097,863170706,2375253569,3596610801,1814182875,2094937945,3421402208,1082520231,3463918190,2785509508,435703966,3908032597,1641649973,2842273706,3305899714,1510255612,2148256476,2655287854,3276092548,4258621189,236887753,3681803219,274041037,1734335097,3815195456,3317970021,1899903192,1026095262,4050517792,356393447,2410691914,3873677099,3682840055],[3913112168,2491498743,4132185628,2489919796,1091903735,1979897079,3170134830,3567386728,3557303409,857797738,1136121015,1342202287,507115054,2535736646,337727348,3213592640,1301675037,2528481711,1895095763,1721773893,3216771564,62756741,2142006736,835421444,2531993523,1442658625,3659876326,2882144922,676362277,1392781812,170690266,3921047035,1759253602,3611846912,1745797284,664899054,1329594018,3901205900,3045908486,2062866102,2865634940,3543621612,3464012697,1080764994,553557557,3656615353,3996768171,991055499,499776247,1265440854,648242737,3940784050,980351604,3713745714,1749149687,3396870395,4211799374,3640570775,1161844396,3125318951,1431517754,545492359,4268468663,3499529547,1437099964,2702547544,3433638243,2581715763,2787789398,1060185593,1593081372,2418618748,4260947970,69676912,2159744348,86519011,2512459080,3838209314,1220612927,3339683548,133810670,1090789135,1078426020,1569222167,845107691,3583754449,4072456591,1091646820,628848692,1613405280,3757631651,526609435,236106946,48312990,2942717905,3402727701,1797494240,859738849,992217954,4005476642,2243076622,3870952857,3732016268,765654824,3490871365,2511836413,1685915746,3888969200,1414112111,2273134842,3281911079,4080962846,172450625,2569994100,980381355,4109958455,2819808352,2716589560,2568741196,3681446669,3329971472,1835478071,660984891,3704678404,4045999559,3422617507,3040415634,1762651403,1719377915,3470491036,2693910283,3642056355,3138596744,1364962596,2073328063,1983633131,926494387,3423689081,2150032023,4096667949,1749200295,3328846651,309677260,2016342300,1779581495,3079819751,111262694,1274766160,443224088,298511866,1025883608,3806446537,1145181785,168956806,3641502830,3584813610,1689216846,3666258015,3200248200,1692713982,2646376535,4042768518,1618508792,1610833997,3523052358,4130873264,2001055236,3610705100,2202168115,4028541809,2961195399,1006657119,2006996926,3186142756,1430667929,3210227297,1314452623,4074634658,4101304120,2273951170,1399257539,3367210612,3027628629,1190975929,2062231137,2333990788,2221543033,2438960610,1181637006,548689776,2362791313,3372408396,3104550113,3145860560,296247880,1970579870,3078560182,3769228297,1714227617,3291629107,3898220290,166772364,1251581989,493813264,448347421,195405023,2709975567,677966185,3703036547,1463355134,2715995803,1338867538,1343315457,2802222074,2684532164,233230375,2599980071,2000651841,3277868038,1638401717,4028070440,3237316320,6314154,819756386,300326615,590932579,1405279636,3267499572,3150704214,2428286686,3959192993,3461946742,1862657033,1266418056,963775037,2089974820,2263052895,1917689273,448879540,3550394620,3981727096,150775221,3627908307,1303187396,508620638,2975983352,2726630617,1817252668,1876281319,1457606340,908771278,3720792119,3617206836,2455994898,1729034894,1080033504],[976866871,3556439503,2881648439,1522871579,1555064734,1336096578,3548522304,2579274686,3574697629,3205460757,3593280638,3338716283,3079412587,564236357,2993598910,1781952180,1464380207,3163844217,3332601554,1699332808,1393555694,1183702653,3581086237,1288719814,691649499,2847557200,2895455976,3193889540,2717570544,1781354906,1676643554,2592534050,3230253752,1126444790,2770207658,2633158820,2210423226,2615765581,2414155088,3127139286,673620729,2805611233,1269405062,4015350505,3341807571,4149409754,1057255273,2012875353,2162469141,2276492801,2601117357,993977747,3918593370,2654263191,753973209,36408145,2530585658,25011837,3520020182,2088578344,530523599,2918365339,1524020338,1518925132,3760827505,3759777254,1202760957,3985898139,3906192525,674977740,4174734889,2031300136,2019492241,3983892565,4153806404,3822280332,352677332,2297720250,60907813,90501309,3286998549,1016092578,2535922412,2839152426,457141659,509813237,4120667899,652014361,1966332200,2975202805,55981186,2327461051,676427537,3255491064,2882294119,3433927263,1307055953,942726286,933058658,2468411793,3933900994,4215176142,1361170020,2001714738,2830558078,3274259782,1222529897,1679025792,2729314320,3714953764,1770335741,151462246,3013232138,1682292957,1483529935,471910574,1539241949,458788160,3436315007,1807016891,3718408830,978976581,1043663428,3165965781,1927990952,4200891579,2372276910,3208408903,3533431907,1412390302,2931980059,4132332400,1947078029,3881505623,4168226417,2941484381,1077988104,1320477388,886195818,18198404,3786409e3,2509781533,112762804,3463356488,1866414978,891333506,18488651,661792760,1628790961,3885187036,3141171499,876946877,2693282273,1372485963,791857591,2686433993,3759982718,3167212022,3472953795,2716379847,445679433,3561995674,3504004811,3574258232,54117162,3331405415,2381918588,3769707343,4154350007,1140177722,4074052095,668550556,3214352940,367459370,261225585,2610173221,4209349473,3468074219,3265815641,314222801,3066103646,3808782860,282218597,3406013506,3773591054,379116347,1285071038,846784868,2669647154,3771962079,3550491691,2305946142,453669953,1268987020,3317592352,3279303384,3744833421,2610507566,3859509063,266596637,3847019092,517658769,3462560207,3443424879,370717030,4247526661,2224018117,4143653529,4112773975,2788324899,2477274417,1456262402,2901442914,1517677493,1846949527,2295493580,3734397586,2176403920,1280348187,1908823572,3871786941,846861322,1172426758,3287448474,3383383037,1655181056,3139813346,901632758,1897031941,2986607138,3066810236,3447102507,1393639104,373351379,950779232,625454576,3124240540,4148612726,2007998917,544563296,2244738638,2330496472,2058025392,1291430526,424198748,50039436,29584100,3605783033,2429876329,2791104160,1057563949,3255363231,3075367218,3463963227,1469046755,985887462]];var o={pbox:[],sbox:[]};function l(f,g){let b=g>>24&255,S=g>>16&255,v=g>>8&255,R=255&g,_=f.sbox[0][b]+f.sbox[1][S];return _^=f.sbox[2][v],_+=f.sbox[3][R],_}function d(f,g,b){let S,v=g,R=b;for(let _=0;_<s;++_)v^=f.pbox[_],R=l(f,v)^R,S=v,v=R,R=S;return S=v,v=R,R=S,R^=f.pbox[s],v^=f.pbox[s+1],{left:v,right:R}}function u(f,g,b){let S,v=g,R=b;for(let _=s+1;_>1;--_)v^=f.pbox[_],R=l(f,v)^R,S=v,v=R,R=S;return S=v,v=R,R=S,R^=f.pbox[1],v^=f.pbox[0],{left:v,right:R}}function p(f,g,b){for(let y=0;y<4;y++){f.sbox[y]=[];for(let w=0;w<256;w++)f.sbox[y][w]=c[y][w]}let S=0;for(let y=0;y<s+2;y++)f.pbox[y]=n[y]^g[S],S++,S>=b&&(S=0);let v=0,R=0,_=0;for(let y=0;y<s+2;y+=2)_=d(f,v,R),v=_.left,R=_.right,f.pbox[y]=v,f.pbox[y+1]=R;for(let y=0;y<4;y++)for(let w=0;w<256;w+=2)_=d(f,v,R),v=_.left,R=_.right,f.sbox[y][w]=v,f.sbox[y][w+1]=R;return!0}var h=i.Blowfish=t.extend({_doReset:function(){if(this._keyPriorReset!==this._key){var f=this._keyPriorReset=this._key,g=f.words,b=f.sigBytes/4;p(o,g,b)}},encryptBlock:function(f,g){var b=d(o,f[g],f[g+1]);f[g]=b.left,f[g+1]=b.right},decryptBlock:function(f,g){var b=u(o,f[g],f[g+1]);f[g]=b.left,f[g+1]=b.right},blockSize:2,keySize:4,ivSize:2});e.Blowfish=t._createHelper(h)}(),r.Blowfish}(fe(),si(),ri(),Kt(),Xe())}(Aa)),Aa.exports}(function(a){a.exports=function(r){return r}(fe(),ji(),fo(),bo(),si(),So(),ri(),Or(),ps(),Br||(Br=1,function(r){r.exports=function(e){return i=(t=e).lib.WordArray,s=t.algo,n=s.SHA256,c=s.SHA224=n.extend({_doReset:function(){this._hash=new i.init([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428])},_doFinalize:function(){var o=n._doFinalize.call(this);return o.sigBytes-=4,o}}),t.SHA224=n._createHelper(c),t.HmacSHA224=n._createHmacHelper(c),e.SHA224;var t,i,s,n,c}(fe(),ps())}(vo)),jr(),$r||($r=1,function(r){r.exports=function(e){return i=(t=e).x64,s=i.Word,n=i.WordArray,c=t.algo,o=c.SHA512,l=c.SHA384=o.extend({_doReset:function(){this._hash=new n.init([new s.init(3418070365,3238371032),new s.init(1654270250,914150663),new s.init(2438529370,812702999),new s.init(355462360,4144912697),new s.init(1731405415,4290775857),new s.init(2394180231,1750603025),new s.init(3675008525,1694076839),new s.init(1203062813,3204075428)])},_doFinalize:function(){var d=o._doFinalize.call(this);return d.sigBytes-=16,d}}),t.SHA384=o._createHelper(l),t.HmacSHA384=o._createHmacHelper(l),e.SHA384;var t,i,s,n,c,o,l}(fe(),ji(),jr())}(yo)),Ro(),Kr||(Kr=1,function(r){r.exports=function(e){return function(){var t=e,i=t.lib,s=i.WordArray,n=i.Hasher,c=t.algo,o=s.create([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13]),l=s.create([5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11]),d=s.create([11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6]),u=s.create([8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]),p=s.create([0,1518500249,1859775393,2400959708,2840853838]),h=s.create([1352829926,1548603684,1836072691,2053994217,0]),f=c.RIPEMD160=n.extend({_doReset:function(){this._hash=s.create([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(y,w){for(var A=0;A<16;A++){var E=w+A,C=y[E];y[E]=16711935&(C<<8|C>>>24)|4278255360&(C<<24|C>>>8)}var P,M,x,K,Q,G,W,Z,te,Se,L,O=this._hash.words,N=p.words,V=h.words,he=o.words,xe=l.words,q=d.words,Re=u.words;for(G=P=O[0],W=M=O[1],Z=x=O[2],te=K=O[3],Se=Q=O[4],A=0;A<80;A+=1)L=P+y[w+he[A]]|0,L+=A<16?g(M,x,K)+N[0]:A<32?b(M,x,K)+N[1]:A<48?S(M,x,K)+N[2]:A<64?v(M,x,K)+N[3]:R(M,x,K)+N[4],L=(L=_(L|=0,q[A]))+Q|0,P=Q,Q=K,K=_(x,10),x=M,M=L,L=G+y[w+xe[A]]|0,L+=A<16?R(W,Z,te)+V[0]:A<32?v(W,Z,te)+V[1]:A<48?S(W,Z,te)+V[2]:A<64?b(W,Z,te)+V[3]:g(W,Z,te)+V[4],L=(L=_(L|=0,Re[A]))+Se|0,G=Se,Se=te,te=_(Z,10),Z=W,W=L;L=O[1]+x+te|0,O[1]=O[2]+K+Se|0,O[2]=O[3]+Q+G|0,O[3]=O[4]+P+W|0,O[4]=O[0]+M+Z|0,O[0]=L},_doFinalize:function(){var y=this._data,w=y.words,A=8*this._nDataBytes,E=8*y.sigBytes;w[E>>>5]|=128<<24-E%32,w[14+(E+64>>>9<<4)]=16711935&(A<<8|A>>>24)|4278255360&(A<<24|A>>>8),y.sigBytes=4*(w.length+1),this._process();for(var C=this._hash,P=C.words,M=0;M<5;M++){var x=P[M];P[M]=16711935&(x<<8|x>>>24)|4278255360&(x<<24|x>>>8)}return C},clone:function(){var y=n.clone.call(this);return y._hash=this._hash.clone(),y}});function g(y,w,A){return y^w^A}function b(y,w,A){return y&w|~y&A}function S(y,w,A){return(y|~w)^A}function v(y,w,A){return y&A|w&~A}function R(y,w,A){return y^(w|~A)}function _(y,w){return y<<w|y>>>32-w}t.RIPEMD160=n._createHelper(f),t.HmacRIPEMD160=n._createHmacHelper(f)}(),e.RIPEMD160}(fe())}(Ao)),ms(),Gr||(Gr=1,function(r){r.exports=function(e){return s=(i=(t=e).lib).Base,n=i.WordArray,o=(c=t.algo).SHA256,l=c.HMAC,d=c.PBKDF2=s.extend({cfg:s.extend({keySize:4,hasher:o,iterations:25e4}),init:function(u){this.cfg=this.cfg.extend(u)},compute:function(u,p){for(var h=this.cfg,f=l.create(h.hasher,u),g=n.create(),b=n.create([1]),S=g.words,v=b.words,R=h.keySize,_=h.iterations;S.length<R;){var y=f.update(p).finalize(b);f.reset();for(var w=y.words,A=w.length,E=y,C=1;C<_;C++){E=f.finalize(E),f.reset();for(var P=E.words,M=0;M<A;M++)w[M]^=P[M]}g.concat(y),v[0]++}return g.sigBytes=4*R,g}}),t.PBKDF2=function(u,p,h){return d.create(h).compute(u,p)},e.PBKDF2;var t,i,s,n,c,o,l,d}(fe(),ps(),ms())}(wo)),Kt(),Xe(),_o(),Io(),Eo(),To(),ca||(ca=1,function(r){r.exports=function(e){return e.mode.ECB=((t=e.lib.BlockCipherMode.extend()).Encryptor=t.extend({processBlock:function(i,s){this._cipher.encryptBlock(i,s)}}),t.Decryptor=t.extend({processBlock:function(i,s){this._cipher.decryptBlock(i,s)}}),t),e.mode.ECB;var t}(fe(),Xe())}(Co)),la||(la=1,function(r){r.exports=function(e){return e.pad.AnsiX923={pad:function(t,i){var s=t.sigBytes,n=4*i,c=n-s%n,o=s+c-1;t.clamp(),t.words[o>>>2]|=c<<24-o%4*8,t.sigBytes+=c},unpad:function(t){var i=255&t.words[t.sigBytes-1>>>2];t.sigBytes-=i}},e.pad.Ansix923}(fe(),Xe())}(ko)),da||(da=1,function(r){r.exports=function(e){return e.pad.Iso10126={pad:function(t,i){var s=4*i,n=s-t.sigBytes%s;t.concat(e.lib.WordArray.random(n-1)).concat(e.lib.WordArray.create([n<<24],1))},unpad:function(t){var i=255&t.words[t.sigBytes-1>>>2];t.sigBytes-=i}},e.pad.Iso10126}(fe(),Xe())}(Po)),ua||(ua=1,function(r){r.exports=function(e){return e.pad.Iso97971={pad:function(t,i){t.concat(e.lib.WordArray.create([2147483648],1)),e.pad.ZeroPadding.pad(t,i)},unpad:function(t){e.pad.ZeroPadding.unpad(t),t.sigBytes--}},e.pad.Iso97971}(fe(),Xe())}(Do)),ha||(ha=1,function(r){r.exports=function(e){return e.pad.ZeroPadding={pad:function(t,i){var s=4*i;t.clamp(),t.sigBytes+=s-(t.sigBytes%s||s)},unpad:function(t){var i=t.words,s=t.sigBytes-1;for(s=t.sigBytes-1;s>=0;s--)if(i[s>>>2]>>>24-s%4*8&255){t.sigBytes=s+1;break}}},e.pad.ZeroPadding}(fe(),Xe())}(Mo)),pa||(pa=1,function(r){r.exports=function(e){return e.pad.NoPadding={pad:function(){},unpad:function(){}},e.pad.NoPadding}(fe(),Xe())}(Lo)),ma||(ma=1,function(r){r.exports=function(e){return i=(t=e).lib.CipherParams,s=t.enc.Hex,t.format.Hex={stringify:function(n){return n.ciphertext.toString(s)},parse:function(n){var c=s.parse(n);return i.create({ciphertext:c})}},e.format.Hex;var t,i,s}(fe(),Xe())}(No)),ga||(ga=1,function(r){r.exports=function(e){return function(){var t=e,i=t.lib.BlockCipher,s=t.algo,n=[],c=[],o=[],l=[],d=[],u=[],p=[],h=[],f=[],g=[];(function(){for(var v=[],R=0;R<256;R++)v[R]=R<128?R<<1:R<<1^283;var _=0,y=0;for(R=0;R<256;R++){var w=y^y<<1^y<<2^y<<3^y<<4;w=w>>>8^255&w^99,n[_]=w,c[w]=_;var A=v[_],E=v[A],C=v[E],P=257*v[w]^16843008*w;o[_]=P<<24|P>>>8,l[_]=P<<16|P>>>16,d[_]=P<<8|P>>>24,u[_]=P,P=16843009*C^65537*E^257*A^16843008*_,p[w]=P<<24|P>>>8,h[w]=P<<16|P>>>16,f[w]=P<<8|P>>>24,g[w]=P,_?(_=A^v[v[v[C^A]]],y^=v[v[y]]):_=y=1}})();var b=[0,1,2,4,8,16,32,64,128,27,54],S=s.AES=i.extend({_doReset:function(){if(!this._nRounds||this._keyPriorReset!==this._key){for(var v=this._keyPriorReset=this._key,R=v.words,_=v.sigBytes/4,y=4*((this._nRounds=_+6)+1),w=this._keySchedule=[],A=0;A<y;A++)A<_?w[A]=R[A]:(P=w[A-1],A%_?_>6&&A%_==4&&(P=n[P>>>24]<<24|n[P>>>16&255]<<16|n[P>>>8&255]<<8|n[255&P]):(P=n[(P=P<<8|P>>>24)>>>24]<<24|n[P>>>16&255]<<16|n[P>>>8&255]<<8|n[255&P],P^=b[A/_|0]<<24),w[A]=w[A-_]^P);for(var E=this._invKeySchedule=[],C=0;C<y;C++){if(A=y-C,C%4)var P=w[A];else P=w[A-4];E[C]=C<4||A<=4?P:p[n[P>>>24]]^h[n[P>>>16&255]]^f[n[P>>>8&255]]^g[n[255&P]]}}},encryptBlock:function(v,R){this._doCryptBlock(v,R,this._keySchedule,o,l,d,u,n)},decryptBlock:function(v,R){var _=v[R+1];v[R+1]=v[R+3],v[R+3]=_,this._doCryptBlock(v,R,this._invKeySchedule,p,h,f,g,c),_=v[R+1],v[R+1]=v[R+3],v[R+3]=_},_doCryptBlock:function(v,R,_,y,w,A,E,C){for(var P=this._nRounds,M=v[R]^_[0],x=v[R+1]^_[1],K=v[R+2]^_[2],Q=v[R+3]^_[3],G=4,W=1;W<P;W++){var Z=y[M>>>24]^w[x>>>16&255]^A[K>>>8&255]^E[255&Q]^_[G++],te=y[x>>>24]^w[K>>>16&255]^A[Q>>>8&255]^E[255&M]^_[G++],Se=y[K>>>24]^w[Q>>>16&255]^A[M>>>8&255]^E[255&x]^_[G++],L=y[Q>>>24]^w[M>>>16&255]^A[x>>>8&255]^E[255&K]^_[G++];M=Z,x=te,K=Se,Q=L}Z=(C[M>>>24]<<24|C[x>>>16&255]<<16|C[K>>>8&255]<<8|C[255&Q])^_[G++],te=(C[x>>>24]<<24|C[K>>>16&255]<<16|C[Q>>>8&255]<<8|C[255&M])^_[G++],Se=(C[K>>>24]<<24|C[Q>>>16&255]<<16|C[M>>>8&255]<<8|C[255&x])^_[G++],L=(C[Q>>>24]<<24|C[M>>>16&255]<<16|C[x>>>8&255]<<8|C[255&K])^_[G++],v[R]=Z,v[R+1]=te,v[R+2]=Se,v[R+3]=L},keySize:8});t.AES=i._createHelper(S)}(),e.AES}(fe(),si(),ri(),Kt(),Xe())}(xo)),Oo(),Sa||(Sa=1,function(r){r.exports=function(e){return function(){var t=e,i=t.lib.StreamCipher,s=t.algo,n=s.RC4=i.extend({_doReset:function(){for(var l=this._key,d=l.words,u=l.sigBytes,p=this._S=[],h=0;h<256;h++)p[h]=h;h=0;for(var f=0;h<256;h++){var g=h%u,b=d[g>>>2]>>>24-g%4*8&255;f=(f+p[h]+b)%256;var S=p[h];p[h]=p[f],p[f]=S}this._i=this._j=0},_doProcessBlock:function(l,d){l[d]^=c.call(this)},keySize:8,ivSize:0});function c(){for(var l=this._S,d=this._i,u=this._j,p=0,h=0;h<4;h++){u=(u+l[d=(d+1)%256])%256;var f=l[d];l[d]=l[u],l[u]=f,p|=l[(l[d]+l[u])%256]<<24-8*h}return this._i=d,this._j=u,p}t.RC4=i._createHelper(n);var o=s.RC4Drop=n.extend({cfg:n.cfg.extend({drop:192}),_doReset:function(){n._doReset.call(this);for(var l=this.cfg.drop;l>0;l--)c.call(this)}});t.RC4Drop=i._createHelper(o)}(),e.RC4}(fe(),si(),ri(),Kt(),Xe())}(Vo)),va||(va=1,function(r){r.exports=function(e){return function(){var t=e,i=t.lib.StreamCipher,s=t.algo,n=[],c=[],o=[],l=s.Rabbit=i.extend({_doReset:function(){for(var u=this._key.words,p=this.cfg.iv,h=0;h<4;h++)u[h]=16711935&(u[h]<<8|u[h]>>>24)|4278255360&(u[h]<<24|u[h]>>>8);var f=this._X=[u[0],u[3]<<16|u[2]>>>16,u[1],u[0]<<16|u[3]>>>16,u[2],u[1]<<16|u[0]>>>16,u[3],u[2]<<16|u[1]>>>16],g=this._C=[u[2]<<16|u[2]>>>16,4294901760&u[0]|65535&u[1],u[3]<<16|u[3]>>>16,4294901760&u[1]|65535&u[2],u[0]<<16|u[0]>>>16,4294901760&u[2]|65535&u[3],u[1]<<16|u[1]>>>16,4294901760&u[3]|65535&u[0]];for(this._b=0,h=0;h<4;h++)d.call(this);for(h=0;h<8;h++)g[h]^=f[h+4&7];if(p){var b=p.words,S=b[0],v=b[1],R=16711935&(S<<8|S>>>24)|4278255360&(S<<24|S>>>8),_=16711935&(v<<8|v>>>24)|4278255360&(v<<24|v>>>8),y=R>>>16|4294901760&_,w=_<<16|65535&R;for(g[0]^=R,g[1]^=y,g[2]^=_,g[3]^=w,g[4]^=R,g[5]^=y,g[6]^=_,g[7]^=w,h=0;h<4;h++)d.call(this)}},_doProcessBlock:function(u,p){var h=this._X;d.call(this),n[0]=h[0]^h[5]>>>16^h[3]<<16,n[1]=h[2]^h[7]>>>16^h[5]<<16,n[2]=h[4]^h[1]>>>16^h[7]<<16,n[3]=h[6]^h[3]>>>16^h[1]<<16;for(var f=0;f<4;f++)n[f]=16711935&(n[f]<<8|n[f]>>>24)|4278255360&(n[f]<<24|n[f]>>>8),u[p+f]^=n[f]},blockSize:4,ivSize:2});function d(){for(var u=this._X,p=this._C,h=0;h<8;h++)c[h]=p[h];for(p[0]=p[0]+1295307597+this._b|0,p[1]=p[1]+3545052371+(p[0]>>>0<c[0]>>>0?1:0)|0,p[2]=p[2]+886263092+(p[1]>>>0<c[1]>>>0?1:0)|0,p[3]=p[3]+1295307597+(p[2]>>>0<c[2]>>>0?1:0)|0,p[4]=p[4]+3545052371+(p[3]>>>0<c[3]>>>0?1:0)|0,p[5]=p[5]+886263092+(p[4]>>>0<c[4]>>>0?1:0)|0,p[6]=p[6]+1295307597+(p[5]>>>0<c[5]>>>0?1:0)|0,p[7]=p[7]+3545052371+(p[6]>>>0<c[6]>>>0?1:0)|0,this._b=p[7]>>>0<c[7]>>>0?1:0,h=0;h<8;h++){var f=u[h]+p[h],g=65535&f,b=f>>>16,S=((g*g>>>17)+g*b>>>15)+b*b,v=((4294901760&f)*f|0)+((65535&f)*f|0);o[h]=S^v}u[0]=o[0]+(o[7]<<16|o[7]>>>16)+(o[6]<<16|o[6]>>>16)|0,u[1]=o[1]+(o[0]<<8|o[0]>>>24)+o[7]|0,u[2]=o[2]+(o[1]<<16|o[1]>>>16)+(o[0]<<16|o[0]>>>16)|0,u[3]=o[3]+(o[2]<<8|o[2]>>>24)+o[1]|0,u[4]=o[4]+(o[3]<<16|o[3]>>>16)+(o[2]<<16|o[2]>>>16)|0,u[5]=o[5]+(o[4]<<8|o[4]>>>24)+o[3]|0,u[6]=o[6]+(o[5]<<16|o[5]>>>16)+(o[4]<<16|o[4]>>>16)|0,u[7]=o[7]+(o[6]<<8|o[6]>>>24)+o[5]|0}t.Rabbit=i._createHelper(l)}(),e.Rabbit}(fe(),si(),ri(),Kt(),Xe())}(Uo)),ya||(ya=1,function(r){r.exports=function(e){return function(){var t=e,i=t.lib.StreamCipher,s=t.algo,n=[],c=[],o=[],l=s.RabbitLegacy=i.extend({_doReset:function(){var u=this._key.words,p=this.cfg.iv,h=this._X=[u[0],u[3]<<16|u[2]>>>16,u[1],u[0]<<16|u[3]>>>16,u[2],u[1]<<16|u[0]>>>16,u[3],u[2]<<16|u[1]>>>16],f=this._C=[u[2]<<16|u[2]>>>16,4294901760&u[0]|65535&u[1],u[3]<<16|u[3]>>>16,4294901760&u[1]|65535&u[2],u[0]<<16|u[0]>>>16,4294901760&u[2]|65535&u[3],u[1]<<16|u[1]>>>16,4294901760&u[3]|65535&u[0]];this._b=0;for(var g=0;g<4;g++)d.call(this);for(g=0;g<8;g++)f[g]^=h[g+4&7];if(p){var b=p.words,S=b[0],v=b[1],R=16711935&(S<<8|S>>>24)|4278255360&(S<<24|S>>>8),_=16711935&(v<<8|v>>>24)|4278255360&(v<<24|v>>>8),y=R>>>16|4294901760&_,w=_<<16|65535&R;for(f[0]^=R,f[1]^=y,f[2]^=_,f[3]^=w,f[4]^=R,f[5]^=y,f[6]^=_,f[7]^=w,g=0;g<4;g++)d.call(this)}},_doProcessBlock:function(u,p){var h=this._X;d.call(this),n[0]=h[0]^h[5]>>>16^h[3]<<16,n[1]=h[2]^h[7]>>>16^h[5]<<16,n[2]=h[4]^h[1]>>>16^h[7]<<16,n[3]=h[6]^h[3]>>>16^h[1]<<16;for(var f=0;f<4;f++)n[f]=16711935&(n[f]<<8|n[f]>>>24)|4278255360&(n[f]<<24|n[f]>>>8),u[p+f]^=n[f]},blockSize:4,ivSize:2});function d(){for(var u=this._X,p=this._C,h=0;h<8;h++)c[h]=p[h];for(p[0]=p[0]+1295307597+this._b|0,p[1]=p[1]+3545052371+(p[0]>>>0<c[0]>>>0?1:0)|0,p[2]=p[2]+886263092+(p[1]>>>0<c[1]>>>0?1:0)|0,p[3]=p[3]+1295307597+(p[2]>>>0<c[2]>>>0?1:0)|0,p[4]=p[4]+3545052371+(p[3]>>>0<c[3]>>>0?1:0)|0,p[5]=p[5]+886263092+(p[4]>>>0<c[4]>>>0?1:0)|0,p[6]=p[6]+1295307597+(p[5]>>>0<c[5]>>>0?1:0)|0,p[7]=p[7]+3545052371+(p[6]>>>0<c[6]>>>0?1:0)|0,this._b=p[7]>>>0<c[7]>>>0?1:0,h=0;h<8;h++){var f=u[h]+p[h],g=65535&f,b=f>>>16,S=((g*g>>>17)+g*b>>>15)+b*b,v=((4294901760&f)*f|0)+((65535&f)*f|0);o[h]=S^v}u[0]=o[0]+(o[7]<<16|o[7]>>>16)+(o[6]<<16|o[6]>>>16)|0,u[1]=o[1]+(o[0]<<8|o[0]>>>24)+o[7]|0,u[2]=o[2]+(o[1]<<16|o[1]>>>16)+(o[0]<<16|o[0]>>>16)|0,u[3]=o[3]+(o[2]<<8|o[2]>>>24)+o[1]|0,u[4]=o[4]+(o[3]<<16|o[3]>>>16)+(o[2]<<16|o[2]>>>16)|0,u[5]=o[5]+(o[4]<<8|o[4]>>>24)+o[3]|0,u[6]=o[6]+(o[5]<<16|o[5]>>>16)+(o[4]<<16|o[4]>>>16)|0,u[7]=o[7]+(o[6]<<8|o[6]>>>24)+o[5]|0}t.RabbitLegacy=i._createHelper(l)}(),e.RabbitLegacy}(fe(),si(),ri(),Kt(),Xe())}(Bo)),Ho())})(vr);const ai=po(vr.exports);function Fo(a){return r=this,e=null,t=function*(){const i=new Date;if(a.refreshSTSTokenInterval||(a.refreshSTSTokenInterval=3e5),!a.stsTokenFreshTime||+i-a.stsTokenFreshTime>=a.refreshSTSTokenInterval){a.stsTokenFreshTime=i;try{yield a.refreshSTSToken()}catch(s){typeof console.error=="function"&&console.error(`Some error occured during excuting refreshSTSToken, see:
5
5
  `+s)}}return null},new Promise((i,s)=>{var n=l=>{try{o(t.next(l))}catch(d){s(d)}},c=l=>{try{o(t.throw(l))}catch(d){s(d)}},o=l=>l.done?i(l.value):Promise.resolve(l.value).then(n,c);o((t=t.apply(r,e)).next())});var r,e,t}function gs(a){return{transString:function(r){let e={},t=0,i=!1;for(let s in r)s!=="time"&&s!=="__time__"||typeof r[s]!="number"?typeof r[s]=="object"?e[s]=JSON.stringify(r[s]):e[s]=String(r[s]):(t=r[s],i=!0);return e.__time__=i?t:Math.floor(new Date().getTime()/1e3),e},process:function(r,e){return t=this,i=null,s=function*(){yield Fo(a);let n=r.slice(r.indexOf("/logstores")),c=e.length,o=(l=e,ai.MD5(l).toString().toUpperCase());var l;let d=new Date().toUTCString(),u=new Map,p=new Map([["Content-Type","application/json"],["Content-MD5",o],["x-log-bodyrawsize",c.toString()]]);a.securityToken&&p.set("x-acs-security-token",a.securityToken),function(f,g,b,S,v,R,_,y){var w;let A="";R.set("x-log-apiversion","0.6.0"),R.set("x-log-signaturemethod","hmac-sha1"),A+=f+`
6
6
  `+_+`
7
7
  `+((w=R.get("Content-Type"))!=null?w:"")+`
@@ -9,7 +9,7 @@
9
9
  `;const E=(M,x)=>M[0].localeCompare(x[0]),C=M=>M[0].startsWith("x-log-")||M[0].startsWith("x-acs-");try{const M=[...R.entries()].filter(C).sort(E).map(x=>x[0]+":"+x[1]+`
10
10
  `).join("");A+=M}catch(M){}A+=g,v.size>0&&(A+="?");try{A+=[...v.entries()].sort(E).map(M=>M[0]+"="+M[1]).join("&")}catch(M){}const P="LOG "+b+":"+ai.HmacSHA1(A,S).toString(ai.enc.Base64);R.set("Authorization",P),R.set("x-log-date",y)}("POST",n,a.accessKeyId,a.accessKeySecret,u,p,o,d);let h=Object.fromEntries(p);return{data:e,header:h}},new Promise((n,c)=>{var o=u=>{try{d(s.next(u))}catch(p){c(p)}},l=u=>{try{d(s.throw(u))}catch(p){c(p)}},d=u=>u.done?n(u.value):Promise.resolve(u.value).then(o,l);d((s=s.apply(t,i)).next())});var t,i,s}}}typeof window!="undefined"&&Sr(window,"stsPlugin",gs);var jo=/d{1,4}|D{3,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|W{1,2}|[LlopSZN]|"[^"]*"|'[^']*'/g,$o=/\b(?:[A-Z]{1,3}[A-Z][TC])(?:[-+]\d{4})?|((?:Australian )?(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time)\b/g,Wo=/[^-+\dA-Z]/g;function $i(a,r,e,t){if(arguments.length!==1||typeof a!="string"||/\d/.test(a)||(r=a,a=void 0),(a=a||a===0?a:new Date)instanceof Date||(a=new Date(a)),isNaN(a))throw TypeError("Invalid date");var i=(r=String(wa[r]||r||wa.default)).slice(0,4);i!=="UTC:"&&i!=="GMT:"||(r=r.slice(4),e=!0,i==="GMT:"&&(t=!0));var s=function(){return e?"getUTC":"get"},n=function(){return a[s()+"Date"]()},c=function(){return a[s()+"Day"]()},o=function(){return a[s()+"Month"]()},l=function(){return a[s()+"FullYear"]()},d=function(){return a[s()+"Hours"]()},u=function(){return a[s()+"Minutes"]()},p=function(){return a[s()+"Seconds"]()},h=function(){return a[s()+"Milliseconds"]()},f=function(){return e?0:a.getTimezoneOffset()},g=function(){return zo(a)},b={d:function(){return n()},dd:function(){return gt(n())},ddd:function(){return ct.dayNames[c()]},DDD:function(){return _a({y:l(),m:o(),d:n(),_:s(),dayName:ct.dayNames[c()],short:!0})},dddd:function(){return ct.dayNames[c()+7]},DDDD:function(){return _a({y:l(),m:o(),d:n(),_:s(),dayName:ct.dayNames[c()+7]})},m:function(){return o()+1},mm:function(){return gt(o()+1)},mmm:function(){return ct.monthNames[o()]},mmmm:function(){return ct.monthNames[o()+12]},yy:function(){return String(l()).slice(2)},yyyy:function(){return gt(l(),4)},h:function(){return d()%12||12},hh:function(){return gt(d()%12||12)},H:function(){return d()},HH:function(){return gt(d())},M:function(){return u()},MM:function(){return gt(u())},s:function(){return p()},ss:function(){return gt(p())},l:function(){return gt(h(),3)},L:function(){return gt(Math.floor(h()/10))},t:function(){return d()<12?ct.timeNames[0]:ct.timeNames[1]},tt:function(){return d()<12?ct.timeNames[2]:ct.timeNames[3]},T:function(){return d()<12?ct.timeNames[4]:ct.timeNames[5]},TT:function(){return d()<12?ct.timeNames[6]:ct.timeNames[7]},Z:function(){return t?"GMT":e?"UTC":Jo(a)},o:function(){return(f()>0?"-":"+")+gt(100*Math.floor(Math.abs(f())/60)+Math.abs(f())%60,4)},p:function(){return(f()>0?"-":"+")+gt(Math.floor(Math.abs(f())/60),2)+":"+gt(Math.floor(Math.abs(f())%60),2)},S:function(){return["th","st","nd","rd"][n()%10>3?0:(n()%100-n()%10!=10)*n()%10]},W:function(){return g()},WW:function(){return gt(g())},N:function(){return Ko(a)}};return r.replace(jo,function(S){return S in b?b[S]():S.slice(1,S.length-1)})}var wa={default:"ddd mmm dd yyyy HH:MM:ss",shortDate:"m/d/yy",paddedShortDate:"mm/dd/yyyy",mediumDate:"mmm d, yyyy",longDate:"mmmm d, yyyy",fullDate:"dddd, mmmm d, yyyy",shortTime:"h:MM TT",mediumTime:"h:MM:ss TT",longTime:"h:MM:ss TT Z",isoDate:"yyyy-mm-dd",isoTime:"HH:MM:ss",isoDateTime:"yyyy-mm-dd'T'HH:MM:sso",isoUtcDateTime:"UTC:yyyy-mm-dd'T'HH:MM:ss'Z'",expiresHeaderFormat:"ddd, dd mmm yyyy HH:MM:ss Z"},ct={dayNames:["Sun","Mon","Tue","Wed","Thu","Fri","Sat","Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],monthNames:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec","January","February","March","April","May","June","July","August","September","October","November","December"],timeNames:["a","p","am","pm","A","P","AM","PM"]},gt=function(a){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:2;return String(a).padStart(r,"0")},_a=function(a){var r=a.y,e=a.m,t=a.d,i=a._,s=a.dayName,n=a.short,c=n!==void 0&&n,o=new Date,l=new Date;l.setDate(l[i+"Date"]()-1);var d=new Date;return d.setDate(d[i+"Date"]()+1),o[i+"FullYear"]()===r&&o[i+"Month"]()===e&&o[i+"Date"]()===t?c?"Tdy":"Today":l[i+"FullYear"]()===r&&l[i+"Month"]()===e&&l[i+"Date"]()===t?c?"Ysd":"Yesterday":d[i+"FullYear"]()===r&&d[i+"Month"]()===e&&d[i+"Date"]()===t?c?"Tmw":"Tomorrow":s},zo=function(a){var r=new Date(a.getFullYear(),a.getMonth(),a.getDate());r.setDate(r.getDate()-(r.getDay()+6)%7+3);var e=new Date(r.getFullYear(),0,4);e.setDate(e.getDate()-(e.getDay()+6)%7+3);var t=r.getTimezoneOffset()-e.getTimezoneOffset();r.setHours(r.getHours()-t);var i=(r-e)/6048e5;return 1+Math.floor(i)},Ko=function(a){var r=a.getDay();return r===0&&(r=7),r},Jo=function(a){return(String(a).match($o)||[""]).pop().replace(Wo,"").replace(/GMT\+0000/g,"UTC")};const{BrowserUtil:qo}=J.AliRTS,Go="EdgeHTML",Ia="Blink",Xo="Trident",Qo="Gecko",Yo="WebKit",Wi=(a,r)=>{const e=r.match(a);return e&&e.length>0&&e[1]||""},Zo=[{test:[/\sedg\//i,[/edg([ea]|ios)/i]],describe(a){if(/\sedg\//i.test(a))return{name:Ia};const r=Wi(/edge\/(\d+(\.?_?\d+)+)/i,a);return{name:Go,version:r}}},{test:[/trident/i],describe(a){const r={name:Xo},e=Wi(/trident\/(\d+(\.?_?\d+)+)/i,a);return e&&(r.version=e),r}},{test(a){const r=/gecko/i.test(a),e=/like gecko/i.test(a);return r&&!e},describe(a){const r={name:Qo},e=Wi(/gecko\/(\d+(\.?_?\d+)+)/i,a);return e&&(r.version=e),r}},{test:[/(apple)?webkit\/537\.36/i],describe:()=>({name:Ia})},{test:[/(apple)?webkit/i],describe(a){const r={name:Yo},e=Wi(/webkit\/(\d+(\.?_?\d+)+)/i,a);return e&&(r.version=e),r}}],fs=(a,r)=>a.find(e=>typeof e.test=="function"?e.test(r):Array.isArray(e.test)?e.test.some(t=>typeof t=="string"?r.indexOf(t)>-1:t instanceof RegExp&&t.test(r)):void 0),ec=()=>{try{const a=navigator.userAgent||"",r=fs(Zo,a);if(r){const e=r.describe(a);return`${e.name}/${e.version||qo.browserVersion}`}}catch(a){}return navigator.userAgent},tc=[{test:["wow64","win64","x64"],describe:()=>"amd64"},{test:["i686","x86"],describe:()=>"x86"},{test:["aarch64","arm64"],describe:()=>"arm64"},{test:["arm"],describe:()=>"arm"}],Ea=()=>{let a="unknown";try{const r=navigator.userAgent||"",e=fs(tc,r);if(!e)return a;a=e.describe(r)}catch(r){}return a},ic=[{test:[/\b((?:s[cgp]h|gt|sm)-\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]([-\w]+)/i,/sec-(sgh\w+)/i],describe:()=>"Samsung"},{test:[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i,/\((ipad);[-\w\),; ]+apple/i,/(macintosh);/i],describe:()=>"Apple"},{test:[/(?:huawei)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],describe:()=>"Huawei"},{test:[/(?:honor)([-\w ]+)[;\)]/i],describe:()=>"Honor"},{test:[/\b(poco[\w ]+|m2\d{3}j\d\d[a-z]{2})(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/oid[^\)]+; (m?[12][0-389][01]\w{3,6}[c-y])( bui|; wv|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite)?)(?: bui|\))/i],describe:()=>"Xiaomi"},{test:[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],describe:()=>"Oppo"},{test:[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],describe:()=>"Vivo"},{test:[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i],describe:()=>"Realme"},{test:[/(pixel c)\b/i,/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],describe:()=>"Google"},{test:[/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],describe:()=>"ZTE"},{test:[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],describe:()=>"Meizu"}],sc=()=>{let a="Unknown";try{const r=navigator.userAgent||"",e=fs(ic,r);if(!e)return a;a=e.describe(r)}catch(r){}return a};let Ta="",Ca="";function ka(){return Ta}typeof navigator!="undefined"&&navigator.userAgentData&&navigator.userAgentData.getHighEntropyValues(["platform","platformVersion","architecture","model","uaFullVersion"]).then(a=>{Ta=a.model||"",Ca=a.platform?a.platform+" - "+a.platformVersion:"",console.log("设备型号 (Model):",a.model),console.log("平台 (Platform):",a.platform+" - "+a.platformVersion)}).catch(a=>{console.error("获取设备信息失败:",a)});class Pa{constructor(r){var e,t;this.timer=null,this.time=10,this.count=10,this.arr=[],this.time=(e=r.time)!=null?e:10,this.count=(t=r.count)!=null?t:10,r.host.startsWith("http://")||r.host.startsWith("https://")?this.url=r.host+"/logstores/"+r.logstore+"/track":this.url="https://"+r.project+"."+r.host+"/logstores/"+r.logstore+"/track",this.opt=r,r.installUnloadHook&&typeof r.installUnloadHook=="function"&&r.installUnloadHook(()=>{this.sendImmediateInner()})}assemblePayload(r){const e={__logs__:r};return this.opt.tags&&(e.__tags__=this.opt.tags),this.opt.topic&&(e.__topic__=this.opt.topic),this.opt.source&&(e.__source__=this.opt.source),JSON.stringify(e)}platformSend(){if(this.opt.sendPayload&&typeof this.opt.sendPayload=="function"){const r=this.assemblePayload(this.arr);this.opt.sendPayload(this.url,r)}}transString(r){let e={};for(let t in r)typeof r[t]=="object"?e[t]=JSON.stringify(r[t]):e[t]=String(r[t]);return e}sendImmediateInner(){this.arr&&this.arr.length>0&&(this.platformSend(),this.timer!=null&&(clearTimeout(this.timer),this.timer=null),this.arr=[])}sendInner(){if(this.timer)this.arr.length>=this.count&&(clearTimeout(this.timer),this.timer=null,this.sendImmediateInner());else{const r=this;this.arr.length>=this.count||this.time<=0?this.sendImmediateInner():this.timer=setTimeout(function(){r.sendImmediateInner()},1e3*this.time)}}send(r){const e=this.transString(r);this.arr.push(e),this.sendInner()}sendImmediate(r){const e=this.transString(r);this.arr.push(e),this.sendImmediateInner()}sendBatchLogs(r){const e=r.map(t=>this.transString(t));this.arr.push(...e),this.sendInner()}sendBatchLogsImmediate(r){const e=r.map(t=>this.transString(t));this.arr.push(...e),this.sendImmediateInner()}overwriteTransString(r){this.transString=r.transString}getOpt(){return this.opt}}function Da(a,r){return new Promise((e,t)=>{const i=new window.XMLHttpRequest;i.onload=()=>{i.status>=200&&i.status<300?e():t(new Error(`HTTP ${i.status}: ${i.statusText}`))},i.onerror=()=>{t(new Error("Network error occurred"))},i.ontimeout=()=>{t(new Error("Request timeout"))},i.timeout=1e4,i.open("POST",`${a}?APIVersion=0.6.0`,!0),i.send(r)})}function rc(a,r,e=!1){return I(this,null,function*(){try{if(e||r.length>=32768)return void(yield Da(a,r));(function(t,i){return!(!navigator||!navigator.sendBeacon)&&navigator.sendBeacon(`${t}?APIVersion=0.6.0`,i)})(a,r)||(yield Da(a,r))}catch(t){const i=t instanceof Error?t:new Error(String(t));throw window&&window.console&&typeof window.console.error=="function"&&(console.error(`Failed to log to ali log service because of this exception:
11
11
  `+i.message),console.error("Failed log data:",a)),i}})}let ac=(re=class extends Pa{constructor(e){const g=e,{maxRetries:t=10,retryDelay:i=2e3,backoffMultiplier:s=2,maxRetryDelay:n=3e5,enableLocalStorage:c=!0,maxStorageSize:o=1e3,storageKey:l="artc_reliable_logs",enableNetworkMonitor:d=!0,onNetworkChange:u=()=>{},forceXhrMode:p=!0,debug:h=!1}=g,f=Wt(g,["maxRetries","retryDelay","backoffMultiplier","maxRetryDelay","enableLocalStorage","maxStorageSize","storageKey","enableNetworkMonitor","onNetworkChange","forceXhrMode","debug"]);super(Object.assign({},f,{installUnloadHook:b=>{re.unloadHooks.push(b),re.globalUnloadListenersRegistered||(re.globalUnloadListenersRegistered=!0,re.beforeUnloadHandler=()=>{re.instances.forEach(S=>{S.saveFailedLogs()}),re.unloadHooks.forEach(S=>S())},re.visibilityChangeHandler=()=>{document.visibilityState==="hidden"&&re.instances.forEach(S=>{S.saveFailedLogs()})},window.addEventListener("beforeunload",re.beforeUnloadHandler),document.addEventListener("visibilitychange",re.visibilityChangeHandler))},sendPayload:(b,S)=>I(this,null,function*(){return Promise.resolve()})}));m(this,"reliableConfig");m(this,"failedLogs",new Map);m(this,"networkStatus","online");m(this,"retryTimer",null);m(this,"originalSendPayload",null);re.instances.add(this),this.reliableConfig={maxRetries:t,retryDelay:i,backoffMultiplier:s,maxRetryDelay:n,enableLocalStorage:c,maxStorageSize:o,storageKey:l,enableNetworkMonitor:d,onNetworkChange:u,forceXhrMode:p,debug:h},this.originalSendPayload=(b,S)=>I(this,null,function*(){return rc(b,S,p)}),this.getOpt().sendPayload=(b,S)=>I(this,null,function*(){return this.reliableSendAsync(b,S)}),this.initNetworkMonitor(),this.loadFailedLogs(),this.startRetryTimer()}reliableSendAsync(e,t){return I(this,null,function*(){const i=this.generateId();try{yield Promise.resolve(this.originalSendPayload(e,t)),this.debug(`Log ${i} sent successfully`)}catch(s){this.debug(`Log ${i} failed, adding to retry queue:`,s),this.addToFailedQueue(i,e,t,s)}})}addToFailedQueue(e,t,i,s){const n={id:e,data:{error:s.message},timestamp:Date.now(),retryCount:0,lastRetryTime:0,url:t,payload:i};this.failedLogs.set(e,n),this.scheduleRetry(n)}scheduleRetry(e){if(e.retryCount>=this.reliableConfig.maxRetries)return this.debug(`Log ${e.id} exceeded max retries, removing from queue`),void this.failedLogs.delete(e.id);const t=Math.min(this.reliableConfig.retryDelay*Math.pow(this.reliableConfig.backoffMultiplier,e.retryCount),this.reliableConfig.maxRetryDelay);this.debug(`Scheduling retry for log ${e.id} in ${t}ms (attempt ${e.retryCount+1}/${this.reliableConfig.maxRetries})`),setTimeout(()=>{this.retryLog(e)},t)}retryLog(e){return I(this,null,function*(){if(this.failedLogs.has(e.id)){e.retryCount++,e.lastRetryTime=Date.now();try{if(this.networkStatus==="offline")return this.debug(`Log ${e.id} retry skipped - network offline`),void this.scheduleRetry(e);yield this.originalSendPayload(e.url,e.payload),this.debug(`Log ${e.id} retry successful`),this.failedLogs.delete(e.id)}catch(t){this.debug(`Log ${e.id} retry failed:`,t),this.scheduleRetry(e)}}})}initNetworkMonitor(){this.reliableConfig.enableNetworkMonitor&&typeof window!="undefined"&&(this.networkStatus=navigator.onLine?"online":"offline",re.globalNetworkListenersRegistered?this.debug(`Network monitor already initialized globally. Current status: ${this.networkStatus}`):(re.globalNetworkListenersRegistered=!0,re.onlineHandler=()=>{re.instances.forEach(e=>{e.handleNetworkChange("online")})},re.offlineHandler=()=>{re.instances.forEach(e=>{e.handleNetworkChange("offline")})},window.addEventListener("online",re.onlineHandler),window.addEventListener("offline",re.offlineHandler),this.debug(`Network monitor initialized. Current status: ${this.networkStatus}`)))}handleNetworkChange(e){const t=this.networkStatus;this.networkStatus=e,this.debug(`Network status changed: ${t} -> ${e}`),this.reliableConfig.onNetworkChange(e==="online"),e==="online"&&t==="offline"&&(this.debug("Network recovered, retrying failed logs"),this.retryAllFailedLogs())}retryAllFailedLogs(){this.failedLogs.size!==0&&(this.debug(`Retrying ${this.failedLogs.size} failed logs after network recovery`),Array.from(this.failedLogs.values()).forEach(e=>{setTimeout(()=>this.retryLog(e),100*Math.random())}))}startRetryTimer(){typeof window!="undefined"&&(this.retryTimer=window.setInterval(()=>{if(this.failedLogs.size>0&&this.networkStatus==="online"){const e=Date.now();Array.from(this.failedLogs.values()).forEach(t=>{e-t.lastRetryTime>this.reliableConfig.retryDelay&&this.retryLog(t)})}},this.reliableConfig.retryDelay),this.debug(`Retry timer started with interval ${this.reliableConfig.retryDelay}ms`))}loadFailedLogs(){if(this.reliableConfig.enableLocalStorage&&typeof localStorage!="undefined")try{const e=localStorage.getItem(this.reliableConfig.storageKey);if(e){const t=JSON.parse(e);t.forEach(i=>{this.failedLogs.set(i.id,i)}),this.debug(`Loaded ${t.length} failed logs from storage`),localStorage.removeItem(this.reliableConfig.storageKey),this.networkStatus==="online"&&this.retryAllFailedLogs()}}catch(e){this.debug("Failed to load failed logs from storage:",e)}}saveFailedLogs(){if(this.reliableConfig.enableLocalStorage&&typeof localStorage!="undefined"&&this.failedLogs.size!==0)try{const e=Array.from(this.failedLogs.values()).slice(-this.reliableConfig.maxStorageSize);localStorage.setItem(this.reliableConfig.storageKey,JSON.stringify(e)),this.debug(`Saved ${e.length} failed logs to storage`)}catch(e){this.debug("Failed to save failed logs to storage:",e)}}generateId(){return`${Date.now()}-${Math.random().toString(36).substr(2,9)}`}debug(...e){this.reliableConfig.debug&&typeof console!="undefined"&&console.log("[ReliableWebTracker]",...e)}useStsPlugin(e){this.originalSendPayload=(t,i)=>I(this,null,function*(){return function(s,n,c){return I(this,null,function*(){try{s=s.slice(0,-6);const{data:o,header:l}=yield c.process(s,n);return new Promise((d,u)=>{const p=new window.XMLHttpRequest;p.onload=()=>{p.status>=200&&p.status<300?d():u(new Error(`HTTP ${p.status}: ${p.statusText}`))},p.onerror=()=>{u(new Error("Network error occurred"))},p.ontimeout=()=>{u(new Error("Request timeout"))},p.timeout=1e4,p.open("POST",s,!0);for(let h in l)p.setRequestHeader(h,l[h]);p.send(o)})}catch(o){const l=o instanceof Error?o:new Error(String(o));throw window&&window.console&&typeof window.console.error=="function"&&(console.error(`Failed to log to ali log service because of this exception:
12
- `+l.message),console.error("Failed log data:",s)),l}})}(t,i,e)}),this.getOpt().sendPayload=(t,i)=>I(this,null,function*(){return this.reliableSendAsync(t,i)}),this.overwriteTransString(e)}getStatus(){return{networkStatus:this.networkStatus,failedLogsCount:this.failedLogs.size,isRetryActive:this.retryTimer!==null,config:this.reliableConfig}}retryAll(){this.debug("Manual retry triggered"),this.retryAllFailedLogs()}clearFailedLogs(){const e=this.failedLogs.size;this.failedLogs.clear(),this.debug(`Cleared ${e} failed logs`)}getFailedLogs(){return Array.from(this.failedLogs.values())}destroy(){this.retryTimer&&(clearInterval(this.retryTimer),this.retryTimer=null),this.saveFailedLogs(),this.failedLogs.clear(),re.instances.delete(this),re.instances.size===0&&(re.beforeUnloadHandler&&(window.removeEventListener("beforeunload",re.beforeUnloadHandler),re.beforeUnloadHandler=null),re.visibilityChangeHandler&&(document.removeEventListener("visibilitychange",re.visibilityChangeHandler),re.visibilityChangeHandler=null),re.globalUnloadListenersRegistered=!1,re.unloadHooks=[],re.onlineHandler&&(window.removeEventListener("online",re.onlineHandler),re.onlineHandler=null),re.offlineHandler&&(window.removeEventListener("offline",re.offlineHandler),re.offlineHandler=null),re.globalNetworkListenersRegistered=!1),this.debug("WebTrackerBrowser destroyed")}},m(re,"globalUnloadListenersRegistered",!1),m(re,"globalNetworkListenersRegistered",!1),m(re,"instances",new Set),m(re,"unloadHooks",[]),m(re,"beforeUnloadHandler",null),m(re,"visibilityChangeHandler",null),m(re,"onlineHandler",null),m(re,"offlineHandler",null),re);const{BrowserUtil:Ma,SystenUtil:La}=J.AliRTS,nc=Ea(),zi=6e5,Na={host:"cn-hangzhou.log.aliyuncs.com",project:"alivc-aio",logstore:"logger",time:10,count:10},xa={host:"ap-southeast-1.log.aliyuncs.com",project:"alivc-aio-sgp",logstore:"logger",time:10,count:10};function bs(){return $i(new Date,"HH:MM:ss.l")}function Oa(){return $i(new Date,"isoDate")}var Ss=(a=>(a[a.DEBUG=0]="DEBUG",a[a.INFO=1]="INFO",a[a.API=2]="API",a[a.WARNING=3]="WARNING",a[a.ERROR=4]="ERROR",a[a.NONE=5]="NONE",a))(Ss||{});class Va{constructor(){m(this,"tracker");m(this,"stsPlugin");m(this,"stsData");m(this,"stsExpiration",Date.now());m(this,"clientId",mt());m(this,"bSesid",mt());m(this,"logLevel",3);m(this,"appId","");m(this,"sessionId","");m(this,"logCache",[]);m(this,"updateTaskTimer");m(this,"endReported",!0);m(this,"logSequence",0);m(this,"globalEnv","DEFAULT");m(this,"beforeUnloadHandler",null);m(this,"sendLogBeforeUnload",r=>I(this,null,function*(){if(!this.stsPlugin)return;this.logSequence+=1,r.unshift(this.getLogParams(710203,{log:`[${Oa()} ${bs()}] [INF] beforeunload`,stat_log_seq:this.logSequence}));const e=this.globalEnv==="SEA"?xa:Na,t=`https://${e.project}.${e.host}/logstores/${e.logstore}`,i={__logs__:r.map(c=>this.stsPlugin.transString(c))},{data:s,header:n}=yield this.stsPlugin.process(t,JSON.stringify(i));fetch(t,{keepalive:!0,method:"POST",headers:n,body:s})}));m(this,"logMethod",(r,e=console.log)=>(...t)=>{let i=bs();this.logLevel<=r&&e(i,...t);let s=Le.paramArrayToString(t);r>0&&this.addLog(s)});m(this,"d",this.logMethod(0,console.debug));m(this,"i",this.logMethod(1));m(this,"w",this.logMethod(3,console.warn));m(this,"e",this.logMethod(4,(...r)=>{const[e,...t]=r;console.error(e,"<error>",t)}));m(this,"ev",this.logMethod(2));m(this,"a",this.logMethod(2,(...r)=>{const[e,...t]=r;if(t.length>2){const i=`${t[1]}`;i.startsWith("__g__")&&console.group(`${i.substring(5)}_${t[2]}`)}console.log(e,...t)}));m(this,"ar",this.logMethod(2,(...r)=>{const[e,...t]=r;console.log(e,...t),t.length>2&&`${t[1]}`.startsWith("__g__")&&console.groupEnd()}));m(this,"ae",this.logMethod(2,(...r)=>{const[e,...t]=r;console.error(e,"<error>",...t),t.length>2&&`${t[1]}`.startsWith("__g__")&&console.groupEnd()}));this.ensureBeforeUnloadHandler()}ensureBeforeUnloadHandler(){this.beforeUnloadHandler||(this.beforeUnloadHandler=()=>{this.reportEnd(!0)},window.addEventListener("beforeunload",this.beforeUnloadHandler))}init(r){r&&(this.globalEnv=r),this.ensureBeforeUnloadHandler(),this.reset(),this.startSTSUpdateTask()}destroy(){this.updateTaskTimer&&clearTimeout(this.updateTaskTimer),this.beforeUnloadHandler&&(window.removeEventListener("beforeunload",this.beforeUnloadHandler),this.beforeUnloadHandler=null),this.tracker&&(this.tracker.destroy(),this.tracker=void 0)}reset(){this.bSesid=mt(),this.endReported=!0,this.logSequence=0,this.appId="",this.sessionId=""}startSTSUpdateTask(){return I(this,null,function*(){this.updateTaskTimer&&clearTimeout(this.updateTaskTimer);try{const r=yield this.refreshSTSToken();this.createTracker(r)}catch(r){}this.updateTaskTimer=setTimeout(()=>{this.startSTSUpdateTask()},zi)})}refreshSTSToken(){return I(this,null,function*(){if(!this.stsData||this.stsExpiration<=Date.now()+zi){const r=yield this.requestSTSToken(),e=new Date(r==null?void 0:r.Expiration).getTime()||0,t=Date.now()+zi;this.stsExpiration=Math.max(e,t),this.stsData=r}return this.stsData})}requestSTSToken(){const r=Date.now(),e=`${this.clientId}|woMMssV6jmyol9fr|${r}`,t={Action:"AssumeSlsRoleV2",AuthInfo:ai.MD5(e).toString(ai.enc.Hex),ClientId:this.clientId,BusinessType:"logger",AppVersion:"1.0",Version:"2017-03-14",AuthTimestamp:`${r}`,TerminalType:"web",DeviceModel:"",Format:"JSON",SignatureMethod:"HMAC-SHA1",SignatureVersion:"1.0",Timestamp:$i(r,"isoUtcDateTime")},i=new URLSearchParams(t).toString(),s=`https://${this.globalEnv==="SEA"?"slsrole-intl.alicdn.com":"slsrole.alicdn.com"}/?${i}`;return fetch(s).then(n=>n.json()).then(n=>JSON.parse(window.atob(n.SlsAuthResult)))}createTracker(r){if(!this.tracker){const e={accessKeyId:r.AccessKeyId,accessKeySecret:r.AccessKeySecret,securityToken:r.SecurityToken,refreshSTSTokenInterval:zi,stsTokenFreshTime:void 0,refreshSTSToken:()=>{this.refreshSTSToken().then(s=>{e.accessKeyId=s.AccessKeyId,e.accessKeySecret=s.AccessKeySecret,e.securityToken=s.SecurityToken}).catch(()=>{})}},t=new ac(this.globalEnv==="SEA"?xa:Na),i=gs(e);t.useStsPlugin(i),this.stsPlugin=i,this.tracker=t,this.reportStartAndCache()}}changeConfig(r){r.logLevel!==void 0&&r.logLevel>=0&&r.logLevel<=5&&(this.logLevel=r.logLevel)}setSessionID(r,e){r&&e&&(this.appId=r,this.sessionId=e,this.reportStartAndCache())}reportStartAndCache(){if(!this.tracker||!this.sessionId)return;this.endReported=!1;const r={task_btm_sec:0,task_duration:0,task_etm_sec:0,task_type:"session"},e=[this.getLogParams(710201,r),this.getLogParams(710202,r)];this.tracker.sendBatchLogsImmediate(e),this.logCache.forEach(t=>{this.sendLog(t)})}reportEnd(r=!1){if(!this.tracker||!this.sessionId||this.endReported)return void this.reset();const e={task_btm_sec:0,task_duration:0,task_etm_sec:0,task_type:"session"},t=[this.getLogParams(710204,e),this.getLogParams(710205,e)];r?this.sendLogBeforeUnload(t):(this.tracker.sendBatchLogsImmediate(t),this.endReported=!0),this.reset()}getLogParams(r,e){return X({appid:`${window.location.host}`,appid_list:this.appId,appver:"",b_sesid:this.bSesid,biz_type:"rtc",cpu_info:nc,db:Ma.browserName,dm:Ma.browserVersion,install_uuid:this.clientId,logger_v:"0.0.1",os:La.systemName,osv:La.systemVersion,p_sesid:this.bSesid,sdk_version:_i,sdkname:"AliRTCSdk",stm:Date.now(),tar_pf:"web",traceid:this.sessionId,event_id:r},e||{})}sendLog(r){if(!this.tracker||!this.sessionId)return;this.logSequence+=1;const e=this.getLogParams(710203,{log:r,stat_log_seq:this.logSequence});this.tracker.send(e)}addLog(r){const e=bs(),t=`[${Oa()} ${e}] ${r}`;this.sessionId&&this.tracker?this.sendLog(t):(this.logCache.push(t),this.logCache.length>=200&&this.logCache.shift())}}class T{static getLogger(){if(this.activeInstanceId&&this.loggers.has(this.activeInstanceId))return this.loggers.get(this.activeInstanceId);const r=this.loggers.values().next().value;return r||new Va}static setActiveInstance(r){this.activeInstanceId=r}static init(r,e){if(this.loggers.has(r))this.loggers.get(r).init(e);else{const t=new Va;t.init(e),this.loggers.set(r,t)}this.activeInstanceId=r}static destroy(r){const e=this.loggers.get(r);if(e&&(e.destroy(),this.loggers.delete(r)),this.activeInstanceId===r){const t=this.loggers.keys().next().value;this.activeInstanceId=t||""}}static setLogLevel(r){this.loggers.forEach(e=>e.changeConfig({logLevel:r}))}static setSessionID(r,e){this.getLogger().setSessionID(r,e)}static reportEnd(){this.getLogger().reportEnd()}static interface(...r){this.getLogger().a("[API]",...r)}static interfaceResult(r,e,t,...i){t?this.getLogger().ar("[ARE]",r,e,...i):this.getLogger().ae("[ARE]",r,e,...i)}static event(...r){this.getLogger().ev("[EVT]",...r)}static debug(...r){this.getLogger().d("[DBG]",...r)}static info(...r){this.getLogger().i("[INF]",...r)}static warn(...r){this.getLogger().w("[WARN]",...r)}static error(...r){this.getLogger().e("[ERR]",...r)}}m(T,"loggers",new Map),m(T,"activeInstanceId","");const be=class be{constructor(){m(this,"userStatsMap",new Map);m(this,"eventDataArray",[]);this.initPageVisibilityMonitor()}static setGlobalQualityStatsEnable(r){be.globalQualityStatsEnable=r}addEventData(r,...e){if(!be.globalQualityStatsEnable)return;let t=Date.now(),i="";if(this.eventDataArray.length>=be.MAX_EVENT_COUNT)return;this.eventDataArray.length>0&&(t-=this.eventDataArray[0].time),i=e.map(String).join(",");const s={name:r,time:t,info:i};this.eventDataArray.push(s)}initPageVisibilityMonitor(){typeof document!="undefined"&&document.addEventListener("visibilitychange",()=>{this.handleVisibilityChange()})}handleVisibilityChange(){document.hidden&&this.userStatsMap.forEach(r=>{r.docHidden=!0})}static generateHexRandomString(r=16){const e="0123456789abcdef";let t="";for(let i=0;i<r;i++)t+=e[Math.floor(16*Math.random())];return t}static getInstance(){return be.instance||(be.instance=new be),be.instance}setRemoteViewConfig(r,e){if(!be.globalQualityStatsEnable)return;const t=Date.now(),i=t+"_"+be.generateHexRandomString();this.userStatsMap.has(r)&&this.removeRemoteViewConfig(r);const s={uid:r,uuid:i,view:e,firstFrameTime:0,subscribeStartTime:t,beginTime:0,playTime:0,playTimeOnce:0,stallData200ms:{stallCount:0,stallCountOnce:0,stallTime:0,stallTimeOnce:0},stallData600ms:{stallCount:0,stallCountOnce:0,stallTime:0,stallTimeOnce:0},lastFrameTimestamp:0,beginTimeOnce:0,docHidden:!1,isStop:!1,needReset:!1};this.userStatsMap.set(r,s),e.requestVideoFrameCallback(function n(c){let o=be.getInstance().userStatsMap.get(r);if(o){if(o.needReset)return o.firstFrameTime=0,o.firstFrameTime=0,o.subscribeStartTime=t,o.beginTime=0,o.playTime=0,o.playTimeOnce=0,o.stallData200ms={stallCount:0,stallCountOnce:0,stallTime:0,stallTimeOnce:0},o.stallData600ms={stallCount:0,stallCountOnce:0,stallTime:0,stallTimeOnce:0},o.lastFrameTimestamp=0,o.beginTimeOnce=0,o.docHidden=!1,void(o.needReset=!1);if(o.isStop=!1,o.firstFrameTime===0&&(o.firstFrameTime=Date.now()-o.subscribeStartTime),o.beginTime===0&&(o.beginTime=c),o.beginTimeOnce===0&&(o.beginTimeOnce=c),o.lastFrameTimestamp!==0&&!o.docHidden){let l=200,d=c-o.lastFrameTimestamp;d>l&&(o.stallData200ms.stallTime+=Math.trunc(d-l),o.stallData200ms.stallTimeOnce+=Math.trunc(d-l),o.stallData200ms.stallCount++,o.stallData200ms.stallCountOnce++),l=600,d>l&&(o.stallData600ms.stallTime+=Math.trunc(d-l),o.stallData600ms.stallTimeOnce+=Math.trunc(d-l),o.stallData600ms.stallCount++,o.stallData600ms.stallCountOnce++)}o.docHidden=!1,o.lastFrameTimestamp=c,o.playTime=Math.trunc(c-o.beginTime),o.playTimeOnce=Math.trunc(c-o.beginTimeOnce),e.requestVideoFrameCallback(n)}})}removeRemoteViewConfig(r){be.globalQualityStatsEnable&&be.getInstance().userStatsMap.delete(r)}unsubscribeRemoteViewConfig(r){if(!be.globalQualityStatsEnable)return;let e=be.getInstance().userStatsMap.get(r);e&&(e.isStop=!0,e.needReset=!0)}clearAll(r){be.globalQualityStatsEnable&&r&&this.userStatsMap.forEach((e,t)=>{t.startsWith(r)&&this.userStatsMap.delete(t)})}getSummary(){if(!be.globalQualityStatsEnable)return"closed";try{if(Date.now()-be.lastSummaryTime<1e3)return"{}";be.lastSummaryTime=Date.now();const r={totalUsers:this.userStatsMap.size,timestamp:Date.now(),totalEvents:this.eventDataArray.length,events:this.eventDataArray.slice(-be.MAX_EVENT_COUNT),users:[]};return this.userStatsMap.forEach((e,t)=>{e.isStop||(r.users.push({uid:t,uuid:e.uuid,fTime:e.firstFrameTime,sct200:e.stallData200ms.stallCount,stt200:e.stallData200ms.stallTime,scto200:e.stallData200ms.stallCountOnce,stto200:e.stallData200ms.stallTimeOnce,sct600:e.stallData600ms.stallCount,stt600:e.stallData600ms.stallTime,scto600:e.stallData600ms.stallCountOnce,stto600:e.stallData600ms.stallTimeOnce,playTime:e.playTime,playTimeOnce:e.playTimeOnce}),e.beginTimeOnce=0,e.stallData600ms.stallCountOnce=0,e.stallData600ms.stallTimeOnce=0,e.stallData200ms.stallCountOnce=0,e.stallData200ms.stallTimeOnce=0,e.playTimeOnce=0)}),this.eventDataArray=[],JSON.stringify(r)}catch(r){return'{"getSummary":"error"}'}}};m(be,"eventStartSub","startSub"),m(be,"eventRemoveSub","RemoveSub"),m(be,"eventSubSuccess","SubOk"),m(be,"eventSubError","SubErr"),m(be,"eventFirstAudio","firstAudio"),m(be,"eventRtsSub","rtsSub"),m(be,"eventRtsSubSuccess","rtsSubOk"),m(be,"eventRtsSubClose","rtsSubClose"),m(be,"eventRetrySub","retry"),m(be,"eventRetrySubAuto","retryAuto"),m(be,"instance"),m(be,"MAX_EVENT_COUNT",100),m(be,"globalQualityStatsEnable",!0),m(be,"lastSummaryTime",0);let _e=be;const is=class is extends oe{constructor(e){super();m(this,"roomServerUrl");m(this,"label");m(this,"rtsInstance");m(this,"currentStatus",ae.AliRtcConnectionStatusInit);m(this,"latestStreamInfo");m(this,"preferredL1Ip");m(this,"usePreferredL1InRetry",!0);m(this,"_remoteStream");m(this,"remoteStream");m(this,"_prevDownlinkStat");m(this,"networkQualityTimer");this.config=e;const{env:t,appId:i,currentUserId:s,targetChannelId:n,targetUserId:c,token:o,nonce:l,timestamp:d}=e,u=Le.createCallid(),p=new URLSearchParams({appid:i,channelid:n,userid:s,timestamp:d.toString(),token:o,nonce:l!=null?l:"",tid:u,pubchannelid:n,pubuserid:c}),h=t===It.pre?Rt.pre:Rt.prod;this.roomServerUrl=`https://${h}/signaling/v1/querypulluri?${p.toString()}`,this.label=`${this.config.currentUserId} => ${this.config.targetChannelId} > ${this.config.targetUserId}`,_e.getInstance().addEventData(_e.eventRtsSub,this.config.currentUserId,this.config.targetChannelId,this.config.targetUserId),this.fetchStreamUrlAndPlay()}get logName(){return`${is.logName}(${this.label})`}updateConnectionStatus(e){this.currentStatus!==e&&(this.currentStatus=e,this.emit("connectionStatusChange",e))}handleError(e,t){var i;T.error(`[${this.logName}]`,"Error:",e,t),this.emit("error",e,t),this.updateConnectionStatus(ae.AliRtcConnectionStatusFailed),(i=this.rtsInstance)==null||i.dispose(),this.rtsInstance=void 0}fetchStreamUrlAndPlay(){return I(this,null,function*(){var e,t,i;this.updateConnectionStatus(ae.AliRtcConnectionStatusConnecting);try{const s=yield fetch(this.roomServerUrl);if(!s.ok){const d=yield s.text();return void this.handleError("FETCH_STREAM_URL_FAILED",`Fetch stream url failed, status: ${s.status} ${d}`)}const n=yield s.json();if(T.debug(`[${this.logName}]`,"Query pull uri response:",n),n.code!==0)return void this.handleError("FETCH_STREAM_URL_FAILED",`Business error, code: ${n.code}`);if(!((t=(e=n==null?void 0:n.data)==null?void 0:e.subscribe)!=null&&t.pullstreamurl)||!((i=n==null?void 0:n.data)!=null&&i.tracks))return void this.handleError("NO_STREAM_AVAILABLE","No stream available");const c=`${n.data.subscribe.pullstreamurl}&curUid=${this.config.currentUserId}&tarCid=${this.config.targetChannelId}&tarUid=${this.config.targetUserId}`,o=n.data.tracks.filter(d=>mr(d.msid)).map(d=>d.msid),l=n.data.tracks.filter(d=>gr(d.msid)).map(d=>d.msid);if(o.length===0&&l.length===0)return void this.handleError("NO_STREAM_AVAILABLE","No tracks available");T.info(`[${this.logName}]`,"Fetch stream url success",c,o,l),this.latestStreamInfo={url:c,vMsid:o,aMsid:l},this.preferredL1Ip=n.l1ip,this.rtsInstance=J.AliRTS.createClient(),this.rtsInstance.on("reconnect",d=>{d.retryTimes>=300?this.handleError("SUBSCRIBE_FAILED","reconnect failed"):this.currentStatus!==ae.AliRtcConnectionStatusReconnecting&&(T.warn(`[${this.logName}]`,"reconnecting",d),this.updateConnectionStatus(ae.AliRtcConnectionStatusReconnecting))}),this.rtsInstance.on("hebtReceived",d=>{var u,p;d.recode===0&&((p=(u=d.streams)==null?void 0:u[0])==null?void 0:p.res_code)===200&&this.currentStatus===ae.AliRtcConnectionStatusReconnecting&&(T.warn(`[${this.logName}]`,"reconnect success",d),this.updateConnectionStatus(ae.AliRtcConnectionStatusConnected))});try{if(this._remoteStream=yield this.subscribeWithPreferredL1Fallback(c,{vMsid:o,aMsid:l,heartbeat:{interval:1e3,timeout:5e3},retryTimes:300,beforeRetry:()=>I(this,null,function*(){var u;T.info(`[${this.logName}]`,"Trying to fetch new stream url...");const d=yield fetch(this.roomServerUrl);if(d.status!==400){if(d.ok&&d.status===200){const p=yield d.json();if(T.debug(`[${this.logName}]`,"Query pull uri response:",p),p.code===0&&((u=p.data.subscribe)==null?void 0:u.pullstreamurl)&&p.data.tracks){const h=`${p.data.subscribe.pullstreamurl}&curUid=${this.config.currentUserId}&tarCid=${this.config.targetChannelId}&tarUid=${this.config.targetUserId}`,f=p.data.tracks.filter(b=>mr(b.msid)).map(b=>b.msid),g=p.data.tracks.filter(b=>gr(b.msid)).map(b=>b.msid);if(f.length>0||g.length>0){const b=this.usePreferredL1InRetry?ls(h,p.l1ip):h;T.info(`[${this.logName}]`,"Fetch new stream url success",b,f,g,`usePreferredL1InRetry=${this.usePreferredL1InRetry}`),this.latestStreamInfo={url:b,vMsid:f,aMsid:g}}}}return this.latestStreamInfo}{const p=yield d.text();this.handleError("FETCH_STREAM_URL_FAILED",`Fetch new stream url failed, status: ${d.status} ${p}`)}})}),T.info(`[${this.logName}]`,"Subscribe success",this._remoteStream.traceId),this.remoteStream=this.createRemoteStreamProxy(this._remoteStream),this.updateConnectionStatus(ae.AliRtcConnectionStatusConnected),this.startNetworkQualityTimer(),_e.getInstance().addEventData(_e.eventRtsSubSuccess,this.config.currentUserId,this.config.targetChannelId,this.config.targetUserId),this.config.view){let d;if(d=typeof this.config.view=="string"?document.getElementById(this.config.view):this.config.view,d instanceof HTMLVideoElement)try{_e.getInstance().setRemoteViewConfig(this.config.currentUserId+"_"+this.config.targetChannelId+"_"+this.config.targetUserId,d)}catch(u){}d instanceof HTMLMediaElement?this._remoteStream.play(d):this.emit("error","INVALID_VIEW_ELEMENT","view is not a media element")}}catch(d){this.handleError("SUBSCRIBE_FAILED",`Subscribe failed: ${d.message}`)}}catch(s){this.handleError("FETCH_STREAM_URL_FAILED",`Fetch stream url failed: ${s.message}`)}})}subscribeWithPreferredL1Fallback(e,t){return I(this,null,function*(){const i=ls(e,this.preferredL1Ip);if(i!==e){const n=window.__ali_prefer_media_server||this.preferredL1Ip;T.info(`[${this.logName}]`,"Subscribing with preferred media server, ip:",n);const c=new Promise((o,l)=>{setTimeout(()=>l(new Error("PREFERRED_L1_TIMEOUT")),3e3)});try{const o=yield Promise.race([this.rtsInstance.subscribe(i,t),c]);return this.latestStreamInfo.url=i,this.logCandidateProtocol("subscribe (preferred)"),o}catch(o){if(o.message==="PREFERRED_L1_TIMEOUT"){T.warn(`[${this.logName}]`,"Preferred media server subscribe timeout, falling back to DNS"),this.usePreferredL1InRetry=!1;const l=yield this.rtsInstance.subscribe(e,t);return this.logCandidateProtocol("subscribe (fallback)"),l}throw o}}const s=yield this.rtsInstance.subscribe(e,t);return this.logCandidateProtocol("subscribe"),s})}logCandidateProtocol(e){return I(this,null,function*(){var t,i,s;try{const n=(s=(i=(t=this.rtsInstance)==null?void 0:t.commonController)==null?void 0:i.peerCore)==null?void 0:s.pc;if(!n)return void T.debug(`[${this.logName}]`,`${e} - PC not available`);const c=yield n.getStats();let o,l,d,u;c.forEach(p=>{p.type==="candidate-pair"&&p.state==="succeeded"&&p.nominated&&(o=p.localCandidateId,l=p.remoteCandidateId)}),o||l||c.forEach(p=>{p.type!=="candidate-pair"||p.state!=="succeeded"&&p.state!=="in-progress"||o||(o=p.localCandidateId,l=p.remoteCandidateId)}),c.forEach(p=>{p.type==="local-candidate"&&p.id===o&&(d=p.protocol),p.type==="remote-candidate"&&p.id===l&&(u=p.protocol)}),T.info(`[${this.logName}]`,`${e} - Candidate Protocol: local=${d||"unknown"}, remote=${u||"unknown"}`)}catch(n){T.warn(`[${this.logName}]`,`${e} - Failed to get candidate protocol:`,n)}})}createRemoteStreamProxy(e){const t=this.logName;return new Proxy(e,{get(i,s,n){const c=Reflect.get(i,s,n);return typeof c=="function"?function(...o){T.interface(`[${t}]`,`remoteStream.${String(s)} called`,o.length>0?o:"");const l=c.apply(i,o);return l instanceof Promise?l.then(d=>(T.info(`[${t}]`,`remoteStream.${String(s)} resolved`,d!==void 0?d:""),d),d=>{throw T.error(`[${t}]`,`remoteStream.${String(s)} rejected`,d),d}):l}:c}})}startNetworkQualityTimer(){this.stopNetworkQualityTimer(),this._prevDownlinkStat=void 0,this.networkQualityTimer=setInterval(()=>I(this,null,function*(){if(this.currentStatus===ae.AliRtcConnectionStatusConnected)try{const e=yield this.getNetworkQuality();this.emit("networkQuality",e)}catch(e){T.warn(`[${this.logName}]`,"Failed to get network quality:",e)}}),2e3)}stopNetworkQualityTimer(){this.networkQualityTimer&&(clearInterval(this.networkQualityTimer),this.networkQualityTimer=void 0)}getNetworkQuality(){return I(this,null,function*(){var h,f,g;const e=(g=(f=(h=this.rtsInstance)==null?void 0:h.commonController)==null?void 0:f.peerCore)==null?void 0:g.pc;if(!e||e.connectionState==="disconnected"||e.connectionState==="failed"||e.connectionState==="closed")return{rtt:0,loss:0,quality:tt.AliRtcNetworkDisconnected};let t=0,i=0,s=0;const n=e.getReceivers();for(const b of n)(yield b.getStats()).forEach(S=>{S.type==="candidate-pair"&&typeof S.currentRoundTripTime=="number"&&(t=Math.round(1e3*S.currentRoundTripTime)),S.type!=="inbound-rtp"||S.mediaType!=="audio"&&S.mediaType!=="video"||(i+=S.packetsLost||0,s+=S.packetsReceived||0)});if(!this._prevDownlinkStat)return this._prevDownlinkStat={totalPacketsLost:i,totalPacketsReceived:s},{rtt:t,loss:0,quality:tt.AliRtcNetworkUnknown};const{totalPacketsLost:c,totalPacketsReceived:o}=this._prevDownlinkStat,l=i-c,d=s-o;let u=0;l>0&&d>=0&&(u=Math.round(l/(l+d)*100));const p=ds(u,t);return this._prevDownlinkStat={totalPacketsLost:i,totalPacketsReceived:s},{rtt:t,loss:u,quality:p}})}dispose(){let e=this.config.currentUserId;T.info(`[${this.logName}]`,"dispose"),this.stopNetworkQualityTimer(),this.updateConnectionStatus(ae.AliRtcConnectionStatusDisconnected),_e.getInstance().addEventData(_e.eventRtsSubClose,this.config.currentUserId,this.config.targetChannelId,this.config.targetUserId),this.rtsInstance&&this.rtsInstance.dispose();try{_e.getInstance().clearAll(e)}catch(t){}}};m(is,"logName","RemoteStreamHandler");let vs=is;var ys={exports:{}};(function(a,r){(function(e,t){var i="function",s="undefined",n="object",c="string",o="major",l="model",d="name",u="type",p="vendor",h="version",f="architecture",g="console",b="mobile",S="tablet",v="smarttv",R="wearable",_="embedded",y="Amazon",w="Apple",A="ASUS",E="BlackBerry",C="Browser",P="Chrome",M="Firefox",x="Google",K="Huawei",Q="LG",G="Microsoft",W="Motorola",Z="Opera",te="Samsung",Se="Sharp",L="Sony",O="Xiaomi",N="Zebra",V="Facebook",he="Chromium OS",xe="Mac OS",q=" Browser",Re=function(le){for(var ne={},ie=0;ie<le.length;ie++)ne[le[ie].toUpperCase()]=le[ie];return ne},Ve=function(le,ne){return typeof le===c&&Ee(ne).indexOf(Ee(le))!==-1},Ee=function(le){return le.toLowerCase()},Ne=function(le,ne){if(typeof le===c)return le=le.replace(/^\s\s*/,""),typeof ne===s?le:le.substring(0,500)},ve=function(le,ne){for(var ie,Ae,Fe,me,qe,Y,Ue=0;Ue<ne.length&&!qe;){var pt=ne[Ue],Be=ne[Ue+1];for(ie=Ae=0;ie<pt.length&&!qe&&pt[ie];)if(qe=pt[ie++].exec(le))for(Fe=0;Fe<Be.length;Fe++)Y=qe[++Ae],typeof(me=Be[Fe])===n&&me.length>0?me.length===2?typeof me[1]==i?this[me[0]]=me[1].call(this,Y):this[me[0]]=me[1]:me.length===3?typeof me[1]!==i||me[1].exec&&me[1].test?this[me[0]]=Y?Y.replace(me[1],me[2]):t:this[me[0]]=Y?me[1].call(this,Y,me[2]):t:me.length===4&&(this[me[0]]=Y?me[3].call(this,Y.replace(me[1],me[2])):t):this[me]=Y||t;Ue+=2}},we=function(le,ne){for(var ie in ne)if(typeof ne[ie]===n&&ne[ie].length>0){for(var Ae=0;Ae<ne[ie].length;Ae++)if(Ve(ne[ie][Ae],le))return ie==="?"?t:ie}else if(Ve(ne[ie],le))return ie==="?"?t:ie;return ne.hasOwnProperty("*")?ne["*"]:le},pe={ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2e3:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2",8.1:"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"},Oe={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[h,[d,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[h,[d,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[d,h],[/opios[\/ ]+([\w\.]+)/i],[h,[d,Z+" Mini"]],[/\bop(?:rg)?x\/([\w\.]+)/i],[h,[d,Z+" GX"]],[/\bopr\/([\w\.]+)/i],[h,[d,Z]],[/\bb[ai]*d(?:uhd|[ub]*[aekoprswx]{5,6})[\/ ]?([\w\.]+)/i],[h,[d,"Baidu"]],[/\b(?:mxbrowser|mxios|myie2)\/?([-\w\.]*)\b/i],[h,[d,"Maxthon"]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer|sleipnir)[\/ ]?([\w\.]*)/i,/(avant|iemobile|slim(?:browser|boat|jet))[\/ ]?([\d\.]*)/i,/(?:ms|\()(ie) ([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|duckduckgo|klar|helio|(?=comodo_)?dragon)\/([-\w\.]+)/i,/(heytap|ovi|115)browser\/([\d\.]+)/i,/(weibo)__([\d\.]+)/i],[d,h],[/quark(?:pc)?\/([-\w\.]+)/i],[h,[d,"Quark"]],[/\bddg\/([\w\.]+)/i],[h,[d,"DuckDuckGo"]],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[h,[d,"UC"+C]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i,/micromessenger\/([\w\.]+)/i],[h,[d,"WeChat"]],[/konqueror\/([\w\.]+)/i],[h,[d,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[h,[d,"IE"]],[/ya(?:search)?browser\/([\w\.]+)/i],[h,[d,"Yandex"]],[/slbrowser\/([\w\.]+)/i],[h,[d,"Smart Lenovo "+C]],[/(avast|avg)\/([\w\.]+)/i],[[d,/(.+)/,"$1 Secure "+C],h],[/\bfocus\/([\w\.]+)/i],[h,[d,M+" Focus"]],[/\bopt\/([\w\.]+)/i],[h,[d,Z+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[h,[d,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[h,[d,"Dolphin"]],[/coast\/([\w\.]+)/i],[h,[d,Z+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[h,[d,"MIUI"+q]],[/fxios\/([\w\.-]+)/i],[h,[d,M]],[/\bqihoobrowser\/?([\w\.]*)/i],[h,[d,"360"]],[/\b(qq)\/([\w\.]+)/i],[[d,/(.+)/,"$1Browser"],h],[/(oculus|sailfish|huawei|vivo|pico)browser\/([\w\.]+)/i],[[d,/(.+)/,"$1"+q],h],[/samsungbrowser\/([\w\.]+)/i],[h,[d,te+" Internet"]],[/metasr[\/ ]?([\d\.]+)/i],[h,[d,"Sogou Explorer"]],[/(sogou)mo\w+\/([\d\.]+)/i],[[d,"Sogou Mobile"],h],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|2345(?=browser|chrome|explorer))\w*[\/ ]?v?([\w\.]+)/i],[d,h],[/(lbbrowser|rekonq)/i,/\[(linkedin)app\]/i],[d],[/ome\/([\w\.]+) \w* ?(iron) saf/i,/ome\/([\w\.]+).+qihu (360)[es]e/i],[h,d],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[d,V],h],[/(Klarna)\/([\w\.]+)/i,/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(alipay)client\/([\w\.]+)/i,/(twitter)(?:and| f.+e\/([\w\.]+))/i,/(chromium|instagram|snapchat)[\/ ]([-\w\.]+)/i],[d,h],[/\bgsa\/([\w\.]+) .*safari\//i],[h,[d,"GSA"]],[/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i],[h,[d,"TikTok"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[h,[d,P+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[d,P+" WebView"],h],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[h,[d,"Android "+C]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[d,h],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[h,[d,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[h,d],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[d,[h,we,{"1.0":"/8",1.2:"/1",1.3:"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"}]],[/(webkit|khtml)\/([\w\.]+)/i],[d,h],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[d,"Netscape"],h],[/(wolvic|librewolf)\/([\w\.]+)/i],[d,h],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[h,[d,M+" Reality"]],[/ekiohf.+(flow)\/([\w\.]+)/i,/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror)[\/ ]?([\w\.\+]+)/i,/(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,/(firefox)\/([\w\.]+)/i,/(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i,/(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|obigo|mosaic|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,/(links) \(([\w\.]+)/i],[d,[h,/_/g,"."]],[/(cobalt)\/([\w\.]+)/i],[d,[h,/master.|lts./,""]]],cpu:[[/(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i],[[f,"amd64"]],[/(ia32(?=;))/i],[[f,Ee]],[/((?:i[346]|x)86)[;\)]/i],[[f,"ia32"]],[/\b(aarch64|arm(v?8e?l?|_?64))\b/i],[[f,"arm64"]],[/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],[[f,"armhf"]],[/windows (ce|mobile); ppc;/i],[[f,"arm"]],[/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i],[[f,/ower/,"",Ee]],[/(sun4\w)[;\)]/i],[[f,"sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i],[[f,Ee]]],device:[[/\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i],[l,[p,te],[u,S]],[/\b((?:s[cgp]h|gt|sm)-(?![lr])\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]((?!sm-[lr])[-\w]+)/i,/sec-(sgh\w+)/i],[l,[p,te],[u,b]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[l,[p,w],[u,b]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[l,[p,w],[u,S]],[/(macintosh);/i],[l,[p,w]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[l,[p,Se],[u,b]],[/(?:honor)([-\w ]+)[;\)]/i],[l,[p,"Honor"],[u,b]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[l,[p,K],[u,S]],[/(?:huawei)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[l,[p,K],[u,b]],[/\b(poco[\w ]+|m2\d{3}j\d\d[a-z]{2})(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/oid[^\)]+; (m?[12][0-389][01]\w{3,6}[c-y])( bui|; wv|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite|pro)?)(?: bui|\))/i],[[l,/_/g," "],[p,O],[u,b]],[/oid[^\)]+; (2\d{4}(283|rpbf)[cgl])( bui|\))/i,/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[l,/_/g," "],[p,O],[u,S]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[l,[p,"OPPO"],[u,b]],[/\b(opd2\d{3}a?) bui/i],[l,[p,"OPPO"],[u,S]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[l,[p,"Vivo"],[u,b]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i],[l,[p,"Realme"],[u,b]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,/\bmot(?:orola)?[- ](\w*)/i,/((?:moto[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i],[l,[p,W],[u,b]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[l,[p,W],[u,S]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[l,[p,Q],[u,S]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[l,[p,Q],[u,b]],[/(ideatab[-\w ]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[l,[p,"Lenovo"],[u,S]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[l,/_/g," "],[p,"Nokia"],[u,b]],[/(pixel c)\b/i],[l,[p,x],[u,S]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[l,[p,x],[u,b]],[/droid.+; (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-a\w[4-7][12])(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i],[l,[p,L],[u,b]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[l,"Xperia Tablet"],[p,L],[u,S]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[l,[p,"OnePlus"],[u,b]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo(?!bc)\w\w)( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[l,[p,y],[u,S]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[l,/(.+)/g,"Fire Phone $1"],[p,y],[u,b]],[/(playbook);[-\w\),; ]+(rim)/i],[l,p,[u,S]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[l,[p,E],[u,b]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[l,[p,A],[u,S]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[l,[p,A],[u,b]],[/(nexus 9)/i],[l,[p,"HTC"],[u,S]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[p,[l,/_/g," "],[u,b]],[/droid [\w\.]+; ((?:8[14]9[16]|9(?:0(?:48|60|8[01])|1(?:3[27]|66)|2(?:6[69]|9[56])|466))[gqswx])\w*(\)| bui)/i],[l,[p,"TCL"],[u,S]],[/(itel) ((\w+))/i],[[p,Ee],l,[u,we,{tablet:["p10001l","w7001"],"*":"mobile"}]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[l,[p,"Acer"],[u,S]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[l,[p,"Meizu"],[u,b]],[/; ((?:power )?armor(?:[\w ]{0,8}))(?: bui|\))/i],[l,[p,"Ulefone"],[u,b]],[/; (energy ?\w+)(?: bui|\))/i,/; energizer ([\w ]+)(?: bui|\))/i],[l,[p,"Energizer"],[u,b]],[/; cat (b35);/i,/; (b15q?|s22 flip|s48c|s62 pro)(?: bui|\))/i],[l,[p,"Cat"],[u,b]],[/((?:new )?andromax[\w- ]+)(?: bui|\))/i],[l,[p,"Smartfren"],[u,b]],[/droid.+; (a(?:015|06[35]|142p?))/i],[l,[p,"Nothing"],[u,b]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron|infinix|tecno|micromax|advan)[-_ ]?([-\w]*)/i,/; (imo) ((?!tab)[\w ]+?)(?: bui|\))/i,/(hp) ([\w ]+\w)/i,/(asus)-?(\w+)/i,/(microsoft); (lumia[\w ]+)/i,/(lenovo)[-_ ]?([-\w]+)/i,/(jolla)/i,/(oppo) ?([\w ]+) bui/i],[p,l,[u,b]],[/(imo) (tab \w+)/i,/(kobo)\s(ereader|touch)/i,/(archos) (gamepad2?)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i,/(nook)[\w ]+build\/(\w+)/i,/(dell) (strea[kpr\d ]*[\dko])/i,/(le[- ]+pan)[- ]+(\w{1,9}) bui/i,/(trinity)[- ]*(t\d{3}) bui/i,/(gigaset)[- ]+(q\w{1,9}) bui/i,/(vodafone) ([\w ]+)(?:\)| bui)/i],[p,l,[u,S]],[/(surface duo)/i],[l,[p,G],[u,S]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[l,[p,"Fairphone"],[u,b]],[/(u304aa)/i],[l,[p,"AT&T"],[u,b]],[/\bsie-(\w*)/i],[l,[p,"Siemens"],[u,b]],[/\b(rct\w+) b/i],[l,[p,"RCA"],[u,S]],[/\b(venue[\d ]{2,7}) b/i],[l,[p,"Dell"],[u,S]],[/\b(q(?:mv|ta)\w+) b/i],[l,[p,"Verizon"],[u,S]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[l,[p,"Barnes & Noble"],[u,S]],[/\b(tm\d{3}\w+) b/i],[l,[p,"NuVision"],[u,S]],[/\b(k88) b/i],[l,[p,"ZTE"],[u,S]],[/\b(nx\d{3}j) b/i],[l,[p,"ZTE"],[u,b]],[/\b(gen\d{3}) b.+49h/i],[l,[p,"Swiss"],[u,b]],[/\b(zur\d{3}) b/i],[l,[p,"Swiss"],[u,S]],[/\b((zeki)?tb.*\b) b/i],[l,[p,"Zeki"],[u,S]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[p,"Dragon Touch"],l,[u,S]],[/\b(ns-?\w{0,9}) b/i],[l,[p,"Insignia"],[u,S]],[/\b((nxa|next)-?\w{0,9}) b/i],[l,[p,"NextBook"],[u,S]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[p,"Voice"],l,[u,b]],[/\b(lvtel\-)?(v1[12]) b/i],[[p,"LvTel"],l,[u,b]],[/\b(ph-1) /i],[l,[p,"Essential"],[u,b]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[l,[p,"Envizen"],[u,S]],[/\b(trio[-\w\. ]+) b/i],[l,[p,"MachSpeed"],[u,S]],[/\btu_(1491) b/i],[l,[p,"Rotor"],[u,S]],[/(shield[\w ]+) b/i],[l,[p,"Nvidia"],[u,S]],[/(sprint) (\w+)/i],[p,l,[u,b]],[/(kin\.[onetw]{3})/i],[[l,/\./g," "],[p,G],[u,b]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[l,[p,N],[u,S]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[l,[p,N],[u,b]],[/smart-tv.+(samsung)/i],[p,[u,v]],[/hbbtv.+maple;(\d+)/i],[[l,/^/,"SmartTV"],[p,te],[u,v]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[p,Q],[u,v]],[/(apple) ?tv/i],[p,[l,w+" TV"],[u,v]],[/crkey/i],[[l,P+"cast"],[p,x],[u,v]],[/droid.+aft(\w+)( bui|\))/i],[l,[p,y],[u,v]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[l,[p,Se],[u,v]],[/(bravia[\w ]+)( bui|\))/i],[l,[p,L],[u,v]],[/(mitv-\w{5}) bui/i],[l,[p,O],[u,v]],[/Hbbtv.*(technisat) (.*);/i],[p,l,[u,v]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[p,Ne],[l,Ne],[u,v]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[u,v]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[p,l,[u,g]],[/droid.+; (shield) bui/i],[l,[p,"Nvidia"],[u,g]],[/(playstation [345portablevi]+)/i],[l,[p,L],[u,g]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[l,[p,G],[u,g]],[/\b(sm-[lr]\d\d[05][fnuw]?s?)\b/i],[l,[p,te],[u,R]],[/((pebble))app/i],[p,l,[u,R]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[l,[p,w],[u,R]],[/droid.+; (glass) \d/i],[l,[p,x],[u,R]],[/droid.+; (wt63?0{2,3})\)/i],[l,[p,N],[u,R]],[/droid.+; (glass) \d/i],[l,[p,x],[u,R]],[/(pico) (4|neo3(?: link|pro)?)/i],[p,l,[u,R]],[/; (quest( \d| pro)?)/i],[l,[p,V],[u,R]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[p,[u,_]],[/(aeobc)\b/i],[l,[p,y],[u,_]],[/droid .+?; ([^;]+?)(?: bui|; wv\)|\) applew).+? mobile safari/i],[l,[u,b]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[l,[u,S]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[u,S]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[u,b]],[/(android[-\w\. ]{0,9});.+buil/i],[l,[p,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[h,[d,"EdgeHTML"]],[/(arkweb)\/([\w\.]+)/i],[d,h],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[h,[d,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna|servo)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i,/\b(libweb)/i],[d,h],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[h,d]],os:[[/microsoft (windows) (vista|xp)/i],[d,h],[/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i],[d,[h,we,pe]],[/windows nt 6\.2; (arm)/i,/windows[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i,/(?:win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[h,we,pe],[d,"Windows"]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/(?:ios;fbsv\/|iphone.+ios[\/ ])([\d\.]+)/i,/cfnetwork\/.+darwin/i],[[h,/_/g,"."],[d,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[d,xe],[h,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[h,d],[/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish|openharmony)[-\/ ]?([\w\.]*)/i,/(blackberry)\w*\/([\w\.]*)/i,/(tizen|kaios)[\/ ]([\w\.]+)/i,/\((series40);/i],[d,h],[/\(bb(10);/i],[h,[d,E]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],[h,[d,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[h,[d,M+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[h,[d,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[h,[d,"watchOS"]],[/crkey\/([\d\.]+)/i],[h,[d,P+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[d,he],h],[/panasonic;(viera)/i,/(netrange)mmh/i,/(nettv)\/(\d+\.[\w\.]+)/i,/(nintendo|playstation) ([wids345portablevuch]+)/i,/(xbox); +xbox ([^\);]+)/i,/\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,/(mint)[\/\(\) ]?(\w*)/i,/(mageia|vectorlinux)[; ]/i,/([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,/(hurd|linux) ?([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) (\w+)/i],[d,h],[/(sunos) ?([\w\.\d]*)/i],[[d,"Solaris"],h],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux|serenityos)/i,/(unix) ?([\w\.]*)/i],[d,h]]},Te=function(le,ne){if(typeof le===n&&(ne=le,le=t),!(this instanceof Te))return new Te(le,ne).getResult();var ie=typeof e!==s&&e.navigator?e.navigator:t,Ae=le||(ie&&ie.userAgent?ie.userAgent:""),Fe=ie&&ie.userAgentData?ie.userAgentData:t,me=ne?function(Y,Ue){var pt={};for(var Be in Y)Ue[Be]&&Ue[Be].length%2==0?pt[Be]=Ue[Be].concat(Y[Be]):pt[Be]=Y[Be];return pt}(Oe,ne):Oe,qe=ie&&ie.userAgent==Ae;return this.getBrowser=function(){var Y,Ue={};return Ue[d]=t,Ue[h]=t,ve.call(Ue,Ae,me.browser),Ue[o]=typeof(Y=Ue[h])===c?Y.replace(/[^\d\.]/g,"").split(".")[0]:t,qe&&ie&&ie.brave&&typeof ie.brave.isBrave==i&&(Ue[d]="Brave"),Ue},this.getCPU=function(){var Y={};return Y[f]=t,ve.call(Y,Ae,me.cpu),Y},this.getDevice=function(){var Y={};return Y[p]=t,Y[l]=t,Y[u]=t,ve.call(Y,Ae,me.device),qe&&!Y[u]&&Fe&&Fe.mobile&&(Y[u]=b),qe&&Y[l]=="Macintosh"&&ie&&typeof ie.standalone!==s&&ie.maxTouchPoints&&ie.maxTouchPoints>2&&(Y[l]="iPad",Y[u]=S),Y},this.getEngine=function(){var Y={};return Y[d]=t,Y[h]=t,ve.call(Y,Ae,me.engine),Y},this.getOS=function(){var Y={};return Y[d]=t,Y[h]=t,ve.call(Y,Ae,me.os),qe&&!Y[d]&&Fe&&Fe.platform&&Fe.platform!="Unknown"&&(Y[d]=Fe.platform.replace(/chrome os/i,he).replace(/macos/i,xe)),Y},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return Ae},this.setUA=function(Y){return Ae=typeof Y===c&&Y.length>500?Ne(Y,500):Y,this},this.setUA(Ae),this};Te.VERSION="1.0.40",Te.BROWSER=Re([d,h,o]),Te.CPU=Re([f]),Te.DEVICE=Re([l,p,u,g,b,v,S,R,_]),Te.ENGINE=Te.OS=Re([d,h]),a.exports&&(r=a.exports=Te),r.UAParser=Te;var Ye=typeof e!==s&&(e.jQuery||e.Zepto);if(Ye&&!Ye.ua){var ht=new Te;Ye.ua=ht.getResult(),Ye.ua.get=function(){return ht.getUA()},Ye.ua.set=function(le){ht.setUA(le);var ne=ht.getResult();for(var ie in ne)Ye.ua[ie]=ne[ie]}}})(typeof window=="object"?window:Fi)})(ys,ys.exports);var oc=ys.exports,$e=(a=>(a.KEEPALIVE="keepalive",a.JOINCHANNEL="joinchannel",a.NOTIFYJOIN="notifyjoin",a.NOTIFYSTATUS="notifystatus",a.STATUSREPORT="statusreport",a.LEAVECHANNEL="leavechannel",a.NOTIFYLEAVE="notifyleave",a.NOTIFYPUBLISH="notifypublish",a.BYE="bye",a.RECONNECT="reconnect",a.PUBLISH="publish",a.REFRESHURL="refreshurl",a.UNSUBSCRIBE="unsubscribe",a.ROLEUPDATE="roleupdate",a))($e||{});class Ki{constructor(r,e){m(this,"authInfo");m(this,"userName");m(this,"seqIndex",0);this.authInfo=r,this.userName=typeof e=="number"?e.toString():e}get roleAuth(){if(this.authInfo.role){const{timestamp:r,nonce:e,token:t,role:i}=this.authInfo;return{timestamp:r,nonce:e,token:t,tokenrole:i}}}static get adaptInfo(){var e,t,i,s;let r=new oc.UAParser().getResult();return{os_name:((e=r.os.name)==null?void 0:e.replace(" ",""))+"_"+((t=r.browser.name)==null?void 0:t.replace(" ","")),device_name:((i=r.device.model)==null?void 0:i.replace(" ",""))||"",brand_name:((s=r.device.vendor)==null?void 0:s.replace(" ",""))||"",device_key:window.navigator.userAgent,os_version:r.browser.version||"",sdk_version:"7.2.9",version:"v1"}}refreshAuthInfo(r){this.authInfo=r}getSeqIndex(){return this.seqIndex}createKeepAlivePackage(){return this.createBaseSendPackage("keepalive")}createJoinPackage(r){let e=this.createBaseSendPackage("joinchannel");return e.header.displayName=this.userName,e.header.clientversion=Le.getVersionNumber().toString(),e.header.platform="web",this.roleAuth&&(e.data.auth=this.roleAuth),e.data.adapt=Ki.adaptInfo,r&&(e.data=X(X({},e.data),r)),e}createLeavePackage(){return this.createBaseSendPackage("leavechannel")}createStatusPackage(r){let e=this.createBaseSendPackage("statusreport");return e.header.displayName=this.userName,e.data.status=r,e}createPublishPackage(){let r=this.createBaseSendPackage("publish");return r.data.users=[{}],this.roleAuth&&(r.data.auth=this.roleAuth),r}createRoleUpdatePackage(){let r=this.createBaseSendPackage("roleupdate");return r.header.displayName=this.userName,r}createReconnectPackage(r){let e=this.createBaseSendPackage("reconnect");return e.header.displayName=this.userName,e.header.clientversion=Le.getVersionNumber().toString(),e.header.platform="web",e.data=X(X({},e.data),r!=null?r:{}),this.roleAuth&&(e.data.auth=this.roleAuth),e}createRefreshUrlPackage(){let r=this.createBaseSendPackage("refreshurl");return r.header.displayName=this.userName,r}createResponsePackage(r,e){return{version:1,code:200,tid:r,msgtype:e}}createBaseSendPackage(r){var e;return++this.seqIndex,{version:1,msgtype:r,tid:mt(),header:{appid:this.authInfo.appId,channelid:this.authInfo.channelId,sessionid:(e=this.authInfo.sessionId)!=null?e:"",userid:this.authInfo.userId},data:{seq:this.seqIndex}}}}const Ua="ALI_RTC_SDK_ALLOCATE_RESULT",yi=class yi{constructor(r,e,t){m(this,"result",null);m(this,"pms",null);m(this,"env");m(this,"config");m(this,"joinMode");this.env=r,this.config=e,this.joinMode=t;let i=localStorage.getItem(Ua);if(i){const s=JSON.parse(i);s.appId===e.appId&&s.expireTs-3e5>Date.now()?this.result=s.allocatedData:T.info(`[${yi.logName}]`,"allocate","cached data is invalid")}}fetchAndUpdate(){if(this.pms)return this.pms;const{appId:r,channelId:e,sessionId:t,userId:i,timestamp:s,token:n,nonce:c}=this.config,o=new URLSearchParams({appid:r,channelid:e,session:t,userid:i,timestamp:`${s}`,token:n,nonce:c!=null?c:"",adapt:"true",clitype:"2"});this.joinMode&&o.set("joinmode",this.joinMode);const l=this.env===It.pre?Rt.pre:Rt.prod;return this.pms=fetch(`https://${l}/gslb/v1/allocate?${o.toString()}`,{method:"POST",body:JSON.stringify(Ki.adaptInfo)}).then(d=>d.json()).then(d=>{if(d.code===0){const u=d.data;this.result=u;const{ice_ufrag:p}=u.h5auth,[h,f]=atob(p).split("_"),g={appId:r,expireTs:1e3*parseInt(f),allocatedData:u};return T.info(`[${yi.logName}]`,"got allocate result and save",u.h5auth.ice_ufrag),localStorage.setItem(Ua,JSON.stringify(g)),u}return null}).catch(d=>(T.error(`[${yi.logName}]`,"allocate",d),null)),this.pms}};m(yi,"logName","Allocator");let Ii=yi;class Rs{constructor(r,e){m(this,"originTrack");m(this,"originVideo");m(this,"targetWidth");m(this,"targetHeight");m(this,"targetFrameRate");m(this,"targetCanvas");m(this,"animationFrameId");m(this,"resultTrack");this.targetWidth=e.width,this.targetHeight=e.height,this.targetFrameRate=e.frameRate,this.originTrack=r,this.originVideo=document.createElement("video"),this.originVideo.muted=!0,this.originVideo.autoplay=!0,this.originVideo.controls=!1,this.targetCanvas=document.createElement("canvas"),this.targetCanvas.width=this.targetWidth,this.targetCanvas.height=this.targetHeight}updateOptions(r){this.targetWidth=r.width,this.targetHeight=r.height,this.targetFrameRate=r.frameRate,this.targetCanvas.width=this.targetWidth,this.targetCanvas.height=this.targetHeight,this.resultTrack&&this.resultTrack.applyConstraints({frameRate:this.targetFrameRate})}dispose(){}getVideoTrack(){return this.resultTrack||(this.resultTrack=this.targetCanvas.captureStream().getVideoTracks()[0],this.resultTrack.applyConstraints({frameRate:this.targetFrameRate})),this.resultTrack}cancelAnimation(){this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=void 0)}getPositionAndSize(r,e,t,i){const s=e/r,n=i/t;let c=t,o=i,l=0,d=0;return n>s?(c=Math.round(o/s),l=Math.round((t-c)/2)):n<s&&(o=Math.round(c*s),d=Math.round((i-o)/2)),{x:l,y:d,width:c,height:o}}}class cc extends Rs{constructor(e,t){super(e,t);m(this,"targetCtx");this.targetCtx=this.targetCanvas.getContext("2d"),this.startRender=this.startRender.bind(this),this.stopRender=this.startRender.bind(this),this.initStream(e)}initStream(e){const t=new MediaStream;t.addTrack(e),this.originVideo.srcObject=t,this.originVideo.play(),this.originVideo.addEventListener("canplay",this.startRender),this.originVideo.addEventListener("pause",this.stopRender),this.originVideo.addEventListener("ended",this.stopRender)}startRender(){this.cancelAnimation();const e=()=>{if(!this.targetCtx)return;const t=this.getPositionAndSize(this.originVideo.videoWidth,this.originVideo.videoHeight,this.targetWidth,this.targetHeight);this.targetCtx.drawImage(this.originVideo,0,0,this.originVideo.videoWidth,this.originVideo.videoHeight,t.x,t.y,t.width,t.height),this.originVideo.paused||this.originVideo.ended||(this.animationFrameId=requestAnimationFrame(e))};e()}stopRender(){this.cancelAnimation()}dispose(){this.stopRender(),this.originVideo.removeEventListener("play",this.startRender),this.originVideo.removeEventListener("pause",this.stopRender),this.originVideo.removeEventListener("ended",this.stopRender),this.originVideo.pause(),this.originVideo.srcObject=null}}function Ba(a,r,e){const t=a.createShader(r);if(t)return a.shaderSource(t,e),a.compileShader(t),a.getShaderParameter(t,a.COMPILE_STATUS)?t:(console.error(`An error occurred compiling the shaders: ${a.getShaderInfoLog(t)}`),a.deleteShader(t),null);console.error("create shader failed")}class Ha extends Rs{constructor(e,t){super(e,t);m(this,"targetCtx");m(this,"targetTexture");m(this,"locationMap");this.targetCtx=this.targetCanvas.getContext("webgl2"),this.locationMap={},this.startRender=this.startRender.bind(this),this.stopRender=this.startRender.bind(this),this.updateBuffer=this.updateBuffer.bind(this),this.initGL(),this.initStream(e)}static isSupport(){return function(){let e;try{const t=document.createElement("canvas");t.width=1,t.height=1;const i={alpha:!1,depth:!1,stencil:!1,antialias:!1,preferLowPowerToHighPerformance:!0};e=t.getContext("webgl2",i)}catch(t){return!1}return!!e}()}initGL(){const e=this.targetCtx;if(!e)return;this.targetTexture=function(o){const l=o.createTexture();return o.bindTexture(o.TEXTURE_2D,l),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.LINEAR),l}(e);const t=function(o,l,d){const u=Ba(o,o.VERTEX_SHADER,l),p=Ba(o,o.FRAGMENT_SHADER,d),h=o.createProgram();if(h&&u&&p)return o.attachShader(h,u),o.attachShader(h,p),o.linkProgram(h),o.getProgramParameter(h,o.LINK_STATUS)?h:(console.error(`Unable to initialize the shader program: ${o.getProgramInfoLog(h)}`),null)}(e,`
12
+ `+l.message),console.error("Failed log data:",s)),l}})}(t,i,e)}),this.getOpt().sendPayload=(t,i)=>I(this,null,function*(){return this.reliableSendAsync(t,i)}),this.overwriteTransString(e)}getStatus(){return{networkStatus:this.networkStatus,failedLogsCount:this.failedLogs.size,isRetryActive:this.retryTimer!==null,config:this.reliableConfig}}retryAll(){this.debug("Manual retry triggered"),this.retryAllFailedLogs()}clearFailedLogs(){const e=this.failedLogs.size;this.failedLogs.clear(),this.debug(`Cleared ${e} failed logs`)}getFailedLogs(){return Array.from(this.failedLogs.values())}destroy(){this.retryTimer&&(clearInterval(this.retryTimer),this.retryTimer=null),this.saveFailedLogs(),this.failedLogs.clear(),re.instances.delete(this),re.instances.size===0&&(re.beforeUnloadHandler&&(window.removeEventListener("beforeunload",re.beforeUnloadHandler),re.beforeUnloadHandler=null),re.visibilityChangeHandler&&(document.removeEventListener("visibilitychange",re.visibilityChangeHandler),re.visibilityChangeHandler=null),re.globalUnloadListenersRegistered=!1,re.unloadHooks=[],re.onlineHandler&&(window.removeEventListener("online",re.onlineHandler),re.onlineHandler=null),re.offlineHandler&&(window.removeEventListener("offline",re.offlineHandler),re.offlineHandler=null),re.globalNetworkListenersRegistered=!1),this.debug("WebTrackerBrowser destroyed")}},m(re,"globalUnloadListenersRegistered",!1),m(re,"globalNetworkListenersRegistered",!1),m(re,"instances",new Set),m(re,"unloadHooks",[]),m(re,"beforeUnloadHandler",null),m(re,"visibilityChangeHandler",null),m(re,"onlineHandler",null),m(re,"offlineHandler",null),re);const{BrowserUtil:Ma,SystenUtil:La}=J.AliRTS,nc=Ea(),zi=6e5,Na={host:"cn-hangzhou.log.aliyuncs.com",project:"alivc-aio",logstore:"logger",time:10,count:10},xa={host:"ap-southeast-1.log.aliyuncs.com",project:"alivc-aio-sgp",logstore:"logger",time:10,count:10};function bs(){return $i(new Date,"HH:MM:ss.l")}function Oa(){return $i(new Date,"isoDate")}var Ss=(a=>(a[a.DEBUG=0]="DEBUG",a[a.INFO=1]="INFO",a[a.API=2]="API",a[a.WARNING=3]="WARNING",a[a.ERROR=4]="ERROR",a[a.NONE=5]="NONE",a))(Ss||{});class Va{constructor(){m(this,"tracker");m(this,"stsPlugin");m(this,"stsData");m(this,"stsExpiration",Date.now());m(this,"clientId",mt());m(this,"bSesid",mt());m(this,"logLevel",3);m(this,"appId","");m(this,"sessionId","");m(this,"logCache",[]);m(this,"updateTaskTimer");m(this,"endReported",!0);m(this,"logSequence",0);m(this,"globalEnv","DEFAULT");m(this,"beforeUnloadHandler",null);m(this,"sendLogBeforeUnload",r=>I(this,null,function*(){if(!this.stsPlugin)return;this.logSequence+=1,r.unshift(this.getLogParams(710203,{log:`[${Oa()} ${bs()}] [INF] beforeunload`,stat_log_seq:this.logSequence}));const e=this.globalEnv==="SEA"?xa:Na,t=`https://${e.project}.${e.host}/logstores/${e.logstore}`,i={__logs__:r.map(c=>this.stsPlugin.transString(c))},{data:s,header:n}=yield this.stsPlugin.process(t,JSON.stringify(i));fetch(t,{keepalive:!0,method:"POST",headers:n,body:s})}));m(this,"logMethod",(r,e=console.log)=>(...t)=>{let i=bs();this.logLevel<=r&&e(i,...t);let s=Le.paramArrayToString(t);r>0&&this.addLog(s)});m(this,"d",this.logMethod(0,console.debug));m(this,"i",this.logMethod(1));m(this,"w",this.logMethod(3,console.warn));m(this,"e",this.logMethod(4,(...r)=>{const[e,...t]=r;console.error(e,"<error>",t)}));m(this,"ev",this.logMethod(2));m(this,"a",this.logMethod(2,(...r)=>{const[e,...t]=r;if(t.length>2){const i=`${t[1]}`;i.startsWith("__g__")&&console.group(`${i.substring(5)}_${t[2]}`)}console.log(e,...t)}));m(this,"ar",this.logMethod(2,(...r)=>{const[e,...t]=r;console.log(e,...t),t.length>2&&`${t[1]}`.startsWith("__g__")&&console.groupEnd()}));m(this,"ae",this.logMethod(2,(...r)=>{const[e,...t]=r;console.error(e,"<error>",...t),t.length>2&&`${t[1]}`.startsWith("__g__")&&console.groupEnd()}));this.ensureBeforeUnloadHandler()}ensureBeforeUnloadHandler(){this.beforeUnloadHandler||(this.beforeUnloadHandler=()=>{this.reportEnd(!0)},window.addEventListener("beforeunload",this.beforeUnloadHandler))}init(r){r&&(this.globalEnv=r),this.ensureBeforeUnloadHandler(),this.reset(),this.startSTSUpdateTask()}destroy(){this.updateTaskTimer&&clearTimeout(this.updateTaskTimer),this.beforeUnloadHandler&&(window.removeEventListener("beforeunload",this.beforeUnloadHandler),this.beforeUnloadHandler=null),this.tracker&&(this.tracker.destroy(),this.tracker=void 0)}reset(){this.bSesid=mt(),this.endReported=!0,this.logSequence=0,this.appId="",this.sessionId=""}startSTSUpdateTask(){return I(this,null,function*(){this.updateTaskTimer&&clearTimeout(this.updateTaskTimer);try{const r=yield this.refreshSTSToken();this.createTracker(r)}catch(r){}this.updateTaskTimer=setTimeout(()=>{this.startSTSUpdateTask()},zi)})}refreshSTSToken(){return I(this,null,function*(){if(!this.stsData||this.stsExpiration<=Date.now()+zi){const r=yield this.requestSTSToken(),e=new Date(r==null?void 0:r.Expiration).getTime()||0,t=Date.now()+zi;this.stsExpiration=Math.max(e,t),this.stsData=r}return this.stsData})}requestSTSToken(){const r=Date.now(),e=`${this.clientId}|woMMssV6jmyol9fr|${r}`,t={Action:"AssumeSlsRoleV2",AuthInfo:ai.MD5(e).toString(ai.enc.Hex),ClientId:this.clientId,BusinessType:"logger",AppVersion:"1.0",Version:"2017-03-14",AuthTimestamp:`${r}`,TerminalType:"web",DeviceModel:"",Format:"JSON",SignatureMethod:"HMAC-SHA1",SignatureVersion:"1.0",Timestamp:$i(r,"isoUtcDateTime")},i=new URLSearchParams(t).toString(),s=`https://${this.globalEnv==="SEA"?"slsrole-intl.alicdn.com":"slsrole.alicdn.com"}/?${i}`;return fetch(s).then(n=>n.json()).then(n=>JSON.parse(window.atob(n.SlsAuthResult)))}createTracker(r){if(!this.tracker){const e={accessKeyId:r.AccessKeyId,accessKeySecret:r.AccessKeySecret,securityToken:r.SecurityToken,refreshSTSTokenInterval:zi,stsTokenFreshTime:void 0,refreshSTSToken:()=>{this.refreshSTSToken().then(s=>{e.accessKeyId=s.AccessKeyId,e.accessKeySecret=s.AccessKeySecret,e.securityToken=s.SecurityToken}).catch(()=>{})}},t=new ac(this.globalEnv==="SEA"?xa:Na),i=gs(e);t.useStsPlugin(i),this.stsPlugin=i,this.tracker=t,this.reportStartAndCache()}}changeConfig(r){r.logLevel!==void 0&&r.logLevel>=0&&r.logLevel<=5&&(this.logLevel=r.logLevel)}setSessionID(r,e){r&&e&&(this.appId=r,this.sessionId=e,this.reportStartAndCache())}reportStartAndCache(){if(!this.tracker||!this.sessionId)return;this.endReported=!1;const r={task_btm_sec:0,task_duration:0,task_etm_sec:0,task_type:"session"},e=[this.getLogParams(710201,r),this.getLogParams(710202,r)];this.tracker.sendBatchLogsImmediate(e),this.logCache.forEach(t=>{this.sendLog(t)})}reportEnd(r=!1){if(!this.tracker||!this.sessionId||this.endReported)return void this.reset();const e={task_btm_sec:0,task_duration:0,task_etm_sec:0,task_type:"session"},t=[this.getLogParams(710204,e),this.getLogParams(710205,e)];r?this.sendLogBeforeUnload(t):(this.tracker.sendBatchLogsImmediate(t),this.endReported=!0),this.reset()}getLogParams(r,e){return X({appid:`${window.location.host}`,appid_list:this.appId,appver:"",b_sesid:this.bSesid,biz_type:"rtc",cpu_info:nc,db:Ma.browserName,dm:Ma.browserVersion,install_uuid:this.clientId,logger_v:"0.0.1",os:La.systemName,osv:La.systemVersion,p_sesid:this.bSesid,sdk_version:_i,sdkname:"AliRTCSdk",stm:Date.now(),tar_pf:"web",traceid:this.sessionId,event_id:r},e||{})}sendLog(r){if(!this.tracker||!this.sessionId)return;this.logSequence+=1;const e=this.getLogParams(710203,{log:r,stat_log_seq:this.logSequence});this.tracker.send(e)}addLog(r){const e=bs(),t=`[${Oa()} ${e}] ${r}`;this.sessionId&&this.tracker?this.sendLog(t):(this.logCache.push(t),this.logCache.length>=200&&this.logCache.shift())}}class T{static getLogger(){if(this.activeInstanceId&&this.loggers.has(this.activeInstanceId))return this.loggers.get(this.activeInstanceId);const r=this.loggers.values().next().value;return r||new Va}static setActiveInstance(r){this.activeInstanceId=r}static init(r,e){if(this.loggers.has(r))this.loggers.get(r).init(e);else{const t=new Va;t.init(e),this.loggers.set(r,t)}this.activeInstanceId=r}static destroy(r){const e=this.loggers.get(r);if(e&&(e.destroy(),this.loggers.delete(r)),this.activeInstanceId===r){const t=this.loggers.keys().next().value;this.activeInstanceId=t||""}}static setLogLevel(r){this.loggers.forEach(e=>e.changeConfig({logLevel:r}))}static setSessionID(r,e){this.getLogger().setSessionID(r,e)}static reportEnd(){this.getLogger().reportEnd()}static interface(...r){this.getLogger().a("[API]",...r)}static interfaceResult(r,e,t,...i){t?this.getLogger().ar("[ARE]",r,e,...i):this.getLogger().ae("[ARE]",r,e,...i)}static event(...r){this.getLogger().ev("[EVT]",...r)}static debug(...r){this.getLogger().d("[DBG]",...r)}static info(...r){this.getLogger().i("[INF]",...r)}static warn(...r){this.getLogger().w("[WARN]",...r)}static error(...r){this.getLogger().e("[ERR]",...r)}}m(T,"loggers",new Map),m(T,"activeInstanceId","");const be=class be{constructor(){m(this,"userStatsMap",new Map);m(this,"eventDataArray",[]);this.initPageVisibilityMonitor()}static setGlobalQualityStatsEnable(r){be.globalQualityStatsEnable=r}addEventData(r,...e){if(!be.globalQualityStatsEnable)return;let t=Date.now(),i="";if(this.eventDataArray.length>=be.MAX_EVENT_COUNT)return;this.eventDataArray.length>0&&(t-=this.eventDataArray[0].time),i=e.map(String).join(",");const s={name:r,time:t,info:i};this.eventDataArray.push(s)}initPageVisibilityMonitor(){typeof document!="undefined"&&document.addEventListener("visibilitychange",()=>{this.handleVisibilityChange()})}handleVisibilityChange(){document.hidden&&this.userStatsMap.forEach(r=>{r.docHidden=!0})}static generateHexRandomString(r=16){const e="0123456789abcdef";let t="";for(let i=0;i<r;i++)t+=e[Math.floor(16*Math.random())];return t}static getInstance(){return be.instance||(be.instance=new be),be.instance}setRemoteViewConfig(r,e){if(!be.globalQualityStatsEnable)return;const t=Date.now(),i=t+"_"+be.generateHexRandomString();this.userStatsMap.has(r)&&this.removeRemoteViewConfig(r);const s={uid:r,uuid:i,view:e,firstFrameTime:0,subscribeStartTime:t,beginTime:0,playTime:0,playTimeOnce:0,stallData200ms:{stallCount:0,stallCountOnce:0,stallTime:0,stallTimeOnce:0},stallData600ms:{stallCount:0,stallCountOnce:0,stallTime:0,stallTimeOnce:0},lastFrameTimestamp:0,beginTimeOnce:0,docHidden:!1,isStop:!1,needReset:!1};this.userStatsMap.set(r,s),e.requestVideoFrameCallback(function n(c){let o=be.getInstance().userStatsMap.get(r);if(o){if(o.needReset)return o.firstFrameTime=0,o.firstFrameTime=0,o.subscribeStartTime=t,o.beginTime=0,o.playTime=0,o.playTimeOnce=0,o.stallData200ms={stallCount:0,stallCountOnce:0,stallTime:0,stallTimeOnce:0},o.stallData600ms={stallCount:0,stallCountOnce:0,stallTime:0,stallTimeOnce:0},o.lastFrameTimestamp=0,o.beginTimeOnce=0,o.docHidden=!1,void(o.needReset=!1);if(o.isStop=!1,o.firstFrameTime===0&&(o.firstFrameTime=Date.now()-o.subscribeStartTime),o.beginTime===0&&(o.beginTime=c),o.beginTimeOnce===0&&(o.beginTimeOnce=c),o.lastFrameTimestamp!==0&&!o.docHidden){let l=200,d=c-o.lastFrameTimestamp;d>l&&(o.stallData200ms.stallTime+=Math.trunc(d-l),o.stallData200ms.stallTimeOnce+=Math.trunc(d-l),o.stallData200ms.stallCount++,o.stallData200ms.stallCountOnce++),l=600,d>l&&(o.stallData600ms.stallTime+=Math.trunc(d-l),o.stallData600ms.stallTimeOnce+=Math.trunc(d-l),o.stallData600ms.stallCount++,o.stallData600ms.stallCountOnce++)}o.docHidden=!1,o.lastFrameTimestamp=c,o.playTime=Math.trunc(c-o.beginTime),o.playTimeOnce=Math.trunc(c-o.beginTimeOnce),e.requestVideoFrameCallback(n)}})}removeRemoteViewConfig(r){be.globalQualityStatsEnable&&be.getInstance().userStatsMap.delete(r)}unsubscribeRemoteViewConfig(r){if(!be.globalQualityStatsEnable)return;let e=be.getInstance().userStatsMap.get(r);e&&(e.isStop=!0,e.needReset=!0)}clearAll(r){be.globalQualityStatsEnable&&r&&this.userStatsMap.forEach((e,t)=>{t.startsWith(r)&&this.userStatsMap.delete(t)})}getSummary(){if(!be.globalQualityStatsEnable)return"closed";try{if(Date.now()-be.lastSummaryTime<1e3)return"{}";be.lastSummaryTime=Date.now();const r={totalUsers:this.userStatsMap.size,timestamp:Date.now(),totalEvents:this.eventDataArray.length,events:this.eventDataArray.slice(-be.MAX_EVENT_COUNT),users:[]};return this.userStatsMap.forEach((e,t)=>{e.isStop||(r.users.push({uid:t,uuid:e.uuid,fTime:e.firstFrameTime,sct200:e.stallData200ms.stallCount,stt200:e.stallData200ms.stallTime,scto200:e.stallData200ms.stallCountOnce,stto200:e.stallData200ms.stallTimeOnce,sct600:e.stallData600ms.stallCount,stt600:e.stallData600ms.stallTime,scto600:e.stallData600ms.stallCountOnce,stto600:e.stallData600ms.stallTimeOnce,playTime:e.playTime,playTimeOnce:e.playTimeOnce}),e.beginTimeOnce=0,e.stallData600ms.stallCountOnce=0,e.stallData600ms.stallTimeOnce=0,e.stallData200ms.stallCountOnce=0,e.stallData200ms.stallTimeOnce=0,e.playTimeOnce=0)}),this.eventDataArray=[],JSON.stringify(r)}catch(r){return'{"getSummary":"error"}'}}};m(be,"eventStartSub","startSub"),m(be,"eventRemoveSub","RemoveSub"),m(be,"eventSubSuccess","SubOk"),m(be,"eventSubError","SubErr"),m(be,"eventFirstAudio","firstAudio"),m(be,"eventRtsSub","rtsSub"),m(be,"eventRtsSubSuccess","rtsSubOk"),m(be,"eventRtsSubClose","rtsSubClose"),m(be,"eventRetrySub","retry"),m(be,"eventRetrySubAuto","retryAuto"),m(be,"instance"),m(be,"MAX_EVENT_COUNT",100),m(be,"globalQualityStatsEnable",!0),m(be,"lastSummaryTime",0);let _e=be;const is=class is extends oe{constructor(e){super();m(this,"roomServerUrl");m(this,"label");m(this,"rtsInstance");m(this,"currentStatus",ae.AliRtcConnectionStatusInit);m(this,"latestStreamInfo");m(this,"preferredL1Ip");m(this,"usePreferredL1InRetry",!0);m(this,"_remoteStream");m(this,"remoteStream");m(this,"_prevDownlinkStat");m(this,"networkQualityTimer");this.config=e;const{env:t,appId:i,currentUserId:s,targetChannelId:n,targetUserId:c,token:o,nonce:l,timestamp:d}=e,u=Le.createCallid(),p=new URLSearchParams({appid:i,channelid:n,userid:s,timestamp:d.toString(),token:o,nonce:l!=null?l:"",tid:u,pubchannelid:n,pubuserid:c}),h=t===It.pre?Rt.pre:Rt.prod;this.roomServerUrl=`https://${h}/signaling/v1/querypulluri?${p.toString()}`,this.label=`${this.config.currentUserId} => ${this.config.targetChannelId} > ${this.config.targetUserId}`,_e.getInstance().addEventData(_e.eventRtsSub,this.config.currentUserId,this.config.targetChannelId,this.config.targetUserId),this.fetchStreamUrlAndPlay()}get logName(){return`${is.logName}(${this.label})`}updateConnectionStatus(e){this.currentStatus!==e&&(this.currentStatus=e,this.emit("connectionStatusChange",e))}handleError(e,t){var i;T.error(`[${this.logName}]`,"Error:",e,t),this.emit("error",e,t),this.updateConnectionStatus(ae.AliRtcConnectionStatusFailed),(i=this.rtsInstance)==null||i.dispose(),this.rtsInstance=void 0}fetchStreamUrlAndPlay(){return I(this,null,function*(){var e,t,i;this.updateConnectionStatus(ae.AliRtcConnectionStatusConnecting);try{const s=yield fetch(this.roomServerUrl);if(!s.ok){const d=yield s.text();return void this.handleError("FETCH_STREAM_URL_FAILED",`Fetch stream url failed, status: ${s.status} ${d}`)}const n=yield s.json();if(T.debug(`[${this.logName}]`,"Query pull uri response:",n),n.code!==0)return void this.handleError("FETCH_STREAM_URL_FAILED",`Business error, code: ${n.code}`);if(!((t=(e=n==null?void 0:n.data)==null?void 0:e.subscribe)!=null&&t.pullstreamurl)||!((i=n==null?void 0:n.data)!=null&&i.tracks))return void this.handleError("NO_STREAM_AVAILABLE","No stream available");const c=`${n.data.subscribe.pullstreamurl}&curUid=${this.config.currentUserId}&tarCid=${this.config.targetChannelId}&tarUid=${this.config.targetUserId}`,o=n.data.tracks.filter(d=>mr(d.msid)).map(d=>d.msid),l=n.data.tracks.filter(d=>gr(d.msid)).map(d=>d.msid);if(o.length===0&&l.length===0)return void this.handleError("NO_STREAM_AVAILABLE","No tracks available");T.info(`[${this.logName}]`,"Fetch stream url success",c,o,l),this.latestStreamInfo={url:c,vMsid:o,aMsid:l},this.preferredL1Ip=n.l1ip,this.rtsInstance=J.AliRTS.createClient(),this.rtsInstance.on("reconnect",d=>{d.retryTimes>=300?this.handleError("SUBSCRIBE_FAILED","reconnect failed"):this.currentStatus!==ae.AliRtcConnectionStatusReconnecting&&(T.warn(`[${this.logName}]`,"reconnecting",d),this.updateConnectionStatus(ae.AliRtcConnectionStatusReconnecting))}),this.rtsInstance.on("hebtReceived",d=>{var u,p;d.recode===0&&((p=(u=d.streams)==null?void 0:u[0])==null?void 0:p.res_code)===200&&this.currentStatus===ae.AliRtcConnectionStatusReconnecting&&(T.warn(`[${this.logName}]`,"reconnect success",d),this.updateConnectionStatus(ae.AliRtcConnectionStatusConnected))});try{if(this._remoteStream=yield this.subscribeWithPreferredL1Fallback(c,{vMsid:o,aMsid:l,heartbeat:{interval:1e3,timeout:5e3},retryTimes:300,beforeRetry:()=>I(this,null,function*(){var u;T.info(`[${this.logName}]`,"Trying to fetch new stream url...");const d=yield fetch(this.roomServerUrl);if(d.status!==400){if(d.ok&&d.status===200){const p=yield d.json();if(T.debug(`[${this.logName}]`,"Query pull uri response:",p),p.code===0&&((u=p.data.subscribe)==null?void 0:u.pullstreamurl)&&p.data.tracks){const h=`${p.data.subscribe.pullstreamurl}&curUid=${this.config.currentUserId}&tarCid=${this.config.targetChannelId}&tarUid=${this.config.targetUserId}`,f=p.data.tracks.filter(b=>mr(b.msid)).map(b=>b.msid),g=p.data.tracks.filter(b=>gr(b.msid)).map(b=>b.msid);if(f.length>0||g.length>0){const b=this.usePreferredL1InRetry?ls(h,p.l1ip):h;T.info(`[${this.logName}]`,"Fetch new stream url success",b,f,g,`usePreferredL1InRetry=${this.usePreferredL1InRetry}`),this.latestStreamInfo={url:b,vMsid:f,aMsid:g}}}}return this.latestStreamInfo}{const p=yield d.text();this.handleError("FETCH_STREAM_URL_FAILED",`Fetch new stream url failed, status: ${d.status} ${p}`)}})}),T.info(`[${this.logName}]`,"Subscribe success",this._remoteStream.traceId),this.remoteStream=this.createRemoteStreamProxy(this._remoteStream),this.updateConnectionStatus(ae.AliRtcConnectionStatusConnected),this.startNetworkQualityTimer(),_e.getInstance().addEventData(_e.eventRtsSubSuccess,this.config.currentUserId,this.config.targetChannelId,this.config.targetUserId),this.config.view){let d;if(d=typeof this.config.view=="string"?document.getElementById(this.config.view):this.config.view,d instanceof HTMLVideoElement)try{_e.getInstance().setRemoteViewConfig(this.config.currentUserId+"_"+this.config.targetChannelId+"_"+this.config.targetUserId,d)}catch(u){}d instanceof HTMLMediaElement?this._remoteStream.play(d):this.emit("error","INVALID_VIEW_ELEMENT","view is not a media element")}}catch(d){this.handleError("SUBSCRIBE_FAILED",`Subscribe failed: ${d.message}`)}}catch(s){this.handleError("FETCH_STREAM_URL_FAILED",`Fetch stream url failed: ${s.message}`)}})}subscribeWithPreferredL1Fallback(e,t){return I(this,null,function*(){const i=ls(e,this.preferredL1Ip);if(i!==e){const n=window.__ali_prefer_media_server||this.preferredL1Ip;T.info(`[${this.logName}]`,"Subscribing with preferred media server, ip:",n);const c=new Promise((o,l)=>{setTimeout(()=>l(new Error("PREFERRED_L1_TIMEOUT")),3e3)});try{const o=yield Promise.race([this.rtsInstance.subscribe(i,t),c]);return this.latestStreamInfo.url=i,this.logCandidateProtocol("subscribe (preferred)"),o}catch(o){if(o.message==="PREFERRED_L1_TIMEOUT"){T.warn(`[${this.logName}]`,"Preferred media server subscribe timeout, falling back to DNS"),this.usePreferredL1InRetry=!1;const l=yield this.rtsInstance.subscribe(e,t);return this.logCandidateProtocol("subscribe (fallback)"),l}throw o}}const s=yield this.rtsInstance.subscribe(e,t);return this.logCandidateProtocol("subscribe"),s})}logCandidateProtocol(e){return I(this,null,function*(){var t,i,s;try{const n=(s=(i=(t=this.rtsInstance)==null?void 0:t.commonController)==null?void 0:i.peerCore)==null?void 0:s.pc;if(!n)return void T.debug(`[${this.logName}]`,`${e} - PC not available`);const c=yield n.getStats();let o,l,d,u;c.forEach(p=>{p.type==="candidate-pair"&&p.state==="succeeded"&&p.nominated&&(o=p.localCandidateId,l=p.remoteCandidateId)}),o||l||c.forEach(p=>{p.type!=="candidate-pair"||p.state!=="succeeded"&&p.state!=="in-progress"||o||(o=p.localCandidateId,l=p.remoteCandidateId)}),c.forEach(p=>{p.type==="local-candidate"&&p.id===o&&(d=p.protocol),p.type==="remote-candidate"&&p.id===l&&(u=p.protocol)}),T.info(`[${this.logName}]`,`${e} - Candidate Protocol: local=${d||"unknown"}, remote=${u||"unknown"}`)}catch(n){T.warn(`[${this.logName}]`,`${e} - Failed to get candidate protocol:`,n)}})}createRemoteStreamProxy(e){const t=this.logName;return new Proxy(e,{get(i,s,n){const c=Reflect.get(i,s,n);return typeof c=="function"?function(...o){T.interface(`[${t}]`,`remoteStream.${String(s)} called`,o.length>0?o:"");const l=c.apply(i,o);return l instanceof Promise?l.then(d=>(T.info(`[${t}]`,`remoteStream.${String(s)} resolved`,d!==void 0?d:""),d),d=>{throw T.error(`[${t}]`,`remoteStream.${String(s)} rejected`,d),d}):l}:c}})}startNetworkQualityTimer(){this.stopNetworkQualityTimer(),this._prevDownlinkStat=void 0,this.networkQualityTimer=setInterval(()=>I(this,null,function*(){if(this.currentStatus===ae.AliRtcConnectionStatusConnected)try{const e=yield this.getNetworkQuality();this.emit("networkQuality",e)}catch(e){T.warn(`[${this.logName}]`,"Failed to get network quality:",e)}}),2e3)}stopNetworkQualityTimer(){this.networkQualityTimer&&(clearInterval(this.networkQualityTimer),this.networkQualityTimer=void 0)}getNetworkQuality(){return I(this,null,function*(){var h,f,g;const e=(g=(f=(h=this.rtsInstance)==null?void 0:h.commonController)==null?void 0:f.peerCore)==null?void 0:g.pc;if(!e||e.connectionState==="disconnected"||e.connectionState==="failed"||e.connectionState==="closed")return{rtt:0,loss:0,quality:tt.AliRtcNetworkDisconnected};let t=0,i=0,s=0;const n=e.getReceivers();for(const b of n)(yield b.getStats()).forEach(S=>{S.type==="candidate-pair"&&typeof S.currentRoundTripTime=="number"&&(t=Math.round(1e3*S.currentRoundTripTime)),S.type!=="inbound-rtp"||S.mediaType!=="audio"&&S.mediaType!=="video"||(i+=S.packetsLost||0,s+=S.packetsReceived||0)});if(!this._prevDownlinkStat)return this._prevDownlinkStat={totalPacketsLost:i,totalPacketsReceived:s},{rtt:t,loss:0,quality:tt.AliRtcNetworkUnknown};const{totalPacketsLost:c,totalPacketsReceived:o}=this._prevDownlinkStat,l=i-c,d=s-o;let u=0;l>0&&d>=0&&(u=Math.round(l/(l+d)*100));const p=ds(u,t);return this._prevDownlinkStat={totalPacketsLost:i,totalPacketsReceived:s},{rtt:t,loss:u,quality:p}})}dispose(){let e=this.config.currentUserId;T.info(`[${this.logName}]`,"dispose"),this.stopNetworkQualityTimer(),this.updateConnectionStatus(ae.AliRtcConnectionStatusDisconnected),_e.getInstance().addEventData(_e.eventRtsSubClose,this.config.currentUserId,this.config.targetChannelId,this.config.targetUserId),this.rtsInstance&&this.rtsInstance.dispose();try{_e.getInstance().clearAll(e)}catch(t){}}};m(is,"logName","RemoteStreamHandler");let vs=is;var ys={exports:{}};(function(a,r){(function(e,t){var i="function",s="undefined",n="object",c="string",o="major",l="model",d="name",u="type",p="vendor",h="version",f="architecture",g="console",b="mobile",S="tablet",v="smarttv",R="wearable",_="embedded",y="Amazon",w="Apple",A="ASUS",E="BlackBerry",C="Browser",P="Chrome",M="Firefox",x="Google",K="Huawei",Q="LG",G="Microsoft",W="Motorola",Z="Opera",te="Samsung",Se="Sharp",L="Sony",O="Xiaomi",N="Zebra",V="Facebook",he="Chromium OS",xe="Mac OS",q=" Browser",Re=function(le){for(var ne={},ie=0;ie<le.length;ie++)ne[le[ie].toUpperCase()]=le[ie];return ne},Ve=function(le,ne){return typeof le===c&&Ee(ne).indexOf(Ee(le))!==-1},Ee=function(le){return le.toLowerCase()},Ne=function(le,ne){if(typeof le===c)return le=le.replace(/^\s\s*/,""),typeof ne===s?le:le.substring(0,500)},ve=function(le,ne){for(var ie,Ae,Fe,me,qe,Y,Ue=0;Ue<ne.length&&!qe;){var pt=ne[Ue],Be=ne[Ue+1];for(ie=Ae=0;ie<pt.length&&!qe&&pt[ie];)if(qe=pt[ie++].exec(le))for(Fe=0;Fe<Be.length;Fe++)Y=qe[++Ae],typeof(me=Be[Fe])===n&&me.length>0?me.length===2?typeof me[1]==i?this[me[0]]=me[1].call(this,Y):this[me[0]]=me[1]:me.length===3?typeof me[1]!==i||me[1].exec&&me[1].test?this[me[0]]=Y?Y.replace(me[1],me[2]):t:this[me[0]]=Y?me[1].call(this,Y,me[2]):t:me.length===4&&(this[me[0]]=Y?me[3].call(this,Y.replace(me[1],me[2])):t):this[me]=Y||t;Ue+=2}},we=function(le,ne){for(var ie in ne)if(typeof ne[ie]===n&&ne[ie].length>0){for(var Ae=0;Ae<ne[ie].length;Ae++)if(Ve(ne[ie][Ae],le))return ie==="?"?t:ie}else if(Ve(ne[ie],le))return ie==="?"?t:ie;return ne.hasOwnProperty("*")?ne["*"]:le},pe={ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2e3:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2",8.1:"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"},Oe={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[h,[d,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[h,[d,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[d,h],[/opios[\/ ]+([\w\.]+)/i],[h,[d,Z+" Mini"]],[/\bop(?:rg)?x\/([\w\.]+)/i],[h,[d,Z+" GX"]],[/\bopr\/([\w\.]+)/i],[h,[d,Z]],[/\bb[ai]*d(?:uhd|[ub]*[aekoprswx]{5,6})[\/ ]?([\w\.]+)/i],[h,[d,"Baidu"]],[/\b(?:mxbrowser|mxios|myie2)\/?([-\w\.]*)\b/i],[h,[d,"Maxthon"]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer|sleipnir)[\/ ]?([\w\.]*)/i,/(avant|iemobile|slim(?:browser|boat|jet))[\/ ]?([\d\.]*)/i,/(?:ms|\()(ie) ([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|duckduckgo|klar|helio|(?=comodo_)?dragon)\/([-\w\.]+)/i,/(heytap|ovi|115)browser\/([\d\.]+)/i,/(weibo)__([\d\.]+)/i],[d,h],[/quark(?:pc)?\/([-\w\.]+)/i],[h,[d,"Quark"]],[/\bddg\/([\w\.]+)/i],[h,[d,"DuckDuckGo"]],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[h,[d,"UC"+C]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i,/micromessenger\/([\w\.]+)/i],[h,[d,"WeChat"]],[/konqueror\/([\w\.]+)/i],[h,[d,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[h,[d,"IE"]],[/ya(?:search)?browser\/([\w\.]+)/i],[h,[d,"Yandex"]],[/slbrowser\/([\w\.]+)/i],[h,[d,"Smart Lenovo "+C]],[/(avast|avg)\/([\w\.]+)/i],[[d,/(.+)/,"$1 Secure "+C],h],[/\bfocus\/([\w\.]+)/i],[h,[d,M+" Focus"]],[/\bopt\/([\w\.]+)/i],[h,[d,Z+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[h,[d,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[h,[d,"Dolphin"]],[/coast\/([\w\.]+)/i],[h,[d,Z+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[h,[d,"MIUI"+q]],[/fxios\/([\w\.-]+)/i],[h,[d,M]],[/\bqihoobrowser\/?([\w\.]*)/i],[h,[d,"360"]],[/\b(qq)\/([\w\.]+)/i],[[d,/(.+)/,"$1Browser"],h],[/(oculus|sailfish|huawei|vivo|pico)browser\/([\w\.]+)/i],[[d,/(.+)/,"$1"+q],h],[/samsungbrowser\/([\w\.]+)/i],[h,[d,te+" Internet"]],[/metasr[\/ ]?([\d\.]+)/i],[h,[d,"Sogou Explorer"]],[/(sogou)mo\w+\/([\d\.]+)/i],[[d,"Sogou Mobile"],h],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|2345(?=browser|chrome|explorer))\w*[\/ ]?v?([\w\.]+)/i],[d,h],[/(lbbrowser|rekonq)/i,/\[(linkedin)app\]/i],[d],[/ome\/([\w\.]+) \w* ?(iron) saf/i,/ome\/([\w\.]+).+qihu (360)[es]e/i],[h,d],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[d,V],h],[/(Klarna)\/([\w\.]+)/i,/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(alipay)client\/([\w\.]+)/i,/(twitter)(?:and| f.+e\/([\w\.]+))/i,/(chromium|instagram|snapchat)[\/ ]([-\w\.]+)/i],[d,h],[/\bgsa\/([\w\.]+) .*safari\//i],[h,[d,"GSA"]],[/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i],[h,[d,"TikTok"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[h,[d,P+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[d,P+" WebView"],h],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[h,[d,"Android "+C]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[d,h],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[h,[d,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[h,d],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[d,[h,we,{"1.0":"/8",1.2:"/1",1.3:"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"}]],[/(webkit|khtml)\/([\w\.]+)/i],[d,h],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[d,"Netscape"],h],[/(wolvic|librewolf)\/([\w\.]+)/i],[d,h],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[h,[d,M+" Reality"]],[/ekiohf.+(flow)\/([\w\.]+)/i,/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror)[\/ ]?([\w\.\+]+)/i,/(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,/(firefox)\/([\w\.]+)/i,/(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i,/(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|obigo|mosaic|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,/(links) \(([\w\.]+)/i],[d,[h,/_/g,"."]],[/(cobalt)\/([\w\.]+)/i],[d,[h,/master.|lts./,""]]],cpu:[[/(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i],[[f,"amd64"]],[/(ia32(?=;))/i],[[f,Ee]],[/((?:i[346]|x)86)[;\)]/i],[[f,"ia32"]],[/\b(aarch64|arm(v?8e?l?|_?64))\b/i],[[f,"arm64"]],[/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],[[f,"armhf"]],[/windows (ce|mobile); ppc;/i],[[f,"arm"]],[/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i],[[f,/ower/,"",Ee]],[/(sun4\w)[;\)]/i],[[f,"sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i],[[f,Ee]]],device:[[/\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i],[l,[p,te],[u,S]],[/\b((?:s[cgp]h|gt|sm)-(?![lr])\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]((?!sm-[lr])[-\w]+)/i,/sec-(sgh\w+)/i],[l,[p,te],[u,b]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[l,[p,w],[u,b]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[l,[p,w],[u,S]],[/(macintosh);/i],[l,[p,w]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[l,[p,Se],[u,b]],[/(?:honor)([-\w ]+)[;\)]/i],[l,[p,"Honor"],[u,b]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[l,[p,K],[u,S]],[/(?:huawei)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[l,[p,K],[u,b]],[/\b(poco[\w ]+|m2\d{3}j\d\d[a-z]{2})(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/oid[^\)]+; (m?[12][0-389][01]\w{3,6}[c-y])( bui|; wv|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite|pro)?)(?: bui|\))/i],[[l,/_/g," "],[p,O],[u,b]],[/oid[^\)]+; (2\d{4}(283|rpbf)[cgl])( bui|\))/i,/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[l,/_/g," "],[p,O],[u,S]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[l,[p,"OPPO"],[u,b]],[/\b(opd2\d{3}a?) bui/i],[l,[p,"OPPO"],[u,S]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[l,[p,"Vivo"],[u,b]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i],[l,[p,"Realme"],[u,b]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,/\bmot(?:orola)?[- ](\w*)/i,/((?:moto[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i],[l,[p,W],[u,b]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[l,[p,W],[u,S]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[l,[p,Q],[u,S]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[l,[p,Q],[u,b]],[/(ideatab[-\w ]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[l,[p,"Lenovo"],[u,S]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[l,/_/g," "],[p,"Nokia"],[u,b]],[/(pixel c)\b/i],[l,[p,x],[u,S]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[l,[p,x],[u,b]],[/droid.+; (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-a\w[4-7][12])(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i],[l,[p,L],[u,b]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[l,"Xperia Tablet"],[p,L],[u,S]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[l,[p,"OnePlus"],[u,b]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo(?!bc)\w\w)( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[l,[p,y],[u,S]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[l,/(.+)/g,"Fire Phone $1"],[p,y],[u,b]],[/(playbook);[-\w\),; ]+(rim)/i],[l,p,[u,S]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[l,[p,E],[u,b]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[l,[p,A],[u,S]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[l,[p,A],[u,b]],[/(nexus 9)/i],[l,[p,"HTC"],[u,S]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[p,[l,/_/g," "],[u,b]],[/droid [\w\.]+; ((?:8[14]9[16]|9(?:0(?:48|60|8[01])|1(?:3[27]|66)|2(?:6[69]|9[56])|466))[gqswx])\w*(\)| bui)/i],[l,[p,"TCL"],[u,S]],[/(itel) ((\w+))/i],[[p,Ee],l,[u,we,{tablet:["p10001l","w7001"],"*":"mobile"}]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[l,[p,"Acer"],[u,S]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[l,[p,"Meizu"],[u,b]],[/; ((?:power )?armor(?:[\w ]{0,8}))(?: bui|\))/i],[l,[p,"Ulefone"],[u,b]],[/; (energy ?\w+)(?: bui|\))/i,/; energizer ([\w ]+)(?: bui|\))/i],[l,[p,"Energizer"],[u,b]],[/; cat (b35);/i,/; (b15q?|s22 flip|s48c|s62 pro)(?: bui|\))/i],[l,[p,"Cat"],[u,b]],[/((?:new )?andromax[\w- ]+)(?: bui|\))/i],[l,[p,"Smartfren"],[u,b]],[/droid.+; (a(?:015|06[35]|142p?))/i],[l,[p,"Nothing"],[u,b]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron|infinix|tecno|micromax|advan)[-_ ]?([-\w]*)/i,/; (imo) ((?!tab)[\w ]+?)(?: bui|\))/i,/(hp) ([\w ]+\w)/i,/(asus)-?(\w+)/i,/(microsoft); (lumia[\w ]+)/i,/(lenovo)[-_ ]?([-\w]+)/i,/(jolla)/i,/(oppo) ?([\w ]+) bui/i],[p,l,[u,b]],[/(imo) (tab \w+)/i,/(kobo)\s(ereader|touch)/i,/(archos) (gamepad2?)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i,/(nook)[\w ]+build\/(\w+)/i,/(dell) (strea[kpr\d ]*[\dko])/i,/(le[- ]+pan)[- ]+(\w{1,9}) bui/i,/(trinity)[- ]*(t\d{3}) bui/i,/(gigaset)[- ]+(q\w{1,9}) bui/i,/(vodafone) ([\w ]+)(?:\)| bui)/i],[p,l,[u,S]],[/(surface duo)/i],[l,[p,G],[u,S]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[l,[p,"Fairphone"],[u,b]],[/(u304aa)/i],[l,[p,"AT&T"],[u,b]],[/\bsie-(\w*)/i],[l,[p,"Siemens"],[u,b]],[/\b(rct\w+) b/i],[l,[p,"RCA"],[u,S]],[/\b(venue[\d ]{2,7}) b/i],[l,[p,"Dell"],[u,S]],[/\b(q(?:mv|ta)\w+) b/i],[l,[p,"Verizon"],[u,S]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[l,[p,"Barnes & Noble"],[u,S]],[/\b(tm\d{3}\w+) b/i],[l,[p,"NuVision"],[u,S]],[/\b(k88) b/i],[l,[p,"ZTE"],[u,S]],[/\b(nx\d{3}j) b/i],[l,[p,"ZTE"],[u,b]],[/\b(gen\d{3}) b.+49h/i],[l,[p,"Swiss"],[u,b]],[/\b(zur\d{3}) b/i],[l,[p,"Swiss"],[u,S]],[/\b((zeki)?tb.*\b) b/i],[l,[p,"Zeki"],[u,S]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[p,"Dragon Touch"],l,[u,S]],[/\b(ns-?\w{0,9}) b/i],[l,[p,"Insignia"],[u,S]],[/\b((nxa|next)-?\w{0,9}) b/i],[l,[p,"NextBook"],[u,S]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[p,"Voice"],l,[u,b]],[/\b(lvtel\-)?(v1[12]) b/i],[[p,"LvTel"],l,[u,b]],[/\b(ph-1) /i],[l,[p,"Essential"],[u,b]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[l,[p,"Envizen"],[u,S]],[/\b(trio[-\w\. ]+) b/i],[l,[p,"MachSpeed"],[u,S]],[/\btu_(1491) b/i],[l,[p,"Rotor"],[u,S]],[/(shield[\w ]+) b/i],[l,[p,"Nvidia"],[u,S]],[/(sprint) (\w+)/i],[p,l,[u,b]],[/(kin\.[onetw]{3})/i],[[l,/\./g," "],[p,G],[u,b]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[l,[p,N],[u,S]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[l,[p,N],[u,b]],[/smart-tv.+(samsung)/i],[p,[u,v]],[/hbbtv.+maple;(\d+)/i],[[l,/^/,"SmartTV"],[p,te],[u,v]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[p,Q],[u,v]],[/(apple) ?tv/i],[p,[l,w+" TV"],[u,v]],[/crkey/i],[[l,P+"cast"],[p,x],[u,v]],[/droid.+aft(\w+)( bui|\))/i],[l,[p,y],[u,v]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[l,[p,Se],[u,v]],[/(bravia[\w ]+)( bui|\))/i],[l,[p,L],[u,v]],[/(mitv-\w{5}) bui/i],[l,[p,O],[u,v]],[/Hbbtv.*(technisat) (.*);/i],[p,l,[u,v]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[p,Ne],[l,Ne],[u,v]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[u,v]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[p,l,[u,g]],[/droid.+; (shield) bui/i],[l,[p,"Nvidia"],[u,g]],[/(playstation [345portablevi]+)/i],[l,[p,L],[u,g]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[l,[p,G],[u,g]],[/\b(sm-[lr]\d\d[05][fnuw]?s?)\b/i],[l,[p,te],[u,R]],[/((pebble))app/i],[p,l,[u,R]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[l,[p,w],[u,R]],[/droid.+; (glass) \d/i],[l,[p,x],[u,R]],[/droid.+; (wt63?0{2,3})\)/i],[l,[p,N],[u,R]],[/droid.+; (glass) \d/i],[l,[p,x],[u,R]],[/(pico) (4|neo3(?: link|pro)?)/i],[p,l,[u,R]],[/; (quest( \d| pro)?)/i],[l,[p,V],[u,R]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[p,[u,_]],[/(aeobc)\b/i],[l,[p,y],[u,_]],[/droid .+?; ([^;]+?)(?: bui|; wv\)|\) applew).+? mobile safari/i],[l,[u,b]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[l,[u,S]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[u,S]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[u,b]],[/(android[-\w\. ]{0,9});.+buil/i],[l,[p,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[h,[d,"EdgeHTML"]],[/(arkweb)\/([\w\.]+)/i],[d,h],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[h,[d,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna|servo)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i,/\b(libweb)/i],[d,h],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[h,d]],os:[[/microsoft (windows) (vista|xp)/i],[d,h],[/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i],[d,[h,we,pe]],[/windows nt 6\.2; (arm)/i,/windows[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i,/(?:win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[h,we,pe],[d,"Windows"]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/(?:ios;fbsv\/|iphone.+ios[\/ ])([\d\.]+)/i,/cfnetwork\/.+darwin/i],[[h,/_/g,"."],[d,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[d,xe],[h,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[h,d],[/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish|openharmony)[-\/ ]?([\w\.]*)/i,/(blackberry)\w*\/([\w\.]*)/i,/(tizen|kaios)[\/ ]([\w\.]+)/i,/\((series40);/i],[d,h],[/\(bb(10);/i],[h,[d,E]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],[h,[d,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[h,[d,M+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[h,[d,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[h,[d,"watchOS"]],[/crkey\/([\d\.]+)/i],[h,[d,P+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[d,he],h],[/panasonic;(viera)/i,/(netrange)mmh/i,/(nettv)\/(\d+\.[\w\.]+)/i,/(nintendo|playstation) ([wids345portablevuch]+)/i,/(xbox); +xbox ([^\);]+)/i,/\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,/(mint)[\/\(\) ]?(\w*)/i,/(mageia|vectorlinux)[; ]/i,/([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,/(hurd|linux) ?([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) (\w+)/i],[d,h],[/(sunos) ?([\w\.\d]*)/i],[[d,"Solaris"],h],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux|serenityos)/i,/(unix) ?([\w\.]*)/i],[d,h]]},Te=function(le,ne){if(typeof le===n&&(ne=le,le=t),!(this instanceof Te))return new Te(le,ne).getResult();var ie=typeof e!==s&&e.navigator?e.navigator:t,Ae=le||(ie&&ie.userAgent?ie.userAgent:""),Fe=ie&&ie.userAgentData?ie.userAgentData:t,me=ne?function(Y,Ue){var pt={};for(var Be in Y)Ue[Be]&&Ue[Be].length%2==0?pt[Be]=Ue[Be].concat(Y[Be]):pt[Be]=Y[Be];return pt}(Oe,ne):Oe,qe=ie&&ie.userAgent==Ae;return this.getBrowser=function(){var Y,Ue={};return Ue[d]=t,Ue[h]=t,ve.call(Ue,Ae,me.browser),Ue[o]=typeof(Y=Ue[h])===c?Y.replace(/[^\d\.]/g,"").split(".")[0]:t,qe&&ie&&ie.brave&&typeof ie.brave.isBrave==i&&(Ue[d]="Brave"),Ue},this.getCPU=function(){var Y={};return Y[f]=t,ve.call(Y,Ae,me.cpu),Y},this.getDevice=function(){var Y={};return Y[p]=t,Y[l]=t,Y[u]=t,ve.call(Y,Ae,me.device),qe&&!Y[u]&&Fe&&Fe.mobile&&(Y[u]=b),qe&&Y[l]=="Macintosh"&&ie&&typeof ie.standalone!==s&&ie.maxTouchPoints&&ie.maxTouchPoints>2&&(Y[l]="iPad",Y[u]=S),Y},this.getEngine=function(){var Y={};return Y[d]=t,Y[h]=t,ve.call(Y,Ae,me.engine),Y},this.getOS=function(){var Y={};return Y[d]=t,Y[h]=t,ve.call(Y,Ae,me.os),qe&&!Y[d]&&Fe&&Fe.platform&&Fe.platform!="Unknown"&&(Y[d]=Fe.platform.replace(/chrome os/i,he).replace(/macos/i,xe)),Y},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return Ae},this.setUA=function(Y){return Ae=typeof Y===c&&Y.length>500?Ne(Y,500):Y,this},this.setUA(Ae),this};Te.VERSION="1.0.40",Te.BROWSER=Re([d,h,o]),Te.CPU=Re([f]),Te.DEVICE=Re([l,p,u,g,b,v,S,R,_]),Te.ENGINE=Te.OS=Re([d,h]),a.exports&&(r=a.exports=Te),r.UAParser=Te;var Ye=typeof e!==s&&(e.jQuery||e.Zepto);if(Ye&&!Ye.ua){var ht=new Te;Ye.ua=ht.getResult(),Ye.ua.get=function(){return ht.getUA()},Ye.ua.set=function(le){ht.setUA(le);var ne=ht.getResult();for(var ie in ne)Ye.ua[ie]=ne[ie]}}})(typeof window=="object"?window:Fi)})(ys,ys.exports);var oc=ys.exports,$e=(a=>(a.KEEPALIVE="keepalive",a.JOINCHANNEL="joinchannel",a.NOTIFYJOIN="notifyjoin",a.NOTIFYSTATUS="notifystatus",a.STATUSREPORT="statusreport",a.LEAVECHANNEL="leavechannel",a.NOTIFYLEAVE="notifyleave",a.NOTIFYPUBLISH="notifypublish",a.BYE="bye",a.RECONNECT="reconnect",a.PUBLISH="publish",a.REFRESHURL="refreshurl",a.UNSUBSCRIBE="unsubscribe",a.ROLEUPDATE="roleupdate",a))($e||{});class Ki{constructor(r,e){m(this,"authInfo");m(this,"userName");m(this,"seqIndex",0);this.authInfo=r,this.userName=typeof e=="number"?e.toString():e}get roleAuth(){if(this.authInfo.role){const{timestamp:r,nonce:e,token:t,role:i}=this.authInfo;return{timestamp:r,nonce:e,token:t,tokenrole:i}}}static get adaptInfo(){var e,t,i,s;let r=new oc.UAParser().getResult();return{os_name:((e=r.os.name)==null?void 0:e.replace(" ",""))+"_"+((t=r.browser.name)==null?void 0:t.replace(" ","")),device_name:((i=r.device.model)==null?void 0:i.replace(" ",""))||"",brand_name:((s=r.device.vendor)==null?void 0:s.replace(" ",""))||"",device_key:window.navigator.userAgent,os_version:r.browser.version||"",sdk_version:"7.2.10",version:"v1"}}refreshAuthInfo(r){this.authInfo=r}getSeqIndex(){return this.seqIndex}createKeepAlivePackage(){return this.createBaseSendPackage("keepalive")}createJoinPackage(r){let e=this.createBaseSendPackage("joinchannel");return e.header.displayName=this.userName,e.header.clientversion=Le.getVersionNumber().toString(),e.header.platform="web",this.roleAuth&&(e.data.auth=this.roleAuth),e.data.adapt=Ki.adaptInfo,r&&(e.data=X(X({},e.data),r)),e}createLeavePackage(){return this.createBaseSendPackage("leavechannel")}createStatusPackage(r){let e=this.createBaseSendPackage("statusreport");return e.header.displayName=this.userName,e.data.status=r,e}createPublishPackage(){let r=this.createBaseSendPackage("publish");return r.data.users=[{}],this.roleAuth&&(r.data.auth=this.roleAuth),r}createRoleUpdatePackage(){let r=this.createBaseSendPackage("roleupdate");return r.header.displayName=this.userName,r}createReconnectPackage(r){let e=this.createBaseSendPackage("reconnect");return e.header.displayName=this.userName,e.header.clientversion=Le.getVersionNumber().toString(),e.header.platform="web",e.data=X(X({},e.data),r!=null?r:{}),this.roleAuth&&(e.data.auth=this.roleAuth),e}createRefreshUrlPackage(){let r=this.createBaseSendPackage("refreshurl");return r.header.displayName=this.userName,r}createResponsePackage(r,e){return{version:1,code:200,tid:r,msgtype:e}}createBaseSendPackage(r){var e;return++this.seqIndex,{version:1,msgtype:r,tid:mt(),header:{appid:this.authInfo.appId,channelid:this.authInfo.channelId,sessionid:(e=this.authInfo.sessionId)!=null?e:"",userid:this.authInfo.userId},data:{seq:this.seqIndex}}}}const Ua="ALI_RTC_SDK_ALLOCATE_RESULT",yi=class yi{constructor(r,e,t){m(this,"result",null);m(this,"pms",null);m(this,"env");m(this,"config");m(this,"joinMode");this.env=r,this.config=e,this.joinMode=t;let i=localStorage.getItem(Ua);if(i){const s=JSON.parse(i);s.appId===e.appId&&s.expireTs-3e5>Date.now()?this.result=s.allocatedData:T.info(`[${yi.logName}]`,"allocate","cached data is invalid")}}fetchAndUpdate(){if(this.pms)return this.pms;const{appId:r,channelId:e,sessionId:t,userId:i,timestamp:s,token:n,nonce:c}=this.config,o=new URLSearchParams({appid:r,channelid:e,session:t,userid:i,timestamp:`${s}`,token:n,nonce:c!=null?c:"",adapt:"true",clitype:"2"});this.joinMode&&o.set("joinmode",this.joinMode);const l=this.env===It.pre?Rt.pre:Rt.prod;return this.pms=fetch(`https://${l}/gslb/v1/allocate?${o.toString()}`,{method:"POST",body:JSON.stringify(Ki.adaptInfo)}).then(d=>d.json()).then(d=>{if(d.code===0){const u=d.data;this.result=u;const{ice_ufrag:p}=u.h5auth,[h,f]=atob(p).split("_"),g={appId:r,expireTs:1e3*parseInt(f),allocatedData:u};return T.info(`[${yi.logName}]`,"got allocate result and save",u.h5auth.ice_ufrag),localStorage.setItem(Ua,JSON.stringify(g)),u}return null}).catch(d=>(T.error(`[${yi.logName}]`,"allocate",d),null)),this.pms}};m(yi,"logName","Allocator");let Ii=yi;class Rs{constructor(r,e){m(this,"originTrack");m(this,"originVideo");m(this,"targetWidth");m(this,"targetHeight");m(this,"targetFrameRate");m(this,"targetCanvas");m(this,"animationFrameId");m(this,"resultTrack");this.targetWidth=e.width,this.targetHeight=e.height,this.targetFrameRate=e.frameRate,this.originTrack=r,this.originVideo=document.createElement("video"),this.originVideo.muted=!0,this.originVideo.autoplay=!0,this.originVideo.controls=!1,this.targetCanvas=document.createElement("canvas"),this.targetCanvas.width=this.targetWidth,this.targetCanvas.height=this.targetHeight}updateOptions(r){this.targetWidth=r.width,this.targetHeight=r.height,this.targetFrameRate=r.frameRate,this.targetCanvas.width=this.targetWidth,this.targetCanvas.height=this.targetHeight,this.resultTrack&&this.resultTrack.applyConstraints({frameRate:this.targetFrameRate})}dispose(){}getVideoTrack(){return this.resultTrack||(this.resultTrack=this.targetCanvas.captureStream().getVideoTracks()[0],this.resultTrack.applyConstraints({frameRate:this.targetFrameRate})),this.resultTrack}cancelAnimation(){this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=void 0)}getPositionAndSize(r,e,t,i){const s=e/r,n=i/t;let c=t,o=i,l=0,d=0;return n>s?(c=Math.round(o/s),l=Math.round((t-c)/2)):n<s&&(o=Math.round(c*s),d=Math.round((i-o)/2)),{x:l,y:d,width:c,height:o}}}class cc extends Rs{constructor(e,t){super(e,t);m(this,"targetCtx");this.targetCtx=this.targetCanvas.getContext("2d"),this.startRender=this.startRender.bind(this),this.stopRender=this.startRender.bind(this),this.initStream(e)}initStream(e){const t=new MediaStream;t.addTrack(e),this.originVideo.srcObject=t,this.originVideo.play(),this.originVideo.addEventListener("canplay",this.startRender),this.originVideo.addEventListener("pause",this.stopRender),this.originVideo.addEventListener("ended",this.stopRender)}startRender(){this.cancelAnimation();const e=()=>{if(!this.targetCtx)return;const t=this.getPositionAndSize(this.originVideo.videoWidth,this.originVideo.videoHeight,this.targetWidth,this.targetHeight);this.targetCtx.drawImage(this.originVideo,0,0,this.originVideo.videoWidth,this.originVideo.videoHeight,t.x,t.y,t.width,t.height),this.originVideo.paused||this.originVideo.ended||(this.animationFrameId=requestAnimationFrame(e))};e()}stopRender(){this.cancelAnimation()}dispose(){this.stopRender(),this.originVideo.removeEventListener("play",this.startRender),this.originVideo.removeEventListener("pause",this.stopRender),this.originVideo.removeEventListener("ended",this.stopRender),this.originVideo.pause(),this.originVideo.srcObject=null}}function Ba(a,r,e){const t=a.createShader(r);if(t)return a.shaderSource(t,e),a.compileShader(t),a.getShaderParameter(t,a.COMPILE_STATUS)?t:(console.error(`An error occurred compiling the shaders: ${a.getShaderInfoLog(t)}`),a.deleteShader(t),null);console.error("create shader failed")}class Ha extends Rs{constructor(e,t){super(e,t);m(this,"targetCtx");m(this,"targetTexture");m(this,"locationMap");this.targetCtx=this.targetCanvas.getContext("webgl2"),this.locationMap={},this.startRender=this.startRender.bind(this),this.stopRender=this.startRender.bind(this),this.updateBuffer=this.updateBuffer.bind(this),this.initGL(),this.initStream(e)}static isSupport(){return function(){let e;try{const t=document.createElement("canvas");t.width=1,t.height=1;const i={alpha:!1,depth:!1,stencil:!1,antialias:!1,preferLowPowerToHighPerformance:!0};e=t.getContext("webgl2",i)}catch(t){return!1}return!!e}()}initGL(){const e=this.targetCtx;if(!e)return;this.targetTexture=function(o){const l=o.createTexture();return o.bindTexture(o.TEXTURE_2D,l),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.LINEAR),l}(e);const t=function(o,l,d){const u=Ba(o,o.VERTEX_SHADER,l),p=Ba(o,o.FRAGMENT_SHADER,d),h=o.createProgram();if(h&&u&&p)return o.attachShader(h,u),o.attachShader(h,p),o.linkProgram(h),o.getProgramParameter(h,o.LINK_STATUS)?h:(console.error(`Unable to initialize the shader program: ${o.getProgramInfoLog(h)}`),null)}(e,`
13
13
  attribute vec2 a_position;
14
14
  attribute vec2 a_texCoord;
15
15
 
@@ -129,9 +129,9 @@ onmessage = function(evt) {
129
129
  `+f)}},Ds.exports}(),i=a.win,s=i.document,n=/^(error|api|speed|sum|avg|percent|custom|msg|setPage|setConfig|behavior|performance)$/,c=function(o){var l=this;return r.call(l,o),l._initialPage=o.page&&a.safetyCall(o.page,[],o.page+"")||null,l._isRobot=a.isRobot(),l._health={errcount:0,apisucc:0,apifail:0},l.beforeSend=function(d,u){d==="error"?l._health.errcount++:d==="api"&&l._health[u.success?"apisucc":"apifail"]++},o.enableInstanceAutoSend!==!1&&(l.initHandler(),l.initHook(),l.initFmpObserver(1e4),l._conf&&l._conf.behavior&&typeof l.initBehavior=="function"&&l.initBehavior(),l._conf&&l._conf.enableResource&&typeof l.initResource=="function"&&l.initResource()),Object.defineProperty&&i.addEventListener&&Object.defineProperty(l,"pipe",{set:l.sendPipe}),l};return c.prototype=a.createObject(r.prototype),a.ext(r._root.dftCon,{uid:null,setUsername:null,ignoreUrlPath:null,ignoreApiPath:null,urlHelper:[{rule:/\/([a-z\-_]+)?\d{2,20}/g,target:"/$1**"},/\/$/],resourceHelper:[],apiHelper:{rule:/\/([a-z\-_]+)?\d{2,20}/g,target:"/$1**"},ignoreUrlCase:!0,imgUrl:"https://arms-retcode.aliyuncs.com/r.png?",cdnHostList:[],resourceTypes:["css","script","img","font"],resourceSlow:2e3,disableHook:!1,autoSendPv:!0,autoSendPerf:!0,enableSPA:!1,enableLinkTrace:!1,linkType:"arms",enableApiCors:!1,sendResource:!0,behavior:!0,enableConsole:!1,parseHash:function(o){return(o?a.cutUrlSearch(o.replace(/^#\/?/,"")):"")||"[index]"},parseResponse:function(o){if(!o||typeof o!="object")return{};var l=o.code,d=o.msg||o.message||o.subMsg||o.errorMsg||o.ret||o.errorResponse||"";return typeof d=="object"&&(l=l||d.code,d=d.msg||d.message||d.info||d.ret||JSON.stringify(d)),{msg:d,code:l,success:!0}}}),a.ext(c.prototype,{constructor:c,_super:r,onReady:function(o){var l=this;if(l.hasReady)return o();s.readyState==="complete"?(l.hasReady=!0,o()):a.on(i,"load",function(){l.hasReady=!0,o()},!0)},getPage:function(o){var l=this._conf,d=l.page,u=location,p=u.host+u.pathname;return d&&!o?a.safetyCall(d,[],d+""):this._initialPage||a.filterByRule(l.ignoreUrlCase?p.toLowerCase():p,u.href,l.ignoreUrlPath?l.ignoreUrlPath:l.urlHelper)},setPage:function(o,l){var d=this,u=d.prevPage;if(l!==!1){if(!o||o===u)return d;d.prevPage=o,clearTimeout(d.sendPVTimmer),d.handleUnload(1),d.resetPageview(),d.sendPVTimmer=setTimeout(function(){d.sendPV()},10)}else d.prevPage=o;return d._conf.page=o,d},setConfig:function(o,l){if(o&&typeof o=="object"){a.verifyConfig(o),o=this.setImgUrl(o);var d=this._conf;if(this._conf=a.ext({},d,o),!l){var u="disableHook";u in o&&d[u]!==o[u]&&(o[u]?this.removeHook():this.addHook()),(u="enableSPA")in o&&d[u]!==o[u]&&this.bindHashChange(o[u])}}},sendRequest:function(o){e(o,this.getConfig("imgUrl"))},postData:function(o,l){var d={};d[l]=o[l],delete o[l];var u="";typeof o=="object"&&(u=a.serialize(o)),t(d,this.getConfig("imgUrl")+u+"&post_res=")},sendPipe:function(o){var l=this;if(!o||!o.length)return l;try{if(a.T(o[0])==="Array")return a.each(o,function(u){return l.sendPipe(u)});if(a.T(o)!=="Array")return l;var d=o.shift();if(!n.test(d))return l;l[d].apply(l,o)}catch(u){return a.warn("[retcode] error in sendPipe",u),l}},sendHealth:function(){var o=a.ext({},this._health);o.healthy=o.errcount>0?0:1,o.begin=Date.now();var l=o.begin-this.sBegin;o.stay=l,this._lg("health",o,1),this._health={errcount:0,apisucc:0,apifail:0}},createInstance:function(o){o=a.ext({pid:this._conf.pid},o);var l=this.__proto__.constructor(o);return o.page&&l.sendPV(),l}}),gc()(c,i),fc()(c,i,s),bc()(c,i,s),(nn||(nn=1,an=function(o,l){var d=it(),u=null,p=d.getCurDomain(),h=function(v,R,_,y,w,A,E,C,P,M,x,K,Q){var G=d.J(w)||null,W=d.safetyCall(R,[G,y],null);if(!W)return!1;var Z=W.code||A,te=!("success"in W)||W.success;v.api(_,te,E,Z,W.msg,C,P,M,te?{}:x,p,K,Q)},f="fetch",g="__oFetch_",b="__oXMLHttpRequest_",S="XMLHttpRequest";return d.ext(o.prototype,{removeHook:function(v,R){return u&&(R||this===u)?(l[g]&&(l[f]=l[g],delete l[g]),l[b]&&(l[S]=l[b],delete l[b]),u=null,this):this},addHook:function(v){return!v&&u||(u||(function(){if(typeof l[f]=="function"){var R=l[f];l[g]=R,l[f]=function(_,y){var w=arguments.length===1?[arguments[0]]:Array.apply(null,arguments),A=u;if(!A||!A.api||y&&(y.method==="HEAD"||y.mode==="no-cors"))return R.apply(l,w);y||(y={});var E=Date.now(),C=A._conf,P=d.duration(),M=(_&&typeof _!="string"?_.url:_)||"",x=M;M=d.cutUrlSearch(M);var K=(C.ignore||{}).ignoreApis,Q=C.parseTraceId;if(!d.checkAPI(M,!0)||d.ignoreByRule(M,K))return R.apply(l,w);M=d.filterByRule(M,x,C.ignoreApiPath?C.ignoreApiPath:C.apiHelper);var G=C.enableLinkTrace,W="",Z="",te=A.getConfig("pid"),Se=null,L=A.getConfig("sample"),O=A.getConfig("linkType"),N=1;if(L&&!A.sampling(L)&&(N=0),G){var V="";try{V=location.origin?location.origin:location.protocol+"//"+location.hostname+(location.port?":"+location.port:"")}catch(pe){V=""}var he=d.checkSameOrigin(x,V);if(A.getConfig("enableApiCors")||he)if(_&&typeof _!="string")try{if(w[0].headers&&typeof w[0].headers.get=="function"&&typeof w[0].headers.append=="function")switch(O){case"arms":var xe=w[0].headers.get("EagleEye-TraceID"),q=w[0].headers.get("EagleEye-SessionID"),Re=w[0].headers.get("EagleEye-pAppName");xe?W=xe:(W=A.getTraceId()["EagleEye-TraceID"],w[0].headers.append("EagleEye-TraceID",W)),q?Z=q:(Z=A.getPageviewId()["EagleEye-SessionID"],w[0].headers.append("EagleEye-SessionID",Z)),Re||w[0].headers.append("EagleEye-pAppName",te);break;case"b3":var Ve=w[0].headers.get("X-B3-TraceId");if(Ve)W=Ve;else{var Ee=A.getB3TraceId(N);w[0].headers.append("X-B3-TraceId",Ee["X-B3-TraceId"]),w[0].headers.append("X-B3-ParentSpanId",Ee["X-B3-ParentSpanId"]),w[0].headers.append("X-B3-SpanId",Ee["X-B3-SpanId"]),w[0].headers.append("X-B3-Sampled",Ee["X-B3-Sampled"]),w[0].headers.append("X-Request-ID",d.guid()),W=Ee["X-B3-TraceId"]}Z=A.pageview;break;default:var Ne=w[0].headers.get("uber-trace-id");Ne?W=Ne.split(":")[0]:(Ne=A.getUberTraceId(N),w[0].headers.append("uber-trace-id",Ne["uber-trace-id"]),W=Ne.traceId),Z=A.pageview}}catch(pe){d.warn(`[retcode] fetch failed to set header, exception is :
130
130
  `+pe)}else switch(y.headers=y.headers?y.headers:{},O){case"arms":y.headers["EagleEye-TraceID"]?W=y.headers["EagleEye-TraceID"]:(W=A.getTraceId()["EagleEye-TraceID"],y.headers["EagleEye-TraceID"]=W),y.headers["EagleEye-SessionID"]?Z=y.headers["EagleEye-SessionID"]:(Z=A.getPageviewId()["EagleEye-SessionID"],y.headers["EagleEye-SessionID"]=Z),y.headers["EagleEye-pAppName"]||(y.headers["EagleEye-pAppName"]=te);break;case"b3":if(y.headers["X-B3-TraceId"])W=y.headers["X-B3-TraceId"];else{var ve=A.getB3TraceId(N);y.headers["X-B3-TraceId"]=ve["X-B3-TraceId"],y.headers["X-B3-ParentSpanId"]=ve["X-B3-ParentSpanId"],y.headers["X-B3-SpanId"]=ve["X-B3-SpanId"],y.headers["X-B3-Sampled"]=ve["X-B3-Sampled"],y.headers["X-Request-ID"]=d.guid(),W=ve["X-B3-TraceId"]}Z=A.getPageviewId()["EagleEye-SessionID"];break;default:if(y.headers["uber-trace-id"])W=y.headers["uber-trace-id"].split(":")[0];else{var we=A.getUberTraceId(N);y.headers["uber-trace-id"]=we["uber-trace-id"],W=we.traceId}Z=A.getPageviewId()["EagleEye-SessionID"]}}return R.apply(l,w).then(function(pe){if(!A||!A.api)return pe;try{if(!pe||typeof pe.clone!="function")return pe;var Oe=pe.clone(),Te=Oe.headers;if(Te&&typeof Te.get=="function"){var Ye=Te.get("content-type");if(Ye&&!/(text)|(json)/.test(Ye))return pe;if(!W){var ht=d.parseFetchHeaders(Te);typeof ht=="object"&&ht["eagleeye-traceid"]&&(W=ht["eagleeye-traceid"],Se="response")}}var le=P();return Oe.text().then(function(ne){if(!W&&d.isFunction(Q)){var ie=Q(Oe,ne);ie&&d.isString(ie)&&(W=ie)}var Ae=d.getFetchSnapshot(w,ne,Te);Oe.ok?h(A,C.parseResponse,M,x,ne,Oe.status||200,le,E,W,Z,Ae,Se,N):(A.api(M,!1,le,Oe.status||404,Oe.statusText,E,W,Z,Ae,p,Se,N),C.enableResource&&u.fixResourceStatus&&u.fixResourceStatus({src:Oe.url,res_type:"api"}))}),pe}catch(ne){return d.warn("[ARMS] fetch response error :",ne),pe}}).catch(function(pe){if(!A||!A.api)throw pe;var Oe=P();throw A.api(M,!1,Oe,pe.name||"Error",pe.message,E,W,Z,{},p),C.enableResource&&u.fixResourceStatus&&u.fixResourceStatus({src:x,res_type:"api"}),pe})},l[f].toString=d.createFakeToString(f)}}(),function(){if(typeof l[S]=="function"){var R,_=l[S];l[b]=_;var y=function(w){var A=new _(w),E=u;if(!E||!E.api||!A.addEventListener)return A;var C,P,M,x,K=A.send,Q=A.open,G=A.setRequestHeader,W=E._conf,Z=(W.ignore||{}).ignoreApis,te=W.parseTraceId,Se=E.getConfig("enableLinkTrace"),L="",O="",N="",V=null,he=E.getConfig("sample"),xe=E.getConfig("linkType"),q=1;return he&&!E.sampling(he)&&(q=0),A.open=function(Re,Ve){R=Re;var Ee=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);Q.apply(A,Ee),x=Ve||"",M=d.cutUrlSearch(x);var Ne=!d.checkAPI(M,!0)||d.ignoreByRule(M,Z);if(M=M?d.filterByRule(M,x,W.ignoreApiPath?W.ignoreApiPath:W.apiHelper):"",!Ne&&Se){var ve="";try{ve=location.origin?location.origin:location.protocol+"//"+location.hostname+(location.port?":"+location.port:"")}catch(Te){ve=""}var we=d.checkSameOrigin(x,ve);if((E.getConfig("enableApiCors")||we)&&G&&typeof G=="function")switch(xe){case"arms":L=E.getTraceId()["EagleEye-TraceID"],G.apply(A,["EagleEye-TraceID",L]),O=E.getPageviewId()["EagleEye-SessionID"],G.apply(A,["EagleEye-SessionID",O]),N=E.getConfig("pid"),G.apply(A,["EagleEye-pAppName",N]);break;case"b3":var pe=E.getB3TraceId(q);G.apply(A,["X-B3-TraceId",pe["X-B3-TraceId"]]),G.apply(A,["X-B3-ParentSpanId",pe["X-B3-ParentSpanId"]]),G.apply(A,["X-B3-SpanId",pe["X-B3-SpanId"]]),G.apply(A,["X-B3-Sampled",pe["X-B3-Sampled"]]),G.apply(A,["X-Request-ID",d.guid()]),L=pe["X-B3-TraceId"],O=E.getPageviewId()["EagleEye-SessionID"];break;default:var Oe=E.getUberTraceId(q);G.apply(A,["uber-trace-id",Oe["uber-trace-id"]]),L=Oe.traceId,O=E.getPageviewId()["EagleEye-SessionID"]}}},A.send=function(){C=Date.now(),P=d.duration();var Re=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);K.apply(A,Re)},d.on(A,"readystatechange",function(){if(M&&A.readyState===4){var Re=P(),Ve=d.getXhrSnapshot(x,R,A);if(!L){var Ee=d.parseXhrHeaders(typeof A.getAllResponseHeaders=="function"&&A.getAllResponseHeaders()||"");typeof Ee=="object"&&Ee["eagleeye-traceid"]&&(L=Ee["eagleeye-traceid"],V="response")}if(!L&&d.isFunction(te)){var Ne=te(A);Ne&&d.isString(Ne)&&(L=Ne)}if(A.status>=200&&A.status<=299){var ve=A.status||200;if(typeof A.getResponseHeader=="function"){var we=A.getResponseHeader("Content-Type");if(we&&!/(text)|(json)/.test(we))return}A.responseType&&A.responseType!=="text"?E.api(M,!0,Re,ve,"",C,L,O,{},p,V,q):h(E,W.parseResponse,M,x,A.responseText,ve,Re,C,L,O,Ve,V,q)}else E.api(M,!1,Re,A.status||"FAILED",A.statusText,C,L,O,Ve,p,V,q),W.enableResource&&u.fixResourceStatus&&u.fixResourceStatus({src:A.responseURL||x,res_type:"api"})}}),A};y.prototype=_.prototype,d.each(Object.keys(_),function(w){y[w]=_[w]}),l[S]=y,l[S].toString=d.createFakeToString(S)}}()),u=this),this},initHook:function(){return this.hasInitHook||(this.getConfig("disableHook")||this.addHook(),this.hasInitHook=!0),this}}),o}),an)(c,i),(cn||(cn=1,on=function(o,l){var d=it(),u=l.history||{},p=l.document,h=function(g,b){var S;l.CustomEvent?S=new CustomEvent(g,{detail:b}):((S=p.createEvent("HTMLEvents")).initEvent(g,!1,!0),S.detail=b),l.dispatchEvent(S)},f=function(g){var b=u[g];typeof b=="function"&&(u[g]=function(S,v,R){var _=arguments.length===1?[arguments[0]]:Array.apply(null,arguments),y=location.href,w=b.apply(u,_);if(!R||typeof R!="string"||R===y)return w;try{var A=y.split("#"),E=R.split("#"),C=d.cutUrlSearch(A[0]),P=d.cutUrlSearch(E[0]),M=A[1]&&A[1].replace(/^\/?(.*)/,"$1"),x=E[1]&&E[1].replace(/^\/?(.*)/,"$1");M!==x?h("historystatechange",x):C!==P&&h("historystatechange",P)}catch(K){d.warn("[retcode] error in "+g+": "+K)}return w},u[g].toString=d.createFakeToString(g))};d.ext(o.prototype,{hackHistoryState:function(){return this.hasHackedHistoryState||(f("pushState"),f("replaceState"),this.hasHackedHistoryState=!0),this}})}),on)(c,i),function(){if(ln)return xs;ln=1;var o=it(),l=Os().TIMING_KEYS;return xs=function(d,u){function p(g,b,S){if(g instanceof u.PerformanceResourceTiming&&g.initiatorType){var v=o.getResType(g.initiatorType,g.name),R=b.resourceTypes||[],_=(b.ignore||{}).ignoreResources;if(v&&R.includes(v)&&!o.ignoreByRule(g.name,_)&&!o.ignoreByRule(o.decode(g.name),_)){var y=g[l[0]],w=g[l[1]],A=g[l[2]],E=g[l[3]],C=g[l[4]],P=g[l[5]],M=g[l[6]],x=g[l[7]],K=g[l[8]],Q=g[l[18]],G=g[l[19]];if(!S.has(g)&&(!o.areInOrder(y,w,A,E,C,P,M,x,K)||y>x))return;if(Q<y&&(Q=y),G<y&&(G=w),o.areInOrder(y,Q,G,w))return{domain:o.getURL(g.name).domain,res_type:v,src_type:o.getSrcType(g.name,b.cdnHostList),success:1,size:Math.round(g.decodedBodySize),duration:Math.round(g.duration),timeStamp:g.responseEnd,timing:g}}}}var h="_resource-"+Date.now(),f="_resource_error-"+Date.now();o.ext(d.prototype,{initResource:function(){var g=this,b=u.performance,S=u.PerformanceObserver;if(g[f]||(g[f]=new WeakMap),!b||!S||typeof b!="object"||typeof b.getEntriesByType!="function")return null;var v=b.getEntriesByType("resource")||[];return setTimeout(function(){g.setResource(v)},10),new S(function(R){setTimeout(function(){g.setResource(R.getEntries())},10)}).observe({entryTypes:["resource"]}),this.onReady(function(){setTimeout(g.resourceComboReport.bind(g),5e3)}),g},setResource:function(g){var b=this._conf,S=this[f];if(o.isArray(g)&&g.length){this[h]||(this[h]={});for(var v=this[h],R=0,_=g.length;R<_;R+=1){var y=g[R];if(o.checkAPI(y.name,!1)){var w=p(y,b,S);if(w){var A=w.res_type+"-"+w.domain;A in v||(v[A]=[]),v[A].push(w)}}}return this}},fixResourceStatus:function(g){var b=u.performance;if(!b||typeof b.getEntriesByName!="function")return null;var S=this[f];if(!g.src||!o.checkAPI(g.src,!1))return this;var v=g.timeStamp||b.now(),R=b.getEntriesByName(g.src,"resource");return o.each(R,function(_){S.has(_)||v-_.responseEnd<100&&S.set(_,{success:0})}),this},resourceComboReport:function(){var g=this[h]||{},b=this._conf.resourceSlow||2e3,S=this[f];this[h]={};var v=Object.keys(g);if(v.length!==0){var R=[];o.each(v,function(A){var E=g[A],C={domain:"",res_type:"",src_type:"",size:0,duration:0,count:0,err_count:0,err_duration:0,slow_count:0,slow_duration:0,timings:[]};o.each(E,function(P){var M=P.timing||{},x=S.get(P.timing),K=x?x.success:1,Q=P.duration>b?1:0;C.domain=P.domain,C.res_type=P.res_type,C.src_type=P.src_type,C.count+=1,C.duration+=P.duration,C.size+=P.size,K||(C.err_count+=1,C.err_duration+=P.duration),Q&&(C.slow_count+=1,C.slow_duration+=P.duration);try{var G=JSON.parse(JSON.stringify(M));G.success=K,G.resourceSlow=b,G.isSlow=Q,C.timings.push(G)}catch(W){}}),C.count&&(C.size=Math.round(C.size/C.count),C.duration=Math.round(C.duration/C.count)),C.slow_count&&(C.slow_duration=Math.round(C.slow_duration/C.slow_count)),C.err_count&&(C.err_duration=Math.round(C.err_duration/C.err_count)),C.timings.length>20&&(C.timings.sort(function(P,M){return M.duration-P.duration}),C.timings.length=20),C.timings=encodeURIComponent(JSON.stringify(C.timings)),R.push(C)});var _={_combo:1,resource:JSON.stringify(R)},y=u.navigator.connection;_.ct=y?y.effectiveType||y.type:"";var w=y&&(y.downlink||y.downlinkMax||y.bandwidth)||null;(w=w>999?999:w)&&(_.bandwidth=w),this._lg("resource",_,this.getConfig("sample"))}}})},xs}()(c,i),c._super=r,c._root=r._root,r.Browser=c,Es.exports=c,Es.exports}var vc={getArmsLogger:function(){return function(){if(un)return Is.exports;function a(s,n){var c=r[t]=new e(s);c.sendPipe(n);var o=c._conf;return o.autoSendPv!==!1&&c.sendPV(),o&&o.useFmp||c.sendPerformance(),o&&o.sendResource&&c.sendResources(),r[i]=!0,c}un=1;var r=window,e=r.BrowserLogger=Sc(),t=it().key,i="__hasInitBlSdk";return e.singleton=function(s,n){return r[i]?r[t]:a(s,n)},e.createExtraInstance=function(s){s&&typeof s=="object"&&s.enableInstanceAutoSend!==!0&&(s.enableInstanceAutoSend=!1);var n=new e(s),c=n._conf;return c.enableInstanceAutoSend&&(c.autoSendPv!==!1&&n.sendPV(),c&&c.useFmp||n.sendPerformance(),c&&c.sendResource&&n.sendResources()),n},typeof window=="object"&&window.navigator&&r[t]&&(e.bl=function(){if(r[i])return r[t];var s={},n=[];return t in r&&(s=r[t].config||{},n=r[t].pipe||[]),a(s,n)}()),Is.exports=e,Is.exports}()}};const pn="https://arms-retcode.aliyuncs.com/r.png?",mn="https://arms-retcode-sg.aliyuncs.com/r.png?",gn="https://retcode-us-west-1.arms.aliyuncs.com/r.png?",fn="e1iftji1w7@7ec1cef2cc88733",bn="e1iftji1w7@10a06d1ec260adc",Sn="e1iftji1w7@10a06d1ec260adc",Vs={cn:{reportUrl:pn,pid:fn},"cn-hangzhou":{reportUrl:pn,pid:fn},sg:{reportUrl:mn,pid:bn},"ap-southeast-1":{reportUrl:mn,pid:bn},usw:{reportUrl:gn,pid:Sn},"us-west-1":{reportUrl:gn,pid:Sn}},yc=a=>!!Object.isExtensible(a)&&(r=>Object.prototype.toString.call(r).slice(8,-1))(a)==="Object";function vn(a,r){if(typeof a!="string")return r;if(yn(a,r))return a;const e=a.indexOf(`
131
131
  `);return e<0?`${a}${r}`:`${a.slice(0,e)}${r}${a.slice(e)}`}function yn(a,r){if(typeof a!="string")return!1;const e=a.indexOf(r);if(e<0)return!1;const t=a.indexOf(`
132
- `);return t<0||e<t}function Ft(a,r,e){return typeof a=="function"?function(t,i,s){if(Reflect.get(t,"__v_skip")===!0)return t;const n={MediaboxWrapperFunctionApply(c,o,l){let d;try{d=Reflect.apply(c,o,l)}catch(u){throw s(u),u}return Ft(d,i,s)},MediaboxWrapperFunctionGet(c,o){const l=Object.getOwnPropertyDescriptor(c,o);return!l||l.writable||l.configurable?Ft(c[o],i,s):c[o]},MediaboxWrapperClassConstructor(c,o){let l;try{l=new c(...o)}catch(d){throw s(d),d}return Ft(l,i,s)}};return Object.defineProperty(t,"__v_skip",{configurable:!0,enumerable:!1,writable:!1,value:!0}),new Proxy(t,{apply:n.MediaboxWrapperFunctionApply,get:n.MediaboxWrapperFunctionGet,construct:n.MediaboxWrapperClassConstructor})}(a,r+1,e):a instanceof Promise?a.then(t=>Ft(t,r+1,e)).catch(t=>(e(t),Promise.reject(t))):Array.isArray(a)?(a.forEach((t,i)=>{a[i]=Ft(t,r+1,e)}),a):(t=>t!==null&&typeof t=="object")(a)&&yc(a)?function(t,i,s){var n;if(Reflect.get(t,"__v_skip")===!0)return t;const c=[],o=typeof Object.getOwnPropertyDescriptors=="function"?Object.getOwnPropertyDescriptors((n=Object.getPrototypeOf(t))!=null?n:{}):{};for(const d of Object.keys(o))o[d].get&&c.push(d);const l={MediaboxWrapperObjectGetter(d,u){if(typeof u=="string"&&c.indexOf(u)>-1){let h;try{h=d[u]}catch(f){throw s(f),f}return Ft(h,i,s)}if(i>10)return d[u];const p=Reflect.getOwnPropertyDescriptor(d,u);return!p||p.writable||p.configurable?Ft(d[u],i,s):d[u]},MediaboxWrapperObjectSetter:(d,u,p)=>(d[u]=Ft(p,i,s),!0)};return Object.defineProperty(t,"__v_skip",{configurable:!0,enumerable:!1,writable:!1,value:!0}),new Proxy(t,{get:l.MediaboxWrapperObjectGetter,set:l.MediaboxWrapperObjectSetter})}(a,r+1,e):a}function Us(a){return typeof a=="string"&&(a.indexOf("g.alicdn.com/apsara-media-")>-1||a.indexOf("g.alicdn.com/thor-server")>-1||a.indexOf("MediaboxWrapper")>-1)}function Rn(a,r){if(Reflect.get(a,"__v_skip")===!0)return a;const e={MediaboxWrapperShallowGet(t,i){const s=t[i];return typeof s=="function"?e.MediaboxWrapperShallowMethod(s,t):s},MediaboxWrapperShallowMethod:(t,i)=>({MediaboxWrapperShallowApply(...s){let n;try{n=t.apply(i,s)}catch(c){throw r(c),c}return n instanceof Promise?n.catch(c=>(r(c),Promise.reject(c))):n}}).MediaboxWrapperShallowApply};return Object.defineProperty(a,"__v_skip",{configurable:!0,enumerable:!1,writable:!1,value:!0}),new Proxy(a,{get:e.MediaboxWrapperShallowGet})}class An extends Error{constructor(r){super(r),this.name="MQTError"}}let Rc=1;class Bs{constructor(r){var e,t;ni(this,"armsLogger"),ni(this,"isReady",!1),ni(this,"isDestroyed",!1),ni(this,"options"),ni(this,"queue",[]),ni(this,"marker"),ni(this,"helper",{MediaboxWrapperQueue:i=>new An(i),MediaboxWrapperInitiative:i=>new An(i)}),this.options=((i,s)=>dc(i,uc(s)))(_s({},r),{region:r.deferRegionSet?void 0:(e=r.region)!=null?e:"cn",env:(t=r.env)!=null?t:"prod"}),this.marker=`-${Rc++}-`,this.initArmsLogger()}static get version(){return"0.31.0"}initArmsLogger(r){const{region:e,env:t,disabled:i}=this.options;if(i||this.armsLogger)return;if(r&&!e)throw new Error("region is required");if(!e)return;if(!Vs[e])throw new Error(`region ${e} is not supported`);const s=vc.getArmsLogger();this.armsLogger=s.createExtraInstance({enableInstanceAutoSend:!0,pid:Vs[e].pid,tag:this.options.businessName,release:`${this.options.businessName}_${this.options.version}`,imgUrl:Vs[e].reportUrl,behavior:!0,sample:1,disableHook:!0,environment:t,beforeReport:n=>{var c;if(this.isDestroyed||yn(n.stack,this.marker)||n.t!=="pv"&&n.t!=="error"&&n.t!=="health")return!1;if(n.c1=(c=this.options.cid)!=null?c:window.location.host,n.c2=Bs.version,this.options.customData&&(n.c3=new URLSearchParams(this.options.customData).toString()),n.t==="error"){if(function(o){return typeof o=="string"&&(o.indexOf("g.alicdn.com/apsara-media-")>-1||o.indexOf("g.alicdn.com/thor-server")>-1)}(n.file)||Us(n.stack)){let o=n;return this.options.beforeSend&&(o=this.options.beforeSend(n)),this.isReady?o:(o&&this.queue.push(o),!1)}return!1}return n}})}wrap(r){return this.options.disabled||typeof Proxy=="undefined"?r:Ft(r,0,e=>{var t;e instanceof Error&&typeof e.stack=="string"&&Us(e.stack)&&((t=this.armsLogger)==null||t.error(e),e.stack=vn(e.stack,this.marker))})}shallowWrapClass(r){return this.options.disabled||typeof Proxy=="undefined"?r:function(e,t){if(Reflect.get(e,"__v_skip")===!0)return e;const i=n=>n instanceof e?Rn(n,t):n,s={MediaboxWrapperStaticGet(n,c){const o=n[c];return typeof o=="function"&&c!=="prototype"?s.MediaboxWrapperStaticMethod(o,n):o},MediaboxWrapperStaticMethod(n,c){const o={MediaboxWrapperStaticApply(l,d,u){let p;try{p=n.apply(c,u)}catch(h){throw t(h),h}return p instanceof Promise?p.then(h=>i(h)).catch(h=>(t(h),Promise.reject(h))):i(p)},MediaboxWrapperStaticConstruct(l,d,u){let p;try{p=Reflect.construct(n,d,u)}catch(h){throw t(h),h}return i(p)}};return new Proxy(n,{apply:o.MediaboxWrapperStaticApply,construct:o.MediaboxWrapperStaticConstruct})},MediaboxWrapperConstruct(n,c,o){let l;try{l=Reflect.construct(n,c,o)}catch(d){throw t(d),d}return Rn(l,t)}};return Object.defineProperty(e,"__v_skip",{configurable:!0,enumerable:!1,writable:!1,value:!0}),new Proxy(e,{get:s.MediaboxWrapperStaticGet,construct:s.MediaboxWrapperConstruct})}(r,e=>{var t;e instanceof Error&&typeof e.stack=="string"&&Us(e.stack)&&((t=this.armsLogger)==null||t.error(e),e.stack=vn(e.stack,this.marker))})}updateOptions(r){this.options=_s(_s({},this.options),r)}setReady(){this.initArmsLogger(!0),this.isReady=!0,this.queue.length&&this.queue.forEach(r=>{var e;(e=this.armsLogger)==null||e.error(this.helper.MediaboxWrapperQueue(r.msg),{filename:r.file,lineno:r.line,colno:r.col})})}report(r,e){var t;(t=this.armsLogger)==null||t.error(this.helper.MediaboxWrapperInitiative(r),e)}destroy(){this.isDestroyed=!0}}class Ac extends oe{constructor(){super();m(this,"audioContext");m(this,"stream");m(this,"sourceNode");m(this,"analyser");this.audioContext=yt.getInstance(),this.stream=new MediaStream}getLevel(){return this.analyser?this.analyser.getLevel():0}start(e,t=1e3){this.sourceNode&&this.stop(),this.stream.addTrack(e),this.sourceNode=this.audioContext.createMediaStreamSource(this.stream);const i=this.audioContext.createMediaStreamDestination();this.analyser=function(s,n,c,o,l){let d,u=o,p=0;const h=s.createAnalyser();h.fftSize=256;const f=new Uint8Array(h.frequencyBinCount);n.connect(h),h.connect(c);const g=()=>{d&&window.clearInterval(d)},b=()=>{s.state==="suspended"&&s.resume(),d=window.setInterval(()=>{h.getByteFrequencyData(f);let S=Math.round(f.reduce((v,R)=>v+R)/f.length);S=Math.min(100,S),p=S,l&&l(S)},u)};return b(),{updateInterval:S=>{g(),u=S,b()},getLevel:()=>p,dispose:()=>{g(),n.disconnect(),h.disconnect()}}}(this.audioContext,this.sourceNode,i,t,s=>{this.emit("audioLevel",s)})}stop(){this.analyser&&this.analyser.dispose(),this.analyser=void 0,this.sourceNode=void 0,this.stream.getAudioTracks().forEach(e=>{this.stream.removeTrack(e)})}dispose(){this.stop()}}class wn extends oe{constructor(e,t,i,s){super();m(this,"uid");m(this,"name");m(this,"rtsManager");m(this,"callId","");m(this,"audioLevelMonitor");m(this,"audioVolumeIndicationInterval",0);this.uid=e,this.name=t,this.rtsManager=i,this.audioVolumeIndicationInterval=s,this.audioLevelMonitor=new Ac}get userId(){return this.uid}get displayname(){return this.name}createCallId(e=!1){this.callId&&!e||(this.callId=Le.createCallid())}setUserInfo(e,t){this.uid=e,this.name=t}refreshUserInfo(e){this.uid=e}getAudioLevel(){return this.audioLevelMonitor.getLevel()}enableAudioVolumeIndication(e){this.audioVolumeIndicationInterval=e}clear(){this.audioLevelMonitor.dispose()}}class _n{static getCurrentStatus(r){let e=0;r.micOpen&&(e+=1),r.micInterrupted&&(e+=2),r.cameraOpen&&(e+=4),r.screenShare&&(e+=128),r.audioDisable&&(e+=8),r.videoDisable&&(e+=16),r.screenDisable&&(e+=256);let t=e.toString(16);for(;t.length<16;)t="0"+t;return t}static parseStatus(r){let e=parseInt(r,16);return{micOpen:!!(1&e),micInterrupted:!!(2&e),cameraOpen:!!(4&e),screenShare:!!(128&e),audioDisable:!!(8&e),videoDisable:!!(16&e),screenDisable:!!(256&e),backgroundMode:!!(32&e),accompanyPlaying:!!(64&e)}}}const k=(a,r)=>(e,t,i)=>{const s=i.value;return i.value=function(...n){var p;const c=this.instanceId||this._loggerInstanceId;c&&T.setActiveInstance(c);const o=`[${this.logName||((p=e.constructor)==null?void 0:p.logName)||""}]`,l=Date.now();let d=[];if(a)try{d=a(n)}catch(h){}T.interface(o,t,...d);const u=s.apply(this,n);return Promise.resolve(u).then(h=>h).catch(h=>h).then(h=>{var S;c&&T.setActiveInstance(c);let f="";const g=h instanceof Error,b=g&&((S=e.constructor)==null?void 0:S.logError);if(r||g){if(b)f=h;else if(g)f=h.message||"";else{if(!r)return;if(h===void 0)f="";else try{f=r(h)}catch(v){}}T.interfaceResult(o,t,!(g&&b),Date.now()-l+"ms",f)}}),u},i},H=a=>a,In="customVideoProfile",En="customScreenProfile",Hs={width:1280,height:720,frameRate:30,maxBitrate:2e3},Tn={width:1920,height:1080,frameRate:30,maxBitrate:2600};var Ei=(a=>(a[a.ERROR_DEVICE_UNKNOWNERROR=1e4]="ERROR_DEVICE_UNKNOWNERROR",a[a.ERROR_DEVICE_AUDIODEVICE_NOTFOUND=10001]="ERROR_DEVICE_AUDIODEVICE_NOTFOUND",a[a.ERROR_DEVICE_AUDIODEVICE_NOTALLOWED=10002]="ERROR_DEVICE_AUDIODEVICE_NOTALLOWED",a[a.ERROR_DEVICE_AUDIODEVICE_NOTREADABLE=10003]="ERROR_DEVICE_AUDIODEVICE_NOTREADABLE",a[a.ERROR_DEVICE_VIDEODEVICE_NOTFOUND=10004]="ERROR_DEVICE_VIDEODEVICE_NOTFOUND",a[a.ERROR_DEVICE_VIDEODEVICE_NOTALLOWED=10005]="ERROR_DEVICE_VIDEODEVICE_NOTALLOWED",a[a.ERROR_DEVICE_VIDEODEVICE_NOTREADABLE=10006]="ERROR_DEVICE_VIDEODEVICE_NOTREADABLE",a[a.ERROR_SCREENSHARE_NOTSUPPORT=10010]="ERROR_SCREENSHARE_NOTSUPPORT",a[a.ERROR_SCREENSHARE_NOTALLOWED=10011]="ERROR_SCREENSHARE_NOTALLOWED",a[a.ERROR_SCREENSHARE_ENDED=10012]="ERROR_SCREENSHARE_ENDED",a[a.ERROR_SCREENSHARE_NOPERMISSION=10013]="ERROR_SCREENSHARE_NOPERMISSION",a[a.ERROR_SCREENSHARE_SAFARI_INVALIDACCESS=10014]="ERROR_SCREENSHARE_SAFARI_INVALIDACCESS",a[a.ERROR_SCREENSHARE_UNKNOWNERRO=10019]="ERROR_SCREENSHARE_UNKNOWNERRO",a[a.ERROR_DEVICE_NOTALLOWED=10021]="ERROR_DEVICE_NOTALLOWED",a[a.ERROR_DEVICE_NOTSUPPORT=2e4]="ERROR_DEVICE_NOTSUPPORT",a))(Ei||{});const wc={1e4:je.AliEngineLocalDeviceExceptionTypeUnknown,2e4:je.AliEngineLocalDeviceExceptionTypeUnknown,10001:je.AliEngineLocalDeviceExceptionTypeMicNotAvailable,10002:je.AliEngineLocalDeviceExceptionTypeMicAuthFail,10003:je.AliEngineLocalDeviceExceptionTypeMicOpenFail,10005:je.AliEngineLocalDeviceExceptionTypeCameraAuthFail,10004:je.AliEngineLocalDeviceExceptionTypeVideoDeviceException,10006:je.AliEngineLocalDeviceExceptionTypeCameraOpenFail,10010:je.AliEngineLocalDeviceExceptionTypeDisplayException,10011:je.AliEngineLocalDeviceExceptionTypeDisplayException,10012:je.AliEngineLocalDeviceExceptionTypeDisplayException,10013:je.AliEngineLocalDeviceExceptionTypeDisplayException,10014:je.AliEngineLocalDeviceExceptionTypeDisplayException,10019:je.AliEngineLocalDeviceExceptionTypeDisplayException};var Ze=(a=>(a.CREATE_ENGINE="create_engine",a.JOIN="join",a.WANT_INSERT_PUB_TASK="wantInsertPubTask",a.INSERT_PUB_TASK="InsertPubTask",a.HANDLE_PUB_TASK="HandlePubTask",a.RECV_NOTIFY_PUBLISH="RecvNotifyPublish",a.INSERT_SUB_TASK="InsertSubTask",a.HANDLE_SUB_TASK="HandleSubTask",a.FIRST_REMOTE="first_remote",a))(Ze||{}),st=(a=>(a.START="start",a.SEND_SIG="send_sig",a.RECV_RST="recv_rst",a.END="end",a.RECEIVED="received",a.DECODED="decoded",a.PLAYED="played",a))(st||{});const Cn=(a,r,e=!1)=>{const t=()=>(a.muted=!0,Promise.race([Ht(500),a._playPromise||Promise.resolve()]).catch(()=>{}).then(()=>{let i;return e&&a.srcObject===r?i=Promise.resolve():(a.load(),a.srcObject=r,i=a.play(),a._playPromise=i),i}));return new Promise(i=>{if(J.AliRTS.BrowserUtil.isMicroMessenger){const s=window.top!==window.self,n=window.WeixinJSBridge||window.top.WeixinJSBridge;n?n.invoke("getNetworkType",{},()=>{i(t())}):(s?window.top.document:document).addEventListener("WeixinJSBridgeReady",()=>{n.invoke("getNetworkType",{},()=>{i(t())})}),setTimeout(()=>{i(t())},1e3)}else setTimeout(()=>{i(t())},0)})},Mt=a=>{Promise.race([Ht(100),a._playPromise||Promise.resolve()]).catch(()=>{}).then(()=>{a.srcObject=null,a._playPromise=void 0})};var Fs=(a=>(a[a.AliEngineDataMsgNone=0]="AliEngineDataMsgNone",a[a.AliEngineDataMsgMusicProgress=1]="AliEngineDataMsgMusicProgress",a[a.AliEngineDataMsgCustom=2]="AliEngineDataMsgCustom",a))(Fs||{});class Ji{constructor(r,e,t,i=0){m(this,"msgType");m(this,"msgId");m(this,"protocolVersion");m(this,"tlvVersion");this.msgType=r,this.msgId=e,this.protocolVersion=t,this.tlvVersion=i}build(){const r=new Uint8Array(4);return r.set(Uint8Array.from([this.protocolVersion,this.tlvVersion<<4|15&this.msgType]),0),r.set(Uint16Array.from([this.msgId]),2),r}static parse(r){const e=new DataView(r),t=e.getUint8(0),i=e.getUint8(1)>>4,s=15&e.getUint8(1),n=e.getUint16(2);return new Ji(s,n,t,i)}}class qi{constructor(r,e,t){m(this,"_byteArray");if(this._byteArray=new Uint8Array(0),r!==void 0&&e!==void 0&&t!==void 0){const i=new Ji(r,e,t).build();this._byteArray=new Uint8Array(i.byteLength+this._byteArray.byteLength),this._byteArray.set(i,0)}}write(r,e){const t=this._byteArray,i=new ArrayBuffer(5),s=new DataView(i);s.setUint8(0,r),s.setUint32(1,e.byteLength);const n=new Uint8Array(t.byteLength+5+e.byteLength);n.set(t,0),n.set(new Uint8Array(i),t.byteLength),n.set(new Uint8Array(e),t.byteLength+5),this._byteArray=n}static parse(r){const e={},t=new DataView(r);let i=0;for(;i<r.byteLength;){const s=t.getUint8(i),n=t.getUint32(i+1);if(!(i+5+n<=r.byteLength))break;{const c=r.slice(i+5,i+5+n);e[s]=c,i+=5+n}}return e}get buffer(){return this._byteArray.buffer}}class Ti{constructor(r=0,e=!0,t=1,i=!1,s=0,n=!1,c=!1,o=3){m(this,"_fin",!0);m(this,"_hasExtension",!1);m(this,"_version",0);m(this,"_frameType",1);m(this,"_isEncrypted",!1);m(this,"_isCompressed",!1);m(this,"_signalType",3);m(this,"_payloadLength",0);this._fin=e,this._hasExtension=i,this._version=s,this._frameType=t,this._isEncrypted=n,this._isCompressed=c,this._signalType=o,this._payloadLength=r}get fin(){return this._fin}get hasExtension(){return this._hasExtension}get version(){return this._version}get frameType(){return this._frameType}get isEncrypted(){return this._isEncrypted}get isCompressed(){return this._isCompressed}get signalType(){return this._signalType}get payloadLength(){return this._payloadLength}toBuffer(){const r=new ArrayBuffer(4),e=new DataView(r);return e.setUint8(0,(this._fin?1:0)<<7|(this._hasExtension?1:0)<<6|this._version<<4|15&this._frameType),e.setUint8(1,(this._isEncrypted?1:0)<<7|(this._isCompressed?1:0)<<6|15&this._signalType),e.setUint16(2,this._payloadLength),r}static parse(r){const e=new DataView(r),t=e.getUint8(0)>>7==1,i=(64&e.getUint8(0))>>6==1,s=(48&e.getUint8(0))>>4,n=15&e.getUint8(0),c=e.getUint8(1)>>7==1,o=(64&e.getUint8(1))>>6==1,l=15&e.getUint8(1),d=e.getUint16(2);return new Ti(d,t,n,i,s,c,o,l)}}class Gi{constructor(r,e){m(this,"_body");m(this,"_header",new Ti);this._header=r,this._body=e}get header(){return this._header}get isFin(){return this._header.fin}get body(){return this._body}toGRTNBuffer(){const r=this._header.toBuffer(),e=this._body,t=new ArrayBuffer(4);new DataView(t).setUint8(0,1*Math.pow(2,4));const i=new Uint8Array(t.byteLength+r.byteLength+e.byteLength);return i.set(new Uint8Array(t),0),i.set(new Uint8Array(r),t.byteLength),i.set(new Uint8Array(e),t.byteLength+r.byteLength),i.buffer}static parse(r){const e=r.slice(0,4),t=Ti.parse(e);let i=new ArrayBuffer(0);return r.byteLength-4>=t.payloadLength&&(i=r.slice(4,4+t.payloadLength)),new Gi(t,i)}}const js=a=>{const r=a.byteLength,e=new DataView(a);let t=0;for(let i=0;i<r;i++)t=256*t+e.getUint8(i);return t};let kn=0;class Jt{constructor(r,e=0,t=0,i=0){m(this,"data");m(this,"networkTime");m(this,"futureOrProgress");m(this,"type");this.data=r,this.type=e,this.networkTime=t,this.futureOrProgress=i}toBuffer(){const r=new qi(0,0,0);r.write(1,Uint8Array.from([0]).buffer),r.write(2,Uint16Array.from([0]).buffer),kn++,r.write(3,Uint32Array.from([kn]).buffer);const e=new qi;return e.write(1,Uint8Array.from([0]).buffer),e.write(2,Uint8Array.from([this.type]).buffer),e.write(3,Uint32Array.from([this.futureOrProgress]).buffer),e.write(4,Uint32Array.from([Number(this.networkTime>>32&4294967295),Number(4294967295&this.networkTime)]).buffer),e.write(5,this.data),r.write(30,e.buffer),r.buffer}static parse(r){if(!r||r.byteLength<4)return;Ji.parse(r.slice(0,4));const e=qi.parse(r.slice(4))[30];if(!e)return;const t=qi.parse(e),i=t[2],s=t[3],n=t[4],c=t[5];return c.byteLength!==0?new Jt(c,js(i),js(n),js(s)):void 0}}var _c=Object.defineProperty,Ic=Object.getOwnPropertyDescriptor,De=(a,r,e,t)=>{for(var i,s=t>1?void 0:t?Ic(r,e):r,n=a.length-1;n>=0;n--)(i=a[n])&&(s=(t?i(r,e,s):i(s))||s);return t&&s&&_c(r,e,s),s};class Ci extends oe{constructor(){super();m(this,"_state");m(this,"time");this._state=ee.AliRtcStatePublishIdle,this.time=Date.now()}get state(){return this._state}setState(e){const t=this._state,i=this.time;this._state=e,this.time=Date.now(),this.emit("change",t,e,Math.floor((this.time-i)/1e3))}}const Ce=(bt=class extends wn{constructor(e){const{rtsManager:t,localStreamManager:i,slsReporter:s,signalingManager:n,audioVolumeIndicationInterval:c,parameter:o}=e;super("","",t,c);m(this,"sessionId","");m(this,"traceId","");m(this,"_url","");m(this,"joinTime",0);m(this,"publishPromise",Promise.resolve({traceId:"",l1ip:void 0}));m(this,"previewElements",[]);m(this,"screenPreviewElements",[]);m(this,"streamManager");m(this,"dc");m(this,"streamTracks");m(this,"publishId",mt());m(this,"signalingManager");m(this,"shouldPublish",!1);m(this,"monitorTimerId");m(this,"monitorDataCache",{});m(this,"candidateDataCache",[]);m(this,"pcMediaStatsMap",{});m(this,"slsReporter");m(this,"audioPubState");m(this,"videoPubState");m(this,"videoSmallPubState");m(this,"screenPubState");m(this,"dataPubState");m(this,"parameter",{});m(this,"onTrackEnd",e=>{this.emit(e)});this.streamManager=i,this.signalingManager=n,this.slsReporter=s,this.parameter=o,this.streamManager.on("trackended",l=>{this.onTrackEnd(l)}),this.streamManager.on("publishupdate",()=>{this.publishUpdate()}),this.audioPubState=new Ci,this.audioPubState.on("change",(l,d,u)=>{this.emit("audioPublishStateChanged",l,d,u)}),this.videoPubState=new Ci,this.videoPubState.on("change",(l,d,u)=>{this.emit("videoPublishStateChanged",l,d,u)}),this.videoSmallPubState=new Ci,this.videoSmallPubState.on("change",(l,d,u)=>{this.emit("dualStreamPublishStateChanged",l,d,u)}),this.screenPubState=new Ci,this.screenPubState.on("change",(l,d,u)=>{this.emit("screenPublishStateChanged",l,d,u)}),this.dataPubState=new Ci,this.dataPubState.on("change",(l,d,u)=>{this.emit("dataPublishStateChanged",l,d,u)}),this.startStreamMonitor(),this.createCallId()}get url(){return this._url}set url(e){this._url=e,this.rtsManager.updateAuth(e)}get joined(){return!!this.uid}get isPublishing(){return this.rtsManager.publishingTracks.length>0}get publishStreams(){return this.streamManager.publishStreams}get cameraTrack(){return this.streamManager.cameraStreamInfo.originVideoTrack}get screenTrack(){return this.streamManager.screenStreamInfo.originVideoTrack}get audioTrack(){return this.streamManager.cameraStreamInfo.originAudioTrack}get hasCamera(){return!!this.streamManager.cameraStreamInfo.originVideoTrack}get hasMicrophone(){return!!this.streamManager.cameraStreamInfo.originAudioTrack}get hasScreenShare(){return!!this.streamManager.screenStreamInfo.originVideoTrack}get hasCameraTrackInMS(){var e;return!!((e=this.streamTracks)!=null&&e.find(({ssrc:t,type:i,msid:s})=>i==="video"&&t&&s===D.VideoLarge))}get hasCameraDualTrackInMS(){var e;return!!((e=this.streamTracks)!=null&&e.find(({ssrc:t,type:i,msid:s})=>i==="video"&&t&&s===D.VideoSmall))}get hasScreenTrackInMS(){var e;return!!((e=this.streamTracks)!=null&&e.find(({ssrc:t,type:i,msid:s})=>i==="video"&&t&&s===D.Screen))}get hasAudioTrackInMS(){var e;return!!((e=this.streamTracks)!=null&&e.find(({ssrc:t,type:i,msid:s})=>i==="audio"&&t&&s===D.Audio))}get cameraDirection(){var e,t;return(t=(e=this.streamManager.cameraStreamInfo)==null?void 0:e.cameraVideoConstraints)==null?void 0:t.facingMode}get audioCaptureDisabled(){return this.streamManager.audioCaptureDisabled}get cameraCaptureDisabled(){return this.streamManager.cameraCaptureDisabled}get publishLocalVideoStreamEnabled(){return this.streamManager.publishLocalVideoStreamEnabled}get publishLocalAudioStreamEnabled(){return this.streamManager.publishLocalAudioStreamEnabled}get publishLocalScreenStreamEnabled(){return this.streamManager.publishLocalScreenStreamEnabled}setPublishLocalAudioStreamEnabled(e){this.streamManager.publishLocalAudioStreamEnabled=e}setPublishLocalVideoStreamEnabled(e){this.streamManager.publishLocalVideoStreamEnabled=e}setPublishLocalScreenStreamEnabled(e){this.streamManager.publishLocalScreenStreamEnabled=e}initInfo(e,t){this.joinTime=Date.now(),this.rtsManager.localJoinTime=this.joinTime,this.setUserInfo(e.userId,e.userId),this.url=t,this.sessionId=e.sessionId||Le.createCallid("web"),this.updatePubId()}setVideoProfile(e){return I(this,null,function*(){yield this.streamManager.setVideoProfile(In,e)})}setVideoContentHint(e){this.streamManager.setVideoContentHint(e)}setScreenContentHint(e){this.streamManager.setScreenContentHint(e)}setAudioProfile(e){return I(this,null,function*(){yield this.streamManager.setAudioProfile(e)})}setScreenProfile(e){return I(this,null,function*(){yield this.streamManager.setScreenProfile(En,e)})}setCameraDirection(e){if(e===Ai.CAMERA_FRONT)this.streamManager.setCameraVideoConstraints({facingMode:"user"});else{if(e!==Ai.CAMERA_REAR)throw new U(B.ERR_CAMERA_OPEN_FAIL,`camera direction set to ${e} failed`);this.streamManager.setCameraVideoConstraints({facingMode:"environment"})}}setCameraDeviceId(e){this.streamManager.setCameraVideoConstraints({deviceId:e})}muteLocalCamera(e){this.streamManager.setCameraMuted(e),this.slsReporter.reportMute(this.callId,!e,"video")}muteLocalMic(e){this.streamManager.setAudioMuted(e),this.slsReporter.reportMute(this.callId,!e,"audio")}muteLocalScreen(e){this.streamManager.setScreenMuted(e),this.slsReporter.reportMute(this.callId,!e,"screen")}setMicrophoneDeviceId(e){this.streamManager.setMicAudioConstraints({deviceId:e})}setMicrophoneConstraints(e){this.streamManager.setMicAudioConstraints(e)}updatePubId(){this.publishId=mt()}clearPublishState(){this.streamTracks=void 0}leave(){return I(this,null,function*(){this.shouldPublish=!1,this.isPublishing&&(yield this.unPublish()),this.joinTime=0,this.dc=void 0,this.dataPubState.setState(ee.AliRtcStateNoPublish)})}clear(){return I(this,null,function*(){ur(bt.prototype,this,"clear").call(this),this.stopPreview(),this.resetPreviewElements(),this.resetSecondayPreviewElements(),this.clearStream(),yield this.leave(),this.streamManager.cameraCaptureDisabled=!1})}resetElement(e){this.previewElements.includes(e)&&(Mt(e),this.previewElements.splice(this.previewElements.indexOf(e),1)),this.screenPreviewElements.includes(e)&&(Mt(e),this.screenPreviewElements.splice(this.screenPreviewElements.indexOf(e),1))}setPreviewElement(e){const{videoElement:t,screen:i}=e;i?this.screenPreviewElements.includes(t)||(this.screenPreviewElements.push(t),this.preview(e)):this.previewElements.includes(t)||(this.previewElements.push(t),this.preview(e))}startDefaultCameraAndMic(e){return I(this,null,function*(){const{hasCamera:t,cameraCaptureDisabled:i,publishLocalVideoStreamEnabled:s}=this,{hasMicrophone:n,audioCaptureDisabled:c,publishLocalAudioStreamEnabled:o}=this,l=!t&&!e&&!i&&s,d=!n&&!c&&o;try{l&&d?yield this.startCameraAndMic():l?yield this.startCameraCapture():d&&(yield this.startAudioCapture())}catch(u){const p=u.errorCode;let h=B.ERR_CAMERA_OPEN_FAIL;throw l?((p===Ei.ERROR_DEVICE_VIDEODEVICE_NOTALLOWED||Ei.ERROR_DEVICE_NOTALLOWED)&&(h=B.ERR_CAMERA_AUTH_FAIL),h=B.ERR_CAMERA_OPEN_FAIL):((p===Ei.ERROR_DEVICE_AUDIODEVICE_NOTALLOWED||Ei.ERROR_DEVICE_NOTALLOWED)&&(h=B.ERR_MIC_AUTH_FAIL),h=B.ERR_MIC_OPEN_FAIL),new U(h,`auto open fail: ${u.message}`)}})}setViewConfig(e,t){if(e){if(![ue.AliRtcVideoTrackCamera,ue.AliRtcVideoTrackScreen].includes(t))throw new U(B.ERR_INVALID_ARGUMENTS,"set view config invalid track",{track:t});e.forEach(i=>{this.setPreviewElement({videoElement:i,screen:t===ue.AliRtcVideoTrackScreen})})}else t===ue.AliRtcVideoTrackCamera?this.stopPreview({primary:!0,screen:!1}):this.stopPreview({primary:!1,screen:!0})}startCameraCapture(){return I(this,null,function*(){return this.streamManager.cameraCaptureDisabled=!1,yield this.createLocalStream({video:!0})})}stopCameraCapture(){return I(this,null,function*(){this.streamManager.cameraCaptureDisabled=!0,yield this.stopLocalStream({video:!0})})}startAudioCapture(){return I(this,null,function*(){return this.streamManager.audioCaptureDisabled=!1,yield this.createLocalStream({audio:!0})})}stopAudioCapture(){return I(this,null,function*(){this.streamManager.audioCaptureDisabled=!0,yield this.stopLocalStream({audio:!0})})}startCameraAndMic(){return I(this,null,function*(){return this.streamManager.cameraCaptureDisabled=!1,this.streamManager.audioCaptureDisabled=!1,yield this.createLocalStream({video:!0,audio:!0})})}preview(e){return I(this,null,function*(){const{videoElement:t,screen:i}=e!=null?e:{};try{let s=i?this.streamManager.screenStreamInfo.previewStream:this.streamManager.cameraStreamInfo.previewStream;if(!t)throw new U(B.ERR_INVALID_ARGUMENTS,"no video element found",{videoElement:t});return s?(Cn(t,s.mediaStream),this.setPreviewElement(e),s.mediaStream):void T.info(`[${bt.logName}]`,"preview no stream founded")}catch(s){const n=B.ERR_INNER;throw U.fromError(s,n,"preview failed")}})}previewAll(e){return I(this,null,function*(){const{primary:t=!0,screen:i=!0}=e!=null?e:{};if(t&&this.previewElements.length)for(let s=0;s<this.previewElements.length;s++){const n=this.previewElements[s];yield this.preview({videoElement:n})}if(i&&this.screenPreviewElements.length)for(let s=0;s<this.screenPreviewElements.length;s++){const n=this.screenPreviewElements[s];yield this.preview({videoElement:n,screen:!0})}})}stopPreview(e){const{videoElement:t,primary:i=!0,screen:s=!0}=e||{};if(t){const n=this.previewElements.findIndex(c=>c===t);if(n>=0)this.previewElements.splice(n,1),Mt(t);else{const c=this.screenPreviewElements.findIndex(o=>o===t);c>=0&&(this.screenPreviewElements.splice(c,1),Mt(t))}}else i&&(this.previewElements.forEach(n=>{Mt(n)}),this.previewElements=[]),s&&(this.screenPreviewElements.forEach(n=>{Mt(n)}),this.screenPreviewElements=[])}resumePublish(){return I(this,null,function*(){this.shouldPublish&&(this.createCallId(!0),yield this.startPublish(!0))})}createLocalStream(e){return I(this,null,function*(){try{if(e.video)for(let i=0;i<this.previewElements.length;i++){const s=this.previewElements[i];Mt(s)}else if(e.screen)for(let i=0;i<this.screenPreviewElements.length;i++){const s=this.screenPreviewElements[i];Mt(s)}const t=yield this.streamManager.createLocalStream(e);return t!=null&&t.audioTrack&&this.audioVolumeIndicationInterval>0&&this.audioLevelMonitor.start(t.audioTrack,this.audioVolumeIndicationInterval),e.video?this.previewAll({primary:!0}):e.screen&&this.previewAll({screen:!0}),t}catch(t){const i=wc[t.errorCode];throw i&&(e.audio?this.emit("localDeviceException",kt.AliEngineLocalDeviceTypeMic,i,""):e.video?this.emit("localDeviceException",kt.AliEngineLocalDeviceTypeCamera,i,""):e.screen?this.emit("localDeviceException",kt.AliEngineLocalDeviceTypeDisplay,i,""):this.emit("localDeviceException",kt.AliEngineLocalDeviceTypeUnknown,i,"")),t}})}stopLocalStream(e){return I(this,null,function*(){e.audio&&this.audioLevelMonitor.stop(),yield this.streamManager.stopLocalStream(e)})}compareAndPublish(e,t,i){return I(this,null,function*(){var n,c;if(!e&&!t)return;if(e&&!t){const o={};return i===D.Audio?o.audio=!0:i===D.VideoLarge||i===D.VideoSmall?(o.video=!0,o.vMsid=i):i===D.Screen&&(o.screen=!0),yield this.publishDeleteTracks(o)}const s={};if(t!=null&&t.hasVideo&&(s.isScreen=i===D.Screen,s.vMsid=i),t!=null&&t.hasAudio&&(s.aMsid=i),!e&&t)return yield this.publishAdd(t,s,!1);if(e&&t&&e.trackId!==(((n=t.videoTrack)==null?void 0:n.id)||((c=t.audioTrack)==null?void 0:c.id)))return yield this.publishReplace(t,s)})}reportAudioProfile(){const e=this.streamManager.cameraStreamInfo.audioProfile||"standard",t=J.AliRTS.AudioProfileMap.get(e);this.slsReporter.reportPublishProfile(D.Audio,{a_profile:e,bits:(t==null?void 0:t.maxBitrate)||0,samplerate:(t==null?void 0:t.sampleRate)||0,channel:(t==null?void 0:t.channelCount)||0})}reportVideoProfile(){const e=this.streamManager.cameraStreamInfo.videoProfile||"",t=J.AliRTS.VideoProfileMap.get(e);t&&this.slsReporter.reportPublishProfile(D.VideoLarge,{v_profile:e,wdth:(t==null?void 0:t.width)||0,hgt:(t==null?void 0:t.height)||0,fps:(t==null?void 0:t.frameRate)||0,bitrate:(t==null?void 0:t.maxBitrate)||0})}reportScreenProfile(){const e=this.streamManager.screenStreamInfo.videoProfile||"",t=J.AliRTS.VideoProfileMap.get(e);t&&this.slsReporter.reportPublishProfile(D.Screen,{v_profile:e,wdth:(t==null?void 0:t.width)||0,hgt:(t==null?void 0:t.height)||0,fps:(t==null?void 0:t.frameRate)||0,bitrate:(t==null?void 0:t.maxBitrate)||0})}updateDataChannel(e){e&&(this.dc=e,this.dc.datachannel&&(this.dc.datachannel.binaryType="arraybuffer"))}publishDataChannel(){return I(this,null,function*(){if(this.dataPubState.state!==ee.AliRtcStatePublishing){this.dataPubState.setState(ee.AliRtcStatePublishing);try{const e=yield this.rtsManager.publishAddDataChannel(this.url);e?(this.updateDataChannel(e),this.dataPubState.setState(ee.AliRtcStatePublished)):(this.dataPubState.setState(ee.AliRtcStateNoPublish),this.emit("publishDataError",new U(B.ERR_INNER,"publishDataError")))}catch(e){T.error("[LocalUser]","publishDataChannel error",e),this.dataPubState.setState(ee.AliRtcStateNoPublish)}}})}startPublish(){return I(this,arguments,function*(e=!1,t=Dt.MANUAL){var l,d,u;if(!this.joined)return;this.shouldPublish=!0;const i=this.streamManager.publishStreams,{audio:s,video:n,videoSmall:c,screen:o}=i;if(s||n||c||o)try{const p=new Date().getTime();s&&this.audioPubState.setState(ee.AliRtcStatePublishing),n&&this.videoPubState.setState(ee.AliRtcStatePublishing),c&&this.videoSmallPubState.setState(ee.AliRtcStatePublishing),o&&this.screenPubState.setState(ee.AliRtcStatePublishing),this.publishPromise=this.rtsManager.publish(this,e,t);const{traceId:h,l1ip:f}=yield this.publishPromise;this.streamTracks=this.rtsManager.publishingTracks,this.traceId=h;const g={type:Bt.Add,userid:this.userId,sessionid:this.sessionId,displayname:this.name,pubid:this.publishId,resume:e,subscribe:{signal:"",pullstreamurl:this.url},l1ip:this.parameter.reportL1IP?f:void 0,callid:this.callId,tracks:this.streamTracks,traceid:h};(l=this.parameter.data)!=null&&l.enablePubDataChannel&&this.publishDataChannel().then(()=>{this.syncPublishToRoomServer(g,i,p)}),h&&(this.traceId=h),s&&this.reportAudioProfile(),n&&this.reportVideoProfile(),o&&this.reportScreenProfile(),yield this.syncPublishToRoomServer(g,i,p),s&&this.audioPubState.setState(ee.AliRtcStatePublished),n&&this.videoPubState.setState(ee.AliRtcStatePublished),c&&this.videoSmallPubState.setState(ee.AliRtcStatePublished),o&&this.screenPubState.setState(ee.AliRtcStatePublished)}catch(p){throw s&&this.audioPubState.setState(ee.AliRtcStateNoPublish),n&&this.videoPubState.setState(ee.AliRtcStateNoPublish),c&&this.videoSmallPubState.setState(ee.AliRtcStateNoPublish),o&&this.screenPubState.setState(ee.AliRtcStateNoPublish),p}else{if((d=this.parameter.data)!=null&&d.enablePubSubDataWithoutMedia&&((u=this.parameter.data)!=null&&u.enablePubDataChannel)){T.event(`[${bt.logName}]`,"startPublish no media stream, publish data channel only");try{const p=new Date().getTime();if(yield this.publishDataChannel(),this.dc){const h={type:Bt.Add,userid:this.userId,sessionid:this.sessionId,displayname:this.name,pubid:this.publishId,resume:e,subscribe:{signal:"",pullstreamurl:this.url},callid:this.callId,tracks:[],traceid:this.traceId};yield this.syncPublishToRoomServer(h,i,p)}}catch(p){T.error(`[${bt.logName}]`,"publishDataChannel without media failed",p)}return}T.event(`[${bt.logName}]`,"startPublish no stream founded")}})}updateStreams(){return I(this,null,function*(){yield this.streamManager.updateStreams()})}publishUpdate(e){return I(this,null,function*(){var n,c,o,l,d;if(T.info(`[${bt.logName}]`,"publishUpdate",e||"-",this.shouldPublish),!this.shouldPublish)return;if(!this.rtsManager.isConnecting&&!this.rtsManager.isConnected)return void(yield this.startPublish());yield this.publishPromise;const t=this.streamManager.publishStreams;let i;const s=new Date().getTime();try{const u=(n=this.streamTracks)==null?void 0:n.find(({ssrc:R,type:_,msid:y})=>_==="audio"&&R&&y===D.Audio),p=yield this.compareAndPublish(u,t.audio,D.Audio);p&&(i=p);const h=(c=this.streamTracks)==null?void 0:c.find(({ssrc:R,type:_,msid:y})=>_==="video"&&R&&y===D.VideoLarge),f=yield this.compareAndPublish(h,t.video,D.VideoLarge);f&&(i=f);const g=(o=this.streamTracks)==null?void 0:o.find(({ssrc:R,type:_,msid:y})=>_==="video"&&R&&y===D.VideoSmall),b=yield this.compareAndPublish(g,t.videoSmall,D.VideoSmall);b&&(i=b);const S=(l=this.streamTracks)==null?void 0:l.find(({ssrc:R,type:_,msid:y})=>_==="video"&&R&&y===D.Screen),v=yield this.compareAndPublish(S,t.screen,D.Screen);v&&(i=v),(d=this.parameter.data)!=null&&d.enablePubDataChannel&&!this.dc&&(yield this.publishDataChannel()),i||e!==Dt.RECONNECT?i&&(yield this.syncPublishToRoomServer(i,t,s)):this.syncPublishToRoomServer({type:Bt.Add,userid:this.userId,sessionid:this.sessionId,displayname:this.name,pubid:this.publishId,subscribe:{signal:"",pullstreamurl:this.url},callid:this.callId,tracks:this.rtsManager.publishingTracks,traceid:this.traceId},t,Date.now())}catch(u){const{code:p}=u!=null?u:{},h=this.url;throw p===403&&h&&(yield this.refreshPushStreamUrl(),i=yield this.publishUpdate()),u}return i})}syncPublishToRoomServer(e,t,i){return I(this,null,function*(){var o;if(!e)return void T.event(`[${bt.logName}]`,"sync publish to room server failed because no publishInfo");let s=e;if(this.dc){const c=e,{tracks:l}=c,d=Wt(c,["tracks"]);s=vt(X({},d),{tracks:[...l,{type:"data",msid:D.Data,ssrc:`web_${this.callId.substring(0,8)}_${((o=this.dc.datachannel)==null?void 0:o.id)||"0"}`,codec:"text"}]})}const n=yield this.signalingManager.publish(s);e.signaltid=n.tid})}refreshPushStreamUrl(){return I(this,null,function*(){const e=new U(B.ERR_INNER,"refresh push stream url error"),t=this.url;if(!t)throw e;const i=yield this.signalingManager.refreshUrl({pushstreamurl:t});if(!(i!=null&&i.pushstreamurl))throw e;this.url=i.pushstreamurl})}publishAdd(e,t,i=!1,s=0){return I(this,null,function*(){const n=(t==null?void 0:t.aMsid)===D.Audio,c=(t==null?void 0:t.vMsid)===D.VideoLarge,o=(t==null?void 0:t.vMsid)===D.VideoSmall,l=(t==null?void 0:t.vMsid)===D.Screen;n&&this.audioPubState.setState(ee.AliRtcStatePublishing),c&&this.videoPubState.setState(ee.AliRtcStatePublishing),o&&this.videoSmallPubState.setState(ee.AliRtcStatePublishing),l&&this.screenPubState.setState(ee.AliRtcStatePublishing);try{const d=yield this.rtsManager.publishAdd(this,e,t,!1,!0);d&&(this.traceId=d),n&&(this.audioPubState.setState(ee.AliRtcStatePublished),this.reportAudioProfile()),c&&(this.videoPubState.setState(ee.AliRtcStatePublished),this.reportVideoProfile()),o&&this.videoSmallPubState.setState(ee.AliRtcStatePublished),l&&(this.screenPubState.setState(ee.AliRtcStatePublished),this.reportScreenProfile()),this.streamTracks=this.rtsManager.publishingTracks;const u={type:Bt.Add,userid:this.userId,sessionid:"",displayname:this.name,pubid:this.publishId,resume:i,subscribe:{signal:"",pullstreamurl:this.url},callid:this.callId,tracks:this.streamTracks,traceid:d};return this.reportSelfDeviceStatus(),this.monitorTimerId||this.startStreamMonitor(),u}catch(d){let u=B.ERR_SDK_PUBLISH_INVAILD;if(n&&(this.audioPubState.setState(ee.AliRtcStateNoPublish),u=B.ERR_SDK_PUBLISH_AUDIO_STREAM_FAILED),c&&(this.videoPubState.setState(ee.AliRtcStateNoPublish),u=B.ERR_SDK_PUBLISH_VIDEO_STREAM_FAILED),o&&(this.videoSmallPubState.setState(ee.AliRtcStateNoPublish),u=B.ERR_SDK_PUBLISH_DUAL_STREAM_FAILED),l&&(this.screenPubState.setState(ee.AliRtcStateNoPublish),u=B.ERR_SDK_PUBLISH_SCEEN_SHARE_FAILED),d.errorCode===15006&&s<3)return this.publishAdd(e,t,i,s+1);throw U.fromError(d,u,"publish add failed")}})}publishReplace(e,t){return I(this,null,function*(){try{yield this.rtsManager.publishReplace(this.url,e,t),this.streamTracks=this.rtsManager.publishingTracks;const i=(t==null?void 0:t.vMsid)===D.VideoLarge,s=(t==null?void 0:t.vMsid)===D.Screen;i&&this.streamManager.setVideoProfile(void 0,void 0,!0),s&&this.streamManager.setScreenProfile(void 0,void 0);const n={type:Bt.Replace,userid:this.userId,sessionid:"",pubid:this.publishId,displayname:this.name,subscribe:{signal:"",pullstreamurl:this.url},callid:this.callId,tracks:this.streamTracks};return this.reportSelfDeviceStatus(),n}catch(i){throw U.fromError(i,B.ERR_INNER,`publish replace failed, vMsid: ${t==null?void 0:t.vMsid} aMsid: ${t==null?void 0:t.aMsid}`)}})}publishDeleteTracks(e){return I(this,null,function*(){const t={type:Bt.Delete,userid:this.userId,sessionid:"",displayname:this.displayname,callid:this.callId,pubid:this.publishId,subscribe:{signal:"",pullstreamurl:this.url},tracks:[]};try{return yield this.rtsManager.publishDelete(this.url,e),this.streamTracks=this.rtsManager.publishingTracks,e.audio&&this.audioPubState.setState(ee.AliRtcStateNoPublish),e.video&&(e.vMsid===D.VideoSmall?this.videoSmallPubState.setState(ee.AliRtcStateNoPublish):this.videoPubState.setState(ee.AliRtcStateNoPublish)),e.screen&&this.screenPubState.setState(ee.AliRtcStateNoPublish),t.tracks=this.streamTracks,this.reportSelfDeviceStatus(),t}catch(i){throw U.fromError(i,B.ERR_INNER,"publish delete tracks failed")}})}publishStop(){return I(this,null,function*(){T.info(`[${bt.logName}]`,"publishStop",{url:this.url});const e=new Date().getTime();try{const t=this.hasAudioTrackInMS,i=this.hasCameraTrackInMS,s=this.hasCameraDualTrackInMS,n=this.hasScreenTrackInMS;yield this.rtsManager.publishStop(this.url),t&&this.audioPubState.setState(ee.AliRtcStateNoPublish),i&&this.videoPubState.setState(ee.AliRtcStateNoPublish),s&&this.videoSmallPubState.setState(ee.AliRtcStateNoPublish),n&&this.screenPubState.setState(ee.AliRtcStateNoPublish),this.traceId="",Object.keys(this.monitorDataCache).forEach(o=>{this.reportPublishMonitor(o)}),this.streamTracks=[];const c={type:Bt.Stop,userid:this.userId,sessionid:this.sessionId,displayname:this.displayname,callid:this.callId,pubid:this.publishId,subscribe:{signal:"",pullstreamurl:this.url},tracks:[]};return this.syncPublishToRoomServer(c,{},e),c}catch(t){throw U.fromError(t,B.ERR_INNER,"publish stop failed")}})}unPublish(){return I(this,null,function*(){this.shouldPublish=!1;const e=new Date().getTime();let t={type:Bt.UnPublish,userid:this.userId,sessionid:"",displayname:this.displayname,callid:this.callId,pubid:this.publishId,subscribe:{signal:"",pullstreamurl:this.url},tracks:[]};try{if(this.isPublishing){const i=this.hasAudioTrackInMS,s=this.hasCameraTrackInMS,n=this.hasCameraDualTrackInMS,c=this.hasScreenTrackInMS;yield this.rtsManager.unpublish(),this.streamTracks=[],this.stopStreamMonitor(),i&&this.audioPubState.setState(ee.AliRtcStateNoPublish),s&&this.videoPubState.setState(ee.AliRtcStateNoPublish),n&&this.videoSmallPubState.setState(ee.AliRtcStateNoPublish),c&&this.screenPubState.setState(ee.AliRtcStateNoPublish),this.traceId="",this.clearStream()}return this.dc&&(this.rtsManager.publishStopDataChannel(this.url,this.dc),this.dataPubState.setState(ee.AliRtcStateNoPublish),this.dc=void 0),this.slsReporter.reportUnpublish(this.callId||"",e,0,""),t}catch(i){throw U.fromError(i,B.ERR_INNER,"unpublish failed")}})}reportSelfDeviceStatus(){this.emit(ot.Local,this.getDeviceStatus())}getDeviceStatus(){var t,i,s,n;let e={micOpen:!1,micInterrupted:!1,cameraOpen:!1,screenShare:!1,audioDisable:!0,videoDisable:!0,screenDisable:!0,backgroundMode:!1,accompanyPlaying:!1};return e.cameraOpen=this.hasCameraTrackInMS,e.videoDisable=this.hasCamera&&!((t=this.streamManager.cameraStreamInfo.originVideoTrack)!=null&&t.enabled),e.micOpen=this.hasAudioTrackInMS,e.audioDisable=this.hasMicrophone&&!((i=this.streamManager.cameraStreamInfo.originAudioTrack)!=null&&i.enabled),e.screenShare=this.hasScreenTrackInMS,e.screenDisable=this.hasScreenShare&&!((n=(s=this.streamManager.screenStreamInfo)==null?void 0:s.originVideoTrack)!=null&&n.enabled),_n.getCurrentStatus(e)}resetPreviewElements(){this.previewElements.forEach(e=>{e.srcObject=null,e._playPromise=void 0},[]),this.previewElements=[]}resetSecondayPreviewElements(){this.screenPreviewElements.forEach(e=>{e.srcObject=null,e._playPromise=void 0},[]),this.screenPreviewElements=[]}getMediaStats(e){return this.pcMediaStatsMap[e]}reportPublishMonitor(e){if(!e)return;let t;try{t=e===D.Audio?this.rtsManager.getStreamByMsid({url:this.url,aMsid:e}).audioTrack:this.rtsManager.getStreamByMsid({url:this.url,vMsid:e}).videoTrack}catch(i){}this.slsReporter.reportPublishMonitor(this.callId,this.traceId||"",e,t,this.monitorDataCache[e]),this.monitorDataCache[e]=[]}reportNetwork(){this.slsReporter.reportNetworkMonitor(this.candidateDataCache),this.candidateDataCache=[]}startStreamMonitor(){this.monitorTimerId||(this.monitorTimerId=window.setInterval(()=>I(this,null,function*(){var e,i;try{const s=yield this.rtsManager.getPCStats();let n,c;if(s==null||s.forEach(l=>{l.type==="media-source"||l.type==="media-playout"?l.id&&(this.pcMediaStatsMap[l.id]=l):l.type==="candidate-pair"&&l.state==="succeeded"&&(n=l)}),((e=this.candidateDataCache)==null?void 0:e.length)>0){const l=this.candidateDataCache[this.candidateDataCache.length-1]||{},t=l,{_last:d}=t;c=Wt(t,["_last"])}((i=this.candidateDataCache)==null?void 0:i.length)>=30&&this.reportNetwork(),n&&(n._last=c,this.candidateDataCache.push(n));let o=Object.keys(this.monitorDataCache).filter(l=>{var d;return((d=this.monitorDataCache[l])==null?void 0:d.length)>0});(this.streamTracks||[]).forEach(l=>{const d=l.msid;if(!d)return;let u;o.includes(d)&&(o=o.filter(p=>p!==d)),u=d===D.Audio?this.rtsManager.getPublishAudioStats(this.url):this.rtsManager.getPublishVideoStats(this.url,d),u.then(p=>{if(!p.timestamp)return;this.monitorDataCache[d]||(this.monitorDataCache[d]=[]);const h=this.getMediaStats(p.mediaSourceId);p._source=h;const f=this.monitorDataCache[d];let g;if((f==null?void 0:f.length)>0){const S=f[f.length-1]||{},b=S,{_last:v}=b;g=Wt(b,["_last"])}(f==null?void 0:f.length)>=30&&this.reportPublishMonitor(d),p._last=g,p._codec=l.codec||"",this.monitorDataCache[d].push(p)})}),o.forEach(l=>{this.reportPublishMonitor(l)})}catch(s){}}),1e3))}stopStreamMonitor(){this.monitorTimerId&&(clearInterval(this.monitorTimerId),this.monitorTimerId=void 0),Object.keys(this.monitorDataCache).forEach(e=>{this.reportPublishMonitor(e)})}clearStream(){this.streamManager.stop(),this.audioPubState.setState(ee.AliRtcStatePublishIdle),this.videoPubState.setState(ee.AliRtcStatePublishIdle),this.videoSmallPubState.setState(ee.AliRtcStatePublishIdle),this.screenPubState.setState(ee.AliRtcStatePublishIdle)}getCurrentCameraDeviceId(){var e;return(e=this.streamManager.cameraStreamInfo.originVideoTrack)==null?void 0:e.getSettings().deviceId}getCurrentMicDeviceId(){var e;return(e=this.streamManager.cameraStreamInfo.originAudioTrack)==null?void 0:e.getSettings().deviceId}enableAudioVolumeIndication(e){this.audioVolumeIndicationInterval!==e&&(this.audioVolumeIndicationInterval>0&&e<=0&&this.audioLevelMonitor.stop(),e>0&&this.streamManager.cameraStreamInfo.originAudioTrack&&this.audioLevelMonitor.start(this.streamManager.cameraStreamInfo.originAudioTrack,e),this.audioVolumeIndicationInterval=e)}sendSEI(e,t,i){return I(this,null,function*(){if(!this.url)return;let s=0;return s=!t||t<1?1:t-1,this.rtsManager.sendSEI(this.url,e,s,i)})}sendDataChannelMessage(e){var i;if(!((i=this.parameter.data)!=null&&i.enablePubDataChannel))throw new U(B.ERR_INNER,"data channel publish is not enabled");if(!this.dc)throw new U(B.ERR_INNER,"data channel is not ready");const t=function(s,n){let c=0;const o=[];for(;c<s.byteLength;){const l=Math.min(n,s.byteLength-c),d=s.slice(c,c+l);o.push(d),c+=l}return o}(e.toBuffer(),1156);t.forEach((s,n)=>{const c=new Gi(new Ti(s.byteLength,n===t.length-1,n===0?1:0),s);this.dc.send(c.toGRTNBuffer())})}getStats(){return I(this,null,function*(){const e=[];if(this.hasAudioTrackInMS){const n=yield this.rtsManager.getPublishAudioStats(this.url);n&&e.push({stats:n,track:ti.AliRtcAudioTrackMic})}const t=[];if(this.hasCameraTrackInMS){const n=yield this.rtsManager.getPublishVideoStats(this.url,D.VideoLarge);n&&t.push({track:ue.AliRtcVideoTrackCamera,streamType:Ge.AliRtcVideoStreamTypeHigh,stats:n})}if(this.hasCameraDualTrackInMS){const n=yield this.rtsManager.getPublishVideoStats(this.url,D.VideoSmall);n&&t.push({track:ue.AliRtcVideoTrackCamera,streamType:Ge.AliRtcVideoStreamTypeLow,stats:n})}if(this.hasScreenTrackInMS){const n=yield this.rtsManager.getPublishVideoStats(this.url,D.Screen);n&&t.push({track:ue.AliRtcVideoTrackScreen,stats:n})}let i;const s=yield this.rtsManager.getPCStats();return s==null||s.forEach(n=>{n.type==="candidate-pair"&&n.state==="succeeded"&&(i=n)}),{audio:e,video:t,candidate:i}})}markReconnect(e){const t=[],i=this.streamManager.publishStreams;!i.audio||e&&!e.includes(D.Audio)||t.push(this.audioPubState),!i.video||e&&!e.includes(D.VideoLarge)||t.push(this.videoPubState),!i.screen||e&&!e.includes(D.Screen)||t.push(this.screenPubState),!this.dc||e&&!e.includes(D.Data)||t.push(this.dataPubState),t.forEach(s=>{s.setState(ee.AliRtcStateReconnecting)})}markReconnected(e){var s;const t=[],i=this.streamManager.publishStreams;if(!i.audio||e&&!e.includes(D.Audio)||t.push(this.audioPubState),!i.video||e&&!e.includes(D.VideoLarge)||t.push(this.videoPubState),!i.screen||e&&!e.includes(D.Screen)||t.push(this.screenPubState),this.dc&&(!e||e.includes(D.Data))&&(t.push(this.dataPubState),(s=this.parameter.data)==null?void 0:s.enablePubDataChannel)){const n=this.rtsManager.getDatachannelByMsid({url:this.url,msid:D.Data});this.updateDataChannel(n)}this.publishUpdate(Dt.RECONNECT),t.forEach(n=>{n.setState(ee.AliRtcStatePublished)})}},m(bt,"logName","LocalUser"),bt);De([k()],Ce.prototype,"clearPublishState",1),De([k()],Ce.prototype,"clear",1),De([k(H)],Ce.prototype,"startDefaultCameraAndMic",1),De([k()],Ce.prototype,"setViewConfig",1),De([k()],Ce.prototype,"startCameraCapture",1),De([k()],Ce.prototype,"stopCameraCapture",1),De([k()],Ce.prototype,"startAudioCapture",1),De([k()],Ce.prototype,"stopAudioCapture",1),De([k()],Ce.prototype,"startCameraAndMic",1),De([k()],Ce.prototype,"stopPreview",1),De([k()],Ce.prototype,"resumePublish",1),De([k()],Ce.prototype,"createLocalStream",1),De([k()],Ce.prototype,"stopLocalStream",1),De([k()],Ce.prototype,"updateDataChannel",1),De([k(H)],Ce.prototype,"startPublish",1),De([k()],Ce.prototype,"updateStreams",1),De([k(([a])=>[a])],Ce.prototype,"syncPublishToRoomServer",1),De([k()],Ce.prototype,"refreshPushStreamUrl",1),De([k(([a,r,e])=>[JSON.stringify(e)])],Ce.prototype,"publishAdd",1),De([k(([a,r])=>[JSON.stringify(r)])],Ce.prototype,"publishReplace",1),De([k(H)],Ce.prototype,"publishDeleteTracks",1),De([k()],Ce.prototype,"publishStop",1),De([k()],Ce.prototype,"unPublish",1),De([k(([a,r,e])=>[a.length,r,e])],Ce.prototype,"sendSEI",1),De([k(H)],Ce.prototype,"markReconnect",1),De([k(H)],Ce.prototype,"markReconnected",1);let Ec=Ce;var At=(a=>(a.OPUS="opus",a.H264="H264",a.H265="H265",a.AV1="AV1",a.UNKNOWN="",a))(At||{}),de=(a=>(a[a.NotSubscribe=0]="NotSubscribe",a[a.Subscribing=1]="Subscribing",a[a.Subscribed=2]="Subscribed",a))(de||{}),oi=(a=>(a.VideoTrackEnded="videoTrackEnded",a.AudioTrackEnded="audioTrackEnded",a.ScreenTrackEnded="screenTrackEnded",a))(oi||{});const Pn=a=>I(this,null,function*(){return yield J.AliRTS.createStream({custom:!0,mediaStream:a})}),ki=a=>I(this,null,function*(){const r=(e=>{const t=new MediaStream;return t.addTrack(e),t})(a);return yield Pn(r)});var Tc=Object.defineProperty,Cc=Object.getOwnPropertyDescriptor;class $s extends oe{constructor(){super();m(this,"audioInfo",{subscribeState:de.NotSubscribe,ssrc:"",msid:"",pt:0,red:0,codec:At.UNKNOWN});m(this,"videoLargeInfo",{subscribeState:de.NotSubscribe,ssrc:"",msid:"",pt:0,red:0,codec:At.UNKNOWN});m(this,"videoSmallInfo",{subscribeState:de.NotSubscribe,ssrc:"",msid:"",pt:0,red:0,codec:At.UNKNOWN});m(this,"screenInfo",{subscribeState:de.NotSubscribe,ssrc:"",msid:"",pt:0,red:0,codec:At.UNKNOWN});m(this,"dataInfo",{subscribeState:de.NotSubscribe,ssrc:"",msid:"",pt:0,red:0,codec:At.UNKNOWN});m(this,"audioVolume",1);m(this,"audioMuted",!1);m(this,"userStatus")}getAudioInfo(){return this.audioInfo}getVideoSmallInfo(){return this.videoSmallInfo}getVideoLargeInfo(){return this.videoLargeInfo}getScreenInfo(){return this.screenInfo}getDataInfo(){return this.dataInfo}get subscribingInfos(){return[this.audioInfo,this.videoLargeInfo,this.videoSmallInfo,this.screenInfo].filter(e=>e.msid&&e.subscribeState===de.Subscribed)}get hasTrack(){return this.hasAudio||this.hasVideo||this.hasScreen||this.hasData}get hasAudio(){return this.audioInfo.ssrc!==""}get hasVideo(){return this.videoLargeInfo.ssrc!==""||this.videoSmallInfo.ssrc!==""}get hasVideoLarge(){return this.videoLargeInfo.ssrc!==""}get hasVideoSmall(){return this.videoSmallInfo.ssrc!==""}get hasScreen(){return this.screenInfo.ssrc!==""}get hasData(){return this.dataInfo.ssrc!==""}get isAudioSubscribed(){return this.audioInfo.subscribeState===de.Subscribed}get isAudioSubscribing(){return this.audioInfo.subscribeState===de.Subscribing}get isVideoSubscribed(){return this.isVideoLargeSubscribed||this.isVideoSmallSubscribed}get isVideoSubscribing(){return this.isVideoLargeSubscribing||this.isVideoSmallSubscribing}get isVideoLargeSubscribed(){return this.videoLargeInfo.subscribeState===de.Subscribed}get isVideoLargeSubscribing(){return this.videoLargeInfo.subscribeState===de.Subscribing}get isVideoSmallSubscribed(){return this.videoSmallInfo.subscribeState===de.Subscribed}get isVideoSmallSubscribing(){return this.videoSmallInfo.subscribeState===de.Subscribing}get isScreenSubscribed(){return this.screenInfo.subscribeState===de.Subscribed}get isScreenSubscribing(){return this.screenInfo.subscribeState===de.Subscribing}get isDataSubscribed(){return this.dataInfo.subscribeState===de.Subscribed}get isDataSubscribing(){return this.dataInfo.subscribeState===de.Subscribing}get audioCodec(){return this.audioInfo.codec}get videoCodec(){return this.hasVideoLarge?this.videoLargeInfo.codec:this.hasVideoSmall?this.videoSmallInfo.codec:this.hasScreen?this.screenInfo.codec:At.UNKNOWN}get audioTrackInfo(){return this.hasAudio?ti.AliRtcAudioTrackMic:ti.AliRtcAudioTrackNo}get videoTrackInfo(){return this.hasVideo&&this.hasScreen?ue.AliRtcVideoTrackBoth:this.hasVideo?ue.AliRtcVideoTrackCamera:this.hasScreen?ue.AliRtcVideoTrackScreen:ue.AliRtcVideoTrackNo}updateTracks(e){let t="",i="",s="",n="",c="";return e?(e.forEach(o=>{var p;let l=At.UNKNOWN;const d=((p=o==null?void 0:o.attr)==null?void 0:p.reason)==="reconnect";if(o.userdata){const{codec:h}=JSON.parse(o.userdata);h&&(l=h)}var u;(u=o.msid)===D.Audio||u===os.Audio?(t=o.ssrc,this.audioInfo.msid=o.msid,this.audioInfo.codec=l,(d||this.audioInfo.ssrc!==t)&&(this.audioInfo.subscribeState=de.NotSubscribe)):(h=>h===D.VideoSmall)(o.msid)?(s=o.ssrc,this.videoSmallInfo.msid=o.msid,this.videoSmallInfo.codec=l,(d||this.videoSmallInfo.ssrc!==s)&&(this.videoSmallInfo.subscribeState=de.NotSubscribe)):(h=>h===D.VideoLarge||h===os.VideoLarge)(o.msid)?(i=o.ssrc,this.videoLargeInfo.msid=o.msid,this.videoLargeInfo.codec=l,(d||this.videoLargeInfo.ssrc!==i)&&(this.videoLargeInfo.subscribeState=de.NotSubscribe)):(h=>h===D.Screen)(o.msid)?(n=o.ssrc,this.screenInfo.msid=o.msid,this.screenInfo.codec=l,(d||this.screenInfo.ssrc!==n)&&(this.screenInfo.subscribeState=de.NotSubscribe)):(h=>h===D.Data)(o.msid)&&(c=o.ssrc,this.dataInfo.msid=o.msid,this.dataInfo.codec=l,(d||this.dataInfo.ssrc!==c)&&(this.dataInfo.subscribeState=de.NotSubscribe))}),this.updateRemoteTrackSsrc(t,i,s,n,c)):this.updateRemoteTrackSsrc(t,i,s,n,c),{}}updateRemoteTrackSsrc(e,t,i,s,n){this.audioInfo.ssrc=e,this.videoSmallInfo.ssrc=i,this.videoLargeInfo.ssrc=t,this.screenInfo.ssrc=s,this.dataInfo.ssrc=n}markRemoteTrackSubscribing(e){return e.video&&(e.vMsid===this.videoSmallInfo.msid&&(this.videoSmallInfo.subscribeState=de.Subscribing),e.vMsid!==this.videoLargeInfo.msid&&e.vMsid||(this.videoLargeInfo.subscribeState=de.Subscribing)),e.screen&&(this.screenInfo.subscribeState=de.Subscribing),e.audio&&(this.audioInfo.subscribeState=de.Subscribing),e.data&&(this.dataInfo.subscribeState=de.Subscribing),{videoLargeInfo:this.videoLargeInfo,videoSmallInfo:this.videoSmallInfo}}updateRemoteTrackSubState(e){return e.video!==void 0&&(e.vMsid===this.videoSmallInfo.msid&&(this.videoSmallInfo.subscribeState=e.video?de.Subscribed:de.NotSubscribe),e.vMsid!==this.videoLargeInfo.msid&&e.vMsid||(this.videoLargeInfo.subscribeState=e.video?de.Subscribed:de.NotSubscribe)),e.screen!==void 0&&(this.screenInfo.subscribeState=e.screen?de.Subscribed:de.NotSubscribe),e.audio!==void 0&&(this.audioInfo.subscribeState=e.audio?de.Subscribed:de.NotSubscribe),e.data!==void 0&&(this.dataInfo.subscribeState=e.data?de.Subscribed:de.NotSubscribe),{audioInfo:this.audioInfo,videoLargeInfo:this.videoLargeInfo,videoSmallInfo:this.videoSmallInfo,screenInfo:this.screenInfo,dataInfo:this.dataInfo}}updateRemoteUserDeviceStatus(e){let t=_n.parseStatus(e);const{audioDisable:i,videoDisable:s,screenDisable:n}=t;return this.userStatus?(this.userStatus.audioDisable!=i&&(this.userStatus.audioDisable=i,this.emit(ot.Remote,i?Me.MuteAudio:Me.UnmuteAudio)),this.userStatus.videoDisable!=s&&(this.userStatus.videoDisable=s,this.emit(ot.Remote,s?Me.MuteVideo:Me.UnmuteVideo)),this.userStatus.screenDisable!=n&&(this.userStatus.screenDisable=n,this.emit(ot.Remote,n?Me.MuteScreen:Me.UnmuteScreen))):(this.userStatus=t,this.emit(ot.Remote,i?Me.MuteAudio:Me.UnmuteAudio),this.emit(ot.Remote,s?Me.MuteVideo:Me.UnmuteVideo),this.emit(ot.Remote,n?Me.MuteScreen:Me.UnmuteScreen)),!1}}m($s,"logName","RemoteStreamInfo"),((a,r,e,t)=>{for(var i,s=t>1?void 0:t?Cc(r,e):r,n=a.length-1;n>=0;n--)(i=a[n])&&(s=(t?i(r,e,s):i(s))||s);t&&s&&Tc(r,e,s)})([k()],$s.prototype,"updateRemoteTrackSubState",1);class Dn{constructor(r){m(this,"remoteUser");this.remoteUser=r}get userId(){return this.remoteUser.userId}get displayName(){return this.remoteUser.displayname}get isMuteAudioPlaying(){return this.remoteUser.getAudioMuted()}get hasAudio(){return this.remoteUser.hasAudioTrack}get hasCamera(){return this.remoteUser.hasVideoTrack}get hasCameraLarge(){return this.remoteUser.hasVideoLargeTrack}get hasCameraSmall(){return this.remoteUser.hasVideoSmallTrack}get hasScreenShare(){return this.remoteUser.hasScreenTrack}get isAudioSubscribing(){return this.remoteUser.isAudioSubscribing}get isVideoSubscribing(){return this.remoteUser.isVideoSubscribing}get isVideoLargeSubscribing(){return this.remoteUser.isVideoLargeSubscribing}get isVideoSmallSubscribing(){return this.remoteUser.isVideoSmallSubscribing}get isScreenSubscribing(){return this.remoteUser.isScreenSubscribing}get audioElement(){return this.remoteUser.getAudioElement()}}var kc=Object.defineProperty,Pc=Object.getOwnPropertyDescriptor,Ke=(a,r,e,t)=>{for(var i,s=t>1?void 0:t?Pc(r,e):r,n=a.length-1;n>=0;n--)(i=a[n])&&(s=(t?i(r,e,s):i(s))||s);return t&&s&&kc(r,e,s),s};class fi extends oe{constructor(){super();m(this,"state");m(this,"time");m(this,"_enabled");this.state=ce.AliRtcStateSubscribeIdle,this.time=Date.now(),this._enabled=!0}setState(e){if(this.state===e)return;const t=this.state,i=this.time;this.state=e,this.time=Date.now(),this.emit("change",t,e,Math.floor((this.time-i)/1e3))}get currentState(){return this.state}getEnabled(){return this._enabled}setEnabled(e){this._enabled=e}}const We=(ui=class extends wn{constructor(e){var h;const{userId:t,displayName:i,rtsManager:s,usersViewMap:n,slsReporter:c,signalingManager:o,localUser:l,audioVolumeIndicationInterval:d,playoutVolume:u,parameter:p}=e;super(t,i,s,d);m(this,"remoteCallId","");m(this,"remoteUserInfo");m(this,"localUser");m(this,"lastPubId","");m(this,"stream");m(this,"screenStream");m(this,"viewMap");m(this,"audioTrack");m(this,"audioElement");m(this,"subscribed",!1);m(this,"mediaStream");m(this,"secondaryMediaStream");m(this,"prevSubConfig");m(this,"signalingManager");m(this,"slsReporter");m(this,"wantSubAudio",!1);m(this,"wantSubVideo",!1);m(this,"wantSubScreen",!1);m(this,"defaultVideoStreamType",Ge.AliRtcVideoStreamTypeHigh);m(this,"audioMuted",!1);m(this,"playoutVolume",1);m(this,"playoutGainNode");m(this,"audioSubState");m(this,"videoSubState");m(this,"videoLargeSubState",new fi);m(this,"videoSmallSubState",new fi);m(this,"screenSubState");m(this,"dataSubState");m(this,"dc");m(this,"dcMsgWaitingPieces",[]);m(this,"streamInfo");m(this,"_streamUrl","");m(this,"parameter",{});m(this,"_audioResumeHandler",null);m(this,"_videoResumeHandler",null);m(this,"monitorTimerId");m(this,"monitorDataCache",{});m(this,"traceId","");m(this,"handleAudioContextSuspended",e=>{e.target.state==="suspended"&&this.emit("remoteAudioPlayError",this.uid,"AudioContext suspended")});m(this,"onDataChannelMessage",e=>{var s;const t=Gi.parse(e.slice(4));let i;if(t.body){if(!t.isFin)return t.header.frameType===1&&(this.dcMsgWaitingPieces=[]),void this.dcMsgWaitingPieces.push(t.body);if(this.dcMsgWaitingPieces.length>0){const n=this.dcMsgWaitingPieces.reduce((c,o)=>c+o.byteLength,t.body.byteLength);try{const c=new ArrayBuffer(n);let o=0;for(let l=0;l<this.dcMsgWaitingPieces.length;l++){const d=this.dcMsgWaitingPieces[l];new Uint8Array(c,o,d.byteLength).set(new Uint8Array(d)),o+=d.byteLength}new Uint8Array(c,o,t.body.byteLength).set(new Uint8Array(t.body)),i=Jt.parse(c)}catch(c){}this.dcMsgWaitingPieces=[],i||(i=Jt.parse(t.body))}else i=Jt.parse(t.body);i||T.event(`[${this.logName}]`,`parse data channel message fail, piece count: ${this.dcMsgWaitingPieces.length+1}`)}i&&(T.event(`[${this.logName}]`,`receive dc message, length(${(s=i.data)==null?void 0:s.byteLength})`),this.emit("remoteDataChannelMessage",this.uid,i))});m(this,"onDataChannelError",e=>{this.emit("occurError",U.fromError(e,B.ERR_SDK_SUBSCRIBE_DATA_ERROR))});m(this,"dataChannelConnected",e=>{e&&(this.dc=e,this.dc.datachannel&&(this.dc.datachannel.binaryType="arraybuffer"),this.dc.off("message",this.onDataChannelMessage),this.dc.off("error",this.onDataChannelError),this.dc.on("message",this.onDataChannelMessage),this.dc.on("error",this.onDataChannelError))});m(this,"handleAudioPaused",()=>{this.emit("remoteAudioPlayError",this.uid,"paused")});this.streamInfo=new $s,this.remoteUserInfo=new Dn(this),this.parameter=p,this.streamInfo.on(ot.Remote,f=>{this.emit(ot.Remote,f,this.userId)}),this.signalingManager=o,this.viewMap=(h=n[t])!=null?h:{cameraViews:[],screenViews:[]},n[t]=this.viewMap,this.slsReporter=c,this.localUser=l,this.audioSubState=new fi,this.audioSubState.on("change",(f,g,b)=>{this.emit("audioSubscribeStateChanged",this.uid,f,g,b)}),this.videoSubState=new fi,this.videoSubState.on("change",(f,g,b)=>{this.emit("videoSubscribeStateChanged",this.uid,f,g,b)}),this.screenSubState=new fi,this.screenSubState.on("change",(f,g,b)=>{this.emit("screenSubscribeStateChanged",this.uid,f,g,b)}),this.dataSubState=new fi,this.dataSubState.on("change",(f,g,b)=>{this.emit("dataSubscribeStateChanged",this.uid,f,g,b)}),this.playoutVolume=u}get logName(){return`${ui.logName}(${this.userId})`}get streamUrl(){return this._streamUrl}set streamUrl(e){this._streamUrl=e,this.rtsManager.updateAuth(e)}isWantSubAudio(){return this.wantSubAudio}setWantSubAudio(e){this.wantSubAudio=e}isWantSubVideo(){return this.wantSubVideo}setWantSubVideo(e){this.wantSubVideo=e}isWantSubScreen(){return this.wantSubScreen}setWantSubScreen(e){this.wantSubScreen=e}setRemoteDefaultVideoStreamType(e){e!==this.defaultVideoStreamType&&(this.defaultVideoStreamType=e,this.updateSubscribe(ge.User))}setAudioMuted(e){this.audioMuted=e,this.toggleAudio(!e)}getAudioElement(){return this.audioElement}setPlayoutVolume(e){if(this.playoutVolume=e,this.audioElement)if(this.parameter.enableAudioContextPlayoutVolume)if(this.playoutGainNode)this.playoutGainNode.gain.value=e;else{const t=this.audioElement.srcObject;if(t){const i=yt.getInstance();i.addEventListener("statechange",this.handleAudioContextSuspended);const s=i.createMediaStreamSource(t);this.audioElement.muted=!0,this.playoutGainNode=i.createGain(),s.connect(this.playoutGainNode),this.playoutGainNode.gain.value=e,this.playoutGainNode.connect(i.destination)}}else this.audioElement.volume=e}getAudioMuted(){return this.audioMuted}get hasAudioTrack(){return this.streamInfo.hasAudio}get audioSSRC(){var e;return this.streamInfo.isAudioSubscribed&&((e=this.streamInfo.getAudioInfo())==null?void 0:e.ssrc)||""}get hasVideoTrack(){return this.streamInfo.hasVideo}get videoSSRC(){var e,t;return this.streamInfo.isVideoSubscribed?((e=this.streamInfo.getVideoLargeInfo())==null?void 0:e.ssrc)||"":this.streamInfo.isVideoSmallSubscribed&&((t=this.streamInfo.getVideoSmallInfo())==null?void 0:t.ssrc)||""}get hasVideoLargeTrack(){return this.streamInfo.hasVideoLarge}get hasVideoSmallTrack(){return this.streamInfo.hasVideoSmall}get hasScreenTrack(){return this.streamInfo.hasScreen}get isAudioSubscribing(){return this.streamInfo.isAudioSubscribed||this.streamInfo.isAudioSubscribing}get isVideoSubscribing(){return this.streamInfo.isVideoSubscribed||this.streamInfo.isVideoSubscribing}get isVideoLargeSubscribing(){return this.streamInfo.isVideoLargeSubscribed||this.streamInfo.isVideoLargeSubscribing}get isVideoSmallSubscribing(){return this.streamInfo.isVideoSmallSubscribed||this.streamInfo.isVideoSmallSubscribing}get isScreenSubscribing(){return this.streamInfo.isScreenSubscribed||this.streamInfo.isScreenSubscribing}get isDataSubscribing(){return this.streamInfo.isDataSubscribed||this.streamInfo.isDataSubscribing}get audioEnabled(){var e,t;return!!((t=(e=this.stream)==null?void 0:e.audioTrack)!=null&&t.enabled)}get videoEnabled(){var e,t;return!!((t=(e=this.stream)==null?void 0:e.videoTrack)!=null&&t.enabled)}get screenEnabled(){var e,t;return!!((t=(e=this.screenStream)==null?void 0:e.videoTrack)!=null&&t.enabled)}get getAudioTrack(){return this.audioTrack}get getCameraStream(){return this.stream}get getScreenStream(){return this.screenStream}setViewConfig(e,t){if(t!==ue.AliRtcVideoTrackScreen&&t!==ue.AliRtcVideoTrackCamera)throw new U(B.ERR_INVALID_ARGUMENTS,"track is not AliRtcVideoTrackScreen or AliRtcVideoTrackCamera");e?cs(e).forEach(i=>{i.setAttribute("playsinline",""),J.AliRTS.BrowserUtil.isMicroMessenger&&(i.setAttribute("x5-video-player-type","h5-page"),i.setAttribute("x5-playsinline",""),J.AliRTS.SystenUtil.isAndroid||J.AliRTS.SystenUtil.isIos&&i.setAttribute("x-webkit-airplay","allow")),t===ue.AliRtcVideoTrackScreen?this.viewMap.screenViews.push(i):this.viewMap.cameraViews.push(i),this.play(i,t===ue.AliRtcVideoTrackScreen)}):(this.stopPlayAll(t===ue.AliRtcVideoTrackScreen),t===ue.AliRtcVideoTrackScreen?this.viewMap.screenViews=[]:this.viewMap.cameraViews=[])}clear(e=!0){return I(this,null,function*(){var t,i,s,n;ur(ui.prototype,this,"clear").call(this),this._removeAudioResumeHandler(),this._removeVideoResumeHandler(),this.stopPlayAudio(),this.stopStreamMonitor(),e&&this.subscribeDeleteAllTracks(this.streamUrl).catch(c=>{T.event(`[${this.logName}]`,`stopSubscribeAllTracks error: ${c.message||c}`)}),this.clearStream(),this.clearScreenStream(),this.playoutGainNode&&(this.playoutGainNode.disconnect(),this.playoutGainNode=void 0,yt.getInstance().removeEventListener("statechange",this.handleAudioContextSuspended)),this.streamInfo.removeAllListeners(),(t=this.audioSubState)==null||t.removeAllListeners(),(i=this.videoSubState)==null||i.removeAllListeners(),(s=this.screenSubState)==null||s.removeAllListeners(),(n=this.dataSubState)==null||n.removeAllListeners()})}updateRemoteUserDeviceStatus(e){this.streamInfo.updateRemoteUserDeviceStatus(e)}updateRemoteTracks(e,t,i,s){return I(this,null,function*(){return this.remoteCallId=e,this.streamUrl&&this.streamInfo.hasTrack||(this.streamUrl=t),this.streamInfo.updateTracks(s)})}subscribe(s,n){return I(this,arguments,function*(e,t,i=Date.now()){var h,f;this.createCallId();let c=e;if(!c){const{hasAudio:g,hasVideo:b,hasScreen:S,hasData:v}=(h=this.streamInfo)!=null?h:{};c={audio:this.wantSubAudio&&g,video:this.wantSubVideo&&b,screen:this.wantSubScreen&&S,data:((f=this.parameter.data)==null?void 0:f.enableSubDataChannel)&&v}}this.streamInfo.markRemoteTrackSubscribing(c);const{screen:o,audio:l,video:d,vMsid:u}=c,p=[];(d||l)&&p.push({audio:l,video:d,vMsid:u}),o&&p.push({screen:o}),(p.length!==0||e!=null&&e.data)&&(yield Promise.all(p.map(g=>this.subscribeProxy(g,t||ge.User,i))),e!=null&&e.data&&this.subscribeDataChannel())})}subscribeProxy(e,t,i){return I(this,null,function*(){var c,o;let s=new Date().getTime(),n="";if(this.streamUrl)try{e.audio&&this.audioSubState.setState(ce.AliRtcStateSubscribing),e.video&&(this.videoSubState.currentState!==ce.AliRtcStateSubscribeIdle&&this.videoSubState.currentState!==ce.AliRtcStateNoSubscribe||this.videoSubState.setState(ce.AliRtcStateSubscribing)),e.screen&&this.screenSubState.setState(ce.AliRtcStateSubscribing);const l=yield this.rtsManager.subscribe({remoteUser:this,options:e},t,((c=this.localUser)==null?void 0:c.callId)||"",this.callId,i);if(!l)return e.audio&&this.audioSubState.setState(ce.AliRtcStateNoSubscribe),e.video&&this.videoSubState.setState(ce.AliRtcStateNoSubscribe),e.screen&&this.screenSubState.setState(ce.AliRtcStateNoSubscribe),this.streamInfo.updateRemoteTrackSubState({audio:e.audio!==!0&&void 0,video:e.video!==!0&&void 0,screen:e.screen!==!0&&void 0,vMsid:e.vMsid}),void _e.getInstance().addEventData(_e.eventSubError,this.uid,e.audio,e.video);this.streamInfo.updateRemoteTrackSubState(e),n=l.traceId||"";const{stream:d}=l;if(n&&(this.traceId=n),e.audio){const h=d.audioTrack;h&&(this.audioTrack=h,(o=d.mediaStream)==null||o.removeTrack(h),this.playAudio(),this.audioVolumeIndicationInterval&&this.audioLevelMonitor.start(h,this.audioVolumeIndicationInterval)),this.audioSubState.getEnabled()||this.toggleAudio(!1),this.audioSubState.setState(ce.AliRtcStateSubscribed)}e.video&&(this.updateStream(d,this.isVideoLargeSubscribing&&this.isVideoSmallSubscribing),this.videoSubState.getEnabled()||this.toggleVideo(!1),this.videoSubState.setState(ce.AliRtcStateSubscribed),e.vMsid===D.VideoSmall?this.videoSmallSubState.setState(ce.AliRtcStateSubscribed):this.videoLargeSubState.setState(ce.AliRtcStateSubscribed)),e.screen&&(this.updateScreenStream(d),this.videoSubState.getEnabled()||this.toggleScreen(!1),this.screenSubState.setState(ce.AliRtcStateSubscribed));const u=new Date().getTime()-s,p=Date.now();setTimeout(()=>I(this,null,function*(){const h=yield this.rtsManager.getGatewayIp();this.slsReporter.reportSubscribe(this.callId,this.remoteCallId,!!e.video&&e.vMsid===D.VideoLarge,!!e.video&&e.vMsid===D.VideoSmall,!!e.screen,!!e.audio,0,"",u,{pctid:this.rtsManager.pcTraceId,subtid:this.traceId,ajsub:t===ge.Join?1:0,url:this.streamUrl,est:s,gi:h},p)}),6e3),this.startStreamMonitor(),l.isHTTP&&l.statsCheckPromise&&(yield Promise.race([l.statsCheckPromise,Ht(1500)])),_e.getInstance().addEventData(_e.eventSubSuccess,this.uid,e.audio,e.video)}catch(l){const d=new Date().getTime()-s;e.audio&&this.audioSubState.setState(ce.AliRtcStateNoSubscribe),e.video&&this.videoSubState.setState(ce.AliRtcStateNoSubscribe),e.screen&&this.screenSubState.setState(ce.AliRtcStateNoSubscribe),this.streamInfo.updateRemoteTrackSubState({audio:e.audio!==!0&&void 0,video:e.video!==!0&&void 0,screen:e.screen!==!0&&void 0,vMsid:e.vMsid}),l&&(l.message=`user(${this.uid}) subscribe error, ${(l==null?void 0:l.message)||""}`);let u=B.ERR_INNER;e.audio&&(u=B.ERR_SDK_SUBSCRIBE_AUDIO_STREAM_FAILED),e.video&&(u=e.vMsid===D.VideoSmall?B.ERR_SDK_SUBSCRIBE_DUAL_STREAM_FAILED:B.ERR_SDK_SUBSCRIBE_VIDEO_STREAM_FAILED),e.screen&&(u=B.ERR_SDK_SUBSCRIBE_SCREEN_SHARE_FAILED);const p=yield this.rtsManager.getGatewayIp();this.slsReporter.reportSubscribe(this.callId,this.remoteCallId,!!e.video&&e.vMsid===D.VideoLarge,!!e.video&&e.vMsid===D.VideoSmall,!!e.screen,!!e.audio,u,"",d,{pctid:this.rtsManager.pcTraceId,subtid:"",ajsub:t===ge.Join?1:0,url:this.streamUrl,est:s,gi:p});const h=U.fromError(l,u);this.emit("remoteSubscribeError",h)}else{const l=new U(B.ERR_SDK_SUBSCRIBE_INVAILD,`user(${this.uid}) subscribe failed: streamUrl is not ready. Please subscribe after receiving 'remoteTrackAvailableNotify' event instead of 'remoteUserOnLineNotify'.`);this.emit("remoteSubscribeError",l)}})}subscribeDeleteTracks(e){return I(this,null,function*(){const{audio:t,video:i,screen:s,data:n,vMsid:c}=e,o=[];(t||i||n)&&o.push({audio:t,video:i,vMsid:c}),s&&o.push({screen:s}),o.length!==0&&(yield Promise.all(o.map(l=>this.subscribeDeleteProxy(l))),e.data&&this.subscribeDeleteDataChannel())})}subscribeDeleteProxy(e){return I(this,null,function*(){try{const t=yield this.rtsManager.subscribeDelete({remoteUser:this,options:e}),{stream:i}=t!=null?t:{},s={};e.audio===!0&&(s.audio=!1,this.audioSubState.setState(ce.AliRtcStateNoSubscribe)),e.video===!0&&(s.video=!1,e.vMsid===D.VideoSmall?(this.videoSmallSubState.setState(ce.AliRtcStateNoSubscribe),this.videoLargeSubState.currentState!==ce.AliRtcStateNoSubscribe&&this.videoLargeSubState.currentState!==ce.AliRtcStateSubscribeIdle||this.videoSubState.setState(ce.AliRtcStateNoSubscribe)):(this.videoLargeSubState.setState(ce.AliRtcStateNoSubscribe),this.videoSmallSubState.currentState!==ce.AliRtcStateNoSubscribe&&this.videoSmallSubState.currentState!==ce.AliRtcStateSubscribeIdle||this.videoSubState.setState(ce.AliRtcStateNoSubscribe))),e.screen===!0&&(s.screen=!1,this.screenSubState.setState(ce.AliRtcStateNoSubscribe));const{callId:n,remoteCallId:c}=this,o={callid:n,remoteCallid:c,remoteStream:i};return e.audio&&(this.audioLevelMonitor.stop(),this.stopPlayAudio(),this.audioTrack=void 0),this.streamInfo.updateRemoteTrackSubState({audio:e.audio!==!0&&void 0,video:e.video!==!0&&void 0,screen:e.screen!==!0&&void 0,vMsid:e.vMsid}),o}catch(t){throw U.fromError(t,B.ERR_INNER,"subscribe delete failed")}})}restore(){this.callId="",this.clearStream(),this.clearScreenStream(),this.audioTrack=void 0,this.streamInfo.updateRemoteTrackSubState({audio:!1,video:!1,screen:!1,data:!1}),this.audioElement&&this.audioElement.removeEventListener("pause",this.handleAudioPaused)}resumeAudio(){return I(this,null,function*(){const e=yt.getInstance();return e.state!=="running"&&e.resume(),this.audioElement?this.audioElement.play():this.playAudio()})}resumeVideo(e){return I(this,null,function*(){return e&&e!==ue.AliRtcVideoTrackCamera&&e!==ue.AliRtcVideoTrackBoth?e&&e!==ue.AliRtcVideoTrackScreen&&e!==ue.AliRtcVideoTrackBoth?void 0:this.playAll(!0):this.playAll()})}resumePlay(){this.playAudio(),this.playAll(),this.playAll(!0)}stopSubscribe(e){return I(this,null,function*(){let t=new Date().getTime();try{e?yield this.subscribeDeleteTracks(e):yield this.subscribeDeleteAllTracks(this.streamUrl),this.slsReporter.reportUnsubscribe(this.callId,this.remoteCallId,new Date().getTime()-t,0,"")}catch(i){throw this.slsReporter.reportUnsubscribe(this.callId,this.remoteCallId,new Date().getTime()-t,0,""),i}})}subscribeDeleteAllTracks(e){return I(this,null,function*(){var s,n,c,o;const{callId:t,remoteCallId:i}=this;if((this.isAudioSubscribing||this.isVideoSubscribing||this.isScreenSubscribing||this.dc)&&e)try{yield this.subscribeDeleteTracks({audio:this.isAudioSubscribing,video:this.isVideoSubscribing,screen:this.isScreenSubscribing,data:!!this.dc}),this.restore();const l={callid:t,remoteCallid:i,remoteStream:this.stream};return this.callId="",l}catch(l){if(((o=(c=(n=(s=l==null?void 0:l.extraInfo)==null?void 0:s.parsedData)==null?void 0:n.streams)==null?void 0:c[0])==null?void 0:o.res_code)!==404)throw U.fromError(l,B.ERR_INNER,"subscribe stop failed")}})}updateStream(e,t=!1){return I(this,null,function*(){this.stream&&this.stream.videoTrack&&e.mediaStream&&t&&(yield new Promise(i=>{let s,n;if(e.mediaStream){n=document.createElement("video");const c=()=>{T.event(`[${this.logName}]`,"new mediaStream canplay"),n&&n.removeEventListener("canplaythrough",c,!1),n=void 0,clearTimeout(s),i(!0)};n.addEventListener("canplaythrough",c,!1),(n._playPromise||Promise.resolve()).then(()=>{n&&e.mediaStream&&(n.srcObject=e.mediaStream)})}else i(!0);s=window.setTimeout(()=>{T.event(`[${this.logName}]`,"new mediaStream timeout"),n=void 0,i(!0)},3e3)}),this.updateSubscribe(ge.User)),this.stream=e,this.playAll(!1,t),!this.subscribed&&e&&(this.subscribed=!0),e.hasAudio&&this.isAudioSubscribing&&e.enableAudio(),e.hasVideo&&this.isVideoSubscribing&&e.enableVideo()})}updateScreenStream(e){this.screenStream=e,this.playAll(!0),!this.subscribed&&e&&(this.subscribed=!0),e.hasVideo&&this.isScreenSubscribing&&e.enableVideo()}clearStream(){var e;(e=this.stream)==null||e.stop(),this.stream=void 0}clearScreenStream(){var e;(e=this.screenStream)==null||e.stop(),this.screenStream=void 0}subscribeDataChannel(){var e;if(this.dc)try{this.dcMsgWaitingPieces=[],this.dc.off("message",this.onDataChannelMessage),this.dc=void 0}catch(t){}if(!((e=this.parameter.data)!=null&&e.enablePubSubDataWithoutMedia||this.streamInfo.hasAudio||this.streamInfo.hasVideo||this.streamInfo.hasScreen))return this.dataSubState.setState(ce.AliRtcStateNoSubscribe),void this.streamInfo.updateRemoteTrackSubState({data:!1});this.dataSubState.setState(ce.AliRtcStateSubscribing),this.rtsManager.subscribeAddDataChannel(this.streamUrl).then(t=>{if(t)return this.dataChannelConnected(t),this.dataSubState.setState(ce.AliRtcStateSubscribed),void this.streamInfo.updateRemoteTrackSubState({data:!0});throw new Error("no dc founded")}).catch(t=>{const i=U.fromError(t,B.ERR_INNER,"subscribe data failed");this.emit("remoteSubscribeError",i),this.dataSubState.setState(ce.AliRtcStateNoSubscribe),this.streamInfo.updateRemoteTrackSubState({data:!1})})}subscribeDeleteDataChannel(){if(this.dc){try{this.rtsManager.subscribeDeleteDatachannel(this.streamUrl,this.dc)}catch(e){}this.dcMsgWaitingPieces=[],this.dc.off("message",this.onDataChannelMessage),this.dc.off("error",this.onDataChannelError),this.dataSubState.setState(ce.AliRtcStateNoSubscribe),this.dc=void 0,this.streamInfo.updateRemoteTrackSubState({data:!1})}}getRetryOptions(){var i,s;const e={};this.wantSubAudio&&this.streamInfo.hasAudio&&(e.audio=!0,e.aMsid=((i=this.streamInfo.getAudioInfo())==null?void 0:i.msid)||D.Audio),this.wantSubVideo&&this.streamInfo.hasVideo&&(this.defaultVideoStreamType===Ge.AliRtcVideoStreamTypeLow&&this.streamInfo.hasVideoSmall?(e.video=!0,e.vMsid=D.VideoSmall):this.streamInfo.hasVideoLarge&&(e.video=!0,e.vMsid=((s=this.streamInfo.getVideoLargeInfo())==null?void 0:s.msid)||D.VideoLarge)),this.wantSubScreen&&this.streamInfo.hasScreen&&(e.screen=!0);let t={};if(e.audio||e.video)t={audio:e.audio,video:e.video},this.streamInfo.updateRemoteTrackSubState({screen:!1,data:!1});else{if(!e.screen)return;t={screen:e.screen},this.streamInfo.updateRemoteTrackSubState({data:!1})}return{remoteUser:this,options:t}}updateSubscribe(e){var n,c,o,l,d,u;const t=Date.now(),i={},s={};return this.wantSubAudio&&!this.isAudioSubscribing&&this.streamInfo.hasAudio&&this.audioSubState.currentState!==ce.AliRtcStateReconnecting?(i.audio=!0,i.aMsid=((n=this.streamInfo.getAudioInfo())==null?void 0:n.msid)||D.Audio):this.wantSubAudio&&this.streamInfo.hasAudio||!this.isAudioSubscribing||(s.audio=!0,s.aMsid=((c=this.streamInfo.getAudioInfo())==null?void 0:c.msid)||D.Audio),this.wantSubVideo&&this.streamInfo.hasVideo?(this.defaultVideoStreamType===Ge.AliRtcVideoStreamTypeLow&&!this.isVideoSmallSubscribing&&this.streamInfo.hasVideoSmall&&this.videoSmallSubState.currentState!==ce.AliRtcStateReconnecting?(i.video=!0,i.vMsid=D.VideoSmall):this.isVideoLargeSubscribing||!this.streamInfo.hasVideoLarge||this.defaultVideoStreamType===Ge.AliRtcVideoStreamTypeLow&&this.isVideoSmallSubscribing&&this.streamInfo.hasVideoSmall||this.videoLargeSubState.currentState===ce.AliRtcStateReconnecting||(i.video=!0,i.vMsid=((o=this.streamInfo.getVideoLargeInfo())==null?void 0:o.msid)||D.VideoLarge),this.defaultVideoStreamType===Ge.AliRtcVideoStreamTypeLow&&this.isVideoLargeSubscribing&&this.isVideoSmallSubscribing&&this.streamInfo.hasVideoSmall?(s.video=!0,s.vMsid=D.VideoLarge):this.defaultVideoStreamType!==Ge.AliRtcVideoStreamTypeHigh&&this.streamInfo.hasVideoSmall||!this.isVideoLargeSubscribing||!this.isVideoSmallSubscribing||(s.video=!0,s.vMsid=D.VideoSmall)):this.wantSubVideo&&this.streamInfo.hasVideo||!this.isVideoSubscribing||(s.video=!0,s.vMsid=this.streamInfo.isVideoSmallSubscribed||this.streamInfo.isVideoSmallSubscribing?D.VideoSmall:((l=this.streamInfo.getVideoLargeInfo())==null?void 0:l.msid)||D.VideoLarge),this.wantSubScreen&&!this.isScreenSubscribing&&this.streamInfo.hasScreen&&this.screenSubState.currentState!==ce.AliRtcStateReconnecting?i.screen=!0:this.wantSubScreen&&this.streamInfo.hasScreen||!this.isScreenSubscribing||(s.screen=!0),(d=this.parameter.data)!=null&&d.enableSubDataChannel&&!this.isDataSubscribing&&this.streamInfo.hasData&&this.dataSubState.currentState!==ce.AliRtcStateReconnecting?i.data=!0:(u=this.parameter.data)!=null&&u.enableSubDataChannel&&this.streamInfo.hasData||!this.isDataSubscribing||(s.data=!0),this.dc&&i.data&&this.subscribeDeleteDataChannel(),(i.audio||i.video||i.screen||i.data)&&this.subscribe(i,e,t),(s.audio||s.video||s.screen)&&this.subscribeDeleteTracks(s),{addOption:i,deleteOption:s}}handleAutoPlayFailed(){T.event(`[${this.logName}]`,"auto play failed"),this.emit("remoteAudioAutoPlayFail",this.uid),this._removeAudioResumeHandler();const e=()=>{this.resumeAudio().finally(()=>{this._removeAudioResumeHandler()})};this._audioResumeHandler=e,document.addEventListener("click",e,!1),document.addEventListener("touchstart",e,!1)}_removeAudioResumeHandler(){this._audioResumeHandler&&(document.removeEventListener("click",this._audioResumeHandler,!1),document.removeEventListener("touchstart",this._audioResumeHandler,!1),this._audioResumeHandler=null)}handleVideoPlayFailded(e,t){this.emit("remoteVideoAutoPlayFail",this.uid,t),this._removeVideoResumeHandler();const i=()=>{var n;const s=(n=t===ue.AliRtcVideoTrackScreen?this.screenStream:this.stream)==null?void 0:n.mediaStream;e.srcObject===s&&this.play(e,t===ue.AliRtcVideoTrackScreen),this._removeVideoResumeHandler()};this._videoResumeHandler=i,document.addEventListener("click",i,!1),document.addEventListener("touchstart",i,!1)}_removeVideoResumeHandler(){this._videoResumeHandler&&(document.removeEventListener("click",this._videoResumeHandler,!1),document.removeEventListener("touchstart",this._videoResumeHandler,!1),this._videoResumeHandler=null)}playAudio(){return I(this,null,function*(){var e,t;if(this.audioTrack){if(this.toggleAudio(!this.audioMuted),this.audioElement||(T.event(`[${this.logName}]`,"create audio element"),this.audioElement=document.createElement("audio"),this.audioElement.setAttribute("autoplay","autoplay"),this.audioElement.addEventListener("pause",this.handleAudioPaused),this.setPlayoutVolume(this.playoutVolume)),((t=(e=this.audioElement.srcObject)==null?void 0:e.getAudioTracks())==null?void 0:t[0])!==this.audioTrack){let i=this.audioElement.srcObject;i?i.getAudioTracks().forEach(s=>{i.removeTrack(s)}):(i=new MediaStream,this.audioElement.srcObject=i),i.addTrack(this.audioTrack)}if(J.AliRTS.SystenUtil.isIos&&parseInt(J.AliRTS.SystenUtil.systemVersion)<=13){T.event(`[${this.logName}]`,"play audio for iOS 13-");const i=this.audioElement;i.setAttribute("autoplay","");const s=()=>{i.removeEventListener("playing",s),i.pause(),i.play().catch(()=>{this.handleAutoPlayFailed()})};this.audioElement.addEventListener("playing",s)}else(()=>{var i;T.event(`[${this.logName}]`,"try play audio"),(i=this.audioElement)==null||i.play().then(()=>{_e.getInstance().addEventData(_e.eventFirstAudio,this.uid),T.event(`[${this.logName}]`,"play audio success")}).catch(()=>{this.handleAutoPlayFailed()})})()}else T.event(`[${this.logName}]`,"audio track is null")})}stopPlayAudio(){this.audioElement&&(this.audioElement.pause(),this.audioElement.removeEventListener("pause",this.handleAudioPaused))}playAll(e=!1,t=!1){e?(this.viewMap.screenViews||[]).forEach(i=>{this.play(i,e,t)}):(this.viewMap.cameraViews||[]).forEach(i=>{this.play(i,e,t)})}play(e,t=!1,i=!1){const s=t?this.screenStream:this.stream;e&&s&&s.mediaStream&&Cn(e,s.mediaStream,i).catch(n=>{n.code!==20&&n.name!=="AbortError"&&this.handleVideoPlayFailded(e,t?ue.AliRtcVideoTrackScreen:ue.AliRtcVideoTrackCamera)})}stopPlayAll(e=!1){e?this.viewMap.screenViews.forEach(t=>{Mt(t)}):this.viewMap.cameraViews.forEach(t=>{Mt(t)})}toggleAudio(e=!0){this.audioSubState.setEnabled(e),this.audioElement&&(this.audioElement.muted=!e)}toggleVideo(e=!0){this.videoSubState.setEnabled(e),this.stream&&(e?this.stream.enableVideo():this.stream.disableVideo())}toggleScreen(e=!0){this.screenSubState.setEnabled(e),this.screenStream&&(e?this.screenStream.enableVideo():this.screenStream.disableVideo())}getStats(){return I(this,null,function*(){var i,s,n;const e=[];if(this.isAudioSubscribing){const c=yield this.rtsManager.getSubscribeAudioStats(this.streamUrl);c&&e.push({uid:this.uid,track:ti.AliRtcAudioTrackMic,stats:c})}const t=[];if(this.streamInfo.isVideoLargeSubscribed){const c=yield this.rtsManager.getSubscribeVideoStats(this.streamUrl,((i=this.streamInfo.getVideoLargeInfo())==null?void 0:i.msid)||D.VideoLarge);c&&t.push({uid:this.uid,track:ue.AliRtcVideoTrackCamera,streamType:Ge.AliRtcVideoStreamTypeHigh,stats:c})}if(this.streamInfo.isVideoSmallSubscribed){const c=yield this.rtsManager.getSubscribeVideoStats(this.streamUrl,((s=this.streamInfo.getVideoSmallInfo())==null?void 0:s.msid)||D.VideoSmall);c&&t.push({uid:this.uid,track:ue.AliRtcVideoTrackCamera,streamType:Ge.AliRtcVideoStreamTypeLow,stats:c})}if(this.isScreenSubscribing){const c=yield this.rtsManager.getSubscribeVideoStats(this.streamUrl,((n=this.streamInfo.getScreenInfo())==null?void 0:n.msid)||D.Screen);c&&t.push({uid:this.uid,track:ue.AliRtcVideoTrackScreen,stats:c})}return{audio:e,video:t}})}enableAudioVolumeIndication(e){this.audioVolumeIndicationInterval!==e&&(this.audioVolumeIndicationInterval>0&&e<=0&&this.audioLevelMonitor.stop(),e>0&&this.audioTrack&&this.audioLevelMonitor.start(this.audioTrack,e),this.audioVolumeIndicationInterval=e)}reportSubscribeMonitor(e){e&&(this.slsReporter.reportSubscribeMonitor(this.callId,this.remoteCallId,this.traceId,e,this.monitorDataCache[e]),this.monitorDataCache[e]=[])}startStreamMonitor(){this.monitorTimerId||(this.monitorTimerId=window.setInterval(()=>I(this,null,function*(){try{if(this.streamInfo.subscribingInfos.length===0)return void this.stopStreamMonitor();let e=Object.keys(this.monitorDataCache).filter(t=>{var i;return((i=this.monitorDataCache[t])==null?void 0:i.length)>0});this.streamInfo.subscribingInfos.forEach(t=>{const i=t.msid;if(!i)return;let s;e.includes(i)&&(e=e.filter(c=>c!==i));const n=i===D.Audio;s=n?this.rtsManager.getSubscribeAudioStats(this.streamUrl):this.rtsManager.getSubscribeVideoStats(this.streamUrl,i),s.then(c=>{var u;if(!c.timestamp)return;this.monitorDataCache[i]||(this.monitorDataCache[i]=[]);const o=this.monitorDataCache[i];let l;if((o==null?void 0:o.length)>0){const p=o[o.length-1]||{},d=p,{_last:h}=d;l=Wt(d,["_last"])}(o==null?void 0:o.length)>=30&&this.reportSubscribeMonitor(i),c._last=l,c._codec=t.codec,n&&(c._source=(u=this.localUser)==null?void 0:u.getMediaStats(c.playoutId)),this.monitorDataCache[i].push(c)})}),e.forEach(t=>{this.reportSubscribeMonitor(t)})}catch(e){}}),1e3))}stopStreamMonitor(){this.monitorTimerId&&(clearInterval(this.monitorTimerId),this.monitorTimerId=void 0),Object.keys(this.monitorDataCache).forEach(e=>{this.reportSubscribeMonitor(e)})}markReconnect(e){const t=[];!this.isAudioSubscribing||e&&!e.includes(this.streamInfo.getAudioInfo().msid)||t.push(this.audioSubState),this.isVideoSubscribing&&(!e||e.includes(this.streamInfo.getVideoLargeInfo().msid)||e.includes(this.streamInfo.getVideoSmallInfo().msid))&&t.push(this.videoSubState),!this.isScreenSubscribing||e&&!e.includes(this.streamInfo.getScreenInfo().msid)||t.push(this.screenSubState),!this.isDataSubscribing||e&&!e.includes(D.Data)||t.push(this.dataSubState),t.forEach(i=>{i.setState(ce.AliRtcStateReconnecting)})}markReconnected(e){const t=[],i=this.streamInfo.getAudioInfo().msid||D.Audio;if(this.isAudioSubscribing&&(!e||e.includes(i))){t.push(this.audioSubState);const o=this.rtsManager.getStreamByMsid({url:this.streamUrl,aMsid:i});o&&o.audioTrack&&(this.audioTrack=o.audioTrack,this.audioVolumeIndicationInterval>0&&(this.audioLevelMonitor.stop(),this.audioLevelMonitor.start(this.audioTrack,this.audioVolumeIndicationInterval)),this.playAudio())}const s=this.streamInfo.getVideoLargeInfo().msid||D.VideoLarge,n=this.streamInfo.getVideoSmallInfo().msid||D.VideoSmall;if(this.isVideoSubscribing&&(!e||e.includes(s)||e.includes(n))){t.push(this.videoSubState);const o=this.rtsManager.getStreamByMsid({url:this.streamUrl,vMsid:this.streamInfo.isVideoSmallSubscribed||this.streamInfo.isVideoSmallSubscribing?n:s});o&&o.mediaStream&&(this.stream=o,this.playAll(!1))}const c=this.streamInfo.getScreenInfo().msid||D.Screen;if(this.isScreenSubscribing&&(!e||e.includes(c))){t.push(this.screenSubState);const o=this.rtsManager.getStreamByMsid({url:this.streamUrl,vMsid:c});o&&o.mediaStream&&(this.screenStream=o,this.playAll(!0))}if(this.isDataSubscribing&&(!e||e.includes(this.streamInfo.getDataInfo().msid))){t.push(this.dataSubState);const o=this.rtsManager.getDatachannelByMsid({url:this.streamUrl,msid:this.streamInfo.getDataInfo().msid||D.Data});this.dataChannelConnected(o)}t.forEach(o=>{o.setState(ce.AliRtcStateSubscribed)}),e||this.updateSubscribe(ge.Reconnect)}},m(ui,"logName","RemoteUser"),ui);Ke([k()],We.prototype,"clear",1),Ke([k()],We.prototype,"updateRemoteUserDeviceStatus",1),Ke([k()],We.prototype,"updateRemoteTracks",1),Ke([k(H)],We.prototype,"subscribe",1),Ke([k()],We.prototype,"subscribeProxy",1),Ke([k(H)],We.prototype,"subscribeDeleteProxy",1),Ke([k()],We.prototype,"restore",1),Ke([k(H)],We.prototype,"resumeAudio",1),Ke([k(H)],We.prototype,"stopSubscribe",1),Ke([k(H)],We.prototype,"subscribeDeleteAllTracks",1),Ke([k()],We.prototype,"clearStream",1),Ke([k()],We.prototype,"clearScreenStream",1),Ke([k()],We.prototype,"updateSubscribe",1),Ke([k()],We.prototype,"playAudio",1),Ke([k()],We.prototype,"stopPlayAudio",1),Ke([k((a,r,e)=>[typeof a=="string"?a:a==null?void 0:a.nodeType,r||"-",e||"-"])],We.prototype,"play",1),Ke([k()],We.prototype,"stopPlayAll",1),Ke([k(H)],We.prototype,"markReconnect",1),Ke([k(H)],We.prototype,"markReconnected",1);let Dc=We;var qt=(a=>(a[a.AliRtcPluginErrorCodeSuccess=0]="AliRtcPluginErrorCodeSuccess",a[a.AliRtcPluginErrorCodeFailed=-1]="AliRtcPluginErrorCodeFailed",a[a.AliRtcPluginErrorNoFindPlugin=-2]="AliRtcPluginErrorNoFindPlugin",a[a.AliRtcPluginErrorParameterError=-3]="AliRtcPluginErrorParameterError",a[a.AliRtcPluginErrorLoadError=-4]="AliRtcPluginErrorLoadError",a[a.AliRtcPluginErrorCreateError=-5]="AliRtcPluginErrorCreateError",a[a.AliRtcPluginErrorInitError=-6]="AliRtcPluginErrorInitError",a[a.AliRtcPluginErrorInitTokenError=-7]="AliRtcPluginErrorInitTokenError",a))(qt||{});class Mc extends oe{constructor(){super(...arguments);m(this,"plugins",new Map)}add(e,t){if(this.plugins.has(e.name))throw new U(qt.AliRtcPluginErrorCreateError,`Plugin ${e.name} already exists`);this.plugins.set(e.name,e),t&&e.setOptions(t),this.emit("added",e),e.on("enabled",()=>this.emit("added",e)),e.on("disabled",()=>this.emit("removed",e)),e.on("updated",()=>this.emit("updated",e))}remove(e){const t=this.plugins.get(e);if(!t)throw new U(qt.AliRtcPluginErrorNoFindPlugin,`Plugin ${e} not founded`);try{t.disable()}catch(i){}if(typeof t.stop=="function")try{t.stop()}catch(i){}if(typeof t.destroy=="function")try{t.destroy()}catch(i){}this.plugins.delete(e),t.removeAllListeners(),this.emit("removed",t)}removeAll(){Array.from(this.plugins.keys()).forEach(e=>{this.remove(e)})}get(e){return this.plugins.get(e)}has(e){return!!this.plugins.get(e)}getAll(){return Array.from(this.plugins.values())}}const Lc=a=>I(this,null,function*(){const r=new J.AliRTS.SupportUtil;window.isSecureContext||console.warn("WebRTC 需要 HTTPS 安全上下文,细节可参考:https://developer.mozilla.org/zh-CN/docs/Web/Security/Secure_Contexts");let e={support:!1,detail:{isWebRTCSupported:r.checkMediaDevices()&&r.checkWebRtcSupport(),isH264DecodeSupported:!1,isH264EncodeSupported:!1,isScreenShareSupported:!1,isSendMediaExtensionMsgSupported:!1,isBrowserSupported:!0}},t=!1;try{e.detail.isWebRTCSupported?(yield r.isSupport({isReceiveVideo:!0}),t=!0):console.warn("当前浏览器不支持 WebRTC")}catch(i){t=!1,e.detail.isBrowserSupported=r.checkBrowser({errorCode:0,message:""})}if(e.support=t,r.checkWebRtcSupport()&&a!=="sendonly"){const i=yield r.checkH264Decode();e.detail.isH264DecodeSupported=i,e.support=e.support&&i}if(r.checkWebRtcSupport()&&a!=="recvonly"){const i=yield r.checkH264Encode();e.detail.isH264EncodeSupported=i,e.support=e.support&&i}return e.detail.isScreenShareSupported=r.checkWebRtcSupport()&&r.checkScreenCapture()&&!J.AliRTS.SystenUtil.isAndroid&&!J.AliRTS.SystenUtil.isIos,e.detail.isSendMediaExtensionMsgSupported=r.checkWebRtcSupport()&&r.checkEncodedTransformSupport(),e}),Mn=a=>{const r=a.toLowerCase();return r.indexOf("h265")>0||r.indexOf("h.265")>0||r.indexOf("hevc")>0},Nc=()=>I(this,null,function*(){var a;try{const r=typeof RTCRtpReceiver!="undefined"&&typeof RTCRtpReceiver.getCapabilities=="function"?RTCRtpReceiver.getCapabilities("video"):null;if((a=r==null?void 0:r.codecs)!=null&&a.some(e=>e.mimeType.toLowerCase()==="video/h265"))return!0}catch(r){}return(()=>I(this,null,function*(){if(typeof RTCPeerConnection=="undefined")return!1;let r=new RTCPeerConnection;try{const e=yield r.createOffer({offerToReceiveVideo:!0,offerToReceiveAudio:!0});return!(!e||!e.sdp)&&Mn(e.sdp)}catch(e){return!1}finally{r==null||r.close(),r=void 0}}))()}),xc=()=>I(this,null,function*(){var r;try{const e=typeof RTCRtpSender!="undefined"&&typeof RTCRtpSender.getCapabilities=="function"?RTCRtpSender.getCapabilities("video"):null;if((r=e==null?void 0:e.codecs)!=null&&r.some(t=>t.mimeType.toLowerCase()==="video/h265"))return!0}catch(e){}if(typeof RTCPeerConnection=="undefined")return!1;let a=new RTCPeerConnection;try{a.addTransceiver("video",{direction:"sendonly"});const e=yield a.createOffer();return Mn(e.sdp||"")}catch(e){return!1}finally{a==null||a.close(),a=void 0}}),{BrowserUtil:Ln}=J.AliRTS,Lt="RtsManager";class Oc{constructor(r){m(this,"ctx");m(this,"rtsClientMap",new Map);m(this,"pubBaseUrl");this.ctx=r}createPerUserRtsInstance(){return J.AliRTS.createClient({singlePcConfig:{usePcReconnect:!0}})}getOrCreateClientEntry(r){let e=this.rtsClientMap.get(r);if(!e){const t=this.createPerUserRtsInstance();e={client:t,connected:!1,traceId:""},this.rtsClientMap.set(r,e),this.addPerUserRTSListener(t,r)}return e}destroyClientEntry(r){const e=this.rtsClientMap.get(r);if(e){try{e.client.removeAllListeners(),e.client.unsubscribe()}catch(t){}this.rtsClientMap.delete(r)}}addPerUserRTSListener(r,e){r.on("connectStatusChange",t=>{T.event(`[${Lt}]`,`[multi-pc:${e}] connectStatusChange to:`,t.status);const i=this.rtsClientMap.get(e);i&&(t.status===J.EConnectStatus.CONNECT_STATUS_DISCONNECTED?(i.connected=!1,e===this.pubBaseUrl&&(this.ctx.slsReporter.reportWarning("rts disconnected (multi-pc pub)"),this.ctx.emit("disconnected"))):t.status===J.EConnectStatus.CONNECT_STATUS_CONNECTED&&(i.connected=!0,e===this.pubBaseUrl&&this.ctx.emit("connected",!1,Pi.PUBLISH)))}),r.on("reconnect",t=>{var i,s,n;T.debug(`[${Lt}]`,`[multi-pc:${e}] reconnect`,t),this.ctx.emit("reconnect",t.type,(i=t.extraInfo)==null?void 0:i.url,(n=(s=t.extraInfo)==null?void 0:s.msids)==null?void 0:n.map(c=>c.name))}),r.on("reconnectFinish",t=>{var s;T.debug(`[${Lt}]`,`[multi-pc:${e}] reconnectFinish`,t),this.ctx.emit("reconnectFinish",(t==null?void 0:t.type)||"pc",t==null?void 0:t.latestUrl,(s=t==null?void 0:t.msids)==null?void 0:s.map(n=>n.name));const i=this.rtsClientMap.get(e);if(i&&(i.connected=!0),e===this.pubBaseUrl)try{this.ctx.emit("connected",!0,Pi.PUBLISH)}catch(n){T.error(`[${Lt}]`,"emit connected error:",n)}}),r.on("receivedSEI",t=>{this.ctx.emit("seimessage",t.url,t.sei.payloadType,t.sei.data)}),r.on("traceId",({url:t,traceId:i})=>{if(!t||!i||this.ctx.traceIdMap[t]===i)return;this.ctx.traceIdMap[t]=i;const s=this.rtsClientMap.get(e);s&&(s.traceId=i),this.ctx.emit("traceIdUpdated",t,i)}),r.on("onError",t=>{T.event(`[${Lt}]`,`[multi-pc:${e}] onError:`,t)})}get isConnected(){var r,e;if(this.pubBaseUrl)return(e=(r=this.rtsClientMap.get(this.pubBaseUrl))==null?void 0:r.connected)!=null?e:!1;for(const t of this.rtsClientMap.values())if(t.connected)return!0;return!1}get isConnecting(){if(this.pubBaseUrl){const r=this.rtsClientMap.get(this.pubBaseUrl);return!!r&&!r.connected}return!1}publish(r,e,t){return I(this,null,function*(){const i=r.url,s=r.callId,n=i.split("?")[0];this.pubBaseUrl=n;const c=this.getOrCreateClientEntry(n),o=Date.now();let l;const{publishStream:d,vMsid:u}=yield this.ctx.localStreamManager.createHTTPPublishStream();if(!d)return T.warn(`[${Lt}]`,"multiPCPublish: publishStream is null"),{traceId:"",l1ip:l};const p=this.ctx.getPubMsid(d,{vMsid:u});p.answerSdpHook=v=>{const R=/\d+\.\d+\.\d+\.\d+(?=\s+1106|\s+8000)/.exec(v);return R!=null&&R[0]&&(l=R[0]),v},this.ctx.handleHTTPConfig(p),p.disableHeartbeat=!0,this.ctx.rtsPeerConnectionType=Pi.PUBLISH;const h=Date.now();let f="";try{const v=this.ctx.suffixHttpUrl(i);f=yield c.client.publish(v,d,p)}catch(v){c.connected=!1;const R=2e3-(Date.now()-h);throw R<=0?this.ctx.emit("disconnected"):setTimeout(()=>{this.ctx.emit("disconnected")},R),this.ctx.slsReporter.reportPublish(e,i,s,d.hasVideo&&(!u||u===D.VideoLarge),d.hasVideo&&u===D.VideoSmall,d.hasVideo&&u===D.Screen,d.hasAudio,(v==null?void 0:v.errorCode)||-1,this.ctx.pcTraceId,"",h,h),U.fromRtsError(v)}f&&(this.ctx.pcTraceId=f,c.traceId=f),c.connected=!0,this.ctx.publishingTracks=c.client.getPublishTrackInfoList(),T.event(`[${Lt}]`,"multiPCPublish success",f);const g=Date.now();setTimeout(()=>{this.ctx.slsReporter.reportPublish(e,i,s,d.hasVideo&&(!u||u===D.VideoLarge),d.hasVideo&&u===D.VideoSmall,d.hasVideo&&u===D.Screen,d.hasAudio,0,this.ctx.pcTraceId,r.traceId,h,g)},6e3),this.ctx.slsReporter.reportConnectionLatencyEvent(Ze.HANDLE_PUB_TASK,st.START,s,f,o),this.ctx.slsReporter.reportConnectionLatencyEvent(Ze.HANDLE_PUB_TASK,st.END,s,f,Date.now());const b=!d.hasVideo,S=u;return yield this.waitPublishSender(i,b,S),this.ctx.slsReporter.reportPublishFirstPacket(e,s,h,g,this.ctx.localJoinTime,b?D.Audio:p.vMsid,f||"",f||"",t),this.ctx.emit("connected",!1,Pi.PUBLISH),{traceId:f,l1ip:l}})}publishStop(r){return I(this,null,function*(){if(this.pubBaseUrl){const e=this.rtsClientMap.get(this.pubBaseUrl);e&&(yield e.client.publishStop([{url:r}]),this.destroyClientEntry(this.pubBaseUrl),this.pubBaseUrl=void 0)}return this.ctx.publishingTracks=[],""})}unpublish(){return I(this,null,function*(){this.pubBaseUrl&&(this.destroyClientEntry(this.pubBaseUrl),this.pubBaseUrl=void 0),this.ctx.publishingTracks=[]})}subscribe(r,e,t,i,s){return I(this,null,function*(){const{options:n,remoteUser:c}=r;if(n.screen)return T.warn(`[${Lt}]`,"screen subscribe not supported in multi-PC mode"),null;const o=c.streamUrl,l=o.split("?")[0];this.ctx.subUrlMap[c.userId]=l;const d=this.getOrCreateClientEntry(l),u=this.ctx.getSubConfig(c.streamInfo,n);this.ctx.handleHTTPConfig(u),u.disableHeartbeat=!0;const p=Date.now();let h;try{const A=this.ctx.suffixHttpUrl(o,u);h=yield d.client.subscribe(A,u)}catch(A){throw d.connected=!1,U.fromRtsError(A)}d.connected=!0,d.traceId=h.traceId,this.ctx.reportSubscribeLatency(n,t,p,!0);const f={traceId:h.traceId,stream:h,isHTTP:!0},g=Date.now();let b=D.VideoLarge;const S=n.video,v=n.audio;n.video&&n.vMsid&&(b=n.vMsid);let R=0,_=0,y=0;const w=((A,E)=>{let C=0;const P=()=>{if(!this.rtsClientMap.has(l))return Promise.resolve();let M;return v&&!R&&(M=d.client.getSubscribeAudioStats(o).then(x=>{if(x.packetsReceived>0)R=Date.now();else if(!S)return C<A&&(C++,new Promise(K=>setTimeout(()=>K(P()),E)));return!0})),S&&!y&&(M=d.client.getSubscribeVideoStats(o,b).then(x=>{if(typeof x.packetsReceived=="number"){if(!_&&x.packetsReceived>0&&(_=Date.now()),x.framesDecoded>0)y=Date.now();else if(C<A)return C++,new Promise(K=>setTimeout(()=>K(P()),E));return!0}})),Promise.resolve(M)};return P()})(20,100);return w.then(()=>{_&&this.ctx.slsReporter.reportSubscribeFirstPacket(e===ge.Resume,t,i,b,{fprt:_-p,ifsprtc:y?y-p:0,ajsub:e===ge.Join?1:0,pctid:d.traceId,subtid:(f==null?void 0:f.traceId)||"",sstc:g-p}),y&&this.ctx.slsReporter.reportSubscribeFirstFrame(e===ge.Resume,t,i,b,{fvfrt:y-p,fp2fftc:y-_,ajsub:e===ge.Join?1:0,tffrtc:e===ge.Join?y-this.ctx.localJoinTime:y-s,pctid:d.traceId,subtid:(f==null?void 0:f.traceId)||"",fvfdtc:y-p}),R&&(this.ctx.slsReporter.reportConnectionLatencyEvent(Ze.FIRST_REMOTE,st.DECODED,t,D.Audio,R),this.ctx.slsReporter.reportSubscribeFirstPacket(e===ge.Resume,t,i,D.Audio,{fprt:R-p,ifsprtc:R-p,ajsub:e===ge.Join?1:0,pctid:d.traceId,subtid:(f==null?void 0:f.traceId)||"",sstc:g-p}))}),f.statsCheckPromise=w,f})}subscribeDelete(r){return I(this,null,function*(){const{remoteUser:e,options:t}=r,i=e.streamUrl.split("?")[0];if(!this.rtsClientMap.get(i))return null;const s=!!t.audio,n=!(!t.video&&!t.screen);if(this.destroyClientEntry(i),s&&n)return null;const c={};s||(c.audio=!0),n||(c.video=!0);const o=this.getOrCreateClientEntry(i),l=this.ctx.getSubConfig(e.streamInfo,c);this.ctx.handleHTTPConfig(l),l.disableHeartbeat=!0;try{const d=this.ctx.suffixHttpUrl(e.streamUrl,l),u=yield o.client.subscribe(d,l);o.connected=!0,o.traceId=u.traceId,T.info(`[${Lt}]`,"multiPCSubscribeDelete: re-subscribed remaining tracks",c)}catch(d){T.error(`[${Lt}]`,"multiPCSubscribeDelete: re-subscribe failed",d),this.destroyClientEntry(i)}return null})}getPublishVideoStats(r,e){return I(this,null,function*(){if(this.pubBaseUrl){const t=this.rtsClientMap.get(this.pubBaseUrl);if(t)return t.client.getPublishVideoStats(r,e)}return{}})}getPublishAudioStats(r,e){return I(this,null,function*(){if(this.pubBaseUrl){const t=this.rtsClientMap.get(this.pubBaseUrl);if(t)return t.client.getPublishAudioStats(r,e)}return{}})}getSubscribeVideoStats(r,e){return I(this,null,function*(){const t=r.split("?")[0],i=this.rtsClientMap.get(t);return i?i.client.getSubscribeVideoStats(r,e):{}})}getSubscribeAudioStats(r,e){return I(this,null,function*(){const t=r.split("?")[0],i=this.rtsClientMap.get(t);return i?i.client.getSubscribeAudioStats(r,e):{}})}getNetworkQuality(){return I(this,null,function*(){var i,s;let r=0,e=0,t=!1;for(const n of this.rtsClientMap.values())if(n.connected)try{const c=(s=(i=n.client.commonController)==null?void 0:i.peerCore)==null?void 0:s.pc;if(!c||c.connectionState==="disconnected"||c.connectionState==="failed"||c.connectionState==="closed")continue;t=!0;const o=c.getReceivers();let l=0,d=0,u=0;for(const h of o)(yield h.getStats()).forEach(f=>{f.type==="candidate-pair"&&typeof f.currentRoundTripTime=="number"&&(l=Math.round(1e3*f.currentRoundTripTime)),f.type!=="inbound-rtp"||f.mediaType!=="audio"&&f.mediaType!=="video"||(d+=f.packetsLost||0,u+=f.packetsReceived||0)});const p=u>0?Math.round(d/(d+u)*100):0;l>r&&(r=l),p>e&&(e=p)}catch(c){}return t?{rtt:r,loss:e,quality:ds(e,r)}:{rtt:0,loss:0,quality:tt.AliRtcNetworkDisconnected}})}getPCStats(){return I(this,null,function*(){var r,e;if(this.pubBaseUrl){const t=this.rtsClientMap.get(this.pubBaseUrl);if(t)return(e=(r=t.client.commonController.peerCore)==null?void 0:r.pc)==null?void 0:e.getStats()}})}getStreamByMsid(r){if(r!=null&&r.url){const e=r.url.split("?")[0],t=this.rtsClientMap.get(e);if(t)return t.client.commonController.streamManager.getStreamByMsid(r)}}updateAuth(r){const e=r.split("?")[0],t=this.rtsClientMap.get(e);t&&t.client.updateAuth(r)}sendSEI(r,e,t,i){return I(this,null,function*(){if(this.pubBaseUrl){const s=this.rtsClientMap.get(this.pubBaseUrl);if(s)return s.client.sendSEI({url:r,vMsid:D.VideoLarge,data:e,repeatCount:t,payloadType:i})}})}waitPublishSender(r,e=!1,t){return I(this,null,function*(){var s;const i=this.pubBaseUrl?(s=this.rtsClientMap.get(this.pubBaseUrl))==null?void 0:s.client:void 0;if(i)return Promise.race([Ht(1e3),((n,c)=>{let o=0;const l=()=>(e?i.getPublishAudioStats(r,t):i.getPublishVideoStats(r,t)).then(d=>!(d.bytesSent>0)&&o<n?(o++,new Promise(u=>setTimeout(()=>u(l()),c))):Promise.resolve());return l()})(5,100)]).catch(()=>{})})}clear(){for(const[r]of this.rtsClientMap)this.destroyClientEntry(r);this.rtsClientMap.clear(),this.pubBaseUrl=void 0}}var Vc=Object.defineProperty,Uc=Object.getOwnPropertyDescriptor,Je=(a,r,e,t)=>{for(var i,s=t>1?void 0:t?Uc(r,e):r,n=a.length-1;n>=0;n--)(i=a[n])&&(s=(t?i(r,e,s):i(s))||s);return t&&s&&Vc(r,e,s),s},Pi=(a=>(a.PUBLISH="publish",a.SUBSCRIBE="subscribe",a))(Pi||{});const Xi=([a])=>{const{remoteUser:r,options:e}=a;return[`user(${r.userId})`,e]};class Bc{constructor(r,e=5){m(this,"queue");m(this,"queue2");m(this,"batchFunc");m(this,"maxCount");m(this,"disabled",!1);m(this,"pendingFlush",Promise.resolve());this.queue=[],this.queue2=[],this.batchFunc=r,this.maxCount=e}add(r){return this.disabled?this.batchFunc([r]).then(e=>e.find(t=>t.url===r.url)||e[0]):(this.queue.length>=this.maxCount||this.queue2.length>=this.maxCount?this.flush():(e=>{if(typeof e!="function")throw new TypeError("Callback must be a function");typeof Promise!="undefined"?Promise.resolve().then(e).catch(t=>console.error(t)):setTimeout(e,0)})(this.flush.bind(this)),new Promise((e,t)=>{this.queue.find(i=>i.config.url===r.url)?this.queue2.push({config:r,resolve:e,reject:t}):this.queue.push({config:r,resolve:e,reject:t})}))}waitForPending(){return I(this,null,function*(){(this.queue.length>0||this.queue2.length>0)&&this.flush(),yield this.pendingFlush})}fallbackToSingleRequest(r){r.forEach(e=>{this.batchFunc([e.config]).then(t=>{const i=t.find(s=>s.url===e.config.url)||t[0];e.resolve(i)}).catch(t=>{e.reject(t)})})}handleError(r,e){var t;(t=r==null?void 0:r.message)!=null&&t.includes("Message too large")?(this.disabled=!0,T.warn("[Batcher]","Message too large, batcher disabled, fallback to single request"),this.fallbackToSingleRequest(e)):e.forEach(i=>i.reject(r))}flush(){if(this.queue.length===0&&this.queue2.length===0)return;const r=this.queue.map(i=>i),e=this.queue2.map(i=>i);this.queue=[],this.queue2=[];const t=[];[r,e].forEach(i=>{if(i.length>0)try{const s=this.batchFunc(i.map(n=>n.config)).then(n=>{n.forEach(c=>{const o=i.find(l=>l.config.url===c.url);o&&o.resolve(c)})}).catch(n=>{this.handleError(n,i)});t.push(s)}catch(s){this.handleError(s,i)}}),t.length>0&&(this.pendingFlush=Promise.all(t).then(()=>{}))}}const ze=(se=class extends oe{constructor(e,t,i){var s,n,c,o;super();m(this,"rts");m(this,"dycConf",new J.DynamicConfig);m(this,"encodedInsertableStreams",!0);m(this,"audioRedEnabled",!1);m(this,"localStreamManager");m(this,"slsReporter");m(this,"_rtsPeerConnectionType","publish");m(this,"connecting",!1);m(this,"connected",!1);m(this,"rtsDisconnected",!1);m(this,"_pcTraceId","");m(this,"_localJoinTime",0);m(this,"connectionResolve");m(this,"connectingPromise");m(this,"dcResolve");m(this,"dcReject");m(this,"dcConnectingPromise");m(this,"_dcReady",!1);m(this,"_prevDownlinkStat");m(this,"_publishingTracks",[]);m(this,"parameter",{});m(this,"preferredPubL1Ip");m(this,"preferredSubL1Ip");m(this,"httpPublishUrlMap",{});m(this,"httpSubscribeUrlMap",{});m(this,"traceIdMap",{});m(this,"subUrlMap",{});m(this,"subscribeAddBatcher");m(this,"multiPC");m(this,"isLowPerfDevice",!1);if(this.localStreamManager=e,this.slsReporter=t,this.parameter=i,this.rts=this.createRtsInstance(),this.addRTSListener(),this.subscribeAddBatcher=new Bc(this.subscribeAddWithRetry.bind(this),((n=(s=this.parameter)==null?void 0:s.subscribe)==null?void 0:n.maxBatchCount)||3),((o=(c=this.parameter)==null?void 0:c.subscribe)==null?void 0:o.disableBatcher)===!0&&(this.subscribeAddBatcher.disabled=!0),(()=>{const l=(Ln.browserName||"").toLowerCase(),d=parseInt(Ln.browserVersion||"0",10);return l==="firefox"&&d>=148})()){T.info(`[${se.logName}]`,"Multi-PC mode enabled (Firefox 148+)"),this.subscribeAddBatcher.disabled=!0;const l=this,d={emit:(u,...p)=>l.emit(u,...p),suffixHttpUrl:l.suffixHttpUrl.bind(l),handleHTTPConfig:l.handleHTTPConfig.bind(l),getSubConfig:l.getSubConfig.bind(l),getPubMsid:l.getPubMsid.bind(l),reportSubscribeLatency:l.reportSubscribeLatency.bind(l),localStreamManager:l.localStreamManager,slsReporter:l.slsReporter,traceIdMap:l.traceIdMap,subUrlMap:l.subUrlMap,get pcTraceId(){return l._pcTraceId},set pcTraceId(u){l._pcTraceId=u},get localJoinTime(){return l._localJoinTime},get publishingTracks(){return l._publishingTracks},set publishingTracks(u){l._publishingTracks=u},get rtsPeerConnectionType(){return l._rtsPeerConnectionType},set rtsPeerConnectionType(u){l._rtsPeerConnectionType=u}};this.multiPC=new Oc(d)}}extractStreamId(e){try{const t=new URL(e.replace(/^artc:\/\//,"https://example.com")),i=t.pathname.split("/").filter(s=>s!=="");return i.length>0?i[i.length-1]:e}catch(t){return e}}subscribeAddWithRetry(e){return pr(t=>I(this,null,function*(){return this._dcReady||(yield this.dcConnectingPromise),t>0&&T.event(`[${se.logName}]`,`subscribeAdd retry times: ${t}`),this.isConnected?(t>=0&&e.forEach(i=>{var s,n;_e.getInstance().addEventData(_e.eventRetrySubAuto,this.extractStreamId(i.url),(s=i.subAudio)!=null?s:!1,(n=i.subVideo)!=null?n:!1,t)}),this.rts.subscribeAdd(e)):Promise.reject()}),10,100,t=>{var i,s,n,c;return(t==null?void 0:t.errorCode)===15006||(t==null?void 0:t.errorCode)===15004&&((c=(n=(s=(i=t.extraInfo)==null?void 0:i.parsedData)==null?void 0:s.streams)==null?void 0:n[0])==null?void 0:c.res_code)===404})}createRtsInstance(){var e,t;return J.AliRTS.createClient({singlePcConfig:{usePcReconnect:!0},datachannelDelayOpen:!1,signalDatachannelInitOptions:(t=(e=this.parameter)==null?void 0:e.net)!=null&&t.datachannelInitOptions?this.parameter.net.datachannelInitOptions:void 0})}addRTSListener(){this.rts.on("connectStatusChange",t=>{var i,s,n,c;if(T.event(`[${se.logName}]`,"rts connectStatusChange to:",t.status),t.status===J.EConnectStatus.CONNECT_STATUS_DISCONNECTED)this.dcReject&&this.dcReject(),this.setConnected(!1),this.rtsDisconnected=!0,this.slsReporter.reportWarning("rts disconnected"),this.emit("disconnected");else if(t.status===J.EConnectStatus.CONNECT_STATUS_CONNECTED){if(this.rtsDisconnected){const o=(c=(n=(s=(i=this.rts.commonController)==null?void 0:i.peerCore)==null?void 0:s.getSignal())==null?void 0:n.getDatachannelCore())==null?void 0:c.readyState;T.event(`[${se.logName}]`,"dcReadyState:",o),o==="open"&&this.dcResolve&&this.dcResolve(!0)}this.rtsDisconnected=!1,this.setConnected(!0)}}),this.rts.on("reconnect",t=>{var i,s,n;T.debug(`[${se.logName}]`,"reconnect",t),this.emit("reconnect",t.type,(i=t.extraInfo)==null?void 0:i.url,(n=(s=t.extraInfo)==null?void 0:s.msids)==null?void 0:n.map(c=>c.name))}),this.rts.on("reconnectFinish",t=>{var i;T.debug(`[${se.logName}]`,"reconnectFinish",t),this.emit("reconnectFinish",(t==null?void 0:t.type)||"pc",t==null?void 0:t.latestUrl,(i=t==null?void 0:t.msids)==null?void 0:i.map(s=>s.name));try{this.emit("connected",!0,this._rtsPeerConnectionType)}catch(s){T.error(`[${se.logName}]`,"emit connected error:",s)}this.logCandidateProtocol("reconnectFinish")}),this.rts.on("datachannelStatusChange",t=>{T.event(`[${se.logName}]`,"rts datachannelStatusChange to:",t.status),t.status===J.EDatachannelStatus.DATACHANNEL_STATUS_OPEN?(this._dcReady=!0,this.dcResolve&&this.dcResolve(!0)):t.status===J.EDatachannelStatus.DATACHANNEL_STATUS_CLOSE&&(this._dcReady=!1,this.dcReject&&this.dcReject(new Error("signal datachannel closed")),this.dcConnectingPromise=new Promise((i,s)=>{this.dcResolve=i,this.dcReject=s}))}),this.rts.on("receivedSEI",t=>{var i;if(this.emit("seimessage",t.url,t.sei.payloadType,t.sei.data),t.sei.payloadType===99)try{const s=JSON.parse(new TextDecoder().decode(t.sei.data));this.slsReporter.reportLoopAudioDelay(((i=this.publishingTracks.find(n=>n.type==="audio"))==null?void 0:i.ssrc)||"",s)}catch(s){}}),this.rts.on("onError",t=>{T.event(`[${se.logName}]`,"rts onError event:",t)}),this.rts.on("reconnect",t=>{T.event(`[${se.logName}]`,"rts reconnect event:",t)}),this.rts.on("traceId",({url:t,traceId:i})=>{t&&i&&this.traceIdMap[t]!==i&&(this.traceIdMap[t]=i,this.emit("traceIdUpdated",t,i))});const e={sophon_audio:"audio",sophon_video_camera_large:"vlarge",sophon_video_camera_small:"vsmall",sophon_video_screen_share:"screen",sophon_data:"data"};this.rts.on("signalSent",t=>{const i=t.streams||[],s=i.map((c,o)=>{let l=i.length>1?`[${o}]`:"";return l+=c.method||"",t.type==="sub"&&c.url&&(l+=` ${Object.keys(this.subUrlMap).find(d=>this.subUrlMap[d]===c.url.split("?")[0])||""}`),c.msid&&(l+=` ${c.msid.map(d=>e[d.name]||d.name).join("+")}`),l}),n=`${t.type} ${s.join(", ")}`;T.event(`[${se.logName}]`,"rts signalSent event:",n,t)}),this.rts.on("signalReceived",t=>{const i=t.streams||[],s=i.map((c,o)=>{let l=i.length>1?`[${o}]`:"";return l+=c.method||"",t.type==="sub"&&c.url&&(l+=` ${Object.keys(this.subUrlMap).find(d=>this.subUrlMap[d]===c.url.split("?")[0])||""}`),l+=` ${c.res_code||""}`,c.msid&&(l+=` ${c.msid.map(d=>e[d.name]||d.name).join("+")}`),l}),n=`${t.type} ${s.join(", ")}`;T.event(`[${se.logName}]`,"rts signalReceived event:",n,t)}),this.rts.on("hebtSent",t=>{var i,s,n;if((n=(s=(i=this.parameter)==null?void 0:i.net)==null?void 0:s.heartbeat)!=null&&n.enableLog){const c=Object.keys(this.subUrlMap).find(o=>{var l,d;return this.subUrlMap[o]===((d=(l=t.streams)==null?void 0:l[0])==null?void 0:d.url.split("?")[0])})||(t.streams?"pub":"empty");T.event(`[${se.logName}]`,"rts hebtSent event:",c,t)}}),this.rts.on("hebtReceived",t=>{var i,s,n,c,o,l,d;if((n=(s=(i=this.parameter)==null?void 0:i.net)==null?void 0:s.heartbeat)!=null&&n.enableLog){let u=`${Object.keys(this.subUrlMap).find(p=>{var h,f;return this.subUrlMap[p]===((f=(h=t.streams)==null?void 0:h[0])==null?void 0:f.url.split("?")[0])})||(t.streams?"pub":"empty")} ${((o=(c=t.streams)==null?void 0:c[0])==null?void 0:o.res_code)||""}`;(d=(l=t.streams)==null?void 0:l[0])!=null&&d.msid&&(u+=` ${t.streams[0].msid.map(p=>e[p.name]||p.name).join("+")}`),T.event(`[${se.logName}]`,"rts hebtReceived event:",u,t)}})}updateAuth(e){if(this.multiPC)return this.multiPC.updateAuth(e);this.rts.updateAuth(e)}get pcTraceId(){return this._pcTraceId}set localJoinTime(e){this._localJoinTime=e}setEncodedInsertableStreams(e){this.encodedInsertableStreams=e}updateDynamicConfig(e){var t;this.dycConf.updateConfigData(e),(t=this.rts)==null||t.updateDynamicConfig(e)}setReceiverPreferredVideoCodecH265(){var s;let e=(s=RTCRtpReceiver.getCapabilities("video"))==null?void 0:s.codecs;if(!e||e.length===0)return;const t=e.filter(n=>n.mimeType.toLowerCase()!=="video/rtx");let i=t.findIndex(n=>n.mimeType==="video/H265");if(i+1){let n=t[i];t.splice(i,1),t.unshift(n),this.rts.setReceiverCodecPreferences({video:t})}}setSenderPreferredVideoCodecH265(){var s;let e=(s=RTCRtpSender.getCapabilities("video"))==null?void 0:s.codecs;if(!e||e.length===0)return;const t=e.filter(n=>n.mimeType.toLowerCase()!=="video/rtx");let i=t.findIndex(n=>n.mimeType==="video/H265");if(i+1){let n=t[i];t.splice(i,1),t.unshift(n),this.rts.setSenderCodecPreferences({video:t})}}supportVideoCodec(e){var t,i,s;return e===At.H265?(t=RTCRtpSender.getCapabilities("video"))==null?void 0:t.codecs.some(n=>n.mimeType==="video/H265"):e===At.H264?(i=RTCRtpSender.getCapabilities("video"))==null?void 0:i.codecs.some(n=>n.mimeType==="video/H264"):e===At.AV1&&((s=RTCRtpSender.getCapabilities("video"))==null?void 0:s.codecs.some(n=>n.mimeType==="video/AV1"))}changeVideoCodec(e){this.supportVideoCodec(e)?(T.info(`[${se.logName}]`,"changeVideoCodec to:",e),At.H265===e&&(this.setSenderPreferredVideoCodecH265(),this.setReceiverPreferredVideoCodecH265())):T.warn(`[${se.logName}]`,`not support video codec: ${e}`)}setAudioRedEnabled(e){var t;if(e!==this.audioRedEnabled){try{const i=[...((t=RTCRtpReceiver.getCapabilities("audio"))==null?void 0:t.codecs)||[]];if(i.length>0){if(e){const s=i.findIndex(c=>c.mimeType==="audio/red"),n=i.findIndex(c=>c.mimeType==="audio/opus");if(s>-1&&n>-1&&s>n){const c=i[n];i[n]=i[s],i[s]=c}}this.rts.setSenderCodecPreferences({audio:i}),this.rts.setReceiverCodecPreferences({audio:i})}}catch(i){}this.audioRedEnabled=e}}clear(){this.multiPC&&this.multiPC.clear(),this.setConnected(!1),this.rtsDisconnected=!1,this._dcReady=!1,this._publishingTracks=[],this._prevDownlinkStat=void 0,this.isLowPerfDevice=!1;try{this.rts.removeAllListeners(),this.rts.unpublish(),this.rts.unsubscribe(),this.rts.dispose()}catch(e){}this.rts=this.createRtsInstance(),this.addRTSListener(),this.subscribeAddBatcher.batchFunc=this.subscribeAddWithRetry.bind(this)}startConnect(){this.connecting=!0,this.connectingPromise=new Promise(e=>{this.connectionResolve=e}),this._dcReady=!1,this.dcConnectingPromise=new Promise((e,t)=>{this.dcResolve=e,this.dcReject=t})}setConnected(e){var t;this.connected=e,this.connecting=!1,(t=this.connectionResolve)==null||t.call(this,!0)}get isConnecting(){return this.multiPC?this.multiPC.isConnecting:this.connecting}get isConnected(){return this.multiPC?this.multiPC.isConnected:this.connected}suffixHttpUrl(e,t){const i=!t;let s=ls(e,i?this.preferredPubL1Ip:this.preferredSubL1Ip);const n={ip_migration:"on",exception_detection:"on"},c=new URL(s),o=c.searchParams;Object.keys(n).forEach(p=>{o.has(p)||o.set(p,n[p])});const l=c.toString(),d=e.split("?")[0];i?this.httpPublishUrlMap[d]=l:this.httpSubscribeUrlMap[d]=l;let u="";return t&&(t.vMsid?t.aMsid||(u="@subaudio=no"):u="@subvideo=no"),l+u}getSuffixedUrl(e,t){const i=e.split("?")[0];return t?this.httpPublishUrlMap[i]||e:this.httpSubscribeUrlMap[i]||e}get publishingTracks(){return this._publishingTracks}getPubMsid(e,t){const{aMsid:i,vMsid:s}=t!=null?t:{},n={};return e.hasAudio&&(n.aMsid=[i!=null?i:D.Audio]),e.hasScreen&&(n.vMsid=[D.Screen]),e.hasVideo&&(n.vMsid=[s!=null?s:t!=null&&t.isScreen?D.Screen:D.VideoLarge]),n}updatePublishingTracks(e){e&&(this._publishingTracks=e.map(({msid:t,from:i,ssrc:s,codec:n,type:c,trackId:o})=>({msid:t,from:i,type:c,ssrc:`${s}`,codec:n!=null?n:"",trackId:o})))}httpPublish(s){return I(this,arguments,function*(e,t=!1,i=Dt.MANUAL){let n;const c=Date.now(),o=e.url,l=e.callId;this.startConnect();const{publishStream:d,videoSmallStream:u,screenStream:p,vMsid:h}=yield this.localStreamManager.createHTTPPublishStream();if(!d)return T.warn(`[${se.logName}]`,"publishStream is null"),{traceId:"",l1ip:n};const f=this.getPubMsid(d,{vMsid:h});f.answerSdpHook=_=>{const y=/\d+\.\d+\.\d+\.\d+(?=\s+1106|\s+8000)/.exec(_);return y!=null&&y[0]&&(n=y[0]),_},this.handleHTTPConfig(f),this._rtsPeerConnectionType="publish";let g=!d.hasVideo,b=h,S="";const v=Date.now();try{S=yield this.publishWithPreferredL1Fallback(o,d,f)}catch(_){this.setConnected(!1);const y=2e3-(Date.now()-v);throw y<=0?this.emit("disconnected"):setTimeout(()=>{this.emit("disconnected")},y),this.slsReporter.reportPublish(t,o,l,d.hasVideo&&(!h||h===D.VideoLarge),d.hasVideo&&h===D.VideoSmall,d.hasVideo&&h===D.Screen,d.hasAudio,(_==null?void 0:_.errorCode)||-1,this.pcTraceId,"",v,v),U.fromRtsError(_)}S&&(this._pcTraceId=S),T.event(`[${se.logName}]`,"rts publish success",S);const R=Date.now();setTimeout(()=>{this.slsReporter.reportPublish(t,o,l,d.hasVideo&&(!h||h===D.VideoLarge),d.hasVideo&&h===D.VideoSmall,d.hasVideo&&h===D.Screen,d.hasAudio,0,this.pcTraceId,e.traceId,v,R)},6e3),this.slsReporter.reportConnectionLatencyEvent(Ze.HANDLE_PUB_TASK,st.START,l,S,c),this.slsReporter.reportConnectionLatencyEvent(Ze.HANDLE_PUB_TASK,st.END,l,S,Date.now());try{const _=Date.now();return this._pcTraceId=S,this.setConnected(!0),this._publishingTracks=this.rts.getPublishTrackInfoList(),u&&(yield this.publishAdd(e,u,{vMsid:D.VideoSmall},t),g=!1,b=D.VideoSmall),p&&(yield this.publishAdd(e,p,{vMsid:D.Screen},t),g=!1,b=D.Screen),yield this.waitPublishSender(o,g,b),this.slsReporter.reportPublishFirstPacket(t,l,v,_,this._localJoinTime,g?D.Audio:f.vMsid,S||"",S||"",i),{traceId:S,l1ip:n}}catch(_){throw this.setConnected(!1),U.fromError(_)}})}waitPublishSender(e,t=!1,i){return I(this,null,function*(){return this.multiPC?this.multiPC.waitPublishSender(e,t,i):Promise.race([Ht(1e3),((s,n)=>{let c=0;const o=()=>(t?this.rts.getPublishAudioStats(e,i):this.rts.getPublishVideoStats(e,i)).then(l=>!(l.bytesSent>0)&&c<s?(c++,new Promise(d=>setTimeout(()=>d(o()),n))):Promise.resolve());return o()})(5,100)]).catch(()=>{})})}getPublishVideoStats(e,t){return I(this,null,function*(){return this.multiPC?this.multiPC.getPublishVideoStats(e,t):yield this.rts.getPublishVideoStats(e,t)})}getPublishAudioStats(e,t){return I(this,null,function*(){return this.multiPC?this.multiPC.getPublishAudioStats(e,t):yield this.rts.getPublishAudioStats(e,t)})}publishAdd(o,l,d){return I(this,arguments,function*(e,t,i,s=!1,n=!1,c=Dt.MANUAL){var g,b,S,v;if(this.multiPC)return T.warn(`[${se.logName}]`,"publishAdd not supported in multi-PC mode"),"";const u=e.url,p=e.callId;this._dcReady||(yield this.dcConnectingPromise);const h=Date.now(),f=this.getPubMsid(t,i);try{const R=yield pr(_=>I(this,null,function*(){return _>0&&T.event(`[${se.logName}]`,`publishAdd retry times: ${_}`),this.isConnected?(this._dcReady||(yield this.dcConnectingPromise),this.rts.publishAdd([X({url:u,stream:t,updateSourceStream:!1},f)])):Promise.reject(new U(B.ERR_INNER,"rts not connected"))}),10,0,_=>(_==null?void 0:_.errorCode)===15006);if(R){const _=Date.now(),[y]=R,w=Date.now();return setTimeout(()=>{var A,E,C,P;this.slsReporter.reportPublish(!1,u,p,((A=f.vMsid)==null?void 0:A[0])===D.VideoLarge,((E=f.vMsid)==null?void 0:E[0])===D.VideoSmall,((C=f.vMsid)==null?void 0:C[0])===D.Screen,((P=f.aMsid)==null?void 0:P[0])===D.Audio,0,this.pcTraceId,y.traceId||"",h,w)},6e3),y.traceId&&(this._pcTraceId=y.traceId),this.updatePublishingTracks(y.trackInfoList),n&&(yield this.waitPublishSender(u,!t.hasVideo,t.hasVideo?i==null?void 0:i.vMsid:i==null?void 0:i.aMsid)),this.slsReporter.reportPublishFirstPacket(s,p,h,_,this._localJoinTime,(t.hasVideo?i==null?void 0:i.vMsid:i==null?void 0:i.aMsid)||"",this.pcTraceId,y.traceId||"",c),y.traceId||""}}catch(R){throw this.slsReporter.reportPublish(!1,u,p,((g=f.vMsid)==null?void 0:g[0])===D.VideoLarge,((b=f.vMsid)==null?void 0:b[0])===D.VideoSmall,((S=f.vMsid)==null?void 0:S[0])===D.Screen,((v=f.aMsid)==null?void 0:v[0])===D.Audio,(R==null?void 0:R.errorCode)||-1,this.pcTraceId,"",h),R!=null&&R.errorCode?U.fromRtsError(R):U.fromError(R)}return""})}publishDelete(e,t){return I(this,null,function*(){var l,d,u,p,h,f,g,b;if(this.multiPC)return T.warn(`[${se.logName}]`,"publishDelete not supported in multi-PC mode"),"";this._dcReady||(yield this.dcConnectingPromise);const i=(d=(l=this.publishingTracks)==null?void 0:l.find(({msid:S})=>S===D.Audio))==null?void 0:d.msid,s=(p=(u=this.publishingTracks)==null?void 0:u.find(({msid:S})=>S===D.VideoLarge))==null?void 0:p.msid,n=(f=(h=this.publishingTracks)==null?void 0:h.find(({msid:S})=>S===D.Screen))==null?void 0:f.msid,c=[];t.screen&&n?c.push(n):t.video&&c.push(t.vMsid||s);const o=[];t.audio&&i&&o.push(i),T.event(se.logName,"publishDelete",{streamUrl:e,aMsid:o,vMsid:c});try{const[S]=(yield this.rts.publishDeleteTracks([{url:e,aMsid:o,vMsid:c}]))||[];return T.event(se.logName,"publishDelete",{result:S}),S&&this.updatePublishingTracks(S.trackInfoList),((b=(g=S==null?void 0:S.trackInfoList)==null?void 0:g[0])==null?void 0:b.trackId)||""}catch(S){throw U.fromRtsError(S)}})}publishReplace(e,t,i){return I(this,null,function*(){var c,o;if(this.multiPC)return T.warn(`[${se.logName}]`,"publishReplace not supported in multi-PC mode"),"";this._dcReady||(yield this.dcConnectingPromise);const{vMsid:s,aMsid:n}=i!=null?i:{};try{const l=yield this.rts.publishReplaceTracks([{url:e,stream:t,vMsid:s,aMsid:n}]),[d]=l;return this.updatePublishingTracks(d.trackInfoList),((o=(c=d==null?void 0:d.trackInfoList)==null?void 0:c[0])==null?void 0:o.trackId)||""}catch(l){throw U.fromRtsError(l)}})}publishStop(e){return I(this,null,function*(){return this.multiPC?(yield this.multiPC.publishStop(e),""):(yield this.rts.publishStop([{url:e}]),this._publishingTracks=[],"")})}publishAddDataChannel(e){return I(this,null,function*(){if(this.multiPC)return T.warn(`[${se.logName}]`,"publishAddDataChannel not supported in multi-PC mode"),null;this._dcReady||(yield this.dcConnectingPromise);const t=yield this.rts.publishAddDatachannel({signalUrl:e,url:this.getSuffixedUrl(e,!0),label:D.Data,msid:D.Data}),i=t==null?void 0:t.datachannel;if(i&&i.send){const s=new ArrayBuffer(4);new DataView(s).setUint8(0,240),i.datachannel.send(s)}return i})}publishStopDataChannel(e,t){return I(this,null,function*(){return this.multiPC?void T.warn(`[${se.logName}]`,"publishStopDataChannel not supported in multi-PC mode"):yield this.rts.publishStopDatachannel({url:e,datachannel:t})})}unpublish(){return I(this,null,function*(){if(this.multiPC)return yield this.multiPC.unpublish(),void(this._publishingTracks=[]);yield this.rts.unpublish(),this._publishingTracks=[],this.connecting=!1,this.connected=!1})}getMultiPCNetworkQuality(){return I(this,null,function*(){return this.multiPC?this.multiPC.getNetworkQuality():{rtt:0,loss:0,quality:tt.AliRtcNetworkDisconnected}})}getSubscribeNetworkQuality(){return I(this,null,function*(){var h;if(this.multiPC)return this.getMultiPCNetworkQuality();const e=(h=this.rts.commonController.peerCore)==null?void 0:h.pc;if(!e||e.connectionState==="disconnected"||e.connectionState==="failed"||e.connectionState==="closed")return{rtt:0,loss:0,quality:tt.AliRtcNetworkDisconnected};let t=0,i=0,s=0;const n=e.getReceivers();for(const f of n)(yield f.getStats()).forEach(g=>{g.type==="candidate-pair"&&typeof g.currentRoundTripTime=="number"&&(t=Math.round(1e3*g.currentRoundTripTime)),g.type!=="inbound-rtp"||g.mediaType!=="audio"&&g.mediaType!=="video"||(i+=g.packetsLost||0,s+=g.packetsReceived||0)});if(!this._prevDownlinkStat)return this._prevDownlinkStat={totalPacketsLost:i,totalPacketsReceived:s},{rtt:t,loss:0,quality:tt.AliRtcNetworkUnknown};const{totalPacketsLost:c,totalPacketsReceived:o}=this._prevDownlinkStat,l=i-c,d=s-o;let u=0;l>0&&d>=0&&(u=Math.round(l/(l+d)*100));const p=ds(u,t);return this._prevDownlinkStat={totalPacketsLost:i,totalPacketsReceived:s},{rtt:t,loss:u,quality:p}})}getSubConfig(e,t){let i=t!=null?t:{};t||(i={audio:!0,video:!0,screen:!0});const s={};return i.audio&&(s.aMsid=[(e==null?void 0:e.getAudioInfo().msid)||D.Audio]),i.video?i.vMsid?s.vMsid=[i.vMsid]:s.vMsid=e!=null&&e.hasVideoLarge?[(e==null?void 0:e.getVideoLargeInfo().msid)||D.VideoLarge]:e!=null&&e.hasVideoSmall?[(e==null?void 0:e.getVideoSmallInfo().msid)||D.VideoSmall]:[D.VideoLarge]:i.screen&&(s.vMsid=[(e==null?void 0:e.getScreenInfo().msid)||D.Screen]),s}handleHTTPConfig(e){var i,s,n,c,o,l,d,u,p,h,f,g;if(this.encodedInsertableStreams&&(e.encodedInsertableStreams=!0),(s=(i=this.parameter)==null?void 0:i.net)!=null&&s.useTCP&&(e.tcpOnly=!0),(c=(n=this.parameter)==null?void 0:n.net)!=null&&c.cumuDelay&&(e.cumuDelay=!0),(l=(o=this.parameter)==null?void 0:o.net)!=null&&l.disableHeartbeat&&(e.disableHeartbeat=!0),(u=(d=this.parameter)==null?void 0:d.net)!=null&&u.heartbeat&&(e.heartbeat=this.parameter.net.heartbeat),(h=(p=this.parameter)==null?void 0:p.net)==null?void 0:h.mediaTimeout){const b=(g=(f=this.parameter)==null?void 0:f.net)==null?void 0:g.mediaTimeout;b>1e3&&b<1e5&&(e.mediaTimeout=b)}e.offerSdpHook=lo;let t=0;e.beforeRetry=b=>I(this,null,function*(){if(t++,T.info(`[${se.logName}]`,`before retry, retryCount: ${t}`),t>=2&&b.url.includes("ali_prefer_media_server"))try{const S=new URL(b.url);S.searchParams.delete("ali_prefer_media_server"),b.url=S.toString(),T.info(`[${se.logName}]`,`removed ali_prefer_media_server, fallback url: ${b.url}`)}catch(S){T.error(`[${se.logName}]`,"failed to parse url for removing ali_prefer_media_server",b.url,S)}return b}),e.retryTimes=17,e.retryInterval=5e3,T.info(`[${se.logName}]`,"http config",e)}httpSubscribe(e){return I(this,null,function*(){const{remoteUser:t,options:i}=e,s=t.streamUrl,n=this.getSubConfig(t.streamInfo,i);this.handleHTTPConfig(n),this._rtsPeerConnectionType="subscribe";try{this.startConnect();const c=yield this.subscribeWithPreferredL1Fallback(s,n);return this._pcTraceId=c.traceId,this.setConnected(!0),{traceId:c.traceId,stream:c}}catch(c){throw this.setConnected(!1),this.emit("disconnected"),U.fromRtsError(c)}})}subscribeWithPreferredL1Fallback(e,t){return I(this,null,function*(){if(this.preferredSubL1Ip){const s=this.suffixHttpUrl(e,t),n=new Promise((c,o)=>{setTimeout(()=>o(new Error("PREFERRED_L1_TIMEOUT")),3e3)});try{const c=yield Promise.race([this.rts.subscribe(s,t),n]);return this.logCandidateProtocol("subscribe (preferred L1)"),c}catch(c){if(c.message==="PREFERRED_L1_TIMEOUT"){T.warn(`[${se.logName}]`,"Preferred L1 subscribe timeout, clearing preferredSubL1Ip and falling back to DNS"),this.preferredSubL1Ip=void 0;const o=yield this.rts.subscribe(this.suffixHttpUrl(e,t),t);return this.logCandidateProtocol("subscribe (fallback)"),o}throw c}}const i=yield this.rts.subscribe(this.suffixHttpUrl(e,t),t);return this.logCandidateProtocol("subscribe"),i})}publishWithPreferredL1Fallback(e,t,i){return I(this,null,function*(){if(this.preferredPubL1Ip){const n=this.suffixHttpUrl(e),c=new Promise((o,l)=>{setTimeout(()=>l(new Error("PREFERRED_L1_TIMEOUT")),3e3)});try{const o=yield Promise.race([this.rts.publish(n,t,i),c]);return this.logCandidateProtocol("publish (preferred L1)"),o}catch(o){if(o.message==="PREFERRED_L1_TIMEOUT"){T.warn(`[${se.logName}]`,"Preferred L1 publish timeout, clearing preferredPubL1Ip and falling back to DNS"),this.preferredPubL1Ip=void 0;const l=yield this.rts.publish(this.suffixHttpUrl(e),t,i);return this.logCandidateProtocol("publish (fallback)"),l}throw o}}const s=yield this.rts.publish(this.suffixHttpUrl(e),t,i);return this.logCandidateProtocol("publish"),s})}subscribeAdd(e){return I(this,null,function*(){var n,c,o,l,d;const{remoteUser:t,options:i}=e,s=vt(X({url:t.streamUrl,subAudio:!!i.audio,subVideo:!(!i.screen&&!i.video)},this.getSubConfig(t.streamInfo,i)),{targetStream:i.screen?t.getScreenStream:t.getCameraStream});this._dcReady||(yield this.dcConnectingPromise);try{return!this.subscribeAddBatcher.disabled&&!((n=this.dycConf.getDycConf("h5_disable_sub_batcher"))==null||n)?yield this.subscribeAddBatcher.add(s):(yield this.subscribeAddWithRetry([s]))[0]}catch(u){if((u==null?void 0:u.errorCode)===15011)return T.info(`[${se.logName}]`,"subscribeAdd ignored",u==null?void 0:u.message),null;if(((d=(l=(o=(c=u==null?void 0:u.extraInfo)==null?void 0:c.parsedData)==null?void 0:o.streams)==null?void 0:l[0])==null?void 0:d.res_code)===508)return this.emit("subscribeexceeds"),null;throw U.fromRtsError(u)}})}subscribeDelete(e){return I(this,null,function*(){var n,c,o,l,d;if(this.multiPC)return this.multiPC.subscribeDelete(e);this.subscribeAddBatcher.disabled||((n=this.dycConf.getDycConf("h5_disable_sub_batcher"))==null||n)||(yield this.subscribeAddBatcher.waitForPending());const{remoteUser:t,options:i}=e,s=vt(X({url:t.streamUrl,subAudio:!!i.audio,subVideo:!(!i.screen&&!i.video)},this.getSubConfig(t.streamInfo,i)),{targetStream:i.screen?t.getScreenStream:t.getCameraStream});this._dcReady||(yield this.dcConnectingPromise);try{return T.event(`[${se.logName}]`,"subscribeDeleteTracks",JSON.stringify({url:s.url,subAudio:s.subAudio,subVideo:s.subVideo,aMsid:s.aMsid,vMsid:s.vMsid})),(yield this.rts.subscribeDeleteTracks([s]))[0]}catch(u){if((u==null?void 0:u.errorCode)===15011)return T.info(`[${se.logName}]`,"subscribeDelete ignored",u==null?void 0:u.message),null;if(((d=(l=(o=(c=u==null?void 0:u.extraInfo)==null?void 0:c.parsedData)==null?void 0:o.streams)==null?void 0:l[0])==null?void 0:d.res_code)===404)return null;throw U.fromRtsError(u)}})}updateSubscribeBatcher(e){e.disableBatcher!==void 0&&(this.subscribeAddBatcher.disabled=e.disableBatcher),e.maxBatchCount!==void 0&&(this.subscribeAddBatcher.maxCount=e.maxBatchCount)}subscribeAddDataChannel(e){return I(this,null,function*(){var s;if(this.multiPC)return T.warn(`[${se.logName}]`,"subscribeAddDataChannel not supported in multi-PC mode"),null;this.subscribeAddBatcher.disabled||((s=this.dycConf.getDycConf("h5_disable_sub_batcher"))==null||s)||(yield this.subscribeAddBatcher.waitForPending()),this._dcReady||(yield this.dcConnectingPromise);const t=yield this.rts.subscribeAddDatachannel({signalUrl:e,url:this.getSuffixedUrl(e,!1),label:D.Data,msid:D.Data}),i=t==null?void 0:t.datachannel;if(i&&i.send){const n=new ArrayBuffer(4);new DataView(n).setUint8(0,240),i.send(n)}return i})}subscribeDeleteDatachannel(e,t){return I(this,null,function*(){var s;if(this.multiPC)return void T.warn(`[${se.logName}]`,"subscribeDeleteDatachannel not supported in multi-PC mode");let i;this.subscribeAddBatcher.disabled||((s=this.dycConf.getDycConf("h5_disable_sub_batcher"))==null||s)||(yield this.subscribeAddBatcher.waitForPending());try{i=yield this.rts.subscribeDeleteDatachannel({url:e,msid:D.Data,datachannel:t})}catch(n){}return i})}publish(s){return I(this,arguments,function*(e,t=!1,i=Dt.MANUAL){if(this.multiPC)return this.multiPC.publish(e,t,i);const n=e.url;let c,o="";if(this.connecting&&(yield this.connectingPromise),this.connected){this._dcReady||(yield this.dcConnectingPromise);let l,d=!1;const{audio:u,video:p,videoSmall:h,screen:f}=this.localStreamManager.publishStreams;u&&(o=yield this.publishAdd(e,u,{aMsid:D.Audio},t),d=!0,l=D.Audio,yield Ht(100)),p&&(o=yield this.publishAdd(e,p,{vMsid:D.VideoLarge},t),d=!1,l=D.VideoLarge,yield Ht(100)),h&&(o=yield this.publishAdd(e,h,{vMsid:D.VideoSmall},t),d=!1,l=D.VideoSmall,yield Ht(100)),f&&(o=yield this.publishAdd(e,f,{isScreen:!0,vMsid:D.Screen},t),d=!1,l=D.Screen),l&&(yield this.waitPublishSender(n,d,l))}else{const l=yield this.httpPublish(e,t,i);o=l.traceId,c=l.l1ip}return{traceId:o,l1ip:c}})}reportSubscribeLatency(e,t,i,s){const n=[];e.audio&&n.push(e.aMsid||D.Audio),e.video?n.push(e.vMsid||D.VideoLarge):e.screen&&n.push(D.Screen),n.forEach(c=>{this.slsReporter.reportConnectionLatencyEvent(Ze.HANDLE_SUB_TASK,st.START,t,c,i,0,s),this.slsReporter.reportConnectionLatencyEvent(Ze.HANDLE_SUB_TASK,st.END,t,c,Date.now(),0,s)})}subscribe(e,t,i,s,n){return I(this,null,function*(){if(this.multiPC)return this.multiPC.subscribe(e,t,i,s,n);let c=!1;const{options:o,remoteUser:l}=e;if(o.video&&o.screen)throw new U(B.ERR_INNER,"subscribe error, video and screen cannot be subscribed at the same time");let d;this.connecting&&(yield this.connectingPromise),this.subUrlMap[l.userId]=l.streamUrl.split("?")[0];let u=Date.now();if(this.connected?d=yield this.subscribeAdd(e):(c=!0,d=yield this.httpSubscribe(e)),!d)return null;this.reportSubscribeLatency(o,i,u,c);const p=Date.now();let h=D.VideoLarge,f=o.video||o.screen,g=o.audio;o.video&&o.vMsid?h=o.vMsid:o.screen&&(h=D.Screen);let b=0,S=0,v=0;const R=((_,y)=>{let w=0;const A=()=>{let E;return g&&!b&&(E=this.rts.getSubscribeAudioStats(l.streamUrl).then(C=>{if(C.packetsReceived>0)b=Date.now(),T.debug(`[${se.logName}]`,l.userId,"Stats 音频首包");else if(!f)return w<_&&(w++,new Promise(P=>setTimeout(()=>P(A()),y)));return!0})),f&&!v&&(E=this.rts.getSubscribeVideoStats(l.streamUrl,h).then(C=>{if(typeof C.packetsReceived=="number")return!S&&C.packetsReceived>0&&(S=Date.now(),T.debug(`[${se.logName}]`,l.userId,"Stats 视频首包")),C.framesDecoded>0?(v=Date.now(),T.debug(`[${se.logName}]`,l.userId,"Stats 视频首帧数据"),!0):w<_?(w++,new Promise(P=>setTimeout(()=>P(A()),y))):(T.event(`[${se.logName}]`,l.userId,"尝试获取首帧数据失败"),!1)})),Promise.resolve(E)};return A()})(20,100);return R.then(()=>{S&&this.slsReporter.reportSubscribeFirstPacket(t===ge.Resume,i,s,h,{fprt:S-u,ifsprtc:v?v-u:0,ajsub:t===ge.Join?1:0,pctid:this.pcTraceId,subtid:(d==null?void 0:d.traceId)||"",sstc:p-u}),v&&this.slsReporter.reportSubscribeFirstFrame(t===ge.Resume,i,s,h,{fvfrt:v-u,fp2fftc:v-S,ajsub:t===ge.Join?1:0,tffrtc:t===ge.Join?v-this.localJoinTime:v-n,pctid:this.pcTraceId,subtid:(d==null?void 0:d.traceId)||"",fvfdtc:v-u}),b&&(this.slsReporter.reportConnectionLatencyEvent(Ze.FIRST_REMOTE,st.DECODED,i,D.Audio,b),this.slsReporter.reportSubscribeFirstPacket(t===ge.Resume,i,s,D.Audio,{fprt:b-u,ifsprtc:b-u,ajsub:t===ge.Join?1:0,pctid:this.pcTraceId,subtid:(d==null?void 0:d.traceId)||"",sstc:p-u}))}),d&&(d.isHTTP=c,d.statsCheckPromise=R),d})}getSubscribeVideoStats(e,t){return I(this,null,function*(){return this.multiPC?this.multiPC.getSubscribeVideoStats(e,t):yield this.rts.getSubscribeVideoStats(e,t)})}getSubscribeAudioStats(e,t){return I(this,null,function*(){return this.multiPC?this.multiPC.getSubscribeAudioStats(e,t):yield this.rts.getSubscribeAudioStats(e,t)})}getStreamByMsid(e){if(this.multiPC){const t=this.multiPC.getStreamByMsid(e);if(t)return t}return this.rts.commonController.streamManager.getStreamByMsid(e)}getDatachannelByMsid(e){var t;return this.multiPC?(T.warn(`[${se.logName}]`,"getDatachannelByMsid not supported in multi-PC mode"),null):(t=this.rts.commonController.datachannelManager)==null?void 0:t.getByMsid(e)}getPCStats(){return I(this,null,function*(){var e,t;return this.multiPC?this.multiPC.getPCStats():(t=(e=this.rts.commonController.peerCore)==null?void 0:e.pc)==null?void 0:t.getStats()})}logCandidateProtocol(e){return I(this,null,function*(){var t,i;try{const s=(i=(t=this.rts.commonController)==null?void 0:t.peerCore)==null?void 0:i.pc;if(!s)return void T.debug(`[${se.logName}]`,`${e} - PC not available`);const n=yield s.getStats();let c,o,l,d;n.forEach(u=>{u.type==="candidate-pair"&&u.state==="succeeded"&&u.nominated&&(c=u.localCandidateId,o=u.remoteCandidateId)}),c||o||n.forEach(u=>{u.type!=="candidate-pair"||u.state!=="succeeded"&&u.state!=="in-progress"||c||(c=u.localCandidateId,o=u.remoteCandidateId)}),n.forEach(u=>{u.type==="local-candidate"&&u.id===c&&(l=u.protocol),u.type==="remote-candidate"&&u.id===o&&(d=u.protocol)}),T.event(`[${se.logName}]`,`${e} - Candidate Protocol: local=${l||"unknown"}, remote=${d||"unknown"}`)}catch(s){T.warn(`[${se.logName}]`,`${e} - Failed to get candidate protocol:`,s)}})}getGatewayIp(){return I(this,null,function*(){var e,t;try{const i=(t=(e=this.rts.commonController)==null?void 0:e.peerCore)==null?void 0:t.pc;if(!i)return"";const s=yield i.getStats();let n;if(s.forEach(o=>{o.type==="candidate-pair"&&o.state==="succeeded"&&o.nominated&&(n=o.remoteCandidateId)}),n||s.forEach(o=>{o.type!=="candidate-pair"||o.state!=="succeeded"&&o.state!=="in-progress"||n||(n=o.remoteCandidateId)}),!n)return"";let c="";return s.forEach(o=>{o.type==="remote-candidate"&&o.id===n&&(c=o.ip||o.address||"")}),T.info(`[${se.logName}]`,`<<<<< getGatewayIp: ${c}`),c}catch(i){return""}})}sendSEI(e,t,i,s){return I(this,null,function*(){return this.multiPC?this.multiPC.sendSEI(e,t,i,s):this.rts.sendSEI({url:e,vMsid:D.VideoLarge,data:t,repeatCount:i,payloadType:s})})}},m(se,"logName","RtsManager"),se);Je([k(H)],ze.prototype,"startConnect",1),Je([k()],ze.prototype,"updatePublishingTracks",1),Je([k(H,H)],ze.prototype,"httpPublish",1),Je([k(H,H)],ze.prototype,"waitPublishSender",1),Je([k(([a,r,e])=>[a,JSON.stringify(e)],H)],ze.prototype,"publishAdd",1),Je([k(H,H)],ze.prototype,"publishDelete",1),Je([k(([a,r,e])=>[a,JSON.stringify(e)])],ze.prototype,"publishReplace",1),Je([k(H)],ze.prototype,"publishStop",1),Je([k(H)],ze.prototype,"publishAddDataChannel",1),Je([k(H)],ze.prototype,"publishStopDataChannel",1),Je([k()],ze.prototype,"unpublish",1),Je([k(Xi,({traceId:a})=>a)],ze.prototype,"httpSubscribe",1),Je([k(Xi,({traceId:a})=>a)],ze.prototype,"subscribeAdd",1),Je([k(Xi)],ze.prototype,"subscribeDelete",1),Je([k(H)],ze.prototype,"subscribeAddDataChannel",1),Je([k(H)],ze.prototype,"subscribeDeleteDatachannel",1),Je([k(H)],ze.prototype,"publish",1),Je([k(Xi)],ze.prototype,"subscribe",1),Je([k()],ze.prototype,"sendSEI",1);let Hc=ze;class Ws{constructor(r=Hs){m(this,"defaultProfile");m(this,"profile");m(this,"profileMap",new Map);m(this,"audioProfile");m(this,"contentHint");this.defaultProfile=X({},r)}updateProfile(r,e){this.profileMap.set(r,X(X(X({},this.defaultProfile),this.profileMap.get(r)||{}),e||{})),this.profile=r}get videoProfile(){return this.profile}updateAudioProfile(r){this.audioProfile=r}setContentHint(r,e){e&&(this.contentHint=e),this.contentHint&&r&&(r.contentHint=this.contentHint)}setVideoProfile(r,e,t=!1){return I(this,null,function*(){if(!this.profile)return;const i=this.profileMap.get(this.profile)||(e==null?void 0:e.VideoProfileMap.get(this.profile));if(i){if(!t&&r&&r.readyState==="live"&&r.applyConstraints)try{yield r.applyConstraints(i)}catch(s){}if(e){const s=X({},i);i.maxSendFrameRate&&(s.frameRate=i.maxSendFrameRate),e==null||e.VideoProfileMap.set(this.profile,s),yield e.setVideoProfile(this.profile)}}})}}const $t=class $t{static acquire(r){if(!r||!r.id)return;const e=$t.refCounts.get(r.id);e?e.count++:$t.refCounts.set(r.id,{track:r,count:1})}static release(r){if(!r||!r.id)return!1;const e=$t.refCounts.get(r.id);return e?(e.count--,e.count<=0&&($t.refCounts.delete(r.id),r.stop(),!0)):(r.stop(),!0)}static getRefCount(r){var e,t;return r&&r.id&&(t=(e=$t.refCounts.get(r.id))==null?void 0:e.count)!=null?t:0}static reset(){$t.refCounts.clear()}};m($t,"refCounts",new Map);let Gt=$t;var He=(a=>(a[a.AliRtcSdkStreamTypeCapture=0]="AliRtcSdkStreamTypeCapture",a[a.AliRtcSdkStreamTypeScreen=1]="AliRtcSdkStreamTypeScreen",a))(He||{});class zs extends oe{constructor(e){super();m(this,"type");m(this,"originVideoTrack");m(this,"videoSource");m(this,"_videoMuted",!1);m(this,"originAudioTrack");m(this,"audioSource");m(this,"_audioMuted",!1);m(this,"_targetVideoTrack");m(this,"_targetDualVideoTrack");m(this,"_targetAudioTrack");m(this,"_publishVideoStream");m(this,"_publishDualVideoStream");m(this,"_publishAudioStream");m(this,"_previewStream");m(this,"plugins",[]);m(this,"_profileManager");m(this,"cameraVideoConstraints");m(this,"micAudioConstraints");m(this,"onVideoTrackEnded",()=>{this.emit("videotrackended")});m(this,"onAudioTrackEnded",()=>{this.emit("audiotrackended")});this.type=e}get profileManager(){return this._profileManager}get audioProfile(){var e;return(e=this.profileManager)==null?void 0:e.audioProfile}updateSource(e,t,i){return I(this,null,function*(){var c,o,l,d;const{videoTrack:s,audioTrack:n}=e;s&&((c=this.originVideoTrack)==null||c.removeEventListener("ended",this.onVideoTrackEnded)),n&&((o=this.originAudioTrack)==null||o.removeEventListener("ended",this.onAudioTrackEnded)),this.type===He.AliRtcSdkStreamTypeScreen?this.stop():(s&&this.originVideoTrack&&Gt.release(this.originVideoTrack),n&&this.originAudioTrack&&Gt.release(this.originAudioTrack)),s&&(this.originVideoTrack=s,Gt.acquire(s),(l=this.originVideoTrack)==null||l.addEventListener("ended",this.onVideoTrackEnded),this.videoSource=t||wi.Camera,this.updateVideoTrack(s)),n&&(this.originAudioTrack=n,Gt.acquire(n),(d=this.originAudioTrack)==null||d.addEventListener("ended",this.onAudioTrackEnded),this.audioSource=i||Hi.Microphone,this.updateAudioTrack(n))})}get currentProfile(){var e;return(e=this.profileManager)==null?void 0:e.profile}get currentVideoTrack(){return this._targetVideoTrack}get currentDualVideoTrack(){return this._targetDualVideoTrack}get publishVideoStream(){return this._publishVideoStream}get publishDualVideoStream(){return this._publishDualVideoStream}get currentAudioTrack(){return this._targetAudioTrack}get publishAudioStream(){return this._publishAudioStream}get previewStream(){return this._previewStream}updateVideoTrack(e,t=!1){return I(this,null,function*(){(this._targetVideoTrack!==e||t)&&(this._targetVideoTrack=e)})}updateDualVideoTrack(e,t=!1){return I(this,null,function*(){(this._targetDualVideoTrack!==e||t)&&(this._targetDualVideoTrack=e)})}updateAudioTrack(e,t=!1){return I(this,null,function*(){(this._targetAudioTrack!==e||t)&&(this._targetAudioTrack=e)})}setAudioMuted(e){var t,i;this._audioMuted=e,e?(t=this.publishAudioStream)==null||t.disableAudio():(i=this.publishAudioStream)==null||i.enableAudio()}get isAudioMuted(){return this._audioMuted}setVideoMuted(e){var t,i;this._videoMuted=e,e?(t=this.publishVideoStream)==null||t.disableVideo():(i=this.publishVideoStream)==null||i.enableVideo()}get isVideoMuted(){return this._videoMuted}process(e){return I(this,null,function*(){var t,i,s,n,c,o,l,d,u,p,h,f;this._targetAudioTrack=this.originAudioTrack,this._targetVideoTrack=this.originVideoTrack;for(const g of this.plugins)try{yield g.execute(this,e)}catch(b){console.error(`error in plugin-${g.name}, error: ${b}`)}this._targetVideoTrack?((i=(t=this._publishVideoStream)==null?void 0:t.videoTrack)==null?void 0:i.id)!==this._targetVideoTrack.id&&(this._publishVideoStream=yield ki(this._targetVideoTrack),this.setVideoMuted(this._videoMuted),(s=this.profileManager)==null||s.setVideoProfile(this.originVideoTrack,this._publishVideoStream,!0),(n=this.profileManager)==null||n.setContentHint(this._targetVideoTrack),this.previewStream?(c=this.previewStream)==null||c.mergeStream(this._publishVideoStream):this._previewStream=yield ki(this._targetVideoTrack)):(this._publishVideoStream=void 0,(o=this.previewStream)==null||o.deleteTracks({video:!0})),this._targetDualVideoTrack?((d=(l=this._publishDualVideoStream)==null?void 0:l.videoTrack)==null?void 0:d.id)!==this._targetDualVideoTrack.id&&(this._publishDualVideoStream=yield ki(this._targetDualVideoTrack),this._videoMuted?this._publishDualVideoStream.disableVideo():this._publishDualVideoStream.enableVideo()):this._publishDualVideoStream=void 0,this._targetAudioTrack?((p=(u=this._publishAudioStream)==null?void 0:u.audioTrack)==null?void 0:p.id)!==this._targetAudioTrack.id&&(this._publishAudioStream=yield ki(this._targetAudioTrack),this.audioProfile&&(yield this._publishAudioStream.setAudioProfile(this.audioProfile)),this.setAudioMuted(this._audioMuted),this.previewStream?(h=this.previewStream)==null||h.mergeStream(this._publishAudioStream):this._previewStream=yield ki(this._targetAudioTrack)):(this._publishAudioStream=void 0,(f=this.previewStream)==null||f.deleteTracks({audio:!0}))})}stopVideo(){this.originVideoTrack&&(this.originVideoTrack.removeEventListener("ended",this.onVideoTrackEnded),Gt.release(this.originVideoTrack),this.originVideoTrack=void 0),this.updateVideoTrack(void 0)}stopAudio(){this.originAudioTrack&&(this.originAudioTrack.removeEventListener("ended",this.onAudioTrackEnded),Gt.release(this.originAudioTrack),this.originAudioTrack=void 0),this.updateAudioTrack(void 0)}stop(){this.stopVideo(),this.stopAudio()}updateVideoProfile(e,t,i=!1){return I(this,null,function*(){this._profileManager||(this._profileManager=new Ws(this.type===He.AliRtcSdkStreamTypeScreen?Tn:Hs)),e&&this._profileManager.updateProfile(e,t),yield this._profileManager.setVideoProfile(this.originVideoTrack,this._publishVideoStream,i)})}get videoProfile(){var e;return(e=this.profileManager)==null?void 0:e.videoProfile}setVideoContentHint(e){this._profileManager||(this._profileManager=new Ws(this.type===He.AliRtcSdkStreamTypeScreen?Tn:Hs)),this._profileManager.setContentHint(this.currentVideoTrack,e)}updateAudioProfile(e){return I(this,null,function*(){this._profileManager||(this._profileManager=new Ws),this._profileManager.updateAudioProfile(e)})}cloneVideoProfile(e){return I(this,null,function*(){var t;yield(t=this.profileManager)==null?void 0:t.setVideoProfile(void 0,e)})}cloneAudioProfile(e){return I(this,null,function*(){this.audioProfile&&(yield e.setAudioProfile(this.audioProfile))})}addPlugin(e){const t=this.plugins.findIndex(i=>i.zIndex>e.zIndex);t>-1?this.plugins.splice(t,0,e):this.plugins.push(e)}removePlugin(e){const t=this.plugins.indexOf(e);return t>-1&&(e.clear(this),this.plugins.splice(t,1),!0)}}var Fc=Object.defineProperty,jc=Object.getOwnPropertyDescriptor,Et=(a,r,e,t)=>{for(var i,s=t>1?void 0:t?jc(r,e):r,n=a.length-1;n>=0;n--)(i=a[n])&&(s=(t?i(r,e,s):i(s))||s);return t&&s&&Fc(r,e,s),s};const wt=(Yt=class extends oe{constructor(e,t){super();m(this,"pluginManager");m(this,"slsReporter");m(this,"publishingCameraVideoStream");m(this,"publishingScreenVideoStream");m(this,"cameraStreamInfo",new zs(He.AliRtcSdkStreamTypeCapture));m(this,"screenStreamInfo",new zs(He.AliRtcSdkStreamTypeScreen));m(this,"streamInfos",[this.cameraStreamInfo,this.screenStreamInfo]);m(this,"_audioCaptureDisabled",!1);m(this,"_cameraCaptureDisabled",!1);m(this,"_publishLocalAudioStreamEnabled",!0);m(this,"_publishLocalVideoStreamEnabled",!0);m(this,"_publishLocalScreenStreamEnabled",!0);this.screenStreamInfo.setVideoContentHint("motion"),this.pluginManager=e,this.slsReporter=t,this.cameraStreamInfo.on("videotrackended",()=>I(this,null,function*(){yield this.stopLocalStream({video:!0}),this.emit("trackended",oi.VideoTrackEnded)})),this.cameraStreamInfo.on("audiotrackended",()=>I(this,null,function*(){yield this.stopLocalStream({audio:!0}),this.emit("trackended",oi.AudioTrackEnded)})),this.screenStreamInfo.on("videotrackended",()=>I(this,null,function*(){yield this.stopLocalStream({screen:!0}),this.emit("trackended",oi.ScreenTrackEnded)})),this.pluginManager.on("added",i=>I(this,null,function*(){if(T.info(`[${Yt.logName}]`,"plugin added",i.name),!i.isSupported("7.2.9"))return console.warn(`${i.name} is not supported!!!`),void i.emit("unsupported");try{yield i.init()}catch(s){i.emit("error",U.fromError(s,qt.AliRtcPluginErrorInitError))}i.streamType===He.AliRtcSdkStreamTypeCapture&&(this.cameraStreamInfo.addPlugin(i),yield this.cameraStreamInfo.process(this.streamInfos)),i.streamType===He.AliRtcSdkStreamTypeScreen&&(this.screenStreamInfo.addPlugin(i),yield this.screenStreamInfo.process(this.streamInfos)),this.emit("publishupdate")})),this.pluginManager.on("removed",i=>I(this,null,function*(){this.cameraStreamInfo.removePlugin(i)&&(yield this.cameraStreamInfo.process(this.streamInfos)),this.screenStreamInfo.removePlugin(i)&&(yield this.screenStreamInfo.process(this.streamInfos)),this.emit("publishupdate")})),this.pluginManager.on("updated",()=>I(this,null,function*(){yield this.updateStreams()}))}get hasCamera(){return!!this.cameraStreamInfo.originVideoTrack}get audioCaptureDisabled(){return this._audioCaptureDisabled}set audioCaptureDisabled(e){this._audioCaptureDisabled=e}get cameraCaptureDisabled(){return this._cameraCaptureDisabled}set cameraCaptureDisabled(e){this._cameraCaptureDisabled=e}setAudioMuted(e){this.cameraStreamInfo.setAudioMuted(e)}get isAudioMuted(){return this.cameraStreamInfo.isAudioMuted}setCameraMuted(e){this.cameraStreamInfo.setVideoMuted(e)}get isCameraMuted(){return this.cameraStreamInfo.isVideoMuted}setScreenMuted(e){this.screenStreamInfo.setVideoMuted(e)}get isScreenMuted(){return this.screenStreamInfo.isVideoMuted}get publishLocalAudioStreamEnabled(){return this._publishLocalAudioStreamEnabled}set publishLocalAudioStreamEnabled(e){this._publishLocalAudioStreamEnabled=e}get publishLocalVideoStreamEnabled(){return this._publishLocalVideoStreamEnabled}set publishLocalVideoStreamEnabled(e){this._publishLocalVideoStreamEnabled=e}get publishLocalScreenStreamEnabled(){return this._publishLocalScreenStreamEnabled}set publishLocalScreenStreamEnabled(e){this._publishLocalScreenStreamEnabled=e}updateStreams(){return I(this,null,function*(){yield this.cameraStreamInfo.process(this.streamInfos),yield this.screenStreamInfo.process(this.streamInfos),this.emit("publishupdate")})}setAvailableCameraDeviceId(){return I(this,null,function*(){var e,t,i,s;if((e=this.cameraStreamInfo.cameraVideoConstraints)!=null&&e.deviceId){let n=(t=this.cameraStreamInfo.cameraVideoConstraints)==null?void 0:t.deviceId;const c=yield J.AliRTS.getCameraList();c.find(o=>o.deviceId===n)||(n=(s=(i=c.find(o=>!!o.deviceId))==null?void 0:i.deviceId)!=null?s:""),this.cameraStreamInfo.cameraVideoConstraints.deviceId=n}})}setAvailableMicrophoneDeviceId(){return I(this,null,function*(){var e,t,i,s;if((e=this.cameraStreamInfo.micAudioConstraints)!=null&&e.deviceId){let n=(t=this.cameraStreamInfo.micAudioConstraints)==null?void 0:t.deviceId;const c=yield J.AliRTS.getMicList();c.find(o=>o.deviceId===n)||(n=(s=(i=c.find(o=>!!o.deviceId))==null?void 0:i.deviceId)!=null?s:""),this.cameraStreamInfo.micAudioConstraints.deviceId=n}})}createLocalStream(e){return I(this,null,function*(){var u;const{screen:t,mediaStream:i,videoProfile:s,screenProfile:n}=e;let{video:c,audio:o}=e;const l=(p=>{const{audio:h,video:f,screen:g}=p;if(f&&g)throw new U(B.ERR_INNER,"create stream error, cannot create video && screen together");return!!(f||h||g)})(e);let d;if(l){i||(c===!0&&this.cameraStreamInfo.cameraVideoConstraints?(yield this.setAvailableCameraDeviceId(),c=X({},this.cameraStreamInfo.cameraVideoConstraints)):typeof c=="object"&&(yield this.setAvailableCameraDeviceId(),c=X(X({},c),this.cameraStreamInfo.cameraVideoConstraints)),o===void 0&&this.audioCaptureDisabled?o=!1:o&&(o===!0&&this.cameraStreamInfo.micAudioConstraints?(yield this.setAvailableMicrophoneDeviceId(),o=X({},this.cameraStreamInfo.micAudioConstraints)):typeof o=="object"&&(yield this.setAvailableMicrophoneDeviceId(),o=X(X({},o),this.cameraStreamInfo.micAudioConstraints)),this._audioCaptureDisabled=!1));const p=Date.now();try{d=yield J.AliRTS.createStream({audio:o,video:c,screen:t,custom:!!i,mediaStream:i,skipProfile:!0}),T.info(`[${Yt.logName}]`,"createLocalStream",{audio:o,video:c,screen:t,custom:!!i,time:Date.now()-p}),o&&!i&&this.slsReporter.reportAudio(null,Date.now()-p,((u=d==null?void 0:d.audioTrack)==null?void 0:u.label)||""),t&&!i&&this.slsReporter.reportScreen(null,Date.now()-p)}catch(h){throw o&&!i&&this.slsReporter.reportAudio(h,Date.now()-p,""),t&&!i&&this.slsReporter.reportScreen(null,Date.now()-p),h}if(t)yield this.screenStreamInfo.updateSource(d,wi.Screen,Hi.Screen),yield this.setScreenProfile(n||En),this.setScreenContentHint(),this.publishingScreenVideoStream=void 0;else if(yield this.cameraStreamInfo.updateSource(d,wi.Camera,Hi.Microphone),d.hasVideo&&(yield this.setVideoProfile(s||In),this.setVideoContentHint(),this.publishingCameraVideoStream=void 0),d.hasAudio&&typeof o=="boolean"){const h=this.cameraStreamInfo.audioProfile;h&&(yield d.setAudioProfile(h))}}return J.AliRTS.SystenUtil.isIos&&J.AliRTS.SystenUtil.compareVersion("15.1")&&!J.AliRTS.SystenUtil.compareVersion("15.2")&&(yield Ht(1e3)),yield this.updateStreams(),d})}stopLocalStream(e){return I(this,null,function*(){const{screen:t,video:i,audio:s}=e!=null?e:{};let n=!1;i&&this.cameraStreamInfo.originVideoTrack&&(n=!0,this.cameraStreamInfo.stopVideo(),this.publishingCameraVideoStream=void 0),s&&this.cameraStreamInfo.originAudioTrack&&(n=!0,this.cameraStreamInfo.stopAudio()),t&&this.screenStreamInfo.originVideoTrack&&(n=!0,this.screenStreamInfo.stop(),this.publishingScreenVideoStream=void 0,this.slsReporter.reportScreenStop(null)),n&&(yield this.updateStreams())})}get publishStreams(){const{publishLocalVideoStreamEnabled:e,publishLocalAudioStreamEnabled:t,publishLocalScreenStreamEnabled:i}=this;return{video:e?this.cameraStreamInfo.publishVideoStream:void 0,videoSmall:e?this.cameraStreamInfo.publishDualVideoStream:void 0,audio:t?this.cameraStreamInfo.publishAudioStream:void 0,screen:i?this.screenStreamInfo.publishVideoStream:void 0}}createHTTPPublishStream(){return I(this,null,function*(){var o,l,d,u;let e,t,i,s,n=!1;const c=this.publishStreams;try{if(!(c.audio||c.video||c.videoSmall||c.screen))throw T.error(`[${Yt.logName}]`,"no tracks founded"),new U(B.ERR_SDK_PUBLISH_INVAILD,"no tracks founded");const p=new MediaStream;(o=c.audio)!=null&&o.audioTrack&&p.addTrack(c.audio.audioTrack),(l=c.video)!=null&&l.videoTrack?(p.addTrack(c.video.videoTrack),i=c.videoSmall,s=c.screen):(d=c.screen)!=null&&d.videoTrack&&(t=D.Screen,p.addTrack((u=c.screen)==null?void 0:u.videoTrack),n=!0),e=yield Pn(p),n?(this.screenStreamInfo.cloneVideoProfile(e),this.publishingScreenVideoStream=e):(this.cameraStreamInfo.cloneVideoProfile(e),this.publishingCameraVideoStream=e),this.cameraStreamInfo.cloneAudioProfile(e)}catch(p){}return{publishStream:e,videoSmallStream:i,screenStream:s,vMsid:t}})}stop(){this.cameraStreamInfo.stop(),this.screenStreamInfo.stop(),this.updateStreams()}setVideoProfile(e,t,i=!1){return I(this,null,function*(){yield this.cameraStreamInfo.updateVideoProfile(e,t,i),this.publishingCameraVideoStream&&this.cameraStreamInfo.cloneVideoProfile(this.publishingCameraVideoStream)})}setVideoContentHint(e){this.cameraStreamInfo.setVideoContentHint(e)}setAudioProfile(e){return I(this,null,function*(){var t;yield this.cameraStreamInfo.updateAudioProfile(e),yield(t=this.publishingCameraVideoStream)==null?void 0:t.setAudioProfile(e)})}setScreenProfile(e,t){return I(this,null,function*(){yield this.screenStreamInfo.updateVideoProfile(e,t),this.publishingScreenVideoStream&&this.screenStreamInfo.cloneVideoProfile(this.publishingScreenVideoStream)})}setScreenContentHint(e){this.screenStreamInfo.setVideoContentHint(e)}setCameraVideoConstraints(e){var t;this.cameraStreamInfo.cameraVideoConstraints=X(X({},(t=this.cameraStreamInfo.cameraVideoConstraints)!=null?t:{}),e)}setMicAudioConstraints(e){var t;this.cameraStreamInfo.micAudioConstraints=X(X({},(t=this.cameraStreamInfo.micAudioConstraints)!=null?t:{}),e)}},m(Yt,"logName","LocalStreamManager"),Yt);Et([k(([a])=>{const{audio:r,video:e,screen:t,custom:i,skipProfile:s,videoProfile:n,screenProfile:c}=a;return[{audio:r,video:e,screen:t,custom:i,skipProfile:s,videoProfile:n,screenProfile:c}]})],wt.prototype,"createLocalStream",1),Et([k(H)],wt.prototype,"stopLocalStream",1),Et([k()],wt.prototype,"createHTTPPublishStream",1),Et([k()],wt.prototype,"stop",1),Et([k(H)],wt.prototype,"setVideoProfile",1),Et([k(H)],wt.prototype,"setVideoContentHint",1),Et([k(H)],wt.prototype,"setAudioProfile",1),Et([k(H)],wt.prototype,"setScreenProfile",1),Et([k(H)],wt.prototype,"setScreenContentHint",1),Et([k(H)],wt.prototype,"setCameraVideoConstraints",1),Et([k(H)],wt.prototype,"setMicAudioConstraints",1);let $c=wt;var Nn=(a=>(a[a.PRE_PROCESSOR=0]="PRE_PROCESSOR",a[a.POST_PROCESSOR=1]="POST_PROCESSOR",a))(Nn||{}),bi=(a=>(a[a.AUDIO=0]="AUDIO",a[a.VIDEO=1]="VIDEO",a[a.BOTH=2]="BOTH",a))(bi||{});class jt extends oe{constructor(e,t=He.AliRtcSdkStreamTypeCapture,i=1){super();m(this,"name");m(this,"options");m(this,"type",0);m(this,"streamType");m(this,"trackType");m(this,"zIndex",1);m(this,"_isEnable",!0);m(this,"shouldCache",!0);m(this,"lastInputAudioTrack");m(this,"lastOutputAudioTrack");m(this,"lastInputVideoTrack");m(this,"lastOutputVideoTrack");m(this,"_hasCleared",!0);this.name=e,this.streamType=t,this.trackType=i,this.options=this.initOptions}get initOptions(){return{}}getOptions(){return this.options}init(){return I(this,null,function*(){})}enable(){this._isEnable||(this._isEnable=!0,this.init(),this.emit("enabled"))}disable(){this._isEnable&&(this._isEnable=!1,this.clear(),this.emit("disabled"))}get isEnable(){return this._isEnable}audioUpdated(e){var t,i;return((t=this.lastInputAudioTrack)==null?void 0:t.id)!==((i=e.currentAudioTrack)==null?void 0:i.id)}videoUpdated(e){var t,i;return((t=this.lastInputVideoTrack)==null?void 0:t.id)!==((i=e.currentVideoTrack)==null?void 0:i.id)}execute(e,t){return I(this,null,function*(){const i=this.shouldUpdate(e,t);this.lastInputAudioTrack=e.currentAudioTrack,this.lastInputVideoTrack=e.currentVideoTrack,this._hasCleared||i?(yield this.process(e,t),this._hasCleared=!1):this.shouldCache&&(!this.lastOutputAudioTrack||this.trackType!==2&&this.trackType!==0||this.lastOutputAudioTrack&&e.updateAudioTrack(this.lastOutputAudioTrack),!this.lastOutputVideoTrack||this.trackType!==2&&this.trackType!==1||this.lastOutputVideoTrack&&e.updateVideoTrack(this.lastOutputVideoTrack)),this.lastOutputAudioTrack=e.currentAudioTrack,this.lastOutputVideoTrack=e.currentVideoTrack})}clear(e){this._hasCleared=!0,this.lastInputAudioTrack=void 0,this.lastInputVideoTrack=void 0,this.lastOutputAudioTrack=void 0,this.lastOutputVideoTrack=void 0}}class Wc extends jt{constructor(){super("AliRtcScreenStandardize",He.AliRtcSdkStreamTypeScreen);m(this,"canvas");m(this,"lastWidth");m(this,"lastHeight");m(this,"isProcessingScreenTrack",!1);this.shouldCache=!1}get initOptions(){return{base:4}}setOptions(e){this.options=e}isSupported(){return!(typeof TransformStream=="undefined"||typeof MediaStreamTrackProcessor=="undefined"||typeof MediaStreamTrackGenerator=="undefined")}updateProcessCanvas(e,t){if(this.canvas&&this.lastWidth===e&&this.lastHeight===t)return;const i=Math.ceil(e/this.options.base)*this.options.base,s=Math.ceil(t/this.options.base)*this.options.base;if(this.canvas||(this.canvas=document.createElement("canvas")),this.canvas.width=i,this.canvas.height=s,this.lastWidth&&e>this.lastWidth||this.lastHeight&&t>this.lastHeight){const n=this.canvas.getContext("2d");n&&n.clearRect(0,0,i,s)}this.lastWidth=e,this.lastHeight=t}shouldProcess(e){var i;let t=!1;if(e.originVideoTrack&&e.videoSource===wi.Screen){const s=(i=e.originVideoTrack)==null?void 0:i.getSettings();if(s){const{width:n,height:c}=s;t=!n||!c||!(n%this.options.base===0&&c%this.options.base===0)}}return t}shouldUpdate(e){return this.shouldProcess(e)!==this.isProcessingScreenTrack}handleFrame(e){return I(this,null,function*(){var n;const{displayWidth:t,displayHeight:i}=e;if(!t||!i||t%this.options.base===0&&i%this.options.base===0)return e;this.updateProcessCanvas(t,i);const s=(n=this.canvas)==null?void 0:n.getContext("2d");if(this.canvas&&s){s.drawImage(e,0,0,t,i);const c=new VideoFrame(this.canvas,{timestamp:e.timestamp});return e.close(),c}return e})}process(e){return I(this,null,function*(){var d;if(!this.shouldProcess(e))return this.clear(e),void(this.isProcessingScreenTrack=!1);if(e.originVideoTrack){const u=e.originVideoTrack.getSettings();if(u){const{width:p,height:h}=u;if(!(!p||!h||!(p%this.options.base===0&&h%this.options.base===0)))return void this.clear(e)}}const t=new MediaStreamTrackProcessor({track:e.originVideoTrack}),i=new MediaStreamTrackGenerator({kind:"video"}),s=new MediaStream([i]),n=this,c=new TransformStream({transform(u,p){return I(this,null,function*(){const h=yield n.handleFrame(u);yield p.enqueue(h),h==null||h.close()})}});t.readable.pipeThrough(c).pipeTo(i.writable);const o=(d=s.getVideoTracks())==null?void 0:d[0];e.updateVideoTrack(o),this.isProcessingScreenTrack=!0})}clear(e){this.canvas=void 0,this.lastWidth=void 0,this.lastHeight=void 0,super.clear(e)}}class zc extends jt{constructor(){super("blankAudio",He.AliRtcSdkStreamTypeCapture,bi.BOTH);m(this,"hasTrack",!1);m(this,"oscillator",null);m(this,"audioTrack",null);m(this,"createAudioTrack",()=>{const e=new AudioContext;this.oscillator=e.createOscillator();const t=e.createGain();t.gain.value=0;const i=e.createMediaStreamDestination();this.oscillator.connect(t),t.connect(i),this.oscillator.start();const s=i.stream;return this.audioTrack=s.getAudioTracks()[0],this.audioTrack});this.zIndex=9}isSupported(){return!0}setOptions(){throw new Error("Method not implemented.")}shouldUpdate(e,t){return this.hasTrack!==t.some(i=>i.originVideoTrack||i.originAudioTrack)}process(e,t){return I(this,null,function*(){var s;const i=t.some(n=>n.originVideoTrack||n.originAudioTrack);this.hasTrack=i,i?this.audioTrack&&((s=this.oscillator)==null||s.stop(),this.oscillator=null,this.audioTrack.stop(),this.audioTrack=null):(this.audioTrack||(this.audioTrack=this.createAudioTrack()),e.updateAudioTrack(this.audioTrack))})}}var Ks=(a=>(a[a.NONE=0]="NONE",a[a.ERROR=1]="ERROR",a[a.WARN=2]="WARN",a[a.INFO=3]="INFO",a[a.DEBUG=4]="DEBUG",a[a.TRACE=5]="TRACE",a))(Ks||{});const ss=class ss{constructor(r){m(this,"name","COMMON");m(this,"instanceLevel");this.name=r||this.name}setLevel(r){this.instanceLevel=r}getEffectiveLevel(){return this.instanceLevel!==void 0?this.instanceLevel:ss.LEVEL}info(...r){this.getEffectiveLevel()>=3&&this.print(Ks[3],...r)}warn(...r){this.getEffectiveLevel()>=2&&this.print(Ks[2],...r)}print(r,...e){const t=r.toLowerCase();t&&console[t](`[${r}][${this.name}]`,...e)}};m(ss,"LEVEL",0);let Js=ss;class Kc{constructor(){m(this,"logger",new Js("AudioMixer"));m(this,"audioContext",yt.getInstance());m(this,"audioDestination",this.audioContext.createMediaStreamDestination());m(this,"audioTrack",(r=>r.getAudioTracks()[0])(this.audioDestination.stream));m(this,"sourceNodeMap",{})}get sourceNodeList(){return Object.values(this.sourceNodeMap).map(r=>r.sourceNode).filter(r=>!!r)}get gainNodeList(){return Object.values(this.sourceNodeMap).map(r=>r.gainNode).filter(r=>!!r)}get sourceCount(){return this.sourceNodeList.length}resume(){var r;return(r=this.audioContext)==null?void 0:r.resume()}addTrack(r){this.connectTrack(r)}hasTrack(r){return!!this.sourceNodeMap[r]}removeTrack(r){const{sourceNode:e,gainNode:t}=this.sourceNodeMap[r]||{};t==null||t.disconnect(),e==null||e.disconnect(),delete this.sourceNodeMap[r],e?this.logger.info("SourceNode disconnected. Active source node:",this.sourceNodeList.length):this.logger.warn(`SourceNode ${r} does not exit. Active source node: ${this.sourceNodeList.length}`)}getAudioTrack(){return this.audioTrack}setVolume(r,e){const{gainNode:t}=this.sourceNodeMap[e]||{};t?(this.logger.info(`Setting node(${e}) volume to ${this.scale(r)}`),t.gain.value=this.scale(r)):this.logger.warn(`GainNode ${e} does not exit.`)}reset(){this.disconnectSourceNode(),this.sourceNodeMap={}}dispose(){var r;this.reset(),(r=this.audioTrack)==null||r.stop(),this.audioDestination.disconnect()}connectTrack(r){if(!this.audioContext)return this.logger.warn("AudioContext not initialized");let e=new MediaStream;e.addTrack(r);const t=this.audioContext.createMediaStreamSource(e),i=this.audioContext.createGain();i.gain.value=1,t.connect(i),i.connect(this.audioDestination),this.sourceNodeMap[r.id]={track:r,sourceNode:t,gainNode:i},this.logger.info("New sourceNode connected. Active source node:",this.sourceNodeList.length)}disconnectSourceNode(){this.sourceNodeList.forEach(r=>r.disconnect()),this.gainNodeList.forEach(r=>r.disconnect())}scale(r){return r/100}}class Jc extends jt{constructor(){super("audioMixer",He.AliRtcSdkStreamTypeCapture,bi.AUDIO);m(this,"audioMixer");m(this,"primaryAudioTrackId");m(this,"screenAudioTrackId");m(this,"dirty",!1);this.zIndex=8}get initOptions(){return{audio:1,screen:1}}setOptions(e){Object.entries(e).forEach(([t,i])=>{this.isValidVolume(i)&&(this.options[t]=i)}),this.dirty=!0,this.emit("updated")}isSupported(){return"AudioContext"in window}shouldUpdate(e,t){var n,c;if(e.type!==He.AliRtcSdkStreamTypeCapture)return!1;const i=t.find(o=>o.type===He.AliRtcSdkStreamTypeCapture),s=t.find(o=>o.type===He.AliRtcSdkStreamTypeScreen);return!(this.primaryAudioTrackId===((n=i==null?void 0:i.currentAudioTrack)==null?void 0:n.id)&&this.screenAudioTrackId===((c=s==null?void 0:s.currentAudioTrack)==null?void 0:c.id)&&!this.dirty)}process(e,t){return I(this,null,function*(){var c,o;this.dirty=!1;const i=t.find(l=>l.type===He.AliRtcSdkStreamTypeScreen),s=e.currentAudioTrack,n=i==null?void 0:i.currentAudioTrack;if(!n&&this.options.audio===1)return this.audioMixer&&(this.audioMixer.dispose(),this.audioMixer=void 0),this.primaryAudioTrackId=s==null?void 0:s.id,void e.updateAudioTrack(s);this.audioMixer||(this.audioMixer=new Kc),yield this.audioMixer.resume(),this.primaryAudioTrackId&&(s==null?void 0:s.id)!==this.primaryAudioTrackId&&((c=this.audioMixer)==null||c.removeTrack(this.primaryAudioTrackId)),s&&!this.audioMixer.hasTrack(s==null?void 0:s.id)&&this.audioMixer.addTrack(s),this.primaryAudioTrackId=s==null?void 0:s.id,this.screenAudioTrackId&&(n==null?void 0:n.id)!==this.screenAudioTrackId&&((o=this.audioMixer)==null||o.removeTrack(this.screenAudioTrackId)),n&&!this.audioMixer.hasTrack(n==null?void 0:n.id)&&this.audioMixer.addTrack(n),this.screenAudioTrackId=n==null?void 0:n.id,this.updateVolume(),e.updateAudioTrack(this.audioMixer.getAudioTrack())})}isValidVolume(e){return e!==void 0&&e>=0&&e<=4}updateVolume(){this.audioMixer&&(this.primaryAudioTrackId&&this.audioMixer.setVolume(100*this.options.audio,this.primaryAudioTrackId),this.screenAudioTrackId&&this.audioMixer.setVolume(100*this.options.screen,this.screenAudioTrackId))}clear(e){var t;(t=this.audioMixer)==null||t.dispose(),super.clear(e)}}class qc extends jt{constructor(){super(...arguments);m(this,"isProcessing",!1);m(this,"videoScaler")}get initOptions(){return{width:320,height:180,frameRate:15}}setOptions(e){var t;this.options=e,(t=this.videoScaler)==null||t.updateOptions(e)}isSupported(){return As.isSupport()}shouldUpdate(e){const t=!!e.currentVideoTrack;return this.isProcessing!==t}process(e){return I(this,null,function*(){if(e.currentVideoTrack){if(this.isProcessing=!0,!this.videoScaler){const i=this.options||this.initOptions;this.videoScaler=As.getInstance(e.currentVideoTrack,i)}const t=this.videoScaler.getVideoTrack();t&&e.updateDualVideoTrack(t)}else this.isProcessing&&this.clear()})}clear(e){var t;super.clear(e),this.isProcessing=!1,e==null||e.updateDualVideoTrack(),(t=this.videoScaler)==null||t.dispose()}}function Si(a,r,e,t){return new(e||(e=Promise))(function(i,s){function n(l){try{o(t.next(l))}catch(d){s(d)}}function c(l){try{o(t.throw(l))}catch(d){s(d)}}function o(l){var d;l.done?i(l.value):(d=l.value,d instanceof e?d:new e(function(u){u(d)})).then(n,c)}o((t=t.apply(a,r||[])).next())})}var Xt,Nt;function xn(){return Si(this,void 0,void 0,function*(){let a=!1;try{a=yield(()=>I(this,null,function*(){return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]))}))()}catch(r){a=!1}return console.log("isSupportedSIMD",a),a})}typeof SuppressedError=="function"&&SuppressedError,(Nt=Xt||(Xt={}))[Nt.ERROR=0]="ERROR",Nt[Nt.WARN=1]="WARN",Nt[Nt.INFO=2]="INFO",Nt[Nt.LOG=3]="LOG",Nt[Nt.DEBUG=4]="DEBUG";class Ie{static error(...r){var e;Ie.logLevel>=Xt.ERROR&&((e=console.error)===null||e===void 0||e.call(console,`[${Ie.logTag}] `,...r))}static warn(...r){var e;Ie.logLevel>=Xt.WARN&&((e=console.warn)===null||e===void 0||e.call(console,`[${Ie.logTag}] `,...r))}static info(...r){var e;Ie.logLevel>=Xt.INFO&&((e=console.info)===null||e===void 0||e.call(console,`[${Ie.logTag}] `,...r))}static log(...r){var e;Ie.logLevel>=Xt.LOG&&((e=console.log)===null||e===void 0||e.call(console,`[${Ie.logTag}] `,...r))}static debug(...r){var e;Ie.logLevel>=Xt.DEBUG&&((e=console.debug)===null||e===void 0||e.call(console,`[${Ie.logTag}] `,...r))}}Ie.logLevel=Xt.WARN,Ie.logTag="aliyun-audio-3a";class Gc{}class On extends Gc{static isSupported(){return function(){if(typeof window=="object"&&window!==null){const r="AudioWorklet"in window,e="WebAssembly"in window;return r&&e}return!1}()}static isSupportedSIMD(){return Si(this,void 0,void 0,function*(){return yield xn()})}static setLogger(r){Ie.logLevel=r}constructor(r){super(),this.channelCount=1,this.sampleRate=48e3,this.collectDumpOutputData=[],this.collectDumpNearInputData=[],this.collectDumpFarInputData=[],this.collectDumpMetaData=[],this.statUpdateTimer=0,this.statUpdateInterval=5e3,this.options=Object.assign({aecOn:!0,ansOn:!0,agcOn:!0,hdOn:!1,ansMode:1,dumpOn:!1,aiaecOn:!1,wasmCdnPath:"https://g.alicdn.com/code/npm/@ali/aliyun-audio-3a/0.0.6/"},r||{})}initWASM(r,e,t){return Si(this,void 0,void 0,function*(){Ie.log("initWASM",r,e,t);const i=n=>Si(this,void 0,void 0,function*(){try{const c=yield fetch(n,{credentials:"same-origin"});return c.ok||this.onLoadError(new Error(`Failed to fetch WASM: ${c.status}:${c.statusText}, url:${n}`)),c.arrayBuffer()}catch(c){return this.onLoadError(new Error("WASM load error")),Ie.error("Error fetching WASM:",c),new Uint8Array(0)}}),s=n=>Si(this,void 0,void 0,function*(){return fetch(n).then(c=>c.text())});try{const n=yield xn(),c=this.options.wasmCdnPath+"audio_module_v2.wasm",o=this.options.wasmCdnPath+"audio_module_v2_simd.wasm",d=yield i(n?o:c),u=this.options.wasmCdnPath+"audio_module_v2.js",p=this.options.wasmCdnPath+"audio_module_v2_simd.js",h=n?p:u,f=yield s(h);r.port.postMessage(Object.assign({type:"init",channelCount:e,sampleRate:t,wasmBuffer:d,isSupportSIMD:n,audioModuleScript:f,logLevel:Ie.logLevel},this.options),[d])}catch(n){Ie.error("Error initializing WASM:",n),this.onLoadError(new Error("WASM init error"))}r.port.onmessage=n=>{n.data.type==="init_done"&&this.onLoadSuccess(void 0),n.data.type==="dump_output_data"&&this.onDumpOutputData(n.data.data),n.data.type==="dump_near_data"&&this.onDumpNearInputData(n.data.data),n.data.type==="dump_far_data"&&this.onDumpFarInputData(n.data.data),n.data.type==="dump_meta_data"&&this.onDumpMeatData(n.data.data),n.data.type==="output_log"&&this.onOutputLog(n.data.data),n.data.type==="apm_stat_data"&&this.onStatData(n.data.data)}})}createProcessor(r,e,t,i,s){return Si(this,void 0,void 0,function*(){this.audioContext=r,this.audioContext.resume(),this.channelCount=t,this.sampleRate=i;try{const o=new Blob(['!function(){"use strict";var kl=Object.defineProperty,Pl=Object.defineProperties;var Dl=Object.getOwnPropertyDescriptors;var as=Object.getOwnPropertySymbols,Ml=Object.getPrototypeOf,oo=Object.prototype.hasOwnProperty,co=Object.prototype.propertyIsEnumerable,Ll=Reflect.get;var dr=(z,J,oe)=>J in z?kl(z,J,{enumerable:!0,configurable:!0,writable:!0,value:oe}):z[J]=oe,X=(z,J)=>{for(var oe in J||(J={}))oo.call(J,oe)&&dr(z,oe,J[oe]);if(as)for(var oe of as(J))co.call(J,oe)&&dr(z,oe,J[oe]);return z},vt=(z,J)=>Pl(z,Dl(J));var Wt=(z,J)=>{var oe={};for(var at in z)oo.call(z,at)&&J.indexOf(at)<0&&(oe[at]=z[at]);if(z!=null&&as)for(var at of as(z))J.indexOf(at)<0&&co.call(z,at)&&(oe[at]=z[at]);return oe};var m=(z,J,oe)=>(dr(z,typeof J!="symbol"?J+"":J,oe),oe);var ur=(z,J,oe)=>Ll(Ml(z),oe,J);var I=(z,J,oe)=>new Promise((at,Vt)=>{var pi=nt=>{try{yt(oe.next(nt))}catch(Rt){Vt(Rt)}},mi=nt=>{try{yt(oe.throw(nt))}catch(Rt){Vt(Rt)}},yt=nt=>nt.done?at(nt.value):Promise.resolve(nt.value).then(pi,mi);yt((oe=oe.apply(z,J)).next())});function t(t,e,a,n){return new(a||(a=Promise))((function(s,i){function o(t){try{h(n.next(t))}catch(t){i(t)}}function r(t){try{h(n.throw(t))}catch(t){i(t)}}function h(t){var e;t.done?s(t.value):(e=t.value,e instanceof a?e:new a((function(t){t(e)}))).then(o,r)}h((n=n.apply(t,e||[])).next())}))}var e;"function"==typeof SuppressedError&&SuppressedError,function(t){t[t.ERROR=0]="ERROR",t[t.WARN=1]="WARN",t[t.INFO=2]="INFO",t[t.LOG=3]="LOG",t[t.DEBUG=4]="DEBUG"}(e||(e={}));class a{static error(...t){var n;a.logLevel>=e.ERROR&&(null===(n=console.error)||void 0===n||n.call(console,`[${a.logTag}] `,...t))}static warn(...t){var n;a.logLevel>=e.WARN&&(null===(n=console.warn)||void 0===n||n.call(console,`[${a.logTag}] `,...t))}static info(...t){var n;a.logLevel>=e.INFO&&(null===(n=console.info)||void 0===n||n.call(console,`[${a.logTag}] `,...t))}static log(...t){var n;a.logLevel>=e.LOG&&(null===(n=console.log)||void 0===n||n.call(console,`[${a.logTag}] `,...t))}static debug(...t){var n;a.logLevel>=e.DEBUG&&(null===(n=console.debug)||void 0===n||n.call(console,`[${a.logTag}] `,...t))}}a.logLevel=e.WARN,a.logTag="aliyun-audio-3a";const n=Float32Array.BYTES_PER_ELEMENT,s=Uint16Array.BYTES_PER_ELEMENT;class i{constructor(t,e,a,n,s){this._channelData=[],this._name=t,this._isInitialized=!1,this._module=e,this._length=a,this._ringLength=2*a,this._maxChannelCount=s?Math.min(s,32):n,this._channelCount=n,this._allocateHeap(),this._isInitialized=!0,this._readIndex=0,this._writeIndex=0,this._framesAvailable=0,this._channelDataLocal=[];for(let t=0;t<this._channelCount;++t)this._channelDataLocal[t]=new Float32Array(this._ringLength)}_allocateHeap(){const t=this._length*n,e=this._channelCount*t;this._dataPtr=this._module._malloc(e),this._channelData=[];for(let e=0;e<this._channelCount;++e){const a=this._dataPtr+e*t,n=a+t;this._channelData[e]=this._module.HEAPF32.subarray(a>>s,n>>s)}}adaptChannel(t){t<this._maxChannelCount&&(this._channelCount=t)}get length(){return this._isInitialized?this._length:null}get numberOfChannels(){return this._isInitialized?this._channelCount:null}get maxChannelCount(){return this._isInitialized?this._maxChannelCount:null}getChannelData(t){return void 0!==t&&t>=this._channelCount?null:void 0===t?this._channelData:this._channelData[t]}getHeapAddress(){return this._dataPtr}getPointer(){return this._dataPtr}free(){this._isInitialized=!1,null!==this._dataPtr&&this._module._free(this._dataPtr),this._channelData=[]}get framesAvailable(){return this._framesAvailable}push(t){const e=t[0].length;for(let a=0;a<e;++a){for(let e=0;e<this._channelCount;++e)this._channelDataLocal[e][this._writeIndex]=t[e][a];this._writeIndex=(this._writeIndex+1)%this._ringLength}this._framesAvailable+=e,this._framesAvailable>this._ringLength&&(console.warn(this._name,"Too many frames available, overflow"),this._framesAvailable=this._ringLength,this._writeIndex=0)}pull(t){if(0===this._framesAvailable)return void console.warn(this._name,"No frames available");const e=t[0].length;for(let a=0;a<e;++a){for(let e=0;e<this._channelCount;++e)t[e][a]=this._channelDataLocal[e][this._readIndex];this._readIndex=(this._readIndex+1)%this._ringLength}this._framesAvailable-=e,this._framesAvailable<0&&(this._framesAvailable=0,this._readIndex=0)}}class o{constructor(t){this.inited=!1,this.handle=null,this.channelCount=1,this.isEnable=!0,this.dumpAudioData=!1,this.kernelBufferSize=512,this.node=t,this.onDumpOutputDataFunction=null,this.onDumpNearDataFunction=null,this.onDumpFarDataFunction=null,this.onDumpMetaDataFunction=null,this.wasmInvoker=null,this._nearAudioBuffer={},this._outputAudioBuffer={}}destructor(){this.wasmInvoker=null,this.handle=null}init(n){return t(this,void 0,void 0,(function*(){const{wasmBuffer:t,audioModuleScript:s,channelCount:o=1,sampleRate:r=44100,dumpAudioData:h=!1,logLevel:l=e.DEBUG}=n;a.logLevel=l,a.log("AudioAPM init",JSON.stringify(n)),this.channelCount=o,this.dumpAudioData=h;try{const e=new Function(`let module={};let exports={};${s}; return module`)();this.wasmInvoker=yield e.exports({wasmBinary:t})}catch(t){this.node.port.postMessage({type:"error",message:"audioModule init error"}),a.error(t)}this._nearAudioBuffer=new i("inBuffer",this.wasmInvoker,this.kernelBufferSize,2*this.channelCount,32),this._outputAudioBuffer=new i("outBuffer",this.wasmInvoker,this.kernelBufferSize,this.channelCount,32);const u=this.wasmInvoker.addFunction(((t,e)=>{const a=this.wasmInvoker.HEAPU8.subarray(t,t+e),n=String.fromCharCode.apply(null,a);this.node&&this.node.port&&this.node.port.postMessage({type:"output_log",message:"output_log",data:n})}),"vii");if(this.wasmInvoker.__apm_log_callback(u),this.handle=this.wasmInvoker.__apm_create(n.aecOn?1:0,n.ansOn?1:0,n.agcOn?1:0,n.hdOn?1:0,r,o,n.dumpOn?1:0,this.kernelBufferSize),n.aiaecOn){const t=102;this.wasmInvoker.__apm_set_param(this.handle,t,7)}if(n.useHardOnly){const t=108;this.wasmInvoker.__apm_set_param(this.handle,t,1)}this.node.port.postMessage({type:"init_done",message:"init done"}),this.inited=!0}))}getStatData(){if(this.wasmInvoker&&this.isEnable){let t=this.wasmInvoker.__apm_get_stat(this.handle),e=this.wasmInvoker.UTF8ToString(t);this.wasmInvoker._free(t),this.node&&this.node.port&&this.node.port.postMessage({type:"apm_stat_data",message:"apm_stat_data",data:e})}}onOutputLog(t){console.log("[WASM_LOG]",t)}destory(){return t(this,void 0,void 0,(function*(){var t;try{null===(t=this.wasmInvoker)||void 0===t||t.__apm_destory(this.handle),this.inited=!1}catch(t){a.error(t)}finally{this.handle=null}}))}enable(){this.isEnable=!0,a.log("APM enable")}disable(){this.isEnable=!1,a.log("APM disable")}getStat(){if(null==this.wasmInvoker||null==this.handle)return"";let t=this.wasmInvoker.__apm_get_stat(this.handle),e=this.wasmInvoker.UTF8ToString(t);return this.wasmInvoker._free(t),e}startDump(){this.onDumpOutputDataFunction=this.wasmInvoker.addFunction(((t,e)=>{const a=this.wasmInvoker.HEAPU8.subarray(t,t+e),n=new Uint8Array(a);this.node&&this.node.port&&this.node.port.postMessage({type:"dump_output_data",message:"dump_output_data",data:n})}),"vii"),this.onDumpNearDataFunction=this.wasmInvoker.addFunction(((t,e)=>{const a=this.wasmInvoker.HEAPU8.subarray(t,t+e),n=new Uint8Array(a);this.node&&this.node.port&&this.node.port.postMessage({type:"dump_near_data",message:"dump_near_data",data:n})}),"vii"),this.onDumpFarDataFunction=this.wasmInvoker.addFunction(((t,e)=>{const a=this.wasmInvoker.HEAPU8.subarray(t,t+e),n=new Uint8Array(a);this.node&&this.node.port&&this.node.port.postMessage({type:"dump_far_data",message:"dump_far_data",data:n})}),"vii"),this.onDumpMetaDataFunction=this.wasmInvoker.addFunction(((t,e)=>{const a=this.wasmInvoker.HEAPU8.subarray(t,t+e),n=new Uint8Array(a);this.node&&this.node.port&&this.node.port.postMessage({type:"dump_meta_data",message:"dump_meta_data",data:n})}),"vii"),this.wasmInvoker.__apm_dump_start(this.handle,this.onDumpOutputDataFunction,this.onDumpNearDataFunction,this.onDumpFarDataFunction,this.onDumpMetaDataFunction)}stopDump(){this.wasmInvoker.__apm_dump_stop(this.handle),this.wasmInvoker&&(this.wasmInvoker.removeFunction(this.onDumpOutputDataFunction),this.wasmInvoker.removeFunction(this.onDumpNearDataFunction),this.wasmInvoker.removeFunction(this.onDumpFarDataFunction),this.wasmInvoker.removeFunction(this.onDumpMetaDataFunction))}process(t,e,a){if(!this.inited||!this.isEnable){for(let e=0;e<this.channelCount;e++){a[e].set(t[e])}return}const n=this.channelCount;let s=0;if(this.handle&&this.isEnable){const i=t[0].length,o=[];for(let a=0;a<n;a++)e[a]&&e[a].length>0&&(s=1),o.push(t[a]||new Float32Array(i).fill(0)),o.push(e[a]||new Float32Array(i).fill(0));if(this._nearAudioBuffer.push(o),this._nearAudioBuffer.framesAvailable>=this.kernelBufferSize){this._nearAudioBuffer.pull(this._nearAudioBuffer.getChannelData()),this.wasmInvoker.__apm_process_new(this.handle,this._nearAudioBuffer.getHeapAddress(),this._outputAudioBuffer.getHeapAddress(),n,s);const t=this._outputAudioBuffer.getChannelData();this._outputAudioBuffer.push(t)}this._outputAudioBuffer.pull(a)}}}class r extends AudioWorkletProcessor{constructor(){super(),this.apm=new o(this),this.port.onmessage=t=>{const e=t.data||{};switch(a.log("onmessage data",e),e.type){case"init":this.apm.init(e);break;case"destroy":this.apm.destory();break;case"enable":this.apm.enable();break;case"disable":this.apm.disable();break;case"start_dump":this.apm.startDump();break;case"stop_dump":this.apm.stopDump();break;case"get_stat_data":this.apm.getStatData();break;default:a.warn("Unknown message type:",e.type)}}}process(t,e){const a=t[0],n=t.length>1?t[1]:[],s=e[0];return this.apm.process(a,n,s),!0}}registerProcessor("aliyun-web-3a-processor",r)}();\n'],{type:"application/javascript"}),l=URL.createObjectURL(o);yield this.audioContext.audioWorklet.addModule(l)}catch(o){Ie.error("Failed to add module to audio worklet:",o)}let n=new AudioWorkletNode(this.audioContext,"aliyun-web-3a-processor",{numberOfInputs:2,outputChannelCount:[t]});this.workletNode=n,e.connect(n),s&&(this.farNode=s,s.connect(n,0,1));const c=this.audioContext.createMediaStreamDestination();n.connect(c),this.targetMediaTrack=c.stream.getAudioTracks()[0],yield this.initWASM(n,t,i),this.statUpdateTimer=window.setInterval(()=>{this.getStatData()},this.statUpdateInterval)})}addFarNode(r){this.workletNode&&(this.farNode&&this.farNode.disconnect(this.workletNode),r&&(this.farNode=r,r.connect(this.workletNode,0,1)))}getStatData(){var r;try{(r=this.workletNode)===null||r===void 0||r.port.postMessage({type:"get_stat_data"})}catch(e){Ie.error("Failed to post message to worklet node:",e)}}destroy(){if(this.statUpdateTimer&&window.clearInterval(this.statUpdateTimer),this.audioContext&&this.workletNode&&this.workletNode.port)try{this.workletNode.port.postMessage({type:"destroy"}),this.workletNode.port.onmessage=null,this.workletNode.disconnect(),Ie.log("postMessage destroy")}catch(r){Ie.error("Failed to post message to worklet node:",r)}}startDump(){var r;try{(r=this.workletNode)===null||r===void 0||r.port.postMessage({type:"start_dump"})}catch(e){Ie.error("Failed to post message to worklet node:",e)}}stopDump(){var r;try{(r=this.workletNode)===null||r===void 0||r.port.postMessage({type:"stop_dump"})}catch(e){Ie.error("Failed to post message to worklet node:",e)}setTimeout(()=>{this.onDumpOutputData(null,!0),this.onDumpNearInputData(null,!0),this.onDumpFarInputData(null,!0),this.onDumpMeatData(null,!0)},3e3)}onDumpOutputData(r,e=!1){if(r&&r.length>0&&this.collectDumpOutputData.push(r),e&&this.collectDumpOutputData.length>0||1024*this.collectDumpOutputData.length>=this.getMaxDumpBytes()){let t=new Blob(this.collectDumpOutputData);this.onDumpData(t,"output_"+this.sampleRate+"hz_"+this.channelCount+"ch.pcm"),this.collectDumpOutputData=[]}}onDumpNearInputData(r,e=!1){if(r&&r.length>0&&this.collectDumpNearInputData.push(r),e&&this.collectDumpNearInputData.length>0||1024*this.collectDumpNearInputData.length>=this.getMaxDumpBytes()){let t=new Blob(this.collectDumpNearInputData);this.onDumpData(t,"near_input_"+this.sampleRate+"hz_"+this.channelCount+"ch.pcm"),this.collectDumpNearInputData=[]}}onDumpFarInputData(r,e=!1){if(r&&r.length>0&&this.collectDumpFarInputData.push(r),e&&this.collectDumpFarInputData.length>0||1024*this.collectDumpFarInputData.length>=this.getMaxDumpBytes()){let t=new Blob(this.collectDumpFarInputData);this.onDumpData(t,"far_input_"+this.sampleRate+"hz_"+this.channelCount+"ch.pcm"),this.collectDumpFarInputData=[]}}onDumpMeatData(r,e=!1){if(r&&r.length>0&&this.collectDumpMetaData.push(r),e&&this.collectDumpMetaData.length>0||1024*this.collectDumpMetaData.length>=this.getMaxDumpBytes()){let t=new Blob(this.collectDumpMetaData);this.onDumpData(t,"meta_"+this.sampleRate+"hz_"+this.channelCount+"ch.pcm"),this.collectDumpMetaData=[]}}getMaxDumpBytes(){return 600*Number(this.sampleRate.toFixed(0))*Number(this.channelCount.toFixed(0))*2}enable(){var r;if(!((r=this.workletNode)===null||r===void 0)&&r.port)try{this.workletNode.port.postMessage({type:"enable"}),Ie.log("postMessage enable")}catch(e){Ie.error("Failed to post message to worklet node:",e)}}disable(){var r;if(!((r=this.workletNode)===null||r===void 0)&&r.port)try{Ie.log("postMessage disable"),this.workletNode.port.postMessage({type:"disable"})}catch(e){Ie.error("Failed to post message to worklet node:",e)}}on(r,e){r==="loaderror"&&(this.onLoadError=e),r==="loadsuccess"&&(this.onLoadSuccess=e),r==="dumpdata"&&(this.onDumpData=e),r==="outputlog"&&(this.onOutputLog=e),r==="statdata"&&(this.onStatData=e)}onLoadError(r){console.log("onLoadError",r)}onLoadSuccess(r){console.log("onLoadSuccess",r)}onDumpData(r,e){console.log("onDumpData",r,e)}onOutputLog(r){console.log("[WASM]",r)}onStatData(r){console.log("onStatData:",r)}}class Xc extends jt{constructor(e){super("AliRtcAudioProcessPlugin",He.AliRtcSdkStreamTypeCapture,bi.AUDIO);m(this,"audioProcessor");m(this,"slsReporter");m(this,"enableSoft3ACheck",!1);m(this,"useHardOnly",!1);m(this,"lastDiffOutputLog","");m(this,"audioContext",new AudioContext({sampleRate:48e3}));m(this,"farNode");m(this,"activeAudioContext",()=>{var e;(e=this.audioContext)==null||e.resume(),document.removeEventListener("click",this.activeAudioContext)});m(this,"createNode",e=>this.audioContext.createMediaStreamSource(new MediaStream([e])));this.options=e,this.slsReporter=e==null?void 0:e.slsReporter,this.enableSoft3ACheck=(e==null?void 0:e.enableSoft3ACheck)||!1,this.useHardOnly=(e==null?void 0:e.useHardOnly)||!1,this.zIndex=7,document.addEventListener("click",this.activeAudioContext)}audioUpdated(e){var t,i;return((t=this.lastInputAudioTrack)==null?void 0:t.id)!==((i=e.currentAudioTrack)==null?void 0:i.id)}videoUpdated(e){return console.log("videoUpdated",e),!1}setOptions(e){var t;!this.farNode&&e.farMediaStream&&(this.farNode=this.audioContext.createMediaStreamSource(e.farMediaStream),this.audioProcessor&&((t=this.audioProcessor)==null||t.addFarNode(this.farNode)),this.options=X(X({},this.options),e))}isSupported(){return On.isSupported()}shouldUpdate(e){return!!(e.originAudioTrack&&!this.audioProcessor||!e.originAudioTrack&&this.audioProcessor)}process(e){return I(this,null,function*(){var t;if(!e.currentAudioTrack)return e.updateAudioTrack(),void this.clear(e);if(!this.audioProcessor){this.audioProcessor=new On({aecOn:!0,ansOn:!0,agcOn:!0,dumpOn:((t=this.options)==null?void 0:t.dumpAudioData)||!1,aiaecOn:this.options.aiaecOn||!1,useHardOnly:this.useHardOnly,wasmCdnPath:this.options.wasmCdnPath||"https://g.alicdn.com/code/npm/@ali/aliyun-audio-3a/0.0.6/"}),this.audioProcessor.on("dumpdata",(s,n)=>{let c=3e3;n.includes("far")?c=5e3:n.includes("output")?c=1e4:n.includes("meta")&&(c=8e3),setTimeout(()=>{const o=URL.createObjectURL(s),l=document.createElement("a");l.href=o,l.download=n,document.body.appendChild(l),l.click(),document.body.removeChild(l)},c)}),this.audioProcessor.on("loadsuccess",()=>{var s,n;this.enableSoft3ACheck||e.updateAudioTrack((s=this.audioProcessor)==null?void 0:s.targetMediaTrack),this.options.dumpAudioData&&((n=this.audioProcessor)==null||n.startDump())}),this.audioProcessor.on("loaderror",s=>{this.emit("error",s)}),this.audioProcessor.on("outputlog",s=>{s!=null&&s.includes("diff")&&(this.lastDiffOutputLog=s||"")}),this.audioProcessor.on("statdata",s=>{var n;if(s)try{let c=s;if(this.lastDiffOutputLog){const o=this.extractDiffValue(this.lastDiffOutputLog),l=JSON.parse(s);o!==null&&(l.diff=o);const d=this.extractLeakValue(this.lastDiffOutputLog);d!==null&&(l.leak=d),c=JSON.stringify(l)}(n=this.slsReporter)==null||n.reportPublishAudio3A("","","",c)}catch(c){}});const i=this.createNode(e.currentAudioTrack);yield this.audioProcessor.createProcessor(this.audioContext,i,1,48e3,this.farNode)}})}extractDiffValue(e){if(!e)return null;const t=e.match(/diff\s*=\s*(-?\d+\.?\d*)/);return t?parseFloat(t[1]):null}extractLeakValue(e){if(!e)return null;const t=e.match(/leak\s*=\s*(-?\d+\.?\d*)/);return t?parseFloat(t[1]):null}clear(e){var t,i,s;this.options.dumpAudioData&&((t=this.audioProcessor)==null||t.stopDump()),super.clear(e),(i=this.audioProcessor)==null||i.destroy(),this.audioProcessor=void 0,document.removeEventListener("click",this.activeAudioContext),(s=this.farNode)==null||s.disconnect(),this.farNode=void 0}dump(){var e;(e=this.audioProcessor)==null||e.stopDump()}}var Di=(a=>(a[a.Default=0]="Default",a[a.Human=1]="Human",a[a.Robot=2]="Robot",a))(Di||{}),Qc=Object.defineProperty,Yc=Object.getOwnPropertyDescriptor,Vn=(a,r,e,t)=>{for(var i,s=t>1?void 0:t?Yc(r,e):r,n=a.length-1;n>=0;n--)(i=a[n])&&(s=(t?i(r,e,s):i(s))||s);return t&&s&&Qc(r,e,s),s};const qs=(Zt=class extends oe{constructor(e,t){super();m(this,"self");m(this,"remoteUser");m(this,"sendReadyMsg",!1);m(this,"hasPubDataChannel",!1);m(this,"hasSubDataChannel",!1);m(this,"readyMsgSuccess",!1);m(this,"sendReadyMsgTimer");m(this,"startReadyMsgTime");m(this,"robotUserId");m(this,"onSubscribeDataChannel",e=>{!this.remoteUser&&e&&(this.robotUserId&&this.robotUserId!==e.userId||(this.hasSubDataChannel=!0,this.remoteUser=e,this.remoteUser.on("remoteDataChannelMessage",this.onCheckReadyMsg),this.trySendReadyMsg()))});m(this,"onCheckReadyMsg",(e,t)=>{var i,s;if(this.sendReadyMsg&&!this.readyMsgSuccess)try{const n=new TextDecoder().decode(t.data),c=JSON.parse(n);c.key==="aliyun_aigc"&&c.type==="ready_resp"&&((i=c.data)==null?void 0:i.ready)===!0&&(T.event(`[${Zt.logName}]`,"onCheckReadyMsg success"),this.readyMsgSuccess=!0,this.emit("dcready",e),(s=this.remoteUser)==null||s.off("remoteDataChannelMessage",this.onCheckReadyMsg),window.clearTimeout(this.sendReadyMsgTimer))}catch(n){}});m(this,"onDataPublishStateChange",(e,t)=>{t===ee.AliRtcStatePublished&&(this.hasPubDataChannel=!0,this.trySendReadyMsg())});this.self=e,this.self.on("dataPublishStateChanged",this.onDataPublishStateChange),this.robotUserId=t}destroy(){this.self.off("dataPublishStateChanged",this.onDataPublishStateChange),window.clearTimeout(this.sendReadyMsgTimer),this.remoteUser=void 0,this.sendReadyMsg=!1,this.hasPubDataChannel=!1,this.hasSubDataChannel=!1,this.readyMsgSuccess=!1,this.startReadyMsgTime=0}trySendReadyMsg(){T.event(`[${Zt.logName}]`,`trySendReadyMsg: pub(${this.hasPubDataChannel}, sub: ${this.hasSubDataChannel})`),this.hasPubDataChannel&&this.hasSubDataChannel&&(this.sendReadyMsg=!0,this.sendReadyMsgLoop())}sendReadyMsgLoop(e=0){return I(this,null,function*(){const t=JSON.stringify({key:"aliyun_aigc",version:"1.0",type:"ready_req",data:{ready:!0}});try{this.self.sendDataChannelMessage(new Jt(new TextEncoder().encode(t).buffer))}catch(n){}this.startReadyMsgTime||(this.startReadyMsgTime=Date.now());let i=50;const s=Date.now()-this.startReadyMsgTime;i=s<1e3?50:s<2e3?100:s<3e3?500:2e3,e>30?T.event(`[${Zt.logName}]`,"sendReadyMsgLoop fail after 30 times"):this.sendReadyMsgTimer=window.setTimeout(()=>{this.sendReadyMsgLoop(e+1)},i)})}},m(Zt,"logName","DataChannelReadyHelper"),Zt);Vn([k()],qs.prototype,"destroy",1),Vn([k()],qs.prototype,"sendReadyMsgLoop",1);let Zc=qs;class el{constructor(r){m(this,"_useSysEchoCancellation",!0);m(this,"_useSysNoiseSuppression",!0);m(this,"_useSysAutoGainControl",!0);m(this,"_useAIAEC",!1);m(this,"_enableSoft3A",!1);m(this,"_enableSoft3ACheck",!1);m(this,"_useHardOnly",!1);m(this,"_dumpAudioData",!1);m(this,"_useAudio3AConfigFromServer",!0);r&&Object.assign(this,r)}get useSysEchoCancellation(){return this._useSysEchoCancellation}set useSysEchoCancellation(r){this._useSysEchoCancellation=r}get useSysNoiseSuppression(){return this._useSysNoiseSuppression}set useSysNoiseSuppression(r){this._useSysNoiseSuppression=r}get useSysAutoGainControl(){return this._useSysAutoGainControl}set useSysAutoGainControl(r){this._useSysAutoGainControl=r}get useAIAEC(){return this._useAIAEC}set useAIAEC(r){this._useAIAEC=r}get enableSoft3A(){return this._enableSoft3A}set enableSoft3A(r){this._enableSoft3A=r}get enableSoft3ACheck(){return this._enableSoft3ACheck}set enableSoft3ACheck(r){this._enableSoft3ACheck=r}get useHardOnly(){return this._useHardOnly}set useHardOnly(r){this._useHardOnly=r}get dumpAudioData(){return this._dumpAudioData}set dumpAudioData(r){this._dumpAudioData=r}get useAudio3AConfigFromServer(){return this._useAudio3AConfigFromServer}set useAudio3AConfigFromServer(r){this._useAudio3AConfigFromServer=r}loadFromLocalConfig(r){var e,t,i,s,n,c,o,l,d;this.useAudio3AConfigFromServer=(e=r.useAudio3AConfigFromServer)!=null?e:this.useAudio3AConfigFromServer,this.useSysEchoCancellation=(t=r.useSysEchoCancellation)!=null?t:this.useSysEchoCancellation,this.useSysNoiseSuppression=(i=r.useSysNoiseSuppression)!=null?i:this.useSysNoiseSuppression,this.useSysAutoGainControl=(s=r.useSysAutoGainControl)!=null?s:this.useSysAutoGainControl,this.useAIAEC=(n=r.useAIAEC)!=null?n:this.useAIAEC,this.enableSoft3A=(c=r.enableSoft3A)!=null?c:this.enableSoft3A,this.dumpAudioData=(o=r.dumpAudioData)!=null?o:this.dumpAudioData,this.enableSoft3ACheck=(l=r.enableSoft3ACheck)!=null?l:this.enableSoft3ACheck,this.useHardOnly=(d=r.useHardOnly)!=null?d:this.useHardOnly}loadFromServerConfig(r){if(r&&typeof r=="object"){const e=ii(r,"enableSoft3A"),t=gi(r,"enableSoft3A");if(e===!0&&t===!0&&(this.enableSoft3A=!0),this.enableSoft3A){if(r.archCfgs){const i=ii(r,"enableSoft3ACheck");i!==void 0&&(this.enableSoft3ACheck=i);const s=ii(r,"useAIAEC");s!==void 0&&(this.useAIAEC=s);const n=ii(r,"useSysNoiseSuppression");n!==void 0&&(this.useSysNoiseSuppression=n);const c=ii(r,"useSysEchoCancellation");c!==void 0&&(this.useSysEchoCancellation=c);const o=ii(r,"useSysAutoGainControl");o!==void 0&&(this.useSysAutoGainControl=o)}if(r.config){const i=gi(r,"enableSoft3ACheck");i!==void 0&&(this.enableSoft3ACheck=i);const s=gi(r,"useAIAEC");s!==void 0&&(this.useAIAEC=s);const n=gi(r,"useSysNoiseSuppression");n!==void 0&&(this.useSysNoiseSuppression=n);const c=gi(r,"useSysEchoCancellation");c!==void 0&&(this.useSysEchoCancellation=c);const o=gi(r,"useSysAutoGainControl");o!==void 0&&(this.useSysAutoGainControl=o)}T.info("setAudio3AConfig:","enableSoft3A",this.enableSoft3A,", enableSoft3ACheck",this.enableSoft3ACheck,", useAIAEC",this.useAIAEC,", useSysNoiseSuppression",this.useSysNoiseSuppression,", useSysEchoCancellation",this.useSysEchoCancellation,", useSysAutoGainControl",this.useSysAutoGainControl)}}}}var tl=Object.defineProperty,il=Object.getOwnPropertyDescriptor,lt=(a,r,e,t)=>{for(var i,s=t>1?void 0:t?il(r,e):r,n=a.length-1;n>=0;n--)(i=a[n])&&(s=(t?i(r,e,s):i(s))||s);return t&&s&&tl(r,e,s),s};class et extends oe{constructor(e){super();m(this,"_loggerInstanceId","");m(this,"self");m(this,"userMap",{});m(this,"usersViewMap",{});m(this,"rtsManager");m(this,"localStreamManager");m(this,"authInfo");m(this,"signalingManager");m(this,"pluginManager");m(this,"audioMixerPlugin");m(this,"dualVideoPlugin");m(this,"blankAudioPlugin");m(this,"audioProcessorPlugin");m(this,"slsReporter");m(this,"statsMonitorId");m(this,"autoSubAudio",!0);m(this,"autoSubVideo",!0);m(this,"autoSubScreen",!0);m(this,"wantSubAudio",!0);m(this,"wantSubVideo",!0);m(this,"wantSubScreen",!0);m(this,"defaultStreamType",Ge.AliRtcVideoStreamTypeHigh);m(this,"audioMuted",!1);m(this,"playoutVolume",1);m(this,"refreshUrlTimer");m(this,"audioVolumeIndicationInterval",0);m(this,"indicationTimer",0);m(this,"parameter",{});m(this,"audio3AConfig",new el);m(this,"dcReadyHelper");m(this,"networkQualityTimer");const{signalingManager:t,slsReporter:i,parameter:s}=e;this._loggerInstanceId=e.instanceId||"",this.signalingManager=t,this.addSignalingManagerListener(),this.slsReporter=i,s&&(this.parameter=s),this.pluginManager=new Mc,this.localStreamManager=new $c(this.pluginManager,this.slsReporter),this.rtsManager=new Hc(this.localStreamManager,this.slsReporter,this.parameter),this.addRTSListener(),this.self=new Ec({rtsManager:this.rtsManager,localStreamManager:this.localStreamManager,slsReporter:this.slsReporter,signalingManager:this.signalingManager,pluginManager:this.pluginManager,audioVolumeIndicationInterval:this.audioVolumeIndicationInterval,parameter:this.parameter}),this.audioMixerPlugin=new Jc,this.pluginManager.add(this.audioMixerPlugin),this.dualVideoPlugin=new qc("dualVideoPlugin"),new J.AliRTS.SupportUtil().checkScreenCapture()&&this.pluginManager.add(new Wc)}addSignalingManagerListener(){this.signalingManager.on("onNotifyPublish",e=>{e.forEach(t=>{var i;(i=t==null?void 0:t.tracks)==null||i.forEach(s=>{var n;if(s.msid===D.Audio&&s.userdata)try{const c=JSON.parse(s.userdata);c.agent_instance&&((n=this.slsReporter)==null||n.setCustomFields({ageniid:c.agent_instance}))}catch(c){console.error("Failed to parse userdata:",c)}})}),this.slsReporter.reportConnectionLatencyEvent(Ze.RECV_NOTIFY_PUBLISH,"","",""),this._loggerInstanceId&&T.setActiveInstance(this._loggerInstanceId),T.event("[Signaling] Notify Publish ",e),e.forEach(t=>{this.onRemotePublishStateChange(t)})})}addRTSListener(){this.rtsManager.on("traceIdUpdated",(e,t)=>{if(Le.removeQueryString(this.self.url)===Le.removeQueryString(e))return void(this.self.traceId=t);const i=this.remoteUsers.find(s=>Le.removeQueryString(s.streamUrl)===Le.removeQueryString(e));i&&(i.traceId=t)}),this.rtsManager.on("reconnect",(e,t,i)=>{if(!e||e==="pc"||e==="all")return this.self.markReconnect(),void this.remoteUsers.forEach(n=>{n.markReconnect()});if(e==="pub"||e==="pub-data")return void this.self.markReconnect(i);const s=this.remoteUsers.find(n=>Le.removeQueryString(n.streamUrl)===Le.removeQueryString(t||""));s==null||s.markReconnect(i)}),this.rtsManager.on("reconnectFinish",(e,t,i)=>{if(this._loggerInstanceId&&T.setActiveInstance(this._loggerInstanceId),T.event("[RtsManager]","reconnectFinish",e,t,i),!e||e==="pc"||e==="all")return this.self.markReconnected(),void this.remoteUsers.forEach(n=>{n.markReconnected()});if(e==="pub"||e==="pub-data")return void this.self.markReconnected(i);const s=this.remoteUsers.find(n=>Le.removeQueryString(n.streamUrl)===Le.removeQueryString(t||""));s==null||s.markReconnected(i)})}isAutoSubAudio(){return this.autoSubAudio}setAutoSubAudio(e){this.autoSubAudio=e}isAutoSubVideo(){return this.autoSubVideo}setAutoSubVideo(e){this.autoSubVideo=e}isAutoSubScreen(){return this.autoSubScreen}setAutoSubScreen(e){this.autoSubScreen=e}isWantSubAudio(){return this.wantSubAudio}setWantSubAudio(e){this.wantSubAudio=e,this.remoteUsers.forEach(t=>{t.setWantSubAudio(e),t.updateSubscribe(ge.User)})}isWantSubVideo(){return this.wantSubVideo}setWantSubVideo(e){this.wantSubVideo=e,this.remoteUsers.forEach(t=>{t.setWantSubVideo(e),t.updateSubscribe(ge.User)})}isWantSubScreen(){return this.wantSubScreen}setWantSubScreen(e){this.wantSubScreen=e,this.remoteUsers.forEach(t=>{t.setWantSubScreen(e),t.updateSubscribe(ge.User)})}setRemoteDefaultVideoStreamType(e){this.defaultStreamType=e,this.remoteUsers.forEach(t=>{t.setRemoteDefaultVideoStreamType(e)})}setRemoteUserVideoStreamType(e,t){var i;(i=this.getRemoteUser(e))==null||i.setRemoteDefaultVideoStreamType(t)}setAudioMuted(e){this.audioMuted=e,this.remoteUsers.forEach(t=>{t.setAudioMuted(e)})}setLocalViewConfig(e,t){if(!e)return this.publisher.setViewConfig(null,t);const i=cs(e);i.length!==0&&i.forEach(s=>{this.publisher.resetElement(s),Object.entries(this.usersViewMap).forEach(([n,c])=>{var u,p;const{cameraViews:o=[],screenViews:l=[]}=c;let d=!1;if(o.includes(s)&&(o.splice(o.indexOf(s),1),d=!0),l.includes(s)&&(l.splice(l.indexOf(s),1),d=!0),d&&o.length===0&&l.length===0)try{_e.getInstance().removeRemoteViewConfig(((p=(u=this.authInfo)==null?void 0:u.userId)!=null?p:"")+n)}catch(h){}}),this.publisher.setViewConfig(i,t)})}setRemoteViewConfig(e,t,i){var c,o,l,d,u,p;const s=_e.getInstance();if(!t){try{s.removeRemoteViewConfig(((o=(c=this.authInfo)==null?void 0:c.userId)!=null?o:"")+e)}catch(h){}return(l=this.userMap[e])==null?void 0:l.setViewConfig(null,i)}const n=cs(t);if(n.length!==0){n.forEach(h=>{this.publisher.resetElement(h),Object.entries(this.usersViewMap).forEach(([f,g])=>{var R,_;const{cameraViews:b=[],screenViews:S=[]}=g;let v=!1;if(b.includes(h)&&(b.splice(b.indexOf(h),1),v=!0),S.includes(h)&&(S.splice(S.indexOf(h),1),v=!0),v&&f!==e&&b.length===0&&S.length===0)try{s.removeRemoteViewConfig(((_=(R=this.authInfo)==null?void 0:R.userId)!=null?_:"")+f)}catch(y){}})});try{if(n.length===1)try{s.setRemoteViewConfig(((u=(d=this.authInfo)==null?void 0:d.userId)!=null?u:"")+e,n[0])}catch(h){}}catch(h){}(p=this.userMap[e])==null||p.setViewConfig(n,i)}}get channel(){var e;return(e=this.authInfo)==null?void 0:e.channelId}get userId(){var e;return(e=this.authInfo)==null?void 0:e.userId}get remoteUsers(){return Object.values(this.userMap)}get publisher(){return this.self}get isSubscribing(){var e;return((e=this.remoteUsers)!=null?e:[]).some(t=>{const{isAudioSubscribing:i,isVideoSubscribing:s,isScreenSubscribing:n}=t;return i||s||n})}onRemotePublishStateChange(e,t=!0){var h;const{userid:i,callid:s,subscribe:n,pubid:c="",tracks:o}=e,l=(h=n==null?void 0:n.pullstreamurl)!=null?h:"";let d=this.getRemoteUser(i);if(!d)return;const u=d.streamInfo.audioTrackInfo,p=d.streamInfo.videoTrackInfo;d.updateRemoteTracks(s,l,c,o),u===d.streamInfo.audioTrackInfo&&p===d.streamInfo.videoTrackInfo||this.emit("remoteTrackAvailableChange",i,d.streamInfo.audioTrackInfo,d.streamInfo.videoTrackInfo),t&&d.updateSubscribe(ge.Publish)}setTimeoutToUpdateAllStreamUrls(e){var s;if(!e)return;let t=354e4;const i=(s=function(n){var c,o;try{const l=new URL(n),[d,u]=l.pathname.slice(1).split("/"),p=/(\w+)(web\w{5}-\w{4}-\w{4}-\w{4}-\w{12})/.exec(u),h=p==null?void 0:p[1],f=p==null?void 0:p[2],g=new URLSearchParams(l.search);return{appId:d,channelId:h,sessionId:f,timeoutTs:1e3*parseInt((o=(c=g.get("auth_key"))==null?void 0:c.split("-")[0])!=null?o:"0")}}catch(l){return null}}(e))==null?void 0:s.timeoutTs;i&&(t=i-Date.now()-6e4),this.refreshUrlTimer=window.setTimeout(()=>I(this,null,function*(){var c;const n=yield this.signalingManager.refreshUrl({pushstreamurl:this.self.url,users:this.remoteUsers.map(o=>({userid:o.userId,subscribe:{pullstreamurl:o.streamUrl}}))});n.pushstreamurl&&(this.self.url=n.pushstreamurl),(c=n.users)==null||c.forEach(o=>{var d;const l=this.getRemoteUser(o.userid);l&&((d=o.subscribe)!=null&&d.pullstreamurl)&&(l.streamUrl=o.subscribe.pullstreamurl)}),this.setTimeoutToUpdateAllStreamUrls(n.pushstreamurl)}),t)}init(e,t,i){var s;this.authInfo=e,this.self.enableAudioVolumeIndication(this.audioVolumeIndicationInterval),this.self.initInfo(e,t.pushstreamurl),this.audio3AConfig.useAudio3AConfigFromServer&&this.audio3AConfig.loadFromServerConfig((s=t==null?void 0:t.config)==null?void 0:s.data),this.setupAudioProcessingPluginIfNeeded(),i.capabilityProfile===Di.Human&&(this.dcReadyHelper=new Zc(this.self,i.robotUserId),this.dcReadyHelper.on("dcready",n=>{var c;this.emit("remoteUserSubscribedDataChannel",n),(c=this.dcReadyHelper)==null||c.destroy(),this.dcReadyHelper=void 0})),this.setTimeoutToUpdateAllStreamUrls(t.pushstreamurl),t.users.forEach(n=>{this.addUser(n,ge.InRoom)}),this.startStatsMonitor(),this.networkQualityTimer=window.setInterval(()=>I(this,null,function*(){if(this.remoteUsers.length===0)return void this.emit("networkQuality",{subscribe:{rtt:0,loss:0,quality:tt.AliRtcNetworkUnknown}});const n=yield this.rtsManager.getSubscribeNetworkQuality();this.emit("networkQuality",{subscribe:n})}),2e3)}leave(){return I(this,null,function*(){var t,i,s;this.stopIndication();let e="";try{this.stopStatsMonitor(),this.refreshUrlTimer!==void 0&&(window.clearTimeout(this.refreshUrlTimer),this.refreshUrlTimer=void 0),Object.values(this.usersViewMap).forEach(({cameraViews:n=[],screenViews:c=[]})=>{n.forEach(o=>{o.srcObject=null,o._playPromise=void 0}),c.forEach(o=>{o.srcObject=null,o._playPromise=void 0})}),this.usersViewMap={};for(let n in this.userMap)this.userMap[n]&&(this.userMap[n].clear(),delete this.userMap[n]);e=(i=(t=this.authInfo)==null?void 0:t.userId)!=null?i:"",this.self.leave(),(s=this.dcReadyHelper)==null||s.destroy(),this.dcReadyHelper=void 0,this.localStreamManager.stop(),this.rtsManager.clear(),this.authInfo=void 0,window.clearInterval(this.networkQualityTimer),this.networkQualityTimer=void 0}finally{this.stopStatsMonitor(),this.stopIndication()}try{_e.getInstance().clearAll(e)}catch(n){}})}clear(){return I(this,null,function*(){yield this.leave(),this.stopIndication(),this.self.clear(),this.pluginManager.removeAll()})}startStatsMonitor(){this.statsMonitorId=window.setInterval(()=>I(this,null,function*(){if(this.publisher){const{audio:i,video:s,candidate:n}=yield this.publisher.getStats();i&&i.length>0&&this.emit("rtcLocalAudioStats",i),s&&s.length>0&&this.emit("rtcLocalVideoStats",s),n&&this.emit("rtcStats",n)}const e=[],t=[];for(const i of this.remoteUsers){const{audio:s,video:n}=yield i.getStats();s&&s.forEach(c=>{e.push(c)}),n&&n.forEach(c=>{t.push(c)})}e.length>0&&this.emit("rtcRemoteAudioStats",e),t.length>0&&this.emit("rtcRemoteVideoStats",t)}),2e3)}stopStatsMonitor(){this.statsMonitorId&&(clearInterval(this.statsMonitorId),this.statsMonitorId=void 0)}addUser(e,t){const i=e.userid;let s=this.userMap[i];return s||(s=this.executeAddUser(i,e.displayname||"",t),this.userMap[i]=s,this.emit("remoteUserJoin",i,0)),this.onRemotePublishStateChange(e,t!==ge.InRoom),s}executeAddUser(e,t,i){const s=new Dc({userId:e,displayName:t,rtsManager:this.rtsManager,signalingManager:this.signalingManager,usersViewMap:this.usersViewMap,slsReporter:this.slsReporter,localUser:this.self,audioVolumeIndicationInterval:this.audioVolumeIndicationInterval,playoutVolume:this.playoutVolume,parameter:this.parameter});return s.on(ot.Remote,this.onRemoteDeviceStatusChange.bind(this)),s.on(Me.PullStreamStats,this.onRemoteStatReport.bind(this)),s.on(Me.RtsSubscribeExceeds,this.onSubscribeExceeds.bind(this)),s.on("audioSubscribeStateChanged",(n,c,o,l)=>{this.emit("audioSubscribeStateChanged",n,c,o,l,this.channel||"")}),s.on("videoSubscribeStateChanged",(n,c,o,l)=>{this.emit("videoSubscribeStateChanged",n,c,o,l,this.channel||"")}),s.on("screenSubscribeStateChanged",(n,c,o,l)=>{this.emit("screenSubscribeStateChanged",n,c,o,l,this.channel||"")}),s.on("dataSubscribeStateChanged",(n,c,o,l)=>{var d;o===ce.AliRtcStateSubscribed&&((d=this.dcReadyHelper)==null||d.onSubscribeDataChannel(this.userMap[n])),this.emit("dataSubscribeStateChanged",n,c,o,l,this.channel||"")}),s.on("remoteAudioAutoPlayFail",n=>{this.emit("remoteAudioAutoPlayFail",n)}),s.on("remoteVideoAutoPlayFail",(n,c)=>{this.emit("remoteVideoAutoPlayFail",n,c)}),s.on("remoteAudioPlayError",(n,c)=>{this.emit("remoteAudioPlayError",n,c)}),s.on("remoteVideoPlayError",(n,c)=>{this.emit("remoteVideoPlayError",n,c)}),s.on("remoteSubscribeError",n=>{this.emit("remoteSubscribeError",n,s.userId)}),s.on("occurError",n=>{this.emit("occurError",n,s.userId)}),s.on("remoteDataChannelMessage",(n,c)=>{this.emit("remoteDataChannelMessage",n,c)}),s.setWantSubAudio(this.autoSubAudio&&this.wantSubAudio),s.setWantSubVideo(this.autoSubVideo&&this.wantSubVideo),s.setWantSubScreen(this.autoSubScreen&&this.wantSubScreen),s.setRemoteDefaultVideoStreamType(this.defaultStreamType),s.setAudioMuted(this.audioMuted),(this.autoSubAudio||this.autoSubVideo||this.autoSubScreen)&&s.updateSubscribe(i),s}onRemoteDeviceStatusChange(e,t){e===Me.MuteAudio?this.emit("userAudioMuted",t,!0):e===Me.UnmuteAudio?this.emit("userAudioMuted",t,!1):e===Me.MuteVideo?this.emit("userVideoMuted",t,!0):e===Me.UnmuteVideo?this.emit("userVideoMuted",t,!1):e===Me.MuteScreen?this.emit("userScreenMuted",t,!0):e===Me.UnmuteScreen&&this.emit("userScreenMuted",t,!1)}onRemoteStatReport(e,t,i){this.emit(Me.PullStreamStats,e,t,i)}onSubscribeExceeds(e,t){this.emit(Me.RtsSubscribeExceeds,e,t)}removeLeftUser(e){return I(this,null,function*(){e.userid&&this.userMap[e.userid]&&(yield this.userMap[e.userid].clear(!1),delete this.userMap[e.userid])})}diffUsers(e){const t=[],i=[];e.forEach(n=>{n.userid&&(this.userMap[n.userid]?i.push(n):t.push(n))});const s=Object.keys(this.userMap).filter(n=>!e.find(c=>c.userid===n)).map(n=>({userid:n,reason:"",leavecode:ns.AliRtcUserOfflineQuit}));return{joinList:t,leaveList:s,presentList:i}}getRemoteUser(e){return this.userMap[e]}updateRemoteUserDeviceStatus(e){e&&e.userid&&this.userMap[e.userid]&&this.userMap[e.userid].updateRemoteUserDeviceStatus(e.status)}updateAudioWant(e,t){const i=this.userMap[e];if(!i)throw new U(B.ERR_INNER,`no remote user(${e}) founded`);i.setWantSubAudio(t),t?i.updateSubscribe(ge.User):i.stopSubscribe({audio:!0})}updateVideoWant(e,t){const i=this.userMap[e];if(!i)throw new U(B.ERR_INNER,`no remote user(${e}) founded`);i.setWantSubVideo(t),t?i.updateSubscribe(ge.User):i.stopSubscribe({video:!0})}updateScreenWant(e,t){const i=this.userMap[e];if(!i)throw new U(B.ERR_INNER,`no remote user(${e}) founded`);i.setWantSubScreen(t),t?i.updateSubscribe(ge.User):i.stopSubscribe({screen:!0})}stopIndication(){this.indicationTimer&&(window.clearInterval(this.indicationTimer),this.indicationTimer=0)}startIndication(e){this.stopIndication(),this.indicationTimer=window.setInterval(()=>{const t=this.remoteUsers.map(i=>({userId:i.userId,volume:i.getAudioLevel()||0}));t.unshift({userId:"",volume:this.self.getAudioLevel()||0}),this.emit("audioVolume",t)},e)}setEnableDualVideoStream(e,t){if(!this.dualVideoPlugin)return;t&&this.dualVideoPlugin.setOptions(t);const i=this.pluginManager.has(this.dualVideoPlugin.name);e?!i&&this.pluginManager.add(this.dualVideoPlugin):i&&this.pluginManager.remove(this.dualVideoPlugin.name)}setAudioVolume(e){var t;(t=this.audioMixerPlugin)==null||t.setOptions(e)}enableAudioVolumeIndication(e){this.audioVolumeIndicationInterval!==e&&(this.audioVolumeIndicationInterval>0&&e<=0&&this.stopIndication(),e>0&&this.startIndication(e),this.audioVolumeIndicationInterval=e,this.remoteUsers.forEach(t=>{t.enableAudioVolumeIndication(e)}),this.self.enableAudioVolumeIndication(e))}setPlayoutVolume(e){this.playoutVolume=e,this.remoteUsers.forEach(t=>{t.setPlayoutVolume(e)})}refreshAuthInfo(e){this.authInfo&&(this.authInfo=X(X({},this.authInfo),e)),e.userId&&this.self.refreshUserInfo(e.userId)}setEnableMediaExtensionMsg(e){this.rtsManager.setEncodedInsertableStreams(e)}setAudioRedEnabled(e){this.rtsManager.setAudioRedEnabled(e)}setVideoCodec(e){this.rtsManager.changeVideoCodec(e)}setParameter(e){var i,s,n,c,o;const t=JSON.parse(e);Object.keys(t).forEach(l=>{const d=this.parameter[l],u=t[l];this.parameter[l]=typeof d=="object"&&typeof u=="object"?X(X({},d),u):u}),t.enableBlankAudio===!0?(this.blankAudioPlugin||(this.blankAudioPlugin=new zc),this.pluginManager.has((i=this.blankAudioPlugin)==null?void 0:i.name)||this.pluginManager.add(this.blankAudioPlugin)):t.enableBlankAudio===!1&&(this.blankAudioPlugin&&this.pluginManager.remove((s=this.blankAudioPlugin)==null?void 0:s.name),(n=this.blankAudioPlugin)==null||n.clear(),this.blankAudioPlugin=void 0),t.audio&&((c=this.audio3AConfig)==null||c.loadFromLocalConfig(t.audio)),t.subscribe&&((o=this.rtsManager)==null||o.updateSubscribeBatcher(t.subscribe))}updateDynamicConfig(e){this.rtsManager.updateDynamicConfig(e)}setupAudioProcessingPluginIfNeeded(){if(this.audio3AConfig.enableSoft3A){let e=0;this.audio3AConfig.enableSoft3ACheck&&(e=1e4),setTimeout(()=>{this.audioProcessorPlugin||(this.audioProcessorPlugin=new Xc({dumpAudioData:this.audio3AConfig.dumpAudioData,aiaecOn:this.audio3AConfig.useAIAEC,slsReporter:this.slsReporter,enableSoft3ACheck:this.audio3AConfig.enableSoft3ACheck,useHardOnly:this.audio3AConfig.useHardOnly})),this.audioProcessorPlugin&&!this.pluginManager.has(this.audioProcessorPlugin.name)&&(this.audioProcessorPlugin.on("error",({message:t})=>{var i;this._loggerInstanceId&&T.setActiveInstance(this._loggerInstanceId),T.error("audioProcessorPlugin error:",t),(i=this.self.audioTrack)==null||i.applyConstraints({echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0})}),this.pluginManager.add(this.audioProcessorPlugin))},e)}else this.audioProcessorPlugin&&(this.pluginManager.remove(this.audioProcessorPlugin.name),this.audioProcessorPlugin=void 0);this.self.setMicrophoneConstraints({echoCancellation:this.audio3AConfig.useSysEchoCancellation,noiseSuppression:this.audio3AConfig.useSysNoiseSuppression,autoGainControl:this.audio3AConfig.useSysAutoGainControl})}getParameter(){return JSON.stringify(this.parameter)}sendDataChannelMessage(e){return this.self.sendDataChannelMessage(e)}}m(et,"logName","BizControl"),lt([k()],et.prototype,"init",1),lt([k()],et.prototype,"leave",1),lt([k()],et.prototype,"clear",1),lt([k(H)],et.prototype,"addUser",1),lt([k()],et.prototype,"removeLeftUser",1),lt([k()],et.prototype,"diffUsers",1),lt([k(H)],et.prototype,"updateAudioWant",1),lt([k(H)],et.prototype,"updateVideoWant",1),lt([k(H)],et.prototype,"updateScreenWant",1),lt([k()],et.prototype,"stopIndication",1),lt([k()],et.prototype,"startIndication",1),lt([k(H)],et.prototype,"setEnableDualVideoStream",1),lt([k(H)],et.prototype,"setAudioVolume",1),lt([k()],et.prototype,"enableAudioVolumeIndication",1);var Mi=(a=>(a[a.LiveTranscodingSingle=0]="LiveTranscodingSingle",a[a.LiveTranscodingMix=1]="LiveTranscodingMix",a))(Mi||{}),Gs=(a=>(a[a.LiveTranscodingOrigin=0]="LiveTranscodingOrigin",a[a.LiveTranscodingAudio=1]="LiveTranscodingAudio",a[a.LiveTranscodingVideo=2]="LiveTranscodingVideo",a))(Gs||{}),vi=(a=>(a[a.LiveTranscodingCamera=0]="LiveTranscodingCamera",a[a.LiveTranscodingShareScreen=1]="LiveTranscodingShareScreen",a))(vi||{});const Li={0:"camera",1:"shareScreen"};var Xs=(a=>(a[a.LiveTranscoding_Profile_1IN_1080P=0]="LiveTranscoding_Profile_1IN_1080P",a[a.LiveTranscoding_Profile_1IN_720P=1]="LiveTranscoding_Profile_1IN_720P",a[a.LiveTranscoding_Profile_1IN_360P=2]="LiveTranscoding_Profile_1IN_360P",a[a.LiveTranscoding_Profile_2IN_1080P=3]="LiveTranscoding_Profile_2IN_1080P",a[a.LiveTranscoding_Profile_2IN_720P=4]="LiveTranscoding_Profile_2IN_720P",a[a.LiveTranscoding_Profile_2IN_360P=5]="LiveTranscoding_Profile_2IN_360P",a[a.LiveTranscoding_Profile_4IN_1080P=6]="LiveTranscoding_Profile_4IN_1080P",a[a.LiveTranscoding_Profile_4IN_720P=7]="LiveTranscoding_Profile_4IN_720P",a[a.LiveTranscoding_Profile_4IN_360P=8]="LiveTranscoding_Profile_4IN_360P",a[a.LiveTranscoding_Profile_9IN_1080P=9]="LiveTranscoding_Profile_9IN_1080P",a[a.LiveTranscoding_Profile_9IN_720P=10]="LiveTranscoding_Profile_9IN_720P",a[a.LiveTranscoding_Profile_9IN_360P=11]="LiveTranscoding_Profile_9IN_360P",a[a.LiveTranscoding_Profile_12IN_1080P=12]="LiveTranscoding_Profile_12IN_1080P",a[a.LiveTranscoding_Profile_12IN_720P=13]="LiveTranscoding_Profile_12IN_720P",a[a.LiveTranscoding_Profile_12IN_360P=14]="LiveTranscoding_Profile_12IN_360P",a[a.LiveTranscoding_Profile_16IN_1080P=15]="LiveTranscoding_Profile_16IN_1080P",a[a.LiveTranscoding_Profile_16IN_720P=16]="LiveTranscoding_Profile_16IN_720P",a[a.LiveTranscoding_Profile_16IN_360P=17]="LiveTranscoding_Profile_16IN_360P",a[a.LiveTranscoding_Profile_Mixed=9999]="LiveTranscoding_Profile_Mixed",a))(Xs||{});const sl={0:"1IN_1080P",1:"1IN_720P",2:"1IN_360P",3:"2IN_1080P",4:"2IN_720P",5:"2IN_360P",6:"4IN_1080P",7:"4IN_720P",8:"4IN_360P",9:"9IN_1080P",10:"9IN_720P",11:"9IN_360P",12:"12IN_1080P",13:"12IN_720P",14:"12IN_360P",15:"16IN_1080P",16:"16IN_720P",17:"16IN_360P",9999:"Mixed_Audio"};var Qi=(a=>(a[a.LiveTranscoding_HZ_48000=48e3]="LiveTranscoding_HZ_48000",a[a.LiveTranscoding_HZ_44100=44100]="LiveTranscoding_HZ_44100",a[a.LiveTranscoding_HZ_32000=32e3]="LiveTranscoding_HZ_32000",a[a.LiveTranscoding_HZ_16000=16e3]="LiveTranscoding_HZ_16000",a[a.LiveTranscoding_HZ_8000=8e3]="LiveTranscoding_HZ_8000",a))(Qi||{}),Ni=(a=>(a[a.LiveTranscodingNoBody=0]="LiveTranscodingNoBody",a[a.LiveTranscodingBody=1]="LiveTranscodingBody",a))(Ni||{}),xi=(a=>(a[a.NOTO_SERIF_CJKSC_REGULAR=0]="NOTO_SERIF_CJKSC_REGULAR",a[a.ALIBABA_PUHUITI_REGULAR=1]="ALIBABA_PUHUITI_REGULAR",a[a.ALIBABA_PUHUITI_BOLD=2]="ALIBABA_PUHUITI_BOLD",a[a.ALIBABA_PUHUITI_Heavy=3]="ALIBABA_PUHUITI_Heavy",a[a.ALIBABA_PUHUITI_LIGHT=4]="ALIBABA_PUHUITI_LIGHT",a[a.ALIBABA_PUHUITI_MEDIUM=5]="ALIBABA_PUHUITI_MEDIUM",a))(xi||{}),Qs=(a=>(a[a.LiveTranscodingOrigin=0]="LiveTranscodingOrigin",a[a.LiveTranscodingCrop=1]="LiveTranscodingCrop",a[a.LiveTranscodingFill=2]="LiveTranscodingFill",a))(Qs||{}),Yi=(a=>(a[a.LiveTranscodingNormal=0]="LiveTranscodingNormal",a[a.LiveTranscodingVirtualBackground=1]="LiveTranscodingVirtualBackground",a))(Yi||{}),Ys=(a=>(a[a.LiveTranscodingState_IDLE=0]="LiveTranscodingState_IDLE",a[a.LiveTranscodingState_CONNNECT=1]="LiveTranscodingState_CONNNECT",a[a.LiveTranscodingState_RUNNING=2]="LiveTranscodingState_RUNNING",a[a.LiveTranscodingState_RECOVERING=3]="LiveTranscodingState_RECOVERING",a[a.LiveTranscodingState_FAILURE=4]="LiveTranscodingState_FAILURE",a[a.LiveTranscodingState_END=5]="LiveTranscodingState_END",a))(Ys||{}),xt=(a=>(a[a.LiveTranscodingErrorPublishOk=0]="LiveTranscodingErrorPublishOk",a[a.LiveTranscodingErrorStreamNotFound=17825793]="LiveTranscodingErrorStreamNotFound",a[a.LiveTranscodingErrorStreamAlreadyExist=17825794]="LiveTranscodingErrorStreamAlreadyExist",a[a.LiveTranscodingErrorInvalidParam=17825795]="LiveTranscodingErrorInvalidParam",a[a.LiveTranscodingErrorInternalError=17825796]="LiveTranscodingErrorInternalError",a[a.LiveTranscodingErrorRtmpServerError=17825797]="LiveTranscodingErrorRtmpServerError",a[a.LiveTranscodingErrorRtmpStreamUrlError=17825798]="LiveTranscodingErrorRtmpStreamUrlError",a[a.LiveTranscodingErrorPublishTimeout=17825799]="LiveTranscodingErrorPublishTimeout",a[a.LiveTranscodingErrorNotAuthorized=17825800]="LiveTranscodingErrorNotAuthorized",a))(xt||{}),Zs=(a=>(a[a.TrascodingPublishTaskStatusStart=0]="TrascodingPublishTaskStatusStart",a[a.TrascodingPublishTaskStatusUpdate=1]="TrascodingPublishTaskStatusUpdate",a[a.TrascodingPublishTaskStatusStop=2]="TrascodingPublishTaskStatusStop",a))(Zs||{}),dt=(a=>(a[a.MPU_TASK_TRANSACTION_START=0]="MPU_TASK_TRANSACTION_START",a[a.MPU_TASK_TRANSACTION_UPDATE=1]="MPU_TASK_TRANSACTION_UPDATE",a[a.MPU_TASK_TRANSACTION_STOP=2]="MPU_TASK_TRANSACTION_STOP",a[a.MPU_TASK_TRANSACTION_LIST=3]="MPU_TASK_TRANSACTION_LIST",a[a.MPU_TASK_TRANSACTION_POLLING=4]="MPU_TASK_TRANSACTION_POLLING",a[a.MPU_TASK_TRANSACTION_ACKNOWLEDGE=5]="MPU_TASK_TRANSACTION_ACKNOWLEDGE",a[a.MPU_TASK_TRANSACTION_END=6]="MPU_TASK_TRANSACTION_END",a))(dt||{});const rl={0:"/libra/v1/sdk/start-task",1:"/libra/v1/sdk/update-task",2:"/libra/v1/sdk/stop-task",3:"/libra/v1/sdk/list-task",4:"/libra/v1/sdk/polling",5:"/libra/v1/sdk/acknowledge",6:"/"};class er{constructor(r,e,t,i,s,n,c,o){m(this,"videoWidth");m(this,"videoHeight");m(this,"videoFramerate",20);m(this,"videoBitrate",2e3);m(this,"videoGop",30);m(this,"audioSamplerate",Qi.LiveTranscoding_HZ_44100);m(this,"audioBitrate",500);m(this,"audioChannels",1);this.videoWidth=r,this.videoHeight=e,t&&(this.videoFramerate=t),i&&(this.videoBitrate=i),s&&(this.videoGop=s),n&&(this.audioSamplerate=n),c&&(this.audioBitrate=c),o&&(this.audioChannels=o)}}const tr=a=>((16711680&a)>>16)+(65280&a)+((255&a)<<16),_t=(a=0,r)=>{if(r==0)return 0;let e=a/r;return e<0&&(e=0),e>1&&(e=1),e};class Zi{constructor(r,e,t){m(this,"mixMode",Mi.LiveTranscodingSingle);m(this,"singleParam");m(this,"mixParam");r&&(this.mixMode=r),e&&(this.singleParam=e),t&&(this.mixParam=t)}toJson(r,e,t,i,s){const n={appid:e.appId,channelid:e.channelId};if(r===dt.MPU_TASK_TRANSACTION_POLLING||r===dt.MPU_TASK_TRANSACTION_LIST||r===dt.MPU_TASK_TRANSACTION_ACKNOWLEDGE)return r===dt.MPU_TASK_TRANSACTION_ACKNOWLEDGE&&(n.messageid=s),n;if(n.taskid=t,r!==dt.MPU_TASK_TRANSACTION_STOP){if(n.mixmode=this.mixMode,i&&(n.streamurl=i),this.mixMode===Mi.LiveTranscodingSingle){const c=this.singleParam;if(c){n.streamtype=c.streamType,c.sourceType===vi.LiveTranscodingShareScreen?n.sourcetype=Li[c.sourceType]:n.sourcetype=Li[vi.LiveTranscodingCamera];const o=[];c.userId&&o.push(c.userId),n.subspecusers=o}}else if(r===dt.MPU_TASK_TRANSACTION_START||r===dt.MPU_TASK_TRANSACTION_UPDATE){const c=this.mixParam;if(c){c.taskProfile&&(n.taskprofile=sl[c.taskProfile]);const o=c.encodeParam||new er(1280,720);let l=o.videoWidth,d=o.videoHeight;const u={};Object.keys(o).forEach(h=>{const f=o[h];f>0&&(u[h.toLowerCase()]=f)}),u.lowbitratehighquality=0,n.encodeparam=u,n.backgrounds=c.backgrounds.map(h=>h.toJson(l,d)),n.watermarks=c.watermarks.map(h=>h.toJson(l,d)),n.clockwidgets=c.clockWidgets.map(h=>h.toJson(l,d));const p=c.users.map(h=>h.userId);n.subspecusers=[...new Set(p)],n.layouts=[{audiomixcount:c.users.length,panes:c.users.map((h,f)=>h.toJson(f,l,d,c.mediaProcessMode))}],n.layoutids=["0"],n.cropmode=c.cropMode,n.backgroundcolor=tr(c.backgroundColor),n.taskmode=c.mediaProcessMode}}}return n}}const ir=a=>I(this,null,function*(){const r=new Uint8Array(160).fill(170),e=new TextEncoder().encode(a),t=yield window.crypto.subtle.importKey("raw",r,{name:"HMAC",hash:{name:"SHA-1"}},!1,["sign"]),i=yield window.crypto.subtle.sign("HMAC",t,e);return Array.from(new Uint8Array(i)).map(s=>s.toString(16).padStart(2,"0")).join("")});class al{constructor(r){m(this,"authInfo");m(this,"slsReporter");this.slsReporter=r}doRequest(r,e){var c;const t=this.authInfo;if(!t)return Promise.reject(xt.LiveTranscodingErrorInvalidParam);const i=rl[r],s={appid:t.appId,userid:t.userId,channelid:t.channelId,timestamp:t.timestamp,token:t.token,nonce:t.nonce?t.nonce:"",requestid:Le.createCallid(),tokensid:!1,session:(c=t.sessionId)!=null?c:Le.createCallid()},n=Object.keys(s).map(o=>`${o}=${encodeURIComponent(s[o])}`).join("&");return fetch(`https://gw.rtn.aliyuncs.com${i}?${n}`,{method:"POST",headers:{"Content-Type":"application/json; charset=UTF-8"},body:JSON.stringify(e)}).then(o=>o.status!==200?(this.slsReporter.reportTranscodingError(o.status,e.taskid||""),Promise.reject(new U(B.ERR_INNER,`transcoding request failed, status: ${o.status}`))):o).catch(o=>Promise.reject(new U(B.ERR_INNER,`transcoding request failed, err: ${o.message}`)))}setAuthInfo(r){this.authInfo=r}clear(){this.authInfo=void 0}startPublishLiveStream(r,e){return I(this,null,function*(){if(!this.authInfo)return Promise.reject(xt.LiveTranscodingErrorInvalidParam);const t=yield ir(r.split("?")[0]),i=dt.MPU_TASK_TRANSACTION_UPDATE,s=e.toJson(i,this.authInfo,t,r);return this.doRequest(i,s)})}startPublishLiveStreamWithTaskId(r,e){return I(this,null,function*(){if(!this.authInfo)return Promise.reject(xt.LiveTranscodingErrorInvalidParam);const t=dt.MPU_TASK_TRANSACTION_UPDATE,i=e.toJson(t,this.authInfo,r);return this.doRequest(t,i)})}updatePublishLiveStream(r,e){return I(this,null,function*(){if(!this.authInfo)return Promise.reject(xt.LiveTranscodingErrorInvalidParam);const t=yield ir(r.split("?")[0]),i=dt.MPU_TASK_TRANSACTION_UPDATE,s=e.toJson(i,this.authInfo,t,r);return this.doRequest(i,s)})}updatePublishLiveStreamWithTaskId(r,e){return I(this,null,function*(){if(!this.authInfo)return Promise.reject(xt.LiveTranscodingErrorInvalidParam);const t=dt.MPU_TASK_TRANSACTION_UPDATE,i=e.toJson(t,this.authInfo,r);return this.doRequest(t,i)})}stopPublishLiveStream(r){return I(this,null,function*(){if(!this.authInfo)return Promise.reject(xt.LiveTranscodingErrorInvalidParam);const e=yield ir(r.split("?")[0]),t=dt.MPU_TASK_TRANSACTION_STOP,i=new Zi().toJson(t,this.authInfo,e,r);return this.doRequest(t,i)})}stopPublishLiveStreamWithTaskId(r){if(!this.authInfo)return Promise.reject(xt.LiveTranscodingErrorInvalidParam);const e=dt.MPU_TASK_TRANSACTION_STOP,t=new Zi().toJson(e,this.authInfo,r);return this.doRequest(e,t)}refreshAuthInfo(r){this.authInfo&&this.setAuthInfo(X(X({},this.authInfo),r))}}function Un(a,r){const e=new window.XMLHttpRequest;e.open("POST",`${a}?APIVersion=0.6.0`,!0),e.send(r)}function nl(a,r){try{if(r.length>=32768)return void Un(a,r);(function(e,t){return!(!navigator||!navigator.sendBeacon)&&navigator.sendBeacon(`${e}?APIVersion=0.6.0`,t)})(a,r)||Un(a,r)}catch(e){window&&window.console&&typeof window.console.error=="function"&&(console.error(`Failed to log to ali log service because of this exception:
132
+ `);return t<0||e<t}function Ft(a,r,e){return typeof a=="function"?function(t,i,s){if(Reflect.get(t,"__v_skip")===!0)return t;const n={MediaboxWrapperFunctionApply(c,o,l){let d;try{d=Reflect.apply(c,o,l)}catch(u){throw s(u),u}return Ft(d,i,s)},MediaboxWrapperFunctionGet(c,o){const l=Object.getOwnPropertyDescriptor(c,o);return!l||l.writable||l.configurable?Ft(c[o],i,s):c[o]},MediaboxWrapperClassConstructor(c,o){let l;try{l=new c(...o)}catch(d){throw s(d),d}return Ft(l,i,s)}};return Object.defineProperty(t,"__v_skip",{configurable:!0,enumerable:!1,writable:!1,value:!0}),new Proxy(t,{apply:n.MediaboxWrapperFunctionApply,get:n.MediaboxWrapperFunctionGet,construct:n.MediaboxWrapperClassConstructor})}(a,r+1,e):a instanceof Promise?a.then(t=>Ft(t,r+1,e)).catch(t=>(e(t),Promise.reject(t))):Array.isArray(a)?(a.forEach((t,i)=>{a[i]=Ft(t,r+1,e)}),a):(t=>t!==null&&typeof t=="object")(a)&&yc(a)?function(t,i,s){var n;if(Reflect.get(t,"__v_skip")===!0)return t;const c=[],o=typeof Object.getOwnPropertyDescriptors=="function"?Object.getOwnPropertyDescriptors((n=Object.getPrototypeOf(t))!=null?n:{}):{};for(const d of Object.keys(o))o[d].get&&c.push(d);const l={MediaboxWrapperObjectGetter(d,u){if(typeof u=="string"&&c.indexOf(u)>-1){let h;try{h=d[u]}catch(f){throw s(f),f}return Ft(h,i,s)}if(i>10)return d[u];const p=Reflect.getOwnPropertyDescriptor(d,u);return!p||p.writable||p.configurable?Ft(d[u],i,s):d[u]},MediaboxWrapperObjectSetter:(d,u,p)=>(d[u]=Ft(p,i,s),!0)};return Object.defineProperty(t,"__v_skip",{configurable:!0,enumerable:!1,writable:!1,value:!0}),new Proxy(t,{get:l.MediaboxWrapperObjectGetter,set:l.MediaboxWrapperObjectSetter})}(a,r+1,e):a}function Us(a){return typeof a=="string"&&(a.indexOf("g.alicdn.com/apsara-media-")>-1||a.indexOf("g.alicdn.com/thor-server")>-1||a.indexOf("MediaboxWrapper")>-1)}function Rn(a,r){if(Reflect.get(a,"__v_skip")===!0)return a;const e={MediaboxWrapperShallowGet(t,i){const s=t[i];return typeof s=="function"?e.MediaboxWrapperShallowMethod(s,t):s},MediaboxWrapperShallowMethod:(t,i)=>({MediaboxWrapperShallowApply(...s){let n;try{n=t.apply(i,s)}catch(c){throw r(c),c}return n instanceof Promise?n.catch(c=>(r(c),Promise.reject(c))):n}}).MediaboxWrapperShallowApply};return Object.defineProperty(a,"__v_skip",{configurable:!0,enumerable:!1,writable:!1,value:!0}),new Proxy(a,{get:e.MediaboxWrapperShallowGet})}class An extends Error{constructor(r){super(r),this.name="MQTError"}}let Rc=1;class Bs{constructor(r){var e,t;ni(this,"armsLogger"),ni(this,"isReady",!1),ni(this,"isDestroyed",!1),ni(this,"options"),ni(this,"queue",[]),ni(this,"marker"),ni(this,"helper",{MediaboxWrapperQueue:i=>new An(i),MediaboxWrapperInitiative:i=>new An(i)}),this.options=((i,s)=>dc(i,uc(s)))(_s({},r),{region:r.deferRegionSet?void 0:(e=r.region)!=null?e:"cn",env:(t=r.env)!=null?t:"prod"}),this.marker=`-${Rc++}-`,this.initArmsLogger()}static get version(){return"0.31.0"}initArmsLogger(r){const{region:e,env:t,disabled:i}=this.options;if(i||this.armsLogger)return;if(r&&!e)throw new Error("region is required");if(!e)return;if(!Vs[e])throw new Error(`region ${e} is not supported`);const s=vc.getArmsLogger();this.armsLogger=s.createExtraInstance({enableInstanceAutoSend:!0,pid:Vs[e].pid,tag:this.options.businessName,release:`${this.options.businessName}_${this.options.version}`,imgUrl:Vs[e].reportUrl,behavior:!0,sample:1,disableHook:!0,environment:t,beforeReport:n=>{var c;if(this.isDestroyed||yn(n.stack,this.marker)||n.t!=="pv"&&n.t!=="error"&&n.t!=="health")return!1;if(n.c1=(c=this.options.cid)!=null?c:window.location.host,n.c2=Bs.version,this.options.customData&&(n.c3=new URLSearchParams(this.options.customData).toString()),n.t==="error"){if(function(o){return typeof o=="string"&&(o.indexOf("g.alicdn.com/apsara-media-")>-1||o.indexOf("g.alicdn.com/thor-server")>-1)}(n.file)||Us(n.stack)){let o=n;return this.options.beforeSend&&(o=this.options.beforeSend(n)),this.isReady?o:(o&&this.queue.push(o),!1)}return!1}return n}})}wrap(r){return this.options.disabled||typeof Proxy=="undefined"?r:Ft(r,0,e=>{var t;e instanceof Error&&typeof e.stack=="string"&&Us(e.stack)&&((t=this.armsLogger)==null||t.error(e),e.stack=vn(e.stack,this.marker))})}shallowWrapClass(r){return this.options.disabled||typeof Proxy=="undefined"?r:function(e,t){if(Reflect.get(e,"__v_skip")===!0)return e;const i=n=>n instanceof e?Rn(n,t):n,s={MediaboxWrapperStaticGet(n,c){const o=n[c];return typeof o=="function"&&c!=="prototype"?s.MediaboxWrapperStaticMethod(o,n):o},MediaboxWrapperStaticMethod(n,c){const o={MediaboxWrapperStaticApply(l,d,u){let p;try{p=n.apply(c,u)}catch(h){throw t(h),h}return p instanceof Promise?p.then(h=>i(h)).catch(h=>(t(h),Promise.reject(h))):i(p)},MediaboxWrapperStaticConstruct(l,d,u){let p;try{p=Reflect.construct(n,d,u)}catch(h){throw t(h),h}return i(p)}};return new Proxy(n,{apply:o.MediaboxWrapperStaticApply,construct:o.MediaboxWrapperStaticConstruct})},MediaboxWrapperConstruct(n,c,o){let l;try{l=Reflect.construct(n,c,o)}catch(d){throw t(d),d}return Rn(l,t)}};return Object.defineProperty(e,"__v_skip",{configurable:!0,enumerable:!1,writable:!1,value:!0}),new Proxy(e,{get:s.MediaboxWrapperStaticGet,construct:s.MediaboxWrapperConstruct})}(r,e=>{var t;e instanceof Error&&typeof e.stack=="string"&&Us(e.stack)&&((t=this.armsLogger)==null||t.error(e),e.stack=vn(e.stack,this.marker))})}updateOptions(r){this.options=_s(_s({},this.options),r)}setReady(){this.initArmsLogger(!0),this.isReady=!0,this.queue.length&&this.queue.forEach(r=>{var e;(e=this.armsLogger)==null||e.error(this.helper.MediaboxWrapperQueue(r.msg),{filename:r.file,lineno:r.line,colno:r.col})})}report(r,e){var t;(t=this.armsLogger)==null||t.error(this.helper.MediaboxWrapperInitiative(r),e)}destroy(){this.isDestroyed=!0}}class Ac extends oe{constructor(){super();m(this,"audioContext");m(this,"stream");m(this,"sourceNode");m(this,"analyser");this.audioContext=yt.getInstance(),this.stream=new MediaStream}getLevel(){return this.analyser?this.analyser.getLevel():0}start(e,t=1e3){this.sourceNode&&this.stop(),this.stream.addTrack(e),this.sourceNode=this.audioContext.createMediaStreamSource(this.stream);const i=this.audioContext.createMediaStreamDestination();this.analyser=function(s,n,c,o,l){let d,u=o,p=0;const h=s.createAnalyser();h.fftSize=256;const f=new Uint8Array(h.frequencyBinCount);n.connect(h),h.connect(c);const g=()=>{d&&window.clearInterval(d)},b=()=>{s.state==="suspended"&&s.resume(),d=window.setInterval(()=>{h.getByteFrequencyData(f);let S=Math.round(f.reduce((v,R)=>v+R)/f.length);S=Math.min(100,S),p=S,l&&l(S)},u)};return b(),{updateInterval:S=>{g(),u=S,b()},getLevel:()=>p,dispose:()=>{g(),n.disconnect(),h.disconnect()}}}(this.audioContext,this.sourceNode,i,t,s=>{this.emit("audioLevel",s)})}stop(){this.analyser&&this.analyser.dispose(),this.analyser=void 0,this.sourceNode=void 0,this.stream.getAudioTracks().forEach(e=>{this.stream.removeTrack(e)})}dispose(){this.stop()}}class wn extends oe{constructor(e,t,i,s){super();m(this,"uid");m(this,"name");m(this,"rtsManager");m(this,"callId","");m(this,"audioLevelMonitor");m(this,"audioVolumeIndicationInterval",0);this.uid=e,this.name=t,this.rtsManager=i,this.audioVolumeIndicationInterval=s,this.audioLevelMonitor=new Ac}get userId(){return this.uid}get displayname(){return this.name}createCallId(e=!1){this.callId&&!e||(this.callId=Le.createCallid())}setUserInfo(e,t){this.uid=e,this.name=t}refreshUserInfo(e){this.uid=e}getAudioLevel(){return this.audioLevelMonitor.getLevel()}enableAudioVolumeIndication(e){this.audioVolumeIndicationInterval=e}clear(){this.audioLevelMonitor.dispose()}}class _n{static getCurrentStatus(r){let e=0;r.micOpen&&(e+=1),r.micInterrupted&&(e+=2),r.cameraOpen&&(e+=4),r.screenShare&&(e+=128),r.audioDisable&&(e+=8),r.videoDisable&&(e+=16),r.screenDisable&&(e+=256);let t=e.toString(16);for(;t.length<16;)t="0"+t;return t}static parseStatus(r){let e=parseInt(r,16);return{micOpen:!!(1&e),micInterrupted:!!(2&e),cameraOpen:!!(4&e),screenShare:!!(128&e),audioDisable:!!(8&e),videoDisable:!!(16&e),screenDisable:!!(256&e),backgroundMode:!!(32&e),accompanyPlaying:!!(64&e)}}}const k=(a,r)=>(e,t,i)=>{const s=i.value;return i.value=function(...n){var p;const c=this.instanceId||this._loggerInstanceId;c&&T.setActiveInstance(c);const o=`[${this.logName||((p=e.constructor)==null?void 0:p.logName)||""}]`,l=Date.now();let d=[];if(a)try{d=a(n)}catch(h){}T.interface(o,t,...d);const u=s.apply(this,n);return Promise.resolve(u).then(h=>h).catch(h=>h).then(h=>{var S;c&&T.setActiveInstance(c);let f="";const g=h instanceof Error,b=g&&((S=e.constructor)==null?void 0:S.logError);if(r||g){if(b)f=h;else if(g)f=h.message||"";else{if(!r)return;if(h===void 0)f="";else try{f=r(h)}catch(v){}}T.interfaceResult(o,t,!(g&&b),Date.now()-l+"ms",f)}}),u},i},H=a=>a,In="customVideoProfile",En="customScreenProfile",Hs={width:1280,height:720,frameRate:30,maxBitrate:2e3},Tn={width:1920,height:1080,frameRate:30,maxBitrate:2600};var Ei=(a=>(a[a.ERROR_DEVICE_UNKNOWNERROR=1e4]="ERROR_DEVICE_UNKNOWNERROR",a[a.ERROR_DEVICE_AUDIODEVICE_NOTFOUND=10001]="ERROR_DEVICE_AUDIODEVICE_NOTFOUND",a[a.ERROR_DEVICE_AUDIODEVICE_NOTALLOWED=10002]="ERROR_DEVICE_AUDIODEVICE_NOTALLOWED",a[a.ERROR_DEVICE_AUDIODEVICE_NOTREADABLE=10003]="ERROR_DEVICE_AUDIODEVICE_NOTREADABLE",a[a.ERROR_DEVICE_VIDEODEVICE_NOTFOUND=10004]="ERROR_DEVICE_VIDEODEVICE_NOTFOUND",a[a.ERROR_DEVICE_VIDEODEVICE_NOTALLOWED=10005]="ERROR_DEVICE_VIDEODEVICE_NOTALLOWED",a[a.ERROR_DEVICE_VIDEODEVICE_NOTREADABLE=10006]="ERROR_DEVICE_VIDEODEVICE_NOTREADABLE",a[a.ERROR_SCREENSHARE_NOTSUPPORT=10010]="ERROR_SCREENSHARE_NOTSUPPORT",a[a.ERROR_SCREENSHARE_NOTALLOWED=10011]="ERROR_SCREENSHARE_NOTALLOWED",a[a.ERROR_SCREENSHARE_ENDED=10012]="ERROR_SCREENSHARE_ENDED",a[a.ERROR_SCREENSHARE_NOPERMISSION=10013]="ERROR_SCREENSHARE_NOPERMISSION",a[a.ERROR_SCREENSHARE_SAFARI_INVALIDACCESS=10014]="ERROR_SCREENSHARE_SAFARI_INVALIDACCESS",a[a.ERROR_SCREENSHARE_UNKNOWNERRO=10019]="ERROR_SCREENSHARE_UNKNOWNERRO",a[a.ERROR_DEVICE_NOTALLOWED=10021]="ERROR_DEVICE_NOTALLOWED",a[a.ERROR_DEVICE_NOTSUPPORT=2e4]="ERROR_DEVICE_NOTSUPPORT",a))(Ei||{});const wc={1e4:je.AliEngineLocalDeviceExceptionTypeUnknown,2e4:je.AliEngineLocalDeviceExceptionTypeUnknown,10001:je.AliEngineLocalDeviceExceptionTypeMicNotAvailable,10002:je.AliEngineLocalDeviceExceptionTypeMicAuthFail,10003:je.AliEngineLocalDeviceExceptionTypeMicOpenFail,10005:je.AliEngineLocalDeviceExceptionTypeCameraAuthFail,10004:je.AliEngineLocalDeviceExceptionTypeVideoDeviceException,10006:je.AliEngineLocalDeviceExceptionTypeCameraOpenFail,10010:je.AliEngineLocalDeviceExceptionTypeDisplayException,10011:je.AliEngineLocalDeviceExceptionTypeDisplayException,10012:je.AliEngineLocalDeviceExceptionTypeDisplayException,10013:je.AliEngineLocalDeviceExceptionTypeDisplayException,10014:je.AliEngineLocalDeviceExceptionTypeDisplayException,10019:je.AliEngineLocalDeviceExceptionTypeDisplayException};var Ze=(a=>(a.CREATE_ENGINE="create_engine",a.JOIN="join",a.WANT_INSERT_PUB_TASK="wantInsertPubTask",a.INSERT_PUB_TASK="InsertPubTask",a.HANDLE_PUB_TASK="HandlePubTask",a.RECV_NOTIFY_PUBLISH="RecvNotifyPublish",a.INSERT_SUB_TASK="InsertSubTask",a.HANDLE_SUB_TASK="HandleSubTask",a.FIRST_REMOTE="first_remote",a))(Ze||{}),st=(a=>(a.START="start",a.SEND_SIG="send_sig",a.RECV_RST="recv_rst",a.END="end",a.RECEIVED="received",a.DECODED="decoded",a.PLAYED="played",a))(st||{});const Cn=(a,r,e=!1)=>{const t=()=>(a.muted=!0,Promise.race([Ht(500),a._playPromise||Promise.resolve()]).catch(()=>{}).then(()=>{let i;return e&&a.srcObject===r?i=Promise.resolve():(a.load(),a.srcObject=r,i=a.play(),a._playPromise=i),i}));return new Promise(i=>{if(J.AliRTS.BrowserUtil.isMicroMessenger){const s=window.top!==window.self,n=window.WeixinJSBridge||window.top.WeixinJSBridge;n?n.invoke("getNetworkType",{},()=>{i(t())}):(s?window.top.document:document).addEventListener("WeixinJSBridgeReady",()=>{n.invoke("getNetworkType",{},()=>{i(t())})}),setTimeout(()=>{i(t())},1e3)}else setTimeout(()=>{i(t())},0)})},Mt=a=>{Promise.race([Ht(100),a._playPromise||Promise.resolve()]).catch(()=>{}).then(()=>{a.srcObject=null,a._playPromise=void 0})};var Fs=(a=>(a[a.AliEngineDataMsgNone=0]="AliEngineDataMsgNone",a[a.AliEngineDataMsgMusicProgress=1]="AliEngineDataMsgMusicProgress",a[a.AliEngineDataMsgCustom=2]="AliEngineDataMsgCustom",a))(Fs||{});class Ji{constructor(r,e,t,i=0){m(this,"msgType");m(this,"msgId");m(this,"protocolVersion");m(this,"tlvVersion");this.msgType=r,this.msgId=e,this.protocolVersion=t,this.tlvVersion=i}build(){const r=new Uint8Array(4);return r.set(Uint8Array.from([this.protocolVersion,this.tlvVersion<<4|15&this.msgType]),0),r.set(Uint16Array.from([this.msgId]),2),r}static parse(r){const e=new DataView(r),t=e.getUint8(0),i=e.getUint8(1)>>4,s=15&e.getUint8(1),n=e.getUint16(2);return new Ji(s,n,t,i)}}class qi{constructor(r,e,t){m(this,"_byteArray");if(this._byteArray=new Uint8Array(0),r!==void 0&&e!==void 0&&t!==void 0){const i=new Ji(r,e,t).build();this._byteArray=new Uint8Array(i.byteLength+this._byteArray.byteLength),this._byteArray.set(i,0)}}write(r,e){const t=this._byteArray,i=new ArrayBuffer(5),s=new DataView(i);s.setUint8(0,r),s.setUint32(1,e.byteLength);const n=new Uint8Array(t.byteLength+5+e.byteLength);n.set(t,0),n.set(new Uint8Array(i),t.byteLength),n.set(new Uint8Array(e),t.byteLength+5),this._byteArray=n}static parse(r){const e={},t=new DataView(r);let i=0;for(;i<r.byteLength;){const s=t.getUint8(i),n=t.getUint32(i+1);if(!(i+5+n<=r.byteLength))break;{const c=r.slice(i+5,i+5+n);e[s]=c,i+=5+n}}return e}get buffer(){return this._byteArray.buffer}}class Ti{constructor(r=0,e=!0,t=1,i=!1,s=0,n=!1,c=!1,o=3){m(this,"_fin",!0);m(this,"_hasExtension",!1);m(this,"_version",0);m(this,"_frameType",1);m(this,"_isEncrypted",!1);m(this,"_isCompressed",!1);m(this,"_signalType",3);m(this,"_payloadLength",0);this._fin=e,this._hasExtension=i,this._version=s,this._frameType=t,this._isEncrypted=n,this._isCompressed=c,this._signalType=o,this._payloadLength=r}get fin(){return this._fin}get hasExtension(){return this._hasExtension}get version(){return this._version}get frameType(){return this._frameType}get isEncrypted(){return this._isEncrypted}get isCompressed(){return this._isCompressed}get signalType(){return this._signalType}get payloadLength(){return this._payloadLength}toBuffer(){const r=new ArrayBuffer(4),e=new DataView(r);return e.setUint8(0,(this._fin?1:0)<<7|(this._hasExtension?1:0)<<6|this._version<<4|15&this._frameType),e.setUint8(1,(this._isEncrypted?1:0)<<7|(this._isCompressed?1:0)<<6|15&this._signalType),e.setUint16(2,this._payloadLength),r}static parse(r){const e=new DataView(r),t=e.getUint8(0)>>7==1,i=(64&e.getUint8(0))>>6==1,s=(48&e.getUint8(0))>>4,n=15&e.getUint8(0),c=e.getUint8(1)>>7==1,o=(64&e.getUint8(1))>>6==1,l=15&e.getUint8(1),d=e.getUint16(2);return new Ti(d,t,n,i,s,c,o,l)}}class Gi{constructor(r,e){m(this,"_body");m(this,"_header",new Ti);this._header=r,this._body=e}get header(){return this._header}get isFin(){return this._header.fin}get body(){return this._body}toGRTNBuffer(){const r=this._header.toBuffer(),e=this._body,t=new ArrayBuffer(4);new DataView(t).setUint8(0,1*Math.pow(2,4));const i=new Uint8Array(t.byteLength+r.byteLength+e.byteLength);return i.set(new Uint8Array(t),0),i.set(new Uint8Array(r),t.byteLength),i.set(new Uint8Array(e),t.byteLength+r.byteLength),i.buffer}static parse(r){const e=r.slice(0,4),t=Ti.parse(e);let i=new ArrayBuffer(0);return r.byteLength-4>=t.payloadLength&&(i=r.slice(4,4+t.payloadLength)),new Gi(t,i)}}const js=a=>{const r=a.byteLength,e=new DataView(a);let t=0;for(let i=0;i<r;i++)t=256*t+e.getUint8(i);return t};let kn=0;class Jt{constructor(r,e=0,t=0,i=0){m(this,"data");m(this,"networkTime");m(this,"futureOrProgress");m(this,"type");this.data=r,this.type=e,this.networkTime=t,this.futureOrProgress=i}toBuffer(){const r=new qi(0,0,0);r.write(1,Uint8Array.from([0]).buffer),r.write(2,Uint16Array.from([0]).buffer),kn++,r.write(3,Uint32Array.from([kn]).buffer);const e=new qi;return e.write(1,Uint8Array.from([0]).buffer),e.write(2,Uint8Array.from([this.type]).buffer),e.write(3,Uint32Array.from([this.futureOrProgress]).buffer),e.write(4,Uint32Array.from([Number(this.networkTime>>32&4294967295),Number(4294967295&this.networkTime)]).buffer),e.write(5,this.data),r.write(30,e.buffer),r.buffer}static parse(r){if(!r||r.byteLength<4)return;Ji.parse(r.slice(0,4));const e=qi.parse(r.slice(4))[30];if(!e)return;const t=qi.parse(e),i=t[2],s=t[3],n=t[4],c=t[5];return c.byteLength!==0?new Jt(c,js(i),js(n),js(s)):void 0}}var _c=Object.defineProperty,Ic=Object.getOwnPropertyDescriptor,De=(a,r,e,t)=>{for(var i,s=t>1?void 0:t?Ic(r,e):r,n=a.length-1;n>=0;n--)(i=a[n])&&(s=(t?i(r,e,s):i(s))||s);return t&&s&&_c(r,e,s),s};class Ci extends oe{constructor(){super();m(this,"_state");m(this,"time");this._state=ee.AliRtcStatePublishIdle,this.time=Date.now()}get state(){return this._state}setState(e){const t=this._state,i=this.time;this._state=e,this.time=Date.now(),this.emit("change",t,e,Math.floor((this.time-i)/1e3))}}const Ce=(bt=class extends wn{constructor(e){const{rtsManager:t,localStreamManager:i,slsReporter:s,signalingManager:n,audioVolumeIndicationInterval:c,parameter:o}=e;super("","",t,c);m(this,"sessionId","");m(this,"traceId","");m(this,"_url","");m(this,"joinTime",0);m(this,"publishPromise",Promise.resolve({traceId:"",l1ip:void 0}));m(this,"previewElements",[]);m(this,"screenPreviewElements",[]);m(this,"streamManager");m(this,"dc");m(this,"streamTracks");m(this,"publishId",mt());m(this,"signalingManager");m(this,"shouldPublish",!1);m(this,"monitorTimerId");m(this,"monitorDataCache",{});m(this,"candidateDataCache",[]);m(this,"pcMediaStatsMap",{});m(this,"slsReporter");m(this,"audioPubState");m(this,"videoPubState");m(this,"videoSmallPubState");m(this,"screenPubState");m(this,"dataPubState");m(this,"parameter",{});m(this,"onTrackEnd",e=>{this.emit(e)});this.streamManager=i,this.signalingManager=n,this.slsReporter=s,this.parameter=o,this.streamManager.on("trackended",l=>{this.onTrackEnd(l)}),this.streamManager.on("publishupdate",()=>{this.publishUpdate()}),this.audioPubState=new Ci,this.audioPubState.on("change",(l,d,u)=>{this.emit("audioPublishStateChanged",l,d,u)}),this.videoPubState=new Ci,this.videoPubState.on("change",(l,d,u)=>{this.emit("videoPublishStateChanged",l,d,u)}),this.videoSmallPubState=new Ci,this.videoSmallPubState.on("change",(l,d,u)=>{this.emit("dualStreamPublishStateChanged",l,d,u)}),this.screenPubState=new Ci,this.screenPubState.on("change",(l,d,u)=>{this.emit("screenPublishStateChanged",l,d,u)}),this.dataPubState=new Ci,this.dataPubState.on("change",(l,d,u)=>{this.emit("dataPublishStateChanged",l,d,u)}),this.startStreamMonitor(),this.createCallId()}get url(){return this._url}set url(e){this._url=e,this.rtsManager.updateAuth(e)}get joined(){return!!this.uid}get isPublishing(){return this.rtsManager.publishingTracks.length>0}get publishStreams(){return this.streamManager.publishStreams}get cameraTrack(){return this.streamManager.cameraStreamInfo.originVideoTrack}get screenTrack(){return this.streamManager.screenStreamInfo.originVideoTrack}get audioTrack(){return this.streamManager.cameraStreamInfo.originAudioTrack}get hasCamera(){return!!this.streamManager.cameraStreamInfo.originVideoTrack}get hasMicrophone(){return!!this.streamManager.cameraStreamInfo.originAudioTrack}get hasScreenShare(){return!!this.streamManager.screenStreamInfo.originVideoTrack}get hasCameraTrackInMS(){var e;return!!((e=this.streamTracks)!=null&&e.find(({ssrc:t,type:i,msid:s})=>i==="video"&&t&&s===D.VideoLarge))}get hasCameraDualTrackInMS(){var e;return!!((e=this.streamTracks)!=null&&e.find(({ssrc:t,type:i,msid:s})=>i==="video"&&t&&s===D.VideoSmall))}get hasScreenTrackInMS(){var e;return!!((e=this.streamTracks)!=null&&e.find(({ssrc:t,type:i,msid:s})=>i==="video"&&t&&s===D.Screen))}get hasAudioTrackInMS(){var e;return!!((e=this.streamTracks)!=null&&e.find(({ssrc:t,type:i,msid:s})=>i==="audio"&&t&&s===D.Audio))}get cameraDirection(){var e,t;return(t=(e=this.streamManager.cameraStreamInfo)==null?void 0:e.cameraVideoConstraints)==null?void 0:t.facingMode}get audioCaptureDisabled(){return this.streamManager.audioCaptureDisabled}get cameraCaptureDisabled(){return this.streamManager.cameraCaptureDisabled}get publishLocalVideoStreamEnabled(){return this.streamManager.publishLocalVideoStreamEnabled}get publishLocalAudioStreamEnabled(){return this.streamManager.publishLocalAudioStreamEnabled}get publishLocalScreenStreamEnabled(){return this.streamManager.publishLocalScreenStreamEnabled}setPublishLocalAudioStreamEnabled(e){this.streamManager.publishLocalAudioStreamEnabled=e}setPublishLocalVideoStreamEnabled(e){this.streamManager.publishLocalVideoStreamEnabled=e}setPublishLocalScreenStreamEnabled(e){this.streamManager.publishLocalScreenStreamEnabled=e}initInfo(e,t){this.joinTime=Date.now(),this.rtsManager.localJoinTime=this.joinTime,this.setUserInfo(e.userId,e.userId),this.url=t,this.sessionId=e.sessionId||Le.createCallid("web"),this.updatePubId()}setVideoProfile(e){return I(this,null,function*(){yield this.streamManager.setVideoProfile(In,e)})}setVideoContentHint(e){this.streamManager.setVideoContentHint(e)}setScreenContentHint(e){this.streamManager.setScreenContentHint(e)}setAudioProfile(e){return I(this,null,function*(){yield this.streamManager.setAudioProfile(e)})}setScreenProfile(e){return I(this,null,function*(){yield this.streamManager.setScreenProfile(En,e)})}setCameraDirection(e){if(e===Ai.CAMERA_FRONT)this.streamManager.setCameraVideoConstraints({facingMode:"user"});else{if(e!==Ai.CAMERA_REAR)throw new U(B.ERR_CAMERA_OPEN_FAIL,`camera direction set to ${e} failed`);this.streamManager.setCameraVideoConstraints({facingMode:"environment"})}}setCameraDeviceId(e){this.streamManager.setCameraVideoConstraints({deviceId:e})}muteLocalCamera(e){this.streamManager.setCameraMuted(e),this.slsReporter.reportMute(this.callId,!e,"video")}muteLocalMic(e){this.streamManager.setAudioMuted(e),this.slsReporter.reportMute(this.callId,!e,"audio")}muteLocalScreen(e){this.streamManager.setScreenMuted(e),this.slsReporter.reportMute(this.callId,!e,"screen")}setMicrophoneDeviceId(e){this.streamManager.setMicAudioConstraints({deviceId:e})}setMicrophoneConstraints(e){this.streamManager.setMicAudioConstraints(e)}updatePubId(){this.publishId=mt()}clearPublishState(){this.streamTracks=void 0}leave(){return I(this,null,function*(){this.shouldPublish=!1,this.isPublishing&&(yield this.unPublish()),this.joinTime=0,this.dc=void 0,this.dataPubState.setState(ee.AliRtcStateNoPublish)})}clear(){return I(this,null,function*(){ur(bt.prototype,this,"clear").call(this),this.stopPreview(),this.resetPreviewElements(),this.resetSecondayPreviewElements(),this.clearStream(),yield this.leave(),this.streamManager.cameraCaptureDisabled=!1})}resetElement(e){this.previewElements.includes(e)&&(Mt(e),this.previewElements.splice(this.previewElements.indexOf(e),1)),this.screenPreviewElements.includes(e)&&(Mt(e),this.screenPreviewElements.splice(this.screenPreviewElements.indexOf(e),1))}setPreviewElement(e){const{videoElement:t,screen:i}=e;i?this.screenPreviewElements.includes(t)||(this.screenPreviewElements.push(t),this.preview(e)):this.previewElements.includes(t)||(this.previewElements.push(t),this.preview(e))}startDefaultCameraAndMic(e){return I(this,null,function*(){const{hasCamera:t,cameraCaptureDisabled:i,publishLocalVideoStreamEnabled:s}=this,{hasMicrophone:n,audioCaptureDisabled:c,publishLocalAudioStreamEnabled:o}=this,l=!t&&!e&&!i&&s,d=!n&&!c&&o;try{l&&d?yield this.startCameraAndMic():l?yield this.startCameraCapture():d&&(yield this.startAudioCapture())}catch(u){const p=u.errorCode;let h=B.ERR_CAMERA_OPEN_FAIL;throw l?((p===Ei.ERROR_DEVICE_VIDEODEVICE_NOTALLOWED||Ei.ERROR_DEVICE_NOTALLOWED)&&(h=B.ERR_CAMERA_AUTH_FAIL),h=B.ERR_CAMERA_OPEN_FAIL):((p===Ei.ERROR_DEVICE_AUDIODEVICE_NOTALLOWED||Ei.ERROR_DEVICE_NOTALLOWED)&&(h=B.ERR_MIC_AUTH_FAIL),h=B.ERR_MIC_OPEN_FAIL),new U(h,`auto open fail: ${u.message}`)}})}setViewConfig(e,t){if(e){if(![ue.AliRtcVideoTrackCamera,ue.AliRtcVideoTrackScreen].includes(t))throw new U(B.ERR_INVALID_ARGUMENTS,"set view config invalid track",{track:t});e.forEach(i=>{this.setPreviewElement({videoElement:i,screen:t===ue.AliRtcVideoTrackScreen})})}else t===ue.AliRtcVideoTrackCamera?this.stopPreview({primary:!0,screen:!1}):this.stopPreview({primary:!1,screen:!0})}startCameraCapture(){return I(this,null,function*(){return this.streamManager.cameraCaptureDisabled=!1,yield this.createLocalStream({video:!0})})}stopCameraCapture(){return I(this,null,function*(){this.streamManager.cameraCaptureDisabled=!0,yield this.stopLocalStream({video:!0})})}startAudioCapture(){return I(this,null,function*(){return this.streamManager.audioCaptureDisabled=!1,yield this.createLocalStream({audio:!0})})}stopAudioCapture(){return I(this,null,function*(){this.streamManager.audioCaptureDisabled=!0,yield this.stopLocalStream({audio:!0})})}startCameraAndMic(){return I(this,null,function*(){return this.streamManager.cameraCaptureDisabled=!1,this.streamManager.audioCaptureDisabled=!1,yield this.createLocalStream({video:!0,audio:!0})})}preview(e){return I(this,null,function*(){const{videoElement:t,screen:i}=e!=null?e:{};try{let s=i?this.streamManager.screenStreamInfo.previewStream:this.streamManager.cameraStreamInfo.previewStream;if(!t)throw new U(B.ERR_INVALID_ARGUMENTS,"no video element found",{videoElement:t});return s?(Cn(t,s.mediaStream),this.setPreviewElement(e),s.mediaStream):void T.info(`[${bt.logName}]`,"preview no stream founded")}catch(s){const n=B.ERR_INNER;throw U.fromError(s,n,"preview failed")}})}previewAll(e){return I(this,null,function*(){const{primary:t=!0,screen:i=!0}=e!=null?e:{};if(t&&this.previewElements.length)for(let s=0;s<this.previewElements.length;s++){const n=this.previewElements[s];yield this.preview({videoElement:n})}if(i&&this.screenPreviewElements.length)for(let s=0;s<this.screenPreviewElements.length;s++){const n=this.screenPreviewElements[s];yield this.preview({videoElement:n,screen:!0})}})}stopPreview(e){const{videoElement:t,primary:i=!0,screen:s=!0}=e||{};if(t){const n=this.previewElements.findIndex(c=>c===t);if(n>=0)this.previewElements.splice(n,1),Mt(t);else{const c=this.screenPreviewElements.findIndex(o=>o===t);c>=0&&(this.screenPreviewElements.splice(c,1),Mt(t))}}else i&&(this.previewElements.forEach(n=>{Mt(n)}),this.previewElements=[]),s&&(this.screenPreviewElements.forEach(n=>{Mt(n)}),this.screenPreviewElements=[])}resumePublish(){return I(this,null,function*(){this.shouldPublish&&(this.createCallId(!0),yield this.startPublish(!0))})}createLocalStream(e){return I(this,null,function*(){try{if(e.video)for(let i=0;i<this.previewElements.length;i++){const s=this.previewElements[i];Mt(s)}else if(e.screen)for(let i=0;i<this.screenPreviewElements.length;i++){const s=this.screenPreviewElements[i];Mt(s)}const t=yield this.streamManager.createLocalStream(e);return t!=null&&t.audioTrack&&this.audioVolumeIndicationInterval>0&&this.audioLevelMonitor.start(t.audioTrack,this.audioVolumeIndicationInterval),e.video?this.previewAll({primary:!0}):e.screen&&this.previewAll({screen:!0}),t}catch(t){const i=wc[t.errorCode];throw i&&(e.audio?this.emit("localDeviceException",kt.AliEngineLocalDeviceTypeMic,i,""):e.video?this.emit("localDeviceException",kt.AliEngineLocalDeviceTypeCamera,i,""):e.screen?this.emit("localDeviceException",kt.AliEngineLocalDeviceTypeDisplay,i,""):this.emit("localDeviceException",kt.AliEngineLocalDeviceTypeUnknown,i,"")),t}})}stopLocalStream(e){return I(this,null,function*(){e.audio&&this.audioLevelMonitor.stop(),yield this.streamManager.stopLocalStream(e)})}compareAndPublish(e,t,i){return I(this,null,function*(){var n,c;if(!e&&!t)return;if(e&&!t){const o={};return i===D.Audio?o.audio=!0:i===D.VideoLarge||i===D.VideoSmall?(o.video=!0,o.vMsid=i):i===D.Screen&&(o.screen=!0),yield this.publishDeleteTracks(o)}const s={};if(t!=null&&t.hasVideo&&(s.isScreen=i===D.Screen,s.vMsid=i),t!=null&&t.hasAudio&&(s.aMsid=i),!e&&t)return yield this.publishAdd(t,s,!1);if(e&&t&&e.trackId!==(((n=t.videoTrack)==null?void 0:n.id)||((c=t.audioTrack)==null?void 0:c.id)))return yield this.publishReplace(t,s)})}reportAudioProfile(){const e=this.streamManager.cameraStreamInfo.audioProfile||"standard",t=J.AliRTS.AudioProfileMap.get(e);this.slsReporter.reportPublishProfile(D.Audio,{a_profile:e,bits:(t==null?void 0:t.maxBitrate)||0,samplerate:(t==null?void 0:t.sampleRate)||0,channel:(t==null?void 0:t.channelCount)||0})}reportVideoProfile(){const e=this.streamManager.cameraStreamInfo.videoProfile||"",t=J.AliRTS.VideoProfileMap.get(e);t&&this.slsReporter.reportPublishProfile(D.VideoLarge,{v_profile:e,wdth:(t==null?void 0:t.width)||0,hgt:(t==null?void 0:t.height)||0,fps:(t==null?void 0:t.frameRate)||0,bitrate:(t==null?void 0:t.maxBitrate)||0})}reportScreenProfile(){const e=this.streamManager.screenStreamInfo.videoProfile||"",t=J.AliRTS.VideoProfileMap.get(e);t&&this.slsReporter.reportPublishProfile(D.Screen,{v_profile:e,wdth:(t==null?void 0:t.width)||0,hgt:(t==null?void 0:t.height)||0,fps:(t==null?void 0:t.frameRate)||0,bitrate:(t==null?void 0:t.maxBitrate)||0})}updateDataChannel(e){e&&(this.dc=e,this.dc.datachannel&&(this.dc.datachannel.binaryType="arraybuffer"))}publishDataChannel(){return I(this,null,function*(){if(this.dataPubState.state!==ee.AliRtcStatePublishing){this.dataPubState.setState(ee.AliRtcStatePublishing);try{const e=yield this.rtsManager.publishAddDataChannel(this.url);e?(this.updateDataChannel(e),this.dataPubState.setState(ee.AliRtcStatePublished)):(this.dataPubState.setState(ee.AliRtcStateNoPublish),this.emit("publishDataError",new U(B.ERR_INNER,"publishDataError")))}catch(e){T.error("[LocalUser]","publishDataChannel error",e),this.dataPubState.setState(ee.AliRtcStateNoPublish)}}})}startPublish(){return I(this,arguments,function*(e=!1,t=Dt.MANUAL){var l,d,u;if(!this.joined)return;this.shouldPublish=!0;const i=this.streamManager.publishStreams,{audio:s,video:n,videoSmall:c,screen:o}=i;if(s||n||c||o)try{const p=new Date().getTime();s&&this.audioPubState.setState(ee.AliRtcStatePublishing),n&&this.videoPubState.setState(ee.AliRtcStatePublishing),c&&this.videoSmallPubState.setState(ee.AliRtcStatePublishing),o&&this.screenPubState.setState(ee.AliRtcStatePublishing),this.publishPromise=this.rtsManager.publish(this,e,t);const{traceId:h,l1ip:f}=yield this.publishPromise;this.streamTracks=this.rtsManager.publishingTracks,this.traceId=h;const g={type:Bt.Add,userid:this.userId,sessionid:this.sessionId,displayname:this.name,pubid:this.publishId,resume:e,subscribe:{signal:"",pullstreamurl:this.url},l1ip:this.parameter.reportL1IP?f:void 0,callid:this.callId,tracks:this.streamTracks,traceid:h};(l=this.parameter.data)!=null&&l.enablePubDataChannel&&this.publishDataChannel().then(()=>{this.syncPublishToRoomServer(g,i,p)}),h&&(this.traceId=h),s&&this.reportAudioProfile(),n&&this.reportVideoProfile(),o&&this.reportScreenProfile(),yield this.syncPublishToRoomServer(g,i,p),s&&this.audioPubState.setState(ee.AliRtcStatePublished),n&&this.videoPubState.setState(ee.AliRtcStatePublished),c&&this.videoSmallPubState.setState(ee.AliRtcStatePublished),o&&this.screenPubState.setState(ee.AliRtcStatePublished)}catch(p){throw s&&this.audioPubState.setState(ee.AliRtcStateNoPublish),n&&this.videoPubState.setState(ee.AliRtcStateNoPublish),c&&this.videoSmallPubState.setState(ee.AliRtcStateNoPublish),o&&this.screenPubState.setState(ee.AliRtcStateNoPublish),p}else{if((d=this.parameter.data)!=null&&d.enablePubSubDataWithoutMedia&&((u=this.parameter.data)!=null&&u.enablePubDataChannel)){T.event(`[${bt.logName}]`,"startPublish no media stream, publish data channel only");try{const p=new Date().getTime();if(yield this.publishDataChannel(),this.dc){const h={type:Bt.Add,userid:this.userId,sessionid:this.sessionId,displayname:this.name,pubid:this.publishId,resume:e,subscribe:{signal:"",pullstreamurl:this.url},callid:this.callId,tracks:[],traceid:this.traceId};yield this.syncPublishToRoomServer(h,i,p)}}catch(p){T.error(`[${bt.logName}]`,"publishDataChannel without media failed",p)}return}T.event(`[${bt.logName}]`,"startPublish no stream founded")}})}updateStreams(){return I(this,null,function*(){yield this.streamManager.updateStreams()})}publishUpdate(e){return I(this,null,function*(){var n,c,o,l,d;if(T.info(`[${bt.logName}]`,"publishUpdate",e||"-",this.shouldPublish),!this.shouldPublish)return;if(!this.rtsManager.isConnecting&&!this.rtsManager.isConnected)return void(yield this.startPublish());yield this.publishPromise;const t=this.streamManager.publishStreams;let i;const s=new Date().getTime();try{const u=(n=this.streamTracks)==null?void 0:n.find(({ssrc:R,type:_,msid:y})=>_==="audio"&&R&&y===D.Audio),p=yield this.compareAndPublish(u,t.audio,D.Audio);p&&(i=p);const h=(c=this.streamTracks)==null?void 0:c.find(({ssrc:R,type:_,msid:y})=>_==="video"&&R&&y===D.VideoLarge),f=yield this.compareAndPublish(h,t.video,D.VideoLarge);f&&(i=f);const g=(o=this.streamTracks)==null?void 0:o.find(({ssrc:R,type:_,msid:y})=>_==="video"&&R&&y===D.VideoSmall),b=yield this.compareAndPublish(g,t.videoSmall,D.VideoSmall);b&&(i=b);const S=(l=this.streamTracks)==null?void 0:l.find(({ssrc:R,type:_,msid:y})=>_==="video"&&R&&y===D.Screen),v=yield this.compareAndPublish(S,t.screen,D.Screen);v&&(i=v),(d=this.parameter.data)!=null&&d.enablePubDataChannel&&!this.dc&&(yield this.publishDataChannel()),i||e!==Dt.RECONNECT?i&&(yield this.syncPublishToRoomServer(i,t,s)):this.syncPublishToRoomServer({type:Bt.Add,userid:this.userId,sessionid:this.sessionId,displayname:this.name,pubid:this.publishId,subscribe:{signal:"",pullstreamurl:this.url},callid:this.callId,tracks:this.rtsManager.publishingTracks,traceid:this.traceId},t,Date.now())}catch(u){const{code:p}=u!=null?u:{},h=this.url;throw p===403&&h&&(yield this.refreshPushStreamUrl(),i=yield this.publishUpdate()),u}return i})}syncPublishToRoomServer(e,t,i){return I(this,null,function*(){var o;if(!e)return void T.event(`[${bt.logName}]`,"sync publish to room server failed because no publishInfo");let s=e;if(this.dc){const c=e,{tracks:l}=c,d=Wt(c,["tracks"]);s=vt(X({},d),{tracks:[...l,{type:"data",msid:D.Data,ssrc:`web_${this.callId.substring(0,8)}_${((o=this.dc.datachannel)==null?void 0:o.id)||"0"}`,codec:"text"}]})}const n=yield this.signalingManager.publish(s);e.signaltid=n.tid})}refreshPushStreamUrl(){return I(this,null,function*(){const e=new U(B.ERR_INNER,"refresh push stream url error"),t=this.url;if(!t)throw e;const i=yield this.signalingManager.refreshUrl({pushstreamurl:t});if(!(i!=null&&i.pushstreamurl))throw e;this.url=i.pushstreamurl})}publishAdd(e,t,i=!1,s=0){return I(this,null,function*(){const n=(t==null?void 0:t.aMsid)===D.Audio,c=(t==null?void 0:t.vMsid)===D.VideoLarge,o=(t==null?void 0:t.vMsid)===D.VideoSmall,l=(t==null?void 0:t.vMsid)===D.Screen;n&&this.audioPubState.setState(ee.AliRtcStatePublishing),c&&this.videoPubState.setState(ee.AliRtcStatePublishing),o&&this.videoSmallPubState.setState(ee.AliRtcStatePublishing),l&&this.screenPubState.setState(ee.AliRtcStatePublishing);try{const d=yield this.rtsManager.publishAdd(this,e,t,!1,!0);d&&(this.traceId=d),n&&(this.audioPubState.setState(ee.AliRtcStatePublished),this.reportAudioProfile()),c&&(this.videoPubState.setState(ee.AliRtcStatePublished),this.reportVideoProfile()),o&&this.videoSmallPubState.setState(ee.AliRtcStatePublished),l&&(this.screenPubState.setState(ee.AliRtcStatePublished),this.reportScreenProfile()),this.streamTracks=this.rtsManager.publishingTracks;const u={type:Bt.Add,userid:this.userId,sessionid:"",displayname:this.name,pubid:this.publishId,resume:i,subscribe:{signal:"",pullstreamurl:this.url},callid:this.callId,tracks:this.streamTracks,traceid:d};return this.reportSelfDeviceStatus(),this.monitorTimerId||this.startStreamMonitor(),u}catch(d){let u=B.ERR_SDK_PUBLISH_INVAILD;if(n&&(this.audioPubState.setState(ee.AliRtcStateNoPublish),u=B.ERR_SDK_PUBLISH_AUDIO_STREAM_FAILED),c&&(this.videoPubState.setState(ee.AliRtcStateNoPublish),u=B.ERR_SDK_PUBLISH_VIDEO_STREAM_FAILED),o&&(this.videoSmallPubState.setState(ee.AliRtcStateNoPublish),u=B.ERR_SDK_PUBLISH_DUAL_STREAM_FAILED),l&&(this.screenPubState.setState(ee.AliRtcStateNoPublish),u=B.ERR_SDK_PUBLISH_SCEEN_SHARE_FAILED),d.errorCode===15006&&s<3)return this.publishAdd(e,t,i,s+1);throw U.fromError(d,u,"publish add failed")}})}publishReplace(e,t){return I(this,null,function*(){try{yield this.rtsManager.publishReplace(this.url,e,t),this.streamTracks=this.rtsManager.publishingTracks;const i=(t==null?void 0:t.vMsid)===D.VideoLarge,s=(t==null?void 0:t.vMsid)===D.Screen;i&&this.streamManager.setVideoProfile(void 0,void 0,!0),s&&this.streamManager.setScreenProfile(void 0,void 0);const n={type:Bt.Replace,userid:this.userId,sessionid:"",pubid:this.publishId,displayname:this.name,subscribe:{signal:"",pullstreamurl:this.url},callid:this.callId,tracks:this.streamTracks};return this.reportSelfDeviceStatus(),n}catch(i){throw U.fromError(i,B.ERR_INNER,`publish replace failed, vMsid: ${t==null?void 0:t.vMsid} aMsid: ${t==null?void 0:t.aMsid}`)}})}publishDeleteTracks(e){return I(this,null,function*(){const t={type:Bt.Delete,userid:this.userId,sessionid:"",displayname:this.displayname,callid:this.callId,pubid:this.publishId,subscribe:{signal:"",pullstreamurl:this.url},tracks:[]};try{return yield this.rtsManager.publishDelete(this.url,e),this.streamTracks=this.rtsManager.publishingTracks,e.audio&&this.audioPubState.setState(ee.AliRtcStateNoPublish),e.video&&(e.vMsid===D.VideoSmall?this.videoSmallPubState.setState(ee.AliRtcStateNoPublish):this.videoPubState.setState(ee.AliRtcStateNoPublish)),e.screen&&this.screenPubState.setState(ee.AliRtcStateNoPublish),t.tracks=this.streamTracks,this.reportSelfDeviceStatus(),t}catch(i){throw U.fromError(i,B.ERR_INNER,"publish delete tracks failed")}})}publishStop(){return I(this,null,function*(){T.info(`[${bt.logName}]`,"publishStop",{url:this.url});const e=new Date().getTime();try{const t=this.hasAudioTrackInMS,i=this.hasCameraTrackInMS,s=this.hasCameraDualTrackInMS,n=this.hasScreenTrackInMS;yield this.rtsManager.publishStop(this.url),t&&this.audioPubState.setState(ee.AliRtcStateNoPublish),i&&this.videoPubState.setState(ee.AliRtcStateNoPublish),s&&this.videoSmallPubState.setState(ee.AliRtcStateNoPublish),n&&this.screenPubState.setState(ee.AliRtcStateNoPublish),this.traceId="",Object.keys(this.monitorDataCache).forEach(o=>{this.reportPublishMonitor(o)}),this.streamTracks=[];const c={type:Bt.Stop,userid:this.userId,sessionid:this.sessionId,displayname:this.displayname,callid:this.callId,pubid:this.publishId,subscribe:{signal:"",pullstreamurl:this.url},tracks:[]};return this.syncPublishToRoomServer(c,{},e),c}catch(t){throw U.fromError(t,B.ERR_INNER,"publish stop failed")}})}unPublish(){return I(this,null,function*(){this.shouldPublish=!1;const e=new Date().getTime();let t={type:Bt.UnPublish,userid:this.userId,sessionid:"",displayname:this.displayname,callid:this.callId,pubid:this.publishId,subscribe:{signal:"",pullstreamurl:this.url},tracks:[]};try{if(this.isPublishing){const i=this.hasAudioTrackInMS,s=this.hasCameraTrackInMS,n=this.hasCameraDualTrackInMS,c=this.hasScreenTrackInMS;yield this.rtsManager.unpublish(),this.streamTracks=[],this.stopStreamMonitor(),i&&this.audioPubState.setState(ee.AliRtcStateNoPublish),s&&this.videoPubState.setState(ee.AliRtcStateNoPublish),n&&this.videoSmallPubState.setState(ee.AliRtcStateNoPublish),c&&this.screenPubState.setState(ee.AliRtcStateNoPublish),this.traceId="",this.clearStream()}return this.dc&&(this.rtsManager.publishStopDataChannel(this.url,this.dc),this.dataPubState.setState(ee.AliRtcStateNoPublish),this.dc=void 0),this.slsReporter.reportUnpublish(this.callId||"",e,0,""),t}catch(i){throw U.fromError(i,B.ERR_INNER,"unpublish failed")}})}reportSelfDeviceStatus(){this.emit(ot.Local,this.getDeviceStatus())}getDeviceStatus(){var t,i,s,n;let e={micOpen:!1,micInterrupted:!1,cameraOpen:!1,screenShare:!1,audioDisable:!0,videoDisable:!0,screenDisable:!0,backgroundMode:!1,accompanyPlaying:!1};return e.cameraOpen=this.hasCameraTrackInMS,e.videoDisable=this.hasCamera&&!((t=this.streamManager.cameraStreamInfo.originVideoTrack)!=null&&t.enabled),e.micOpen=this.hasAudioTrackInMS,e.audioDisable=this.hasMicrophone&&!((i=this.streamManager.cameraStreamInfo.originAudioTrack)!=null&&i.enabled),e.screenShare=this.hasScreenTrackInMS,e.screenDisable=this.hasScreenShare&&!((n=(s=this.streamManager.screenStreamInfo)==null?void 0:s.originVideoTrack)!=null&&n.enabled),_n.getCurrentStatus(e)}resetPreviewElements(){this.previewElements.forEach(e=>{e.srcObject=null,e._playPromise=void 0},[]),this.previewElements=[]}resetSecondayPreviewElements(){this.screenPreviewElements.forEach(e=>{e.srcObject=null,e._playPromise=void 0},[]),this.screenPreviewElements=[]}getMediaStats(e){return this.pcMediaStatsMap[e]}reportPublishMonitor(e){if(!e)return;let t;try{t=e===D.Audio?this.rtsManager.getStreamByMsid({url:this.url,aMsid:e}).audioTrack:this.rtsManager.getStreamByMsid({url:this.url,vMsid:e}).videoTrack}catch(i){}this.slsReporter.reportPublishMonitor(this.callId,this.traceId||"",e,t,this.monitorDataCache[e]),this.monitorDataCache[e]=[]}reportNetwork(){this.slsReporter.reportNetworkMonitor(this.candidateDataCache),this.candidateDataCache=[]}startStreamMonitor(){this.monitorTimerId||(this.monitorTimerId=window.setInterval(()=>I(this,null,function*(){var e,i;try{const s=yield this.rtsManager.getPCStats();let n,c;if(s==null||s.forEach(l=>{l.type==="media-source"||l.type==="media-playout"?l.id&&(this.pcMediaStatsMap[l.id]=l):l.type==="candidate-pair"&&l.state==="succeeded"&&(n=l)}),((e=this.candidateDataCache)==null?void 0:e.length)>0){const l=this.candidateDataCache[this.candidateDataCache.length-1]||{},t=l,{_last:d}=t;c=Wt(t,["_last"])}((i=this.candidateDataCache)==null?void 0:i.length)>=30&&this.reportNetwork(),n&&(n._last=c,this.candidateDataCache.push(n));let o=Object.keys(this.monitorDataCache).filter(l=>{var d;return((d=this.monitorDataCache[l])==null?void 0:d.length)>0});(this.streamTracks||[]).forEach(l=>{const d=l.msid;if(!d)return;let u;o.includes(d)&&(o=o.filter(p=>p!==d)),u=d===D.Audio?this.rtsManager.getPublishAudioStats(this.url):this.rtsManager.getPublishVideoStats(this.url,d),u.then(p=>{if(!p.timestamp)return;this.monitorDataCache[d]||(this.monitorDataCache[d]=[]);const h=this.getMediaStats(p.mediaSourceId);p._source=h;const f=this.monitorDataCache[d];let g;if((f==null?void 0:f.length)>0){const S=f[f.length-1]||{},b=S,{_last:v}=b;g=Wt(b,["_last"])}(f==null?void 0:f.length)>=30&&this.reportPublishMonitor(d),p._last=g,p._codec=l.codec||"",this.monitorDataCache[d].push(p)})}),o.forEach(l=>{this.reportPublishMonitor(l)})}catch(s){}}),1e3))}stopStreamMonitor(){this.monitorTimerId&&(clearInterval(this.monitorTimerId),this.monitorTimerId=void 0),Object.keys(this.monitorDataCache).forEach(e=>{this.reportPublishMonitor(e)})}clearStream(){this.streamManager.stop(),this.audioPubState.setState(ee.AliRtcStatePublishIdle),this.videoPubState.setState(ee.AliRtcStatePublishIdle),this.videoSmallPubState.setState(ee.AliRtcStatePublishIdle),this.screenPubState.setState(ee.AliRtcStatePublishIdle)}getCurrentCameraDeviceId(){var e;return(e=this.streamManager.cameraStreamInfo.originVideoTrack)==null?void 0:e.getSettings().deviceId}getCurrentMicDeviceId(){var e;return(e=this.streamManager.cameraStreamInfo.originAudioTrack)==null?void 0:e.getSettings().deviceId}enableAudioVolumeIndication(e){this.audioVolumeIndicationInterval!==e&&(this.audioVolumeIndicationInterval>0&&e<=0&&this.audioLevelMonitor.stop(),e>0&&this.streamManager.cameraStreamInfo.originAudioTrack&&this.audioLevelMonitor.start(this.streamManager.cameraStreamInfo.originAudioTrack,e),this.audioVolumeIndicationInterval=e)}sendSEI(e,t,i){return I(this,null,function*(){if(!this.url)return;let s=0;return s=!t||t<1?1:t-1,this.rtsManager.sendSEI(this.url,e,s,i)})}sendDataChannelMessage(e){var i;if(!((i=this.parameter.data)!=null&&i.enablePubDataChannel))throw new U(B.ERR_INNER,"data channel publish is not enabled");if(!this.dc)throw new U(B.ERR_INNER,"data channel is not ready");const t=function(s,n){let c=0;const o=[];for(;c<s.byteLength;){const l=Math.min(n,s.byteLength-c),d=s.slice(c,c+l);o.push(d),c+=l}return o}(e.toBuffer(),1156);t.forEach((s,n)=>{const c=new Gi(new Ti(s.byteLength,n===t.length-1,n===0?1:0),s);this.dc.send(c.toGRTNBuffer())})}getStats(){return I(this,null,function*(){const e=[];if(this.hasAudioTrackInMS){const n=yield this.rtsManager.getPublishAudioStats(this.url);n&&e.push({stats:n,track:ti.AliRtcAudioTrackMic})}const t=[];if(this.hasCameraTrackInMS){const n=yield this.rtsManager.getPublishVideoStats(this.url,D.VideoLarge);n&&t.push({track:ue.AliRtcVideoTrackCamera,streamType:Ge.AliRtcVideoStreamTypeHigh,stats:n})}if(this.hasCameraDualTrackInMS){const n=yield this.rtsManager.getPublishVideoStats(this.url,D.VideoSmall);n&&t.push({track:ue.AliRtcVideoTrackCamera,streamType:Ge.AliRtcVideoStreamTypeLow,stats:n})}if(this.hasScreenTrackInMS){const n=yield this.rtsManager.getPublishVideoStats(this.url,D.Screen);n&&t.push({track:ue.AliRtcVideoTrackScreen,stats:n})}let i;const s=yield this.rtsManager.getPCStats();return s==null||s.forEach(n=>{n.type==="candidate-pair"&&n.state==="succeeded"&&(i=n)}),{audio:e,video:t,candidate:i}})}markReconnect(e){const t=[],i=this.streamManager.publishStreams;!i.audio||e&&!e.includes(D.Audio)||t.push(this.audioPubState),!i.video||e&&!e.includes(D.VideoLarge)||t.push(this.videoPubState),!i.screen||e&&!e.includes(D.Screen)||t.push(this.screenPubState),!this.dc||e&&!e.includes(D.Data)||t.push(this.dataPubState),t.forEach(s=>{s.setState(ee.AliRtcStateReconnecting)})}markReconnected(e){var s;const t=[],i=this.streamManager.publishStreams;if(!i.audio||e&&!e.includes(D.Audio)||t.push(this.audioPubState),!i.video||e&&!e.includes(D.VideoLarge)||t.push(this.videoPubState),!i.screen||e&&!e.includes(D.Screen)||t.push(this.screenPubState),this.dc&&(!e||e.includes(D.Data))&&(t.push(this.dataPubState),(s=this.parameter.data)==null?void 0:s.enablePubDataChannel)){const n=this.rtsManager.getDatachannelByMsid({url:this.url,msid:D.Data});this.updateDataChannel(n)}this.publishUpdate(Dt.RECONNECT),t.forEach(n=>{n.setState(ee.AliRtcStatePublished)})}},m(bt,"logName","LocalUser"),bt);De([k()],Ce.prototype,"clearPublishState",1),De([k()],Ce.prototype,"clear",1),De([k(H)],Ce.prototype,"startDefaultCameraAndMic",1),De([k()],Ce.prototype,"setViewConfig",1),De([k()],Ce.prototype,"startCameraCapture",1),De([k()],Ce.prototype,"stopCameraCapture",1),De([k()],Ce.prototype,"startAudioCapture",1),De([k()],Ce.prototype,"stopAudioCapture",1),De([k()],Ce.prototype,"startCameraAndMic",1),De([k()],Ce.prototype,"stopPreview",1),De([k()],Ce.prototype,"resumePublish",1),De([k()],Ce.prototype,"createLocalStream",1),De([k()],Ce.prototype,"stopLocalStream",1),De([k()],Ce.prototype,"updateDataChannel",1),De([k(H)],Ce.prototype,"startPublish",1),De([k()],Ce.prototype,"updateStreams",1),De([k(([a])=>[a])],Ce.prototype,"syncPublishToRoomServer",1),De([k()],Ce.prototype,"refreshPushStreamUrl",1),De([k(([a,r,e])=>[JSON.stringify(e)])],Ce.prototype,"publishAdd",1),De([k(([a,r])=>[JSON.stringify(r)])],Ce.prototype,"publishReplace",1),De([k(H)],Ce.prototype,"publishDeleteTracks",1),De([k()],Ce.prototype,"publishStop",1),De([k()],Ce.prototype,"unPublish",1),De([k(([a,r,e])=>[a.length,r,e])],Ce.prototype,"sendSEI",1),De([k(H)],Ce.prototype,"markReconnect",1),De([k(H)],Ce.prototype,"markReconnected",1);let Ec=Ce;var At=(a=>(a.OPUS="opus",a.H264="H264",a.H265="H265",a.AV1="AV1",a.UNKNOWN="",a))(At||{}),de=(a=>(a[a.NotSubscribe=0]="NotSubscribe",a[a.Subscribing=1]="Subscribing",a[a.Subscribed=2]="Subscribed",a))(de||{}),oi=(a=>(a.VideoTrackEnded="videoTrackEnded",a.AudioTrackEnded="audioTrackEnded",a.ScreenTrackEnded="screenTrackEnded",a))(oi||{});const Pn=a=>I(this,null,function*(){return yield J.AliRTS.createStream({custom:!0,mediaStream:a})}),ki=a=>I(this,null,function*(){const r=(e=>{const t=new MediaStream;return t.addTrack(e),t})(a);return yield Pn(r)});var Tc=Object.defineProperty,Cc=Object.getOwnPropertyDescriptor;class $s extends oe{constructor(){super();m(this,"audioInfo",{subscribeState:de.NotSubscribe,ssrc:"",msid:"",pt:0,red:0,codec:At.UNKNOWN});m(this,"videoLargeInfo",{subscribeState:de.NotSubscribe,ssrc:"",msid:"",pt:0,red:0,codec:At.UNKNOWN});m(this,"videoSmallInfo",{subscribeState:de.NotSubscribe,ssrc:"",msid:"",pt:0,red:0,codec:At.UNKNOWN});m(this,"screenInfo",{subscribeState:de.NotSubscribe,ssrc:"",msid:"",pt:0,red:0,codec:At.UNKNOWN});m(this,"dataInfo",{subscribeState:de.NotSubscribe,ssrc:"",msid:"",pt:0,red:0,codec:At.UNKNOWN});m(this,"audioVolume",1);m(this,"audioMuted",!1);m(this,"userStatus")}getAudioInfo(){return this.audioInfo}getVideoSmallInfo(){return this.videoSmallInfo}getVideoLargeInfo(){return this.videoLargeInfo}getScreenInfo(){return this.screenInfo}getDataInfo(){return this.dataInfo}get subscribingInfos(){return[this.audioInfo,this.videoLargeInfo,this.videoSmallInfo,this.screenInfo].filter(e=>e.msid&&e.subscribeState===de.Subscribed)}get hasTrack(){return this.hasAudio||this.hasVideo||this.hasScreen||this.hasData}get hasAudio(){return this.audioInfo.ssrc!==""}get hasVideo(){return this.videoLargeInfo.ssrc!==""||this.videoSmallInfo.ssrc!==""}get hasVideoLarge(){return this.videoLargeInfo.ssrc!==""}get hasVideoSmall(){return this.videoSmallInfo.ssrc!==""}get hasScreen(){return this.screenInfo.ssrc!==""}get hasData(){return this.dataInfo.ssrc!==""}get isAudioSubscribed(){return this.audioInfo.subscribeState===de.Subscribed}get isAudioSubscribing(){return this.audioInfo.subscribeState===de.Subscribing}get isVideoSubscribed(){return this.isVideoLargeSubscribed||this.isVideoSmallSubscribed}get isVideoSubscribing(){return this.isVideoLargeSubscribing||this.isVideoSmallSubscribing}get isVideoLargeSubscribed(){return this.videoLargeInfo.subscribeState===de.Subscribed}get isVideoLargeSubscribing(){return this.videoLargeInfo.subscribeState===de.Subscribing}get isVideoSmallSubscribed(){return this.videoSmallInfo.subscribeState===de.Subscribed}get isVideoSmallSubscribing(){return this.videoSmallInfo.subscribeState===de.Subscribing}get isScreenSubscribed(){return this.screenInfo.subscribeState===de.Subscribed}get isScreenSubscribing(){return this.screenInfo.subscribeState===de.Subscribing}get isDataSubscribed(){return this.dataInfo.subscribeState===de.Subscribed}get isDataSubscribing(){return this.dataInfo.subscribeState===de.Subscribing}get audioCodec(){return this.audioInfo.codec}get videoCodec(){return this.hasVideoLarge?this.videoLargeInfo.codec:this.hasVideoSmall?this.videoSmallInfo.codec:this.hasScreen?this.screenInfo.codec:At.UNKNOWN}get audioTrackInfo(){return this.hasAudio?ti.AliRtcAudioTrackMic:ti.AliRtcAudioTrackNo}get videoTrackInfo(){return this.hasVideo&&this.hasScreen?ue.AliRtcVideoTrackBoth:this.hasVideo?ue.AliRtcVideoTrackCamera:this.hasScreen?ue.AliRtcVideoTrackScreen:ue.AliRtcVideoTrackNo}updateTracks(e){let t="",i="",s="",n="",c="";return e?(e.forEach(o=>{var p;let l=At.UNKNOWN;const d=((p=o==null?void 0:o.attr)==null?void 0:p.reason)==="reconnect";if(o.userdata){const{codec:h}=JSON.parse(o.userdata);h&&(l=h)}var u;(u=o.msid)===D.Audio||u===os.Audio?(t=o.ssrc,this.audioInfo.msid=o.msid,this.audioInfo.codec=l,(d||this.audioInfo.ssrc!==t)&&(this.audioInfo.subscribeState=de.NotSubscribe)):(h=>h===D.VideoSmall)(o.msid)?(s=o.ssrc,this.videoSmallInfo.msid=o.msid,this.videoSmallInfo.codec=l,(d||this.videoSmallInfo.ssrc!==s)&&(this.videoSmallInfo.subscribeState=de.NotSubscribe)):(h=>h===D.VideoLarge||h===os.VideoLarge)(o.msid)?(i=o.ssrc,this.videoLargeInfo.msid=o.msid,this.videoLargeInfo.codec=l,(d||this.videoLargeInfo.ssrc!==i)&&(this.videoLargeInfo.subscribeState=de.NotSubscribe)):(h=>h===D.Screen)(o.msid)?(n=o.ssrc,this.screenInfo.msid=o.msid,this.screenInfo.codec=l,(d||this.screenInfo.ssrc!==n)&&(this.screenInfo.subscribeState=de.NotSubscribe)):(h=>h===D.Data)(o.msid)&&(c=o.ssrc,this.dataInfo.msid=o.msid,this.dataInfo.codec=l,(d||this.dataInfo.ssrc!==c)&&(this.dataInfo.subscribeState=de.NotSubscribe))}),this.updateRemoteTrackSsrc(t,i,s,n,c)):this.updateRemoteTrackSsrc(t,i,s,n,c),{}}updateRemoteTrackSsrc(e,t,i,s,n){this.audioInfo.ssrc=e,this.videoSmallInfo.ssrc=i,this.videoLargeInfo.ssrc=t,this.screenInfo.ssrc=s,this.dataInfo.ssrc=n}markRemoteTrackSubscribing(e){return e.video&&(e.vMsid===this.videoSmallInfo.msid&&(this.videoSmallInfo.subscribeState=de.Subscribing),e.vMsid!==this.videoLargeInfo.msid&&e.vMsid||(this.videoLargeInfo.subscribeState=de.Subscribing)),e.screen&&(this.screenInfo.subscribeState=de.Subscribing),e.audio&&(this.audioInfo.subscribeState=de.Subscribing),e.data&&(this.dataInfo.subscribeState=de.Subscribing),{videoLargeInfo:this.videoLargeInfo,videoSmallInfo:this.videoSmallInfo}}updateRemoteTrackSubState(e){return e.video!==void 0&&(e.vMsid===this.videoSmallInfo.msid&&(this.videoSmallInfo.subscribeState=e.video?de.Subscribed:de.NotSubscribe),e.vMsid!==this.videoLargeInfo.msid&&e.vMsid||(this.videoLargeInfo.subscribeState=e.video?de.Subscribed:de.NotSubscribe)),e.screen!==void 0&&(this.screenInfo.subscribeState=e.screen?de.Subscribed:de.NotSubscribe),e.audio!==void 0&&(this.audioInfo.subscribeState=e.audio?de.Subscribed:de.NotSubscribe),e.data!==void 0&&(this.dataInfo.subscribeState=e.data?de.Subscribed:de.NotSubscribe),{audioInfo:this.audioInfo,videoLargeInfo:this.videoLargeInfo,videoSmallInfo:this.videoSmallInfo,screenInfo:this.screenInfo,dataInfo:this.dataInfo}}updateRemoteUserDeviceStatus(e){let t=_n.parseStatus(e);const{audioDisable:i,videoDisable:s,screenDisable:n}=t;return this.userStatus?(this.userStatus.audioDisable!=i&&(this.userStatus.audioDisable=i,this.emit(ot.Remote,i?Me.MuteAudio:Me.UnmuteAudio)),this.userStatus.videoDisable!=s&&(this.userStatus.videoDisable=s,this.emit(ot.Remote,s?Me.MuteVideo:Me.UnmuteVideo)),this.userStatus.screenDisable!=n&&(this.userStatus.screenDisable=n,this.emit(ot.Remote,n?Me.MuteScreen:Me.UnmuteScreen))):(this.userStatus=t,this.emit(ot.Remote,i?Me.MuteAudio:Me.UnmuteAudio),this.emit(ot.Remote,s?Me.MuteVideo:Me.UnmuteVideo),this.emit(ot.Remote,n?Me.MuteScreen:Me.UnmuteScreen)),!1}}m($s,"logName","RemoteStreamInfo"),((a,r,e,t)=>{for(var i,s=t>1?void 0:t?Cc(r,e):r,n=a.length-1;n>=0;n--)(i=a[n])&&(s=(t?i(r,e,s):i(s))||s);t&&s&&Tc(r,e,s)})([k()],$s.prototype,"updateRemoteTrackSubState",1);class Dn{constructor(r){m(this,"remoteUser");this.remoteUser=r}get userId(){return this.remoteUser.userId}get displayName(){return this.remoteUser.displayname}get isMuteAudioPlaying(){return this.remoteUser.getAudioMuted()}get hasAudio(){return this.remoteUser.hasAudioTrack}get hasCamera(){return this.remoteUser.hasVideoTrack}get hasCameraLarge(){return this.remoteUser.hasVideoLargeTrack}get hasCameraSmall(){return this.remoteUser.hasVideoSmallTrack}get hasScreenShare(){return this.remoteUser.hasScreenTrack}get isAudioSubscribing(){return this.remoteUser.isAudioSubscribing}get isVideoSubscribing(){return this.remoteUser.isVideoSubscribing}get isVideoLargeSubscribing(){return this.remoteUser.isVideoLargeSubscribing}get isVideoSmallSubscribing(){return this.remoteUser.isVideoSmallSubscribing}get isScreenSubscribing(){return this.remoteUser.isScreenSubscribing}get audioElement(){return this.remoteUser.getAudioElement()}}var kc=Object.defineProperty,Pc=Object.getOwnPropertyDescriptor,Ke=(a,r,e,t)=>{for(var i,s=t>1?void 0:t?Pc(r,e):r,n=a.length-1;n>=0;n--)(i=a[n])&&(s=(t?i(r,e,s):i(s))||s);return t&&s&&kc(r,e,s),s};class fi extends oe{constructor(){super();m(this,"state");m(this,"time");m(this,"_enabled");this.state=ce.AliRtcStateSubscribeIdle,this.time=Date.now(),this._enabled=!0}setState(e){if(this.state===e)return;const t=this.state,i=this.time;this.state=e,this.time=Date.now(),this.emit("change",t,e,Math.floor((this.time-i)/1e3))}get currentState(){return this.state}getEnabled(){return this._enabled}setEnabled(e){this._enabled=e}}const We=(ui=class extends wn{constructor(e){var h;const{userId:t,displayName:i,rtsManager:s,usersViewMap:n,slsReporter:c,signalingManager:o,localUser:l,audioVolumeIndicationInterval:d,playoutVolume:u,parameter:p}=e;super(t,i,s,d);m(this,"remoteCallId","");m(this,"remoteUserInfo");m(this,"localUser");m(this,"lastPubId","");m(this,"stream");m(this,"screenStream");m(this,"viewMap");m(this,"audioTrack");m(this,"audioElement");m(this,"subscribed",!1);m(this,"mediaStream");m(this,"secondaryMediaStream");m(this,"prevSubConfig");m(this,"signalingManager");m(this,"slsReporter");m(this,"wantSubAudio",!1);m(this,"wantSubVideo",!1);m(this,"wantSubScreen",!1);m(this,"defaultVideoStreamType",Ge.AliRtcVideoStreamTypeHigh);m(this,"audioMuted",!1);m(this,"playoutVolume",1);m(this,"playoutGainNode");m(this,"audioSubState");m(this,"videoSubState");m(this,"videoLargeSubState",new fi);m(this,"videoSmallSubState",new fi);m(this,"screenSubState");m(this,"dataSubState");m(this,"dc");m(this,"dcMsgWaitingPieces",[]);m(this,"streamInfo");m(this,"_streamUrl","");m(this,"parameter",{});m(this,"_audioResumeHandler",null);m(this,"_videoResumeHandler",null);m(this,"monitorTimerId");m(this,"monitorDataCache",{});m(this,"traceId","");m(this,"handleAudioContextSuspended",e=>{e.target.state==="suspended"&&this.emit("remoteAudioPlayError",this.uid,"AudioContext suspended")});m(this,"onDataChannelMessage",e=>{var s;const t=Gi.parse(e.slice(4));let i;if(t.body){if(!t.isFin)return t.header.frameType===1&&(this.dcMsgWaitingPieces=[]),void this.dcMsgWaitingPieces.push(t.body);if(this.dcMsgWaitingPieces.length>0){const n=this.dcMsgWaitingPieces.reduce((c,o)=>c+o.byteLength,t.body.byteLength);try{const c=new ArrayBuffer(n);let o=0;for(let l=0;l<this.dcMsgWaitingPieces.length;l++){const d=this.dcMsgWaitingPieces[l];new Uint8Array(c,o,d.byteLength).set(new Uint8Array(d)),o+=d.byteLength}new Uint8Array(c,o,t.body.byteLength).set(new Uint8Array(t.body)),i=Jt.parse(c)}catch(c){}this.dcMsgWaitingPieces=[],i||(i=Jt.parse(t.body))}else i=Jt.parse(t.body);i||T.event(`[${this.logName}]`,`parse data channel message fail, piece count: ${this.dcMsgWaitingPieces.length+1}`)}i&&(T.event(`[${this.logName}]`,`receive dc message, length(${(s=i.data)==null?void 0:s.byteLength})`),this.emit("remoteDataChannelMessage",this.uid,i))});m(this,"onDataChannelError",e=>{this.emit("occurError",U.fromError(e,B.ERR_SDK_SUBSCRIBE_DATA_ERROR))});m(this,"dataChannelConnected",e=>{e&&(this.dc=e,this.dc.datachannel&&(this.dc.datachannel.binaryType="arraybuffer"),this.dc.off("message",this.onDataChannelMessage),this.dc.off("error",this.onDataChannelError),this.dc.on("message",this.onDataChannelMessage),this.dc.on("error",this.onDataChannelError))});m(this,"handleAudioPaused",()=>{this.emit("remoteAudioPlayError",this.uid,"paused")});this.streamInfo=new $s,this.remoteUserInfo=new Dn(this),this.parameter=p,this.streamInfo.on(ot.Remote,f=>{this.emit(ot.Remote,f,this.userId)}),this.signalingManager=o,this.viewMap=(h=n[t])!=null?h:{cameraViews:[],screenViews:[]},n[t]=this.viewMap,this.slsReporter=c,this.localUser=l,this.audioSubState=new fi,this.audioSubState.on("change",(f,g,b)=>{this.emit("audioSubscribeStateChanged",this.uid,f,g,b)}),this.videoSubState=new fi,this.videoSubState.on("change",(f,g,b)=>{this.emit("videoSubscribeStateChanged",this.uid,f,g,b)}),this.screenSubState=new fi,this.screenSubState.on("change",(f,g,b)=>{this.emit("screenSubscribeStateChanged",this.uid,f,g,b)}),this.dataSubState=new fi,this.dataSubState.on("change",(f,g,b)=>{this.emit("dataSubscribeStateChanged",this.uid,f,g,b)}),this.playoutVolume=u}get logName(){return`${ui.logName}(${this.userId})`}get streamUrl(){return this._streamUrl}set streamUrl(e){this._streamUrl=e,this.rtsManager.updateAuth(e)}isWantSubAudio(){return this.wantSubAudio}setWantSubAudio(e){this.wantSubAudio=e}isWantSubVideo(){return this.wantSubVideo}setWantSubVideo(e){this.wantSubVideo=e}isWantSubScreen(){return this.wantSubScreen}setWantSubScreen(e){this.wantSubScreen=e}setRemoteDefaultVideoStreamType(e){e!==this.defaultVideoStreamType&&(this.defaultVideoStreamType=e,this.updateSubscribe(ge.User))}setAudioMuted(e){this.audioMuted=e,this.toggleAudio(!e)}getAudioElement(){return this.audioElement}setPlayoutVolume(e){if(this.playoutVolume=e,this.audioElement)if(this.parameter.enableAudioContextPlayoutVolume)if(this.playoutGainNode)this.playoutGainNode.gain.value=e;else{const t=this.audioElement.srcObject;if(t){const i=yt.getInstance();i.addEventListener("statechange",this.handleAudioContextSuspended);const s=i.createMediaStreamSource(t);this.audioElement.muted=!0,this.playoutGainNode=i.createGain(),s.connect(this.playoutGainNode),this.playoutGainNode.gain.value=e,this.playoutGainNode.connect(i.destination)}}else this.audioElement.volume=e}getAudioMuted(){return this.audioMuted}get hasAudioTrack(){return this.streamInfo.hasAudio}get audioSSRC(){var e;return this.streamInfo.isAudioSubscribed&&((e=this.streamInfo.getAudioInfo())==null?void 0:e.ssrc)||""}get hasVideoTrack(){return this.streamInfo.hasVideo}get videoSSRC(){var e,t;return this.streamInfo.isVideoSubscribed?((e=this.streamInfo.getVideoLargeInfo())==null?void 0:e.ssrc)||"":this.streamInfo.isVideoSmallSubscribed&&((t=this.streamInfo.getVideoSmallInfo())==null?void 0:t.ssrc)||""}get hasVideoLargeTrack(){return this.streamInfo.hasVideoLarge}get hasVideoSmallTrack(){return this.streamInfo.hasVideoSmall}get hasScreenTrack(){return this.streamInfo.hasScreen}get isAudioSubscribing(){return this.streamInfo.isAudioSubscribed||this.streamInfo.isAudioSubscribing}get isVideoSubscribing(){return this.streamInfo.isVideoSubscribed||this.streamInfo.isVideoSubscribing}get isVideoLargeSubscribing(){return this.streamInfo.isVideoLargeSubscribed||this.streamInfo.isVideoLargeSubscribing}get isVideoSmallSubscribing(){return this.streamInfo.isVideoSmallSubscribed||this.streamInfo.isVideoSmallSubscribing}get isScreenSubscribing(){return this.streamInfo.isScreenSubscribed||this.streamInfo.isScreenSubscribing}get isDataSubscribing(){return this.streamInfo.isDataSubscribed||this.streamInfo.isDataSubscribing}get audioEnabled(){var e,t;return!!((t=(e=this.stream)==null?void 0:e.audioTrack)!=null&&t.enabled)}get videoEnabled(){var e,t;return!!((t=(e=this.stream)==null?void 0:e.videoTrack)!=null&&t.enabled)}get screenEnabled(){var e,t;return!!((t=(e=this.screenStream)==null?void 0:e.videoTrack)!=null&&t.enabled)}get getAudioTrack(){return this.audioTrack}get getCameraStream(){return this.stream}get getScreenStream(){return this.screenStream}setViewConfig(e,t){if(t!==ue.AliRtcVideoTrackScreen&&t!==ue.AliRtcVideoTrackCamera)throw new U(B.ERR_INVALID_ARGUMENTS,"track is not AliRtcVideoTrackScreen or AliRtcVideoTrackCamera");e?cs(e).forEach(i=>{i.setAttribute("playsinline",""),J.AliRTS.BrowserUtil.isMicroMessenger&&(i.setAttribute("x5-video-player-type","h5-page"),i.setAttribute("x5-playsinline",""),J.AliRTS.SystenUtil.isAndroid||J.AliRTS.SystenUtil.isIos&&i.setAttribute("x-webkit-airplay","allow")),t===ue.AliRtcVideoTrackScreen?this.viewMap.screenViews.push(i):this.viewMap.cameraViews.push(i),this.play(i,t===ue.AliRtcVideoTrackScreen)}):(this.stopPlayAll(t===ue.AliRtcVideoTrackScreen),t===ue.AliRtcVideoTrackScreen?this.viewMap.screenViews=[]:this.viewMap.cameraViews=[])}clear(e=!0){return I(this,null,function*(){var t,i,s,n;ur(ui.prototype,this,"clear").call(this),this._removeAudioResumeHandler(),this._removeVideoResumeHandler(),this.stopPlayAudio(),this.stopStreamMonitor(),e&&this.subscribeDeleteAllTracks(this.streamUrl).catch(c=>{T.event(`[${this.logName}]`,`stopSubscribeAllTracks error: ${c.message||c}`)}),this.clearStream(),this.clearScreenStream(),this.playoutGainNode&&(this.playoutGainNode.disconnect(),this.playoutGainNode=void 0,yt.getInstance().removeEventListener("statechange",this.handleAudioContextSuspended)),this.streamInfo.removeAllListeners(),(t=this.audioSubState)==null||t.removeAllListeners(),(i=this.videoSubState)==null||i.removeAllListeners(),(s=this.screenSubState)==null||s.removeAllListeners(),(n=this.dataSubState)==null||n.removeAllListeners()})}updateRemoteUserDeviceStatus(e){this.streamInfo.updateRemoteUserDeviceStatus(e)}updateRemoteTracks(e,t,i,s){return I(this,null,function*(){return this.remoteCallId=e,this.streamUrl&&this.streamInfo.hasTrack||(this.streamUrl=t),this.streamInfo.updateTracks(s)})}subscribe(s,n){return I(this,arguments,function*(e,t,i=Date.now()){var h,f;this.createCallId();let c=e;if(!c){const{hasAudio:g,hasVideo:b,hasScreen:S,hasData:v}=(h=this.streamInfo)!=null?h:{};c={audio:this.wantSubAudio&&g,video:this.wantSubVideo&&b,screen:this.wantSubScreen&&S,data:((f=this.parameter.data)==null?void 0:f.enableSubDataChannel)&&v}}this.streamInfo.markRemoteTrackSubscribing(c);const{screen:o,audio:l,video:d,vMsid:u}=c,p=[];(d||l)&&p.push({audio:l,video:d,vMsid:u}),o&&p.push({screen:o}),(p.length!==0||e!=null&&e.data)&&(yield Promise.all(p.map(g=>this.subscribeProxy(g,t||ge.User,i))),e!=null&&e.data&&this.subscribeDataChannel())})}subscribeProxy(e,t,i){return I(this,null,function*(){var c,o;let s=new Date().getTime(),n="";if(this.streamUrl)try{e.audio&&this.audioSubState.setState(ce.AliRtcStateSubscribing),e.video&&(this.videoSubState.currentState!==ce.AliRtcStateSubscribeIdle&&this.videoSubState.currentState!==ce.AliRtcStateNoSubscribe||this.videoSubState.setState(ce.AliRtcStateSubscribing)),e.screen&&this.screenSubState.setState(ce.AliRtcStateSubscribing);const l=yield this.rtsManager.subscribe({remoteUser:this,options:e},t,((c=this.localUser)==null?void 0:c.callId)||"",this.callId,i);if(!l)return e.audio&&this.audioSubState.setState(ce.AliRtcStateNoSubscribe),e.video&&this.videoSubState.setState(ce.AliRtcStateNoSubscribe),e.screen&&this.screenSubState.setState(ce.AliRtcStateNoSubscribe),this.streamInfo.updateRemoteTrackSubState({audio:e.audio!==!0&&void 0,video:e.video!==!0&&void 0,screen:e.screen!==!0&&void 0,vMsid:e.vMsid}),void _e.getInstance().addEventData(_e.eventSubError,this.uid,e.audio,e.video);this.streamInfo.updateRemoteTrackSubState(e),n=l.traceId||"";const{stream:d}=l;if(n&&(this.traceId=n),e.audio){const h=d.audioTrack;h&&(this.audioTrack=h,(o=d.mediaStream)==null||o.removeTrack(h),this.playAudio(),this.audioVolumeIndicationInterval&&this.audioLevelMonitor.start(h,this.audioVolumeIndicationInterval)),this.audioSubState.getEnabled()||this.toggleAudio(!1),this.audioSubState.setState(ce.AliRtcStateSubscribed)}e.video&&(this.updateStream(d,this.isVideoLargeSubscribing&&this.isVideoSmallSubscribing),this.videoSubState.getEnabled()||this.toggleVideo(!1),this.videoSubState.setState(ce.AliRtcStateSubscribed),e.vMsid===D.VideoSmall?this.videoSmallSubState.setState(ce.AliRtcStateSubscribed):this.videoLargeSubState.setState(ce.AliRtcStateSubscribed)),e.screen&&(this.updateScreenStream(d),this.videoSubState.getEnabled()||this.toggleScreen(!1),this.screenSubState.setState(ce.AliRtcStateSubscribed));const u=new Date().getTime()-s,p=Date.now();setTimeout(()=>I(this,null,function*(){const h=yield this.rtsManager.getGatewayIp();this.slsReporter.reportSubscribe(this.callId,this.remoteCallId,!!e.video&&e.vMsid===D.VideoLarge,!!e.video&&e.vMsid===D.VideoSmall,!!e.screen,!!e.audio,0,"",u,{pctid:this.rtsManager.pcTraceId,subtid:this.traceId,ajsub:t===ge.Join?1:0,url:this.streamUrl,est:s,gi:h},p)}),6e3),this.startStreamMonitor(),l.isHTTP&&l.statsCheckPromise&&(yield Promise.race([l.statsCheckPromise,Ht(1500)])),_e.getInstance().addEventData(_e.eventSubSuccess,this.uid,e.audio,e.video)}catch(l){const d=new Date().getTime()-s;e.audio&&this.audioSubState.setState(ce.AliRtcStateNoSubscribe),e.video&&this.videoSubState.setState(ce.AliRtcStateNoSubscribe),e.screen&&this.screenSubState.setState(ce.AliRtcStateNoSubscribe),this.streamInfo.updateRemoteTrackSubState({audio:e.audio!==!0&&void 0,video:e.video!==!0&&void 0,screen:e.screen!==!0&&void 0,vMsid:e.vMsid}),l&&(l.message=`user(${this.uid}) subscribe error, ${(l==null?void 0:l.message)||""}`);let u=B.ERR_INNER;e.audio&&(u=B.ERR_SDK_SUBSCRIBE_AUDIO_STREAM_FAILED),e.video&&(u=e.vMsid===D.VideoSmall?B.ERR_SDK_SUBSCRIBE_DUAL_STREAM_FAILED:B.ERR_SDK_SUBSCRIBE_VIDEO_STREAM_FAILED),e.screen&&(u=B.ERR_SDK_SUBSCRIBE_SCREEN_SHARE_FAILED);const p=yield this.rtsManager.getGatewayIp();this.slsReporter.reportSubscribe(this.callId,this.remoteCallId,!!e.video&&e.vMsid===D.VideoLarge,!!e.video&&e.vMsid===D.VideoSmall,!!e.screen,!!e.audio,u,"",d,{pctid:this.rtsManager.pcTraceId,subtid:"",ajsub:t===ge.Join?1:0,url:this.streamUrl,est:s,gi:p});const h=U.fromError(l,u);this.emit("remoteSubscribeError",h)}else{const l=new U(B.ERR_SDK_SUBSCRIBE_INVAILD,`user(${this.uid}) subscribe failed: streamUrl is not ready. Please subscribe after receiving 'remoteTrackAvailableNotify' event instead of 'remoteUserOnLineNotify'.`);this.emit("remoteSubscribeError",l)}})}subscribeDeleteTracks(e){return I(this,null,function*(){const{audio:t,video:i,screen:s,data:n,vMsid:c}=e,o=[];(t||i||n)&&o.push({audio:t,video:i,vMsid:c}),s&&o.push({screen:s}),o.length!==0&&(yield Promise.all(o.map(l=>this.subscribeDeleteProxy(l))),e.data&&this.subscribeDeleteDataChannel())})}subscribeDeleteProxy(e){return I(this,null,function*(){try{const t=yield this.rtsManager.subscribeDelete({remoteUser:this,options:e}),{stream:i}=t!=null?t:{},s={};e.audio===!0&&(s.audio=!1,this.audioSubState.setState(ce.AliRtcStateNoSubscribe)),e.video===!0&&(s.video=!1,e.vMsid===D.VideoSmall?(this.videoSmallSubState.setState(ce.AliRtcStateNoSubscribe),this.videoLargeSubState.currentState!==ce.AliRtcStateNoSubscribe&&this.videoLargeSubState.currentState!==ce.AliRtcStateSubscribeIdle||this.videoSubState.setState(ce.AliRtcStateNoSubscribe)):(this.videoLargeSubState.setState(ce.AliRtcStateNoSubscribe),this.videoSmallSubState.currentState!==ce.AliRtcStateNoSubscribe&&this.videoSmallSubState.currentState!==ce.AliRtcStateSubscribeIdle||this.videoSubState.setState(ce.AliRtcStateNoSubscribe))),e.screen===!0&&(s.screen=!1,this.screenSubState.setState(ce.AliRtcStateNoSubscribe));const{callId:n,remoteCallId:c}=this,o={callid:n,remoteCallid:c,remoteStream:i};return e.audio&&(this.audioLevelMonitor.stop(),this.stopPlayAudio(),this.audioTrack=void 0),this.streamInfo.updateRemoteTrackSubState({audio:e.audio!==!0&&void 0,video:e.video!==!0&&void 0,screen:e.screen!==!0&&void 0,vMsid:e.vMsid}),o}catch(t){throw U.fromError(t,B.ERR_INNER,"subscribe delete failed")}})}restore(){this.callId="",this.clearStream(),this.clearScreenStream(),this.audioTrack=void 0,this.streamInfo.updateRemoteTrackSubState({audio:!1,video:!1,screen:!1,data:!1}),this.audioElement&&this.audioElement.removeEventListener("pause",this.handleAudioPaused)}resumeAudio(){return I(this,null,function*(){const e=yt.getInstance();return e.state!=="running"&&e.resume(),this.audioElement?this.audioElement.play():this.playAudio()})}resumeVideo(e){return I(this,null,function*(){return e&&e!==ue.AliRtcVideoTrackCamera&&e!==ue.AliRtcVideoTrackBoth?e&&e!==ue.AliRtcVideoTrackScreen&&e!==ue.AliRtcVideoTrackBoth?void 0:this.playAll(!0):this.playAll()})}resumePlay(){this.playAudio(),this.playAll(),this.playAll(!0)}stopSubscribe(e){return I(this,null,function*(){let t=new Date().getTime();try{e?yield this.subscribeDeleteTracks(e):yield this.subscribeDeleteAllTracks(this.streamUrl),this.slsReporter.reportUnsubscribe(this.callId,this.remoteCallId,new Date().getTime()-t,0,"")}catch(i){throw this.slsReporter.reportUnsubscribe(this.callId,this.remoteCallId,new Date().getTime()-t,0,""),i}})}subscribeDeleteAllTracks(e){return I(this,null,function*(){var s,n,c,o;const{callId:t,remoteCallId:i}=this;if((this.isAudioSubscribing||this.isVideoSubscribing||this.isScreenSubscribing||this.dc)&&e)try{yield this.subscribeDeleteTracks({audio:this.isAudioSubscribing,video:this.isVideoSubscribing,screen:this.isScreenSubscribing,data:!!this.dc}),this.restore();const l={callid:t,remoteCallid:i,remoteStream:this.stream};return this.callId="",l}catch(l){if(((o=(c=(n=(s=l==null?void 0:l.extraInfo)==null?void 0:s.parsedData)==null?void 0:n.streams)==null?void 0:c[0])==null?void 0:o.res_code)!==404)throw U.fromError(l,B.ERR_INNER,"subscribe stop failed")}})}updateStream(e,t=!1){return I(this,null,function*(){this.stream&&this.stream.videoTrack&&e.mediaStream&&t&&(yield new Promise(i=>{let s,n;if(e.mediaStream){n=document.createElement("video");const c=()=>{T.event(`[${this.logName}]`,"new mediaStream canplay"),n&&n.removeEventListener("canplaythrough",c,!1),n=void 0,clearTimeout(s),i(!0)};n.addEventListener("canplaythrough",c,!1),(n._playPromise||Promise.resolve()).then(()=>{n&&e.mediaStream&&(n.srcObject=e.mediaStream)})}else i(!0);s=window.setTimeout(()=>{T.event(`[${this.logName}]`,"new mediaStream timeout"),n=void 0,i(!0)},3e3)}),this.updateSubscribe(ge.User)),this.stream=e,this.playAll(!1,t),!this.subscribed&&e&&(this.subscribed=!0),e.hasAudio&&this.isAudioSubscribing&&e.enableAudio(),e.hasVideo&&this.isVideoSubscribing&&e.enableVideo()})}updateScreenStream(e){this.screenStream=e,this.playAll(!0),!this.subscribed&&e&&(this.subscribed=!0),e.hasVideo&&this.isScreenSubscribing&&e.enableVideo()}clearStream(){var e;(e=this.stream)==null||e.stop(),this.stream=void 0}clearScreenStream(){var e;(e=this.screenStream)==null||e.stop(),this.screenStream=void 0}subscribeDataChannel(){var e;if(this.dc)try{this.dcMsgWaitingPieces=[],this.dc.off("message",this.onDataChannelMessage),this.dc=void 0}catch(t){}if(!((e=this.parameter.data)!=null&&e.enablePubSubDataWithoutMedia||this.streamInfo.hasAudio||this.streamInfo.hasVideo||this.streamInfo.hasScreen))return this.dataSubState.setState(ce.AliRtcStateNoSubscribe),void this.streamInfo.updateRemoteTrackSubState({data:!1});this.dataSubState.setState(ce.AliRtcStateSubscribing),this.rtsManager.subscribeAddDataChannel(this.streamUrl).then(t=>{if(t)return this.dataChannelConnected(t),this.dataSubState.setState(ce.AliRtcStateSubscribed),void this.streamInfo.updateRemoteTrackSubState({data:!0});throw new Error("no dc founded")}).catch(t=>{const i=U.fromError(t,B.ERR_INNER,"subscribe data failed");this.emit("remoteSubscribeError",i),this.dataSubState.setState(ce.AliRtcStateNoSubscribe),this.streamInfo.updateRemoteTrackSubState({data:!1})})}subscribeDeleteDataChannel(){if(this.dc){try{this.rtsManager.subscribeDeleteDatachannel(this.streamUrl,this.dc)}catch(e){}this.dcMsgWaitingPieces=[],this.dc.off("message",this.onDataChannelMessage),this.dc.off("error",this.onDataChannelError),this.dataSubState.setState(ce.AliRtcStateNoSubscribe),this.dc=void 0,this.streamInfo.updateRemoteTrackSubState({data:!1})}}getRetryOptions(){var i,s;const e={};this.wantSubAudio&&this.streamInfo.hasAudio&&(e.audio=!0,e.aMsid=((i=this.streamInfo.getAudioInfo())==null?void 0:i.msid)||D.Audio),this.wantSubVideo&&this.streamInfo.hasVideo&&(this.defaultVideoStreamType===Ge.AliRtcVideoStreamTypeLow&&this.streamInfo.hasVideoSmall?(e.video=!0,e.vMsid=D.VideoSmall):this.streamInfo.hasVideoLarge&&(e.video=!0,e.vMsid=((s=this.streamInfo.getVideoLargeInfo())==null?void 0:s.msid)||D.VideoLarge)),this.wantSubScreen&&this.streamInfo.hasScreen&&(e.screen=!0);let t={};if(e.audio||e.video)t={audio:e.audio,video:e.video},this.streamInfo.updateRemoteTrackSubState({screen:!1,data:!1});else{if(!e.screen)return;t={screen:e.screen},this.streamInfo.updateRemoteTrackSubState({data:!1})}return{remoteUser:this,options:t}}updateSubscribe(e){var n,c,o,l,d,u;const t=Date.now(),i={},s={};return this.wantSubAudio&&!this.isAudioSubscribing&&this.streamInfo.hasAudio&&this.audioSubState.currentState!==ce.AliRtcStateReconnecting?(i.audio=!0,i.aMsid=((n=this.streamInfo.getAudioInfo())==null?void 0:n.msid)||D.Audio):this.wantSubAudio&&this.streamInfo.hasAudio||!this.isAudioSubscribing||(s.audio=!0,s.aMsid=((c=this.streamInfo.getAudioInfo())==null?void 0:c.msid)||D.Audio),this.wantSubVideo&&this.streamInfo.hasVideo?(this.defaultVideoStreamType===Ge.AliRtcVideoStreamTypeLow&&!this.isVideoSmallSubscribing&&this.streamInfo.hasVideoSmall&&this.videoSmallSubState.currentState!==ce.AliRtcStateReconnecting?(i.video=!0,i.vMsid=D.VideoSmall):this.isVideoLargeSubscribing||!this.streamInfo.hasVideoLarge||this.defaultVideoStreamType===Ge.AliRtcVideoStreamTypeLow&&this.isVideoSmallSubscribing&&this.streamInfo.hasVideoSmall||this.videoLargeSubState.currentState===ce.AliRtcStateReconnecting||(i.video=!0,i.vMsid=((o=this.streamInfo.getVideoLargeInfo())==null?void 0:o.msid)||D.VideoLarge),this.defaultVideoStreamType===Ge.AliRtcVideoStreamTypeLow&&this.isVideoLargeSubscribing&&this.isVideoSmallSubscribing&&this.streamInfo.hasVideoSmall?(s.video=!0,s.vMsid=D.VideoLarge):this.defaultVideoStreamType!==Ge.AliRtcVideoStreamTypeHigh&&this.streamInfo.hasVideoSmall||!this.isVideoLargeSubscribing||!this.isVideoSmallSubscribing||(s.video=!0,s.vMsid=D.VideoSmall)):this.wantSubVideo&&this.streamInfo.hasVideo||!this.isVideoSubscribing||(s.video=!0,s.vMsid=this.streamInfo.isVideoSmallSubscribed||this.streamInfo.isVideoSmallSubscribing?D.VideoSmall:((l=this.streamInfo.getVideoLargeInfo())==null?void 0:l.msid)||D.VideoLarge),this.wantSubScreen&&!this.isScreenSubscribing&&this.streamInfo.hasScreen&&this.screenSubState.currentState!==ce.AliRtcStateReconnecting?i.screen=!0:this.wantSubScreen&&this.streamInfo.hasScreen||!this.isScreenSubscribing||(s.screen=!0),(d=this.parameter.data)!=null&&d.enableSubDataChannel&&!this.isDataSubscribing&&this.streamInfo.hasData&&this.dataSubState.currentState!==ce.AliRtcStateReconnecting?i.data=!0:(u=this.parameter.data)!=null&&u.enableSubDataChannel&&this.streamInfo.hasData||!this.isDataSubscribing||(s.data=!0),this.dc&&i.data&&this.subscribeDeleteDataChannel(),(i.audio||i.video||i.screen||i.data)&&this.subscribe(i,e,t),(s.audio||s.video||s.screen)&&this.subscribeDeleteTracks(s),{addOption:i,deleteOption:s}}handleAutoPlayFailed(){T.event(`[${this.logName}]`,"auto play failed"),this.emit("remoteAudioAutoPlayFail",this.uid),this._removeAudioResumeHandler();const e=()=>{this.resumeAudio().finally(()=>{this._removeAudioResumeHandler()})};this._audioResumeHandler=e,document.addEventListener("click",e,!1),document.addEventListener("touchstart",e,!1)}_removeAudioResumeHandler(){this._audioResumeHandler&&(document.removeEventListener("click",this._audioResumeHandler,!1),document.removeEventListener("touchstart",this._audioResumeHandler,!1),this._audioResumeHandler=null)}handleVideoPlayFailded(e,t){this.emit("remoteVideoAutoPlayFail",this.uid,t),this._removeVideoResumeHandler();const i=()=>{var n;const s=(n=t===ue.AliRtcVideoTrackScreen?this.screenStream:this.stream)==null?void 0:n.mediaStream;e.srcObject===s&&this.play(e,t===ue.AliRtcVideoTrackScreen),this._removeVideoResumeHandler()};this._videoResumeHandler=i,document.addEventListener("click",i,!1),document.addEventListener("touchstart",i,!1)}_removeVideoResumeHandler(){this._videoResumeHandler&&(document.removeEventListener("click",this._videoResumeHandler,!1),document.removeEventListener("touchstart",this._videoResumeHandler,!1),this._videoResumeHandler=null)}playAudio(){return I(this,null,function*(){var e,t;if(this.audioTrack){if(this.toggleAudio(!this.audioMuted),this.audioElement||(T.event(`[${this.logName}]`,"create audio element"),this.audioElement=document.createElement("audio"),this.audioElement.setAttribute("autoplay","autoplay"),this.audioElement.addEventListener("pause",this.handleAudioPaused),this.setPlayoutVolume(this.playoutVolume)),((t=(e=this.audioElement.srcObject)==null?void 0:e.getAudioTracks())==null?void 0:t[0])!==this.audioTrack){let i=this.audioElement.srcObject;i?i.getAudioTracks().forEach(s=>{i.removeTrack(s)}):(i=new MediaStream,this.audioElement.srcObject=i),i.addTrack(this.audioTrack)}if(J.AliRTS.SystenUtil.isIos&&parseInt(J.AliRTS.SystenUtil.systemVersion)<=13){T.event(`[${this.logName}]`,"play audio for iOS 13-");const i=this.audioElement;i.setAttribute("autoplay","");const s=()=>{i.removeEventListener("playing",s),i.pause(),i.play().catch(()=>{this.handleAutoPlayFailed()})};this.audioElement.addEventListener("playing",s)}else(()=>{var i;T.event(`[${this.logName}]`,"try play audio"),(i=this.audioElement)==null||i.play().then(()=>{_e.getInstance().addEventData(_e.eventFirstAudio,this.uid),T.event(`[${this.logName}]`,"play audio success")}).catch(()=>{this.handleAutoPlayFailed()})})()}else T.event(`[${this.logName}]`,"audio track is null")})}stopPlayAudio(){this.audioElement&&(this.audioElement.pause(),this.audioElement.removeEventListener("pause",this.handleAudioPaused))}playAll(e=!1,t=!1){e?(this.viewMap.screenViews||[]).forEach(i=>{this.play(i,e,t)}):(this.viewMap.cameraViews||[]).forEach(i=>{this.play(i,e,t)})}play(e,t=!1,i=!1){const s=t?this.screenStream:this.stream;e&&s&&s.mediaStream&&Cn(e,s.mediaStream,i).catch(n=>{n.code!==20&&n.name!=="AbortError"&&this.handleVideoPlayFailded(e,t?ue.AliRtcVideoTrackScreen:ue.AliRtcVideoTrackCamera)})}stopPlayAll(e=!1){e?this.viewMap.screenViews.forEach(t=>{Mt(t)}):this.viewMap.cameraViews.forEach(t=>{Mt(t)})}toggleAudio(e=!0){this.audioSubState.setEnabled(e),this.audioElement&&(this.audioElement.muted=!e)}toggleVideo(e=!0){this.videoSubState.setEnabled(e),this.stream&&(e?this.stream.enableVideo():this.stream.disableVideo())}toggleScreen(e=!0){this.screenSubState.setEnabled(e),this.screenStream&&(e?this.screenStream.enableVideo():this.screenStream.disableVideo())}getStats(){return I(this,null,function*(){var i,s,n;const e=[];if(this.isAudioSubscribing){const c=yield this.rtsManager.getSubscribeAudioStats(this.streamUrl);c&&e.push({uid:this.uid,track:ti.AliRtcAudioTrackMic,stats:c})}const t=[];if(this.streamInfo.isVideoLargeSubscribed){const c=yield this.rtsManager.getSubscribeVideoStats(this.streamUrl,((i=this.streamInfo.getVideoLargeInfo())==null?void 0:i.msid)||D.VideoLarge);c&&t.push({uid:this.uid,track:ue.AliRtcVideoTrackCamera,streamType:Ge.AliRtcVideoStreamTypeHigh,stats:c})}if(this.streamInfo.isVideoSmallSubscribed){const c=yield this.rtsManager.getSubscribeVideoStats(this.streamUrl,((s=this.streamInfo.getVideoSmallInfo())==null?void 0:s.msid)||D.VideoSmall);c&&t.push({uid:this.uid,track:ue.AliRtcVideoTrackCamera,streamType:Ge.AliRtcVideoStreamTypeLow,stats:c})}if(this.isScreenSubscribing){const c=yield this.rtsManager.getSubscribeVideoStats(this.streamUrl,((n=this.streamInfo.getScreenInfo())==null?void 0:n.msid)||D.Screen);c&&t.push({uid:this.uid,track:ue.AliRtcVideoTrackScreen,stats:c})}return{audio:e,video:t}})}enableAudioVolumeIndication(e){this.audioVolumeIndicationInterval!==e&&(this.audioVolumeIndicationInterval>0&&e<=0&&this.audioLevelMonitor.stop(),e>0&&this.audioTrack&&this.audioLevelMonitor.start(this.audioTrack,e),this.audioVolumeIndicationInterval=e)}reportSubscribeMonitor(e){e&&(this.slsReporter.reportSubscribeMonitor(this.callId,this.remoteCallId,this.traceId,e,this.monitorDataCache[e]),this.monitorDataCache[e]=[])}startStreamMonitor(){this.monitorTimerId||(this.monitorTimerId=window.setInterval(()=>I(this,null,function*(){try{if(this.streamInfo.subscribingInfos.length===0)return void this.stopStreamMonitor();let e=Object.keys(this.monitorDataCache).filter(t=>{var i;return((i=this.monitorDataCache[t])==null?void 0:i.length)>0});this.streamInfo.subscribingInfos.forEach(t=>{const i=t.msid;if(!i)return;let s;e.includes(i)&&(e=e.filter(c=>c!==i));const n=i===D.Audio;s=n?this.rtsManager.getSubscribeAudioStats(this.streamUrl):this.rtsManager.getSubscribeVideoStats(this.streamUrl,i),s.then(c=>{var u;if(!c.timestamp)return;this.monitorDataCache[i]||(this.monitorDataCache[i]=[]);const o=this.monitorDataCache[i];let l;if((o==null?void 0:o.length)>0){const p=o[o.length-1]||{},d=p,{_last:h}=d;l=Wt(d,["_last"])}(o==null?void 0:o.length)>=30&&this.reportSubscribeMonitor(i),c._last=l,c._codec=t.codec,n&&(c._source=(u=this.localUser)==null?void 0:u.getMediaStats(c.playoutId)),this.monitorDataCache[i].push(c)})}),e.forEach(t=>{this.reportSubscribeMonitor(t)})}catch(e){}}),1e3))}stopStreamMonitor(){this.monitorTimerId&&(clearInterval(this.monitorTimerId),this.monitorTimerId=void 0),Object.keys(this.monitorDataCache).forEach(e=>{this.reportSubscribeMonitor(e)})}markReconnect(e){const t=[];!this.isAudioSubscribing||e&&!e.includes(this.streamInfo.getAudioInfo().msid)||t.push(this.audioSubState),this.isVideoSubscribing&&(!e||e.includes(this.streamInfo.getVideoLargeInfo().msid)||e.includes(this.streamInfo.getVideoSmallInfo().msid))&&t.push(this.videoSubState),!this.isScreenSubscribing||e&&!e.includes(this.streamInfo.getScreenInfo().msid)||t.push(this.screenSubState),!this.isDataSubscribing||e&&!e.includes(D.Data)||t.push(this.dataSubState),t.forEach(i=>{i.setState(ce.AliRtcStateReconnecting)})}markReconnected(e){const t=[],i=this.streamInfo.getAudioInfo().msid||D.Audio;if(this.isAudioSubscribing&&(!e||e.includes(i))){t.push(this.audioSubState);const o=this.rtsManager.getStreamByMsid({url:this.streamUrl,aMsid:i});o&&o.audioTrack&&(this.audioTrack=o.audioTrack,this.audioVolumeIndicationInterval>0&&(this.audioLevelMonitor.stop(),this.audioLevelMonitor.start(this.audioTrack,this.audioVolumeIndicationInterval)),this.playAudio())}const s=this.streamInfo.getVideoLargeInfo().msid||D.VideoLarge,n=this.streamInfo.getVideoSmallInfo().msid||D.VideoSmall;if(this.isVideoSubscribing&&(!e||e.includes(s)||e.includes(n))){t.push(this.videoSubState);const o=this.rtsManager.getStreamByMsid({url:this.streamUrl,vMsid:this.streamInfo.isVideoSmallSubscribed||this.streamInfo.isVideoSmallSubscribing?n:s});o&&o.mediaStream&&(this.stream=o,this.playAll(!1))}const c=this.streamInfo.getScreenInfo().msid||D.Screen;if(this.isScreenSubscribing&&(!e||e.includes(c))){t.push(this.screenSubState);const o=this.rtsManager.getStreamByMsid({url:this.streamUrl,vMsid:c});o&&o.mediaStream&&(this.screenStream=o,this.playAll(!0))}if(this.isDataSubscribing&&(!e||e.includes(this.streamInfo.getDataInfo().msid))){t.push(this.dataSubState);const o=this.rtsManager.getDatachannelByMsid({url:this.streamUrl,msid:this.streamInfo.getDataInfo().msid||D.Data});this.dataChannelConnected(o)}t.forEach(o=>{o.setState(ce.AliRtcStateSubscribed)}),e||this.updateSubscribe(ge.Reconnect)}},m(ui,"logName","RemoteUser"),ui);Ke([k()],We.prototype,"clear",1),Ke([k()],We.prototype,"updateRemoteUserDeviceStatus",1),Ke([k()],We.prototype,"updateRemoteTracks",1),Ke([k(H)],We.prototype,"subscribe",1),Ke([k()],We.prototype,"subscribeProxy",1),Ke([k(H)],We.prototype,"subscribeDeleteProxy",1),Ke([k()],We.prototype,"restore",1),Ke([k(H)],We.prototype,"resumeAudio",1),Ke([k(H)],We.prototype,"stopSubscribe",1),Ke([k(H)],We.prototype,"subscribeDeleteAllTracks",1),Ke([k()],We.prototype,"clearStream",1),Ke([k()],We.prototype,"clearScreenStream",1),Ke([k()],We.prototype,"updateSubscribe",1),Ke([k()],We.prototype,"playAudio",1),Ke([k()],We.prototype,"stopPlayAudio",1),Ke([k((a,r,e)=>[typeof a=="string"?a:a==null?void 0:a.nodeType,r||"-",e||"-"])],We.prototype,"play",1),Ke([k()],We.prototype,"stopPlayAll",1),Ke([k(H)],We.prototype,"markReconnect",1),Ke([k(H)],We.prototype,"markReconnected",1);let Dc=We;var qt=(a=>(a[a.AliRtcPluginErrorCodeSuccess=0]="AliRtcPluginErrorCodeSuccess",a[a.AliRtcPluginErrorCodeFailed=-1]="AliRtcPluginErrorCodeFailed",a[a.AliRtcPluginErrorNoFindPlugin=-2]="AliRtcPluginErrorNoFindPlugin",a[a.AliRtcPluginErrorParameterError=-3]="AliRtcPluginErrorParameterError",a[a.AliRtcPluginErrorLoadError=-4]="AliRtcPluginErrorLoadError",a[a.AliRtcPluginErrorCreateError=-5]="AliRtcPluginErrorCreateError",a[a.AliRtcPluginErrorInitError=-6]="AliRtcPluginErrorInitError",a[a.AliRtcPluginErrorInitTokenError=-7]="AliRtcPluginErrorInitTokenError",a))(qt||{});class Mc extends oe{constructor(){super(...arguments);m(this,"plugins",new Map)}add(e,t){if(this.plugins.has(e.name))throw new U(qt.AliRtcPluginErrorCreateError,`Plugin ${e.name} already exists`);this.plugins.set(e.name,e),t&&e.setOptions(t),this.emit("added",e),e.on("enabled",()=>this.emit("added",e)),e.on("disabled",()=>this.emit("removed",e)),e.on("updated",()=>this.emit("updated",e))}remove(e){const t=this.plugins.get(e);if(!t)throw new U(qt.AliRtcPluginErrorNoFindPlugin,`Plugin ${e} not founded`);try{t.disable()}catch(i){}if(typeof t.stop=="function")try{t.stop()}catch(i){}if(typeof t.destroy=="function")try{t.destroy()}catch(i){}this.plugins.delete(e),t.removeAllListeners(),this.emit("removed",t)}removeAll(){Array.from(this.plugins.keys()).forEach(e=>{this.remove(e)})}get(e){return this.plugins.get(e)}has(e){return!!this.plugins.get(e)}getAll(){return Array.from(this.plugins.values())}}const Lc=a=>I(this,null,function*(){const r=new J.AliRTS.SupportUtil;window.isSecureContext||console.warn("WebRTC 需要 HTTPS 安全上下文,细节可参考:https://developer.mozilla.org/zh-CN/docs/Web/Security/Secure_Contexts");let e={support:!1,detail:{isWebRTCSupported:r.checkMediaDevices()&&r.checkWebRtcSupport(),isH264DecodeSupported:!1,isH264EncodeSupported:!1,isScreenShareSupported:!1,isSendMediaExtensionMsgSupported:!1,isBrowserSupported:!0}},t=!1;try{e.detail.isWebRTCSupported?(yield r.isSupport({isReceiveVideo:!0}),t=!0):console.warn("当前浏览器不支持 WebRTC")}catch(i){t=!1,e.detail.isBrowserSupported=r.checkBrowser({errorCode:0,message:""})}if(e.support=t,r.checkWebRtcSupport()&&a!=="sendonly"){const i=yield r.checkH264Decode();e.detail.isH264DecodeSupported=i,e.support=e.support&&i}if(r.checkWebRtcSupport()&&a!=="recvonly"){const i=yield r.checkH264Encode();e.detail.isH264EncodeSupported=i,e.support=e.support&&i}return e.detail.isScreenShareSupported=r.checkWebRtcSupport()&&r.checkScreenCapture()&&!J.AliRTS.SystenUtil.isAndroid&&!J.AliRTS.SystenUtil.isIos,e.detail.isSendMediaExtensionMsgSupported=r.checkWebRtcSupport()&&r.checkEncodedTransformSupport(),e}),Mn=a=>{const r=a.toLowerCase();return r.indexOf("h265")>0||r.indexOf("h.265")>0||r.indexOf("hevc")>0},Nc=()=>I(this,null,function*(){var a;try{const r=typeof RTCRtpReceiver!="undefined"&&typeof RTCRtpReceiver.getCapabilities=="function"?RTCRtpReceiver.getCapabilities("video"):null;if((a=r==null?void 0:r.codecs)!=null&&a.some(e=>e.mimeType.toLowerCase()==="video/h265"))return!0}catch(r){}return(()=>I(this,null,function*(){if(typeof RTCPeerConnection=="undefined")return!1;let r=new RTCPeerConnection;try{const e=yield r.createOffer({offerToReceiveVideo:!0,offerToReceiveAudio:!0});return!(!e||!e.sdp)&&Mn(e.sdp)}catch(e){return!1}finally{r==null||r.close(),r=void 0}}))()}),xc=()=>I(this,null,function*(){var r;try{const e=typeof RTCRtpSender!="undefined"&&typeof RTCRtpSender.getCapabilities=="function"?RTCRtpSender.getCapabilities("video"):null;if((r=e==null?void 0:e.codecs)!=null&&r.some(t=>t.mimeType.toLowerCase()==="video/h265"))return!0}catch(e){}if(typeof RTCPeerConnection=="undefined")return!1;let a=new RTCPeerConnection;try{a.addTransceiver("video",{direction:"sendonly"});const e=yield a.createOffer();return Mn(e.sdp||"")}catch(e){return!1}finally{a==null||a.close(),a=void 0}}),{BrowserUtil:Ln}=J.AliRTS,Lt="RtsManager";class Oc{constructor(r){m(this,"ctx");m(this,"rtsClientMap",new Map);m(this,"pubBaseUrl");this.ctx=r}createPerUserRtsInstance(){return J.AliRTS.createClient({singlePcConfig:{usePcReconnect:!0}})}getOrCreateClientEntry(r){let e=this.rtsClientMap.get(r);if(!e){const t=this.createPerUserRtsInstance();e={client:t,connected:!1,traceId:""},this.rtsClientMap.set(r,e),this.addPerUserRTSListener(t,r)}return e}destroyClientEntry(r){const e=this.rtsClientMap.get(r);if(e){try{e.client.removeAllListeners(),e.client.unsubscribe()}catch(t){}this.rtsClientMap.delete(r)}}addPerUserRTSListener(r,e){r.on("connectStatusChange",t=>{T.event(`[${Lt}]`,`[multi-pc:${e}] connectStatusChange to:`,t.status);const i=this.rtsClientMap.get(e);i&&(t.status===J.EConnectStatus.CONNECT_STATUS_DISCONNECTED?(i.connected=!1,e===this.pubBaseUrl&&(this.ctx.slsReporter.reportWarning("rts disconnected (multi-pc pub)"),this.ctx.emit("disconnected"))):t.status===J.EConnectStatus.CONNECT_STATUS_CONNECTED&&(i.connected=!0,e===this.pubBaseUrl&&this.ctx.emit("connected",!1,Pi.PUBLISH)))}),r.on("reconnect",t=>{var i,s,n;T.debug(`[${Lt}]`,`[multi-pc:${e}] reconnect`,t),this.ctx.emit("reconnect",t.type,(i=t.extraInfo)==null?void 0:i.url,(n=(s=t.extraInfo)==null?void 0:s.msids)==null?void 0:n.map(c=>c.name))}),r.on("reconnectFinish",t=>{var s;T.debug(`[${Lt}]`,`[multi-pc:${e}] reconnectFinish`,t),this.ctx.emit("reconnectFinish",(t==null?void 0:t.type)||"pc",t==null?void 0:t.latestUrl,(s=t==null?void 0:t.msids)==null?void 0:s.map(n=>n.name));const i=this.rtsClientMap.get(e);if(i&&(i.connected=!0),e===this.pubBaseUrl)try{this.ctx.emit("connected",!0,Pi.PUBLISH)}catch(n){T.error(`[${Lt}]`,"emit connected error:",n)}}),r.on("receivedSEI",t=>{this.ctx.emit("seimessage",t.url,t.sei.payloadType,t.sei.data)}),r.on("traceId",({url:t,traceId:i})=>{if(!t||!i||this.ctx.traceIdMap[t]===i)return;this.ctx.traceIdMap[t]=i;const s=this.rtsClientMap.get(e);s&&(s.traceId=i),this.ctx.emit("traceIdUpdated",t,i)}),r.on("onError",t=>{T.event(`[${Lt}]`,`[multi-pc:${e}] onError:`,t)})}get isConnected(){var r,e;if(this.pubBaseUrl)return(e=(r=this.rtsClientMap.get(this.pubBaseUrl))==null?void 0:r.connected)!=null?e:!1;for(const t of this.rtsClientMap.values())if(t.connected)return!0;return!1}get isConnecting(){if(this.pubBaseUrl){const r=this.rtsClientMap.get(this.pubBaseUrl);return!!r&&!r.connected}return!1}publish(r,e,t){return I(this,null,function*(){const i=r.url,s=r.callId,n=i.split("?")[0];this.pubBaseUrl=n;const c=this.getOrCreateClientEntry(n),o=Date.now();let l;const{publishStream:d,vMsid:u}=yield this.ctx.localStreamManager.createHTTPPublishStream();if(!d)return T.warn(`[${Lt}]`,"multiPCPublish: publishStream is null"),{traceId:"",l1ip:l};const p=this.ctx.getPubMsid(d,{vMsid:u});p.answerSdpHook=v=>{const R=/\d+\.\d+\.\d+\.\d+(?=\s+1106|\s+8000)/.exec(v);return R!=null&&R[0]&&(l=R[0]),v},this.ctx.handleHTTPConfig(p),p.disableHeartbeat=!0,this.ctx.rtsPeerConnectionType=Pi.PUBLISH;const h=Date.now();let f="";try{const v=this.ctx.suffixHttpUrl(i);f=yield c.client.publish(v,d,p)}catch(v){c.connected=!1;const R=2e3-(Date.now()-h);throw R<=0?this.ctx.emit("disconnected"):setTimeout(()=>{this.ctx.emit("disconnected")},R),this.ctx.slsReporter.reportPublish(e,i,s,d.hasVideo&&(!u||u===D.VideoLarge),d.hasVideo&&u===D.VideoSmall,d.hasVideo&&u===D.Screen,d.hasAudio,(v==null?void 0:v.errorCode)||-1,this.ctx.pcTraceId,"",h,h),U.fromRtsError(v)}f&&(this.ctx.pcTraceId=f,c.traceId=f),c.connected=!0,this.ctx.publishingTracks=c.client.getPublishTrackInfoList(),T.event(`[${Lt}]`,"multiPCPublish success",f);const g=Date.now();setTimeout(()=>{this.ctx.slsReporter.reportPublish(e,i,s,d.hasVideo&&(!u||u===D.VideoLarge),d.hasVideo&&u===D.VideoSmall,d.hasVideo&&u===D.Screen,d.hasAudio,0,this.ctx.pcTraceId,r.traceId,h,g)},6e3),this.ctx.slsReporter.reportConnectionLatencyEvent(Ze.HANDLE_PUB_TASK,st.START,s,f,o),this.ctx.slsReporter.reportConnectionLatencyEvent(Ze.HANDLE_PUB_TASK,st.END,s,f,Date.now());const b=!d.hasVideo,S=u;return yield this.waitPublishSender(i,b,S),this.ctx.slsReporter.reportPublishFirstPacket(e,s,h,g,this.ctx.localJoinTime,b?D.Audio:p.vMsid,f||"",f||"",t),this.ctx.emit("connected",!1,Pi.PUBLISH),{traceId:f,l1ip:l}})}publishStop(r){return I(this,null,function*(){if(this.pubBaseUrl){const e=this.rtsClientMap.get(this.pubBaseUrl);e&&(yield e.client.publishStop([{url:r}]),this.destroyClientEntry(this.pubBaseUrl),this.pubBaseUrl=void 0)}return this.ctx.publishingTracks=[],""})}unpublish(){return I(this,null,function*(){this.pubBaseUrl&&(this.destroyClientEntry(this.pubBaseUrl),this.pubBaseUrl=void 0),this.ctx.publishingTracks=[]})}subscribe(r,e,t,i,s){return I(this,null,function*(){const{options:n,remoteUser:c}=r;if(n.screen)return T.warn(`[${Lt}]`,"screen subscribe not supported in multi-PC mode"),null;const o=c.streamUrl,l=o.split("?")[0];this.ctx.subUrlMap[c.userId]=l;const d=this.getOrCreateClientEntry(l),u=this.ctx.getSubConfig(c.streamInfo,n);this.ctx.handleHTTPConfig(u),u.disableHeartbeat=!0;const p=Date.now();let h;try{const A=this.ctx.suffixHttpUrl(o,u);h=yield d.client.subscribe(A,u)}catch(A){throw d.connected=!1,U.fromRtsError(A)}d.connected=!0,d.traceId=h.traceId,this.ctx.reportSubscribeLatency(n,t,p,!0);const f={traceId:h.traceId,stream:h,isHTTP:!0},g=Date.now();let b=D.VideoLarge;const S=n.video,v=n.audio;n.video&&n.vMsid&&(b=n.vMsid);let R=0,_=0,y=0;const w=((A,E)=>{let C=0;const P=()=>{if(!this.rtsClientMap.has(l))return Promise.resolve();let M;return v&&!R&&(M=d.client.getSubscribeAudioStats(o).then(x=>{if(x.packetsReceived>0)R=Date.now();else if(!S)return C<A&&(C++,new Promise(K=>setTimeout(()=>K(P()),E)));return!0})),S&&!y&&(M=d.client.getSubscribeVideoStats(o,b).then(x=>{if(typeof x.packetsReceived=="number"){if(!_&&x.packetsReceived>0&&(_=Date.now()),x.framesDecoded>0)y=Date.now();else if(C<A)return C++,new Promise(K=>setTimeout(()=>K(P()),E));return!0}})),Promise.resolve(M)};return P()})(20,100);return w.then(()=>{_&&this.ctx.slsReporter.reportSubscribeFirstPacket(e===ge.Resume,t,i,b,{fprt:_-p,ifsprtc:y?y-p:0,ajsub:e===ge.Join?1:0,pctid:d.traceId,subtid:(f==null?void 0:f.traceId)||"",sstc:g-p}),y&&this.ctx.slsReporter.reportSubscribeFirstFrame(e===ge.Resume,t,i,b,{fvfrt:y-p,fp2fftc:y-_,ajsub:e===ge.Join?1:0,tffrtc:e===ge.Join?y-this.ctx.localJoinTime:y-s,pctid:d.traceId,subtid:(f==null?void 0:f.traceId)||"",fvfdtc:y-p}),R&&(this.ctx.slsReporter.reportConnectionLatencyEvent(Ze.FIRST_REMOTE,st.DECODED,t,D.Audio,R),this.ctx.slsReporter.reportSubscribeFirstPacket(e===ge.Resume,t,i,D.Audio,{fprt:R-p,ifsprtc:R-p,ajsub:e===ge.Join?1:0,pctid:d.traceId,subtid:(f==null?void 0:f.traceId)||"",sstc:g-p}))}),f.statsCheckPromise=w,f})}subscribeDelete(r){return I(this,null,function*(){const{remoteUser:e,options:t}=r,i=e.streamUrl.split("?")[0];if(!this.rtsClientMap.get(i))return null;const s=!!t.audio,n=!(!t.video&&!t.screen);if(this.destroyClientEntry(i),s&&n)return null;const c={};s||(c.audio=!0),n||(c.video=!0);const o=this.getOrCreateClientEntry(i),l=this.ctx.getSubConfig(e.streamInfo,c);this.ctx.handleHTTPConfig(l),l.disableHeartbeat=!0;try{const d=this.ctx.suffixHttpUrl(e.streamUrl,l),u=yield o.client.subscribe(d,l);o.connected=!0,o.traceId=u.traceId,T.info(`[${Lt}]`,"multiPCSubscribeDelete: re-subscribed remaining tracks",c)}catch(d){T.error(`[${Lt}]`,"multiPCSubscribeDelete: re-subscribe failed",d),this.destroyClientEntry(i)}return null})}getPublishVideoStats(r,e){return I(this,null,function*(){if(this.pubBaseUrl){const t=this.rtsClientMap.get(this.pubBaseUrl);if(t)return t.client.getPublishVideoStats(r,e)}return{}})}getPublishAudioStats(r,e){return I(this,null,function*(){if(this.pubBaseUrl){const t=this.rtsClientMap.get(this.pubBaseUrl);if(t)return t.client.getPublishAudioStats(r,e)}return{}})}getSubscribeVideoStats(r,e){return I(this,null,function*(){const t=r.split("?")[0],i=this.rtsClientMap.get(t);return i?i.client.getSubscribeVideoStats(r,e):{}})}getSubscribeAudioStats(r,e){return I(this,null,function*(){const t=r.split("?")[0],i=this.rtsClientMap.get(t);return i?i.client.getSubscribeAudioStats(r,e):{}})}getNetworkQuality(){return I(this,null,function*(){var i,s;let r=0,e=0,t=!1;for(const n of this.rtsClientMap.values())if(n.connected)try{const c=(s=(i=n.client.commonController)==null?void 0:i.peerCore)==null?void 0:s.pc;if(!c||c.connectionState==="disconnected"||c.connectionState==="failed"||c.connectionState==="closed")continue;t=!0;const o=c.getReceivers();let l=0,d=0,u=0;for(const h of o)(yield h.getStats()).forEach(f=>{f.type==="candidate-pair"&&typeof f.currentRoundTripTime=="number"&&(l=Math.round(1e3*f.currentRoundTripTime)),f.type!=="inbound-rtp"||f.mediaType!=="audio"&&f.mediaType!=="video"||(d+=f.packetsLost||0,u+=f.packetsReceived||0)});const p=u>0?Math.round(d/(d+u)*100):0;l>r&&(r=l),p>e&&(e=p)}catch(c){}return t?{rtt:r,loss:e,quality:ds(e,r)}:{rtt:0,loss:0,quality:tt.AliRtcNetworkDisconnected}})}getPCStats(){return I(this,null,function*(){var r,e;if(this.pubBaseUrl){const t=this.rtsClientMap.get(this.pubBaseUrl);if(t)return(e=(r=t.client.commonController.peerCore)==null?void 0:r.pc)==null?void 0:e.getStats()}})}getStreamByMsid(r){if(r!=null&&r.url){const e=r.url.split("?")[0],t=this.rtsClientMap.get(e);if(t)return t.client.commonController.streamManager.getStreamByMsid(r)}}updateAuth(r){const e=r.split("?")[0],t=this.rtsClientMap.get(e);t&&t.client.updateAuth(r)}sendSEI(r,e,t,i){return I(this,null,function*(){if(this.pubBaseUrl){const s=this.rtsClientMap.get(this.pubBaseUrl);if(s)return s.client.sendSEI({url:r,vMsid:D.VideoLarge,data:e,repeatCount:t,payloadType:i})}})}waitPublishSender(r,e=!1,t){return I(this,null,function*(){var s;const i=this.pubBaseUrl?(s=this.rtsClientMap.get(this.pubBaseUrl))==null?void 0:s.client:void 0;if(i)return Promise.race([Ht(1e3),((n,c)=>{let o=0;const l=()=>(e?i.getPublishAudioStats(r,t):i.getPublishVideoStats(r,t)).then(d=>!(d.bytesSent>0)&&o<n?(o++,new Promise(u=>setTimeout(()=>u(l()),c))):Promise.resolve());return l()})(5,100)]).catch(()=>{})})}clear(){for(const[r]of this.rtsClientMap)this.destroyClientEntry(r);this.rtsClientMap.clear(),this.pubBaseUrl=void 0}}var Vc=Object.defineProperty,Uc=Object.getOwnPropertyDescriptor,Je=(a,r,e,t)=>{for(var i,s=t>1?void 0:t?Uc(r,e):r,n=a.length-1;n>=0;n--)(i=a[n])&&(s=(t?i(r,e,s):i(s))||s);return t&&s&&Vc(r,e,s),s},Pi=(a=>(a.PUBLISH="publish",a.SUBSCRIBE="subscribe",a))(Pi||{});const Xi=([a])=>{const{remoteUser:r,options:e}=a;return[`user(${r.userId})`,e]};class Bc{constructor(r,e=5){m(this,"queue");m(this,"queue2");m(this,"batchFunc");m(this,"maxCount");m(this,"disabled",!1);m(this,"pendingFlush",Promise.resolve());this.queue=[],this.queue2=[],this.batchFunc=r,this.maxCount=e}add(r){return this.disabled?this.batchFunc([r]).then(e=>e.find(t=>t.url===r.url)||e[0]):(this.queue.length>=this.maxCount||this.queue2.length>=this.maxCount?this.flush():(e=>{if(typeof e!="function")throw new TypeError("Callback must be a function");typeof Promise!="undefined"?Promise.resolve().then(e).catch(t=>console.error(t)):setTimeout(e,0)})(this.flush.bind(this)),new Promise((e,t)=>{this.queue.find(i=>i.config.url===r.url)?this.queue2.push({config:r,resolve:e,reject:t}):this.queue.push({config:r,resolve:e,reject:t})}))}waitForPending(){return I(this,null,function*(){(this.queue.length>0||this.queue2.length>0)&&this.flush(),yield this.pendingFlush})}fallbackToSingleRequest(r){r.forEach(e=>{this.batchFunc([e.config]).then(t=>{const i=t.find(s=>s.url===e.config.url)||t[0];e.resolve(i)}).catch(t=>{e.reject(t)})})}handleError(r,e){var t;(t=r==null?void 0:r.message)!=null&&t.includes("Message too large")?(this.disabled=!0,T.warn("[Batcher]","Message too large, batcher disabled, fallback to single request"),this.fallbackToSingleRequest(e)):e.forEach(i=>i.reject(r))}flush(){if(this.queue.length===0&&this.queue2.length===0)return;const r=this.queue.map(i=>i),e=this.queue2.map(i=>i);this.queue=[],this.queue2=[];const t=[];[r,e].forEach(i=>{if(i.length>0)try{const s=this.batchFunc(i.map(n=>n.config)).then(n=>{n.forEach(c=>{const o=i.find(l=>l.config.url===c.url);o&&o.resolve(c)})}).catch(n=>{this.handleError(n,i)});t.push(s)}catch(s){this.handleError(s,i)}}),t.length>0&&(this.pendingFlush=Promise.all(t).then(()=>{}))}}const ze=(se=class extends oe{constructor(e,t,i){var s,n,c,o;super();m(this,"rts");m(this,"dycConf",new J.DynamicConfig);m(this,"encodedInsertableStreams",!0);m(this,"audioRedEnabled",!1);m(this,"localStreamManager");m(this,"slsReporter");m(this,"_rtsPeerConnectionType","publish");m(this,"connecting",!1);m(this,"connected",!1);m(this,"rtsDisconnected",!1);m(this,"_pcTraceId","");m(this,"_localJoinTime",0);m(this,"connectionResolve");m(this,"connectingPromise");m(this,"dcResolve");m(this,"dcReject");m(this,"dcConnectingPromise");m(this,"_dcReady",!1);m(this,"_prevDownlinkStat");m(this,"_publishingTracks",[]);m(this,"parameter",{});m(this,"preferredPubL1Ip");m(this,"preferredSubL1Ip");m(this,"httpPublishUrlMap",{});m(this,"httpSubscribeUrlMap",{});m(this,"traceIdMap",{});m(this,"subUrlMap",{});m(this,"subscribeAddBatcher");m(this,"multiPC");m(this,"isLowPerfDevice",!1);if(this.localStreamManager=e,this.slsReporter=t,this.parameter=i,this.rts=this.createRtsInstance(),this.addRTSListener(),this.subscribeAddBatcher=new Bc(this.subscribeAddWithRetry.bind(this),((n=(s=this.parameter)==null?void 0:s.subscribe)==null?void 0:n.maxBatchCount)||3),((o=(c=this.parameter)==null?void 0:c.subscribe)==null?void 0:o.disableBatcher)===!0&&(this.subscribeAddBatcher.disabled=!0),(()=>{const l=(Ln.browserName||"").toLowerCase(),d=parseInt(Ln.browserVersion||"0",10);return l==="firefox"&&d>=148})()){T.info(`[${se.logName}]`,"Multi-PC mode enabled (Firefox 148+)"),this.subscribeAddBatcher.disabled=!0;const l=this,d={emit:(u,...p)=>l.emit(u,...p),suffixHttpUrl:l.suffixHttpUrl.bind(l),handleHTTPConfig:l.handleHTTPConfig.bind(l),getSubConfig:l.getSubConfig.bind(l),getPubMsid:l.getPubMsid.bind(l),reportSubscribeLatency:l.reportSubscribeLatency.bind(l),localStreamManager:l.localStreamManager,slsReporter:l.slsReporter,traceIdMap:l.traceIdMap,subUrlMap:l.subUrlMap,get pcTraceId(){return l._pcTraceId},set pcTraceId(u){l._pcTraceId=u},get localJoinTime(){return l._localJoinTime},get publishingTracks(){return l._publishingTracks},set publishingTracks(u){l._publishingTracks=u},get rtsPeerConnectionType(){return l._rtsPeerConnectionType},set rtsPeerConnectionType(u){l._rtsPeerConnectionType=u}};this.multiPC=new Oc(d)}}extractStreamId(e){try{const t=new URL(e.replace(/^artc:\/\//,"https://example.com")),i=t.pathname.split("/").filter(s=>s!=="");return i.length>0?i[i.length-1]:e}catch(t){return e}}subscribeAddWithRetry(e){return pr(t=>I(this,null,function*(){return this._dcReady||(yield this.dcConnectingPromise),t>0&&T.event(`[${se.logName}]`,`subscribeAdd retry times: ${t}`),this.isConnected?(t>=0&&e.forEach(i=>{var s,n;_e.getInstance().addEventData(_e.eventRetrySubAuto,this.extractStreamId(i.url),(s=i.subAudio)!=null?s:!1,(n=i.subVideo)!=null?n:!1,t)}),this.rts.subscribeAdd(e)):Promise.reject()}),10,100,t=>{var i,s,n,c;return(t==null?void 0:t.errorCode)===15006||(t==null?void 0:t.errorCode)===15004&&((c=(n=(s=(i=t.extraInfo)==null?void 0:i.parsedData)==null?void 0:s.streams)==null?void 0:n[0])==null?void 0:c.res_code)===404})}createRtsInstance(){var e,t;return J.AliRTS.createClient({singlePcConfig:{usePcReconnect:!0},datachannelDelayOpen:!1,signalDatachannelInitOptions:(t=(e=this.parameter)==null?void 0:e.net)!=null&&t.datachannelInitOptions?this.parameter.net.datachannelInitOptions:void 0})}addRTSListener(){this.rts.on("connectStatusChange",t=>{var i,s,n,c;if(T.event(`[${se.logName}]`,"rts connectStatusChange to:",t.status),t.status===J.EConnectStatus.CONNECT_STATUS_DISCONNECTED)this.dcReject&&this.dcReject(),this.setConnected(!1),this.rtsDisconnected=!0,this.slsReporter.reportWarning("rts disconnected"),this.emit("disconnected");else if(t.status===J.EConnectStatus.CONNECT_STATUS_CONNECTED){if(this.rtsDisconnected){const o=(c=(n=(s=(i=this.rts.commonController)==null?void 0:i.peerCore)==null?void 0:s.getSignal())==null?void 0:n.getDatachannelCore())==null?void 0:c.readyState;T.event(`[${se.logName}]`,"dcReadyState:",o),o==="open"&&this.dcResolve&&this.dcResolve(!0)}this.rtsDisconnected=!1,this.setConnected(!0)}}),this.rts.on("reconnect",t=>{var i,s,n;T.debug(`[${se.logName}]`,"reconnect",t),this.emit("reconnect",t.type,(i=t.extraInfo)==null?void 0:i.url,(n=(s=t.extraInfo)==null?void 0:s.msids)==null?void 0:n.map(c=>c.name))}),this.rts.on("reconnectFinish",t=>{var i;T.debug(`[${se.logName}]`,"reconnectFinish",t),this.emit("reconnectFinish",(t==null?void 0:t.type)||"pc",t==null?void 0:t.latestUrl,(i=t==null?void 0:t.msids)==null?void 0:i.map(s=>s.name));try{this.emit("connected",!0,this._rtsPeerConnectionType)}catch(s){T.error(`[${se.logName}]`,"emit connected error:",s)}this.logCandidateProtocol("reconnectFinish")}),this.rts.on("datachannelStatusChange",t=>{T.event(`[${se.logName}]`,"rts datachannelStatusChange to:",t.status),t.status===J.EDatachannelStatus.DATACHANNEL_STATUS_OPEN?(this._dcReady=!0,this.dcResolve&&this.dcResolve(!0)):t.status===J.EDatachannelStatus.DATACHANNEL_STATUS_CLOSE&&(this._dcReady=!1,this.dcReject&&this.dcReject(new Error("signal datachannel closed")),this.dcConnectingPromise=new Promise((i,s)=>{this.dcResolve=i,this.dcReject=s}))}),this.rts.on("receivedSEI",t=>{var i;if(this.emit("seimessage",t.url,t.sei.payloadType,t.sei.data),t.sei.payloadType===99)try{const s=JSON.parse(new TextDecoder().decode(t.sei.data));this.slsReporter.reportLoopAudioDelay(((i=this.publishingTracks.find(n=>n.type==="audio"))==null?void 0:i.ssrc)||"",s)}catch(s){}}),this.rts.on("onError",t=>{T.event(`[${se.logName}]`,"rts onError event:",t)}),this.rts.on("reconnect",t=>{T.event(`[${se.logName}]`,"rts reconnect event:",t)}),this.rts.on("traceId",({url:t,traceId:i})=>{t&&i&&this.traceIdMap[t]!==i&&(this.traceIdMap[t]=i,this.emit("traceIdUpdated",t,i))});const e={sophon_audio:"audio",sophon_video_camera_large:"vlarge",sophon_video_camera_small:"vsmall",sophon_video_screen_share:"screen",sophon_data:"data"};this.rts.on("signalSent",t=>{const i=t.streams||[],s=i.map((c,o)=>{let l=i.length>1?`[${o}]`:"";return l+=c.method||"",t.type==="sub"&&c.url&&(l+=` ${Object.keys(this.subUrlMap).find(d=>this.subUrlMap[d]===c.url.split("?")[0])||""}`),c.msid&&(l+=` ${c.msid.map(d=>e[d.name]||d.name).join("+")}`),l}),n=`${t.type} ${s.join(", ")}`;T.event(`[${se.logName}]`,"rts signalSent event:",n,t)}),this.rts.on("signalReceived",t=>{const i=t.streams||[],s=i.map((c,o)=>{let l=i.length>1?`[${o}]`:"";return l+=c.method||"",t.type==="sub"&&c.url&&(l+=` ${Object.keys(this.subUrlMap).find(d=>this.subUrlMap[d]===c.url.split("?")[0])||""}`),l+=` ${c.res_code||""}`,c.msid&&(l+=` ${c.msid.map(d=>e[d.name]||d.name).join("+")}`),l}),n=`${t.type} ${s.join(", ")}`;T.event(`[${se.logName}]`,"rts signalReceived event:",n,t)}),this.rts.on("hebtSent",t=>{var i,s,n;if((n=(s=(i=this.parameter)==null?void 0:i.net)==null?void 0:s.heartbeat)!=null&&n.enableLog){const c=Object.keys(this.subUrlMap).find(o=>{var l,d;return this.subUrlMap[o]===((d=(l=t.streams)==null?void 0:l[0])==null?void 0:d.url.split("?")[0])})||(t.streams?"pub":"empty");T.event(`[${se.logName}]`,"rts hebtSent event:",c,t)}}),this.rts.on("hebtReceived",t=>{var i,s,n,c,o,l,d;if((n=(s=(i=this.parameter)==null?void 0:i.net)==null?void 0:s.heartbeat)!=null&&n.enableLog){let u=`${Object.keys(this.subUrlMap).find(p=>{var h,f;return this.subUrlMap[p]===((f=(h=t.streams)==null?void 0:h[0])==null?void 0:f.url.split("?")[0])})||(t.streams?"pub":"empty")} ${((o=(c=t.streams)==null?void 0:c[0])==null?void 0:o.res_code)||""}`;(d=(l=t.streams)==null?void 0:l[0])!=null&&d.msid&&(u+=` ${t.streams[0].msid.map(p=>e[p.name]||p.name).join("+")}`),T.event(`[${se.logName}]`,"rts hebtReceived event:",u,t)}})}updateAuth(e){if(this.multiPC)return this.multiPC.updateAuth(e);this.rts.updateAuth(e)}get pcTraceId(){return this._pcTraceId}set localJoinTime(e){this._localJoinTime=e}setEncodedInsertableStreams(e){this.encodedInsertableStreams=e}updateDynamicConfig(e){var t;this.dycConf.updateConfigData(e),(t=this.rts)==null||t.updateDynamicConfig(e)}setChannelContext(e){var t;(t=this.rts)==null||t.setChannelContext(e)}setReceiverPreferredVideoCodecH265(){var s;let e=(s=RTCRtpReceiver.getCapabilities("video"))==null?void 0:s.codecs;if(!e||e.length===0)return;const t=e.filter(n=>n.mimeType.toLowerCase()!=="video/rtx");let i=t.findIndex(n=>n.mimeType==="video/H265");if(i+1){let n=t[i];t.splice(i,1),t.unshift(n),this.rts.setReceiverCodecPreferences({video:t})}}setSenderPreferredVideoCodecH265(){var s;let e=(s=RTCRtpSender.getCapabilities("video"))==null?void 0:s.codecs;if(!e||e.length===0)return;const t=e.filter(n=>n.mimeType.toLowerCase()!=="video/rtx");let i=t.findIndex(n=>n.mimeType==="video/H265");if(i+1){let n=t[i];t.splice(i,1),t.unshift(n),this.rts.setSenderCodecPreferences({video:t})}}supportVideoCodec(e){var t,i,s;return e===At.H265?(t=RTCRtpSender.getCapabilities("video"))==null?void 0:t.codecs.some(n=>n.mimeType==="video/H265"):e===At.H264?(i=RTCRtpSender.getCapabilities("video"))==null?void 0:i.codecs.some(n=>n.mimeType==="video/H264"):e===At.AV1&&((s=RTCRtpSender.getCapabilities("video"))==null?void 0:s.codecs.some(n=>n.mimeType==="video/AV1"))}changeVideoCodec(e){this.supportVideoCodec(e)?(T.info(`[${se.logName}]`,"changeVideoCodec to:",e),At.H265===e&&(this.setSenderPreferredVideoCodecH265(),this.setReceiverPreferredVideoCodecH265())):T.warn(`[${se.logName}]`,`not support video codec: ${e}`)}setAudioRedEnabled(e){var t;if(e!==this.audioRedEnabled){try{const i=[...((t=RTCRtpReceiver.getCapabilities("audio"))==null?void 0:t.codecs)||[]];if(i.length>0){if(e){const s=i.findIndex(c=>c.mimeType==="audio/red"),n=i.findIndex(c=>c.mimeType==="audio/opus");if(s>-1&&n>-1&&s>n){const c=i[n];i[n]=i[s],i[s]=c}}this.rts.setSenderCodecPreferences({audio:i}),this.rts.setReceiverCodecPreferences({audio:i})}}catch(i){}this.audioRedEnabled=e}}clear(){this.multiPC&&this.multiPC.clear(),this.setConnected(!1),this.rtsDisconnected=!1,this._dcReady=!1,this._publishingTracks=[],this._prevDownlinkStat=void 0,this.isLowPerfDevice=!1;try{this.rts.removeAllListeners(),this.rts.unpublish(),this.rts.unsubscribe(),this.rts.dispose()}catch(e){}this.rts=this.createRtsInstance(),this.addRTSListener(),this.subscribeAddBatcher.batchFunc=this.subscribeAddWithRetry.bind(this)}startConnect(){this.connecting=!0,this.connectingPromise=new Promise(e=>{this.connectionResolve=e}),this._dcReady=!1,this.dcConnectingPromise=new Promise((e,t)=>{this.dcResolve=e,this.dcReject=t})}setConnected(e){var t;this.connected=e,this.connecting=!1,(t=this.connectionResolve)==null||t.call(this,!0)}get isConnecting(){return this.multiPC?this.multiPC.isConnecting:this.connecting}get isConnected(){return this.multiPC?this.multiPC.isConnected:this.connected}suffixHttpUrl(e,t){const i=!t;let s=ls(e,i?this.preferredPubL1Ip:this.preferredSubL1Ip);const n={ip_migration:"on",exception_detection:"on"},c=new URL(s),o=c.searchParams;Object.keys(n).forEach(p=>{o.has(p)||o.set(p,n[p])});const l=c.toString(),d=e.split("?")[0];i?this.httpPublishUrlMap[d]=l:this.httpSubscribeUrlMap[d]=l;let u="";return t&&(t.vMsid?t.aMsid||(u="@subaudio=no"):u="@subvideo=no"),l+u}getSuffixedUrl(e,t){const i=e.split("?")[0];return t?this.httpPublishUrlMap[i]||e:this.httpSubscribeUrlMap[i]||e}get publishingTracks(){return this._publishingTracks}getPubMsid(e,t){const{aMsid:i,vMsid:s}=t!=null?t:{},n={};return e.hasAudio&&(n.aMsid=[i!=null?i:D.Audio]),e.hasScreen&&(n.vMsid=[D.Screen]),e.hasVideo&&(n.vMsid=[s!=null?s:t!=null&&t.isScreen?D.Screen:D.VideoLarge]),n}updatePublishingTracks(e){e&&(this._publishingTracks=e.map(({msid:t,from:i,ssrc:s,codec:n,type:c,trackId:o})=>({msid:t,from:i,type:c,ssrc:`${s}`,codec:n!=null?n:"",trackId:o})))}httpPublish(s){return I(this,arguments,function*(e,t=!1,i=Dt.MANUAL){let n;const c=Date.now(),o=e.url,l=e.callId;this.startConnect();const{publishStream:d,videoSmallStream:u,screenStream:p,vMsid:h}=yield this.localStreamManager.createHTTPPublishStream();if(!d)return T.warn(`[${se.logName}]`,"publishStream is null"),{traceId:"",l1ip:n};const f=this.getPubMsid(d,{vMsid:h});f.answerSdpHook=_=>{const y=/\d+\.\d+\.\d+\.\d+(?=\s+1106|\s+8000)/.exec(_);return y!=null&&y[0]&&(n=y[0]),_},this.handleHTTPConfig(f),this._rtsPeerConnectionType="publish";let g=!d.hasVideo,b=h,S="";const v=Date.now();try{S=yield this.publishWithPreferredL1Fallback(o,d,f)}catch(_){this.setConnected(!1);const y=2e3-(Date.now()-v);throw y<=0?this.emit("disconnected"):setTimeout(()=>{this.emit("disconnected")},y),this.slsReporter.reportPublish(t,o,l,d.hasVideo&&(!h||h===D.VideoLarge),d.hasVideo&&h===D.VideoSmall,d.hasVideo&&h===D.Screen,d.hasAudio,(_==null?void 0:_.errorCode)||-1,this.pcTraceId,"",v,v),U.fromRtsError(_)}S&&(this._pcTraceId=S),T.event(`[${se.logName}]`,"rts publish success",S);const R=Date.now();setTimeout(()=>{this.slsReporter.reportPublish(t,o,l,d.hasVideo&&(!h||h===D.VideoLarge),d.hasVideo&&h===D.VideoSmall,d.hasVideo&&h===D.Screen,d.hasAudio,0,this.pcTraceId,e.traceId,v,R)},6e3),this.slsReporter.reportConnectionLatencyEvent(Ze.HANDLE_PUB_TASK,st.START,l,S,c),this.slsReporter.reportConnectionLatencyEvent(Ze.HANDLE_PUB_TASK,st.END,l,S,Date.now());try{const _=Date.now();return this._pcTraceId=S,this.setConnected(!0),this._publishingTracks=this.rts.getPublishTrackInfoList(),u&&(yield this.publishAdd(e,u,{vMsid:D.VideoSmall},t),g=!1,b=D.VideoSmall),p&&(yield this.publishAdd(e,p,{vMsid:D.Screen},t),g=!1,b=D.Screen),yield this.waitPublishSender(o,g,b),this.slsReporter.reportPublishFirstPacket(t,l,v,_,this._localJoinTime,g?D.Audio:f.vMsid,S||"",S||"",i),{traceId:S,l1ip:n}}catch(_){throw this.setConnected(!1),U.fromError(_)}})}waitPublishSender(e,t=!1,i){return I(this,null,function*(){return this.multiPC?this.multiPC.waitPublishSender(e,t,i):Promise.race([Ht(1e3),((s,n)=>{let c=0;const o=()=>(t?this.rts.getPublishAudioStats(e,i):this.rts.getPublishVideoStats(e,i)).then(l=>!(l.bytesSent>0)&&c<s?(c++,new Promise(d=>setTimeout(()=>d(o()),n))):Promise.resolve());return o()})(5,100)]).catch(()=>{})})}getPublishVideoStats(e,t){return I(this,null,function*(){return this.multiPC?this.multiPC.getPublishVideoStats(e,t):yield this.rts.getPublishVideoStats(e,t)})}getPublishAudioStats(e,t){return I(this,null,function*(){return this.multiPC?this.multiPC.getPublishAudioStats(e,t):yield this.rts.getPublishAudioStats(e,t)})}publishAdd(o,l,d){return I(this,arguments,function*(e,t,i,s=!1,n=!1,c=Dt.MANUAL){var g,b,S,v;if(this.multiPC)return T.warn(`[${se.logName}]`,"publishAdd not supported in multi-PC mode"),"";const u=e.url,p=e.callId;this._dcReady||(yield this.dcConnectingPromise);const h=Date.now(),f=this.getPubMsid(t,i);try{const R=yield pr(_=>I(this,null,function*(){return _>0&&T.event(`[${se.logName}]`,`publishAdd retry times: ${_}`),this.isConnected?(this._dcReady||(yield this.dcConnectingPromise),this.rts.publishAdd([X({url:u,stream:t,updateSourceStream:!1},f)])):Promise.reject(new U(B.ERR_INNER,"rts not connected"))}),10,0,_=>(_==null?void 0:_.errorCode)===15006);if(R){const _=Date.now(),[y]=R,w=Date.now();return setTimeout(()=>{var A,E,C,P;this.slsReporter.reportPublish(!1,u,p,((A=f.vMsid)==null?void 0:A[0])===D.VideoLarge,((E=f.vMsid)==null?void 0:E[0])===D.VideoSmall,((C=f.vMsid)==null?void 0:C[0])===D.Screen,((P=f.aMsid)==null?void 0:P[0])===D.Audio,0,this.pcTraceId,y.traceId||"",h,w)},6e3),y.traceId&&(this._pcTraceId=y.traceId),this.updatePublishingTracks(y.trackInfoList),n&&(yield this.waitPublishSender(u,!t.hasVideo,t.hasVideo?i==null?void 0:i.vMsid:i==null?void 0:i.aMsid)),this.slsReporter.reportPublishFirstPacket(s,p,h,_,this._localJoinTime,(t.hasVideo?i==null?void 0:i.vMsid:i==null?void 0:i.aMsid)||"",this.pcTraceId,y.traceId||"",c),y.traceId||""}}catch(R){throw this.slsReporter.reportPublish(!1,u,p,((g=f.vMsid)==null?void 0:g[0])===D.VideoLarge,((b=f.vMsid)==null?void 0:b[0])===D.VideoSmall,((S=f.vMsid)==null?void 0:S[0])===D.Screen,((v=f.aMsid)==null?void 0:v[0])===D.Audio,(R==null?void 0:R.errorCode)||-1,this.pcTraceId,"",h),R!=null&&R.errorCode?U.fromRtsError(R):U.fromError(R)}return""})}publishDelete(e,t){return I(this,null,function*(){var l,d,u,p,h,f,g,b;if(this.multiPC)return T.warn(`[${se.logName}]`,"publishDelete not supported in multi-PC mode"),"";this._dcReady||(yield this.dcConnectingPromise);const i=(d=(l=this.publishingTracks)==null?void 0:l.find(({msid:S})=>S===D.Audio))==null?void 0:d.msid,s=(p=(u=this.publishingTracks)==null?void 0:u.find(({msid:S})=>S===D.VideoLarge))==null?void 0:p.msid,n=(f=(h=this.publishingTracks)==null?void 0:h.find(({msid:S})=>S===D.Screen))==null?void 0:f.msid,c=[];t.screen&&n?c.push(n):t.video&&c.push(t.vMsid||s);const o=[];t.audio&&i&&o.push(i),T.event(se.logName,"publishDelete",{streamUrl:e,aMsid:o,vMsid:c});try{const[S]=(yield this.rts.publishDeleteTracks([{url:e,aMsid:o,vMsid:c}]))||[];return T.event(se.logName,"publishDelete",{result:S}),S&&this.updatePublishingTracks(S.trackInfoList),((b=(g=S==null?void 0:S.trackInfoList)==null?void 0:g[0])==null?void 0:b.trackId)||""}catch(S){throw U.fromRtsError(S)}})}publishReplace(e,t,i){return I(this,null,function*(){var c,o;if(this.multiPC)return T.warn(`[${se.logName}]`,"publishReplace not supported in multi-PC mode"),"";this._dcReady||(yield this.dcConnectingPromise);const{vMsid:s,aMsid:n}=i!=null?i:{};try{const l=yield this.rts.publishReplaceTracks([{url:e,stream:t,vMsid:s,aMsid:n}]),[d]=l;return this.updatePublishingTracks(d.trackInfoList),((o=(c=d==null?void 0:d.trackInfoList)==null?void 0:c[0])==null?void 0:o.trackId)||""}catch(l){throw U.fromRtsError(l)}})}publishStop(e){return I(this,null,function*(){return this.multiPC?(yield this.multiPC.publishStop(e),""):(yield this.rts.publishStop([{url:e}]),this._publishingTracks=[],"")})}publishAddDataChannel(e){return I(this,null,function*(){if(this.multiPC)return T.warn(`[${se.logName}]`,"publishAddDataChannel not supported in multi-PC mode"),null;this._dcReady||(yield this.dcConnectingPromise);const t=yield this.rts.publishAddDatachannel({signalUrl:e,url:this.getSuffixedUrl(e,!0),label:D.Data,msid:D.Data}),i=t==null?void 0:t.datachannel;if(i&&i.send){const s=new ArrayBuffer(4);new DataView(s).setUint8(0,240),i.datachannel.send(s)}return i})}publishStopDataChannel(e,t){return I(this,null,function*(){return this.multiPC?void T.warn(`[${se.logName}]`,"publishStopDataChannel not supported in multi-PC mode"):yield this.rts.publishStopDatachannel({url:e,datachannel:t})})}unpublish(){return I(this,null,function*(){if(this.multiPC)return yield this.multiPC.unpublish(),void(this._publishingTracks=[]);yield this.rts.unpublish(),this._publishingTracks=[],this.connecting=!1,this.connected=!1})}getMultiPCNetworkQuality(){return I(this,null,function*(){return this.multiPC?this.multiPC.getNetworkQuality():{rtt:0,loss:0,quality:tt.AliRtcNetworkDisconnected}})}getSubscribeNetworkQuality(){return I(this,null,function*(){var h;if(this.multiPC)return this.getMultiPCNetworkQuality();const e=(h=this.rts.commonController.peerCore)==null?void 0:h.pc;if(!e||e.connectionState==="disconnected"||e.connectionState==="failed"||e.connectionState==="closed")return{rtt:0,loss:0,quality:tt.AliRtcNetworkDisconnected};let t=0,i=0,s=0;const n=e.getReceivers();for(const f of n)(yield f.getStats()).forEach(g=>{g.type==="candidate-pair"&&typeof g.currentRoundTripTime=="number"&&(t=Math.round(1e3*g.currentRoundTripTime)),g.type!=="inbound-rtp"||g.mediaType!=="audio"&&g.mediaType!=="video"||(i+=g.packetsLost||0,s+=g.packetsReceived||0)});if(!this._prevDownlinkStat)return this._prevDownlinkStat={totalPacketsLost:i,totalPacketsReceived:s},{rtt:t,loss:0,quality:tt.AliRtcNetworkUnknown};const{totalPacketsLost:c,totalPacketsReceived:o}=this._prevDownlinkStat,l=i-c,d=s-o;let u=0;l>0&&d>=0&&(u=Math.round(l/(l+d)*100));const p=ds(u,t);return this._prevDownlinkStat={totalPacketsLost:i,totalPacketsReceived:s},{rtt:t,loss:u,quality:p}})}getSubConfig(e,t){let i=t!=null?t:{};t||(i={audio:!0,video:!0,screen:!0});const s={};return i.audio&&(s.aMsid=[(e==null?void 0:e.getAudioInfo().msid)||D.Audio]),i.video?i.vMsid?s.vMsid=[i.vMsid]:s.vMsid=e!=null&&e.hasVideoLarge?[(e==null?void 0:e.getVideoLargeInfo().msid)||D.VideoLarge]:e!=null&&e.hasVideoSmall?[(e==null?void 0:e.getVideoSmallInfo().msid)||D.VideoSmall]:[D.VideoLarge]:i.screen&&(s.vMsid=[(e==null?void 0:e.getScreenInfo().msid)||D.Screen]),s}handleHTTPConfig(e){var i,s,n,c,o,l,d,u,p,h,f,g;if(this.encodedInsertableStreams&&(e.encodedInsertableStreams=!0),(s=(i=this.parameter)==null?void 0:i.net)!=null&&s.useTCP&&(e.tcpOnly=!0),(c=(n=this.parameter)==null?void 0:n.net)!=null&&c.cumuDelay&&(e.cumuDelay=!0),(l=(o=this.parameter)==null?void 0:o.net)!=null&&l.disableHeartbeat&&(e.disableHeartbeat=!0),(u=(d=this.parameter)==null?void 0:d.net)!=null&&u.heartbeat&&(e.heartbeat=this.parameter.net.heartbeat),(h=(p=this.parameter)==null?void 0:p.net)==null?void 0:h.mediaTimeout){const b=(g=(f=this.parameter)==null?void 0:f.net)==null?void 0:g.mediaTimeout;b>1e3&&b<1e5&&(e.mediaTimeout=b)}e.offerSdpHook=lo;let t=0;e.beforeRetry=b=>I(this,null,function*(){if(t++,T.info(`[${se.logName}]`,`before retry, retryCount: ${t}`),t>=2&&b.url.includes("ali_prefer_media_server"))try{const S=new URL(b.url);S.searchParams.delete("ali_prefer_media_server"),b.url=S.toString(),T.info(`[${se.logName}]`,`removed ali_prefer_media_server, fallback url: ${b.url}`)}catch(S){T.error(`[${se.logName}]`,"failed to parse url for removing ali_prefer_media_server",b.url,S)}return b}),e.retryTimes=17,e.retryInterval=5e3,T.info(`[${se.logName}]`,"http config",e)}httpSubscribe(e){return I(this,null,function*(){const{remoteUser:t,options:i}=e,s=t.streamUrl,n=this.getSubConfig(t.streamInfo,i);this.handleHTTPConfig(n),this._rtsPeerConnectionType="subscribe";try{this.startConnect();const c=yield this.subscribeWithPreferredL1Fallback(s,n);return this._pcTraceId=c.traceId,this.setConnected(!0),{traceId:c.traceId,stream:c}}catch(c){throw this.setConnected(!1),this.emit("disconnected"),U.fromRtsError(c)}})}subscribeWithPreferredL1Fallback(e,t){return I(this,null,function*(){if(this.preferredSubL1Ip){const s=this.suffixHttpUrl(e,t),n=new Promise((c,o)=>{setTimeout(()=>o(new Error("PREFERRED_L1_TIMEOUT")),3e3)});try{const c=yield Promise.race([this.rts.subscribe(s,t),n]);return this.logCandidateProtocol("subscribe (preferred L1)"),c}catch(c){if(c.message==="PREFERRED_L1_TIMEOUT"){T.warn(`[${se.logName}]`,"Preferred L1 subscribe timeout, clearing preferredSubL1Ip and falling back to DNS"),this.preferredSubL1Ip=void 0;const o=yield this.rts.subscribe(this.suffixHttpUrl(e,t),t);return this.logCandidateProtocol("subscribe (fallback)"),o}throw c}}const i=yield this.rts.subscribe(this.suffixHttpUrl(e,t),t);return this.logCandidateProtocol("subscribe"),i})}publishWithPreferredL1Fallback(e,t,i){return I(this,null,function*(){if(this.preferredPubL1Ip){const n=this.suffixHttpUrl(e),c=new Promise((o,l)=>{setTimeout(()=>l(new Error("PREFERRED_L1_TIMEOUT")),3e3)});try{const o=yield Promise.race([this.rts.publish(n,t,i),c]);return this.logCandidateProtocol("publish (preferred L1)"),o}catch(o){if(o.message==="PREFERRED_L1_TIMEOUT"){T.warn(`[${se.logName}]`,"Preferred L1 publish timeout, clearing preferredPubL1Ip and falling back to DNS"),this.preferredPubL1Ip=void 0;const l=yield this.rts.publish(this.suffixHttpUrl(e),t,i);return this.logCandidateProtocol("publish (fallback)"),l}throw o}}const s=yield this.rts.publish(this.suffixHttpUrl(e),t,i);return this.logCandidateProtocol("publish"),s})}subscribeAdd(e){return I(this,null,function*(){var n,c,o,l,d;const{remoteUser:t,options:i}=e,s=vt(X({url:t.streamUrl,subAudio:!!i.audio,subVideo:!(!i.screen&&!i.video)},this.getSubConfig(t.streamInfo,i)),{targetStream:i.screen?t.getScreenStream:t.getCameraStream});this._dcReady||(yield this.dcConnectingPromise);try{return!this.subscribeAddBatcher.disabled&&!((n=this.dycConf.getDycConf("h5_disable_sub_batcher"))==null||n)?yield this.subscribeAddBatcher.add(s):(yield this.subscribeAddWithRetry([s]))[0]}catch(u){if((u==null?void 0:u.errorCode)===15011)return T.info(`[${se.logName}]`,"subscribeAdd ignored",u==null?void 0:u.message),null;if(((d=(l=(o=(c=u==null?void 0:u.extraInfo)==null?void 0:c.parsedData)==null?void 0:o.streams)==null?void 0:l[0])==null?void 0:d.res_code)===508)return this.emit("subscribeexceeds"),null;throw U.fromRtsError(u)}})}subscribeDelete(e){return I(this,null,function*(){var n,c,o,l,d;if(this.multiPC)return this.multiPC.subscribeDelete(e);this.subscribeAddBatcher.disabled||((n=this.dycConf.getDycConf("h5_disable_sub_batcher"))==null||n)||(yield this.subscribeAddBatcher.waitForPending());const{remoteUser:t,options:i}=e,s=vt(X({url:t.streamUrl,subAudio:!!i.audio,subVideo:!(!i.screen&&!i.video)},this.getSubConfig(t.streamInfo,i)),{targetStream:i.screen?t.getScreenStream:t.getCameraStream});this._dcReady||(yield this.dcConnectingPromise);try{return T.event(`[${se.logName}]`,"subscribeDeleteTracks",JSON.stringify({url:s.url,subAudio:s.subAudio,subVideo:s.subVideo,aMsid:s.aMsid,vMsid:s.vMsid})),(yield this.rts.subscribeDeleteTracks([s]))[0]}catch(u){if((u==null?void 0:u.errorCode)===15011)return T.info(`[${se.logName}]`,"subscribeDelete ignored",u==null?void 0:u.message),null;if(((d=(l=(o=(c=u==null?void 0:u.extraInfo)==null?void 0:c.parsedData)==null?void 0:o.streams)==null?void 0:l[0])==null?void 0:d.res_code)===404)return null;throw U.fromRtsError(u)}})}updateSubscribeBatcher(e){e.disableBatcher!==void 0&&(this.subscribeAddBatcher.disabled=e.disableBatcher),e.maxBatchCount!==void 0&&(this.subscribeAddBatcher.maxCount=e.maxBatchCount)}subscribeAddDataChannel(e){return I(this,null,function*(){var s;if(this.multiPC)return T.warn(`[${se.logName}]`,"subscribeAddDataChannel not supported in multi-PC mode"),null;this.subscribeAddBatcher.disabled||((s=this.dycConf.getDycConf("h5_disable_sub_batcher"))==null||s)||(yield this.subscribeAddBatcher.waitForPending()),this._dcReady||(yield this.dcConnectingPromise);const t=yield this.rts.subscribeAddDatachannel({signalUrl:e,url:this.getSuffixedUrl(e,!1),label:D.Data,msid:D.Data}),i=t==null?void 0:t.datachannel;if(i&&i.send){const n=new ArrayBuffer(4);new DataView(n).setUint8(0,240),i.send(n)}return i})}subscribeDeleteDatachannel(e,t){return I(this,null,function*(){var s;if(this.multiPC)return void T.warn(`[${se.logName}]`,"subscribeDeleteDatachannel not supported in multi-PC mode");let i;this.subscribeAddBatcher.disabled||((s=this.dycConf.getDycConf("h5_disable_sub_batcher"))==null||s)||(yield this.subscribeAddBatcher.waitForPending());try{i=yield this.rts.subscribeDeleteDatachannel({url:e,msid:D.Data,datachannel:t})}catch(n){}return i})}publish(s){return I(this,arguments,function*(e,t=!1,i=Dt.MANUAL){if(this.multiPC)return this.multiPC.publish(e,t,i);const n=e.url;let c,o="";if(this.connecting&&(yield this.connectingPromise),this.connected){this._dcReady||(yield this.dcConnectingPromise);let l,d=!1;const{audio:u,video:p,videoSmall:h,screen:f}=this.localStreamManager.publishStreams;u&&(o=yield this.publishAdd(e,u,{aMsid:D.Audio},t),d=!0,l=D.Audio,yield Ht(100)),p&&(o=yield this.publishAdd(e,p,{vMsid:D.VideoLarge},t),d=!1,l=D.VideoLarge,yield Ht(100)),h&&(o=yield this.publishAdd(e,h,{vMsid:D.VideoSmall},t),d=!1,l=D.VideoSmall,yield Ht(100)),f&&(o=yield this.publishAdd(e,f,{isScreen:!0,vMsid:D.Screen},t),d=!1,l=D.Screen),l&&(yield this.waitPublishSender(n,d,l))}else{const l=yield this.httpPublish(e,t,i);o=l.traceId,c=l.l1ip}return{traceId:o,l1ip:c}})}reportSubscribeLatency(e,t,i,s){const n=[];e.audio&&n.push(e.aMsid||D.Audio),e.video?n.push(e.vMsid||D.VideoLarge):e.screen&&n.push(D.Screen),n.forEach(c=>{this.slsReporter.reportConnectionLatencyEvent(Ze.HANDLE_SUB_TASK,st.START,t,c,i,0,s),this.slsReporter.reportConnectionLatencyEvent(Ze.HANDLE_SUB_TASK,st.END,t,c,Date.now(),0,s)})}subscribe(e,t,i,s,n){return I(this,null,function*(){if(this.multiPC)return this.multiPC.subscribe(e,t,i,s,n);let c=!1;const{options:o,remoteUser:l}=e;if(o.video&&o.screen)throw new U(B.ERR_INNER,"subscribe error, video and screen cannot be subscribed at the same time");let d;this.connecting&&(yield this.connectingPromise),this.subUrlMap[l.userId]=l.streamUrl.split("?")[0];let u=Date.now();if(this.connected?d=yield this.subscribeAdd(e):(c=!0,d=yield this.httpSubscribe(e)),!d)return null;this.reportSubscribeLatency(o,i,u,c);const p=Date.now();let h=D.VideoLarge,f=o.video||o.screen,g=o.audio;o.video&&o.vMsid?h=o.vMsid:o.screen&&(h=D.Screen);let b=0,S=0,v=0;const R=((_,y)=>{let w=0;const A=()=>{let E;return g&&!b&&(E=this.rts.getSubscribeAudioStats(l.streamUrl).then(C=>{if(C.packetsReceived>0)b=Date.now(),T.debug(`[${se.logName}]`,l.userId,"Stats 音频首包");else if(!f)return w<_&&(w++,new Promise(P=>setTimeout(()=>P(A()),y)));return!0})),f&&!v&&(E=this.rts.getSubscribeVideoStats(l.streamUrl,h).then(C=>{if(typeof C.packetsReceived=="number")return!S&&C.packetsReceived>0&&(S=Date.now(),T.debug(`[${se.logName}]`,l.userId,"Stats 视频首包")),C.framesDecoded>0?(v=Date.now(),T.debug(`[${se.logName}]`,l.userId,"Stats 视频首帧数据"),!0):w<_?(w++,new Promise(P=>setTimeout(()=>P(A()),y))):(T.event(`[${se.logName}]`,l.userId,"尝试获取首帧数据失败"),!1)})),Promise.resolve(E)};return A()})(20,100);return R.then(()=>{S&&this.slsReporter.reportSubscribeFirstPacket(t===ge.Resume,i,s,h,{fprt:S-u,ifsprtc:v?v-u:0,ajsub:t===ge.Join?1:0,pctid:this.pcTraceId,subtid:(d==null?void 0:d.traceId)||"",sstc:p-u}),v&&this.slsReporter.reportSubscribeFirstFrame(t===ge.Resume,i,s,h,{fvfrt:v-u,fp2fftc:v-S,ajsub:t===ge.Join?1:0,tffrtc:t===ge.Join?v-this.localJoinTime:v-n,pctid:this.pcTraceId,subtid:(d==null?void 0:d.traceId)||"",fvfdtc:v-u}),b&&(this.slsReporter.reportConnectionLatencyEvent(Ze.FIRST_REMOTE,st.DECODED,i,D.Audio,b),this.slsReporter.reportSubscribeFirstPacket(t===ge.Resume,i,s,D.Audio,{fprt:b-u,ifsprtc:b-u,ajsub:t===ge.Join?1:0,pctid:this.pcTraceId,subtid:(d==null?void 0:d.traceId)||"",sstc:p-u}))}),d&&(d.isHTTP=c,d.statsCheckPromise=R),d})}getSubscribeVideoStats(e,t){return I(this,null,function*(){return this.multiPC?this.multiPC.getSubscribeVideoStats(e,t):yield this.rts.getSubscribeVideoStats(e,t)})}getSubscribeAudioStats(e,t){return I(this,null,function*(){return this.multiPC?this.multiPC.getSubscribeAudioStats(e,t):yield this.rts.getSubscribeAudioStats(e,t)})}getStreamByMsid(e){if(this.multiPC){const t=this.multiPC.getStreamByMsid(e);if(t)return t}return this.rts.commonController.streamManager.getStreamByMsid(e)}getDatachannelByMsid(e){var t;return this.multiPC?(T.warn(`[${se.logName}]`,"getDatachannelByMsid not supported in multi-PC mode"),null):(t=this.rts.commonController.datachannelManager)==null?void 0:t.getByMsid(e)}getPCStats(){return I(this,null,function*(){var e,t;return this.multiPC?this.multiPC.getPCStats():(t=(e=this.rts.commonController.peerCore)==null?void 0:e.pc)==null?void 0:t.getStats()})}logCandidateProtocol(e){return I(this,null,function*(){var t,i;try{const s=(i=(t=this.rts.commonController)==null?void 0:t.peerCore)==null?void 0:i.pc;if(!s)return void T.debug(`[${se.logName}]`,`${e} - PC not available`);const n=yield s.getStats();let c,o,l,d;n.forEach(u=>{u.type==="candidate-pair"&&u.state==="succeeded"&&u.nominated&&(c=u.localCandidateId,o=u.remoteCandidateId)}),c||o||n.forEach(u=>{u.type!=="candidate-pair"||u.state!=="succeeded"&&u.state!=="in-progress"||c||(c=u.localCandidateId,o=u.remoteCandidateId)}),n.forEach(u=>{u.type==="local-candidate"&&u.id===c&&(l=u.protocol),u.type==="remote-candidate"&&u.id===o&&(d=u.protocol)}),T.event(`[${se.logName}]`,`${e} - Candidate Protocol: local=${l||"unknown"}, remote=${d||"unknown"}`)}catch(s){T.warn(`[${se.logName}]`,`${e} - Failed to get candidate protocol:`,s)}})}getGatewayIp(){return I(this,null,function*(){var e,t;try{const i=(t=(e=this.rts.commonController)==null?void 0:e.peerCore)==null?void 0:t.pc;if(!i)return"";const s=yield i.getStats();let n;if(s.forEach(o=>{o.type==="candidate-pair"&&o.state==="succeeded"&&o.nominated&&(n=o.remoteCandidateId)}),n||s.forEach(o=>{o.type!=="candidate-pair"||o.state!=="succeeded"&&o.state!=="in-progress"||n||(n=o.remoteCandidateId)}),!n)return"";let c="";return s.forEach(o=>{o.type==="remote-candidate"&&o.id===n&&(c=o.ip||o.address||"")}),T.info(`[${se.logName}]`,`<<<<< getGatewayIp: ${c}`),c}catch(i){return""}})}sendSEI(e,t,i,s){return I(this,null,function*(){return this.multiPC?this.multiPC.sendSEI(e,t,i,s):this.rts.sendSEI({url:e,vMsid:D.VideoLarge,data:t,repeatCount:i,payloadType:s})})}},m(se,"logName","RtsManager"),se);Je([k(H)],ze.prototype,"startConnect",1),Je([k()],ze.prototype,"updatePublishingTracks",1),Je([k(H,H)],ze.prototype,"httpPublish",1),Je([k(H,H)],ze.prototype,"waitPublishSender",1),Je([k(([a,r,e])=>[a,JSON.stringify(e)],H)],ze.prototype,"publishAdd",1),Je([k(H,H)],ze.prototype,"publishDelete",1),Je([k(([a,r,e])=>[a,JSON.stringify(e)])],ze.prototype,"publishReplace",1),Je([k(H)],ze.prototype,"publishStop",1),Je([k(H)],ze.prototype,"publishAddDataChannel",1),Je([k(H)],ze.prototype,"publishStopDataChannel",1),Je([k()],ze.prototype,"unpublish",1),Je([k(Xi,({traceId:a})=>a)],ze.prototype,"httpSubscribe",1),Je([k(Xi,({traceId:a})=>a)],ze.prototype,"subscribeAdd",1),Je([k(Xi)],ze.prototype,"subscribeDelete",1),Je([k(H)],ze.prototype,"subscribeAddDataChannel",1),Je([k(H)],ze.prototype,"subscribeDeleteDatachannel",1),Je([k(H)],ze.prototype,"publish",1),Je([k(Xi)],ze.prototype,"subscribe",1),Je([k()],ze.prototype,"sendSEI",1);let Hc=ze;class Ws{constructor(r=Hs){m(this,"defaultProfile");m(this,"profile");m(this,"profileMap",new Map);m(this,"audioProfile");m(this,"contentHint");this.defaultProfile=X({},r)}updateProfile(r,e){this.profileMap.set(r,X(X(X({},this.defaultProfile),this.profileMap.get(r)||{}),e||{})),this.profile=r}get videoProfile(){return this.profile}updateAudioProfile(r){this.audioProfile=r}setContentHint(r,e){e&&(this.contentHint=e),this.contentHint&&r&&(r.contentHint=this.contentHint)}setVideoProfile(r,e,t=!1){return I(this,null,function*(){if(!this.profile)return;const i=this.profileMap.get(this.profile)||(e==null?void 0:e.VideoProfileMap.get(this.profile));if(i){if(!t&&r&&r.readyState==="live"&&r.applyConstraints)try{yield r.applyConstraints(i)}catch(s){}if(e){const s=X({},i);i.maxSendFrameRate&&(s.frameRate=i.maxSendFrameRate),e==null||e.VideoProfileMap.set(this.profile,s),yield e.setVideoProfile(this.profile)}}})}}const $t=class $t{static acquire(r){if(!r||!r.id)return;const e=$t.refCounts.get(r.id);e?e.count++:$t.refCounts.set(r.id,{track:r,count:1})}static release(r){if(!r||!r.id)return!1;const e=$t.refCounts.get(r.id);return e?(e.count--,e.count<=0&&($t.refCounts.delete(r.id),r.stop(),!0)):(r.stop(),!0)}static getRefCount(r){var e,t;return r&&r.id&&(t=(e=$t.refCounts.get(r.id))==null?void 0:e.count)!=null?t:0}static reset(){$t.refCounts.clear()}};m($t,"refCounts",new Map);let Gt=$t;var He=(a=>(a[a.AliRtcSdkStreamTypeCapture=0]="AliRtcSdkStreamTypeCapture",a[a.AliRtcSdkStreamTypeScreen=1]="AliRtcSdkStreamTypeScreen",a))(He||{});class zs extends oe{constructor(e){super();m(this,"type");m(this,"originVideoTrack");m(this,"videoSource");m(this,"_videoMuted",!1);m(this,"originAudioTrack");m(this,"audioSource");m(this,"_audioMuted",!1);m(this,"_targetVideoTrack");m(this,"_targetDualVideoTrack");m(this,"_targetAudioTrack");m(this,"_publishVideoStream");m(this,"_publishDualVideoStream");m(this,"_publishAudioStream");m(this,"_previewStream");m(this,"plugins",[]);m(this,"_profileManager");m(this,"cameraVideoConstraints");m(this,"micAudioConstraints");m(this,"onVideoTrackEnded",()=>{this.emit("videotrackended")});m(this,"onAudioTrackEnded",()=>{this.emit("audiotrackended")});this.type=e}get profileManager(){return this._profileManager}get audioProfile(){var e;return(e=this.profileManager)==null?void 0:e.audioProfile}updateSource(e,t,i){return I(this,null,function*(){var c,o,l,d;const{videoTrack:s,audioTrack:n}=e;s&&((c=this.originVideoTrack)==null||c.removeEventListener("ended",this.onVideoTrackEnded)),n&&((o=this.originAudioTrack)==null||o.removeEventListener("ended",this.onAudioTrackEnded)),this.type===He.AliRtcSdkStreamTypeScreen?this.stop():(s&&this.originVideoTrack&&Gt.release(this.originVideoTrack),n&&this.originAudioTrack&&Gt.release(this.originAudioTrack)),s&&(this.originVideoTrack=s,Gt.acquire(s),(l=this.originVideoTrack)==null||l.addEventListener("ended",this.onVideoTrackEnded),this.videoSource=t||wi.Camera,this.updateVideoTrack(s)),n&&(this.originAudioTrack=n,Gt.acquire(n),(d=this.originAudioTrack)==null||d.addEventListener("ended",this.onAudioTrackEnded),this.audioSource=i||Hi.Microphone,this.updateAudioTrack(n))})}get currentProfile(){var e;return(e=this.profileManager)==null?void 0:e.profile}get currentVideoTrack(){return this._targetVideoTrack}get currentDualVideoTrack(){return this._targetDualVideoTrack}get publishVideoStream(){return this._publishVideoStream}get publishDualVideoStream(){return this._publishDualVideoStream}get currentAudioTrack(){return this._targetAudioTrack}get publishAudioStream(){return this._publishAudioStream}get previewStream(){return this._previewStream}updateVideoTrack(e,t=!1){return I(this,null,function*(){(this._targetVideoTrack!==e||t)&&(this._targetVideoTrack=e)})}updateDualVideoTrack(e,t=!1){return I(this,null,function*(){(this._targetDualVideoTrack!==e||t)&&(this._targetDualVideoTrack=e)})}updateAudioTrack(e,t=!1){return I(this,null,function*(){(this._targetAudioTrack!==e||t)&&(this._targetAudioTrack=e)})}setAudioMuted(e){var t,i;this._audioMuted=e,e?(t=this.publishAudioStream)==null||t.disableAudio():(i=this.publishAudioStream)==null||i.enableAudio()}get isAudioMuted(){return this._audioMuted}setVideoMuted(e){var t,i;this._videoMuted=e,e?(t=this.publishVideoStream)==null||t.disableVideo():(i=this.publishVideoStream)==null||i.enableVideo()}get isVideoMuted(){return this._videoMuted}process(e){return I(this,null,function*(){var t,i,s,n,c,o,l,d,u,p,h,f;this._targetAudioTrack=this.originAudioTrack,this._targetVideoTrack=this.originVideoTrack;for(const g of this.plugins)try{yield g.execute(this,e)}catch(b){console.error(`error in plugin-${g.name}, error: ${b}`)}this._targetVideoTrack?((i=(t=this._publishVideoStream)==null?void 0:t.videoTrack)==null?void 0:i.id)!==this._targetVideoTrack.id&&(this._publishVideoStream=yield ki(this._targetVideoTrack),this.setVideoMuted(this._videoMuted),(s=this.profileManager)==null||s.setVideoProfile(this.originVideoTrack,this._publishVideoStream,!0),(n=this.profileManager)==null||n.setContentHint(this._targetVideoTrack),this.previewStream?(c=this.previewStream)==null||c.mergeStream(this._publishVideoStream):this._previewStream=yield ki(this._targetVideoTrack)):(this._publishVideoStream=void 0,(o=this.previewStream)==null||o.deleteTracks({video:!0})),this._targetDualVideoTrack?((d=(l=this._publishDualVideoStream)==null?void 0:l.videoTrack)==null?void 0:d.id)!==this._targetDualVideoTrack.id&&(this._publishDualVideoStream=yield ki(this._targetDualVideoTrack),this._videoMuted?this._publishDualVideoStream.disableVideo():this._publishDualVideoStream.enableVideo()):this._publishDualVideoStream=void 0,this._targetAudioTrack?((p=(u=this._publishAudioStream)==null?void 0:u.audioTrack)==null?void 0:p.id)!==this._targetAudioTrack.id&&(this._publishAudioStream=yield ki(this._targetAudioTrack),this.audioProfile&&(yield this._publishAudioStream.setAudioProfile(this.audioProfile)),this.setAudioMuted(this._audioMuted),this.previewStream?(h=this.previewStream)==null||h.mergeStream(this._publishAudioStream):this._previewStream=yield ki(this._targetAudioTrack)):(this._publishAudioStream=void 0,(f=this.previewStream)==null||f.deleteTracks({audio:!0}))})}stopVideo(){this.originVideoTrack&&(this.originVideoTrack.removeEventListener("ended",this.onVideoTrackEnded),Gt.release(this.originVideoTrack),this.originVideoTrack=void 0),this.updateVideoTrack(void 0)}stopAudio(){this.originAudioTrack&&(this.originAudioTrack.removeEventListener("ended",this.onAudioTrackEnded),Gt.release(this.originAudioTrack),this.originAudioTrack=void 0),this.updateAudioTrack(void 0)}stop(){this.stopVideo(),this.stopAudio()}updateVideoProfile(e,t,i=!1){return I(this,null,function*(){this._profileManager||(this._profileManager=new Ws(this.type===He.AliRtcSdkStreamTypeScreen?Tn:Hs)),e&&this._profileManager.updateProfile(e,t),yield this._profileManager.setVideoProfile(this.originVideoTrack,this._publishVideoStream,i)})}get videoProfile(){var e;return(e=this.profileManager)==null?void 0:e.videoProfile}setVideoContentHint(e){this._profileManager||(this._profileManager=new Ws(this.type===He.AliRtcSdkStreamTypeScreen?Tn:Hs)),this._profileManager.setContentHint(this.currentVideoTrack,e)}updateAudioProfile(e){return I(this,null,function*(){this._profileManager||(this._profileManager=new Ws),this._profileManager.updateAudioProfile(e)})}cloneVideoProfile(e){return I(this,null,function*(){var t;yield(t=this.profileManager)==null?void 0:t.setVideoProfile(void 0,e)})}cloneAudioProfile(e){return I(this,null,function*(){this.audioProfile&&(yield e.setAudioProfile(this.audioProfile))})}addPlugin(e){const t=this.plugins.findIndex(i=>i.zIndex>e.zIndex);t>-1?this.plugins.splice(t,0,e):this.plugins.push(e)}removePlugin(e){const t=this.plugins.indexOf(e);return t>-1&&(e.clear(this),this.plugins.splice(t,1),!0)}}var Fc=Object.defineProperty,jc=Object.getOwnPropertyDescriptor,Et=(a,r,e,t)=>{for(var i,s=t>1?void 0:t?jc(r,e):r,n=a.length-1;n>=0;n--)(i=a[n])&&(s=(t?i(r,e,s):i(s))||s);return t&&s&&Fc(r,e,s),s};const wt=(Yt=class extends oe{constructor(e,t){super();m(this,"pluginManager");m(this,"slsReporter");m(this,"publishingCameraVideoStream");m(this,"publishingScreenVideoStream");m(this,"cameraStreamInfo",new zs(He.AliRtcSdkStreamTypeCapture));m(this,"screenStreamInfo",new zs(He.AliRtcSdkStreamTypeScreen));m(this,"streamInfos",[this.cameraStreamInfo,this.screenStreamInfo]);m(this,"_audioCaptureDisabled",!1);m(this,"_cameraCaptureDisabled",!1);m(this,"_publishLocalAudioStreamEnabled",!0);m(this,"_publishLocalVideoStreamEnabled",!0);m(this,"_publishLocalScreenStreamEnabled",!0);this.screenStreamInfo.setVideoContentHint("motion"),this.pluginManager=e,this.slsReporter=t,this.cameraStreamInfo.on("videotrackended",()=>I(this,null,function*(){yield this.stopLocalStream({video:!0}),this.emit("trackended",oi.VideoTrackEnded)})),this.cameraStreamInfo.on("audiotrackended",()=>I(this,null,function*(){yield this.stopLocalStream({audio:!0}),this.emit("trackended",oi.AudioTrackEnded)})),this.screenStreamInfo.on("videotrackended",()=>I(this,null,function*(){yield this.stopLocalStream({screen:!0}),this.emit("trackended",oi.ScreenTrackEnded)})),this.pluginManager.on("added",i=>I(this,null,function*(){if(T.info(`[${Yt.logName}]`,"plugin added",i.name),!i.isSupported("7.2.10"))return console.warn(`${i.name} is not supported!!!`),void i.emit("unsupported");try{yield i.init()}catch(s){i.emit("error",U.fromError(s,qt.AliRtcPluginErrorInitError))}i.streamType===He.AliRtcSdkStreamTypeCapture&&(this.cameraStreamInfo.addPlugin(i),yield this.cameraStreamInfo.process(this.streamInfos)),i.streamType===He.AliRtcSdkStreamTypeScreen&&(this.screenStreamInfo.addPlugin(i),yield this.screenStreamInfo.process(this.streamInfos)),this.emit("publishupdate")})),this.pluginManager.on("removed",i=>I(this,null,function*(){this.cameraStreamInfo.removePlugin(i)&&(yield this.cameraStreamInfo.process(this.streamInfos)),this.screenStreamInfo.removePlugin(i)&&(yield this.screenStreamInfo.process(this.streamInfos)),this.emit("publishupdate")})),this.pluginManager.on("updated",()=>I(this,null,function*(){yield this.updateStreams()}))}get hasCamera(){return!!this.cameraStreamInfo.originVideoTrack}get audioCaptureDisabled(){return this._audioCaptureDisabled}set audioCaptureDisabled(e){this._audioCaptureDisabled=e}get cameraCaptureDisabled(){return this._cameraCaptureDisabled}set cameraCaptureDisabled(e){this._cameraCaptureDisabled=e}setAudioMuted(e){this.cameraStreamInfo.setAudioMuted(e)}get isAudioMuted(){return this.cameraStreamInfo.isAudioMuted}setCameraMuted(e){this.cameraStreamInfo.setVideoMuted(e)}get isCameraMuted(){return this.cameraStreamInfo.isVideoMuted}setScreenMuted(e){this.screenStreamInfo.setVideoMuted(e)}get isScreenMuted(){return this.screenStreamInfo.isVideoMuted}get publishLocalAudioStreamEnabled(){return this._publishLocalAudioStreamEnabled}set publishLocalAudioStreamEnabled(e){this._publishLocalAudioStreamEnabled=e}get publishLocalVideoStreamEnabled(){return this._publishLocalVideoStreamEnabled}set publishLocalVideoStreamEnabled(e){this._publishLocalVideoStreamEnabled=e}get publishLocalScreenStreamEnabled(){return this._publishLocalScreenStreamEnabled}set publishLocalScreenStreamEnabled(e){this._publishLocalScreenStreamEnabled=e}updateStreams(){return I(this,null,function*(){yield this.cameraStreamInfo.process(this.streamInfos),yield this.screenStreamInfo.process(this.streamInfos),this.emit("publishupdate")})}setAvailableCameraDeviceId(){return I(this,null,function*(){var e,t,i,s;if((e=this.cameraStreamInfo.cameraVideoConstraints)!=null&&e.deviceId){let n=(t=this.cameraStreamInfo.cameraVideoConstraints)==null?void 0:t.deviceId;const c=yield J.AliRTS.getCameraList();c.find(o=>o.deviceId===n)||(n=(s=(i=c.find(o=>!!o.deviceId))==null?void 0:i.deviceId)!=null?s:""),this.cameraStreamInfo.cameraVideoConstraints.deviceId=n}})}setAvailableMicrophoneDeviceId(){return I(this,null,function*(){var e,t,i,s;if((e=this.cameraStreamInfo.micAudioConstraints)!=null&&e.deviceId){let n=(t=this.cameraStreamInfo.micAudioConstraints)==null?void 0:t.deviceId;const c=yield J.AliRTS.getMicList();c.find(o=>o.deviceId===n)||(n=(s=(i=c.find(o=>!!o.deviceId))==null?void 0:i.deviceId)!=null?s:""),this.cameraStreamInfo.micAudioConstraints.deviceId=n}})}createLocalStream(e){return I(this,null,function*(){var u;const{screen:t,mediaStream:i,videoProfile:s,screenProfile:n}=e;let{video:c,audio:o}=e;const l=(p=>{const{audio:h,video:f,screen:g}=p;if(f&&g)throw new U(B.ERR_INNER,"create stream error, cannot create video && screen together");return!!(f||h||g)})(e);let d;if(l){i||(c===!0&&this.cameraStreamInfo.cameraVideoConstraints?(yield this.setAvailableCameraDeviceId(),c=X({},this.cameraStreamInfo.cameraVideoConstraints)):typeof c=="object"&&(yield this.setAvailableCameraDeviceId(),c=X(X({},c),this.cameraStreamInfo.cameraVideoConstraints)),o===void 0&&this.audioCaptureDisabled?o=!1:o&&(o===!0&&this.cameraStreamInfo.micAudioConstraints?(yield this.setAvailableMicrophoneDeviceId(),o=X({},this.cameraStreamInfo.micAudioConstraints)):typeof o=="object"&&(yield this.setAvailableMicrophoneDeviceId(),o=X(X({},o),this.cameraStreamInfo.micAudioConstraints)),this._audioCaptureDisabled=!1));const p=Date.now();try{d=yield J.AliRTS.createStream({audio:o,video:c,screen:t,custom:!!i,mediaStream:i,skipProfile:!0}),T.info(`[${Yt.logName}]`,"createLocalStream",{audio:o,video:c,screen:t,custom:!!i,time:Date.now()-p}),o&&!i&&this.slsReporter.reportAudio(null,Date.now()-p,((u=d==null?void 0:d.audioTrack)==null?void 0:u.label)||""),t&&!i&&this.slsReporter.reportScreen(null,Date.now()-p)}catch(h){throw o&&!i&&this.slsReporter.reportAudio(h,Date.now()-p,""),t&&!i&&this.slsReporter.reportScreen(null,Date.now()-p),h}if(t)yield this.screenStreamInfo.updateSource(d,wi.Screen,Hi.Screen),yield this.setScreenProfile(n||En),this.setScreenContentHint(),this.publishingScreenVideoStream=void 0;else if(yield this.cameraStreamInfo.updateSource(d,wi.Camera,Hi.Microphone),d.hasVideo&&(yield this.setVideoProfile(s||In),this.setVideoContentHint(),this.publishingCameraVideoStream=void 0),d.hasAudio&&typeof o=="boolean"){const h=this.cameraStreamInfo.audioProfile;h&&(yield d.setAudioProfile(h))}}return J.AliRTS.SystenUtil.isIos&&J.AliRTS.SystenUtil.compareVersion("15.1")&&!J.AliRTS.SystenUtil.compareVersion("15.2")&&(yield Ht(1e3)),yield this.updateStreams(),d})}stopLocalStream(e){return I(this,null,function*(){const{screen:t,video:i,audio:s}=e!=null?e:{};let n=!1;i&&this.cameraStreamInfo.originVideoTrack&&(n=!0,this.cameraStreamInfo.stopVideo(),this.publishingCameraVideoStream=void 0),s&&this.cameraStreamInfo.originAudioTrack&&(n=!0,this.cameraStreamInfo.stopAudio()),t&&this.screenStreamInfo.originVideoTrack&&(n=!0,this.screenStreamInfo.stop(),this.publishingScreenVideoStream=void 0,this.slsReporter.reportScreenStop(null)),n&&(yield this.updateStreams())})}get publishStreams(){const{publishLocalVideoStreamEnabled:e,publishLocalAudioStreamEnabled:t,publishLocalScreenStreamEnabled:i}=this;return{video:e?this.cameraStreamInfo.publishVideoStream:void 0,videoSmall:e?this.cameraStreamInfo.publishDualVideoStream:void 0,audio:t?this.cameraStreamInfo.publishAudioStream:void 0,screen:i?this.screenStreamInfo.publishVideoStream:void 0}}createHTTPPublishStream(){return I(this,null,function*(){var o,l,d,u;let e,t,i,s,n=!1;const c=this.publishStreams;try{if(!(c.audio||c.video||c.videoSmall||c.screen))throw T.error(`[${Yt.logName}]`,"no tracks founded"),new U(B.ERR_SDK_PUBLISH_INVAILD,"no tracks founded");const p=new MediaStream;(o=c.audio)!=null&&o.audioTrack&&p.addTrack(c.audio.audioTrack),(l=c.video)!=null&&l.videoTrack?(p.addTrack(c.video.videoTrack),i=c.videoSmall,s=c.screen):(d=c.screen)!=null&&d.videoTrack&&(t=D.Screen,p.addTrack((u=c.screen)==null?void 0:u.videoTrack),n=!0),e=yield Pn(p),n?(this.screenStreamInfo.cloneVideoProfile(e),this.publishingScreenVideoStream=e):(this.cameraStreamInfo.cloneVideoProfile(e),this.publishingCameraVideoStream=e),this.cameraStreamInfo.cloneAudioProfile(e)}catch(p){}return{publishStream:e,videoSmallStream:i,screenStream:s,vMsid:t}})}stop(){this.cameraStreamInfo.stop(),this.screenStreamInfo.stop(),this.updateStreams()}setVideoProfile(e,t,i=!1){return I(this,null,function*(){yield this.cameraStreamInfo.updateVideoProfile(e,t,i),this.publishingCameraVideoStream&&this.cameraStreamInfo.cloneVideoProfile(this.publishingCameraVideoStream)})}setVideoContentHint(e){this.cameraStreamInfo.setVideoContentHint(e)}setAudioProfile(e){return I(this,null,function*(){var t;yield this.cameraStreamInfo.updateAudioProfile(e),yield(t=this.publishingCameraVideoStream)==null?void 0:t.setAudioProfile(e)})}setScreenProfile(e,t){return I(this,null,function*(){yield this.screenStreamInfo.updateVideoProfile(e,t),this.publishingScreenVideoStream&&this.screenStreamInfo.cloneVideoProfile(this.publishingScreenVideoStream)})}setScreenContentHint(e){this.screenStreamInfo.setVideoContentHint(e)}setCameraVideoConstraints(e){var t;this.cameraStreamInfo.cameraVideoConstraints=X(X({},(t=this.cameraStreamInfo.cameraVideoConstraints)!=null?t:{}),e)}setMicAudioConstraints(e){var t;this.cameraStreamInfo.micAudioConstraints=X(X({},(t=this.cameraStreamInfo.micAudioConstraints)!=null?t:{}),e)}},m(Yt,"logName","LocalStreamManager"),Yt);Et([k(([a])=>{const{audio:r,video:e,screen:t,custom:i,skipProfile:s,videoProfile:n,screenProfile:c}=a;return[{audio:r,video:e,screen:t,custom:i,skipProfile:s,videoProfile:n,screenProfile:c}]})],wt.prototype,"createLocalStream",1),Et([k(H)],wt.prototype,"stopLocalStream",1),Et([k()],wt.prototype,"createHTTPPublishStream",1),Et([k()],wt.prototype,"stop",1),Et([k(H)],wt.prototype,"setVideoProfile",1),Et([k(H)],wt.prototype,"setVideoContentHint",1),Et([k(H)],wt.prototype,"setAudioProfile",1),Et([k(H)],wt.prototype,"setScreenProfile",1),Et([k(H)],wt.prototype,"setScreenContentHint",1),Et([k(H)],wt.prototype,"setCameraVideoConstraints",1),Et([k(H)],wt.prototype,"setMicAudioConstraints",1);let $c=wt;var Nn=(a=>(a[a.PRE_PROCESSOR=0]="PRE_PROCESSOR",a[a.POST_PROCESSOR=1]="POST_PROCESSOR",a))(Nn||{}),bi=(a=>(a[a.AUDIO=0]="AUDIO",a[a.VIDEO=1]="VIDEO",a[a.BOTH=2]="BOTH",a))(bi||{});class jt extends oe{constructor(e,t=He.AliRtcSdkStreamTypeCapture,i=1){super();m(this,"name");m(this,"options");m(this,"type",0);m(this,"streamType");m(this,"trackType");m(this,"zIndex",1);m(this,"_isEnable",!0);m(this,"shouldCache",!0);m(this,"lastInputAudioTrack");m(this,"lastOutputAudioTrack");m(this,"lastInputVideoTrack");m(this,"lastOutputVideoTrack");m(this,"_hasCleared",!0);this.name=e,this.streamType=t,this.trackType=i,this.options=this.initOptions}get initOptions(){return{}}getOptions(){return this.options}init(){return I(this,null,function*(){})}enable(){this._isEnable||(this._isEnable=!0,this.init(),this.emit("enabled"))}disable(){this._isEnable&&(this._isEnable=!1,this.clear(),this.emit("disabled"))}get isEnable(){return this._isEnable}audioUpdated(e){var t,i;return((t=this.lastInputAudioTrack)==null?void 0:t.id)!==((i=e.currentAudioTrack)==null?void 0:i.id)}videoUpdated(e){var t,i;return((t=this.lastInputVideoTrack)==null?void 0:t.id)!==((i=e.currentVideoTrack)==null?void 0:i.id)}execute(e,t){return I(this,null,function*(){const i=this.shouldUpdate(e,t);this.lastInputAudioTrack=e.currentAudioTrack,this.lastInputVideoTrack=e.currentVideoTrack,this._hasCleared||i?(yield this.process(e,t),this._hasCleared=!1):this.shouldCache&&(!this.lastOutputAudioTrack||this.trackType!==2&&this.trackType!==0||this.lastOutputAudioTrack&&e.updateAudioTrack(this.lastOutputAudioTrack),!this.lastOutputVideoTrack||this.trackType!==2&&this.trackType!==1||this.lastOutputVideoTrack&&e.updateVideoTrack(this.lastOutputVideoTrack)),this.lastOutputAudioTrack=e.currentAudioTrack,this.lastOutputVideoTrack=e.currentVideoTrack})}clear(e){this._hasCleared=!0,this.lastInputAudioTrack=void 0,this.lastInputVideoTrack=void 0,this.lastOutputAudioTrack=void 0,this.lastOutputVideoTrack=void 0}}class Wc extends jt{constructor(){super("AliRtcScreenStandardize",He.AliRtcSdkStreamTypeScreen);m(this,"canvas");m(this,"lastWidth");m(this,"lastHeight");m(this,"isProcessingScreenTrack",!1);this.shouldCache=!1}get initOptions(){return{base:4}}setOptions(e){this.options=e}isSupported(){return!(typeof TransformStream=="undefined"||typeof MediaStreamTrackProcessor=="undefined"||typeof MediaStreamTrackGenerator=="undefined")}updateProcessCanvas(e,t){if(this.canvas&&this.lastWidth===e&&this.lastHeight===t)return;const i=Math.ceil(e/this.options.base)*this.options.base,s=Math.ceil(t/this.options.base)*this.options.base;if(this.canvas||(this.canvas=document.createElement("canvas")),this.canvas.width=i,this.canvas.height=s,this.lastWidth&&e>this.lastWidth||this.lastHeight&&t>this.lastHeight){const n=this.canvas.getContext("2d");n&&n.clearRect(0,0,i,s)}this.lastWidth=e,this.lastHeight=t}shouldProcess(e){var i;let t=!1;if(e.originVideoTrack&&e.videoSource===wi.Screen){const s=(i=e.originVideoTrack)==null?void 0:i.getSettings();if(s){const{width:n,height:c}=s;t=!n||!c||!(n%this.options.base===0&&c%this.options.base===0)}}return t}shouldUpdate(e){return this.shouldProcess(e)!==this.isProcessingScreenTrack}handleFrame(e){return I(this,null,function*(){var n;const{displayWidth:t,displayHeight:i}=e;if(!t||!i||t%this.options.base===0&&i%this.options.base===0)return e;this.updateProcessCanvas(t,i);const s=(n=this.canvas)==null?void 0:n.getContext("2d");if(this.canvas&&s){s.drawImage(e,0,0,t,i);const c=new VideoFrame(this.canvas,{timestamp:e.timestamp});return e.close(),c}return e})}process(e){return I(this,null,function*(){var d;if(!this.shouldProcess(e))return this.clear(e),void(this.isProcessingScreenTrack=!1);if(e.originVideoTrack){const u=e.originVideoTrack.getSettings();if(u){const{width:p,height:h}=u;if(!(!p||!h||!(p%this.options.base===0&&h%this.options.base===0)))return void this.clear(e)}}const t=new MediaStreamTrackProcessor({track:e.originVideoTrack}),i=new MediaStreamTrackGenerator({kind:"video"}),s=new MediaStream([i]),n=this,c=new TransformStream({transform(u,p){return I(this,null,function*(){const h=yield n.handleFrame(u);yield p.enqueue(h),h==null||h.close()})}});t.readable.pipeThrough(c).pipeTo(i.writable);const o=(d=s.getVideoTracks())==null?void 0:d[0];e.updateVideoTrack(o),this.isProcessingScreenTrack=!0})}clear(e){this.canvas=void 0,this.lastWidth=void 0,this.lastHeight=void 0,super.clear(e)}}class zc extends jt{constructor(){super("blankAudio",He.AliRtcSdkStreamTypeCapture,bi.BOTH);m(this,"hasTrack",!1);m(this,"oscillator",null);m(this,"audioTrack",null);m(this,"createAudioTrack",()=>{const e=new AudioContext;this.oscillator=e.createOscillator();const t=e.createGain();t.gain.value=0;const i=e.createMediaStreamDestination();this.oscillator.connect(t),t.connect(i),this.oscillator.start();const s=i.stream;return this.audioTrack=s.getAudioTracks()[0],this.audioTrack});this.zIndex=9}isSupported(){return!0}setOptions(){throw new Error("Method not implemented.")}shouldUpdate(e,t){return this.hasTrack!==t.some(i=>i.originVideoTrack||i.originAudioTrack)}process(e,t){return I(this,null,function*(){var s;const i=t.some(n=>n.originVideoTrack||n.originAudioTrack);this.hasTrack=i,i?this.audioTrack&&((s=this.oscillator)==null||s.stop(),this.oscillator=null,this.audioTrack.stop(),this.audioTrack=null):(this.audioTrack||(this.audioTrack=this.createAudioTrack()),e.updateAudioTrack(this.audioTrack))})}}var Ks=(a=>(a[a.NONE=0]="NONE",a[a.ERROR=1]="ERROR",a[a.WARN=2]="WARN",a[a.INFO=3]="INFO",a[a.DEBUG=4]="DEBUG",a[a.TRACE=5]="TRACE",a))(Ks||{});const ss=class ss{constructor(r){m(this,"name","COMMON");m(this,"instanceLevel");this.name=r||this.name}setLevel(r){this.instanceLevel=r}getEffectiveLevel(){return this.instanceLevel!==void 0?this.instanceLevel:ss.LEVEL}info(...r){this.getEffectiveLevel()>=3&&this.print(Ks[3],...r)}warn(...r){this.getEffectiveLevel()>=2&&this.print(Ks[2],...r)}print(r,...e){const t=r.toLowerCase();t&&console[t](`[${r}][${this.name}]`,...e)}};m(ss,"LEVEL",0);let Js=ss;class Kc{constructor(){m(this,"logger",new Js("AudioMixer"));m(this,"audioContext",yt.getInstance());m(this,"audioDestination",this.audioContext.createMediaStreamDestination());m(this,"audioTrack",(r=>r.getAudioTracks()[0])(this.audioDestination.stream));m(this,"sourceNodeMap",{})}get sourceNodeList(){return Object.values(this.sourceNodeMap).map(r=>r.sourceNode).filter(r=>!!r)}get gainNodeList(){return Object.values(this.sourceNodeMap).map(r=>r.gainNode).filter(r=>!!r)}get sourceCount(){return this.sourceNodeList.length}resume(){var r;return(r=this.audioContext)==null?void 0:r.resume()}addTrack(r){this.connectTrack(r)}hasTrack(r){return!!this.sourceNodeMap[r]}removeTrack(r){const{sourceNode:e,gainNode:t}=this.sourceNodeMap[r]||{};t==null||t.disconnect(),e==null||e.disconnect(),delete this.sourceNodeMap[r],e?this.logger.info("SourceNode disconnected. Active source node:",this.sourceNodeList.length):this.logger.warn(`SourceNode ${r} does not exit. Active source node: ${this.sourceNodeList.length}`)}getAudioTrack(){return this.audioTrack}setVolume(r,e){const{gainNode:t}=this.sourceNodeMap[e]||{};t?(this.logger.info(`Setting node(${e}) volume to ${this.scale(r)}`),t.gain.value=this.scale(r)):this.logger.warn(`GainNode ${e} does not exit.`)}reset(){this.disconnectSourceNode(),this.sourceNodeMap={}}dispose(){var r;this.reset(),(r=this.audioTrack)==null||r.stop(),this.audioDestination.disconnect()}connectTrack(r){if(!this.audioContext)return this.logger.warn("AudioContext not initialized");let e=new MediaStream;e.addTrack(r);const t=this.audioContext.createMediaStreamSource(e),i=this.audioContext.createGain();i.gain.value=1,t.connect(i),i.connect(this.audioDestination),this.sourceNodeMap[r.id]={track:r,sourceNode:t,gainNode:i},this.logger.info("New sourceNode connected. Active source node:",this.sourceNodeList.length)}disconnectSourceNode(){this.sourceNodeList.forEach(r=>r.disconnect()),this.gainNodeList.forEach(r=>r.disconnect())}scale(r){return r/100}}class Jc extends jt{constructor(){super("audioMixer",He.AliRtcSdkStreamTypeCapture,bi.AUDIO);m(this,"audioMixer");m(this,"primaryAudioTrackId");m(this,"screenAudioTrackId");m(this,"dirty",!1);this.zIndex=8}get initOptions(){return{audio:1,screen:1}}setOptions(e){Object.entries(e).forEach(([t,i])=>{this.isValidVolume(i)&&(this.options[t]=i)}),this.dirty=!0,this.emit("updated")}isSupported(){return"AudioContext"in window}shouldUpdate(e,t){var n,c;if(e.type!==He.AliRtcSdkStreamTypeCapture)return!1;const i=t.find(o=>o.type===He.AliRtcSdkStreamTypeCapture),s=t.find(o=>o.type===He.AliRtcSdkStreamTypeScreen);return!(this.primaryAudioTrackId===((n=i==null?void 0:i.currentAudioTrack)==null?void 0:n.id)&&this.screenAudioTrackId===((c=s==null?void 0:s.currentAudioTrack)==null?void 0:c.id)&&!this.dirty)}process(e,t){return I(this,null,function*(){var c,o;this.dirty=!1;const i=t.find(l=>l.type===He.AliRtcSdkStreamTypeScreen),s=e.currentAudioTrack,n=i==null?void 0:i.currentAudioTrack;if(!n&&this.options.audio===1)return this.audioMixer&&(this.audioMixer.dispose(),this.audioMixer=void 0),this.primaryAudioTrackId=s==null?void 0:s.id,void e.updateAudioTrack(s);this.audioMixer||(this.audioMixer=new Kc),yield this.audioMixer.resume(),this.primaryAudioTrackId&&(s==null?void 0:s.id)!==this.primaryAudioTrackId&&((c=this.audioMixer)==null||c.removeTrack(this.primaryAudioTrackId)),s&&!this.audioMixer.hasTrack(s==null?void 0:s.id)&&this.audioMixer.addTrack(s),this.primaryAudioTrackId=s==null?void 0:s.id,this.screenAudioTrackId&&(n==null?void 0:n.id)!==this.screenAudioTrackId&&((o=this.audioMixer)==null||o.removeTrack(this.screenAudioTrackId)),n&&!this.audioMixer.hasTrack(n==null?void 0:n.id)&&this.audioMixer.addTrack(n),this.screenAudioTrackId=n==null?void 0:n.id,this.updateVolume(),e.updateAudioTrack(this.audioMixer.getAudioTrack())})}isValidVolume(e){return e!==void 0&&e>=0&&e<=4}updateVolume(){this.audioMixer&&(this.primaryAudioTrackId&&this.audioMixer.setVolume(100*this.options.audio,this.primaryAudioTrackId),this.screenAudioTrackId&&this.audioMixer.setVolume(100*this.options.screen,this.screenAudioTrackId))}clear(e){var t;(t=this.audioMixer)==null||t.dispose(),super.clear(e)}}class qc extends jt{constructor(){super(...arguments);m(this,"isProcessing",!1);m(this,"videoScaler")}get initOptions(){return{width:320,height:180,frameRate:15}}setOptions(e){var t;this.options=e,(t=this.videoScaler)==null||t.updateOptions(e)}isSupported(){return As.isSupport()}shouldUpdate(e){const t=!!e.currentVideoTrack;return this.isProcessing!==t}process(e){return I(this,null,function*(){if(e.currentVideoTrack){if(this.isProcessing=!0,!this.videoScaler){const i=this.options||this.initOptions;this.videoScaler=As.getInstance(e.currentVideoTrack,i)}const t=this.videoScaler.getVideoTrack();t&&e.updateDualVideoTrack(t)}else this.isProcessing&&this.clear()})}clear(e){var t;super.clear(e),this.isProcessing=!1,e==null||e.updateDualVideoTrack(),(t=this.videoScaler)==null||t.dispose()}}function Si(a,r,e,t){return new(e||(e=Promise))(function(i,s){function n(l){try{o(t.next(l))}catch(d){s(d)}}function c(l){try{o(t.throw(l))}catch(d){s(d)}}function o(l){var d;l.done?i(l.value):(d=l.value,d instanceof e?d:new e(function(u){u(d)})).then(n,c)}o((t=t.apply(a,r||[])).next())})}var Xt,Nt;function xn(){return Si(this,void 0,void 0,function*(){let a=!1;try{a=yield(()=>I(this,null,function*(){return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]))}))()}catch(r){a=!1}return console.log("isSupportedSIMD",a),a})}typeof SuppressedError=="function"&&SuppressedError,(Nt=Xt||(Xt={}))[Nt.ERROR=0]="ERROR",Nt[Nt.WARN=1]="WARN",Nt[Nt.INFO=2]="INFO",Nt[Nt.LOG=3]="LOG",Nt[Nt.DEBUG=4]="DEBUG";class Ie{static error(...r){var e;Ie.logLevel>=Xt.ERROR&&((e=console.error)===null||e===void 0||e.call(console,`[${Ie.logTag}] `,...r))}static warn(...r){var e;Ie.logLevel>=Xt.WARN&&((e=console.warn)===null||e===void 0||e.call(console,`[${Ie.logTag}] `,...r))}static info(...r){var e;Ie.logLevel>=Xt.INFO&&((e=console.info)===null||e===void 0||e.call(console,`[${Ie.logTag}] `,...r))}static log(...r){var e;Ie.logLevel>=Xt.LOG&&((e=console.log)===null||e===void 0||e.call(console,`[${Ie.logTag}] `,...r))}static debug(...r){var e;Ie.logLevel>=Xt.DEBUG&&((e=console.debug)===null||e===void 0||e.call(console,`[${Ie.logTag}] `,...r))}}Ie.logLevel=Xt.WARN,Ie.logTag="aliyun-audio-3a";class Gc{}class On extends Gc{static isSupported(){return function(){if(typeof window=="object"&&window!==null){const r="AudioWorklet"in window,e="WebAssembly"in window;return r&&e}return!1}()}static isSupportedSIMD(){return Si(this,void 0,void 0,function*(){return yield xn()})}static setLogger(r){Ie.logLevel=r}constructor(r){super(),this.channelCount=1,this.sampleRate=48e3,this.collectDumpOutputData=[],this.collectDumpNearInputData=[],this.collectDumpFarInputData=[],this.collectDumpMetaData=[],this.statUpdateTimer=0,this.statUpdateInterval=5e3,this.options=Object.assign({aecOn:!0,ansOn:!0,agcOn:!0,hdOn:!1,ansMode:1,dumpOn:!1,aiaecOn:!1,wasmCdnPath:"https://g.alicdn.com/code/npm/@ali/aliyun-audio-3a/0.0.6/"},r||{})}initWASM(r,e,t){return Si(this,void 0,void 0,function*(){Ie.log("initWASM",r,e,t);const i=n=>Si(this,void 0,void 0,function*(){try{const c=yield fetch(n,{credentials:"same-origin"});return c.ok||this.onLoadError(new Error(`Failed to fetch WASM: ${c.status}:${c.statusText}, url:${n}`)),c.arrayBuffer()}catch(c){return this.onLoadError(new Error("WASM load error")),Ie.error("Error fetching WASM:",c),new Uint8Array(0)}}),s=n=>Si(this,void 0,void 0,function*(){return fetch(n).then(c=>c.text())});try{const n=yield xn(),c=this.options.wasmCdnPath+"audio_module_v2.wasm",o=this.options.wasmCdnPath+"audio_module_v2_simd.wasm",d=yield i(n?o:c),u=this.options.wasmCdnPath+"audio_module_v2.js",p=this.options.wasmCdnPath+"audio_module_v2_simd.js",h=n?p:u,f=yield s(h);r.port.postMessage(Object.assign({type:"init",channelCount:e,sampleRate:t,wasmBuffer:d,isSupportSIMD:n,audioModuleScript:f,logLevel:Ie.logLevel},this.options),[d])}catch(n){Ie.error("Error initializing WASM:",n),this.onLoadError(new Error("WASM init error"))}r.port.onmessage=n=>{n.data.type==="init_done"&&this.onLoadSuccess(void 0),n.data.type==="dump_output_data"&&this.onDumpOutputData(n.data.data),n.data.type==="dump_near_data"&&this.onDumpNearInputData(n.data.data),n.data.type==="dump_far_data"&&this.onDumpFarInputData(n.data.data),n.data.type==="dump_meta_data"&&this.onDumpMeatData(n.data.data),n.data.type==="output_log"&&this.onOutputLog(n.data.data),n.data.type==="apm_stat_data"&&this.onStatData(n.data.data)}})}createProcessor(r,e,t,i,s){return Si(this,void 0,void 0,function*(){this.audioContext=r,this.audioContext.resume(),this.channelCount=t,this.sampleRate=i;try{const o=new Blob(['!function(){"use strict";var kl=Object.defineProperty,Pl=Object.defineProperties;var Dl=Object.getOwnPropertyDescriptors;var as=Object.getOwnPropertySymbols,Ml=Object.getPrototypeOf,oo=Object.prototype.hasOwnProperty,co=Object.prototype.propertyIsEnumerable,Ll=Reflect.get;var dr=(z,J,oe)=>J in z?kl(z,J,{enumerable:!0,configurable:!0,writable:!0,value:oe}):z[J]=oe,X=(z,J)=>{for(var oe in J||(J={}))oo.call(J,oe)&&dr(z,oe,J[oe]);if(as)for(var oe of as(J))co.call(J,oe)&&dr(z,oe,J[oe]);return z},vt=(z,J)=>Pl(z,Dl(J));var Wt=(z,J)=>{var oe={};for(var at in z)oo.call(z,at)&&J.indexOf(at)<0&&(oe[at]=z[at]);if(z!=null&&as)for(var at of as(z))J.indexOf(at)<0&&co.call(z,at)&&(oe[at]=z[at]);return oe};var m=(z,J,oe)=>(dr(z,typeof J!="symbol"?J+"":J,oe),oe);var ur=(z,J,oe)=>Ll(Ml(z),oe,J);var I=(z,J,oe)=>new Promise((at,Vt)=>{var pi=nt=>{try{yt(oe.next(nt))}catch(Rt){Vt(Rt)}},mi=nt=>{try{yt(oe.throw(nt))}catch(Rt){Vt(Rt)}},yt=nt=>nt.done?at(nt.value):Promise.resolve(nt.value).then(pi,mi);yt((oe=oe.apply(z,J)).next())});function t(t,e,a,n){return new(a||(a=Promise))((function(s,i){function o(t){try{h(n.next(t))}catch(t){i(t)}}function r(t){try{h(n.throw(t))}catch(t){i(t)}}function h(t){var e;t.done?s(t.value):(e=t.value,e instanceof a?e:new a((function(t){t(e)}))).then(o,r)}h((n=n.apply(t,e||[])).next())}))}var e;"function"==typeof SuppressedError&&SuppressedError,function(t){t[t.ERROR=0]="ERROR",t[t.WARN=1]="WARN",t[t.INFO=2]="INFO",t[t.LOG=3]="LOG",t[t.DEBUG=4]="DEBUG"}(e||(e={}));class a{static error(...t){var n;a.logLevel>=e.ERROR&&(null===(n=console.error)||void 0===n||n.call(console,`[${a.logTag}] `,...t))}static warn(...t){var n;a.logLevel>=e.WARN&&(null===(n=console.warn)||void 0===n||n.call(console,`[${a.logTag}] `,...t))}static info(...t){var n;a.logLevel>=e.INFO&&(null===(n=console.info)||void 0===n||n.call(console,`[${a.logTag}] `,...t))}static log(...t){var n;a.logLevel>=e.LOG&&(null===(n=console.log)||void 0===n||n.call(console,`[${a.logTag}] `,...t))}static debug(...t){var n;a.logLevel>=e.DEBUG&&(null===(n=console.debug)||void 0===n||n.call(console,`[${a.logTag}] `,...t))}}a.logLevel=e.WARN,a.logTag="aliyun-audio-3a";const n=Float32Array.BYTES_PER_ELEMENT,s=Uint16Array.BYTES_PER_ELEMENT;class i{constructor(t,e,a,n,s){this._channelData=[],this._name=t,this._isInitialized=!1,this._module=e,this._length=a,this._ringLength=2*a,this._maxChannelCount=s?Math.min(s,32):n,this._channelCount=n,this._allocateHeap(),this._isInitialized=!0,this._readIndex=0,this._writeIndex=0,this._framesAvailable=0,this._channelDataLocal=[];for(let t=0;t<this._channelCount;++t)this._channelDataLocal[t]=new Float32Array(this._ringLength)}_allocateHeap(){const t=this._length*n,e=this._channelCount*t;this._dataPtr=this._module._malloc(e),this._channelData=[];for(let e=0;e<this._channelCount;++e){const a=this._dataPtr+e*t,n=a+t;this._channelData[e]=this._module.HEAPF32.subarray(a>>s,n>>s)}}adaptChannel(t){t<this._maxChannelCount&&(this._channelCount=t)}get length(){return this._isInitialized?this._length:null}get numberOfChannels(){return this._isInitialized?this._channelCount:null}get maxChannelCount(){return this._isInitialized?this._maxChannelCount:null}getChannelData(t){return void 0!==t&&t>=this._channelCount?null:void 0===t?this._channelData:this._channelData[t]}getHeapAddress(){return this._dataPtr}getPointer(){return this._dataPtr}free(){this._isInitialized=!1,null!==this._dataPtr&&this._module._free(this._dataPtr),this._channelData=[]}get framesAvailable(){return this._framesAvailable}push(t){const e=t[0].length;for(let a=0;a<e;++a){for(let e=0;e<this._channelCount;++e)this._channelDataLocal[e][this._writeIndex]=t[e][a];this._writeIndex=(this._writeIndex+1)%this._ringLength}this._framesAvailable+=e,this._framesAvailable>this._ringLength&&(console.warn(this._name,"Too many frames available, overflow"),this._framesAvailable=this._ringLength,this._writeIndex=0)}pull(t){if(0===this._framesAvailable)return void console.warn(this._name,"No frames available");const e=t[0].length;for(let a=0;a<e;++a){for(let e=0;e<this._channelCount;++e)t[e][a]=this._channelDataLocal[e][this._readIndex];this._readIndex=(this._readIndex+1)%this._ringLength}this._framesAvailable-=e,this._framesAvailable<0&&(this._framesAvailable=0,this._readIndex=0)}}class o{constructor(t){this.inited=!1,this.handle=null,this.channelCount=1,this.isEnable=!0,this.dumpAudioData=!1,this.kernelBufferSize=512,this.node=t,this.onDumpOutputDataFunction=null,this.onDumpNearDataFunction=null,this.onDumpFarDataFunction=null,this.onDumpMetaDataFunction=null,this.wasmInvoker=null,this._nearAudioBuffer={},this._outputAudioBuffer={}}destructor(){this.wasmInvoker=null,this.handle=null}init(n){return t(this,void 0,void 0,(function*(){const{wasmBuffer:t,audioModuleScript:s,channelCount:o=1,sampleRate:r=44100,dumpAudioData:h=!1,logLevel:l=e.DEBUG}=n;a.logLevel=l,a.log("AudioAPM init",JSON.stringify(n)),this.channelCount=o,this.dumpAudioData=h;try{const e=new Function(`let module={};let exports={};${s}; return module`)();this.wasmInvoker=yield e.exports({wasmBinary:t})}catch(t){this.node.port.postMessage({type:"error",message:"audioModule init error"}),a.error(t)}this._nearAudioBuffer=new i("inBuffer",this.wasmInvoker,this.kernelBufferSize,2*this.channelCount,32),this._outputAudioBuffer=new i("outBuffer",this.wasmInvoker,this.kernelBufferSize,this.channelCount,32);const u=this.wasmInvoker.addFunction(((t,e)=>{const a=this.wasmInvoker.HEAPU8.subarray(t,t+e),n=String.fromCharCode.apply(null,a);this.node&&this.node.port&&this.node.port.postMessage({type:"output_log",message:"output_log",data:n})}),"vii");if(this.wasmInvoker.__apm_log_callback(u),this.handle=this.wasmInvoker.__apm_create(n.aecOn?1:0,n.ansOn?1:0,n.agcOn?1:0,n.hdOn?1:0,r,o,n.dumpOn?1:0,this.kernelBufferSize),n.aiaecOn){const t=102;this.wasmInvoker.__apm_set_param(this.handle,t,7)}if(n.useHardOnly){const t=108;this.wasmInvoker.__apm_set_param(this.handle,t,1)}this.node.port.postMessage({type:"init_done",message:"init done"}),this.inited=!0}))}getStatData(){if(this.wasmInvoker&&this.isEnable){let t=this.wasmInvoker.__apm_get_stat(this.handle),e=this.wasmInvoker.UTF8ToString(t);this.wasmInvoker._free(t),this.node&&this.node.port&&this.node.port.postMessage({type:"apm_stat_data",message:"apm_stat_data",data:e})}}onOutputLog(t){console.log("[WASM_LOG]",t)}destory(){return t(this,void 0,void 0,(function*(){var t;try{null===(t=this.wasmInvoker)||void 0===t||t.__apm_destory(this.handle),this.inited=!1}catch(t){a.error(t)}finally{this.handle=null}}))}enable(){this.isEnable=!0,a.log("APM enable")}disable(){this.isEnable=!1,a.log("APM disable")}getStat(){if(null==this.wasmInvoker||null==this.handle)return"";let t=this.wasmInvoker.__apm_get_stat(this.handle),e=this.wasmInvoker.UTF8ToString(t);return this.wasmInvoker._free(t),e}startDump(){this.onDumpOutputDataFunction=this.wasmInvoker.addFunction(((t,e)=>{const a=this.wasmInvoker.HEAPU8.subarray(t,t+e),n=new Uint8Array(a);this.node&&this.node.port&&this.node.port.postMessage({type:"dump_output_data",message:"dump_output_data",data:n})}),"vii"),this.onDumpNearDataFunction=this.wasmInvoker.addFunction(((t,e)=>{const a=this.wasmInvoker.HEAPU8.subarray(t,t+e),n=new Uint8Array(a);this.node&&this.node.port&&this.node.port.postMessage({type:"dump_near_data",message:"dump_near_data",data:n})}),"vii"),this.onDumpFarDataFunction=this.wasmInvoker.addFunction(((t,e)=>{const a=this.wasmInvoker.HEAPU8.subarray(t,t+e),n=new Uint8Array(a);this.node&&this.node.port&&this.node.port.postMessage({type:"dump_far_data",message:"dump_far_data",data:n})}),"vii"),this.onDumpMetaDataFunction=this.wasmInvoker.addFunction(((t,e)=>{const a=this.wasmInvoker.HEAPU8.subarray(t,t+e),n=new Uint8Array(a);this.node&&this.node.port&&this.node.port.postMessage({type:"dump_meta_data",message:"dump_meta_data",data:n})}),"vii"),this.wasmInvoker.__apm_dump_start(this.handle,this.onDumpOutputDataFunction,this.onDumpNearDataFunction,this.onDumpFarDataFunction,this.onDumpMetaDataFunction)}stopDump(){this.wasmInvoker.__apm_dump_stop(this.handle),this.wasmInvoker&&(this.wasmInvoker.removeFunction(this.onDumpOutputDataFunction),this.wasmInvoker.removeFunction(this.onDumpNearDataFunction),this.wasmInvoker.removeFunction(this.onDumpFarDataFunction),this.wasmInvoker.removeFunction(this.onDumpMetaDataFunction))}process(t,e,a){if(!this.inited||!this.isEnable){for(let e=0;e<this.channelCount;e++){a[e].set(t[e])}return}const n=this.channelCount;let s=0;if(this.handle&&this.isEnable){const i=t[0].length,o=[];for(let a=0;a<n;a++)e[a]&&e[a].length>0&&(s=1),o.push(t[a]||new Float32Array(i).fill(0)),o.push(e[a]||new Float32Array(i).fill(0));if(this._nearAudioBuffer.push(o),this._nearAudioBuffer.framesAvailable>=this.kernelBufferSize){this._nearAudioBuffer.pull(this._nearAudioBuffer.getChannelData()),this.wasmInvoker.__apm_process_new(this.handle,this._nearAudioBuffer.getHeapAddress(),this._outputAudioBuffer.getHeapAddress(),n,s);const t=this._outputAudioBuffer.getChannelData();this._outputAudioBuffer.push(t)}this._outputAudioBuffer.pull(a)}}}class r extends AudioWorkletProcessor{constructor(){super(),this.apm=new o(this),this.port.onmessage=t=>{const e=t.data||{};switch(a.log("onmessage data",e),e.type){case"init":this.apm.init(e);break;case"destroy":this.apm.destory();break;case"enable":this.apm.enable();break;case"disable":this.apm.disable();break;case"start_dump":this.apm.startDump();break;case"stop_dump":this.apm.stopDump();break;case"get_stat_data":this.apm.getStatData();break;default:a.warn("Unknown message type:",e.type)}}}process(t,e){const a=t[0],n=t.length>1?t[1]:[],s=e[0];return this.apm.process(a,n,s),!0}}registerProcessor("aliyun-web-3a-processor",r)}();\n'],{type:"application/javascript"}),l=URL.createObjectURL(o);yield this.audioContext.audioWorklet.addModule(l)}catch(o){Ie.error("Failed to add module to audio worklet:",o)}let n=new AudioWorkletNode(this.audioContext,"aliyun-web-3a-processor",{numberOfInputs:2,outputChannelCount:[t]});this.workletNode=n,e.connect(n),s&&(this.farNode=s,s.connect(n,0,1));const c=this.audioContext.createMediaStreamDestination();n.connect(c),this.targetMediaTrack=c.stream.getAudioTracks()[0],yield this.initWASM(n,t,i),this.statUpdateTimer=window.setInterval(()=>{this.getStatData()},this.statUpdateInterval)})}addFarNode(r){this.workletNode&&(this.farNode&&this.farNode.disconnect(this.workletNode),r&&(this.farNode=r,r.connect(this.workletNode,0,1)))}getStatData(){var r;try{(r=this.workletNode)===null||r===void 0||r.port.postMessage({type:"get_stat_data"})}catch(e){Ie.error("Failed to post message to worklet node:",e)}}destroy(){if(this.statUpdateTimer&&window.clearInterval(this.statUpdateTimer),this.audioContext&&this.workletNode&&this.workletNode.port)try{this.workletNode.port.postMessage({type:"destroy"}),this.workletNode.port.onmessage=null,this.workletNode.disconnect(),Ie.log("postMessage destroy")}catch(r){Ie.error("Failed to post message to worklet node:",r)}}startDump(){var r;try{(r=this.workletNode)===null||r===void 0||r.port.postMessage({type:"start_dump"})}catch(e){Ie.error("Failed to post message to worklet node:",e)}}stopDump(){var r;try{(r=this.workletNode)===null||r===void 0||r.port.postMessage({type:"stop_dump"})}catch(e){Ie.error("Failed to post message to worklet node:",e)}setTimeout(()=>{this.onDumpOutputData(null,!0),this.onDumpNearInputData(null,!0),this.onDumpFarInputData(null,!0),this.onDumpMeatData(null,!0)},3e3)}onDumpOutputData(r,e=!1){if(r&&r.length>0&&this.collectDumpOutputData.push(r),e&&this.collectDumpOutputData.length>0||1024*this.collectDumpOutputData.length>=this.getMaxDumpBytes()){let t=new Blob(this.collectDumpOutputData);this.onDumpData(t,"output_"+this.sampleRate+"hz_"+this.channelCount+"ch.pcm"),this.collectDumpOutputData=[]}}onDumpNearInputData(r,e=!1){if(r&&r.length>0&&this.collectDumpNearInputData.push(r),e&&this.collectDumpNearInputData.length>0||1024*this.collectDumpNearInputData.length>=this.getMaxDumpBytes()){let t=new Blob(this.collectDumpNearInputData);this.onDumpData(t,"near_input_"+this.sampleRate+"hz_"+this.channelCount+"ch.pcm"),this.collectDumpNearInputData=[]}}onDumpFarInputData(r,e=!1){if(r&&r.length>0&&this.collectDumpFarInputData.push(r),e&&this.collectDumpFarInputData.length>0||1024*this.collectDumpFarInputData.length>=this.getMaxDumpBytes()){let t=new Blob(this.collectDumpFarInputData);this.onDumpData(t,"far_input_"+this.sampleRate+"hz_"+this.channelCount+"ch.pcm"),this.collectDumpFarInputData=[]}}onDumpMeatData(r,e=!1){if(r&&r.length>0&&this.collectDumpMetaData.push(r),e&&this.collectDumpMetaData.length>0||1024*this.collectDumpMetaData.length>=this.getMaxDumpBytes()){let t=new Blob(this.collectDumpMetaData);this.onDumpData(t,"meta_"+this.sampleRate+"hz_"+this.channelCount+"ch.pcm"),this.collectDumpMetaData=[]}}getMaxDumpBytes(){return 600*Number(this.sampleRate.toFixed(0))*Number(this.channelCount.toFixed(0))*2}enable(){var r;if(!((r=this.workletNode)===null||r===void 0)&&r.port)try{this.workletNode.port.postMessage({type:"enable"}),Ie.log("postMessage enable")}catch(e){Ie.error("Failed to post message to worklet node:",e)}}disable(){var r;if(!((r=this.workletNode)===null||r===void 0)&&r.port)try{Ie.log("postMessage disable"),this.workletNode.port.postMessage({type:"disable"})}catch(e){Ie.error("Failed to post message to worklet node:",e)}}on(r,e){r==="loaderror"&&(this.onLoadError=e),r==="loadsuccess"&&(this.onLoadSuccess=e),r==="dumpdata"&&(this.onDumpData=e),r==="outputlog"&&(this.onOutputLog=e),r==="statdata"&&(this.onStatData=e)}onLoadError(r){console.log("onLoadError",r)}onLoadSuccess(r){console.log("onLoadSuccess",r)}onDumpData(r,e){console.log("onDumpData",r,e)}onOutputLog(r){console.log("[WASM]",r)}onStatData(r){console.log("onStatData:",r)}}class Xc extends jt{constructor(e){super("AliRtcAudioProcessPlugin",He.AliRtcSdkStreamTypeCapture,bi.AUDIO);m(this,"audioProcessor");m(this,"slsReporter");m(this,"enableSoft3ACheck",!1);m(this,"useHardOnly",!1);m(this,"lastDiffOutputLog","");m(this,"audioContext",new AudioContext({sampleRate:48e3}));m(this,"farNode");m(this,"activeAudioContext",()=>{var e;(e=this.audioContext)==null||e.resume(),document.removeEventListener("click",this.activeAudioContext)});m(this,"createNode",e=>this.audioContext.createMediaStreamSource(new MediaStream([e])));this.options=e,this.slsReporter=e==null?void 0:e.slsReporter,this.enableSoft3ACheck=(e==null?void 0:e.enableSoft3ACheck)||!1,this.useHardOnly=(e==null?void 0:e.useHardOnly)||!1,this.zIndex=7,document.addEventListener("click",this.activeAudioContext)}audioUpdated(e){var t,i;return((t=this.lastInputAudioTrack)==null?void 0:t.id)!==((i=e.currentAudioTrack)==null?void 0:i.id)}videoUpdated(e){return console.log("videoUpdated",e),!1}setOptions(e){var t;!this.farNode&&e.farMediaStream&&(this.farNode=this.audioContext.createMediaStreamSource(e.farMediaStream),this.audioProcessor&&((t=this.audioProcessor)==null||t.addFarNode(this.farNode)),this.options=X(X({},this.options),e))}isSupported(){return On.isSupported()}shouldUpdate(e){return!!(e.originAudioTrack&&!this.audioProcessor||!e.originAudioTrack&&this.audioProcessor)}process(e){return I(this,null,function*(){var t;if(!e.currentAudioTrack)return e.updateAudioTrack(),void this.clear(e);if(!this.audioProcessor){this.audioProcessor=new On({aecOn:!0,ansOn:!0,agcOn:!0,dumpOn:((t=this.options)==null?void 0:t.dumpAudioData)||!1,aiaecOn:this.options.aiaecOn||!1,useHardOnly:this.useHardOnly,wasmCdnPath:this.options.wasmCdnPath||"https://g.alicdn.com/code/npm/@ali/aliyun-audio-3a/0.0.6/"}),this.audioProcessor.on("dumpdata",(s,n)=>{let c=3e3;n.includes("far")?c=5e3:n.includes("output")?c=1e4:n.includes("meta")&&(c=8e3),setTimeout(()=>{const o=URL.createObjectURL(s),l=document.createElement("a");l.href=o,l.download=n,document.body.appendChild(l),l.click(),document.body.removeChild(l)},c)}),this.audioProcessor.on("loadsuccess",()=>{var s,n;this.enableSoft3ACheck||e.updateAudioTrack((s=this.audioProcessor)==null?void 0:s.targetMediaTrack),this.options.dumpAudioData&&((n=this.audioProcessor)==null||n.startDump())}),this.audioProcessor.on("loaderror",s=>{this.emit("error",s)}),this.audioProcessor.on("outputlog",s=>{s!=null&&s.includes("diff")&&(this.lastDiffOutputLog=s||"")}),this.audioProcessor.on("statdata",s=>{var n;if(s)try{let c=s;if(this.lastDiffOutputLog){const o=this.extractDiffValue(this.lastDiffOutputLog),l=JSON.parse(s);o!==null&&(l.diff=o);const d=this.extractLeakValue(this.lastDiffOutputLog);d!==null&&(l.leak=d),c=JSON.stringify(l)}(n=this.slsReporter)==null||n.reportPublishAudio3A("","","",c)}catch(c){}});const i=this.createNode(e.currentAudioTrack);yield this.audioProcessor.createProcessor(this.audioContext,i,1,48e3,this.farNode)}})}extractDiffValue(e){if(!e)return null;const t=e.match(/diff\s*=\s*(-?\d+\.?\d*)/);return t?parseFloat(t[1]):null}extractLeakValue(e){if(!e)return null;const t=e.match(/leak\s*=\s*(-?\d+\.?\d*)/);return t?parseFloat(t[1]):null}clear(e){var t,i,s;this.options.dumpAudioData&&((t=this.audioProcessor)==null||t.stopDump()),super.clear(e),(i=this.audioProcessor)==null||i.destroy(),this.audioProcessor=void 0,document.removeEventListener("click",this.activeAudioContext),(s=this.farNode)==null||s.disconnect(),this.farNode=void 0}dump(){var e;(e=this.audioProcessor)==null||e.stopDump()}}var Di=(a=>(a[a.Default=0]="Default",a[a.Human=1]="Human",a[a.Robot=2]="Robot",a))(Di||{}),Qc=Object.defineProperty,Yc=Object.getOwnPropertyDescriptor,Vn=(a,r,e,t)=>{for(var i,s=t>1?void 0:t?Yc(r,e):r,n=a.length-1;n>=0;n--)(i=a[n])&&(s=(t?i(r,e,s):i(s))||s);return t&&s&&Qc(r,e,s),s};const qs=(Zt=class extends oe{constructor(e,t){super();m(this,"self");m(this,"remoteUser");m(this,"sendReadyMsg",!1);m(this,"hasPubDataChannel",!1);m(this,"hasSubDataChannel",!1);m(this,"readyMsgSuccess",!1);m(this,"sendReadyMsgTimer");m(this,"startReadyMsgTime");m(this,"robotUserId");m(this,"onSubscribeDataChannel",e=>{!this.remoteUser&&e&&(this.robotUserId&&this.robotUserId!==e.userId||(this.hasSubDataChannel=!0,this.remoteUser=e,this.remoteUser.on("remoteDataChannelMessage",this.onCheckReadyMsg),this.trySendReadyMsg()))});m(this,"onCheckReadyMsg",(e,t)=>{var i,s;if(this.sendReadyMsg&&!this.readyMsgSuccess)try{const n=new TextDecoder().decode(t.data),c=JSON.parse(n);c.key==="aliyun_aigc"&&c.type==="ready_resp"&&((i=c.data)==null?void 0:i.ready)===!0&&(T.event(`[${Zt.logName}]`,"onCheckReadyMsg success"),this.readyMsgSuccess=!0,this.emit("dcready",e),(s=this.remoteUser)==null||s.off("remoteDataChannelMessage",this.onCheckReadyMsg),window.clearTimeout(this.sendReadyMsgTimer))}catch(n){}});m(this,"onDataPublishStateChange",(e,t)=>{t===ee.AliRtcStatePublished&&(this.hasPubDataChannel=!0,this.trySendReadyMsg())});this.self=e,this.self.on("dataPublishStateChanged",this.onDataPublishStateChange),this.robotUserId=t}destroy(){this.self.off("dataPublishStateChanged",this.onDataPublishStateChange),window.clearTimeout(this.sendReadyMsgTimer),this.remoteUser=void 0,this.sendReadyMsg=!1,this.hasPubDataChannel=!1,this.hasSubDataChannel=!1,this.readyMsgSuccess=!1,this.startReadyMsgTime=0}trySendReadyMsg(){T.event(`[${Zt.logName}]`,`trySendReadyMsg: pub(${this.hasPubDataChannel}, sub: ${this.hasSubDataChannel})`),this.hasPubDataChannel&&this.hasSubDataChannel&&(this.sendReadyMsg=!0,this.sendReadyMsgLoop())}sendReadyMsgLoop(e=0){return I(this,null,function*(){const t=JSON.stringify({key:"aliyun_aigc",version:"1.0",type:"ready_req",data:{ready:!0}});try{this.self.sendDataChannelMessage(new Jt(new TextEncoder().encode(t).buffer))}catch(n){}this.startReadyMsgTime||(this.startReadyMsgTime=Date.now());let i=50;const s=Date.now()-this.startReadyMsgTime;i=s<1e3?50:s<2e3?100:s<3e3?500:2e3,e>30?T.event(`[${Zt.logName}]`,"sendReadyMsgLoop fail after 30 times"):this.sendReadyMsgTimer=window.setTimeout(()=>{this.sendReadyMsgLoop(e+1)},i)})}},m(Zt,"logName","DataChannelReadyHelper"),Zt);Vn([k()],qs.prototype,"destroy",1),Vn([k()],qs.prototype,"sendReadyMsgLoop",1);let Zc=qs;class el{constructor(r){m(this,"_useSysEchoCancellation",!0);m(this,"_useSysNoiseSuppression",!0);m(this,"_useSysAutoGainControl",!0);m(this,"_useAIAEC",!1);m(this,"_enableSoft3A",!1);m(this,"_enableSoft3ACheck",!1);m(this,"_useHardOnly",!1);m(this,"_dumpAudioData",!1);m(this,"_useAudio3AConfigFromServer",!0);r&&Object.assign(this,r)}get useSysEchoCancellation(){return this._useSysEchoCancellation}set useSysEchoCancellation(r){this._useSysEchoCancellation=r}get useSysNoiseSuppression(){return this._useSysNoiseSuppression}set useSysNoiseSuppression(r){this._useSysNoiseSuppression=r}get useSysAutoGainControl(){return this._useSysAutoGainControl}set useSysAutoGainControl(r){this._useSysAutoGainControl=r}get useAIAEC(){return this._useAIAEC}set useAIAEC(r){this._useAIAEC=r}get enableSoft3A(){return this._enableSoft3A}set enableSoft3A(r){this._enableSoft3A=r}get enableSoft3ACheck(){return this._enableSoft3ACheck}set enableSoft3ACheck(r){this._enableSoft3ACheck=r}get useHardOnly(){return this._useHardOnly}set useHardOnly(r){this._useHardOnly=r}get dumpAudioData(){return this._dumpAudioData}set dumpAudioData(r){this._dumpAudioData=r}get useAudio3AConfigFromServer(){return this._useAudio3AConfigFromServer}set useAudio3AConfigFromServer(r){this._useAudio3AConfigFromServer=r}loadFromLocalConfig(r){var e,t,i,s,n,c,o,l,d;this.useAudio3AConfigFromServer=(e=r.useAudio3AConfigFromServer)!=null?e:this.useAudio3AConfigFromServer,this.useSysEchoCancellation=(t=r.useSysEchoCancellation)!=null?t:this.useSysEchoCancellation,this.useSysNoiseSuppression=(i=r.useSysNoiseSuppression)!=null?i:this.useSysNoiseSuppression,this.useSysAutoGainControl=(s=r.useSysAutoGainControl)!=null?s:this.useSysAutoGainControl,this.useAIAEC=(n=r.useAIAEC)!=null?n:this.useAIAEC,this.enableSoft3A=(c=r.enableSoft3A)!=null?c:this.enableSoft3A,this.dumpAudioData=(o=r.dumpAudioData)!=null?o:this.dumpAudioData,this.enableSoft3ACheck=(l=r.enableSoft3ACheck)!=null?l:this.enableSoft3ACheck,this.useHardOnly=(d=r.useHardOnly)!=null?d:this.useHardOnly}loadFromServerConfig(r){if(r&&typeof r=="object"){const e=ii(r,"enableSoft3A"),t=gi(r,"enableSoft3A");if(e===!0&&t===!0&&(this.enableSoft3A=!0),this.enableSoft3A){if(r.archCfgs){const i=ii(r,"enableSoft3ACheck");i!==void 0&&(this.enableSoft3ACheck=i);const s=ii(r,"useAIAEC");s!==void 0&&(this.useAIAEC=s);const n=ii(r,"useSysNoiseSuppression");n!==void 0&&(this.useSysNoiseSuppression=n);const c=ii(r,"useSysEchoCancellation");c!==void 0&&(this.useSysEchoCancellation=c);const o=ii(r,"useSysAutoGainControl");o!==void 0&&(this.useSysAutoGainControl=o)}if(r.config){const i=gi(r,"enableSoft3ACheck");i!==void 0&&(this.enableSoft3ACheck=i);const s=gi(r,"useAIAEC");s!==void 0&&(this.useAIAEC=s);const n=gi(r,"useSysNoiseSuppression");n!==void 0&&(this.useSysNoiseSuppression=n);const c=gi(r,"useSysEchoCancellation");c!==void 0&&(this.useSysEchoCancellation=c);const o=gi(r,"useSysAutoGainControl");o!==void 0&&(this.useSysAutoGainControl=o)}T.info("setAudio3AConfig:","enableSoft3A",this.enableSoft3A,", enableSoft3ACheck",this.enableSoft3ACheck,", useAIAEC",this.useAIAEC,", useSysNoiseSuppression",this.useSysNoiseSuppression,", useSysEchoCancellation",this.useSysEchoCancellation,", useSysAutoGainControl",this.useSysAutoGainControl)}}}}var tl=Object.defineProperty,il=Object.getOwnPropertyDescriptor,lt=(a,r,e,t)=>{for(var i,s=t>1?void 0:t?il(r,e):r,n=a.length-1;n>=0;n--)(i=a[n])&&(s=(t?i(r,e,s):i(s))||s);return t&&s&&tl(r,e,s),s};class et extends oe{constructor(e){super();m(this,"_loggerInstanceId","");m(this,"self");m(this,"userMap",{});m(this,"usersViewMap",{});m(this,"rtsManager");m(this,"localStreamManager");m(this,"authInfo");m(this,"signalingManager");m(this,"pluginManager");m(this,"audioMixerPlugin");m(this,"dualVideoPlugin");m(this,"blankAudioPlugin");m(this,"audioProcessorPlugin");m(this,"slsReporter");m(this,"statsMonitorId");m(this,"autoSubAudio",!0);m(this,"autoSubVideo",!0);m(this,"autoSubScreen",!0);m(this,"wantSubAudio",!0);m(this,"wantSubVideo",!0);m(this,"wantSubScreen",!0);m(this,"defaultStreamType",Ge.AliRtcVideoStreamTypeHigh);m(this,"audioMuted",!1);m(this,"playoutVolume",1);m(this,"refreshUrlTimer");m(this,"audioVolumeIndicationInterval",0);m(this,"indicationTimer",0);m(this,"parameter",{});m(this,"audio3AConfig",new el);m(this,"dcReadyHelper");m(this,"networkQualityTimer");const{signalingManager:t,slsReporter:i,parameter:s}=e;this._loggerInstanceId=e.instanceId||"",this.signalingManager=t,this.addSignalingManagerListener(),this.slsReporter=i,s&&(this.parameter=s),this.pluginManager=new Mc,this.localStreamManager=new $c(this.pluginManager,this.slsReporter),this.rtsManager=new Hc(this.localStreamManager,this.slsReporter,this.parameter),this.addRTSListener(),this.self=new Ec({rtsManager:this.rtsManager,localStreamManager:this.localStreamManager,slsReporter:this.slsReporter,signalingManager:this.signalingManager,pluginManager:this.pluginManager,audioVolumeIndicationInterval:this.audioVolumeIndicationInterval,parameter:this.parameter}),this.audioMixerPlugin=new Jc,this.pluginManager.add(this.audioMixerPlugin),this.dualVideoPlugin=new qc("dualVideoPlugin"),new J.AliRTS.SupportUtil().checkScreenCapture()&&this.pluginManager.add(new Wc)}addSignalingManagerListener(){this.signalingManager.on("onNotifyPublish",e=>{e.forEach(t=>{var i;(i=t==null?void 0:t.tracks)==null||i.forEach(s=>{var n;if(s.msid===D.Audio&&s.userdata)try{const c=JSON.parse(s.userdata);c.agent_instance&&((n=this.slsReporter)==null||n.setCustomFields({ageniid:c.agent_instance}))}catch(c){console.error("Failed to parse userdata:",c)}})}),this.slsReporter.reportConnectionLatencyEvent(Ze.RECV_NOTIFY_PUBLISH,"","",""),this._loggerInstanceId&&T.setActiveInstance(this._loggerInstanceId),T.event("[Signaling] Notify Publish ",e),e.forEach(t=>{this.onRemotePublishStateChange(t)})})}addRTSListener(){this.rtsManager.on("traceIdUpdated",(e,t)=>{if(Le.removeQueryString(this.self.url)===Le.removeQueryString(e))return void(this.self.traceId=t);const i=this.remoteUsers.find(s=>Le.removeQueryString(s.streamUrl)===Le.removeQueryString(e));i&&(i.traceId=t)}),this.rtsManager.on("reconnect",(e,t,i)=>{if(!e||e==="pc"||e==="all")return this.self.markReconnect(),void this.remoteUsers.forEach(n=>{n.markReconnect()});if(e==="pub"||e==="pub-data")return void this.self.markReconnect(i);const s=this.remoteUsers.find(n=>Le.removeQueryString(n.streamUrl)===Le.removeQueryString(t||""));s==null||s.markReconnect(i)}),this.rtsManager.on("reconnectFinish",(e,t,i)=>{if(this._loggerInstanceId&&T.setActiveInstance(this._loggerInstanceId),T.event("[RtsManager]","reconnectFinish",e,t,i),!e||e==="pc"||e==="all")return this.self.markReconnected(),void this.remoteUsers.forEach(n=>{n.markReconnected()});if(e==="pub"||e==="pub-data")return void this.self.markReconnected(i);const s=this.remoteUsers.find(n=>Le.removeQueryString(n.streamUrl)===Le.removeQueryString(t||""));s==null||s.markReconnected(i)})}isAutoSubAudio(){return this.autoSubAudio}setAutoSubAudio(e){this.autoSubAudio=e}isAutoSubVideo(){return this.autoSubVideo}setAutoSubVideo(e){this.autoSubVideo=e}isAutoSubScreen(){return this.autoSubScreen}setAutoSubScreen(e){this.autoSubScreen=e}isWantSubAudio(){return this.wantSubAudio}setWantSubAudio(e){this.wantSubAudio=e,this.remoteUsers.forEach(t=>{t.setWantSubAudio(e),t.updateSubscribe(ge.User)})}isWantSubVideo(){return this.wantSubVideo}setWantSubVideo(e){this.wantSubVideo=e,this.remoteUsers.forEach(t=>{t.setWantSubVideo(e),t.updateSubscribe(ge.User)})}isWantSubScreen(){return this.wantSubScreen}setWantSubScreen(e){this.wantSubScreen=e,this.remoteUsers.forEach(t=>{t.setWantSubScreen(e),t.updateSubscribe(ge.User)})}setRemoteDefaultVideoStreamType(e){this.defaultStreamType=e,this.remoteUsers.forEach(t=>{t.setRemoteDefaultVideoStreamType(e)})}setRemoteUserVideoStreamType(e,t){var i;(i=this.getRemoteUser(e))==null||i.setRemoteDefaultVideoStreamType(t)}setAudioMuted(e){this.audioMuted=e,this.remoteUsers.forEach(t=>{t.setAudioMuted(e)})}setLocalViewConfig(e,t){if(!e)return this.publisher.setViewConfig(null,t);const i=cs(e);i.length!==0&&i.forEach(s=>{this.publisher.resetElement(s),Object.entries(this.usersViewMap).forEach(([n,c])=>{var u,p;const{cameraViews:o=[],screenViews:l=[]}=c;let d=!1;if(o.includes(s)&&(o.splice(o.indexOf(s),1),d=!0),l.includes(s)&&(l.splice(l.indexOf(s),1),d=!0),d&&o.length===0&&l.length===0)try{_e.getInstance().removeRemoteViewConfig(((p=(u=this.authInfo)==null?void 0:u.userId)!=null?p:"")+n)}catch(h){}}),this.publisher.setViewConfig(i,t)})}setRemoteViewConfig(e,t,i){var c,o,l,d,u,p;const s=_e.getInstance();if(!t){try{s.removeRemoteViewConfig(((o=(c=this.authInfo)==null?void 0:c.userId)!=null?o:"")+e)}catch(h){}return(l=this.userMap[e])==null?void 0:l.setViewConfig(null,i)}const n=cs(t);if(n.length!==0){n.forEach(h=>{this.publisher.resetElement(h),Object.entries(this.usersViewMap).forEach(([f,g])=>{var R,_;const{cameraViews:b=[],screenViews:S=[]}=g;let v=!1;if(b.includes(h)&&(b.splice(b.indexOf(h),1),v=!0),S.includes(h)&&(S.splice(S.indexOf(h),1),v=!0),v&&f!==e&&b.length===0&&S.length===0)try{s.removeRemoteViewConfig(((_=(R=this.authInfo)==null?void 0:R.userId)!=null?_:"")+f)}catch(y){}})});try{if(n.length===1)try{s.setRemoteViewConfig(((u=(d=this.authInfo)==null?void 0:d.userId)!=null?u:"")+e,n[0])}catch(h){}}catch(h){}(p=this.userMap[e])==null||p.setViewConfig(n,i)}}get channel(){var e;return(e=this.authInfo)==null?void 0:e.channelId}get userId(){var e;return(e=this.authInfo)==null?void 0:e.userId}get remoteUsers(){return Object.values(this.userMap)}get publisher(){return this.self}get isSubscribing(){var e;return((e=this.remoteUsers)!=null?e:[]).some(t=>{const{isAudioSubscribing:i,isVideoSubscribing:s,isScreenSubscribing:n}=t;return i||s||n})}onRemotePublishStateChange(e,t=!0){var h;const{userid:i,callid:s,subscribe:n,pubid:c="",tracks:o}=e,l=(h=n==null?void 0:n.pullstreamurl)!=null?h:"";let d=this.getRemoteUser(i);if(!d)return;const u=d.streamInfo.audioTrackInfo,p=d.streamInfo.videoTrackInfo;d.updateRemoteTracks(s,l,c,o),u===d.streamInfo.audioTrackInfo&&p===d.streamInfo.videoTrackInfo||this.emit("remoteTrackAvailableChange",i,d.streamInfo.audioTrackInfo,d.streamInfo.videoTrackInfo),t&&d.updateSubscribe(ge.Publish)}setTimeoutToUpdateAllStreamUrls(e){var s;if(!e)return;let t=354e4;const i=(s=function(n){var c,o;try{const l=new URL(n),[d,u]=l.pathname.slice(1).split("/"),p=/(\w+)(web\w{5}-\w{4}-\w{4}-\w{4}-\w{12})/.exec(u),h=p==null?void 0:p[1],f=p==null?void 0:p[2],g=new URLSearchParams(l.search);return{appId:d,channelId:h,sessionId:f,timeoutTs:1e3*parseInt((o=(c=g.get("auth_key"))==null?void 0:c.split("-")[0])!=null?o:"0")}}catch(l){return null}}(e))==null?void 0:s.timeoutTs;i&&(t=i-Date.now()-6e4),this.refreshUrlTimer=window.setTimeout(()=>I(this,null,function*(){var c;const n=yield this.signalingManager.refreshUrl({pushstreamurl:this.self.url,users:this.remoteUsers.map(o=>({userid:o.userId,subscribe:{pullstreamurl:o.streamUrl}}))});n.pushstreamurl&&(this.self.url=n.pushstreamurl),(c=n.users)==null||c.forEach(o=>{var d;const l=this.getRemoteUser(o.userid);l&&((d=o.subscribe)!=null&&d.pullstreamurl)&&(l.streamUrl=o.subscribe.pullstreamurl)}),this.setTimeoutToUpdateAllStreamUrls(n.pushstreamurl)}),t)}init(e,t,i){var s;this.authInfo=e,this.self.enableAudioVolumeIndication(this.audioVolumeIndicationInterval),this.self.initInfo(e,t.pushstreamurl),this.audio3AConfig.useAudio3AConfigFromServer&&this.audio3AConfig.loadFromServerConfig((s=t==null?void 0:t.config)==null?void 0:s.data),this.setupAudioProcessingPluginIfNeeded(),i.capabilityProfile===Di.Human&&(this.dcReadyHelper=new Zc(this.self,i.robotUserId),this.dcReadyHelper.on("dcready",n=>{var c;this.emit("remoteUserSubscribedDataChannel",n),(c=this.dcReadyHelper)==null||c.destroy(),this.dcReadyHelper=void 0})),this.setTimeoutToUpdateAllStreamUrls(t.pushstreamurl),t.users.forEach(n=>{this.addUser(n,ge.InRoom)}),this.startStatsMonitor(),this.networkQualityTimer=window.setInterval(()=>I(this,null,function*(){if(this.remoteUsers.length===0)return void this.emit("networkQuality",{subscribe:{rtt:0,loss:0,quality:tt.AliRtcNetworkUnknown}});const n=yield this.rtsManager.getSubscribeNetworkQuality();this.emit("networkQuality",{subscribe:n})}),2e3)}leave(){return I(this,null,function*(){var t,i,s;this.stopIndication();let e="";try{this.stopStatsMonitor(),this.refreshUrlTimer!==void 0&&(window.clearTimeout(this.refreshUrlTimer),this.refreshUrlTimer=void 0),Object.values(this.usersViewMap).forEach(({cameraViews:n=[],screenViews:c=[]})=>{n.forEach(o=>{o.srcObject=null,o._playPromise=void 0}),c.forEach(o=>{o.srcObject=null,o._playPromise=void 0})}),this.usersViewMap={};for(let n in this.userMap)this.userMap[n]&&(this.userMap[n].clear(),delete this.userMap[n]);e=(i=(t=this.authInfo)==null?void 0:t.userId)!=null?i:"",this.self.leave(),(s=this.dcReadyHelper)==null||s.destroy(),this.dcReadyHelper=void 0,this.localStreamManager.stop(),this.rtsManager.clear(),this.authInfo=void 0,window.clearInterval(this.networkQualityTimer),this.networkQualityTimer=void 0}finally{this.stopStatsMonitor(),this.stopIndication()}try{_e.getInstance().clearAll(e)}catch(n){}})}clear(){return I(this,null,function*(){yield this.leave(),this.stopIndication(),this.self.clear(),this.pluginManager.removeAll()})}startStatsMonitor(){this.statsMonitorId=window.setInterval(()=>I(this,null,function*(){if(this.publisher){const{audio:i,video:s,candidate:n}=yield this.publisher.getStats();i&&i.length>0&&this.emit("rtcLocalAudioStats",i),s&&s.length>0&&this.emit("rtcLocalVideoStats",s),n&&this.emit("rtcStats",n)}const e=[],t=[];for(const i of this.remoteUsers){const{audio:s,video:n}=yield i.getStats();s&&s.forEach(c=>{e.push(c)}),n&&n.forEach(c=>{t.push(c)})}e.length>0&&this.emit("rtcRemoteAudioStats",e),t.length>0&&this.emit("rtcRemoteVideoStats",t)}),2e3)}stopStatsMonitor(){this.statsMonitorId&&(clearInterval(this.statsMonitorId),this.statsMonitorId=void 0)}addUser(e,t){const i=e.userid;let s=this.userMap[i];return s||(s=this.executeAddUser(i,e.displayname||"",t),this.userMap[i]=s,this.emit("remoteUserJoin",i,0)),this.onRemotePublishStateChange(e,t!==ge.InRoom),s}executeAddUser(e,t,i){const s=new Dc({userId:e,displayName:t,rtsManager:this.rtsManager,signalingManager:this.signalingManager,usersViewMap:this.usersViewMap,slsReporter:this.slsReporter,localUser:this.self,audioVolumeIndicationInterval:this.audioVolumeIndicationInterval,playoutVolume:this.playoutVolume,parameter:this.parameter});return s.on(ot.Remote,this.onRemoteDeviceStatusChange.bind(this)),s.on(Me.PullStreamStats,this.onRemoteStatReport.bind(this)),s.on(Me.RtsSubscribeExceeds,this.onSubscribeExceeds.bind(this)),s.on("audioSubscribeStateChanged",(n,c,o,l)=>{this.emit("audioSubscribeStateChanged",n,c,o,l,this.channel||"")}),s.on("videoSubscribeStateChanged",(n,c,o,l)=>{this.emit("videoSubscribeStateChanged",n,c,o,l,this.channel||"")}),s.on("screenSubscribeStateChanged",(n,c,o,l)=>{this.emit("screenSubscribeStateChanged",n,c,o,l,this.channel||"")}),s.on("dataSubscribeStateChanged",(n,c,o,l)=>{var d;o===ce.AliRtcStateSubscribed&&((d=this.dcReadyHelper)==null||d.onSubscribeDataChannel(this.userMap[n])),this.emit("dataSubscribeStateChanged",n,c,o,l,this.channel||"")}),s.on("remoteAudioAutoPlayFail",n=>{this.emit("remoteAudioAutoPlayFail",n)}),s.on("remoteVideoAutoPlayFail",(n,c)=>{this.emit("remoteVideoAutoPlayFail",n,c)}),s.on("remoteAudioPlayError",(n,c)=>{this.emit("remoteAudioPlayError",n,c)}),s.on("remoteVideoPlayError",(n,c)=>{this.emit("remoteVideoPlayError",n,c)}),s.on("remoteSubscribeError",n=>{this.emit("remoteSubscribeError",n,s.userId)}),s.on("occurError",n=>{this.emit("occurError",n,s.userId)}),s.on("remoteDataChannelMessage",(n,c)=>{this.emit("remoteDataChannelMessage",n,c)}),s.setWantSubAudio(this.autoSubAudio&&this.wantSubAudio),s.setWantSubVideo(this.autoSubVideo&&this.wantSubVideo),s.setWantSubScreen(this.autoSubScreen&&this.wantSubScreen),s.setRemoteDefaultVideoStreamType(this.defaultStreamType),s.setAudioMuted(this.audioMuted),(this.autoSubAudio||this.autoSubVideo||this.autoSubScreen)&&s.updateSubscribe(i),s}onRemoteDeviceStatusChange(e,t){e===Me.MuteAudio?this.emit("userAudioMuted",t,!0):e===Me.UnmuteAudio?this.emit("userAudioMuted",t,!1):e===Me.MuteVideo?this.emit("userVideoMuted",t,!0):e===Me.UnmuteVideo?this.emit("userVideoMuted",t,!1):e===Me.MuteScreen?this.emit("userScreenMuted",t,!0):e===Me.UnmuteScreen&&this.emit("userScreenMuted",t,!1)}onRemoteStatReport(e,t,i){this.emit(Me.PullStreamStats,e,t,i)}onSubscribeExceeds(e,t){this.emit(Me.RtsSubscribeExceeds,e,t)}removeLeftUser(e){return I(this,null,function*(){e.userid&&this.userMap[e.userid]&&(yield this.userMap[e.userid].clear(!1),delete this.userMap[e.userid])})}diffUsers(e){const t=[],i=[];e.forEach(n=>{n.userid&&(this.userMap[n.userid]?i.push(n):t.push(n))});const s=Object.keys(this.userMap).filter(n=>!e.find(c=>c.userid===n)).map(n=>({userid:n,reason:"",leavecode:ns.AliRtcUserOfflineQuit}));return{joinList:t,leaveList:s,presentList:i}}getRemoteUser(e){return this.userMap[e]}updateRemoteUserDeviceStatus(e){e&&e.userid&&this.userMap[e.userid]&&this.userMap[e.userid].updateRemoteUserDeviceStatus(e.status)}updateAudioWant(e,t){const i=this.userMap[e];if(!i)throw new U(B.ERR_INNER,`no remote user(${e}) founded`);i.setWantSubAudio(t),t?i.updateSubscribe(ge.User):i.stopSubscribe({audio:!0})}updateVideoWant(e,t){const i=this.userMap[e];if(!i)throw new U(B.ERR_INNER,`no remote user(${e}) founded`);i.setWantSubVideo(t),t?i.updateSubscribe(ge.User):i.stopSubscribe({video:!0})}updateScreenWant(e,t){const i=this.userMap[e];if(!i)throw new U(B.ERR_INNER,`no remote user(${e}) founded`);i.setWantSubScreen(t),t?i.updateSubscribe(ge.User):i.stopSubscribe({screen:!0})}stopIndication(){this.indicationTimer&&(window.clearInterval(this.indicationTimer),this.indicationTimer=0)}startIndication(e){this.stopIndication(),this.indicationTimer=window.setInterval(()=>{const t=this.remoteUsers.map(i=>({userId:i.userId,volume:i.getAudioLevel()||0}));t.unshift({userId:"",volume:this.self.getAudioLevel()||0}),this.emit("audioVolume",t)},e)}setEnableDualVideoStream(e,t){if(!this.dualVideoPlugin)return;t&&this.dualVideoPlugin.setOptions(t);const i=this.pluginManager.has(this.dualVideoPlugin.name);e?!i&&this.pluginManager.add(this.dualVideoPlugin):i&&this.pluginManager.remove(this.dualVideoPlugin.name)}setAudioVolume(e){var t;(t=this.audioMixerPlugin)==null||t.setOptions(e)}enableAudioVolumeIndication(e){this.audioVolumeIndicationInterval!==e&&(this.audioVolumeIndicationInterval>0&&e<=0&&this.stopIndication(),e>0&&this.startIndication(e),this.audioVolumeIndicationInterval=e,this.remoteUsers.forEach(t=>{t.enableAudioVolumeIndication(e)}),this.self.enableAudioVolumeIndication(e))}setPlayoutVolume(e){this.playoutVolume=e,this.remoteUsers.forEach(t=>{t.setPlayoutVolume(e)})}refreshAuthInfo(e){this.authInfo&&(this.authInfo=X(X({},this.authInfo),e)),e.userId&&this.self.refreshUserInfo(e.userId)}setEnableMediaExtensionMsg(e){this.rtsManager.setEncodedInsertableStreams(e)}setAudioRedEnabled(e){this.rtsManager.setAudioRedEnabled(e)}setVideoCodec(e){this.rtsManager.changeVideoCodec(e)}setParameter(e){var i,s,n,c,o;const t=JSON.parse(e);Object.keys(t).forEach(l=>{const d=this.parameter[l],u=t[l];this.parameter[l]=typeof d=="object"&&typeof u=="object"?X(X({},d),u):u}),t.enableBlankAudio===!0?(this.blankAudioPlugin||(this.blankAudioPlugin=new zc),this.pluginManager.has((i=this.blankAudioPlugin)==null?void 0:i.name)||this.pluginManager.add(this.blankAudioPlugin)):t.enableBlankAudio===!1&&(this.blankAudioPlugin&&this.pluginManager.remove((s=this.blankAudioPlugin)==null?void 0:s.name),(n=this.blankAudioPlugin)==null||n.clear(),this.blankAudioPlugin=void 0),t.audio&&((c=this.audio3AConfig)==null||c.loadFromLocalConfig(t.audio)),t.subscribe&&((o=this.rtsManager)==null||o.updateSubscribeBatcher(t.subscribe))}updateDynamicConfig(e){this.rtsManager.updateDynamicConfig(e)}setChannelContext(){this.rtsManager.setChannelContext({channelId:this.channel,userId:this.userId})}setupAudioProcessingPluginIfNeeded(){if(this.audio3AConfig.enableSoft3A){let e=0;this.audio3AConfig.enableSoft3ACheck&&(e=1e4),setTimeout(()=>{this.audioProcessorPlugin||(this.audioProcessorPlugin=new Xc({dumpAudioData:this.audio3AConfig.dumpAudioData,aiaecOn:this.audio3AConfig.useAIAEC,slsReporter:this.slsReporter,enableSoft3ACheck:this.audio3AConfig.enableSoft3ACheck,useHardOnly:this.audio3AConfig.useHardOnly})),this.audioProcessorPlugin&&!this.pluginManager.has(this.audioProcessorPlugin.name)&&(this.audioProcessorPlugin.on("error",({message:t})=>{var i;this._loggerInstanceId&&T.setActiveInstance(this._loggerInstanceId),T.error("audioProcessorPlugin error:",t),(i=this.self.audioTrack)==null||i.applyConstraints({echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0})}),this.pluginManager.add(this.audioProcessorPlugin))},e)}else this.audioProcessorPlugin&&(this.pluginManager.remove(this.audioProcessorPlugin.name),this.audioProcessorPlugin=void 0);this.self.setMicrophoneConstraints({echoCancellation:this.audio3AConfig.useSysEchoCancellation,noiseSuppression:this.audio3AConfig.useSysNoiseSuppression,autoGainControl:this.audio3AConfig.useSysAutoGainControl})}getParameter(){return JSON.stringify(this.parameter)}sendDataChannelMessage(e){return this.self.sendDataChannelMessage(e)}}m(et,"logName","BizControl"),lt([k()],et.prototype,"init",1),lt([k()],et.prototype,"leave",1),lt([k()],et.prototype,"clear",1),lt([k(H)],et.prototype,"addUser",1),lt([k()],et.prototype,"removeLeftUser",1),lt([k()],et.prototype,"diffUsers",1),lt([k(H)],et.prototype,"updateAudioWant",1),lt([k(H)],et.prototype,"updateVideoWant",1),lt([k(H)],et.prototype,"updateScreenWant",1),lt([k()],et.prototype,"stopIndication",1),lt([k()],et.prototype,"startIndication",1),lt([k(H)],et.prototype,"setEnableDualVideoStream",1),lt([k(H)],et.prototype,"setAudioVolume",1),lt([k()],et.prototype,"enableAudioVolumeIndication",1);var Mi=(a=>(a[a.LiveTranscodingSingle=0]="LiveTranscodingSingle",a[a.LiveTranscodingMix=1]="LiveTranscodingMix",a))(Mi||{}),Gs=(a=>(a[a.LiveTranscodingOrigin=0]="LiveTranscodingOrigin",a[a.LiveTranscodingAudio=1]="LiveTranscodingAudio",a[a.LiveTranscodingVideo=2]="LiveTranscodingVideo",a))(Gs||{}),vi=(a=>(a[a.LiveTranscodingCamera=0]="LiveTranscodingCamera",a[a.LiveTranscodingShareScreen=1]="LiveTranscodingShareScreen",a))(vi||{});const Li={0:"camera",1:"shareScreen"};var Xs=(a=>(a[a.LiveTranscoding_Profile_1IN_1080P=0]="LiveTranscoding_Profile_1IN_1080P",a[a.LiveTranscoding_Profile_1IN_720P=1]="LiveTranscoding_Profile_1IN_720P",a[a.LiveTranscoding_Profile_1IN_360P=2]="LiveTranscoding_Profile_1IN_360P",a[a.LiveTranscoding_Profile_2IN_1080P=3]="LiveTranscoding_Profile_2IN_1080P",a[a.LiveTranscoding_Profile_2IN_720P=4]="LiveTranscoding_Profile_2IN_720P",a[a.LiveTranscoding_Profile_2IN_360P=5]="LiveTranscoding_Profile_2IN_360P",a[a.LiveTranscoding_Profile_4IN_1080P=6]="LiveTranscoding_Profile_4IN_1080P",a[a.LiveTranscoding_Profile_4IN_720P=7]="LiveTranscoding_Profile_4IN_720P",a[a.LiveTranscoding_Profile_4IN_360P=8]="LiveTranscoding_Profile_4IN_360P",a[a.LiveTranscoding_Profile_9IN_1080P=9]="LiveTranscoding_Profile_9IN_1080P",a[a.LiveTranscoding_Profile_9IN_720P=10]="LiveTranscoding_Profile_9IN_720P",a[a.LiveTranscoding_Profile_9IN_360P=11]="LiveTranscoding_Profile_9IN_360P",a[a.LiveTranscoding_Profile_12IN_1080P=12]="LiveTranscoding_Profile_12IN_1080P",a[a.LiveTranscoding_Profile_12IN_720P=13]="LiveTranscoding_Profile_12IN_720P",a[a.LiveTranscoding_Profile_12IN_360P=14]="LiveTranscoding_Profile_12IN_360P",a[a.LiveTranscoding_Profile_16IN_1080P=15]="LiveTranscoding_Profile_16IN_1080P",a[a.LiveTranscoding_Profile_16IN_720P=16]="LiveTranscoding_Profile_16IN_720P",a[a.LiveTranscoding_Profile_16IN_360P=17]="LiveTranscoding_Profile_16IN_360P",a[a.LiveTranscoding_Profile_Mixed=9999]="LiveTranscoding_Profile_Mixed",a))(Xs||{});const sl={0:"1IN_1080P",1:"1IN_720P",2:"1IN_360P",3:"2IN_1080P",4:"2IN_720P",5:"2IN_360P",6:"4IN_1080P",7:"4IN_720P",8:"4IN_360P",9:"9IN_1080P",10:"9IN_720P",11:"9IN_360P",12:"12IN_1080P",13:"12IN_720P",14:"12IN_360P",15:"16IN_1080P",16:"16IN_720P",17:"16IN_360P",9999:"Mixed_Audio"};var Qi=(a=>(a[a.LiveTranscoding_HZ_48000=48e3]="LiveTranscoding_HZ_48000",a[a.LiveTranscoding_HZ_44100=44100]="LiveTranscoding_HZ_44100",a[a.LiveTranscoding_HZ_32000=32e3]="LiveTranscoding_HZ_32000",a[a.LiveTranscoding_HZ_16000=16e3]="LiveTranscoding_HZ_16000",a[a.LiveTranscoding_HZ_8000=8e3]="LiveTranscoding_HZ_8000",a))(Qi||{}),Ni=(a=>(a[a.LiveTranscodingNoBody=0]="LiveTranscodingNoBody",a[a.LiveTranscodingBody=1]="LiveTranscodingBody",a))(Ni||{}),xi=(a=>(a[a.NOTO_SERIF_CJKSC_REGULAR=0]="NOTO_SERIF_CJKSC_REGULAR",a[a.ALIBABA_PUHUITI_REGULAR=1]="ALIBABA_PUHUITI_REGULAR",a[a.ALIBABA_PUHUITI_BOLD=2]="ALIBABA_PUHUITI_BOLD",a[a.ALIBABA_PUHUITI_Heavy=3]="ALIBABA_PUHUITI_Heavy",a[a.ALIBABA_PUHUITI_LIGHT=4]="ALIBABA_PUHUITI_LIGHT",a[a.ALIBABA_PUHUITI_MEDIUM=5]="ALIBABA_PUHUITI_MEDIUM",a))(xi||{}),Qs=(a=>(a[a.LiveTranscodingOrigin=0]="LiveTranscodingOrigin",a[a.LiveTranscodingCrop=1]="LiveTranscodingCrop",a[a.LiveTranscodingFill=2]="LiveTranscodingFill",a))(Qs||{}),Yi=(a=>(a[a.LiveTranscodingNormal=0]="LiveTranscodingNormal",a[a.LiveTranscodingVirtualBackground=1]="LiveTranscodingVirtualBackground",a))(Yi||{}),Ys=(a=>(a[a.LiveTranscodingState_IDLE=0]="LiveTranscodingState_IDLE",a[a.LiveTranscodingState_CONNNECT=1]="LiveTranscodingState_CONNNECT",a[a.LiveTranscodingState_RUNNING=2]="LiveTranscodingState_RUNNING",a[a.LiveTranscodingState_RECOVERING=3]="LiveTranscodingState_RECOVERING",a[a.LiveTranscodingState_FAILURE=4]="LiveTranscodingState_FAILURE",a[a.LiveTranscodingState_END=5]="LiveTranscodingState_END",a))(Ys||{}),xt=(a=>(a[a.LiveTranscodingErrorPublishOk=0]="LiveTranscodingErrorPublishOk",a[a.LiveTranscodingErrorStreamNotFound=17825793]="LiveTranscodingErrorStreamNotFound",a[a.LiveTranscodingErrorStreamAlreadyExist=17825794]="LiveTranscodingErrorStreamAlreadyExist",a[a.LiveTranscodingErrorInvalidParam=17825795]="LiveTranscodingErrorInvalidParam",a[a.LiveTranscodingErrorInternalError=17825796]="LiveTranscodingErrorInternalError",a[a.LiveTranscodingErrorRtmpServerError=17825797]="LiveTranscodingErrorRtmpServerError",a[a.LiveTranscodingErrorRtmpStreamUrlError=17825798]="LiveTranscodingErrorRtmpStreamUrlError",a[a.LiveTranscodingErrorPublishTimeout=17825799]="LiveTranscodingErrorPublishTimeout",a[a.LiveTranscodingErrorNotAuthorized=17825800]="LiveTranscodingErrorNotAuthorized",a))(xt||{}),Zs=(a=>(a[a.TrascodingPublishTaskStatusStart=0]="TrascodingPublishTaskStatusStart",a[a.TrascodingPublishTaskStatusUpdate=1]="TrascodingPublishTaskStatusUpdate",a[a.TrascodingPublishTaskStatusStop=2]="TrascodingPublishTaskStatusStop",a))(Zs||{}),dt=(a=>(a[a.MPU_TASK_TRANSACTION_START=0]="MPU_TASK_TRANSACTION_START",a[a.MPU_TASK_TRANSACTION_UPDATE=1]="MPU_TASK_TRANSACTION_UPDATE",a[a.MPU_TASK_TRANSACTION_STOP=2]="MPU_TASK_TRANSACTION_STOP",a[a.MPU_TASK_TRANSACTION_LIST=3]="MPU_TASK_TRANSACTION_LIST",a[a.MPU_TASK_TRANSACTION_POLLING=4]="MPU_TASK_TRANSACTION_POLLING",a[a.MPU_TASK_TRANSACTION_ACKNOWLEDGE=5]="MPU_TASK_TRANSACTION_ACKNOWLEDGE",a[a.MPU_TASK_TRANSACTION_END=6]="MPU_TASK_TRANSACTION_END",a))(dt||{});const rl={0:"/libra/v1/sdk/start-task",1:"/libra/v1/sdk/update-task",2:"/libra/v1/sdk/stop-task",3:"/libra/v1/sdk/list-task",4:"/libra/v1/sdk/polling",5:"/libra/v1/sdk/acknowledge",6:"/"};class er{constructor(r,e,t,i,s,n,c,o){m(this,"videoWidth");m(this,"videoHeight");m(this,"videoFramerate",20);m(this,"videoBitrate",2e3);m(this,"videoGop",30);m(this,"audioSamplerate",Qi.LiveTranscoding_HZ_44100);m(this,"audioBitrate",500);m(this,"audioChannels",1);this.videoWidth=r,this.videoHeight=e,t&&(this.videoFramerate=t),i&&(this.videoBitrate=i),s&&(this.videoGop=s),n&&(this.audioSamplerate=n),c&&(this.audioBitrate=c),o&&(this.audioChannels=o)}}const tr=a=>((16711680&a)>>16)+(65280&a)+((255&a)<<16),_t=(a=0,r)=>{if(r==0)return 0;let e=a/r;return e<0&&(e=0),e>1&&(e=1),e};class Zi{constructor(r,e,t){m(this,"mixMode",Mi.LiveTranscodingSingle);m(this,"singleParam");m(this,"mixParam");r&&(this.mixMode=r),e&&(this.singleParam=e),t&&(this.mixParam=t)}toJson(r,e,t,i,s){const n={appid:e.appId,channelid:e.channelId};if(r===dt.MPU_TASK_TRANSACTION_POLLING||r===dt.MPU_TASK_TRANSACTION_LIST||r===dt.MPU_TASK_TRANSACTION_ACKNOWLEDGE)return r===dt.MPU_TASK_TRANSACTION_ACKNOWLEDGE&&(n.messageid=s),n;if(n.taskid=t,r!==dt.MPU_TASK_TRANSACTION_STOP){if(n.mixmode=this.mixMode,i&&(n.streamurl=i),this.mixMode===Mi.LiveTranscodingSingle){const c=this.singleParam;if(c){n.streamtype=c.streamType,c.sourceType===vi.LiveTranscodingShareScreen?n.sourcetype=Li[c.sourceType]:n.sourcetype=Li[vi.LiveTranscodingCamera];const o=[];c.userId&&o.push(c.userId),n.subspecusers=o}}else if(r===dt.MPU_TASK_TRANSACTION_START||r===dt.MPU_TASK_TRANSACTION_UPDATE){const c=this.mixParam;if(c){c.taskProfile&&(n.taskprofile=sl[c.taskProfile]);const o=c.encodeParam||new er(1280,720);let l=o.videoWidth,d=o.videoHeight;const u={};Object.keys(o).forEach(h=>{const f=o[h];f>0&&(u[h.toLowerCase()]=f)}),u.lowbitratehighquality=0,n.encodeparam=u,n.backgrounds=c.backgrounds.map(h=>h.toJson(l,d)),n.watermarks=c.watermarks.map(h=>h.toJson(l,d)),n.clockwidgets=c.clockWidgets.map(h=>h.toJson(l,d));const p=c.users.map(h=>h.userId);n.subspecusers=[...new Set(p)],n.layouts=[{audiomixcount:c.users.length,panes:c.users.map((h,f)=>h.toJson(f,l,d,c.mediaProcessMode))}],n.layoutids=["0"],n.cropmode=c.cropMode,n.backgroundcolor=tr(c.backgroundColor),n.taskmode=c.mediaProcessMode}}}return n}}const ir=a=>I(this,null,function*(){const r=new Uint8Array(160).fill(170),e=new TextEncoder().encode(a),t=yield window.crypto.subtle.importKey("raw",r,{name:"HMAC",hash:{name:"SHA-1"}},!1,["sign"]),i=yield window.crypto.subtle.sign("HMAC",t,e);return Array.from(new Uint8Array(i)).map(s=>s.toString(16).padStart(2,"0")).join("")});class al{constructor(r){m(this,"authInfo");m(this,"slsReporter");this.slsReporter=r}doRequest(r,e){var c;const t=this.authInfo;if(!t)return Promise.reject(xt.LiveTranscodingErrorInvalidParam);const i=rl[r],s={appid:t.appId,userid:t.userId,channelid:t.channelId,timestamp:t.timestamp,token:t.token,nonce:t.nonce?t.nonce:"",requestid:Le.createCallid(),tokensid:!1,session:(c=t.sessionId)!=null?c:Le.createCallid()},n=Object.keys(s).map(o=>`${o}=${encodeURIComponent(s[o])}`).join("&");return fetch(`https://gw.rtn.aliyuncs.com${i}?${n}`,{method:"POST",headers:{"Content-Type":"application/json; charset=UTF-8"},body:JSON.stringify(e)}).then(o=>o.status!==200?(this.slsReporter.reportTranscodingError(o.status,e.taskid||""),Promise.reject(new U(B.ERR_INNER,`transcoding request failed, status: ${o.status}`))):o).catch(o=>Promise.reject(new U(B.ERR_INNER,`transcoding request failed, err: ${o.message}`)))}setAuthInfo(r){this.authInfo=r}clear(){this.authInfo=void 0}startPublishLiveStream(r,e){return I(this,null,function*(){if(!this.authInfo)return Promise.reject(xt.LiveTranscodingErrorInvalidParam);const t=yield ir(r.split("?")[0]),i=dt.MPU_TASK_TRANSACTION_UPDATE,s=e.toJson(i,this.authInfo,t,r);return this.doRequest(i,s)})}startPublishLiveStreamWithTaskId(r,e){return I(this,null,function*(){if(!this.authInfo)return Promise.reject(xt.LiveTranscodingErrorInvalidParam);const t=dt.MPU_TASK_TRANSACTION_UPDATE,i=e.toJson(t,this.authInfo,r);return this.doRequest(t,i)})}updatePublishLiveStream(r,e){return I(this,null,function*(){if(!this.authInfo)return Promise.reject(xt.LiveTranscodingErrorInvalidParam);const t=yield ir(r.split("?")[0]),i=dt.MPU_TASK_TRANSACTION_UPDATE,s=e.toJson(i,this.authInfo,t,r);return this.doRequest(i,s)})}updatePublishLiveStreamWithTaskId(r,e){return I(this,null,function*(){if(!this.authInfo)return Promise.reject(xt.LiveTranscodingErrorInvalidParam);const t=dt.MPU_TASK_TRANSACTION_UPDATE,i=e.toJson(t,this.authInfo,r);return this.doRequest(t,i)})}stopPublishLiveStream(r){return I(this,null,function*(){if(!this.authInfo)return Promise.reject(xt.LiveTranscodingErrorInvalidParam);const e=yield ir(r.split("?")[0]),t=dt.MPU_TASK_TRANSACTION_STOP,i=new Zi().toJson(t,this.authInfo,e,r);return this.doRequest(t,i)})}stopPublishLiveStreamWithTaskId(r){if(!this.authInfo)return Promise.reject(xt.LiveTranscodingErrorInvalidParam);const e=dt.MPU_TASK_TRANSACTION_STOP,t=new Zi().toJson(e,this.authInfo,r);return this.doRequest(e,t)}refreshAuthInfo(r){this.authInfo&&this.setAuthInfo(X(X({},this.authInfo),r))}}function Un(a,r){const e=new window.XMLHttpRequest;e.open("POST",`${a}?APIVersion=0.6.0`,!0),e.send(r)}function nl(a,r){try{if(r.length>=32768)return void Un(a,r);(function(e,t){return!(!navigator||!navigator.sendBeacon)&&navigator.sendBeacon(`${e}?APIVersion=0.6.0`,t)})(a,r)||Un(a,r)}catch(e){window&&window.console&&typeof window.console.error=="function"&&(console.error(`Failed to log to ali log service because of this exception:
133
133
  `+e),console.error("Failed log data:",a))}}function ol(a,r,e){return t=this,i=null,s=function*(){try{a=a.slice(0,-6);const{data:n,header:c}=yield e.process(a,r),o=new window.XMLHttpRequest;o.open("POST",a,!0);for(let l in c)o.setRequestHeader(l,c[l]);o.send(n)}catch(n){window&&window.console&&typeof window.console.error=="function"&&(console.error(`Failed to log to ali log service because of this exception:
134
- `+n),console.error("Failed log data:",a))}},new Promise((n,c)=>{var o=u=>{try{d(s.next(u))}catch(p){c(p)}},l=u=>{try{d(s.throw(u))}catch(p){c(p)}},d=u=>u.done?n(u.value):Promise.resolve(u.value).then(o,l);d((s=s.apply(t,i)).next())});var t,i,s}class Bn extends Pa{constructor(r){super(Object.assign({},r,{installUnloadHook:e=>{window.addEventListener("beforeunload",()=>{e()})},sendPayload:(e,t)=>{nl(e,t)}}))}useStsPlugin(r){this.getOpt().sendPayload=(e,t)=>{ol(e,t,r)},this.overwriteTransString(r)}}Sr(window,"SLS_Tracker",Bn);const ut=class ut{constructor(){m(this,"ntpClock");this.ntpClock=new J.AliRTS.Clock}static getInstance(r="DEFAULT"){let e=ut.instances.get(r);e||(e=new ut,ut.instances.set(r,e),ut.refCounts.set(r,0));const t=ut.refCounts.get(r)||0;return ut.refCounts.set(r,t+1),e}static releaseInstance(r="DEFAULT"){const e=ut.refCounts.get(r)||0;if(e<=0)return;const t=e-1;t===0?(ut.instances.delete(r),ut.refCounts.delete(r)):ut.refCounts.set(r,t)}now(){return this.ntpClock.now()}};m(ut,"instances",new Map),m(ut,"refCounts",new Map);let Oi=ut;const Hn=(a="DEFAULT")=>Oi.getInstance(a),{BrowserUtil:sr,SystenUtil:Fn}=J.AliRTS,es=6e5,cl={host:"cn-shanghai.log.aliyuncs.com",project:"apsara-video-client",logstore:"client"},ll={host:"ap-southeast-1.log.aliyuncs.com",project:"apsara-video-client-sgp",logstore:"client"},ye=class ye{constructor(r){m(this,"param");m(this,"msgCacheArr",[]);m(this,"index",0);m(this,"ntpClock");m(this,"globalEnv","DEFAULT");m(this,"envKey");m(this,"stopped",!1);this.ntpClock=Hn(r),r&&(this.globalEnv=r),this.envKey=this.globalEnv;const e=ye.instanceCount.get(this.envKey)||0;ye.instanceCount.set(this.envKey,e+1),e===0&&this.startSTSUpdateTask()}get stsData(){return ye.sharedStsData.get(this.envKey)}set stsData(r){r?ye.sharedStsData.set(this.envKey,r):ye.sharedStsData.delete(this.envKey)}get stsExpiration(){return ye.sharedStsExpiration.get(this.envKey)||Date.now()}set stsExpiration(r){ye.sharedStsExpiration.set(this.envKey,r)}createTracker(){if(ye.sharedTrackers.has(this.envKey)){const s=ye.sharedTrackers.get(this.envKey);return this.msgCacheArr.forEach((n,c)=>{var o;s==null||s.send(X(vt(X({},this.param),{stat_log_id:`${((o=this.param)==null?void 0:o.sesid)||"nosession"}-${c}`}),n))}),this.index=this.index+this.msgCacheArr.length,void(this.msgCacheArr=[])}if(!this.stsData||!this.param)return;const r=this.globalEnv==="SEA"?ll:cl,e=new Bn({host:r.host,project:r.project,logstore:r.logstore}),t={accessKeyId:this.stsData.AccessKeyId,accessKeySecret:this.stsData.AccessKeySecret,securityToken:this.stsData.SecurityToken,refreshSTSTokenInterval:es,refreshSTSToken:()=>{this.refreshSTSToken().then(s=>{t.accessKeyId=s.AccessKeyId,t.accessKeySecret=s.AccessKeySecret,t.securityToken=s.SecurityToken}).catch(()=>{})}},i=gs(t);e.useStsPlugin(i),ye.sharedTrackers.set(this.envKey,e),this.msgCacheArr.forEach((s,n)=>{var c;e==null||e.send(X(vt(X({},this.param),{stat_log_id:`${((c=this.param)==null?void 0:c.sesid)||"nosession"}-${n}`}),s))}),this.index=this.index+this.msgCacheArr.length,this.msgCacheArr=[]}startSTSUpdateTask(){return I(this,null,function*(){const r=ye.sharedUpdateTimers.get(this.envKey);r&&clearTimeout(r);try{this.stsData=yield this.refreshSTSToken(),this.createTracker()}catch(t){}const e=setTimeout(()=>{this.startSTSUpdateTask()},es);ye.sharedUpdateTimers.set(this.envKey,e)})}refreshSTSToken(){return I(this,null,function*(){const r=ye.sharedStsData.get(this.envKey),e=ye.sharedStsExpiration.get(this.envKey)||0;if(!r||e<=Date.now()+es){const t=yield this.requestSTSToken(),i=new Date(t==null?void 0:t.Expiration).getTime()||0,s=Date.now()+es;return this.stsExpiration=Math.max(i,s),this.stsData=t,t}return r})}requestSTSToken(){const r=Date.now(),e=`${ye.sharedClientId}|woMMssV6jmyol9fr|${r}`,t={Action:"AssumeSlsRoleV2",AuthInfo:ai.MD5(e).toString(ai.enc.Hex),ClientId:ye.sharedClientId,BusinessType:"rtc",AppVersion:"1.0",Version:"2017-03-14",AuthTimestamp:`${r}`,TerminalType:"web",DeviceModel:"",Format:"JSON",SignatureMethod:"HMAC-SHA1",SignatureVersion:"1.0",Timestamp:$i(r,"isoUtcDateTime")},i=new URLSearchParams(t).toString(),s=`https://${this.globalEnv==="SEA"?"vod.ap-southeast-1.aliyuncs.com":"vod.cn-shanghai.aliyuncs.com"}/?${i}`;return fetch(s).then(n=>n.json()).then(n=>JSON.parse(window.atob(n.SlsAuthResult)))}start(r){this.initParam(r),this.createTracker(),this.startSTSUpdateTask()}stop(){if(this.stopped)return;this.stopped=!0,this.param=void 0,this.msgCacheArr=[],this.index=0;const r=ye.instanceCount.get(this.envKey)||0,e=Math.max(0,r-1);if(ye.instanceCount.set(this.envKey,e),e===0){const t=ye.sharedUpdateTimers.get(this.envKey);t&&(clearTimeout(t),ye.sharedUpdateTimers.delete(this.envKey)),ye.sharedTrackers.delete(this.envKey),ye.sharedStsData.delete(this.envKey),ye.sharedStsExpiration.delete(this.envKey),ye.instanceCount.delete(this.envKey)}Oi.releaseInstance(this.envKey)}sendReport(r){var i;let e;r.tm=Date.now();try{e=JSON.parse(JSON.stringify(X(vt(X({bt:sr.browserName||"unknown",ntptm:this.ntpClock.now(),ntpofs:this.ntpClock.now()-Date.now()},this.param),{stat_log_id:`${((i=this.param)==null?void 0:i.sesid)||"nosession"}-${this.index}`}),r)))}catch(s){}if(!e)return;const t=ye.sharedTrackers.get(this.envKey);t?(t.send(e),this.index++):this.msgCacheArr.push(e)}initParam(r){let e="";try{e=(localStorage==null?void 0:localStorage.getItem("AliRtcUUID"))||"",e||(e=mt(),localStorage==null||localStorage.setItem("AliRtcUUID",e))}catch(t){}this.param||(this.param={apid:r.appId,usrid:r.userId,statsvrs:"0.6.1",evetid:0,sesid:r.sessionId,sessionId:r.sessionId,channelid:r.channelId,usrn:r.userId,osn:Fn.systemName,osv:Fn.systemVersion,deb:sc(),den:ec(),model:ka(),platfm:Ca,udid:e,sdkvrs:_i,acs:"Unknown",cput:Ea(),dm:`${window.location.protocol}//${window.location.host}`,bt:sr.browserName,bv:sr.browserVersion,envir:"PRODUCT",args:"",instid:mt()})}};m(ye,"sharedTrackers",new Map),m(ye,"sharedStsData",new Map),m(ye,"sharedStsExpiration",new Map),m(ye,"sharedUpdateTimers",new Map),m(ye,"sharedClientId",mt()),m(ye,"instanceCount",new Map);let rr=ye;const ke=(a,r=1,e=6e4,t=0)=>{let i=a;return i||(i=0),Math.min(e,Math.max(t,Math.round(i*r)))},ft=(a,r,e=2e7,t=0)=>{let i=r;(!r||r<0||r>1e4)&&(i=1e3);let s=a;return s||(s=0),Math.min(e,Math.max(t,Math.round(s/(i/1e3))))},ci=(a,r)=>{if(r===0||!r)return"0.00";let e=a;return(!e||e<0)&&(e=0),(e/r*100).toFixed(2)},jn=a=>a>=0&&a<=1?ke(Math.floor(32767*a),1,32767):0,Pe=(a,r)=>{var t,i,s;let e=((t=a._last)==null?void 0:t[r])||0;return a.ssrc&&((i=a._last)!=null&&i.ssrc)&&a.ssrc!==((s=a._last)==null?void 0:s.ssrc)&&(e=0),((a==null?void 0:a[r])||0)-e},$n=(a,r)=>ke(Pe(a,r),1e3,1e4),li=(a,r=2e7)=>ke(a,1,r);class dl{constructor(r,e){m(this,"engine");m(this,"logClient");m(this,"authInfo");m(this,"ntpClock");m(this,"globalEnv");m(this,"customFields",{});this.globalEnv=e||"DEFAULT",this.logClient=new rr(e),this.engine=r,this.ntpClock=Hn(this.globalEnv)}setCustomFields(r){this.customFields=X(X({},this.customFields),r)}getCustomField(r){return this.customFields[r]}start(r){this.authInfo=r,this.logClient.start(r)}stop(){this.logClient.stop(),Oi.releaseInstance(this.globalEnv)}reportPublishAudio3A(r,e,t,i){const s={};let n=JSON.parse(i);s.publevel=n.capture_audio_cur_level_db||0,s.eleakrate=n.echo_leak_rate||0,s.playbw=n.render_bandwidth||-1,s.capbw=n.capture_bandwidth||-1,s.diff=n.diff||0,s.leak=n.leak||0,this.log({evetid:10070,traceid:t,calid:r,rmtid:"",args:this.data2String(X({calid:r,tckid:e||"audio3a",rmtid:"",traceid:t},s))})}reportPublishMonitor(r,e,t,i,s){if(!t||s.length<=0)return;const n=t===D.Audio,c={ctm:Math.floor(s[0].timestamp||0),src:s[0].ssrc||"",codec:s[0]._codec||""},o=[],l=[],d=[],u=[],p=[],h=[],f=[],g=[],b=[],S=[],v=[],R=[],_=[],y=[],w=[],A=[],E=[],C=[],P=[],M=[];try{if(s.forEach(x=>{var he,xe,q,Re,Ve,Ee;if(!x||!x.timestamp)return;const K=(he=x._last)!=null&&he.timestamp?x.timestamp-x._last.timestamp:1e3,Q=Pe(x,"bytesSent"),G=Pe(x,"headerBytesSent"),W=ft(ke(Q+G,8,2e7),K);o.push(W);const Z=ft(ke(Q,8,2e7),K);l.push(Z);const te=ft(ke(G,8,2e7),K);d.push(te);const Se=Pe(x,"packetsSent"),L=ft(Se,K);u.push(L);const O=Pe(x,"packetsLost"),N=ft(O,K);p.push(N);const V=ci(O,Se);if(h.push(V),n)(xe=x._source)!=null&&xe.audioLevel&&f.push(jn(x._source.audioLevel)),g.push(0);else{b.push($n(x,"totalEncodeTime")),S.push(li((q=x._source)==null?void 0:q.framesPerSecond,100)),v.push(li((Re=x._source)==null?void 0:Re.framesPerSecond,100)),R.push(li(x.framesPerSecond,100));const Ne=Pe(x,"framesEncoded");_.push(ft(Ne,K,100)),y.push(li((Ve=x._source)==null?void 0:Ve.height,4400)),w.push(li((Ee=x._source)==null?void 0:Ee.width,7700)),A.push(li(x.frameHeight,4400)),E.push(li(x.frameWidth,7700));const ve=Pe(x,"totalPacketSendDelay");C.push(ke(ve,1/(O||1),2e3));const we=Pe(x,"qpSum");P.push(ke(we,1/(x.framesPerSecond||1),51)),M.push(0)}}),c.sbr=o.join(","),c.mbrs=l.join(","),c.pbrs=d.join(","),c.ps=u.join(","),c.pl=p.join(","),c.plr=h.join(","),n){const x=(i==null?void 0:i.getSettings().sampleRate)||0;c.ailevel=f.join(","),c.arpc=g.join(","),c.arsr=x,c.aesr=x,c.publevel=-90,c.rawlevel=-90}else c.em=b.join(","),c.cfps=S.join(","),c.ifps=v.join(","),c.sfps=R.join(","),c.efps=_.join(","),c.ih=y.join(","),c.iw=w.join(","),c.sh=A.join(","),c.sw=E.join(","),c.sd=C.join(","),c.aqp=P.join(","),c.caf=M.join(","),c.can=M.join(","),c.cav=l.join(","),c.ifimax=M.join(","),c.ifimin=M.join(","),c.efimax=M.join(","),c.efimin=M.join(","),c.sfimax=M.join(","),c.sfimin=M.join(","),c.apsnr=M.join(",")}catch(x){}this.log({evetid:10070,traceid:e,calid:r,rmtid:"",args:this.data2String(X({calid:r,tckid:t,rmtid:"",traceid:e},c))})}reportSubscribeMonitor(r,e,t,i,s){if(!i||!s||s.length<=0)return;const n=i===D.Audio,c={ctm:Math.floor(s[0].timestamp||0),src:s[0].ssrc||"",codec:s[0]._codec||""},o=[],l=[],d=[],u=[],p=[],h=[],f=[],g=[],b=[],S=[],v=[],R=[],_=[],y=[],w=[],A=[],E=[],C=[],P=[],M=[],x=[],K=[],Q=[],G=[],W=[],Z=[],te=[],Se=[],L=[],O=[],N=[],V=[],he=[],xe=[];try{s.forEach(q=>{var me,qe;if(!q||!q.timestamp)return;const Re=(me=q._last)!=null&&me.timestamp?q.timestamp-q._last.timestamp:1e3,Ve=Pe(q,"bytesReceived"),Ee=Pe(q,"headerBytesReceived"),Ne=ft(ke(Ve+Ee,8,2e7),Re);o.push(Ne);const ve=ft(ke(Ve,8,2e7),Re);l.push(ve);const we=ft(ke(Ee,8,2e7),Re);d.push(we);const pe=Pe(q,"packetsReceived"),Oe=ft(pe,Re);u.push(Oe);const Te=Pe(q,"packetsLost"),Ye=ft(Te,Re);p.push(Ye);const ht=ci(Te,pe);h.push(ht);const le=Pe(q,"jitterBufferDelay"),ne=Pe(q,"jitterBufferEmittedCount");if(q.jitterBufferDelay&&q.jitterBufferEmittedCount){const Y=ke(le,1e3/ne,1e4);f.push(Y)}else f.push(0);const ie=Pe(q,"fecPacketsReceived");R.push(ci(ie,pe));const Ae=Pe(q,"retransmittedPacketsReceived"),Fe=pe+Te-Ae;if(b.push(ci(pe-Ae,Fe)),S.push(ci(Te,Fe)),g.push(ci(Ae,Fe)),v.push(Fe),he.push(0),xe.push(""),n){y.push(jn(q.audioLevel));const Y=((Be,Tt)=>{var Ot,Ct,ei;return(((Ot=Be==null?void 0:Be._source)==null?void 0:Ot[Tt])||0)-(((ei=(Ct=Be==null?void 0:Be._last)==null?void 0:Ct._source)==null?void 0:ei[Tt])||0)})(q,"synthesizedSamplesEvents");w.push(Y);const Ue=$n(q,"synthesizedSamplesDuration");A.push(Ue);const pt=ci(Ue,Re);_.push(pt),E.push(0)}else{const Y=(qe=q._last)!=null&&qe.totalInterFrameDelay?q.totalInterFrameDelay-q._last.totalInterFrameDelay:0;C.push(ke(Y,1e3/(q.framesDecoded||30),500)),P.push(ke(q.framesPerSecond,1,100)),M.push(Pe(q,"framesReceived")),V.push(Pe(q,"framesRendered")),x.push(ke(q.frameHeight,1,4400)),K.push(ke(q.frameWidth,1,7700));const Ue=Pe(q,"totalProcessingDelay");Q.push(ke(Ue,1e3/(q.framesDecoded||30),12e4));const pt=Pe(q,"nackCount");W.push(pt);const Be=Pe(q,"pliCount");G.push(Be);const Tt=Pe(q,"qpSum");Z.push(ke(Tt,1/(q.framesPerSecond||1),51)),te.push(ke(q.framesDropped));const Ot=Pe(q,"totalFreezesDuration");Se.push(ke(Ot,1e3,3e4));const Ct=Pe(q,"jitterBufferEmittedCount"),ei=Pe(q,"jitterBufferDelay");ei&&Ct?L.push(ke(ei,1e3/Ct,3e4)):L.push(0);const Ui=Pe(q,"jitterBufferTargetDelay");Ui&&Ct?O.push(ke(Ui,1e3/Ct,3e4)):O.push(0);const rs=Pe(q,"jitterBufferMinimumDelay");rs&&Ct?N.push(ke(rs,1e3/Ct,3e4)):N.push(0)}}),c.rbr=o.join(","),c.mbrs=l.join(","),c.pbrs=d.join(","),c.pr=u.join(","),c.pl=p.join(","),c.plr=h.join(","),c.jd=f.join(","),c.fecr=R.join(","),c.retransr=g.join(","),c.baser=b.join(","),c.basel=S.join(","),c.recoverr=he.join(","),c.alll=S.join(","),c.totalc=v.join(","),n?(c.er=_.join(","),c.aolevel=y.join(","),c.asrc=E.join(","),c.scnt=w.join(","),c.sdura=A.join(",")):(c.dm=C.join(","),c.dfps=P.join(","),c.rfps=M.join(","),c.rh=x.join(","),c.rw=K.join(","),c.fpt=xe.join(","),c.ns=W.join(","),c.pliss=G.join(","),c.aqp=Z.join(","),c.ofimax=he.join(","),c.ofimin=he.join(","),c.dfimax=he.join(","),c.dfimin=he.join(","),c.rfimax=he.join(","),c.rfimin=he.join(","),c.vrstutter=Se.join(","),c.cdm=L.join(","),c.tdm=O.join(","),c.pdm=N.join(","),c.ofps=V.join(","),c.dfbd=te.join(","))}catch(q){}this.log({evetid:10080,traceid:t,rmtid:e,calid:r,new_args:_e.getInstance().getSummary(),args:this.data2String(X({calid:r,rmtid:e,tckid:i,traceid:t},c))})}reportNetworkMonitor(r){if(r.length<=0)return;const e=[],t=[],i=[],s=[],n=[],c=[],o=[],l=[],d=[],u=[];r.forEach((h,f)=>{var v,R,_;if(!h.timestamp)return;const g=(v=h._last)!=null&&v.timestamp?h.timestamp-h._last.timestamp:1e3;e.push(ke(h.currentRoundTripTime,1e3)),t.push(ke(h.availableOutgoingBitrate,8,2e8));const b=(h.bytesSent||0)-(((R=h._last)==null?void 0:R.bytesSent)||0),S=(h.bytesReceived||0)-(((_=h._last)==null?void 0:_.bytesReceived)||0);i.push(ft(ke(b,8,2e7),g,25e6)),s.push(ft(ke(S,8,2e7),g,25e6)),n.push(0),c.push(0),f%5==0&&(o.push(""),l.push(""),d.push(""),u.push(""))});const p={ctm:Math.floor(r[0].timestamp||0),rtt:e.join(","),bsps:i.join(","),brps:s.join(","),cpu:o.join(","),mem:l.join(","),sysmem:d.join(","),systotalmem:u.join(","),audioonly:this.engine.isAudioOnly()?1:0};this.log({evetid:10071,args:this.data2String(X({asb:t.join(","),abms:n.join(","),vbms:c.join(",")},p))}),this.log({evetid:10081,args:this.data2String(X({},p))})}reportLoopAudioDelay(r,e){var f;const{AIAgent:t={},AIGrtn:i={},AIPub:s={},AISub:n={},pub:c={},sub:o={},grtn:l={}}=e||{};if(Object.keys(t).length===0)return;let d=0;d=Object.keys(l).length?(c.vTotalCost||0)+(c.upRTTHalf||0)+(l.totalCost||0)+(o.downRTTHalf||0)+(o.vTotalCost||0):(c.vEncPlugCost||0)+((c.timestampRecv||0)-(c.timestamp||0))+(o.vJitterBufferDelay||0)+(o.vDecPlugCost||0);const u={};let p=0;for(let g=0;g<10;g++){const b=`ngxRtcSeiCumulativeDelayKeyInternalRttHalf_${g}`,S=`ngxRtcSeiCumulativeDelayKeyGrtnNodeBefPacer_${g}`,v=`ngxRtcSeiCumulativeDelayKeyGrtnNodePacerCost_${g}`;if(!l.hasOwnProperty(b))break;p+=l[b]||0,p+=l[S]||0,p+=l[v]||0,u[`_gnd${g}`]=`gnd[${g}]: {${this.data2String({gnirh:l[b]||0,gnbp:l[S]||0,gnpc:l[v]||0})}}`}const h={};for(let g=0;g<10;g++){const b=`aigrtninternalrtthalf_${g}`,S=`aigrtnbeforepacer_${g}`,v=`aigrtnpacercost_${g}`;if(!i.hasOwnProperty(b))break;h[`_lgnd${g}`]=`lgnd[${g}]: {${this.data2String({gnirh:i[b]||0,gnbp:i[S]||0,gnpc:i[v]||0})}}`}this.log({evetid:10073,args:this.data2String(vt(X({tdlms:d+(t.aiagenttotalcost||0),_:`aiqud:{${this.data2String(vt(X({uid:((f=this.authInfo)==null?void 0:f.userId)||"",sid:s.aAIClientScentenceId||0,quct:65535*(s.aAIClientQuestionTimestampHEAD||0)+(s.aAIClientQuestionTimestampTAIL||0),anct:65535*(s.aAIClientAnswerTimestampHEAD||0)+(s.aAIClientAnswerTimestampTAIL||0),casc:s.aAIClientSourceCost||0,camc:s.aAIClientMixerCost||0,caec:s.aAIClientEncoderCost||0,cantc:s.aIClientNetsdkThrCost||0,caqtc:s.aIClientQosThrCost||0,capc:s.aIClientPacerCost||0,cuphr:s.aIClientUpRTTHalf||0},h),{qgac:0,ldhr:l.ngxRtcSeiCumulativeDelayKeyDownRttHalf_0||0,larc:n.aAILinuxReceiveCost||0,lanqc:n.aAILinuxNeteqCost||0,larsc:n.aAILinuxRemoteSourceCost||0,lapmc:n.aAILinuxPlayMixerCost||0,lapc:n.aAILinuxPlayCost||0,lsdnc:n.aIClinetSmartDenoise||0,asrc:t.aiasrcost||0,llmc:t.aillmcost||0,ttsc:t.aittscost||0,aamc:t.aimutecost||0,aatc:t.aiagenttotalcost||0}))}};`,ssrc:r,tpd:0,scc:s.aAIClientSourceCost||0,mxc:s.aAIClientMixerCost||0,encc:s.aAIClientEncoderCost||0,netc:s.aIClientNetsdkThrCost||0,qostc:s.aIClientQosThrCost||0,pacerc:s.aIClientPacerCost||0,uphr:s.aIClientUpRTTHalf||0},u),{agac:p,dnhr:o.downRTTHalf||0,tsd:o.vTotalCost||0,rcc:n.aAILinuxReceiveCost||0,nqc:n.aAILinuxNeteqCost||0,rscc:n.aAILinuxRemoteSourceCost||0,plmxc:n.aAILinuxPlayMixerCost||0,plc:n.aAILinuxPlayCost||0,dvd:0}))})}reportCumuAudioDelay(r,e){const{pub:t={},sub:i={},grtn:s={}}=e||{};let n=0;n=Object.keys(s).length?(t.vTotalCost||0)+(t.upRTTHalf||0)+(s.totalCost||0)+(i.downRTTHalf||0)+(i.vTotalCost||0):(t.vEncPlugCost||0)+((t.timestampRecv||0)-(t.timestamp||0))+(i.vJitterBufferDelay||0)+(i.vDecPlugCost||0);const c={};let o=0;for(let l=0;l<10;l++){const d=`ngxRtcSeiCumulativeDelayKeyInternalRttHalf_${l}`,u=`ngxRtcSeiCumulativeDelayKeyGrtnNodeBefPacer_${l}`,p=`ngxRtcSeiCumulativeDelayKeyGrtnNodePacerCost_${l}`;if(!s.hasOwnProperty(d))break;o+=s[d]||0,o+=s[u]||0,o+=s[p]||0,c[`_gnd${l}`]=`gnd[${l}]: {${this.data2String({gnirh:s[d]||0,gnbp:s[u]||0,gnpc:s[p]||0})}}`}this.log({evetid:10074,args:this.data2String(vt(X({ssrc:r,tpd:n,scc:(t==null?void 0:t.aSourceCCost)||0,mxc:(t==null?void 0:t.aMixerCost)||0,encc:(t==null?void 0:t.aEncodeCCost)||0,netc:(t==null?void 0:t.netsdkThrCost)||0,qostc:(t==null?void 0:t.qosThrCost)||0,pacerc:(t==null?void 0:t.pacerCost)||0,uphr:(t==null?void 0:t.upRTTHalf)||0},c),{agac:o,dnhr:(i==null?void 0:i.downRTTHalf)||0,tsd:(i==null?void 0:i.vTotalCost)||0,rcc:0,nqc:0,rscc:0,plmxc:0,plc:0,device_delay:0,psdkt:0,pub_sdk_version:_i}))})}reportCumuVideoDelay(r,e){const{pub:t={},sub:i={},grtn:s={}}=e||{};let n=0;n=Object.keys(s).length?(t.vTotalCost||0)+(t.upRTTHalf||0)+(s.totalCost||0)+(i.downRTTHalf||0)+(i.vTotalCost||0):(t.vEncPlugCost||0)+((t.timestampRecv||0)-(t.timestamp||0))+(i.vJitterBufferDelay||0)+(i.vDecPlugCost||0);const c={};let o=0;for(let l=0;l<10;l++){const d=`ngxRtcSeiCumulativeDelayKeyInternalRttHalf_${l}`,u=`ngxRtcSeiCumulativeDelayKeyGrtnNodeBefPacer_${l}`,p=`ngxRtcSeiCumulativeDelayKeyGrtnNodePacerCost_${l}`;if(!s.hasOwnProperty(d))break;o+=s[d]||0,o+=s[u]||0,o+=s[p]||0,c[`_gnd${l}`]=`vgnd[${l}]: {${this.data2String({vgnirh:s[d]||0,vgnbp:s[u]||0,vgnpc:s[p]||0})}}`}this.log({evetid:10075,args:this.data2String(vt(X({vssrc:r,valld:n,vcdc:(t==null?void 0:t.capDeviceCost)||0,vpec:(t==null?void 0:t.pushExtCost)||0,vcpc:(t==null?void 0:t.capPlugCost)||0,vptc:(t==null?void 0:t.prepThrCost)||0,vppc:(t==null?void 0:t.prepPlugCost)||0,vdptc:(t==null?void 0:t.dispThrCost)||0,vdppc:(t==null?void 0:t.dispPlugCost)||0,vetc:(t==null?void 0:t.vEncThrCost)||0,vepc:(t==null?void 0:t.vEncPlugCost)||0,vntc:(t==null?void 0:t.netsdkThrCost)||0,vqtc:(t==null?void 0:t.qosThrCost)||0,vvpac:(t==null?void 0:t.pacerCost)||0,vuphr:(t==null?void 0:t.upRTTHalf)||0},c),{vagac:o,vdnhr:(i==null?void 0:i.downRTTHalf)||0,vrc:(i==null?void 0:i.vAssemblyCost)||0,vstc:0,vfbc:i.vJitterBufferDelay||0,vdtc:(i==null?void 0:i.vDecPlugCost)||0,vdvpc:(i==null?void 0:i.vDecPlugCost)||0,vrtc:0,vrpc:0}))})}reportJoin(r,e,t=""){var u,p;const{start:i,rs:s=0,re:n=0}=e,c=Date.now()-i,o=n-s;let l=0;s&&(l=s-i);let d=0;n&&(d=n-s),this.log({evetid:10010,args:this.data2String({sesid:((u=this.authInfo)==null?void 0:u.sessionId)||"",joitm:c,rslt:r,gslbtm:0,dnstm:0,avcftm:0,gslbrslt:0,dnsrslt:0,avcfrslt:0,mode:2,jrtc:o,usrn:(p=this.authInfo)==null?void 0:p.userId,mgt:"cdn",cttc:l,iptc:d,ndn:1,gslbloc:1,ccag:0,ucag:0,cpg:0,upg:0,tid:t})})}reportJoinConnection(r){this.log({evetid:20002,args:this.data2String(X({transretrynum:0,ldnstc:0,tcptc:0,ssltc:0,url:""},r))})}reportLeave(r,e,t){this.log({evetid:10020,args:this.data2String({lvetm:r,rslt:e,tid:t})})}reportPublish(r,e,t,i,s,n,c,o,l,d,u,p){this.log({evetid:r?10032:10030,calid:t,tm:p,args:this.data2String({calid:t,url:e,isvl:i?1:0,isvs:s?1:0,isvss:n?1:0,isaudio:c?1:0,rslt:o,tid:"123",pubtm:Date.now()-u,pctid:l,pubtid:d,isvp:0,isarecording:0,isad:0,isdc:0,pubretry:0,pbrttimes:0})})}reportPublishFirstPacket(r,e,t,i,s,n,c,o,l){const d=Date.now();this.log({evetid:r?10033:10031,calid:e,args:this.data2String({calid:e,fpst:d-t,tckid:n,est:t,pctid:c,pubtid:o,totaltm:d-s,jorm:l===Dt.JOIN_CHANNEL?1:0,cptc:0,sptc:i-t,iptc:0,ipc2fptc:0,dctc:0,patc:0})})}reportUnpublish(r,e,t,i){var s;this.log({evetid:10040,args:this.data2String({calid:r,unpubtm:e,rslt:t,tid:i,sesid:((s=this.authInfo)==null?void 0:s.sessionId)||""})})}reportSubscribe(r,e,t,i,s,n,c,o,l,d,u){this.log({evetid:10050,calid:r,rmtid:e,tm:u,args:this.data2String(X({calid:r,rmtid:e,isvl:t?1:0,isvs:i?1:0,isvss:s?1:0,isaudio:n?1:0,rslt:c,tid:o,subtm:l,isvp:0,isaplaying:0,isad:0,isdc:0,subretry:0,sbrttimes:0},d))})}reportSubscribeFirstPacket(r,e,t,i,s){this.log({evetid:r?10054:10051,calid:e,rmtid:t,args:this.data2String(X({calid:e,rmtid:t,tckid:i,cptc:0,iptc:0,ipc2fptc:0,dctc:0,patc:0},s))})}reportSubscribeFirstFrame(r,e,t,i,s){this.log({evetid:r?10055:10052,calid:e,rmtid:t,args:this.data2String(X({calid:e,rmtid:t,tckid:i},s))}),this.log({evetid:r?10058:10057,args:this.data2String(X({calid:e,rmtid:t,tckid:i},s))})}reportUnsubscribe(r,e,t,i,s){this.log({evetid:10060,calid:r,args:this.data2String({calid:r,rmtid:e,unsubtm:t,rslt:i,tid:s})})}reportMute(r,e,t){this.log({evetid:11030,args:this.data2String({calid:r,rmtid:"",enable:e?1:0,mt:t})})}reportRoleUpdate(r,e){this.log({evetid:11040,args:this.data2String({or:r||"",nr:e,ctm:Date.now(),rslt:0})})}reportRoleUpdateResult(r,e,t,i){this.log({evetid:11041,args:this.data2String({or:r||"",nr:e,ctm:t,rslt:i})})}reportVideoProfile(r){this.log({evetid:20074,args:this.data2String({pf:r,tckid:"sophon_camera_large"})})}reportScreenProfile(r){this.log({evetid:20074,args:this.data2String({pf:r,tckid:"sophon_screenshare"})})}reportError(r){this.log({evetid:10091,args:this.data2String({rslt:(r==null?void 0:r.code)||-1})})}reportWarning(r){this.log({evetid:10092,args:this.data2String({rslt:-1,errmsg:r})})}reportRoomServerEvent(r,e,t,i){this.log({evetid:20005,args:this.data2String({calid:"",rmtid:"",rt:r?0:1,dr:r?"s":"r",mt:e,ri:t,cs:1,srt:Date.now(),rspc:(i==null?void 0:i.code)||"",mc:JSON.stringify(i)})})}reportTranscodingError(r,e){this.log({evetid:10101,args:this.data2String({rslt:r,taskid:e})})}reportBye(r){var e;this.log({evetid:10093,args:this.data2String({rslt:r,sesid:((e=this.authInfo)==null?void 0:e.sessionId)||""})})}reportAudio(r,e,t){var i;this.log({evetid:80013,args:this.data2String({rslt:r?-1:0,adm:1,adt:0,adr:r?2:0,acms:e,adrpn:t})}),this.log({evetid:80014,args:this.data2String({sesid:((i=this.authInfo)==null?void 0:i.sessionId)||"",rslt:r?-1:0,adm:1,adt:0,adr:r?2:0,acms:e,adrpn:t})})}reportScreen(r,e){var t,i,s,n;this.log({evetid:90013,args:this.data2String({rslt:r?-1:0,vcms:e,vde:(t=r==null?void 0:r.code)!=null?t:-1,sesid:((i=this.authInfo)==null?void 0:i.sessionId)||""})}),this.log({evetid:90014,args:this.data2String({rslt:r?-1:0,vcms:e,vde:(s=r==null?void 0:r.code)!=null?s:-1,sesid:((n=this.authInfo)==null?void 0:n.sessionId)||""})})}reportScreenStop(r){this.log({evetid:90019,args:this.data2String({rslt:r?r.code||-1:0})}),this.log({evetid:90020,args:this.data2String({rslt:r?r.code||-1:0})})}reportSwitchCamera(r){var e;this.log({evetid:90025,args:this.data2String({rslt:0,td:r,sesid:((e=this.authInfo)==null?void 0:e.sessionId)||""})})}reportPublishProfile(r,e){this.log({evetid:10201,args:this.data2String(X({tckid:r},e))})}reportSDKCreated(r){this.log({evetid:70011,createtm:Date.now()-r,tm:r})}reportJoinInvoked(r){this.log({evetid:70012,jnnonce:r.nonce||"",jntoken:r.token||"",jntm:r.timestamp||""})}reportJoinResult(r){this.log({evetid:70013,rslt:r?r.code||-1:0,dnsrslt:0})}reportSTSResult(r,e){this.log({evetid:70014,rslt:r,asty:1,reqtm:Date.now()-e})}reportLeaveInvoked(){this.log({evetid:70015})}reportSEIMessage(r,e,t,i,s){this.log({evetid:40301,args:this.data2String({tm:Date.now(),sei_pt:r,sei_len:e,sei_rep:t,sei_delay:i,sei_key:s})})}reportConnectionLatencyEvent(r,e,t,i,s,n,c=!1){const o={ageniid:this.getCustomField("ageniid")},l=X({tm:s||Date.now(),ntptm:n||this.ntpClock.now(),stage:r,status:e,calid:t,tckid:i,cltp:1,http:c?1:0},o);this.log({evetid:12001,args:this.data2String(l)})}log(r){r&&(r.tm=r.tm||new Date().getTime(),T.debug("[ConsoleLogger]","log",r),this.logClient.sendReport(r))}data2String(r){let e="";for(let t in r)e.length&&(e+="&"),e+=t.startsWith("_")?r[t]:`${t}=${r[t]}`;return e}}const Ri=class Ri extends oe{constructor(e){super();m(this,"ws");m(this,"socketStatus",0);m(this,"wsUrl","");m(this,"lastConnectStartTime",0);m(this,"connectRetryMinTimeGap",5e3);m(this,"shouldReconnect",!0);m(this,"connectRetryCount",0);m(this,"gotErr",!1);m(this,"closedByInvoke",!0);m(this,"isReconnecting",!1);m(this,"networkAvailableChecked",!0);m(this,"reconnectTimeoutId",0);e&&(this.connectRetryMinTimeGap=e),this.onOpen=this.onOpen.bind(this),this.onMessage=this.onMessage.bind(this),this.onError=this.onError.bind(this),this.onClose=this.onClose.bind(this)}get connectUrl(){return this.wsUrl}get connectStatus(){return this.socketStatus}start(e){this.wsUrl=e,this.initWebSocket()}send(e){return!(!this.ws||this.socketStatus!==2)&&(this.ws.send(JSON.stringify(e)),!0)}close(){this.closedByInvoke=!0,this.reconnectTimeoutId&&(clearTimeout(this.reconnectTimeoutId),this.reconnectTimeoutId=0),this.uninitWebsocket()}markShouldReconnect(e){this.shouldReconnect=e}reconnect(){this.reconnectTimeoutId&&(clearTimeout(this.reconnectTimeoutId),this.reconnectTimeoutId=0),this.emit("onWillReconnect"),this.shouldReconnect?(this.emit("onReconnectStart"),this.isReconnecting=!0,this.initWebSocket()):this.emit("onConnectFail")}onOpen(e){T.info(`[${Ri.logName}]`,"onOpen"),this.socketStatus=2,this.connectRetryCount=0,this.shouldReconnect=!0,this.networkAvailableChecked=!1,this.closedByInvoke=!1,this.gotErr=!1,this.isReconnecting=!1,this.emit("onOpen",e)}onMessage(e){this.emit("onMessage",e)}onError(e){this.isReconnecting&&this.emit("onReconnectFail",e),this.emit("onError",e),this.isReconnecting=!1,this.socketStatus!==2&&Le.isNetworkAvailable().then(t=>{t&&console.error(Ri.logName,"onError, Network is available, token may be invalid")})}onClose(e){return I(this,null,function*(){if(this.closedByInvoke)this.socketStatus=0;else{if(T.info(`[${Ri.logName}]`,`onClose, code: ${e.code}, reason: ${e.reason}, status: ${status}, retryCount: ${this.connectRetryCount}`),(yield Le.isNetworkAvailable())&&!this.networkAvailableChecked)return this.reconnect(),void(this.networkAvailableChecked=!0);if(this.connectRetryCount||this.emit("onNetworkError"),!this.reconnectTimeoutId){this.connectRetryCount+=1;const t=Date.now()-this.lastConnectStartTime;t>=this.connectRetryMinTimeGap?this.reconnect():this.reconnectTimeoutId=window.setTimeout(()=>{this.reconnect()},this.connectRetryMinTimeGap-Math.max(0,t))}this.socketStatus=0,this.emit("onClose",e)}})}initWebSocket(){this.uninitWebsocket(),this.socketStatus=1,this.lastConnectStartTime=Date.now(),this.ws=new WebSocket(this.wsUrl),this.ws.addEventListener("open",this.onOpen),this.ws.addEventListener("message",this.onMessage),this.ws.addEventListener("error",this.onError),this.ws.addEventListener("close",this.onClose)}uninitWebsocket(){this.reconnectTimeoutId&&(clearTimeout(this.reconnectTimeoutId),this.reconnectTimeoutId=0),this.ws&&(this.ws.removeEventListener("open",this.onOpen),this.ws.removeEventListener("message",this.onMessage),this.ws.removeEventListener("error",this.onError),this.ws.removeEventListener("close",this.onClose),this.ws.readyState!==WebSocket.CLOSED&&this.ws.close(),this.ws=void 0,this.socketStatus=0)}};m(Ri,"logName","Socket");let ar=Ri;const St=class St extends oe{constructor(e,t,i,s,n,c){super();m(this,"authInfo");m(this,"userName");m(this,"channelProfile");m(this,"clientRole");m(this,"slsReporter");m(this,"wsClient");m(this,"packageCreator");m(this,"keepAliveTimer",0);m(this,"lastKeepAliveResponseTime",0);m(this,"maxConnectRetryDuration",90);m(this,"packageCache",new Map);m(this,"isFirstConnect",!0);m(this,"aliveChecker",0);m(this,"reconnectData");m(this,"joinChannelExtraData");m(this,"onOpen",()=>{if(T.info(`[${St.logName}] onOpen`),this.isFirstConnect){let e=this.packageCreator.createJoinPackage(this.joinChannelExtraData);e.data.configure={channelprofile:this.channelProfile},this.channelProfile!==Ut.AliRtcSdkInteractiveLive&&this.channelProfile!==Ut.AliRtcSdkInteractiveWithLowLatencyLive||(e.data.configure.clientrole=this.clientRole),this.sendPackage(e)}else{this.stopKeepAlive();const e=this.packageCreator.createReconnectPackage(this.reconnectData);this.sendPackage(e)}});m(this,"onMessage",e=>{try{let t=JSON.parse(e.data);this.packageCache.delete(t.tid),this.onRecvMessage(t),t!=null&&t.msgtype&&(t==null?void 0:t.msgtype)!==$e.KEEPALIVE&&this.slsReporter.reportRoomServerEvent(!1,t.msgtype,t.tid,t)}catch(t){T.warn(`[${St.logName}] onMessage err`,t,e)}});m(this,"onError",e=>{T.warn(`[${St.logName}] onError`,e),this.isFirstConnect&&this.onConnectFail()});m(this,"onConnectFail",()=>{T.warn(`[${St.logName}] onConnectFail`);const e=new U(B.ERR_INNER,"Signaling connect failed.");this.isFirstConnect?this.emit("onJoinChannelResult",e):this.emit("onConnectFail",e)});m(this,"onAuthInvalid",()=>{T.warn(`[${St.logName}] onAuthInvalid`),this.isFirstConnect&&this.emit("onAuthInvalid")});m(this,"onNetworkError",()=>{T.warn(`[${St.logName}] onNetworkError`);const e=new U(B.ERR_INNER,"Network error, signaling connect failed.");this.emit("onNetworkError",e)});m(this,"onClose",e=>{T.info(`[${St.logName}] onClose`,e),this.stopKeepAlive()});m(this,"onWillReconnect",()=>{this.lastKeepAliveResponseTime||(this.lastKeepAliveResponseTime=Date.now()),Date.now()-this.lastKeepAliveResponseTime>1e3*this.maxConnectRetryDuration&&this.wsClient.markShouldReconnect(!1)});m(this,"onReconnectStart",()=>{this.emit("onReconnectStart")});m(this,"onReconnectFail",()=>{this.emit("onReconnectFail",new U(B.ERR_INNER,"signaling reconnect failed."))});this.authInfo=e,this.userName=t,this.packageCreator=new Ki(e,t),this.channelProfile=i,this.clientRole=s,this.slsReporter=n,c&&(this.maxConnectRetryDuration=c),this.wsClient=new ar,this.wsClient.on("onOpen",this.onOpen),this.wsClient.on("onMessage",this.onMessage),this.wsClient.on("onError",this.onError),this.wsClient.on("onClose",this.onClose),this.wsClient.on("onConnectFail",this.onConnectFail),this.wsClient.on("onAuthInvalid",this.onAuthInvalid),this.wsClient.on("onNetworkError",this.onNetworkError),this.wsClient.on("onWillReconnect",this.onWillReconnect),this.wsClient.on("onReconnectStart",this.onReconnectStart),this.wsClient.on("onReconnectFail",this.onReconnectFail)}get retryCount(){return this.wsClient.connectRetryCount}destroy(){this.lastKeepAliveResponseTime=0,this.close()}start(e,t){this.joinChannelExtraData=t,this.wsClient.start(e)}startKeepAlive(){this.keepAliveTimer===0&&(this.keepAliveTimer=window.setInterval(()=>{let e=this.packageCreator.createKeepAlivePackage();this.sendPackage(e)},5e3)),this.checkAlive()}stopKeepAlive(){this.keepAliveTimer!==0&&(clearInterval(this.keepAliveTimer),this.keepAliveTimer=0),this.aliveChecker&&(window.clearTimeout(this.aliveChecker),this.aliveChecker=0)}sendPkgCache(){this.packageCache.forEach(e=>{this.wsClient.send(e)})}leave(){let e=this.packageCreator.createLeavePackage();this.sendPackage(e)}reportStatus(e){let t=this.packageCreator.createStatusPackage(e);this.sendPackage(t)}publish(e){const l=e,{l1ip:t}=l,i=Wt(l,["l1ip"]);let s=this.packageCreator.createPublishPackage();s.data.users=[],s.data.l1ip=t,i.subscribe.signal=this.wsClient.connectUrl;const{tracks:n,resume:c}=i;let o="7.2.9";o&&(o=o.split("-")[0]),n.forEach(d=>{const{codec:u,ssrc:p}=d;d.userdata=JSON.stringify({sdk_version:o,codec:u}),d.ssrc=`${p}`,c&&(d.attr={reason:"reconnect"})}),s.data.users.push(i),this.sendPackage(s)}roleUpdate(e){let t=this.packageCreator.createRoleUpdatePackage();t.data.clientrole=e,this.sendPackage(t)}refreshUrl(e){const t=this.packageCreator.createRefreshUrlPackage();t.data=X(vt(X({},t.data),{sessionid:t.header.sessionid}),e),this.sendPackage(t)}refreshAuthInfo(e){this.authInfo=e,this.packageCreator.refreshAuthInfo(e)}close(){T.info(`[${St.logName}] close`),this.stopKeepAlive(),this.wsClient.off("onOpen",this.onOpen),this.wsClient.off("onMessage",this.onMessage),this.wsClient.off("onError",this.onError),this.wsClient.off("onClose",this.onClose),this.wsClient.off("onConnectFail",this.onConnectFail),this.wsClient.off("onAuthInvalid",this.onAuthInvalid),this.wsClient.off("onNetworkError",this.onNetworkError),this.wsClient.off("onWillReconnect",this.onWillReconnect),this.wsClient.off("onReconnectStart",this.onReconnectStart),this.wsClient.off("onReconnectFail",this.onReconnectFail),this.wsClient.close()}sendPackage(e){[$e.KEEPALIVE,$e.RECONNECT,$e.JOINCHANNEL].includes(e.msgtype)||this.packageCache.set(e.tid,e),this.wsClient.send(e),e.msgtype!==$e.KEEPALIVE&&this.slsReporter.reportRoomServerEvent(!0,e.msgtype,e.tid,e)}updateReconnectData(e){this.reconnectData=e}onKeepAliveRsp(){this.emit("onKeepAliveRsp"),this.lastKeepAliveResponseTime=Date.now(),this.checkAlive()}checkAlive(){window.clearTimeout(this.aliveChecker),this.aliveChecker=window.setTimeout(()=>{T.info(`[${St.logName}] not alive, reconnect`),this.stopKeepAlive(),this.emit("onReconnectStart"),this.wsClient.reconnect()},15e3)}onRecvMessage(e){switch(e.msgtype!==$e.KEEPALIVE&&T.info(`[${St.logName}] recv msg: ${e.msgtype}`),e.msgtype){case $e.JOINCHANNEL:this.onJoinResult(e);break;case $e.KEEPALIVE:this.onKeepAliveRsp();break;case $e.PUBLISH:this.onPublishResult(e);break;case $e.NOTIFYJOIN:this.onNotifyJoin(e);break;case $e.NOTIFYSTATUS:this.onNotifyStatus(e);break;case $e.LEAVECHANNEL:this.onLeaveResult(e);break;case $e.NOTIFYLEAVE:this.onNotifyLeave(e);break;case $e.NOTIFYPUBLISH:this.onNotifyPublish(e);break;case $e.STATUSREPORT:this.onStatusReport(e);break;case $e.BYE:this.onBye(e);break;case $e.ROLEUPDATE:this.onRoleUpdateResult(e);break;case $e.REFRESHURL:this.onRefreshUrlResult(e);break;case $e.RECONNECT:this.onReconnectResult(e);break;default:this.onUnknownMessage(e)}}onJoinResult(e){this.isFirstConnect=!1,this.emit("onJoinChannelResult",e)}onLeaveResult(e){this.emit("onLeaveResult",e.code,e.tid)}onPublishResult(e){this.emit("onPublishResult",e.code,e.tid,e.description)}onRoleUpdateResult(e){this.emit("onRoleUpdateResult",e.code,e.tid,e.description)}onRefreshUrlResult(e){this.emit("onRefreshUrlResult",e)}onReconnectResult(e){if(e.code===200)this.sendPkgCache(),this.startKeepAlive(),this.emit("onReconnectSuccess",e.data.users);else{const t=new U(B.ERR_INNER,`reconnect failed, code: ${e.code};description: ${e.description}`);e.code===403&&(t.code=403),this.emit("onReconnectFail",t),this.close()}}onNotifyJoin(e){let t=this.packageCreator.createResponsePackage(e.tid,e.msgtype);this.wsClient.send(t),e&&e.data&&e.data.users&&this.emit("onNotifyJoin",e.data.users)}onNotifyStatus(e){let t=this.packageCreator.createResponsePackage(e.tid,e.msgtype);this.wsClient.send(t),e.data&&e.data.status&&e.data.status.length&&this.emit("onNotifyStatus",e.data.status)}onNotifyLeave(e){let t=this.packageCreator.createResponsePackage(e.tid,e.msgtype);this.wsClient.send(t),e.data&&e.data.users&&e.data.users.length&&this.emit("onNotifyLeave",e.data.users)}onNotifyPublish(e){let t=this.packageCreator.createResponsePackage(e.tid,e.msgtype);this.wsClient.send(t),e.data&&e.data.users&&e.data.users.length&&this.emit("onNotifyPublish",e.data.users)}onStatusReport(e){this.emit("onStatusReport",e.code,e.tid,e.description)}onBye(e){this.stopKeepAlive(),this.emit("onBye",e.reason,e.description)}onUnknownMessage(e){this.emit("onUnknownMessage",e)}};m(St,"logName","RSMessageCenter");let nr=St;var ul=Object.defineProperty,hl=Object.getOwnPropertyDescriptor,or=(a,r,e,t)=>{for(var i,s=t>1?void 0:t?hl(r,e):r,n=a.length-1;n>=0;n--)(i=a[n])&&(s=(t?i(r,e,s):i(s))||s);return t&&s&&ul(r,e,s),s};const ts=(rt=class extends oe{constructor(e,t,i,s=It.prod){super();m(this,"messageCenter");m(this,"authInfo");m(this,"userName");m(this,"channelProfile");m(this,"clientRole");m(this,"slsReporter");m(this,"reconnectData");m(this,"roomServerUri","");this.channelProfile=e,this.clientRole=t,this.slsReporter=i,this.reconnectData={role:{channelprofile:e,clientrole:t}};const n=s===It.pre?Rt.pre:Rt.prod;this.roomServerUri=`wss://${n}/roomserver/v1/ws`}updateReconnectData(e){var t;this.reconnectData=e,(t=this.messageCenter)==null||t.updateReconnectData(this.reconnectData)}reset(){T.info("[roomsig] reset"),this.messageCenter&&(this.messageCenter.destroy(),this.messageCenter=void 0),this.authInfo=void 0}join(e,t,i,s){return I(this,null,function*(){return new Promise((n,c)=>{const o={};this.authInfo=e,this.userName=t,this.messageCenter=new nr(e,t,this.channelProfile,this.clientRole,this.slsReporter,i),this.initMessageCenter(),this.messageCenter.once("onJoinChannelResult",d=>{var u,p,h;if(T.info(`[${rt.logName}]`,"join result: ",d),o.taskretrynum=((u=this.messageCenter)==null?void 0:u.retryCount)||0,d.code==200){(p=this.messageCenter)==null||p.sendPkgCache(),(h=this.messageCenter)==null||h.startKeepAlive();let f=d.data;f.tid=d.tid,f.users=d.data.users,f.timestamp=d.timestamp,o.est&&(o.joinconnecttc=Date.now()-o.est),this.slsReporter.reportJoinConnection(o),n(f)}else this.reset(),c(this.handleSignalError(d.code,d.reason,B.ERR_JOIN_CHANNEL_FAILED))}),this.messageCenter.once("onAuthInvalid",()=>{this.reset(),c(new U(B.ERR_JOIN_BAD_TOKEN,"join failed because authentication failed"))}),T.info(`[${rt.logName}]`,"start ws connecting roomserver and auto join when connected");const l={appid:this.authInfo.appId,channelid:this.authInfo.channelId,userid:this.authInfo.userId,nonce:this.authInfo.nonce||"",timestamp:this.authInfo.timestamp,token:this.authInfo.token,authtype:"app",tid:mt()};e.role&&(l.tokenrole=e.role),o.est=Date.now(),this.messageCenter.start(this.roomServerUri+"?"+Le.queryingParam(l),s)})})}leave(){return T.info("[roomsig] leave .."),new Promise((e,t)=>{this.messageCenter?(this.messageCenter.on("onLeaveResult",(i,s)=>{T.info(`[${rt.logName}]`,"recv leave response "+i),i===200?(this.updateReconnectData(),this.reset(),e({tid:s})):t(this.handleSignalError(i,"leave error"))}),T.info(`[${rt.logName}]`,"send leave request"),this.messageCenter.leave()):(T.info(`[${rt.logName}]`,"no message center, ok to leave"),e({tid:""}))})}publish(e){return new Promise((t,i)=>{var s;this.messageCenter?(this.messageCenter.once("onPublishResult",(n,c,o)=>{T.info(`[${rt.logName}]`,"recv pubish response "+n),n===200?(this.updateReconnectData(vt(X({},this.reconnectData),{publish:{users:[e]}})),t({tid:c})):i(this.handleSignalError(n,`publish error, ${o}`))}),this.authInfo&&(e.sessionid=(s=this.authInfo.sessionId)!=null?s:""),e.callid||(e.callid=mt()),T.info(`[${rt.logName}]`,"assign callid "+e.callid+" and send publish request"),this.messageCenter.publish(e)):i(this.handleSignalError(-1,"publish error, no message center"))})}roleUpdate(e){return new Promise((t,i)=>{this.messageCenter?(this.messageCenter.on("onRoleUpdateResult",(s,n,c)=>{var o,l;T.info(`[${rt.logName}]`,"recv role update response "+s),s===200?((l=(o=this.reconnectData)==null?void 0:o.role)!=null&&l.clientrole&&(this.reconnectData.role.clientrole=e,this.updateReconnectData(this.reconnectData)),t({tid:n})):i(this.handleSignalError(s,`role update error, ${c}`))}),this.messageCenter.roleUpdate(e)):i(this.handleSignalError(-1,"role update error, no message center"))})}setChannelProfile(e){this.channelProfile=e}refreshUrl(e){return T.info(`[${rt.logName}]`,"refreshUrl .."),new Promise((t,i)=>{this.messageCenter?(this.messageCenter.on("onRefreshUrlResult",s=>{const{code:n,description:c,data:o={}}=s||{};T.info("recv refresh url response "+n),n===200?t(o):i(this.handleSignalError(n,`refresh url error, ${c}`))}),T.info("send refresh url request"),this.messageCenter.refreshUrl(e)):i(this.handleSignalError(-1,"refresh url error, no message center"))})}reportStatus(e){return T.info(`[${rt.logName}]`,"reportStatus "+e),new Promise((t,i)=>{this.messageCenter?(this.messageCenter.once("onStatusReport",(s,n)=>{s===200?t():i(new U(s,n))}),this.messageCenter.reportStatus(e)):i(new U(-1,"No messageCenter"))})}handleSignalError(e,t,i=B.ERR_INNER){return new U(i,`signal error: code - ${e}; description - ${t}`)}refreshAuthInfo(e){return I(this,null,function*(){var t;this.authInfo&&(this.authInfo=e,(t=this.messageCenter)==null||t.refreshAuthInfo(this.authInfo))})}initMessageCenter(){var e,t,i,s,n,c,o,l,d,u,p,h,f;(e=this.messageCenter)==null||e.on("onKeepAliveRsp",()=>{this.emit("onKeepAliveRsp")}),(t=this.messageCenter)==null||t.on("onNotifyJoin",g=>{this.emit("onNotifyJoin",g)}),(i=this.messageCenter)==null||i.on("onNotifyStatus",g=>{this.emit("onNotifyStatus",g)}),(s=this.messageCenter)==null||s.on("onNotifyLeave",g=>{this.emit("onNotifyLeave",g)}),(n=this.messageCenter)==null||n.on("onNotifyPublish",g=>{this.emit("onNotifyPublish",g)}),(c=this.messageCenter)==null||c.on("onBye",(g,b)=>{this.emit("onBye",g,b)}),(o=this.messageCenter)==null||o.on("onReconnectStart",()=>{this.emit("onReconnectStart")}),(l=this.messageCenter)==null||l.on("onReconnectSuccess",g=>{this.emit("onReconnectSuccess",g)}),(d=this.messageCenter)==null||d.on("onReconnectFail",g=>{this.emit("onReconnectFail",g)}),(u=this.messageCenter)==null||u.on("onConnectFail",g=>{this.emit("onConnectFail",g),this.reset()}),(p=this.messageCenter)==null||p.on("onNetworkError",g=>{this.emit("onNetworkError",g)}),(h=this.messageCenter)==null||h.on("onAuthInvalid",()=>{this.emit("onAuthInvalid")}),(f=this.messageCenter)==null||f.on("onUnknownMessage",g=>{this.emit("onUnknownMessage",g)})}},m(rt,"logName","RoomServerSignaling"),rt);or([k()],ts.prototype,"join",1),or([k()],ts.prototype,"publish",1),or([k()],ts.prototype,"roleUpdate",1);let pl=ts;var ml=Object.defineProperty,gl=Object.getOwnPropertyDescriptor;class cr extends oe{constructor(e,t,i,s=It.prod){super();m(this,"signaling");m(this,"authInfo");m(this,"userName");m(this,"channelProfile");m(this,"clientRole");m(this,"env",It.prod);m(this,"maxSignalingReconnectDuration");m(this,"slsReporter");this.channelProfile=e,this.clientRole=t,this.env=s,this.slsReporter=i}reset(){var e;T.info("[signalingmanager] reset"),(e=this.signaling)==null||e.reset(),this.signaling=void 0,this.authInfo=void 0}join(e,t=e.userId,i,s,n){return this.maxSignalingReconnectDuration=i,this.userName=t,new Promise((c,o)=>{this.signaling?o(new U(B.ERR_JOIN_ALREADY_JOINED,"already joined")):(T.info("[signalingmanager] create signaling"),this.signaling=new pl(this.channelProfile,this.clientRole,this.slsReporter,this.env),this.initSignaling(),s&&(s.rs=Date.now()),this.signaling.join(e,t,i,n).then(l=>{this.authInfo=e,s&&(s.re=Date.now()),c(l)}).catch(l=>{this.reset(),o(l)}))})}retryJoin(){const e=this.authInfo;this.reset(),e&&this.join(e,this.userName,this.maxSignalingReconnectDuration)}leave(){return new Promise((e,t)=>{this.signaling?this.signaling.leave().then(i=>{this.reset(),e(i)}).catch(i=>{t(i)}):e({tid:""})})}publish(e){return new Promise((t,i)=>{var s;this.signaling&&this.authInfo?(e.userid=this.authInfo.userId,e.displayname=(s=this.userName)!=null?s:this.authInfo.userId,this.signaling.publish(e).then(n=>{t(n)}).catch(n=>{i(n)})):i(new U(B.ERR_SDK_PUBLISH_NOT_JOIN_CHANNEL,"no signaling"))})}reportStatus(e){return new Promise((t,i)=>{this.signaling?this.signaling.reportStatus(e).then(()=>{t()}).catch(s=>{i(s)}):i(new U(-1,"no signaling"))})}setClientRole(e){return I(this,null,function*(){const t=this.clientRole;if(!this.signaling)return void(this.clientRole=e);const i=Date.now();try{const s=yield this.signaling.roleUpdate(e);return this.slsReporter.reportRoleUpdateResult(t,e,Date.now()-i,0),s}catch(s){this.slsReporter.reportRoleUpdateResult(t,e,Date.now()-i,s.code||-1)}})}setChannelProfile(e){this.signaling?this.signaling.setChannelProfile(e):this.channelProfile=e}refreshUrl(e){return this.signaling?this.signaling.refreshUrl(e):Promise.reject(new U(B.ERR_SDK_INVALID_STATE,"should join first"))}refreshAuthInfo(e){return I(this,null,function*(){var t;try{this.authInfo&&(this.authInfo=X(X({},this.authInfo),e),(t=this.signaling)==null||t.refreshAuthInfo(this.authInfo))}catch(i){throw i}})}initSignaling(){var e,t,i,s,n,c,o,l,d,u,p,h,f,g;(e=this.signaling)==null||e.on("onKeepAliveRsp",this.onKeepAliveRsp.bind(this)),(t=this.signaling)==null||t.on("onNotifyJoin",this.onNotifyJoin.bind(this)),(i=this.signaling)==null||i.on("onNotifyStatus",this.onNotifyStatus.bind(this)),(s=this.signaling)==null||s.on("onNotifyLeave",this.onNotifyLeave.bind(this)),(n=this.signaling)==null||n.on("onNotifyPublish",this.onNotifyPublish.bind(this)),(c=this.signaling)==null||c.on("onBye",this.onBye.bind(this)),(o=this.signaling)==null||o.on("onReconnectStart",this.onReconnectStart.bind(this)),(l=this.signaling)==null||l.on("onReconnectSuccess",this.onReconnectSuccess.bind(this)),(d=this.signaling)==null||d.on("onReconnectFail",this.onReconnectFail.bind(this)),(u=this.signaling)==null||u.on("onConnectFail",this.onConnectFail.bind(this)),(p=this.signaling)==null||p.on("onNetworkError",this.onNetworkError.bind(this)),(h=this.signaling)==null||h.on("onAuthInvalid",this.onAuthInvalid.bind(this)),(f=this.signaling)==null||f.on("onError",this.onError.bind(this)),(g=this.signaling)==null||g.on("onUnknownMessage",this.onUnknownMessage.bind(this))}onKeepAliveRsp(){this.emit("onKeepAliveRsp")}onNotifyJoin(e){this.emit("onNotifyJoin",e)}onNotifyStatus(e){this.emit("onNotifyStatus",e)}onNotifyLeave(e){this.emit("onNotifyLeave",e)}onNotifyPublish(e){this.emit("onNotifyPublish",e)}onBye(e,t){this.emit("onBye",e,t)}onConnectFail(e){this.reset(),this.emit("onConnectFail",e)}onNetworkError(e){this.emit("onNetworkError",e)}onAuthInvalid(){}onReconnectStart(){this.emit("onReconnectStart")}onReconnectSuccess(e){this.emit("onReconnectSuccess",e)}onReconnectFail(e){this.emit("onReconnectFail",e)}onError(e){this.emit("onError",e)}onUnknownMessage(e){this.emit("onUnknownMessage",e)}}m(cr,"logName","SignalingManager"),((a,r,e,t)=>{for(var i,s=t>1?void 0:t?gl(r,e):r,n=a.length-1;n>=0;n--)(i=a[n])&&(s=(t?i(r,e,s):i(s))||s);t&&s&&ml(r,e,s)})([k(H)],cr.prototype,"publish",1);class Wn{constructor(r){m(this,"taskProfile");m(this,"encodeParam");m(this,"users",[]);m(this,"backgroundColor",0);m(this,"backgrounds",[]);m(this,"watermarks",[]);m(this,"clockWidgets",[]);m(this,"cropMode");m(this,"mediaProcessMode");this.taskProfile=r}}class zn{constructor(r,e,t){m(this,"userId");m(this,"streamType");m(this,"sourceType");this.userId=r,this.streamType=e,this.sourceType=t}}class Kn{constructor(r,e,t,i=0,s=16777215,n=xi.NOTO_SERIF_CJKSC_REGULAR){m(this,"x");m(this,"y");m(this,"fontSize");m(this,"zOrder");m(this,"fontColor");m(this,"fontType");this.x=r,this.y=e,this.fontSize=t,this.zOrder=i,this.fontColor=s,this.fontType=n}toJson(r,e){return{x:_t(this.x,r),y:_t(this.y,e),fonttype:this.fontType,fontsize:this.fontSize,fontcolor:tr(this.fontColor),zorder:this.zOrder}}}var Jn=(a=>(a[a.NOT_DISPLAY=0]="NOT_DISPLAY",a[a.ALWAYS=1]="ALWAYS",a[a.WHEN_NO_VIDEO=2]="WHEN_NO_VIDEO",a))(Jn||{});class lr{constructor(r,e,t,i,s,n=0,c=1,o=1){m(this,"url");m(this,"x");m(this,"y");m(this,"width");m(this,"height");m(this,"alpha");m(this,"display",1);m(this,"zOrder");this.url=r,this.x=e,this.y=t,this.width=i,this.height=s,this.zOrder=n,this.alpha=c,this.display=o}toJson(r,e){return{url:this.url,alpha:this.alpha,display:this.display,x:_t(this.x,r),y:_t(this.y,e),width:_t(this.width,r),height:_t(this.height,e),zorder:this.zOrder}}}m(lr,"DisplayType",Jn);class qn{constructor(r,e,t,i,s=0,n=16777215,c=xi.NOTO_SERIF_CJKSC_REGULAR){m(this,"text");m(this,"x");m(this,"y");m(this,"fontSize");m(this,"zOrder");m(this,"fontColor");m(this,"fontType");this.text=r,this.x=e,this.y=t,this.fontSize=i,this.zOrder=s,this.fontColor=n,this.fontType=c}toJson(r,e){return{text:this.text,x:_t(this.x,r),y:_t(this.y,e),fonttype:this.fontType,fontsize:this.fontSize,fontcolor:tr(this.fontColor),zorder:this.zOrder}}}class Gn{constructor(r,e,t,i,s,n=0,c){m(this,"userId");m(this,"x");m(this,"y");m(this,"width");m(this,"height");m(this,"zOrder");m(this,"sourceType");m(this,"segmentType",Ni.LiveTranscodingNoBody);m(this,"images",[]);m(this,"texts",[]);this.userId=typeof r=="number"?r.toString():r,this.x=e,this.y=t,this.width=i,this.height=s,this.zOrder=n,c&&(this.sourceType=c)}toJson(r,e,t,i){const s={paneid:r,majorpane:0,x:_t(this.x,e),y:_t(this.y,t),width:_t(this.width,e),height:_t(this.height,t),zorder:this.zOrder,userid:this.userId,images:this.images.map(n=>n.toJson(e,t)),texts:this.texts.map(n=>n.toJson(e,t))};return this.sourceType&&Li[this.sourceType]?s.sourcetype=Li[this.sourceType]:s.sourcetype=Li[vi.LiveTranscodingCamera],this.segmentType&&i===Yi.LiveTranscodingVirtualBackground?s.segmenttype=this.segmentType:s.segmenttype=Ni.LiveTranscodingNoBody,s}}class fl{constructor(r){m(this,"_updateables");m(this,"_useWebworker");m(this,"_inited");m(this,"_active");m(this,"_previousRAFTime");m(this,"_previousWorkerTime");m(this,"_webWorkerString");m(this,"_webWorker");m(this,"_intervalThreshold");m(this,"_rafId");m(this,"_focusHandler",null);m(this,"_blurHandler",null);m(this,"_visibilityHandler",null);this._updateables=[],this._useWebworker=!1,this._inited=!1,this._active=!1,this._previousRAFTime=void 0,this._previousWorkerTime=void 0,this._intervalThreshold=r&&r>0&&r<=60?1/r:.1,this._webWorkerString=`
134
+ `+n),console.error("Failed log data:",a))}},new Promise((n,c)=>{var o=u=>{try{d(s.next(u))}catch(p){c(p)}},l=u=>{try{d(s.throw(u))}catch(p){c(p)}},d=u=>u.done?n(u.value):Promise.resolve(u.value).then(o,l);d((s=s.apply(t,i)).next())});var t,i,s}class Bn extends Pa{constructor(r){super(Object.assign({},r,{installUnloadHook:e=>{window.addEventListener("beforeunload",()=>{e()})},sendPayload:(e,t)=>{nl(e,t)}}))}useStsPlugin(r){this.getOpt().sendPayload=(e,t)=>{ol(e,t,r)},this.overwriteTransString(r)}}Sr(window,"SLS_Tracker",Bn);const ut=class ut{constructor(){m(this,"ntpClock");this.ntpClock=new J.AliRTS.Clock}static getInstance(r="DEFAULT"){let e=ut.instances.get(r);e||(e=new ut,ut.instances.set(r,e),ut.refCounts.set(r,0));const t=ut.refCounts.get(r)||0;return ut.refCounts.set(r,t+1),e}static releaseInstance(r="DEFAULT"){const e=ut.refCounts.get(r)||0;if(e<=0)return;const t=e-1;t===0?(ut.instances.delete(r),ut.refCounts.delete(r)):ut.refCounts.set(r,t)}now(){return this.ntpClock.now()}};m(ut,"instances",new Map),m(ut,"refCounts",new Map);let Oi=ut;const Hn=(a="DEFAULT")=>Oi.getInstance(a),{BrowserUtil:sr,SystenUtil:Fn}=J.AliRTS,es=6e5,cl={host:"cn-shanghai.log.aliyuncs.com",project:"apsara-video-client",logstore:"client"},ll={host:"ap-southeast-1.log.aliyuncs.com",project:"apsara-video-client-sgp",logstore:"client"},ye=class ye{constructor(r){m(this,"param");m(this,"msgCacheArr",[]);m(this,"index",0);m(this,"ntpClock");m(this,"globalEnv","DEFAULT");m(this,"envKey");m(this,"stopped",!1);this.ntpClock=Hn(r),r&&(this.globalEnv=r),this.envKey=this.globalEnv;const e=ye.instanceCount.get(this.envKey)||0;ye.instanceCount.set(this.envKey,e+1),e===0&&this.startSTSUpdateTask()}get stsData(){return ye.sharedStsData.get(this.envKey)}set stsData(r){r?ye.sharedStsData.set(this.envKey,r):ye.sharedStsData.delete(this.envKey)}get stsExpiration(){return ye.sharedStsExpiration.get(this.envKey)||Date.now()}set stsExpiration(r){ye.sharedStsExpiration.set(this.envKey,r)}createTracker(){if(ye.sharedTrackers.has(this.envKey)){const s=ye.sharedTrackers.get(this.envKey);return this.msgCacheArr.forEach((n,c)=>{var o;s==null||s.send(X(vt(X({},this.param),{stat_log_id:`${((o=this.param)==null?void 0:o.sesid)||"nosession"}-${c}`}),n))}),this.index=this.index+this.msgCacheArr.length,void(this.msgCacheArr=[])}if(!this.stsData||!this.param)return;const r=this.globalEnv==="SEA"?ll:cl,e=new Bn({host:r.host,project:r.project,logstore:r.logstore}),t={accessKeyId:this.stsData.AccessKeyId,accessKeySecret:this.stsData.AccessKeySecret,securityToken:this.stsData.SecurityToken,refreshSTSTokenInterval:es,refreshSTSToken:()=>{this.refreshSTSToken().then(s=>{t.accessKeyId=s.AccessKeyId,t.accessKeySecret=s.AccessKeySecret,t.securityToken=s.SecurityToken}).catch(()=>{})}},i=gs(t);e.useStsPlugin(i),ye.sharedTrackers.set(this.envKey,e),this.msgCacheArr.forEach((s,n)=>{var c;e==null||e.send(X(vt(X({},this.param),{stat_log_id:`${((c=this.param)==null?void 0:c.sesid)||"nosession"}-${n}`}),s))}),this.index=this.index+this.msgCacheArr.length,this.msgCacheArr=[]}startSTSUpdateTask(){return I(this,null,function*(){const r=ye.sharedUpdateTimers.get(this.envKey);r&&clearTimeout(r);try{this.stsData=yield this.refreshSTSToken(),this.createTracker()}catch(t){}const e=setTimeout(()=>{this.startSTSUpdateTask()},es);ye.sharedUpdateTimers.set(this.envKey,e)})}refreshSTSToken(){return I(this,null,function*(){const r=ye.sharedStsData.get(this.envKey),e=ye.sharedStsExpiration.get(this.envKey)||0;if(!r||e<=Date.now()+es){const t=yield this.requestSTSToken(),i=new Date(t==null?void 0:t.Expiration).getTime()||0,s=Date.now()+es;return this.stsExpiration=Math.max(i,s),this.stsData=t,t}return r})}requestSTSToken(){const r=Date.now(),e=`${ye.sharedClientId}|woMMssV6jmyol9fr|${r}`,t={Action:"AssumeSlsRoleV2",AuthInfo:ai.MD5(e).toString(ai.enc.Hex),ClientId:ye.sharedClientId,BusinessType:"rtc",AppVersion:"1.0",Version:"2017-03-14",AuthTimestamp:`${r}`,TerminalType:"web",DeviceModel:"",Format:"JSON",SignatureMethod:"HMAC-SHA1",SignatureVersion:"1.0",Timestamp:$i(r,"isoUtcDateTime")},i=new URLSearchParams(t).toString(),s=`https://${this.globalEnv==="SEA"?"vod.ap-southeast-1.aliyuncs.com":"vod.cn-shanghai.aliyuncs.com"}/?${i}`;return fetch(s).then(n=>n.json()).then(n=>JSON.parse(window.atob(n.SlsAuthResult)))}start(r){this.initParam(r),this.createTracker(),this.startSTSUpdateTask()}stop(){if(this.stopped)return;this.stopped=!0,this.param=void 0,this.msgCacheArr=[],this.index=0;const r=ye.instanceCount.get(this.envKey)||0,e=Math.max(0,r-1);if(ye.instanceCount.set(this.envKey,e),e===0){const t=ye.sharedUpdateTimers.get(this.envKey);t&&(clearTimeout(t),ye.sharedUpdateTimers.delete(this.envKey)),ye.sharedTrackers.delete(this.envKey),ye.sharedStsData.delete(this.envKey),ye.sharedStsExpiration.delete(this.envKey),ye.instanceCount.delete(this.envKey)}Oi.releaseInstance(this.envKey)}sendReport(r){var i;let e;r.tm=Date.now();try{e=JSON.parse(JSON.stringify(X(vt(X({bt:sr.browserName||"unknown",ntptm:this.ntpClock.now(),ntpofs:this.ntpClock.now()-Date.now()},this.param),{stat_log_id:`${((i=this.param)==null?void 0:i.sesid)||"nosession"}-${this.index}`}),r)))}catch(s){}if(!e)return;const t=ye.sharedTrackers.get(this.envKey);t?(t.send(e),this.index++):this.msgCacheArr.push(e)}initParam(r){let e="";try{e=(localStorage==null?void 0:localStorage.getItem("AliRtcUUID"))||"",e||(e=mt(),localStorage==null||localStorage.setItem("AliRtcUUID",e))}catch(t){}this.param||(this.param={apid:r.appId,usrid:r.userId,statsvrs:"0.6.1",evetid:0,sesid:r.sessionId,sessionId:r.sessionId,channelid:r.channelId,usrn:r.userId,osn:Fn.systemName,osv:Fn.systemVersion,deb:sc(),den:ec(),model:ka(),platfm:Ca,udid:e,sdkvrs:_i,acs:"Unknown",cput:Ea(),dm:`${window.location.protocol}//${window.location.host}`,bt:sr.browserName,bv:sr.browserVersion,envir:"PRODUCT",args:"",instid:mt()})}};m(ye,"sharedTrackers",new Map),m(ye,"sharedStsData",new Map),m(ye,"sharedStsExpiration",new Map),m(ye,"sharedUpdateTimers",new Map),m(ye,"sharedClientId",mt()),m(ye,"instanceCount",new Map);let rr=ye;const ke=(a,r=1,e=6e4,t=0)=>{let i=a;return i||(i=0),Math.min(e,Math.max(t,Math.round(i*r)))},ft=(a,r,e=2e7,t=0)=>{let i=r;(!r||r<0||r>1e4)&&(i=1e3);let s=a;return s||(s=0),Math.min(e,Math.max(t,Math.round(s/(i/1e3))))},ci=(a,r)=>{if(r===0||!r)return"0.00";let e=a;return(!e||e<0)&&(e=0),(e/r*100).toFixed(2)},jn=a=>a>=0&&a<=1?ke(Math.floor(32767*a),1,32767):0,Pe=(a,r)=>{var t,i,s;let e=((t=a._last)==null?void 0:t[r])||0;return a.ssrc&&((i=a._last)!=null&&i.ssrc)&&a.ssrc!==((s=a._last)==null?void 0:s.ssrc)&&(e=0),((a==null?void 0:a[r])||0)-e},$n=(a,r)=>ke(Pe(a,r),1e3,1e4),li=(a,r=2e7)=>ke(a,1,r);class dl{constructor(r,e){m(this,"engine");m(this,"logClient");m(this,"authInfo");m(this,"ntpClock");m(this,"globalEnv");m(this,"customFields",{});this.globalEnv=e||"DEFAULT",this.logClient=new rr(e),this.engine=r,this.ntpClock=Hn(this.globalEnv)}setCustomFields(r){this.customFields=X(X({},this.customFields),r)}getCustomField(r){return this.customFields[r]}start(r){this.authInfo=r,this.logClient.start(r)}stop(){this.logClient.stop(),Oi.releaseInstance(this.globalEnv)}reportPublishAudio3A(r,e,t,i){const s={};let n=JSON.parse(i);s.publevel=n.capture_audio_cur_level_db||0,s.eleakrate=n.echo_leak_rate||0,s.playbw=n.render_bandwidth||-1,s.capbw=n.capture_bandwidth||-1,s.diff=n.diff||0,s.leak=n.leak||0,this.log({evetid:10070,traceid:t,calid:r,rmtid:"",args:this.data2String(X({calid:r,tckid:e||"audio3a",rmtid:"",traceid:t},s))})}reportPublishMonitor(r,e,t,i,s){if(!t||s.length<=0)return;const n=t===D.Audio,c={ctm:Math.floor(s[0].timestamp||0),src:s[0].ssrc||"",codec:s[0]._codec||""},o=[],l=[],d=[],u=[],p=[],h=[],f=[],g=[],b=[],S=[],v=[],R=[],_=[],y=[],w=[],A=[],E=[],C=[],P=[],M=[];try{if(s.forEach(x=>{var he,xe,q,Re,Ve,Ee;if(!x||!x.timestamp)return;const K=(he=x._last)!=null&&he.timestamp?x.timestamp-x._last.timestamp:1e3,Q=Pe(x,"bytesSent"),G=Pe(x,"headerBytesSent"),W=ft(ke(Q+G,8,2e7),K);o.push(W);const Z=ft(ke(Q,8,2e7),K);l.push(Z);const te=ft(ke(G,8,2e7),K);d.push(te);const Se=Pe(x,"packetsSent"),L=ft(Se,K);u.push(L);const O=Pe(x,"packetsLost"),N=ft(O,K);p.push(N);const V=ci(O,Se);if(h.push(V),n)(xe=x._source)!=null&&xe.audioLevel&&f.push(jn(x._source.audioLevel)),g.push(0);else{b.push($n(x,"totalEncodeTime")),S.push(li((q=x._source)==null?void 0:q.framesPerSecond,100)),v.push(li((Re=x._source)==null?void 0:Re.framesPerSecond,100)),R.push(li(x.framesPerSecond,100));const Ne=Pe(x,"framesEncoded");_.push(ft(Ne,K,100)),y.push(li((Ve=x._source)==null?void 0:Ve.height,4400)),w.push(li((Ee=x._source)==null?void 0:Ee.width,7700)),A.push(li(x.frameHeight,4400)),E.push(li(x.frameWidth,7700));const ve=Pe(x,"totalPacketSendDelay");C.push(ke(ve,1/(O||1),2e3));const we=Pe(x,"qpSum");P.push(ke(we,1/(x.framesPerSecond||1),51)),M.push(0)}}),c.sbr=o.join(","),c.mbrs=l.join(","),c.pbrs=d.join(","),c.ps=u.join(","),c.pl=p.join(","),c.plr=h.join(","),n){const x=(i==null?void 0:i.getSettings().sampleRate)||0;c.ailevel=f.join(","),c.arpc=g.join(","),c.arsr=x,c.aesr=x,c.publevel=-90,c.rawlevel=-90}else c.em=b.join(","),c.cfps=S.join(","),c.ifps=v.join(","),c.sfps=R.join(","),c.efps=_.join(","),c.ih=y.join(","),c.iw=w.join(","),c.sh=A.join(","),c.sw=E.join(","),c.sd=C.join(","),c.aqp=P.join(","),c.caf=M.join(","),c.can=M.join(","),c.cav=l.join(","),c.ifimax=M.join(","),c.ifimin=M.join(","),c.efimax=M.join(","),c.efimin=M.join(","),c.sfimax=M.join(","),c.sfimin=M.join(","),c.apsnr=M.join(",")}catch(x){}this.log({evetid:10070,traceid:e,calid:r,rmtid:"",args:this.data2String(X({calid:r,tckid:t,rmtid:"",traceid:e},c))})}reportSubscribeMonitor(r,e,t,i,s){if(!i||!s||s.length<=0)return;const n=i===D.Audio,c={ctm:Math.floor(s[0].timestamp||0),src:s[0].ssrc||"",codec:s[0]._codec||""},o=[],l=[],d=[],u=[],p=[],h=[],f=[],g=[],b=[],S=[],v=[],R=[],_=[],y=[],w=[],A=[],E=[],C=[],P=[],M=[],x=[],K=[],Q=[],G=[],W=[],Z=[],te=[],Se=[],L=[],O=[],N=[],V=[],he=[],xe=[];try{s.forEach(q=>{var me,qe;if(!q||!q.timestamp)return;const Re=(me=q._last)!=null&&me.timestamp?q.timestamp-q._last.timestamp:1e3,Ve=Pe(q,"bytesReceived"),Ee=Pe(q,"headerBytesReceived"),Ne=ft(ke(Ve+Ee,8,2e7),Re);o.push(Ne);const ve=ft(ke(Ve,8,2e7),Re);l.push(ve);const we=ft(ke(Ee,8,2e7),Re);d.push(we);const pe=Pe(q,"packetsReceived"),Oe=ft(pe,Re);u.push(Oe);const Te=Pe(q,"packetsLost"),Ye=ft(Te,Re);p.push(Ye);const ht=ci(Te,pe);h.push(ht);const le=Pe(q,"jitterBufferDelay"),ne=Pe(q,"jitterBufferEmittedCount");if(q.jitterBufferDelay&&q.jitterBufferEmittedCount){const Y=ke(le,1e3/ne,1e4);f.push(Y)}else f.push(0);const ie=Pe(q,"fecPacketsReceived");R.push(ci(ie,pe));const Ae=Pe(q,"retransmittedPacketsReceived"),Fe=pe+Te-Ae;if(b.push(ci(pe-Ae,Fe)),S.push(ci(Te,Fe)),g.push(ci(Ae,Fe)),v.push(Fe),he.push(0),xe.push(""),n){y.push(jn(q.audioLevel));const Y=((Be,Tt)=>{var Ot,Ct,ei;return(((Ot=Be==null?void 0:Be._source)==null?void 0:Ot[Tt])||0)-(((ei=(Ct=Be==null?void 0:Be._last)==null?void 0:Ct._source)==null?void 0:ei[Tt])||0)})(q,"synthesizedSamplesEvents");w.push(Y);const Ue=$n(q,"synthesizedSamplesDuration");A.push(Ue);const pt=ci(Ue,Re);_.push(pt),E.push(0)}else{const Y=(qe=q._last)!=null&&qe.totalInterFrameDelay?q.totalInterFrameDelay-q._last.totalInterFrameDelay:0;C.push(ke(Y,1e3/(q.framesDecoded||30),500)),P.push(ke(q.framesPerSecond,1,100)),M.push(Pe(q,"framesReceived")),V.push(Pe(q,"framesRendered")),x.push(ke(q.frameHeight,1,4400)),K.push(ke(q.frameWidth,1,7700));const Ue=Pe(q,"totalProcessingDelay");Q.push(ke(Ue,1e3/(q.framesDecoded||30),12e4));const pt=Pe(q,"nackCount");W.push(pt);const Be=Pe(q,"pliCount");G.push(Be);const Tt=Pe(q,"qpSum");Z.push(ke(Tt,1/(q.framesPerSecond||1),51)),te.push(ke(q.framesDropped));const Ot=Pe(q,"totalFreezesDuration");Se.push(ke(Ot,1e3,3e4));const Ct=Pe(q,"jitterBufferEmittedCount"),ei=Pe(q,"jitterBufferDelay");ei&&Ct?L.push(ke(ei,1e3/Ct,3e4)):L.push(0);const Ui=Pe(q,"jitterBufferTargetDelay");Ui&&Ct?O.push(ke(Ui,1e3/Ct,3e4)):O.push(0);const rs=Pe(q,"jitterBufferMinimumDelay");rs&&Ct?N.push(ke(rs,1e3/Ct,3e4)):N.push(0)}}),c.rbr=o.join(","),c.mbrs=l.join(","),c.pbrs=d.join(","),c.pr=u.join(","),c.pl=p.join(","),c.plr=h.join(","),c.jd=f.join(","),c.fecr=R.join(","),c.retransr=g.join(","),c.baser=b.join(","),c.basel=S.join(","),c.recoverr=he.join(","),c.alll=S.join(","),c.totalc=v.join(","),n?(c.er=_.join(","),c.aolevel=y.join(","),c.asrc=E.join(","),c.scnt=w.join(","),c.sdura=A.join(",")):(c.dm=C.join(","),c.dfps=P.join(","),c.rfps=M.join(","),c.rh=x.join(","),c.rw=K.join(","),c.fpt=xe.join(","),c.ns=W.join(","),c.pliss=G.join(","),c.aqp=Z.join(","),c.ofimax=he.join(","),c.ofimin=he.join(","),c.dfimax=he.join(","),c.dfimin=he.join(","),c.rfimax=he.join(","),c.rfimin=he.join(","),c.vrstutter=Se.join(","),c.cdm=L.join(","),c.tdm=O.join(","),c.pdm=N.join(","),c.ofps=V.join(","),c.dfbd=te.join(","))}catch(q){}this.log({evetid:10080,traceid:t,rmtid:e,calid:r,new_args:_e.getInstance().getSummary(),args:this.data2String(X({calid:r,rmtid:e,tckid:i,traceid:t},c))})}reportNetworkMonitor(r){if(r.length<=0)return;const e=[],t=[],i=[],s=[],n=[],c=[],o=[],l=[],d=[],u=[];r.forEach((h,f)=>{var v,R,_;if(!h.timestamp)return;const g=(v=h._last)!=null&&v.timestamp?h.timestamp-h._last.timestamp:1e3;e.push(ke(h.currentRoundTripTime,1e3)),t.push(ke(h.availableOutgoingBitrate,8,2e8));const b=(h.bytesSent||0)-(((R=h._last)==null?void 0:R.bytesSent)||0),S=(h.bytesReceived||0)-(((_=h._last)==null?void 0:_.bytesReceived)||0);i.push(ft(ke(b,8,2e7),g,25e6)),s.push(ft(ke(S,8,2e7),g,25e6)),n.push(0),c.push(0),f%5==0&&(o.push(""),l.push(""),d.push(""),u.push(""))});const p={ctm:Math.floor(r[0].timestamp||0),rtt:e.join(","),bsps:i.join(","),brps:s.join(","),cpu:o.join(","),mem:l.join(","),sysmem:d.join(","),systotalmem:u.join(","),audioonly:this.engine.isAudioOnly()?1:0};this.log({evetid:10071,args:this.data2String(X({asb:t.join(","),abms:n.join(","),vbms:c.join(",")},p))}),this.log({evetid:10081,args:this.data2String(X({},p))})}reportLoopAudioDelay(r,e){var f;const{AIAgent:t={},AIGrtn:i={},AIPub:s={},AISub:n={},pub:c={},sub:o={},grtn:l={}}=e||{};if(Object.keys(t).length===0)return;let d=0;d=Object.keys(l).length?(c.vTotalCost||0)+(c.upRTTHalf||0)+(l.totalCost||0)+(o.downRTTHalf||0)+(o.vTotalCost||0):(c.vEncPlugCost||0)+((c.timestampRecv||0)-(c.timestamp||0))+(o.vJitterBufferDelay||0)+(o.vDecPlugCost||0);const u={};let p=0;for(let g=0;g<10;g++){const b=`ngxRtcSeiCumulativeDelayKeyInternalRttHalf_${g}`,S=`ngxRtcSeiCumulativeDelayKeyGrtnNodeBefPacer_${g}`,v=`ngxRtcSeiCumulativeDelayKeyGrtnNodePacerCost_${g}`;if(!l.hasOwnProperty(b))break;p+=l[b]||0,p+=l[S]||0,p+=l[v]||0,u[`_gnd${g}`]=`gnd[${g}]: {${this.data2String({gnirh:l[b]||0,gnbp:l[S]||0,gnpc:l[v]||0})}}`}const h={};for(let g=0;g<10;g++){const b=`aigrtninternalrtthalf_${g}`,S=`aigrtnbeforepacer_${g}`,v=`aigrtnpacercost_${g}`;if(!i.hasOwnProperty(b))break;h[`_lgnd${g}`]=`lgnd[${g}]: {${this.data2String({gnirh:i[b]||0,gnbp:i[S]||0,gnpc:i[v]||0})}}`}this.log({evetid:10073,args:this.data2String(vt(X({tdlms:d+(t.aiagenttotalcost||0),_:`aiqud:{${this.data2String(vt(X({uid:((f=this.authInfo)==null?void 0:f.userId)||"",sid:s.aAIClientScentenceId||0,quct:65535*(s.aAIClientQuestionTimestampHEAD||0)+(s.aAIClientQuestionTimestampTAIL||0),anct:65535*(s.aAIClientAnswerTimestampHEAD||0)+(s.aAIClientAnswerTimestampTAIL||0),casc:s.aAIClientSourceCost||0,camc:s.aAIClientMixerCost||0,caec:s.aAIClientEncoderCost||0,cantc:s.aIClientNetsdkThrCost||0,caqtc:s.aIClientQosThrCost||0,capc:s.aIClientPacerCost||0,cuphr:s.aIClientUpRTTHalf||0},h),{qgac:0,ldhr:l.ngxRtcSeiCumulativeDelayKeyDownRttHalf_0||0,larc:n.aAILinuxReceiveCost||0,lanqc:n.aAILinuxNeteqCost||0,larsc:n.aAILinuxRemoteSourceCost||0,lapmc:n.aAILinuxPlayMixerCost||0,lapc:n.aAILinuxPlayCost||0,lsdnc:n.aIClinetSmartDenoise||0,asrc:t.aiasrcost||0,llmc:t.aillmcost||0,ttsc:t.aittscost||0,aamc:t.aimutecost||0,aatc:t.aiagenttotalcost||0}))}};`,ssrc:r,tpd:0,scc:s.aAIClientSourceCost||0,mxc:s.aAIClientMixerCost||0,encc:s.aAIClientEncoderCost||0,netc:s.aIClientNetsdkThrCost||0,qostc:s.aIClientQosThrCost||0,pacerc:s.aIClientPacerCost||0,uphr:s.aIClientUpRTTHalf||0},u),{agac:p,dnhr:o.downRTTHalf||0,tsd:o.vTotalCost||0,rcc:n.aAILinuxReceiveCost||0,nqc:n.aAILinuxNeteqCost||0,rscc:n.aAILinuxRemoteSourceCost||0,plmxc:n.aAILinuxPlayMixerCost||0,plc:n.aAILinuxPlayCost||0,dvd:0}))})}reportCumuAudioDelay(r,e){const{pub:t={},sub:i={},grtn:s={}}=e||{};let n=0;n=Object.keys(s).length?(t.vTotalCost||0)+(t.upRTTHalf||0)+(s.totalCost||0)+(i.downRTTHalf||0)+(i.vTotalCost||0):(t.vEncPlugCost||0)+((t.timestampRecv||0)-(t.timestamp||0))+(i.vJitterBufferDelay||0)+(i.vDecPlugCost||0);const c={};let o=0;for(let l=0;l<10;l++){const d=`ngxRtcSeiCumulativeDelayKeyInternalRttHalf_${l}`,u=`ngxRtcSeiCumulativeDelayKeyGrtnNodeBefPacer_${l}`,p=`ngxRtcSeiCumulativeDelayKeyGrtnNodePacerCost_${l}`;if(!s.hasOwnProperty(d))break;o+=s[d]||0,o+=s[u]||0,o+=s[p]||0,c[`_gnd${l}`]=`gnd[${l}]: {${this.data2String({gnirh:s[d]||0,gnbp:s[u]||0,gnpc:s[p]||0})}}`}this.log({evetid:10074,args:this.data2String(vt(X({ssrc:r,tpd:n,scc:(t==null?void 0:t.aSourceCCost)||0,mxc:(t==null?void 0:t.aMixerCost)||0,encc:(t==null?void 0:t.aEncodeCCost)||0,netc:(t==null?void 0:t.netsdkThrCost)||0,qostc:(t==null?void 0:t.qosThrCost)||0,pacerc:(t==null?void 0:t.pacerCost)||0,uphr:(t==null?void 0:t.upRTTHalf)||0},c),{agac:o,dnhr:(i==null?void 0:i.downRTTHalf)||0,tsd:(i==null?void 0:i.vTotalCost)||0,rcc:0,nqc:0,rscc:0,plmxc:0,plc:0,device_delay:0,psdkt:0,pub_sdk_version:_i}))})}reportCumuVideoDelay(r,e){const{pub:t={},sub:i={},grtn:s={}}=e||{};let n=0;n=Object.keys(s).length?(t.vTotalCost||0)+(t.upRTTHalf||0)+(s.totalCost||0)+(i.downRTTHalf||0)+(i.vTotalCost||0):(t.vEncPlugCost||0)+((t.timestampRecv||0)-(t.timestamp||0))+(i.vJitterBufferDelay||0)+(i.vDecPlugCost||0);const c={};let o=0;for(let l=0;l<10;l++){const d=`ngxRtcSeiCumulativeDelayKeyInternalRttHalf_${l}`,u=`ngxRtcSeiCumulativeDelayKeyGrtnNodeBefPacer_${l}`,p=`ngxRtcSeiCumulativeDelayKeyGrtnNodePacerCost_${l}`;if(!s.hasOwnProperty(d))break;o+=s[d]||0,o+=s[u]||0,o+=s[p]||0,c[`_gnd${l}`]=`vgnd[${l}]: {${this.data2String({vgnirh:s[d]||0,vgnbp:s[u]||0,vgnpc:s[p]||0})}}`}this.log({evetid:10075,args:this.data2String(vt(X({vssrc:r,valld:n,vcdc:(t==null?void 0:t.capDeviceCost)||0,vpec:(t==null?void 0:t.pushExtCost)||0,vcpc:(t==null?void 0:t.capPlugCost)||0,vptc:(t==null?void 0:t.prepThrCost)||0,vppc:(t==null?void 0:t.prepPlugCost)||0,vdptc:(t==null?void 0:t.dispThrCost)||0,vdppc:(t==null?void 0:t.dispPlugCost)||0,vetc:(t==null?void 0:t.vEncThrCost)||0,vepc:(t==null?void 0:t.vEncPlugCost)||0,vntc:(t==null?void 0:t.netsdkThrCost)||0,vqtc:(t==null?void 0:t.qosThrCost)||0,vvpac:(t==null?void 0:t.pacerCost)||0,vuphr:(t==null?void 0:t.upRTTHalf)||0},c),{vagac:o,vdnhr:(i==null?void 0:i.downRTTHalf)||0,vrc:(i==null?void 0:i.vAssemblyCost)||0,vstc:0,vfbc:i.vJitterBufferDelay||0,vdtc:(i==null?void 0:i.vDecPlugCost)||0,vdvpc:(i==null?void 0:i.vDecPlugCost)||0,vrtc:0,vrpc:0}))})}reportJoin(r,e,t=""){var u,p;const{start:i,rs:s=0,re:n=0}=e,c=Date.now()-i,o=n-s;let l=0;s&&(l=s-i);let d=0;n&&(d=n-s),this.log({evetid:10010,args:this.data2String({sesid:((u=this.authInfo)==null?void 0:u.sessionId)||"",joitm:c,rslt:r,gslbtm:0,dnstm:0,avcftm:0,gslbrslt:0,dnsrslt:0,avcfrslt:0,mode:2,jrtc:o,usrn:(p=this.authInfo)==null?void 0:p.userId,mgt:"cdn",cttc:l,iptc:d,ndn:1,gslbloc:1,ccag:0,ucag:0,cpg:0,upg:0,tid:t})})}reportJoinConnection(r){this.log({evetid:20002,args:this.data2String(X({transretrynum:0,ldnstc:0,tcptc:0,ssltc:0,url:""},r))})}reportLeave(r,e,t){this.log({evetid:10020,args:this.data2String({lvetm:r,rslt:e,tid:t})})}reportPublish(r,e,t,i,s,n,c,o,l,d,u,p){this.log({evetid:r?10032:10030,calid:t,tm:p,args:this.data2String({calid:t,url:e,isvl:i?1:0,isvs:s?1:0,isvss:n?1:0,isaudio:c?1:0,rslt:o,tid:"123",pubtm:Date.now()-u,pctid:l,pubtid:d,isvp:0,isarecording:0,isad:0,isdc:0,pubretry:0,pbrttimes:0})})}reportPublishFirstPacket(r,e,t,i,s,n,c,o,l){const d=Date.now();this.log({evetid:r?10033:10031,calid:e,args:this.data2String({calid:e,fpst:d-t,tckid:n,est:t,pctid:c,pubtid:o,totaltm:d-s,jorm:l===Dt.JOIN_CHANNEL?1:0,cptc:0,sptc:i-t,iptc:0,ipc2fptc:0,dctc:0,patc:0})})}reportUnpublish(r,e,t,i){var s;this.log({evetid:10040,args:this.data2String({calid:r,unpubtm:e,rslt:t,tid:i,sesid:((s=this.authInfo)==null?void 0:s.sessionId)||""})})}reportSubscribe(r,e,t,i,s,n,c,o,l,d,u){this.log({evetid:10050,calid:r,rmtid:e,tm:u,args:this.data2String(X({calid:r,rmtid:e,isvl:t?1:0,isvs:i?1:0,isvss:s?1:0,isaudio:n?1:0,rslt:c,tid:o,subtm:l,isvp:0,isaplaying:0,isad:0,isdc:0,subretry:0,sbrttimes:0},d))})}reportSubscribeFirstPacket(r,e,t,i,s){this.log({evetid:r?10054:10051,calid:e,rmtid:t,args:this.data2String(X({calid:e,rmtid:t,tckid:i,cptc:0,iptc:0,ipc2fptc:0,dctc:0,patc:0},s))})}reportSubscribeFirstFrame(r,e,t,i,s){this.log({evetid:r?10055:10052,calid:e,rmtid:t,args:this.data2String(X({calid:e,rmtid:t,tckid:i},s))}),this.log({evetid:r?10058:10057,args:this.data2String(X({calid:e,rmtid:t,tckid:i},s))})}reportUnsubscribe(r,e,t,i,s){this.log({evetid:10060,calid:r,args:this.data2String({calid:r,rmtid:e,unsubtm:t,rslt:i,tid:s})})}reportMute(r,e,t){this.log({evetid:11030,args:this.data2String({calid:r,rmtid:"",enable:e?1:0,mt:t})})}reportRoleUpdate(r,e){this.log({evetid:11040,args:this.data2String({or:r||"",nr:e,ctm:Date.now(),rslt:0})})}reportRoleUpdateResult(r,e,t,i){this.log({evetid:11041,args:this.data2String({or:r||"",nr:e,ctm:t,rslt:i})})}reportVideoProfile(r){this.log({evetid:20074,args:this.data2String({pf:r,tckid:"sophon_camera_large"})})}reportScreenProfile(r){this.log({evetid:20074,args:this.data2String({pf:r,tckid:"sophon_screenshare"})})}reportError(r){this.log({evetid:10091,args:this.data2String({rslt:(r==null?void 0:r.code)||-1})})}reportWarning(r){this.log({evetid:10092,args:this.data2String({rslt:-1,errmsg:r})})}reportRoomServerEvent(r,e,t,i){this.log({evetid:20005,args:this.data2String({calid:"",rmtid:"",rt:r?0:1,dr:r?"s":"r",mt:e,ri:t,cs:1,srt:Date.now(),rspc:(i==null?void 0:i.code)||"",mc:JSON.stringify(i)})})}reportTranscodingError(r,e){this.log({evetid:10101,args:this.data2String({rslt:r,taskid:e})})}reportBye(r){var e;this.log({evetid:10093,args:this.data2String({rslt:r,sesid:((e=this.authInfo)==null?void 0:e.sessionId)||""})})}reportAudio(r,e,t){var i;this.log({evetid:80013,args:this.data2String({rslt:r?-1:0,adm:1,adt:0,adr:r?2:0,acms:e,adrpn:t})}),this.log({evetid:80014,args:this.data2String({sesid:((i=this.authInfo)==null?void 0:i.sessionId)||"",rslt:r?-1:0,adm:1,adt:0,adr:r?2:0,acms:e,adrpn:t})})}reportScreen(r,e){var t,i,s,n;this.log({evetid:90013,args:this.data2String({rslt:r?-1:0,vcms:e,vde:(t=r==null?void 0:r.code)!=null?t:-1,sesid:((i=this.authInfo)==null?void 0:i.sessionId)||""})}),this.log({evetid:90014,args:this.data2String({rslt:r?-1:0,vcms:e,vde:(s=r==null?void 0:r.code)!=null?s:-1,sesid:((n=this.authInfo)==null?void 0:n.sessionId)||""})})}reportScreenStop(r){this.log({evetid:90019,args:this.data2String({rslt:r?r.code||-1:0})}),this.log({evetid:90020,args:this.data2String({rslt:r?r.code||-1:0})})}reportSwitchCamera(r){var e;this.log({evetid:90025,args:this.data2String({rslt:0,td:r,sesid:((e=this.authInfo)==null?void 0:e.sessionId)||""})})}reportPublishProfile(r,e){this.log({evetid:10201,args:this.data2String(X({tckid:r},e))})}reportSDKCreated(r){this.log({evetid:70011,createtm:Date.now()-r,tm:r})}reportJoinInvoked(r){this.log({evetid:70012,jnnonce:r.nonce||"",jntoken:r.token||"",jntm:r.timestamp||""})}reportJoinResult(r){this.log({evetid:70013,rslt:r?r.code||-1:0,dnsrslt:0})}reportSTSResult(r,e){this.log({evetid:70014,rslt:r,asty:1,reqtm:Date.now()-e})}reportLeaveInvoked(){this.log({evetid:70015})}reportSEIMessage(r,e,t,i,s){this.log({evetid:40301,args:this.data2String({tm:Date.now(),sei_pt:r,sei_len:e,sei_rep:t,sei_delay:i,sei_key:s})})}reportConnectionLatencyEvent(r,e,t,i,s,n,c=!1){const o={ageniid:this.getCustomField("ageniid")},l=X({tm:s||Date.now(),ntptm:n||this.ntpClock.now(),stage:r,status:e,calid:t,tckid:i,cltp:1,http:c?1:0},o);this.log({evetid:12001,args:this.data2String(l)})}log(r){r&&(r.tm=r.tm||new Date().getTime(),T.debug("[ConsoleLogger]","log",r),this.logClient.sendReport(r))}data2String(r){let e="";for(let t in r)e.length&&(e+="&"),e+=t.startsWith("_")?r[t]:`${t}=${r[t]}`;return e}}const Ri=class Ri extends oe{constructor(e){super();m(this,"ws");m(this,"socketStatus",0);m(this,"wsUrl","");m(this,"lastConnectStartTime",0);m(this,"connectRetryMinTimeGap",5e3);m(this,"shouldReconnect",!0);m(this,"connectRetryCount",0);m(this,"gotErr",!1);m(this,"closedByInvoke",!0);m(this,"isReconnecting",!1);m(this,"networkAvailableChecked",!0);m(this,"reconnectTimeoutId",0);e&&(this.connectRetryMinTimeGap=e),this.onOpen=this.onOpen.bind(this),this.onMessage=this.onMessage.bind(this),this.onError=this.onError.bind(this),this.onClose=this.onClose.bind(this)}get connectUrl(){return this.wsUrl}get connectStatus(){return this.socketStatus}start(e){this.wsUrl=e,this.initWebSocket()}send(e){return!(!this.ws||this.socketStatus!==2)&&(this.ws.send(JSON.stringify(e)),!0)}close(){this.closedByInvoke=!0,this.reconnectTimeoutId&&(clearTimeout(this.reconnectTimeoutId),this.reconnectTimeoutId=0),this.uninitWebsocket()}markShouldReconnect(e){this.shouldReconnect=e}reconnect(){this.reconnectTimeoutId&&(clearTimeout(this.reconnectTimeoutId),this.reconnectTimeoutId=0),this.emit("onWillReconnect"),this.shouldReconnect?(this.emit("onReconnectStart"),this.isReconnecting=!0,this.initWebSocket()):this.emit("onConnectFail")}onOpen(e){T.info(`[${Ri.logName}]`,"onOpen"),this.socketStatus=2,this.connectRetryCount=0,this.shouldReconnect=!0,this.networkAvailableChecked=!1,this.closedByInvoke=!1,this.gotErr=!1,this.isReconnecting=!1,this.emit("onOpen",e)}onMessage(e){this.emit("onMessage",e)}onError(e){this.isReconnecting&&this.emit("onReconnectFail",e),this.emit("onError",e),this.isReconnecting=!1,this.socketStatus!==2&&Le.isNetworkAvailable().then(t=>{t&&console.error(Ri.logName,"onError, Network is available, token may be invalid")})}onClose(e){return I(this,null,function*(){if(this.closedByInvoke)this.socketStatus=0;else{if(T.info(`[${Ri.logName}]`,`onClose, code: ${e.code}, reason: ${e.reason}, status: ${status}, retryCount: ${this.connectRetryCount}`),(yield Le.isNetworkAvailable())&&!this.networkAvailableChecked)return this.reconnect(),void(this.networkAvailableChecked=!0);if(this.connectRetryCount||this.emit("onNetworkError"),!this.reconnectTimeoutId){this.connectRetryCount+=1;const t=Date.now()-this.lastConnectStartTime;t>=this.connectRetryMinTimeGap?this.reconnect():this.reconnectTimeoutId=window.setTimeout(()=>{this.reconnect()},this.connectRetryMinTimeGap-Math.max(0,t))}this.socketStatus=0,this.emit("onClose",e)}})}initWebSocket(){this.uninitWebsocket(),this.socketStatus=1,this.lastConnectStartTime=Date.now(),this.ws=new WebSocket(this.wsUrl),this.ws.addEventListener("open",this.onOpen),this.ws.addEventListener("message",this.onMessage),this.ws.addEventListener("error",this.onError),this.ws.addEventListener("close",this.onClose)}uninitWebsocket(){this.reconnectTimeoutId&&(clearTimeout(this.reconnectTimeoutId),this.reconnectTimeoutId=0),this.ws&&(this.ws.removeEventListener("open",this.onOpen),this.ws.removeEventListener("message",this.onMessage),this.ws.removeEventListener("error",this.onError),this.ws.removeEventListener("close",this.onClose),this.ws.readyState!==WebSocket.CLOSED&&this.ws.close(),this.ws=void 0,this.socketStatus=0)}};m(Ri,"logName","Socket");let ar=Ri;const St=class St extends oe{constructor(e,t,i,s,n,c){super();m(this,"authInfo");m(this,"userName");m(this,"channelProfile");m(this,"clientRole");m(this,"slsReporter");m(this,"wsClient");m(this,"packageCreator");m(this,"keepAliveTimer",0);m(this,"lastKeepAliveResponseTime",0);m(this,"maxConnectRetryDuration",90);m(this,"packageCache",new Map);m(this,"isFirstConnect",!0);m(this,"aliveChecker",0);m(this,"reconnectData");m(this,"joinChannelExtraData");m(this,"onOpen",()=>{if(T.info(`[${St.logName}] onOpen`),this.isFirstConnect){let e=this.packageCreator.createJoinPackage(this.joinChannelExtraData);e.data.configure={channelprofile:this.channelProfile},this.channelProfile!==Ut.AliRtcSdkInteractiveLive&&this.channelProfile!==Ut.AliRtcSdkInteractiveWithLowLatencyLive||(e.data.configure.clientrole=this.clientRole),this.sendPackage(e)}else{this.stopKeepAlive();const e=this.packageCreator.createReconnectPackage(this.reconnectData);this.sendPackage(e)}});m(this,"onMessage",e=>{try{let t=JSON.parse(e.data);this.packageCache.delete(t.tid),this.onRecvMessage(t),t!=null&&t.msgtype&&(t==null?void 0:t.msgtype)!==$e.KEEPALIVE&&this.slsReporter.reportRoomServerEvent(!1,t.msgtype,t.tid,t)}catch(t){T.warn(`[${St.logName}] onMessage err`,t,e)}});m(this,"onError",e=>{T.warn(`[${St.logName}] onError`,e),this.isFirstConnect&&this.onConnectFail()});m(this,"onConnectFail",()=>{T.warn(`[${St.logName}] onConnectFail`);const e=new U(B.ERR_INNER,"Signaling connect failed.");this.isFirstConnect?this.emit("onJoinChannelResult",e):this.emit("onConnectFail",e)});m(this,"onAuthInvalid",()=>{T.warn(`[${St.logName}] onAuthInvalid`),this.isFirstConnect&&this.emit("onAuthInvalid")});m(this,"onNetworkError",()=>{T.warn(`[${St.logName}] onNetworkError`);const e=new U(B.ERR_INNER,"Network error, signaling connect failed.");this.emit("onNetworkError",e)});m(this,"onClose",e=>{T.info(`[${St.logName}] onClose`,e),this.stopKeepAlive()});m(this,"onWillReconnect",()=>{this.lastKeepAliveResponseTime||(this.lastKeepAliveResponseTime=Date.now()),Date.now()-this.lastKeepAliveResponseTime>1e3*this.maxConnectRetryDuration&&this.wsClient.markShouldReconnect(!1)});m(this,"onReconnectStart",()=>{this.emit("onReconnectStart")});m(this,"onReconnectFail",()=>{this.emit("onReconnectFail",new U(B.ERR_INNER,"signaling reconnect failed."))});this.authInfo=e,this.userName=t,this.packageCreator=new Ki(e,t),this.channelProfile=i,this.clientRole=s,this.slsReporter=n,c&&(this.maxConnectRetryDuration=c),this.wsClient=new ar,this.wsClient.on("onOpen",this.onOpen),this.wsClient.on("onMessage",this.onMessage),this.wsClient.on("onError",this.onError),this.wsClient.on("onClose",this.onClose),this.wsClient.on("onConnectFail",this.onConnectFail),this.wsClient.on("onAuthInvalid",this.onAuthInvalid),this.wsClient.on("onNetworkError",this.onNetworkError),this.wsClient.on("onWillReconnect",this.onWillReconnect),this.wsClient.on("onReconnectStart",this.onReconnectStart),this.wsClient.on("onReconnectFail",this.onReconnectFail)}get retryCount(){return this.wsClient.connectRetryCount}destroy(){this.lastKeepAliveResponseTime=0,this.close()}start(e,t){this.joinChannelExtraData=t,this.wsClient.start(e)}startKeepAlive(){this.keepAliveTimer===0&&(this.keepAliveTimer=window.setInterval(()=>{let e=this.packageCreator.createKeepAlivePackage();this.sendPackage(e)},5e3)),this.checkAlive()}stopKeepAlive(){this.keepAliveTimer!==0&&(clearInterval(this.keepAliveTimer),this.keepAliveTimer=0),this.aliveChecker&&(window.clearTimeout(this.aliveChecker),this.aliveChecker=0)}sendPkgCache(){this.packageCache.forEach(e=>{this.wsClient.send(e)})}leave(){let e=this.packageCreator.createLeavePackage();this.sendPackage(e)}reportStatus(e){let t=this.packageCreator.createStatusPackage(e);this.sendPackage(t)}publish(e){const l=e,{l1ip:t}=l,i=Wt(l,["l1ip"]);let s=this.packageCreator.createPublishPackage();s.data.users=[],s.data.l1ip=t,i.subscribe.signal=this.wsClient.connectUrl;const{tracks:n,resume:c}=i;let o="7.2.10";o&&(o=o.split("-")[0]),n.forEach(d=>{const{codec:u,ssrc:p}=d;d.userdata=JSON.stringify({sdk_version:o,codec:u}),d.ssrc=`${p}`,c&&(d.attr={reason:"reconnect"})}),s.data.users.push(i),this.sendPackage(s)}roleUpdate(e){let t=this.packageCreator.createRoleUpdatePackage();t.data.clientrole=e,this.sendPackage(t)}refreshUrl(e){const t=this.packageCreator.createRefreshUrlPackage();t.data=X(vt(X({},t.data),{sessionid:t.header.sessionid}),e),this.sendPackage(t)}refreshAuthInfo(e){this.authInfo=e,this.packageCreator.refreshAuthInfo(e)}close(){T.info(`[${St.logName}] close`),this.stopKeepAlive(),this.wsClient.off("onOpen",this.onOpen),this.wsClient.off("onMessage",this.onMessage),this.wsClient.off("onError",this.onError),this.wsClient.off("onClose",this.onClose),this.wsClient.off("onConnectFail",this.onConnectFail),this.wsClient.off("onAuthInvalid",this.onAuthInvalid),this.wsClient.off("onNetworkError",this.onNetworkError),this.wsClient.off("onWillReconnect",this.onWillReconnect),this.wsClient.off("onReconnectStart",this.onReconnectStart),this.wsClient.off("onReconnectFail",this.onReconnectFail),this.wsClient.close()}sendPackage(e){[$e.KEEPALIVE,$e.RECONNECT,$e.JOINCHANNEL].includes(e.msgtype)||this.packageCache.set(e.tid,e),this.wsClient.send(e),e.msgtype!==$e.KEEPALIVE&&this.slsReporter.reportRoomServerEvent(!0,e.msgtype,e.tid,e)}updateReconnectData(e){this.reconnectData=e}onKeepAliveRsp(){this.emit("onKeepAliveRsp"),this.lastKeepAliveResponseTime=Date.now(),this.checkAlive()}checkAlive(){window.clearTimeout(this.aliveChecker),this.aliveChecker=window.setTimeout(()=>{T.info(`[${St.logName}] not alive, reconnect`),this.stopKeepAlive(),this.emit("onReconnectStart"),this.wsClient.reconnect()},15e3)}onRecvMessage(e){switch(e.msgtype!==$e.KEEPALIVE&&T.info(`[${St.logName}] recv msg: ${e.msgtype}`),e.msgtype){case $e.JOINCHANNEL:this.onJoinResult(e);break;case $e.KEEPALIVE:this.onKeepAliveRsp();break;case $e.PUBLISH:this.onPublishResult(e);break;case $e.NOTIFYJOIN:this.onNotifyJoin(e);break;case $e.NOTIFYSTATUS:this.onNotifyStatus(e);break;case $e.LEAVECHANNEL:this.onLeaveResult(e);break;case $e.NOTIFYLEAVE:this.onNotifyLeave(e);break;case $e.NOTIFYPUBLISH:this.onNotifyPublish(e);break;case $e.STATUSREPORT:this.onStatusReport(e);break;case $e.BYE:this.onBye(e);break;case $e.ROLEUPDATE:this.onRoleUpdateResult(e);break;case $e.REFRESHURL:this.onRefreshUrlResult(e);break;case $e.RECONNECT:this.onReconnectResult(e);break;default:this.onUnknownMessage(e)}}onJoinResult(e){this.isFirstConnect=!1,this.emit("onJoinChannelResult",e)}onLeaveResult(e){this.emit("onLeaveResult",e.code,e.tid)}onPublishResult(e){this.emit("onPublishResult",e.code,e.tid,e.description)}onRoleUpdateResult(e){this.emit("onRoleUpdateResult",e.code,e.tid,e.description)}onRefreshUrlResult(e){this.emit("onRefreshUrlResult",e)}onReconnectResult(e){if(e.code===200)this.sendPkgCache(),this.startKeepAlive(),this.emit("onReconnectSuccess",e.data.users);else{const t=new U(B.ERR_INNER,`reconnect failed, code: ${e.code};description: ${e.description}`);e.code===403&&(t.code=403),this.emit("onReconnectFail",t),this.close()}}onNotifyJoin(e){let t=this.packageCreator.createResponsePackage(e.tid,e.msgtype);this.wsClient.send(t),e&&e.data&&e.data.users&&this.emit("onNotifyJoin",e.data.users)}onNotifyStatus(e){let t=this.packageCreator.createResponsePackage(e.tid,e.msgtype);this.wsClient.send(t),e.data&&e.data.status&&e.data.status.length&&this.emit("onNotifyStatus",e.data.status)}onNotifyLeave(e){let t=this.packageCreator.createResponsePackage(e.tid,e.msgtype);this.wsClient.send(t),e.data&&e.data.users&&e.data.users.length&&this.emit("onNotifyLeave",e.data.users)}onNotifyPublish(e){let t=this.packageCreator.createResponsePackage(e.tid,e.msgtype);this.wsClient.send(t),e.data&&e.data.users&&e.data.users.length&&this.emit("onNotifyPublish",e.data.users)}onStatusReport(e){this.emit("onStatusReport",e.code,e.tid,e.description)}onBye(e){this.stopKeepAlive(),this.emit("onBye",e.reason,e.description)}onUnknownMessage(e){this.emit("onUnknownMessage",e)}};m(St,"logName","RSMessageCenter");let nr=St;var ul=Object.defineProperty,hl=Object.getOwnPropertyDescriptor,or=(a,r,e,t)=>{for(var i,s=t>1?void 0:t?hl(r,e):r,n=a.length-1;n>=0;n--)(i=a[n])&&(s=(t?i(r,e,s):i(s))||s);return t&&s&&ul(r,e,s),s};const ts=(rt=class extends oe{constructor(e,t,i,s=It.prod){super();m(this,"messageCenter");m(this,"authInfo");m(this,"userName");m(this,"channelProfile");m(this,"clientRole");m(this,"slsReporter");m(this,"reconnectData");m(this,"roomServerUri","");this.channelProfile=e,this.clientRole=t,this.slsReporter=i,this.reconnectData={role:{channelprofile:e,clientrole:t}};const n=s===It.pre?Rt.pre:Rt.prod;this.roomServerUri=`wss://${n}/roomserver/v1/ws`}updateReconnectData(e){var t;this.reconnectData=e,(t=this.messageCenter)==null||t.updateReconnectData(this.reconnectData)}reset(){T.info("[roomsig] reset"),this.messageCenter&&(this.messageCenter.destroy(),this.messageCenter=void 0),this.authInfo=void 0}join(e,t,i,s){return I(this,null,function*(){return new Promise((n,c)=>{const o={};this.authInfo=e,this.userName=t,this.messageCenter=new nr(e,t,this.channelProfile,this.clientRole,this.slsReporter,i),this.initMessageCenter(),this.messageCenter.once("onJoinChannelResult",d=>{var u,p,h;if(T.info(`[${rt.logName}]`,"join result: ",d),o.taskretrynum=((u=this.messageCenter)==null?void 0:u.retryCount)||0,d.code==200){(p=this.messageCenter)==null||p.sendPkgCache(),(h=this.messageCenter)==null||h.startKeepAlive();let f=d.data;f.tid=d.tid,f.users=d.data.users,f.timestamp=d.timestamp,o.est&&(o.joinconnecttc=Date.now()-o.est),this.slsReporter.reportJoinConnection(o),n(f)}else this.reset(),c(this.handleSignalError(d.code,d.reason,B.ERR_JOIN_CHANNEL_FAILED))}),this.messageCenter.once("onAuthInvalid",()=>{this.reset(),c(new U(B.ERR_JOIN_BAD_TOKEN,"join failed because authentication failed"))}),T.info(`[${rt.logName}]`,"start ws connecting roomserver and auto join when connected");const l={appid:this.authInfo.appId,channelid:this.authInfo.channelId,userid:this.authInfo.userId,nonce:this.authInfo.nonce||"",timestamp:this.authInfo.timestamp,token:this.authInfo.token,authtype:"app",tid:mt()};e.role&&(l.tokenrole=e.role),o.est=Date.now(),this.messageCenter.start(this.roomServerUri+"?"+Le.queryingParam(l),s)})})}leave(){return T.info("[roomsig] leave .."),new Promise((e,t)=>{this.messageCenter?(this.messageCenter.on("onLeaveResult",(i,s)=>{T.info(`[${rt.logName}]`,"recv leave response "+i),i===200?(this.updateReconnectData(),this.reset(),e({tid:s})):t(this.handleSignalError(i,"leave error"))}),T.info(`[${rt.logName}]`,"send leave request"),this.messageCenter.leave()):(T.info(`[${rt.logName}]`,"no message center, ok to leave"),e({tid:""}))})}publish(e){return new Promise((t,i)=>{var s;this.messageCenter?(this.messageCenter.once("onPublishResult",(n,c,o)=>{T.info(`[${rt.logName}]`,"recv pubish response "+n),n===200?(this.updateReconnectData(vt(X({},this.reconnectData),{publish:{users:[e]}})),t({tid:c})):i(this.handleSignalError(n,`publish error, ${o}`))}),this.authInfo&&(e.sessionid=(s=this.authInfo.sessionId)!=null?s:""),e.callid||(e.callid=mt()),T.info(`[${rt.logName}]`,"assign callid "+e.callid+" and send publish request"),this.messageCenter.publish(e)):i(this.handleSignalError(-1,"publish error, no message center"))})}roleUpdate(e){return new Promise((t,i)=>{this.messageCenter?(this.messageCenter.on("onRoleUpdateResult",(s,n,c)=>{var o,l;T.info(`[${rt.logName}]`,"recv role update response "+s),s===200?((l=(o=this.reconnectData)==null?void 0:o.role)!=null&&l.clientrole&&(this.reconnectData.role.clientrole=e,this.updateReconnectData(this.reconnectData)),t({tid:n})):i(this.handleSignalError(s,`role update error, ${c}`))}),this.messageCenter.roleUpdate(e)):i(this.handleSignalError(-1,"role update error, no message center"))})}setChannelProfile(e){this.channelProfile=e}refreshUrl(e){return T.info(`[${rt.logName}]`,"refreshUrl .."),new Promise((t,i)=>{this.messageCenter?(this.messageCenter.on("onRefreshUrlResult",s=>{const{code:n,description:c,data:o={}}=s||{};T.info("recv refresh url response "+n),n===200?t(o):i(this.handleSignalError(n,`refresh url error, ${c}`))}),T.info("send refresh url request"),this.messageCenter.refreshUrl(e)):i(this.handleSignalError(-1,"refresh url error, no message center"))})}reportStatus(e){return T.info(`[${rt.logName}]`,"reportStatus "+e),new Promise((t,i)=>{this.messageCenter?(this.messageCenter.once("onStatusReport",(s,n)=>{s===200?t():i(new U(s,n))}),this.messageCenter.reportStatus(e)):i(new U(-1,"No messageCenter"))})}handleSignalError(e,t,i=B.ERR_INNER){return new U(i,`signal error: code - ${e}; description - ${t}`)}refreshAuthInfo(e){return I(this,null,function*(){var t;this.authInfo&&(this.authInfo=e,(t=this.messageCenter)==null||t.refreshAuthInfo(this.authInfo))})}initMessageCenter(){var e,t,i,s,n,c,o,l,d,u,p,h,f;(e=this.messageCenter)==null||e.on("onKeepAliveRsp",()=>{this.emit("onKeepAliveRsp")}),(t=this.messageCenter)==null||t.on("onNotifyJoin",g=>{this.emit("onNotifyJoin",g)}),(i=this.messageCenter)==null||i.on("onNotifyStatus",g=>{this.emit("onNotifyStatus",g)}),(s=this.messageCenter)==null||s.on("onNotifyLeave",g=>{this.emit("onNotifyLeave",g)}),(n=this.messageCenter)==null||n.on("onNotifyPublish",g=>{this.emit("onNotifyPublish",g)}),(c=this.messageCenter)==null||c.on("onBye",(g,b)=>{this.emit("onBye",g,b)}),(o=this.messageCenter)==null||o.on("onReconnectStart",()=>{this.emit("onReconnectStart")}),(l=this.messageCenter)==null||l.on("onReconnectSuccess",g=>{this.emit("onReconnectSuccess",g)}),(d=this.messageCenter)==null||d.on("onReconnectFail",g=>{this.emit("onReconnectFail",g)}),(u=this.messageCenter)==null||u.on("onConnectFail",g=>{this.emit("onConnectFail",g),this.reset()}),(p=this.messageCenter)==null||p.on("onNetworkError",g=>{this.emit("onNetworkError",g)}),(h=this.messageCenter)==null||h.on("onAuthInvalid",()=>{this.emit("onAuthInvalid")}),(f=this.messageCenter)==null||f.on("onUnknownMessage",g=>{this.emit("onUnknownMessage",g)})}},m(rt,"logName","RoomServerSignaling"),rt);or([k()],ts.prototype,"join",1),or([k()],ts.prototype,"publish",1),or([k()],ts.prototype,"roleUpdate",1);let pl=ts;var ml=Object.defineProperty,gl=Object.getOwnPropertyDescriptor;class cr extends oe{constructor(e,t,i,s=It.prod){super();m(this,"signaling");m(this,"authInfo");m(this,"userName");m(this,"channelProfile");m(this,"clientRole");m(this,"env",It.prod);m(this,"maxSignalingReconnectDuration");m(this,"slsReporter");this.channelProfile=e,this.clientRole=t,this.env=s,this.slsReporter=i}reset(){var e;T.info("[signalingmanager] reset"),(e=this.signaling)==null||e.reset(),this.signaling=void 0,this.authInfo=void 0}join(e,t=e.userId,i,s,n){return this.maxSignalingReconnectDuration=i,this.userName=t,new Promise((c,o)=>{this.signaling?o(new U(B.ERR_JOIN_ALREADY_JOINED,"already joined")):(T.info("[signalingmanager] create signaling"),this.signaling=new pl(this.channelProfile,this.clientRole,this.slsReporter,this.env),this.initSignaling(),s&&(s.rs=Date.now()),this.signaling.join(e,t,i,n).then(l=>{this.authInfo=e,s&&(s.re=Date.now()),c(l)}).catch(l=>{this.reset(),o(l)}))})}retryJoin(){const e=this.authInfo;this.reset(),e&&this.join(e,this.userName,this.maxSignalingReconnectDuration)}leave(){return new Promise((e,t)=>{this.signaling?this.signaling.leave().then(i=>{this.reset(),e(i)}).catch(i=>{t(i)}):e({tid:""})})}publish(e){return new Promise((t,i)=>{var s;this.signaling&&this.authInfo?(e.userid=this.authInfo.userId,e.displayname=(s=this.userName)!=null?s:this.authInfo.userId,this.signaling.publish(e).then(n=>{t(n)}).catch(n=>{i(n)})):i(new U(B.ERR_SDK_PUBLISH_NOT_JOIN_CHANNEL,"no signaling"))})}reportStatus(e){return new Promise((t,i)=>{this.signaling?this.signaling.reportStatus(e).then(()=>{t()}).catch(s=>{i(s)}):i(new U(-1,"no signaling"))})}setClientRole(e){return I(this,null,function*(){const t=this.clientRole;if(!this.signaling)return void(this.clientRole=e);const i=Date.now();try{const s=yield this.signaling.roleUpdate(e);return this.slsReporter.reportRoleUpdateResult(t,e,Date.now()-i,0),s}catch(s){this.slsReporter.reportRoleUpdateResult(t,e,Date.now()-i,s.code||-1)}})}setChannelProfile(e){this.signaling?this.signaling.setChannelProfile(e):this.channelProfile=e}refreshUrl(e){return this.signaling?this.signaling.refreshUrl(e):Promise.reject(new U(B.ERR_SDK_INVALID_STATE,"should join first"))}refreshAuthInfo(e){return I(this,null,function*(){var t;try{this.authInfo&&(this.authInfo=X(X({},this.authInfo),e),(t=this.signaling)==null||t.refreshAuthInfo(this.authInfo))}catch(i){throw i}})}initSignaling(){var e,t,i,s,n,c,o,l,d,u,p,h,f,g;(e=this.signaling)==null||e.on("onKeepAliveRsp",this.onKeepAliveRsp.bind(this)),(t=this.signaling)==null||t.on("onNotifyJoin",this.onNotifyJoin.bind(this)),(i=this.signaling)==null||i.on("onNotifyStatus",this.onNotifyStatus.bind(this)),(s=this.signaling)==null||s.on("onNotifyLeave",this.onNotifyLeave.bind(this)),(n=this.signaling)==null||n.on("onNotifyPublish",this.onNotifyPublish.bind(this)),(c=this.signaling)==null||c.on("onBye",this.onBye.bind(this)),(o=this.signaling)==null||o.on("onReconnectStart",this.onReconnectStart.bind(this)),(l=this.signaling)==null||l.on("onReconnectSuccess",this.onReconnectSuccess.bind(this)),(d=this.signaling)==null||d.on("onReconnectFail",this.onReconnectFail.bind(this)),(u=this.signaling)==null||u.on("onConnectFail",this.onConnectFail.bind(this)),(p=this.signaling)==null||p.on("onNetworkError",this.onNetworkError.bind(this)),(h=this.signaling)==null||h.on("onAuthInvalid",this.onAuthInvalid.bind(this)),(f=this.signaling)==null||f.on("onError",this.onError.bind(this)),(g=this.signaling)==null||g.on("onUnknownMessage",this.onUnknownMessage.bind(this))}onKeepAliveRsp(){this.emit("onKeepAliveRsp")}onNotifyJoin(e){this.emit("onNotifyJoin",e)}onNotifyStatus(e){this.emit("onNotifyStatus",e)}onNotifyLeave(e){this.emit("onNotifyLeave",e)}onNotifyPublish(e){this.emit("onNotifyPublish",e)}onBye(e,t){this.emit("onBye",e,t)}onConnectFail(e){this.reset(),this.emit("onConnectFail",e)}onNetworkError(e){this.emit("onNetworkError",e)}onAuthInvalid(){}onReconnectStart(){this.emit("onReconnectStart")}onReconnectSuccess(e){this.emit("onReconnectSuccess",e)}onReconnectFail(e){this.emit("onReconnectFail",e)}onError(e){this.emit("onError",e)}onUnknownMessage(e){this.emit("onUnknownMessage",e)}}m(cr,"logName","SignalingManager"),((a,r,e,t)=>{for(var i,s=t>1?void 0:t?gl(r,e):r,n=a.length-1;n>=0;n--)(i=a[n])&&(s=(t?i(r,e,s):i(s))||s);t&&s&&ml(r,e,s)})([k(H)],cr.prototype,"publish",1);class Wn{constructor(r){m(this,"taskProfile");m(this,"encodeParam");m(this,"users",[]);m(this,"backgroundColor",0);m(this,"backgrounds",[]);m(this,"watermarks",[]);m(this,"clockWidgets",[]);m(this,"cropMode");m(this,"mediaProcessMode");this.taskProfile=r}}class zn{constructor(r,e,t){m(this,"userId");m(this,"streamType");m(this,"sourceType");this.userId=r,this.streamType=e,this.sourceType=t}}class Kn{constructor(r,e,t,i=0,s=16777215,n=xi.NOTO_SERIF_CJKSC_REGULAR){m(this,"x");m(this,"y");m(this,"fontSize");m(this,"zOrder");m(this,"fontColor");m(this,"fontType");this.x=r,this.y=e,this.fontSize=t,this.zOrder=i,this.fontColor=s,this.fontType=n}toJson(r,e){return{x:_t(this.x,r),y:_t(this.y,e),fonttype:this.fontType,fontsize:this.fontSize,fontcolor:tr(this.fontColor),zorder:this.zOrder}}}var Jn=(a=>(a[a.NOT_DISPLAY=0]="NOT_DISPLAY",a[a.ALWAYS=1]="ALWAYS",a[a.WHEN_NO_VIDEO=2]="WHEN_NO_VIDEO",a))(Jn||{});class lr{constructor(r,e,t,i,s,n=0,c=1,o=1){m(this,"url");m(this,"x");m(this,"y");m(this,"width");m(this,"height");m(this,"alpha");m(this,"display",1);m(this,"zOrder");this.url=r,this.x=e,this.y=t,this.width=i,this.height=s,this.zOrder=n,this.alpha=c,this.display=o}toJson(r,e){return{url:this.url,alpha:this.alpha,display:this.display,x:_t(this.x,r),y:_t(this.y,e),width:_t(this.width,r),height:_t(this.height,e),zorder:this.zOrder}}}m(lr,"DisplayType",Jn);class qn{constructor(r,e,t,i,s=0,n=16777215,c=xi.NOTO_SERIF_CJKSC_REGULAR){m(this,"text");m(this,"x");m(this,"y");m(this,"fontSize");m(this,"zOrder");m(this,"fontColor");m(this,"fontType");this.text=r,this.x=e,this.y=t,this.fontSize=i,this.zOrder=s,this.fontColor=n,this.fontType=c}toJson(r,e){return{text:this.text,x:_t(this.x,r),y:_t(this.y,e),fonttype:this.fontType,fontsize:this.fontSize,fontcolor:tr(this.fontColor),zorder:this.zOrder}}}class Gn{constructor(r,e,t,i,s,n=0,c){m(this,"userId");m(this,"x");m(this,"y");m(this,"width");m(this,"height");m(this,"zOrder");m(this,"sourceType");m(this,"segmentType",Ni.LiveTranscodingNoBody);m(this,"images",[]);m(this,"texts",[]);this.userId=typeof r=="number"?r.toString():r,this.x=e,this.y=t,this.width=i,this.height=s,this.zOrder=n,c&&(this.sourceType=c)}toJson(r,e,t,i){const s={paneid:r,majorpane:0,x:_t(this.x,e),y:_t(this.y,t),width:_t(this.width,e),height:_t(this.height,t),zorder:this.zOrder,userid:this.userId,images:this.images.map(n=>n.toJson(e,t)),texts:this.texts.map(n=>n.toJson(e,t))};return this.sourceType&&Li[this.sourceType]?s.sourcetype=Li[this.sourceType]:s.sourcetype=Li[vi.LiveTranscodingCamera],this.segmentType&&i===Yi.LiveTranscodingVirtualBackground?s.segmenttype=this.segmentType:s.segmenttype=Ni.LiveTranscodingNoBody,s}}class fl{constructor(r){m(this,"_updateables");m(this,"_useWebworker");m(this,"_inited");m(this,"_active");m(this,"_previousRAFTime");m(this,"_previousWorkerTime");m(this,"_webWorkerString");m(this,"_webWorker");m(this,"_intervalThreshold");m(this,"_rafId");m(this,"_focusHandler",null);m(this,"_blurHandler",null);m(this,"_visibilityHandler",null);this._updateables=[],this._useWebworker=!1,this._inited=!1,this._active=!1,this._previousRAFTime=void 0,this._previousWorkerTime=void 0,this._intervalThreshold=r&&r>0&&r<=60?1/r:.1,this._webWorkerString=`
135
135
  var running = false;
136
136
  function tick(){
137
137
  postMessage(Date.now());
@@ -146,4 +146,4 @@ onmessage = function(evt) {
146
146
  tick();
147
147
  }
148
148
  if (data === 'stop') running = false;
149
- });`,this._webWorker=void 0}_initWebWorker(){window.URL=window.URL||window.webkitURL;let r=new Blob([this._webWorkerString],{type:"application/javascript"});this._webWorker=new Worker(URL.createObjectURL(r)),this._webWorker.onmessage=e=>{let t=e.data;this._updateWorkerTime(t)}}_lostVisibility(){var r;this._previousWorkerTime=Date.now(),this._useWebworker=!0,this._webWorker||this._initWebWorker(),this._active&&((r=this._webWorker)==null||r.postMessage("start"))}_gainedVisibility(){this._useWebworker=!1,this._previousRAFTime=void 0,this._webWorker&&this._webWorker.postMessage("stop"),this._active&&(this._rafId=requestAnimationFrame(this._updateRAFTime.bind(this)))}_init(){if(window.Worker){if(document.hidden===void 0)return this._focusHandler=this._gainedVisibility.bind(this),this._blurHandler=this._lostVisibility.bind(this),window.addEventListener("focus",this._focusHandler),void window.addEventListener("blur",this._blurHandler);this._visibilityHandler=()=>{document.hidden===!0?this._lostVisibility():this._gainedVisibility()},document.addEventListener("visibilitychange",this._visibilityHandler,!1)}}_stopUpdate(){this._active=!1,this._rafId&&(cancelAnimationFrame(this._rafId),this._rafId=0),this._useWebworker&&this._webWorker&&this._webWorker.postMessage("stop")}destroy(){this._focusHandler&&(window.removeEventListener("focus",this._focusHandler),this._focusHandler=null),this._blurHandler&&(window.removeEventListener("blur",this._blurHandler),this._blurHandler=null),this._visibilityHandler&&(document.removeEventListener("visibilitychange",this._visibilityHandler),this._visibilityHandler=null),this._stopUpdate()}_updateWorkerTime(r){let e=(r-(this._previousWorkerTime||0))/1e3;e>this._intervalThreshold&&(this._update(e),this._previousWorkerTime=r)}_updateRAFTime(r){this._previousRAFTime===void 0&&(this._previousRAFTime=r);let e=(r-this._previousRAFTime)/1e3;e>this._intervalThreshold&&(this._update(e),this._previousRAFTime=r),!this._useWebworker&&this._active?this._rafId=requestAnimationFrame(this._updateRAFTime.bind(this)):this._rafId=0}_update(r){for(let e=0;e<this._updateables.length;e++)this._updateables[e]._update(typeof r=="number"?r:parseFloat(r))}register(r){this._updateables.push(r),this._inited===!1&&(this._inited=!0,this._init()),this._active===!1&&(this._rafId=requestAnimationFrame(this._updateRAFTime.bind(this)),this._active=!0)}unregister(r){const e=this._updateables.indexOf(r);e!==-1&&this._updateables.splice(e,1),this._updateables.length===0&&this._stopUpdate()}}class Xn extends jt{constructor(e,t=10){super("AliRtcImageHolder");m(this,"url");m(this,"image");m(this,"canvas");m(this,"mediaStream");m(this,"updateableManager");m(this,"updateable");m(this,"hasVideoTrack",!1);this.url=e,this.canvas=document.createElement("canvas"),this.canvas.width=1280,this.canvas.height=720,this.drawImageToCanvas(),this.updateableManager=new fl(t)}get initOptions(){return{imageUrl:""}}setOptions(e){e.imageUrl&&(this.options=e,e.imageUrl!==this.url&&this.drawImageToCanvas())}drawImageToCanvas(){return I(this,null,function*(){if(!this.url)return;const e=this.canvas.getContext("2d"),t=document.createElement("img");let i;this.image=t,t.crossOrigin="anonymous",t.src=this.url;const{width:s,height:n}=yield new Promise(c=>{t.onload=()=>{i&&clearTimeout(i),c({width:t.width||16,height:t.height||16})},t.onerror=()=>{i&&clearTimeout(i),c({width:16,height:16})},i=setTimeout(()=>{c({width:16,height:16})},5e3)});this.canvas.width=s,this.canvas.height=n,e.drawImage(t,0,0,s,n)})}start(){return I(this,null,function*(){var i;if(!this.url)throw new Error("no image url founded");if(!this.canvas)throw new Error("get canvas error");const e=this.canvas.captureStream(25),t=this.canvas.getContext("2d");return this.image&&this.image.width&&t.drawImage(this.image,0,0,this.image.width,this.image.height),this.mediaStream=e,t.fillStyle="transparent",this.updateable={_update:()=>{t.fillRect(0,0,1,1)}},this.updateableManager.register(this.updateable),(i=e.getVideoTracks())==null?void 0:i[0]})}stop(){var e,t;this.updateable&&(this.updateableManager.unregister(this.updateable),this.updateable=null),this.updateableManager.destroy(),(t=(e=this.mediaStream)==null?void 0:e.getVideoTracks()[0])==null||t.stop(),this.mediaStream=void 0}isSupported(){return!0}shouldUpdate(e){return this.hasVideoTrack===!!e.originVideoTrack}process(e){return I(this,null,function*(){if(this.hasVideoTrack=!!e.originVideoTrack,e.originVideoTrack){const i=e.currentVideoTrack;return i&&i.id===e.originVideoTrack.id||e.updateVideoTrack(e.originVideoTrack),void this.stop()}const t=yield this.start();e.updateVideoTrack(t)})}}class Vi{static checkString(r){return typeof r=="string"}static checkNumber(r){return typeof r=="number"}static checkHtmlVideoElement(r){return r&&r.nodeName==="VIDEO"}static checkHtmlAudioElement(r){return r&&r.nodeName==="AUDIO"}static checkAuthInfo(r){return r?r.appId?r.channelId?Vi.checkString(r.channelId)?r.userId?Vi.checkString(r.userId)?r.timestamp?Vi.checkNumber(r.timestamp)?r.token?null:new U(B.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"no token founded"):new U(B.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"timestamp is not number"):new U(B.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"no timestamp founded"):new U(B.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"userId is not string"):new U(B.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"no userId founded"):new U(B.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"channelId is not string"):new U(B.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"no channelId founded"):new U(B.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"no appId founded"):new U(B.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"no authInfo founded")}static checkMediaStreamTrack(r){return r instanceof MediaStreamTrack}static checkVideoEncoderConfiguration(r){return r&&(r.width||r.height||r.frameRate||r.bitrateMax)}}var bl=Object.defineProperty,Sl=Object.getOwnPropertyDescriptor,$=(a,r,e,t)=>{for(var i,s=t>1?void 0:t?Sl(r,e):r,n=a.length-1;n>=0;n--)(i=a[n])&&(s=(t?i(r,e,s):i(s))||s);return t&&s&&bl(r,e,s),s};let Qt,Qn=!1;const j=(F=class extends oe{constructor(e,t){super();m(this,"instanceId");m(this,"_globalEnv");m(this,"channelProfile");m(this,"clientRole");m(this,"signalingManager");m(this,"bizControl");m(this,"liveTranscoding");m(this,"maxSignalingReconnectDuration");m(this,"slsReporter");m(this,"connectState",ae.AliRtcConnectionStatusInit);m(this,"networkError",!1);m(this,"_audioOnlyMode",!1);m(this,"_destroyed",!1);m(this,"_authInfoWillExpireTimer",null);m(this,"_authInfoExpiredTimer",null);m(this,"_serverCheckAuthInfoTimestamp",null);m(this,"_localCheckAuthInfoTimestamp",null);m(this,"_proxyAiTid",null);m(this,"_agentParam",null);m(this,"sessionId");this.config=e,this.instanceId=t||(e==null?void 0:e.instanceId)||`rtc_default_${Date.now()}`,this._globalEnv=e==null?void 0:e.globalEnv;const i=Date.now();T.init(this.instanceId,e==null?void 0:e.globalEnv),this.slsReporter=new dl(this,e==null?void 0:e.globalEnv),this.channelProfile=Ut.AliRtcSdkCommunication,this.clientRole=zt.AliRtcSdkLive,this.liveTranscoding=new al(this.slsReporter),this.signalingManager=new cr(this.channelProfile,this.clientRole,this.slsReporter,(e==null?void 0:e.env)===It.pre?It.pre:It.prod),this.addSignalingManagerListeners(),this.maxSignalingReconnectDuration=e==null?void 0:e.maxSignalingReconnectDuration,this.bizControl=new et({slsReporter:this.slsReporter,signalingManager:this.signalingManager,parameter:e==null?void 0:e.parameter,instanceId:this.instanceId}),this.addBizControlListeners(),this.addPublisherListeners(),this.slsReporter.reportConnectionLatencyEvent(Ze.CREATE_ENGINE,st.START,"","",i),this.slsReporter.reportConnectionLatencyEvent(Ze.CREATE_ENGINE,st.END,"","",Date.now()),this.slsReporter.reportSDKCreated(i),pi++,mi||(mi=!0,window.addEventListener("mousedown",nt),window.addEventListener("touchstart",nt))}static getSdkVersion(){return _i}static setLogLevel(e){T.setLogLevel(e)}static createInstance(e){J.AliRTS.ENV=(e==null?void 0:e.globalEnv)==="SEA"?"SEA":void 0;const t=(e==null?void 0:e.instanceId)||`rtc_${++F._instanceCounter}_${Date.now()}`,i=new F(e,t);return F._instances.set(t,i),i.configureTracer(e),i}static getAllInstances(){return Array.from(F._instances.values())}static getInstanceById(e){return F._instances.get(e)}static destroyAll(){return I(this,null,function*(){const e=Array.from(F._instances.values());yield Promise.all(e.map(t=>t.destroy()))})}static getInstance(e){return F._instance||(J.AliRTS.ENV=(e==null?void 0:e.globalEnv)==="SEA"?"SEA":void 0,F._instance=new F(e),F._instance.configureTracer(e)),F._instance}destroy(){return I(this,null,function*(){var e,t,i;this._destroyed||(this._destroyed=!0,F._instances.delete(this.instanceId),F._instance===this&&(F._instance=void 0),yield this.leaveChannel(),yield this.bizControl.clear(),this.removeAllListeners(),(e=this.bizControl)==null||e.removeAllListeners(),(t=this.signalingManager)==null||t.removeAllListeners(),(i=this.slsReporter)==null||i.stop(),pi--,pi<=0&&(pi=0,mi&&(mi=!1,window.removeEventListener("mousedown",nt),window.removeEventListener("touchstart",nt))),T.destroy(this.instanceId))})}configureTracer(e){Qn||(Qt==null||Qt.updateOptions({region:(e==null?void 0:e.globalEnv)==="SEA"?"sg":"cn"}),Qt==null||Qt.setReady(),Qn=!0)}syncGlobalEnv(){J.AliRTS.ENV=this._globalEnv==="SEA"?"SEA":void 0}get channel(){return this.bizControl.channel}get userId(){return this.bizControl.userId}get remoteUsers(){return this.bizControl.remoteUsers}get publisher(){return this.bizControl.publisher}get publishAudioStream(){return this.publisher.publishStreams.audio}get isPublishing(){const{publisher:e}=this.bizControl;return!!e&&e.isPublishing}get currentRoleCanPublish(){return this.channelProfile===Ut.AliRtcSdkCommunication||this.clientRole===zt.AliRtcSdkInteractive}addPublisherListeners(){this.publisher.on(ot.Local,e=>{T.setActiveInstance(this.instanceId),T.event("[Publisher] Device Status Change",e),this.onLocalDeviceStatusChange(e)}),this.publisher.on(oi.VideoTrackEnded,()=>{T.setActiveInstance(this.instanceId),T.event("[Publisher] VideoTrack Ended"),this.emit("localDeviceException",kt.AliEngineLocalDeviceTypeCamera,je.AliEngineLocalDeviceExceptionTypeCameraInterrupt,"")}),this.publisher.on(oi.ScreenTrackEnded,()=>{T.setActiveInstance(this.instanceId),T.event("[Publisher] ScreenTrack Ended"),this.emit("localDeviceException",kt.AliEngineLocalDeviceTypeDisplay,je.AliEngineLocalDeviceExceptionTypeDisplayException,"")}),this.publisher.on(oi.AudioTrackEnded,()=>{T.setActiveInstance(this.instanceId),T.event("[Publisher] AudioTrack Ended"),this.emit("localDeviceException",kt.AliEngineLocalDeviceTypeMic,je.AliEngineLocalDeviceExceptionTypeMicInterrupt,"")}),this.publisher.on("localDeviceException",(e,t,i="")=>{this.emit("localDeviceException",e,t,i)}),this.publisher.on("audioPublishStateChanged",(e,t,i)=>{var s;this.emit("audioPublishStateChanged",e,t,i,(s=this.channel)!=null?s:"")}),this.publisher.on("videoPublishStateChanged",(e,t,i)=>{var s;this.emit("videoPublishStateChanged",e,t,i,(s=this.channel)!=null?s:"")}),this.publisher.on("dualStreamPublishStateChanged",(e,t,i)=>{var s;this.emit("dualStreamPublishStateChanged",e,t,i,(s=this.channel)!=null?s:"")}),this.publisher.on("screenPublishStateChanged",(e,t,i)=>{var s;this.emit("screenSharePublishStateChanged",e,t,i,(s=this.channel)!=null?s:"")}),this.publisher.on("dataPublishStateChanged",(e,t,i)=>{var s;this.emit("dataPublishStateChanged",e,t,i,(s=this.channel)!=null?s:"")})}occurError(e,t){T.setActiveInstance(this.instanceId),T.event(`[${F.logName}]`,"Occur Error",e,t),this.emit("onOccurError",e,t),this.emit("occurError",e,t)}addBizControlListeners(){this.bizControl.rtsManager.on("disconnected",()=>I(this,null,function*(){T.setActiveInstance(this.instanceId),T.event(`[${F.logName}]`,"RTS Disconnected"),(yield Le.isNetworkAvailable())?this.onNetworkRecovery():this.onNetworkError()})),this.bizControl.rtsManager.on("subscribeexceeds",()=>I(this,null,function*(){T.setActiveInstance(this.instanceId),T.event(`[${F.logName}]`,"RTS SubscribeExceeds"),this.bizControl.rtsManager.clear(),yield this.resumePublishForNetworkRecovery(),yield this.resumeSubList()})),this.bizControl.rtsManager.on("seimessage",(e,t,i)=>I(this,null,function*(){const s=this.remoteUsers.find(n=>Le.removeQueryString(n.streamUrl)===Le.removeQueryString(e));if(s){try{this.emit("mediaExtensionMsgReceived",s.userId,i,t)}catch(n){}if(t===99)try{const n=JSON.parse(new TextDecoder().decode(i)),c=n.pub||{},o=n.grtn||{},l=n.sub||{};let d;d=Object.keys(o).length?(c.vTotalCost||0)+(c.upRTTHalf||0)+(o.totalCost||0)+(l.downRTTHalf||0)+(l.vTotalCost||0):(c.vEncPlugCost||0)+((c.timestampRecv||0)-(c.timestamp||0))+(l.vJitterBufferDelay||0)+(l.vDecPlugCost||0);const u=s.streamInfo.getVideoLargeInfo(),p=s.streamInfo.getVideoSmallInfo(),h=[u,p,s.streamInfo.getScreenInfo()].filter(f=>f&&f.subscribeState===de.Subscribed&&f.msid);for(const f of h)try{this.emit("rtcCumuDelayReceived",s.userId,f.msid,d)}catch(g){}if(s.audioSSRC&&this.slsReporter.reportCumuAudioDelay(s.audioSSRC,n),s.videoSSRC){const f=yield this.bizControl.rtsManager.getSubscribeVideoStats(e);(f==null?void 0:f.frameHeight)===16&&(f==null?void 0:f.frameWidth)===16||this.slsReporter.reportCumuVideoDelay(s.videoSSRC,n)}}catch(n){}}})),this.bizControl.on(ot.Remote,(e,t)=>{T.setActiveInstance(this.instanceId),T.event(`[${F.logName}]`,"RemoteUser Device Status Change",e,t)}),this.bizControl.on("remoteUserJoin",(e,t)=>{this.emit("remoteUserOnLineNotify",e,t)}),this.bizControl.on("remoteTrackAvailableChange",(e,t,i)=>{this.emit("remoteTrackAvailableNotify",e,t,i)}),this.bizControl.on("audioSubscribeStateChanged",(e,t,i,s,n)=>{this.emit("audioSubscribeStateChanged",e,t,i,s,n)}),this.bizControl.on("videoSubscribeStateChanged",(e,t,i,s,n)=>{this.emit("videoSubscribeStateChanged",e,t,i,s,n)}),this.bizControl.on("screenSubscribeStateChanged",(e,t,i,s,n)=>{this.emit("screenShareSubscribeStateChanged",e,t,i,s,n)}),this.bizControl.on("dataSubscribeStateChanged",(e,t,i,s,n)=>{this.emit("dataSubscribeStateChanged",e,t,i,s,n)}),this.bizControl.on("userAudioMuted",(e,t)=>{this.emit("userAudioMuted",e,t)}),this.bizControl.on("userVideoMuted",(e,t)=>{this.emit("userVideoMuted",e,t)}),this.bizControl.on("userScreenMuted",(e,t)=>{this.emit("userScreenMuted",e,t)}),this.bizControl.on("audioVolume",e=>{this.emit("audioVolume",e)}),this.bizControl.on("remoteAudioAutoPlayFail",e=>{this.emit("remoteAudioAutoPlayFail",e)}),this.bizControl.on("remoteVideoAutoPlayFail",(e,t)=>{this.emit("remoteVideoAutoPlayFail",e,t)}),this.bizControl.on("remoteAudioPlayError",(e,t)=>{this.emit("remoteAudioPlayError",e,t)}),this.bizControl.on("remoteVideoPlayError",(e,t)=>{this.emit("remoteVideoPlayError",e,t)}),this.bizControl.on("rtcStats",e=>{this.emit("rtcStats",e)}),this.bizControl.on("rtcLocalAudioStats",e=>{this.emit("rtcLocalAudioStats",e)}),this.bizControl.on("rtcLocalVideoStats",e=>{this.emit("rtcLocalVideoStats",e)}),this.bizControl.on("rtcRemoteAudioStats",e=>{this.emit("rtcRemoteAudioStats",e)}),this.bizControl.on("rtcRemoteVideoStats",e=>{this.emit("rtcRemoteVideoStats",e)}),this.bizControl.on("remoteSubscribeError",(e,t)=>{this.occurError(e,t),this.slsReporter.reportError(e)}),this.bizControl.on("occurError",(e,t)=>{this.occurError(e,t),this.slsReporter.reportError(e)}),this.bizControl.on("remoteDataChannelMessage",(e,t)=>{this.emit("dataChannelMsg",e,t)}),this.bizControl.on("remoteUserSubscribedDataChannel",e=>{this.emit("remoteUserSubscribedDataChannel",e)}),this.bizControl.on("networkQuality",e=>{this.emit("networkQuality",e)})}addSignalingManagerListeners(){this.signalingManager.on("onKeepAliveRsp",()=>{this.networkError&&(T.setActiveInstance(this.instanceId),T.event("[Signaling] Receive KeepAlive Response",`networkError: ${this.networkError}`),this.onNetworkRecovery())}),this.signalingManager.on("onNotifyJoin",e=>{T.setActiveInstance(this.instanceId),T.event("[Signaling] Notify Join ",e),this.handleUsersJoin(e)}),this.signalingManager.on("onNotifyStatus",e=>{T.setActiveInstance(this.instanceId),T.event("[Signaling] Notify Status ",e),e.forEach(t=>{this.bizControl.updateRemoteUserDeviceStatus(t)})}),this.signalingManager.on("onNotifyLeave",e=>{T.setActiveInstance(this.instanceId),T.event("[Signaling] Notify Leave ",e),e.forEach(t=>I(this,null,function*(){yield this.bizControl.removeLeftUser(t),this.emit("remoteUserOffLineNotify",t.userid,t.leavecode)}))}),this.signalingManager.on("onBye",(e,t)=>{T.setActiveInstance(this.instanceId),T.event("[Signaling] Bye ",e,t),this.slsReporter.reportError({message:`reason: ${e}, description: ${t}`}),this.emit("bye",e),this.signalingManager.reset(),this.leaveChannel(),this.slsReporter.reportBye(e)}),this.signalingManager.on("onConnectFail",e=>{T.setActiveInstance(this.instanceId),T.event("[Signaling] Connect Failed ",e),this.onError(e),this.backToUnpublishStatus(),this.bizControl.leave(),this.signalingManager.reset(),this.connectState=ae.AliRtcConnectionStatusFailed,this.emit("connectionStatusChange",ae.AliRtcConnectionStatusFailed,Pt.AliRtcConnectionChangedNetworkInterrupted)}),this.signalingManager.on("onNetworkError",e=>{this.slsReporter.reportWarning("signaling network error"),T.setActiveInstance(this.instanceId),T.event("[Signaling] Network error ",e),this.onNetworkError()}),this.signalingManager.on("onAuthInvalid",()=>{T.setActiveInstance(this.instanceId),T.event("[Signaling] Auth Invalid")}),this.signalingManager.on("onReconnectStart",()=>{this.onNetworkError(),T.setActiveInstance(this.instanceId),T.event("[Signaling] Reconnect Start "),this.connectState=ae.AliRtcConnectionStatusReconnecting,this.emit("connectionStatusChange",ae.AliRtcConnectionStatusReconnecting,Pt.AliRtcConnectionSignalingConnecting)}),this.signalingManager.on("onReconnectSuccess",e=>{T.setActiveInstance(this.instanceId),T.event("[Signaling] Reconnect Success ",e),this.onNetworkRecovery(e)}),this.signalingManager.on("onReconnectFail",e=>{this.slsReporter.reportWarning("signaling reconnect fail: ${err.code}"),T.setActiveInstance(this.instanceId),T.event("[Signaling] Reconnect Failed ",e),e.code===403&&this.emit("authInfoExpired")}),this.signalingManager.on("onError",e=>{this.slsReporter.reportWarning("signaling error: ${err.message}"),T.setActiveInstance(this.instanceId),T.event("[Signaling] Error ",e),this.onError(e)}),this.signalingManager.on("onUnknownMessage",e=>{if(e.msgtype==="proxyai"&&e.tid===this._proxyAiTid){let t=e.data.retcode;t===200&&(t=0),this.emit("AIAgentResult",t,this._agentParam.action,e.data.body)}})}backToUnpublishStatus(){this.connectState=ae.AliRtcConnectionStatusDisconnected,this.publisher.isPublishing&&this.publisher.clearPublishState(),this.networkError=!1}handleUsersJoin(e){e.forEach(t=>{this.bizControl.addUser(t,ge.Join)})}onLocalDeviceStatusChange(e){T.event(`[${F.logName}]`,ot.Local,e),this.signalingManager.reportStatus(e).then(()=>{T.debug("[signaling] reportStatus suc")}).catch(t=>{T.error("[signaling] reportStatus failed",t)})}resumePublishForNetworkRecovery(){return I(this,null,function*(){try{yield this.publisher.resumePublish()}catch(e){const{code:t}=e;if(t===10205){let s=1;try{yield new Promise((n,c)=>{const o=setInterval(()=>I(this,null,function*(){s>1&&(clearInterval(o),c()),s+=1;try{yield this.publisher.resumePublish(),clearInterval(o),n()}catch(l){const{code:d}=l;d!==10205&&(clearInterval(o),c())}}),1e3)})}catch(n){}}throw e}})}onNetworkRecovery(e){return I(this,null,function*(){T.event(F.logName,"onNetworkRecovery",`rts isConnected: ${this.bizControl.rtsManager.isConnected}; rts isConnecting: ${this.bizControl.rtsManager.isConnecting}`,{users:e}),yield this.resumeSubList(e),this.networkError&&(this.networkError=!1,this.publisher.reportSelfDeviceStatus(),this.connectState=ae.AliRtcConnectionStatusConnected,this.emit("connectionStatusChange",ae.AliRtcConnectionStatusConnected,Pt.AliRtcConnectionSignalingHeartbeatAlive))})}resumeSubList(e){return I(this,null,function*(){if(e){const{joinList:t,leaveList:i,presentList:s}=this.bizControl.diffUsers(e);T.info(`[${F.logName}]`,"resumeSubList",{joinList:t,leaveList:i,presentList:s}),this.handleUsersJoin(t),i.forEach(n=>{T.event(F.logName,Me.UserLeft,n.userid,n.reason),this.bizControl.onRemotePublishStateChange({userid:n.userid,displayname:"",callid:"",tracks:[]}),this.bizControl.removeLeftUser(n),this.emit("remoteUserOffLineNotify",n.userid,ns.AliRtcUserOfflineQuit)}),s.forEach(n=>{this.bizControl.onRemotePublishStateChange(n)})}else for(let t=0;t<this.remoteUsers.length;t++){const i=this.remoteUsers[t];try{i.restore(),i.updateSubscribe(ge.Resume)}catch(s){}}})}retrySubscribe(e){return I(this,null,function*(){const t=this.bizControl.getRemoteUser(e);if(!t)throw new U(B.ERR_INNER,`no remote user(${e}) founded`);_e.getInstance().addEventData(_e.eventRetrySub,e),t.restore(),t.updateSubscribe(ge.Retry)})}onNetworkError(){this.connectState===ae.AliRtcConnectionStatusConnected&&(this.networkError||(this.connectState=ae.AliRtcConnectionStatusDisconnected,this.emit("connectionStatusChange",ae.AliRtcConnectionStatusDisconnected,Pt.AliRtcConnectionChangedNetworkInterrupted)),this.networkError=!0)}onError(e){this.slsReporter.reportError(e),T.event(F.logName,Me.Error,e)}setEnableDualVideoStream(e,t){this.bizControl.setEnableDualVideoStream(e,t)}hadPushStream(e){if(!this.publisher||!e)throw new U(B.ERR_INNER,"stream is not publishing")}getCurrentMicDeviceId(){return this.publisher.getCurrentMicDeviceId()}setChannelProfile(e){if(![ae.AliRtcConnectionStatusInit,ae.AliRtcConnectionStatusDisconnected,ae.AliRtcConnectionStatusFailed].includes(this.connectState))throw new U(B.ERR_INNER,"cannot set channel profile in call");this.channelProfile=e,this.channelProfile===Ut.AliRtcSdkCommunication&&(this.clientRole=zt.AliRtcSdkLive),this.signalingManager.setChannelProfile(e)}startDefaultDevices(){return I(this,null,function*(){if(!this.publisher)return;const{hasCamera:e,hasMicrophone:t,hasScreenShare:i}=this.publisher;if(!e&&!t&&!i){try{yield this.publisher.startDefaultCameraAndMic(this._audioOnlyMode)}catch(s){T.warn(`[${F.logName}]`,"startDefaultDevices failed",s.code,s.message),s instanceof U&&this.occurError(s);const n=s.code;this.occurError(new U(n>=B.ERR_CAMERA_OPEN_FAIL&&n<=B.ERR_CAMERA_NOT_AVAILABLE?B.ERR_SDK_PUBLISH_VIDEO_STREAM_FAILED:B.ERR_SDK_PUBLISH_AUDIO_STREAM_FAILED,`auto publish device failed, ${s.message||""}`))}yield this.publisher.previewAll()}})}startPublish(e){return I(this,null,function*(){try{yield this.publisher.startPublish(!1,e)}catch(t){const i=this.publisher.publishStreams||{},s=[];i!=null&&i.audio&&s.push(B.ERR_SDK_PUBLISH_AUDIO_STREAM_FAILED),i!=null&&i.video&&s.push(B.ERR_SDK_PUBLISH_VIDEO_STREAM_FAILED),s.forEach(n=>{this.occurError(new U(n,`auto publish stream failed, ${t.message||""}`))})}})}setClientRole(e){return I(this,null,function*(){this.syncGlobalEnv();try{if(this.channelProfile===Ut.AliRtcSdkCommunication)return;if(!Object.values(zt).includes(e))throw new U(B.ERR_INVALID_ARGUMENTS,`set client role error, role value(${e}) is invalid`);if(this.clientRole===e)return;this.slsReporter.reportRoleUpdate(this.clientRole,e),this.isInCall()?this.clientRole===zt.AliRtcSdkInteractive?(this.publisher.isPublishing?yield this.publisher.unPublish():yield this.publisher.clearStream(),yield this.signalingManager.setClientRole(e)):(yield this.signalingManager.setClientRole(e),yield this.startDefaultDevices(),yield this.startPublish(Dt.ROLE_CHANGE)):yield this.signalingManager.setClientRole(e),this.clientRole=e}catch(t){throw t.code===403&&this.emit("authInfoExpired"),t}})}getCurrentClientRole(){return this.clientRole}setAudioOnlyMode(e){if(this.isInCall())throw new U(B.ERR_INNER,"can not change audioOnly mode in call");this._audioOnlyMode=e}setAudioRedEnabled(e){if(this.isInCall())throw new U(B.ERR_INNER,"can not change audioRedEnabled in call");this.bizControl.setAudioRedEnabled(e)}setVideoCodec(e){this.bizControl.setVideoCodec(e)}setCheckAuthInfoTimer(e,t){const i=1e3*(e-t);this._authInfoExpiredTimer=window.setTimeout(()=>{this.emit("authInfoExpired")},i),this._authInfoWillExpireTimer=window.setTimeout(()=>{this.emit("authInfoWillExpire")},i-3e4),this._serverCheckAuthInfoTimestamp=t,this._localCheckAuthInfoTimestamp=+Date.now()/1e3}clearCheckAuthInfoTimer(){this._authInfoExpiredTimer&&window.clearTimeout(this._authInfoExpiredTimer),this._authInfoWillExpireTimer&&window.clearTimeout(this._authInfoWillExpireTimer)}joinChannel(s,n){return I(this,arguments,function*(e,t,i={}){this.syncGlobalEnv();const c=Date.now();let o,l=typeof t=="string"?t:t==null?void 0:t.userName;if(typeof e=="string")try{const p=JSON.parse(window.atob(e));o={appId:p.appid,channelId:p.channelid,userId:p.userid,timestamp:p.timestamp,nonce:p.nonce,token:p.token}}catch(p){throw new U(B.ERR_INVALID_ARGUMENTS,`authInfo is invalid: ${p.message||""}`)}else o=e;l||(l=o.userId);const d={start:Date.now()};let u=Vi.checkAuthInfo(o);if(ae.AliRtcConnectionStatusInit!==this.connectState&&ae.AliRtcConnectionStatusDisconnected!==this.connectState&&ae.AliRtcConnectionStatusFailed!==this.connectState){const p=new U(B.ERR_JOIN_ALREADY_JOINED,"already joined");throw this.connectState===ae.AliRtcConnectionStatusConnecting&&(p.message="Repeated operation during login"),this.slsReporter.reportJoin(p.code,d,""),p}{if(u)throw this.connectState=ae.AliRtcConnectionStatusFailed,this.slsReporter.reportJoin(u.code,d,""),this.slsReporter.reportJoinResult(u),u;o.sessionId=Le.createCallid("web"),this.sessionId=o.sessionId,this.slsReporter.start(o),this.slsReporter.reportConnectionLatencyEvent(Ze.JOIN,st.START,"","",c),this.connectState=ae.AliRtcConnectionStatusConnecting,this.emit("connectionStatusChange",ae.AliRtcConnectionStatusConnecting,Pt.AliRtcConnectionSignalingConnecting),T.setActiveInstance(this.instanceId),T.setSessionID(o.appId,o.sessionId);const p=()=>I(this,null,function*(){var g,b,S,v;try{let R="Conference";typeof t=="object"&&t.capabilityProfile===Di.Human&&(R="AIUser");const _=JSON.parse(this.getParameter());_.joinMode&&(R=_.joinMode);const y=new Ii(((g=this.config)==null?void 0:g.env)||It.prod,o,R);if(y.result){const C=(h=y.result.config,f=at.EnableNonOnePcDefaultJoinMode,ii(h==null?void 0:h.data,f));y.result.useonepc&&C!==!1||(R=""),T.info(`[${Ii.logName}]`,"got allocate result from localStorage",`joinMode: ${R}`,y.result.useonepc,C)}else T.info(`[${Ii.logName}]`,"no allocate result in localStorage",`joinMode: ${R}`);R&&(i.joinmode=R);const w=Date.now(),A=yield this.signalingManager.join(o,l,this.maxSignalingReconnectDuration,d,i);A.l1ip?(T.info("allocate l1 pub ip with mode",R,A.l1ip),this.bizControl.rtsManager.preferredPubL1Ip=A.l1ip):this.bizControl.rtsManager.preferredPubL1Ip=void 0,A.l1subip?(T.info("allocate l1 sub ip with mode",R,A.l1subip),this.bizControl.rtsManager.preferredSubL1Ip=A.l1subip):this.bizControl.rtsManager.preferredSubL1Ip=void 0;const E=Date.now();if(this.connectState=ae.AliRtcConnectionStatusConnected,this.emit("connectionStatusChange",ae.AliRtcConnectionStatusConnected,Pt.AliRtcConnectionSignalingJoinRoomSuccess),y.fetchAndUpdate(),this.bizControl.init(o,A,{capabilityProfile:typeof t=="object"?t.capabilityProfile:Di.Default,robotUserId:typeof t=="object"?t.robotUserId:void 0}),(b=A==null?void 0:A.config)==null?void 0:b.data){this.bizControl.updateDynamicConfig(A.config.data),_e.setGlobalQualityStatsEnable((S=this.bizControl.rtsManager.dycConf.getDycConf("h5_quality_stats_enable"))!=null?S:!0);const C=this.bizControl.rtsManager.dycConf.getDycConf("h5_low_perf_devices")||"";if(C){const P=ka();P&&(Array.isArray(C)?C:String(C).split(",").map(M=>M.trim()).filter(Boolean)).includes(P)&&(T.info("[LowPerfDevice]",`Current device "${P}" is in low performance device list, suggesting lower resolution subscription`),this.emit("sdkAdvisory",{type:"lowPerformanceDevice",deviceModel:P}),this.bizControl.rtsManager.isLowPerfDevice=!0)}}this.setCheckAuthInfoTimer(o.timestamp,A.timestamp),this.liveTranscoding.setAuthInfo(o),this.slsReporter.reportJoin(0,d,A.tid),this.slsReporter.reportJoinResult(null),this.slsReporter.reportConnectionLatencyEvent(Ze.JOIN,st.SEND_SIG,"","",w),this.slsReporter.reportConnectionLatencyEvent(Ze.JOIN,st.RECV_RST,"","",E),this.slsReporter.reportConnectionLatencyEvent(Ze.JOIN,st.END,"","")}catch(R){const _=(v=R.code)!=null?v:-1,y=R.reason||R.message||"";throw this.connectState=ae.AliRtcConnectionStatusDisconnected,this.emit("connectionStatusChange",ae.AliRtcConnectionStatusDisconnected,Pt.AliRtcConnectionSignalingJoinRoomFailure),this.slsReporter.reportJoin(_,d,""),this.slsReporter.reportJoinResult(R),new U(_,y)}var h,f});this.currentRoleCanPublish?(yield Promise.all([p(),this.startDefaultDevices()]),yield this.startPublish(Dt.JOIN_CHANNEL)):yield p(),this.publisher.reportSelfDeviceStatus(),this.remoteUsers.forEach(h=>{h.updateSubscribe(ge.Join)})}})}joinAIChannel(e,t,i){return I(this,null,function*(){return this._proxyAiTid=mt(),this._agentParam=i,this.joinChannel(e,t,{proxyai:{tid:this._proxyAiTid,region:i.region,proxydata:JSON.stringify({Region:i.region,Action:i.action,ActionParams:i.params})}})})}leaveChannel(){return I(this,null,function*(){var t;this.slsReporter.reportLeaveInvoked(),yield this.bizControl.leave();let e=new Date().getTime();if(ae.AliRtcConnectionStatusConnected===this.connectState)try{let i;i=yield this.signalingManager.leave(),this.slsReporter.reportLeave(new Date().getTime()-e,0,(t=i==null?void 0:i.tid)!=null?t:"")}catch(i){this.slsReporter.reportLeave(new Date().getTime()-e,i.code,i.reason)}else this.slsReporter.reportLeave(0,0,"");this.sessionId=void 0,this.networkError=!1,this.connectState=ae.AliRtcConnectionStatusDisconnected,this.clearCheckAuthInfoTimer(),this.liveTranscoding.clear(),this.slsReporter.stop(),this.signalingManager.reset(),T.setActiveInstance(this.instanceId),T.reportEnd()})}isInCall(){return this.connectState===ae.AliRtcConnectionStatusConnected}refreshAuthInfo(e){return I(this,null,function*(){let t;if(this.syncGlobalEnv(),typeof e=="string")try{const d=JSON.parse(window.atob(e));t={userId:d.userid,timestamp:d.timestamp,nonce:d.nonce,token:d.token}}catch(d){throw new U(B.ERR_INVALID_ARGUMENTS,`authInfo is invalid: ${d.message||""}`)}else t=e;const{userId:i,nonce:s,timestamp:n,token:c,role:o}=t,l={userId:i,nonce:s,timestamp:n,token:c,role:o};try{yield this.signalingManager.refreshAuthInfo(l),this.bizControl.refreshAuthInfo(l),this.liveTranscoding.refreshAuthInfo(l),this.clearCheckAuthInfoTimer(),this._serverCheckAuthInfoTimestamp&&this._localCheckAuthInfoTimestamp&&t.timestamp&&this.setCheckAuthInfoTimer(t.timestamp,this._serverCheckAuthInfoTimestamp+(Date.now()-this._localCheckAuthInfoTimestamp))}catch(d){throw d}})}isAudioOnly(){return this._audioOnlyMode}publishLocalAudioStream(e){return I(this,null,function*(){this.syncGlobalEnv(),this.publisher.setPublishLocalAudioStreamEnabled(e),this.connectState===ae.AliRtcConnectionStatusConnected&&(e?this.publisher.hasMicrophone?yield this.publisher.updateStreams():yield this.startAudioCapture():yield this.publisher.publishUpdate())})}isLocalAudioStreamPublished(){var e;return(e=this.publisher.publishLocalAudioStreamEnabled)!=null?e:!0}setDefaultSubscribeAllRemoteAudioStreams(e){this.bizControl.setAutoSubAudio(e)}subscribeAllRemoteAudioStreams(e){this.bizControl.setWantSubAudio(e)}subscribeRemoteAudioStream(e,t){if(t&&!this.bizControl.isWantSubAudio)throw new U(B.ERR_INVALID_ARGUMENTS,"subscribeAllRemoteAudioStreams(true) must be called first");this.bizControl.updateAudioWant(e,t)}resumeRemoteAudioStream(e){const t=this.bizControl.getRemoteUser(e);if(!t)throw new U(B.ERR_INNER,`no remote user(${e}) founded`);t.resumeAudio()}stopRemoteAudioPlay(e){const t=this.bizControl.getRemoteUser(e);if(!t)throw new U(B.ERR_INNER,`no remote user(${e}) founded`);t.stopPlayAudio()}publishLocalVideoStream(e){return I(this,null,function*(){this.syncGlobalEnv(),this.publisher.setPublishLocalVideoStreamEnabled(e),this.connectState===ae.AliRtcConnectionStatusConnected&&(e?this.publisher.hasCamera?yield this.publisher.updateStreams():yield this.enableLocalVideo():yield this.publisher.publishUpdate())})}isLocalVideoStreamPublished(){var e;return(e=this.publisher.publishLocalVideoStreamEnabled)!=null?e:!0}setRemoteDefaultVideoStreamType(e){[Ge.AliRtcVideoStreamTypeHigh,Ge.AliRtcVideoStreamTypeLow].includes(e)&&this.bizControl.setRemoteDefaultVideoStreamType(e)}setRemoteUserVideoStreamType(e,t){[Ge.AliRtcVideoStreamTypeHigh,Ge.AliRtcVideoStreamTypeLow].includes(t)&&this.bizControl.setRemoteUserVideoStreamType(e,t)}setDefaultSubscribeAllRemoteVideoStreams(e){this.bizControl.setAutoSubVideo(e),this.bizControl.setAutoSubScreen(e)}subscribeAllRemoteVideoStreams(e){this.bizControl.setWantSubVideo(e),this.bizControl.setWantSubScreen(e)}subscribeRemoteMediaStream(e,t,i,s){var o;const n=this.bizControl.getRemoteUser(e),c=_e.getInstance();if(!n)throw new U(B.ERR_INNER,`no remote user(${e}) founded`);if(!i||t!==ue.AliRtcVideoTrackScreen&&t!==ue.AliRtcVideoTrackBoth?n.setWantSubScreen(!1):n.setWantSubScreen(!0),!i||t!==ue.AliRtcVideoTrackCamera&&t!==ue.AliRtcVideoTrackBoth?n.setWantSubVideo(!1):n.setWantSubVideo(!0),n.setWantSubAudio(s),i||s)n.subscribe({video:i,audio:s},ge.User),c.addEventData(_e.eventStartSub,e,i,s);else{try{c.unsubscribeRemoteViewConfig(((o=this.bizControl.userId)!=null?o:"")+e)}catch(l){}n.stopSubscribe({video:!0,audio:!0}),c.addEventData(_e.eventRemoveSub,e,i,s)}}resumeRemoteMediaStream(e,t){const i=this.bizControl.getRemoteUser(e);i&&i.resumeVideo(t)}getOnlineRemoteUsers(){return this.bizControl.remoteUsers.map(e=>e.userId)}getUserInfo(e){var t;return(t=this.bizControl.getRemoteUser(e))==null?void 0:t.remoteUserInfo}isUserOnline(e){return!!this.bizControl.remoteUsers.find(t=>t.userId===e)}startScreenShare(e){return I(this,null,function*(){this.syncGlobalEnv();const t={video:!1,audio:!1},{audio:i=!1,videoTrack:s,audioTrack:n}=e||{};if(s||n){t.screen=!0;const c=new MediaStream;s&&c.addTrack(s),n&&c.addTrack(n),t.mediaStream=c}else t.screen=!i||{audio:!0};yield this.publisher.createLocalStream(t)})}stopScreenShare(){return I(this,null,function*(){this.publisher.stopLocalStream({screen:!0})})}setScreenShareConfiguration(e){return I(this,null,function*(){const{width:t,height:i}=e;if(t&&!isNaN(t)&&i&&!isNaN(i)&&t*i>9437184)throw new U(B.ERR_INVALID_ARGUMENTS,"width * height must be less than 9437184");const o=e,{bitrate:s}=o,n=Wt(o,["bitrate"]),c=X({},n);s&&(c.maxBitrate=e.bitrate),yield this.publisher.setScreenProfile(c)})}setScreenShareContentHint(e){return I(this,null,function*(){e&&this.publisher.setScreenContentHint(e)})}publishLocalScreenShareStream(e,t){return I(this,null,function*(){this.syncGlobalEnv(),this.publisher.setPublishLocalScreenStreamEnabled(e),this.connectState===ae.AliRtcConnectionStatusConnected&&(e?this.publisher.hasScreenShare?yield this.publisher.updateStreams():yield this.startScreenShare(t):yield this.publisher.publishUpdate())})}isScreenSharePublished(){var e;return(e=this.publisher.publishLocalScreenStreamEnabled)!=null?e:!0}setAudioShareVolume(e){if(typeof e!="number")throw new U(B.ERR_INVALID_ARGUMENTS,"volume must be a number");this.bizControl.setAudioVolume({screen:Math.max(0,Math.min(e,400))/100})}enableAudioVolumeIndication(e){this.bizControl.enableAudioVolumeIndication(e)}muteLocalMic(e=!1){this.publisher.muteLocalMic(e),this.connectState===ae.AliRtcConnectionStatusConnected&&this.isPublishing&&this.publisher.reportSelfDeviceStatus()}muteRemoteAudioPlaying(e,t=!1){const i=this.bizControl.getRemoteUser(e);if(!i)throw new U(B.ERR_INNER,`no remote user(${e}) founded`);i.setAudioMuted(t)}muteAllRemoteAudioPlaying(e=!1){this.bizControl.setAudioMuted(e)}startAudioCapture(e){return I(this,null,function*(){const t={audio:e||!0};yield this.publisher.createLocalStream(t)})}setAudioConstraints(e){return I(this,null,function*(){yield this.publisher.setMicrophoneConstraints(e)})}stopAudioCapture(){this.publisher.stopAudioCapture()}switchMicrophone(e,t){return I(this,null,function*(){if(yield this.publisher.setMicrophoneDeviceId(e),!this.publisher.audioCaptureDisabled){if(t)return void(yield this.publisher.createLocalStream({audio:!0,mediaStream:new MediaStream([t])}));yield this.publisher.createLocalStream({audio:{deviceId:e}})}})}setRecordingVolume(e){if(typeof e!="number")throw new U(B.ERR_INVALID_ARGUMENTS,"volume must be a number");this.bizControl.setAudioVolume({audio:Math.max(0,Math.min(e,400))/100})}setPlayoutVolume(e){if(typeof e!="number")throw new U(B.ERR_INVALID_ARGUMENTS,"volume must be a number");this.bizControl.setPlayoutVolume(Math.max(0,Math.min(e,100))/100)}setRemoteAudioVolume(e,t){const i=this.bizControl.getRemoteUser(e);if(!i)throw new U(B.ERR_INNER,`no remote user(${e}) founded`);if(typeof t!="number")throw new U(B.ERR_INVALID_ARGUMENTS,"volume must be a number");i.setPlayoutVolume(Math.max(0,Math.min(t,100))/100)}setAudioProfile(e){return I(this,null,function*(){yield this.publisher.setAudioProfile(e)})}getAudioTrack(e){return I(this,null,function*(){if(!e)return this.publisher.audioTrack;const t=this.bizControl.getRemoteUser(e);return t==null?void 0:t.getAudioTrack})}setLocalViewConfig(e,t){return I(this,null,function*(){var i;if(this._audioOnlyMode)throw new U(B.ERR_INNER,"Cannot set local view in audio only mode");(i=this.bizControl)==null||i.setLocalViewConfig(e,t),t===ue.AliRtcVideoTrackCamera&&this.publisher.hasCamera?yield this.startPreview():t===ue.AliRtcVideoTrackScreen&&this.publisher.hasScreenShare&&(yield this.startPreviewScreen())})}setCameraCapturerConfiguration(e){return I(this,null,function*(){const l=e,{cameraDirection:t,deviceId:i,bitrate:s,maxSendFrameRate:n}=l,c=Wt(l,["cameraDirection","deviceId","bitrate","maxSendFrameRate"]),o=X({},c);s&&(o.maxBitrate=s),n&&(o.maxSendFrameRate=n),Object.keys(o).length>0&&(yield this.publisher.setVideoProfile(o)),t!==void 0&&this.publisher.setCameraDirection(t),i&&this.publisher.setCameraDeviceId(i)})}setCameraCapturerContentHint(e){return I(this,null,function*(){e&&this.publisher.setVideoContentHint(e)})}enableLocalVideo(e=!0){return I(this,null,function*(){var t,i,s,n,c,o;if(this._audioOnlyMode)throw new U(B.ERR_INNER,"Cannot enable local video in audio only mode");e?((t=this.publisher.publishStreams)!=null&&t.video&&((s=(i=this.publisher.publishStreams)==null?void 0:i.video)==null||s.disableVideo(),(o=(c=(n=this.publisher.publishStreams)==null?void 0:n.video)==null?void 0:c.videoTrack)==null||o.stop()),yield this.publisher.startCameraCapture()):yield this.publisher.stopCameraCapture()})}muteLocalCamera(e){return I(this,null,function*(){this.publisher.muteLocalCamera(e),this.connectState===ae.AliRtcConnectionStatusConnected&&this.isPublishing&&this.publisher.reportSelfDeviceStatus()})}muteLocalScreen(e){return I(this,null,function*(){this.publisher.muteLocalScreen(e),this.connectState===ae.AliRtcConnectionStatusConnected&&this.isPublishing&&this.publisher.reportSelfDeviceStatus()})}setRemoteViewConfig(e,t,i){this.bizControl.setRemoteViewConfig(t,e,i)}isCameraOn(){var e;return(e=this.publisher.hasCamera)!=null?e:!1}switchCamera(e,t){return I(this,null,function*(){var s;if(this._audioOnlyMode)throw new U(B.ERR_INNER,"Cannot switch camera in audio only mode");const i={};if(e?(i.deviceId=e,this.slsReporter.reportSwitchCamera(e)):t||(i.cameraDirection=this.publisher.cameraDirection==="environment"?Ai.CAMERA_FRONT:Ai.CAMERA_REAR,this.slsReporter.reportSwitchCamera(this.publisher.cameraDirection||"")),yield this.setCameraCapturerConfiguration(i),!this.publisher.cameraCaptureDisabled){(s=this.publisher.cameraTrack)==null||s.stop();const n={video:!0};t&&(n.mediaStream=new MediaStream([t])),yield this.publisher.createLocalStream(n)}})}getCurrentCameraDeviceId(){return this.publisher.getCurrentCameraDeviceId()}startPreview(){return I(this,null,function*(){if(this._audioOnlyMode)throw new U(B.ERR_INNER,"Cannot start preview camera in audio only mode");this.publisher.hasCamera||(yield this.enableLocalVideo(!0)),yield this.publisher.previewAll({screen:!1})})}startPreviewScreen(e){return I(this,null,function*(){if(this._audioOnlyMode)throw new U(B.ERR_INNER,"Cannot start preview screen share in audio only mode");this.publisher.hasScreenShare||(yield this.startScreenShare(e)),yield this.publisher.previewAll({primary:!1})})}stopPreview(){return I(this,null,function*(){yield this.publisher.stopPreview({primary:!0,screen:!1})})}stopPreviewScreen(){return I(this,null,function*(){yield this.publisher.stopPreview({primary:!1,screen:!0})})}getVideoTrack(e){return I(this,null,function*(){var n,c;const{userId:t,streamType:i}=e;if(!t)return i===He.AliRtcSdkStreamTypeCapture?this.publisher.cameraTrack:this.publisher.screenTrack;const s=this.bizControl.getRemoteUser(t);return i===He.AliRtcSdkStreamTypeCapture?(n=s==null?void 0:s.getCameraStream)==null?void 0:n.videoTrack:(c=s==null?void 0:s.getScreenStream)==null?void 0:c.videoTrack})}startPublishLiveStream(e,t){return I(this,null,function*(){return this.liveTranscoding.startPublishLiveStream(e,t)})}updatePublishLiveStream(e,t){return I(this,null,function*(){return this.liveTranscoding.updatePublishLiveStream(e,t)})}updatePublishLiveStreamWithTaskId(e,t){return this.liveTranscoding.updatePublishLiveStreamWithTaskId(e,t)}stopPublishLiveStream(e){return I(this,null,function*(){return this.liveTranscoding.stopPublishLiveStream(e)})}stopPublishLiveStreamWithTaskId(e){return this.liveTranscoding.stopPublishLiveStreamWithTaskId(e)}setEnableMediaExtensionMsg(e){var t;(t=this.bizControl)==null||t.setEnableMediaExtensionMsg(!!e)}sendMediaExtensionMsg(e,t){return I(this,null,function*(){return this.sendMediaExtensionMsgEx(e,t,5)})}sendMediaExtensionMsgEx(e,t,i){return I(this,null,function*(){if(!this.publisher||!this.isPublishing)throw new U(B.ERR_INNER,"you should publish first");return this.slsReporter.reportSEIMessage(i,e.byteLength,t,0,!1),this.publisher.sendSEI(e,t,i)})}enablePlugin(e,t){this.bizControl.pluginManager.add(e,t)}removePlugin(e){this.bizControl.pluginManager.remove(e)}setPluginOption(e,t){const i=this.bizControl.pluginManager.get(e);i&&t&&i.setOptions(t)}getPluginByName(e){return this.bizControl.pluginManager.get(e)}getPluginOption(e){const t=this.bizControl.pluginManager.get(e);return t==null?void 0:t.getOptions()}isBeautyAvailable(){return this.bizControl.pluginManager.has("AliRtcBeauty")}isBeautyEnabled(){const e=this.bizControl.pluginManager.get("AliRtcBeauty");if(!e)throw new U(qt.AliRtcPluginErrorNoFindPlugin,"you should enable beautyPlugin first");return!!(e!=null&&e.isEnable)}setBeautyEffect(e,t){const i=this.bizControl.pluginManager.get("AliRtcBeauty");if(!i)throw new U(qt.AliRtcPluginErrorNoFindPlugin,"you should enable beautyPlugin first");e?i.enable():i.disable(),i.setOptions({basicBeauty:{skinBuffing:Math.max(Math.min(1,+t.smoothnessLevel),0),whitening:Math.max(Math.min(1,+t.whiteningLevel),0)}})}enableBackgroundExchange(e,t){const i=this.bizControl.pluginManager.get("AliRtcBeauty");if(!i||!i.isEnable)throw new U(qt.AliRtcPluginErrorNoFindPlugin,"you should enable beautyPlugin first");const s={setSegmentBackgroundImage:{backgroundImgUrl:e?t:""}};e&&(s.segmentBackgroundProcess={enable:!1}),i.setOptions(s)}enableBackgroundBlur(e){const t=this.bizControl.pluginManager.get("AliRtcBeauty");if(!t||!t.isEnable)throw new U(qt.AliRtcPluginErrorNoFindPlugin,"you should enable beautyPlugin first");const i={segmentBackgroundProcess:{type:0,enable:e}};e&&(i.setSegmentBackgroundImage={type:0,backgroundImgUrl:""}),t.setOptions(i)}setParameter(e){this.bizControl.setParameter(e)}getParameter(){return this.bizControl.getParameter()}sendDataChannelMessage(e){this.bizControl.sendDataChannelMessage(e)}subscribeRemoteStream(e){const{currentUserId:t,targetUserId:i}=e;if(i===t)throw new U(B.ERR_INNER,"targetUserId should not be equal to currentUserId");return new vs(e)}},m(F,"logName","AliRtcEngine"),m(F,"logError",!0),m(F,"isSupported",Lc),m(F,"checkH265Decode",Nc),m(F,"checkH265Encode",xc),m(F,"isDualVideoStreamSupported",As.isSupport),m(F,"getCameraList",()=>I(F,null,function*(){return(yield J.AliRTS.getCameraList()).filter(e=>e.deviceId)})),m(F,"getMicrophoneList",()=>I(F,null,function*(){return(yield J.AliRTS.getMicList()).filter(e=>e.deviceId)})),m(F,"getSpeakerList",()=>I(F,null,function*(){return(yield J.AliRTS.getSpeakerList()).filter(e=>e.deviceId)})),m(F,"_instances",new Map),m(F,"_instanceCounter",0),m(F,"_instance"),m(F,"AliRtcSdkChannelProfile",Ut),m(F,"AliRtcSdkClientRole",zt),m(F,"AliRtcVideoStreamType",Ge),m(F,"AliRtcVideoTrack",ue),m(F,"AliRtcAudioTrack",ti),m(F,"AliRtcPublishState",ee),m(F,"AliRtcSubscribeState",ce),m(F,"AliRtcRawDataStreamType",He),m(F,"AliRtcLogLevel",Ss),m(F,"AliRtcEngineLocalDeviceType",kt),m(F,"AliRtcEngineLocalDeviceExceptionType",je),m(F,"AliRtcConnectionStatus",ae),m(F,"AliRtcConnectionStatusChangeReason",Pt),m(F,"AliRtcPlugin",jt),m(F,"AliRtcPluginTrackType",bi),m(F,"AliRtcImageHolderPlugin",Xn),m(F,"AliRtcLiveTranscodingParam",Zi),m(F,"AliRtcLiveTranscodingEncodeParam",er),m(F,"AliRtcLiveTranscodingMixParam",Wn),m(F,"AliRtcLiveTranscodingSingleParam",zn),m(F,"AliRtcTranscodingClockWidget",Kn),m(F,"AliRtcTranscodingImage",lr),m(F,"AliRtcTranscodingText",qn),m(F,"AliRtcTranscodingUser",Gn),m(F,"AliRtcLiveTranscodingMixMode",Mi),m(F,"AliRtcLiveTranscodingStreamType",Gs),m(F,"AliRtcLiveTranscodingSourceType",vi),m(F,"AliRtcLiveTranscodingTaskProfile",Xs),m(F,"AliRtcLiveTranscodingAudioSampleRate",Qi),m(F,"AliRtcLiveTranscodingSegmentType",Ni),m(F,"AliRtcLiveTranscodingFontType",xi),m(F,"AliRtcLiveTranscodingCropMode",Qs),m(F,"AliRtcLiveTranscodingMediaProcessMode",Yi),m(F,"AliRtcLiveTranscodingState",Ys),m(F,"AliRtcLiveTranscodingErrorCode",xt),m(F,"AliRtcTrascodingPublishTaskStatus",Zs),m(F,"AliRtcDataChannelMsg",Jt),m(F,"AliRtcDataMsgType",Fs),m(F,"Plugin",jt),F);$([k()],j.prototype,"destroy",1),$([k()],j.prototype,"backToUnpublishStatus",1),$([k()],j.prototype,"resumePublishForNetworkRecovery",1),$([k()],j.prototype,"onNetworkRecovery",1),$([k()],j.prototype,"resumeSubList",1),$([k(H)],j.prototype,"retrySubscribe",1),$([k(H)],j.prototype,"setEnableDualVideoStream",1),$([k(H)],j.prototype,"setChannelProfile",1),$([k(H)],j.prototype,"setClientRole",1),$([k(H)],j.prototype,"setAudioOnlyMode",1),$([k()],j.prototype,"clearCheckAuthInfoTimer",1),$([k(H)],j.prototype,"joinChannel",1),$([k(H)],j.prototype,"joinAIChannel",1),$([k(H)],j.prototype,"leaveChannel",1),$([k(H)],j.prototype,"refreshAuthInfo",1),$([k(H)],j.prototype,"publishLocalAudioStream",1),$([k(H)],j.prototype,"setDefaultSubscribeAllRemoteAudioStreams",1),$([k(H)],j.prototype,"subscribeAllRemoteAudioStreams",1),$([k(H)],j.prototype,"subscribeRemoteAudioStream",1),$([k(H)],j.prototype,"resumeRemoteAudioStream",1),$([k(H)],j.prototype,"stopRemoteAudioPlay",1),$([k(H)],j.prototype,"publishLocalVideoStream",1),$([k(H)],j.prototype,"setRemoteDefaultVideoStreamType",1),$([k(H)],j.prototype,"setRemoteUserVideoStreamType",1),$([k(H)],j.prototype,"setDefaultSubscribeAllRemoteVideoStreams",1),$([k(H)],j.prototype,"subscribeAllRemoteVideoStreams",1),$([k(H)],j.prototype,"subscribeRemoteMediaStream",1),$([k(H)],j.prototype,"resumeRemoteMediaStream",1),$([k(([a])=>[`${a==null?void 0:a.audio}`])],j.prototype,"startScreenShare",1),$([k()],j.prototype,"stopScreenShare",1),$([k(H)],j.prototype,"setScreenShareConfiguration",1),$([k(H)],j.prototype,"setScreenShareContentHint",1),$([k()],j.prototype,"publishLocalScreenShareStream",1),$([k(H)],j.prototype,"setAudioShareVolume",1),$([k(H)],j.prototype,"enableAudioVolumeIndication",1),$([k(H)],j.prototype,"muteLocalMic",1),$([k(H)],j.prototype,"muteRemoteAudioPlaying",1),$([k(H)],j.prototype,"muteAllRemoteAudioPlaying",1),$([k(H)],j.prototype,"startAudioCapture",1),$([k(H)],j.prototype,"setAudioConstraints",1),$([k()],j.prototype,"stopAudioCapture",1),$([k(H)],j.prototype,"switchMicrophone",1),$([k(H)],j.prototype,"setRecordingVolume",1),$([k(H)],j.prototype,"setPlayoutVolume",1),$([k(H)],j.prototype,"setRemoteAudioVolume",1),$([k(H)],j.prototype,"setAudioProfile",1),$([k(H)],j.prototype,"getAudioTrack",1),$([k(H)],j.prototype,"setLocalViewConfig",1),$([k(H)],j.prototype,"setCameraCapturerConfiguration",1),$([k(H)],j.prototype,"setCameraCapturerContentHint",1),$([k(H)],j.prototype,"enableLocalVideo",1),$([k(H)],j.prototype,"muteLocalCamera",1),$([k(H)],j.prototype,"muteLocalScreen",1),$([k(H)],j.prototype,"setRemoteViewConfig",1),$([k(H)],j.prototype,"switchCamera",1),$([k()],j.prototype,"startPreview",1),$([k()],j.prototype,"startPreviewScreen",1),$([k()],j.prototype,"stopPreview",1),$([k()],j.prototype,"stopPreviewScreen",1),$([k()],j.prototype,"startPublishLiveStream",1),$([k()],j.prototype,"updatePublishLiveStream",1),$([k()],j.prototype,"updatePublishLiveStreamWithTaskId",1),$([k()],j.prototype,"stopPublishLiveStream",1),$([k()],j.prototype,"stopPublishLiveStreamWithTaskId",1),$([k(H)],j.prototype,"setEnableMediaExtensionMsg",1),$([k(([a,r,e])=>[a.byteLength,r,e])],j.prototype,"sendMediaExtensionMsgEx",1),$([k(([a,r])=>[a.name||"",r])],j.prototype,"enablePlugin",1),$([k(H)],j.prototype,"removePlugin",1),$([k(H)],j.prototype,"setPluginOption",1),$([k(H)],j.prototype,"getPluginByName",1),$([k(H)],j.prototype,"getPluginOption",1),$([k(H)],j.prototype,"setBeautyEffect",1),$([k(H)],j.prototype,"enableBackgroundExchange",1),$([k(H)],j.prototype,"enableBackgroundBlur",1),$([k(H)],j.prototype,"setParameter",1),$([k(([a])=>{var r;return[(r=a.data)==null?void 0:r.byteLength]})],j.prototype,"sendDataChannelMessage",1),$([k(H)],j.prototype,"subscribeRemoteStream",1),$([k(H)],j,"setLogLevel",1);let Yn=j;Qt=new Bs({businessName:"imp-web-rtc",version:(Zn=Yn.getSdkVersion())!=null?Zn:"unknown",env:"prod",disabled:window.AliRtcOptionsDisableProxy===!0,deferRegionSet:!0});const vl=Qt.shallowWrapClass(Yn);z.AliRtcAudioTrack=ti,z.AliRtcCapabilityProfile=Di,z.AliRtcConnectionStatus=ae,z.AliRtcConnectionStatusChangeReason=Pt,z.AliRtcDataChannelMsg=Jt,z.AliRtcDataMsgType=Fs,z.AliRtcEngineLocalDeviceExceptionType=je,z.AliRtcEngineLocalDeviceType=kt,z.AliRtcErrorCode=B,z.AliRtcImageHolderPlugin=Xn,z.AliRtcLiveTranscodingAudioSampleRate=Qi,z.AliRtcLiveTranscodingCropMode=Qs,z.AliRtcLiveTranscodingEncodeParam=er,z.AliRtcLiveTranscodingErrorCode=xt,z.AliRtcLiveTranscodingFontType=xi,z.AliRtcLiveTranscodingMediaProcessMode=Yi,z.AliRtcLiveTranscodingMixMode=Mi,z.AliRtcLiveTranscodingMixParam=Wn,z.AliRtcLiveTranscodingParam=Zi,z.AliRtcLiveTranscodingSegmentType=Ni,z.AliRtcLiveTranscodingSingleParam=zn,z.AliRtcLiveTranscodingSourceType=vi,z.AliRtcLiveTranscodingState=Ys,z.AliRtcLiveTranscodingStreamType=Gs,z.AliRtcLiveTranscodingTaskProfile=Xs,z.AliRtcLocalStreamInfo=zs,z.AliRtcLogLevel=Ss,z.AliRtcNetworkQuality=tt,z.AliRtcPlugin=jt,z.AliRtcPluginTrackType=bi,z.AliRtcPluginType=Nn,z.AliRtcPublishState=ee,z.AliRtcRawDataStreamType=He,z.AliRtcRemoteUserInfo=Dn,z.AliRtcSdkChannelProfile=Ut,z.AliRtcSdkClientRole=zt,z.AliRtcSubscribeState=ce,z.AliRtcTranscodingClockWidget=Kn,z.AliRtcTranscodingImage=lr,z.AliRtcTranscodingText=qn,z.AliRtcTranscodingUser=Gn,z.AliRtcTrascodingPublishTaskStatus=Zs,z.AliRtcVideoStreamType=Ge,z.AliRtcVideoTrack=ue,z.default=vl,Object.defineProperties(z,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
149
+ });`,this._webWorker=void 0}_initWebWorker(){window.URL=window.URL||window.webkitURL;let r=new Blob([this._webWorkerString],{type:"application/javascript"});this._webWorker=new Worker(URL.createObjectURL(r)),this._webWorker.onmessage=e=>{let t=e.data;this._updateWorkerTime(t)}}_lostVisibility(){var r;this._previousWorkerTime=Date.now(),this._useWebworker=!0,this._webWorker||this._initWebWorker(),this._active&&((r=this._webWorker)==null||r.postMessage("start"))}_gainedVisibility(){this._useWebworker=!1,this._previousRAFTime=void 0,this._webWorker&&this._webWorker.postMessage("stop"),this._active&&(this._rafId=requestAnimationFrame(this._updateRAFTime.bind(this)))}_init(){if(window.Worker){if(document.hidden===void 0)return this._focusHandler=this._gainedVisibility.bind(this),this._blurHandler=this._lostVisibility.bind(this),window.addEventListener("focus",this._focusHandler),void window.addEventListener("blur",this._blurHandler);this._visibilityHandler=()=>{document.hidden===!0?this._lostVisibility():this._gainedVisibility()},document.addEventListener("visibilitychange",this._visibilityHandler,!1)}}_stopUpdate(){this._active=!1,this._rafId&&(cancelAnimationFrame(this._rafId),this._rafId=0),this._useWebworker&&this._webWorker&&this._webWorker.postMessage("stop")}destroy(){this._focusHandler&&(window.removeEventListener("focus",this._focusHandler),this._focusHandler=null),this._blurHandler&&(window.removeEventListener("blur",this._blurHandler),this._blurHandler=null),this._visibilityHandler&&(document.removeEventListener("visibilitychange",this._visibilityHandler),this._visibilityHandler=null),this._stopUpdate()}_updateWorkerTime(r){let e=(r-(this._previousWorkerTime||0))/1e3;e>this._intervalThreshold&&(this._update(e),this._previousWorkerTime=r)}_updateRAFTime(r){this._previousRAFTime===void 0&&(this._previousRAFTime=r);let e=(r-this._previousRAFTime)/1e3;e>this._intervalThreshold&&(this._update(e),this._previousRAFTime=r),!this._useWebworker&&this._active?this._rafId=requestAnimationFrame(this._updateRAFTime.bind(this)):this._rafId=0}_update(r){for(let e=0;e<this._updateables.length;e++)this._updateables[e]._update(typeof r=="number"?r:parseFloat(r))}register(r){this._updateables.push(r),this._inited===!1&&(this._inited=!0,this._init()),this._active===!1&&(this._rafId=requestAnimationFrame(this._updateRAFTime.bind(this)),this._active=!0)}unregister(r){const e=this._updateables.indexOf(r);e!==-1&&this._updateables.splice(e,1),this._updateables.length===0&&this._stopUpdate()}}class Xn extends jt{constructor(e,t=10){super("AliRtcImageHolder");m(this,"url");m(this,"image");m(this,"canvas");m(this,"mediaStream");m(this,"updateableManager");m(this,"updateable");m(this,"hasVideoTrack",!1);this.url=e,this.canvas=document.createElement("canvas"),this.canvas.width=1280,this.canvas.height=720,this.drawImageToCanvas(),this.updateableManager=new fl(t)}get initOptions(){return{imageUrl:""}}setOptions(e){e.imageUrl&&(this.options=e,e.imageUrl!==this.url&&this.drawImageToCanvas())}drawImageToCanvas(){return I(this,null,function*(){if(!this.url)return;const e=this.canvas.getContext("2d"),t=document.createElement("img");let i;this.image=t,t.crossOrigin="anonymous",t.src=this.url;const{width:s,height:n}=yield new Promise(c=>{t.onload=()=>{i&&clearTimeout(i),c({width:t.width||16,height:t.height||16})},t.onerror=()=>{i&&clearTimeout(i),c({width:16,height:16})},i=setTimeout(()=>{c({width:16,height:16})},5e3)});this.canvas.width=s,this.canvas.height=n,e.drawImage(t,0,0,s,n)})}start(){return I(this,null,function*(){var i;if(!this.url)throw new Error("no image url founded");if(!this.canvas)throw new Error("get canvas error");const e=this.canvas.captureStream(25),t=this.canvas.getContext("2d");return this.image&&this.image.width&&t.drawImage(this.image,0,0,this.image.width,this.image.height),this.mediaStream=e,t.fillStyle="transparent",this.updateable={_update:()=>{t.fillRect(0,0,1,1)}},this.updateableManager.register(this.updateable),(i=e.getVideoTracks())==null?void 0:i[0]})}stop(){var e,t;this.updateable&&(this.updateableManager.unregister(this.updateable),this.updateable=null),this.updateableManager.destroy(),(t=(e=this.mediaStream)==null?void 0:e.getVideoTracks()[0])==null||t.stop(),this.mediaStream=void 0}isSupported(){return!0}shouldUpdate(e){return this.hasVideoTrack===!!e.originVideoTrack}process(e){return I(this,null,function*(){if(this.hasVideoTrack=!!e.originVideoTrack,e.originVideoTrack){const i=e.currentVideoTrack;return i&&i.id===e.originVideoTrack.id||e.updateVideoTrack(e.originVideoTrack),void this.stop()}const t=yield this.start();e.updateVideoTrack(t)})}}class Vi{static checkString(r){return typeof r=="string"}static checkNumber(r){return typeof r=="number"}static checkHtmlVideoElement(r){return r&&r.nodeName==="VIDEO"}static checkHtmlAudioElement(r){return r&&r.nodeName==="AUDIO"}static checkAuthInfo(r){return r?r.appId?r.channelId?Vi.checkString(r.channelId)?r.userId?Vi.checkString(r.userId)?r.timestamp?Vi.checkNumber(r.timestamp)?r.token?null:new U(B.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"no token founded"):new U(B.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"timestamp is not number"):new U(B.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"no timestamp founded"):new U(B.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"userId is not string"):new U(B.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"no userId founded"):new U(B.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"channelId is not string"):new U(B.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"no channelId founded"):new U(B.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"no appId founded"):new U(B.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"no authInfo founded")}static checkMediaStreamTrack(r){return r instanceof MediaStreamTrack}static checkVideoEncoderConfiguration(r){return r&&(r.width||r.height||r.frameRate||r.bitrateMax)}}var bl=Object.defineProperty,Sl=Object.getOwnPropertyDescriptor,$=(a,r,e,t)=>{for(var i,s=t>1?void 0:t?Sl(r,e):r,n=a.length-1;n>=0;n--)(i=a[n])&&(s=(t?i(r,e,s):i(s))||s);return t&&s&&bl(r,e,s),s};let Qt,Qn=!1;const j=(F=class extends oe{constructor(e,t){super();m(this,"instanceId");m(this,"_globalEnv");m(this,"channelProfile");m(this,"clientRole");m(this,"signalingManager");m(this,"bizControl");m(this,"liveTranscoding");m(this,"maxSignalingReconnectDuration");m(this,"slsReporter");m(this,"connectState",ae.AliRtcConnectionStatusInit);m(this,"networkError",!1);m(this,"_audioOnlyMode",!1);m(this,"_destroyed",!1);m(this,"_authInfoWillExpireTimer",null);m(this,"_authInfoExpiredTimer",null);m(this,"_serverCheckAuthInfoTimestamp",null);m(this,"_localCheckAuthInfoTimestamp",null);m(this,"_proxyAiTid",null);m(this,"_agentParam",null);m(this,"sessionId");this.config=e,this.instanceId=t||(e==null?void 0:e.instanceId)||`rtc_default_${Date.now()}`,this._globalEnv=e==null?void 0:e.globalEnv;const i=Date.now();T.init(this.instanceId,e==null?void 0:e.globalEnv),this.slsReporter=new dl(this,e==null?void 0:e.globalEnv),this.channelProfile=Ut.AliRtcSdkCommunication,this.clientRole=zt.AliRtcSdkLive,this.liveTranscoding=new al(this.slsReporter),this.signalingManager=new cr(this.channelProfile,this.clientRole,this.slsReporter,(e==null?void 0:e.env)===It.pre?It.pre:It.prod),this.addSignalingManagerListeners(),this.maxSignalingReconnectDuration=e==null?void 0:e.maxSignalingReconnectDuration,this.bizControl=new et({slsReporter:this.slsReporter,signalingManager:this.signalingManager,parameter:e==null?void 0:e.parameter,instanceId:this.instanceId}),this.addBizControlListeners(),this.addPublisherListeners(),this.slsReporter.reportConnectionLatencyEvent(Ze.CREATE_ENGINE,st.START,"","",i),this.slsReporter.reportConnectionLatencyEvent(Ze.CREATE_ENGINE,st.END,"","",Date.now()),this.slsReporter.reportSDKCreated(i),pi++,mi||(mi=!0,window.addEventListener("mousedown",nt),window.addEventListener("touchstart",nt))}static getSdkVersion(){return _i}static setLogLevel(e){T.setLogLevel(e)}static createInstance(e){J.AliRTS.ENV=(e==null?void 0:e.globalEnv)==="SEA"?"SEA":void 0;const t=(e==null?void 0:e.instanceId)||`rtc_${++F._instanceCounter}_${Date.now()}`,i=new F(e,t);return F._instances.set(t,i),i.configureTracer(e),i}static getAllInstances(){return Array.from(F._instances.values())}static getInstanceById(e){return F._instances.get(e)}static destroyAll(){return I(this,null,function*(){const e=Array.from(F._instances.values());yield Promise.all(e.map(t=>t.destroy()))})}static getInstance(e){return F._instance||(J.AliRTS.ENV=(e==null?void 0:e.globalEnv)==="SEA"?"SEA":void 0,F._instance=new F(e),F._instance.configureTracer(e)),F._instance}destroy(){return I(this,null,function*(){var e,t,i;this._destroyed||(this._destroyed=!0,F._instances.delete(this.instanceId),F._instance===this&&(F._instance=void 0),yield this.leaveChannel(),yield this.bizControl.clear(),this.removeAllListeners(),(e=this.bizControl)==null||e.removeAllListeners(),(t=this.signalingManager)==null||t.removeAllListeners(),(i=this.slsReporter)==null||i.stop(),pi--,pi<=0&&(pi=0,mi&&(mi=!1,window.removeEventListener("mousedown",nt),window.removeEventListener("touchstart",nt))),T.destroy(this.instanceId))})}configureTracer(e){Qn||(Qt==null||Qt.updateOptions({region:(e==null?void 0:e.globalEnv)==="SEA"?"sg":"cn"}),Qt==null||Qt.setReady(),Qn=!0)}syncGlobalEnv(){J.AliRTS.ENV=this._globalEnv==="SEA"?"SEA":void 0}get channel(){return this.bizControl.channel}get userId(){return this.bizControl.userId}get remoteUsers(){return this.bizControl.remoteUsers}get publisher(){return this.bizControl.publisher}get publishAudioStream(){return this.publisher.publishStreams.audio}get isPublishing(){const{publisher:e}=this.bizControl;return!!e&&e.isPublishing}get currentRoleCanPublish(){return this.channelProfile===Ut.AliRtcSdkCommunication||this.clientRole===zt.AliRtcSdkInteractive}addPublisherListeners(){this.publisher.on(ot.Local,e=>{T.setActiveInstance(this.instanceId),T.event("[Publisher] Device Status Change",e),this.onLocalDeviceStatusChange(e)}),this.publisher.on(oi.VideoTrackEnded,()=>{T.setActiveInstance(this.instanceId),T.event("[Publisher] VideoTrack Ended"),this.emit("localDeviceException",kt.AliEngineLocalDeviceTypeCamera,je.AliEngineLocalDeviceExceptionTypeCameraInterrupt,"")}),this.publisher.on(oi.ScreenTrackEnded,()=>{T.setActiveInstance(this.instanceId),T.event("[Publisher] ScreenTrack Ended"),this.emit("localDeviceException",kt.AliEngineLocalDeviceTypeDisplay,je.AliEngineLocalDeviceExceptionTypeDisplayException,"")}),this.publisher.on(oi.AudioTrackEnded,()=>{T.setActiveInstance(this.instanceId),T.event("[Publisher] AudioTrack Ended"),this.emit("localDeviceException",kt.AliEngineLocalDeviceTypeMic,je.AliEngineLocalDeviceExceptionTypeMicInterrupt,"")}),this.publisher.on("localDeviceException",(e,t,i="")=>{this.emit("localDeviceException",e,t,i)}),this.publisher.on("audioPublishStateChanged",(e,t,i)=>{var s;this.emit("audioPublishStateChanged",e,t,i,(s=this.channel)!=null?s:"")}),this.publisher.on("videoPublishStateChanged",(e,t,i)=>{var s;this.emit("videoPublishStateChanged",e,t,i,(s=this.channel)!=null?s:"")}),this.publisher.on("dualStreamPublishStateChanged",(e,t,i)=>{var s;this.emit("dualStreamPublishStateChanged",e,t,i,(s=this.channel)!=null?s:"")}),this.publisher.on("screenPublishStateChanged",(e,t,i)=>{var s;this.emit("screenSharePublishStateChanged",e,t,i,(s=this.channel)!=null?s:"")}),this.publisher.on("dataPublishStateChanged",(e,t,i)=>{var s;this.emit("dataPublishStateChanged",e,t,i,(s=this.channel)!=null?s:"")})}occurError(e,t){T.setActiveInstance(this.instanceId),T.event(`[${F.logName}]`,"Occur Error",e,t),this.emit("onOccurError",e,t),this.emit("occurError",e,t)}addBizControlListeners(){this.bizControl.rtsManager.on("disconnected",()=>I(this,null,function*(){T.setActiveInstance(this.instanceId),T.event(`[${F.logName}]`,"RTS Disconnected"),(yield Le.isNetworkAvailable())?this.onNetworkRecovery():this.onNetworkError()})),this.bizControl.rtsManager.on("subscribeexceeds",()=>I(this,null,function*(){T.setActiveInstance(this.instanceId),T.event(`[${F.logName}]`,"RTS SubscribeExceeds"),this.bizControl.rtsManager.clear(),yield this.resumePublishForNetworkRecovery(),yield this.resumeSubList()})),this.bizControl.rtsManager.on("seimessage",(e,t,i)=>I(this,null,function*(){const s=this.remoteUsers.find(n=>Le.removeQueryString(n.streamUrl)===Le.removeQueryString(e));if(s){try{this.emit("mediaExtensionMsgReceived",s.userId,i,t)}catch(n){}if(t===99)try{const n=JSON.parse(new TextDecoder().decode(i)),c=n.pub||{},o=n.grtn||{},l=n.sub||{};let d;d=Object.keys(o).length?(c.vTotalCost||0)+(c.upRTTHalf||0)+(o.totalCost||0)+(l.downRTTHalf||0)+(l.vTotalCost||0):(c.vEncPlugCost||0)+((c.timestampRecv||0)-(c.timestamp||0))+(l.vJitterBufferDelay||0)+(l.vDecPlugCost||0);const u=s.streamInfo.getVideoLargeInfo(),p=s.streamInfo.getVideoSmallInfo(),h=[u,p,s.streamInfo.getScreenInfo()].filter(f=>f&&f.subscribeState===de.Subscribed&&f.msid);for(const f of h)try{this.emit("rtcCumuDelayReceived",s.userId,f.msid,d)}catch(g){}if(s.audioSSRC&&this.slsReporter.reportCumuAudioDelay(s.audioSSRC,n),s.videoSSRC){const f=yield this.bizControl.rtsManager.getSubscribeVideoStats(e);(f==null?void 0:f.frameHeight)===16&&(f==null?void 0:f.frameWidth)===16||this.slsReporter.reportCumuVideoDelay(s.videoSSRC,n)}}catch(n){}}})),this.bizControl.on(ot.Remote,(e,t)=>{T.setActiveInstance(this.instanceId),T.event(`[${F.logName}]`,"RemoteUser Device Status Change",e,t)}),this.bizControl.on("remoteUserJoin",(e,t)=>{this.emit("remoteUserOnLineNotify",e,t)}),this.bizControl.on("remoteTrackAvailableChange",(e,t,i)=>{this.emit("remoteTrackAvailableNotify",e,t,i)}),this.bizControl.on("audioSubscribeStateChanged",(e,t,i,s,n)=>{this.emit("audioSubscribeStateChanged",e,t,i,s,n)}),this.bizControl.on("videoSubscribeStateChanged",(e,t,i,s,n)=>{this.emit("videoSubscribeStateChanged",e,t,i,s,n)}),this.bizControl.on("screenSubscribeStateChanged",(e,t,i,s,n)=>{this.emit("screenShareSubscribeStateChanged",e,t,i,s,n)}),this.bizControl.on("dataSubscribeStateChanged",(e,t,i,s,n)=>{this.emit("dataSubscribeStateChanged",e,t,i,s,n)}),this.bizControl.on("userAudioMuted",(e,t)=>{this.emit("userAudioMuted",e,t)}),this.bizControl.on("userVideoMuted",(e,t)=>{this.emit("userVideoMuted",e,t)}),this.bizControl.on("userScreenMuted",(e,t)=>{this.emit("userScreenMuted",e,t)}),this.bizControl.on("audioVolume",e=>{this.emit("audioVolume",e)}),this.bizControl.on("remoteAudioAutoPlayFail",e=>{this.emit("remoteAudioAutoPlayFail",e)}),this.bizControl.on("remoteVideoAutoPlayFail",(e,t)=>{this.emit("remoteVideoAutoPlayFail",e,t)}),this.bizControl.on("remoteAudioPlayError",(e,t)=>{this.emit("remoteAudioPlayError",e,t)}),this.bizControl.on("remoteVideoPlayError",(e,t)=>{this.emit("remoteVideoPlayError",e,t)}),this.bizControl.on("rtcStats",e=>{this.emit("rtcStats",e)}),this.bizControl.on("rtcLocalAudioStats",e=>{this.emit("rtcLocalAudioStats",e)}),this.bizControl.on("rtcLocalVideoStats",e=>{this.emit("rtcLocalVideoStats",e)}),this.bizControl.on("rtcRemoteAudioStats",e=>{this.emit("rtcRemoteAudioStats",e)}),this.bizControl.on("rtcRemoteVideoStats",e=>{this.emit("rtcRemoteVideoStats",e)}),this.bizControl.on("remoteSubscribeError",(e,t)=>{this.occurError(e,t),this.slsReporter.reportError(e)}),this.bizControl.on("occurError",(e,t)=>{this.occurError(e,t),this.slsReporter.reportError(e)}),this.bizControl.on("remoteDataChannelMessage",(e,t)=>{this.emit("dataChannelMsg",e,t)}),this.bizControl.on("remoteUserSubscribedDataChannel",e=>{this.emit("remoteUserSubscribedDataChannel",e)}),this.bizControl.on("networkQuality",e=>{this.emit("networkQuality",e)})}addSignalingManagerListeners(){this.signalingManager.on("onKeepAliveRsp",()=>{this.networkError&&(T.setActiveInstance(this.instanceId),T.event("[Signaling] Receive KeepAlive Response",`networkError: ${this.networkError}`),this.onNetworkRecovery())}),this.signalingManager.on("onNotifyJoin",e=>{T.setActiveInstance(this.instanceId),T.event("[Signaling] Notify Join ",e),this.handleUsersJoin(e)}),this.signalingManager.on("onNotifyStatus",e=>{T.setActiveInstance(this.instanceId),T.event("[Signaling] Notify Status ",e),e.forEach(t=>{this.bizControl.updateRemoteUserDeviceStatus(t)})}),this.signalingManager.on("onNotifyLeave",e=>{T.setActiveInstance(this.instanceId),T.event("[Signaling] Notify Leave ",e),e.forEach(t=>I(this,null,function*(){yield this.bizControl.removeLeftUser(t),this.emit("remoteUserOffLineNotify",t.userid,t.leavecode)}))}),this.signalingManager.on("onBye",(e,t)=>{T.setActiveInstance(this.instanceId),T.event("[Signaling] Bye ",e,t),this.slsReporter.reportError({message:`reason: ${e}, description: ${t}`}),this.emit("bye",e),this.signalingManager.reset(),this.leaveChannel(),this.slsReporter.reportBye(e)}),this.signalingManager.on("onConnectFail",e=>{T.setActiveInstance(this.instanceId),T.event("[Signaling] Connect Failed ",e),this.onError(e),this.backToUnpublishStatus(),this.bizControl.leave(),this.signalingManager.reset(),this.connectState=ae.AliRtcConnectionStatusFailed,this.emit("connectionStatusChange",ae.AliRtcConnectionStatusFailed,Pt.AliRtcConnectionChangedNetworkInterrupted)}),this.signalingManager.on("onNetworkError",e=>{this.slsReporter.reportWarning("signaling network error"),T.setActiveInstance(this.instanceId),T.event("[Signaling] Network error ",e),this.onNetworkError()}),this.signalingManager.on("onAuthInvalid",()=>{T.setActiveInstance(this.instanceId),T.event("[Signaling] Auth Invalid")}),this.signalingManager.on("onReconnectStart",()=>{this.onNetworkError(),T.setActiveInstance(this.instanceId),T.event("[Signaling] Reconnect Start "),this.connectState=ae.AliRtcConnectionStatusReconnecting,this.emit("connectionStatusChange",ae.AliRtcConnectionStatusReconnecting,Pt.AliRtcConnectionSignalingConnecting)}),this.signalingManager.on("onReconnectSuccess",e=>{T.setActiveInstance(this.instanceId),T.event("[Signaling] Reconnect Success ",e),this.onNetworkRecovery(e)}),this.signalingManager.on("onReconnectFail",e=>{this.slsReporter.reportWarning("signaling reconnect fail: ${err.code}"),T.setActiveInstance(this.instanceId),T.event("[Signaling] Reconnect Failed ",e),e.code===403&&this.emit("authInfoExpired")}),this.signalingManager.on("onError",e=>{this.slsReporter.reportWarning("signaling error: ${err.message}"),T.setActiveInstance(this.instanceId),T.event("[Signaling] Error ",e),this.onError(e)}),this.signalingManager.on("onUnknownMessage",e=>{if(e.msgtype==="proxyai"&&e.tid===this._proxyAiTid){let t=e.data.retcode;t===200&&(t=0),this.emit("AIAgentResult",t,this._agentParam.action,e.data.body)}})}backToUnpublishStatus(){this.connectState=ae.AliRtcConnectionStatusDisconnected,this.publisher.isPublishing&&this.publisher.clearPublishState(),this.networkError=!1}handleUsersJoin(e){e.forEach(t=>{this.bizControl.addUser(t,ge.Join)})}onLocalDeviceStatusChange(e){T.event(`[${F.logName}]`,ot.Local,e),this.signalingManager.reportStatus(e).then(()=>{T.debug("[signaling] reportStatus suc")}).catch(t=>{T.error("[signaling] reportStatus failed",t)})}resumePublishForNetworkRecovery(){return I(this,null,function*(){try{yield this.publisher.resumePublish()}catch(e){const{code:t}=e;if(t===10205){let s=1;try{yield new Promise((n,c)=>{const o=setInterval(()=>I(this,null,function*(){s>1&&(clearInterval(o),c()),s+=1;try{yield this.publisher.resumePublish(),clearInterval(o),n()}catch(l){const{code:d}=l;d!==10205&&(clearInterval(o),c())}}),1e3)})}catch(n){}}throw e}})}onNetworkRecovery(e){return I(this,null,function*(){T.event(F.logName,"onNetworkRecovery",`rts isConnected: ${this.bizControl.rtsManager.isConnected}; rts isConnecting: ${this.bizControl.rtsManager.isConnecting}`,{users:e}),yield this.resumeSubList(e),this.networkError&&(this.networkError=!1,this.publisher.reportSelfDeviceStatus(),this.connectState=ae.AliRtcConnectionStatusConnected,this.emit("connectionStatusChange",ae.AliRtcConnectionStatusConnected,Pt.AliRtcConnectionSignalingHeartbeatAlive))})}resumeSubList(e){return I(this,null,function*(){if(e){const{joinList:t,leaveList:i,presentList:s}=this.bizControl.diffUsers(e);T.info(`[${F.logName}]`,"resumeSubList",{joinList:t,leaveList:i,presentList:s}),this.handleUsersJoin(t),i.forEach(n=>{T.event(F.logName,Me.UserLeft,n.userid,n.reason),this.bizControl.onRemotePublishStateChange({userid:n.userid,displayname:"",callid:"",tracks:[]}),this.bizControl.removeLeftUser(n),this.emit("remoteUserOffLineNotify",n.userid,ns.AliRtcUserOfflineQuit)}),s.forEach(n=>{this.bizControl.onRemotePublishStateChange(n)})}else for(let t=0;t<this.remoteUsers.length;t++){const i=this.remoteUsers[t];try{i.restore(),i.updateSubscribe(ge.Resume)}catch(s){}}})}retrySubscribe(e){return I(this,null,function*(){const t=this.bizControl.getRemoteUser(e);if(!t)throw new U(B.ERR_INNER,`no remote user(${e}) founded`);_e.getInstance().addEventData(_e.eventRetrySub,e),t.restore(),t.updateSubscribe(ge.Retry)})}onNetworkError(){this.connectState===ae.AliRtcConnectionStatusConnected&&(this.networkError||(this.connectState=ae.AliRtcConnectionStatusDisconnected,this.emit("connectionStatusChange",ae.AliRtcConnectionStatusDisconnected,Pt.AliRtcConnectionChangedNetworkInterrupted)),this.networkError=!0)}onError(e){this.slsReporter.reportError(e),T.event(F.logName,Me.Error,e)}setEnableDualVideoStream(e,t){this.bizControl.setEnableDualVideoStream(e,t)}hadPushStream(e){if(!this.publisher||!e)throw new U(B.ERR_INNER,"stream is not publishing")}getCurrentMicDeviceId(){return this.publisher.getCurrentMicDeviceId()}setChannelProfile(e){if(![ae.AliRtcConnectionStatusInit,ae.AliRtcConnectionStatusDisconnected,ae.AliRtcConnectionStatusFailed].includes(this.connectState))throw new U(B.ERR_INNER,"cannot set channel profile in call");this.channelProfile=e,this.channelProfile===Ut.AliRtcSdkCommunication&&(this.clientRole=zt.AliRtcSdkLive),this.signalingManager.setChannelProfile(e)}startDefaultDevices(){return I(this,null,function*(){if(!this.publisher)return;const{hasCamera:e,hasMicrophone:t,hasScreenShare:i}=this.publisher;if(!e&&!t&&!i){try{yield this.publisher.startDefaultCameraAndMic(this._audioOnlyMode)}catch(s){T.warn(`[${F.logName}]`,"startDefaultDevices failed",s.code,s.message),s instanceof U&&this.occurError(s);const n=s.code;this.occurError(new U(n>=B.ERR_CAMERA_OPEN_FAIL&&n<=B.ERR_CAMERA_NOT_AVAILABLE?B.ERR_SDK_PUBLISH_VIDEO_STREAM_FAILED:B.ERR_SDK_PUBLISH_AUDIO_STREAM_FAILED,`auto publish device failed, ${s.message||""}`))}yield this.publisher.previewAll()}})}startPublish(e){return I(this,null,function*(){try{yield this.publisher.startPublish(!1,e)}catch(t){const i=this.publisher.publishStreams||{},s=[];i!=null&&i.audio&&s.push(B.ERR_SDK_PUBLISH_AUDIO_STREAM_FAILED),i!=null&&i.video&&s.push(B.ERR_SDK_PUBLISH_VIDEO_STREAM_FAILED),s.forEach(n=>{this.occurError(new U(n,`auto publish stream failed, ${t.message||""}`))})}})}setClientRole(e){return I(this,null,function*(){this.syncGlobalEnv();try{if(this.channelProfile===Ut.AliRtcSdkCommunication)return;if(!Object.values(zt).includes(e))throw new U(B.ERR_INVALID_ARGUMENTS,`set client role error, role value(${e}) is invalid`);if(this.clientRole===e)return;this.slsReporter.reportRoleUpdate(this.clientRole,e),this.isInCall()?this.clientRole===zt.AliRtcSdkInteractive?(this.publisher.isPublishing?yield this.publisher.unPublish():yield this.publisher.clearStream(),yield this.signalingManager.setClientRole(e)):(yield this.signalingManager.setClientRole(e),yield this.startDefaultDevices(),yield this.startPublish(Dt.ROLE_CHANGE)):yield this.signalingManager.setClientRole(e),this.clientRole=e}catch(t){throw t.code===403&&this.emit("authInfoExpired"),t}})}getCurrentClientRole(){return this.clientRole}setAudioOnlyMode(e){if(this.isInCall())throw new U(B.ERR_INNER,"can not change audioOnly mode in call");this._audioOnlyMode=e}setAudioRedEnabled(e){if(this.isInCall())throw new U(B.ERR_INNER,"can not change audioRedEnabled in call");this.bizControl.setAudioRedEnabled(e)}setVideoCodec(e){this.bizControl.setVideoCodec(e)}setCheckAuthInfoTimer(e,t){const i=1e3*(e-t);this._authInfoExpiredTimer=window.setTimeout(()=>{this.emit("authInfoExpired")},i),this._authInfoWillExpireTimer=window.setTimeout(()=>{this.emit("authInfoWillExpire")},i-3e4),this._serverCheckAuthInfoTimestamp=t,this._localCheckAuthInfoTimestamp=+Date.now()/1e3}clearCheckAuthInfoTimer(){this._authInfoExpiredTimer&&window.clearTimeout(this._authInfoExpiredTimer),this._authInfoWillExpireTimer&&window.clearTimeout(this._authInfoWillExpireTimer)}joinChannel(s,n){return I(this,arguments,function*(e,t,i={}){this.syncGlobalEnv();const c=Date.now();let o,l=typeof t=="string"?t:t==null?void 0:t.userName;if(typeof e=="string")try{const p=JSON.parse(window.atob(e));o={appId:p.appid,channelId:p.channelid,userId:p.userid,timestamp:p.timestamp,nonce:p.nonce,token:p.token}}catch(p){throw new U(B.ERR_INVALID_ARGUMENTS,`authInfo is invalid: ${p.message||""}`)}else o=e;l||(l=o.userId);const d={start:Date.now()};let u=Vi.checkAuthInfo(o);if(ae.AliRtcConnectionStatusInit!==this.connectState&&ae.AliRtcConnectionStatusDisconnected!==this.connectState&&ae.AliRtcConnectionStatusFailed!==this.connectState){const p=new U(B.ERR_JOIN_ALREADY_JOINED,"already joined");throw this.connectState===ae.AliRtcConnectionStatusConnecting&&(p.message="Repeated operation during login"),this.slsReporter.reportJoin(p.code,d,""),p}{if(u)throw this.connectState=ae.AliRtcConnectionStatusFailed,this.slsReporter.reportJoin(u.code,d,""),this.slsReporter.reportJoinResult(u),u;o.sessionId=Le.createCallid("web"),this.sessionId=o.sessionId,this.slsReporter.start(o),this.slsReporter.reportConnectionLatencyEvent(Ze.JOIN,st.START,"","",c),this.connectState=ae.AliRtcConnectionStatusConnecting,this.emit("connectionStatusChange",ae.AliRtcConnectionStatusConnecting,Pt.AliRtcConnectionSignalingConnecting),T.setActiveInstance(this.instanceId),T.setSessionID(o.appId,o.sessionId);const p=()=>I(this,null,function*(){var g,b,S,v;try{let R="Conference";typeof t=="object"&&t.capabilityProfile===Di.Human&&(R="AIUser");const _=JSON.parse(this.getParameter());_.joinMode&&(R=_.joinMode);const y=new Ii(((g=this.config)==null?void 0:g.env)||It.prod,o,R);if(y.result){const C=(h=y.result.config,f=at.EnableNonOnePcDefaultJoinMode,ii(h==null?void 0:h.data,f));y.result.useonepc&&C!==!1||(R=""),T.info(`[${Ii.logName}]`,"got allocate result from localStorage",`joinMode: ${R}`,y.result.useonepc,C)}else T.info(`[${Ii.logName}]`,"no allocate result in localStorage",`joinMode: ${R}`);R&&(i.joinmode=R);const w=Date.now(),A=yield this.signalingManager.join(o,l,this.maxSignalingReconnectDuration,d,i);A.l1ip?(T.info("allocate l1 pub ip with mode",R,A.l1ip),this.bizControl.rtsManager.preferredPubL1Ip=A.l1ip):this.bizControl.rtsManager.preferredPubL1Ip=void 0,A.l1subip?(T.info("allocate l1 sub ip with mode",R,A.l1subip),this.bizControl.rtsManager.preferredSubL1Ip=A.l1subip):this.bizControl.rtsManager.preferredSubL1Ip=void 0;const E=Date.now();if(this.connectState=ae.AliRtcConnectionStatusConnected,this.emit("connectionStatusChange",ae.AliRtcConnectionStatusConnected,Pt.AliRtcConnectionSignalingJoinRoomSuccess),y.fetchAndUpdate(),this.bizControl.init(o,A,{capabilityProfile:typeof t=="object"?t.capabilityProfile:Di.Default,robotUserId:typeof t=="object"?t.robotUserId:void 0}),(b=A==null?void 0:A.config)==null?void 0:b.data){this.bizControl.updateDynamicConfig(A.config.data),_e.setGlobalQualityStatsEnable((S=this.bizControl.rtsManager.dycConf.getDycConf("h5_quality_stats_enable"))!=null?S:!0);const C=this.bizControl.rtsManager.dycConf.getDycConf("h5_low_perf_devices")||"";if(C){const P=ka();P&&(Array.isArray(C)?C:String(C).split(",").map(M=>M.trim()).filter(Boolean)).includes(P)&&(T.info("[LowPerfDevice]",`Current device "${P}" is in low performance device list, suggesting lower resolution subscription`),this.emit("sdkAdvisory",{type:"lowPerformanceDevice",deviceModel:P}),this.bizControl.rtsManager.isLowPerfDevice=!0)}}this.bizControl.setChannelContext(),this.setCheckAuthInfoTimer(o.timestamp,A.timestamp),this.liveTranscoding.setAuthInfo(o),this.slsReporter.reportJoin(0,d,A.tid),this.slsReporter.reportJoinResult(null),this.slsReporter.reportConnectionLatencyEvent(Ze.JOIN,st.SEND_SIG,"","",w),this.slsReporter.reportConnectionLatencyEvent(Ze.JOIN,st.RECV_RST,"","",E),this.slsReporter.reportConnectionLatencyEvent(Ze.JOIN,st.END,"","")}catch(R){const _=(v=R.code)!=null?v:-1,y=R.reason||R.message||"";throw this.connectState=ae.AliRtcConnectionStatusDisconnected,this.emit("connectionStatusChange",ae.AliRtcConnectionStatusDisconnected,Pt.AliRtcConnectionSignalingJoinRoomFailure),this.slsReporter.reportJoin(_,d,""),this.slsReporter.reportJoinResult(R),new U(_,y)}var h,f});this.currentRoleCanPublish?(yield Promise.all([p(),this.startDefaultDevices()]),yield this.startPublish(Dt.JOIN_CHANNEL)):yield p(),this.publisher.reportSelfDeviceStatus(),this.remoteUsers.forEach(h=>{h.updateSubscribe(ge.Join)})}})}joinAIChannel(e,t,i){return I(this,null,function*(){return this._proxyAiTid=mt(),this._agentParam=i,this.joinChannel(e,t,{proxyai:{tid:this._proxyAiTid,region:i.region,proxydata:JSON.stringify({Region:i.region,Action:i.action,ActionParams:i.params})}})})}leaveChannel(){return I(this,null,function*(){var t;this.slsReporter.reportLeaveInvoked(),yield this.bizControl.leave();let e=new Date().getTime();if(ae.AliRtcConnectionStatusConnected===this.connectState)try{let i;i=yield this.signalingManager.leave(),this.slsReporter.reportLeave(new Date().getTime()-e,0,(t=i==null?void 0:i.tid)!=null?t:"")}catch(i){this.slsReporter.reportLeave(new Date().getTime()-e,i.code,i.reason)}else this.slsReporter.reportLeave(0,0,"");this.sessionId=void 0,this.networkError=!1,this.connectState=ae.AliRtcConnectionStatusDisconnected,this.clearCheckAuthInfoTimer(),this.liveTranscoding.clear(),this.slsReporter.stop(),this.signalingManager.reset(),T.setActiveInstance(this.instanceId),T.reportEnd()})}isInCall(){return this.connectState===ae.AliRtcConnectionStatusConnected}refreshAuthInfo(e){return I(this,null,function*(){let t;if(this.syncGlobalEnv(),typeof e=="string")try{const d=JSON.parse(window.atob(e));t={userId:d.userid,timestamp:d.timestamp,nonce:d.nonce,token:d.token}}catch(d){throw new U(B.ERR_INVALID_ARGUMENTS,`authInfo is invalid: ${d.message||""}`)}else t=e;const{userId:i,nonce:s,timestamp:n,token:c,role:o}=t,l={userId:i,nonce:s,timestamp:n,token:c,role:o};try{yield this.signalingManager.refreshAuthInfo(l),this.bizControl.refreshAuthInfo(l),this.liveTranscoding.refreshAuthInfo(l),this.clearCheckAuthInfoTimer(),this._serverCheckAuthInfoTimestamp&&this._localCheckAuthInfoTimestamp&&t.timestamp&&this.setCheckAuthInfoTimer(t.timestamp,this._serverCheckAuthInfoTimestamp+(Date.now()-this._localCheckAuthInfoTimestamp))}catch(d){throw d}})}isAudioOnly(){return this._audioOnlyMode}publishLocalAudioStream(e){return I(this,null,function*(){this.syncGlobalEnv(),this.publisher.setPublishLocalAudioStreamEnabled(e),this.connectState===ae.AliRtcConnectionStatusConnected&&(e?this.publisher.hasMicrophone?yield this.publisher.updateStreams():yield this.startAudioCapture():yield this.publisher.publishUpdate())})}isLocalAudioStreamPublished(){var e;return(e=this.publisher.publishLocalAudioStreamEnabled)!=null?e:!0}setDefaultSubscribeAllRemoteAudioStreams(e){this.bizControl.setAutoSubAudio(e)}subscribeAllRemoteAudioStreams(e){this.bizControl.setWantSubAudio(e)}subscribeRemoteAudioStream(e,t){if(t&&!this.bizControl.isWantSubAudio)throw new U(B.ERR_INVALID_ARGUMENTS,"subscribeAllRemoteAudioStreams(true) must be called first");this.bizControl.updateAudioWant(e,t)}resumeRemoteAudioStream(e){const t=this.bizControl.getRemoteUser(e);if(!t)throw new U(B.ERR_INNER,`no remote user(${e}) founded`);t.resumeAudio()}stopRemoteAudioPlay(e){const t=this.bizControl.getRemoteUser(e);if(!t)throw new U(B.ERR_INNER,`no remote user(${e}) founded`);t.stopPlayAudio()}publishLocalVideoStream(e){return I(this,null,function*(){this.syncGlobalEnv(),this.publisher.setPublishLocalVideoStreamEnabled(e),this.connectState===ae.AliRtcConnectionStatusConnected&&(e?this.publisher.hasCamera?yield this.publisher.updateStreams():yield this.enableLocalVideo():yield this.publisher.publishUpdate())})}isLocalVideoStreamPublished(){var e;return(e=this.publisher.publishLocalVideoStreamEnabled)!=null?e:!0}setRemoteDefaultVideoStreamType(e){[Ge.AliRtcVideoStreamTypeHigh,Ge.AliRtcVideoStreamTypeLow].includes(e)&&this.bizControl.setRemoteDefaultVideoStreamType(e)}setRemoteUserVideoStreamType(e,t){[Ge.AliRtcVideoStreamTypeHigh,Ge.AliRtcVideoStreamTypeLow].includes(t)&&this.bizControl.setRemoteUserVideoStreamType(e,t)}setDefaultSubscribeAllRemoteVideoStreams(e){this.bizControl.setAutoSubVideo(e),this.bizControl.setAutoSubScreen(e)}subscribeAllRemoteVideoStreams(e){this.bizControl.setWantSubVideo(e),this.bizControl.setWantSubScreen(e)}subscribeRemoteMediaStream(e,t,i,s){var o;const n=this.bizControl.getRemoteUser(e),c=_e.getInstance();if(!n)throw new U(B.ERR_INNER,`no remote user(${e}) founded`);if(!i||t!==ue.AliRtcVideoTrackScreen&&t!==ue.AliRtcVideoTrackBoth?n.setWantSubScreen(!1):n.setWantSubScreen(!0),!i||t!==ue.AliRtcVideoTrackCamera&&t!==ue.AliRtcVideoTrackBoth?n.setWantSubVideo(!1):n.setWantSubVideo(!0),n.setWantSubAudio(s),i||s)n.subscribe({video:i,audio:s},ge.User),c.addEventData(_e.eventStartSub,e,i,s);else{try{c.unsubscribeRemoteViewConfig(((o=this.bizControl.userId)!=null?o:"")+e)}catch(l){}n.stopSubscribe({video:!0,audio:!0}),c.addEventData(_e.eventRemoveSub,e,i,s)}}resumeRemoteMediaStream(e,t){const i=this.bizControl.getRemoteUser(e);i&&i.resumeVideo(t)}getOnlineRemoteUsers(){return this.bizControl.remoteUsers.map(e=>e.userId)}getUserInfo(e){var t;return(t=this.bizControl.getRemoteUser(e))==null?void 0:t.remoteUserInfo}isUserOnline(e){return!!this.bizControl.remoteUsers.find(t=>t.userId===e)}startScreenShare(e){return I(this,null,function*(){this.syncGlobalEnv();const t={video:!1,audio:!1},{audio:i=!1,videoTrack:s,audioTrack:n}=e||{};if(s||n){t.screen=!0;const c=new MediaStream;s&&c.addTrack(s),n&&c.addTrack(n),t.mediaStream=c}else t.screen=!i||{audio:!0};yield this.publisher.createLocalStream(t)})}stopScreenShare(){return I(this,null,function*(){this.publisher.stopLocalStream({screen:!0})})}setScreenShareConfiguration(e){return I(this,null,function*(){const{width:t,height:i}=e;if(t&&!isNaN(t)&&i&&!isNaN(i)&&t*i>9437184)throw new U(B.ERR_INVALID_ARGUMENTS,"width * height must be less than 9437184");const o=e,{bitrate:s}=o,n=Wt(o,["bitrate"]),c=X({},n);s&&(c.maxBitrate=e.bitrate),yield this.publisher.setScreenProfile(c)})}setScreenShareContentHint(e){return I(this,null,function*(){e&&this.publisher.setScreenContentHint(e)})}publishLocalScreenShareStream(e,t){return I(this,null,function*(){this.syncGlobalEnv(),this.publisher.setPublishLocalScreenStreamEnabled(e),this.connectState===ae.AliRtcConnectionStatusConnected&&(e?this.publisher.hasScreenShare?yield this.publisher.updateStreams():yield this.startScreenShare(t):yield this.publisher.publishUpdate())})}isScreenSharePublished(){var e;return(e=this.publisher.publishLocalScreenStreamEnabled)!=null?e:!0}setAudioShareVolume(e){if(typeof e!="number")throw new U(B.ERR_INVALID_ARGUMENTS,"volume must be a number");this.bizControl.setAudioVolume({screen:Math.max(0,Math.min(e,400))/100})}enableAudioVolumeIndication(e){this.bizControl.enableAudioVolumeIndication(e)}muteLocalMic(e=!1){this.publisher.muteLocalMic(e),this.connectState===ae.AliRtcConnectionStatusConnected&&this.isPublishing&&this.publisher.reportSelfDeviceStatus()}muteRemoteAudioPlaying(e,t=!1){const i=this.bizControl.getRemoteUser(e);if(!i)throw new U(B.ERR_INNER,`no remote user(${e}) founded`);i.setAudioMuted(t)}muteAllRemoteAudioPlaying(e=!1){this.bizControl.setAudioMuted(e)}startAudioCapture(e){return I(this,null,function*(){const t={audio:e||!0};yield this.publisher.createLocalStream(t)})}setAudioConstraints(e){return I(this,null,function*(){yield this.publisher.setMicrophoneConstraints(e)})}stopAudioCapture(){this.publisher.stopAudioCapture()}switchMicrophone(e,t){return I(this,null,function*(){if(yield this.publisher.setMicrophoneDeviceId(e),!this.publisher.audioCaptureDisabled){if(t)return void(yield this.publisher.createLocalStream({audio:!0,mediaStream:new MediaStream([t])}));yield this.publisher.createLocalStream({audio:{deviceId:e}})}})}setRecordingVolume(e){if(typeof e!="number")throw new U(B.ERR_INVALID_ARGUMENTS,"volume must be a number");this.bizControl.setAudioVolume({audio:Math.max(0,Math.min(e,400))/100})}setPlayoutVolume(e){if(typeof e!="number")throw new U(B.ERR_INVALID_ARGUMENTS,"volume must be a number");this.bizControl.setPlayoutVolume(Math.max(0,Math.min(e,100))/100)}setRemoteAudioVolume(e,t){const i=this.bizControl.getRemoteUser(e);if(!i)throw new U(B.ERR_INNER,`no remote user(${e}) founded`);if(typeof t!="number")throw new U(B.ERR_INVALID_ARGUMENTS,"volume must be a number");i.setPlayoutVolume(Math.max(0,Math.min(t,100))/100)}setAudioProfile(e){return I(this,null,function*(){yield this.publisher.setAudioProfile(e)})}getAudioTrack(e){return I(this,null,function*(){if(!e)return this.publisher.audioTrack;const t=this.bizControl.getRemoteUser(e);return t==null?void 0:t.getAudioTrack})}setLocalViewConfig(e,t){return I(this,null,function*(){var i;if(this._audioOnlyMode)throw new U(B.ERR_INNER,"Cannot set local view in audio only mode");(i=this.bizControl)==null||i.setLocalViewConfig(e,t),t===ue.AliRtcVideoTrackCamera&&this.publisher.hasCamera?yield this.startPreview():t===ue.AliRtcVideoTrackScreen&&this.publisher.hasScreenShare&&(yield this.startPreviewScreen())})}setCameraCapturerConfiguration(e){return I(this,null,function*(){const l=e,{cameraDirection:t,deviceId:i,bitrate:s,maxSendFrameRate:n}=l,c=Wt(l,["cameraDirection","deviceId","bitrate","maxSendFrameRate"]),o=X({},c);s&&(o.maxBitrate=s),n&&(o.maxSendFrameRate=n),Object.keys(o).length>0&&(yield this.publisher.setVideoProfile(o)),t!==void 0&&this.publisher.setCameraDirection(t),i&&this.publisher.setCameraDeviceId(i)})}setCameraCapturerContentHint(e){return I(this,null,function*(){e&&this.publisher.setVideoContentHint(e)})}enableLocalVideo(e=!0){return I(this,null,function*(){var t,i,s,n,c,o;if(this._audioOnlyMode)throw new U(B.ERR_INNER,"Cannot enable local video in audio only mode");e?((t=this.publisher.publishStreams)!=null&&t.video&&((s=(i=this.publisher.publishStreams)==null?void 0:i.video)==null||s.disableVideo(),(o=(c=(n=this.publisher.publishStreams)==null?void 0:n.video)==null?void 0:c.videoTrack)==null||o.stop()),yield this.publisher.startCameraCapture()):yield this.publisher.stopCameraCapture()})}muteLocalCamera(e){return I(this,null,function*(){this.publisher.muteLocalCamera(e),this.connectState===ae.AliRtcConnectionStatusConnected&&this.isPublishing&&this.publisher.reportSelfDeviceStatus()})}muteLocalScreen(e){return I(this,null,function*(){this.publisher.muteLocalScreen(e),this.connectState===ae.AliRtcConnectionStatusConnected&&this.isPublishing&&this.publisher.reportSelfDeviceStatus()})}setRemoteViewConfig(e,t,i){this.bizControl.setRemoteViewConfig(t,e,i)}isCameraOn(){var e;return(e=this.publisher.hasCamera)!=null?e:!1}switchCamera(e,t){return I(this,null,function*(){var s;if(this._audioOnlyMode)throw new U(B.ERR_INNER,"Cannot switch camera in audio only mode");const i={};if(e?(i.deviceId=e,this.slsReporter.reportSwitchCamera(e)):t||(i.cameraDirection=this.publisher.cameraDirection==="environment"?Ai.CAMERA_FRONT:Ai.CAMERA_REAR,this.slsReporter.reportSwitchCamera(this.publisher.cameraDirection||"")),yield this.setCameraCapturerConfiguration(i),!this.publisher.cameraCaptureDisabled){(s=this.publisher.cameraTrack)==null||s.stop();const n={video:!0};t&&(n.mediaStream=new MediaStream([t])),yield this.publisher.createLocalStream(n)}})}getCurrentCameraDeviceId(){return this.publisher.getCurrentCameraDeviceId()}startPreview(){return I(this,null,function*(){if(this._audioOnlyMode)throw new U(B.ERR_INNER,"Cannot start preview camera in audio only mode");this.publisher.hasCamera||(yield this.enableLocalVideo(!0)),yield this.publisher.previewAll({screen:!1})})}startPreviewScreen(e){return I(this,null,function*(){if(this._audioOnlyMode)throw new U(B.ERR_INNER,"Cannot start preview screen share in audio only mode");this.publisher.hasScreenShare||(yield this.startScreenShare(e)),yield this.publisher.previewAll({primary:!1})})}stopPreview(){return I(this,null,function*(){yield this.publisher.stopPreview({primary:!0,screen:!1})})}stopPreviewScreen(){return I(this,null,function*(){yield this.publisher.stopPreview({primary:!1,screen:!0})})}getVideoTrack(e){return I(this,null,function*(){var n,c;const{userId:t,streamType:i}=e;if(!t)return i===He.AliRtcSdkStreamTypeCapture?this.publisher.cameraTrack:this.publisher.screenTrack;const s=this.bizControl.getRemoteUser(t);return i===He.AliRtcSdkStreamTypeCapture?(n=s==null?void 0:s.getCameraStream)==null?void 0:n.videoTrack:(c=s==null?void 0:s.getScreenStream)==null?void 0:c.videoTrack})}startPublishLiveStream(e,t){return I(this,null,function*(){return this.liveTranscoding.startPublishLiveStream(e,t)})}updatePublishLiveStream(e,t){return I(this,null,function*(){return this.liveTranscoding.updatePublishLiveStream(e,t)})}updatePublishLiveStreamWithTaskId(e,t){return this.liveTranscoding.updatePublishLiveStreamWithTaskId(e,t)}stopPublishLiveStream(e){return I(this,null,function*(){return this.liveTranscoding.stopPublishLiveStream(e)})}stopPublishLiveStreamWithTaskId(e){return this.liveTranscoding.stopPublishLiveStreamWithTaskId(e)}setEnableMediaExtensionMsg(e){var t;(t=this.bizControl)==null||t.setEnableMediaExtensionMsg(!!e)}sendMediaExtensionMsg(e,t){return I(this,null,function*(){return this.sendMediaExtensionMsgEx(e,t,5)})}sendMediaExtensionMsgEx(e,t,i){return I(this,null,function*(){if(!this.publisher||!this.isPublishing)throw new U(B.ERR_INNER,"you should publish first");return this.slsReporter.reportSEIMessage(i,e.byteLength,t,0,!1),this.publisher.sendSEI(e,t,i)})}enablePlugin(e,t){this.bizControl.pluginManager.add(e,t)}removePlugin(e){this.bizControl.pluginManager.remove(e)}setPluginOption(e,t){const i=this.bizControl.pluginManager.get(e);i&&t&&i.setOptions(t)}getPluginByName(e){return this.bizControl.pluginManager.get(e)}getPluginOption(e){const t=this.bizControl.pluginManager.get(e);return t==null?void 0:t.getOptions()}isBeautyAvailable(){return this.bizControl.pluginManager.has("AliRtcBeauty")}isBeautyEnabled(){const e=this.bizControl.pluginManager.get("AliRtcBeauty");if(!e)throw new U(qt.AliRtcPluginErrorNoFindPlugin,"you should enable beautyPlugin first");return!!(e!=null&&e.isEnable)}setBeautyEffect(e,t){const i=this.bizControl.pluginManager.get("AliRtcBeauty");if(!i)throw new U(qt.AliRtcPluginErrorNoFindPlugin,"you should enable beautyPlugin first");e?i.enable():i.disable(),i.setOptions({basicBeauty:{skinBuffing:Math.max(Math.min(1,+t.smoothnessLevel),0),whitening:Math.max(Math.min(1,+t.whiteningLevel),0)}})}enableBackgroundExchange(e,t){const i=this.bizControl.pluginManager.get("AliRtcBeauty");if(!i||!i.isEnable)throw new U(qt.AliRtcPluginErrorNoFindPlugin,"you should enable beautyPlugin first");const s={setSegmentBackgroundImage:{backgroundImgUrl:e?t:""}};e&&(s.segmentBackgroundProcess={enable:!1}),i.setOptions(s)}enableBackgroundBlur(e){const t=this.bizControl.pluginManager.get("AliRtcBeauty");if(!t||!t.isEnable)throw new U(qt.AliRtcPluginErrorNoFindPlugin,"you should enable beautyPlugin first");const i={segmentBackgroundProcess:{type:0,enable:e}};e&&(i.setSegmentBackgroundImage={type:0,backgroundImgUrl:""}),t.setOptions(i)}setParameter(e){this.bizControl.setParameter(e)}getParameter(){return this.bizControl.getParameter()}sendDataChannelMessage(e){this.bizControl.sendDataChannelMessage(e)}subscribeRemoteStream(e){const{currentUserId:t,targetUserId:i}=e;if(i===t)throw new U(B.ERR_INNER,"targetUserId should not be equal to currentUserId");return new vs(e)}},m(F,"logName","AliRtcEngine"),m(F,"logError",!0),m(F,"isSupported",Lc),m(F,"checkH265Decode",Nc),m(F,"checkH265Encode",xc),m(F,"isDualVideoStreamSupported",As.isSupport),m(F,"getCameraList",()=>I(F,null,function*(){return(yield J.AliRTS.getCameraList()).filter(e=>e.deviceId)})),m(F,"getMicrophoneList",()=>I(F,null,function*(){return(yield J.AliRTS.getMicList()).filter(e=>e.deviceId)})),m(F,"getSpeakerList",()=>I(F,null,function*(){return(yield J.AliRTS.getSpeakerList()).filter(e=>e.deviceId)})),m(F,"_instances",new Map),m(F,"_instanceCounter",0),m(F,"_instance"),m(F,"AliRtcSdkChannelProfile",Ut),m(F,"AliRtcSdkClientRole",zt),m(F,"AliRtcVideoStreamType",Ge),m(F,"AliRtcVideoTrack",ue),m(F,"AliRtcAudioTrack",ti),m(F,"AliRtcPublishState",ee),m(F,"AliRtcSubscribeState",ce),m(F,"AliRtcRawDataStreamType",He),m(F,"AliRtcLogLevel",Ss),m(F,"AliRtcEngineLocalDeviceType",kt),m(F,"AliRtcEngineLocalDeviceExceptionType",je),m(F,"AliRtcConnectionStatus",ae),m(F,"AliRtcConnectionStatusChangeReason",Pt),m(F,"AliRtcPlugin",jt),m(F,"AliRtcPluginTrackType",bi),m(F,"AliRtcImageHolderPlugin",Xn),m(F,"AliRtcLiveTranscodingParam",Zi),m(F,"AliRtcLiveTranscodingEncodeParam",er),m(F,"AliRtcLiveTranscodingMixParam",Wn),m(F,"AliRtcLiveTranscodingSingleParam",zn),m(F,"AliRtcTranscodingClockWidget",Kn),m(F,"AliRtcTranscodingImage",lr),m(F,"AliRtcTranscodingText",qn),m(F,"AliRtcTranscodingUser",Gn),m(F,"AliRtcLiveTranscodingMixMode",Mi),m(F,"AliRtcLiveTranscodingStreamType",Gs),m(F,"AliRtcLiveTranscodingSourceType",vi),m(F,"AliRtcLiveTranscodingTaskProfile",Xs),m(F,"AliRtcLiveTranscodingAudioSampleRate",Qi),m(F,"AliRtcLiveTranscodingSegmentType",Ni),m(F,"AliRtcLiveTranscodingFontType",xi),m(F,"AliRtcLiveTranscodingCropMode",Qs),m(F,"AliRtcLiveTranscodingMediaProcessMode",Yi),m(F,"AliRtcLiveTranscodingState",Ys),m(F,"AliRtcLiveTranscodingErrorCode",xt),m(F,"AliRtcTrascodingPublishTaskStatus",Zs),m(F,"AliRtcDataChannelMsg",Jt),m(F,"AliRtcDataMsgType",Fs),m(F,"Plugin",jt),F);$([k()],j.prototype,"destroy",1),$([k()],j.prototype,"backToUnpublishStatus",1),$([k()],j.prototype,"resumePublishForNetworkRecovery",1),$([k()],j.prototype,"onNetworkRecovery",1),$([k()],j.prototype,"resumeSubList",1),$([k(H)],j.prototype,"retrySubscribe",1),$([k(H)],j.prototype,"setEnableDualVideoStream",1),$([k(H)],j.prototype,"setChannelProfile",1),$([k(H)],j.prototype,"setClientRole",1),$([k(H)],j.prototype,"setAudioOnlyMode",1),$([k()],j.prototype,"clearCheckAuthInfoTimer",1),$([k(H)],j.prototype,"joinChannel",1),$([k(H)],j.prototype,"joinAIChannel",1),$([k(H)],j.prototype,"leaveChannel",1),$([k(H)],j.prototype,"refreshAuthInfo",1),$([k(H)],j.prototype,"publishLocalAudioStream",1),$([k(H)],j.prototype,"setDefaultSubscribeAllRemoteAudioStreams",1),$([k(H)],j.prototype,"subscribeAllRemoteAudioStreams",1),$([k(H)],j.prototype,"subscribeRemoteAudioStream",1),$([k(H)],j.prototype,"resumeRemoteAudioStream",1),$([k(H)],j.prototype,"stopRemoteAudioPlay",1),$([k(H)],j.prototype,"publishLocalVideoStream",1),$([k(H)],j.prototype,"setRemoteDefaultVideoStreamType",1),$([k(H)],j.prototype,"setRemoteUserVideoStreamType",1),$([k(H)],j.prototype,"setDefaultSubscribeAllRemoteVideoStreams",1),$([k(H)],j.prototype,"subscribeAllRemoteVideoStreams",1),$([k(H)],j.prototype,"subscribeRemoteMediaStream",1),$([k(H)],j.prototype,"resumeRemoteMediaStream",1),$([k(([a])=>[`${a==null?void 0:a.audio}`])],j.prototype,"startScreenShare",1),$([k()],j.prototype,"stopScreenShare",1),$([k(H)],j.prototype,"setScreenShareConfiguration",1),$([k(H)],j.prototype,"setScreenShareContentHint",1),$([k()],j.prototype,"publishLocalScreenShareStream",1),$([k(H)],j.prototype,"setAudioShareVolume",1),$([k(H)],j.prototype,"enableAudioVolumeIndication",1),$([k(H)],j.prototype,"muteLocalMic",1),$([k(H)],j.prototype,"muteRemoteAudioPlaying",1),$([k(H)],j.prototype,"muteAllRemoteAudioPlaying",1),$([k(H)],j.prototype,"startAudioCapture",1),$([k(H)],j.prototype,"setAudioConstraints",1),$([k()],j.prototype,"stopAudioCapture",1),$([k(H)],j.prototype,"switchMicrophone",1),$([k(H)],j.prototype,"setRecordingVolume",1),$([k(H)],j.prototype,"setPlayoutVolume",1),$([k(H)],j.prototype,"setRemoteAudioVolume",1),$([k(H)],j.prototype,"setAudioProfile",1),$([k(H)],j.prototype,"getAudioTrack",1),$([k(H)],j.prototype,"setLocalViewConfig",1),$([k(H)],j.prototype,"setCameraCapturerConfiguration",1),$([k(H)],j.prototype,"setCameraCapturerContentHint",1),$([k(H)],j.prototype,"enableLocalVideo",1),$([k(H)],j.prototype,"muteLocalCamera",1),$([k(H)],j.prototype,"muteLocalScreen",1),$([k(H)],j.prototype,"setRemoteViewConfig",1),$([k(H)],j.prototype,"switchCamera",1),$([k()],j.prototype,"startPreview",1),$([k()],j.prototype,"startPreviewScreen",1),$([k()],j.prototype,"stopPreview",1),$([k()],j.prototype,"stopPreviewScreen",1),$([k()],j.prototype,"startPublishLiveStream",1),$([k()],j.prototype,"updatePublishLiveStream",1),$([k()],j.prototype,"updatePublishLiveStreamWithTaskId",1),$([k()],j.prototype,"stopPublishLiveStream",1),$([k()],j.prototype,"stopPublishLiveStreamWithTaskId",1),$([k(H)],j.prototype,"setEnableMediaExtensionMsg",1),$([k(([a,r,e])=>[a.byteLength,r,e])],j.prototype,"sendMediaExtensionMsgEx",1),$([k(([a,r])=>[a.name||"",r])],j.prototype,"enablePlugin",1),$([k(H)],j.prototype,"removePlugin",1),$([k(H)],j.prototype,"setPluginOption",1),$([k(H)],j.prototype,"getPluginByName",1),$([k(H)],j.prototype,"getPluginOption",1),$([k(H)],j.prototype,"setBeautyEffect",1),$([k(H)],j.prototype,"enableBackgroundExchange",1),$([k(H)],j.prototype,"enableBackgroundBlur",1),$([k(H)],j.prototype,"setParameter",1),$([k(([a])=>{var r;return[(r=a.data)==null?void 0:r.byteLength]})],j.prototype,"sendDataChannelMessage",1),$([k(H)],j.prototype,"subscribeRemoteStream",1),$([k(H)],j,"setLogLevel",1);let Yn=j;Qt=new Bs({businessName:"imp-web-rtc",version:(Zn=Yn.getSdkVersion())!=null?Zn:"unknown",env:"prod",disabled:window.AliRtcOptionsDisableProxy===!0,deferRegionSet:!0});const vl=Qt.shallowWrapClass(Yn);z.AliRtcAudioTrack=ti,z.AliRtcCapabilityProfile=Di,z.AliRtcConnectionStatus=ae,z.AliRtcConnectionStatusChangeReason=Pt,z.AliRtcDataChannelMsg=Jt,z.AliRtcDataMsgType=Fs,z.AliRtcEngineLocalDeviceExceptionType=je,z.AliRtcEngineLocalDeviceType=kt,z.AliRtcErrorCode=B,z.AliRtcImageHolderPlugin=Xn,z.AliRtcLiveTranscodingAudioSampleRate=Qi,z.AliRtcLiveTranscodingCropMode=Qs,z.AliRtcLiveTranscodingEncodeParam=er,z.AliRtcLiveTranscodingErrorCode=xt,z.AliRtcLiveTranscodingFontType=xi,z.AliRtcLiveTranscodingMediaProcessMode=Yi,z.AliRtcLiveTranscodingMixMode=Mi,z.AliRtcLiveTranscodingMixParam=Wn,z.AliRtcLiveTranscodingParam=Zi,z.AliRtcLiveTranscodingSegmentType=Ni,z.AliRtcLiveTranscodingSingleParam=zn,z.AliRtcLiveTranscodingSourceType=vi,z.AliRtcLiveTranscodingState=Ys,z.AliRtcLiveTranscodingStreamType=Gs,z.AliRtcLiveTranscodingTaskProfile=Xs,z.AliRtcLocalStreamInfo=zs,z.AliRtcLogLevel=Ss,z.AliRtcNetworkQuality=tt,z.AliRtcPlugin=jt,z.AliRtcPluginTrackType=bi,z.AliRtcPluginType=Nn,z.AliRtcPublishState=ee,z.AliRtcRawDataStreamType=He,z.AliRtcRemoteUserInfo=Dn,z.AliRtcSdkChannelProfile=Ut,z.AliRtcSdkClientRole=zt,z.AliRtcSubscribeState=ce,z.AliRtcTranscodingClockWidget=Kn,z.AliRtcTranscodingImage=lr,z.AliRtcTranscodingText=qn,z.AliRtcTranscodingUser=Gn,z.AliRtcTrascodingPublishTaskStatus=Zs,z.AliRtcVideoStreamType=Ge,z.AliRtcVideoTrack=ue,z.default=vl,Object.defineProperties(z,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});