@agora-js/media 4.23.4-1 → 4.23.4-3
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.
- package/AgoraRTC_N-media.esm.mjs +2 -2
- package/AgoraRTC_N-media.js +2 -2
- package/media.d.ts +10 -1
- package/package.json +3 -3
- package/rtc-sdk-media_en.d.ts +4 -1
package/AgoraRTC_N-media.esm.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* AgoraWebSDK_N-v4.23.4-
|
|
2
|
+
* AgoraWebSDK_N-v4.23.4-3-0-g2fa1388f-dirty Copyright AgoraInc.
|
|
3
3
|
*/
|
|
4
4
|
|
|
5
|
-
import"webrtc-adapter";import{getBrowserInfo as e,BrowserName as t,isChromeKernel as i,nextTick as r,isAboveChrome as s,isAboveFirefox as o,isAboveSafari as n,BrowserOS as a,isSafari as c,isWkWebview as d,getParameter as u,isFirefox as h,isChrome as l,isEdge as p,isMobile as m,checkValidConstrainLong as g,checkValidNumber as _,checkValidBoolean as T,checkValidEnum as v,AgoraRTCError as f,AgoraRTCErrorCode as E,isEmpty as S,EventEmitter as y,getRandomString as k,runOnce as b,AgoraAPIName as I,AgoraAPITag as A,PromiseMutex as R,emitAsPromiseNoResponse as w,removeItemFromList as D,isIOS as C,isIpadOS as M,wait as N,showElectronSelectSourceWindow as O,getElectronInstance as L,isElectron as P,recursiveMerge as V,isAndroid as x,isHarmonyOS as U,detectSecureContext as B,isAndroidChromium as F,domLoadedPromise as G,isIOS15 as W,emitAsPromise as H,noop as K,isLegacyChrome as Z,isAboveEdge as Y,isAboveOpera as z,constrainLongToNumber as j,hexToBytes as X,md5 as Q,atom as J,emitAsInvokerNoResponse as q,isIOS16 as $,retryable as ee,getOSWithVersion as te,isAboveIOS15_1 as ie,isInPage as re,sumArray as se,jsonClone as oe,isBetweenBrowser as ne,isWindows as ae,elementVisibleChecker as ce,safeCloneJson as de,isAboveIOS15_2 as ue,isWechatBrowser as he}from"@agora-js/shared";export{isElectron}from"@agora-js/shared";import{logger as le,report as pe,AgoraRTCEventUploadType as me,apiInvoke as ge}from"@agora-js/report";import _e from"axios";const Te={getDisplayMedia:!1,getStreamFromExtension:!1,supportUnifiedPlan:!1,supportMinBitrate:!1,supportSetRtpSenderParameters:!1,supportDualStream:!0,webAudioMediaStreamDest:!1,supportReplaceTrack:!1,supportWebGL:!1,webAudioWithAEC:!1,supportRequestFrame:!1,supportShareAudio:!1,supportDualStreamEncoding:!1,supportDataChannel:!1,supportPCSetConfiguration:!1,supportWebRTCEncodedTransform:!1,supportWebRTCInsertableStream:!1,supportRequestVideoFrameCallback:!1,supportWebCrypto:!1};function ve(){const l=e();Te.getDisplayMedia=function(e){if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)return!0;return!1}(),Te.getStreamFromExtension=l.name===t.CHROME&&Number(l.version)>34,Te.supportUnifiedPlan=function(){if(!window.RTCRtpTransceiver)return!1;if(!("currentDirection"in RTCRtpTransceiver.prototype))return!1;const e=new RTCPeerConnection;let t=!1;try{e.addTransceiver("audio"),t=!0}catch(e){}return e.close(),t}(),Te.supportMinBitrate=l.name===t.CHROME||l.name===t.EDGE,Te.supportSetRtpSenderParameters=function(){const r=e();if(!window.RTCRtpSender||!window.RTCRtpSender.prototype.setParameters||!window.RTCRtpSender.prototype.getParameters)return!1;return!!i()||(!(!c()&&!d())||r.name===t.FIREFOX&&Number(r.version)>=64)}(),l.name===t.SAFARI&&(Number(l.version)>=14?Te.supportDualStream=!0:Te.supportDualStream=!1),Te.webAudioMediaStreamDest=function(){const i=e();if(i.name===t.SAFARI&&Number(i.version)<12)return!1;return!0}(),Te.supportReplaceTrack=function(){if(!window.RTCRtpSender)return!1;if("function"==typeof RTCRtpSender.prototype.replaceTrack)return!0;return!1}(),Te.supportWebGL="undefined"!=typeof WebGLRenderingContext,Te.supportRequestFrame=!!window.CanvasCaptureMediaStreamTrack,i()||(Te.webAudioWithAEC=!0),Te.supportShareAudio=function(){const i=e();if((i.os===a.WIN_10||i.os===a.WIN_81||i.os===a.WIN_7||i.os===a.LINUX||i.os===a.MAC_OS||i.os===a.CHROMIUM_OS)&&i.name===t.CHROME&&Number(i.version)>=74)return!0;return!1}(),Te.supportDataChannel=function(){if(s(76)||o(68)||n(14))return!0;return!1}(),Te.supportPCSetConfiguration=function(){const e=window.RTCPeerConnection;return!h()&&!!e&&e.prototype.setConfiguration instanceof Function}(),Te.supportWebRTCEncodedTransform=function(){const t=e();return"Chrome"===t.name&&Number(t.version)>=87||"Safari"===t.name&&Number(t.version)>=15}(),Te.supportWebRTCInsertableStream=function(){const i=e();return(i.name===t.CHROME||i.name===t.EDGE)&&Number(i.version)>=94&&"MediaStreamTrackGenerator"in window&&"MediaStreamTrackProcessor"in window}(),Te.supportRequestVideoFrameCallback=function(){if("requestVideoFrameCallback"in HTMLVideoElement.prototype)return!0;return!1}(),Te.supportWebCrypto="undefined"!=typeof window&&void 0!==window.crypto&&void 0!==window.crypto.subtle,r((()=>{Te.supportDualStreamEncoding=function(){const t=e();if(u("DISABLE_WEBAUDIO"))return!0;return"Safari"===t.name&&Number(t.version)>=14||!!("Chrome"===t.name&&/Windows/i.test(t.os||"")&&Number(t.version)>=100&&u("CHROME_DUAL_STREAM_USE_ENCODING"))}(),le.debug("browser ua: ",navigator.userAgent),le.info("browser info: ",l),le.info("browser compatibility: ",Te)}))}function fe(){return Te}function Ee(){return"setSinkId"in HTMLAudioElement.prototype&&(!u("RESTRICTION_SET_PLAYBACK_DEVICE")||(l()||p())&&!m())}function Se(){return!Te.supportUnifiedPlan||u("CHROME_FORCE_PLAN_B")&&i()}let ye=function(e){return e.IOS_15_16_INTERRUPTION_START="ios15_16-interruption-start",e.IOS_15_16_INTERRUPTION_END="ios15_16-interruption-end",e.IOS_INTERRUPTION_START="ios-interruption-start",e.IOS_INTERRUPTION_END="ios-interruption-end",e.STATE_CHANGE="state-change",e}({});function ke(e,t,i){return{sampleRate:e,stereo:t,bitrate:i}}function be(e,t,i,r,s){return{width:e,height:t,frameRate:i,bitrateMin:r,bitrateMax:s}}function Ie(e,t,i,r,s){return{width:{max:e},height:{max:t},frameRate:i,bitrateMin:r,bitrateMax:s}}function Ae(e,t){return{numSpatialLayers:e,numTemporalLayers:t}}const Re={"90p":be(160,90),"90p_1":be(160,90),"120p":be(160,120,15,30,65),"120p_1":be(160,120,15,30,65),"120p_3":be(120,120,15,30,50),"120p_4":be(212,120),"180p":be(320,180,15,30,140),"180p_1":be(320,180,15,30,140),"180p_3":be(180,180,15,30,100),"180p_4":be(240,180,15,30,120),"240p":be(320,240,15,40,200),"240p_1":be(320,240,15,40,200),"240p_3":be(240,240,15,40,140),"240p_4":be(424,240,15,40,220),"360p":be(640,360,15,80,400),"360p_1":be(640,360,15,80,400),"360p_3":be(360,360,15,80,260),"360p_4":be(640,360,30,80,600),"360p_6":be(360,360,30,80,400),"360p_7":be(480,360,15,80,320),"360p_8":be(480,360,30,80,490),"360p_9":be(640,360,15,80,800),"360p_10":be(640,360,24,80,800),"360p_11":be(640,360,24,80,1e3),"480p":be(640,480,15,100,500),"480p_1":be(640,480,15,100,500),"480p_2":be(640,480,30,100,1e3),"480p_3":be(480,480,15,100,400),"480p_4":be(640,480,30,100,750),"480p_6":be(480,480,30,100,600),"480p_8":be(848,480,15,100,610),"480p_9":be(848,480,30,100,930),"480p_10":be(640,480,10,100,400),"720p":be(1280,720,15,120,1130),"720p_auto":be(1280,720,30,900,3e3),"720p_1":be(1280,720,15,120,1130),"720p_2":be(1280,720,30,120,2e3),"720p_3":be(1280,720,30,120,1710),"720p_5":be(960,720,15,120,910),"720p_6":be(960,720,30,120,1380),"1080p":be(1920,1080,15,120,2080),"1080p_1":be(1920,1080,15,120,2080),"1080p_2":be(1920,1080,30,120,3e3),"1080p_3":be(1920,1080,30,120,3150),"1080p_5":be(1920,1080,60,120,4780),"1440p":be(2560,1440,30,120,4850),"1440p_1":be(2560,1440,30,120,4850),"1440p_2":be(2560,1440,60,120,7350),"4k":be(3840,2160,30,120,8910),"4k_1":be(3840,2160,30,120,8910),"4k_3":be(3840,2160,60,120,13500)},we={"480p":Ie(640,480,5),"480p_1":Ie(640,480,5),"480p_2":Ie(640,480,30),"480p_3":Ie(640,480,15),"720p":Ie(1280,720,5),"720p_auto":be(1280,720,30,900,3e3),"720p_1":Ie(1280,720,5),"720p_2":Ie(1280,720,30),"720p_3":Ie(1280,720,15),"1080p":Ie(1920,1080,5),"1080p_1":Ie(1920,1080,5),"1080p_2":Ie(1920,1080,30),"1080p_3":Ie(1920,1080,15)},De={"1SL1TL":Ae(1,1),"3SL3TL":Ae(3,3),"2SL3TL":Ae(2,3)};function Ce(e){return e||(e="480p_1"),"string"==typeof e?Object.assign({},Re[e]):e}function Me(e){return"string"==typeof e?Object.assign({},we[e]):e}function Ne(e){return"string"==typeof e?Object.assign({},De[e]):e}const Oe={speech_low_quality:ke(16e3,!1),speech_standard:ke(32e3,!1,18),music_standard:ke(48e3,!1),standard_stereo:ke(48e3,!0,56),high_quality:ke(48e3,!1,128),high_quality_stereo:ke(48e3,!0,192)};function Le(e){return"string"==typeof e?Object.assign({},Oe[e]):e}const Pe=[];function Ve(e){Pe.includes(e)||Pe.push(e)}function xe(e){const t=Pe.indexOf(e);-1!==t&&Pe.splice(t,1)}function Ue(e){return g(e.width,"config.width"),g(e.height,"config.height"),void 0!==e.frameRate&&g(e.frameRate,"config.frameRate"),void 0!==e.bitrateMax&&_(e.bitrateMax,"config.bitrateMax"),void 0!==e.bitrateMin&&_(e.bitrateMin,"config.bitrateMin"),!0}function Be(e){return void 0!==e.sampleRate&&_(e.sampleRate,"config.sampleRate",0,96e3,!0),void 0!==e.sampleSize&&_(e.sampleRate,"config.sampleSize",0,128,!0),void 0!==e.stereo&&T(e.stereo,"config.stereo"),void 0!==e.bitrate&&_(e.bitrate,"config.bitrate",0,1e4,!1),!0}function Fe(e){return"string"==typeof e?v(e,"profile",Object.keys(Re)):Ue(e),!0}function Ge(e){return"string"==typeof e?v(e,"profile",Object.keys(Oe)):Be(e),!0}function We(e){return v(e,"mediaSource",["screen","window","application"]),!0}let He=function(e){return e.NEED_RENEGOTIATE="@need_renegotiate",e.NEED_REPLACE_TRACK="@need_replace_track",e.NEED_REPLACE_MIXING_TRACK="@need_replace_mixing_track",e.NEED_CLOSE="@need_close",e.NEED_ENABLE_TRACK="@need_enable_track",e.NEED_DISABLE_TRACK="@need_disable_track",e.NEED_SESSION_ID="@need_sid",e.SET_OPTIMIZATION_MODE="@set_optimization_mode",e.GET_STATS="@get_stats",e.GET_RTC_STATS="@get_rtc_stats",e.GET_LOW_VIDEO_TRACK="@get_low_video_track",e.NEED_RESET_REMOTE_SDP="@need_reset_remote_sdp",e.NEED_UPDATE_VIDEO_ENCODER="@need_update_video_encoder",e.NEED_UPDATE_VIDEO_SEND_PARAMETERS="@need_update_video_send_parameters",e.NEED_MUTE_TRACK="@need_mute_track",e.NEED_UNMUTE_TRACK="@need_unmute_track",e}({}),Ke=function(e){return e.SCREEN_TRACK="screen_track",e.CUSTOM_TRACK="custome_track",e.LOW_STREAM="low_stream",e.SCREEN_LOW_TRACK="screen_low_track",e}({});function Ze(e){if(!e)throw new f(E.INVALID_PARAMS);return S(e.width)||g(e.width,"streamParameter.width"),S(e.height)||g(e.height,"streamParameter.height"),S(e.framerate)||g(e.framerate,"streamParameter.framerate"),S(e.bitrate)||_(e.bitrate,"streamParameter.bitrate"),!0}let Ye=function(e){return e[e.HIGH_STREAM=0]="HIGH_STREAM",e[e.LOW_STREAM=1]="LOW_STREAM",e}({}),ze=function(e){return e[e.HIGH_STREAM=0]="HIGH_STREAM",e[e.LOW_STREAM=1]="LOW_STREAM",e[e.HIGH_STREAM_LAYER1=4]="HIGH_STREAM_LAYER1",e[e.HIGH_STREAM_LAYER2=5]="HIGH_STREAM_LAYER2",e[e.HIGH_STREAM_LAYER3=6]="HIGH_STREAM_LAYER3",e[e.HIGH_STREAM_LAYER4=7]="HIGH_STREAM_LAYER4",e[e.HIGH_STREAM_LAYER5=8]="HIGH_STREAM_LAYER5",e[e.HIGH_STREAM_LAYER6=9]="HIGH_STREAM_LAYER6",e}({}),je=function(e){return e[e.DISABLE=0]="DISABLE",e[e.LOW_STREAM=1]="LOW_STREAM",e[e.AUDIO_ONLY=2]="AUDIO_ONLY",e[e.HIGH_STREAM_LAYER1=3]="HIGH_STREAM_LAYER1",e[e.HIGH_STREAM_LAYER2=4]="HIGH_STREAM_LAYER2",e[e.HIGH_STREAM_LAYER3=5]="HIGH_STREAM_LAYER3",e[e.HIGH_STREAM_LAYER4=6]="HIGH_STREAM_LAYER4",e[e.HIGH_STREAM_LAYER5=7]="HIGH_STREAM_LAYER5",e[e.HIGH_STREAM_LAYER6=8]="HIGH_STREAM_LAYER6",e}({}),Xe=function(e){return e.TRANSCEIVER_UPDATED="transceiver-updated",e.SEI_TO_SEND="sei-to-send",e.SEI_RECEIVED="sei-received",e.TRACK_UPDATED="track-updated",e}({}),Qe=function(e){return e.SOURCE_STATE_CHANGE="source-state-change",e.TRACK_ENDED="track-ended",e.BEAUTY_EFFECT_OVERLOAD="beauty-effect-overload",e.VIDEO_ELEMENT_VISIBLE_STATUS="video-element-visible-status",e.CLOSED="closed",e}({}),Je=function(e){return e.FIRST_FRAME_DECODED="first-frame-decoded",e.VIDEO_ELEMENT_VISIBLE_STATUS="video-element-visible-status",e.VIDEO_STATE_CHANGED="video-state-changed",e}({}),qe=function(e){return e.AUDIO="audio",e.VIDEO="video",e.DATA="data",e}({}),$e=function(e){return e.AUDIO_SOURCE_STATE_CHANGE="audio_source_state_change",e.RECEIVE_TRACK_BUFFER="receive_track_buffer",e.ON_AUDIO_BUFFER="on_audio_buffer",e.UPDATE_SOURCE="update_source",e}({}),et=function(e){return e.UPDATE_TRACK_SOURCE="update-track-source",e}({});const tt={sendVolumeLevel:0,sendBitrate:0,sendBytes:0,sendPackets:0,sendPacketsLost:0,sendJitterMs:0,sendRttMs:0,currentPacketLossRate:0},it={sendBytes:0,sendBitrate:0,sendPackets:0,sendPacketsLost:0,sendJitterMs:0,sendRttMs:0,sendResolutionHeight:0,sendResolutionWidth:0,captureResolutionHeight:0,captureResolutionWidth:0,targetSendBitrate:0,totalDuration:0,totalFreezeTime:0,currentPacketLossRate:0},rt={transportDelay:0,end2EndDelay:0,receiveBitrate:0,receiveLevel:0,receiveBytes:0,receiveDelay:0,receivePackets:0,receivePacketsLost:0,receivePacketsDiscarded:0,totalDuration:0,totalFreezeTime:0,freezeRate:0,packetLossRate:0,currentPacketLossRate:0,publishDuration:-1},st={uplinkNetworkQuality:0,downlinkNetworkQuality:0},ot={transportDelay:0,end2EndDelay:0,receiveBitrate:0,receiveBytes:0,receiveDelay:0,receivePackets:0,receivePacketsLost:0,receiveResolutionHeight:0,receiveResolutionWidth:0,totalDuration:0,totalFreezeTime:0,freezeRate:0,packetLossRate:0,currentPacketLossRate:0,publishDuration:-1};let nt=function(e){return e.ON_TRACK="on_track",e.ON_NODE="on_node",e}({}),at=function(e){return e.REQUEST_UPDATE_CONSTRAINTS="request_update_constraints",e.REQUEST_CONSTRAINTS="request_constraints",e}({}),ct=function(e){return e.IDLE="IDLE",e.INITING="INITING",e.INITEND="INITEND",e}({}),dt=function(e){return e.STATE_CHANGE="state_change",e.RECORDING_DEVICE_CHANGED="recordingDeviceChanged",e.PLAYOUT_DEVICE_CHANGED="playoutDeviceChanged",e.CAMERA_DEVICE_CHANGED="cameraDeviceChanged",e}({});function ut(e){return void 0!==e.smoothnessLevel&&_(e.smoothnessLevel,"options.smoothnessLevel",0,1,!1),void 0!==e.lighteningLevel&&_(e.lighteningLevel,"options.lighteningLevel",0,1,!1),void 0!==e.rednessLevel&&_(e.rednessLevel,"options.rednessLevel",0,1,!1),void 0!==e.lighteningContrastLevel&&v(e.lighteningContrastLevel,"options.lighteningContrastLevel",[0,1,2]),!0}let ht=function(e){return e.NONE="none",e.INIT="init",e.CANPLAY="canplay",e.PLAYING="playing",e.PAUSED="paused",e.SUSPEND="suspend",e.STALLED="stalled",e.WAITING="waiting",e.ERROR="error",e.DESTROYED="destroyed",e.ABORT="abort",e.ENDED="ended",e.EMPTIED="emptied",e.LOADEDDATA="loadeddata",e}({}),lt=function(e){return e[e.VideoStateStopped=0]="VideoStateStopped",e[e.VideoStateStarting=1]="VideoStateStarting",e[e.VideoStateDecoding=2]="VideoStateDecoding",e[e.VideoStateFrozen=3]="VideoStateFrozen",e}({});const pt={uninit:100,none:110,init:120,loadeddata:130,canplay:200,playing:210,paused:220,suspend:300,stalled:310,waiting:320,error:330,destroyed:340,abort:350,ended:360,emptied:370};let mt=function(e){return e.OPEN="open",e.MESSAGE="message",e.CLOSE="close",e.CLOSING="closing",e.ERROR="error",e}({});function gt(e,t,i,r,s){var o={};return Object.keys(r).forEach((function(e){o[e]=r[e]})),o.enumerable=!!o.enumerable,o.configurable=!!o.configurable,("value"in o||o.initializer)&&(o.writable=!0),o=i.slice().reverse().reduce((function(i,r){return r(e,t,i)||i}),o),s&&void 0!==o.initializer&&(o.value=o.initializer?o.initializer.call(s):void 0,o.initializer=void 0),void 0===o.initializer?(Object.defineProperty(e,t,o),null):o}function _t(e,t,i){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var r=i.call(e,t||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function Tt(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,r)}return i}function vt(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Tt(Object(i),!0).forEach((function(t){_t(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Tt(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}class ft extends y{set _mediaStreamTrack(e){e!==this.mediaStreamTrack&&(this.safeEmit(Xe.TRACK_UPDATED,e),this.mediaStreamTrack=e)}get _mediaStreamTrack(){return this.mediaStreamTrack}constructor(e,t){super(),_t(this,"trackMediaType",void 0),_t(this,"_ID",void 0),_t(this,"_rtpTransceiver",void 0),_t(this,"_lowRtpTransceiver",void 0),_t(this,"_hints",[]),_t(this,"_isClosed",!1),_t(this,"_originMediaStreamTrack",void 0),_t(this,"mediaStreamTrack",void 0),_t(this,"_external",{}),this._ID=t||k(8,"track-"),this._originMediaStreamTrack=e,this.mediaStreamTrack=e,Ve(this)}toString(){return this._ID}getTrackId(){return this._ID}getMediaStreamTrack(e){return e||b((()=>{var e;pe.reportApiInvoke(null,{name:I.GET_MEDIA_STREAM_TRACK,options:[],tag:A.TRACER}).onSuccess((null===(e=this._mediaStreamTrack)||void 0===e?void 0:e.label)||"")}),this.mediaStreamTrack.id||this.getTrackId()),this._mediaStreamTrack}getRTCRtpTransceiver(e){return e===Ye.LOW_STREAM?this._lowRtpTransceiver:this._rtpTransceiver}getMediaStreamTrackSettings(){return this.getMediaStreamTrack(!0).getSettings()}close(){this._isClosed=!0,this._lowRtpTransceiver=void 0,this._rtpTransceiver=void 0,xe(this),this.emit(Qe.CLOSED),this.removeAllListeners(Xe.SEI_RECEIVED)}_updateRtpTransceiver(e,t){if(t===Ye.LOW_STREAM){if(this._lowRtpTransceiver===e)return;this._lowRtpTransceiver=e}else{if(this._rtpTransceiver===e)return;this._rtpTransceiver=e}this.emit(Xe.TRANSCEIVER_UPDATED,e,t)}}class Et extends ft{get isExternalTrack(){return this._isExternalTrack}get muted(){return this._muted}get enabled(){return this._enabled}get processorContext(){return this._processorContext}constructor(e,t){super(e,t),_t(this,"_enabled",!0),_t(this,"_muted",!1),_t(this,"_isExternalTrack",!1),_t(this,"_isClosed",!1),_t(this,"_enabledMutex",void 0),_t(this,"processor",void 0),_t(this,"_processorContext",void 0),_t(this,"_handleTrackEnded",(()=>{this.onTrackEnded()})),this._enabledMutex=new R("".concat(this.getTrackId())),e.addEventListener("ended",this._handleTrackEnded)}getTrackLabel(){var e,t;return null!==(e=null===(t=this._originMediaStreamTrack)||void 0===t?void 0:t.label)&&void 0!==e?e:""}close(){this._isClosed||(this.stop(),this._originMediaStreamTrack.stop(),this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack.stop(),this._mediaStreamTrack=null),this._originMediaStreamTrack=null,this._enabledMutex=null,le.debug("[".concat(this.getTrackId(),"] close")),this.emit(He.NEED_CLOSE),super.close())}async _updateOriginMediaStreamTrack(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];this._isExternalTrack=i,e!==this._originMediaStreamTrack&&(this._originMediaStreamTrack&&(this._originMediaStreamTrack.removeEventListener("ended",this._handleTrackEnded),t&&this._originMediaStreamTrack.stop()),e.addEventListener("ended",this._handleTrackEnded),this._originMediaStreamTrack=e,this._muted&&(this._originMediaStreamTrack.enabled=!1),this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await w(this,He.NEED_REPLACE_TRACK,this),this.processor&&this._processorContext&&this.processor.updateInput({track:this._originMediaStreamTrack,context:this._processorContext}))}_getDefaultPlayerConfig(){return{}}onTrackEnded(){le.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(Qe.TRACK_ENDED)}stateCheck(e,t){if(le.debug("check track state, [muted: ".concat(this._muted,", enabled: ").concat(this._enabled,"] to [").concat(e,": ").concat(t,"]")),T(t,e),this._enabled&&this._muted&&"enabled"===e&&!1===t)throw new f(E.TRACK_STATE_UNREACHABLE,"cannot set enabled while the track is muted").print("error",le);if(!this._enabled&&!this._muted&&"muted"===e&&!0===t)throw new f(E.TRACK_STATE_UNREACHABLE,"cannot set muted while the track is disabled").print("error",le)}getProcessorStats(){return this._processorContext&&this._processorContext.gatherStats()||[]}getProcessorUsage(){return this._processorContext?this._processorContext.gatherUsage():Promise.resolve([])}}const St=window.AudioContext||window.webkitAudioContext;let yt=null;const kt=new class extends y{constructor(){super(...arguments),_t(this,"prevState",void 0),_t(this,"curState",void 0),_t(this,"currentTime",void 0),_t(this,"currentTimeStuckAt",void 0),_t(this,"interruptDetectorTrack",void 0),_t(this,"onLocalAudioTrackMute",(()=>{le.info("ios15-interruption-start"),this.emit(ye.IOS_15_16_INTERRUPTION_START)})),_t(this,"onLocalAudioTrackUnmute",(async()=>{le.info("ios15-interruption-end"),"running"!==this.curState||this.duringInterruption?le.info("ios15-interruption-end-canceled"):(yt&&await yt.suspend(),this.emit(ye.IOS_15_16_INTERRUPTION_END))}))}get duringInterruption(){return"running"===this.prevState&&"interrupted"===this.curState}bindInterruptDetectorTrack(e){le.debug("webaudio bindInterruptDetectorTrack ".concat(e.getTrackId())),this.interruptDetectorTrack||(this.interruptDetectorTrack=e,this.interruptDetectorTrack._mediaStreamTrack.onmute=this.onLocalAudioTrackMute,this.interruptDetectorTrack._mediaStreamTrack.onunmute=this.onLocalAudioTrackUnmute)}unbindInterruptDetectorTrack(e){le.debug("webaudio unbindInterruptDetectorTrack ".concat(e.getTrackId())),this.interruptDetectorTrack&&this.interruptDetectorTrack===e&&(this.interruptDetectorTrack._mediaStreamTrack&&(this.interruptDetectorTrack._mediaStreamTrack.onmute=null,this.interruptDetectorTrack._mediaStreamTrack.onunmute=null),this.interruptDetectorTrack=void 0)}};function bt(){if(!St)return void le.error("your browser is not support web audio");le.info("create audio context");const t=vt({},u("WEBAUDIO_INIT_OPTIONS"));le.debug("audio context init option:",JSON.stringify(t)),yt=new St(t),kt.curState=yt.state,yt.onstatechange=()=>{kt.prevState=kt.curState,kt.curState=yt?yt.state:void 0;const{prevState:t,curState:i}=kt,r="running"===i,s="interrupted"===i,o="running"===t,n="suspended"===t,a="interrupted"===t,c=e().osVersion;(C()||M())&&o&&s&&(le.info("ios".concat(c,"-interruption-start")),kt.emit(ye.IOS_INTERRUPTION_START)),(C()||M())&&(n||a)&&r&&(le.info("ios".concat(c,"-interruption-end")),kt.emit(ye.IOS_INTERRUPTION_END)),t!==i&&kt.emit(ye.STATE_CHANGE,i,t)},setInterval((()=>{var e;const t=null===(e=yt)||void 0===e?void 0:e.currentTime;if(kt.currentTime!==t)kt.currentTimeStuckAt&&(le.debug("AudioContext current time resume at ".concat(t)),kt.currentTimeStuckAt=void 0),kt.currentTime=t;else{if(t!==kt.currentTimeStuckAt){pe.reportApiInvoke(null,{name:"WEB_AUDIO_CURRENT_TIME_STUCK",options:{currentTime:t},tag:A.TRACER}).onSuccess(),le.warning("AudioContext current time stuck at ".concat(t))}kt.currentTimeStuckAt=t}}),5e3),async function(e){const t=["click","contextmenu","auxclick","dblclick","mousedown","mouseup","touchend","keydown","keyup"];let i,r=!1,s=!1,o=!1;function n(t){"running"===e.state?a(!1):C()||M()?"suspended"===e.state&&(a(!0),t&&e.resume().then(d,d)):"closed"!==e.state&&(a(!0),t&&e.resume().then(d,d))}function a(e){if(r!==e){r=e;for(let i=0,r=t;i<r.length;i+=1){const t=r[i];e?window.addEventListener(t,u,{capture:!0,passive:!0}):window.removeEventListener(t,u,{capture:!0,passive:!0})}}}function c(){n(!0)}function d(){n(!1)}function u(){n(!0)}function h(e){if(!o)if(i.paused)if(e){let e;l(!1),o=!0;try{e=i.play(),e?e.then(p,p):(i.addEventListener("playing",p),i.addEventListener("abort",p),i.addEventListener("error",p))}catch(e){p()}}else l(!0);else l(!1)}function l(e){if(s!==e){s=e;for(let i=0,r=t;i<r.length;i++){const t=r[i];e?window.addEventListener(t,m,{capture:!0,passive:!0}):window.removeEventListener(t,m,{capture:!0,passive:!0})}}}function p(){i.removeEventListener("playing",p),i.removeEventListener("abort",p),i.removeEventListener("error",p),o=!1,h(!1)}function m(){h(!0)}if(C()){const t=e.createMediaStreamDestination(),r=document.createElement("div");r.innerHTML="<audio x-webkit-airplay='deny'></audio>",i=r.children.item(0),i.controls=!1,i.disableRemotePlayback=!0,i.preload="auto",i.srcObject=t.stream,h(!0)}kt.on(ye.STATE_CHANGE,c),n(!1)}(yt)}function It(){if(!yt){if(bt(),!yt)throw new f(E.NOT_SUPPORTED,"can not create audio context");return yt}return yt}function At(){return!!yt}function Rt(e){if(function(){if(null!==Dt)return Dt;const e=It(),t=e.createBufferSource(),i=e.createGain(),r=e.createGain();t.connect(i),t.connect(r),t.disconnect(i);let s=!1;try{t.disconnect(i)}catch(e){s=!0}return t.disconnect(),Dt=s,s}())return;const t=e.connect,i=e.disconnect;e.connect=(i,r,s)=>(e._inputNodes||(e._inputNodes=[]),e._inputNodes.includes(i)||(i instanceof AudioNode?(e._inputNodes.push(i),t.call(e,i,r,s)):t.call(e,i,r)),e),e.disconnect=(r,s,o)=>{i.call(e),r?D(e._inputNodes,r):e._inputNodes=[];for(const i of e._inputNodes)t.call(e,i)}}function wt(e){const t=It();return new Promise(((i,r)=>{t.decodeAudioData(e,(e=>{i(e)}),(e=>{r(new f(E.DECODE_AUDIO_FILE_FAILED,e.toString()))}))}))}let Dt=null;function Ct(e,t){let i=!1;const r=1/t;if(u("DISABLE_WEBAUDIO")){const t=window.setInterval((()=>{i?window.clearInterval(t):e(performance.now()/1e3)}),1e3*r)}else{const t=It();let s=t.createGain();s.gain.value=0,s.connect(t.destination);const o=()=>{if(i)return void(s=null);const n=t.createOscillator();n.onended=o,n.connect(s),n.start(0),n.stop(t.currentTime+r),e(t.currentTime)};o()}return()=>{i=!0}}let Mt=null;function Nt(){if(Mt)return Mt;const e=It();if(!e.createMediaStreamDestination)throw new f(E.NOT_SUPPORTED,"can not create silence audio track");const t=e.createBufferSource(),i=e.createBuffer(1,44100,44100);t.loop=!0,t.buffer=i;const r=e.createMediaStreamDestination();return t.connect(r),Mt=r.stream.getAudioTracks()[0],Mt}function Ot(e){for(let t=0;t<e.outputBuffer.numberOfChannels;t+=1){const i=e.outputBuffer.getChannelData(t);for(let e=0;e<i.length;e+=1)i[e]=0}return e.inputBuffer}function Lt(e){const t=e.getChannelData(0);let i=0,r=0;for(let e=0;e<t.length;e+=1)0===t[e]?(i+=1,i>r&&(r=i)):i=0;return r/t.length*e.duration}class Pt{constructor(){_t(this,"context",void 0),_t(this,"analyserNode",void 0),_t(this,"sourceNode",void 0),this.context=It(),this.analyserNode=this.context.createAnalyser(),this.analyserNode.fftSize=2048,this.analyserNode.smoothingTimeConstant=.4}updateSource(e){if(e!==this.sourceNode){if(this.sourceNode)try{this.sourceNode.disconnect(this.analyserNode)}catch(e){}this.sourceNode=e,null==e||e.connect(this.analyserNode)}}getVolumeLevel(){if(!this.sourceNode)return 0;if(!this.context||C()||M()||"running"!==this.context.state&&this.context.resume(),!this.analyserNode)return 0;const e=new Float32Array(this.analyserNode.fftSize);if(this.analyserNode.getFloatTimeDomainData)this.analyserNode.getFloatTimeDomainData(e);else{const t=new Uint8Array(this.analyserNode.fftSize);this.analyserNode.getByteTimeDomainData(t);for(let i=0;i<e.length;++i)e[i]=t[i]/128-1}const t=e.reduce(((e,t)=>e+t*t),0)/e.length;return Math.max(10*Math.log10(t)+100,0)/100}getAnalyserNode(){return this.analyserNode}rebuildAnalyser(){try{var e,t;null===(e=this.sourceNode)||void 0===e||e.disconnect(this.analyserNode),this.analyserNode=this.context.createAnalyser(),this.analyserNode.fftSize=2048,this.analyserNode.smoothingTimeConstant=.4,null===(t=this.sourceNode)||void 0===t||t.connect(this.analyserNode)}catch(e){le.warning("rebuild analyser node failed.")}}destroy(){this.updateSource(void 0)}}class Vt extends y{get processSourceNode(){return this.sourceNode}set processedNode(e){var t;if(!this.isDestroyed&&this._processedNode!==e){try{var i;null===(i=this.sourceNode)||void 0===i||i.disconnect(this.outputNode)}catch(e){}null===(t=this._processedNode)||void 0===t||t.disconnect(),this._processedNode=e,this.connect()}}get processedNode(){return this._processedNode}constructor(){super(),_t(this,"outputNode",void 0),_t(this,"outputTrack",void 0),_t(this,"isPlayed",!1),_t(this,"sourceNode",void 0),_t(this,"context",void 0),_t(this,"audioBufferNode",void 0),_t(this,"destNode",void 0),_t(this,"audioOutputLevel",0),_t(this,"volumeLevelAnalyser",void 0),_t(this,"_processedNode",void 0),_t(this,"playNode",void 0),_t(this,"isDestroyed",!1),_t(this,"onNoAudioInput",void 0),_t(this,"isNoAudioInput",!1),_t(this,"_noAudioInputCount",0),this.context=It(),this.playNode=this.context.destination,this.outputNode=this.context.createGain(),Rt(this.outputNode),this.volumeLevelAnalyser=new Pt}startGetAudioBuffer(e){this.audioBufferNode||(this.audioBufferNode=this.context.createScriptProcessor(e),this.outputNode.connect(this.audioBufferNode),this.audioBufferNode.connect(this.context.destination),this.audioBufferNode.onaudioprocess=e=>{this.emit($e.ON_AUDIO_BUFFER,Ot(e))})}stopGetAudioBuffer(){this.audioBufferNode&&(this.audioBufferNode.onaudioprocess=null,this.outputNode.disconnect(this.audioBufferNode),this.audioBufferNode=void 0)}createOutputTrack(){if(!fe().webAudioMediaStreamDest)throw new f(E.NOT_SUPPORTED,"your browser is not support audio processor");return this.destNode&&this.outputTrack||(this.destNode=this.context.createMediaStreamDestination(),this.outputNode.connect(this.destNode),this.outputTrack=this.destNode.stream.getAudioTracks()[0]),this.outputTrack}play(e){"running"!==this.context.state&&r((()=>{kt.emit("autoplay-failed")})),this.isPlayed=!0,this.playNode=e||this.context.destination,this.outputNode.connect(this.playNode)}stop(){if(this.isPlayed)try{this.outputNode.disconnect(this.playNode)}catch(e){}this.isPlayed=!1}getAccurateVolumeLevel(){return this.volumeLevelAnalyser.getVolumeLevel()}async checkHasAudioInput(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;if(e>5)return this.isNoAudioInput=!0,this.onNoAudioInput&&this.onNoAudioInput(),!1;C()||M()?"suspended"===this.context.state&&this.context.resume():"running"!==this.context.state&&this.context.resume();const t=this.volumeLevelAnalyser.getAnalyserNode();let i;t.getFloatTimeDomainData?(i=new Float32Array(t.fftSize),t.getFloatTimeDomainData(i)):(i=new Uint8Array(t.fftSize),t.getByteTimeDomainData(i));let r=!1;for(let e=0;e<i.length;e++)0!==i[e]&&(r=!0);return r?(this.isNoAudioInput=!1,!0):(await N(200),await this.checkHasAudioInput(e?e+1:1)&&r)}getAudioVolume(){return this.outputNode.gain.value}setVolume(e){this.outputNode.gain.setValueAtTime(e,this.context.currentTime)}destroy(){this.disconnect(),this.stop(),this.isDestroyed=!0,this.onNoAudioInput=void 0}disconnect(){var e,t;null===(e=this.processedNode)||void 0===e||e.disconnect(),null===(t=this.sourceNode)||void 0===t||t.disconnect(),this.outputNode&&this.outputNode.disconnect()}connect(){var e;this.processedNode?null===(e=this.processedNode)||void 0===e||e.connect(this.outputNode):this.sourceNode&&this.sourceNode.connect(this.outputNode);this.volumeLevelAnalyser.updateSource(this.outputNode)}}class xt extends Vt{get isFreeze(){return!1}constructor(t,i,r){var s;if(super(),_t(this,"sourceNode",void 0),_t(this,"track",void 0),_t(this,"clonedTrack",void 0),_t(this,"audioElement",void 0),_t(this,"isCurrentTrackCloned",!1),_t(this,"isRemoteTrack",!1),_t(this,"originVolumeLevelAnalyser",void 0),_t(this,"rebuildWebAudio",(async()=>{if(le.debug("ready to rebuild web audio, state:",this.context.state),this.isNoAudioInput&&await this.checkHasAudioInput(),!this.isNoAudioInput||this.isDestroyed)return document.body.removeEventListener("click",this.rebuildWebAudio,!0),void le.debug("rebuild web audio success, current volume status",this.getAccurateVolumeLevel());this.context.resume().then((()=>le.info("resume success"))),le.debug("rebuild web audio because of ios 12 bugs"),this.disconnect();const e=this.track;this.track=this.track.clone(),this.isCurrentTrackCloned?e.stop():this.isCurrentTrackCloned=!0;const t=new MediaStream([this.track]);this.sourceNode=this.context.createMediaStreamSource(t),Rt(this.sourceNode),this.volumeLevelAnalyser.rebuildAnalyser();const i=this.outputNode.gain.value;this.outputNode=this.context.createGain(),this.outputNode.gain.setValueAtTime(i,this.context.currentTime),Rt(this.outputNode),this.emit($e.UPDATE_SOURCE),this.connect(),this.audioElement.srcObject=t,this.isPlayed&&this.play(this.playNode),this.checkHasAudioInput()})),"audio"!==t.kind)throw new f(E.UNEXPECTED_ERROR);this.track=t;const o=new MediaStream([this.track]);if(this.isRemoteTrack=!!i,this.sourceNode=this.context.createMediaStreamSource(o),Rt(this.sourceNode),r){const e=r.clone();e.enabled=!0,this.clonedTrack=e,le.debug("create an unmuted track ".concat(e.id," from the original track ").concat(r.id," to get the volume"));const t=this.context.createMediaStreamSource(new MediaStream([e]));Rt(t),this.originVolumeLevelAnalyser=new Pt,this.originVolumeLevelAnalyser.updateSource(t)}this.connect(),this.audioElement=document.createElement("audio"),this.audioElement.srcObject=o;const n=e();i&&n.os===a.IOS&&Number(null===(s=n.osVersion)||void 0===s?void 0:s.split(".")[0])<15&&(kt.on(ye.STATE_CHANGE,(()=>{"suspended"===this.context.state?document.body.addEventListener("click",this.rebuildWebAudio,!0):"running"===this.context.state&&this.rebuildWebAudio()})),this.checkHasAudioInput().then((e=>{e||document.body.addEventListener("click",this.rebuildWebAudio,!0)})))}updateTrack(e){this.sourceNode.disconnect(),this.track=e,this.isCurrentTrackCloned=!1;const t=new MediaStream([e]);this.sourceNode=this.context.createMediaStreamSource(t),Rt(this.sourceNode),this.processedNode||this.sourceNode.connect(this.outputNode),this.emit($e.UPDATE_SOURCE),this.audioElement.srcObject=t}destroy(){var e;this.audioElement.srcObject=null,this.audioElement.remove(),kt.off("state-change",this.rebuildWebAudio),null===(e=this.originVolumeLevelAnalyser)||void 0===e||e.destroy(),this.clonedTrack=void 0,super.destroy()}createMediaStreamSourceNode(e){return this.context.createMediaStreamSource(new MediaStream([e]))}updateOriginTrack(e){const t=e.clone();t.enabled=!0,this.clonedTrack&&(this.clonedTrack.stop(),this.clonedTrack=t),le.debug("create an unmuted track ".concat(t.id," from the original track ").concat(e.id," to get the volume"));const i=this.context.createMediaStreamSource(new MediaStream([t]));Rt(i),this.originVolumeLevelAnalyser&&this.originVolumeLevelAnalyser.updateSource(i)}getOriginVolumeLevel(){return this.originVolumeLevelAnalyser?this.originVolumeLevelAnalyser.getVolumeLevel():this.getAccurateVolumeLevel()}}async function Ut(e,t,i){const r=(e,t)=>e?"number"!=typeof e?e.max||e.exact||e.ideal||e.min||t:e:t,s={audio:!!i&&{mandatory:{chromeMediaSource:"desktop"}},video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:e,maxHeight:r(t.height,1080),maxWidth:r(t.width,1920)}}};return t.frameRate&&"number"!=typeof t.frameRate?(s.video.mandatory.maxFrameRate=t.frameRate.max,s.video.mandatory.minFrameRate=t.frameRate.min):"number"==typeof t.frameRate&&(s.video.mandatory.maxFrameRate=t.frameRate),await navigator.mediaDevices.getUserMedia(s)}async function Bt(e,t){const i=await Ft(e.mediaSource),{sourceId:r,audio:s}=await O(i,t);return await Ut(r,e,s)}async function Ft(e){let t=["window","screen"];"application"!==e&&"window"!==e||(t=["window"]),"screen"===e&&(t=["screen"]);const i=L();if(!i)throw console.error("failed to fetch electron, please mount it to window"),new f(E.ELECTRON_IS_NULL);let r=null;try{var s;r=(null===(s=i.desktopCapturer)||void 0===s?void 0:s.getSources({types:t}))||i.ipcRenderer.invoke("DESKTOP_CAPTURER_GET_SOURCES",{types:t})}catch(e){r=null}r&&r.then||(r=new Promise(((e,r)=>{i.desktopCapturer.getSources({types:t},((t,i)=>{t?r(t):e(i)}))})));try{return await r}catch(e){throw new f(E.ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR,e.toString())}}const Gt=new R("safari");let Wt=!1,Ht=!1;async function Kt(e,t){let i=0,r=null;for(;i<2;)try{r=await Zt(e,t,i>0);break}catch(e){if(e instanceof f)throw le.error("[".concat(t,"] ").concat(e.toString())),e;const r=Yt(e.name||e.code||e,e.message);if(r.code===E.MEDIA_OPTION_INVALID){le.debug("[".concat(t,"] detect media option invalid, retry")),i+=1,await N(500);continue}throw le.error("[".concat(t,"] ").concat(r.toString())),r}if(!r)throw new f(E.UNEXPECTED_ERROR,"can not find stream after getUserMedia");return r}async function Zt(t,i,r){if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)throw new f(E.NOT_SUPPORTED,"can not find getUserMedia");r&&(t.video&&(delete t.video.width,delete t.video.height),t.screen&&(delete t.screen.width,delete t.screen.height));const s=fe(),o=new MediaStream;if(t.audioSource&&o.addTrack(t.audioSource),t.videoSource&&o.addTrack(t.videoSource),!t.audio&&!t.video&&!t.screen)return le.debug("Using Video Source/ Audio Source"),o;if(t.screen)if(P())if(t.screen.sourceId){zt(o,await Ut(t.screen.sourceId,t.screen,!!t.screenAudio))}else{zt(o,await Bt(t.screen,!!t.screenAudio))}else if(l()&&t.screen.extensionId&&t.screen.mandatory){if(!s.getStreamFromExtension)throw new f(E.NOT_SUPPORTED,"This browser does not support screen sharing");le.debug("[".concat(i,'] Screen access on chrome stable, looking for extension"'));const e=await(a=t.screen.extensionId,p=i,new Promise(((e,t)=>{try{chrome.runtime.sendMessage(a,{getStream:!0},(i=>{if(!i||!i.streamId)return le.error("[".concat(p,"] No response from Chrome Plugin. Plugin not installed properly"),i),void t(new f(E.CHROME_PLUGIN_NO_RESPONSE,"No response from Chrome Plugin. Plugin not installed properly"));e(i.streamId)}))}catch(e){le.error("[".concat(p,"] AgoraRTC screensharing plugin is not accessible(").concat(a,")"),e.toString()),t(new f(E.CHROME_PLUGIN_NOT_INSTALL))}})));t.screen.mandatory.chromeMediaSourceId=e;zt(o,await navigator.mediaDevices.getUserMedia({video:{mandatory:t.screen.mandatory}}))}else if(s.getDisplayMedia){var n;t.screen.mediaSource&&We(t.screen.mediaSource);const e={width:t.screen.width,height:t.screen.height,frameRate:t.screen.frameRate,displaySurface:null!==(n=t.screen.displaySurface)&&void 0!==n?n:"screen"===t.screen.mediaSource?"monitor":t.screen.mediaSource},{selfBrowserSurface:r,surfaceSwitching:s,systemAudio:a,preferCurrentTab:c}=t.screen,d={selfBrowserSurface:r,surfaceSwitching:s,systemAudio:a,preferCurrentTab:c};!r&&delete d.selfBrowserSurface,!s&&delete d.surfaceSwitching,!a&&delete d.systemAudio,!c&&delete d.preferCurrentTab,le.debug("[".concat(i,"] getDisplayMedia:"),JSON.stringify({video:e,audio:t.screenAudio,controls:d}));zt(o,await navigator.mediaDevices.getDisplayMedia(vt({video:e,audio:t.screenAudio},d)))}else{if(!h())throw le.error("[".concat(i,"] This browser does not support screenSharing")),new f(E.NOT_SUPPORTED,"This browser does not support screen sharing");{t.screen.mediaSource&&We(t.screen.mediaSource);const e={video:{mediaSource:t.screen.mediaSource,width:t.screen.width,height:t.screen.height,frameRate:t.screen.frameRate}};le.debug("[".concat(i,"] getUserMedia: ").concat(JSON.stringify(e)));zt(o,await navigator.mediaDevices.getUserMedia(e))}}var a,p;if(!t.video&&!t.audio)return o;let m={video:t.video,audio:t.audio},g=u("MEDIA_DEVICE_CONSTRAINTS");if(g)try{"string"==typeof g&&(g=JSON.parse(g)),m=V(m,g)}catch(e){}le.debug("[".concat(i,"] GetUserMedia"),JSON.stringify(m)),e();let _,T=null;(c()||C()||d())&&(T=await Gt.lock());try{_=await navigator.mediaDevices.getUserMedia(m)}catch(e){throw T&&T(),e}return m.audio&&(Wt=!0),m.video&&(Ht=!0),zt(o,_),T&&T(),o}function Yt(e,t){switch(e){case"Starting video failed":case"OverconstrainedError":case"TrackStartError":return new f(E.MEDIA_OPTION_INVALID,"".concat(e,": ").concat(t));case"NotFoundError":case"DevicesNotFoundError":return new f(E.DEVICE_NOT_FOUND,"".concat(e,": ").concat(t));case"NotSupportedError":return new f(E.NOT_SUPPORTED,"".concat(e,": ").concat(t));case"NotReadableError":return new f(E.NOT_READABLE,"".concat(e,": ").concat(t));case"InvalidStateError":case"NotAllowedError":case"PERMISSION_DENIED":case"PermissionDeniedError":return new f(E.PERMISSION_DENIED,"".concat(e,": ").concat(t));case"ConstraintNotSatisfiedError":return new f(E.CONSTRAINT_NOT_SATISFIED,"".concat(e,": ").concat(t));default:return le.error("getUserMedia unexpected error",e),new f(E.UNEXPECTED_ERROR,"".concat(e,": ").concat(t))}}function zt(e,t){const i=e.getVideoTracks()[0],r=e.getAudioTracks()[0],s=t.getVideoTracks()[0],o=t.getAudioTracks()[0];o&&(r&&e.removeTrack(r),e.addTrack(o)),s&&(i&&e.removeTrack(i),e.addTrack(s))}class jt extends y{get state(){return this._state}set state(e){e!==this._state&&(this.emit(dt.STATE_CHANGE,e),this._state=e)}constructor(){super(),_t(this,"_state",ct.IDLE),_t(this,"isAccessMicrophonePermission",!1),_t(this,"isAccessCameraPermission",!1),_t(this,"lastAccessMicrophonePermission",!1),_t(this,"lastAccessCameraPermission",!1),_t(this,"checkdeviceMatched",!1),_t(this,"deviceInfoMap",new Map),this.init().then((()=>{navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",this.updateDevicesInfo.bind(this)),window.setInterval((()=>{(u("ENUMERATE_DEVICES_INTERVAL")||(x()||U())&&i())&&this.updateDevicesInfo()}),u("ENUMERATE_DEVICES_INTERVAL_TIME"))})).catch((e=>le.error(e.toString())))}async enumerateDevices(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices){return new f(E.NOT_SUPPORTED,"enumerateDevices() not supported.").throw()}const r=await navigator.mediaDevices.enumerateDevices(),s=this.checkMediaDeviceInfoIsOk(r);let o=!this.isAccessMicrophonePermission&&e,n=!this.isAccessCameraPermission&&t;s.audio&&(o=!1),s.video&&(n=!1);let a=null,c=null,d=null;if(!i&&(o||n)){if(Gt.isLocked){le.debug("[device manager] wait GUM lock");(await Gt.lock())(),le.debug("[device manager] GUM unlock")}if(Wt&&(o=!1,this.isAccessMicrophonePermission=!0),Ht&&(n=!1,this.isAccessCameraPermission=!0),le.debug("[device manager] check media device permissions",e,t,o,n),o&&n){try{d=await navigator.mediaDevices.getUserMedia({audio:!0,video:!0})}catch(e){const t=Yt(e.name||e.code||e,e.message);if(t.code===E.PERMISSION_DENIED)throw t;le.warning("getUserMedia failed in getDevices",t)}this.isAccessCameraPermission=!0,this.isAccessMicrophonePermission=!0}else if(o){try{a=await navigator.mediaDevices.getUserMedia({audio:e})}catch(e){const t=Yt(e.name||e.code||e,e.message);if(t.code===E.PERMISSION_DENIED)throw t;le.warning("getUserMedia failed in getDevices",t)}this.isAccessMicrophonePermission=!0}else if(n){try{c=await navigator.mediaDevices.getUserMedia({video:t})}catch(e){const t=Yt(e.name||e.code||e,e.message);if(t.code===E.PERMISSION_DENIED)throw t;le.warning("getUserMedia failed in getDevices",t)}this.isAccessCameraPermission=!0}le.debug("[device manager] mic permission",e,"cam permission",t)}try{const e=await navigator.mediaDevices.enumerateDevices();return a&&a.getTracks().forEach((e=>e.stop())),c&&c.getTracks().forEach((e=>e.stop())),d&&d.getTracks().forEach((e=>e.stop())),a=null,c=null,d=null,e}catch(e){a&&a.getTracks().forEach((e=>e.stop())),c&&c.getTracks().forEach((e=>e.stop())),d&&d.getTracks().forEach((e=>e.stop())),a=null,c=null,d=null;return new f(E.ENUMERATE_DEVICES_FAILED,e.toString()).throw()}}async getRecordingDevices(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return(await this.enumerateDevices(!0,!1,e)).filter((e=>"audioinput"===e.kind))}async getCamerasDevices(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return(await this.enumerateDevices(!1,!0,e)).filter((e=>"videoinput"===e.kind))}async getSpeakers(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return(await this.enumerateDevices(!0,!1,e)).filter((e=>"audiooutput"===e.kind))}searchDeviceIdByName(e){let t=null;return this.deviceInfoMap.forEach((i=>{i.device.label===e&&(t=i.device.deviceId)})),t}async getDeviceById(e){const t=(await this.enumerateDevices(!0,!0,!0)).find((t=>t.deviceId===e));if(!t)throw new f(E.DEVICE_NOT_FOUND,"deviceId: ".concat(e));return t}async init(){this.state=ct.INITING;try{await this.updateDevicesInfo(),this.state=ct.INITEND}catch(e){if(le.warning("Device Detection functionality cannot start properly.",e.toString()),this.state=ct.IDLE,!B()){new f(E.WEB_SECURITY_RESTRICT,"Your context is limited by web security, please try using https protocol or localhost.").throw()}throw e}}async updateDevicesInfo(){const e=await this.enumerateDevices(!0,!0,!0),t=Date.now(),i=[];if(e[0]&&e[0].label&&!1===this.checkdeviceMatched){this.checkdeviceMatched=!0;const t=e.find((e=>"audioinput"===e.kind&&"default"===e.deviceId)),i=e.find((e=>"audiooutput"===e.kind&&"default"===e.deviceId));t&&i?i.groupId===t.groupId?le.debug("[device-check] default input ".concat(t.label," and output ").concat(i.label," is the same group")):le.debug("[device-check] default input ".concat(t.label," and output ").concat(i.label," is not the same group")):le.debug("[device-check] default input or output not found")}const r=this.checkMediaDeviceInfoIsOk(e);if(e.forEach((e=>{if(!e.deviceId)return;const r=this.deviceInfoMap.get("".concat(e.kind,"_").concat(e.deviceId));if("ACTIVE"!==(r?r.state:"INACTIVE")){const r={initAt:t,updateAt:t,device:e,state:"ACTIVE"};this.deviceInfoMap.set("".concat(e.kind,"_").concat(e.deviceId),r),i.push(r)}r&&(r.updateAt=t)})),this.deviceInfoMap.forEach(((e,r)=>{"ACTIVE"===e.state&&e.updateAt!==t&&(e.state="INACTIVE",i.push(e))})),this.state!==ct.INITEND)return r.audio&&(this.lastAccessMicrophonePermission=!0,this.isAccessMicrophonePermission=!0),void(r.video&&(this.lastAccessCameraPermission=!0,this.isAccessCameraPermission=!0));i.forEach((e=>{switch(e.device.kind){case"audioinput":this.lastAccessMicrophonePermission&&this.isAccessMicrophonePermission&&this.emit(dt.RECORDING_DEVICE_CHANGED,e);break;case"videoinput":this.lastAccessCameraPermission&&this.isAccessCameraPermission&&this.emit(dt.CAMERA_DEVICE_CHANGED,e);break;case"audiooutput":this.lastAccessMicrophonePermission&&this.isAccessMicrophonePermission&&this.emit(dt.PLAYOUT_DEVICE_CHANGED,e)}})),r.audio&&(this.lastAccessMicrophonePermission=!0,this.isAccessMicrophonePermission=!0),r.video&&(this.lastAccessCameraPermission=!0,this.isAccessCameraPermission=!0)}checkMediaDeviceInfoIsOk(e){const t=e.filter((e=>"audioinput"===e.kind)),i=e.filter((e=>"videoinput"===e.kind)),r={audio:!1,video:!1};for(const e of t)if(e.label&&e.deviceId){r.audio=!0;break}for(const e of i)if(e.label&&e.deviceId){r.video=!0;break}return r}}const Xt=new jt;let Qt=!1;const Jt=new class extends y{constructor(){super(...arguments),_t(this,"onAutoplayFailed",void 0),_t(this,"onAudioAutoplayFailed",void 0)}};function qt(){if(e(),!Qt){const e=t=>{t.preventDefault(),Qt=!1,F()?document.body.removeEventListener("click",e,!0):(document.body.removeEventListener("touchstart",e,!0),document.body.removeEventListener("mousedown",e,!0))};Qt=!0,F()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0)),le.info("detect media autoplay failed, document: https://docs.agora.io/cn/Voice/autoplay_policy_web_ng?platform=Web"),Jt.onAutoplayFailed?Jt.onAutoplayFailed():Jt.onAudioAutoplayFailed?le.warning("AgoraRTC.onAudioAutoplayFailed has been deprecated in favor of AgoraRTC.onAutoplayFailed.\n\n Please refer to the Agora document to migrate the newer API, https://docs.agora.io/en/Voice/autoplay_policy_web_ng?platform=Web ."):le.warning("We have detected a media autoplay failed event, and found out that you haven't implemented AgoraRTC.onAutoplayFailed callback yet.\n\n It will cause audio/video element not playing automatically on some browsers without user interaction, possibly hurting user experiences.\n\n Please refer to the Agora document to properly handle autoplay failed event, https://docs.agora.io/en/Voice/autoplay_policy_web_ng?platform=Web ."),Jt.emit("autoplay-failed")}}function $t(e,t,i,r){if(!e)return;const s=pe.getBaseInfoBySessionId(e);if(!s)return;const o=s.info,n=Date.now(),a=vt(vt({},o),{},{vid:void 0===o.vid?0:Number(o.vid),lts:n,elapse:n-s.startTime,cbRegistered:Jt.onAutoplayFailed||Jt.onAudioAutoplayFailed?1:-1,errorMsg:i,mediaType:t,trackId:r,extend:void 0});pe.send({type:me.AUTOPLAY_FAILED,data:a},!0)}const ei=["play","playing","loadeddata","canplay","pause","stalled","suspend","waiting","abort","emptied","ended","error"],ti=new class{constructor(){_t(this,"onAutoplayFailed",void 0),_t(this,"elementMap",new Map),_t(this,"elementStateMap",new Map),_t(this,"elementsNeedToResume",[]),_t(this,"sinkIdMap",new Map),_t(this,"autoResumeAfterInterruption",(e=>{Array.from(this.elementMap.entries()).forEach((t=>{let[i,r]=t;const s=this.elementStateMap.get(i),o=r.srcObject.getAudioTracks()[0],n=o&&o.readyState;if(le.debug("resume after interrupted, ele: ".concat(s," audio: ").concat(n," ").concat(e)),"live"===n){if(e)return r.pause(),void r.play();if("running"===kt.curState)return W()?(r.pause(),void r.play()):void(s&&"paused"===s&&r.play())}}))})),_t(this,"autoResumeAfterInterruptionOnIOS15_16",(()=>{Array.from(this.elementMap.entries()).forEach((e=>{let[t,i]=e;const r=i.srcObject.getAudioTracks()[0];r&&"live"===r.readyState&&(le.debug("auto resume after interruption inside autoResumeAfterInterruptionOnIOS15"),i.pause(),i.play())}))})),this.autoResumeAudioElement(),kt.on(ye.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),kt.on(ye.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16),kt.on(ye.STATE_CHANGE,(()=>{C()&&"suspended"===kt.prevState&&"running"===kt.curState&&this.autoResumeAfterInterruption()}))}async setSinkID(e,t){const i=this.elementMap.get(e);if(this.sinkIdMap.set(e,t),i)try{await i.setSinkId(t)}catch(e){throw new f(E.PERMISSION_DENIED,"can not set sink id: "+e.toString())}}play(e,t,i,s){if(this.elementMap.has(t))return;const o=document.createElement("audio");o.autoplay=!0,o.srcObject=new MediaStream([e]),this.bindAudioElementEvents(t,o),this.elementMap.set(t,o),this.elementStateMap.set(t,ht.INIT),this.setVolume(t,i);const n=this.sinkIdMap.get(t);if(n)try{o.setSinkId(n).catch((e=>{le.warning("[".concat(t,"] set sink id failed"),e.toString())}))}catch(e){le.warning("[".concat(t,"] set sink id failed"),e.toString())}const a=o.play();a&&a.then&&a.catch((e=>{s&&$t(s,"audio",e.message,t),le.warning("audio element play warning",e.toString()),this.elementMap.has(t)&&"NotAllowedError"===e.name&&(le.warning("detected audio element autoplay failed"),this.elementsNeedToResume.push(o),r((()=>{this.onAutoplayFailed&&this.onAutoplayFailed(),qt()})))}))}updateTrack(e,t){const i=this.elementMap.get(e);i&&(i.srcObject=new MediaStream([t]))}isPlaying(e){return this.elementMap.has(e)&&"playing"===this.elementStateMap.get(e)}setVolume(e,t){const i=this.elementMap.get(e);i&&(t=Math.max(0,Math.min(100,t)),i.volume=t/100)}stop(e){const t=this.elementMap.get(e);if(this.sinkIdMap.delete(e),!t)return;const i=this.elementsNeedToResume.indexOf(t);this.elementsNeedToResume.splice(i,1),t.srcObject=null,t.remove(),this.elementMap.delete(e),this.elementStateMap.delete(e)}bindAudioElementEvents(e,t){ei.forEach((i=>{t.addEventListener(i,(i=>{const r=this.elementStateMap.get(e),s="pause"===i.type?"paused":i.type;if(le.debug("[".concat(e,"] audio-element-status change ").concat(r," => ").concat(s)),"error"===i.type){const i=null==t?void 0:t.error;i&&le.error("[".concat(e,"] media error, code: ").concat(i.code,", message: ").concat(i.message))}this.elementStateMap.set(e,s)}))}))}getPlayerState(e){return this.elementStateMap.get(e)||"uninit"}autoResumeAudioElement(){const e=()=>{this.elementsNeedToResume.forEach((e=>{e.play().then((e=>{le.debug("Auto resume audio element success")})).catch((e=>{le.warning("Auto resume audio element failed!",e)}))})),this.elementsNeedToResume=[]};G().then((()=>{F()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0))}))}};function ii(){return function(e,t,i){const r=i.value;return"function"==typeof r&&(i.value=function(){this._isClosed&&new f(E.INVALID_OPERATION,"[".concat(this.getTrackId(),"] cannot operate a closed track")).print("warning",le);for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];const s=r.apply(this,t);return s instanceof Promise?new Promise(((e,t)=>{s.then(e).catch(t)})):s}),i}}class ri extends y{constructor(e){super(),_t(this,"name","VideoProcessorDestination"),_t(this,"ID","0"),_t(this,"_source",void 0),_t(this,"videoContext",void 0),_t(this,"inputTrack",void 0),this.videoContext=e}get kind(){return"video"}get enabled(){return!0}pipe(){throw new f(E.NOT_SUPPORTED,"VideoProcessor cannot pipe to any other Processor")}unpipe(){throw new f(E.NOT_SUPPORTED,"VideoProcessor cannot unpipe to any other Processor")}enable(){}disable(){}updateInput(e){if(e.context!==this.videoContext)throw new Error("ProcessorContext passed to VideoTrack.processorDestination doesn't match it's belonging VideoTrack's context.\nProbably you are making pipeline like this:\nvideoTrack1.pipe(processor).pipe(videoTrack2.processorDestination).");e.track&&e.track!==this.inputTrack&&(this.videoContext.chained=!0,this.inputTrack=e.track,this.emit(nt.ON_TRACK,e.track))}reset(){this.inputTrack=void 0,this.videoContext.chained=!1,this.emit(nt.ON_TRACK,void 0)}}class si extends y{set chained(e){this._chained=e}get chained(){return this._chained}constructor(e,t){super(),_t(this,"constraintsMap",new Map),_t(this,"statsRegistry",[]),_t(this,"usageRegistry",[]),_t(this,"trackId",void 0),_t(this,"direction",void 0),_t(this,"_chained",!1),this.trackId=e,this.direction=t}async getConstraints(){return await H(this,at.REQUEST_CONSTRAINTS)}async requestApplyConstraints(e,t){return le.info("processor ".concat(t.name," requestApplyConstraints for ").concat(this.trackId)),e&&this.constraintsMap.set(t,e),w(this,at.REQUEST_UPDATE_CONSTRAINTS,Array.from(this.constraintsMap.values()))}async requestRevertConstraints(e){if(this.constraintsMap.has(e))return le.info("processor ".concat(e.name," requestRevertConstraints for ").concat(this.trackId)),this.constraintsMap.delete(e),w(this,at.REQUEST_UPDATE_CONSTRAINTS,Array.from(this.constraintsMap.values()))}registerStats(e,t,i){this.statsRegistry.find((i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t))||this.statsRegistry.push({processorName:e.name,processorID:e.ID,type:t,cb:i})}unregisterStats(e,t){const i=this.statsRegistry.findIndex((i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t));-1!==i&&this.statsRegistry.splice(i,1)}gatherStats(){const e=[];for(const{processorID:t,processorName:i,type:r,cb:s}of this.statsRegistry)try{const o=s();e.push({processorID:t,processorName:i,type:r,stats:o})}catch(e){le.error(new f(E.UNEXPECTED_ERROR,e.message))}return e}registerUsage(e,t){this.usageRegistry.find((t=>t.processorID===e.ID&&t.processorName===e.name))||this.usageRegistry.push({processorID:e.ID,processorName:e.name,cb:t})}unregisterUsage(e){const t=this.usageRegistry.findIndex((t=>t.processorID===e.ID&&t.processorName===e.name));-1!==t&&this.usageRegistry.splice(t,1)}async gatherUsage(){const e=[];if(!this.chained)return[];for(const{cb:t}of this.usageRegistry)try{let i=t();i instanceof Promise&&(i=await i),e.push(vt(vt({},i),{},{direction:this.direction}))}catch(e){le.error("gather extension usage error",e)}return e}getDirection(){return this.direction}}class oi extends y{constructor(e){super(),_t(this,"name","AudioProcessorDestination"),_t(this,"ID","0"),_t(this,"inputTrack",void 0),_t(this,"inputNode",void 0),_t(this,"audioProcessorContext",void 0),_t(this,"_source",void 0),this.audioProcessorContext=e}get kind(){return"audio"}get enabled(){return!0}pipe(){throw new f(E.NOT_SUPPORTED,"AudioProcessorDestination cannot pipe to any other Processor")}unpipe(){throw new f(E.NOT_SUPPORTED,"AudioProcessor cannot unpipe to any other Processor")}enable(){}disable(){}reset(){this.inputTrack=void 0,this.inputNode=void 0,this.audioProcessorContext.chained=!1,this.emit(nt.ON_TRACK,void 0),this.emit(nt.ON_NODE,void 0)}updateInput(e){if(e.context!==this.audioProcessorContext)throw new Error("ProcessorContext passed to AudioTrack.processorDestination doesn't match it's belonging AudioTrack's context.\n Probably you are making pipeline like this: audioTrack1.pipe(processor).pipe(audioTrack2.processorDestination).");e.track&&this.inputTrack!==e.track&&(this.audioProcessorContext.chained=!0,this.inputTrack=e.track,this.emit(nt.ON_TRACK,this.inputTrack)),e.node&&this.inputNode!==e.node&&(this.audioProcessorContext.chained=!0,this.inputNode=e.node,this.emit(nt.ON_NODE,this.inputNode))}}class ni extends y{set chained(e){this._chained=e}get chained(){return this._chained}constructor(e,t,i){super(),_t(this,"constraintsMap",new Map),_t(this,"statsRegistry",[]),_t(this,"audioContext",void 0),_t(this,"trackId",void 0),_t(this,"direction",void 0),_t(this,"usageRegistry",[]),_t(this,"_chained",!1),this.audioContext=e,this.trackId=t,this.direction=i}async getConstraints(){return H(this,at.REQUEST_CONSTRAINTS)}getAudioContext(){return this.audioContext}async requestApplyConstraints(e,t){return le.info("processor ".concat(t.name," requestApplyConstraints for ").concat(this.trackId)),e&&this.constraintsMap.set(t,e),w(this,at.REQUEST_UPDATE_CONSTRAINTS,Array.from(this.constraintsMap.values()))}async requestRevertConstraints(e){if(this.constraintsMap.has(e))return this.constraintsMap.delete(e),w(this,at.REQUEST_UPDATE_CONSTRAINTS,Array.from(this.constraintsMap.values()))}registerStats(e,t,i){this.statsRegistry.find((i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t))||this.statsRegistry.push({processorName:e.name,processorID:e.ID,type:t,cb:i})}unregisterStats(e,t){const i=this.statsRegistry.findIndex((i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t));-1!==i&&this.statsRegistry.splice(i,1)}gatherStats(){const e=[];for(const{processorID:t,processorName:i,type:r,cb:s}of this.statsRegistry)try{const o=s();e.push({processorID:t,processorName:i,type:r,stats:o})}catch(e){le.error(new f(E.UNEXPECTED_ERROR,e.message))}return e}registerUsage(e,t){this.usageRegistry.find((t=>t.processorID===e.ID&&t.processorName===e.name))||this.usageRegistry.push({processorID:e.ID,processorName:e.name,cb:t})}unregisterUsage(e){const t=this.usageRegistry.findIndex((t=>t.processorID===e.ID&&t.processorName===e.name));-1!==t&&this.usageRegistry.splice(t,1)}async gatherUsage(){const e=[];if(!this.chained)return[];for(const{cb:t}of this.usageRegistry)try{let i=t();i instanceof Promise&&(i=await i),e.push(vt(vt({},i),{},{direction:this.direction}))}catch(e){le.error("gather extension usage error",e)}return e}getDirection(){return this.direction}}class ai extends y{get isPlayed(){return!0}get isFreeze(){return!1}constructor(){super(),_t(this,"context",void 0),_t(this,"processSourceNode",void 0),_t(this,"outputTrack",void 0),_t(this,"processedNode",void 0),_t(this,"clonedTrack",void 0),_t(this,"outputNode",void 0),this.outputNode=new ci}setVolume(){}createOutputTrack(){throw new f(E.NOT_SUPPORTED,"can not create output MediaStreamTrack when WebAudio disabled")}getOriginVolumeLevel(){return 0}getAccurateVolumeLevel(){return 0}stopGetAudioBuffer(){}startGetAudioBuffer(){}play(){}stop(){}destroy(){}updateTrack(){}updateOriginTrack(){}createMediaStreamSourceNode(){}}class ci{disconnect(){}connect(){}}function di(e){return new Promise(((t,i)=>{let r=!1;const s=document.createElement("video");s.setAttribute("autoplay",""),s.setAttribute("muted",""),s.muted=!0,s.autoplay=!0,s.setAttribute("playsinline",""),s.setAttribute("style","position: fixed; top: 0; left: 0; width: 1px; height: 1px"),document.body.appendChild(s);const o=C()?"canplay":"playing";s.addEventListener(o,(()=>{const e=s.videoWidth,i=s.videoHeight;!e&&h()||(r=!0,s.srcObject=null,s.remove(),t([e,i]))})),s.srcObject=new MediaStream([e]),s.play().catch(K),setTimeout((()=>{r||(s.srcObject=null,s.remove(),t([s.videoWidth,s.videoHeight]))}),4e3)}))}function ui(e){const t={};e.facingMode&&(t.facingMode=e.facingMode),e.cameraId&&(t.deviceId={exact:e.cameraId});const i=Ce(e.encoderConfig);return null!=i.width&&(t.width=i.width),null!=i.height&&(t.height=i.height),!Z()&&i.frameRate&&(t.frameRate=i.frameRate),p()&&"object"==typeof t.frameRate&&(t.frameRate.max=60),h()&&(t.frameRate={ideal:30,max:30}),t}function hi(e){const t={};e.screenSourceType&&(t.mediaSource=e.screenSourceType),e.extensionId&&l()&&(t.extensionId=e.extensionId);const{displaySurface:i,selfBrowserSurface:r,surfaceSwitching:o,systemAudio:n,preferCurrentTab:a}=e;(s(107)||Y(107)||z(93))&&(i&&(v(i,"displaySurface",["browser","window","monitor"]),t.displaySurface=i),r?(v(r,"selfBrowserSurface",["exclude","include"]),t.selfBrowserSurface=r):t.selfBrowserSurface="include",o&&(v(o,"surfaceSwitching",["exclude","include"]),t.surfaceSwitching=o)),(s(105)||Y(105)||z(91))&&n&&(v(n,"systemAudio",["exclude","include"]),t.systemAudio=n),(s(94)||Y(94)||z(80))&&a&&(t.preferCurrentTab=!0),e.electronScreenSourceId&&(t.sourceId=e.electronScreenSourceId);const c=e.encoderConfig?Me(e.encoderConfig):null;return t.mandatory={chromeMediaSource:"desktop",maxWidth:c?c.width:void 0,maxHeight:c?c.height:void 0},c&&(c.frameRate&&("number"==typeof c.frameRate?(t.mandatory.maxFrameRate=c.frameRate,t.mandatory.minFrameRate=c.frameRate):(t.mandatory.maxFrameRate=c.frameRate.max||c.frameRate.ideal||c.frameRate.exact||void 0,t.mandatory.minFrameRate=c.frameRate.min||c.frameRate.ideal||c.frameRate.exact||void 0),t.frameRate=c.frameRate),c.width&&(t.width=c.width),c.height&&(t.height=c.height)),t}function li(e){const t={};return Z()||(void 0!==e.AGC&&(t.autoGainControl=e.AGC),void 0!==e.AEC&&(t.echoCancellation=e.AEC),void 0!==e.ANS&&(t.noiseSuppression=e.ANS,l()&&e.ANS&&(t.googHighpassFilter=e.ANS))),t}function pi(e){return li(e)}function mi(e){const t=li(e);if(e.encoderConfig){const i=Le(e.encoderConfig);t.channelCount=i.stereo?2:1,t.sampleRate=i.sampleRate,t.sampleSize=i.sampleSize}return e.microphoneId&&(t.deviceId={exact:e.microphoneId}),x()&&(t.sampleRate=void 0),t}function gi(e,t,i){const r=4*Math.floor(2e5*Math.pow(i/15,.6)*Math.pow(e*t/230400,.75)),s=e*t,o=new Map([[19200,.9],[230400,.85],[518400,.75],[921600,.7],[2073600,.6],[3686400,.5]]),n=new Map([[230400,.95],[518400,.9],[921600,.85],[2073600,.8]]);let a=o.values().next().value,c=1;if(o.has(s))a=o.get(s);else{const e=Array.from(o.entries()).sort(((e,t)=>{let[i]=e,[r]=t;return i-r})),t=e.find((e=>{let[t]=e;return t>s}));if(t){const i=e.indexOf(t);if(i>0){const r=e[i-1],o=(s-r[0])/(t[0]-r[0]);a=r[1]+o*(t[1]-r[1])}else a=t[1]}else a=e[e.length-1][1]}if(n.has(s))c=n.get(s);else{const e=Array.from(n.entries()).sort(((e,t)=>{let[i]=e,[r]=t;return i-r})),t=e.find((e=>{let[t]=e;return t>s}));if(t){const i=e.indexOf(t);if(i>0){const r=e[i-1],o=(s-r[0])/(t[0]-r[0]);c=r[1]+o*(t[1]-r[1])}else c=t[1]}else c=e[e.length-1][1]}const d=u("VIDEO_NEW_BITRATE_RATIO");d&&d>0&&(a=d/100);const h=Math.floor(r*a),l=Math.floor(65e4*Math.pow(e*t/230400,.5)*Math.pow(i/15,.69));let p=h;const m=u("VIDEO_STANDARD_BITRATE_VERSION");return m&&m>0&&(1===m?p=r:2===m?p=h:3===m&&(p=l)),[Math.floor(p/1e3),c]}function _i(e,t,i,r,s){const o=u("BITRATE_ADAPTER_TYPE");if("DEFAULT_BITRATE"===o)return{min:r,max:s};if(void 0===s){const n=Math.floor(200*Math.pow(i/15,.6)*Math.pow(e*t/640/360,.75));s="STANDARD_BITRATE"===o?4*n:2*n,r=null!=r?r:n}else r=null!=r?r:Math.floor(s/10);return{min:r,max:s}}function Ti(e,t,i){const r=200*Math.pow(i/15,.6)*Math.pow(e*t/640/360,.75);return{min:Math.floor(r),max:Math.floor(4*r)}}const vi=e=>{const t=e._encoderConfig;if(!t)return;const{frameRate:i,width:r,height:s}=e.getMediaStreamTrackSettings();let{frameRate:o=i,width:n=r,height:a=s}=t;if(!o||!n||!a)return;n=j(n),a=j(a),o=j(o);const{max:c,min:d}=Ti(n,a,o),{bitrateMax:h,bitrateMin:l}=t||{};h||le.debug("calculate bitrate: [w: ".concat(n,", h: ").concat(a,", fps: ").concat(o,"] => [brMax: ").concat(h,", brMin: ").concat(l,"]"));const{maxFramerate:p}=u("ENCODER_CONFIG_LIMIT");return p&&"number"==typeof p&&(o=Math.min(o,p)),{frameRate:o,bitrateMax:h||c,bitrateMin:l||d,scaleResolutionDownBy:1,scale:0}},fi=async(e,t,i)=>await(async(e,t,i)=>{const r=X(Q(""+t+i)).slice(0,16),s=r.slice(0,12),o=await window.crypto.subtle.importKey("raw",r,"AES-GCM",!0,["encrypt"]);return new Uint8Array(await window.crypto.subtle.encrypt({name:"AES-GCM",iv:s},o,e))})(e.buffer,t,i),Ei=e=>{const t=document.createElement("canvas");return t.width=2,t.height=2,new Promise(((i,r)=>{t.toBlob((async e=>{if(t.remove(),e){const r=await Si(e);i({buffer:r,width:t.width,height:t.height})}else r(new f(E.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED))}),e,1)}))},Si=async e=>{const t=await e.arrayBuffer();return new Uint8Array(t)};function yi(e,t){if("VideoFrame"in window&&"TransformStream"in window&&fe().supportWebRTCInsertableStream){const i=new MediaStreamTrackProcessor(e),r=new MediaStreamTrackGenerator({kind:"video"});let s,o,n=Date.now();const a=()=>{c&&(clearInterval(c),c=void 0),s&&(s.close(),s=void 0),e.stop(),o=void 0,r.removeEventListener("ended",a)};let c=window.setInterval((()=>{if(o&&s&&Date.now()-n>(null!=t?t:1e3))try{"live"===r.readyState?o.enqueue(s.clone()):a()}catch(e){a()}}),null!=t?t:1e3);const d=new TransformStream({transform:(e,t)=>{"live"===r.readyState?(o=t,n=Date.now(),void 0===s?(s=e,t.enqueue(e.clone())):(t.enqueue(s),s=e)):e.close()}});return r.addEventListener("ended",a),i.readable.pipeThrough(d).pipeTo(r.writable),r}}var ki,bi,Ii,Ai,Ri,wi,Di,Ci,Mi,Ni,Oi,Li,Pi,Vi,xi,Ui,Bi,Fi,Gi,Wi,Hi,Ki,Zi,Yi,zi,ji,Xi,Qi,Ji,qi,$i,er,tr,ir,rr,sr,or,nr,ar,cr;let dr=(ki=ge({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),bi=ge({argsMap:(e,t)=>[e.getTrackId(),t]}),Ii=ii(),Ai=J("LocalAudioTrack","_enabledMutex"),Ri=ge({argsMap:(e,t)=>[e.getTrackId(),t]}),wi=ii(),Di=J("LocalAudioTrack","_enabledMutex"),Ci=ge({argsMap:(e,t)=>[e.getTrackId(),t]}),Mi=ii(),Ni=ii(),Oi=ii(),Li=ge({argsMap:e=>[e.getTrackId()]}),Pi=ii(),Vi=ge({argsMap:e=>[e.getTrackId()]}),xi=ii(),Ui=ge({argsMap:e=>[e.getTrackId()]}),Bi=ge({argsMap:(e,t)=>[e.getTrackId(),t.name]}),Fi=ge({argsMap:e=>[e.getTrackId()]}),gt((Gi=class extends Et{get _source(){return this.initWebAudio()}set _source(e){this._trackSource=e}get processorContext(){return this._processorContext||(this._processorContext=this.initProcessor().processorContext),this._processorContext}get processorDestination(){return this._processorDestination||(this._processorDestination=this.initProcessor().processorDestination),this._processorDestination}get isPlaying(){return this._useAudioElement?ti.isPlaying(this.getTrackId()):this._source.isPlayed}get __className__(){return"LocalAudioTrack"}constructor(e,t,i,r){super(e,i),_t(this,"trackMediaType",qe.AUDIO),_t(this,"_encoderConfig",void 0),_t(this,"_trackSource",void 0),_t(this,"metadata",[]),_t(this,"_enabled",!0),_t(this,"_volume",100),_t(this,"_useAudioElement",!0),_t(this,"_bypassWebAudio",!1),_t(this,"processor",void 0),_t(this,"_processorContext",void 0),_t(this,"_processorDestination",void 0),_t(this,"_getOriginVolumeLevel",void 0),this._encoderConfig=t,this._getOriginVolumeLevel=!!r,this._trackSource=new ai,u("DISABLE_WEBAUDIO")&&(this._bypassWebAudio=!0),u("LOCAL_AUDIO_TRACK_USES_WEB_AUDIO")&&(this._useAudioElement=!1);c()&&!At()?setTimeout((()=>this.initWebAudio())):this.initWebAudio()}setVolume(e){_(e,"volume",0,1e3),this._volume=e,this._source.setVolume(e/100),this._useAudioElement&&ti.setVolume(this.getTrackId(),e);try{if(this._bypassWebAudio)return void le.debug("[".concat(this.getTrackId(),"] setVolume returned because no pass through WebAudio."));const e=this._source.createOutputTrack();this._mediaStreamTrack!==e&&(this._mediaStreamTrack=e,w(this,He.NEED_REPLACE_TRACK,this).then((()=>{le.debug("[".concat(this.getTrackId(),"] replace web audio track success"))})).catch((e=>{le.warning("[".concat(this.getTrackId(),"] replace web audio track failed"),e)})))}catch(e){}}getVolumeLevel(){return this._muted&&this.enabled&&this._getOriginVolumeLevel?this._source.getOriginVolumeLevel():this._source.getAccurateVolumeLevel()}async setPlaybackDevice(e){if(!this._useAudioElement||!Ee())throw new f(E.NOT_SUPPORTED,"your browser does not support setting the audio output device");await ti.setSinkID(this.getTrackId(),e)}async setEnabled(e,t,i){return this._setEnabled(e,t,i)}async _setEnabled(e,t,i){if(!i){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(le.info("[".concat(this.getTrackId(),"] start setEnabled"),e),e){this._originMediaStreamTrack.enabled=!0;try{i||(this._enabled=!0),await w(this,He.NEED_ENABLE_TRACK,this),le.info("[".concat(this.getTrackId(),"] setEnabled to ").concat(e," success"))}catch(e){throw i||(this._enabled=!1),le.error("[".concat(this.getTrackId(),"] setEnabled to true error"),e.toString()),e}}else{this._originMediaStreamTrack.enabled=!1,i||(this._enabled=!1);try{await w(this,He.NEED_DISABLE_TRACK,this)}catch(e){throw i||(this._enabled=!0),le.error("[".concat(this.getTrackId(),"] setEnabled to false error"),e.toString()),e}}}async setMuted(e){e!==this._muted&&(this.stateCheck("muted",e),this._muted=e,this._originMediaStreamTrack.enabled=!e,le.debug("[".concat(this.getTrackId(),"] start set muted: ").concat(e)),e?await w(this,He.NEED_MUTE_TRACK,this):await w(this,He.NEED_UNMUTE_TRACK,this))}getStats(){b((()=>{le.warning("[deprecated] LocalAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalAudioStats instead")}),"localAudioTrackGetStatsWarning");const e=q(this,He.GET_STATS);return e||vt({},tt)}setAudioFrameCallback(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:4096;if(!e)return this._source.removeAllListeners($e.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(t),this._source.removeAllListeners($e.ON_AUDIO_BUFFER),this._source.on($e.ON_AUDIO_BUFFER,(t=>e(t)))}play(){le.debug("[".concat(this.getTrackId(),"] start audio playback")),this._useAudioElement?(le.debug("[".concat(this.getTrackId(),"] start audio playback in element")),ti.play(this._mediaStreamTrack,this.getTrackId(),this._volume)):this._source.play()}stop(){le.debug("[".concat(this.getTrackId(),"] stop audio playback")),this._useAudioElement?ti.stop(this.getTrackId()):this._source.stop()}close(){super.close(),this._processorDestination&&this.unbindProcessorDestinationEvents(this._processorDestination),this._processorContext&&this.unbindProcessorContextEvents(this._processorContext),this.unpipe(),this._processorDestination&&this._processorDestination._source&&this._processorDestination._source.unpipe(),this._source.destroy()}_updatePlayerSource(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];le.debug("[".concat(this.getTrackId(),"] update player source track")),e&&this._source.updateTrack(this._mediaStreamTrack),this._useAudioElement&&ti.updateTrack(this.getTrackId(),this._mediaStreamTrack)}async _updateOriginMediaStreamTrack(e,t){this._originMediaStreamTrack!==e&&(this._originMediaStreamTrack&&(this._originMediaStreamTrack.removeEventListener("ended",this._handleTrackEnded),t&&this._originMediaStreamTrack.stop()),e.addEventListener("ended",this._handleTrackEnded),this._originMediaStreamTrack=e,this._muted&&(this._originMediaStreamTrack.enabled=!1),this.processor&&this._processorContext&&this.processor.updateInput({track:e,context:this._processorContext}),this._mediaStreamTrack!==this._source.outputTrack?(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await w(this,He.NEED_REPLACE_TRACK,this)):this._source.updateTrack(this._originMediaStreamTrack),this._getOriginVolumeLevel&&this._source.updateOriginTrack(e))}renewMediaStreamTrack(e){return Promise.resolve(void 0)}pipe(e){if(this._bypassWebAudio)throw new f(E.INVALID_OPERATION,"Can not process AudioTrack when bypassWebAudio set to true.");if(this.processor===e)return e;if(e._source)throw new f(E.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,node:this._source.processSourceNode,context:this.processorContext}),e}unpipe(){var e;if(!this.processor)return;const t=this.processor;null===(e=this._source.processSourceNode)||void 0===e||e.disconnect(),this.processor._source=!1,this.processor=void 0,t.reset()}bindProcessorDestinationEvents(e){e.on(nt.ON_TRACK,(async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(!1),this._source.processedNode=this._source.createMediaStreamSourceNode(e),await w(this,He.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await w(this,He.NEED_REPLACE_TRACK,this))})),e.on(nt.ON_NODE,(e=>{this._source.processedNode=e}))}unbindProcessorDestinationEvents(e){e.removeAllListeners(nt.ON_TRACK),e.removeAllListeners(nt.ON_NODE)}bindProcessorContextEvents(e){e.on(at.REQUEST_CONSTRAINTS,(async e=>{e(this._originMediaStreamTrack.getSettings())}))}unbindProcessorContextEvents(e){e.removeAllListeners(at.REQUEST_CONSTRAINTS)}initWebAudio(){return this._trackSource instanceof ai&&(this._trackSource=new xt(this._mediaStreamTrack,!1,this._getOriginVolumeLevel?this._mediaStreamTrack:void 0)),this._trackSource}initProcessor(){const e=new ni(this._source.context,this.getTrackId(),"local"),t=new oi(e);return this._processorContext=e,this._processorDestination=t,this.bindProcessorContextEvents(e),this.bindProcessorDestinationEvents(t),this._source.on($e.UPDATE_SOURCE,(()=>{this.processor&&this.processor.updateInput({node:this._source.processSourceNode,context:e})})),this._useAudioElement&&(this._useAudioElement=!1,this.isPlaying&&(ti.stop(this.getTrackId()),this._source.play()),w(this,He.NEED_REPLACE_MIXING_TRACK,this).then((()=>{le.debug("[".concat(this.getTrackId(),"] replace from origin track to web audio track success"))})).catch((e=>{le.warning("[".concat(this.getTrackId(),"] replace from origin track to web audio track failed"),e)}))),{processorContext:e,processorDestination:t}}}).prototype,"setVolume",[ki],Object.getOwnPropertyDescriptor(Gi.prototype,"setVolume"),Gi.prototype),gt(Gi.prototype,"setPlaybackDevice",[bi,Ii],Object.getOwnPropertyDescriptor(Gi.prototype,"setPlaybackDevice"),Gi.prototype),gt(Gi.prototype,"setEnabled",[Ai,Ri,wi],Object.getOwnPropertyDescriptor(Gi.prototype,"setEnabled"),Gi.prototype),gt(Gi.prototype,"setMuted",[Di,Ci,Mi],Object.getOwnPropertyDescriptor(Gi.prototype,"setMuted"),Gi.prototype),gt(Gi.prototype,"getStats",[Ni],Object.getOwnPropertyDescriptor(Gi.prototype,"getStats"),Gi.prototype),gt(Gi.prototype,"setAudioFrameCallback",[Oi],Object.getOwnPropertyDescriptor(Gi.prototype,"setAudioFrameCallback"),Gi.prototype),gt(Gi.prototype,"play",[Li,Pi],Object.getOwnPropertyDescriptor(Gi.prototype,"play"),Gi.prototype),gt(Gi.prototype,"stop",[Vi,xi],Object.getOwnPropertyDescriptor(Gi.prototype,"stop"),Gi.prototype),gt(Gi.prototype,"close",[Ui],Object.getOwnPropertyDescriptor(Gi.prototype,"close"),Gi.prototype),gt(Gi.prototype,"pipe",[Bi],Object.getOwnPropertyDescriptor(Gi.prototype,"pipe"),Gi.prototype),gt(Gi.prototype,"unpipe",[Fi],Object.getOwnPropertyDescriptor(Gi.prototype,"unpipe"),Gi.prototype),Gi),ur=(Wi=ge({argsMap:(e,t)=>[e.getTrackId(),t]}),Hi=ii(),Ki=J("MicrophoneAudioTrack","_enabledMutex"),Zi=ge({argsMap:(e,t,i)=>[e.getTrackId(),t,i]}),Yi=ii(),zi=ge({argsMap:e=>[e.getTrackId()]}),gt((ji=class extends dr{get __className__(){return"MicrophoneAudioTrack"}constructor(e,t,i,r){super(e,t.encoderConfig?Le(t.encoderConfig):{},r,u("GET_VOLUME_OF_MUTED_AUDIO_TRACK")),_t(this,"_config",void 0),_t(this,"_deviceName","default"),_t(this,"_constraints",void 0),_t(this,"_originalConstraints",void 0),_t(this,"_enabled",!0),this._config=t,this._constraints=i,this._originalConstraints=i,this._deviceName=e.label,"boolean"==typeof t.bypassWebAudio&&(this._bypassWebAudio=t.bypassWebAudio),(W()||$())&&kt.bindInterruptDetectorTrack(this)}async setDevice(e){if(le.info("[".concat(this.getTrackId(),"] start set device to ").concat(e)),this._enabled)try{const t=await Xt.getDeviceById(e),i={};i.audio=vt({},this._constraints),i.audio.deviceId={exact:e},this._originMediaStreamTrack.stop();let r=null;try{r=await Kt(i,this.getTrackId())}catch(e){throw le.error("[".concat(this.getTrackId(),"] setDevice failed"),e.toString()),r=await Kt({audio:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(r.getAudioTracks()[0],!1),e}await this._updateOriginMediaStreamTrack(r.getAudioTracks()[0],!1),this._deviceName=t.label,this._config.microphoneId=e,this._constraints.deviceId={exact:e}}catch(e){throw le.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}else try{const t=await Xt.getDeviceById(e);this._deviceName=t.label,this._config.microphoneId=e,this._constraints.deviceId={exact:e}}catch(e){throw le.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}le.info("[".concat(this.getTrackId(),"] set device to ").concat(e," success"))}async setEnabled(e,t,i){if(t)return le.debug("[".concat(this.getTrackId(),"] setEnabled false (do not close microphone)")),await super._setEnabled(e);if(!i){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(le.info("[".concat(this.getTrackId(),"] start setEnabled"),e),u("AUTO_RESET_AUDIO_ROUTE")&&(C()||M())){const t=navigator.audioSession;t&&(e||(t.type="playback"),t.type="auto")}if(!e){var r;this._originMediaStreamTrack.onended=null,this._originMediaStreamTrack.stop(),null===(r=this._source.clonedTrack)||void 0===r||r.stop(),i||(this._enabled=!1);try{await w(this,He.NEED_DISABLE_TRACK,this)}catch(e){throw le.error("[".concat(this.getTrackId(),"] setEnabled false failed"),e.toString()),e}return}const s=vt({},this._constraints),o=Xt.searchDeviceIdByName(this._deviceName);o&&!s.deviceId&&(s.deviceId=o);try{i||(this._enabled=!0);const e=await Kt({audio:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getAudioTracks()[0],!1),await w(this,He.NEED_ENABLE_TRACK,this)}catch(e){throw i||(this._enabled=!1),le.error("[".concat(this.getTrackId(),"] setEnabled true failed"),e.toString()),e}le.info("[".concat(this.getTrackId(),"] setEnabled success"))}close(){super.close(),(W()||$())&&kt.unbindInterruptDetectorTrack(this)}onTrackEnded(){if((C()||M())&&this._enabled&&!this._isClosed&&kt.duringInterruption){const e=async()=>{kt.off(ye.IOS_INTERRUPTION_END,e),this._enabled&&!this._isClosed&&(le.debug("[".concat(this.getTrackId(),"] try capture microphone media device for interrupted iOS device.")),await this.setEnabled(!1),await this.setEnabled(!0))};kt.on(ye.IOS_INTERRUPTION_END,e)}else le.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(Qe.TRACK_ENDED)}async renewMediaStreamTrack(e){const t=e||this._constraints,i=Xt.searchDeviceIdByName(this._deviceName);if(i&&!t.deviceId&&(t.deviceId=i),this._constraints=t,this._enabled){this._originMediaStreamTrack.stop();const e=await Kt({audio:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getAudioTracks()[0],!0)}}bindProcessorContextEvents(e){super.bindProcessorContextEvents(e),e.on(at.REQUEST_UPDATE_CONSTRAINTS,(async(e,t,i)=>{try{const i=Object.assign({},this._originalConstraints,...e);await this.renewMediaStreamTrack(i),t()}catch(e){i(e)}}))}unbindProcessorContextEvents(e){super.unbindProcessorContextEvents(e),e.removeAllListeners(at.REQUEST_UPDATE_CONSTRAINTS)}}).prototype,"setDevice",[Wi,Hi],Object.getOwnPropertyDescriptor(ji.prototype,"setDevice"),ji.prototype),gt(ji.prototype,"setEnabled",[Ki,Zi,Yi],Object.getOwnPropertyDescriptor(ji.prototype,"setEnabled"),ji.prototype),gt(ji.prototype,"close",[zi],Object.getOwnPropertyDescriptor(ji.prototype,"close"),ji.prototype),ji),hr=(Xi=ge({argsMap:(e,t)=>[e.getTrackId(),t,e.duration]}),Qi=ii(),Ji=ge({argsMap:e=>[e.getTrackId()]}),qi=ii(),$i=ge({argsMap:e=>[e.getTrackId()]}),er=ii(),tr=ge({argsMap:e=>[e.getTrackId()]}),ir=ii(),rr=ge({argsMap:e=>[e.getTrackId()]}),sr=ii(),or=ge({argsMap:e=>[e.getTrackId()]}),nr=ge({argsMap:e=>[e.getTrackId()]}),ar=ii(),gt((cr=class extends dr{get __className__(){return"BufferSourceAudioTrack"}constructor(e,t,i,r){super(t.createOutputTrack(),i,r),_t(this,"source",void 0),_t(this,"_bufferSource",void 0),this._useAudioElement=!1,this.source=e,this._bufferSource=t,this._bufferSource.on($e.AUDIO_SOURCE_STATE_CHANGE,(e=>{this.safeEmit(Qe.SOURCE_STATE_CHANGE,e)}));try{this._mediaStreamTrack=this._source.createOutputTrack()}catch(e){}}get currentState(){return this._bufferSource.currentState}get duration(){return this._bufferSource.duration}get playbackSpeed(){return this._bufferSource.playbackSpeed}getCurrentTime(){return this._bufferSource.currentTime}startProcessAudioBuffer(e){e&&this._bufferSource.updateOptions(e),this._bufferSource.startProcessAudioBuffer()}pauseProcessAudioBuffer(){this._bufferSource.pauseProcessAudioBuffer()}seekAudioBuffer(e){this._bufferSource.seekAudioBuffer(e)}resumeProcessAudioBuffer(){this._bufferSource.resumeProcessAudioBuffer()}stopProcessAudioBuffer(){this._bufferSource.stopProcessAudioBuffer()}close(){this.source=null,this._bufferSource.destroy(),super.close()}setAudioBufferPlaybackSpeed(e){_(e,"speed",0),this._bufferSource.setAudioBufferPlaybackSpeed(e)}}).prototype,"startProcessAudioBuffer",[Xi,Qi],Object.getOwnPropertyDescriptor(cr.prototype,"startProcessAudioBuffer"),cr.prototype),gt(cr.prototype,"pauseProcessAudioBuffer",[Ji,qi],Object.getOwnPropertyDescriptor(cr.prototype,"pauseProcessAudioBuffer"),cr.prototype),gt(cr.prototype,"seekAudioBuffer",[$i,er],Object.getOwnPropertyDescriptor(cr.prototype,"seekAudioBuffer"),cr.prototype),gt(cr.prototype,"resumeProcessAudioBuffer",[tr,ir],Object.getOwnPropertyDescriptor(cr.prototype,"resumeProcessAudioBuffer"),cr.prototype),gt(cr.prototype,"stopProcessAudioBuffer",[rr,sr],Object.getOwnPropertyDescriptor(cr.prototype,"stopProcessAudioBuffer"),cr.prototype),gt(cr.prototype,"close",[or],Object.getOwnPropertyDescriptor(cr.prototype,"close"),cr.prototype),gt(cr.prototype,"setAudioBufferPlaybackSpeed",[nr,ar],Object.getOwnPropertyDescriptor(cr.prototype,"setAudioBufferPlaybackSpeed"),cr.prototype),cr);class lr extends dr{get __className__(){return"MixingAudioTrack"}get isActive(){for(const e of this.trackList)if(e._enabled&&!e._isClosed&&!e.muted)return!0;return!1}constructor(){const e=It().createMediaStreamDestination();super(e.stream.getAudioTracks()[0],void 0,k(8,"track-mix-")),_t(this,"trackList",void 0),_t(this,"destNode",void 0),this._useAudioElement=!1;try{this._mediaStreamTrack=this._source.createOutputTrack()}catch(e){}this.destNode=e,this.trackList=[]}hasAudioTrack(e){return-1!==this.trackList.indexOf(e)}addAudioTrack(e){-1===this.trackList.indexOf(e)?(le.debug("add ".concat(e.getTrackId()," to mixing track")),e._source.outputNode.connect(this.destNode),this.trackList.push(e),this.updateEncoderConfig()):le.debug("track ".concat(e.getTrackId()," is already added"))}removeAudioTrack(e){if(-1!==this.trackList.indexOf(e)){le.debug("remove ".concat(e.getTrackId()," from mixing track"));try{e._source.outputNode.disconnect(this.destNode)}catch(e){}D(this.trackList,e),this.updateEncoderConfig()}}updateEncoderConfig(){const e={};this.trackList.forEach((t=>{t._encoderConfig&&((t._encoderConfig.bitrate||0)>(e.bitrate||0)&&(e.bitrate=t._encoderConfig.bitrate),(t._encoderConfig.sampleRate||0)>(e.sampleRate||0)&&(e.sampleRate=t._encoderConfig.sampleRate),(t._encoderConfig.sampleSize||0)>(e.sampleSize||0)&&(e.sampleSize=t._encoderConfig.sampleSize),t._encoderConfig.stereo&&(e.stereo=!0))})),this._encoderConfig=e}_updateRtpTransceiver(e){this._rtpTransceiver!==e&&(this._rtpTransceiver=e,this.trackList.forEach((t=>{t instanceof lr?t.emit(Xe.TRANSCEIVER_UPDATED,e):t._updateRtpTransceiver(e)})))}}class pr extends Vt{set currentState(e){e!==this._currentState&&(this._currentState=e,this.safeEmit($e.AUDIO_SOURCE_STATE_CHANGE,this._currentState))}get currentState(){return this._currentState}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),_t(this,"audioBuffer",void 0),_t(this,"sourceNode",void 0),_t(this,"startPlayTime",0),_t(this,"startPlayOffset",0),_t(this,"pausePlayTime",0),_t(this,"options",void 0),_t(this,"currentLoopCount",0),_t(this,"currentPlaybackSpeed",100),_t(this,"_currentState","stopped"),this.audioBuffer=e,this.options=t,this.startPlayOffset=this.options.startPlayTime||0}createWebAudioDiagram(){return this.context.createGain()}get duration(){return this.audioBuffer?this.audioBuffer.duration:0}get playbackSpeed(){return this.currentPlaybackSpeed}get currentTime(){return this.audioBuffer?"stopped"===this.currentState?0:"paused"===this.currentState?this.pausePlayTime:((this.context.currentTime-this.startPlayTime)*(this.playbackSpeed/100)+this.startPlayOffset)%this.audioBuffer.duration:0}updateOptions(e){"stopped"===this.currentState?(this.options=e,this.startPlayOffset=this.options.startPlayTime||0):le.warning("can not set audio source options")}startProcessAudioBuffer(){this.sourceNode&&this.stopProcessAudioBuffer(),this.sourceNode=this.createSourceNode(),this.startSourceNode(),this.currentState="playing"}pauseProcessAudioBuffer(){this.sourceNode&&"playing"===this.currentState&&(this.pausePlayTime=this.currentTime,this.sourceNode.onended=null,this.sourceNode.stop(),this.sourceNode.buffer=null,this.sourceNode=this.createSourceNode(),this.currentState="paused")}seekAudioBuffer(e){this.sourceNode&&(this.sourceNode.onended=null,"playing"===this.currentState&&this.sourceNode.stop(),this.sourceNode=this.createSourceNode(),"playing"===this.currentState?(this.startPlayOffset=e,this.startSourceNode()):"paused"===this.currentState&&(this.pausePlayTime=e))}resumeProcessAudioBuffer(){"paused"===this.currentState&&this.sourceNode&&(this.startPlayOffset=this.pausePlayTime,this.pausePlayTime=0,this.startSourceNode(),this.currentState="playing")}stopProcessAudioBuffer(){if(this.sourceNode){this.sourceNode.onended=null;try{this.sourceNode.stop()}catch(e){}this.reset()}}destroy(){this.audioBuffer=null,super.destroy()}setAudioBufferPlaybackSpeed(e){this.sourceNode&&("playing"===this.currentState&&(this.startPlayOffset=this.currentTime,this.startPlayTime=this.context.currentTime),this.sourceNode.playbackRate.value=e/100),this.currentPlaybackSpeed=e}startSourceNode(){this.sourceNode&&this.sourceNode.buffer&&(this.sourceNode.start(0,this.startPlayOffset),this.startPlayTime=this.context.currentTime,this.sourceNode.onended=this.handleSourceNodeEnded.bind(this))}createSourceNode(){const e=this.context.createBufferSource();return e.buffer=this.audioBuffer,e.loop=!!this.options.loop,e.connect(this.outputNode),e.playbackRate.value=this.currentPlaybackSpeed/100,e}handleSourceNodeEnded(){if(this.currentLoopCount+=1,this.options.cycle&&this.options.cycle>this.currentLoopCount)return this.startPlayOffset=0,this.sourceNode=void 0,void this.startProcessAudioBuffer();this.reset()}reset(){this.startPlayOffset=this.options.startPlayTime||0,this.currentState="stopped",this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=void 0),this.currentLoopCount=0}}const mr=new Map;function gr(e,t){if(0===e.length||0===t.length)return 1/0;const i=se(e),r=se(t);return Math.floor(r/i)}class _r{get rendFrameRate(){const e=Math.max(1,gr(this._render_interframe_delays_sizes,this._render_interframe_delays));return Math.floor(1e3/e)}get videoElementStatus(){return this._videoElementStatus}set videoElementStatus(e){e!==this._videoElementStatus&&(le.debug("[".concat(this.trackId,"] video-element-status change ").concat(this._videoElementStatus," => ").concat(e)),this._videoElementStatus=e)}get videoState(){return this._videoState}set videoState(e){var t;e!==this._videoState&&(this._videoState=e,null===(t=this.onVideoStateChanged)||void 0===t||t.call(this,this.videoState))}constructor(e){_t(this,"trackId",void 0),_t(this,"config",void 0),_t(this,"onFirstVideoFrameDecoded",void 0),_t(this,"onVideoStateChanged",void 0),_t(this,"freezeTimeCounterList",[]),_t(this,"renderFreezeAccTime",0),_t(this,"renderFreezeAccTime2",0),_t(this,"isKeepLastFrame",!1),_t(this,"timeUpdatedCount",0),_t(this,"freezeTime",0),_t(this,"playbackTime",0),_t(this,"lastTimeUpdatedTime",0),_t(this,"autoplayFailed",!1),_t(this,"videoTrack",void 0),_t(this,"videoElement",void 0),_t(this,"cacheVideoElement",void 0),_t(this,"_render_interframe_delays",[]),_t(this,"_render_interframe_delays_sizes",[]),_t(this,"_videoState",lt.VideoStateStopped),_t(this,"videoElementCheckInterval",void 0),_t(this,"videoElementFreezeTimeout",void 0),_t(this,"_videoElementStatus",ht.NONE),_t(this,"isGettingVideoDimensions",!1),_t(this,"startGetVideoDimensions",(()=>{const e=()=>{if(this.isGettingVideoDimensions=!0,this.videoElement.videoWidth*this.videoElement.videoHeight>4)return le.debug("[".concat(this.trackId,"] current video dimensions:"),this.videoElement.videoWidth,this.videoElement.videoHeight),void(this.isGettingVideoDimensions=!1);setTimeout(e,500)};!this.isGettingVideoDimensions&&e()})),_t(this,"autoResumeAfterInterruption",(()=>{this.videoTrack&&"live"===this.videoTrack.readyState&&"running"===kt.curState&&(le.debug("[track-".concat(this.trackId,"] video element paused, auto resume for ").concat(te())),ie()?(this.videoElement.srcObject=null,this.videoElement.srcObject=new MediaStream([this.videoTrack]),this.videoElement.play()):(this.videoElement.pause(),this.videoElement.play()))})),_t(this,"handleVideoEvents",(e=>{switch(e.type){case"play":case"playing":this.startGetVideoDimensions(),this.videoElementStatus=ht.PLAYING;break;case"loadeddata":if(this.videoState=lt.VideoStateStarting,this.onFirstVideoFrameDecoded&&this.onFirstVideoFrameDecoded(),this.cacheVideoElement){try{this.cacheVideoElement.srcObject=null,this.cacheVideoElement.remove()}catch(e){}this.cacheVideoElement=void 0}break;case"canplay":this.videoElementStatus=ht.CANPLAY;break;case"stalled":this.videoElementStatus=ht.STALLED;break;case"suspend":this.videoElementStatus=ht.SUSPEND;break;case"pause":this.videoElementStatus=ht.PAUSED,C()||M()||c()&&this.autoplayFailed||!this.videoTrack||"live"!==this.videoTrack.readyState||(le.debug("[track-".concat(this.trackId,"] video element paused, auto resume")),this.videoElement.play());break;case"waiting":this.videoElementStatus=ht.WAITING;break;case"abort":this.videoElementStatus=ht.ABORT;break;case"ended":this.videoElementStatus=ht.ENDED;break;case"emptied":this.videoElementStatus=ht.EMPTIED;break;case"error":{const e=this.videoElement.error;e&&(this.videoElementStatus=ht.ERROR,le.error("[".concat(this.trackId,"] media error: ").concat(e.message," (").concat(e.code,")")));break}case"timeupdate":{const e=performance.now();if(this.timeUpdatedCount+=1,this.timeUpdatedCount<10)return void(this.lastTimeUpdatedTime=e);const t=e-this.lastTimeUpdatedTime,i=this.lastTimeUpdatedTime;if(this.lastTimeUpdatedTime=e,Rs.lastVisibleTime<Rs.lastHiddenTime||i<Rs.lastHiddenTime||i<Rs.lastVisibleTime)return;for(t>u("VIDEO_FREEZE_DURATION")&&(this.freezeTime+=t),this.playbackTime+=t;this.playbackTime>=6e3;){this.playbackTime-=6e3;const e=Math.min(6e3,this.freezeTime);this.freezeTimeCounterList.push(e),this.freezeTime=Math.max(0,this.freezeTime-6e3)}break}}})),_t(this,"autoResumeAfterInterruptionOnIOS15_16",(()=>{this.videoTrack&&"live"===this.videoTrack.readyState&&(le.debug("[track-".concat(this.trackId,"] video element paused, auto resume for ").concat(te())),ie()?(this.videoElement.srcObject=null,this.videoElement.srcObject=new MediaStream([this.videoTrack]),this.videoElement.play()):(this.videoElement.pause(),this.videoElement.play()))})),this.trackId=e.trackId,this.config=e,e.element instanceof HTMLVideoElement?this.videoElement=e.element:this.videoElement=document.createElement("video"),kt.on(ye.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),kt.on(ye.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16)}getVideoElement(){return this.videoElement}getContainerElement(){var e;return null!==(e=this.videoElement.parentElement)&&void 0!==e?e:void 0}updateConfig(e){this.config=e,this.trackId=e.trackId,e.element!==this.videoElement&&(this.destroy(),this.videoElement=e.element),this.videoTrack&&this.initVideoElement()}updateVideoTrack(e){this.videoTrack!==e&&(this.videoTrack=e,this.initVideoElement())}play(t){const i=this.videoElement.play();i&&i.catch&&i.catch((e=>{t&&$t(t,"video",e.message,this.trackId),"NotAllowedError"===e.name?(le.warning("detected video element autoplay failed",e),this.autoplayFailed=!0,this.handleAutoPlayFailed()):le.warning("[".concat(this.trackId,"] play warning: "),e)}));const r=e();if(("Safari"===r.name&&15===Number(r.version)||W())&&i&&i.then){const e=()=>{this.config.mirror&&(this.videoElement.style.transform="rotateY(180deg)")};i.then(e).catch(e)}}getCurrentFrame(){const e=document.createElement("canvas");e.width=this.videoElement.videoWidth,e.height=this.videoElement.videoHeight;const t=e.getContext("2d");if(!t)return le.error("create canvas context failed!"),new ImageData(2,2);t.drawImage(this.videoElement,0,0,e.width,e.height);const i=t.getImageData(0,0,e.width,e.height);return e.remove(),i}async getCurrentFrameToUint8Array(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;const i=document.createElement("canvas");i.width=this.videoElement.videoWidth,i.height=this.videoElement.videoHeight;const r=i.getContext("2d");return r?(r.drawImage(this.videoElement,0,0,i.width,i.height),new Promise(((r,s)=>{i.toBlob((async e=>{if(i.remove(),e){const t=await Si(e);r({buffer:t,width:i.width,height:i.height})}else s(new f(E.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED))}),e,t<0?.1:t>1?1:t)}))):await Ei(e)}destroy(){kt.off(ye.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),kt.off(ye.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16),this.videoElement.srcObject=null,this.resetVideoElement(),this.freezeTimeCounterList=[],this.videoState=lt.VideoStateStopped}initVideoElement(){if(this.videoElementStatus=ht.INIT,!this.videoElementCheckInterval&&(Tr.forEach((e=>{this.videoElement.addEventListener(e,this.handleVideoEvents)})),this.videoElementCheckInterval=window.setInterval((()=>{re(this.videoElement)||(this.videoElementStatus=ht.DESTROYED)}),1e3),u("ENABLE_VIDEO_FRAME_CALLBACK"))){var t,i;let e;const r=()=>{"visible"===document.visibilityState&&(document.removeEventListener("visibilitychange",r),this.videoElementFreezeTimeout=window.setTimeout(s,u("VIDEO_FREEZE_DURATION")))},s=()=>{this.videoElementFreezeTimeout=void 0,this.videoState===lt.VideoStateDecoding&&("visible"===document.visibilityState?this.videoState=lt.VideoStateFrozen:document.addEventListener("visibilitychange",r))},o=(t,i)=>{if(this.videoElementStatus===ht.PLAYING){if(e){const t=i.presentationTime-e.presentationTime,r=i.presentedFrames-e.presentedFrames;this._render_interframe_delays_sizes.push(r),this._render_interframe_delays.push(t);const o=se(this._render_interframe_delays_sizes),n=o-this._render_interframe_delays_sizes[0];if(o>30&&n>5&&(this._render_interframe_delays_sizes.shift(),this._render_interframe_delays.shift()),this.videoState===lt.VideoStateStarting&&(this.videoState=lt.VideoStateDecoding),this.videoState===lt.VideoStateDecoding&&this.onVideoStateChanged&&(this.videoElementFreezeTimeout&&window.clearTimeout(this.videoElementFreezeTimeout),this.videoElementFreezeTimeout=window.setTimeout(s,u("VIDEO_FREEZE_DURATION"))),t<u("VIDEO_FREEZE_DURATION")&&this.videoState===lt.VideoStateFrozen&&(this.videoState=lt.VideoStateDecoding),t>u("VIDEO_FREEZE_DURATION")&&Rs.lastVisibleTime>=Rs.lastHiddenTime&&e.timestamp>Rs.lastVisibleTime&&e.timestamp>Rs.lastHiddenTime){const e=Math.min(66,gr(this._render_interframe_delays_sizes,this._render_interframe_delays)),i=Math.max(0,t-(r-1)*e);this.renderFreezeAccTime2+=i>e?i:0,this.renderFreezeAccTime+=t}}e=vt(vt({},i),{},{timestamp:t})}var r,n;u("ENABLE_VIDEO_FRAME_CALLBACK")&&(null===(r=(n=this.videoElement).requestVideoFrameCallback)||void 0===r||r.call(n,o))};null===(t=(i=this.videoElement).requestVideoFrameCallback)||void 0===t||t.call(i,o)}this.videoElement.controls=!1,this.videoElement.setAttribute("playsinline",""),x()&&!u("HIDE_NO_POSTER")&&(this.videoElement.poster="noposter");const r=e();if("Safari"===r.name&&15===Number(r.version)||W()||!this.config.mirror||(this.videoElement.style.transform="rotateY(180deg)"),this.config.fit?this.videoElement.style.objectFit=this.config.fit:this.videoElement.style.objectFit="cover",this.videoElement.setAttribute("muted",""),this.videoElement.muted=!0,this.videoElement.srcObject&&this.videoElement.srcObject instanceof MediaStream){this.videoElement.srcObject.getVideoTracks()[0]!==this.videoTrack&&(this.videoElement.srcObject=this.videoTrack?new MediaStream([this.videoTrack]):null,h()&&this.videoElement.load())}else this.videoElement.srcObject=this.videoTrack?new MediaStream([this.videoTrack]):null,h()&&this.videoElement.load();const s=this.videoElement.play();void 0!==s&&s.catch((e=>{le.debug("[".concat(this.trackId,"] playback interrupted"),e.toString())}))}resetVideoElement(){Tr.forEach((e=>{this.videoElement&&this.videoElement.removeEventListener(e,this.handleVideoEvents)})),this.videoElementCheckInterval&&(window.clearInterval(this.videoElementCheckInterval),this.videoElementCheckInterval=void 0),this.videoElementStatus=ht.NONE}handleAutoPlayFailed(){const e=t=>{t.preventDefault(),this.videoElement.play().then((()=>{le.debug("[".concat(this.trackId,"] Video element for trackId:").concat(this.trackId," autoplay resumed."))})).catch((e=>{le.error(e)})),this.autoplayFailed=!1,F()?document.body.removeEventListener("click",e,!0):(document.body.removeEventListener("touchstart",e,!0),document.body.removeEventListener("mousedown",e,!0))};F()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0)),qt()}}const Tr=["play","playing","loadeddata","canplay","pause","stalled","suspend","waiting","abort","emptied","ended","timeupdate","error"];class vr extends _r{constructor(e){super(e),_t(this,"container",void 0),_t(this,"slot",void 0),this.slot=e.element,this.updateConfig(e)}updateConfig(e){this.config=e,this.trackId=e.trackId;const t=e.element;t!==this.slot&&(this.destroy(),this.slot=t),this.createElements()}updateVideoTrack(e){this.videoTrack!==e&&(this.videoTrack=e,this.createElements())}play(e){var t;null!==(t=this.container)&&void 0!==t&&t.contains(this.videoElement)&&super.play(e)}getCurrentFrame(){var e;return null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)?super.getCurrentFrame():new ImageData(2,2)}async getCurrentFrameToUint8Array(e){var t;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return null!==(t=this.container)&&void 0!==t&&t.contains(this.videoElement)?await super.getCurrentFrameToUint8Array(e,i):await Ei(e)}destroy(){if(super.destroy(),this.videoElement.remove(),this.videoElement=document.createElement("video"),this.container){try{this.container.remove(),this.slot.removeChild(this.container)}catch(e){}this.container=void 0}}createElements(){this.container||(this.container=document.createElement("div")),this.container.id="agora-video-player-".concat(this.trackId),this.container.style.width="100%",this.container.style.height="100%",this.container.style.position="relative",this.container.style.overflow="hidden",this.videoTrack?(this.container.style.backgroundColor="black",u("KEEP_LAST_FRAME")&&this.isKeepLastFrame&&this.videoElement.paused&&this.resetVideoElement(),this.mountedVideoElement()):this.unmountedVideoElement(),this.slot.appendChild(this.container)}mountedVideoElement(){var e;!this.container||null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)||this.container.appendChild(this.videoElement),super.initVideoElement(),this.videoElement.id="video_".concat(this.trackId),this.videoElement.className="agora_video_player",this.videoElement.style.width="100%",this.videoElement.style.height="100%",this.videoElement.style.position="absolute",this.videoElement.style.left="0",this.videoElement.style.top="0"}unmountedVideoElement(){var e;if(null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)){super.resetVideoElement();try{this.container&&this.container.removeChild(this.videoElement)}catch(e){}this.videoElement=document.createElement("video")}}resetVideoElement(){var e;null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)&&(super.resetVideoElement(),this.cacheVideoElement=this.videoElement,this.videoElement=document.createElement("video"))}getContainerElement(){return this.container}}var fr,Er,Sr,yr,kr,br,Ir,Ar,Rr,wr,Dr,Cr,Mr,Nr,Or,Lr,Pr,Vr,xr,Ur,Br,Fr,Gr,Wr,Hr,Kr,Zr,Yr,zr,jr,Xr,Qr,Jr,qr,$r,es;let ts=(fr=ge({argsMap:(e,t,i)=>[e.getTrackId(),"string"==typeof t?t:t instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement",i]}),Er=ii(),Sr=ge({argsMap:e=>[e.getTrackId()]}),yr=J("LocalVideoTrack","_enabledMutex"),kr=ge({argsMap:(e,t)=>[e.getTrackId(),t]}),br=ii(),Ir=J("LocalVideoTrack","_enabledMutex"),Ar=ge({argsMap:(e,t)=>[e.getTrackId(),t]}),Rr=ii(),wr=ge({argsMap:(e,t)=>[e.getTrackId(),t,e._saveEncodeBitrateRatio]}),Dr=ii(),Cr=ge({argsMap:(e,t)=>[e.getTrackId(),t]}),Mr=ii(),Nr=ii(),Or=ge({argsMap:(e,t,i)=>[e.getTrackId(),t,i]}),Lr=ii(),Pr=ii(),Vr=ii(),xr=ii(),Ur=ii(),Br=ii(),Fr=ii(),Gr=ge({argsMap:(e,t)=>[e.getTrackId(),t.name]}),Wr=ge({argsMap:e=>[e.getTrackId()]}),Hr=ge({argsMap:e=>[e.getTrackId()]}),Kr=ge({argsMap:(e,t,i)=>[e.getTrackId(),t.label,i]}),Zr=class e extends Et{get videoHeight(){if(c()){const{height:e}=this._mediaStreamTrack.getSettings();return this._videoHeight=e,this._videoHeight}return this._videoHeight}get videoWidth(){if(c()){const{width:e}=this._mediaStreamTrack.getSettings();return this._videoWidth=e,this._videoWidth}return this._videoWidth}get isPlaying(){return!(!this._player||this._player.videoElementStatus!==ht.PLAYING)}get processorDestination(){return this._processorDestination}get processorContext(){return this._processorContext}set processorContext(e){this._processorContext=e}get __className__(){return"LocalVideoTrack"}constructor(e,i,r,s,o,n){if(super(e,o),_t(this,"trackMediaType",qe.VIDEO),_t(this,"_player",void 0),_t(this,"isUseScaleResolutionDownBy",!1),_t(this,"_videoVisibleTimer",null),_t(this,"_previousVideoVisibleStatus",void 0),_t(this,"_clearPreviousVideoVisibleStatus",(()=>this._previousVideoVisibleStatus=void 0)),_t(this,"_encoderConfig",void 0),_t(this,"_scalabilityMode",{numSpatialLayers:1,numTemporalLayers:1}),_t(this,"_optimizationMode",void 0),_t(this,"_saveEncodeBitrateRatio",1),_t(this,"_videoHeight",void 0),_t(this,"_videoWidth",void 0),_t(this,"_forceBitrateLimit",void 0),_t(this,"_enabled",!0),_t(this,"_processorDestination",void 0),_t(this,"_processorContext",void 0),c()){const{width:t,height:i}=e.getSettings();this._videoWidth=t,this._videoHeight=i}else this.updateMediaStreamTrackResolution();if(this._scalabilityMode=r,this._optimizationMode=s,this._hints=n||[],i&&-1!==this._hints.indexOf(Ke.CUSTOM_TRACK)?this._encoderConfig=oe(i):this._encoderConfig=i,-1===this._hints.indexOf(Ke.SCREEN_TRACK))this.updateBitrateFromProfile();else if(ne(t.CHROME,115)&&ae()){const t=yi(e);t&&(le.info("local screen video track begin to inject frame"),this._mediaStreamTrack=t)}i&&-1!==this._hints.indexOf(Ke.CUSTOM_TRACK)&&this.setEncoderConfiguration(i),this._processorContext=new si(this.getTrackId(),"local"),this._processorDestination=new ri(this.processorContext),this.bindProcessorDestinationEvents()}play(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("string"==typeof e){const t=document.getElementById(e);t?e=t:(le.warning("[".concat(this.getTrackId(),'] can not find "#').concat(e,'" element, use document.body')),e=document.body)}le.debug("[".concat(this.getTrackId(),"] start video playback in ").concat(e instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement"),JSON.stringify(t));const i=vt(vt(vt({},this._getDefaultPlayerConfig()),t),{},{trackId:this.getTrackId(),element:e});this._player?this._player.updateConfig(i):(e instanceof HTMLVideoElement?this._player=new _r(i):this._player=new vr(i),this._player.updateVideoTrack(this._mediaStreamTrack)),this._player.play(),this._videoVisibleTimer&&window.clearInterval(this._videoVisibleTimer),this._clearPreviousVideoVisibleStatus(),this._videoVisibleTimer=window.setInterval((()=>{try{const e=this.getVideoElementVisibleStatus();this.safeEmit(Qe.VIDEO_ELEMENT_VISIBLE_STATUS,e)}catch(e){}}),u("CHECK_VIDEO_VISIBLE_INTERVAL"))}stop(){this._player&&(this._videoVisibleTimer&&(window.clearInterval(this._videoVisibleTimer),this._videoVisibleTimer=null),this._clearPreviousVideoVisibleStatus(),this._player.destroy(),this._player=void 0,le.debug("[".concat(this.getTrackId(),"] stop video playback")))}async setEnabled(e,t){if(!t){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(le.info("[".concat(this.getTrackId(),"] start setEnabled"),e),!e){this._originMediaStreamTrack.enabled=!1;try{await w(this,He.NEED_DISABLE_TRACK,this)}catch(e){throw le.error("[".concat(this.getTrackId(),"] setEnabled to false error"),e.toString()),e}return t||(this._enabled=!1),void le.info("[".concat(this.getTrackId(),"] setEnabled to false success"))}this._originMediaStreamTrack.enabled=!0;try{await w(this,He.NEED_ENABLE_TRACK,this)}catch(e){throw le.error("[".concat(this.getTrackId(),"] setEnabled to true error"),e.toString()),e}le.info("[".concat(this.getTrackId(),"] setEnabled to true success")),t||(this._enabled=!0)}async setMuted(e){e!==this._muted&&(this.stateCheck("muted",e),this._muted=e,this._originMediaStreamTrack.enabled=!e,le.debug("[".concat(this.getTrackId(),"] start set muted: ").concat(e)),e?await w(this,He.NEED_MUTE_TRACK,this):await w(this,He.NEED_UNMUTE_TRACK,this))}async setSaveEncodeBitrateRatio(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this._saveEncodeBitrateRatio;if(1!==this._saveEncodeBitrateRatio&&this._encoderConfig&&this._encoderConfig.bitrateMax&&this._encoderConfig.bitrateMin){this._encoderConfig.bitrateMin=Math.floor(this._encoderConfig.bitrateMin*e),this._encoderConfig.bitrateMax=Math.floor(this._encoderConfig.bitrateMax*e),le.debug("[".concat(this.getTrackId(),"] set save encode bitrate ratio, ").concat(e)),this._saveEncodeBitrateRatio=1;try{await w(this,He.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(le)}}}async setEncoderConfiguration(e,t){if(!this._enabled)throw new f(E.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");if(e=Ce(e),u("USE_STANDARD_BITRATE_DEFAULT")&&(delete e.bitrateMax,delete e.bitrateMin),this._forceBitrateLimit&&(e.bitrateMax=this._forceBitrateLimit.max_bitrate?this._forceBitrateLimit.max_bitrate:e.bitrateMax,e.bitrateMin=this._forceBitrateLimit.min_bitrate?this._forceBitrateLimit.min_bitrate:e.bitrateMin),e.width||e.height||e.frameRate){const t=ui({encoderConfig:e});(c()||C()||M())&&(t.deviceId=void 0),le.debug("[".concat(this.getTrackId(),"] setEncoderConfiguration applyConstraints"),JSON.stringify(e),JSON.stringify(t));try{await this._originMediaStreamTrack.applyConstraints(t),this.updateMediaStreamTrackResolution()}catch(e){const t=new f(E.UNEXPECTED_ERROR,e.toString());throw le.error("[".concat(this.getTrackId(),"] applyConstraints error"),t.toString()),t}}this._encoderConfig=e,-1===this._hints.indexOf(Ke.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await w(this,He.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(le)}}getStats(){b((()=>{le.warning("[deprecated] LocalVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalVideoStats instead")}),"localVideoTrackGetStatsWarning");const e=q(this,He.GET_STATS);return e||vt({},it)}async setBeautyEffect(e){le.error("LocalVideoTrack.setBeautyEffect was deprecated, please migrate to agora-extension-beauty-effect")}getCurrentFrameData(){return this._player?this._player.getCurrentFrame():new ImageData(2,2)}async getCurrentFrameImage(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return this._player?this._player.getCurrentFrameToUint8Array(e,t):await Ei(e)}async setBitrateLimit(e){le.debug("[".concat(this.getTrackId(),"] set bitrate limit, ").concat(JSON.stringify(e))),e&&(this._forceBitrateLimit=e,this._encoderConfig&&(this._encoderConfig.bitrateMax?this._encoderConfig.bitrateMax=this._encoderConfig.bitrateMax<e.max_bitrate?this._encoderConfig.bitrateMax:e.max_bitrate:this._encoderConfig.bitrateMax=e.max_bitrate,this._encoderConfig.bitrateMin,this._encoderConfig.bitrateMin=e.min_bitrate))}async setOptimizationMode(e){if("motion"!==e&&"detail"!==e&&"balanced"!==e)return void le.error(E.INVALID_PARAMS,"optimization mode must be motion, detail or balanced");const t=this._optimizationMode;try{this._optimizationMode=e,await w(this,He.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this)}catch(e){throw this._optimizationMode=t,le.error("[".concat(this.getTrackId(),"] set optimization mode failed"),e.toString()),e}le.info("[".concat(this.getTrackId(),"] set optimization mode success (").concat(e,")"))}setScalabiltyMode(e){if(1===e.numSpatialLayers&&1!==e.numTemporalLayers)return le.error(E.INVALID_PARAMS,"scalability mode currently not supported, no SVC."),void(this._scalabilityMode={numSpatialLayers:1,numTemporalLayers:1});this._scalabilityMode=e,le.info("[".concat(this.getTrackId(),"] set scalability mode success (").concat(e,")"))}updateMediaStreamTrackResolution(){di(this._originMediaStreamTrack).then((e=>{let[t,i]=e;this._videoHeight=i,this._videoWidth=t})).catch(K)}_updatePlayerSource(){this._player&&this._player.updateVideoTrack(this._mediaStreamTrack)}_getDefaultPlayerConfig(){return{fit:"contain"}}async setSenderConfiguration(e){if(!this._enabled)throw new f(E.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");le.debug("[".concat(this.getTrackId(),"] setSenderConfiguration applyConstraints"),JSON.stringify(e)),e=Ce(e),this._forceBitrateLimit&&(e.bitrateMax=this._forceBitrateLimit.max_bitrate?this._forceBitrateLimit.max_bitrate:e.bitrateMax,e.bitrateMin=this._forceBitrateLimit.min_bitrate?this._forceBitrateLimit.min_bitrate:e.bitrateMin),this._encoderConfig=e,-1===this._hints.indexOf(Ke.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await w(this,He.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(le)}}updateBitrateFromProfile(){if(!this._encoderConfig)return;const{width:e,height:t,frameRate:i}=this.getMediaStreamTrackSettings();if(!e||!t||!i)return;const{bitrateMax:r,bitrateMin:s}=this._encoderConfig;if(null==s||null==r){const{max:o,min:n}=_i(e,t,i,s,r);if(this._encoderConfig.bitrateMin=n,this._encoderConfig.bitrateMax=o,u("VIDEO_STANDARD_BITRATE_VERSION")&&null==s&&null==r){const[r,s]=gi(e,t,i);this._encoderConfig.bitrateMax=r,this._encoderConfig.bitrateMin=n?Math.min(n,r):r,this._saveEncodeBitrateRatio=s,le.debug("[".concat(this.getTrackId(),"] update new bitrate from profile, [w: ").concat(e,", h: ").concat(t,", fps: ").concat(i,"] => [brMax: ").concat(this._encoderConfig.bitrateMax,", brMin: ").concat(this._encoderConfig.bitrateMin,", save_bitrate_ratio: ").concat(this._saveEncodeBitrateRatio,"]"))}else le.debug("[".concat(this.getTrackId(),"] update bitrate from profile, [w: ").concat(e,", h: ").concat(t,", fps: ").concat(i,"] => [brMax: ").concat(o,", brMin: ").concat(n,"]")),this._saveEncodeBitrateRatio=1}}getVideoElementVisibleStatus(){try{var e,t;const i=null==this||null===(e=this._player)||void 0===e?void 0:e.getContainerElement(),r={track:this,element:null==this||null===(t=this._player)||void 0===t?void 0:t.getVideoElement(),slot:null==i?void 0:i.parentElement},{element:s,slot:o}=r;if(this.isPlaying&&s instanceof HTMLVideoElement&&o instanceof HTMLElement){const e=ce.checkOneElementVisible(s),t=Object.assign({},e);if(t.visible!==this._previousVideoVisibleStatus){this._previousVideoVisibleStatus=t.visible;const e=pe.reportApiInvoke(null,{tag:A.TRACER,name:I.LOCAL_VIDEO_TRACK_GET_VIDEO_VISIBLE,options:[this.getTrackId()]});t.visible?e.onSuccess("Video is visible"):e.onSuccess("Invisible because of ".concat(t.reason))}return t}return}catch(e){throw new f(E.GET_VIDEO_ELEMENT_VISIBLE_ERROR,e.message)}}async renewMediaStreamTrack(e){}pipe(e){if(this.processor===e)return e;if(e._source)throw new f(E.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,context:this.processorContext}),e}unpipe(){if(!this.processor)return;const e=this.processor;this.processor._source=void 0,this.processor=void 0,e.reset()}close(){super.close(),this.unbindProcessorDestinationEvents(),this.unbindProcessorContextEvents(),this.unpipe(),this.processorDestination._source&&this.processorDestination._source.unpipe()}clone(t){let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],r=this._encoderConfig;t&&(r=vt(vt({},r),Ce(t))),r=de(r);const s=k(8,"track-video-cloned-"),o=new e(i?this._mediaStreamTrack.clone():this._mediaStreamTrack,r,de(this._scalabilityMode),this._optimizationMode,s,de(this._hints));return t&&r&&o.setEncoderConfiguration(r),le.debug("clone video track from ".concat(this.getTrackId()," to ").concat(s,", clone ").concat(i)),o}async replaceTrack(e,t){if(!(e instanceof MediaStreamTrack))throw new f(E.INVALID_PARAMS,"track should be an instance of MediaStreamTrack");if("video"!==e.kind)throw new f(E.INVALID_PARAMS,"track should be a video MediaStreamTrack");await this._updateOriginMediaStreamTrack(e,t,!0),this.updateMediaStreamTrackResolution()}sendSeiData(e){if(b((()=>{pe.reportApiInvoke(null,{name:I.LOCAL_VIDEO_SEND_SEI_DATA,options:[],tag:A.TRACER}).onSuccess("")}),this._mediaStreamTrack.id||this.getTrackId()),!u("ENABLE_VIDEO_SEI")||!u("ENABLE_ENCODED_TRANSFORM"))return void le.warning('To send/receive SEI, please call AgoraRTC.setParameter("ENABLE_VIDEO_SEI", true) before instantiate IAgoraRtcClient');if(e instanceof Uint8Array==!1)return new f(E.INVALID_PARAMS,"Invalid argument type, ILocalVideoTrack.sendSeiData() only accept Uint8Array argument.").throw();const t=this.getRTCRtpTransceiver();if(!t)return void le.warning("Video track is not published, SEI can not be send");const i=t.sender.getParameters();if(0===i.codecs.length)return;const r=i.codecs[0].mimeType.toLocaleLowerCase();"video/h264"===r?this.safeEmit("sei-to-send",e):le.warning("SEI is not supported by ".concat(r))}bindProcessorDestinationEvents(){this.processorDestination.on(nt.ON_TRACK,(async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(),await w(this,He.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await w(this,He.NEED_REPLACE_TRACK,this))}))}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(nt.ON_TRACK)}unbindProcessorContextEvents(){this.processorContext.removeAllListeners(at.REQUEST_UPDATE_CONSTRAINTS),this.processorContext.removeAllListeners(at.REQUEST_CONSTRAINTS)}},gt(Zr.prototype,"play",[fr,Er],Object.getOwnPropertyDescriptor(Zr.prototype,"play"),Zr.prototype),gt(Zr.prototype,"stop",[Sr],Object.getOwnPropertyDescriptor(Zr.prototype,"stop"),Zr.prototype),gt(Zr.prototype,"setEnabled",[yr,kr,br],Object.getOwnPropertyDescriptor(Zr.prototype,"setEnabled"),Zr.prototype),gt(Zr.prototype,"setMuted",[Ir,Ar,Rr],Object.getOwnPropertyDescriptor(Zr.prototype,"setMuted"),Zr.prototype),gt(Zr.prototype,"setSaveEncodeBitrateRatio",[wr,Dr],Object.getOwnPropertyDescriptor(Zr.prototype,"setSaveEncodeBitrateRatio"),Zr.prototype),gt(Zr.prototype,"setEncoderConfiguration",[Cr,Mr],Object.getOwnPropertyDescriptor(Zr.prototype,"setEncoderConfiguration"),Zr.prototype),gt(Zr.prototype,"getStats",[Nr],Object.getOwnPropertyDescriptor(Zr.prototype,"getStats"),Zr.prototype),gt(Zr.prototype,"setBeautyEffect",[Or,Lr],Object.getOwnPropertyDescriptor(Zr.prototype,"setBeautyEffect"),Zr.prototype),gt(Zr.prototype,"getCurrentFrameData",[Pr],Object.getOwnPropertyDescriptor(Zr.prototype,"getCurrentFrameData"),Zr.prototype),gt(Zr.prototype,"getCurrentFrameImage",[Vr],Object.getOwnPropertyDescriptor(Zr.prototype,"getCurrentFrameImage"),Zr.prototype),gt(Zr.prototype,"setBitrateLimit",[xr],Object.getOwnPropertyDescriptor(Zr.prototype,"setBitrateLimit"),Zr.prototype),gt(Zr.prototype,"setOptimizationMode",[Ur],Object.getOwnPropertyDescriptor(Zr.prototype,"setOptimizationMode"),Zr.prototype),gt(Zr.prototype,"setScalabiltyMode",[Br],Object.getOwnPropertyDescriptor(Zr.prototype,"setScalabiltyMode"),Zr.prototype),gt(Zr.prototype,"updateMediaStreamTrackResolution",[Fr],Object.getOwnPropertyDescriptor(Zr.prototype,"updateMediaStreamTrackResolution"),Zr.prototype),gt(Zr.prototype,"pipe",[Gr],Object.getOwnPropertyDescriptor(Zr.prototype,"pipe"),Zr.prototype),gt(Zr.prototype,"unpipe",[Wr],Object.getOwnPropertyDescriptor(Zr.prototype,"unpipe"),Zr.prototype),gt(Zr.prototype,"close",[Hr],Object.getOwnPropertyDescriptor(Zr.prototype,"close"),Zr.prototype),gt(Zr.prototype,"replaceTrack",[Kr],Object.getOwnPropertyDescriptor(Zr.prototype,"replaceTrack"),Zr.prototype),Zr),is=(Yr=ge({argsMap:(e,t)=>[e.getTrackId(),t]}),zr=ii(),jr=J("CameraVideoTrack","_enabledMutex"),Xr=ge({argsMap:(e,t)=>[e.getTrackId(),t]}),Qr=ii(),Jr=ge({argsMap:(e,t)=>[e.getTrackId(),t]}),qr=ii(),$r=ge({argsMap:e=>[e.getTrackId()]}),es=class e extends ts{get __className__(){return"CameraVideoTrack"}constructor(e,t,i,r,s,o){super(e,Ce(t.encoderConfig),r,s,o),_t(this,"_config",void 0),_t(this,"_originalConstraints",void 0),_t(this,"_constraints",void 0),_t(this,"_enabled",!0),_t(this,"_deviceName","default"),_t(this,"tryResumeVideoForIOS15_16WeChat",(async()=>{(W()||$())&&!ue()&&he()&&this._enabled&&!this._isClosed&&(le.debug("[".concat(this.getTrackId(),"] try capture camera media device for interrupted iOS 15 device on WeChat.")),await this.renewMediaStreamTrack())})),this._config=t,this._originalConstraints=i,this._constraints=i,this._deviceName=e.label,this._encoderConfig=Ce(this._config.encoderConfig),kt.on(ye.IOS_15_16_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),kt.on(ye.IOS_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),this.bindProcessorContextEvents()}async setDevice(e){return"string"==typeof e?this._setDeviceById(e):e.deviceId?this._setDeviceById(e.deviceId):e.facingMode?this._setDeviceByFacingModel(e.facingMode):void 0}async _setDeviceById(e){if(le.info("[".concat(this.getTrackId(),"] set device to ").concat(e)),this._enabled)try{const t=await Xt.getDeviceById(e),i={};i.video=vt({},this._constraints),i.video.deviceId={exact:e},i.video.facingMode=void 0,this._originMediaStreamTrack.stop();let r=null;try{r=await Kt(i,this.getTrackId())}catch(e){throw le.error("[".concat(this.getTrackId(),"] setDevice failed"),e.toString()),r=await Kt({video:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(r.getVideoTracks()[0],!1),e}await this._updateOriginMediaStreamTrack(r.getVideoTracks()[0],!1),this.updateMediaStreamTrackResolution(),this._deviceName=t.label,this._config.cameraId=e,this._constraints.deviceId={exact:e}}catch(e){throw le.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}else try{const t=await Xt.getDeviceById(e);this._deviceName=t.label,this._config.cameraId=e,this._constraints.deviceId={exact:e}}catch(e){throw le.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}le.info("[".concat(this.getTrackId(),"] setDevice success"))}async _setDeviceByFacingModel(e){le.info("[".concat(this.getTrackId(),"] set facingMode ").concat(e));const t={video:vt(vt({},this._constraints),{},{deviceId:void 0,facingMode:{exact:e}})};if(this._enabled){this._originMediaStreamTrack.stop();let e=null;try{e=await Kt(t,this.getTrackId())}catch(t){throw le.error("[".concat(this.getTrackId(),"] setDeviceByFacingModel failed"),t.toString()),e=await Kt({video:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!1),t}await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!1),this.updateMediaStreamTrackResolution()}this._deviceName="",this._config.facingMode=e,this._config.cameraId=void 0,this._constraints=vt({},t.video),le.info("[".concat(this.getTrackId(),"] setDeviceByFacingModel success"))}async setEnabled(e,t){if(!t){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(le.info("[".concat(this.getTrackId(),"] start setEnabled"),e),e){try{if(this.isExternalTrack)this._originMediaStreamTrack.enabled=!0;else{const e=await Kt({video:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!1)}await w(this,He.NEED_ENABLE_TRACK,this)}catch(e){throw le.error("[".concat(this.getTrackId(),"] setEnabled true error"),e.toString()),e}this.updateMediaStreamTrackResolution(),le.info("[".concat(this.getTrackId(),"] setEnabled to true success")),t||(this._enabled=!0)}else{this.isExternalTrack?this._originMediaStreamTrack.enabled=!1:(this._originMediaStreamTrack.onended=null,this._originMediaStreamTrack.stop()),t||(this._enabled=!1);try{await w(this,He.NEED_DISABLE_TRACK,this)}catch(e){throw le.error("[".concat(this.getTrackId(),"] setEnabled to false error"),e.toString()),e}le.info("[".concat(this.getTrackId(),"] setEnabled to false success"))}}async setEncoderConfiguration(e,t){if(!this._enabled)throw new f(E.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");e=Ce(e),u("USE_STANDARD_BITRATE_DEFAULT")&&(delete e.bitrateMax,delete e.bitrateMin),this._forceBitrateLimit&&(e.bitrateMax=this._forceBitrateLimit.max_bitrate||e.bitrateMax,e.bitrateMin=this._forceBitrateLimit.min_bitrate||e.bitrateMin);const i=oe(this._config);i.encoderConfig=e;const r=ui(i);(c()||C()||M())&&(r.deviceId=void 0),le.debug("[".concat(this.getTrackId(),"] setEncoderConfiguration applyConstraints"),JSON.stringify(e),JSON.stringify(r));try{await this._originMediaStreamTrack.applyConstraints(r),this.updateMediaStreamTrackResolution()}catch(e){const t=new f(E.UNEXPECTED_ERROR,e.toString());throw le.error("[".concat(this.getTrackId(),"] applyConstraints error"),t.toString()),t}this._config=i,this._constraints=r,this._originalConstraints=r,this._encoderConfig=e,-1===this._hints.indexOf(Ke.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await w(this,He.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(le)}}_getDefaultPlayerConfig(){return{mirror:!0,fit:"cover"}}onTrackEnded(){if((C()||M())&&this._enabled&&!this._isClosed&&kt.duringInterruption){const e=async()=>{kt.off(ye.IOS_INTERRUPTION_END,e),this._enabled&&!this._isClosed&&(le.debug("[".concat(this.getTrackId(),"] try capture camera media device for interrupted iOS device.")),await this.setEnabled(!1),await this.setEnabled(!0))};kt.on(ye.IOS_INTERRUPTION_END,e)}else le.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(Qe.TRACK_ENDED)}async renewMediaStreamTrack(e){const t=e||this._constraints,i=Xt.searchDeviceIdByName(this._deviceName);if(i&&!t.deviceId&&(t.deviceId={exact:i}),this._enabled){const e=await Kt({video:t},this.getTrackId());this._constraints=t,await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!0),this.updateMediaStreamTrackResolution()}}close(){super.close(),kt.off(ye.IOS_15_16_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),kt.off(ye.IOS_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat)}clone(t){let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],r=this._encoderConfig;t&&(r=vt(vt({},r),Ce(t))),r=de(r);const s=k(8,"track-cam-cloned-"),o=new e(i?this._mediaStreamTrack.clone():this._mediaStreamTrack,de(vt(vt({},this._config),{},{encoderConfig:r})),de(this._constraints),de(this._scalabilityMode),this._optimizationMode,s);return t&&r&&o.setEncoderConfiguration(r),le.debug("clone track from ".concat(this.getTrackId()," to ").concat(s,", clone ").concat(i)),o}bindProcessorContextEvents(){this.processorContext.on(at.REQUEST_UPDATE_CONSTRAINTS,(async(e,t,i)=>{try{const i=Object.assign({},this._originalConstraints,...e);await this.renewMediaStreamTrack(i),t()}catch(e){i(e)}})),this.processorContext.on(at.REQUEST_CONSTRAINTS,(async e=>{e(this._originMediaStreamTrack.getSettings())}))}},gt(es.prototype,"setDevice",[Yr,zr],Object.getOwnPropertyDescriptor(es.prototype,"setDevice"),es.prototype),gt(es.prototype,"setEnabled",[jr,Xr,Qr],Object.getOwnPropertyDescriptor(es.prototype,"setEnabled"),es.prototype),gt(es.prototype,"setEncoderConfiguration",[Jr,qr],Object.getOwnPropertyDescriptor(es.prototype,"setEncoderConfiguration"),es.prototype),gt(es.prototype,"close",[$r],Object.getOwnPropertyDescriptor(es.prototype,"close"),es.prototype),es);function rs(e){const t=k(8,"track-cus-"),i=pe.reportApiInvoke(null,{id:t,tag:A.TRACER,name:I.CREATE_CUSTOM_AUDIO_TRACK,options:[e]}),r=new dr(e.mediaStreamTrack,e.encoderConfig?Le(e.encoderConfig):{},t,!1);return le.info("create custom audio track success with config",e,"trackId",r.getTrackId()),i.onSuccess(r.getTrackId()),r}async function ss(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const t=k(8,"track-mic-"),i=pe.reportApiInvoke(null,{id:t,tag:A.TRACER,name:I.CREATE_MIC_AUDIO_TRACK,options:[e]}),r=mi(e);let s=null;le.info("start create microphone audio track with config",JSON.stringify(e),"trackId",t);try{s=(await Kt({audio:r},t)).getAudioTracks()[0]||null}catch(e){throw i.onError(e),e}if(!s){const e=new f(E.UNEXPECTED_ERROR,"can not find track in media stream");return i.onError(e),e.throw(le)}const o=new ur(s,e,r,t);return i.onSuccess(o.getTrackId()),le.info("create microphone audio track success, trackId:",t),o}async function os(e){var t;const{cacheOnlineFile:i,encoderConfig:r}=e;let{source:s}=e;const o={source:s instanceof AudioBuffer?"AudioBuffer":s instanceof File?null!==(t=File.name)&&void 0!==t?t:"File":s,cacheOnlineFile:i,encoderConfig:r},n=k(8,"track-buf-"),a=pe.reportApiInvoke(null,{id:n,tag:A.TRACER,name:I.CREATE_BUFFER_AUDIO_TRACK,options:[o]});if(u("DISABLE_WEBAUDIO"))throw new f(E.NOT_SUPPORTED,"can not create BufferSourceAudioTrack when WebAudio disabled");le.info("start create buffer source audio track with config",JSON.stringify(o),"trackId",n);const c=s;if(!(s instanceof AudioBuffer))try{s=await async function(e,t){let i=null;if("string"==typeof e){const t=mr.get(e);if(t)return le.debug("use cached audio resource: ",e),t;try{i=(await ee((()=>_e.get(e,{responseType:"arraybuffer"})),void 0,void 0,{maxRetryCount:3})).data}catch(e){throw new f(E.FETCH_AUDIO_FILE_FAILED,e.toString())}}else{const t=new Promise(((t,i)=>{const r=new FileReader;r.onload=e=>{e.target?t(e.target.result):i(new f(E.READ_LOCAL_AUDIO_FILE_ERROR))},r.onerror=()=>{i(new f(E.READ_LOCAL_AUDIO_FILE_ERROR))},r.readAsArrayBuffer(e)}));i=await t}const r=await wt(i);return"string"==typeof e&&t&&mr.set(e,r),r}(s,i)}catch(e){return a.onError(e),e.throw(le)}const d=new pr(s),h=new hr(c,d,r?Le(r):{},n);return le.info("create buffer source audio track success, trackId:",n),a.onSuccess(h.getTrackId()),h}function ns(e){const t=new lr;return e.forEach((e=>t.addAudioTrack(e))),t}function as(e){const t=k(8,"track-cus-"),i=pe.reportApiInvoke(null,{id:t,tag:A.TRACER,name:I.CREATE_CUSTOM_VIDEO_TRACK,options:[e]});u("USE_STANDARD_BITRATE_DEFAULT")&&(delete e.bitrateMax,delete e.bitrateMin);const r=new ts(e.mediaStreamTrack,{width:e.width,height:e.height,frameRate:e.frameRate,bitrateMax:e.bitrateMax,bitrateMin:e.bitrateMin},e.scalabiltyMode?Ne(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,t,[Ke.CUSTOM_TRACK]);return i.onSuccess(r.getTrackId()),le.info("create custom video track success with config",e,"trackId",r.getTrackId()),r}async function cs(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const t=u("CAMERA_CAPTURE_CONFIG"),i=k(8,"track-cam-"),r=pe.reportApiInvoke(null,{id:i,tag:A.TRACER,name:I.CREATE_CAM_VIDEO_TRACK,options:[vt({},e),t]});t&&(e.encoderConfig=t);const s=ui(e);let o=null;le.info("start create camera video track with config",JSON.stringify(e),"trackId",i);try{o=(await Kt({video:s},i)).getVideoTracks()[0]||null}catch(e){throw r.onError(e),e}if(!o){const e=new f(E.UNEXPECTED_ERROR,"can not find track in media stream");return r.onError(e),e.throw(le)}if(e.optimizationMode&&hs(i,o,e,Ce(e.encoderConfig)),u("USE_STANDARD_BITRATE_DEFAULT")){const t=Ce(e.encoderConfig);e.encoderConfig=t,delete t.bitrateMax,delete t.bitrateMin}const n=new is(o,e,s,e.scalabiltyMode?Ne(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,i);return r.onSuccess(n.getTrackId()),le.info("create camera video success, trackId:",i),n}async function ds(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=u("CAMERA_CAPTURE_CONFIG"),r=k(8,"track-mic-"),s=k(8,"track-cam-"),o=pe.reportApiInvoke(null,{id:"".concat(r,"-").concat(s),tag:A.TRACER,name:I.CREATE_MIC_AND_CAM_TRACKS,options:[e,t,i]});i&&(t.encoderConfig=i);const n=ui(t),a=mi(e);let c=null,d=null;le.info("start create camera video track(".concat(s,") and microphone audio track(").concat(r,") with config, audio: ").concat(JSON.stringify(e),", video: ").concat(JSON.stringify(t)));try{const e=await Kt({audio:a,video:n},"".concat(r,"-").concat(s));c=e.getAudioTracks()[0],d=e.getVideoTracks()[0]}catch(e){throw o.onError(e),e}if(!c||!d){const e=new f(E.UNEXPECTED_ERROR,"can not find tracks in media stream");return o.onError(e),e.throw(le)}if(t.optimizationMode&&hs(s,d,t,Ce(t.encoderConfig)),u("USE_STANDARD_BITRATE_DEFAULT")){const e=Ce(t.encoderConfig);t.encoderConfig=e,delete e.bitrateMax,delete e.bitrateMin}const h=new ur(c,e,a,r),l=new is(d,t,n,t.scalabiltyMode?Ne(t.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},t.optimizationMode,s);return o.onSuccess([h.getTrackId(),l.getTrackId()]),le.info("create camera video track(".concat(s,") and microphone audio track(").concat(r,") success")),[h,l]}async function us(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"disable";const i="object"==typeof t?pi(t):void 0;i&&(t="auto");const r=k(8,"track-scr-v-"),s=pe.reportApiInvoke(null,{id:r,tag:A.TRACER,name:I.CREATE_SCREEN_VIDEO_TRACK,options:[vt({},e),t]});e.encoderConfig?"string"==typeof e.encoderConfig||e.encoderConfig.width&&e.encoderConfig.height||(e.encoderConfig.width={max:1920},e.encoderConfig.height={max:1080}):e.encoderConfig="1080p_2";const o=hi(e);let n=null,a=null;const c=fe();if(!c.supportShareAudio&&"enable"===t){const e=new f(E.NOT_SUPPORTED,"your browser or platform is not support share-screen with audio");return s.onError(e),e.throw(le)}le.info("start create screen video track with config",e,"withAudio",t,"trackId",r);const d=c.supportShareAudio&&"disable"!==t;try{const e=await Kt({screen:o,screenAudio:d?i||!0:void 0},r);n=e.getVideoTracks()[0]||null,a=e.getAudioTracks()[0]||null}catch(e){throw s.onError(e),e}if(!n){const e=new f(E.UNEXPECTED_ERROR,"can not find track in media stream");return s.onError(e),e.throw(le)}if(!a&&"enable"===t){n&&n.stop();const e=new f(E.SHARE_AUDIO_NOT_ALLOWED);return s.onError(e),e.throw(le)}if(e.optimizationMode||(e.optimizationMode="detail"),e.optimizationMode){hs(r,n,e,e.encoderConfig&&Me(e.encoderConfig)||void 0),e.encoderConfig&&"string"!=typeof e.encoderConfig&&(e.encoderConfig.bitrateMin=e.encoderConfig.bitrateMax)}const u=new ts(n,e.encoderConfig?Me(e.encoderConfig):{},e.scalabiltyMode?Ne(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,r,[Ke.SCREEN_TRACK]);if(!a)return s.onSuccess(u.getTrackId()),le.info("create screen video track success","video:",u.getTrackId()),u;const h=new dr(a,void 0,k(8,"track-scr-a-"),!1);return s.onSuccess([u.getTrackId(),h.getTrackId()]),le.info("create screen video track success","video:",u.getTrackId(),"audio:",h.getTrackId()),[u,h]}function hs(e,t,i,r){i.optimizationMode&&(r&&r.width&&r.height?(i.encoderConfig=vt(vt({},r),{},{bitrateMin:r.bitrateMin,bitrateMax:r.bitrateMax}),"motion"!==i.optimizationMode&&"detail"!==i.optimizationMode||(t.contentHint=i.optimizationMode,t.contentHint===i.optimizationMode?le.debug("[".concat(e,"] set content hint to"),i.optimizationMode):le.debug("[".concat(e,"] set content hint failed")))):le.warning("[".concat(e,"] can not apply optimization mode bitrate config, no encoderConfig")))}var ls,ps,ms,gs,_s,Ts,vs,fs,Es,Ss,ys,ks;class bs extends ft{getUserId(){return this._userId}constructor(e,t,i,r){super(e,"track-".concat(e.kind,"-").concat(t,"-").concat(r.clientId,"_").concat(k(5,""))),_t(this,"_userId",void 0),_t(this,"_uintId",void 0),_t(this,"_isDestroyed",!1),_t(this,"store",void 0),_t(this,"processor",void 0),_t(this,"processorContext",void 0),this._userId=t,this._uintId=i,this.store=r}_updateOriginMediaStreamTrack(e){this._originMediaStreamTrack=e,this._mediaStreamTrack=e,this._updatePlayerSource(),this.processor&&this.processor.updateInput({track:this._originMediaStreamTrack,context:this.processorContext})}_destroy(){this._isDestroyed=!0,le.info("[".concat(this.getTrackId(),"] is destroyed")),this.stop(),super.close()}getProcessorStats(){return this.processorContext.gatherStats()}getProcessorUsage(){return this.processorContext.gatherUsage()}}let Is=(ls=ge({argsMap:(e,t,i)=>[e.getTrackId(),"string"==typeof t?t:t instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement",i]}),ps=ge({argsMap:e=>[e.getTrackId()]}),ms=ge({argsMap:(e,t)=>[e.getTrackId(),t.name]}),gs=ge({argsMap:e=>[e.getTrackId()]}),gt((_s=class extends bs{get isPlaying(){return!(!this._player||this._player.videoElementStatus!==ht.PLAYING)}get __className__(){return"RemoteVideoTrack"}constructor(e,t,i,r){super(e,t,i,r),_t(this,"_videoVisibleTimer",null),_t(this,"_previousVideoVisibleStatus",void 0),_t(this,"_clearPreviousVideoVisibleStatus",(()=>this._previousVideoVisibleStatus=void 0)),_t(this,"trackMediaType",qe.VIDEO),_t(this,"_videoWidth",void 0),_t(this,"_videoHeight",void 0),_t(this,"_player",void 0),_t(this,"processorDestination",void 0),_t(this,"processorContext",void 0),this.updateMediaStreamTrackResolution(),this.processorContext=new si(this.getTrackId(),"remote"),this.processorDestination=new ri(this.processorContext),this.bindProcessorDestinationEvents()}getStats(){b((()=>{le.warning("[deprecated] RemoteVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteVideoStats instead")}),"remoteVideoTrackGetStatsWarning");return q(this,He.GET_STATS)||vt({},ot)}play(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("string"==typeof e){const t=document.getElementById(e);t?e=t:(le.warning("[".concat(this.getTrackId(),'] can not find "#').concat(e,'" element, use document.body')),e=document.body)}le.debug("[".concat(this.getTrackId(),"] start video playback in ").concat(e instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement"),JSON.stringify(t));const i=vt(vt({fit:"cover"},t),{},{trackId:this.getTrackId(),element:e});this._player?this._player.updateConfig(i):(e instanceof HTMLVideoElement?this._player=new _r(i):this._player=new vr(i),this._player.updateVideoTrack(this._mediaStreamTrack),this._player.onFirstVideoFrameDecoded=()=>{this.store.subscribe(this.getUserId(),"video",void 0,void 0,Date.now()),this.safeEmit(Je.FIRST_FRAME_DECODED)},this._player.onVideoStateChanged=e=>{this.safeEmit(Je.VIDEO_STATE_CHANGED,e)}),this._player.play(this.store.sessionId||void 0),this._videoVisibleTimer&&window.clearInterval(this._videoVisibleTimer),this._clearPreviousVideoVisibleStatus(),this._videoVisibleTimer=window.setInterval((()=>{try{const e=this.getVideoElementVisibleStatus();this.safeEmit(Je.VIDEO_ELEMENT_VISIBLE_STATUS,e)}catch(e){}}),u("CHECK_VIDEO_VISIBLE_INTERVAL"))}stop(){this._player&&(this._videoVisibleTimer&&(window.clearInterval(this._videoVisibleTimer),this._videoVisibleTimer=null),this._clearPreviousVideoVisibleStatus(),this._player.destroy(),this._player=void 0,le.debug("[".concat(this.getTrackId(),"] stop video playback")))}getCurrentFrameData(){return this._player?this._player.getCurrentFrame():new ImageData(2,2)}updateMediaStreamTrackResolution(){di(this._originMediaStreamTrack).then((e=>{let[t,i]=e;this._videoHeight=i,this._videoWidth=t})).catch(K)}_updatePlayerSource(){le.debug("[".concat(this.getTrackId(),"] update player source track")),this._player&&this._player.updateVideoTrack(this._mediaStreamTrack)}getVideoElementVisibleStatus(){try{var e,t;const i=null==this||null===(e=this._player)||void 0===e?void 0:e.getContainerElement(),r={track:this,element:null==this||null===(t=this._player)||void 0===t?void 0:t.getVideoElement(),slot:null==i?void 0:i.parentElement},{element:s,slot:o}=r;if(this.isPlaying&&s instanceof HTMLVideoElement&&o instanceof HTMLElement){const e=ce.checkOneElementVisible(s),t=Object.assign({},e);if(t.visible!==this._previousVideoVisibleStatus){this._previousVideoVisibleStatus=t.visible;const e=pe.reportApiInvoke(null,{tag:A.TRACER,name:I.REMOTE_VIDEO_TRACK_GET_VIDEO_VISIBLE,options:[this.getTrackId()]});t.visible?e.onSuccess("Video is visible"):e.onSuccess("Invisible because of ".concat(t.reason))}return t}return}catch(e){throw new f(E.GET_VIDEO_ELEMENT_VISIBLE_ERROR,e.message)}}pipe(e){if(this.processor===e)return e;if(e._source)throw new f(E.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,context:this.processorContext}),e}unpipe(){if(!this.processor)return;const e=this.processor;this.processor._source=void 0,this.processor=void 0,e.reset()}bindProcessorDestinationEvents(){this.processorDestination.on(nt.ON_TRACK,(async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource()):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource())}))}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(nt.ON_TRACK)}_destroy(){super._destroy(),this.unbindProcessorDestinationEvents()}_onSei(e){this.emit(Xe.SEI_RECEIVED,e)}}).prototype,"play",[ls],Object.getOwnPropertyDescriptor(_s.prototype,"play"),_s.prototype),gt(_s.prototype,"stop",[ps],Object.getOwnPropertyDescriptor(_s.prototype,"stop"),_s.prototype),gt(_s.prototype,"pipe",[ms],Object.getOwnPropertyDescriptor(_s.prototype,"pipe"),_s.prototype),gt(_s.prototype,"unpipe",[gs],Object.getOwnPropertyDescriptor(_s.prototype,"unpipe"),_s.prototype),_s),As=(Ts=ge({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),vs=ge({argsMap:(e,t)=>[e.getTrackId(),t]}),fs=ge({argsMap:e=>[e.getTrackId()]}),Es=ge({argsMap:e=>[e.getTrackId()]}),Ss=ge({argsMap:(e,t)=>[e.getTrackId(),t.name]}),ys=ge({argsMap:e=>[e.getTrackId()]}),gt((ks=class extends bs{get isPlaying(){return this._useAudioElement?ti.isPlaying(this.getTrackId()):this._source.isPlayed}get __className__(){return"RemoteAudioTrack"}constructor(e,t,i,r){super(e,t,i,r),_t(this,"trackMediaType",qe.AUDIO),_t(this,"_source",void 0),_t(this,"_useAudioElement",!0),_t(this,"_volume",100),_t(this,"processorContext",void 0),_t(this,"processorDestination",void 0),_t(this,"_played",!1),_t(this,"_bypassWebAudio",!1),u("DISABLE_WEBAUDIO")?(this._source=new ai,this._bypassWebAudio=!0,this._useAudioElement=!0):(this._source=new xt(e,!0),u("REMOTE_AUDIO_TRACK_USES_WEB_AUDIO")&&(this._useAudioElement=!1)),this._source.once($e.RECEIVE_TRACK_BUFFER,(()=>{this.safeEmit(Je.FIRST_FRAME_DECODED)})),this.processorContext=new ni(this._source.context,this.getTrackId(),"remote"),this.processorDestination=new oi(this.processorContext),this.bindProcessorDestinationEvents(),this._source.on($e.UPDATE_SOURCE,(()=>{this.processor&&this.processor.updateInput({node:this._source.processSourceNode,context:this.processorContext})}))}setAudioFrameCallback(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:4096;if(!e)return this._source.removeAllListeners($e.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(t),this._source.removeAllListeners($e.ON_AUDIO_BUFFER),this._source.on($e.ON_AUDIO_BUFFER,(t=>e(t)))}setVolume(e){this._volume=e,this._useAudioElement?ti.setVolume(this.getTrackId(),e):this._source.setVolume(e/100)}async setPlaybackDevice(e){if(!this._useAudioElement||!Ee())throw new f(E.NOT_SUPPORTED,"your browser does not support setting the audio output device");await ti.setSinkID(this.getTrackId(),e)}getVolumeLevel(){return this._source.getAccurateVolumeLevel()}getStats(){b((()=>{le.warning("[deprecated] RemoteAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteAudioStats instead")}),"remoteAudioTrackGetStatsWarning");return q(this,He.GET_STATS)||vt({},rt)}play(){le.debug("[".concat(this.getTrackId(),"] start audio playback")),this._played=!0,this._useAudioElement?(le.debug("[".concat(this.getTrackId(),"] use audio element to play")),ti.play(this._mediaStreamTrack,this.getTrackId(),this._volume,this.store.sessionId||void 0)):this._source.play()}stop(){le.debug("[".concat(this.getTrackId(),"] stop audio playback")),this._played=!1,this._useAudioElement?ti.stop(this.getTrackId()):this._source.stop()}_destroy(){super._destroy(),this._played=!1,this.unbindProcessorDestinationEvents(),this._source.destroy()}_isFreeze(){return this._source.isFreeze}_updatePlayerSource(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];le.debug("[".concat(this.getTrackId(),"] update player source track")),e&&this._source.updateTrack(this._mediaStreamTrack),this._useAudioElement&&ti.updateTrack(this.getTrackId(),this._mediaStreamTrack)}pipe(e){if(this._bypassWebAudio)throw new f(E.NOT_SUPPORTED,"can not pipe extension when WebAudio disabled");if(this.processor===e)return e;if(e._source)throw new f(E.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,node:this._source.processSourceNode,context:this.processorContext}),e}unpipe(){var e;if(this._bypassWebAudio)throw new f(E.NOT_SUPPORTED,"can not unpipe extension when WebAudio disabled");if(!this.processor)return;const t=this.processor;null===(e=this._source.processSourceNode)||void 0===e||e.disconnect(),this.processor._source=!1,this.processor=void 0,t.reset()}bindProcessorDestinationEvents(){this.processorDestination.on(nt.ON_TRACK,(async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(!1),this._source.processedNode=this._source.createMediaStreamSourceNode(e)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource())})),this.processorDestination.on(nt.ON_NODE,(e=>{this._source.processedNode=e;const t=!e;this._useAudioElement!==t&&(this._played?(this.stop(),this._useAudioElement=t,this.play()):this._useAudioElement=t)}))}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(nt.ON_TRACK),this.processorDestination.removeAllListeners(nt.ON_NODE)}}).prototype,"setVolume",[Ts],Object.getOwnPropertyDescriptor(ks.prototype,"setVolume"),ks.prototype),gt(ks.prototype,"setPlaybackDevice",[vs],Object.getOwnPropertyDescriptor(ks.prototype,"setPlaybackDevice"),ks.prototype),gt(ks.prototype,"play",[fs],Object.getOwnPropertyDescriptor(ks.prototype,"play"),ks.prototype),gt(ks.prototype,"stop",[Es],Object.getOwnPropertyDescriptor(ks.prototype,"stop"),ks.prototype),gt(ks.prototype,"pipe",[Ss],Object.getOwnPropertyDescriptor(ks.prototype,"pipe"),ks.prototype),gt(ks.prototype,"unpipe",[ys],Object.getOwnPropertyDescriptor(ks.prototype,"unpipe"),ks.prototype),ks);const Rs=new class extends y{get visibility(){return document.visibilityState}get lastHiddenTime(){return this._lastHiddenTime}get lastVisibleTime(){return this._lastVisibleTime}constructor(){super(),_t(this,"_lastHiddenTime",0),_t(this,"_lastVisibleTime",0),document.addEventListener("visibilitychange",(()=>{"hidden"===document.visibilityState?this._lastHiddenTime=performance.now():this._lastVisibleTime=performance.now(),le.debug("current web page is ".concat(document.visibilityState)),this.emit("VISIBILITY_CHANGE",document.visibilityState)}))}};class ws extends y{constructor(e,t){super(),_t(this,"trackMediaType",qe.DATA),_t(this,"_version",1),_t(this,"_type",3),_t(this,"_config",void 0),_t(this,"_originDataChannel",void 0),_t(this,"_dataStreamPacketHeader",new ArrayBuffer(4)),_t(this,"_dataStreamPacketHandler",{serialize:e=>e,deserialize:e=>e}),_t(this,"_datachannelEventMap",new Map),this._config=e,t&&(this._originDataChannel=t,this._bandDataChannelEvents(t)),this._initPacketHeader()}useDataStream(e){this._dataStreamPacketHandler=e}get id(){return this._config.id}get ordered(){return this._config.ordered}get maxRetransmits(){return u("DATASTREAM_MAX_RETRANSMITS")}get metadata(){return this._config.metadata}get readyState(){var e,t;return null!==(e=null===(t=this._originDataChannel)||void 0===t?void 0:t.readyState)&&void 0!==e?e:"connecting"}get _originDataChannelId(){var e,t;return null!==(e=null===(t=this._originDataChannel)||void 0===t?void 0:t.id)&&void 0!==e?e:null}getChannelId(){return this.id}getConfig(){return this._config}_close(){this._originDataChannel&&(this._unbindDataChannelEvents(this._originDataChannel),this._originDataChannel=void 0)}async _waitTillOpen(){return new Promise(((e,t)=>{if(this._originDataChannel){"open"===this._originDataChannel.readyState&&e();const i=setTimeout((()=>{var e;t(new f(E.DATACHANNEL_CONNECTION_TIMEOUT,"Cannot create datachannel, id: ".concat(null===(e=this._originDataChannel)||void 0===e?void 0:e.id)))}),1e4);this._originDataChannel.onopen=()=>{clearTimeout(i),this._originDataChannel&&this._bandDataChannelEvents(this._originDataChannel),e()},this._originDataChannel.onerror=()=>{throw clearTimeout(i),new f(E.DATACHANNEL_CONNECTION_TIMEOUT)}}else t(new f(E.DATACHANNEL_CONNECTION_TIMEOUT,"cannot find dataChannel"))}))}_updateOriginDataChannel(e){this._originDataChannel=e,this._bandDataChannelEvents(e)}_initPacketHeader(){const e=new DataView(this._dataStreamPacketHeader);e.setUint16(0,this._version),e.setUint8(2,this._type),e.setUint8(3,this._config.id)}_bandDataChannelEvents(e){this._unbindDataChannelEvents(e),[mt.OPEN,mt.CLOSE,mt.ERROR].forEach((t=>{const i=()=>{this.emit(t)};this._datachannelEventMap.set(t,i),e.addEventListener(t,i)}))}_unbindDataChannelEvents(e){Array.from(this._datachannelEventMap.entries()).forEach((t=>{let[i,r]=t;e.removeEventListener(i,r)})),this._datachannelEventMap.clear()}}class Ds extends ws{constructor(e){super(e),_t(this,"_messageListener",void 0),this._messageListener=e=>{if(e.data.byteLength<this._dataStreamPacketHeader.byteLength)throw Error("invalid byteLength: the byte length must exceed "+this._dataStreamPacketHeader.byteLength);const t=e.data.slice(0,this._dataStreamPacketHeader.byteLength),i=new DataView(t).getUint8(3);if(i!==this.id)return void(u("SHOW_DATASTREAM2_LOG")&&le.debug("invalid datachannel id: ".concat(i," !== ").concat(this.id)));let r=e.data.slice(this._dataStreamPacketHeader.byteLength);r=this._dataStreamPacketHandler.deserialize(r),this.emit(mt.MESSAGE,r)}}_updateOriginDataChannel(e){super._updateOriginDataChannel(e),this._bandRemoteDataChannelEvents()}_close(){this._originDataChannel&&(this._originDataChannel.removeEventListener("message",this._messageListener),super._close())}_bandRemoteDataChannelEvents(){this._originDataChannel&&this._originDataChannel.addEventListener("message",this._messageListener)}}class Cs extends ws{send(e){if(this._originDataChannel){let t=e;t=this._dataStreamPacketHandler.serialize(e);const i=new Uint8Array(this._dataStreamPacketHeader.byteLength+t.byteLength);i.set(new Uint8Array(this._dataStreamPacketHeader),0),i.set(new Uint8Array(t),this._dataStreamPacketHeader.byteLength),this._originDataChannel.send(i.buffer)}}}function Ms(){const e=new Blob([atob("ZnVuY3Rpb24gdCh0LGUsbil7bGV0IGE9bmV3IFVpbnQ4QXJyYXkodCxlLG4pLG89W10scj0wO2Zvcig7by5sZW5ndGg8bjspciszPG4mJjA9PT1hW3JdJiYwPT09YVtyKzFdJiYzPT09YVtyKzJdJiYoMD09PWFbciszXXx8MT09PWFbciszXXx8Mj09PWFbciszXXx8Mz09PWFbciszXSk/KG8ucHVzaChhW3JdLGFbcisxXSxhW3IrM10pLHIrPTQpOihvLnB1c2goYVtyXSkscisrKTtyZXR1cm4gbmV3IFVpbnQ4QXJyYXkobyl9ZnVuY3Rpb24gZSh0LGUpe2NvbnN0IG49ZnVuY3Rpb24odCl7Y29uc3QgZT10Lmxlbmd0aDtsZXQgbj1bXSxhPTA7Zm9yKDthPGU7KWErMjxlJiYwPT09dFthXSYmMD09PXRbYSsxXSYmKDA9PT10W2ErMl18fDE9PT10W2ErMl18fDI9PT10W2ErMl18fDM9PT10W2ErMl0pPyhuLnB1c2godFthXSx0W2ErMV0sMyx0W2ErMl0pLGErPTMpOihuLnB1c2godFthXSksYSsrKTtyZXR1cm4gbmV3IFVpbnQ4QXJyYXkobil9KGUpLGE9bi5sZW5ndGgsbz1NYXRoLmZsb29yKGEvMjU1KSxyPWElMjU1LHM9bmV3IFVpbnQ4QXJyYXkoNitvKzErYSt0LmJ5dGVMZW5ndGgpO3NbMF09MCxzWzFdPTAsc1syXT0wLHNbM109MSxzWzRdPTYsc1s1XT0xMDE7bGV0IGk9MDtmb3IoO2k8bzspc1s2K2ldPTI1NSxpKys7cmV0dXJuIHNbNitpXT1yLGkrKyxzLnNldChuLDYraSkscy5zZXQobmV3IFVpbnQ4QXJyYXkodCksNitpK2EpLHMuYnVmZmVyfWNvbnN0IG49NzEsYT0xLG89MixyPTEscz0yO3ZhciBpOyFmdW5jdGlvbih0KXt0W3QuQVVESU9fTEVWRUw9MV09IkFVRElPX0xFVkVMIix0W3QuTUVUQURBVEE9Ml09Ik1FVEFEQVRBIix0W3QuQVVESU9fNjRfQklUX1BUUz0zXT0iQVVESU9fNjRfQklUX1BUUyJ9KGl8fChpPXt9KSk7bmF2aWdhdG9yLnVzZXJBZ2VudC5pbmRleE9mKCJTYWZhcmkiKT4tMSYmLTE9PT1uYXZpZ2F0b3IudXNlckFnZW50LmluZGV4T2YoIkNocm9tZSIpJiYoc2VsZi5vbnJ0Y3RyYW5zZm9ybT1mPT57Y29uc3QgdT1mLnRyYW5zZm9ybWVyO2xldCBkPVtdLGw9W107dS5vcHRpb25zLnBvcnQub25tZXNzYWdlPXQ9Pnt0LmRhdGEuc2VpJiZkLnB1c2godC5kYXRhLnNlaSksdC5kYXRhLm1ldGFkYXRhJiZsLnB1c2godC5kYXRhLm1ldGFkYXRhKX0sc2VsZi5wb3N0TWVzc2FnZSgic3RhcnRlZCIpO2NvbnN0IGc9dS5yZWFkYWJsZS5nZXRSZWFkZXIoKSxjPXUud3JpdGFibGUuZ2V0V3JpdGVyKCk7InNlaS1yeCI9PT11Lm9wdGlvbnMubmFtZT9mdW5jdGlvbiBlKG4pe2cucmVhZCgpLnRoZW4oKGE9PntpZighYS5kb25lKXtpZihhLnZhbHVlIGluc3RhbmNlb2YgUlRDRW5jb2RlZFZpZGVvRnJhbWUpe2NvbnN0IGU9ZnVuY3Rpb24oZSl7Y29uc3Qgbj1uZXcgRGF0YVZpZXcoZS5kYXRhKTtsZXQgYT0wO2Zvcig7YSs0PGUuZGF0YS5ieXRlTGVuZ3RoOyl7aWYoMD09PW4uZ2V0VWludDgoYSswKSYmMD09PW4uZ2V0VWludDgoYSsxKSYmMD09PW4uZ2V0VWludDgoYSsyKSYmMT09PW4uZ2V0VWludDgoYSszKSYmNj09PW4uZ2V0VWludDgoYSs0KSl7bGV0IG89YSs2LHI9MCxzPTA7Zm9yKDsyNTU9PT0ocz1uLmdldFVpbnQ4KG8rKykpOylyKz0yNTU7cis9cztjb25zdCBpPXQoZS5kYXRhLG8scik7cmV0dXJuIG5ldyBVaW50OEFycmF5KGkpfWErK31yZXR1cm4gbnVsbH0oYS52YWx1ZSk7ZSYmbi5vcHRpb25zLnBvcnQucG9zdE1lc3NhZ2Uoe3NlaTplfSl9Yy53cml0ZShhLnZhbHVlKSxuLm9wdGlvbnMucG9ydC5wb3N0TWVzc2FnZSh7dHJhbnNmb3JtZWQ6ITB9KSxlKG4pfX0pKX0odSk6InNlaS10eCI9PT11Lm9wdGlvbnMubmFtZT9mdW5jdGlvbiB0KG4pe2cucmVhZCgpLnRoZW4oKGE9PntpZighYS5kb25lKXtpZihhLnZhbHVlIGluc3RhbmNlb2YgUlRDRW5jb2RlZFZpZGVvRnJhbWUpe2NvbnN0IHQ9ZC5zaGlmdCgpO3QmJihhLnZhbHVlLmRhdGE9ZShhLnZhbHVlLmRhdGEsdCkpfWMud3JpdGUoYS52YWx1ZSksbi5vcHRpb25zLnBvcnQucG9zdE1lc3NhZ2Uoe3RyYW5zZm9ybWVkOiEwfSksdChuKX19KSl9KHUpOiJhdWRpby1tZXRhZGF0YS1yeCI9PT11Lm9wdGlvbnMubmFtZT9mdW5jdGlvbiB0KGUpe2cucmVhZCgpLnRoZW4oKGY9PntpZighZi5kb25lKXtpZihmLnZhbHVlIGluc3RhbmNlb2YgUlRDRW5jb2RlZEF1ZGlvRnJhbWUpe2NvbnN0IHQ9ZnVuY3Rpb24odCxlPSExKXtjb25zdCBmPXQuZ2V0VWludDgoMCk7aWYoZiE9PW4pcmV0dXJuO2NvbnN0IHU9dC5nZXRVaW50MTYoMSksZD1hK28rdSxsPW5ldyBVaW50OEFycmF5KHQuYnl0ZUxlbmd0aC1kKTtsLnNldChuZXcgVWludDhBcnJheSh0LmJ1ZmZlcixkLHQuYnl0ZUxlbmd0aC1kKSk7Y29uc3QgZz17bTpmLHRsdkxlbjp1LHRsdjpbXSxmcmFtZTpsfTtsZXQgYz1hK287Zm9yKDtjPGQ7KXtjb25zdCBuPXQuZ2V0VWludDgoYyksYT10LmdldFVpbnQxNihjK3IpLG89citzO2lmKG49PT1pLkFVRElPX0xFVkVMKXtsZXQgcj10LmdldFVpbnQ4KGMrbyk7Zm9yKGxldCBlPTE7ZTxhO2UrKylyPXI8PDh8dC5nZXRVaW50OChjK28rZSk7Zy50bHYucHVzaCh7dGFnOm4sbGVuZ3RoOmEsdmFsdWU6ZT8xMjdecj4+MToxMjcmcn0pfWVsc2UgaWYobj09PWkuTUVUQURBVEF8fG49PT1pLkFVRElPXzY0X0JJVF9QVFMpe2NvbnN0IGU9bmV3IFVpbnQ4QXJyYXkoYSk7Zm9yKGxldCBuPTA7bjxhO24rKyllW25dPXQuZ2V0VWludDgoYytvK24pO2cudGx2LnB1c2goe3RhZzpuLGxlbmd0aDphLHZhbHVlOmV9KX1jKz1vK2F9cmV0dXJuIGd9KG5ldyBEYXRhVmlldyhmLnZhbHVlLmRhdGEpKTtpZih0KXtjb25zdCBuPXQudGx2LmZpbmQoKHQ9PnQudGFnPT09aS5NRVRBREFUQXx8dC50YWc9PT1pLkFVRElPXzY0X0JJVF9QVFMpKTtuJiZuLnZhbHVlIGluc3RhbmNlb2YgVWludDhBcnJheSYmZS5vcHRpb25zLnBvcnQucG9zdE1lc3NhZ2Uoe21ldGFkYXRhOm4udmFsdWV9KSxmLnZhbHVlLmRhdGE9dC5mcmFtZS5idWZmZXJ9fWMud3JpdGUoZi52YWx1ZSksZS5vcHRpb25zLnBvcnQucG9zdE1lc3NhZ2Uoe3RyYW5zZm9ybWVkOiEwfSksdChlKX19KSl9KHUpOiJhdWRpby1tZXRhZGF0YS10eCI9PT11Lm9wdGlvbnMubmFtZSYmZnVuY3Rpb24gdChlKXtnLnJlYWQoKS50aGVuKChmPT57aWYoIWYuZG9uZSl7aWYoZS5vcHRpb25zLnBvcnQucG9zdE1lc3NhZ2Uoe2dldE1ldGFkYXRhOiEwfSksZi52YWx1ZSBpbnN0YW5jZW9mIFJUQ0VuY29kZWRBdWRpb0ZyYW1lKXtjb25zdCB0PWwuc2hpZnQoKTt0JiYoZi52YWx1ZS5kYXRhPWZ1bmN0aW9uKHQsZSxpKXtjb25zdCBmPWkuYnl0ZUxlbmd0aCx1PWYrcitzLGQ9YStvK3UsbD1uZXcgQXJyYXlCdWZmZXIodC5ieXRlTGVuZ3RoK2QpLGc9bmV3IERhdGFWaWV3KGwpO2cuc2V0VWludDgoMCxuKSxnLnNldFVpbnQxNigxLHUpLGcuc2V0VWludDgoMyxlKSxnLnNldFVpbnQxNig0LGYpO2ZvcihsZXQgdD0wO3Q8Zjt0KyspZy5zZXRVaW50OCg2K3QsaVt0XSk7Y29uc3QgYz1uZXcgVWludDhBcnJheShnLmJ1ZmZlcik7cmV0dXJuIGMuc2V0KG5ldyBVaW50OEFycmF5KHQpLGQpLGMuYnVmZmVyfShmLnZhbHVlLmRhdGEsaS5BVURJT182NF9CSVRfUFRTLHQpKX1jLndyaXRlKGYudmFsdWUpLGUub3B0aW9ucy5wb3J0LnBvc3RNZXNzYWdlKHt0cmFuc2Zvcm1lZDohMH0pLHQoZSl9fSkpfSh1KX0sc2VsZi5wb3N0TWVzc2FnZSgicmVnaXN0ZXJlZCIpKTsK")],{type:"text/javascript"});return setTimeout((()=>URL.revokeObjectURL(e)),0),new Worker(URL.createObjectURL(e))}const Ns=71,Os=1,Ls=2,Ps=1,Vs=2;var xs=function(e){return e[e.AUDIO_LEVEL=1]="AUDIO_LEVEL",e[e.METADATA=2]="METADATA",e[e.AUDIO_64_BIT_PTS=3]="AUDIO_64_BIT_PTS",e}(xs||{});function Us(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const i=e.getUint8(0);if(i!==Ns)return;const r=e.getUint16(1),s=Os+Ls+r,o=new Uint8Array(e.byteLength-s);o.set(new Uint8Array(e.buffer,s,e.byteLength-s));const n={m:i,tlvLen:r,tlv:[],frame:o};let a=Os+Ls;for(;a<s;){const i=e.getUint8(a),r=e.getUint16(a+Ps),s=Ps+Vs;if(i===xs.AUDIO_LEVEL){let o=e.getUint8(a+s);for(let t=1;t<r;t++)o=o<<8|e.getUint8(a+s+t);n.tlv.push({tag:i,length:r,value:t?127^o>>1:127&o})}else if(i===xs.METADATA||i===xs.AUDIO_64_BIT_PTS){const t=new Uint8Array(r);for(let i=0;i<r;i++)t[i]=e.getUint8(a+s+i);n.tlv.push({tag:i,length:r,value:t})}a+=s+r}return n}const Bs=new Map;function Fs(e,t){const{chunk:i,controller:r}=t,s=u("ENABLE_AUDIO_PTS_METADATA")?xs.AUDIO_64_BIT_PTS:xs.METADATA;i.data=function(e,t,i){const r=i.byteLength,s=r+Ps+Vs,o=Os+Ls+s,n=new ArrayBuffer(e.byteLength+o),a=new DataView(n);a.setUint8(0,Ns),a.setUint16(1,s),a.setUint8(3,t),a.setUint16(4,r);for(let e=0;e<r;e++)a.setUint8(6+e,i[e]);const c=new Uint8Array(a.buffer);return c.set(new Uint8Array(e),o),c.buffer}(i.data,s,e),r.enqueue(i)}async function Gs(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!fe().supportWebRTCEncodedTransform)return void le.warning("browser not support audio encoded transform");if(Bs.has(e))return;if(!e.track)return;const i={track:e.track};if(l()){if(!e.createEncodedStreams)return void le.warning("browser not support createEncodedStreams() API");let s=null;try{s=e.createEncodedStreams()}catch(e){return void le.error("create audio-encoded-streams error",e&&e.message)}const o=new TransformStream({transform(s,o){i.controller||(i.controller=o),e.track&&e.track.id!==i.track.id&&(le.debug("audio track changed: ".concat(i.track.id," => ").concat(e.track.id)),i.track.removeEventListener("ended",r),i.track=e.track,i.track.addEventListener("ended",r));const n=t.metadata&&t.metadata();n?Fs(n,{sender:e,chunk:s,controller:o}):o.enqueue(s)}});s.readable.pipeThrough(o).pipeTo(s.writable)}else if(c()){if("undefined"==typeof RTCRtpScriptTransform)return void le.warning("browser not support RTCRtpScriptTransform");const s=Ms(),o=new MessageChannel;await new Promise((e=>s.onmessage=t=>{"registered"===t.data&&e(void 0)}));const n=new RTCRtpScriptTransform(s,{name:"audio-metadata-tx",port:o.port2},[o.port2]);e.transform=n,await new Promise((e=>s.onmessage=t=>{"started"===t.data&&e(void 0)})),o.port1.onmessage=s=>{var n;if(s.data.transformed&&e.track&&(null===(n=e.track)||void 0===n?void 0:n.id)!==i.track.id)le.debug("audio track changed: ".concat(i.track.id," => ").concat(e.track.id)),i.track.removeEventListener("ended",r),i.track=e.track,i.track.addEventListener("ended",r);else if(s.data.getMetadata){const e=t.metadata&&t.metadata();e&&o.port1.postMessage({metadata:e})}},i.worker=s}function r(){if(e.track){if(this.id!==e.track.id)return;e.track.removeEventListener("ended",r)}const t=Bs.get(e);if(t){Bs.delete(e);try{var i,s;null===(i=t.controller)||void 0===i||i.terminate(),null===(s=t.worker)||void 0===s||s.terminate()}catch(e){le.warning(e&&e.message)}}}Bs.set(e,i),e.track.addEventListener("ended",r)}const Ws=127,Hs=1e-10,Ks=139/13;const Zs=new Map;function Ys(e,t,i){const r="".concat(e,"-").concat(t,"-").concat(i);let s=0;if(Zs.has(r))s=Zs.get(r);else{const o=.5;s=Math.log(function(e,t){const i=e-t;t<i&&(t=i);let r=1;for(let i=e,s=1;i>t;i--,s++)r=r*i/s;return r}(t,e))+e*Math.log(o)+(t-e)*Math.log(1-o)-Math.log(i)+i*e,Zs.set(r,s)}return s<Hs&&(s=Hs),s}function zs(e,t,i){const r=t.length,s=e.length/r;let o=!1;for(let n=0,a=0;n<r;n++){let r=0;for(let t=a+s;a<t;a++)e[a]>i&&r++;t[n]!==r&&(t[n]=r,o=!0)}return o}window.cache=Zs;let js=0;class Xs{constructor(e){_t(this,"id",void 0),_t(this,"immediates",[]),_t(this,"lastNonSilence",-1),_t(this,"immediateSpeechActivityScore",Hs),_t(this,"lastLevelChangedTime",Date.now()),_t(this,"levels",[]),_t(this,"longs",[]),_t(this,"longSpeechActivityScore",Hs),_t(this,"mediums",[]),_t(this,"mediumSpeechActivityScore",Hs),_t(this,"minLevel",0),_t(this,"nextMinLevel",0),_t(this,"nextMinLevelWindowLength",0),_t(this,"energyScore",0),this.id=e||"".concat(js++),this.immediates.length=50,this.mediums.length=10,this.longs.length=1,this.levels.length=this.immediates.length}computeImmediates(){const e=this.immediates,t=this.levels,i=this.minLevel+Ks;let r=!1;for(let s=0;s<e.length;++s){let o=t[s];o<i&&(o=0);const n=Math.floor(o/Ks);e[s]!==n&&(e[s]=n,r=!0)}return r}computeLongs(){return zs(this.mediums,this.longs,4)}computeMediums(){return zs(this.immediates,this.mediums,7)}evaluateImmediateSpeechActivityScore(){this.immediateSpeechActivityScore=Ys(this.immediates[0],13,.78)}evaluateLongSpeechActivityScore(e){this.longSpeechActivityScore=Ys(this.longs[0],10,47),this.longSpeechActivityScore>Hs&&(this.lastNonSilence=e)}evaluateMediumSpeechActivityScore(){this.mediumSpeechActivityScore=Ys(this.mediums[0],5,24)}evaluateSpeechActivityScores(e){this.computeImmediates()&&(this.evaluateImmediateSpeechActivityScore(),this.computeMediums()&&(this.evaluateMediumSpeechActivityScore(),this.computeLongs()&&this.evaluateLongSpeechActivityScore(e)))}getLastLevelChangedTime(){return this.lastLevelChangedTime}getLevels(){return"[".concat([...this.levels].reverse().join(),"]")}getSpeechActivityScore(e){switch(e){case 0:return this.immediateSpeechActivityScore;case 1:return this.mediumSpeechActivityScore;case 2:return this.longSpeechActivityScore;default:throw new Error("interval "+e)}}levelChanged(e,t){if(this.lastLevelChangedTime<=t){this.lastLevelChangedTime=t;let i=e;return e<0&&(i=0),e>Ws&&(i=Ws),this.levels.unshift(i),this.levels.length>this.immediates.length&&this.levels.pop(),this.updateMinLevel(i),i>=this.minLevel+Ks?i:i/2}return-1}levelTimedOut(){this.levelChanged(0,this.lastLevelChangedTime)}updateMinLevel(e){if(0!==e){if(0===this.minLevel||this.minLevel>e)return this.minLevel=e,this.nextMinLevel=0,void(this.nextMinLevelWindowLength=0);if(0===this.nextMinLevel)return this.nextMinLevel=e,void(this.nextMinLevelWindowLength=1);if(this.nextMinLevel>e&&(this.nextMinLevel=e),this.nextMinLevelWindowLength++,this.nextMinLevelWindowLength>=750){let e=Math.sqrt(this.minLevel*this.nextMinLevel);e<0?e=0:e>Ws&&(e=Ws),this.minLevel=e,this.nextMinLevel=0,this.nextMinLevelWindowLength=0}}}}class Qs{constructor(e){_t(this,"algorithm",void 0),this.algorithm=e}execute(){let e=!this.algorithm;if(!e)try{const t=this.algorithm.runInDecisionMaker(this);t<=0?e=!0:setTimeout(this.execute.bind(this),t)}catch(t){e=!0}e&&this.algorithm&&this.algorithm.decisionMakerExited(this)}}class Js{constructor(e,t,i){_t(this,"isDominant",void 0),_t(this,"energyRanking",void 0),_t(this,"energyScore",void 0),this.isDominant=e,this.energyRanking=t,this.energyScore=i}}class qs extends y{constructor(e){super(),_t(this,"dominantId",null),_t(this,"lastDecisionTime",0),_t(this,"lastLevelChangedTime",0),_t(this,"lastLevelIdleTime",0),_t(this,"relativeSpeechActivities",[]),_t(this,"speakers",new Map),_t(this,"enableSilence",!1),_t(this,"timeoutToSilenceInterval",0),_t(this,"decisionMaker",null),_t(this,"loudest",[]),_t(this,"numLoudestToTrack",3),_t(this,"energyExpireTimeMs",250),_t(this,"energyAlphaPct",50),this.timeoutToSilenceInterval=e,this.enableSilence=e>0,this.relativeSpeechActivities.length=3}setLoudestConfig(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:3,t=arguments.length>1?arguments[1]:void 0,i=arguments.length>2?arguments[2]:void 0;this.numLoudestToTrack=e,null!=t&&(this.energyExpireTimeMs=t),null!=i&&(this.energyAlphaPct=i),this.loudest.length>e&&this.loudest.splice(e)}getDominantSpeaker(){return this.dominantId}isAmongLoudest(e){return this.loudest.some((t=>t.id===e))}levelChanged(e,t){const i=Date.now(),r=this.getOrCreateSpeaker(e);this.lastLevelChangedTime<i&&(this.lastLevelChangedTime=i,this.maybeStartDecisionMaker());const s=r.levelChanged(t,i);return this.updateLoudestList(r,s,i)}runInDecisionMaker(e){if(this.decisionMaker!==e)return-1;if(this.lastDecisionTime>0){if(this.lastDecisionTime-this.lastLevelChangedTime>=15e3)return-1}return this._runInDecisionMaker()}decisionMakerExited(e){this.decisionMaker===e&&(this.decisionMaker=null)}destroy(){this.decisionMaker=null,this.loudest.length=0,this.speakers.clear(),this.removeAllListeners()}addSpeakers(e){e.forEach((e=>{this.speakers.has(e.id)||this.speakers.set(e.id,e)}))}removeSpeakers(e){e.forEach((e=>{this.speakers.delete(e.id)}))}getOrCreateSpeaker(e){let t=this.speakers.get(e);return t||(t=new Xs(e),this.speakers.set(e,t),this.maybeStartDecisionMaker()),t}updateLoudestList(e,t,i){const r=e.id===this.dominantId;if(t<0){let t=0;for(;t<this.loudest.length&&this.loudest[t]!==e;)++t;return new Js(r,t,e.energyScore)}if(e.energyScore=Math.floor((this.energyAlphaPct*t+(100-this.energyAlphaPct)*e.energyScore+50)/100),0===this.numLoudestToTrack)return new Js(r,0,e.energyScore);const s=i-this.energyExpireTimeMs;let o=0;for(;o<this.loudest.length;){const t=this.loudest[o];if(t.getLastLevelChangedTime()<s&&this.loudest.length>=this.numLoudestToTrack)this.loudest.splice(o,1);else if(t.id!==e.id)++o;else if(this.loudest.splice(o,1),this.loudest.length<this.numLoudestToTrack)break}let n=0;for(;n<this.loudest.length;){if(this.loudest[n].energyScore<e.energyScore)break;++n}return n<this.numLoudestToTrack&&(this.loudest.splice(n,0,e),this.loudest.length>this.numLoudestToTrack&&this.loudest.splice(this.numLoudestToTrack,1)),new Js(r,n,e.energyScore)}maybeStartDecisionMaker(){!this.decisionMaker&&this.speakers.size>0&&(this.decisionMaker=new Qs(this),this.decisionMaker.execute())}makeDecision(e){let t=null,i=null;const r=this.speakers.size;let s=null;if(0===r)s=null;else if(1===r){const t=this.speakers.values().next().value;if(this.enableSilence&&t){s=t.id,t.evaluateSpeechActivityScores(e);e-t.lastNonSilence>this.timeoutToSilenceInterval&&(s=null)}}else{let t=null==this.dominantId?null:this.speakers.get(this.dominantId);if(null==t){const e=this.speakers.entries().next();e.value&&(s=e.value[0],t=e.value[1])}else s=t.id;null!=t&&t.evaluateSpeechActivityScores(e);const i=this.relativeSpeechActivities;let r=2;for(const o of this.speakers.entries()){const[n,a]=o;if(a===t)continue;a.evaluateSpeechActivityScores(e);for(let e=0;e<i.length;++e){const r=null==t?Hs:t.getSpeechActivityScore(e);i[e]=Math.log(a.getSpeechActivityScore(e)/r)}const c=i[0],d=i[1],u=i[2];c>3&&d>2&&u>0&&d>r&&(r=d,s=n)}if(this.enableSilence&&null!=t&&s===t.id){e-t.lastNonSilence>this.timeoutToSilenceInterval&&(s=null)}}null==s&&!this.enableSilence||s===this.dominantId||(t=this.dominantId,this.dominantId=s,i=this.dominantId),null==i&&!this.enableSilence||i===t||this.emit("ActiveSpeakerChanged",i)}_runInDecisionMaker(){const e=Date.now(),t=300-(e-this.lastLevelIdleTime);let i=0;t<=0?(0!==this.lastLevelIdleTime&&this.timeoutIdleLevels(e),this.lastLevelIdleTime=e):i=t;let r=300-(e-this.lastDecisionTime);return r<=0&&(this.lastDecisionTime=e,this.makeDecision(e),r=300-(Date.now()-e)),r>0&&i>r&&(i=r),i}timeoutIdleLevels(e){const t=[];for(const i of this.speakers.values()){const r=e-i.getLastLevelChangedTime();36e5<r&&(null==this.dominantId||i.id!==this.dominantId)?t.push(i.id):300<r&&i.levelTimedOut()}t.forEach((e=>this.speakers.delete(e)))}}const $s=new Map;let eo=null,to=null;const io=3;let ro=[];function so(e,t){let i=$s.get(e);if(i||(i=function(e){const t=new Xs;return $s.set(e,t),eo||(eo=new qs(u("TOPN_SILENCE_THRESHOLD")||500),eo.on("ActiveSpeakerChanged",(e=>{null!=e&&(to=e)}))),eo.addSpeakers([t]),t}(e)),$s.size<=io)return{selected:!0,speaker:i};if(!eo)throw new Error("no active speaker detector");eo.levelChanged(i.id,t),ro=eo.loudest.map((e=>e.id)),to&&!ro.includes(to)&&ro.length>=io&&ro.pop();return{selected:ro.includes(i.id)||i.id===to,speaker:i}}const oo=1e3,no=40,ao=new Map,co=new Map;class uo{get samples(){return this.actives+this.inactives}get activeRate(){return this.actives/this.samples}constructor(e,t){_t(this,"id",void 0),_t(this,"track",void 0),_t(this,"score",0),_t(this,"active",!0),_t(this,"muted",!1),_t(this,"timer",0),_t(this,"actives",0),_t(this,"inactives",0),this.id=e,this.track=t,this.setActive(ao.size<3)}autoCheckActive(){this.autoSetActive(),this.autoAdjustActive(),this.resetTimer(),this.actives=0,this.inactives=0}autoSetActive(){const e=this.active;this.active=this.activeRate>=.8;const{actives:t,inactives:i}=function(){const e=[],t=[];return Array.from(ao.values()).forEach((i=>{i.active?e.push(i):t.push(i)})),{actives:e,inactives:t}}();if(t.length>3){let e;t.forEach((t=>{(!e||e.score>t.score)&&(e=t)})),e&&e.setActive(!1)}if(t.length<3&&i.length>0){let t;i.forEach((e=>{(!t||t.score<e.score)&&e.id!==this.id&&(t=e)})),t&&e&&!this.active&&(t.samples>no&&t.activeRate-this.activeRate>.4?t.setActive(!0):this.active=!0)}this.setMuted(!this.active)}setActive(e){this.active=e,this.resetTimer(),this.setMuted(!e)}autoAdjustActive(){this.active?this.autoSwitchToInactive():this.autoSwitchToActive()}autoSwitchToActive(){const e=function(e){let t;return Array.from(ao.values()).forEach((i=>{!i.active||i.id===e||i.samples<no||(!t||i.score<t.score)&&(t=i)})),t}(this.id);e&&this.activeRate-e.activeRate>.4&&(e.setActive(!1),this.setActive(!0))}autoSwitchToInactive(){const e=function(e){let t;return Array.from(ao.values()).forEach((i=>{i.active||i.id===e||i.samples<no||(!t||i.score>t.score)&&(t=i)})),t}(this.id);e&&e.activeRate-this.activeRate>.4&&(e.setActive(!0),this.setActive(!1))}addSample(e){e?this.actives+=1:this.inactives+=1,this.samples>66.66666666666667&&this.autoCheckActive()}setMuted(e){this.track&&(this.track.enabled=!e,this.muted=e)}resetTimer(){this.clearTimer(),this.timer=window.setTimeout((()=>{if(0!==this.samples)return this.samples<50?this.resetTimer():void this.autoCheckActive()}),oo)}clearTimer(){this.timer&&(clearTimeout(this.timer),this.timer=0)}}let ho;function lo(e,t,i){const r=ao.get(e)||new uo(e,t);return r.score=i,ao.set(e,r),function(e){if(co.set(e,!0),!ho)return void(ho=Date.now());const t=Date.now();t-ho>1e3&&(co.get(e)?co.set(e,!1):(po(e),co.delete(e)),ho=t)}(e),r}function po(e){const t=ao.get(e);t&&(ao.delete(e),t.clearTimer())}const mo=new Map,go=new Map;async function _o(e){let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!fe().supportWebRTCEncodedTransform)return void le.warning("browser not support audio encoded transform");if(mo.has(e))return;const r={track:e.track,onMetadata:i.onMetadata};if(l()){if(!e.createEncodedStreams)return void le.warning("browser not support createEncodedStreams() API");ne(t.CHROME,87,116)||(i.enableTopn=!1);let o=null;try{o=e.createEncodedStreams()}catch(e){return void le.error("create audio-encoded-streams error",e&&e.message)}const n=new TransformStream({transform(t,o){r.controller||(r.controller=o),e.track&&e.track.id!==r.track.id&&(le.debug("audio track changed: ".concat(r.track.id," => ").concat(e.track.id)),r.track.removeEventListener("ended",s),r.track=e.track,r.track.addEventListener("ended",s)),i.enableTopn?function(e,t,i){var r;const s=Us(new DataView(t.data));if(!s)return i.enqueue(t);const o=e.track.id;go.set(o,e.track);const n=null===(r=s.tlv.find((e=>e.tag===xs.AUDIO_LEVEL)))||void 0===r?void 0:r.value;let a=0;"number"==typeof n&&(a=127-n);const c=Math.round(Math.pow(10,a/60)-1),{selected:d,speaker:u}=so(e,c),h=lo(o,e.track,u.energyScore);h.addSample(d),h.active&&(t.data=s.frame.buffer,i.enqueue(t))}(e,t,o):i.enableMetadata?function(e,t,i){const r=Us(new DataView(e.data));if(!r)return t.enqueue(e);const s=r.tlv.find((e=>e.tag===xs.METADATA||e.tag===xs.AUDIO_64_BIT_PTS));s&&i&&s.value instanceof Uint8Array&&i(s.value),e.data=r.frame.buffer,t.enqueue(e)}(t,o,i.onMetadata):o.enqueue(t)}});o.readable.pipeThrough(n).pipeTo(o.writable)}else if(c()){if("undefined"==typeof RTCRtpScriptTransform)return void le.warning("browser not support RTCRtpScriptTransform");const t=Ms(),i=new MessageChannel;await new Promise((e=>t.onmessage=t=>{"registered"===t.data&&e(void 0)}));const o=new RTCRtpScriptTransform(t,{name:"audio-metadata-rx",port:i.port2},[i.port2]);e.transform=o,await new Promise((e=>t.onmessage=t=>{"started"===t.data&&e(void 0)})),i.port1.onmessage=t=>{var i;t.data.transformed&&e.track&&(null===(i=e.track)||void 0===i?void 0:i.id)!==r.track.id?(le.debug("audio track changed: ".concat(r.track.id," => ").concat(e.track.id)),r.track.removeEventListener("ended",s),r.track=e.track,r.track.addEventListener("ended",s)):t.data.metadata&&r.onMetadata&&r.onMetadata(t.data.metadata)},r.worker=t}function s(){e.track.removeEventListener("ended",s),function(e){const t=mo.get(e);if(t){!function(e){const t=$s.get(e);t&&($s.delete(e),eo&&(eo.removeSpeakers([t]),0===$s.size&&(eo.destroy(),eo=null)))}(e),po(e.track.id),mo.delete(e);try{var i,r;null===(i=t.controller)||void 0===i||i.terminate(),null===(r=t.worker)||void 0===r||r.terminate()}catch(e){le.warning(e&&e.message)}}}(e)}mo.set(e,r),e.track.addEventListener("ended",s)}function To(e,t,i){let r=new Uint8Array(e,t,i),s=[],o=0;for(;s.length<i;)o+3<i&&0===r[o]&&0===r[o+1]&&3===r[o+2]&&(0===r[o+3]||1===r[o+3]||2===r[o+3]||3===r[o+3])?(s.push(r[o],r[o+1],r[o+3]),o+=4):(s.push(r[o]),o++);return new Uint8Array(s)}function vo(e,t){const i=function(e){const t=e.length;let i=[],r=0;for(;r<t;)r+2<t&&0===e[r]&&0===e[r+1]&&(0===e[r+2]||1===e[r+2]||2===e[r+2]||3===e[r+2])?(i.push(e[r],e[r+1],3,e[r+2]),r+=3):(i.push(e[r]),r++);return new Uint8Array(i)}(t),r=i.length,s=Math.floor(r/255),o=r%255,n=new Uint8Array(6+s+1+r+e.byteLength);n[0]=0,n[1]=0,n[2]=0,n[3]=1,n[4]=6,n[5]=101;let a=0;for(;a<s;)n[6+a]=255,a++;return n[6+a]=o,a++,n.set(i,6+a),n.set(new Uint8Array(e),6+a+r),n.buffer}const fo=new Map;async function Eo(e,t){if(!fe().supportWebRTCEncodedTransform)return void le.warning("browser not support video encoded transform");if(fo.has(e))return;if(!e.track)return;const i={track:e.track};if(l()){if(!e.createEncodedStreams)return void le.warning("browser not support createEncodedStreams() API");let s=null;try{s=e.createEncodedStreams()}catch(e){return void le.error("create video-encoded-streams error",e&&e.message)}const o=[];t.on("sei-to-send",(e=>{o.push(e)}));const n=new TransformStream({transform(t,s){i.controller||(i.controller=s),e.track&&e.track.id!==i.track.id&&(le.debug("video track changed: ".concat(i.track.id," => ").concat(e.track.id)),i.track.removeEventListener("ended",r),i.track=e.track,i.track.addEventListener("ended",r));const n=o.shift();n&&(t.data=vo(t.data,n)),s.enqueue(t)}});s.readable.pipeThrough(n).pipeTo(s.writable)}else{if(!c())return;{if("undefined"==typeof RTCRtpScriptTransform)return void le.warning("browser not support RTCRtpScriptTransform");const s=Ms(),o=new MessageChannel;await new Promise((e=>s.onmessage=t=>{"registered"===t.data&&e(void 0)}));const n=new RTCRtpScriptTransform(s,{name:"sei-tx",port:o.port2},[o.port2]);e.transform=n,await new Promise((e=>s.onmessage=t=>{"started"===t.data&&e(void 0)})),t.on("sei-to-send",(e=>{o.port1.postMessage({sei:e})})),o.port1.onmessage=t=>{var s;t.data.transformed&&e.track&&(null===(s=e.track)||void 0===s?void 0:s.id)!==i.track.id&&(le.debug("video track changed: ".concat(i.track.id," => ").concat(e.track.id)),i.track.removeEventListener("ended",r),i.track=e.track,i.track.addEventListener("ended",r))},i.worker=s}}function r(){if(e.track){if(this.id!==e.track.id)return;e.track.removeEventListener("ended",r)}const t=fo.get(e);if(t){fo.delete(e);try{var i,s;null===(i=t.controller)||void 0===i||i.terminate(),null===(s=t.worker)||void 0===s||s.terminate()}catch(e){le.warning(e&&e.message)}}}fo.set(e,i),e.track.addEventListener("ended",r)}const So=new Map;async function yo(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!fe().supportWebRTCEncodedTransform)return void le.warning("browser not support video encoded transform");if(!e.track)return;if(So.has(e)){const i=So.get(e);return void(i&&(i.onSei=t.onSei))}const i={track:e.track,onSei:t.onSei};if(l()){if(!e.createEncodedStreams)return void le.warning("browser not support createEncodedStreams() API");let t=null;try{t=e.createEncodedStreams()}catch(e){return void le.error("create video-encoded-streams error",e&&e.message)}const s=new TransformStream({transform(t,s){i.controller||(i.controller=s),e.track&&e.track.id!==i.track.id&&(le.debug("video track changed: ".concat(i.track.id," => ").concat(e.track.id)),i.track.removeEventListener("ended",r),i.track=e.track,i.track.addEventListener("ended",r));const o=function(e){const t=new DataView(e.data);let i=0;for(;i+4<e.data.byteLength;){if(0===t.getUint8(i+0)&&0===t.getUint8(i+1)&&0===t.getUint8(i+2)&&1===t.getUint8(i+3)&&6===t.getUint8(i+4)){let r=i+6,s=0,o=0;for(;255===(o=t.getUint8(r++));)s+=255;s+=o;const n=To(e.data,r,s);return new Uint8Array(n)}i++}return null}(t);o&&i.onSei&&i.onSei(o),s.enqueue(t)}});t.readable.pipeThrough(s).pipeTo(t.writable)}else if(c()){if("undefined"==typeof RTCRtpScriptTransform)return void le.warning("browser not support RTCRtpScriptTransform");const t=Ms(),s=new MessageChannel;await new Promise((e=>t.onmessage=t=>{"registered"===t.data&&e(void 0)}));const o=new RTCRtpScriptTransform(t,{name:"sei-rx",port:s.port2},[s.port2]);e.transform=o,await new Promise((e=>t.onmessage=t=>{"started"===t.data&&e(void 0)})),s.port1.onmessage=t=>{var s;t.data.transformed&&e.track&&(null===(s=e.track)||void 0===s?void 0:s.id)!==i.track.id?(le.debug("video track changed: ".concat(i.track.id," => ").concat(e.track.id)),i.track.removeEventListener("ended",r),i.track=e.track,i.track.addEventListener("ended",r)):t.data.sei&&i.onSei&&i.onSei(t.data.sei)},i.worker=t}function r(){if(e.track){if(this.id!==e.track.id)return;e.track.removeEventListener("ended",r)}!function(e){const t=So.get(e);if(t){So.delete(e);try{var i,r;null===(i=t.controller)||void 0===i||i.terminate(),null===(r=t.worker)||void 0===r||r.terminate()}catch(e){le.warning(e&&e.message)}}}(e)}So.set(e,i),e.track.addEventListener("ended",r)}ve();export{ye as AUDIO_CONTEXT_EVENT,Oe as AUDIO_ENCODER_CONFIG_SETTINGS,et as AUDIO_TRACK_EVENT,ni as AudioProcessorContext,oi as AudioProcessorDestination,$e as AudioSourceEvents,hr as BufferSourceAudioTrack,is as CameraVideoTrack,tt as DEFAULT_LOCAL_AUDIO_TRACK_STATS,it as DEFAULT_LOCAL_VIDEO_TRACK_STATS,st as DEFAULT_NETWORK_QUALITY_STATS,rt as DEFAULT_REMOTE_AUDIO_TRACK_STATS,ot as DEFAULT_REMOTE_VIDEO_TRACK_STATS,ws as DataChannel,mt as DataChannelEvents,jt as DeviceManager,dt as DeviceManagerEvent,ct as DeviceManagerState,Wt as HAS_GUM_AUDIO,Ht as HAS_GUM_VIDEO,dr as LocalAudioTrack,Cs as LocalDataChannel,Et as LocalTrack,Qe as LocalTrackEvents,ts as LocalVideoTrack,pt as MediaElementNumStatus,ht as MediaElementStatus,ur as MicrophoneAudioTrack,lr as MixingAudioTrack,at as PROCESSOR_CONTEXT_EVENTS,nt as PROCESSOR_DESTINATION_EVENTS,As as RemoteAudioTrack,Ds as RemoteDataChannel,je as RemoteStreamFallbackType,ze as RemoteStreamType,bs as RemoteTrack,Je as RemoteTrackEvents,Is as RemoteVideoTrack,Gt as SAFARI_GLOBAL_GUM_LOCK,we as SUPPORT_SCREEN_ENCODER_CONFIG_LIST,De as SUPPORT_SVC_CONFIG_LIST,Re as SUPPORT_VIDEO_ENCODER_CONFIG_LIST,Ye as StreamType,ft as Track,Xe as TrackEvents,Ke as TrackHint,He as TrackInternalEvent,qe as TrackMediaType,si as VideoProcessorContext,ri as VideoProcessorDestination,lt as VideoState,Pe as __TRACK_LIST__,Ve as addTrack,kt as audioContextState,ti as audioElementPlayCenter,Ct as audioTimerLoop,Jt as autoPlayGestureEventEmitter,Si as blob2Uint8Array,di as checkMediaStreamTrackResolution,ii as checkTrackState,os as createBufferSourceAudioTrack,cs as createCameraVideoTrack,rs as createCustomAudioTrack,as as createCustomVideoTrack,ds as createMicrophoneAndCameraTracks,ss as createMicrophoneAudioTrack,ns as createMixingAudioTrack,us as createScreenVideoTrack,wt as decodeAudioData,Ee as detectSupportAudioElementSetSinkId,Xt as deviceManager,Ei as emptyImage2TypedArray,fi as frameData2CryptoBuffer,It as getAudioContext,Le as getAudioEncoderConfiguration,_i as getBitrateConstrainRange,Ti as getBitrateFromResAndFps,fe as getCompatibility,li as getConstraintsFromAudioConfig,ui as getConstraintsFromCameraConfig,mi as getConstraintsFromMicrophoneConfig,pi as getConstraintsFromScreenAudioConfig,hi as getConstraintsFromScreenConfig,Ft as getElectronScreenSources,Ut as getElectronScreenStream,Bt as getElectronScreenStreamByUserSelect,Kt as getLocalStream,gi as getNewVideoBitrate,vi as getOriginSenderConfig,Ne as getScalabilityConfiguration,Me as getScreenEncoderConfiguration,Nt as getSilenceAudioTrack,Lt as getSilenceSamplesDuration,yi as getStaticTrackStream,Ce as getVideoEncoderConfiguration,Yt as handleGetUserMediaError,At as hasAudioContext,Gs as interceptLocalAudioFrame,Eo as interceptLocalVideoFrame,_o as interceptRemoteAudioFrame,yo as interceptRemoteVideoFrame,Be as isAudioEncoderConfiguration,Ge as isAudioEncoderConfigurationOrPreset,ut as isBeautyEffectOptions,Ze as isLowStreamParameter,Se as isPlanB,We as isScreenSourceType,Ue as isVideoEncoderConfiguration,Fe as isVideoEncoderConfigurationOrPreset,Rt as polyfillAudioNode,xe as removeTrack,qt as requestAutoplayGesture,Ot as silenceScriptProcessHandler,ve as updateAgoraRTCCompatibility,Rs as visibilityWatcher};
|
|
5
|
+
import"webrtc-adapter";import{getBrowserInfo as e,BrowserName as t,isChromeKernel as i,nextTick as r,isAboveChrome as s,isAboveFirefox as o,isAboveSafari as n,BrowserOS as a,isSafari as c,isWkWebview as d,getParameter as h,isFirefox as u,isChrome as l,isEdge as p,isMobile as m,checkValidConstrainLong as g,checkValidNumber as _,checkValidBoolean as f,checkValidEnum as T,AgoraRTCError as v,AgoraRTCErrorCode as E,isEmpty as S,EventEmitter as y,getRandomString as k,runOnce as b,AgoraAPIName as I,AgoraAPITag as A,PromiseMutex as R,emitAsPromiseNoResponse as w,removeItemFromList as D,isIOS as C,isIpadOS as N,wait as M,showElectronSelectSourceWindow as O,getElectronInstance as L,isElectron as P,recursiveMerge as V,isAndroid as x,isHarmonyOS as U,detectSecureContext as B,isAndroidChromium as F,domLoadedPromise as G,isIOS15 as W,emitAsPromise as H,noop as K,isLegacyChrome as Z,isAboveEdge as Y,isAboveOpera as z,constrainLongToNumber as j,hexToBytes as X,md5 as Q,atom as J,emitAsInvokerNoResponse as q,isIOS16 as $,retryable as ee,getOSWithVersion as te,isAboveIOS15_1 as ie,isInPage as re,sumArray as se,jsonClone as oe,isBetweenBrowser as ne,isWindows as ae,elementVisibleChecker as ce,safeCloneJson as de,isAboveIOS15_2 as he,isWechatBrowser as ue}from"@agora-js/shared";export{isElectron}from"@agora-js/shared";import{logger as le,report as pe,AgoraRTCEventUploadType as me,apiInvoke as ge}from"@agora-js/report";import _e from"axios";const fe={getDisplayMedia:!1,getStreamFromExtension:!1,supportUnifiedPlan:!1,supportMinBitrate:!1,supportSetRtpSenderParameters:!1,supportDualStream:!0,webAudioMediaStreamDest:!1,supportReplaceTrack:!1,supportWebGL:!1,webAudioWithAEC:!1,supportRequestFrame:!1,supportShareAudio:!1,supportDualStreamEncoding:!1,supportDataChannel:!1,supportPCSetConfiguration:!1,supportWebRTCEncodedTransform:!1,supportWebRTCInsertableStream:!1,supportRequestVideoFrameCallback:!1,supportWebCrypto:!1};function Te(){const l=e();fe.getDisplayMedia=function(e){if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)return!0;return!1}(),fe.getStreamFromExtension=l.name===t.CHROME&&Number(l.version)>34,fe.supportUnifiedPlan=function(){if(!window.RTCRtpTransceiver)return!1;if(!("currentDirection"in RTCRtpTransceiver.prototype))return!1;const e=new RTCPeerConnection;let t=!1;try{e.addTransceiver("audio"),t=!0}catch(e){}return e.close(),t}(),fe.supportMinBitrate=l.name===t.CHROME||l.name===t.EDGE,fe.supportSetRtpSenderParameters=function(){const r=e();if(!window.RTCRtpSender||!window.RTCRtpSender.prototype.setParameters||!window.RTCRtpSender.prototype.getParameters)return!1;return!!i()||(!(!c()&&!d())||r.name===t.FIREFOX&&Number(r.version)>=64)}(),l.name===t.SAFARI&&(Number(l.version)>=14?fe.supportDualStream=!0:fe.supportDualStream=!1),fe.webAudioMediaStreamDest=function(){const i=e();if(i.name===t.SAFARI&&Number(i.version)<12)return!1;return!0}(),fe.supportReplaceTrack=function(){if(!window.RTCRtpSender)return!1;if("function"==typeof RTCRtpSender.prototype.replaceTrack)return!0;return!1}(),fe.supportWebGL="undefined"!=typeof WebGLRenderingContext,fe.supportRequestFrame=!!window.CanvasCaptureMediaStreamTrack,i()||(fe.webAudioWithAEC=!0),fe.supportShareAudio=function(){const i=e();if((i.os===a.WIN_10||i.os===a.WIN_81||i.os===a.WIN_7||i.os===a.LINUX||i.os===a.MAC_OS||i.os===a.CHROMIUM_OS)&&i.name===t.CHROME&&Number(i.version)>=74)return!0;return!1}(),fe.supportDataChannel=function(){if(s(76)||o(68)||n(14))return!0;return!1}(),fe.supportPCSetConfiguration=function(){const e=window.RTCPeerConnection;return!u()&&!!e&&e.prototype.setConfiguration instanceof Function}(),fe.supportWebRTCEncodedTransform=function(){const t=e();return"Chrome"===t.name&&Number(t.version)>=87||"Safari"===t.name&&Number(t.version)>=15}(),fe.supportWebRTCInsertableStream=function(){const i=e();return(i.name===t.CHROME||i.name===t.EDGE)&&Number(i.version)>=94&&"MediaStreamTrackGenerator"in window&&"MediaStreamTrackProcessor"in window}(),fe.supportRequestVideoFrameCallback=function(){if("requestVideoFrameCallback"in HTMLVideoElement.prototype)return!0;return!1}(),fe.supportWebCrypto="undefined"!=typeof window&&void 0!==window.crypto&&void 0!==window.crypto.subtle,r((()=>{fe.supportDualStreamEncoding=function(){const t=e();if(h("DISABLE_WEBAUDIO"))return!0;return"Safari"===t.name&&Number(t.version)>=14||!!("Chrome"===t.name&&/Windows/i.test(t.os||"")&&Number(t.version)>=100&&h("CHROME_DUAL_STREAM_USE_ENCODING"))}(),le.debug("browser ua: ",navigator.userAgent),le.info("browser info: ",l),le.info("browser compatibility: ",fe)}))}function ve(){return fe}function Ee(){return"setSinkId"in HTMLAudioElement.prototype&&(!h("RESTRICTION_SET_PLAYBACK_DEVICE")||(l()||p())&&!m())}function Se(){return!fe.supportUnifiedPlan||h("CHROME_FORCE_PLAN_B")&&i()}let ye=function(e){return e.IOS_15_16_INTERRUPTION_START="ios15_16-interruption-start",e.IOS_15_16_INTERRUPTION_END="ios15_16-interruption-end",e.IOS_INTERRUPTION_START="ios-interruption-start",e.IOS_INTERRUPTION_END="ios-interruption-end",e.STATE_CHANGE="state-change",e}({});function ke(e,t,i){return{sampleRate:e,stereo:t,bitrate:i}}function be(e,t,i,r,s){return{width:e,height:t,frameRate:i,bitrateMin:r,bitrateMax:s}}function Ie(e,t,i,r,s){return{width:{max:e},height:{max:t},frameRate:i,bitrateMin:r,bitrateMax:s}}function Ae(e,t){return{numSpatialLayers:e,numTemporalLayers:t}}const Re={"90p":be(160,90),"90p_1":be(160,90),"120p":be(160,120,15,30,65),"120p_1":be(160,120,15,30,65),"120p_3":be(120,120,15,30,50),"120p_4":be(212,120),"180p":be(320,180,15,30,140),"180p_1":be(320,180,15,30,140),"180p_3":be(180,180,15,30,100),"180p_4":be(240,180,15,30,120),"240p":be(320,240,15,40,200),"240p_1":be(320,240,15,40,200),"240p_3":be(240,240,15,40,140),"240p_4":be(424,240,15,40,220),"360p":be(640,360,15,80,400),"360p_1":be(640,360,15,80,400),"360p_3":be(360,360,15,80,260),"360p_4":be(640,360,30,80,600),"360p_6":be(360,360,30,80,400),"360p_7":be(480,360,15,80,320),"360p_8":be(480,360,30,80,490),"360p_9":be(640,360,15,80,800),"360p_10":be(640,360,24,80,800),"360p_11":be(640,360,24,80,1e3),"480p":be(640,480,15,100,500),"480p_1":be(640,480,15,100,500),"480p_2":be(640,480,30,100,1e3),"480p_3":be(480,480,15,100,400),"480p_4":be(640,480,30,100,750),"480p_6":be(480,480,30,100,600),"480p_8":be(848,480,15,100,610),"480p_9":be(848,480,30,100,930),"480p_10":be(640,480,10,100,400),"720p":be(1280,720,15,120,1130),"720p_auto":be(1280,720,30,900,3e3),"720p_1":be(1280,720,15,120,1130),"720p_2":be(1280,720,30,120,2e3),"720p_3":be(1280,720,30,120,1710),"720p_5":be(960,720,15,120,910),"720p_6":be(960,720,30,120,1380),"1080p":be(1920,1080,15,120,2080),"1080p_1":be(1920,1080,15,120,2080),"1080p_2":be(1920,1080,30,120,3e3),"1080p_3":be(1920,1080,30,120,3150),"1080p_5":be(1920,1080,60,120,4780),"1440p":be(2560,1440,30,120,4850),"1440p_1":be(2560,1440,30,120,4850),"1440p_2":be(2560,1440,60,120,7350),"4k":be(3840,2160,30,120,8910),"4k_1":be(3840,2160,30,120,8910),"4k_3":be(3840,2160,60,120,13500)},we={"480p":Ie(640,480,5),"480p_1":Ie(640,480,5),"480p_2":Ie(640,480,30),"480p_3":Ie(640,480,15),"720p":Ie(1280,720,5),"720p_auto":be(1280,720,30,900,3e3),"720p_1":Ie(1280,720,5),"720p_2":Ie(1280,720,30),"720p_3":Ie(1280,720,15),"1080p":Ie(1920,1080,5),"1080p_1":Ie(1920,1080,5),"1080p_2":Ie(1920,1080,30),"1080p_3":Ie(1920,1080,15)},De={"1SL1TL":Ae(1,1),"3SL3TL":Ae(3,3),"2SL3TL":Ae(2,3)};function Ce(e){return e||(e="480p_1"),"string"==typeof e?Object.assign({},Re[e]):e}function Ne(e){return"string"==typeof e?Object.assign({},we[e]):e}function Me(e){return"string"==typeof e?Object.assign({},De[e]):e}const Oe={speech_low_quality:ke(16e3,!1),speech_standard:ke(32e3,!1,18),music_standard:ke(48e3,!1),standard_stereo:ke(48e3,!0,56),high_quality:ke(48e3,!1,128),high_quality_stereo:ke(48e3,!0,192)};function Le(e){return"string"==typeof e?Object.assign({},Oe[e]):e}const Pe=[];function Ve(e){Pe.includes(e)||Pe.push(e)}function xe(e){const t=Pe.indexOf(e);-1!==t&&Pe.splice(t,1)}function Ue(e){return g(e.width,"config.width"),g(e.height,"config.height"),void 0!==e.frameRate&&g(e.frameRate,"config.frameRate"),void 0!==e.bitrateMax&&_(e.bitrateMax,"config.bitrateMax"),void 0!==e.bitrateMin&&_(e.bitrateMin,"config.bitrateMin"),!0}function Be(e){return void 0!==e.sampleRate&&_(e.sampleRate,"config.sampleRate",0,96e3,!0),void 0!==e.sampleSize&&_(e.sampleRate,"config.sampleSize",0,128,!0),void 0!==e.stereo&&f(e.stereo,"config.stereo"),void 0!==e.bitrate&&_(e.bitrate,"config.bitrate",0,1e4,!1),!0}function Fe(e){return"string"==typeof e?T(e,"profile",Object.keys(Re)):Ue(e),!0}function Ge(e){return"string"==typeof e?T(e,"profile",Object.keys(Oe)):Be(e),!0}function We(e){return T(e,"mediaSource",["screen","window","application"]),!0}let He=function(e){return e.NEED_RENEGOTIATE="@need_renegotiate",e.NEED_REPLACE_TRACK="@need_replace_track",e.NEED_REPLACE_MIXING_TRACK="@need_replace_mixing_track",e.NEED_CLOSE="@need_close",e.NEED_ENABLE_TRACK="@need_enable_track",e.NEED_DISABLE_TRACK="@need_disable_track",e.NEED_SESSION_ID="@need_sid",e.SET_OPTIMIZATION_MODE="@set_optimization_mode",e.GET_STATS="@get_stats",e.GET_RTC_STATS="@get_rtc_stats",e.GET_LOW_VIDEO_TRACK="@get_low_video_track",e.NEED_RESET_REMOTE_SDP="@need_reset_remote_sdp",e.NEED_UPDATE_VIDEO_ENCODER="@need_update_video_encoder",e.NEED_UPDATE_VIDEO_SEND_PARAMETERS="@need_update_video_send_parameters",e.NEED_MUTE_TRACK="@need_mute_track",e.NEED_UNMUTE_TRACK="@need_unmute_track",e}({}),Ke=function(e){return e.SCREEN_TRACK="screen_track",e.CUSTOM_TRACK="custome_track",e.LOW_STREAM="low_stream",e.SCREEN_LOW_TRACK="screen_low_track",e}({});function Ze(e){if(!e)throw new v(E.INVALID_PARAMS);return S(e.width)||g(e.width,"streamParameter.width"),S(e.height)||g(e.height,"streamParameter.height"),S(e.framerate)||g(e.framerate,"streamParameter.framerate"),S(e.bitrate)||_(e.bitrate,"streamParameter.bitrate"),!0}let Ye=function(e){return e[e.HIGH_STREAM=0]="HIGH_STREAM",e[e.LOW_STREAM=1]="LOW_STREAM",e}({}),ze=function(e){return e[e.HIGH_STREAM=0]="HIGH_STREAM",e[e.LOW_STREAM=1]="LOW_STREAM",e[e.HIGH_STREAM_LAYER1=4]="HIGH_STREAM_LAYER1",e[e.HIGH_STREAM_LAYER2=5]="HIGH_STREAM_LAYER2",e[e.HIGH_STREAM_LAYER3=6]="HIGH_STREAM_LAYER3",e[e.HIGH_STREAM_LAYER4=7]="HIGH_STREAM_LAYER4",e[e.HIGH_STREAM_LAYER5=8]="HIGH_STREAM_LAYER5",e[e.HIGH_STREAM_LAYER6=9]="HIGH_STREAM_LAYER6",e}({}),je=function(e){return e[e.DISABLE=0]="DISABLE",e[e.LOW_STREAM=1]="LOW_STREAM",e[e.AUDIO_ONLY=2]="AUDIO_ONLY",e[e.HIGH_STREAM_LAYER1=3]="HIGH_STREAM_LAYER1",e[e.HIGH_STREAM_LAYER2=4]="HIGH_STREAM_LAYER2",e[e.HIGH_STREAM_LAYER3=5]="HIGH_STREAM_LAYER3",e[e.HIGH_STREAM_LAYER4=6]="HIGH_STREAM_LAYER4",e[e.HIGH_STREAM_LAYER5=7]="HIGH_STREAM_LAYER5",e[e.HIGH_STREAM_LAYER6=8]="HIGH_STREAM_LAYER6",e}({}),Xe=function(e){return e.TRANSCEIVER_UPDATED="transceiver-updated",e.SEI_TO_SEND="sei-to-send",e.SEI_RECEIVED="sei-received",e.TRACK_UPDATED="track-updated",e}({}),Qe=function(e){return e.SOURCE_STATE_CHANGE="source-state-change",e.TRACK_ENDED="track-ended",e.BEAUTY_EFFECT_OVERLOAD="beauty-effect-overload",e.VIDEO_ELEMENT_VISIBLE_STATUS="video-element-visible-status",e.CLOSED="closed",e}({}),Je=function(e){return e.FIRST_FRAME_DECODED="first-frame-decoded",e.VIDEO_ELEMENT_VISIBLE_STATUS="video-element-visible-status",e.VIDEO_STATE_CHANGED="video-state-changed",e}({}),qe=function(e){return e.AUDIO="audio",e.VIDEO="video",e.DATA="data",e}({}),$e=function(e){return e.AUDIO_SOURCE_STATE_CHANGE="audio_source_state_change",e.RECEIVE_TRACK_BUFFER="receive_track_buffer",e.ON_AUDIO_BUFFER="on_audio_buffer",e.UPDATE_SOURCE="update_source",e}({}),et=function(e){return e.UPDATE_TRACK_SOURCE="update-track-source",e}({});const tt={sendVolumeLevel:0,sendBitrate:0,sendBytes:0,sendPackets:0,sendPacketsLost:0,sendJitterMs:0,sendRttMs:0,currentPacketLossRate:0},it={sendBytes:0,sendBitrate:0,sendPackets:0,sendPacketsLost:0,sendJitterMs:0,sendRttMs:0,sendResolutionHeight:0,sendResolutionWidth:0,captureResolutionHeight:0,captureResolutionWidth:0,targetSendBitrate:0,totalDuration:0,totalFreezeTime:0,currentPacketLossRate:0},rt={transportDelay:0,end2EndDelay:0,receiveBitrate:0,receiveLevel:0,receiveBytes:0,receiveDelay:0,receivePackets:0,receivePacketsLost:0,receivePacketsDiscarded:0,totalDuration:0,totalFreezeTime:0,freezeRate:0,packetLossRate:0,currentPacketLossRate:0,publishDuration:-1},st={uplinkNetworkQuality:0,downlinkNetworkQuality:0},ot={transportDelay:0,end2EndDelay:0,receiveBitrate:0,receiveBytes:0,receiveDelay:0,receivePackets:0,receivePacketsLost:0,receiveResolutionHeight:0,receiveResolutionWidth:0,totalDuration:0,totalFreezeTime:0,freezeRate:0,packetLossRate:0,currentPacketLossRate:0,publishDuration:-1};let nt=function(e){return e.ON_TRACK="on_track",e.ON_NODE="on_node",e}({}),at=function(e){return e.REQUEST_UPDATE_CONSTRAINTS="request_update_constraints",e.REQUEST_CONSTRAINTS="request_constraints",e}({}),ct=function(e){return e.IDLE="IDLE",e.INITING="INITING",e.INITEND="INITEND",e}({}),dt=function(e){return e.STATE_CHANGE="state_change",e.RECORDING_DEVICE_CHANGED="recordingDeviceChanged",e.PLAYOUT_DEVICE_CHANGED="playoutDeviceChanged",e.CAMERA_DEVICE_CHANGED="cameraDeviceChanged",e}({});function ht(e){return void 0!==e.smoothnessLevel&&_(e.smoothnessLevel,"options.smoothnessLevel",0,1,!1),void 0!==e.lighteningLevel&&_(e.lighteningLevel,"options.lighteningLevel",0,1,!1),void 0!==e.rednessLevel&&_(e.rednessLevel,"options.rednessLevel",0,1,!1),void 0!==e.lighteningContrastLevel&&T(e.lighteningContrastLevel,"options.lighteningContrastLevel",[0,1,2]),!0}let ut=function(e){return e.NONE="none",e.INIT="init",e.CANPLAY="canplay",e.PLAYING="playing",e.PAUSED="paused",e.SUSPEND="suspend",e.STALLED="stalled",e.WAITING="waiting",e.ERROR="error",e.DESTROYED="destroyed",e.ABORT="abort",e.ENDED="ended",e.EMPTIED="emptied",e.LOADEDDATA="loadeddata",e}({}),lt=function(e){return e[e.VideoStateStopped=0]="VideoStateStopped",e[e.VideoStateStarting=1]="VideoStateStarting",e[e.VideoStateDecoding=2]="VideoStateDecoding",e[e.VideoStateFrozen=3]="VideoStateFrozen",e}({});const pt={uninit:100,none:110,init:120,loadeddata:130,canplay:200,playing:210,paused:220,suspend:300,stalled:310,waiting:320,error:330,destroyed:340,abort:350,ended:360,emptied:370};let mt=function(e){return e.OPEN="open",e.MESSAGE="message",e.CLOSE="close",e.CLOSING="closing",e.ERROR="error",e}({});function gt(e,t,i,r,s){var o={};return Object.keys(r).forEach((function(e){o[e]=r[e]})),o.enumerable=!!o.enumerable,o.configurable=!!o.configurable,("value"in o||o.initializer)&&(o.writable=!0),o=i.slice().reverse().reduce((function(i,r){return r(e,t,i)||i}),o),s&&void 0!==o.initializer&&(o.value=o.initializer?o.initializer.call(s):void 0,o.initializer=void 0),void 0===o.initializer?(Object.defineProperty(e,t,o),null):o}function _t(e,t,i){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var r=i.call(e,t||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function ft(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,r)}return i}function Tt(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?ft(Object(i),!0).forEach((function(t){_t(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):ft(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}class vt extends y{set _mediaStreamTrack(e){e!==this.mediaStreamTrack&&(this.safeEmit(Xe.TRACK_UPDATED,e),this.mediaStreamTrack=e)}get _mediaStreamTrack(){return this.mediaStreamTrack}constructor(e,t){super(),_t(this,"trackMediaType",void 0),_t(this,"_ID",void 0),_t(this,"_rtpTransceiver",void 0),_t(this,"_lowRtpTransceiver",void 0),_t(this,"_hints",[]),_t(this,"_isClosed",!1),_t(this,"_originMediaStreamTrack",void 0),_t(this,"mediaStreamTrack",void 0),_t(this,"_external",{}),this._ID=t||k(8,"track-"),this._originMediaStreamTrack=e,this.mediaStreamTrack=e,Ve(this)}toString(){return this._ID}getTrackId(){return this._ID}getMediaStreamTrack(e){return e||b((()=>{var e;pe.reportApiInvoke(null,{name:I.GET_MEDIA_STREAM_TRACK,options:[],tag:A.TRACER}).onSuccess((null===(e=this._mediaStreamTrack)||void 0===e?void 0:e.label)||"")}),this.mediaStreamTrack.id||this.getTrackId()),this._mediaStreamTrack}getRTCRtpTransceiver(e){return e===Ye.LOW_STREAM?this._lowRtpTransceiver:this._rtpTransceiver}getMediaStreamTrackSettings(){return this.getMediaStreamTrack(!0).getSettings()}close(){this._isClosed=!0,this._lowRtpTransceiver=void 0,this._rtpTransceiver=void 0,xe(this),this.emit(Qe.CLOSED),this.removeAllListeners(Xe.SEI_RECEIVED)}_updateRtpTransceiver(e,t){if(t===Ye.LOW_STREAM){if(this._lowRtpTransceiver===e)return;this._lowRtpTransceiver=e}else{if(this._rtpTransceiver===e)return;this._rtpTransceiver=e}this.emit(Xe.TRANSCEIVER_UPDATED,e,t)}}class Et extends vt{get isExternalTrack(){return this._isExternalTrack}get muted(){return this._muted}get enabled(){return this._enabled}get processorContext(){return this._processorContext}constructor(e,t){super(e,t),_t(this,"_enabled",!0),_t(this,"_muted",!1),_t(this,"_isExternalTrack",!1),_t(this,"_isClosed",!1),_t(this,"_enabledMutex",void 0),_t(this,"processor",void 0),_t(this,"_processorContext",void 0),_t(this,"_handleTrackEnded",(()=>{this.onTrackEnded()})),this._enabledMutex=new R("".concat(this.getTrackId())),e.addEventListener("ended",this._handleTrackEnded)}getTrackLabel(){var e,t;return null!==(e=null===(t=this._originMediaStreamTrack)||void 0===t?void 0:t.label)&&void 0!==e?e:""}close(){this._isClosed||(this.stop(),this._originMediaStreamTrack.stop(),this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack.stop(),this._mediaStreamTrack=null),this._originMediaStreamTrack=null,this._enabledMutex=null,le.debug("[".concat(this.getTrackId(),"] close")),this.emit(He.NEED_CLOSE),super.close())}async _updateOriginMediaStreamTrack(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];this._isExternalTrack=i,e!==this._originMediaStreamTrack&&(this._originMediaStreamTrack&&(this._originMediaStreamTrack.removeEventListener("ended",this._handleTrackEnded),t&&this._originMediaStreamTrack.stop()),e.addEventListener("ended",this._handleTrackEnded),this._originMediaStreamTrack=e,this._muted&&(this._originMediaStreamTrack.enabled=!1),this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await w(this,He.NEED_REPLACE_TRACK,this),this.processor&&this._processorContext&&this.processor.updateInput({track:this._originMediaStreamTrack,context:this._processorContext}))}_getDefaultPlayerConfig(){return{}}onTrackEnded(){le.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(Qe.TRACK_ENDED)}stateCheck(e,t){if(le.debug("check track state, [muted: ".concat(this._muted,", enabled: ").concat(this._enabled,"] to [").concat(e,": ").concat(t,"]")),f(t,e),this._enabled&&this._muted&&"enabled"===e&&!1===t)throw new v(E.TRACK_STATE_UNREACHABLE,"cannot set enabled while the track is muted").print("error",le);if(!this._enabled&&!this._muted&&"muted"===e&&!0===t)throw new v(E.TRACK_STATE_UNREACHABLE,"cannot set muted while the track is disabled").print("error",le)}getProcessorStats(){return this._processorContext&&this._processorContext.gatherStats()||[]}getProcessorUsage(){return this._processorContext?this._processorContext.gatherUsage():Promise.resolve([])}}const St=window.AudioContext||window.webkitAudioContext;let yt=null;const kt=new class extends y{constructor(){super(...arguments),_t(this,"prevState",void 0),_t(this,"curState",void 0),_t(this,"currentTime",void 0),_t(this,"currentTimeStuckAt",void 0),_t(this,"interruptDetectorTrack",void 0),_t(this,"onLocalAudioTrackMute",(()=>{le.info("ios15-interruption-start"),this.emit(ye.IOS_15_16_INTERRUPTION_START)})),_t(this,"onLocalAudioTrackUnmute",(async()=>{le.info("ios15-interruption-end"),"running"!==this.curState||this.duringInterruption?le.info("ios15-interruption-end-canceled"):(yt&&await yt.suspend(),this.emit(ye.IOS_15_16_INTERRUPTION_END))}))}get duringInterruption(){return"running"===this.prevState&&"interrupted"===this.curState}bindInterruptDetectorTrack(e){le.debug("webaudio bindInterruptDetectorTrack ".concat(e.getTrackId())),this.interruptDetectorTrack||(this.interruptDetectorTrack=e,this.interruptDetectorTrack._mediaStreamTrack.onmute=this.onLocalAudioTrackMute,this.interruptDetectorTrack._mediaStreamTrack.onunmute=this.onLocalAudioTrackUnmute)}unbindInterruptDetectorTrack(e){le.debug("webaudio unbindInterruptDetectorTrack ".concat(e.getTrackId())),this.interruptDetectorTrack&&this.interruptDetectorTrack===e&&(this.interruptDetectorTrack._mediaStreamTrack&&(this.interruptDetectorTrack._mediaStreamTrack.onmute=null,this.interruptDetectorTrack._mediaStreamTrack.onunmute=null),this.interruptDetectorTrack=void 0)}};function bt(){if(!St)return void le.error("your browser is not support web audio");le.info("create audio context");const t=Tt({},h("WEBAUDIO_INIT_OPTIONS"));le.debug("audio context init option:",JSON.stringify(t)),yt=new St(t),kt.curState=yt.state,yt.onstatechange=()=>{kt.prevState=kt.curState,kt.curState=yt?yt.state:void 0;const{prevState:t,curState:i}=kt,r="running"===i,s="interrupted"===i,o="running"===t,n="suspended"===t,a="interrupted"===t,c=e().osVersion;(C()||N())&&o&&s&&(le.info("ios".concat(c,"-interruption-start")),kt.emit(ye.IOS_INTERRUPTION_START)),(C()||N())&&(n||a)&&r&&(le.info("ios".concat(c,"-interruption-end")),kt.emit(ye.IOS_INTERRUPTION_END)),t!==i&&kt.emit(ye.STATE_CHANGE,i,t)},setInterval((()=>{var e;const t=null===(e=yt)||void 0===e?void 0:e.currentTime;if(kt.currentTime!==t)kt.currentTimeStuckAt&&(le.debug("AudioContext current time resume at ".concat(t)),kt.currentTimeStuckAt=void 0),kt.currentTime=t;else{if(t!==kt.currentTimeStuckAt){pe.reportApiInvoke(null,{name:"WEB_AUDIO_CURRENT_TIME_STUCK",options:{currentTime:t},tag:A.TRACER}).onSuccess(),le.warning("AudioContext current time stuck at ".concat(t))}kt.currentTimeStuckAt=t}}),5e3),async function(e){const t=["click","contextmenu","auxclick","dblclick","mousedown","mouseup","touchend","keydown","keyup"];let i,r=!1,s=!1,o=!1;function n(t){"running"===e.state?a(!1):C()||N()?"suspended"===e.state&&(a(!0),t&&e.resume().then(d,d)):"closed"!==e.state&&(a(!0),t&&e.resume().then(d,d))}function a(e){if(r!==e){r=e;for(let i=0,r=t;i<r.length;i+=1){const t=r[i];e?window.addEventListener(t,h,{capture:!0,passive:!0}):window.removeEventListener(t,h,{capture:!0,passive:!0})}}}function c(){n(!0)}function d(){n(!1)}function h(){n(!0)}function u(e){if(!o)if(i.paused)if(e){let e;l(!1),o=!0;try{e=i.play(),e?e.then(p,p):(i.addEventListener("playing",p),i.addEventListener("abort",p),i.addEventListener("error",p))}catch(e){p()}}else l(!0);else l(!1)}function l(e){if(s!==e){s=e;for(let i=0,r=t;i<r.length;i++){const t=r[i];e?window.addEventListener(t,m,{capture:!0,passive:!0}):window.removeEventListener(t,m,{capture:!0,passive:!0})}}}function p(){i.removeEventListener("playing",p),i.removeEventListener("abort",p),i.removeEventListener("error",p),o=!1,u(!1)}function m(){u(!0)}if(C()){const t=e.createMediaStreamDestination(),r=document.createElement("div");r.innerHTML="<audio x-webkit-airplay='deny'></audio>",i=r.children.item(0),i.controls=!1,i.disableRemotePlayback=!0,i.preload="auto",i.srcObject=t.stream,u(!0)}kt.on(ye.STATE_CHANGE,c),n(!1)}(yt)}function It(){if(!yt){if(bt(),!yt)throw new v(E.NOT_SUPPORTED,"can not create audio context");return yt}return yt}function At(){return!!yt}function Rt(e){if(function(){if(null!==Dt)return Dt;const e=It(),t=e.createBufferSource(),i=e.createGain(),r=e.createGain();t.connect(i),t.connect(r),t.disconnect(i);let s=!1;try{t.disconnect(i)}catch(e){s=!0}return t.disconnect(),Dt=s,s}())return;const t=e.connect,i=e.disconnect;e.connect=(i,r,s)=>(e._inputNodes||(e._inputNodes=[]),e._inputNodes.includes(i)||(i instanceof AudioNode?(e._inputNodes.push(i),t.call(e,i,r,s)):t.call(e,i,r)),e),e.disconnect=(r,s,o)=>{i.call(e),r?D(e._inputNodes,r):e._inputNodes=[];for(const i of e._inputNodes)t.call(e,i)}}function wt(e){const t=It();return new Promise(((i,r)=>{t.decodeAudioData(e,(e=>{i(e)}),(e=>{r(new v(E.DECODE_AUDIO_FILE_FAILED,e.toString()))}))}))}let Dt=null;function Ct(e,t){let i=!1;const r=1/t;if(h("DISABLE_WEBAUDIO")){const t=window.setInterval((()=>{i?window.clearInterval(t):e(performance.now()/1e3)}),1e3*r)}else{const t=It();let s=t.createGain();s.gain.value=0,s.connect(t.destination);const o=()=>{if(i)return void(s=null);const n=t.createOscillator();n.onended=o,n.connect(s),n.start(0),n.stop(t.currentTime+r),e(t.currentTime)};o()}return()=>{i=!0}}let Nt=null;function Mt(){if(Nt)return Nt;const e=It();if(!e.createMediaStreamDestination)throw new v(E.NOT_SUPPORTED,"can not create silence audio track");const t=e.createBufferSource(),i=e.createBuffer(1,44100,44100);t.loop=!0,t.buffer=i;const r=e.createMediaStreamDestination();return t.connect(r),Nt=r.stream.getAudioTracks()[0],Nt}function Ot(e){for(let t=0;t<e.outputBuffer.numberOfChannels;t+=1){const i=e.outputBuffer.getChannelData(t);for(let e=0;e<i.length;e+=1)i[e]=0}return e.inputBuffer}function Lt(e){const t=e.getChannelData(0);let i=0,r=0;for(let e=0;e<t.length;e+=1)0===t[e]?(i+=1,i>r&&(r=i)):i=0;return r/t.length*e.duration}class Pt{constructor(){_t(this,"context",void 0),_t(this,"analyserNode",void 0),_t(this,"sourceNode",void 0),this.context=It(),this.analyserNode=this.context.createAnalyser(),this.analyserNode.fftSize=2048,this.analyserNode.smoothingTimeConstant=.4}updateSource(e){if(e!==this.sourceNode){if(this.sourceNode)try{this.sourceNode.disconnect(this.analyserNode)}catch(e){}this.sourceNode=e,null==e||e.connect(this.analyserNode)}}getVolumeLevel(){if(!this.sourceNode)return 0;if(!this.context||C()||N()||"running"!==this.context.state&&this.context.resume(),!this.analyserNode)return 0;const e=new Float32Array(this.analyserNode.fftSize);if(this.analyserNode.getFloatTimeDomainData)this.analyserNode.getFloatTimeDomainData(e);else{const t=new Uint8Array(this.analyserNode.fftSize);this.analyserNode.getByteTimeDomainData(t);for(let i=0;i<e.length;++i)e[i]=t[i]/128-1}const t=e.reduce(((e,t)=>e+t*t),0)/e.length;return Math.max(10*Math.log10(t)+100,0)/100}getAnalyserNode(){return this.analyserNode}rebuildAnalyser(){try{var e,t;null===(e=this.sourceNode)||void 0===e||e.disconnect(this.analyserNode),this.analyserNode=this.context.createAnalyser(),this.analyserNode.fftSize=2048,this.analyserNode.smoothingTimeConstant=.4,null===(t=this.sourceNode)||void 0===t||t.connect(this.analyserNode)}catch(e){le.warning("rebuild analyser node failed.")}}destroy(){this.updateSource(void 0)}}class Vt extends y{get processSourceNode(){return this.sourceNode}set processedNode(e){var t;if(!this.isDestroyed&&this._processedNode!==e){try{var i;null===(i=this.sourceNode)||void 0===i||i.disconnect(this.outputNode)}catch(e){}null===(t=this._processedNode)||void 0===t||t.disconnect(),this._processedNode=e,this.connect()}}get processedNode(){return this._processedNode}constructor(){super(),_t(this,"outputNode",void 0),_t(this,"outputTrack",void 0),_t(this,"isPlayed",!1),_t(this,"sourceNode",void 0),_t(this,"context",void 0),_t(this,"audioBufferNode",void 0),_t(this,"destNode",void 0),_t(this,"audioOutputLevel",0),_t(this,"volumeLevelAnalyser",void 0),_t(this,"_processedNode",void 0),_t(this,"playNode",void 0),_t(this,"isDestroyed",!1),_t(this,"onNoAudioInput",void 0),_t(this,"isNoAudioInput",!1),_t(this,"_noAudioInputCount",0),this.context=It(),this.playNode=this.context.destination,this.outputNode=this.context.createGain(),Rt(this.outputNode),this.volumeLevelAnalyser=new Pt}startGetAudioBuffer(e){this.audioBufferNode||(this.audioBufferNode=this.context.createScriptProcessor(e),this.outputNode.connect(this.audioBufferNode),this.audioBufferNode.connect(this.context.destination),this.audioBufferNode.onaudioprocess=e=>{this.emit($e.ON_AUDIO_BUFFER,Ot(e))})}stopGetAudioBuffer(){this.audioBufferNode&&(this.audioBufferNode.onaudioprocess=null,this.outputNode.disconnect(this.audioBufferNode),this.audioBufferNode=void 0)}createOutputTrack(){if(!ve().webAudioMediaStreamDest)throw new v(E.NOT_SUPPORTED,"your browser is not support audio processor");return this.destNode&&this.outputTrack||(this.destNode=this.context.createMediaStreamDestination(),this.outputNode.connect(this.destNode),this.outputTrack=this.destNode.stream.getAudioTracks()[0]),this.outputTrack}play(e){"running"!==this.context.state&&r((()=>{kt.emit("autoplay-failed")})),this.isPlayed=!0,this.playNode=e||this.context.destination,this.outputNode.connect(this.playNode)}stop(){if(this.isPlayed)try{this.outputNode.disconnect(this.playNode)}catch(e){}this.isPlayed=!1}getAccurateVolumeLevel(){return this.volumeLevelAnalyser.getVolumeLevel()}async checkHasAudioInput(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;if(e>5)return this.isNoAudioInput=!0,this.onNoAudioInput&&this.onNoAudioInput(),!1;C()||N()?"suspended"===this.context.state&&this.context.resume():"running"!==this.context.state&&this.context.resume();const t=this.volumeLevelAnalyser.getAnalyserNode();let i;t.getFloatTimeDomainData?(i=new Float32Array(t.fftSize),t.getFloatTimeDomainData(i)):(i=new Uint8Array(t.fftSize),t.getByteTimeDomainData(i));let r=!1;for(let e=0;e<i.length;e++)0!==i[e]&&(r=!0);return r?(this.isNoAudioInput=!1,!0):(await M(200),await this.checkHasAudioInput(e?e+1:1)&&r)}getAudioVolume(){return this.outputNode.gain.value}setVolume(e){this.outputNode.gain.setValueAtTime(e,this.context.currentTime)}destroy(){this.disconnect(),this.stop(),this.isDestroyed=!0,this.onNoAudioInput=void 0}disconnect(){var e,t;null===(e=this.processedNode)||void 0===e||e.disconnect(),null===(t=this.sourceNode)||void 0===t||t.disconnect(),this.outputNode&&this.outputNode.disconnect()}connect(){var e;this.processedNode?null===(e=this.processedNode)||void 0===e||e.connect(this.outputNode):this.sourceNode&&this.sourceNode.connect(this.outputNode);this.volumeLevelAnalyser.updateSource(this.outputNode)}}class xt extends Vt{get isFreeze(){return!1}constructor(t,i,r){var s;if(super(),_t(this,"sourceNode",void 0),_t(this,"track",void 0),_t(this,"clonedTrack",void 0),_t(this,"audioElement",void 0),_t(this,"isCurrentTrackCloned",!1),_t(this,"isRemoteTrack",!1),_t(this,"originVolumeLevelAnalyser",void 0),_t(this,"rebuildWebAudio",(async()=>{if(le.debug("ready to rebuild web audio, state:",this.context.state),this.isNoAudioInput&&await this.checkHasAudioInput(),!this.isNoAudioInput||this.isDestroyed)return document.body.removeEventListener("click",this.rebuildWebAudio,!0),void le.debug("rebuild web audio success, current volume status",this.getAccurateVolumeLevel());this.context.resume().then((()=>le.info("resume success"))),le.debug("rebuild web audio because of ios 12 bugs"),this.disconnect();const e=this.track;this.track=this.track.clone(),this.isCurrentTrackCloned?e.stop():this.isCurrentTrackCloned=!0;const t=new MediaStream([this.track]);this.sourceNode=this.context.createMediaStreamSource(t),Rt(this.sourceNode),this.volumeLevelAnalyser.rebuildAnalyser();const i=this.outputNode.gain.value;this.outputNode=this.context.createGain(),this.outputNode.gain.setValueAtTime(i,this.context.currentTime),Rt(this.outputNode),this.emit($e.UPDATE_SOURCE),this.connect(),this.audioElement.srcObject=t,this.isPlayed&&this.play(this.playNode),this.checkHasAudioInput()})),"audio"!==t.kind)throw new v(E.UNEXPECTED_ERROR);this.track=t;const o=new MediaStream([this.track]);if(this.isRemoteTrack=!!i,this.sourceNode=this.context.createMediaStreamSource(o),Rt(this.sourceNode),r){const e=r.clone();e.enabled=!0,this.clonedTrack=e,le.debug("create an unmuted track ".concat(e.id," from the original track ").concat(r.id," to get the volume"));const t=this.context.createMediaStreamSource(new MediaStream([e]));Rt(t),this.originVolumeLevelAnalyser=new Pt,this.originVolumeLevelAnalyser.updateSource(t)}this.connect(),this.audioElement=document.createElement("audio"),this.audioElement.srcObject=o;const n=e();i&&n.os===a.IOS&&Number(null===(s=n.osVersion)||void 0===s?void 0:s.split(".")[0])<15&&(kt.on(ye.STATE_CHANGE,(()=>{"suspended"===this.context.state?document.body.addEventListener("click",this.rebuildWebAudio,!0):"running"===this.context.state&&this.rebuildWebAudio()})),this.checkHasAudioInput().then((e=>{e||document.body.addEventListener("click",this.rebuildWebAudio,!0)})))}updateTrack(e){this.sourceNode.disconnect(),this.track=e,this.isCurrentTrackCloned=!1;const t=new MediaStream([e]);this.sourceNode=this.context.createMediaStreamSource(t),Rt(this.sourceNode),this.processedNode||this.sourceNode.connect(this.outputNode),this.emit($e.UPDATE_SOURCE),this.audioElement.srcObject=t}destroy(){var e;this.audioElement.srcObject=null,this.audioElement.remove(),kt.off("state-change",this.rebuildWebAudio),null===(e=this.originVolumeLevelAnalyser)||void 0===e||e.destroy(),this.clonedTrack=void 0,super.destroy()}createMediaStreamSourceNode(e){return this.context.createMediaStreamSource(new MediaStream([e]))}updateOriginTrack(e){const t=e.clone();t.enabled=!0,this.clonedTrack&&(this.clonedTrack.stop(),this.clonedTrack=t),le.debug("create an unmuted track ".concat(t.id," from the original track ").concat(e.id," to get the volume"));const i=this.context.createMediaStreamSource(new MediaStream([t]));Rt(i),this.originVolumeLevelAnalyser&&this.originVolumeLevelAnalyser.updateSource(i)}getOriginVolumeLevel(){return this.originVolumeLevelAnalyser?this.originVolumeLevelAnalyser.getVolumeLevel():this.getAccurateVolumeLevel()}}async function Ut(e,t,i){const r=(e,t)=>e?"number"!=typeof e?e.max||e.exact||e.ideal||e.min||t:e:t,s={audio:!!i&&{mandatory:{chromeMediaSource:"desktop"}},video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:e,maxHeight:r(t.height,1080),maxWidth:r(t.width,1920)}}};return t.frameRate&&"number"!=typeof t.frameRate?(s.video.mandatory.maxFrameRate=t.frameRate.max,s.video.mandatory.minFrameRate=t.frameRate.min):"number"==typeof t.frameRate&&(s.video.mandatory.maxFrameRate=t.frameRate),await navigator.mediaDevices.getUserMedia(s)}async function Bt(e,t){const i=await Ft(e.mediaSource),{sourceId:r,audio:s}=await O(i,t);return await Ut(r,e,s)}async function Ft(e){let t=["window","screen"];"application"!==e&&"window"!==e||(t=["window"]),"screen"===e&&(t=["screen"]);const i=L();if(!i)throw console.error("failed to fetch electron, please mount it to window"),new v(E.ELECTRON_IS_NULL);let r=null;try{var s;r=(null===(s=i.desktopCapturer)||void 0===s?void 0:s.getSources({types:t}))||i.ipcRenderer.invoke("DESKTOP_CAPTURER_GET_SOURCES",{types:t})}catch(e){r=null}r&&r.then||(r=new Promise(((e,r)=>{i.desktopCapturer.getSources({types:t},((t,i)=>{t?r(t):e(i)}))})));try{return await r}catch(e){throw new v(E.ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR,e.toString())}}const Gt=new R("safari");let Wt=!1,Ht=!1;async function Kt(e,t){let i=0,r=null;for(;i<2;)try{r=await Zt(e,t,i>0);break}catch(e){if(e instanceof v)throw le.error("[".concat(t,"] ").concat(e.toString())),e;const r=Yt(e.name||e.code||e,e.message);if(r.code===E.MEDIA_OPTION_INVALID){le.debug("[".concat(t,"] detect media option invalid, retry")),i+=1,await M(500);continue}throw le.error("[".concat(t,"] ").concat(r.toString())),r}if(!r)throw new v(E.UNEXPECTED_ERROR,"can not find stream after getUserMedia");return r}async function Zt(t,i,r){if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)throw new v(E.NOT_SUPPORTED,"can not find getUserMedia");r&&(t.video&&(delete t.video.width,delete t.video.height),t.screen&&(delete t.screen.width,delete t.screen.height));const s=ve(),o=new MediaStream;if(t.audioSource&&o.addTrack(t.audioSource),t.videoSource&&o.addTrack(t.videoSource),!t.audio&&!t.video&&!t.screen)return le.debug("Using Video Source/ Audio Source"),o;if(t.screen)if(P())if(t.screen.sourceId){zt(o,await Ut(t.screen.sourceId,t.screen,!!t.screenAudio))}else{zt(o,await Bt(t.screen,!!t.screenAudio))}else if(l()&&t.screen.extensionId&&t.screen.mandatory){if(!s.getStreamFromExtension)throw new v(E.NOT_SUPPORTED,"This browser does not support screen sharing");le.debug("[".concat(i,'] Screen access on chrome stable, looking for extension"'));const e=await(a=t.screen.extensionId,p=i,new Promise(((e,t)=>{try{chrome.runtime.sendMessage(a,{getStream:!0},(i=>{if(!i||!i.streamId)return le.error("[".concat(p,"] No response from Chrome Plugin. Plugin not installed properly"),i),void t(new v(E.CHROME_PLUGIN_NO_RESPONSE,"No response from Chrome Plugin. Plugin not installed properly"));e(i.streamId)}))}catch(e){le.error("[".concat(p,"] AgoraRTC screensharing plugin is not accessible(").concat(a,")"),e.toString()),t(new v(E.CHROME_PLUGIN_NOT_INSTALL))}})));t.screen.mandatory.chromeMediaSourceId=e;zt(o,await navigator.mediaDevices.getUserMedia({video:{mandatory:t.screen.mandatory}}))}else if(s.getDisplayMedia){var n;t.screen.mediaSource&&We(t.screen.mediaSource);const e={width:t.screen.width,height:t.screen.height,frameRate:t.screen.frameRate,displaySurface:null!==(n=t.screen.displaySurface)&&void 0!==n?n:"screen"===t.screen.mediaSource?"monitor":t.screen.mediaSource},{selfBrowserSurface:r,surfaceSwitching:s,systemAudio:a,preferCurrentTab:c}=t.screen,d={selfBrowserSurface:r,surfaceSwitching:s,systemAudio:a,preferCurrentTab:c};!r&&delete d.selfBrowserSurface,!s&&delete d.surfaceSwitching,!a&&delete d.systemAudio,!c&&delete d.preferCurrentTab,le.debug("[".concat(i,"] getDisplayMedia:"),JSON.stringify({video:e,audio:t.screenAudio,controls:d}));zt(o,await navigator.mediaDevices.getDisplayMedia(Tt({video:e,audio:t.screenAudio},d)))}else{if(!u())throw le.error("[".concat(i,"] This browser does not support screenSharing")),new v(E.NOT_SUPPORTED,"This browser does not support screen sharing");{t.screen.mediaSource&&We(t.screen.mediaSource);const e={video:{mediaSource:t.screen.mediaSource,width:t.screen.width,height:t.screen.height,frameRate:t.screen.frameRate}};le.debug("[".concat(i,"] getUserMedia: ").concat(JSON.stringify(e)));zt(o,await navigator.mediaDevices.getUserMedia(e))}}var a,p;if(!t.video&&!t.audio)return o;let m={video:t.video,audio:t.audio},g=h("MEDIA_DEVICE_CONSTRAINTS");if(g)try{"string"==typeof g&&(g=JSON.parse(g)),m=V(m,g)}catch(e){}le.debug("[".concat(i,"] GetUserMedia"),JSON.stringify(m)),e();let _,f=null;(c()||C()||d())&&(f=await Gt.lock());try{_=await navigator.mediaDevices.getUserMedia(m)}catch(e){throw f&&f(),e}return m.audio&&(Wt=!0),m.video&&(Ht=!0),zt(o,_),f&&f(),o}function Yt(e,t){switch(e){case"Starting video failed":case"OverconstrainedError":case"TrackStartError":return new v(E.MEDIA_OPTION_INVALID,"".concat(e,": ").concat(t));case"NotFoundError":case"DevicesNotFoundError":return new v(E.DEVICE_NOT_FOUND,"".concat(e,": ").concat(t));case"NotSupportedError":return new v(E.NOT_SUPPORTED,"".concat(e,": ").concat(t));case"NotReadableError":return new v(E.NOT_READABLE,"".concat(e,": ").concat(t));case"InvalidStateError":case"NotAllowedError":case"PERMISSION_DENIED":case"PermissionDeniedError":return new v(E.PERMISSION_DENIED,"".concat(e,": ").concat(t));case"ConstraintNotSatisfiedError":return new v(E.CONSTRAINT_NOT_SATISFIED,"".concat(e,": ").concat(t));default:return le.error("getUserMedia unexpected error",e),new v(E.UNEXPECTED_ERROR,"".concat(e,": ").concat(t))}}function zt(e,t){const i=e.getVideoTracks()[0],r=e.getAudioTracks()[0],s=t.getVideoTracks()[0],o=t.getAudioTracks()[0];o&&(r&&e.removeTrack(r),e.addTrack(o)),s&&(i&&e.removeTrack(i),e.addTrack(s))}class jt extends y{get state(){return this._state}set state(e){e!==this._state&&(this.emit(dt.STATE_CHANGE,e),this._state=e)}constructor(){super(),_t(this,"_state",ct.IDLE),_t(this,"isAccessMicrophonePermission",!1),_t(this,"isAccessCameraPermission",!1),_t(this,"lastAccessMicrophonePermission",!1),_t(this,"lastAccessCameraPermission",!1),_t(this,"checkdeviceMatched",!1),_t(this,"deviceInfoMap",new Map),this.init().then((()=>{navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",this.updateDevicesInfo.bind(this)),window.setInterval((()=>{(h("ENUMERATE_DEVICES_INTERVAL")||(x()||U())&&i())&&this.updateDevicesInfo()}),h("ENUMERATE_DEVICES_INTERVAL_TIME"))})).catch((e=>le.error(e.toString())))}async enumerateDevices(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices){return new v(E.NOT_SUPPORTED,"enumerateDevices() not supported.").throw()}const r=await navigator.mediaDevices.enumerateDevices(),s=this.checkMediaDeviceInfoIsOk(r);let o=!this.isAccessMicrophonePermission&&e,n=!this.isAccessCameraPermission&&t;s.audio&&(o=!1),s.video&&(n=!1);let a=null,c=null,d=null;if(!i&&(o||n)){if(Gt.isLocked){le.debug("[device manager] wait GUM lock");(await Gt.lock())(),le.debug("[device manager] GUM unlock")}if(Wt&&(o=!1,this.isAccessMicrophonePermission=!0),Ht&&(n=!1,this.isAccessCameraPermission=!0),le.debug("[device manager] check media device permissions",e,t,o,n),o&&n){try{d=await navigator.mediaDevices.getUserMedia({audio:!0,video:!0})}catch(e){const t=Yt(e.name||e.code||e,e.message);if(t.code===E.PERMISSION_DENIED)throw t;le.warning("getUserMedia failed in getDevices",t)}this.isAccessCameraPermission=!0,this.isAccessMicrophonePermission=!0}else if(o){try{a=await navigator.mediaDevices.getUserMedia({audio:e})}catch(e){const t=Yt(e.name||e.code||e,e.message);if(t.code===E.PERMISSION_DENIED)throw t;le.warning("getUserMedia failed in getDevices",t)}this.isAccessMicrophonePermission=!0}else if(n){try{c=await navigator.mediaDevices.getUserMedia({video:t})}catch(e){const t=Yt(e.name||e.code||e,e.message);if(t.code===E.PERMISSION_DENIED)throw t;le.warning("getUserMedia failed in getDevices",t)}this.isAccessCameraPermission=!0}le.debug("[device manager] mic permission",e,"cam permission",t)}try{const e=await navigator.mediaDevices.enumerateDevices();return a&&a.getTracks().forEach((e=>e.stop())),c&&c.getTracks().forEach((e=>e.stop())),d&&d.getTracks().forEach((e=>e.stop())),a=null,c=null,d=null,e}catch(e){a&&a.getTracks().forEach((e=>e.stop())),c&&c.getTracks().forEach((e=>e.stop())),d&&d.getTracks().forEach((e=>e.stop())),a=null,c=null,d=null;return new v(E.ENUMERATE_DEVICES_FAILED,e.toString()).throw()}}async getRecordingDevices(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return(await this.enumerateDevices(!0,!1,e)).filter((e=>"audioinput"===e.kind))}async getCamerasDevices(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return(await this.enumerateDevices(!1,!0,e)).filter((e=>"videoinput"===e.kind))}async getSpeakers(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return(await this.enumerateDevices(!0,!1,e)).filter((e=>"audiooutput"===e.kind))}searchDeviceIdByName(e){let t=null;return this.deviceInfoMap.forEach((i=>{i.device.label===e&&(t=i.device.deviceId)})),t}async getDeviceById(e){const t=(await this.enumerateDevices(!0,!0,!0)).find((t=>t.deviceId===e));if(!t)throw new v(E.DEVICE_NOT_FOUND,"deviceId: ".concat(e));return t}async init(){this.state=ct.INITING;try{await this.updateDevicesInfo(),this.state=ct.INITEND}catch(e){if(le.warning("Device Detection functionality cannot start properly.",e.toString()),this.state=ct.IDLE,!B()){new v(E.WEB_SECURITY_RESTRICT,"Your context is limited by web security, please try using https protocol or localhost.").throw()}throw e}}async updateDevicesInfo(){const e=await this.enumerateDevices(!0,!0,!0),t=Date.now(),i=[];if(e[0]&&e[0].label&&!1===this.checkdeviceMatched){this.checkdeviceMatched=!0;const t=e.find((e=>"audioinput"===e.kind&&"default"===e.deviceId)),i=e.find((e=>"audiooutput"===e.kind&&"default"===e.deviceId));t&&i?i.groupId===t.groupId?le.debug("[device-check] default input ".concat(t.label," and output ").concat(i.label," is the same group")):le.debug("[device-check] default input ".concat(t.label," and output ").concat(i.label," is not the same group")):le.debug("[device-check] default input or output not found")}const r=this.checkMediaDeviceInfoIsOk(e);if(e.forEach((e=>{if(!e.deviceId)return;const r=this.deviceInfoMap.get("".concat(e.kind,"_").concat(e.deviceId));if("ACTIVE"!==(r?r.state:"INACTIVE")){const r={initAt:t,updateAt:t,device:e,state:"ACTIVE"};this.deviceInfoMap.set("".concat(e.kind,"_").concat(e.deviceId),r),i.push(r)}r&&(r.updateAt=t)})),this.deviceInfoMap.forEach(((e,r)=>{"ACTIVE"===e.state&&e.updateAt!==t&&(e.state="INACTIVE",i.push(e))})),this.state!==ct.INITEND)return r.audio&&(this.lastAccessMicrophonePermission=!0,this.isAccessMicrophonePermission=!0),void(r.video&&(this.lastAccessCameraPermission=!0,this.isAccessCameraPermission=!0));i.forEach((e=>{switch(e.device.kind){case"audioinput":this.lastAccessMicrophonePermission&&this.isAccessMicrophonePermission&&this.emit(dt.RECORDING_DEVICE_CHANGED,e);break;case"videoinput":this.lastAccessCameraPermission&&this.isAccessCameraPermission&&this.emit(dt.CAMERA_DEVICE_CHANGED,e);break;case"audiooutput":this.lastAccessMicrophonePermission&&this.isAccessMicrophonePermission&&this.emit(dt.PLAYOUT_DEVICE_CHANGED,e)}})),r.audio&&(this.lastAccessMicrophonePermission=!0,this.isAccessMicrophonePermission=!0),r.video&&(this.lastAccessCameraPermission=!0,this.isAccessCameraPermission=!0)}checkMediaDeviceInfoIsOk(e){const t=e.filter((e=>"audioinput"===e.kind)),i=e.filter((e=>"videoinput"===e.kind)),r={audio:!1,video:!1};for(const e of t)if(e.label&&e.deviceId){r.audio=!0;break}for(const e of i)if(e.label&&e.deviceId){r.video=!0;break}return r}}const Xt=new jt;let Qt=!1;const Jt=new class extends y{constructor(){super(...arguments),_t(this,"onAutoplayFailed",void 0),_t(this,"onAudioAutoplayFailed",void 0)}};function qt(){if(e(),!Qt){const e=t=>{t.preventDefault(),Qt=!1,F()?document.body.removeEventListener("click",e,!0):(document.body.removeEventListener("touchstart",e,!0),document.body.removeEventListener("mousedown",e,!0))};Qt=!0,F()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0)),le.info("detect media autoplay failed, document: https://docs.agora.io/cn/Voice/autoplay_policy_web_ng?platform=Web"),Jt.onAutoplayFailed?Jt.onAutoplayFailed():Jt.onAudioAutoplayFailed?le.warning("AgoraRTC.onAudioAutoplayFailed has been deprecated in favor of AgoraRTC.onAutoplayFailed.\n\n Please refer to the Agora document to migrate the newer API, https://docs.agora.io/en/Voice/autoplay_policy_web_ng?platform=Web ."):le.warning("We have detected a media autoplay failed event, and found out that you haven't implemented AgoraRTC.onAutoplayFailed callback yet.\n\n It will cause audio/video element not playing automatically on some browsers without user interaction, possibly hurting user experiences.\n\n Please refer to the Agora document to properly handle autoplay failed event, https://docs.agora.io/en/Voice/autoplay_policy_web_ng?platform=Web ."),Jt.emit("autoplay-failed")}}function $t(e,t,i,r){if(!e)return;const s=pe.getBaseInfoBySessionId(e);if(!s)return;const o=s.info,n=Date.now(),a=Tt(Tt({},o),{},{vid:void 0===o.vid?0:Number(o.vid),lts:n,elapse:n-s.startTime,cbRegistered:Jt.onAutoplayFailed||Jt.onAudioAutoplayFailed?1:-1,errorMsg:i,mediaType:t,trackId:r,extend:void 0});pe.send({type:me.AUTOPLAY_FAILED,data:a},!0)}const ei=["play","playing","loadeddata","canplay","pause","stalled","suspend","waiting","abort","emptied","ended","error"],ti=new class{constructor(){_t(this,"onAutoplayFailed",void 0),_t(this,"elementMap",new Map),_t(this,"elementStateMap",new Map),_t(this,"elementsNeedToResume",[]),_t(this,"sinkIdMap",new Map),_t(this,"autoResumeAfterInterruption",(e=>{Array.from(this.elementMap.entries()).forEach((t=>{let[i,r]=t;const s=this.elementStateMap.get(i),o=r.srcObject.getAudioTracks()[0],n=o&&o.readyState;if(le.debug("resume after interrupted, ele: ".concat(s," audio: ").concat(n," ").concat(e)),"live"===n){if(e)return r.pause(),void r.play();if("running"===kt.curState)return W()?(r.pause(),void r.play()):void(s&&"paused"===s&&r.play())}}))})),_t(this,"autoResumeAfterInterruptionOnIOS15_16",(()=>{Array.from(this.elementMap.entries()).forEach((e=>{let[t,i]=e;const r=i.srcObject.getAudioTracks()[0];r&&"live"===r.readyState&&(le.debug("auto resume after interruption inside autoResumeAfterInterruptionOnIOS15"),i.pause(),i.play())}))})),this.autoResumeAudioElement(),kt.on(ye.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),kt.on(ye.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16),kt.on(ye.STATE_CHANGE,(()=>{C()&&"suspended"===kt.prevState&&"running"===kt.curState&&this.autoResumeAfterInterruption()}))}async setSinkID(e,t){const i=this.elementMap.get(e);if(this.sinkIdMap.set(e,t),i)try{await i.setSinkId(t)}catch(e){throw new v(E.PERMISSION_DENIED,"can not set sink id: "+e.toString())}}play(e,t,i,s){if(this.elementMap.has(t))return;const o=document.createElement("audio");o.autoplay=!0,o.srcObject=new MediaStream([e]),this.bindAudioElementEvents(t,o),this.elementMap.set(t,o),this.elementStateMap.set(t,ut.INIT),this.setVolume(t,i);const n=this.sinkIdMap.get(t);if(n)try{o.setSinkId(n).catch((e=>{le.warning("[".concat(t,"] set sink id failed"),e.toString())}))}catch(e){le.warning("[".concat(t,"] set sink id failed"),e.toString())}const a=o.play();a&&a.then&&a.catch((e=>{s&&$t(s,"audio",e.message,t),le.warning("audio element play warning",e.toString()),this.elementMap.has(t)&&"NotAllowedError"===e.name&&(le.warning("detected audio element autoplay failed"),this.elementsNeedToResume.push(o),r((()=>{this.onAutoplayFailed&&this.onAutoplayFailed(),qt()})))}))}updateTrack(e,t){const i=this.elementMap.get(e);i&&(i.srcObject=new MediaStream([t]))}isPlaying(e){return this.elementMap.has(e)&&"playing"===this.elementStateMap.get(e)}setVolume(e,t){const i=this.elementMap.get(e);i&&(t=Math.max(0,Math.min(100,t)),i.volume=t/100)}stop(e){const t=this.elementMap.get(e);if(this.sinkIdMap.delete(e),!t)return;const i=this.elementsNeedToResume.indexOf(t);this.elementsNeedToResume.splice(i,1),t.srcObject=null,t.remove(),this.elementMap.delete(e),this.elementStateMap.delete(e)}bindAudioElementEvents(e,t){ei.forEach((i=>{t.addEventListener(i,(i=>{const r=this.elementStateMap.get(e),s="pause"===i.type?"paused":i.type;if(le.debug("[".concat(e,"] audio-element-status change ").concat(r," => ").concat(s)),"error"===i.type){const i=null==t?void 0:t.error;i&&le.error("[".concat(e,"] media error, code: ").concat(i.code,", message: ").concat(i.message))}this.elementStateMap.set(e,s)}))}))}getPlayerState(e){return this.elementStateMap.get(e)||"uninit"}autoResumeAudioElement(){const e=()=>{this.elementsNeedToResume.forEach((e=>{e.play().then((e=>{le.debug("Auto resume audio element success")})).catch((e=>{le.warning("Auto resume audio element failed!",e)}))})),this.elementsNeedToResume=[]};G().then((()=>{F()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0))}))}};function ii(){return function(e,t,i){const r=i.value;return"function"==typeof r&&(i.value=function(){this._isClosed&&new v(E.INVALID_OPERATION,"[".concat(this.getTrackId(),"] cannot operate a closed track")).print("warning",le);for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];const s=r.apply(this,t);return s instanceof Promise?new Promise(((e,t)=>{s.then(e).catch(t)})):s}),i}}class ri extends y{constructor(e){super(),_t(this,"name","VideoProcessorDestination"),_t(this,"ID","0"),_t(this,"_source",void 0),_t(this,"videoContext",void 0),_t(this,"inputTrack",void 0),this.videoContext=e}get kind(){return"video"}get enabled(){return!0}pipe(){throw new v(E.NOT_SUPPORTED,"VideoProcessor cannot pipe to any other Processor")}unpipe(){throw new v(E.NOT_SUPPORTED,"VideoProcessor cannot unpipe to any other Processor")}enable(){}disable(){}updateInput(e){if(e.context!==this.videoContext)throw new Error("ProcessorContext passed to VideoTrack.processorDestination doesn't match it's belonging VideoTrack's context.\nProbably you are making pipeline like this:\nvideoTrack1.pipe(processor).pipe(videoTrack2.processorDestination).");e.track&&e.track!==this.inputTrack&&(this.videoContext.chained=!0,this.inputTrack=e.track,this.emit(nt.ON_TRACK,e.track))}reset(){this.inputTrack=void 0,this.videoContext.chained=!1,this.emit(nt.ON_TRACK,void 0)}}class si extends y{set chained(e){this._chained=e}get chained(){return this._chained}constructor(e,t){super(),_t(this,"constraintsMap",new Map),_t(this,"statsRegistry",[]),_t(this,"usageRegistry",[]),_t(this,"trackId",void 0),_t(this,"direction",void 0),_t(this,"_chained",!1),this.trackId=e,this.direction=t}async getConstraints(){return await H(this,at.REQUEST_CONSTRAINTS)}async requestApplyConstraints(e,t){return le.info("processor ".concat(t.name," requestApplyConstraints for ").concat(this.trackId)),e&&this.constraintsMap.set(t,e),w(this,at.REQUEST_UPDATE_CONSTRAINTS,Array.from(this.constraintsMap.values()))}async requestRevertConstraints(e){if(this.constraintsMap.has(e))return le.info("processor ".concat(e.name," requestRevertConstraints for ").concat(this.trackId)),this.constraintsMap.delete(e),w(this,at.REQUEST_UPDATE_CONSTRAINTS,Array.from(this.constraintsMap.values()))}registerStats(e,t,i){this.statsRegistry.find((i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t))||this.statsRegistry.push({processorName:e.name,processorID:e.ID,type:t,cb:i})}unregisterStats(e,t){const i=this.statsRegistry.findIndex((i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t));-1!==i&&this.statsRegistry.splice(i,1)}gatherStats(){const e=[];for(const{processorID:t,processorName:i,type:r,cb:s}of this.statsRegistry)try{const o=s();e.push({processorID:t,processorName:i,type:r,stats:o})}catch(e){le.error(new v(E.UNEXPECTED_ERROR,e.message))}return e}registerUsage(e,t){this.usageRegistry.find((t=>t.processorID===e.ID&&t.processorName===e.name))||this.usageRegistry.push({processorID:e.ID,processorName:e.name,cb:t})}unregisterUsage(e){const t=this.usageRegistry.findIndex((t=>t.processorID===e.ID&&t.processorName===e.name));-1!==t&&this.usageRegistry.splice(t,1)}async gatherUsage(){const e=[];if(!this.chained)return[];for(const{cb:t}of this.usageRegistry)try{let i=t();i instanceof Promise&&(i=await i),e.push(Tt(Tt({},i),{},{direction:this.direction}))}catch(e){le.error("gather extension usage error",e)}return e}getDirection(){return this.direction}}class oi extends y{constructor(e){super(),_t(this,"name","AudioProcessorDestination"),_t(this,"ID","0"),_t(this,"inputTrack",void 0),_t(this,"inputNode",void 0),_t(this,"audioProcessorContext",void 0),_t(this,"_source",void 0),this.audioProcessorContext=e}get kind(){return"audio"}get enabled(){return!0}pipe(){throw new v(E.NOT_SUPPORTED,"AudioProcessorDestination cannot pipe to any other Processor")}unpipe(){throw new v(E.NOT_SUPPORTED,"AudioProcessor cannot unpipe to any other Processor")}enable(){}disable(){}reset(){this.inputTrack=void 0,this.inputNode=void 0,this.audioProcessorContext.chained=!1,this.emit(nt.ON_TRACK,void 0),this.emit(nt.ON_NODE,void 0)}updateInput(e){if(e.context!==this.audioProcessorContext)throw new Error("ProcessorContext passed to AudioTrack.processorDestination doesn't match it's belonging AudioTrack's context.\n Probably you are making pipeline like this: audioTrack1.pipe(processor).pipe(audioTrack2.processorDestination).");e.track&&this.inputTrack!==e.track&&(this.audioProcessorContext.chained=!0,this.inputTrack=e.track,this.emit(nt.ON_TRACK,this.inputTrack)),e.node&&this.inputNode!==e.node&&(this.audioProcessorContext.chained=!0,this.inputNode=e.node,this.emit(nt.ON_NODE,this.inputNode))}}class ni extends y{set chained(e){this._chained=e}get chained(){return this._chained}constructor(e,t,i){super(),_t(this,"constraintsMap",new Map),_t(this,"statsRegistry",[]),_t(this,"audioContext",void 0),_t(this,"trackId",void 0),_t(this,"direction",void 0),_t(this,"usageRegistry",[]),_t(this,"_chained",!1),this.audioContext=e,this.trackId=t,this.direction=i}async getConstraints(){return H(this,at.REQUEST_CONSTRAINTS)}getAudioContext(){return this.audioContext}async requestApplyConstraints(e,t){return le.info("processor ".concat(t.name," requestApplyConstraints for ").concat(this.trackId)),e&&this.constraintsMap.set(t,e),w(this,at.REQUEST_UPDATE_CONSTRAINTS,Array.from(this.constraintsMap.values()))}async requestRevertConstraints(e){if(this.constraintsMap.has(e))return this.constraintsMap.delete(e),w(this,at.REQUEST_UPDATE_CONSTRAINTS,Array.from(this.constraintsMap.values()))}registerStats(e,t,i){this.statsRegistry.find((i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t))||this.statsRegistry.push({processorName:e.name,processorID:e.ID,type:t,cb:i})}unregisterStats(e,t){const i=this.statsRegistry.findIndex((i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t));-1!==i&&this.statsRegistry.splice(i,1)}gatherStats(){const e=[];for(const{processorID:t,processorName:i,type:r,cb:s}of this.statsRegistry)try{const o=s();e.push({processorID:t,processorName:i,type:r,stats:o})}catch(e){le.error(new v(E.UNEXPECTED_ERROR,e.message))}return e}registerUsage(e,t){this.usageRegistry.find((t=>t.processorID===e.ID&&t.processorName===e.name))||this.usageRegistry.push({processorID:e.ID,processorName:e.name,cb:t})}unregisterUsage(e){const t=this.usageRegistry.findIndex((t=>t.processorID===e.ID&&t.processorName===e.name));-1!==t&&this.usageRegistry.splice(t,1)}async gatherUsage(){const e=[];if(!this.chained)return[];for(const{cb:t}of this.usageRegistry)try{let i=t();i instanceof Promise&&(i=await i),e.push(Tt(Tt({},i),{},{direction:this.direction}))}catch(e){le.error("gather extension usage error",e)}return e}getDirection(){return this.direction}}class ai extends y{get isPlayed(){return!0}get isFreeze(){return!1}constructor(){super(),_t(this,"context",void 0),_t(this,"processSourceNode",void 0),_t(this,"outputTrack",void 0),_t(this,"processedNode",void 0),_t(this,"clonedTrack",void 0),_t(this,"outputNode",void 0),this.outputNode=new ci}setVolume(){}createOutputTrack(){throw new v(E.NOT_SUPPORTED,"can not create output MediaStreamTrack when WebAudio disabled")}getOriginVolumeLevel(){return 0}getAccurateVolumeLevel(){return 0}stopGetAudioBuffer(){}startGetAudioBuffer(){}play(){}stop(){}destroy(){}updateTrack(){}updateOriginTrack(){}createMediaStreamSourceNode(){}}class ci{disconnect(){}connect(){}}function di(e){return new Promise(((t,i)=>{let r=!1;const s=document.createElement("video");s.setAttribute("autoplay",""),s.setAttribute("muted",""),s.muted=!0,s.autoplay=!0,s.setAttribute("playsinline",""),s.setAttribute("style","position: fixed; top: 0; left: 0; width: 1px; height: 1px"),document.body.appendChild(s);const o=C()?"canplay":"playing";s.addEventListener(o,(()=>{const e=s.videoWidth,i=s.videoHeight;!e&&u()||(r=!0,s.srcObject=null,s.remove(),t([e,i]))})),s.srcObject=new MediaStream([e]),s.play().catch(K),setTimeout((()=>{r||(s.srcObject=null,s.remove(),t([s.videoWidth,s.videoHeight]))}),4e3)}))}function hi(e){const t={};e.facingMode&&(t.facingMode=e.facingMode),e.cameraId&&(t.deviceId={exact:e.cameraId});const i=Ce(e.encoderConfig);return null!=i.width&&(t.width=i.width),null!=i.height&&(t.height=i.height),!Z()&&i.frameRate&&(t.frameRate=i.frameRate),p()&&"object"==typeof t.frameRate&&(t.frameRate.max=60),u()&&(t.frameRate={ideal:30,max:30}),t}function ui(e){const t={};e.screenSourceType&&(t.mediaSource=e.screenSourceType),e.extensionId&&l()&&(t.extensionId=e.extensionId);const{displaySurface:i,selfBrowserSurface:r,surfaceSwitching:o,systemAudio:n,preferCurrentTab:a}=e;(s(107)||Y(107)||z(93))&&(i&&(T(i,"displaySurface",["browser","window","monitor"]),t.displaySurface=i),r?(T(r,"selfBrowserSurface",["exclude","include"]),t.selfBrowserSurface=r):t.selfBrowserSurface="include",o&&(T(o,"surfaceSwitching",["exclude","include"]),t.surfaceSwitching=o)),(s(105)||Y(105)||z(91))&&n&&(T(n,"systemAudio",["exclude","include"]),t.systemAudio=n),(s(94)||Y(94)||z(80))&&a&&(t.preferCurrentTab=!0),e.electronScreenSourceId&&(t.sourceId=e.electronScreenSourceId);const c=e.encoderConfig?Ne(e.encoderConfig):null;return t.mandatory={chromeMediaSource:"desktop",maxWidth:c?c.width:void 0,maxHeight:c?c.height:void 0},c&&(c.frameRate&&("number"==typeof c.frameRate?(t.mandatory.maxFrameRate=c.frameRate,t.mandatory.minFrameRate=c.frameRate):(t.mandatory.maxFrameRate=c.frameRate.max||c.frameRate.ideal||c.frameRate.exact||void 0,t.mandatory.minFrameRate=c.frameRate.min||c.frameRate.ideal||c.frameRate.exact||void 0),t.frameRate=c.frameRate),c.width&&(t.width=c.width),c.height&&(t.height=c.height)),t}function li(e){const t={};return Z()||(void 0!==e.AGC&&(t.autoGainControl=e.AGC),void 0!==e.AEC&&(t.echoCancellation=e.AEC),void 0!==e.ANS&&(t.noiseSuppression=e.ANS,l()&&e.ANS&&(t.googHighpassFilter=e.ANS))),t}function pi(e){return li(e)}function mi(e){const t=li(e);if(e.encoderConfig){const i=Le(e.encoderConfig);t.channelCount=i.stereo?2:1,t.sampleRate=i.sampleRate,t.sampleSize=i.sampleSize}return e.microphoneId&&(t.deviceId={exact:e.microphoneId}),x()&&(t.sampleRate=void 0),t}function gi(e,t,i){const r=4*Math.floor(2e5*Math.pow(i/15,.6)*Math.pow(e*t/230400,.75)),s=e*t,o=new Map([[19200,.9],[230400,.85],[518400,.75],[921600,.7],[2073600,.6],[3686400,.5]]),n=new Map([[230400,.95],[518400,.9],[921600,.85],[2073600,.8]]);let a=o.values().next().value,c=1;if(o.has(s))a=o.get(s);else{const e=Array.from(o.entries()).sort(((e,t)=>{let[i]=e,[r]=t;return i-r})),t=e.find((e=>{let[t]=e;return t>s}));if(t){const i=e.indexOf(t);if(i>0){const r=e[i-1],o=(s-r[0])/(t[0]-r[0]);a=r[1]+o*(t[1]-r[1])}else a=t[1]}else a=e[e.length-1][1]}if(n.has(s))c=n.get(s);else{const e=Array.from(n.entries()).sort(((e,t)=>{let[i]=e,[r]=t;return i-r})),t=e.find((e=>{let[t]=e;return t>s}));if(t){const i=e.indexOf(t);if(i>0){const r=e[i-1],o=(s-r[0])/(t[0]-r[0]);c=r[1]+o*(t[1]-r[1])}else c=t[1]}else c=e[e.length-1][1]}const d=h("VIDEO_NEW_BITRATE_RATIO");d&&d>0&&(a=d/100);const u=Math.floor(r*a),l=Math.floor(65e4*Math.pow(e*t/230400,.5)*Math.pow(i/15,.69));let p=u;const m=h("VIDEO_STANDARD_BITRATE_VERSION");return m&&m>0&&(1===m?p=r:2===m?p=u:3===m&&(p=l)),[Math.floor(p/1e3),c]}function _i(e,t,i){if(!Array.isArray(h("VIDEO_ENCODER_CONFIG_LIST")))return!1;if(0===h("VIDEO_ENCODER_CONFIG_LIST").length)return!1;const r=Math.min(e,t);if(r>480)return!1;return Tt(Tt({},h("VIDEO_ENCODER_CONFIG_LIST").find((e=>e.height>r))),{},{frameRate:i})}function fi(e,t,i,r,s){const o=h("BITRATE_ADAPTER_TYPE");if("DEFAULT_BITRATE"===o)return{min:r,max:s};if(void 0===s){const n=Math.floor(200*Math.pow(i/15,.6)*Math.pow(e*t/640/360,.75));s="STANDARD_BITRATE"===o?4*n:2*n,r=null!=r?r:n}else r=null!=r?r:Math.floor(s/10);return{min:r,max:s}}function Ti(e,t,i){const r=200*Math.pow(i/15,.6)*Math.pow(e*t/640/360,.75);return{min:Math.floor(r),max:Math.floor(4*r)}}const vi=e=>{const t=e._encoderConfig;if(!t)return;const{frameRate:i,width:r,height:s}=e.getMediaStreamTrackSettings();let{frameRate:o=i,width:n=r,height:a=s}=t;if(!o||!n||!a)return;n=j(n),a=j(a),o=j(o);const{max:c,min:d}=Ti(n,a,o),{bitrateMax:u,bitrateMin:l}=t||{};u||le.debug("calculate bitrate: [w: ".concat(n,", h: ").concat(a,", fps: ").concat(o,"] => [brMax: ").concat(u,", brMin: ").concat(l,"]"));const{maxFramerate:p}=h("ENCODER_CONFIG_LIMIT");return p&&"number"==typeof p&&(o=Math.min(o,p)),{frameRate:o,bitrateMax:u||c,bitrateMin:l||d,scaleResolutionDownBy:1,scale:0}},Ei=async(e,t,i)=>await(async(e,t,i)=>{const r=X(Q(""+t+i)).slice(0,16),s=r.slice(0,12),o=await window.crypto.subtle.importKey("raw",r,"AES-GCM",!0,["encrypt"]);return new Uint8Array(await window.crypto.subtle.encrypt({name:"AES-GCM",iv:s},o,e))})(e.buffer,t,i),Si=e=>{const t=document.createElement("canvas");return t.width=2,t.height=2,new Promise(((i,r)=>{t.toBlob((async e=>{if(t.remove(),e){const r=await yi(e);i({buffer:r,width:t.width,height:t.height})}else r(new v(E.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED))}),e,1)}))},yi=async e=>{const t=await e.arrayBuffer();return new Uint8Array(t)};function ki(e,t){if("VideoFrame"in window&&"TransformStream"in window&&ve().supportWebRTCInsertableStream){const i=new MediaStreamTrackProcessor(e),r=new MediaStreamTrackGenerator({kind:"video"});let s,o,n=Date.now();const a=()=>{c&&(clearInterval(c),c=void 0),s&&(s.close(),s=void 0),e.stop(),o=void 0,r.removeEventListener("ended",a)};let c=window.setInterval((()=>{if(o&&s&&Date.now()-n>(null!=t?t:1e3))try{"live"===r.readyState?o.enqueue(s.clone()):a()}catch(e){a()}}),null!=t?t:1e3);const d=new TransformStream({transform:(e,t)=>{"live"===r.readyState?(o=t,n=Date.now(),void 0===s?(s=e,t.enqueue(e.clone())):(t.enqueue(s),s=e)):e.close()}});return r.addEventListener("ended",a),i.readable.pipeThrough(d).pipeTo(r.writable),r}}var bi,Ii,Ai,Ri,wi,Di,Ci,Ni,Mi,Oi,Li,Pi,Vi,xi,Ui,Bi,Fi,Gi,Wi,Hi,Ki,Zi,Yi,zi,ji,Xi,Qi,Ji,qi,$i,er,tr,ir,rr,sr,or,nr,ar,cr,dr;let hr=(bi=ge({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),Ii=ge({argsMap:(e,t)=>[e.getTrackId(),t]}),Ai=ii(),Ri=J("LocalAudioTrack","_enabledMutex"),wi=ge({argsMap:(e,t)=>[e.getTrackId(),t]}),Di=ii(),Ci=J("LocalAudioTrack","_enabledMutex"),Ni=ge({argsMap:(e,t)=>[e.getTrackId(),t]}),Mi=ii(),Oi=ii(),Li=ii(),Pi=ge({argsMap:e=>[e.getTrackId()]}),Vi=ii(),xi=ge({argsMap:e=>[e.getTrackId()]}),Ui=ii(),Bi=ge({argsMap:e=>[e.getTrackId()]}),Fi=ge({argsMap:(e,t)=>[e.getTrackId(),t.name]}),Gi=ge({argsMap:e=>[e.getTrackId()]}),gt((Wi=class extends Et{get _source(){return this.initWebAudio()}set _source(e){this._trackSource=e}get processorContext(){return this._processorContext||(this._processorContext=this.initProcessor().processorContext),this._processorContext}get processorDestination(){return this._processorDestination||(this._processorDestination=this.initProcessor().processorDestination),this._processorDestination}get isPlaying(){return this._useAudioElement?ti.isPlaying(this.getTrackId()):this._source.isPlayed}get __className__(){return"LocalAudioTrack"}constructor(e,t,i,r){super(e,i),_t(this,"trackMediaType",qe.AUDIO),_t(this,"_encoderConfig",void 0),_t(this,"_trackSource",void 0),_t(this,"metadata",[]),_t(this,"_enabled",!0),_t(this,"_volume",100),_t(this,"_useAudioElement",!0),_t(this,"_bypassWebAudio",!1),_t(this,"processor",void 0),_t(this,"_processorContext",void 0),_t(this,"_processorDestination",void 0),_t(this,"_getOriginVolumeLevel",void 0),this._encoderConfig=t,this._getOriginVolumeLevel=!!r,this._trackSource=new ai,h("DISABLE_WEBAUDIO")&&(this._bypassWebAudio=!0),h("LOCAL_AUDIO_TRACK_USES_WEB_AUDIO")&&(this._useAudioElement=!1);c()&&!At()?setTimeout((()=>this.initWebAudio())):this.initWebAudio()}setVolume(e){_(e,"volume",0,1e3),this._volume=e,this._source.setVolume(e/100),this._useAudioElement&&ti.setVolume(this.getTrackId(),e);try{if(this._bypassWebAudio)return void le.debug("[".concat(this.getTrackId(),"] setVolume returned because no pass through WebAudio."));const e=this._source.createOutputTrack();this._mediaStreamTrack!==e&&(this._mediaStreamTrack=e,w(this,He.NEED_REPLACE_TRACK,this).then((()=>{le.debug("[".concat(this.getTrackId(),"] replace web audio track success"))})).catch((e=>{le.warning("[".concat(this.getTrackId(),"] replace web audio track failed"),e)})))}catch(e){}}getVolumeLevel(){return this._muted&&this.enabled&&this._getOriginVolumeLevel?this._source.getOriginVolumeLevel():this._source.getAccurateVolumeLevel()}async setPlaybackDevice(e){if(!this._useAudioElement||!Ee())throw new v(E.NOT_SUPPORTED,"your browser does not support setting the audio output device");await ti.setSinkID(this.getTrackId(),e)}async setEnabled(e,t,i){return this._setEnabled(e,t,i)}async _setEnabled(e,t,i){if(!i){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(le.info("[".concat(this.getTrackId(),"] start setEnabled"),e),e){this._originMediaStreamTrack.enabled=!0;try{i||(this._enabled=!0),await w(this,He.NEED_ENABLE_TRACK,this),le.info("[".concat(this.getTrackId(),"] setEnabled to ").concat(e," success"))}catch(e){throw i||(this._enabled=!1),le.error("[".concat(this.getTrackId(),"] setEnabled to true error"),e.toString()),e}}else{this._originMediaStreamTrack.enabled=!1,i||(this._enabled=!1);try{await w(this,He.NEED_DISABLE_TRACK,this)}catch(e){throw i||(this._enabled=!0),le.error("[".concat(this.getTrackId(),"] setEnabled to false error"),e.toString()),e}}}async setMuted(e){e!==this._muted&&(this.stateCheck("muted",e),this._muted=e,this._originMediaStreamTrack.enabled=!e,le.debug("[".concat(this.getTrackId(),"] start set muted: ").concat(e)),e?await w(this,He.NEED_MUTE_TRACK,this):await w(this,He.NEED_UNMUTE_TRACK,this))}getStats(){b((()=>{le.warning("[deprecated] LocalAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalAudioStats instead")}),"localAudioTrackGetStatsWarning");const e=q(this,He.GET_STATS);return e||Tt({},tt)}setAudioFrameCallback(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:4096;if(!e)return this._source.removeAllListeners($e.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(t),this._source.removeAllListeners($e.ON_AUDIO_BUFFER),this._source.on($e.ON_AUDIO_BUFFER,(t=>e(t)))}play(){le.debug("[".concat(this.getTrackId(),"] start audio playback")),this._useAudioElement?(le.debug("[".concat(this.getTrackId(),"] start audio playback in element")),ti.play(this._mediaStreamTrack,this.getTrackId(),this._volume)):this._source.play()}stop(){le.debug("[".concat(this.getTrackId(),"] stop audio playback")),this._useAudioElement?ti.stop(this.getTrackId()):this._source.stop()}close(){super.close(),this._processorDestination&&this.unbindProcessorDestinationEvents(this._processorDestination),this._processorContext&&this.unbindProcessorContextEvents(this._processorContext),this.unpipe(),this._processorDestination&&this._processorDestination._source&&this._processorDestination._source.unpipe(),this._source.destroy()}_updatePlayerSource(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];le.debug("[".concat(this.getTrackId(),"] update player source track")),e&&this._source.updateTrack(this._mediaStreamTrack),this._useAudioElement&&ti.updateTrack(this.getTrackId(),this._mediaStreamTrack)}async _updateOriginMediaStreamTrack(e,t){this._originMediaStreamTrack!==e&&(this._originMediaStreamTrack&&(this._originMediaStreamTrack.removeEventListener("ended",this._handleTrackEnded),t&&this._originMediaStreamTrack.stop()),e.addEventListener("ended",this._handleTrackEnded),this._originMediaStreamTrack=e,this._muted&&(this._originMediaStreamTrack.enabled=!1),this.processor&&this._processorContext&&this.processor.updateInput({track:e,context:this._processorContext}),this._mediaStreamTrack!==this._source.outputTrack?(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await w(this,He.NEED_REPLACE_TRACK,this)):this._source.updateTrack(this._originMediaStreamTrack),this._getOriginVolumeLevel&&this._source.updateOriginTrack(e))}renewMediaStreamTrack(e){return Promise.resolve(void 0)}pipe(e){if(this._bypassWebAudio)throw new v(E.INVALID_OPERATION,"Can not process AudioTrack when bypassWebAudio set to true.");if(this.processor===e)return e;if(e._source)throw new v(E.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,node:this._source.processSourceNode,context:this.processorContext}),e}unpipe(){var e;if(!this.processor)return;const t=this.processor;null===(e=this._source.processSourceNode)||void 0===e||e.disconnect(),this.processor._source=!1,this.processor=void 0,t.reset()}bindProcessorDestinationEvents(e){e.on(nt.ON_TRACK,(async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(!1),this._source.processedNode=this._source.createMediaStreamSourceNode(e),await w(this,He.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await w(this,He.NEED_REPLACE_TRACK,this))})),e.on(nt.ON_NODE,(e=>{this._source.processedNode=e}))}unbindProcessorDestinationEvents(e){e.removeAllListeners(nt.ON_TRACK),e.removeAllListeners(nt.ON_NODE)}bindProcessorContextEvents(e){e.on(at.REQUEST_CONSTRAINTS,(async e=>{e(this._originMediaStreamTrack.getSettings())}))}unbindProcessorContextEvents(e){e.removeAllListeners(at.REQUEST_CONSTRAINTS)}initWebAudio(){return this._trackSource instanceof ai&&(this._trackSource=new xt(this._mediaStreamTrack,!1,this._getOriginVolumeLevel?this._mediaStreamTrack:void 0)),this._trackSource}initProcessor(){const e=new ni(this._source.context,this.getTrackId(),"local"),t=new oi(e);return this._processorContext=e,this._processorDestination=t,this.bindProcessorContextEvents(e),this.bindProcessorDestinationEvents(t),this._source.on($e.UPDATE_SOURCE,(()=>{this.processor&&this.processor.updateInput({node:this._source.processSourceNode,context:e})})),this._useAudioElement&&(this._useAudioElement=!1,this.isPlaying&&(ti.stop(this.getTrackId()),this._source.play()),w(this,He.NEED_REPLACE_MIXING_TRACK,this).then((()=>{le.debug("[".concat(this.getTrackId(),"] replace from origin track to web audio track success"))})).catch((e=>{le.warning("[".concat(this.getTrackId(),"] replace from origin track to web audio track failed"),e)}))),{processorContext:e,processorDestination:t}}}).prototype,"setVolume",[bi],Object.getOwnPropertyDescriptor(Wi.prototype,"setVolume"),Wi.prototype),gt(Wi.prototype,"setPlaybackDevice",[Ii,Ai],Object.getOwnPropertyDescriptor(Wi.prototype,"setPlaybackDevice"),Wi.prototype),gt(Wi.prototype,"setEnabled",[Ri,wi,Di],Object.getOwnPropertyDescriptor(Wi.prototype,"setEnabled"),Wi.prototype),gt(Wi.prototype,"setMuted",[Ci,Ni,Mi],Object.getOwnPropertyDescriptor(Wi.prototype,"setMuted"),Wi.prototype),gt(Wi.prototype,"getStats",[Oi],Object.getOwnPropertyDescriptor(Wi.prototype,"getStats"),Wi.prototype),gt(Wi.prototype,"setAudioFrameCallback",[Li],Object.getOwnPropertyDescriptor(Wi.prototype,"setAudioFrameCallback"),Wi.prototype),gt(Wi.prototype,"play",[Pi,Vi],Object.getOwnPropertyDescriptor(Wi.prototype,"play"),Wi.prototype),gt(Wi.prototype,"stop",[xi,Ui],Object.getOwnPropertyDescriptor(Wi.prototype,"stop"),Wi.prototype),gt(Wi.prototype,"close",[Bi],Object.getOwnPropertyDescriptor(Wi.prototype,"close"),Wi.prototype),gt(Wi.prototype,"pipe",[Fi],Object.getOwnPropertyDescriptor(Wi.prototype,"pipe"),Wi.prototype),gt(Wi.prototype,"unpipe",[Gi],Object.getOwnPropertyDescriptor(Wi.prototype,"unpipe"),Wi.prototype),Wi),ur=(Hi=ge({argsMap:(e,t)=>[e.getTrackId(),t]}),Ki=ii(),Zi=J("MicrophoneAudioTrack","_enabledMutex"),Yi=ge({argsMap:(e,t,i)=>[e.getTrackId(),t,i]}),zi=ii(),ji=ge({argsMap:e=>[e.getTrackId()]}),gt((Xi=class extends hr{get __className__(){return"MicrophoneAudioTrack"}constructor(e,t,i,r){super(e,t.encoderConfig?Le(t.encoderConfig):{},r,h("GET_VOLUME_OF_MUTED_AUDIO_TRACK")),_t(this,"_config",void 0),_t(this,"_deviceName","default"),_t(this,"_constraints",void 0),_t(this,"_originalConstraints",void 0),_t(this,"_enabled",!0),this._config=t,this._constraints=i,this._originalConstraints=i,this._deviceName=e.label,"boolean"==typeof t.bypassWebAudio&&(this._bypassWebAudio=t.bypassWebAudio),(W()||$())&&kt.bindInterruptDetectorTrack(this)}async setDevice(e){if(le.info("[".concat(this.getTrackId(),"] start set device to ").concat(e)),this._enabled)try{const t=await Xt.getDeviceById(e),i={};i.audio=Tt({},this._constraints),i.audio.deviceId={exact:e},this._originMediaStreamTrack.stop();let r=null;try{r=await Kt(i,this.getTrackId())}catch(e){throw le.error("[".concat(this.getTrackId(),"] setDevice failed"),e.toString()),r=await Kt({audio:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(r.getAudioTracks()[0],!1),e}await this._updateOriginMediaStreamTrack(r.getAudioTracks()[0],!1),this._deviceName=t.label,this._config.microphoneId=e,this._constraints.deviceId={exact:e}}catch(e){throw le.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}else try{const t=await Xt.getDeviceById(e);this._deviceName=t.label,this._config.microphoneId=e,this._constraints.deviceId={exact:e}}catch(e){throw le.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}le.info("[".concat(this.getTrackId(),"] set device to ").concat(e," success"))}async setEnabled(e,t,i){if(t)return le.debug("[".concat(this.getTrackId(),"] setEnabled false (do not close microphone)")),await super._setEnabled(e);if(!i){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(le.info("[".concat(this.getTrackId(),"] start setEnabled"),e),h("AUTO_RESET_AUDIO_ROUTE")&&(C()||N())){const t=navigator.audioSession;t&&(e||(t.type="playback"),t.type="auto")}if(!e){var r;this._originMediaStreamTrack.onended=null,this._originMediaStreamTrack.stop(),null===(r=this._source.clonedTrack)||void 0===r||r.stop(),i||(this._enabled=!1);try{await w(this,He.NEED_DISABLE_TRACK,this)}catch(e){throw le.error("[".concat(this.getTrackId(),"] setEnabled false failed"),e.toString()),e}return}const s=Tt({},this._constraints),o=Xt.searchDeviceIdByName(this._deviceName);o&&!s.deviceId&&(s.deviceId=o);try{i||(this._enabled=!0);const e=await Kt({audio:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getAudioTracks()[0],!1),await w(this,He.NEED_ENABLE_TRACK,this)}catch(e){throw i||(this._enabled=!1),le.error("[".concat(this.getTrackId(),"] setEnabled true failed"),e.toString()),e}le.info("[".concat(this.getTrackId(),"] setEnabled success"))}close(){super.close(),(W()||$())&&kt.unbindInterruptDetectorTrack(this)}onTrackEnded(){if((C()||N())&&this._enabled&&!this._isClosed&&kt.duringInterruption){const e=async()=>{kt.off(ye.IOS_INTERRUPTION_END,e),this._enabled&&!this._isClosed&&(le.debug("[".concat(this.getTrackId(),"] try capture microphone media device for interrupted iOS device.")),await this.setEnabled(!1),await this.setEnabled(!0))};kt.on(ye.IOS_INTERRUPTION_END,e)}else le.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(Qe.TRACK_ENDED)}async renewMediaStreamTrack(e){const t=e||this._constraints,i=Xt.searchDeviceIdByName(this._deviceName);if(i&&!t.deviceId&&(t.deviceId=i),this._constraints=t,this._enabled){this._originMediaStreamTrack.stop();const e=await Kt({audio:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getAudioTracks()[0],!0)}}bindProcessorContextEvents(e){super.bindProcessorContextEvents(e),e.on(at.REQUEST_UPDATE_CONSTRAINTS,(async(e,t,i)=>{try{const i=Object.assign({},this._originalConstraints,...e);await this.renewMediaStreamTrack(i),t()}catch(e){i(e)}}))}unbindProcessorContextEvents(e){super.unbindProcessorContextEvents(e),e.removeAllListeners(at.REQUEST_UPDATE_CONSTRAINTS)}}).prototype,"setDevice",[Hi,Ki],Object.getOwnPropertyDescriptor(Xi.prototype,"setDevice"),Xi.prototype),gt(Xi.prototype,"setEnabled",[Zi,Yi,zi],Object.getOwnPropertyDescriptor(Xi.prototype,"setEnabled"),Xi.prototype),gt(Xi.prototype,"close",[ji],Object.getOwnPropertyDescriptor(Xi.prototype,"close"),Xi.prototype),Xi),lr=(Qi=ge({argsMap:(e,t)=>[e.getTrackId(),t,e.duration]}),Ji=ii(),qi=ge({argsMap:e=>[e.getTrackId()]}),$i=ii(),er=ge({argsMap:e=>[e.getTrackId()]}),tr=ii(),ir=ge({argsMap:e=>[e.getTrackId()]}),rr=ii(),sr=ge({argsMap:e=>[e.getTrackId()]}),or=ii(),nr=ge({argsMap:e=>[e.getTrackId()]}),ar=ge({argsMap:e=>[e.getTrackId()]}),cr=ii(),gt((dr=class extends hr{get __className__(){return"BufferSourceAudioTrack"}constructor(e,t,i,r){super(t.createOutputTrack(),i,r),_t(this,"source",void 0),_t(this,"_bufferSource",void 0),this._useAudioElement=!1,this.source=e,this._bufferSource=t,this._bufferSource.on($e.AUDIO_SOURCE_STATE_CHANGE,(e=>{this.safeEmit(Qe.SOURCE_STATE_CHANGE,e)}));try{this._mediaStreamTrack=this._source.createOutputTrack()}catch(e){}}get currentState(){return this._bufferSource.currentState}get duration(){return this._bufferSource.duration}get playbackSpeed(){return this._bufferSource.playbackSpeed}getCurrentTime(){return this._bufferSource.currentTime}startProcessAudioBuffer(e){e&&this._bufferSource.updateOptions(e),this._bufferSource.startProcessAudioBuffer()}pauseProcessAudioBuffer(){this._bufferSource.pauseProcessAudioBuffer()}seekAudioBuffer(e){this._bufferSource.seekAudioBuffer(e)}resumeProcessAudioBuffer(){this._bufferSource.resumeProcessAudioBuffer()}stopProcessAudioBuffer(){this._bufferSource.stopProcessAudioBuffer()}close(){this.source=null,this._bufferSource.destroy(),super.close()}setAudioBufferPlaybackSpeed(e){_(e,"speed",0),this._bufferSource.setAudioBufferPlaybackSpeed(e)}}).prototype,"startProcessAudioBuffer",[Qi,Ji],Object.getOwnPropertyDescriptor(dr.prototype,"startProcessAudioBuffer"),dr.prototype),gt(dr.prototype,"pauseProcessAudioBuffer",[qi,$i],Object.getOwnPropertyDescriptor(dr.prototype,"pauseProcessAudioBuffer"),dr.prototype),gt(dr.prototype,"seekAudioBuffer",[er,tr],Object.getOwnPropertyDescriptor(dr.prototype,"seekAudioBuffer"),dr.prototype),gt(dr.prototype,"resumeProcessAudioBuffer",[ir,rr],Object.getOwnPropertyDescriptor(dr.prototype,"resumeProcessAudioBuffer"),dr.prototype),gt(dr.prototype,"stopProcessAudioBuffer",[sr,or],Object.getOwnPropertyDescriptor(dr.prototype,"stopProcessAudioBuffer"),dr.prototype),gt(dr.prototype,"close",[nr],Object.getOwnPropertyDescriptor(dr.prototype,"close"),dr.prototype),gt(dr.prototype,"setAudioBufferPlaybackSpeed",[ar,cr],Object.getOwnPropertyDescriptor(dr.prototype,"setAudioBufferPlaybackSpeed"),dr.prototype),dr);class pr extends hr{get __className__(){return"MixingAudioTrack"}get isActive(){for(const e of this.trackList)if(e._enabled&&!e._isClosed&&!e.muted)return!0;return!1}constructor(){const e=It().createMediaStreamDestination();super(e.stream.getAudioTracks()[0],void 0,k(8,"track-mix-")),_t(this,"trackList",void 0),_t(this,"destNode",void 0),this._useAudioElement=!1;try{this._mediaStreamTrack=this._source.createOutputTrack()}catch(e){}this.destNode=e,this.trackList=[]}hasAudioTrack(e){return-1!==this.trackList.indexOf(e)}addAudioTrack(e){-1===this.trackList.indexOf(e)?(le.debug("add ".concat(e.getTrackId()," to mixing track")),e._source.outputNode.connect(this.destNode),this.trackList.push(e),this.updateEncoderConfig()):le.debug("track ".concat(e.getTrackId()," is already added"))}removeAudioTrack(e){if(-1!==this.trackList.indexOf(e)){le.debug("remove ".concat(e.getTrackId()," from mixing track"));try{e._source.outputNode.disconnect(this.destNode)}catch(e){}D(this.trackList,e),this.updateEncoderConfig()}}updateEncoderConfig(){const e={};this.trackList.forEach((t=>{t._encoderConfig&&((t._encoderConfig.bitrate||0)>(e.bitrate||0)&&(e.bitrate=t._encoderConfig.bitrate),(t._encoderConfig.sampleRate||0)>(e.sampleRate||0)&&(e.sampleRate=t._encoderConfig.sampleRate),(t._encoderConfig.sampleSize||0)>(e.sampleSize||0)&&(e.sampleSize=t._encoderConfig.sampleSize),t._encoderConfig.stereo&&(e.stereo=!0))})),this._encoderConfig=e}_updateRtpTransceiver(e){this._rtpTransceiver!==e&&(this._rtpTransceiver=e,this.trackList.forEach((t=>{t instanceof pr?t.emit(Xe.TRANSCEIVER_UPDATED,e):t._updateRtpTransceiver(e)})))}}class mr extends Vt{set currentState(e){e!==this._currentState&&(this._currentState=e,this.safeEmit($e.AUDIO_SOURCE_STATE_CHANGE,this._currentState))}get currentState(){return this._currentState}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),_t(this,"audioBuffer",void 0),_t(this,"sourceNode",void 0),_t(this,"startPlayTime",0),_t(this,"startPlayOffset",0),_t(this,"pausePlayTime",0),_t(this,"options",void 0),_t(this,"currentLoopCount",0),_t(this,"currentPlaybackSpeed",100),_t(this,"_currentState","stopped"),this.audioBuffer=e,this.options=t,this.startPlayOffset=this.options.startPlayTime||0}createWebAudioDiagram(){return this.context.createGain()}get duration(){return this.audioBuffer?this.audioBuffer.duration:0}get playbackSpeed(){return this.currentPlaybackSpeed}get currentTime(){return this.audioBuffer?"stopped"===this.currentState?0:"paused"===this.currentState?this.pausePlayTime:((this.context.currentTime-this.startPlayTime)*(this.playbackSpeed/100)+this.startPlayOffset)%this.audioBuffer.duration:0}updateOptions(e){"stopped"===this.currentState?(this.options=e,this.startPlayOffset=this.options.startPlayTime||0):le.warning("can not set audio source options")}startProcessAudioBuffer(){this.sourceNode&&this.stopProcessAudioBuffer(),this.sourceNode=this.createSourceNode(),this.startSourceNode(),this.currentState="playing"}pauseProcessAudioBuffer(){this.sourceNode&&"playing"===this.currentState&&(this.pausePlayTime=this.currentTime,this.sourceNode.onended=null,this.sourceNode.stop(),this.sourceNode.buffer=null,this.sourceNode=this.createSourceNode(),this.currentState="paused")}seekAudioBuffer(e){this.sourceNode&&(this.sourceNode.onended=null,"playing"===this.currentState&&this.sourceNode.stop(),this.sourceNode=this.createSourceNode(),"playing"===this.currentState?(this.startPlayOffset=e,this.startSourceNode()):"paused"===this.currentState&&(this.pausePlayTime=e))}resumeProcessAudioBuffer(){"paused"===this.currentState&&this.sourceNode&&(this.startPlayOffset=this.pausePlayTime,this.pausePlayTime=0,this.startSourceNode(),this.currentState="playing")}stopProcessAudioBuffer(){if(this.sourceNode){this.sourceNode.onended=null;try{this.sourceNode.stop()}catch(e){}this.reset()}}destroy(){this.audioBuffer=null,super.destroy()}setAudioBufferPlaybackSpeed(e){this.sourceNode&&("playing"===this.currentState&&(this.startPlayOffset=this.currentTime,this.startPlayTime=this.context.currentTime),this.sourceNode.playbackRate.value=e/100),this.currentPlaybackSpeed=e}startSourceNode(){this.sourceNode&&this.sourceNode.buffer&&(this.sourceNode.start(0,this.startPlayOffset),this.startPlayTime=this.context.currentTime,this.sourceNode.onended=this.handleSourceNodeEnded.bind(this))}createSourceNode(){const e=this.context.createBufferSource();return e.buffer=this.audioBuffer,e.loop=!!this.options.loop,e.connect(this.outputNode),e.playbackRate.value=this.currentPlaybackSpeed/100,e}handleSourceNodeEnded(){if(this.currentLoopCount+=1,this.options.cycle&&this.options.cycle>this.currentLoopCount)return this.startPlayOffset=0,this.sourceNode=void 0,void this.startProcessAudioBuffer();this.reset()}reset(){this.startPlayOffset=this.options.startPlayTime||0,this.currentState="stopped",this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=void 0),this.currentLoopCount=0}}const gr=new Map;function _r(e,t){if(0===e.length||0===t.length)return 1/0;const i=se(e),r=se(t);return Math.floor(r/i)}class fr{get rendFrameRate(){const e=Math.max(1,_r(this._render_interframe_delays_sizes,this._render_interframe_delays));return Math.floor(1e3/e)}get videoElementStatus(){return this._videoElementStatus}set videoElementStatus(e){e!==this._videoElementStatus&&(le.debug("[".concat(this.trackId,"] video-element-status change ").concat(this._videoElementStatus," => ").concat(e)),this._videoElementStatus=e)}get videoState(){return this._videoState}set videoState(e){var t;e!==this._videoState&&(this._videoState=e,null===(t=this.onVideoStateChanged)||void 0===t||t.call(this,this.videoState))}constructor(e){_t(this,"trackId",void 0),_t(this,"config",void 0),_t(this,"onFirstVideoFrameDecoded",void 0),_t(this,"onVideoStateChanged",void 0),_t(this,"freezeTimeCounterList",[]),_t(this,"renderFreezeAccTime",0),_t(this,"renderFreezeAccTime2",0),_t(this,"isKeepLastFrame",!1),_t(this,"timeUpdatedCount",0),_t(this,"freezeTime",0),_t(this,"playbackTime",0),_t(this,"lastTimeUpdatedTime",0),_t(this,"autoplayFailed",!1),_t(this,"videoTrack",void 0),_t(this,"videoElement",void 0),_t(this,"cacheVideoElement",void 0),_t(this,"_render_interframe_delays",[]),_t(this,"_render_interframe_delays_sizes",[]),_t(this,"_videoState",lt.VideoStateStopped),_t(this,"videoElementCheckInterval",void 0),_t(this,"videoElementFreezeTimeout",void 0),_t(this,"_videoElementStatus",ut.NONE),_t(this,"isGettingVideoDimensions",!1),_t(this,"startGetVideoDimensions",(()=>{const e=()=>{if(this.isGettingVideoDimensions=!0,this.videoElement.videoWidth*this.videoElement.videoHeight>4)return le.debug("[".concat(this.trackId,"] current video dimensions:"),this.videoElement.videoWidth,this.videoElement.videoHeight),void(this.isGettingVideoDimensions=!1);setTimeout(e,500)};!this.isGettingVideoDimensions&&e()})),_t(this,"autoResumeAfterInterruption",(()=>{this.videoTrack&&"live"===this.videoTrack.readyState&&"running"===kt.curState&&(le.debug("[track-".concat(this.trackId,"] video element paused, auto resume for ").concat(te())),ie()?(this.videoElement.srcObject=null,this.videoElement.srcObject=new MediaStream([this.videoTrack]),this.videoElement.play()):(this.videoElement.pause(),this.videoElement.play()))})),_t(this,"handleVideoEvents",(e=>{switch(e.type){case"play":case"playing":this.startGetVideoDimensions(),this.videoElementStatus=ut.PLAYING;break;case"loadeddata":if(this.videoState=lt.VideoStateStarting,this.onFirstVideoFrameDecoded&&this.onFirstVideoFrameDecoded(),this.cacheVideoElement){try{this.cacheVideoElement.srcObject=null,this.cacheVideoElement.remove()}catch(e){}this.cacheVideoElement=void 0}break;case"canplay":this.videoElementStatus=ut.CANPLAY;break;case"stalled":this.videoElementStatus=ut.STALLED;break;case"suspend":this.videoElementStatus=ut.SUSPEND;break;case"pause":this.videoElementStatus=ut.PAUSED,C()||N()||c()&&this.autoplayFailed||!this.videoTrack||"live"!==this.videoTrack.readyState||(le.debug("[track-".concat(this.trackId,"] video element paused, auto resume")),this.videoElement.play());break;case"waiting":this.videoElementStatus=ut.WAITING;break;case"abort":this.videoElementStatus=ut.ABORT;break;case"ended":this.videoElementStatus=ut.ENDED;break;case"emptied":this.videoElementStatus=ut.EMPTIED;break;case"error":{const e=this.videoElement.error;e&&(this.videoElementStatus=ut.ERROR,le.error("[".concat(this.trackId,"] media error: ").concat(e.message," (").concat(e.code,")")));break}case"timeupdate":{const e=performance.now();if(this.timeUpdatedCount+=1,this.timeUpdatedCount<10)return void(this.lastTimeUpdatedTime=e);const t=e-this.lastTimeUpdatedTime,i=this.lastTimeUpdatedTime;if(this.lastTimeUpdatedTime=e,Cs.lastVisibleTime<Cs.lastHiddenTime||i<Cs.lastHiddenTime||i<Cs.lastVisibleTime)return;for(t>h("VIDEO_FREEZE_DURATION")&&(this.freezeTime+=t),this.playbackTime+=t;this.playbackTime>=6e3;){this.playbackTime-=6e3;const e=Math.min(6e3,this.freezeTime);this.freezeTimeCounterList.push(e),this.freezeTime=Math.max(0,this.freezeTime-6e3)}break}}})),_t(this,"autoResumeAfterInterruptionOnIOS15_16",(()=>{this.videoTrack&&"live"===this.videoTrack.readyState&&(le.debug("[track-".concat(this.trackId,"] video element paused, auto resume for ").concat(te())),ie()?(this.videoElement.srcObject=null,this.videoElement.srcObject=new MediaStream([this.videoTrack]),this.videoElement.play()):(this.videoElement.pause(),this.videoElement.play()))})),this.trackId=e.trackId,this.config=e,e.element instanceof HTMLVideoElement?this.videoElement=e.element:this.videoElement=document.createElement("video"),kt.on(ye.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),kt.on(ye.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16)}getVideoElement(){return this.videoElement}getContainerElement(){var e;return null!==(e=this.videoElement.parentElement)&&void 0!==e?e:void 0}updateConfig(e){this.config=e,this.trackId=e.trackId,e.element!==this.videoElement&&(this.destroy(),this.videoElement=e.element),this.videoTrack&&this.initVideoElement()}updateVideoTrack(e){this.videoTrack!==e&&(this.videoTrack=e,this.initVideoElement())}play(t){const i=this.videoElement.play();i&&i.catch&&i.catch((e=>{t&&$t(t,"video",e.message,this.trackId),"NotAllowedError"===e.name?(le.warning("detected video element autoplay failed",e),this.autoplayFailed=!0,this.handleAutoPlayFailed()):le.warning("[".concat(this.trackId,"] play warning: "),e)}));const r=e();if(("Safari"===r.name&&15===Number(r.version)||W())&&i&&i.then){const e=()=>{this.config.mirror&&(this.videoElement.style.transform="rotateY(180deg)")};i.then(e).catch(e)}}getCurrentFrame(){const e=document.createElement("canvas");e.width=this.videoElement.videoWidth,e.height=this.videoElement.videoHeight;const t=e.getContext("2d");if(!t)return le.error("create canvas context failed!"),new ImageData(2,2);t.drawImage(this.videoElement,0,0,e.width,e.height);const i=t.getImageData(0,0,e.width,e.height);return e.remove(),i}async getCurrentFrameToUint8Array(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;const i=document.createElement("canvas");i.width=this.videoElement.videoWidth,i.height=this.videoElement.videoHeight;const r=i.getContext("2d");return r?(r.drawImage(this.videoElement,0,0,i.width,i.height),new Promise(((r,s)=>{i.toBlob((async e=>{if(i.remove(),e){const t=await yi(e);r({buffer:t,width:i.width,height:i.height})}else s(new v(E.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED))}),e,t<0?.1:t>1?1:t)}))):await Si(e)}destroy(){kt.off(ye.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),kt.off(ye.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16),this.videoElement.srcObject=null,this.resetVideoElement(),this.freezeTimeCounterList=[],this.videoState=lt.VideoStateStopped}initVideoElement(){if(this.videoElementStatus=ut.INIT,!this.videoElementCheckInterval&&(Tr.forEach((e=>{this.videoElement.addEventListener(e,this.handleVideoEvents)})),this.videoElementCheckInterval=window.setInterval((()=>{re(this.videoElement)||(this.videoElementStatus=ut.DESTROYED)}),1e3),h("ENABLE_VIDEO_FRAME_CALLBACK"))){var t,i;let e;const r=()=>{"visible"===document.visibilityState&&(document.removeEventListener("visibilitychange",r),this.videoElementFreezeTimeout=window.setTimeout(s,h("VIDEO_FREEZE_DURATION")))},s=()=>{this.videoElementFreezeTimeout=void 0,this.videoState===lt.VideoStateDecoding&&("visible"===document.visibilityState?this.videoState=lt.VideoStateFrozen:document.addEventListener("visibilitychange",r))},o=(t,i)=>{if(this.videoElementStatus===ut.PLAYING){if(e){const t=i.presentationTime-e.presentationTime,r=i.presentedFrames-e.presentedFrames;this._render_interframe_delays_sizes.push(r),this._render_interframe_delays.push(t);const o=se(this._render_interframe_delays_sizes),n=o-this._render_interframe_delays_sizes[0];if(o>30&&n>5&&(this._render_interframe_delays_sizes.shift(),this._render_interframe_delays.shift()),this.videoState===lt.VideoStateStarting&&(this.videoState=lt.VideoStateDecoding),this.videoState===lt.VideoStateDecoding&&this.onVideoStateChanged&&(this.videoElementFreezeTimeout&&window.clearTimeout(this.videoElementFreezeTimeout),this.videoElementFreezeTimeout=window.setTimeout(s,h("VIDEO_FREEZE_DURATION"))),t<h("VIDEO_FREEZE_DURATION")&&this.videoState===lt.VideoStateFrozen&&(this.videoState=lt.VideoStateDecoding),t>h("VIDEO_FREEZE_DURATION")&&Cs.lastVisibleTime>=Cs.lastHiddenTime&&e.timestamp>Cs.lastVisibleTime&&e.timestamp>Cs.lastHiddenTime){const e=Math.min(66,_r(this._render_interframe_delays_sizes,this._render_interframe_delays)),i=Math.max(0,t-(r-1)*e);this.renderFreezeAccTime2+=i>e?i:0,this.renderFreezeAccTime+=t}}e=Tt(Tt({},i),{},{timestamp:t})}var r,n;h("ENABLE_VIDEO_FRAME_CALLBACK")&&(null===(r=(n=this.videoElement).requestVideoFrameCallback)||void 0===r||r.call(n,o))};null===(t=(i=this.videoElement).requestVideoFrameCallback)||void 0===t||t.call(i,o)}this.videoElement.controls=!1,this.videoElement.setAttribute("playsinline",""),x()&&!h("HIDE_NO_POSTER")&&(this.videoElement.poster="noposter");const r=e();if("Safari"===r.name&&15===Number(r.version)||W()||!this.config.mirror||(this.videoElement.style.transform="rotateY(180deg)"),this.config.fit?this.videoElement.style.objectFit=this.config.fit:this.videoElement.style.objectFit="cover",this.videoElement.setAttribute("muted",""),this.videoElement.muted=!0,this.videoElement.srcObject&&this.videoElement.srcObject instanceof MediaStream){this.videoElement.srcObject.getVideoTracks()[0]!==this.videoTrack&&(this.videoElement.srcObject=this.videoTrack?new MediaStream([this.videoTrack]):null,u()&&this.videoElement.load())}else this.videoElement.srcObject=this.videoTrack?new MediaStream([this.videoTrack]):null,u()&&this.videoElement.load();const s=this.videoElement.play();void 0!==s&&s.catch((e=>{le.debug("[".concat(this.trackId,"] playback interrupted"),e.toString())}))}resetVideoElement(){Tr.forEach((e=>{this.videoElement&&this.videoElement.removeEventListener(e,this.handleVideoEvents)})),this.videoElementCheckInterval&&(window.clearInterval(this.videoElementCheckInterval),this.videoElementCheckInterval=void 0),this.videoElementStatus=ut.NONE}handleAutoPlayFailed(){const e=t=>{t.preventDefault(),this.videoElement.play().then((()=>{le.debug("[".concat(this.trackId,"] Video element for trackId:").concat(this.trackId," autoplay resumed."))})).catch((e=>{le.error(e)})),this.autoplayFailed=!1,F()?document.body.removeEventListener("click",e,!0):(document.body.removeEventListener("touchstart",e,!0),document.body.removeEventListener("mousedown",e,!0))};F()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0)),qt()}}const Tr=["play","playing","loadeddata","canplay","pause","stalled","suspend","waiting","abort","emptied","ended","timeupdate","error"];class vr extends fr{constructor(e){super(e),_t(this,"container",void 0),_t(this,"slot",void 0),this.slot=e.element,this.updateConfig(e)}updateConfig(e){this.config=e,this.trackId=e.trackId;const t=e.element;t!==this.slot&&(this.destroy(),this.slot=t),this.createElements()}updateVideoTrack(e){this.videoTrack!==e&&(this.videoTrack=e,this.createElements())}play(e){var t;null!==(t=this.container)&&void 0!==t&&t.contains(this.videoElement)&&super.play(e)}getCurrentFrame(){var e;return null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)?super.getCurrentFrame():new ImageData(2,2)}async getCurrentFrameToUint8Array(e){var t;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return null!==(t=this.container)&&void 0!==t&&t.contains(this.videoElement)?await super.getCurrentFrameToUint8Array(e,i):await Si(e)}destroy(){if(super.destroy(),this.videoElement.remove(),this.videoElement=document.createElement("video"),this.container){try{this.container.remove(),this.slot.removeChild(this.container)}catch(e){}this.container=void 0}}createElements(){this.container||(this.container=document.createElement("div")),this.container.id="agora-video-player-".concat(this.trackId),this.container.style.width="100%",this.container.style.height="100%",this.container.style.position="relative",this.container.style.overflow="hidden",this.videoTrack?(this.container.style.backgroundColor="black",h("KEEP_LAST_FRAME")&&this.isKeepLastFrame&&this.videoElement.paused&&this.resetVideoElement(),this.mountedVideoElement()):this.unmountedVideoElement(),this.slot.appendChild(this.container)}mountedVideoElement(){var e;!this.container||null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)||this.container.appendChild(this.videoElement),super.initVideoElement(),this.videoElement.id="video_".concat(this.trackId),this.videoElement.className="agora_video_player",this.videoElement.style.width="100%",this.videoElement.style.height="100%",this.videoElement.style.position="absolute",this.videoElement.style.left="0",this.videoElement.style.top="0"}unmountedVideoElement(){var e;if(null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)){super.resetVideoElement();try{this.container&&this.container.removeChild(this.videoElement)}catch(e){}this.videoElement=document.createElement("video")}}resetVideoElement(){var e;null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)&&(super.resetVideoElement(),this.cacheVideoElement=this.videoElement,this.videoElement=document.createElement("video"))}getContainerElement(){return this.container}}var Er,Sr,yr,kr,br,Ir,Ar,Rr,wr,Dr,Cr,Nr,Mr,Or,Lr,Pr,Vr,xr,Ur,Br,Fr,Gr,Wr,Hr,Kr,Zr,Yr,zr,jr,Xr,Qr,Jr,qr,$r,es,ts,is,rs;let ss=(Er=ge({argsMap:(e,t,i)=>[e.getTrackId(),"string"==typeof t?t:t instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement",i]}),Sr=ii(),yr=ge({argsMap:e=>[e.getTrackId()]}),kr=J("LocalVideoTrack","_enabledMutex"),br=ge({argsMap:(e,t)=>[e.getTrackId(),t]}),Ir=ii(),Ar=J("LocalVideoTrack","_enabledMutex"),Rr=ge({argsMap:(e,t)=>[e.getTrackId(),t]}),wr=ii(),Dr=ge({argsMap:(e,t)=>[e.getTrackId(),t,e._saveEncodeBitrateRatio]}),Cr=ii(),Nr=ge({argsMap:(e,t)=>[e.getTrackId(),t]}),Mr=ii(),Or=ii(),Lr=ge({argsMap:(e,t,i)=>[e.getTrackId(),t,i]}),Pr=ii(),Vr=ii(),xr=ii(),Ur=ge({argsMap:e=>[e.getTrackId()]}),Br=ii(),Fr=ii(),Gr=ii(),Wr=ii(),Hr=ii(),Kr=ge({argsMap:(e,t)=>[e.getTrackId(),t.name]}),Zr=ge({argsMap:e=>[e.getTrackId()]}),Yr=ge({argsMap:e=>[e.getTrackId()]}),zr=ge({argsMap:(e,t,i)=>[e.getTrackId(),t.label,i]}),jr=class e extends Et{get videoHeight(){if(c()){const{height:e}=this._mediaStreamTrack.getSettings();return this._videoHeight=e,this._videoHeight}return this._videoHeight}get videoWidth(){if(c()){const{width:e}=this._mediaStreamTrack.getSettings();return this._videoWidth=e,this._videoWidth}return this._videoWidth}get isPlaying(){return!(!this._player||this._player.videoElementStatus!==ut.PLAYING)}get processorDestination(){return this._processorDestination}get processorContext(){return this._processorContext}set processorContext(e){this._processorContext=e}get __className__(){return"LocalVideoTrack"}constructor(e,i,r,s,o,n){if(super(e,o),_t(this,"trackMediaType",qe.VIDEO),_t(this,"_player",void 0),_t(this,"isUseScaleResolutionDownBy",!1),_t(this,"_videoVisibleTimer",null),_t(this,"_previousVideoVisibleStatus",void 0),_t(this,"_clearPreviousVideoVisibleStatus",(()=>this._previousVideoVisibleStatus=void 0)),_t(this,"_encoderConfig",void 0),_t(this,"_scalabilityMode",{numSpatialLayers:1,numTemporalLayers:1}),_t(this,"_optimizationMode",void 0),_t(this,"_saveEncodeBitrateRatio",1),_t(this,"_videoHeight",void 0),_t(this,"_videoWidth",void 0),_t(this,"_forceBitrateLimit",void 0),_t(this,"_enabled",!0),_t(this,"_processorDestination",void 0),_t(this,"_processorContext",void 0),c()){const{width:t,height:i}=e.getSettings();this._videoWidth=t,this._videoHeight=i}else this.updateMediaStreamTrackResolution();if(this._scalabilityMode=r,this._optimizationMode=s,this._hints=n||[],i&&-1!==this._hints.indexOf(Ke.CUSTOM_TRACK)?this._encoderConfig=oe(i):this._encoderConfig=i,-1===this._hints.indexOf(Ke.SCREEN_TRACK))this.updateBitrateFromProfile();else if(ne(t.CHROME,115)&&ae()){const t=ki(e);t&&(le.info("local screen video track begin to inject frame"),this._mediaStreamTrack=t)}i&&-1!==this._hints.indexOf(Ke.CUSTOM_TRACK)&&this.setEncoderConfiguration(i),this._processorContext=new si(this.getTrackId(),"local"),this._processorDestination=new ri(this.processorContext),this.bindProcessorDestinationEvents()}play(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("string"==typeof e){const t=document.getElementById(e);t?e=t:(le.warning("[".concat(this.getTrackId(),'] can not find "#').concat(e,'" element, use document.body')),e=document.body)}le.debug("[".concat(this.getTrackId(),"] start video playback in ").concat(e instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement"),JSON.stringify(t));const i=Tt(Tt(Tt({},this._getDefaultPlayerConfig()),t),{},{trackId:this.getTrackId(),element:e});this._player?this._player.updateConfig(i):(e instanceof HTMLVideoElement?this._player=new fr(i):this._player=new vr(i),this._player.updateVideoTrack(this._mediaStreamTrack)),this._player.play(),this._videoVisibleTimer&&window.clearInterval(this._videoVisibleTimer),this._clearPreviousVideoVisibleStatus(),this._videoVisibleTimer=window.setInterval((()=>{try{const e=this.getVideoElementVisibleStatus();this.safeEmit(Qe.VIDEO_ELEMENT_VISIBLE_STATUS,e)}catch(e){}}),h("CHECK_VIDEO_VISIBLE_INTERVAL"))}stop(){this._player&&(this._videoVisibleTimer&&(window.clearInterval(this._videoVisibleTimer),this._videoVisibleTimer=null),this._clearPreviousVideoVisibleStatus(),this._player.destroy(),this._player=void 0,le.debug("[".concat(this.getTrackId(),"] stop video playback")))}async setEnabled(e,t){if(!t){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(le.info("[".concat(this.getTrackId(),"] start setEnabled"),e),!e){this._originMediaStreamTrack.enabled=!1;try{await w(this,He.NEED_DISABLE_TRACK,this)}catch(e){throw le.error("[".concat(this.getTrackId(),"] setEnabled to false error"),e.toString()),e}return t||(this._enabled=!1),void le.info("[".concat(this.getTrackId(),"] setEnabled to false success"))}this._originMediaStreamTrack.enabled=!0;try{await w(this,He.NEED_ENABLE_TRACK,this)}catch(e){throw le.error("[".concat(this.getTrackId(),"] setEnabled to true error"),e.toString()),e}le.info("[".concat(this.getTrackId(),"] setEnabled to true success")),t||(this._enabled=!0)}async setMuted(e){e!==this._muted&&(this.stateCheck("muted",e),this._muted=e,this._originMediaStreamTrack.enabled=!e,le.debug("[".concat(this.getTrackId(),"] start set muted: ").concat(e)),e?await w(this,He.NEED_MUTE_TRACK,this):await w(this,He.NEED_UNMUTE_TRACK,this))}async setSaveEncodeBitrateRatio(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this._saveEncodeBitrateRatio;if(1!==this._saveEncodeBitrateRatio&&this._encoderConfig&&this._encoderConfig.bitrateMax&&this._encoderConfig.bitrateMin){this._encoderConfig.bitrateMin=Math.floor(this._encoderConfig.bitrateMin*e),this._encoderConfig.bitrateMax=Math.floor(this._encoderConfig.bitrateMax*e),le.debug("[".concat(this.getTrackId(),"] set save encode bitrate ratio, ").concat(e)),this._saveEncodeBitrateRatio=1;try{await w(this,He.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(le)}}}async setEncoderConfiguration(e,t){if(!this._enabled)throw new v(E.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");if(e=Ce(e),h("USE_STANDARD_BITRATE_DEFAULT")&&(delete e.bitrateMax,delete e.bitrateMin),this._forceBitrateLimit&&(e.bitrateMax=this._forceBitrateLimit.max_bitrate?this._forceBitrateLimit.max_bitrate:e.bitrateMax,e.bitrateMin=this._forceBitrateLimit.min_bitrate?this._forceBitrateLimit.min_bitrate:e.bitrateMin),e.width||e.height||e.frameRate){const t=hi({encoderConfig:e});(c()||C()||N())&&(t.deviceId=void 0),le.debug("[".concat(this.getTrackId(),"] setEncoderConfiguration applyConstraints"),JSON.stringify(e),JSON.stringify(t));try{await this._originMediaStreamTrack.applyConstraints(t),this.updateMediaStreamTrackResolution()}catch(e){const t=new v(E.UNEXPECTED_ERROR,e.toString());throw le.error("[".concat(this.getTrackId(),"] applyConstraints error"),t.toString()),t}}this._encoderConfig=e,-1===this._hints.indexOf(Ke.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await w(this,He.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(le)}}getStats(){b((()=>{le.warning("[deprecated] LocalVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalVideoStats instead")}),"localVideoTrackGetStatsWarning");const e=q(this,He.GET_STATS);return e||Tt({},it)}async setBeautyEffect(e){le.error("LocalVideoTrack.setBeautyEffect was deprecated, please migrate to agora-extension-beauty-effect")}getCurrentFrameData(){return this._player?this._player.getCurrentFrame():new ImageData(2,2)}async getCurrentFrameImage(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return this._player?this._player.getCurrentFrameToUint8Array(e,t):await Si(e)}async findClosestProfile(){const{width:e,height:t,frameRate:i}=this.getMediaStreamTrackSettings(),{width:r,height:s,frameRate:o}=this._encoderConfig||{},n=j(this._videoWidth||e||r||0),a=j(this._videoHeight||t||s||0),c=_i(n,a,j(i||o||15));if(c)return le.debug("[".concat(this.getTrackId(),"] find closest profile, ").concat(n,"x").concat(a," => ").concat(JSON.stringify(c))),this.setEncoderConfiguration(c)}async setBitrateLimit(e){le.debug("[".concat(this.getTrackId(),"] set bitrate limit, ").concat(JSON.stringify(e))),e&&(this._forceBitrateLimit=e,this._encoderConfig&&(this._encoderConfig.bitrateMax?this._encoderConfig.bitrateMax=this._encoderConfig.bitrateMax<e.max_bitrate?this._encoderConfig.bitrateMax:e.max_bitrate:this._encoderConfig.bitrateMax=e.max_bitrate,this._encoderConfig.bitrateMin,this._encoderConfig.bitrateMin=e.min_bitrate))}async setOptimizationMode(e){if("motion"!==e&&"detail"!==e&&"balanced"!==e)return void le.error(E.INVALID_PARAMS,"optimization mode must be motion, detail or balanced");const t=this._optimizationMode;try{this._optimizationMode=e,await w(this,He.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this)}catch(e){throw this._optimizationMode=t,le.error("[".concat(this.getTrackId(),"] set optimization mode failed"),e.toString()),e}le.info("[".concat(this.getTrackId(),"] set optimization mode success (").concat(e,")"))}setScalabiltyMode(e){if(1===e.numSpatialLayers&&1!==e.numTemporalLayers)return le.error(E.INVALID_PARAMS,"scalability mode currently not supported, no SVC."),void(this._scalabilityMode={numSpatialLayers:1,numTemporalLayers:1});this._scalabilityMode=e,le.info("[".concat(this.getTrackId(),"] set scalability mode success (").concat(e,")"))}updateMediaStreamTrackResolution(){di(this._originMediaStreamTrack).then((e=>{let[t,i]=e;this._videoHeight=i,this._videoWidth=t})).catch(K)}_updatePlayerSource(){this._player&&this._player.updateVideoTrack(this._mediaStreamTrack)}_getDefaultPlayerConfig(){return{fit:"contain"}}async setSenderConfiguration(e){if(!this._enabled)throw new v(E.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");le.debug("[".concat(this.getTrackId(),"] setSenderConfiguration applyConstraints"),JSON.stringify(e)),e=Ce(e),this._forceBitrateLimit&&(e.bitrateMax=this._forceBitrateLimit.max_bitrate?this._forceBitrateLimit.max_bitrate:e.bitrateMax,e.bitrateMin=this._forceBitrateLimit.min_bitrate?this._forceBitrateLimit.min_bitrate:e.bitrateMin),this._encoderConfig=e,-1===this._hints.indexOf(Ke.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await w(this,He.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(le)}}updateBitrateFromProfile(){if(!this._encoderConfig)return;const{width:e,height:t,frameRate:i}=this.getMediaStreamTrackSettings();if(!e||!t||!i)return;const{bitrateMax:r,bitrateMin:s}=this._encoderConfig;if(null==s||null==r){const{max:o,min:n}=fi(e,t,i,s,r);if(this._encoderConfig.bitrateMin=n,this._encoderConfig.bitrateMax=o,h("VIDEO_STANDARD_BITRATE_VERSION")&&null==s&&null==r){const[r,s]=gi(e,t,i);this._encoderConfig.bitrateMax=r,this._encoderConfig.bitrateMin=n?Math.min(n,r):r,this._saveEncodeBitrateRatio=s,le.debug("[".concat(this.getTrackId(),"] update new bitrate from profile, [w: ").concat(e,", h: ").concat(t,", fps: ").concat(i,"] => [brMax: ").concat(this._encoderConfig.bitrateMax,", brMin: ").concat(this._encoderConfig.bitrateMin,", save_bitrate_ratio: ").concat(this._saveEncodeBitrateRatio,"]"))}else le.debug("[".concat(this.getTrackId(),"] update bitrate from profile, [w: ").concat(e,", h: ").concat(t,", fps: ").concat(i,"] => [brMax: ").concat(o,", brMin: ").concat(n,"]")),this._saveEncodeBitrateRatio=1}}getVideoElementVisibleStatus(){try{var e,t;const i=null==this||null===(e=this._player)||void 0===e?void 0:e.getContainerElement(),r={track:this,element:null==this||null===(t=this._player)||void 0===t?void 0:t.getVideoElement(),slot:null==i?void 0:i.parentElement},{element:s,slot:o}=r;if(this.isPlaying&&s instanceof HTMLVideoElement&&o instanceof HTMLElement){const e=ce.checkOneElementVisible(s),t=Object.assign({},e);if(t.visible!==this._previousVideoVisibleStatus){this._previousVideoVisibleStatus=t.visible;const e=pe.reportApiInvoke(null,{tag:A.TRACER,name:I.LOCAL_VIDEO_TRACK_GET_VIDEO_VISIBLE,options:[this.getTrackId()]});t.visible?e.onSuccess("Video is visible"):e.onSuccess("Invisible because of ".concat(t.reason))}return t}return}catch(e){throw new v(E.GET_VIDEO_ELEMENT_VISIBLE_ERROR,e.message)}}async renewMediaStreamTrack(e){}pipe(e){if(this.processor===e)return e;if(e._source)throw new v(E.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,context:this.processorContext}),e}unpipe(){if(!this.processor)return;const e=this.processor;this.processor._source=void 0,this.processor=void 0,e.reset()}close(){super.close(),this.unbindProcessorDestinationEvents(),this.unbindProcessorContextEvents(),this.unpipe(),this.processorDestination._source&&this.processorDestination._source.unpipe()}clone(t){let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],r=this._encoderConfig;t&&(r=Tt(Tt({},r),Ce(t))),r=de(r);const s=k(8,"track-video-cloned-"),o=new e(i?this._mediaStreamTrack.clone():this._mediaStreamTrack,r,de(this._scalabilityMode),this._optimizationMode,s,de(this._hints));return t&&r&&o.setEncoderConfiguration(r),le.debug("clone video track from ".concat(this.getTrackId()," to ").concat(s,", clone ").concat(i)),o}async replaceTrack(e,t){if(!(e instanceof MediaStreamTrack))throw new v(E.INVALID_PARAMS,"track should be an instance of MediaStreamTrack");if("video"!==e.kind)throw new v(E.INVALID_PARAMS,"track should be a video MediaStreamTrack");await this._updateOriginMediaStreamTrack(e,t,!0),this.updateMediaStreamTrackResolution()}sendSeiData(e){if(b((()=>{pe.reportApiInvoke(null,{name:I.LOCAL_VIDEO_SEND_SEI_DATA,options:[],tag:A.TRACER}).onSuccess("")}),this._mediaStreamTrack.id||this.getTrackId()),!h("ENABLE_VIDEO_SEI")||!h("ENABLE_ENCODED_TRANSFORM"))return void le.warning('To send/receive SEI, please call AgoraRTC.setParameter("ENABLE_VIDEO_SEI", true) before instantiate IAgoraRtcClient');if(e instanceof Uint8Array==!1)return new v(E.INVALID_PARAMS,"Invalid argument type, ILocalVideoTrack.sendSeiData() only accept Uint8Array argument.").throw();const t=this.getRTCRtpTransceiver();if(!t)return void le.warning("Video track is not published, SEI can not be send");const i=t.sender.getParameters();if(0===i.codecs.length)return;const r=i.codecs[0].mimeType.toLocaleLowerCase();"video/h264"===r?this.safeEmit("sei-to-send",e):le.warning("SEI is not supported by ".concat(r))}bindProcessorDestinationEvents(){this.processorDestination.on(nt.ON_TRACK,(async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(),await w(this,He.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await w(this,He.NEED_REPLACE_TRACK,this))}))}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(nt.ON_TRACK)}unbindProcessorContextEvents(){this.processorContext.removeAllListeners(at.REQUEST_UPDATE_CONSTRAINTS),this.processorContext.removeAllListeners(at.REQUEST_CONSTRAINTS)}},gt(jr.prototype,"play",[Er,Sr],Object.getOwnPropertyDescriptor(jr.prototype,"play"),jr.prototype),gt(jr.prototype,"stop",[yr],Object.getOwnPropertyDescriptor(jr.prototype,"stop"),jr.prototype),gt(jr.prototype,"setEnabled",[kr,br,Ir],Object.getOwnPropertyDescriptor(jr.prototype,"setEnabled"),jr.prototype),gt(jr.prototype,"setMuted",[Ar,Rr,wr],Object.getOwnPropertyDescriptor(jr.prototype,"setMuted"),jr.prototype),gt(jr.prototype,"setSaveEncodeBitrateRatio",[Dr,Cr],Object.getOwnPropertyDescriptor(jr.prototype,"setSaveEncodeBitrateRatio"),jr.prototype),gt(jr.prototype,"setEncoderConfiguration",[Nr,Mr],Object.getOwnPropertyDescriptor(jr.prototype,"setEncoderConfiguration"),jr.prototype),gt(jr.prototype,"getStats",[Or],Object.getOwnPropertyDescriptor(jr.prototype,"getStats"),jr.prototype),gt(jr.prototype,"setBeautyEffect",[Lr,Pr],Object.getOwnPropertyDescriptor(jr.prototype,"setBeautyEffect"),jr.prototype),gt(jr.prototype,"getCurrentFrameData",[Vr],Object.getOwnPropertyDescriptor(jr.prototype,"getCurrentFrameData"),jr.prototype),gt(jr.prototype,"getCurrentFrameImage",[xr],Object.getOwnPropertyDescriptor(jr.prototype,"getCurrentFrameImage"),jr.prototype),gt(jr.prototype,"findClosestProfile",[Ur,Br],Object.getOwnPropertyDescriptor(jr.prototype,"findClosestProfile"),jr.prototype),gt(jr.prototype,"setBitrateLimit",[Fr],Object.getOwnPropertyDescriptor(jr.prototype,"setBitrateLimit"),jr.prototype),gt(jr.prototype,"setOptimizationMode",[Gr],Object.getOwnPropertyDescriptor(jr.prototype,"setOptimizationMode"),jr.prototype),gt(jr.prototype,"setScalabiltyMode",[Wr],Object.getOwnPropertyDescriptor(jr.prototype,"setScalabiltyMode"),jr.prototype),gt(jr.prototype,"updateMediaStreamTrackResolution",[Hr],Object.getOwnPropertyDescriptor(jr.prototype,"updateMediaStreamTrackResolution"),jr.prototype),gt(jr.prototype,"pipe",[Kr],Object.getOwnPropertyDescriptor(jr.prototype,"pipe"),jr.prototype),gt(jr.prototype,"unpipe",[Zr],Object.getOwnPropertyDescriptor(jr.prototype,"unpipe"),jr.prototype),gt(jr.prototype,"close",[Yr],Object.getOwnPropertyDescriptor(jr.prototype,"close"),jr.prototype),gt(jr.prototype,"replaceTrack",[zr],Object.getOwnPropertyDescriptor(jr.prototype,"replaceTrack"),jr.prototype),jr),os=(Xr=ge({argsMap:(e,t)=>[e.getTrackId(),t]}),Qr=ii(),Jr=J("CameraVideoTrack","_enabledMutex"),qr=ge({argsMap:(e,t)=>[e.getTrackId(),t]}),$r=ii(),es=ge({argsMap:(e,t)=>[e.getTrackId(),t]}),ts=ii(),is=ge({argsMap:e=>[e.getTrackId()]}),rs=class e extends ss{get __className__(){return"CameraVideoTrack"}constructor(e,t,i,r,s,o){super(e,Ce(t.encoderConfig),r,s,o),_t(this,"_config",void 0),_t(this,"_originalConstraints",void 0),_t(this,"_constraints",void 0),_t(this,"_enabled",!0),_t(this,"_deviceName","default"),_t(this,"tryResumeVideoForIOS15_16WeChat",(async()=>{(W()||$())&&!he()&&ue()&&this._enabled&&!this._isClosed&&(le.debug("[".concat(this.getTrackId(),"] try capture camera media device for interrupted iOS 15 device on WeChat.")),await this.renewMediaStreamTrack())})),this._config=t,this._originalConstraints=i,this._constraints=i,this._deviceName=e.label,this._encoderConfig=Ce(this._config.encoderConfig),kt.on(ye.IOS_15_16_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),kt.on(ye.IOS_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),this.bindProcessorContextEvents()}async setDevice(e){return"string"==typeof e?this._setDeviceById(e):e.deviceId?this._setDeviceById(e.deviceId):e.facingMode?this._setDeviceByFacingModel(e.facingMode):void 0}async _setDeviceById(e){if(le.info("[".concat(this.getTrackId(),"] set device to ").concat(e)),this._enabled)try{const t=await Xt.getDeviceById(e),i={};i.video=Tt({},this._constraints),i.video.deviceId={exact:e},i.video.facingMode=void 0,this._originMediaStreamTrack.stop();let r=null;try{r=await Kt(i,this.getTrackId())}catch(e){throw le.error("[".concat(this.getTrackId(),"] setDevice failed"),e.toString()),r=await Kt({video:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(r.getVideoTracks()[0],!1),e}await this._updateOriginMediaStreamTrack(r.getVideoTracks()[0],!1),this.updateMediaStreamTrackResolution(),this._deviceName=t.label,this._config.cameraId=e,this._constraints.deviceId={exact:e}}catch(e){throw le.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}else try{const t=await Xt.getDeviceById(e);this._deviceName=t.label,this._config.cameraId=e,this._constraints.deviceId={exact:e}}catch(e){throw le.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}le.info("[".concat(this.getTrackId(),"] setDevice success"))}async _setDeviceByFacingModel(e){le.info("[".concat(this.getTrackId(),"] set facingMode ").concat(e));const t={video:Tt(Tt({},this._constraints),{},{deviceId:void 0,facingMode:{exact:e}})};if(this._enabled){this._originMediaStreamTrack.stop();let e=null;try{e=await Kt(t,this.getTrackId())}catch(t){throw le.error("[".concat(this.getTrackId(),"] setDeviceByFacingModel failed"),t.toString()),e=await Kt({video:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!1),t}await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!1),this.updateMediaStreamTrackResolution()}this._deviceName="",this._config.facingMode=e,this._config.cameraId=void 0,this._constraints=Tt({},t.video),le.info("[".concat(this.getTrackId(),"] setDeviceByFacingModel success"))}async setEnabled(e,t){if(!t){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(le.info("[".concat(this.getTrackId(),"] start setEnabled"),e),e){try{if(this.isExternalTrack)this._originMediaStreamTrack.enabled=!0;else{const e=await Kt({video:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!1)}await w(this,He.NEED_ENABLE_TRACK,this)}catch(e){throw le.error("[".concat(this.getTrackId(),"] setEnabled true error"),e.toString()),e}this.updateMediaStreamTrackResolution(),le.info("[".concat(this.getTrackId(),"] setEnabled to true success")),t||(this._enabled=!0)}else{this.isExternalTrack?this._originMediaStreamTrack.enabled=!1:(this._originMediaStreamTrack.onended=null,this._originMediaStreamTrack.stop()),t||(this._enabled=!1);try{await w(this,He.NEED_DISABLE_TRACK,this)}catch(e){throw le.error("[".concat(this.getTrackId(),"] setEnabled to false error"),e.toString()),e}le.info("[".concat(this.getTrackId(),"] setEnabled to false success"))}}async setEncoderConfiguration(e,t){if(!this._enabled)throw new v(E.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");if(e=Ce(e),h("USE_STANDARD_BITRATE_DEFAULT")&&(delete e.bitrateMax,delete e.bitrateMin),this._forceBitrateLimit&&(e.bitrateMax=this._forceBitrateLimit.max_bitrate||e.bitrateMax,e.bitrateMin=this._forceBitrateLimit.min_bitrate||e.bitrateMin),(l()&&x()||h("ADAPT_IGNORE_BROWSER_CHECK"))&&h("LIMIT_LOWEST_PROFILE")){const t=j(e.width||0),i=j(e.height||0),r=j(e.frameRate||15);if(t&&i&&t*i<=19200){const s=_i(t,i,r||15);s&&(e.width=s.width,e.height=s.height,e.frameRate=s.frameRate,le.debug("find closest profile, ".concat(t,"x").concat(i," => ").concat(JSON.stringify(s))))}}const i=oe(this._config);i.encoderConfig=e;const r=hi(i);(c()||C()||N())&&(r.deviceId=void 0),le.debug("[".concat(this.getTrackId(),"] setEncoderConfiguration applyConstraints"),JSON.stringify(e),JSON.stringify(r));try{await this._originMediaStreamTrack.applyConstraints(r),this.updateMediaStreamTrackResolution()}catch(e){const t=new v(E.UNEXPECTED_ERROR,e.toString());throw le.error("[".concat(this.getTrackId(),"] applyConstraints error"),t.toString()),t}this._config=i,this._constraints=r,this._originalConstraints=r,this._encoderConfig=e,-1===this._hints.indexOf(Ke.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await w(this,He.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(le)}}_getDefaultPlayerConfig(){return{mirror:!0,fit:"cover"}}onTrackEnded(){if((C()||N())&&this._enabled&&!this._isClosed&&kt.duringInterruption){const e=async()=>{kt.off(ye.IOS_INTERRUPTION_END,e),this._enabled&&!this._isClosed&&(le.debug("[".concat(this.getTrackId(),"] try capture camera media device for interrupted iOS device.")),await this.setEnabled(!1),await this.setEnabled(!0))};kt.on(ye.IOS_INTERRUPTION_END,e)}else le.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(Qe.TRACK_ENDED)}async renewMediaStreamTrack(e){const t=e||this._constraints,i=Xt.searchDeviceIdByName(this._deviceName);if(i&&!t.deviceId&&(t.deviceId={exact:i}),this._enabled){const e=await Kt({video:t},this.getTrackId());this._constraints=t,await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!0),this.updateMediaStreamTrackResolution()}}close(){super.close(),kt.off(ye.IOS_15_16_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),kt.off(ye.IOS_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat)}clone(t){let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],r=this._encoderConfig;t&&(r=Tt(Tt({},r),Ce(t))),r=de(r);const s=k(8,"track-cam-cloned-"),o=new e(i?this._mediaStreamTrack.clone():this._mediaStreamTrack,de(Tt(Tt({},this._config),{},{encoderConfig:r})),de(this._constraints),de(this._scalabilityMode),this._optimizationMode,s);return t&&r&&o.setEncoderConfiguration(r),le.debug("clone track from ".concat(this.getTrackId()," to ").concat(s,", clone ").concat(i)),o}bindProcessorContextEvents(){this.processorContext.on(at.REQUEST_UPDATE_CONSTRAINTS,(async(e,t,i)=>{try{const i=Object.assign({},this._originalConstraints,...e);await this.renewMediaStreamTrack(i),t()}catch(e){i(e)}})),this.processorContext.on(at.REQUEST_CONSTRAINTS,(async e=>{e(this._originMediaStreamTrack.getSettings())}))}},gt(rs.prototype,"setDevice",[Xr,Qr],Object.getOwnPropertyDescriptor(rs.prototype,"setDevice"),rs.prototype),gt(rs.prototype,"setEnabled",[Jr,qr,$r],Object.getOwnPropertyDescriptor(rs.prototype,"setEnabled"),rs.prototype),gt(rs.prototype,"setEncoderConfiguration",[es,ts],Object.getOwnPropertyDescriptor(rs.prototype,"setEncoderConfiguration"),rs.prototype),gt(rs.prototype,"close",[is],Object.getOwnPropertyDescriptor(rs.prototype,"close"),rs.prototype),rs);function ns(e){const t=k(8,"track-cus-"),i=pe.reportApiInvoke(null,{id:t,tag:A.TRACER,name:I.CREATE_CUSTOM_AUDIO_TRACK,options:[e]}),r=new hr(e.mediaStreamTrack,e.encoderConfig?Le(e.encoderConfig):{},t,!1);return le.info("create custom audio track success with config",e,"trackId",r.getTrackId()),i.onSuccess(r.getTrackId()),r}async function as(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const t=k(8,"track-mic-"),i=pe.reportApiInvoke(null,{id:t,tag:A.TRACER,name:I.CREATE_MIC_AUDIO_TRACK,options:[e]}),r=mi(e);let s=null;le.info("start create microphone audio track with config",JSON.stringify(e),"trackId",t);try{s=(await Kt({audio:r},t)).getAudioTracks()[0]||null}catch(e){throw i.onError(e),e}if(!s){const e=new v(E.UNEXPECTED_ERROR,"can not find track in media stream");return i.onError(e),e.throw(le)}const o=new ur(s,e,r,t);return i.onSuccess(o.getTrackId()),le.info("create microphone audio track success, trackId:",t),o}async function cs(e){var t;const{cacheOnlineFile:i,encoderConfig:r}=e;let{source:s}=e;const o={source:s instanceof AudioBuffer?"AudioBuffer":s instanceof File?null!==(t=File.name)&&void 0!==t?t:"File":s,cacheOnlineFile:i,encoderConfig:r},n=k(8,"track-buf-"),a=pe.reportApiInvoke(null,{id:n,tag:A.TRACER,name:I.CREATE_BUFFER_AUDIO_TRACK,options:[o]});if(h("DISABLE_WEBAUDIO"))throw new v(E.NOT_SUPPORTED,"can not create BufferSourceAudioTrack when WebAudio disabled");le.info("start create buffer source audio track with config",JSON.stringify(o),"trackId",n);const c=s;if(!(s instanceof AudioBuffer))try{s=await async function(e,t){let i=null;if("string"==typeof e){const t=gr.get(e);if(t)return le.debug("use cached audio resource: ",e),t;try{i=(await ee((()=>_e.get(e,{responseType:"arraybuffer"})),void 0,void 0,{maxRetryCount:3})).data}catch(e){throw new v(E.FETCH_AUDIO_FILE_FAILED,e.toString())}}else{const t=new Promise(((t,i)=>{const r=new FileReader;r.onload=e=>{e.target?t(e.target.result):i(new v(E.READ_LOCAL_AUDIO_FILE_ERROR))},r.onerror=()=>{i(new v(E.READ_LOCAL_AUDIO_FILE_ERROR))},r.readAsArrayBuffer(e)}));i=await t}const r=await wt(i);return"string"==typeof e&&t&&gr.set(e,r),r}(s,i)}catch(e){return a.onError(e),e.throw(le)}const d=new mr(s),u=new lr(c,d,r?Le(r):{},n);return le.info("create buffer source audio track success, trackId:",n),a.onSuccess(u.getTrackId()),u}function ds(e){const t=new pr;return e.forEach((e=>t.addAudioTrack(e))),t}function hs(e){const t=k(8,"track-cus-"),i=pe.reportApiInvoke(null,{id:t,tag:A.TRACER,name:I.CREATE_CUSTOM_VIDEO_TRACK,options:[e]});h("USE_STANDARD_BITRATE_DEFAULT")&&(delete e.bitrateMax,delete e.bitrateMin);const r=new ss(e.mediaStreamTrack,{width:e.width,height:e.height,frameRate:e.frameRate,bitrateMax:e.bitrateMax,bitrateMin:e.bitrateMin},e.scalabiltyMode?Me(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,t,[Ke.CUSTOM_TRACK]);return i.onSuccess(r.getTrackId()),le.info("create custom video track success with config",e,"trackId",r.getTrackId()),r}async function us(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const t=h("CAMERA_CAPTURE_CONFIG"),i=k(8,"track-cam-"),r=pe.reportApiInvoke(null,{id:i,tag:A.TRACER,name:I.CREATE_CAM_VIDEO_TRACK,options:[Tt({},e),t]});t&&(e.encoderConfig=t);const s=hi(e);let o=null;le.info("start create camera video track with config",JSON.stringify(e),"trackId",i);try{const t=j(s.width||0),r=j(s.height||0),n=j(s.frameRate||0);if((l()&&x()||h("ADAPT_IGNORE_BROWSER_CHECK"))&&h("LIMIT_LOWEST_PROFILE")&&t&&r&&t*r<=19200){const i=_i(t,r,n||15);i&&(s.width=i.width,s.height=i.height,e.encoderConfig={width:i.width,height:i.height,frameRate:i.frameRate},le.debug("find closest profile, ".concat(t,"x").concat(r," => ").concat(JSON.stringify(i))))}o=(await Kt({video:s},i)).getVideoTracks()[0]||null}catch(e){throw r.onError(e),e}if(!o){const e=new v(E.UNEXPECTED_ERROR,"can not find track in media stream");return r.onError(e),e.throw(le)}if(e.optimizationMode&&ms(i,o,e,Ce(e.encoderConfig)),h("USE_STANDARD_BITRATE_DEFAULT")){const t=Ce(e.encoderConfig);e.encoderConfig=t,delete t.bitrateMax,delete t.bitrateMin}const n=new os(o,e,s,e.scalabiltyMode?Me(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,i);return r.onSuccess(n.getTrackId()),le.info("create camera video success, trackId:",i),n}async function ls(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=h("CAMERA_CAPTURE_CONFIG"),r=k(8,"track-mic-"),s=k(8,"track-cam-"),o=pe.reportApiInvoke(null,{id:"".concat(r,"-").concat(s),tag:A.TRACER,name:I.CREATE_MIC_AND_CAM_TRACKS,options:[e,t,i]});i&&(t.encoderConfig=i);const n=hi(t),a=mi(e);let c=null,d=null;le.info("start create camera video track(".concat(s,") and microphone audio track(").concat(r,") with config, audio: ").concat(JSON.stringify(e),", video: ").concat(JSON.stringify(t)));try{const e=j(n.width||0),i=j(n.height||0),o=j(n.frameRate||0);if((l()&&x()||h("ADAPT_IGNORE_BROWSER_CHECK"))&&h("LIMIT_LOWEST_PROFILE")&&e&&i&&e*i<=19200){const r=_i(e,i,o||15);r&&(n.width=r.width,n.height=r.height,t.encoderConfig={width:r.width,height:r.height,frameRate:r.frameRate},le.debug("find closest profile, ".concat(e,"x").concat(i," => ").concat(JSON.stringify(r))))}const u=await Kt({audio:a,video:n},"".concat(r,"-").concat(s));c=u.getAudioTracks()[0],d=u.getVideoTracks()[0]}catch(e){throw o.onError(e),e}if(!c||!d){const e=new v(E.UNEXPECTED_ERROR,"can not find tracks in media stream");return o.onError(e),e.throw(le)}if(t.optimizationMode&&ms(s,d,t,Ce(t.encoderConfig)),h("USE_STANDARD_BITRATE_DEFAULT")){const e=Ce(t.encoderConfig);t.encoderConfig=e,delete e.bitrateMax,delete e.bitrateMin}const u=new ur(c,e,a,r),p=new os(d,t,n,t.scalabiltyMode?Me(t.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},t.optimizationMode,s);return o.onSuccess([u.getTrackId(),p.getTrackId()]),le.info("create camera video track(".concat(s,") and microphone audio track(").concat(r,") success")),[u,p]}async function ps(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"disable";const i="object"==typeof t?pi(t):void 0;i&&(t="auto");const r=k(8,"track-scr-v-"),s=pe.reportApiInvoke(null,{id:r,tag:A.TRACER,name:I.CREATE_SCREEN_VIDEO_TRACK,options:[Tt({},e),t]});e.encoderConfig?"string"==typeof e.encoderConfig||e.encoderConfig.width&&e.encoderConfig.height||(e.encoderConfig.width={max:1920},e.encoderConfig.height={max:1080}):e.encoderConfig="1080p_2";const o=ui(e);let n=null,a=null;const c=ve();if(!c.supportShareAudio&&"enable"===t){const e=new v(E.NOT_SUPPORTED,"your browser or platform is not support share-screen with audio");return s.onError(e),e.throw(le)}le.info("start create screen video track with config",e,"withAudio",t,"trackId",r);const d=c.supportShareAudio&&"disable"!==t;try{const e=await Kt({screen:o,screenAudio:d?i||!0:void 0},r);n=e.getVideoTracks()[0]||null,a=e.getAudioTracks()[0]||null}catch(e){throw s.onError(e),e}if(!n){const e=new v(E.UNEXPECTED_ERROR,"can not find track in media stream");return s.onError(e),e.throw(le)}if(!a&&"enable"===t){n&&n.stop();const e=new v(E.SHARE_AUDIO_NOT_ALLOWED);return s.onError(e),e.throw(le)}if(e.optimizationMode||(e.optimizationMode="detail"),e.optimizationMode){ms(r,n,e,e.encoderConfig&&Ne(e.encoderConfig)||void 0),e.encoderConfig&&"string"!=typeof e.encoderConfig&&(e.encoderConfig.bitrateMin=e.encoderConfig.bitrateMax)}const h=new ss(n,e.encoderConfig?Ne(e.encoderConfig):{},e.scalabiltyMode?Me(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,r,[Ke.SCREEN_TRACK]);if(!a)return s.onSuccess(h.getTrackId()),le.info("create screen video track success","video:",h.getTrackId()),h;const u=new hr(a,void 0,k(8,"track-scr-a-"),!1);return s.onSuccess([h.getTrackId(),u.getTrackId()]),le.info("create screen video track success","video:",h.getTrackId(),"audio:",u.getTrackId()),[h,u]}function ms(e,t,i,r){i.optimizationMode&&(r&&r.width&&r.height?(i.encoderConfig=Tt(Tt({},r),{},{bitrateMin:r.bitrateMin,bitrateMax:r.bitrateMax}),"motion"!==i.optimizationMode&&"detail"!==i.optimizationMode||(t.contentHint=i.optimizationMode,t.contentHint===i.optimizationMode?le.debug("[".concat(e,"] set content hint to"),i.optimizationMode):le.debug("[".concat(e,"] set content hint failed")))):le.warning("[".concat(e,"] can not apply optimization mode bitrate config, no encoderConfig")))}var gs,_s,fs,Ts,vs,Es,Ss,ys,ks,bs,Is,As;class Rs extends vt{getUserId(){return this._userId}constructor(e,t,i,r){super(e,"track-".concat(e.kind,"-").concat(t,"-").concat(r.clientId,"_").concat(k(5,""))),_t(this,"_userId",void 0),_t(this,"_uintId",void 0),_t(this,"_isDestroyed",!1),_t(this,"store",void 0),_t(this,"processor",void 0),_t(this,"processorContext",void 0),this._userId=t,this._uintId=i,this.store=r}_updateOriginMediaStreamTrack(e){this._originMediaStreamTrack=e,this._mediaStreamTrack=e,this._updatePlayerSource(),this.processor&&this.processor.updateInput({track:this._originMediaStreamTrack,context:this.processorContext})}_destroy(){this._isDestroyed=!0,le.info("[".concat(this.getTrackId(),"] is destroyed")),this.stop(),super.close()}getProcessorStats(){return this.processorContext.gatherStats()}getProcessorUsage(){return this.processorContext.gatherUsage()}}let ws=(gs=ge({argsMap:(e,t,i)=>[e.getTrackId(),"string"==typeof t?t:t instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement",i]}),_s=ge({argsMap:e=>[e.getTrackId()]}),fs=ge({argsMap:(e,t)=>[e.getTrackId(),t.name]}),Ts=ge({argsMap:e=>[e.getTrackId()]}),gt((vs=class extends Rs{get isPlaying(){return!(!this._player||this._player.videoElementStatus!==ut.PLAYING)}get __className__(){return"RemoteVideoTrack"}constructor(e,t,i,r){super(e,t,i,r),_t(this,"_videoVisibleTimer",null),_t(this,"_previousVideoVisibleStatus",void 0),_t(this,"_clearPreviousVideoVisibleStatus",(()=>this._previousVideoVisibleStatus=void 0)),_t(this,"trackMediaType",qe.VIDEO),_t(this,"_videoWidth",void 0),_t(this,"_videoHeight",void 0),_t(this,"_player",void 0),_t(this,"processorDestination",void 0),_t(this,"processorContext",void 0),this.updateMediaStreamTrackResolution(),this.processorContext=new si(this.getTrackId(),"remote"),this.processorDestination=new ri(this.processorContext),this.bindProcessorDestinationEvents()}getStats(){b((()=>{le.warning("[deprecated] RemoteVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteVideoStats instead")}),"remoteVideoTrackGetStatsWarning");return q(this,He.GET_STATS)||Tt({},ot)}play(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("string"==typeof e){const t=document.getElementById(e);t?e=t:(le.warning("[".concat(this.getTrackId(),'] can not find "#').concat(e,'" element, use document.body')),e=document.body)}le.debug("[".concat(this.getTrackId(),"] start video playback in ").concat(e instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement"),JSON.stringify(t));const i=Tt(Tt({fit:"cover"},t),{},{trackId:this.getTrackId(),element:e});this._player?this._player.updateConfig(i):(e instanceof HTMLVideoElement?this._player=new fr(i):this._player=new vr(i),this._player.updateVideoTrack(this._mediaStreamTrack),this._player.onFirstVideoFrameDecoded=()=>{this.store.subscribe(this.getUserId(),"video",void 0,void 0,Date.now()),this.safeEmit(Je.FIRST_FRAME_DECODED)},this._player.onVideoStateChanged=e=>{this.safeEmit(Je.VIDEO_STATE_CHANGED,e)}),this._player.play(this.store.sessionId||void 0),this._videoVisibleTimer&&window.clearInterval(this._videoVisibleTimer),this._clearPreviousVideoVisibleStatus(),this._videoVisibleTimer=window.setInterval((()=>{try{const e=this.getVideoElementVisibleStatus();this.safeEmit(Je.VIDEO_ELEMENT_VISIBLE_STATUS,e)}catch(e){}}),h("CHECK_VIDEO_VISIBLE_INTERVAL"))}stop(){this._player&&(this._videoVisibleTimer&&(window.clearInterval(this._videoVisibleTimer),this._videoVisibleTimer=null),this._clearPreviousVideoVisibleStatus(),this._player.destroy(),this._player=void 0,le.debug("[".concat(this.getTrackId(),"] stop video playback")))}getCurrentFrameData(){return this._player?this._player.getCurrentFrame():new ImageData(2,2)}updateMediaStreamTrackResolution(){di(this._originMediaStreamTrack).then((e=>{let[t,i]=e;this._videoHeight=i,this._videoWidth=t})).catch(K)}_updatePlayerSource(){le.debug("[".concat(this.getTrackId(),"] update player source track")),this._player&&this._player.updateVideoTrack(this._mediaStreamTrack)}getVideoElementVisibleStatus(){try{var e,t;const i=null==this||null===(e=this._player)||void 0===e?void 0:e.getContainerElement(),r={track:this,element:null==this||null===(t=this._player)||void 0===t?void 0:t.getVideoElement(),slot:null==i?void 0:i.parentElement},{element:s,slot:o}=r;if(this.isPlaying&&s instanceof HTMLVideoElement&&o instanceof HTMLElement){const e=ce.checkOneElementVisible(s),t=Object.assign({},e);if(t.visible!==this._previousVideoVisibleStatus){this._previousVideoVisibleStatus=t.visible;const e=pe.reportApiInvoke(null,{tag:A.TRACER,name:I.REMOTE_VIDEO_TRACK_GET_VIDEO_VISIBLE,options:[this.getTrackId()]});t.visible?e.onSuccess("Video is visible"):e.onSuccess("Invisible because of ".concat(t.reason))}return t}return}catch(e){throw new v(E.GET_VIDEO_ELEMENT_VISIBLE_ERROR,e.message)}}pipe(e){if(this.processor===e)return e;if(e._source)throw new v(E.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,context:this.processorContext}),e}unpipe(){if(!this.processor)return;const e=this.processor;this.processor._source=void 0,this.processor=void 0,e.reset()}bindProcessorDestinationEvents(){this.processorDestination.on(nt.ON_TRACK,(async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource()):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource())}))}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(nt.ON_TRACK)}_destroy(){super._destroy(),this.unbindProcessorDestinationEvents()}_onSei(e){this.emit(Xe.SEI_RECEIVED,e)}}).prototype,"play",[gs],Object.getOwnPropertyDescriptor(vs.prototype,"play"),vs.prototype),gt(vs.prototype,"stop",[_s],Object.getOwnPropertyDescriptor(vs.prototype,"stop"),vs.prototype),gt(vs.prototype,"pipe",[fs],Object.getOwnPropertyDescriptor(vs.prototype,"pipe"),vs.prototype),gt(vs.prototype,"unpipe",[Ts],Object.getOwnPropertyDescriptor(vs.prototype,"unpipe"),vs.prototype),vs),Ds=(Es=ge({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),Ss=ge({argsMap:(e,t)=>[e.getTrackId(),t]}),ys=ge({argsMap:e=>[e.getTrackId()]}),ks=ge({argsMap:e=>[e.getTrackId()]}),bs=ge({argsMap:(e,t)=>[e.getTrackId(),t.name]}),Is=ge({argsMap:e=>[e.getTrackId()]}),gt((As=class extends Rs{get isPlaying(){return this._useAudioElement?ti.isPlaying(this.getTrackId()):this._source.isPlayed}get __className__(){return"RemoteAudioTrack"}constructor(e,t,i,r){super(e,t,i,r),_t(this,"trackMediaType",qe.AUDIO),_t(this,"_source",void 0),_t(this,"_useAudioElement",!0),_t(this,"_volume",100),_t(this,"processorContext",void 0),_t(this,"processorDestination",void 0),_t(this,"_played",!1),_t(this,"_bypassWebAudio",!1),h("DISABLE_WEBAUDIO")?(this._source=new ai,this._bypassWebAudio=!0,this._useAudioElement=!0):(this._source=new xt(e,!0),h("REMOTE_AUDIO_TRACK_USES_WEB_AUDIO")&&(this._useAudioElement=!1)),this._source.once($e.RECEIVE_TRACK_BUFFER,(()=>{this.safeEmit(Je.FIRST_FRAME_DECODED)})),this.processorContext=new ni(this._source.context,this.getTrackId(),"remote"),this.processorDestination=new oi(this.processorContext),this.bindProcessorDestinationEvents(),this._source.on($e.UPDATE_SOURCE,(()=>{this.processor&&this.processor.updateInput({node:this._source.processSourceNode,context:this.processorContext})}))}setAudioFrameCallback(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:4096;if(!e)return this._source.removeAllListeners($e.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(t),this._source.removeAllListeners($e.ON_AUDIO_BUFFER),this._source.on($e.ON_AUDIO_BUFFER,(t=>e(t)))}setVolume(e){this._volume=e,this._useAudioElement?ti.setVolume(this.getTrackId(),e):this._source.setVolume(e/100)}async setPlaybackDevice(e){if(!this._useAudioElement||!Ee())throw new v(E.NOT_SUPPORTED,"your browser does not support setting the audio output device");await ti.setSinkID(this.getTrackId(),e)}getVolumeLevel(){return this._source.getAccurateVolumeLevel()}getStats(){b((()=>{le.warning("[deprecated] RemoteAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteAudioStats instead")}),"remoteAudioTrackGetStatsWarning");return q(this,He.GET_STATS)||Tt({},rt)}play(){le.debug("[".concat(this.getTrackId(),"] start audio playback")),this._played=!0,this._useAudioElement?(le.debug("[".concat(this.getTrackId(),"] use audio element to play")),ti.play(this._mediaStreamTrack,this.getTrackId(),this._volume,this.store.sessionId||void 0)):this._source.play()}stop(){le.debug("[".concat(this.getTrackId(),"] stop audio playback")),this._played=!1,this._useAudioElement?ti.stop(this.getTrackId()):this._source.stop()}_destroy(){super._destroy(),this._played=!1,this.unbindProcessorDestinationEvents(),this._source.destroy()}_isFreeze(){return this._source.isFreeze}_updatePlayerSource(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];le.debug("[".concat(this.getTrackId(),"] update player source track")),e&&this._source.updateTrack(this._mediaStreamTrack),this._useAudioElement&&ti.updateTrack(this.getTrackId(),this._mediaStreamTrack)}pipe(e){if(this._bypassWebAudio)throw new v(E.NOT_SUPPORTED,"can not pipe extension when WebAudio disabled");if(this.processor===e)return e;if(e._source)throw new v(E.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,node:this._source.processSourceNode,context:this.processorContext}),e}unpipe(){var e;if(this._bypassWebAudio)throw new v(E.NOT_SUPPORTED,"can not unpipe extension when WebAudio disabled");if(!this.processor)return;const t=this.processor;null===(e=this._source.processSourceNode)||void 0===e||e.disconnect(),this.processor._source=!1,this.processor=void 0,t.reset()}bindProcessorDestinationEvents(){this.processorDestination.on(nt.ON_TRACK,(async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(!1),this._source.processedNode=this._source.createMediaStreamSourceNode(e)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource())})),this.processorDestination.on(nt.ON_NODE,(e=>{this._source.processedNode=e;const t=!e;this._useAudioElement!==t&&(this._played?(this.stop(),this._useAudioElement=t,this.play()):this._useAudioElement=t)}))}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(nt.ON_TRACK),this.processorDestination.removeAllListeners(nt.ON_NODE)}}).prototype,"setVolume",[Es],Object.getOwnPropertyDescriptor(As.prototype,"setVolume"),As.prototype),gt(As.prototype,"setPlaybackDevice",[Ss],Object.getOwnPropertyDescriptor(As.prototype,"setPlaybackDevice"),As.prototype),gt(As.prototype,"play",[ys],Object.getOwnPropertyDescriptor(As.prototype,"play"),As.prototype),gt(As.prototype,"stop",[ks],Object.getOwnPropertyDescriptor(As.prototype,"stop"),As.prototype),gt(As.prototype,"pipe",[bs],Object.getOwnPropertyDescriptor(As.prototype,"pipe"),As.prototype),gt(As.prototype,"unpipe",[Is],Object.getOwnPropertyDescriptor(As.prototype,"unpipe"),As.prototype),As);const Cs=new class extends y{get visibility(){return document.visibilityState}get lastHiddenTime(){return this._lastHiddenTime}get lastVisibleTime(){return this._lastVisibleTime}constructor(){super(),_t(this,"_lastHiddenTime",0),_t(this,"_lastVisibleTime",0),document.addEventListener("visibilitychange",(()=>{"hidden"===document.visibilityState?this._lastHiddenTime=performance.now():this._lastVisibleTime=performance.now(),le.debug("current web page is ".concat(document.visibilityState)),this.emit("VISIBILITY_CHANGE",document.visibilityState)}))}};class Ns extends y{constructor(e,t){super(),_t(this,"trackMediaType",qe.DATA),_t(this,"_version",1),_t(this,"_type",3),_t(this,"_config",void 0),_t(this,"_originDataChannel",void 0),_t(this,"_dataStreamPacketHeader",new ArrayBuffer(4)),_t(this,"_dataStreamPacketHandler",{serialize:e=>e,deserialize:e=>e}),_t(this,"_datachannelEventMap",new Map),this._config=e,t&&(this._originDataChannel=t,this._bandDataChannelEvents(t)),this._initPacketHeader()}useDataStream(e){this._dataStreamPacketHandler=e}get id(){return this._config.id}get ordered(){return this._config.ordered}get maxRetransmits(){return h("DATASTREAM_MAX_RETRANSMITS")}get metadata(){return this._config.metadata}get readyState(){var e,t;return null!==(e=null===(t=this._originDataChannel)||void 0===t?void 0:t.readyState)&&void 0!==e?e:"connecting"}get _originDataChannelId(){var e,t;return null!==(e=null===(t=this._originDataChannel)||void 0===t?void 0:t.id)&&void 0!==e?e:null}getChannelId(){return this.id}getConfig(){return this._config}_close(){this._originDataChannel&&(this._unbindDataChannelEvents(this._originDataChannel),this._originDataChannel=void 0)}async _waitTillOpen(){return new Promise(((e,t)=>{if(this._originDataChannel){"open"===this._originDataChannel.readyState&&e();const i=setTimeout((()=>{var e;t(new v(E.DATACHANNEL_CONNECTION_TIMEOUT,"Cannot create datachannel, id: ".concat(null===(e=this._originDataChannel)||void 0===e?void 0:e.id)))}),1e4);this._originDataChannel.onopen=()=>{clearTimeout(i),this._originDataChannel&&this._bandDataChannelEvents(this._originDataChannel),e()},this._originDataChannel.onerror=()=>{throw clearTimeout(i),new v(E.DATACHANNEL_CONNECTION_TIMEOUT)}}else t(new v(E.DATACHANNEL_CONNECTION_TIMEOUT,"cannot find dataChannel"))}))}_updateOriginDataChannel(e){this._originDataChannel=e,this._bandDataChannelEvents(e)}_initPacketHeader(){const e=new DataView(this._dataStreamPacketHeader);e.setUint16(0,this._version),e.setUint8(2,this._type),e.setUint8(3,this._config.id)}_bandDataChannelEvents(e){this._unbindDataChannelEvents(e),[mt.OPEN,mt.CLOSE,mt.ERROR].forEach((t=>{const i=()=>{this.emit(t)};this._datachannelEventMap.set(t,i),e.addEventListener(t,i)}))}_unbindDataChannelEvents(e){Array.from(this._datachannelEventMap.entries()).forEach((t=>{let[i,r]=t;e.removeEventListener(i,r)})),this._datachannelEventMap.clear()}}class Ms extends Ns{constructor(e){super(e),_t(this,"_messageListener",void 0),this._messageListener=e=>{if(e.data.byteLength<this._dataStreamPacketHeader.byteLength)throw Error("invalid byteLength: the byte length must exceed "+this._dataStreamPacketHeader.byteLength);const t=e.data.slice(0,this._dataStreamPacketHeader.byteLength),i=new DataView(t).getUint8(3);if(i!==this.id)return void(h("SHOW_DATASTREAM2_LOG")&&le.debug("invalid datachannel id: ".concat(i," !== ").concat(this.id)));let r=e.data.slice(this._dataStreamPacketHeader.byteLength);r=this._dataStreamPacketHandler.deserialize(r),this.emit(mt.MESSAGE,r)}}_updateOriginDataChannel(e){super._updateOriginDataChannel(e),this._bandRemoteDataChannelEvents()}_close(){this._originDataChannel&&(this._originDataChannel.removeEventListener("message",this._messageListener),super._close())}_bandRemoteDataChannelEvents(){this._originDataChannel&&this._originDataChannel.addEventListener("message",this._messageListener)}}class Os extends Ns{send(e){if(this._originDataChannel){let t=e;t=this._dataStreamPacketHandler.serialize(e);const i=new Uint8Array(this._dataStreamPacketHeader.byteLength+t.byteLength);i.set(new Uint8Array(this._dataStreamPacketHeader),0),i.set(new Uint8Array(t),this._dataStreamPacketHeader.byteLength),this._originDataChannel.send(i.buffer)}}}function Ls(){const e=new Blob([atob("ZnVuY3Rpb24gdCh0LGUsbil7bGV0IGE9bmV3IFVpbnQ4QXJyYXkodCxlLG4pLG89W10scj0wO2Zvcig7by5sZW5ndGg8bjspciszPG4mJjA9PT1hW3JdJiYwPT09YVtyKzFdJiYzPT09YVtyKzJdJiYoMD09PWFbciszXXx8MT09PWFbciszXXx8Mj09PWFbciszXXx8Mz09PWFbciszXSk/KG8ucHVzaChhW3JdLGFbcisxXSxhW3IrM10pLHIrPTQpOihvLnB1c2goYVtyXSkscisrKTtyZXR1cm4gbmV3IFVpbnQ4QXJyYXkobyl9ZnVuY3Rpb24gZSh0LGUpe2NvbnN0IG49ZnVuY3Rpb24odCl7Y29uc3QgZT10Lmxlbmd0aDtsZXQgbj1bXSxhPTA7Zm9yKDthPGU7KWErMjxlJiYwPT09dFthXSYmMD09PXRbYSsxXSYmKDA9PT10W2ErMl18fDE9PT10W2ErMl18fDI9PT10W2ErMl18fDM9PT10W2ErMl0pPyhuLnB1c2godFthXSx0W2ErMV0sMyx0W2ErMl0pLGErPTMpOihuLnB1c2godFthXSksYSsrKTtyZXR1cm4gbmV3IFVpbnQ4QXJyYXkobil9KGUpLGE9bi5sZW5ndGgsbz1NYXRoLmZsb29yKGEvMjU1KSxyPWElMjU1LHM9bmV3IFVpbnQ4QXJyYXkoNitvKzErYSt0LmJ5dGVMZW5ndGgpO3NbMF09MCxzWzFdPTAsc1syXT0wLHNbM109MSxzWzRdPTYsc1s1XT0xMDE7bGV0IGk9MDtmb3IoO2k8bzspc1s2K2ldPTI1NSxpKys7cmV0dXJuIHNbNitpXT1yLGkrKyxzLnNldChuLDYraSkscy5zZXQobmV3IFVpbnQ4QXJyYXkodCksNitpK2EpLHMuYnVmZmVyfWNvbnN0IG49NzEsYT0xLG89MixyPTEscz0yO3ZhciBpOyFmdW5jdGlvbih0KXt0W3QuQVVESU9fTEVWRUw9MV09IkFVRElPX0xFVkVMIix0W3QuTUVUQURBVEE9Ml09Ik1FVEFEQVRBIix0W3QuQVVESU9fNjRfQklUX1BUUz0zXT0iQVVESU9fNjRfQklUX1BUUyJ9KGl8fChpPXt9KSk7bmF2aWdhdG9yLnVzZXJBZ2VudC5pbmRleE9mKCJTYWZhcmkiKT4tMSYmLTE9PT1uYXZpZ2F0b3IudXNlckFnZW50LmluZGV4T2YoIkNocm9tZSIpJiYoc2VsZi5vbnJ0Y3RyYW5zZm9ybT1mPT57Y29uc3QgdT1mLnRyYW5zZm9ybWVyO2xldCBkPVtdLGw9W107dS5vcHRpb25zLnBvcnQub25tZXNzYWdlPXQ9Pnt0LmRhdGEuc2VpJiZkLnB1c2godC5kYXRhLnNlaSksdC5kYXRhLm1ldGFkYXRhJiZsLnB1c2godC5kYXRhLm1ldGFkYXRhKX0sc2VsZi5wb3N0TWVzc2FnZSgic3RhcnRlZCIpO2NvbnN0IGc9dS5yZWFkYWJsZS5nZXRSZWFkZXIoKSxjPXUud3JpdGFibGUuZ2V0V3JpdGVyKCk7InNlaS1yeCI9PT11Lm9wdGlvbnMubmFtZT9mdW5jdGlvbiBlKG4pe2cucmVhZCgpLnRoZW4oKGE9PntpZighYS5kb25lKXtpZihhLnZhbHVlIGluc3RhbmNlb2YgUlRDRW5jb2RlZFZpZGVvRnJhbWUpe2NvbnN0IGU9ZnVuY3Rpb24oZSl7Y29uc3Qgbj1uZXcgRGF0YVZpZXcoZS5kYXRhKTtsZXQgYT0wO2Zvcig7YSs0PGUuZGF0YS5ieXRlTGVuZ3RoOyl7aWYoMD09PW4uZ2V0VWludDgoYSswKSYmMD09PW4uZ2V0VWludDgoYSsxKSYmMD09PW4uZ2V0VWludDgoYSsyKSYmMT09PW4uZ2V0VWludDgoYSszKSYmNj09PW4uZ2V0VWludDgoYSs0KSl7bGV0IG89YSs2LHI9MCxzPTA7Zm9yKDsyNTU9PT0ocz1uLmdldFVpbnQ4KG8rKykpOylyKz0yNTU7cis9cztjb25zdCBpPXQoZS5kYXRhLG8scik7cmV0dXJuIG5ldyBVaW50OEFycmF5KGkpfWErK31yZXR1cm4gbnVsbH0oYS52YWx1ZSk7ZSYmbi5vcHRpb25zLnBvcnQucG9zdE1lc3NhZ2Uoe3NlaTplfSl9Yy53cml0ZShhLnZhbHVlKSxuLm9wdGlvbnMucG9ydC5wb3N0TWVzc2FnZSh7dHJhbnNmb3JtZWQ6ITB9KSxlKG4pfX0pKX0odSk6InNlaS10eCI9PT11Lm9wdGlvbnMubmFtZT9mdW5jdGlvbiB0KG4pe2cucmVhZCgpLnRoZW4oKGE9PntpZighYS5kb25lKXtpZihhLnZhbHVlIGluc3RhbmNlb2YgUlRDRW5jb2RlZFZpZGVvRnJhbWUpe2NvbnN0IHQ9ZC5zaGlmdCgpO3QmJihhLnZhbHVlLmRhdGE9ZShhLnZhbHVlLmRhdGEsdCkpfWMud3JpdGUoYS52YWx1ZSksbi5vcHRpb25zLnBvcnQucG9zdE1lc3NhZ2Uoe3RyYW5zZm9ybWVkOiEwfSksdChuKX19KSl9KHUpOiJhdWRpby1tZXRhZGF0YS1yeCI9PT11Lm9wdGlvbnMubmFtZT9mdW5jdGlvbiB0KGUpe2cucmVhZCgpLnRoZW4oKGY9PntpZighZi5kb25lKXtpZihmLnZhbHVlIGluc3RhbmNlb2YgUlRDRW5jb2RlZEF1ZGlvRnJhbWUpe2NvbnN0IHQ9ZnVuY3Rpb24odCxlPSExKXtjb25zdCBmPXQuZ2V0VWludDgoMCk7aWYoZiE9PW4pcmV0dXJuO2NvbnN0IHU9dC5nZXRVaW50MTYoMSksZD1hK28rdSxsPW5ldyBVaW50OEFycmF5KHQuYnl0ZUxlbmd0aC1kKTtsLnNldChuZXcgVWludDhBcnJheSh0LmJ1ZmZlcixkLHQuYnl0ZUxlbmd0aC1kKSk7Y29uc3QgZz17bTpmLHRsdkxlbjp1LHRsdjpbXSxmcmFtZTpsfTtsZXQgYz1hK287Zm9yKDtjPGQ7KXtjb25zdCBuPXQuZ2V0VWludDgoYyksYT10LmdldFVpbnQxNihjK3IpLG89citzO2lmKG49PT1pLkFVRElPX0xFVkVMKXtsZXQgcj10LmdldFVpbnQ4KGMrbyk7Zm9yKGxldCBlPTE7ZTxhO2UrKylyPXI8PDh8dC5nZXRVaW50OChjK28rZSk7Zy50bHYucHVzaCh7dGFnOm4sbGVuZ3RoOmEsdmFsdWU6ZT8xMjdecj4+MToxMjcmcn0pfWVsc2UgaWYobj09PWkuTUVUQURBVEF8fG49PT1pLkFVRElPXzY0X0JJVF9QVFMpe2NvbnN0IGU9bmV3IFVpbnQ4QXJyYXkoYSk7Zm9yKGxldCBuPTA7bjxhO24rKyllW25dPXQuZ2V0VWludDgoYytvK24pO2cudGx2LnB1c2goe3RhZzpuLGxlbmd0aDphLHZhbHVlOmV9KX1jKz1vK2F9cmV0dXJuIGd9KG5ldyBEYXRhVmlldyhmLnZhbHVlLmRhdGEpKTtpZih0KXtjb25zdCBuPXQudGx2LmZpbmQoKHQ9PnQudGFnPT09aS5NRVRBREFUQXx8dC50YWc9PT1pLkFVRElPXzY0X0JJVF9QVFMpKTtuJiZuLnZhbHVlIGluc3RhbmNlb2YgVWludDhBcnJheSYmZS5vcHRpb25zLnBvcnQucG9zdE1lc3NhZ2Uoe21ldGFkYXRhOm4udmFsdWV9KSxmLnZhbHVlLmRhdGE9dC5mcmFtZS5idWZmZXJ9fWMud3JpdGUoZi52YWx1ZSksZS5vcHRpb25zLnBvcnQucG9zdE1lc3NhZ2Uoe3RyYW5zZm9ybWVkOiEwfSksdChlKX19KSl9KHUpOiJhdWRpby1tZXRhZGF0YS10eCI9PT11Lm9wdGlvbnMubmFtZSYmZnVuY3Rpb24gdChlKXtnLnJlYWQoKS50aGVuKChmPT57aWYoIWYuZG9uZSl7aWYoZS5vcHRpb25zLnBvcnQucG9zdE1lc3NhZ2Uoe2dldE1ldGFkYXRhOiEwfSksZi52YWx1ZSBpbnN0YW5jZW9mIFJUQ0VuY29kZWRBdWRpb0ZyYW1lKXtjb25zdCB0PWwuc2hpZnQoKTt0JiYoZi52YWx1ZS5kYXRhPWZ1bmN0aW9uKHQsZSxpKXtjb25zdCBmPWkuYnl0ZUxlbmd0aCx1PWYrcitzLGQ9YStvK3UsbD1uZXcgQXJyYXlCdWZmZXIodC5ieXRlTGVuZ3RoK2QpLGc9bmV3IERhdGFWaWV3KGwpO2cuc2V0VWludDgoMCxuKSxnLnNldFVpbnQxNigxLHUpLGcuc2V0VWludDgoMyxlKSxnLnNldFVpbnQxNig0LGYpO2ZvcihsZXQgdD0wO3Q8Zjt0KyspZy5zZXRVaW50OCg2K3QsaVt0XSk7Y29uc3QgYz1uZXcgVWludDhBcnJheShnLmJ1ZmZlcik7cmV0dXJuIGMuc2V0KG5ldyBVaW50OEFycmF5KHQpLGQpLGMuYnVmZmVyfShmLnZhbHVlLmRhdGEsaS5BVURJT182NF9CSVRfUFRTLHQpKX1jLndyaXRlKGYudmFsdWUpLGUub3B0aW9ucy5wb3J0LnBvc3RNZXNzYWdlKHt0cmFuc2Zvcm1lZDohMH0pLHQoZSl9fSkpfSh1KX0sc2VsZi5wb3N0TWVzc2FnZSgicmVnaXN0ZXJlZCIpKTsK")],{type:"text/javascript"});return setTimeout((()=>URL.revokeObjectURL(e)),0),new Worker(URL.createObjectURL(e))}const Ps=71,Vs=1,xs=2,Us=1,Bs=2;var Fs=function(e){return e[e.AUDIO_LEVEL=1]="AUDIO_LEVEL",e[e.METADATA=2]="METADATA",e[e.AUDIO_64_BIT_PTS=3]="AUDIO_64_BIT_PTS",e}(Fs||{});function Gs(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const i=e.getUint8(0);if(i!==Ps)return;const r=e.getUint16(1),s=Vs+xs+r,o=new Uint8Array(e.byteLength-s);o.set(new Uint8Array(e.buffer,s,e.byteLength-s));const n={m:i,tlvLen:r,tlv:[],frame:o};let a=Vs+xs;for(;a<s;){const i=e.getUint8(a),r=e.getUint16(a+Us),s=Us+Bs;if(i===Fs.AUDIO_LEVEL){let o=e.getUint8(a+s);for(let t=1;t<r;t++)o=o<<8|e.getUint8(a+s+t);n.tlv.push({tag:i,length:r,value:t?127^o>>1:127&o})}else if(i===Fs.METADATA||i===Fs.AUDIO_64_BIT_PTS){const t=new Uint8Array(r);for(let i=0;i<r;i++)t[i]=e.getUint8(a+s+i);n.tlv.push({tag:i,length:r,value:t})}a+=s+r}return n}const Ws=new Map;function Hs(e,t){const{chunk:i,controller:r}=t,s=h("ENABLE_AUDIO_PTS_METADATA")?Fs.AUDIO_64_BIT_PTS:Fs.METADATA;i.data=function(e,t,i){const r=i.byteLength,s=r+Us+Bs,o=Vs+xs+s,n=new ArrayBuffer(e.byteLength+o),a=new DataView(n);a.setUint8(0,Ps),a.setUint16(1,s),a.setUint8(3,t),a.setUint16(4,r);for(let e=0;e<r;e++)a.setUint8(6+e,i[e]);const c=new Uint8Array(a.buffer);return c.set(new Uint8Array(e),o),c.buffer}(i.data,s,e),r.enqueue(i)}async function Ks(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!ve().supportWebRTCEncodedTransform)return void le.warning("browser not support audio encoded transform");if(Ws.has(e))return;if(!e.track)return;const i={track:e.track};if(l()){if(!e.createEncodedStreams)return void le.warning("browser not support createEncodedStreams() API");let s=null;try{s=e.createEncodedStreams()}catch(e){return void le.error("create audio-encoded-streams error",e&&e.message)}const o=new TransformStream({transform(s,o){i.controller||(i.controller=o),e.track&&e.track.id!==i.track.id&&(le.debug("audio track changed: ".concat(i.track.id," => ").concat(e.track.id)),i.track.removeEventListener("ended",r),i.track=e.track,i.track.addEventListener("ended",r));const n=t.metadata&&t.metadata();n?Hs(n,{sender:e,chunk:s,controller:o}):o.enqueue(s)}});s.readable.pipeThrough(o).pipeTo(s.writable)}else if(c()){if("undefined"==typeof RTCRtpScriptTransform)return void le.warning("browser not support RTCRtpScriptTransform");const s=Ls(),o=new MessageChannel;await new Promise((e=>s.onmessage=t=>{"registered"===t.data&&e(void 0)}));const n=new RTCRtpScriptTransform(s,{name:"audio-metadata-tx",port:o.port2},[o.port2]);e.transform=n,await new Promise((e=>s.onmessage=t=>{"started"===t.data&&e(void 0)})),o.port1.onmessage=s=>{var n;if(s.data.transformed&&e.track&&(null===(n=e.track)||void 0===n?void 0:n.id)!==i.track.id)le.debug("audio track changed: ".concat(i.track.id," => ").concat(e.track.id)),i.track.removeEventListener("ended",r),i.track=e.track,i.track.addEventListener("ended",r);else if(s.data.getMetadata){const e=t.metadata&&t.metadata();e&&o.port1.postMessage({metadata:e})}},i.worker=s}function r(){if(e.track){if(this.id!==e.track.id)return;e.track.removeEventListener("ended",r)}const t=Ws.get(e);if(t){Ws.delete(e);try{var i,s;null===(i=t.controller)||void 0===i||i.terminate(),null===(s=t.worker)||void 0===s||s.terminate()}catch(e){le.warning(e&&e.message)}}}Ws.set(e,i),e.track.addEventListener("ended",r)}const Zs=127,Ys=1e-10,zs=139/13;const js=new Map;function Xs(e,t,i){const r="".concat(e,"-").concat(t,"-").concat(i);let s=0;if(js.has(r))s=js.get(r);else{const o=.5;s=Math.log(function(e,t){const i=e-t;t<i&&(t=i);let r=1;for(let i=e,s=1;i>t;i--,s++)r=r*i/s;return r}(t,e))+e*Math.log(o)+(t-e)*Math.log(1-o)-Math.log(i)+i*e,js.set(r,s)}return s<Ys&&(s=Ys),s}function Qs(e,t,i){const r=t.length,s=e.length/r;let o=!1;for(let n=0,a=0;n<r;n++){let r=0;for(let t=a+s;a<t;a++)e[a]>i&&r++;t[n]!==r&&(t[n]=r,o=!0)}return o}window.cache=js;let Js=0;class qs{constructor(e){_t(this,"id",void 0),_t(this,"immediates",[]),_t(this,"lastNonSilence",-1),_t(this,"immediateSpeechActivityScore",Ys),_t(this,"lastLevelChangedTime",Date.now()),_t(this,"levels",[]),_t(this,"longs",[]),_t(this,"longSpeechActivityScore",Ys),_t(this,"mediums",[]),_t(this,"mediumSpeechActivityScore",Ys),_t(this,"minLevel",0),_t(this,"nextMinLevel",0),_t(this,"nextMinLevelWindowLength",0),_t(this,"energyScore",0),this.id=e||"".concat(Js++),this.immediates.length=50,this.mediums.length=10,this.longs.length=1,this.levels.length=this.immediates.length}computeImmediates(){const e=this.immediates,t=this.levels,i=this.minLevel+zs;let r=!1;for(let s=0;s<e.length;++s){let o=t[s];o<i&&(o=0);const n=Math.floor(o/zs);e[s]!==n&&(e[s]=n,r=!0)}return r}computeLongs(){return Qs(this.mediums,this.longs,4)}computeMediums(){return Qs(this.immediates,this.mediums,7)}evaluateImmediateSpeechActivityScore(){this.immediateSpeechActivityScore=Xs(this.immediates[0],13,.78)}evaluateLongSpeechActivityScore(e){this.longSpeechActivityScore=Xs(this.longs[0],10,47),this.longSpeechActivityScore>Ys&&(this.lastNonSilence=e)}evaluateMediumSpeechActivityScore(){this.mediumSpeechActivityScore=Xs(this.mediums[0],5,24)}evaluateSpeechActivityScores(e){this.computeImmediates()&&(this.evaluateImmediateSpeechActivityScore(),this.computeMediums()&&(this.evaluateMediumSpeechActivityScore(),this.computeLongs()&&this.evaluateLongSpeechActivityScore(e)))}getLastLevelChangedTime(){return this.lastLevelChangedTime}getLevels(){return"[".concat([...this.levels].reverse().join(),"]")}getSpeechActivityScore(e){switch(e){case 0:return this.immediateSpeechActivityScore;case 1:return this.mediumSpeechActivityScore;case 2:return this.longSpeechActivityScore;default:throw new Error("interval "+e)}}levelChanged(e,t){if(this.lastLevelChangedTime<=t){this.lastLevelChangedTime=t;let i=e;return e<0&&(i=0),e>Zs&&(i=Zs),this.levels.unshift(i),this.levels.length>this.immediates.length&&this.levels.pop(),this.updateMinLevel(i),i>=this.minLevel+zs?i:i/2}return-1}levelTimedOut(){this.levelChanged(0,this.lastLevelChangedTime)}updateMinLevel(e){if(0!==e){if(0===this.minLevel||this.minLevel>e)return this.minLevel=e,this.nextMinLevel=0,void(this.nextMinLevelWindowLength=0);if(0===this.nextMinLevel)return this.nextMinLevel=e,void(this.nextMinLevelWindowLength=1);if(this.nextMinLevel>e&&(this.nextMinLevel=e),this.nextMinLevelWindowLength++,this.nextMinLevelWindowLength>=750){let e=Math.sqrt(this.minLevel*this.nextMinLevel);e<0?e=0:e>Zs&&(e=Zs),this.minLevel=e,this.nextMinLevel=0,this.nextMinLevelWindowLength=0}}}}class $s{constructor(e){_t(this,"algorithm",void 0),this.algorithm=e}execute(){let e=!this.algorithm;if(!e)try{const t=this.algorithm.runInDecisionMaker(this);t<=0?e=!0:setTimeout(this.execute.bind(this),t)}catch(t){e=!0}e&&this.algorithm&&this.algorithm.decisionMakerExited(this)}}class eo{constructor(e,t,i){_t(this,"isDominant",void 0),_t(this,"energyRanking",void 0),_t(this,"energyScore",void 0),this.isDominant=e,this.energyRanking=t,this.energyScore=i}}class to extends y{constructor(e){super(),_t(this,"dominantId",null),_t(this,"lastDecisionTime",0),_t(this,"lastLevelChangedTime",0),_t(this,"lastLevelIdleTime",0),_t(this,"relativeSpeechActivities",[]),_t(this,"speakers",new Map),_t(this,"enableSilence",!1),_t(this,"timeoutToSilenceInterval",0),_t(this,"decisionMaker",null),_t(this,"loudest",[]),_t(this,"numLoudestToTrack",3),_t(this,"energyExpireTimeMs",250),_t(this,"energyAlphaPct",50),this.timeoutToSilenceInterval=e,this.enableSilence=e>0,this.relativeSpeechActivities.length=3}setLoudestConfig(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:3,t=arguments.length>1?arguments[1]:void 0,i=arguments.length>2?arguments[2]:void 0;this.numLoudestToTrack=e,null!=t&&(this.energyExpireTimeMs=t),null!=i&&(this.energyAlphaPct=i),this.loudest.length>e&&this.loudest.splice(e)}getDominantSpeaker(){return this.dominantId}isAmongLoudest(e){return this.loudest.some((t=>t.id===e))}levelChanged(e,t){const i=Date.now(),r=this.getOrCreateSpeaker(e);this.lastLevelChangedTime<i&&(this.lastLevelChangedTime=i,this.maybeStartDecisionMaker());const s=r.levelChanged(t,i);return this.updateLoudestList(r,s,i)}runInDecisionMaker(e){if(this.decisionMaker!==e)return-1;if(this.lastDecisionTime>0){if(this.lastDecisionTime-this.lastLevelChangedTime>=15e3)return-1}return this._runInDecisionMaker()}decisionMakerExited(e){this.decisionMaker===e&&(this.decisionMaker=null)}destroy(){this.decisionMaker=null,this.loudest.length=0,this.speakers.clear(),this.removeAllListeners()}addSpeakers(e){e.forEach((e=>{this.speakers.has(e.id)||this.speakers.set(e.id,e)}))}removeSpeakers(e){e.forEach((e=>{this.speakers.delete(e.id)}))}getOrCreateSpeaker(e){let t=this.speakers.get(e);return t||(t=new qs(e),this.speakers.set(e,t),this.maybeStartDecisionMaker()),t}updateLoudestList(e,t,i){const r=e.id===this.dominantId;if(t<0){let t=0;for(;t<this.loudest.length&&this.loudest[t]!==e;)++t;return new eo(r,t,e.energyScore)}if(e.energyScore=Math.floor((this.energyAlphaPct*t+(100-this.energyAlphaPct)*e.energyScore+50)/100),0===this.numLoudestToTrack)return new eo(r,0,e.energyScore);const s=i-this.energyExpireTimeMs;let o=0;for(;o<this.loudest.length;){const t=this.loudest[o];if(t.getLastLevelChangedTime()<s&&this.loudest.length>=this.numLoudestToTrack)this.loudest.splice(o,1);else if(t.id!==e.id)++o;else if(this.loudest.splice(o,1),this.loudest.length<this.numLoudestToTrack)break}let n=0;for(;n<this.loudest.length;){if(this.loudest[n].energyScore<e.energyScore)break;++n}return n<this.numLoudestToTrack&&(this.loudest.splice(n,0,e),this.loudest.length>this.numLoudestToTrack&&this.loudest.splice(this.numLoudestToTrack,1)),new eo(r,n,e.energyScore)}maybeStartDecisionMaker(){!this.decisionMaker&&this.speakers.size>0&&(this.decisionMaker=new $s(this),this.decisionMaker.execute())}makeDecision(e){let t=null,i=null;const r=this.speakers.size;let s=null;if(0===r)s=null;else if(1===r){const t=this.speakers.values().next().value;if(this.enableSilence&&t){s=t.id,t.evaluateSpeechActivityScores(e);e-t.lastNonSilence>this.timeoutToSilenceInterval&&(s=null)}}else{let t=null==this.dominantId?null:this.speakers.get(this.dominantId);if(null==t){const e=this.speakers.entries().next();e.value&&(s=e.value[0],t=e.value[1])}else s=t.id;null!=t&&t.evaluateSpeechActivityScores(e);const i=this.relativeSpeechActivities;let r=2;for(const o of this.speakers.entries()){const[n,a]=o;if(a===t)continue;a.evaluateSpeechActivityScores(e);for(let e=0;e<i.length;++e){const r=null==t?Ys:t.getSpeechActivityScore(e);i[e]=Math.log(a.getSpeechActivityScore(e)/r)}const c=i[0],d=i[1],h=i[2];c>3&&d>2&&h>0&&d>r&&(r=d,s=n)}if(this.enableSilence&&null!=t&&s===t.id){e-t.lastNonSilence>this.timeoutToSilenceInterval&&(s=null)}}null==s&&!this.enableSilence||s===this.dominantId||(t=this.dominantId,this.dominantId=s,i=this.dominantId),null==i&&!this.enableSilence||i===t||this.emit("ActiveSpeakerChanged",i)}_runInDecisionMaker(){const e=Date.now(),t=300-(e-this.lastLevelIdleTime);let i=0;t<=0?(0!==this.lastLevelIdleTime&&this.timeoutIdleLevels(e),this.lastLevelIdleTime=e):i=t;let r=300-(e-this.lastDecisionTime);return r<=0&&(this.lastDecisionTime=e,this.makeDecision(e),r=300-(Date.now()-e)),r>0&&i>r&&(i=r),i}timeoutIdleLevels(e){const t=[];for(const i of this.speakers.values()){const r=e-i.getLastLevelChangedTime();36e5<r&&(null==this.dominantId||i.id!==this.dominantId)?t.push(i.id):300<r&&i.levelTimedOut()}t.forEach((e=>this.speakers.delete(e)))}}const io=new Map;let ro=null,so=null;const oo=3;let no=[];function ao(e,t){let i=io.get(e);if(i||(i=function(e){const t=new qs;return io.set(e,t),ro||(ro=new to(h("TOPN_SILENCE_THRESHOLD")||500),ro.on("ActiveSpeakerChanged",(e=>{null!=e&&(so=e)}))),ro.addSpeakers([t]),t}(e)),io.size<=oo)return{selected:!0,speaker:i};if(!ro)throw new Error("no active speaker detector");ro.levelChanged(i.id,t),no=ro.loudest.map((e=>e.id)),so&&!no.includes(so)&&no.length>=oo&&no.pop();return{selected:no.includes(i.id)||i.id===so,speaker:i}}const co=1e3,ho=40,uo=new Map,lo=new Map;class po{get samples(){return this.actives+this.inactives}get activeRate(){return this.actives/this.samples}constructor(e,t){_t(this,"id",void 0),_t(this,"track",void 0),_t(this,"score",0),_t(this,"active",!0),_t(this,"muted",!1),_t(this,"timer",0),_t(this,"actives",0),_t(this,"inactives",0),this.id=e,this.track=t,this.setActive(uo.size<3)}autoCheckActive(){this.autoSetActive(),this.autoAdjustActive(),this.resetTimer(),this.actives=0,this.inactives=0}autoSetActive(){const e=this.active;this.active=this.activeRate>=.8;const{actives:t,inactives:i}=function(){const e=[],t=[];return Array.from(uo.values()).forEach((i=>{i.active?e.push(i):t.push(i)})),{actives:e,inactives:t}}();if(t.length>3){let e;t.forEach((t=>{(!e||e.score>t.score)&&(e=t)})),e&&e.setActive(!1)}if(t.length<3&&i.length>0){let t;i.forEach((e=>{(!t||t.score<e.score)&&e.id!==this.id&&(t=e)})),t&&e&&!this.active&&(t.samples>ho&&t.activeRate-this.activeRate>.4?t.setActive(!0):this.active=!0)}this.setMuted(!this.active)}setActive(e){this.active=e,this.resetTimer(),this.setMuted(!e)}autoAdjustActive(){this.active?this.autoSwitchToInactive():this.autoSwitchToActive()}autoSwitchToActive(){const e=function(e){let t;return Array.from(uo.values()).forEach((i=>{!i.active||i.id===e||i.samples<ho||(!t||i.score<t.score)&&(t=i)})),t}(this.id);e&&this.activeRate-e.activeRate>.4&&(e.setActive(!1),this.setActive(!0))}autoSwitchToInactive(){const e=function(e){let t;return Array.from(uo.values()).forEach((i=>{i.active||i.id===e||i.samples<ho||(!t||i.score>t.score)&&(t=i)})),t}(this.id);e&&e.activeRate-this.activeRate>.4&&(e.setActive(!0),this.setActive(!1))}addSample(e){e?this.actives+=1:this.inactives+=1,this.samples>66.66666666666667&&this.autoCheckActive()}setMuted(e){this.track&&(this.track.enabled=!e,this.muted=e)}resetTimer(){this.clearTimer(),this.timer=window.setTimeout((()=>{if(0!==this.samples)return this.samples<50?this.resetTimer():void this.autoCheckActive()}),co)}clearTimer(){this.timer&&(clearTimeout(this.timer),this.timer=0)}}let mo;function go(e,t,i){const r=uo.get(e)||new po(e,t);return r.score=i,uo.set(e,r),function(e){if(lo.set(e,!0),!mo)return void(mo=Date.now());const t=Date.now();t-mo>1e3&&(lo.get(e)?lo.set(e,!1):(_o(e),lo.delete(e)),mo=t)}(e),r}function _o(e){const t=uo.get(e);t&&(uo.delete(e),t.clearTimer())}const fo=new Map,To=new Map;async function vo(e){let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!ve().supportWebRTCEncodedTransform)return void le.warning("browser not support audio encoded transform");if(fo.has(e))return;const r={track:e.track,onMetadata:i.onMetadata};if(l()){if(!e.createEncodedStreams)return void le.warning("browser not support createEncodedStreams() API");ne(t.CHROME,87,116)||(i.enableTopn=!1);let o=null;try{o=e.createEncodedStreams()}catch(e){return void le.error("create audio-encoded-streams error",e&&e.message)}const n=new TransformStream({transform(t,o){r.controller||(r.controller=o),e.track&&e.track.id!==r.track.id&&(le.debug("audio track changed: ".concat(r.track.id," => ").concat(e.track.id)),r.track.removeEventListener("ended",s),r.track=e.track,r.track.addEventListener("ended",s)),i.enableTopn?function(e,t,i){var r;const s=Gs(new DataView(t.data));if(!s)return i.enqueue(t);const o=e.track.id;To.set(o,e.track);const n=null===(r=s.tlv.find((e=>e.tag===Fs.AUDIO_LEVEL)))||void 0===r?void 0:r.value;let a=0;"number"==typeof n&&(a=127-n);const c=Math.round(Math.pow(10,a/60)-1),{selected:d,speaker:h}=ao(e,c),u=go(o,e.track,h.energyScore);u.addSample(d),u.active&&(t.data=s.frame.buffer,i.enqueue(t))}(e,t,o):i.enableMetadata?function(e,t,i){const r=Gs(new DataView(e.data));if(!r)return t.enqueue(e);const s=r.tlv.find((e=>e.tag===Fs.METADATA||e.tag===Fs.AUDIO_64_BIT_PTS));s&&i&&s.value instanceof Uint8Array&&i(s.value),e.data=r.frame.buffer,t.enqueue(e)}(t,o,i.onMetadata):o.enqueue(t)}});o.readable.pipeThrough(n).pipeTo(o.writable)}else if(c()){if("undefined"==typeof RTCRtpScriptTransform)return void le.warning("browser not support RTCRtpScriptTransform");const t=Ls(),i=new MessageChannel;await new Promise((e=>t.onmessage=t=>{"registered"===t.data&&e(void 0)}));const o=new RTCRtpScriptTransform(t,{name:"audio-metadata-rx",port:i.port2},[i.port2]);e.transform=o,await new Promise((e=>t.onmessage=t=>{"started"===t.data&&e(void 0)})),i.port1.onmessage=t=>{var i;t.data.transformed&&e.track&&(null===(i=e.track)||void 0===i?void 0:i.id)!==r.track.id?(le.debug("audio track changed: ".concat(r.track.id," => ").concat(e.track.id)),r.track.removeEventListener("ended",s),r.track=e.track,r.track.addEventListener("ended",s)):t.data.metadata&&r.onMetadata&&r.onMetadata(t.data.metadata)},r.worker=t}function s(){e.track.removeEventListener("ended",s),function(e){const t=fo.get(e);if(t){!function(e){const t=io.get(e);t&&(io.delete(e),ro&&(ro.removeSpeakers([t]),0===io.size&&(ro.destroy(),ro=null)))}(e),_o(e.track.id),fo.delete(e);try{var i,r;null===(i=t.controller)||void 0===i||i.terminate(),null===(r=t.worker)||void 0===r||r.terminate()}catch(e){le.warning(e&&e.message)}}}(e)}fo.set(e,r),e.track.addEventListener("ended",s)}function Eo(e,t,i){let r=new Uint8Array(e,t,i),s=[],o=0;for(;s.length<i;)o+3<i&&0===r[o]&&0===r[o+1]&&3===r[o+2]&&(0===r[o+3]||1===r[o+3]||2===r[o+3]||3===r[o+3])?(s.push(r[o],r[o+1],r[o+3]),o+=4):(s.push(r[o]),o++);return new Uint8Array(s)}function So(e,t){const i=function(e){const t=e.length;let i=[],r=0;for(;r<t;)r+2<t&&0===e[r]&&0===e[r+1]&&(0===e[r+2]||1===e[r+2]||2===e[r+2]||3===e[r+2])?(i.push(e[r],e[r+1],3,e[r+2]),r+=3):(i.push(e[r]),r++);return new Uint8Array(i)}(t),r=i.length,s=Math.floor(r/255),o=r%255,n=new Uint8Array(6+s+1+r+e.byteLength);n[0]=0,n[1]=0,n[2]=0,n[3]=1,n[4]=6,n[5]=101;let a=0;for(;a<s;)n[6+a]=255,a++;return n[6+a]=o,a++,n.set(i,6+a),n.set(new Uint8Array(e),6+a+r),n.buffer}const yo=new Map;async function ko(e,t){if(!ve().supportWebRTCEncodedTransform)return void le.warning("browser not support video encoded transform");if(yo.has(e))return;if(!e.track)return;const i={track:e.track};if(l()){if(!e.createEncodedStreams)return void le.warning("browser not support createEncodedStreams() API");let s=null;try{s=e.createEncodedStreams()}catch(e){return void le.error("create video-encoded-streams error",e&&e.message)}const o=[];t.on("sei-to-send",(e=>{o.push(e)}));const n=new TransformStream({transform(t,s){i.controller||(i.controller=s),e.track&&e.track.id!==i.track.id&&(le.debug("video track changed: ".concat(i.track.id," => ").concat(e.track.id)),i.track.removeEventListener("ended",r),i.track=e.track,i.track.addEventListener("ended",r));const n=o.shift();n&&(t.data=So(t.data,n)),s.enqueue(t)}});s.readable.pipeThrough(n).pipeTo(s.writable)}else{if(!c())return;{if("undefined"==typeof RTCRtpScriptTransform)return void le.warning("browser not support RTCRtpScriptTransform");const s=Ls(),o=new MessageChannel;await new Promise((e=>s.onmessage=t=>{"registered"===t.data&&e(void 0)}));const n=new RTCRtpScriptTransform(s,{name:"sei-tx",port:o.port2},[o.port2]);e.transform=n,await new Promise((e=>s.onmessage=t=>{"started"===t.data&&e(void 0)})),t.on("sei-to-send",(e=>{o.port1.postMessage({sei:e})})),o.port1.onmessage=t=>{var s;t.data.transformed&&e.track&&(null===(s=e.track)||void 0===s?void 0:s.id)!==i.track.id&&(le.debug("video track changed: ".concat(i.track.id," => ").concat(e.track.id)),i.track.removeEventListener("ended",r),i.track=e.track,i.track.addEventListener("ended",r))},i.worker=s}}function r(){if(e.track){if(this.id!==e.track.id)return;e.track.removeEventListener("ended",r)}const t=yo.get(e);if(t){yo.delete(e);try{var i,s;null===(i=t.controller)||void 0===i||i.terminate(),null===(s=t.worker)||void 0===s||s.terminate()}catch(e){le.warning(e&&e.message)}}}yo.set(e,i),e.track.addEventListener("ended",r)}const bo=new Map;async function Io(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!ve().supportWebRTCEncodedTransform)return void le.warning("browser not support video encoded transform");if(!e.track)return;if(bo.has(e)){const i=bo.get(e);return void(i&&(i.onSei=t.onSei))}const i={track:e.track,onSei:t.onSei};if(l()){if(!e.createEncodedStreams)return void le.warning("browser not support createEncodedStreams() API");let t=null;try{t=e.createEncodedStreams()}catch(e){return void le.error("create video-encoded-streams error",e&&e.message)}const s=new TransformStream({transform(t,s){i.controller||(i.controller=s),e.track&&e.track.id!==i.track.id&&(le.debug("video track changed: ".concat(i.track.id," => ").concat(e.track.id)),i.track.removeEventListener("ended",r),i.track=e.track,i.track.addEventListener("ended",r));const o=function(e){const t=new DataView(e.data);let i=0;for(;i+4<e.data.byteLength;){if(0===t.getUint8(i+0)&&0===t.getUint8(i+1)&&0===t.getUint8(i+2)&&1===t.getUint8(i+3)&&6===t.getUint8(i+4)){let r=i+6,s=0,o=0;for(;255===(o=t.getUint8(r++));)s+=255;s+=o;const n=Eo(e.data,r,s);return new Uint8Array(n)}i++}return null}(t);o&&i.onSei&&i.onSei(o),s.enqueue(t)}});t.readable.pipeThrough(s).pipeTo(t.writable)}else if(c()){if("undefined"==typeof RTCRtpScriptTransform)return void le.warning("browser not support RTCRtpScriptTransform");const t=Ls(),s=new MessageChannel;await new Promise((e=>t.onmessage=t=>{"registered"===t.data&&e(void 0)}));const o=new RTCRtpScriptTransform(t,{name:"sei-rx",port:s.port2},[s.port2]);e.transform=o,await new Promise((e=>t.onmessage=t=>{"started"===t.data&&e(void 0)})),s.port1.onmessage=t=>{var s;t.data.transformed&&e.track&&(null===(s=e.track)||void 0===s?void 0:s.id)!==i.track.id?(le.debug("video track changed: ".concat(i.track.id," => ").concat(e.track.id)),i.track.removeEventListener("ended",r),i.track=e.track,i.track.addEventListener("ended",r)):t.data.sei&&i.onSei&&i.onSei(t.data.sei)},i.worker=t}function r(){if(e.track){if(this.id!==e.track.id)return;e.track.removeEventListener("ended",r)}!function(e){const t=bo.get(e);if(t){bo.delete(e);try{var i,r;null===(i=t.controller)||void 0===i||i.terminate(),null===(r=t.worker)||void 0===r||r.terminate()}catch(e){le.warning(e&&e.message)}}}(e)}bo.set(e,i),e.track.addEventListener("ended",r)}Te();export{ye as AUDIO_CONTEXT_EVENT,Oe as AUDIO_ENCODER_CONFIG_SETTINGS,et as AUDIO_TRACK_EVENT,ni as AudioProcessorContext,oi as AudioProcessorDestination,$e as AudioSourceEvents,lr as BufferSourceAudioTrack,os as CameraVideoTrack,tt as DEFAULT_LOCAL_AUDIO_TRACK_STATS,it as DEFAULT_LOCAL_VIDEO_TRACK_STATS,st as DEFAULT_NETWORK_QUALITY_STATS,rt as DEFAULT_REMOTE_AUDIO_TRACK_STATS,ot as DEFAULT_REMOTE_VIDEO_TRACK_STATS,Ns as DataChannel,mt as DataChannelEvents,jt as DeviceManager,dt as DeviceManagerEvent,ct as DeviceManagerState,Wt as HAS_GUM_AUDIO,Ht as HAS_GUM_VIDEO,hr as LocalAudioTrack,Os as LocalDataChannel,Et as LocalTrack,Qe as LocalTrackEvents,ss as LocalVideoTrack,pt as MediaElementNumStatus,ut as MediaElementStatus,ur as MicrophoneAudioTrack,pr as MixingAudioTrack,at as PROCESSOR_CONTEXT_EVENTS,nt as PROCESSOR_DESTINATION_EVENTS,Ds as RemoteAudioTrack,Ms as RemoteDataChannel,je as RemoteStreamFallbackType,ze as RemoteStreamType,Rs as RemoteTrack,Je as RemoteTrackEvents,ws as RemoteVideoTrack,Gt as SAFARI_GLOBAL_GUM_LOCK,we as SUPPORT_SCREEN_ENCODER_CONFIG_LIST,De as SUPPORT_SVC_CONFIG_LIST,Re as SUPPORT_VIDEO_ENCODER_CONFIG_LIST,Ye as StreamType,vt as Track,Xe as TrackEvents,Ke as TrackHint,He as TrackInternalEvent,qe as TrackMediaType,si as VideoProcessorContext,ri as VideoProcessorDestination,lt as VideoState,Pe as __TRACK_LIST__,Ve as addTrack,kt as audioContextState,ti as audioElementPlayCenter,Ct as audioTimerLoop,Jt as autoPlayGestureEventEmitter,yi as blob2Uint8Array,di as checkMediaStreamTrackResolution,ii as checkTrackState,cs as createBufferSourceAudioTrack,us as createCameraVideoTrack,ns as createCustomAudioTrack,hs as createCustomVideoTrack,ls as createMicrophoneAndCameraTracks,as as createMicrophoneAudioTrack,ds as createMixingAudioTrack,ps as createScreenVideoTrack,wt as decodeAudioData,Ee as detectSupportAudioElementSetSinkId,Xt as deviceManager,Si as emptyImage2TypedArray,Ei as frameData2CryptoBuffer,It as getAudioContext,Le as getAudioEncoderConfiguration,fi as getBitrateConstrainRange,Ti as getBitrateFromResAndFps,ve as getCompatibility,li as getConstraintsFromAudioConfig,hi as getConstraintsFromCameraConfig,mi as getConstraintsFromMicrophoneConfig,pi as getConstraintsFromScreenAudioConfig,ui as getConstraintsFromScreenConfig,Ft as getElectronScreenSources,Ut as getElectronScreenStream,Bt as getElectronScreenStreamByUserSelect,Kt as getLocalStream,_i as getNewNearestVideoProfile,gi as getNewVideoBitrate,vi as getOriginSenderConfig,Me as getScalabilityConfiguration,Ne as getScreenEncoderConfiguration,Mt as getSilenceAudioTrack,Lt as getSilenceSamplesDuration,ki as getStaticTrackStream,Ce as getVideoEncoderConfiguration,Yt as handleGetUserMediaError,At as hasAudioContext,Ks as interceptLocalAudioFrame,ko as interceptLocalVideoFrame,vo as interceptRemoteAudioFrame,Io as interceptRemoteVideoFrame,Be as isAudioEncoderConfiguration,Ge as isAudioEncoderConfigurationOrPreset,ht as isBeautyEffectOptions,Ze as isLowStreamParameter,Se as isPlanB,We as isScreenSourceType,Ue as isVideoEncoderConfiguration,Fe as isVideoEncoderConfigurationOrPreset,Rt as polyfillAudioNode,xe as removeTrack,qt as requestAutoplayGesture,Ot as silenceScriptProcessHandler,Te as updateAgoraRTCCompatibility,Cs as visibilityWatcher};
|