@agora-js/media 4.24.8-100 → 4.24.8-200

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  /**
2
- * AgoraWebSDK_N-v4.24.8-100-0-g87ff3f8ed Copyright AgoraInc.
2
+ * AgoraWebSDK_N-v4.24.8-200-0-g84b8c732e 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,isAboveSafari15_4 as l,isChrome as p,isEdge as m,isMobile as g,isBelowChrome as _,isAboveEdge as T,isAboveOpera as f,checkValidConstrainLong as E,checkValidNumber as v,checkValidBoolean as y,checkValidEnum as S,AgoraRTCError as b,AgoraRTCErrorCode as k,isEmpty as I,EventEmitter as A,getRandomString as R,runOnce as w,AgoraAPIName as C,AgoraAPITag as M,PromiseMutex as D,emitAsPromiseNoResponse as N,removeItemFromList as O,isIOS as P,isIpadOS as L,wait as V,isQuark as x,showElectronSelectSourceWindow as U,getElectronInstance as Z,isElectron as W,recursiveMerge as G,isAndroid as B,isHarmonyOS as F,detectSecureContext as K,isAndroidChromium as H,domLoadedPromise as X,isIOS15 as Y,emitAsPromise as z,noop as j,isLegacyChrome as J,constrainLongToNumber as Q,hexToBytes as q,md5 as $,atom as ee,emitAsInvokerNoResponse as te,isIOS16 as ie,retryable as re,isInPage as se,sumArray as oe,getOSWithVersion as ne,isAboveIOS15_1 as ae,jsonClone as ce,isBetweenBrowser as de,isWindows as ue,elementVisibleChecker as he,safeCloneJson as le,isAboveIOS15_2 as pe,isWechatBrowser as me}from"@agora-js/shared";export{isElectron}from"@agora-js/shared";import{logger as ge,report as _e,AgoraRTCEventUploadType as Te,apiInvoke as fe}from"@agora-js/report";import Ee from"axios";const ve={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,supportSuppressLocalAudioPlayback:!1,supportRestrictOwnAudio:!1};function ye(){const p=e();ve.getDisplayMedia=function(e){if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)return!0;return!1}(),ve.getStreamFromExtension=p.name===t.CHROME&&Number(p.version)>34,ve.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}(),ve.supportMinBitrate=p.name===t.CHROME||p.name===t.EDGE,ve.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)}(),p.name===t.SAFARI&&(Number(p.version)>=14?ve.supportDualStream=!0:ve.supportDualStream=!1),ve.webAudioMediaStreamDest=function(){const i=e();if(i.name===t.SAFARI&&Number(i.version)<12)return!1;return!0}(),ve.supportReplaceTrack=function(){if(!window.RTCRtpSender)return!1;if("function"==typeof RTCRtpSender.prototype.replaceTrack)return!0;return!1}(),ve.supportWebGL="undefined"!=typeof WebGLRenderingContext,ve.supportRequestFrame=!!window.CanvasCaptureMediaStreamTrack,i()||(ve.webAudioWithAEC=!0),ve.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}(),ve.supportDataChannel=function(){if(s(76)||o(68)||n(14))return!0;return!1}(),ve.supportPCSetConfiguration=function(){const e=window.RTCPeerConnection;return!h()&&!!e&&e.prototype.setConfiguration instanceof Function}(),ve.supportWebRTCEncodedTransform=s(87)||l()||o(117),ve.supportWebRTCInsertableStream=function(){const i=e();return(i.name===t.CHROME||i.name===t.EDGE)&&Number(i.version)>=94&&"MediaStreamTrackGenerator"in window&&"MediaStreamTrackProcessor"in window}(),ve.supportRequestVideoFrameCallback=function(){if("requestVideoFrameCallback"in HTMLVideoElement.prototype)return!0;return!1}(),ve.supportWebCrypto="undefined"!=typeof window&&void 0!==window.crypto&&void 0!==window.crypto.subtle,ve.supportSuppressLocalAudioPlayback=Ne(),ve.supportRestrictOwnAudio=Oe(),r((()=>{ve.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"))}(),ge.debug("browser ua: ",navigator.userAgent),ge.info("browser info: ",p),ge.info("browser compatibility: ",ve)}))}function Se(){return ve}function be(){return"setSinkId"in HTMLAudioElement.prototype&&(!u("RESTRICTION_SET_PLAYBACK_DEVICE")||(p()||m())&&!g())}function ke(){return!ve.supportUnifiedPlan||u("CHROME_FORCE_PLAN_B")&&i()}function Ie(){return u("ENABLE_JOIN_V4")}function Ae(e){return!(h()||_(87)||ke())&&(!!u("ENABLE_PRE_SUB")||!(null==e||!e.autoSubscribe||u("FORCE_DISABLE_AUTO_SUB")))}function Re(e){return!ke()&&!u("USE_NEW_TOKEN")&&(!!u("ENABLE_PREALLOC_PC")||!(null==e||!e.autoSubscribe||u("FORCE_DISABLE_AUTO_SUB")))}function we(e){return u("ENABLE_INSTANT_VIDEO")?u("ENABLE_INSTANT_VIDEO"):!(null==e||!e.autoSubscribe||u("FORCE_DISABLE_AUTO_SUB"))}function Ce(){return!!u("FORCE_ENABLE_AUT_CC")||!ke()&&(!!u("ENABLE_AUT_CC")||void 0)}function Me(){return!!u("FORCE_ENABLE_AUT_CC")||!ke()&&(!!u("ENABLE_AUT_FEEDBACK")||void 0)}function De(){return navigator.mediaDevices&&"getSupportedConstraints"in navigator.mediaDevices}function Ne(){if(De()){const e=navigator.mediaDevices.getSupportedConstraints();return!(!("suppressLocalAudioPlayback"in e)||!e.suppressLocalAudioPlayback)}return s(141)||T(141)||f(141)}function Oe(){if(De()){const e=navigator.mediaDevices.getSupportedConstraints();return!(!("restrictOwnAudio"in e)||!e.restrictOwnAudio)}return s(141)||T(141)||f(125)}let Pe=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 Le(e,t,i){return{sampleRate:e,stereo:t,bitrate:i}}function Ve(e,t,i,r,s){return{width:e,height:t,frameRate:i,bitrateMin:r,bitrateMax:s}}function xe(e,t,i,r,s){return{width:{max:e},height:{max:t},frameRate:i,bitrateMin:r,bitrateMax:s}}function Ue(e,t){return{numSpatialLayers:e,numTemporalLayers:t}}const Ze={"90p":Ve(160,90),"90p_1":Ve(160,90),"120p":Ve(160,120,15,30,65),"120p_1":Ve(160,120,15,30,65),"120p_3":Ve(120,120,15,30,50),"120p_4":Ve(212,120),"180p":Ve(320,180,15,30,140),"180p_1":Ve(320,180,15,30,140),"180p_3":Ve(180,180,15,30,100),"180p_4":Ve(240,180,15,30,120),"240p":Ve(320,240,15,40,200),"240p_1":Ve(320,240,15,40,200),"240p_3":Ve(240,240,15,40,140),"240p_4":Ve(424,240,15,40,220),"360p":Ve(640,360,15,80,400),"360p_1":Ve(640,360,15,80,400),"360p_3":Ve(360,360,15,80,260),"360p_4":Ve(640,360,30,80,600),"360p_6":Ve(360,360,30,80,400),"360p_7":Ve(480,360,15,80,320),"360p_8":Ve(480,360,30,80,490),"360p_9":Ve(640,360,15,80,800),"360p_10":Ve(640,360,24,80,800),"360p_11":Ve(640,360,24,80,1e3),"480p":Ve(640,480,15,100,500),"480p_1":Ve(640,480,15,100,500),"480p_2":Ve(640,480,30,100,1e3),"480p_3":Ve(480,480,15,100,400),"480p_4":Ve(640,480,30,100,750),"480p_6":Ve(480,480,30,100,600),"480p_8":Ve(848,480,15,100,610),"480p_9":Ve(848,480,30,100,930),"480p_10":Ve(640,480,10,100,400),"720p":Ve(1280,720,15,120,1130),"720p_auto":Ve(1280,720,30,900,3e3),"720p_1":Ve(1280,720,15,120,1130),"720p_2":Ve(1280,720,30,120,2e3),"720p_3":Ve(1280,720,30,120,1710),"720p_5":Ve(960,720,15,120,910),"720p_6":Ve(960,720,30,120,1380),"1080p":Ve(1920,1080,15,120,2080),"1080p_1":Ve(1920,1080,15,120,2080),"1080p_2":Ve(1920,1080,30,120,3e3),"1080p_3":Ve(1920,1080,30,120,3150),"1080p_5":Ve(1920,1080,60,120,4780),"1440p":Ve(2560,1440,30,120,4850),"1440p_1":Ve(2560,1440,30,120,4850),"1440p_2":Ve(2560,1440,60,120,7350),"4k":Ve(3840,2160,30,120,8910),"4k_1":Ve(3840,2160,30,120,8910),"4k_3":Ve(3840,2160,60,120,13500)},We={"480p":xe(640,480,5),"480p_1":xe(640,480,5),"480p_2":xe(640,480,30),"480p_3":xe(640,480,15),"720p":xe(1280,720,5),"720p_auto":Ve(1280,720,30,900,3e3),"720p_1":xe(1280,720,5),"720p_2":xe(1280,720,30),"720p_3":xe(1280,720,15),"1080p":xe(1920,1080,5),"1080p_1":xe(1920,1080,5),"1080p_2":xe(1920,1080,30),"1080p_3":xe(1920,1080,15)},Ge={"1SL1TL":Ue(1,1),"3SL3TL":Ue(3,3),"2SL3TL":Ue(2,3)};function Be(e){return e||(e="480p_1"),"string"==typeof e?Object.assign({},Ze[e]):e}function Fe(e){return"string"==typeof e?Object.assign({},We[e]):e}function Ke(e){return"string"==typeof e?Object.assign({},Ge[e]):e}const He={speech_low_quality:Le(16e3,!1),speech_standard:Le(32e3,!1,18),music_standard:Le(48e3,!1),standard_stereo:Le(48e3,!0,56),high_quality:Le(48e3,!1,128),high_quality_stereo:Le(48e3,!0,192)};function Xe(e){return"string"==typeof e?Object.assign({},He[e]):e}const Ye=[];function ze(e){Ye.includes(e)||Ye.push(e)}function je(e){const t=Ye.indexOf(e);-1!==t&&Ye.splice(t,1)}function Je(){return Ye.some((e=>function(e){return"__className__"in e&&"MicrophoneAudioTrack"===e.__className__}(e)))}function Qe(e){return E(e.width,"config.width"),E(e.height,"config.height"),void 0!==e.frameRate&&E(e.frameRate,"config.frameRate"),void 0!==e.bitrateMax&&v(e.bitrateMax,"config.bitrateMax"),void 0!==e.bitrateMin&&v(e.bitrateMin,"config.bitrateMin"),void 0!==e.minDownscaleWidth&&v(e.minDownscaleWidth,"config.minDownscaleWidth",1,1/0,!0),void 0!==e.minDownscaleHeight&&v(e.minDownscaleHeight,"config.minDownscaleHeight",1,1/0,!0),!0}function qe(e){return void 0!==e.sampleRate&&v(e.sampleRate,"config.sampleRate",0,96e3,!0),void 0!==e.sampleSize&&v(e.sampleRate,"config.sampleSize",0,128,!0),void 0!==e.stereo&&y(e.stereo,"config.stereo"),void 0!==e.bitrate&&v(e.bitrate,"config.bitrate",0,1e4,!1),!0}function $e(e){return"string"==typeof e?S(e,"profile",Object.keys(Ze)):Qe(e),!0}function et(e){return"string"==typeof e?S(e,"profile",Object.keys(He)):qe(e),!0}function tt(e){return S(e,"mediaSource",["screen","window","application"]),!0}let it=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}({}),rt=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 st(e){if(!e)throw new b(k.INVALID_PARAMS);return I(e.width)||E(e.width,"streamParameter.width"),I(e.height)||E(e.height,"streamParameter.height"),I(e.framerate)||E(e.framerate,"streamParameter.framerate"),I(e.bitrate)||v(e.bitrate,"streamParameter.bitrate"),!0}let ot=function(e){return e[e.HIGH_STREAM=0]="HIGH_STREAM",e[e.LOW_STREAM=1]="LOW_STREAM",e}({}),nt=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}({}),at=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}({}),ct=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}({}),dt=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}({}),ut=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.PLAY_START="play-start",e.PLAY_END="play-end",e.FIRST_FRAME_RENDER="first-frame-render",e}({}),ht=function(e){return e.AUDIO="audio",e.VIDEO="video",e.DATA="data",e}({}),lt=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}({}),pt=function(e){return e.UPDATE_TRACK_SOURCE="update-track-source",e}({});const mt={sendVolumeLevel:0,sendBitrate:0,sendBytes:0,sendPackets:0,sendPacketsLost:0,sendJitterMs:0,sendRttMs:0,currentPacketLossRate:0},gt={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},_t={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},Tt={uplinkNetworkQuality:0,downlinkNetworkQuality:0},ft={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 Et=function(e){return e.ON_TRACK="on_track",e.ON_NODE="on_node",e}({}),vt=function(e){return e.REQUEST_UPDATE_CONSTRAINTS="request_update_constraints",e.REQUEST_CONSTRAINTS="request_constraints",e}({}),yt=function(e){return e.IDLE="IDLE",e.INITING="INITING",e.INITEND="INITEND",e}({}),St=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 bt(e){return void 0!==e.smoothnessLevel&&v(e.smoothnessLevel,"options.smoothnessLevel",0,1,!1),void 0!==e.lighteningLevel&&v(e.lighteningLevel,"options.lighteningLevel",0,1,!1),void 0!==e.rednessLevel&&v(e.rednessLevel,"options.rednessLevel",0,1,!1),void 0!==e.lighteningContrastLevel&&S(e.lighteningContrastLevel,"options.lighteningContrastLevel",[0,1,2]),!0}let kt=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}({}),It=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 At={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 Rt=function(e){return e.OPEN="open",e.MESSAGE="message",e.CLOSE="close",e.CLOSING="closing",e.ERROR="error",e}({});function wt(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 Ct(e,t){(null==t||t>e.length)&&(t=e.length);for(var i=0,r=Array(t);i<t;i++)r[i]=e[i];return r}function Mt(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 Dt(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 Nt(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Dt(Object(i),!0).forEach((function(t){Mt(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Dt(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function Ot(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var i=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=i){var r,s,o,n,a=[],c=!0,d=!1;try{if(o=(i=i.call(e)).next,0===t){if(Object(i)!==i)return;c=!1}else for(;!(c=(r=o.call(i)).done)&&(a.push(r.value),a.length!==t);c=!0);}catch(e){d=!0,s=e}finally{try{if(!c&&null!=i.return&&(n=i.return(),Object(n)!==n))return}finally{if(d)throw s}}return a}}(e,t)||function(e,t){if(e){if("string"==typeof e)return Ct(e,t);var i={}.toString.call(e).slice(8,-1);return"Object"===i&&e.constructor&&(i=e.constructor.name),"Map"===i||"Set"===i?Array.from(e):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?Ct(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}class Pt extends A{set _mediaStreamTrack(e){e!==this.mediaStreamTrack&&(this.safeEmit(ct.TRACK_UPDATED,e),this.mediaStreamTrack=e)}get _mediaStreamTrack(){return this.mediaStreamTrack}constructor(e,t){super(),Mt(this,"trackMediaType",void 0),Mt(this,"_ID",void 0),Mt(this,"_rtpTransceiver",void 0),Mt(this,"_lowRtpTransceiver",void 0),Mt(this,"_hints",[]),Mt(this,"_isClosed",!1),Mt(this,"_originMediaStreamTrack",void 0),Mt(this,"mediaStreamTrack",void 0),Mt(this,"_external",{}),this._ID=t||R(8,"track-"),this._originMediaStreamTrack=e,this.mediaStreamTrack=e,ze(this)}toString(){return this._ID}getTrackId(){return this._ID}getMediaStreamTrack(e){return e||w((()=>{var e;_e.reportApiInvoke(null,{name:C.GET_MEDIA_STREAM_TRACK,options:[],tag:M.TRACER}).onSuccess((null===(e=this._mediaStreamTrack)||void 0===e?void 0:e.label)||"")}),this.mediaStreamTrack.id||this.getTrackId()),this._mediaStreamTrack}getRTCRtpTransceiver(e){return e===ot.LOW_STREAM?this._lowRtpTransceiver:this._rtpTransceiver}getMediaStreamTrackSettings(){return this.getMediaStreamTrack(!0).getSettings()}close(){this._isClosed=!0,this._lowRtpTransceiver=void 0,this._rtpTransceiver=void 0,je(this),this.emit(dt.CLOSED),this.removeAllListeners(ct.SEI_RECEIVED)}_updateRtpTransceiver(e,t){if(t===ot.LOW_STREAM){if(this._lowRtpTransceiver===e)return;this._lowRtpTransceiver=e}else{if(this._rtpTransceiver===e)return;this._rtpTransceiver=e}this.emit(ct.TRANSCEIVER_UPDATED,e,t)}}class Lt extends Pt{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),Mt(this,"_enabled",!0),Mt(this,"_muted",!1),Mt(this,"_isExternalTrack",!1),Mt(this,"_isClosed",!1),Mt(this,"_enabledMutex",void 0),Mt(this,"processor",void 0),Mt(this,"_processorContext",void 0),Mt(this,"_handleTrackEnded",(()=>{this.onTrackEnded()})),this._enabledMutex=new D("".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,ge.debug("[".concat(this.getTrackId(),"] close")),this.emit(it.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 N(this,it.NEED_REPLACE_TRACK,this),this.processor&&this._processorContext&&this.processor.updateInput({track:this._originMediaStreamTrack,context:this._processorContext}))}_getDefaultPlayerConfig(){return{}}onTrackEnded(){ge.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(dt.TRACK_ENDED)}stateCheck(e,t){if(ge.debug("check track state, [muted: ".concat(this._muted,", enabled: ").concat(this._enabled,"] to [").concat(e,": ").concat(t,"]")),y(t,e),this._enabled&&this._muted&&"enabled"===e&&!1===t)throw new b(k.TRACK_STATE_UNREACHABLE,"cannot set enabled while the track is muted").print("error",ge);if(!this._enabled&&!this._muted&&"muted"===e&&!0===t)throw new b(k.TRACK_STATE_UNREACHABLE,"cannot set muted while the track is disabled").print("error",ge)}getProcessorStats(){return this._processorContext&&this._processorContext.gatherStats()||[]}getProcessorUsage(){return this._processorContext?this._processorContext.gatherUsage():Promise.resolve([])}}const Vt=window.AudioContext||window.webkitAudioContext;let xt,Ut=null;const Zt=new class extends A{constructor(){super(...arguments),Mt(this,"prevState",void 0),Mt(this,"curState",void 0),Mt(this,"currentTime",void 0),Mt(this,"currentTimeStuckAt",void 0),Mt(this,"interruptDetectorTrack",void 0),Mt(this,"onLocalAudioTrackMute",(()=>{ge.info("ios15-interruption-start"),this.emit(Pe.IOS_15_16_INTERRUPTION_START)})),Mt(this,"onLocalAudioTrackUnmute",(async()=>{ge.info("ios15-interruption-end"),"running"!==this.curState||this.duringInterruption?ge.info("ios15-interruption-end-canceled"):(Ut&&await Ut.suspend(),this.emit(Pe.IOS_15_16_INTERRUPTION_END))}))}get duringInterruption(){return"running"===this.prevState&&"interrupted"===this.curState}bindInterruptDetectorTrack(e){ge.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){ge.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 Wt(){if(!Vt)return void ge.error("your browser is not support web audio");ge.info("create audio context");const t=Nt({},u("WEBAUDIO_INIT_OPTIONS"));ge.debug("audio context init option:",JSON.stringify(t)),Ut=new Vt(t),Zt.curState=Ut.state,Ut.onstatechange=()=>{Zt.prevState=Zt.curState,Zt.curState=Ut?Ut.state:void 0;const t=Zt.prevState,i=Zt.curState,r="running"===i,s="interrupted"===i,o="running"===t,n="suspended"===t,a="interrupted"===t,c=e().osVersion;(P()||L())&&o&&s&&(ge.info("ios".concat(c,"-interruption-start")),Zt.emit(Pe.IOS_INTERRUPTION_START)),(P()||L())&&(n||a)&&r&&(ge.info("ios".concat(c,"-interruption-end")),Zt.emit(Pe.IOS_INTERRUPTION_END)),t!==i&&Zt.emit(Pe.STATE_CHANGE,i,t)},setInterval((()=>{var e;const t=null===(e=Ut)||void 0===e?void 0:e.currentTime;if(Zt.currentTime!==t)Zt.currentTimeStuckAt&&(ge.debug("AudioContext current time resume at ".concat(t)),Zt.currentTimeStuckAt=void 0),Zt.currentTime=t;else{if(t!==Zt.currentTimeStuckAt){_e.reportApiInvoke(null,{name:"WEB_AUDIO_CURRENT_TIME_STUCK",options:{currentTime:t},tag:M.TRACER}).onSuccess(),ge.warning("AudioContext current time stuck at ".concat(t))}Zt.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):P()||L()?"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 l(){let e;try{e=i.play(),e?e.then(g,g):(i.addEventListener("playing",g),i.addEventListener("abort",g),i.addEventListener("error",g))}catch(e){g()}}function p(e){o||(i.paused?e?(m(!1),o=!0,l()):m(!0):m(!1))}function m(e){if(s!==e){s=e;for(let i=0,r=t;i<r.length;i++){const t=r[i];e?window.addEventListener(t,_,{capture:!0,passive:!0}):window.removeEventListener(t,_,{capture:!0,passive:!0})}}}function g(){i.removeEventListener("playing",g),i.removeEventListener("abort",g),i.removeEventListener("error",g),o=!1,p(!1)}function _(){p(!0)}let T;if(P()&&u("IOS_BG_TAG")){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,T=()=>{if(u("IOS_AUTO_RESTART_BG_TAG")&&i&&i.srcObject&&!o&&(!i.paused||!0!==s)){i.paused||i.pause();try{o=!0,l()}catch(e){o=!1}return!0}},p(!0)}return Zt.on(Pe.STATE_CHANGE,c),n(!1),T}(Ut).then((e=>{xt=e}))}function Gt(){if(xt){if(xt()){_e.reportApiInvoke(null,{name:"BG_AUDIO_TAG_RESTART",options:{},tag:M.TRACER}).onSuccess(),ge.debug("restart background audio tag success")}}}function Bt(){if(!Ut){if(Wt(),!Ut)throw new b(k.NOT_SUPPORTED,"can not create audio context");return Ut}return Ut}function Ft(){return!!Ut}function Kt(e){if(function(){if(null!==Xt)return Xt;const e=Bt(),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(),Xt=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?O(e._inputNodes,r):e._inputNodes=[];for(const i of e._inputNodes)t.call(e,i)}}function Ht(e){const t=Bt();return new Promise(((i,r)=>{t.decodeAudioData(e,(e=>{i(e)}),(e=>{r(new b(k.DECODE_AUDIO_FILE_FAILED,e.toString()))}))}))}let Xt=null;function Yt(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=Bt();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 zt=null;function jt(){if(zt)return zt;const e=Bt();if(!e.createMediaStreamDestination)throw new b(k.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),zt=r.stream.getAudioTracks()[0],zt}function Jt(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 Qt(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 qt{constructor(){Mt(this,"context",void 0),Mt(this,"analyserNode",void 0),Mt(this,"sourceNode",void 0),this.context=Bt(),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||P()||L()||"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){ge.warning("rebuild analyser node failed.")}}destroy(){this.updateSource(void 0)}}class $t extends A{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(),Mt(this,"outputNode",void 0),Mt(this,"outputTrack",void 0),Mt(this,"isPlayed",!1),Mt(this,"sourceNode",void 0),Mt(this,"context",void 0),Mt(this,"audioBufferNode",void 0),Mt(this,"destNode",void 0),Mt(this,"audioOutputLevel",0),Mt(this,"volumeLevelAnalyser",void 0),Mt(this,"_processedNode",void 0),Mt(this,"playNode",void 0),Mt(this,"isDestroyed",!1),Mt(this,"onNoAudioInput",void 0),Mt(this,"isNoAudioInput",!1),Mt(this,"_noAudioInputCount",0),this.context=Bt(),this.playNode=this.context.destination,this.outputNode=this.context.createGain(),Kt(this.outputNode),this.volumeLevelAnalyser=new qt}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(lt.ON_AUDIO_BUFFER,Jt(e))})}stopGetAudioBuffer(){this.audioBufferNode&&(this.audioBufferNode.onaudioprocess=null,this.outputNode.disconnect(this.audioBufferNode),this.audioBufferNode=void 0)}createOutputTrack(){if(!Se().webAudioMediaStreamDest)throw new b(k.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((()=>{Zt.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;P()||L()?"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 V(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 ei extends $t{get isFreeze(){return!1}constructor(t,i,r){var s;if(super(),Mt(this,"sourceNode",void 0),Mt(this,"track",void 0),Mt(this,"clonedTrack",void 0),Mt(this,"audioElement",void 0),Mt(this,"isCurrentTrackCloned",!1),Mt(this,"isRemoteTrack",!1),Mt(this,"originVolumeLevelAnalyser",void 0),Mt(this,"rebuildWebAudio",(async()=>{if(ge.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 ge.debug("rebuild web audio success, current volume status",this.getAccurateVolumeLevel());this.context.resume().then((()=>ge.info("resume success"))),ge.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),Kt(this.sourceNode),this.volumeLevelAnalyser.rebuildAnalyser();const i=this.outputNode.gain.value;this.outputNode=this.context.createGain(),this.outputNode.gain.setValueAtTime(i,this.context.currentTime),Kt(this.outputNode),this.emit(lt.UPDATE_SOURCE),this.connect(),this.audioElement.srcObject=t,this.isPlayed&&this.play(this.playNode),this.checkHasAudioInput()})),"audio"!==t.kind)throw new b(k.UNEXPECTED_ERROR);this.track=t;const o=new MediaStream([this.track]);if(this.isRemoteTrack=!!i,this.sourceNode=this.context.createMediaStreamSource(o),Kt(this.sourceNode),r){const e=r.clone();e.enabled=!0,this.clonedTrack=e,ge.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]));Kt(t),this.originVolumeLevelAnalyser=new qt,this.originVolumeLevelAnalyser.updateSource(t)}this.connect(),this.audioElement=document.createElement("audio"),this.audioElement.srcObject=o,x()&&(this.audioElement.muted=!0);const n=e();i&&n.os===a.IOS&&Number(null===(s=n.osVersion)||void 0===s?void 0:s.split(".")[0])<15&&(Zt.on(Pe.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),Kt(this.sourceNode),this.processedNode||this.sourceNode.connect(this.outputNode),this.emit(lt.UPDATE_SOURCE),this.audioElement.srcObject=t}destroy(){var e;this.audioElement.srcObject=null,this.audioElement.remove(),Zt.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),ge.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]));Kt(i),this.originVolumeLevelAnalyser&&this.originVolumeLevelAnalyser.updateSource(i)}getOriginVolumeLevel(){return this.originVolumeLevelAnalyser?this.originVolumeLevelAnalyser.getVolumeLevel():this.getAccurateVolumeLevel()}}async function ti(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 ii(e,t){const i=await ri(e.mediaSource),r=await U(i,t),s=r.sourceId,o=r.audio;return await ti(s,e,o)}async function ri(e){let t=["window","screen"];"application"!==e&&"window"!==e||(t=["window"]),"screen"===e&&(t=["screen"]);const i=Z();if(!i)throw console.error("failed to fetch electron, please mount it to window"),new b(k.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 b(k.ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR,e.toString())}}const si=new D("safari");let oi=!1,ni=!1;async function ai(e,t){let i=0,r=null;for(;i<2;)try{r=await ci(e,t,i>0);break}catch(e){if(e instanceof b)throw ge.error("[".concat(t,"] ").concat(e.toString())),e;const r=di(e.name||e.code||e,e.message);if(r.code===k.MEDIA_OPTION_INVALID){ge.debug("[".concat(t,"] detect media option invalid, retry")),i+=1,await V(500);continue}throw ge.error("[".concat(t,"] ").concat(r.toString())),r}if(!r)throw new b(k.UNEXPECTED_ERROR,"can not find stream after getUserMedia");return r}async function ci(t,i,r){if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)throw new b(k.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=Se(),o=new MediaStream;if(t.audioSource&&o.addTrack(t.audioSource),t.videoSource&&o.addTrack(t.videoSource),!t.audio&&!t.video&&!t.screen)return ge.debug("Using Video Source/ Audio Source"),o;if(t.screen)if(W())if(t.screen.sourceId){ui(o,await ti(t.screen.sourceId,t.screen,!!t.screenAudio))}else{ui(o,await ii(t.screen,!!t.screenAudio))}else if(p()&&t.screen.extensionId&&t.screen.mandatory){if(!s.getStreamFromExtension)throw new b(k.NOT_SUPPORTED,"This browser does not support screen sharing");ge.debug("[".concat(i,'] Screen access on chrome stable, looking for extension"'));const e=await(a=t.screen.extensionId,l=i,new Promise(((e,t)=>{try{chrome.runtime.sendMessage(a,{getStream:!0},(i=>{if(!i||!i.streamId)return ge.error("[".concat(l,"] No response from Chrome Plugin. Plugin not installed properly"),i),void t(new b(k.CHROME_PLUGIN_NO_RESPONSE,"No response from Chrome Plugin. Plugin not installed properly"));e(i.streamId)}))}catch(e){ge.error("[".concat(l,"] AgoraRTC screensharing plugin is not accessible(").concat(a,")"),e.toString()),t(new b(k.CHROME_PLUGIN_NOT_INSTALL))}})));t.screen.mandatory.chromeMediaSourceId=e;ui(o,await navigator.mediaDevices.getUserMedia({video:{mandatory:t.screen.mandatory}}))}else if(s.getDisplayMedia){var n;t.screen.mediaSource&&tt(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},r=t.screen,s=r.selfBrowserSurface,a=r.surfaceSwitching,c=r.systemAudio,d=r.preferCurrentTab,u=r.windowAudio,h=r.monitorTypeSurfaces,l={selfBrowserSurface:s,surfaceSwitching:a,systemAudio:c,preferCurrentTab:d,windowAudio:u,monitorTypeSurfaces:h};!s&&delete l.selfBrowserSurface,!a&&delete l.surfaceSwitching,!c&&delete l.systemAudio,!d&&delete l.preferCurrentTab,!u&&delete l.windowAudio,!h&&delete l.monitorTypeSurfaces,ge.debug("[".concat(i,"] getDisplayMedia:"),JSON.stringify({video:e,audio:t.screenAudio,controls:l}));ui(o,await navigator.mediaDevices.getDisplayMedia(Nt({video:e,audio:t.screenAudio},l)))}else{if(!h())throw ge.error("[".concat(i,"] This browser does not support screenSharing")),new b(k.NOT_SUPPORTED,"This browser does not support screen sharing");{t.screen.mediaSource&&tt(t.screen.mediaSource);const e={video:{mediaSource:t.screen.mediaSource,width:t.screen.width,height:t.screen.height,frameRate:t.screen.frameRate}};ge.debug("[".concat(i,"] getUserMedia: ").concat(JSON.stringify(e)));ui(o,await navigator.mediaDevices.getUserMedia(e))}}var a,l;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=G(m,g)}catch(e){}ge.debug("[".concat(i,"] GetUserMedia"),JSON.stringify(m)),e();let _,T=null;(c()||P()||d())&&(T=await si.lock());try{_=await navigator.mediaDevices.getUserMedia(m)}catch(e){throw T&&T(),e}return m.audio&&(oi=!0),m.video&&(ni=!0),ui(o,_),T&&T(),o}function di(e,t){switch(e){case"Starting video failed":case"OverconstrainedError":case"TrackStartError":return new b(k.MEDIA_OPTION_INVALID,"".concat(e,": ").concat(t));case"NotFoundError":case"DevicesNotFoundError":return new b(k.DEVICE_NOT_FOUND,"".concat(e,": ").concat(t));case"NotSupportedError":return new b(k.NOT_SUPPORTED,"".concat(e,": ").concat(t));case"NotReadableError":return new b(k.NOT_READABLE,"".concat(e,": ").concat(t));case"InvalidStateError":case"NotAllowedError":case"PERMISSION_DENIED":case"PermissionDeniedError":return new b(k.PERMISSION_DENIED,"".concat(e,": ").concat(t));case"ConstraintNotSatisfiedError":return new b(k.CONSTRAINT_NOT_SATISFIED,"".concat(e,": ").concat(t));default:return ge.error("getUserMedia unexpected error",e),new b(k.UNEXPECTED_ERROR,"".concat(e,": ").concat(t))}}function ui(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 hi extends A{get state(){return this._state}set state(e){e!==this._state&&(this.emit(St.STATE_CHANGE,e),this._state=e)}constructor(){super(),Mt(this,"_state",yt.IDLE),Mt(this,"isAccessMicrophonePermission",!1),Mt(this,"isAccessCameraPermission",!1),Mt(this,"lastAccessMicrophonePermission",!1),Mt(this,"lastAccessCameraPermission",!1),Mt(this,"checkdeviceMatched",!1),Mt(this,"deviceInfoMap",new Map),this.init().then((()=>{navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",this.updateDevicesInfo.bind(this)),window.setInterval((()=>{(u("ENUMERATE_DEVICES_INTERVAL")||(B()||F())&&i())&&this.updateDevicesInfo()}),u("ENUMERATE_DEVICES_INTERVAL_TIME"))})).catch((e=>ge.error(e.toString())))}async enumerateDevices(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices)throw new b(k.NOT_SUPPORTED,"enumerateDevices() not supported.");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(si.isLocked){ge.debug("[device manager] wait GUM lock");(await si.lock())(),ge.debug("[device manager] GUM unlock")}if(oi&&(o=!1,this.isAccessMicrophonePermission=!0),ni&&(n=!1,this.isAccessCameraPermission=!0),ge.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=di(e.name||e.code||e,e.message);if(t.code===k.PERMISSION_DENIED)throw t;ge.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=di(e.name||e.code||e,e.message);if(t.code===k.PERMISSION_DENIED)throw t;ge.warning("getUserMedia failed in getDevices",t)}this.isAccessMicrophonePermission=!0}else if(n){try{c=await navigator.mediaDevices.getUserMedia({video:t})}catch(e){const t=di(e.name||e.code||e,e.message);if(t.code===k.PERMISSION_DENIED)throw t;ge.warning("getUserMedia failed in getDevices",t)}this.isAccessCameraPermission=!0}ge.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 b(k.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 b(k.DEVICE_NOT_FOUND,"deviceId: ".concat(e));return t}async init(){this.state=yt.INITING;try{await this.updateDevicesInfo(),this.state=yt.INITEND}catch(e){if(this.state=yt.IDLE,!K())throw new b(k.WEB_SECURITY_RESTRICT,"Your context is limited by web security, please try using https protocol or localhost.");throw ge.warning("Device Detection functionality cannot start properly.",e.toString()),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?ge.debug("[device-check] default input ".concat(t.label," and output ").concat(i.label," is the same group")):ge.debug("[device-check] default input ".concat(t.label," and output ").concat(i.label," is not the same group")):ge.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!==yt.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(St.RECORDING_DEVICE_CHANGED,e);break;case"videoinput":this.lastAccessCameraPermission&&this.isAccessCameraPermission&&this.emit(St.CAMERA_DEVICE_CHANGED,e);break;case"audiooutput":this.lastAccessMicrophonePermission&&this.isAccessMicrophonePermission&&this.emit(St.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 li=new hi;let pi=!1;const mi=new class extends A{constructor(){super(...arguments),Mt(this,"onAutoplayFailed",void 0),Mt(this,"onAudioAutoplayFailed",void 0)}};function gi(){if(pi)return u("FLS_AUTOPLAY_EMITS")?(mi.onAutoplayFailed&&mi.onAutoplayFailed(),mi.emit("autoplay-failed")):void 0;{const e=t=>{t.preventDefault(),function(){try{const e=Bt();"running"!==e.state&&e.resume().catch((e=>{var t;ge.warning("resume web audio context on autoplay gesture failed",(null==e||null===(t=e.toString)||void 0===t?void 0:t.call(e))||e)}))}catch(t){var e;ge.warning("create web audio context on autoplay gesture failed",(null==t||null===(e=t.toString)||void 0===e?void 0:e.call(t))||t)}}(),pi=!1,H()?document.body.removeEventListener("click",e,!0):(document.body.removeEventListener("touchstart",e,!0),document.body.removeEventListener("mousedown",e,!0))};pi=!0,H()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0)),ge.info("detect media autoplay failed, document: https://docs.agora.io/cn/Voice/autoplay_policy_web_ng?platform=Web"),mi.onAutoplayFailed?mi.onAutoplayFailed():mi.onAudioAutoplayFailed?ge.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 ."):ge.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 ."),mi.emit("autoplay-failed")}}function _i(e,t,i,r){if(!e)return;const s=_e.getBaseInfoBySessionId(e);if(!s)return;const o=s.info,n=Date.now(),a=Nt(Nt({},o),{},{vid:void 0===o.vid?0:Number(o.vid),lts:n,elapse:n-s.startTime,cbRegistered:mi.onAutoplayFailed||mi.onAudioAutoplayFailed?1:-1,errorMsg:i,mediaType:t,trackId:r,extend:void 0});_e.send({type:Te.AUTOPLAY_FAILED,data:a},!0)}const Ti=["play","playing","loadeddata","canplay","pause","stalled","suspend","waiting","abort","emptied","ended","error"],fi=new class{constructor(){Mt(this,"onAutoplayFailed",void 0),Mt(this,"elementMap",new Map),Mt(this,"elementStateMap",new Map),Mt(this,"elementsNeedToResume",[]),Mt(this,"sinkIdMap",new Map),Mt(this,"elementIdMap",new WeakMap),Mt(this,"autoResumeAfterInterruption",(e=>Promise.all(Array.from(this.elementMap.entries()).map((async t=>{let i=Ot(t,2),r=i[0],s=i[1];const o=this.elementStateMap.get(r),n=s.srcObject.getAudioTracks()[0],a=n&&n.readyState;if(ge.debug("resume after interrupted, ele: ".concat(o," audio: ").concat(a," ").concat(e)),"live"===a){if(e)return s.pause(),s.play();if("running"===Zt.curState)return Y()?(s.pause(),s.play()):o&&"paused"===o?s.play():void 0}}))))),Mt(this,"autoResumeAfterInterruptionOnIOS15_16",(()=>{Array.from(this.elementMap.entries()).forEach((e=>{let t=Ot(e,2);t[0];let i=t[1];const r=i.srcObject.getAudioTracks()[0];r&&"live"===r.readyState&&(ge.debug("auto resume after interruption inside autoResumeAfterInterruptionOnIOS15"),i.pause(),i.play())}))})),this.autoResumeAudioElement(),Zt.on(Pe.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),Zt.on(Pe.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16),Zt.on(Pe.STATE_CHANGE,(()=>{P()&&"suspended"===Zt.prevState&&"running"===Zt.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 b(k.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.elementIdMap.set(o,{id:t}),this.bindAudioElementEvents(t,o),this.elementMap.set(t,o),this.elementStateMap.set(t,kt.INIT),this.setVolume(t,i);const n=this.sinkIdMap.get(t);if(n)try{o.setSinkId(n).catch((e=>{ge.warning("[".concat(t,"] set sink id failed"),e.toString())}))}catch(e){ge.warning("[".concat(t,"] set sink id failed"),e.toString())}const a=o.play();a&&a.then&&a.catch((e=>{s&&_i(s,"audio",e.message,t),ge.warning("audio element play warning",e.toString()),this.elementMap.has(t)&&"NotAllowedError"===e.name&&(ge.warning("detected audio element autoplay failed"),this.elementsNeedToResume.push(o),r((()=>{this.onAutoplayFailed&&this.onAutoplayFailed(),gi()})))}))}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)}getVolume(e){const t=this.elementMap.get(e);return t?t.volume:0}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)}reuseTrackId(e,t){if(e===t)return;const i=this.elementMap.get(e);if(!i)return;this.elementMap.has(t)&&this.stop(t),this.elementMap.delete(e),this.elementMap.set(t,i);const r=this.elementStateMap.get(e);this.elementStateMap.delete(e),void 0!==r&&this.elementStateMap.set(t,r);const s=this.sinkIdMap.get(e);void 0!==s&&(this.sinkIdMap.delete(e),this.sinkIdMap.set(t,s));const o=this.elementIdMap.get(i);o&&(o.id=t)}bindAudioElementEvents(e,t){Ti.forEach((i=>{t.addEventListener(i,(i=>{var r,s;const o=null!==(r=null===(s=this.elementIdMap.get(t))||void 0===s?void 0:s.id)&&void 0!==r?r:e,n=this.elementStateMap.get(o),a="pause"===i.type?"paused":i.type;if(ge.debug("[".concat(o,"] audio-element-status change ").concat(n," => ").concat(a)),"error"===i.type){const e=null==t?void 0:t.error;e&&ge.error("[".concat(o,"] media error, code: ").concat(e.code,", message: ").concat(e.message))}this.elementStateMap.set(o,a)}))}))}getPlayerState(e){return this.elementStateMap.get(e)||"uninit"}autoResumeAudioElement(){const e=()=>{this.elementsNeedToResume.forEach((e=>{e.play().then((e=>{ge.debug("Auto resume audio element success")})).catch((e=>{ge.warning("Auto resume audio element failed!",e)}))})),this.elementsNeedToResume=[]};X().then((()=>{H()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0))}))}};function Ei(){return function(e,t,i){const r=i.value;return"function"==typeof r&&(i.value=function(){this._isClosed&&new b(k.INVALID_OPERATION,"[".concat(this.getTrackId(),"] cannot operate a closed track")).print("warning",ge);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 vi extends A{constructor(e){super(),Mt(this,"name","VideoProcessorDestination"),Mt(this,"ID","0"),Mt(this,"_source",void 0),Mt(this,"videoContext",void 0),Mt(this,"inputTrack",void 0),this.videoContext=e}get kind(){return"video"}get enabled(){return!0}pipe(){throw new b(k.NOT_SUPPORTED,"VideoProcessor cannot pipe to any other Processor")}unpipe(){throw new b(k.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(Et.ON_TRACK,e.track))}reset(){this.inputTrack=void 0,this.videoContext.chained=!1,this.emit(Et.ON_TRACK,void 0)}}class yi extends A{set chained(e){this._chained=e}get chained(){return this._chained}constructor(e,t){super(),Mt(this,"constraintsMap",new Map),Mt(this,"statsRegistry",[]),Mt(this,"usageRegistry",[]),Mt(this,"trackId",void 0),Mt(this,"direction",void 0),Mt(this,"_chained",!1),this.trackId=e,this.direction=t}async getConstraints(){return await z(this,vt.REQUEST_CONSTRAINTS)}async requestApplyConstraints(e,t){return ge.info("processor ".concat(t.name," requestApplyConstraints for ").concat(this.trackId)),e&&this.constraintsMap.set(t,e),N(this,vt.REQUEST_UPDATE_CONSTRAINTS,Array.from(this.constraintsMap.values()))}async requestRevertConstraints(e){if(this.constraintsMap.has(e))return ge.info("processor ".concat(e.name," requestRevertConstraints for ").concat(this.trackId)),this.constraintsMap.delete(e),N(this,vt.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 t of this.statsRegistry){const i=t.processorID,r=t.processorName,s=t.type,o=t.cb;try{const t=o();e.push({processorID:i,processorName:r,type:s,stats:t})}catch(e){ge.error(new b(k.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 t of this.usageRegistry){const i=t.cb;try{let t=i();t instanceof Promise&&(t=await t),e.push(Nt(Nt({},t),{},{direction:this.direction}))}catch(e){ge.error("gather extension usage error",e)}}return e}getDirection(){return this.direction}}class Si extends A{constructor(e){super(),Mt(this,"name","AudioProcessorDestination"),Mt(this,"ID","0"),Mt(this,"inputTrack",void 0),Mt(this,"inputNode",void 0),Mt(this,"audioProcessorContext",void 0),Mt(this,"_source",void 0),this.audioProcessorContext=e}get kind(){return"audio"}get enabled(){return!0}pipe(){throw new b(k.NOT_SUPPORTED,"AudioProcessorDestination cannot pipe to any other Processor")}unpipe(){throw new b(k.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(Et.ON_TRACK,void 0),this.emit(Et.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(Et.ON_TRACK,this.inputTrack)),e.node&&this.inputNode!==e.node&&(this.audioProcessorContext.chained=!0,this.inputNode=e.node,this.emit(Et.ON_NODE,this.inputNode))}}class bi extends A{set chained(e){this._chained=e}get chained(){return this._chained}constructor(e,t,i){super(),Mt(this,"constraintsMap",new Map),Mt(this,"statsRegistry",[]),Mt(this,"audioContext",void 0),Mt(this,"trackId",void 0),Mt(this,"direction",void 0),Mt(this,"usageRegistry",[]),Mt(this,"_chained",!1),this.audioContext=e,this.trackId=t,this.direction=i}async getConstraints(){return z(this,vt.REQUEST_CONSTRAINTS)}getAudioContext(){return this.audioContext}async requestApplyConstraints(e,t){return ge.info("processor ".concat(t.name," requestApplyConstraints for ").concat(this.trackId)),e&&this.constraintsMap.set(t,e),N(this,vt.REQUEST_UPDATE_CONSTRAINTS,Array.from(this.constraintsMap.values()))}async requestRevertConstraints(e){if(this.constraintsMap.has(e))return this.constraintsMap.delete(e),N(this,vt.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 t of this.statsRegistry){const i=t.processorID,r=t.processorName,s=t.type,o=t.cb;try{const t=o();e.push({processorID:i,processorName:r,type:s,stats:t})}catch(e){ge.error(new b(k.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 t of this.usageRegistry){const i=t.cb;try{let t=i();t instanceof Promise&&(t=await t),e.push(Nt(Nt({},t),{},{direction:this.direction}))}catch(e){ge.error("gather extension usage error",e)}}return e}getDirection(){return this.direction}}class ki extends A{get isPlayed(){return!0}get isFreeze(){return!1}constructor(){super(),Mt(this,"context",void 0),Mt(this,"processSourceNode",void 0),Mt(this,"outputTrack",void 0),Mt(this,"processedNode",void 0),Mt(this,"clonedTrack",void 0),Mt(this,"outputNode",void 0),this.outputNode=new Ii}setVolume(){}createOutputTrack(){throw new b(k.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 Ii{disconnect(){}connect(){}}function Ai(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=P()?"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(j),setTimeout((()=>{r||(s.srcObject=null,s.remove(),t([s.videoWidth,s.videoHeight]))}),4e3)}))}function Ri(e){const t={};e.facingMode&&(t.facingMode=e.facingMode),e.cameraId&&(t.deviceId={exact:e.cameraId});const i=Be(e.encoderConfig);return null!=i.width&&(t.width=i.width),null!=i.height&&(t.height=i.height),!J()&&i.frameRate&&(t.frameRate=i.frameRate),m()&&"object"==typeof t.frameRate&&(t.frameRate.max=60),h()&&(t.frameRate={ideal:30,max:30}),t}function wi(e){const t={};e.screenSourceType&&(t.mediaSource=e.screenSourceType),e.extensionId&&p()&&(t.extensionId=e.extensionId);const i=e.displaySurface,r=e.selfBrowserSurface,o=e.surfaceSwitching,n=e.systemAudio,a=e.preferCurrentTab,c=e.windowAudio,d=e.monitorTypeSurfaces;(s(107)||T(107)||f(93))&&(i&&(S(i,"displaySurface",["browser","window","monitor"]),t.displaySurface=i),r?(S(r,"selfBrowserSurface",["exclude","include"]),t.selfBrowserSurface=r):t.selfBrowserSurface="include",o&&(S(o,"surfaceSwitching",["exclude","include"]),t.surfaceSwitching=o)),(s(105)||T(105)||f(91))&&n&&(S(n,"systemAudio",["exclude","include"]),t.systemAudio=n),(s(94)||T(94)||f(80))&&a&&(t.preferCurrentTab=!0),(s(141)||T(141)||f(125))&&c&&(S(c,"windowAudio",["exclude","system"]),t.windowAudio=c),(s(119)||T(119)||f(105))&&d&&(S(d,"monitorTypeSurfaces",["exclude","include"]),t.monitorTypeSurfaces=d),e.electronScreenSourceId&&(t.sourceId=e.electronScreenSourceId);const u=e.encoderConfig?Fe(e.encoderConfig):null;return t.mandatory={chromeMediaSource:"desktop",maxWidth:u?u.width:void 0,maxHeight:u?u.height:void 0},u&&(u.frameRate&&("number"==typeof u.frameRate?(t.mandatory.maxFrameRate=u.frameRate,t.mandatory.minFrameRate=u.frameRate):(t.mandatory.maxFrameRate=u.frameRate.max||u.frameRate.ideal||u.frameRate.exact||void 0,t.mandatory.minFrameRate=u.frameRate.min||u.frameRate.ideal||u.frameRate.exact||void 0),t.frameRate=u.frameRate),u.width&&(t.width=u.width),u.height&&(t.height=u.height)),t}function Ci(e){const t={};return J()||(void 0!==e.AGC&&(t.autoGainControl=e.AGC),void 0!==e.AEC&&(t.echoCancellation=e.AEC),void 0!==e.ANS&&(t.noiseSuppression=e.ANS,p()&&e.ANS&&(t.googHighpassFilter=e.ANS))),t}function Mi(e){const t=Ci(e);return Ne()&&e.suppressLocalAudioPlayback&&(t.suppressLocalAudioPlayback=e.suppressLocalAudioPlayback),Oe()&&e.restrictOwnAudio&&(t.restrictOwnAudio=!0),t}function Di(e){const t=Ci(e);if(e.encoderConfig){const i=Xe(e.encoderConfig);t.channelCount=i.stereo?2:1,t.sampleRate=i.sampleRate,t.sampleSize=i.sampleSize}return e.microphoneId&&(t.deviceId={exact:e.microphoneId}),B()&&(t.sampleRate=void 0),t}function Ni(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)=>Ot(e,1)[0]-Ot(t,1)[0])),t=e.find((e=>Ot(e,1)[0]>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)=>Ot(e,1)[0]-Ot(t,1)[0])),t=e.find((e=>Ot(e,1)[0]>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 Oi(e,t,i){if(!Array.isArray(u("VIDEO_ENCODER_CONFIG_LIST")))return!1;if(0===u("VIDEO_ENCODER_CONFIG_LIST").length)return!1;const r=Math.min(e,t);if(r>=480)return!1;return Nt(Nt({},u("VIDEO_ENCODER_CONFIG_LIST").find((e=>e.height>r))),{},{frameRate:i})}function Pi(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 Li(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 i=e.getMediaStreamTrackSettings(),r=i.frameRate,s=i.width,o=i.height;let n=t.frameRate,a=void 0===n?r:n,c=t.width,d=void 0===c?s:c,h=t.height,l=void 0===h?o:h;if(!a||!d||!l)return;d=Q(d),l=Q(l),a=Q(a);const p=Li(d,l,a),m=p.max,g=p.min,_=t||{},T=_.bitrateMax,f=_.bitrateMin,E=_.minDownscaleWidth,v=_.minDownscaleHeight;T||ge.debug("calculate bitrate: [w: ".concat(d,", h: ").concat(l,", fps: ").concat(a,"] => [brMax: ").concat(T,", brMin: ").concat(f,"]"));const y=u("ENCODER_CONFIG_LIMIT").maxFramerate;return y&&"number"==typeof y&&(a=Math.min(a,y)),{width:d,height:l,frameRate:a,bitrateMax:T||m,bitrateMin:f||g,scaleResolutionDownBy:1,scale:0,minDownscaleWidth:E,minDownscaleHeight:v}},xi=async(e,t,i)=>await(async(e,t,i)=>{const r=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),Ui=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 Zi(e);i({buffer:r,width:t.width,height:t.height})}else r(new b(k.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED))}),e,1)}))},Zi=async e=>{const t=await e.arrayBuffer();return new Uint8Array(t)};function Wi(e,t){if("VideoFrame"in window&&"TransformStream"in window&&Se().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 Gi,Bi,Fi,Ki,Hi,Xi,Yi,zi,ji,Ji,Qi,qi,$i,er,tr,ir,rr,sr,or,nr,ar,cr,dr,ur,hr,lr,pr,mr,gr,_r,Tr,fr,Er,vr,yr,Sr,br,kr,Ir,Ar;let Rr=(Gi=fe({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),Bi=fe({argsMap:(e,t)=>[e.getTrackId(),t]}),Fi=Ei(),Ki=ee("LocalAudioTrack","_enabledMutex"),Hi=fe({argsMap:(e,t)=>[e.getTrackId(),t]}),Xi=Ei(),Yi=ee("LocalAudioTrack","_enabledMutex"),zi=fe({argsMap:(e,t)=>[e.getTrackId(),t]}),ji=Ei(),Ji=Ei(),Qi=Ei(),qi=fe({argsMap:e=>[e.getTrackId()]}),$i=Ei(),er=fe({argsMap:e=>[e.getTrackId()]}),tr=Ei(),ir=fe({argsMap:e=>[e.getTrackId()]}),rr=fe({argsMap:(e,t)=>[e.getTrackId(),t.name]}),sr=fe({argsMap:e=>[e.getTrackId()]}),wt((or=class extends Lt{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?fi.isPlaying(this.getTrackId()):this._source.isPlayed}get __className__(){return"LocalAudioTrack"}constructor(e,t,i,r){super(e,i),Mt(this,"trackMediaType",ht.AUDIO),Mt(this,"_encoderConfig",void 0),Mt(this,"_trackSource",void 0),Mt(this,"metadata",[]),Mt(this,"_enabled",!0),Mt(this,"_volume",100),Mt(this,"_useAudioElement",!0),Mt(this,"_bypassWebAudio",!1),Mt(this,"processor",void 0),Mt(this,"_processorContext",void 0),Mt(this,"_processorDestination",void 0),Mt(this,"_getOriginVolumeLevel",void 0),Mt(this,"_usePipeMode",!1),Mt(this,"_useExtensionMode",!1),Mt(this,"_extensionManager",void 0),this._encoderConfig=t,this._getOriginVolumeLevel=!!r,this._trackSource=new ki,u("DISABLE_WEBAUDIO")&&(this._bypassWebAudio=!0),u("LOCAL_AUDIO_TRACK_USES_WEB_AUDIO")&&(this._useAudioElement=!1);c()&&!Ft()?setTimeout((()=>this.initWebAudio())):this.initWebAudio()}setVolume(e){v(e,"volume",0,1e3),this._volume=e,this._source.setVolume(e/100),this._useAudioElement&&fi.setVolume(this.getTrackId(),e);try{if(this._bypassWebAudio)return void ge.debug("[".concat(this.getTrackId(),"] setVolume returned because no pass through WebAudio."));const e=this._source.createOutputTrack();this._mediaStreamTrack!==e&&(this._mediaStreamTrack=e,N(this,it.NEED_REPLACE_TRACK,this).then((()=>{ge.debug("[".concat(this.getTrackId(),"] replace web audio track success"))})).catch((e=>{ge.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||!be())throw new b(k.NOT_SUPPORTED,"your browser does not support setting the audio output device");await fi.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(ge.info("[".concat(this.getTrackId(),"] start setEnabled"),e),e){this._originMediaStreamTrack.enabled=!0;try{i||(this._enabled=!0),await N(this,it.NEED_ENABLE_TRACK,this),ge.info("[".concat(this.getTrackId(),"] setEnabled to ").concat(e," success"))}catch(e){throw i||(this._enabled=!1),ge.error("[".concat(this.getTrackId(),"] setEnabled to true error"),e.toString()),e}}else{this._originMediaStreamTrack.enabled=!1,i||(this._enabled=!1);try{await N(this,it.NEED_DISABLE_TRACK,this)}catch(e){throw i||(this._enabled=!0),ge.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,ge.debug("[".concat(this.getTrackId(),"] start set muted: ").concat(e)),e?await N(this,it.NEED_MUTE_TRACK,this):await N(this,it.NEED_UNMUTE_TRACK,this))}getStats(){w((()=>{ge.warning("[deprecated] LocalAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalAudioStats instead")}),"localAudioTrackGetStatsWarning");const e=te(this,it.GET_STATS);return e||Nt({},mt)}setAudioFrameCallback(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:4096;if(!e)return this._source.removeAllListeners(lt.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(t),this._source.removeAllListeners(lt.ON_AUDIO_BUFFER),this._source.on(lt.ON_AUDIO_BUFFER,(t=>e(t)))}play(){ge.debug("[".concat(this.getTrackId(),"] start audio playback")),this._useAudioElement?(ge.debug("[".concat(this.getTrackId(),"] start audio playback in element")),fi.play(this._mediaStreamTrack,this.getTrackId(),this._volume)):this._source.play()}stop(){ge.debug("[".concat(this.getTrackId(),"] stop audio playback")),this._useAudioElement?fi.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._extensionManager&&(this._extensionManager.destroy(),this._extensionManager=void 0,this._useExtensionMode=!1),this._source.destroy()}_updatePlayerSource(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];ge.debug("[".concat(this.getTrackId(),"] update player source track")),e&&this._source.updateTrack(this._mediaStreamTrack),this._useAudioElement&&fi.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 N(this,it.NEED_REPLACE_TRACK,this)):this._source.updateTrack(this._originMediaStreamTrack),this._getOriginVolumeLevel&&this._source.updateOriginTrack(e))}renewMediaStreamTrack(e){return Promise.resolve(void 0)}_ensureExtensionManager(e){return this._extensionManager||(this._extensionManager=e.createAudioExtensionManager(this),this._extensionManager.onOutputTrackChanged=e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,N(this,it.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,N(this,it.NEED_REPLACE_TRACK,this))}),this._extensionManager}useExtension(e,t){if(this._usePipeMode)throw new b(k.INVALID_OPERATION,"Cannot use useExtension() when pipe() mode is active. Call unpipe() first.");return this._ensureExtensionManager(e),this._useExtensionMode=!0,this._extensionManager.useExtension(e,t)}removeExtension(e){if(!this._extensionManager)return!1;const t=this._extensionManager.removeExtension(e);return t&&ge.info("[".concat(this.getTrackId(),"] removeExtension: ").concat(e.name)),this._extensionManager.hasExtensions||(this._useExtensionMode=!1),t}addReferenceTrack(e){if(!this._extensionManager)throw new b(k.INVALID_OPERATION,"Call useExtension() before addReferenceTrack().");this._extensionManager.addReferenceTrack(e),ge.info("[".concat(this.getTrackId(),"] addReferenceTrack"))}removeReferenceTrack(e){return!!this._extensionManager&&this._extensionManager.removeReferenceTrack(e)}pipe(e){if(this._useExtensionMode)throw new b(k.INVALID_OPERATION,"Cannot use pipe() when useExtension() mode is active. Call removeExtension() for all extensions first.");if(this._bypassWebAudio)throw new b(k.INVALID_OPERATION,"Can not process AudioTrack when bypassWebAudio set to true.");if(this.processor===e)return e;if(e._source)throw new b(k.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this._usePipeMode=!0,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,this._usePipeMode=!1,t.reset()}bindProcessorDestinationEvents(e){e.on(Et.ON_TRACK,(async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(!1),this._source.processedNode=this._source.createMediaStreamSourceNode(e),await N(this,it.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await N(this,it.NEED_REPLACE_TRACK,this))})),e.on(Et.ON_NODE,(e=>{this._source.processedNode=e}))}unbindProcessorDestinationEvents(e){e.removeAllListeners(Et.ON_TRACK),e.removeAllListeners(Et.ON_NODE)}bindProcessorContextEvents(e){e.on(vt.REQUEST_CONSTRAINTS,(async e=>{e(this._originMediaStreamTrack.getSettings())}))}unbindProcessorContextEvents(e){e.removeAllListeners(vt.REQUEST_CONSTRAINTS)}initWebAudio(){return this._trackSource instanceof ki&&(this._trackSource=new ei(this._mediaStreamTrack,!1,this._getOriginVolumeLevel?this._mediaStreamTrack:void 0)),this._trackSource}initProcessor(){const e=new bi(this._source.context,this.getTrackId(),"local"),t=new Si(e);return this._processorContext=e,this._processorDestination=t,this.bindProcessorContextEvents(e),this.bindProcessorDestinationEvents(t),this._source.on(lt.UPDATE_SOURCE,(()=>{this.processor&&this.processor.updateInput({node:this._source.processSourceNode,context:e})})),this._useAudioElement&&(this._useAudioElement=!1,this.isPlaying&&(fi.stop(this.getTrackId()),this._source.play()),N(this,it.NEED_REPLACE_MIXING_TRACK,this).then((()=>{ge.debug("[".concat(this.getTrackId(),"] replace from origin track to web audio track success"))})).catch((e=>{ge.warning("[".concat(this.getTrackId(),"] replace from origin track to web audio track failed"),e)}))),{processorContext:e,processorDestination:t}}}).prototype,"setVolume",[Gi],Object.getOwnPropertyDescriptor(or.prototype,"setVolume"),or.prototype),wt(or.prototype,"setPlaybackDevice",[Bi,Fi],Object.getOwnPropertyDescriptor(or.prototype,"setPlaybackDevice"),or.prototype),wt(or.prototype,"setEnabled",[Ki,Hi,Xi],Object.getOwnPropertyDescriptor(or.prototype,"setEnabled"),or.prototype),wt(or.prototype,"setMuted",[Yi,zi,ji],Object.getOwnPropertyDescriptor(or.prototype,"setMuted"),or.prototype),wt(or.prototype,"getStats",[Ji],Object.getOwnPropertyDescriptor(or.prototype,"getStats"),or.prototype),wt(or.prototype,"setAudioFrameCallback",[Qi],Object.getOwnPropertyDescriptor(or.prototype,"setAudioFrameCallback"),or.prototype),wt(or.prototype,"play",[qi,$i],Object.getOwnPropertyDescriptor(or.prototype,"play"),or.prototype),wt(or.prototype,"stop",[er,tr],Object.getOwnPropertyDescriptor(or.prototype,"stop"),or.prototype),wt(or.prototype,"close",[ir],Object.getOwnPropertyDescriptor(or.prototype,"close"),or.prototype),wt(or.prototype,"pipe",[rr],Object.getOwnPropertyDescriptor(or.prototype,"pipe"),or.prototype),wt(or.prototype,"unpipe",[sr],Object.getOwnPropertyDescriptor(or.prototype,"unpipe"),or.prototype),or),wr=(nr=fe({argsMap:(e,t)=>[e.getTrackId(),t]}),ar=Ei(),cr=ee("MicrophoneAudioTrack","_enabledMutex"),dr=fe({argsMap:(e,t,i)=>[e.getTrackId(),t,i]}),ur=Ei(),hr=fe({argsMap:e=>[e.getTrackId()]}),wt((lr=class extends Rr{get __className__(){return"MicrophoneAudioTrack"}constructor(e,t,i,r){super(e,t.encoderConfig?Xe(t.encoderConfig):{},r,u("GET_VOLUME_OF_MUTED_AUDIO_TRACK")),Mt(this,"_config",void 0),Mt(this,"_deviceName","default"),Mt(this,"_constraints",void 0),Mt(this,"_originalConstraints",void 0),Mt(this,"_enabled",!0),this._config=t,this._constraints=i,this._originalConstraints=i,this._deviceName=e.label,"boolean"==typeof t.bypassWebAudio&&(this._bypassWebAudio=t.bypassWebAudio),(Y()||ie())&&Zt.bindInterruptDetectorTrack(this)}async setDevice(e){if(ge.info("[".concat(this.getTrackId(),"] start set device to ").concat(e)),this._enabled)try{const t=await li.getDeviceById(e),i={};i.audio=Nt({},this._constraints),i.audio.deviceId={exact:e},this._originMediaStreamTrack.stop();let r=null;try{r=await ai(i,this.getTrackId())}catch(e){throw ge.error("[".concat(this.getTrackId(),"] setDevice failed"),e.toString()),r=await ai({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 ge.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}else try{const t=await li.getDeviceById(e);this._deviceName=t.label,this._config.microphoneId=e,this._constraints.deviceId={exact:e}}catch(e){throw ge.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}ge.info("[".concat(this.getTrackId(),"] set device to ").concat(e," success"))}async setEnabled(e,t,i){if(t)return ge.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(ge.info("[".concat(this.getTrackId(),"] start setEnabled"),e),u("AUTO_RESET_AUDIO_ROUTE")&&(P()||L())){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 N(this,it.NEED_DISABLE_TRACK,this)}catch(e){throw ge.error("[".concat(this.getTrackId(),"] setEnabled false failed"),e.toString()),e}return}const s=Nt({},this._constraints),o=li.searchDeviceIdByName(this._deviceName);o&&!s.deviceId&&(s.deviceId=o);try{i||(this._enabled=!0);const e=await ai({audio:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getAudioTracks()[0],!1),await N(this,it.NEED_ENABLE_TRACK,this)}catch(e){throw i||(this._enabled=!1),ge.error("[".concat(this.getTrackId(),"] setEnabled true failed"),e.toString()),e}ge.info("[".concat(this.getTrackId(),"] setEnabled success"))}close(){super.close(),(Y()||ie())&&Zt.unbindInterruptDetectorTrack(this),Je()||Gt()}onTrackEnded(){if((P()||L())&&this._enabled&&!this._isClosed&&Zt.duringInterruption){const e=async()=>{Zt.off(Pe.IOS_INTERRUPTION_END,e),this._enabled&&!this._isClosed&&(ge.debug("[".concat(this.getTrackId(),"] try capture microphone media device for interrupted iOS device.")),await this.setEnabled(!1),await this.setEnabled(!0))};Zt.on(Pe.IOS_INTERRUPTION_END,e)}else ge.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(dt.TRACK_ENDED)}async renewMediaStreamTrack(e){const t=e||this._constraints,i=li.searchDeviceIdByName(this._deviceName);if(i&&!t.deviceId&&(t.deviceId=i),this._constraints=t,this._enabled){this._originMediaStreamTrack.stop();const e=await ai({audio:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getAudioTracks()[0],!0)}}bindProcessorContextEvents(e){super.bindProcessorContextEvents(e),e.on(vt.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(vt.REQUEST_UPDATE_CONSTRAINTS)}}).prototype,"setDevice",[nr,ar],Object.getOwnPropertyDescriptor(lr.prototype,"setDevice"),lr.prototype),wt(lr.prototype,"setEnabled",[cr,dr,ur],Object.getOwnPropertyDescriptor(lr.prototype,"setEnabled"),lr.prototype),wt(lr.prototype,"close",[hr],Object.getOwnPropertyDescriptor(lr.prototype,"close"),lr.prototype),lr),Cr=(pr=fe({argsMap:(e,t)=>[e.getTrackId(),t,e.duration]}),mr=Ei(),gr=fe({argsMap:e=>[e.getTrackId()]}),_r=Ei(),Tr=fe({argsMap:e=>[e.getTrackId()]}),fr=Ei(),Er=fe({argsMap:e=>[e.getTrackId()]}),vr=Ei(),yr=fe({argsMap:e=>[e.getTrackId()]}),Sr=Ei(),br=fe({argsMap:e=>[e.getTrackId()]}),kr=fe({argsMap:e=>[e.getTrackId()]}),Ir=Ei(),wt((Ar=class extends Rr{get __className__(){return"BufferSourceAudioTrack"}constructor(e,t,i,r){super(t.createOutputTrack(),i,r),Mt(this,"source",void 0),Mt(this,"_bufferSource",void 0),this._useAudioElement=!1,this.source=e,this._bufferSource=t,this._bufferSource.on(lt.AUDIO_SOURCE_STATE_CHANGE,(e=>{this.safeEmit(dt.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){v(e,"speed",0),this._bufferSource.setAudioBufferPlaybackSpeed(e)}}).prototype,"startProcessAudioBuffer",[pr,mr],Object.getOwnPropertyDescriptor(Ar.prototype,"startProcessAudioBuffer"),Ar.prototype),wt(Ar.prototype,"pauseProcessAudioBuffer",[gr,_r],Object.getOwnPropertyDescriptor(Ar.prototype,"pauseProcessAudioBuffer"),Ar.prototype),wt(Ar.prototype,"seekAudioBuffer",[Tr,fr],Object.getOwnPropertyDescriptor(Ar.prototype,"seekAudioBuffer"),Ar.prototype),wt(Ar.prototype,"resumeProcessAudioBuffer",[Er,vr],Object.getOwnPropertyDescriptor(Ar.prototype,"resumeProcessAudioBuffer"),Ar.prototype),wt(Ar.prototype,"stopProcessAudioBuffer",[yr,Sr],Object.getOwnPropertyDescriptor(Ar.prototype,"stopProcessAudioBuffer"),Ar.prototype),wt(Ar.prototype,"close",[br],Object.getOwnPropertyDescriptor(Ar.prototype,"close"),Ar.prototype),wt(Ar.prototype,"setAudioBufferPlaybackSpeed",[kr,Ir],Object.getOwnPropertyDescriptor(Ar.prototype,"setAudioBufferPlaybackSpeed"),Ar.prototype),Ar);class Mr extends Rr{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=Bt().createMediaStreamDestination();super(e.stream.getAudioTracks()[0],void 0,R(8,"track-mix-")),Mt(this,"trackList",void 0),Mt(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)?(ge.debug("add ".concat(e.getTrackId()," to mixing track")),e._source.outputNode.connect(this.destNode),this.trackList.push(e),this.updateEncoderConfig()):ge.debug("track ".concat(e.getTrackId()," is already added"))}removeAudioTrack(e){if(-1!==this.trackList.indexOf(e)){ge.debug("remove ".concat(e.getTrackId()," from mixing track"));try{e._source.outputNode.disconnect(this.destNode)}catch(e){}O(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 Mr?t.emit(ct.TRANSCEIVER_UPDATED,e):t._updateRtpTransceiver(e)})))}}class Dr extends $t{set currentState(e){e!==this._currentState&&(this._currentState=e,this.safeEmit(lt.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(),Mt(this,"audioBuffer",void 0),Mt(this,"sourceNode",void 0),Mt(this,"startPlayTime",0),Mt(this,"startPlayOffset",0),Mt(this,"pausePlayTime",0),Mt(this,"options",void 0),Mt(this,"currentLoopCount",0),Mt(this,"currentPlaybackSpeed",100),Mt(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):ge.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 Nr=new Map;function Or(e,t){if(0===e.length||0===t.length)return 1/0;const i=oe(e),r=oe(t);return Math.floor(r/i)}class Pr{get rendFrameRate(){const e=Math.max(1,Or(this._render_interframe_delays_sizes,this._render_interframe_delays));return Math.floor(1e3/e)}get videoElementStatus(){return this._isInPage?this._videoElementStatus:kt.DESTROYED}set videoElementStatus(e){e!==this._videoElementStatus&&(ge.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){Mt(this,"trackId",void 0),Mt(this,"config",void 0),Mt(this,"onFirstVideoFrameDecoded",void 0),Mt(this,"onFirstVideoFrameRender",void 0),Mt(this,"onVideoBufferReady",void 0),Mt(this,"onVideoStateChanged",void 0),Mt(this,"freezeTimeCounterList",[]),Mt(this,"renderFreezeAccTime",0),Mt(this,"renderFreezeAccTime2",0),Mt(this,"totalFreezeTime",0),Mt(this,"isKeepLastFrame",!1),Mt(this,"isDestroyed",!1),Mt(this,"timeUpdatedCount",0),Mt(this,"freezeTime",0),Mt(this,"playbackTime",0),Mt(this,"lastTimeUpdatedTime",0),Mt(this,"autoplayFailed",!1),Mt(this,"videoTrack",void 0),Mt(this,"videoElement",void 0),Mt(this,"cacheVideoElement",void 0),Mt(this,"cancelRVFId",void 0),Mt(this,"internal",!1),Mt(this,"_render_interframe_delays",[]),Mt(this,"_render_interframe_delays_sizes",[]),Mt(this,"_videoState",It.VideoStateStopped),Mt(this,"videoElementCheckInterval",void 0),Mt(this,"videoElementFreezeTimeout",void 0),Mt(this,"_videoElementStatus",kt.NONE),Mt(this,"_isInPage",!0),Mt(this,"isGettingVideoDimensions",!1),Mt(this,"startGetVideoDimensions",(()=>{const e=()=>{if(this.isGettingVideoDimensions=!0,this.videoElement.videoWidth*this.videoElement.videoHeight>4)return ge.debug("[".concat(this.trackId,"] current video dimensions:"),this.videoElement.videoWidth,this.videoElement.videoHeight),void(this.isGettingVideoDimensions=!1);setTimeout(e,500)};!this.isGettingVideoDimensions&&e()})),Mt(this,"autoResumeAfterInterruption",(()=>{this.videoTrack&&"live"===this.videoTrack.readyState&&"running"===Zt.curState&&(ge.debug("[track-".concat(this.trackId,"] video element paused, auto resume for ").concat(ne())),ae()?(this.videoElement.srcObject=null,this.videoElement.srcObject=new MediaStream([this.videoTrack]),this.videoElement.play()):(this.videoElement.pause(),this.videoElement.play()))})),Mt(this,"handleVideoEvents",(e=>{switch(e.type){case"play":case"playing":"play"===e.type&&ge.debug("[".concat(this.trackId,"] video element status: play")),this.startGetVideoDimensions(),this.videoElementStatus=kt.PLAYING;break;case"loadeddata":if(this.videoState=It.VideoStateStarting,this.onFirstVideoFrameRender&&this.onFirstVideoFrameRender(),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=kt.CANPLAY;break;case"stalled":this.videoElementStatus=kt.STALLED;break;case"suspend":this.videoElementStatus=kt.SUSPEND;break;case"pause":this.videoElementStatus=kt.PAUSED,P()||L()||c()&&this.autoplayFailed||!this.videoTrack||"live"!==this.videoTrack.readyState||(ge.debug("[track-".concat(this.trackId,"] video element paused, auto resume")),this.videoElement.play());break;case"waiting":this.videoElementStatus=kt.WAITING;break;case"abort":this.videoElementStatus=kt.ABORT;break;case"ended":this.videoElementStatus=kt.ENDED;break;case"emptied":this.videoElementStatus=kt.EMPTIED;break;case"error":{const e=this.videoElement.error;e&&(this.videoElementStatus=kt.ERROR,ge.error("[".concat(this.trackId,"] media error: ").concat(e.message," (").concat(e.code,")")));break}case"timeupdate":{const e=performance.now();if(this.timeUpdatedCount+=1,this.onVideoBufferReady&&this.timeUpdatedCount>u("BUFFER_READY_FRAMES")&&this.onVideoBufferReady(),this.timeUpdatedCount<10)return void(this.lastTimeUpdatedTime=e);const t=e-this.lastTimeUpdatedTime,i=this.lastTimeUpdatedTime;if(this.lastTimeUpdatedTime=e,zs.lastVisibleTime<zs.lastHiddenTime||i<zs.lastHiddenTime||i<zs.lastVisibleTime)return;if(this.isSkipCalcRenderFreezeTime())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}}})),Mt(this,"autoResumeAfterInterruptionOnIOS15_16",(()=>{this.videoTrack&&"live"===this.videoTrack.readyState&&(ge.debug("[track-".concat(this.trackId,"] video element paused, auto resume for ").concat(ne())),ae()?(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"),Zt.on(Pe.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),Zt.on(Pe.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&&_i(t,"video",e.message,this.trackId),"NotAllowedError"===e.name?(ge.warning("detected video element autoplay failed",e),this.autoplayFailed=!0,this.handleAutoPlayFailed()):ge.warning("[".concat(this.trackId,"] play warning: "),e)}));const r=e();if(("Safari"===r.name&&15===Number(r.version)||Y())&&i&&i.then){const e=()=>{this.config.mirror&&!this.config.noStyle&&(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 ge.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 Zi(e);r({buffer:t,width:i.width,height:i.height})}else s(new b(k.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED))}),e,t<0?.1:t>1?1:t)}))):await Ui(e)}destroy(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.isDestroyed=!0,Zt.off(Pe.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),Zt.off(Pe.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16),e?this.videoElement.pause():this.videoElement.srcObject=null,this.resetVideoElement(),this.freezeTimeCounterList=[],this.videoState=It.VideoStateStopped}initVideoElement(){if(this._videoElementStatus!==kt.NONE&&this._videoElementStatus!==kt.DESTROYED||(this.videoElementStatus=kt.INIT),!this.videoElementCheckInterval&&(Lr.forEach((e=>{this.videoElement.addEventListener(e,this.handleVideoEvents)})),this.videoElementCheckInterval=window.setInterval((()=>{this._isInPage=se(this.videoElement)}),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===It.VideoStateDecoding&&("visible"===document.visibilityState?this.videoState=It.VideoStateFrozen:document.addEventListener("visibilitychange",r))},o=(t,i)=>{if(this.videoElementStatus===kt.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=oe(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===It.VideoStateStarting&&(this.videoState=It.VideoStateDecoding),this.videoState===It.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===It.VideoStateFrozen&&(this.videoState=It.VideoStateDecoding),t>u("VIDEO_FREEZE_DURATION")&&zs.lastVisibleTime>=zs.lastHiddenTime&&e.timestamp>zs.lastVisibleTime&&e.timestamp>zs.lastHiddenTime){const e=Math.min(66,Or(this._render_interframe_delays_sizes,this._render_interframe_delays)),i=Math.max(0,t-(r-1)*e),s=i>e?i:0;this.renderFreezeAccTime2+=s,this.totalFreezeTime+=s,this.renderFreezeAccTime+=t}}e=Nt(Nt({},i),{},{timestamp:t})}else this.isSkipCalcRenderFreezeTime()&&(e=Nt(Nt({},i),{},{timestamp:t}));var r,n;u("ENABLE_VIDEO_FRAME_CALLBACK")&&(this.cancelRVFId=null===(r=(n=this.videoElement).requestVideoFrameCallback)||void 0===r?void 0:r.call(n,o))};this.cancelRVFId=null===(t=(i=this.videoElement).requestVideoFrameCallback)||void 0===t?void 0:t.call(i,o)}this.videoElement.controls=!1,this.videoElement.setAttribute("playsinline",""),B()&&!u("HIDE_NO_POSTER")&&(this.videoElement.poster="noposter");const r=e();if(this.config.noStyle||("Safari"===r.name&&15===Number(r.version)||Y()||!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=>{ge.debug("[".concat(this.trackId,"] playback interrupted"),e.toString())}))}resetVideoElement(){var e,t;(Lr.forEach((e=>{this.videoElement&&this.videoElement.removeEventListener(e,this.handleVideoEvents)})),this.videoElementCheckInterval&&(window.clearInterval(this.videoElementCheckInterval),this.videoElementCheckInterval=void 0),this.cancelRVFId&&this.videoElement)&&(null===(e=(t=this.videoElement).cancelVideoFrameCallback)||void 0===e||e.call(t,this.cancelRVFId),this.cancelRVFId=void 0);this.videoElementStatus=kt.NONE}isSkipCalcRenderFreezeTime(){return this.videoElementStatus===kt.DESTROYED||this.internal}handleAutoPlayFailed(){const e=t=>{t.preventDefault(),this.videoElement.play().then((()=>{ge.debug("[".concat(this.trackId,"] Video element for trackId:").concat(this.trackId," autoplay resumed."))})).catch((e=>{ge.error(e)})),this.autoplayFailed=!1,H()?document.body.removeEventListener("click",e,!0):(document.body.removeEventListener("touchstart",e,!0),document.body.removeEventListener("mousedown",e,!0))};H()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0)),gi()}}const Lr=["play","playing","loadeddata","canplay","pause","stalled","suspend","waiting","abort","emptied","ended","timeupdate","error"];class Vr extends Pr{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];super(e),Mt(this,"container",void 0),Mt(this,"slot",void 0),this.slot=e.element,this.internal=t,this.updateConfig(e)}updateConfig(e){this.config=e,this.trackId=e.trackId;const t=e.element;var i;!this.internal||this.slot?(t!==this.slot&&(this.destroy(),this.slot=t),this.createElements()):(this.slot=t,t&&this.container?(this.internal=!1,this.container.id="agora-video-player-".concat(this.trackId),this.videoElement.id="video_".concat(this.trackId),this.config.fit?this.videoElement.style.objectFit=this.config.fit:this.videoElement.style.objectFit="cover",null===(i=this.slot)||void 0===i||i.appendChild(this.container)):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 Ui(e)}destroy(){if(super.destroy(),this.videoElement.remove(),this.videoElement=document.createElement("video"),this.container){try{var e;this.container.remove(),null===(e=this.slot)||void 0===e||e.removeChild(this.container)}catch(e){}this.container=void 0}}createElements(){var e;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(),null===(e=this.slot)||void 0===e||e.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 xr,Ur,Zr,Wr,Gr,Br,Fr,Kr,Hr,Xr,Yr,zr,jr,Jr,Qr,qr,$r,es,ts,is,rs,ss,os,ns,as,cs,ds,us,hs,ls,ps,ms,gs,_s,Ts,fs,Es,vs;let ys=(xr=fe({argsMap:(e,t,i)=>[e.getTrackId(),"string"==typeof t?t:t instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement",i]}),Ur=Ei(),Zr=fe({argsMap:e=>[e.getTrackId()]}),Wr=ee("LocalVideoTrack","_enabledMutex"),Gr=fe({argsMap:(e,t)=>[e.getTrackId(),t]}),Br=Ei(),Fr=ee("LocalVideoTrack","_enabledMutex"),Kr=fe({argsMap:(e,t)=>[e.getTrackId(),t]}),Hr=Ei(),Xr=fe({argsMap:(e,t)=>[e.getTrackId(),t,e._saveEncodeBitrateRatio]}),Yr=Ei(),zr=fe({argsMap:(e,t)=>[e.getTrackId(),t]}),jr=Ei(),Jr=Ei(),Qr=fe({argsMap:(e,t,i)=>[e.getTrackId(),t,i]}),qr=Ei(),$r=Ei(),es=Ei(),ts=fe({argsMap:e=>[e.getTrackId()]}),is=Ei(),rs=Ei(),ss=Ei(),os=Ei(),ns=Ei(),as=fe({argsMap:(e,t)=>[e.getTrackId(),t.name]}),cs=fe({argsMap:e=>[e.getTrackId()]}),ds=fe({argsMap:e=>[e.getTrackId()]}),us=fe({argsMap:(e,t,i)=>[e.getTrackId(),t.label,i]}),hs=class e extends Lt{get videoHeight(){if(c()){const e=this._mediaStreamTrack.getSettings().height;return this._videoHeight=e,this._videoHeight}return this._videoHeight}get videoWidth(){if(c()){const e=this._mediaStreamTrack.getSettings().width;return this._videoWidth=e,this._videoWidth}return this._videoWidth}get isPlaying(){return!(!this._player||this._player.videoElementStatus!==kt.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),Mt(this,"trackMediaType",ht.VIDEO),Mt(this,"_player",void 0),Mt(this,"isUseScaleResolutionDownBy",!1),Mt(this,"_videoVisibleTimer",null),Mt(this,"_previousVideoVisibleStatus",void 0),Mt(this,"_clearPreviousVideoVisibleStatus",(()=>this._previousVideoVisibleStatus=void 0)),Mt(this,"_encoderConfig",void 0),Mt(this,"_scalabilityMode",{numSpatialLayers:1,numTemporalLayers:1}),Mt(this,"_optimizationMode",void 0),Mt(this,"_saveEncodeBitrateRatio",1),Mt(this,"_videoHeight",void 0),Mt(this,"_videoWidth",void 0),Mt(this,"_forceBitrateLimit",void 0),Mt(this,"_enabled",!0),Mt(this,"_processorDestination",void 0),Mt(this,"_processorContext",void 0),Mt(this,"_usePipeMode",!1),Mt(this,"_useExtensionMode",!1),Mt(this,"_extensionManager",void 0),c()){const t=e.getSettings(),i=t.width,r=t.height;this._videoWidth=i,this._videoHeight=r}else this.updateMediaStreamTrackResolution();if(this._scalabilityMode=r,this._optimizationMode=s,this._hints=n||[],i&&-1!==this._hints.indexOf(rt.CUSTOM_TRACK)?this._encoderConfig=ce(i):this._encoderConfig=i,-1===this._hints.indexOf(rt.SCREEN_TRACK))this.updateBitrateFromProfile();else if(de(t.CHROME,115)&&ue()){const t=Wi(e);t&&(ge.info("local screen video track begin to inject frame"),this._mediaStreamTrack=t)}i&&-1!==this._hints.indexOf(rt.CUSTOM_TRACK)&&this.setEncoderConfiguration(i),this._processorContext=new yi(this.getTrackId(),"local"),this._processorDestination=new vi(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:(ge.warning("[".concat(this.getTrackId(),'] can not find "#').concat(e,'" element, use document.body')),e=document.body)}ge.debug("[".concat(this.getTrackId(),"] start video playback in ").concat(e instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement"),JSON.stringify(t));const i=Nt(Nt(Nt({},this._getDefaultPlayerConfig()),t),{},{trackId:this.getTrackId(),element:e});this._player?this._player.updateConfig(i):(e instanceof HTMLVideoElement?this._player=new Pr(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(dt.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,ge.debug("[".concat(this.getTrackId(),"] stop video playback")))}async setEnabled(e,t){if(!t){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(ge.info("[".concat(this.getTrackId(),"] start setEnabled"),e),!e){this._originMediaStreamTrack.enabled=!1;try{await N(this,it.NEED_DISABLE_TRACK,this)}catch(e){throw ge.error("[".concat(this.getTrackId(),"] setEnabled to false error"),e.toString()),e}return t||(this._enabled=!1),void ge.info("[".concat(this.getTrackId(),"] setEnabled to false success"))}this._originMediaStreamTrack.enabled=!0;try{await N(this,it.NEED_ENABLE_TRACK,this)}catch(e){throw ge.error("[".concat(this.getTrackId(),"] setEnabled to true error"),e.toString()),e}ge.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,ge.debug("[".concat(this.getTrackId(),"] start set muted: ").concat(e)),e?await N(this,it.NEED_MUTE_TRACK,this):await N(this,it.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),ge.debug("[".concat(this.getTrackId(),"] set save encode bitrate ratio, ").concat(e)),this._saveEncodeBitrateRatio=1;try{await N(this,it.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(ge)}}}async setEncoderConfiguration(e,t){if(!this._enabled)throw new b(k.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");if(e=Be(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=Ri({encoderConfig:e});(c()||P()||L())&&(t.deviceId=void 0),ge.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 b(k.UNEXPECTED_ERROR,e.toString());throw ge.error("[".concat(this.getTrackId(),"] applyConstraints error"),t.toString()),t}}this._encoderConfig=e,-1===this._hints.indexOf(rt.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await N(this,it.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(ge)}}getStats(){w((()=>{ge.warning("[deprecated] LocalVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalVideoStats instead")}),"localVideoTrackGetStatsWarning");const e=te(this,it.GET_STATS);return e||Nt({},gt)}async setBeautyEffect(e){ge.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 Ui(e)}async findClosestProfile(){const e=this.getMediaStreamTrackSettings(),t=e.width,i=e.height,r=e.frameRate,s=this._encoderConfig||{},o=s.width,n=s.height,a=s.frameRate,c=Q(this._videoWidth||t||o||0),d=Q(this._videoHeight||i||n||0),u=Oi(c,d,Q(r||a||15));if(u)return ge.debug("[".concat(this.getTrackId(),"] find closest profile, ").concat(c,"x").concat(d," => ").concat(JSON.stringify(u))),this.setEncoderConfiguration(u)}async setBitrateLimit(e){ge.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 ge.error(k.INVALID_PARAMS,"optimization mode must be motion, detail or balanced");const t=this._optimizationMode;try{this._optimizationMode=e,await N(this,it.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this)}catch(e){throw this._optimizationMode=t,ge.error("[".concat(this.getTrackId(),"] set optimization mode failed"),e.toString()),e}ge.info("[".concat(this.getTrackId(),"] set optimization mode success (").concat(e,")"))}setScalabiltyMode(e){if(1===e.numSpatialLayers&&1!==e.numTemporalLayers)return ge.error(k.INVALID_PARAMS,"scalability mode currently not supported, no SVC."),void(this._scalabilityMode={numSpatialLayers:1,numTemporalLayers:1});this._scalabilityMode=e,ge.info("[".concat(this.getTrackId(),"] set scalability mode success (").concat(e,")"))}updateMediaStreamTrackResolution(){Ai(this._originMediaStreamTrack).then((e=>{let t=Ot(e,2),i=t[0],r=t[1];this._videoHeight=r,this._videoWidth=i})).catch(j)}_updatePlayerSource(){this._player&&this._player.updateVideoTrack(this._mediaStreamTrack)}_getDefaultPlayerConfig(){return{fit:"contain"}}async setSenderConfiguration(e){if(!this._enabled)throw new b(k.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");ge.debug("[".concat(this.getTrackId(),"] setSenderConfiguration applyConstraints"),JSON.stringify(e)),e=Be(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(rt.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await N(this,it.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(ge)}}updateBitrateFromProfile(){if(!this._encoderConfig)return;const e=this.getMediaStreamTrackSettings(),t=e.width,i=e.height,r=e.frameRate;if(!t||!i||!r)return;const s=this._encoderConfig,o=s.bitrateMax,n=s.bitrateMin;if(null==n||null==o){const e=Pi(t,i,r,n,o),s=e.max,a=e.min;if(this._encoderConfig.bitrateMin=a,this._encoderConfig.bitrateMax=s,u("VIDEO_STANDARD_BITRATE_VERSION")&&null==n&&null==o){const e=Ot(Ni(t,i,r),2),s=e[0],o=e[1];this._encoderConfig.bitrateMax=s,this._encoderConfig.bitrateMin=a?Math.min(a,s):s,this._saveEncodeBitrateRatio=o,ge.debug("[".concat(this.getTrackId(),"] update new bitrate from profile, [w: ").concat(t,", h: ").concat(i,", fps: ").concat(r,"] => [brMax: ").concat(this._encoderConfig.bitrateMax,", brMin: ").concat(this._encoderConfig.bitrateMin,", save_bitrate_ratio: ").concat(this._saveEncodeBitrateRatio,"]"))}else ge.debug("[".concat(this.getTrackId(),"] update bitrate from profile, [w: ").concat(t,", h: ").concat(i,", fps: ").concat(r,"] => [brMax: ").concat(s,", brMin: ").concat(a,"]")),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},s=r.element,o=r.slot;if(this.isPlaying&&s instanceof HTMLVideoElement&&o instanceof HTMLElement){const e=he.checkOneElementVisible(s),t=Object.assign({},e);if(t.visible!==this._previousVideoVisibleStatus){this._previousVideoVisibleStatus=t.visible;const e=_e.reportApiInvoke(null,{tag:M.TRACER,name:C.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 b(k.GET_VIDEO_ELEMENT_VISIBLE_ERROR,e.message)}}async renewMediaStreamTrack(e){}_ensureVideoExtensionManager(e){return this._extensionManager||(this._extensionManager=e.createVideoExtensionManager(this),this._extensionManager.onOutputTrackChanged=e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(),N(this,it.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),N(this,it.NEED_REPLACE_TRACK,this))},this._extensionManager.onEmpty=()=>{this._useExtensionMode=!1,this._extensionManager=void 0}),this._extensionManager}useExtension(e,t){if(this._usePipeMode)throw new b(k.INVALID_OPERATION,"Cannot use useExtension() when pipe() mode is active. Call unpipe() first.");return this._ensureVideoExtensionManager(e),this._useExtensionMode=!0,this._extensionManager.useExtension(e,t)}removeExtension(e){if(!this._extensionManager)return!1;const t=this._extensionManager.removeExtension(e);return t&&ge.info("[".concat(this.getTrackId(),"] removeExtension: ").concat(e.name)),this._extensionManager.hasExtensions||(this._useExtensionMode=!1),t}pipe(e){if(this._useExtensionMode)throw new b(k.INVALID_OPERATION,"Cannot use pipe() when useExtension() mode is active. Call removeExtension() for all extensions first.");if(this.processor===e)return e;if(e._source)throw new b(k.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this._usePipeMode=!0,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,this._usePipeMode=!1,e.reset()}close(){super.close(),this.unbindProcessorDestinationEvents(),this.unbindProcessorContextEvents(),this.unpipe(),this.processorDestination._source&&this.processorDestination._source.unpipe(),this._extensionManager&&(this._extensionManager.destroy(),this._extensionManager=void 0,this._useExtensionMode=!1)}clone(t){let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],r=this._encoderConfig;t&&(r=Nt(Nt({},r),Be(t))),r=le(r);const s=R(8,"track-video-cloned-"),o=new e(i?this._mediaStreamTrack.clone():this._mediaStreamTrack,r,le(this._scalabilityMode),this._optimizationMode,s,le(this._hints));return t&&r&&o.setEncoderConfiguration(r),ge.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 b(k.INVALID_PARAMS,"track should be an instance of MediaStreamTrack");if("video"!==e.kind)throw new b(k.INVALID_PARAMS,"track should be a video MediaStreamTrack");await this._updateOriginMediaStreamTrack(e,t,!0),this.updateMediaStreamTrackResolution()}sendSeiData(e){if(w((()=>{_e.reportApiInvoke(null,{name:C.LOCAL_VIDEO_SEND_SEI_DATA,options:[],tag:M.TRACER}).onSuccess("")}),this._mediaStreamTrack.id||this.getTrackId()),!u("ENABLE_VIDEO_SEI")||!u("ENABLE_ENCODED_TRANSFORM"))return void ge.warning('To send/receive SEI, please call AgoraRTC.setParameter("ENABLE_VIDEO_SEI", true) before instantiate IAgoraRtcClient');if(e instanceof Uint8Array==!1)return new b(k.INVALID_PARAMS,"Invalid argument type, ILocalVideoTrack.sendSeiData() only accept Uint8Array argument.").throw();const t=this.getRTCRtpTransceiver();if(!t)return void ge.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||"video/h265"===r?this.safeEmit("sei-to-send",e):ge.warning("SEI is not supported by ".concat(r))}bindProcessorDestinationEvents(){this.processorDestination.on(Et.ON_TRACK,(async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(),await N(this,it.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await N(this,it.NEED_REPLACE_TRACK,this))}))}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(Et.ON_TRACK)}unbindProcessorContextEvents(){this.processorContext.removeAllListeners(vt.REQUEST_UPDATE_CONSTRAINTS),this.processorContext.removeAllListeners(vt.REQUEST_CONSTRAINTS)}},wt(hs.prototype,"play",[xr,Ur],Object.getOwnPropertyDescriptor(hs.prototype,"play"),hs.prototype),wt(hs.prototype,"stop",[Zr],Object.getOwnPropertyDescriptor(hs.prototype,"stop"),hs.prototype),wt(hs.prototype,"setEnabled",[Wr,Gr,Br],Object.getOwnPropertyDescriptor(hs.prototype,"setEnabled"),hs.prototype),wt(hs.prototype,"setMuted",[Fr,Kr,Hr],Object.getOwnPropertyDescriptor(hs.prototype,"setMuted"),hs.prototype),wt(hs.prototype,"setSaveEncodeBitrateRatio",[Xr,Yr],Object.getOwnPropertyDescriptor(hs.prototype,"setSaveEncodeBitrateRatio"),hs.prototype),wt(hs.prototype,"setEncoderConfiguration",[zr,jr],Object.getOwnPropertyDescriptor(hs.prototype,"setEncoderConfiguration"),hs.prototype),wt(hs.prototype,"getStats",[Jr],Object.getOwnPropertyDescriptor(hs.prototype,"getStats"),hs.prototype),wt(hs.prototype,"setBeautyEffect",[Qr,qr],Object.getOwnPropertyDescriptor(hs.prototype,"setBeautyEffect"),hs.prototype),wt(hs.prototype,"getCurrentFrameData",[$r],Object.getOwnPropertyDescriptor(hs.prototype,"getCurrentFrameData"),hs.prototype),wt(hs.prototype,"getCurrentFrameImage",[es],Object.getOwnPropertyDescriptor(hs.prototype,"getCurrentFrameImage"),hs.prototype),wt(hs.prototype,"findClosestProfile",[ts,is],Object.getOwnPropertyDescriptor(hs.prototype,"findClosestProfile"),hs.prototype),wt(hs.prototype,"setBitrateLimit",[rs],Object.getOwnPropertyDescriptor(hs.prototype,"setBitrateLimit"),hs.prototype),wt(hs.prototype,"setOptimizationMode",[ss],Object.getOwnPropertyDescriptor(hs.prototype,"setOptimizationMode"),hs.prototype),wt(hs.prototype,"setScalabiltyMode",[os],Object.getOwnPropertyDescriptor(hs.prototype,"setScalabiltyMode"),hs.prototype),wt(hs.prototype,"updateMediaStreamTrackResolution",[ns],Object.getOwnPropertyDescriptor(hs.prototype,"updateMediaStreamTrackResolution"),hs.prototype),wt(hs.prototype,"pipe",[as],Object.getOwnPropertyDescriptor(hs.prototype,"pipe"),hs.prototype),wt(hs.prototype,"unpipe",[cs],Object.getOwnPropertyDescriptor(hs.prototype,"unpipe"),hs.prototype),wt(hs.prototype,"close",[ds],Object.getOwnPropertyDescriptor(hs.prototype,"close"),hs.prototype),wt(hs.prototype,"replaceTrack",[us],Object.getOwnPropertyDescriptor(hs.prototype,"replaceTrack"),hs.prototype),hs),Ss=(ls=fe({argsMap:(e,t)=>[e.getTrackId(),t]}),ps=Ei(),ms=ee("CameraVideoTrack","_enabledMutex"),gs=fe({argsMap:(e,t)=>[e.getTrackId(),t]}),_s=Ei(),Ts=fe({argsMap:(e,t)=>[e.getTrackId(),t]}),fs=Ei(),Es=fe({argsMap:e=>[e.getTrackId()]}),vs=class e extends ys{get __className__(){return"CameraVideoTrack"}constructor(e,t,i,r,s,o){super(e,Be(t.encoderConfig),r,s,o),Mt(this,"_config",void 0),Mt(this,"_originalConstraints",void 0),Mt(this,"_constraints",void 0),Mt(this,"_enabled",!0),Mt(this,"_deviceName","default"),Mt(this,"tryResumeVideoForIOS15_16WeChat",(async()=>{(Y()||ie())&&!pe()&&me()&&this._enabled&&!this._isClosed&&(ge.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=Be(this._config.encoderConfig),Zt.on(Pe.IOS_15_16_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),Zt.on(Pe.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(ge.info("[".concat(this.getTrackId(),"] set device to ").concat(e)),this._enabled)try{const t=await li.getDeviceById(e),i={};i.video=Nt({},this._constraints),i.video.deviceId={exact:e},i.video.facingMode=void 0,this._originMediaStreamTrack.stop();let r=null;try{r=await ai(i,this.getTrackId())}catch(e){throw ge.error("[".concat(this.getTrackId(),"] setDevice failed"),e.toString()),r=await ai({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 ge.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}else try{const t=await li.getDeviceById(e);this._deviceName=t.label,this._config.cameraId=e,this._constraints.deviceId={exact:e}}catch(e){throw ge.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}ge.info("[".concat(this.getTrackId(),"] setDevice success"))}async _setDeviceByFacingModel(e){ge.info("[".concat(this.getTrackId(),"] set facingMode ").concat(e));const t={video:Nt(Nt({},this._constraints),{},{deviceId:void 0,facingMode:{exact:e}})};if(this._enabled){this._originMediaStreamTrack.stop();let e=null;try{e=await ai(t,this.getTrackId())}catch(t){throw ge.error("[".concat(this.getTrackId(),"] setDeviceByFacingModel failed"),t.toString()),e=await ai({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=Nt({},t.video),ge.info("[".concat(this.getTrackId(),"] setDeviceByFacingModel success"))}async setEnabled(e,t){if(!t){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(ge.info("[".concat(this.getTrackId(),"] start setEnabled"),e),e){try{if(this.isExternalTrack)this._originMediaStreamTrack.enabled=!0;else{const e=await ai({video:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!1)}await N(this,it.NEED_ENABLE_TRACK,this)}catch(e){throw ge.error("[".concat(this.getTrackId(),"] setEnabled true error"),e.toString()),e}this.updateMediaStreamTrackResolution(),ge.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 N(this,it.NEED_DISABLE_TRACK,this)}catch(e){throw ge.error("[".concat(this.getTrackId(),"] setEnabled to false error"),e.toString()),e}ge.info("[".concat(this.getTrackId(),"] setEnabled to false success"))}}async setEncoderConfiguration(e,t){if(!this._enabled)throw new b(k.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");e=Be(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=ce(this._config);i.encoderConfig=e;const r=Ri(i);(c()||P()||L())&&(r.deviceId=void 0),ge.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 b(k.UNEXPECTED_ERROR,e.toString());throw ge.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(rt.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await N(this,it.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(ge)}}_getDefaultPlayerConfig(){return{mirror:!0,fit:"cover"}}onTrackEnded(){if((P()||L())&&this._enabled&&!this._isClosed&&Zt.duringInterruption){const e=async()=>{Zt.off(Pe.IOS_INTERRUPTION_END,e),this._enabled&&!this._isClosed&&(ge.debug("[".concat(this.getTrackId(),"] try capture camera media device for interrupted iOS device.")),await this.setEnabled(!1),await this.setEnabled(!0))};Zt.on(Pe.IOS_INTERRUPTION_END,e)}else ge.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(dt.TRACK_ENDED)}async renewMediaStreamTrack(e){const t=e||this._constraints,i=li.searchDeviceIdByName(this._deviceName);if(i&&!t.deviceId&&(t.deviceId={exact:i}),this._enabled){const e=await ai({video:t},this.getTrackId());this._constraints=t,await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!0),this.updateMediaStreamTrackResolution()}}close(){super.close(),Zt.off(Pe.IOS_15_16_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),Zt.off(Pe.IOS_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat)}clone(t){let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],r=this._encoderConfig;t&&(r=Nt(Nt({},r),Be(t))),r=le(r);const s=R(8,"track-cam-cloned-"),o=new e(i?this._mediaStreamTrack.clone():this._mediaStreamTrack,le(Nt(Nt({},this._config),{},{encoderConfig:r})),le(this._constraints),le(this._scalabilityMode),this._optimizationMode,s);return t&&r&&o.setEncoderConfiguration(r),ge.debug("clone track from ".concat(this.getTrackId()," to ").concat(s,", clone ").concat(i)),o}bindProcessorContextEvents(){this.processorContext.on(vt.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(vt.REQUEST_CONSTRAINTS,(async e=>{e(this._originMediaStreamTrack.getSettings())}))}},wt(vs.prototype,"setDevice",[ls,ps],Object.getOwnPropertyDescriptor(vs.prototype,"setDevice"),vs.prototype),wt(vs.prototype,"setEnabled",[ms,gs,_s],Object.getOwnPropertyDescriptor(vs.prototype,"setEnabled"),vs.prototype),wt(vs.prototype,"setEncoderConfiguration",[Ts,fs],Object.getOwnPropertyDescriptor(vs.prototype,"setEncoderConfiguration"),vs.prototype),wt(vs.prototype,"close",[Es],Object.getOwnPropertyDescriptor(vs.prototype,"close"),vs.prototype),vs);function bs(e){const t=R(8,"track-cus-"),i=_e.reportApiInvoke(null,{id:t,tag:M.TRACER,name:C.CREATE_CUSTOM_AUDIO_TRACK,options:[e]}),r=new Rr(e.mediaStreamTrack,e.encoderConfig?Xe(e.encoderConfig):{},t,!1);return ge.info("create custom audio track success with config",e,"trackId",r.getTrackId()),i.onSuccess(r.getTrackId()),r}async function ks(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const t=R(8,"track-mic-"),i=_e.reportApiInvoke(null,{id:t,tag:M.TRACER,name:C.CREATE_MIC_AUDIO_TRACK,options:[e]}),r=Di(e);let s=null;ge.info("start create microphone audio track with config",JSON.stringify(e),"trackId",t);try{s=(await ai({audio:r},t)).getAudioTracks()[0]||null}catch(e){throw i.onError(e),e}if(!s){const e=new b(k.UNEXPECTED_ERROR,"can not find track in media stream");return i.onError(e),e.throw(ge)}const o=new wr(s,e,r,t);return i.onSuccess(o.getTrackId()),ge.info("create microphone audio track success, trackId:",t),o}async function Is(e){var t;const i=e.cacheOnlineFile,r=e.encoderConfig;let s=e.source;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=R(8,"track-buf-"),a=_e.reportApiInvoke(null,{id:n,tag:M.TRACER,name:C.CREATE_BUFFER_AUDIO_TRACK,options:[o]});if(u("DISABLE_WEBAUDIO"))throw new b(k.NOT_SUPPORTED,"can not create BufferSourceAudioTrack when WebAudio disabled");ge.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=Nr.get(e);if(t)return ge.debug("use cached audio resource: ",e),t;try{i=(await re((()=>Ee.get(e,{responseType:"arraybuffer"})),void 0,void 0,{maxRetryCount:3})).data}catch(e){throw new b(k.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 b(k.READ_LOCAL_AUDIO_FILE_ERROR))},r.onerror=()=>{i(new b(k.READ_LOCAL_AUDIO_FILE_ERROR))},r.readAsArrayBuffer(e)}));i=await t}const r=await Ht(i);return"string"==typeof e&&t&&Nr.set(e,r),r}(s,i)}catch(e){return a.onError(e),e.throw(ge)}const d=new Dr(s),h=new Cr(c,d,r?Xe(r):{},n);return ge.info("create buffer source audio track success, trackId:",n),a.onSuccess(h.getTrackId()),h}function As(e){const t=new Mr;return e.forEach((e=>t.addAudioTrack(e))),t}function Rs(e){const t=R(8,"track-cus-"),i=_e.reportApiInvoke(null,{id:t,tag:M.TRACER,name:C.CREATE_CUSTOM_VIDEO_TRACK,options:[e]});u("USE_STANDARD_BITRATE_DEFAULT")&&(delete e.bitrateMax,delete e.bitrateMin);const r=new ys(e.mediaStreamTrack,{width:e.width,height:e.height,frameRate:e.frameRate,bitrateMax:e.bitrateMax,bitrateMin:e.bitrateMin,minDownscaleWidth:e.minDownscaleWidth,minDownscaleHeight:e.minDownscaleHeight},e.scalabiltyMode?Ke(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,t,[rt.CUSTOM_TRACK]);return i.onSuccess(r.getTrackId()),ge.info("create custom video track success with config",e,"trackId",r.getTrackId()),r}async function ws(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const t=u("CAMERA_CAPTURE_CONFIG"),i=R(8,"track-cam-"),r=_e.reportApiInvoke(null,{id:i,tag:M.TRACER,name:C.CREATE_CAM_VIDEO_TRACK,options:[Nt({},e),t]});t&&(e.encoderConfig=t);const s=Ri(e);let o=null;ge.info("start create camera video track with config",JSON.stringify(e),"trackId",i);try{o=(await ai({video:s},i)).getVideoTracks()[0]||null}catch(e){throw r.onError(e),e}if(!o){const e=new b(k.UNEXPECTED_ERROR,"can not find track in media stream");return r.onError(e),e.throw(ge)}if(e.optimizationMode&&Ds(i,o,e,Be(e.encoderConfig)),u("USE_STANDARD_BITRATE_DEFAULT")){const t=Be(e.encoderConfig);e.encoderConfig=t,delete t.bitrateMax,delete t.bitrateMin}const n=new Ss(o,e,s,e.scalabiltyMode?Ke(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,i);return r.onSuccess(n.getTrackId()),ge.info("create camera video success, trackId:",i),n}async function Cs(){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=R(8,"track-mic-"),s=R(8,"track-cam-"),o=_e.reportApiInvoke(null,{id:"".concat(r,"-").concat(s),tag:M.TRACER,name:C.CREATE_MIC_AND_CAM_TRACKS,options:[e,t,i]});i&&(t.encoderConfig=i);const n=Ri(t),a=Di(e);let c=null,d=null;ge.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 ai({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 b(k.UNEXPECTED_ERROR,"can not find tracks in media stream");return o.onError(e),e.throw(ge)}if(t.optimizationMode&&Ds(s,d,t,Be(t.encoderConfig)),u("USE_STANDARD_BITRATE_DEFAULT")){const e=Be(t.encoderConfig);t.encoderConfig=e,delete e.bitrateMax,delete e.bitrateMin}const h=new wr(c,e,a,r),l=new Ss(d,t,n,t.scalabiltyMode?Ke(t.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},t.optimizationMode,s);return o.onSuccess([h.getTrackId(),l.getTrackId()]),ge.info("create camera video track(".concat(s,") and microphone audio track(").concat(r,") success")),[h,l]}async function Ms(){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?Mi(t):void 0;i&&(t="auto");const r=R(8,"track-scr-v-"),s=_e.reportApiInvoke(null,{id:r,tag:M.TRACER,name:C.CREATE_SCREEN_VIDEO_TRACK,options:[Nt({},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=wi(e);let n=null,a=null;const c=Se();if(!c.supportShareAudio&&"enable"===t){const e=new b(k.NOT_SUPPORTED,"your browser or platform is not support share-screen with audio");return s.onError(e),e.throw(ge)}ge.info("start create screen video track with config",e,"withAudio",t,"trackId",r);const d=c.supportShareAudio&&"disable"!==t;try{const e=await ai({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 b(k.UNEXPECTED_ERROR,"can not find track in media stream");return s.onError(e),e.throw(ge)}if(!a&&"enable"===t){n&&n.stop();const e=new b(k.SHARE_AUDIO_NOT_ALLOWED);return s.onError(e),e.throw(ge)}if(e.optimizationMode||(e.optimizationMode="detail"),e.optimizationMode){Ds(r,n,e,e.encoderConfig&&Fe(e.encoderConfig)||void 0),e.encoderConfig&&"string"!=typeof e.encoderConfig&&(e.encoderConfig.bitrateMin=e.encoderConfig.bitrateMax)}const u=new ys(n,e.encoderConfig?Fe(e.encoderConfig):{},e.scalabiltyMode?Ke(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,r,[rt.SCREEN_TRACK]);if(!a)return s.onSuccess(u.getTrackId()),ge.info("create screen video track success","video:",u.getTrackId()),u;const h=new Rr(a,void 0,R(8,"track-scr-a-"),!1);return s.onSuccess([u.getTrackId(),h.getTrackId()]),ge.info("create screen video track success","video:",u.getTrackId(),"audio:",h.getTrackId()),[u,h]}function Ds(e,t,i,r){i.optimizationMode&&(r&&r.width&&r.height?(i.encoderConfig=Nt(Nt({},r),{},{bitrateMin:r.bitrateMin,bitrateMax:r.bitrateMax}),"motion"!==i.optimizationMode&&"detail"!==i.optimizationMode||(t.contentHint=i.optimizationMode,t.contentHint===i.optimizationMode?ge.debug("[".concat(e,"] set content hint to"),i.optimizationMode):ge.debug("[".concat(e,"] set content hint failed")))):ge.warning("[".concat(e,"] can not apply optimization mode bitrate config, no encoderConfig")))}var Ns,Os,Ps,Ls,Vs,xs,Us,Zs,Ws,Gs,Bs,Fs,Ks;class Hs extends Pt{getUserId(){return this._userId}constructor(e,t,i,r){super(e,"track-".concat(e.kind,"-").concat(t,"-").concat(r.clientId,"_").concat(R(5,""))),Mt(this,"_userId",void 0),Mt(this,"_uintId",void 0),Mt(this,"_isDestroyed",!1),Mt(this,"store",void 0),Mt(this,"processor",void 0),Mt(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,ge.info("[".concat(this.getTrackId(),"] is destroyed")),this.stop(),super.close()}getProcessorStats(){return this.processorContext.gatherStats()}getProcessorUsage(){return this.processorContext.gatherUsage()}}let Xs=(Ns=fe({argsMap:(e,t,i)=>[e.getTrackId(),"string"==typeof t?t:t instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement",i]}),Os=fe({argsMap:e=>[e.getTrackId()]}),Ps=fe({argsMap:(e,t)=>[e.getTrackId(),t.name]}),Ls=fe({argsMap:e=>[e.getTrackId()]}),wt((Vs=class extends Hs{get isPlaying(){return!(!this._player||this._player.videoElementStatus!==kt.PLAYING)}get __className__(){return"RemoteVideoTrack"}constructor(e,t,i,r,s){super(e,t,i,r),Mt(this,"_videoVisibleTimer",null),Mt(this,"_previousVideoVisibleStatus",void 0),Mt(this,"_clearPreviousVideoVisibleStatus",(()=>this._previousVideoVisibleStatus=void 0)),Mt(this,"trackMediaType",ht.VIDEO),Mt(this,"_videoWidth",void 0),Mt(this,"_videoHeight",void 0),Mt(this,"_player",void 0),Mt(this,"_prePlayer",void 0),Mt(this,"processorDestination",void 0),Mt(this,"processorContext",void 0),Mt(this,"_usePipeMode",!1),Mt(this,"_useExtensionMode",!1),Mt(this,"_extensionManager",void 0),this._prePlayer=s,this.updateMediaStreamTrackResolution(),this.processorContext=new yi(this.getTrackId(),"remote"),this.processorDestination=new vi(this.processorContext),this.bindProcessorDestinationEvents()}getStats(){w((()=>{ge.warning("[deprecated] RemoteVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteVideoStats instead")}),"remoteVideoTrackGetStatsWarning");return te(this,it.GET_STATS)||Nt({},ft)}play(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.safeEmit(ut.PLAY_START),"string"==typeof e){const t=document.getElementById(e);t?e=t:(ge.warning("[".concat(this.getTrackId(),'] can not find "#').concat(e,'" element, use document.body')),e=document.body)}ge.debug("[".concat(this.getTrackId(),"] start video playback in ").concat(e instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement"),JSON.stringify(t));const i=Nt(Nt({fit:"cover"},t),{},{trackId:this.getTrackId(),element:e});if(this._player)this._player.updateConfig(i);else{let t=!1,r=!1;const s=this._prePlayer&&!this._prePlayer.isDestroyed&&e===this._prePlayer.config.element;this._prePlayer&&!s&&(this._prePlayer.destroy(),r=!0),s?(this._player=this._prePlayer,t=this._player.videoState>0,this._player.updateConfig(i)):this._player=e instanceof HTMLVideoElement?new Pr(i):new Vr(i),this._prePlayer=void 0,this._player.updateVideoTrack(this._mediaStreamTrack),this._player.onFirstVideoFrameDecoded=()=>{this.store.subscribe(this.getUserId(),"video",void 0,void 0,Date.now()),this.safeEmit(ut.FIRST_FRAME_DECODED),r&&this.safeEmit(ut.FIRST_FRAME_RENDER)},this._player.onVideoStateChanged=e=>{this.safeEmit(ut.VIDEO_STATE_CHANGED,e)},t&&(this._player.onFirstVideoFrameDecoded(),this._player.onVideoStateChanged(this._player.videoState))}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(ut.VIDEO_ELEMENT_VISIBLE_STATUS,e)}catch(e){}}),u("CHECK_VIDEO_VISIBLE_INTERVAL")),this.safeEmit(ut.PLAY_END)}stop(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this._player&&(this._videoVisibleTimer&&(window.clearInterval(this._videoVisibleTimer),this._videoVisibleTimer=null),this._clearPreviousVideoVisibleStatus(),this._player.destroy(e),this._player=void 0,ge.debug("[".concat(this.getTrackId(),"] stop video playback")))}getCurrentFrameData(){return this._player?this._player.getCurrentFrame():new ImageData(2,2)}updateMediaStreamTrackResolution(){Ai(this._originMediaStreamTrack).then((e=>{let t=Ot(e,2),i=t[0],r=t[1];this._videoHeight=r,this._videoWidth=i})).catch(j)}_updatePlayerSource(){ge.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},s=r.element,o=r.slot;if(this.isPlaying&&s instanceof HTMLVideoElement&&o instanceof HTMLElement){const e=he.checkOneElementVisible(s),t=Object.assign({},e);if(t.visible!==this._previousVideoVisibleStatus){this._previousVideoVisibleStatus=t.visible;const e=_e.reportApiInvoke(null,{tag:M.TRACER,name:C.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 b(k.GET_VIDEO_ELEMENT_VISIBLE_ERROR,e.message)}}_ensureVideoExtensionManager(e){return this._extensionManager||(this._extensionManager=e.createVideoExtensionManager(this),this._extensionManager.onOutputTrackChanged=e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource()):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource())},this._extensionManager.onEmpty=()=>{this._useExtensionMode=!1,this._extensionManager=void 0}),this._extensionManager}useExtension(e,t){if(this._usePipeMode)throw new b(k.INVALID_OPERATION,"Cannot use useExtension() when pipe() mode is active. Call unpipe() first.");return this._ensureVideoExtensionManager(e),this._useExtensionMode=!0,this._extensionManager.useExtension(e,t)}removeExtension(e){if(!this._extensionManager)return!1;const t=this._extensionManager.removeExtension(e);return t&&ge.info("[".concat(this.getTrackId(),"] removeExtension: ").concat(e.name)),this._extensionManager.hasExtensions||(this._useExtensionMode=!1),t}pipe(e){if(this._useExtensionMode)throw new b(k.INVALID_OPERATION,"Cannot use pipe() when useExtension() mode is active. Call removeExtension() for all extensions first.");if(this.processor===e)return e;if(e._source)throw new b(k.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this._usePipeMode=!0,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,this._usePipeMode=!1,e.reset()}bindProcessorDestinationEvents(){this.processorDestination.on(Et.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(Et.ON_TRACK)}_destroy(){this._prePlayer&&(this._prePlayer.destroy(),this._prePlayer=void 0),this._extensionManager&&(this._extensionManager.destroy(),this._extensionManager=void 0,this._useExtensionMode=!1),super._destroy(),this.unbindProcessorDestinationEvents()}_onSei(e,t){this.emit(ct.SEI_RECEIVED,e,t)}}).prototype,"play",[Ns],Object.getOwnPropertyDescriptor(Vs.prototype,"play"),Vs.prototype),wt(Vs.prototype,"stop",[Os],Object.getOwnPropertyDescriptor(Vs.prototype,"stop"),Vs.prototype),wt(Vs.prototype,"pipe",[Ps],Object.getOwnPropertyDescriptor(Vs.prototype,"pipe"),Vs.prototype),wt(Vs.prototype,"unpipe",[Ls],Object.getOwnPropertyDescriptor(Vs.prototype,"unpipe"),Vs.prototype),Vs),Ys=(xs=fe({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),Us=fe({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),Zs=fe({argsMap:(e,t)=>[e.getTrackId(),t]}),Ws=fe({argsMap:e=>[e.getTrackId()]}),Gs=fe({argsMap:e=>[e.getTrackId()]}),Bs=fe({argsMap:(e,t)=>[e.getTrackId(),t.name]}),Fs=fe({argsMap:e=>[e.getTrackId()]}),wt((Ks=class extends Hs{get isPlaying(){return this._useAudioElement?fi.isPlaying(this.getTrackId()):this._source.isPlayed}get __className__(){return"RemoteAudioTrack"}constructor(e,t,i,r){super(e,t,i,r),Mt(this,"trackMediaType",ht.AUDIO),Mt(this,"_source",void 0),Mt(this,"_useAudioElement",!0),Mt(this,"_volume",100),Mt(this,"processorContext",void 0),Mt(this,"processorDestination",void 0),Mt(this,"_usePipeMode",!1),Mt(this,"_useExtensionMode",!1),Mt(this,"_extensionManager",void 0),Mt(this,"_played",!1),Mt(this,"_bypassWebAudio",!1),u("DISABLE_WEBAUDIO")?(this._source=new ki,this._bypassWebAudio=!0,this._useAudioElement=!0):(this._source=new ei(e,!0),u("REMOTE_AUDIO_TRACK_USES_WEB_AUDIO")&&(this._useAudioElement=!1)),this._source.once(lt.RECEIVE_TRACK_BUFFER,(()=>{this.safeEmit(ut.FIRST_FRAME_DECODED)})),this.processorContext=new bi(this._source.context,this.getTrackId(),"remote"),this.processorDestination=new Si(this.processorContext),this.bindProcessorDestinationEvents(),this._source.on(lt.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(lt.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(t),this._source.removeAllListeners(lt.ON_AUDIO_BUFFER),this._source.on(lt.ON_AUDIO_BUFFER,(t=>e(t)))}setVolume(e){this._volume=e,this._useAudioElement?fi.setVolume(this.getTrackId(),e):this._source.setVolume(e/100)}setAmplifiedVolume(e){this._useAudioElement&&this._played&&(fi.stop(this.getTrackId()),this._source.play()),this._useAudioElement=!1,e=Math.min(e,u("MAX_WEBAUDIO_VOLUME")),this._volume=e,this._source.setVolume(e/100)}async setPlaybackDevice(e){if(!this._useAudioElement||!be())throw new b(k.NOT_SUPPORTED,"your browser does not support setting the audio output device");await fi.setSinkID(this.getTrackId(),e)}getVolumeLevel(){return this._source.getAccurateVolumeLevel()}getVolume(){return this._useAudioElement?fi.getVolume(this.getTrackId()):this._source instanceof ei?this._source.getAudioVolume():0}getStats(){w((()=>{ge.warning("[deprecated] RemoteAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteAudioStats instead")}),"remoteAudioTrackGetStatsWarning");return te(this,it.GET_STATS)||Nt({},_t)}play(){if(ge.debug("[".concat(this.getTrackId(),"] start audio playback")),this._played=!0,this._useAudioElement)ge.debug("[".concat(this.getTrackId(),"] use audio element to play")),fi.play(this._mediaStreamTrack,this.getTrackId(),this._volume,this.store.sessionId||void 0);else{var e;ge.debug("[".concat(this.getTrackId(),"] use audio context to play"));const t=null===(e=this._source.context)||void 0===e?void 0:e.state;t&&"running"!==t&&_i(this.store.sessionId||null,"audio","AudioContext state is ".concat(t),this.getTrackId()),this._source.play()}}stop(){ge.debug("[".concat(this.getTrackId(),"] stop audio playback")),this._played=!1,this._useAudioElement?fi.stop(this.getTrackId()):this._source.stop()}_reusePreAudioElement(e,t){this._played=t,this._useAudioElement?(fi.reuseTrackId(e,this.getTrackId()),this._updatePlayerSource()):(fi.stop(e),this._updatePlayerSource(),t&&this._source.play()),this.setVolume(this._volume)}_destroy(){super._destroy(),this._played=!1,this._extensionManager&&(this._extensionManager.destroy(),this._extensionManager=void 0,this._useExtensionMode=!1),this.unbindProcessorDestinationEvents(),this._source.destroy()}_isFreeze(){return this._source.isFreeze}_updatePlayerSource(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];ge.debug("[".concat(this.getTrackId(),"] update player source track")),e&&this._source.updateTrack(this._mediaStreamTrack),this._useAudioElement&&fi.updateTrack(this.getTrackId(),this._mediaStreamTrack)}_ensureAudioExtensionManager(e){return this._extensionManager||(this._extensionManager=e.createAudioExtensionManager(this),this._extensionManager.onOutputTrackChanged=e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(!1)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource())}),this._extensionManager}useExtension(e){if(this._usePipeMode)throw new b(k.INVALID_OPERATION,"Cannot use useExtension() when pipe() mode is active. Call unpipe() first.");return this._ensureAudioExtensionManager(e),this._useExtensionMode=!0,this._extensionManager.useExtension(e)}removeExtension(e){if(!this._extensionManager)return!1;const t=this._extensionManager.removeExtension(e);return t&&ge.info("[".concat(this.getTrackId(),"] removeExtension: ").concat(e.name)),this._extensionManager.hasExtensions||(this._useExtensionMode=!1),t}addReferenceTrack(e){if(!this._extensionManager)throw new b(k.INVALID_OPERATION,"Call useExtension() before addReferenceTrack().");this._extensionManager.addReferenceTrack(e),ge.info("[".concat(this.getTrackId(),"] addReferenceTrack"))}removeReferenceTrack(e){return!!this._extensionManager&&this._extensionManager.removeReferenceTrack(e)}pipe(e){if(this._useExtensionMode)throw new b(k.INVALID_OPERATION,"Cannot use pipe() when useExtension() mode is active.");if(this._bypassWebAudio)throw new b(k.NOT_SUPPORTED,"can not pipe extension when WebAudio disabled");if(this.processor===e)return e;if(e._source)throw new b(k.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this._usePipeMode=!0,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 b(k.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,this._usePipeMode=!1,t.reset()}bindProcessorDestinationEvents(){this.processorDestination.on(Et.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(Et.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(Et.ON_TRACK),this.processorDestination.removeAllListeners(Et.ON_NODE)}}).prototype,"setVolume",[xs],Object.getOwnPropertyDescriptor(Ks.prototype,"setVolume"),Ks.prototype),wt(Ks.prototype,"setAmplifiedVolume",[Us],Object.getOwnPropertyDescriptor(Ks.prototype,"setAmplifiedVolume"),Ks.prototype),wt(Ks.prototype,"setPlaybackDevice",[Zs],Object.getOwnPropertyDescriptor(Ks.prototype,"setPlaybackDevice"),Ks.prototype),wt(Ks.prototype,"play",[Ws],Object.getOwnPropertyDescriptor(Ks.prototype,"play"),Ks.prototype),wt(Ks.prototype,"stop",[Gs],Object.getOwnPropertyDescriptor(Ks.prototype,"stop"),Ks.prototype),wt(Ks.prototype,"pipe",[Bs],Object.getOwnPropertyDescriptor(Ks.prototype,"pipe"),Ks.prototype),wt(Ks.prototype,"unpipe",[Fs],Object.getOwnPropertyDescriptor(Ks.prototype,"unpipe"),Ks.prototype),Ks);const zs=new class extends A{get visibility(){return document.visibilityState}get lastHiddenTime(){return this._lastHiddenTime}get lastVisibleTime(){return this._lastVisibleTime}constructor(){super(),Mt(this,"_lastHiddenTime",0),Mt(this,"_lastVisibleTime",0),Mt(this,"needUploadStats",[]),Mt(this,"isCollectingStats",!1),document.addEventListener("visibilitychange",(()=>{"hidden"===document.visibilityState?this._lastHiddenTime=performance.now():this._lastVisibleTime=performance.now(),this.isCollectingStats&&this.needUploadStats.push("visible"===document.visibilityState?1:0),ge.debug("current web page is ".concat(document.visibilityState)),this.emit("VISIBILITY_CHANGE",document.visibilityState)}))}startCollectStats(){this.isCollectingStats=!0,this.needUploadStats.push("visible"===this.visibility?1:0)}stopCollectStats(){this.isCollectingStats=!1,this.needUploadStats.length=0}};class js extends A{constructor(e,t){super(),Mt(this,"trackMediaType",ht.DATA),Mt(this,"_version",1),Mt(this,"_type",3),Mt(this,"_config",void 0),Mt(this,"_originDataChannel",void 0),Mt(this,"_dataStreamPacketHeader",new ArrayBuffer(4)),Mt(this,"_dataStreamPacketHandler",{serialize:e=>e,deserialize:e=>e}),Mt(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 b(k.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 b(k.DATACHANNEL_CONNECTION_TIMEOUT)}}else t(new b(k.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),[Rt.OPEN,Rt.CLOSE,Rt.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=Ot(t,2),r=i[0],s=i[1];e.removeEventListener(r,s)})),this._datachannelEventMap.clear()}}class Js extends js{constructor(e){super(e),Mt(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")&&ge.debug("invalid datachannel id: ".concat(i," !== ").concat(this.id)));let r=e.data.slice(this._dataStreamPacketHeader.byteLength);r=this._dataStreamPacketHandler.deserialize(r),this.emit(Rt.MESSAGE,r)}}_updateDataChannelConfig(e){this._config=e}_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 Qs extends js{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 qs(){const e=new Blob([atob("ZnVuY3Rpb24gdCh0LGUsbil7cmV0dXJuKGU9ZnVuY3Rpb24odCl7dmFyIGU9ZnVuY3Rpb24odCxlKXtpZigib2JqZWN0IiE9dHlwZW9mIHR8fCF0KXJldHVybiB0O3ZhciBuPXRbU3ltYm9sLnRvUHJpbWl0aXZlXTtpZih2b2lkIDAhPT1uKXt2YXIgcj1uLmNhbGwodCxlfHwiZGVmYXVsdCIpO2lmKCJvYmplY3QiIT10eXBlb2YgcilyZXR1cm4gcjt0aHJvdyBuZXcgVHlwZUVycm9yKCJAQHRvUHJpbWl0aXZlIG11c3QgcmV0dXJuIGEgcHJpbWl0aXZlIHZhbHVlLiIpfXJldHVybigic3RyaW5nIj09PWU/U3RyaW5nOk51bWJlcikodCl9KHQsInN0cmluZyIpO3JldHVybiJzeW1ib2wiPT10eXBlb2YgZT9lOmUrIiJ9KGUpKWluIHQ/T2JqZWN0LmRlZmluZVByb3BlcnR5KHQsZSx7dmFsdWU6bixlbnVtZXJhYmxlOiEwLGNvbmZpZ3VyYWJsZTohMCx3cml0YWJsZTohMH0pOnRbZV09bix0fWZ1bmN0aW9uIGUodCxlKXt2YXIgbj1PYmplY3Qua2V5cyh0KTtpZihPYmplY3QuZ2V0T3duUHJvcGVydHlTeW1ib2xzKXt2YXIgcj1PYmplY3QuZ2V0T3duUHJvcGVydHlTeW1ib2xzKHQpO2UmJihyPXIuZmlsdGVyKChmdW5jdGlvbihlKXtyZXR1cm4gT2JqZWN0LmdldE93blByb3BlcnR5RGVzY3JpcHRvcih0LGUpLmVudW1lcmFibGV9KSkpLG4ucHVzaC5hcHBseShuLHIpfXJldHVybiBufWNvbnN0IG49InZpZGVvL2gyNjQiLHI9InZpZGVvL2gyNjUiO2Z1bmN0aW9uIGEodCxlLG4pe2NvbnN0IHI9bmV3IFVpbnQ4QXJyYXkodCxlLG4pLGE9W107bGV0IG89MDtmb3IoO2EubGVuZ3RoPG47KW8rMzxuJiYwPT09cltvXSYmMD09PXJbbysxXSYmMz09PXJbbysyXSYmKDA9PT1yW28rM118fDE9PT1yW28rM118fDI9PT1yW28rM118fDM9PT1yW28rM10pPyhhLnB1c2gocltvXSxyW28rMV0scltvKzNdKSxvKz00KTooYS5wdXNoKHJbb10pLG8rKyk7cmV0dXJuIG5ldyBVaW50OEFycmF5KGEpfWZ1bmN0aW9uIG8odCxlKXtzd2l0Y2goZSl7Y2FzZSBuOnJldHVybiBmdW5jdGlvbih0KXtjb25zdCBlPW5ldyBEYXRhVmlldyh0LmRhdGEpO2xldCBuPTA7Zm9yKDtuKzQ8dC5kYXRhLmJ5dGVMZW5ndGg7KXtpZigwPT09ZS5nZXRVaW50OChuKzApJiYwPT09ZS5nZXRVaW50OChuKzEpJiYwPT09ZS5nZXRVaW50OChuKzIpJiYxPT09ZS5nZXRVaW50OChuKzMpJiY2PT09ZS5nZXRVaW50OChuKzQpKXtsZXQgcj1uKzYsbz0wLGk9MDtmb3IoOzI1NT09PShpPWUuZ2V0VWludDgocisrKSk7KW8rPTI1NTtvKz1pO2NvbnN0IHM9YSh0LmRhdGEscixvKTtyZXR1cm4gbmV3IFVpbnQ4QXJyYXkocyl9bisrfXJldHVybiBudWxsfSh0KTtjYXNlIHI6cmV0dXJuIGZ1bmN0aW9uKHQpe2NvbnN0IGU9bmV3IERhdGFWaWV3KHQuZGF0YSk7bGV0IG49MDtmb3IoO24rNTx0LmRhdGEuYnl0ZUxlbmd0aDspe2lmKDA9PT1lLmdldFVpbnQ4KG4rMCkmJjA9PT1lLmdldFVpbnQ4KG4rMSkmJjA9PT1lLmdldFVpbnQ4KG4rMikmJjE9PT1lLmdldFVpbnQ4KG4rMykmJjc4PT09ZS5nZXRVaW50OChuKzQpJiYxPT09ZS5nZXRVaW50OChuKzUpJiYxMDE9PT1lLmdldFVpbnQ4KG4rNikpe2xldCByPW4rNyxvPTAsaT0wO2Zvcig7MjU1PT09KGk9ZS5nZXRVaW50OChyKyspKTspbys9MjU1O28rPWk7Y29uc3Qgcz1hKHQuZGF0YSxyLG8pO3JldHVybiBuZXcgVWludDhBcnJheShzKX1uKyt9cmV0dXJuIG51bGx9KHQpO2RlZmF1bHQ6cmV0dXJuIG51bGx9fWZ1bmN0aW9uIGkodCl7Y29uc3QgZT10Lmxlbmd0aCxuPVtdO2xldCByPTA7Zm9yKDtyPGU7KXIrMjxlJiYwPT09dFtyXSYmMD09PXRbcisxXSYmKDA9PT10W3IrMl18fDE9PT10W3IrMl18fDI9PT10W3IrMl18fDM9PT10W3IrMl0pPyhuLnB1c2godFtyXSx0W3IrMV0sMyx0W3IrMl0pLHIrPTMpOihuLnB1c2godFtyXSkscisrKTtyZXR1cm4gbmV3IFVpbnQ4QXJyYXkobil9ZnVuY3Rpb24gcyh0LGUsYSl7c3dpdGNoKGEpe2Nhc2UgbjpyZXR1cm4gZnVuY3Rpb24odCxlKXtjb25zdCBuPWkoZSkscj1uLmxlbmd0aCxhPU1hdGguZmxvb3Ioci8yNTUpLG89ciUyNTUscz1uZXcgVWludDhBcnJheSg2K2ErMStyKzErdC5ieXRlTGVuZ3RoKTtzWzBdPTAsc1sxXT0wLHNbMl09MCxzWzNdPTEsc1s0XT02LHNbNV09MTAxO2xldCBmPTA7Zm9yKDtmPGE7KXNbNitmXT0yNTUsZisrO3JldHVybiBzWzYrZl09byxmKysscy5zZXQobiw2K2YpLGYrPXIsc1s2K2ZdPTEyOCxmKysscy5zZXQobmV3IFVpbnQ4QXJyYXkodCksNitmKSxzLmJ1ZmZlcn0odCxlKTtjYXNlIHI6cmV0dXJuIGZ1bmN0aW9uKHQsZSl7Y29uc3Qgbj1pKGUpLHI9bi5sZW5ndGgsYT1NYXRoLmZsb29yKHIvMjU1KSxvPXIlMjU1LHM9bmV3IFVpbnQ4QXJyYXkoNythKzErcisxK3QuYnl0ZUxlbmd0aCk7c1swXT0wLHNbMV09MCxzWzJdPTAsc1szXT0xLHNbNF09Nzgsc1s1XT0xLHNbNl09MTAxO2xldCBmPTA7Zm9yKDtmPGE7KXNbNytmXT0yNTUsZisrO3JldHVybiBzWzcrZl09byxmKysscy5zZXQobiw3K2YpLGYrPXIsc1s3K2ZdPTEyOCxmKysscy5zZXQobmV3IFVpbnQ4QXJyYXkodCksNytmKSxzLmJ1ZmZlcn0odCxlKTtkZWZhdWx0OnJldHVybiBudWxsfX1mdW5jdGlvbiBmKHQpe2lmKHQubGVuZ3RoPDUpcmV0dXJuIiI7bGV0IGU9LTE7Zm9yKGxldCBuPTA7bjx0Lmxlbmd0aC0zO24rKyl7aWYoMD09PXRbbl0mJjA9PT10W24rMV0mJjE9PT10W24rMl0pe2U9bjticmVha31pZihuPHQubGVuZ3RoLTQmJjA9PT10W25dJiYwPT09dFtuKzFdJiYwPT09dFtuKzJdJiYxPT09dFtuKzNdKXtlPW47YnJlYWt9fWlmKC0xPT09ZSlyZXR1cm4iIjtjb25zdCBhPWUrKDA9PT10W2UrMl0/NDozKTtpZihhPj10Lmxlbmd0aClyZXR1cm4iIjtjb25zdCBvPXRbYV07aWYoMTI4Jm8pcmV0dXJuIiI7aWYoKG8+PjEmNjMpPj0zMilyZXR1cm4gcjtpZihhKzE8dC5sZW5ndGgpe2lmKDA9PSgyNDgmdFthKzFdKSlyZXR1cm4gcn1yZXR1cm4oMzEmbyk8PTMxP246IiJ9Y29uc3QgbD03MSx1PTEsYz0yLGc9MSxwPTI7dmFyIGQ9ZnVuY3Rpb24odCl7cmV0dXJuIHRbdC5BVURJT19MRVZFTD0xXT0iQVVESU9fTEVWRUwiLHRbdC5NRVRBREFUQT0yXT0iTUVUQURBVEEiLHRbdC5BVURJT182NF9CSVRfUFRTPTNdPSJBVURJT182NF9CSVRfUFRTIix0fShkfHx7fSk7ZnVuY3Rpb24gaCh0KXtsZXQgZT1hcmd1bWVudHMubGVuZ3RoPjEmJnZvaWQgMCE9PWFyZ3VtZW50c1sxXSYmYXJndW1lbnRzWzFdO2NvbnN0IG49dC5nZXRVaW50OCgwKTtpZihuIT09bClyZXR1cm47Y29uc3Qgcj10LmdldFVpbnQxNigxKSxhPXUrYytyLG89bmV3IFVpbnQ4QXJyYXkodC5ieXRlTGVuZ3RoLWEpO28uc2V0KG5ldyBVaW50OEFycmF5KHQuYnVmZmVyLGEsdC5ieXRlTGVuZ3RoLWEpKTtjb25zdCBpPXttOm4sdGx2TGVuOnIsdGx2OltdLGZyYW1lOm99O2xldCBzPXUrYztmb3IoO3M8YTspe2NvbnN0IG49dC5nZXRVaW50OChzKSxyPXQuZ2V0VWludDE2KHMrZyksYT1nK3A7aWYobj09PWQuQVVESU9fTEVWRUwpe2xldCBvPXQuZ2V0VWludDgocythKTtmb3IobGV0IGU9MTtlPHI7ZSsrKW89bzw8OHx0LmdldFVpbnQ4KHMrYStlKTtpLnRsdi5wdXNoKHt0YWc6bixsZW5ndGg6cix2YWx1ZTplPzEyN15vPj4xOjEyNyZvfSl9ZWxzZSBpZihuPT09ZC5NRVRBREFUQXx8bj09PWQuQVVESU9fNjRfQklUX1BUUyl7Y29uc3QgZT1uZXcgVWludDhBcnJheShyKTtmb3IobGV0IG49MDtuPHI7bisrKWVbbl09dC5nZXRVaW50OChzK2Erbik7aS50bHYucHVzaCh7dGFnOm4sbGVuZ3RoOnIsdmFsdWU6ZX0pfXMrPWErcn1yZXR1cm4gaX1zZWxmLm9ucnRjdHJhbnNmb3JtPW49Pntjb25zdCByPW4udHJhbnNmb3JtZXIsYT1bXSxpPVtdO2xldCB5PW51bGw7ci5vcHRpb25zLnBvcnQub25tZXNzYWdlPXQ9Pnt0LmRhdGEuc2VpJiZhLnB1c2godC5kYXRhLnNlaSksdC5kYXRhLm1ldGFkYXRhJiZpLnB1c2godC5kYXRhLm1ldGFkYXRhKX0sc2VsZi5wb3N0TWVzc2FnZSgic3RhcnRlZCIpO2NvbnN0IFU9ci5yZWFkYWJsZS5nZXRSZWFkZXIoKSx2PXIud3JpdGFibGUuZ2V0V3JpdGVyKCk7InNlaS1yeCI9PT1yLm9wdGlvbnMubmFtZT9mdW5jdGlvbiBuKHIpe1UucmVhZCgpLnRoZW4oKGE9PntpZighYS5kb25lKXtpZihhLnZhbHVlIGluc3RhbmNlb2YgUlRDRW5jb2RlZFZpZGVvRnJhbWUpe2NvbnN0IG49ZihuZXcgVWludDhBcnJheShhLnZhbHVlLmRhdGEpKSxpPW8oYS52YWx1ZSxuKTtpZihpJiZyLm9wdGlvbnMucG9ydC5wb3N0TWVzc2FnZSh7c2VpOmkscnRwVGltZXN0YW1wOmEudmFsdWUudGltZXN0YW1wfSksIXkpe2NvbnN0IG49YS52YWx1ZS5nZXRNZXRhZGF0YSgpfHx7fTt5PWZ1bmN0aW9uKG4pe2Zvcih2YXIgcj0xO3I8YXJndW1lbnRzLmxlbmd0aDtyKyspe3ZhciBhPW51bGwhPWFyZ3VtZW50c1tyXT9hcmd1bWVudHNbcl06e307ciUyP2UoT2JqZWN0KGEpLCEwKS5mb3JFYWNoKChmdW5jdGlvbihlKXt0KG4sZSxhW2VdKX0pKTpPYmplY3QuZ2V0T3duUHJvcGVydHlEZXNjcmlwdG9ycz9PYmplY3QuZGVmaW5lUHJvcGVydGllcyhuLE9iamVjdC5nZXRPd25Qcm9wZXJ0eURlc2NyaXB0b3JzKGEpKTplKE9iamVjdChhKSkuZm9yRWFjaCgoZnVuY3Rpb24odCl7T2JqZWN0LmRlZmluZVByb3BlcnR5KG4sdCxPYmplY3QuZ2V0T3duUHJvcGVydHlEZXNjcmlwdG9yKGEsdCkpfSkpfXJldHVybiBufSh7dHlwZTphLnZhbHVlLnR5cGUscnRwVGltZXN0YW1wOmEudmFsdWUudGltZXN0YW1wLHBheWxvYWRUeXBlOm4ucGF5bG9hZFR5cGV8fDAsc3NyYzpuLnN5bmNocm9uaXphdGlvblNvdXJjZXx8MCxsZW5ndGg6YS52YWx1ZS5kYXRhLmJ5dGVMZW5ndGh9LCJtaW1lVHlwZSJpbiBuP3ttaW1lVHlwZTpuLm1pbWVUeXBlfTp7fSksci5vcHRpb25zLnBvcnQucG9zdE1lc3NhZ2Uoe2ZpcnN0RnJhbWVJbmZvOnl9KX19di53cml0ZShhLnZhbHVlKSxyLm9wdGlvbnMucG9ydC5wb3N0TWVzc2FnZSh7dHJhbnNmb3JtZWQ6ITB9KSxuKHIpfX0pKX0ocik6InNlaS10eCI9PT1yLm9wdGlvbnMubmFtZT9mdW5jdGlvbiB0KGUpe1UucmVhZCgpLnRoZW4oKG49PntpZighbi5kb25lKXtpZihuLnZhbHVlIGluc3RhbmNlb2YgUlRDRW5jb2RlZFZpZGVvRnJhbWUpe2NvbnN0IHQ9ZihuZXcgVWludDhBcnJheShuLnZhbHVlLmRhdGEpKSxlPWEuc2hpZnQoKTtpZihlKXtjb25zdCByPXMobi52YWx1ZS5kYXRhLGUsdCk7ciYmKG4udmFsdWUuZGF0YT1yKX19di53cml0ZShuLnZhbHVlKSxlLm9wdGlvbnMucG9ydC5wb3N0TWVzc2FnZSh7dHJhbnNmb3JtZWQ6ITB9KSx0KGUpfX0pKX0ocik6ImF1ZGlvLW1ldGFkYXRhLXJ4Ij09PXIub3B0aW9ucy5uYW1lP2Z1bmN0aW9uIHQoZSl7VS5yZWFkKCkudGhlbigobj0+e2lmKCFuLmRvbmUpe2lmKG4udmFsdWUgaW5zdGFuY2VvZiBSVENFbmNvZGVkQXVkaW9GcmFtZSl7Y29uc3QgdD1uZXcgRGF0YVZpZXcobi52YWx1ZS5kYXRhKSxyPXQuZ2V0VWludDgoMCk7bGV0IGE7aWYoMCE9KDEyOCZyKSYmNzEhPT1yKXtjb25zdCBlPWZ1bmN0aW9uKHQpe2lmKHQuYnl0ZUxlbmd0aDw9MClyZXR1cm5bXTtjb25zdCBlPVtdO2xldCBuPTA7Zm9yKDtuPHQuYnl0ZUxlbmd0aDspe2NvbnN0IHI9KDEyOCZ0LmdldFVpbnQ4KG4pKT4+NyxhPTEyNyZ0LmdldFVpbnQ4KG4pO2lmKCEociYmbis0PD10LmJ5dGVMZW5ndGgpKXtuKys7YnJlYWt9e2NvbnN0IHI9dC5nZXRVaW50MzIobiwhMSksbz0oMTY3NzYxOTImcik+PjEwLGk9MTAyMyZyO2UucHVzaCh7cHQ6YSx0c19vZmZzZXQ6byxsZW5ndGg6aSxkYXRhOm5ldyBVaW50OEFycmF5fSksbis9NH19bGV0IHI9dC5ieXRlTGVuZ3RoLW47Zm9yKGNvbnN0IGEgb2YgZSl7aWYoYS5sZW5ndGg+cilyZXR1cm4gY29uc29sZS53YXJuKCJCcm9rZW4gcmVkIHBheWxvYWQiKSxbXTthLmxlbmd0aD4wJiYoYS5kYXRhPW5ldyBVaW50OEFycmF5KHQuYnVmZmVyLHQuYnl0ZU9mZnNldCtuLGEubGVuZ3RoKSxuKz1hLmxlbmd0aCxyLT1hLmxlbmd0aCl9aWYocj4wKXtjb25zdCBhPXtwdDplLmxlbmd0aD4wP2VbZS5sZW5ndGgtMV0ucHQ6MCx0c19vZmZzZXQ6MCxsZW5ndGg6cixkYXRhOm5ldyBVaW50OEFycmF5KHQuYnVmZmVyLHQuYnl0ZU9mZnNldCtuLHIpfTtlLnB1c2goYSl9cmV0dXJuIGV9KHQpO2lmKGUubGVuZ3RoPjApe2NvbnN0IHQ9ZnVuY3Rpb24odCl7bGV0IGU9MDtmb3IobGV0IG49MDtuPHQubGVuZ3RoO24rKyllKz1uPHQubGVuZ3RoLTE/NDoxLGUrPXRbbl0ubGVuZ3RoO2NvbnN0IG49bmV3IFVpbnQ4QXJyYXkoZSk7bGV0IHI9MDtmb3IobGV0IGU9MDtlPHQubGVuZ3RoO2UrKylpZihlPHQubGVuZ3RoLTEpe2NvbnN0IGE9KDIxNDc0ODM2NDh8KDEyNyZ0W2VdLnB0KTw8MjR8KDI2MjE0MyZ0W2VdLnRzX29mZnNldCk8PDEwfDEwMjMmdFtlXS5sZW5ndGgpPj4+MDtuW3IrK109YT4+MjQmMjU1LG5bcisrXT1hPj4xNiYyNTUsbltyKytdPWE+PjgmMjU1LG5bcisrXT0yNTUmYX1lbHNlIG5bcisrXT0xMjcmdFtlXS5wdDtmb3IoY29uc3QgZSBvZiB0KW4uc2V0KGUuZGF0YSxyKSxyKz1lLmxlbmd0aDtyZXR1cm4gbn0oZS5tYXAoKHQ9Pntjb25zdCBlPW5ldyBVaW50OEFycmF5KHQubGVuZ3RoKTtlLnNldCh0LmRhdGEpO2NvbnN0IG49aChuZXcgRGF0YVZpZXcoZS5idWZmZXIpKTtyZXR1cm4gbnVsbCE9biYmbi5mcmFtZSYmKHQuZGF0YT1udWxsPT1uP3ZvaWQgMDpuLmZyYW1lKSxhPW4sdH0pKSk7bi52YWx1ZS5kYXRhPXQuYnVmZmVyfX1lbHNlIGE9aCh0KSxhJiYobi52YWx1ZS5kYXRhPWEuZnJhbWUuYnVmZmVyKTtpZihhKXtsZXQgdD1hLnRsdi5maW5kKCh0PT50LnRhZz09PWQuTUVUQURBVEEpKTtpZih0JiZ0LnZhbHVlIGluc3RhbmNlb2YgVWludDhBcnJheSYmZS5vcHRpb25zLnBvcnQucG9zdE1lc3NhZ2Uoe21ldGFkYXRhOnQudmFsdWV9KSx0PWEudGx2LmZpbmQoKHQ9PnQudGFnPT09ZC5BVURJT182NF9CSVRfUFRTKSksdCYmdC52YWx1ZSBpbnN0YW5jZW9mIFVpbnQ4QXJyYXkmJjg9PXQudmFsdWUubGVuZ3RoKXtjb25zdCBuPW5ldyBEYXRhVmlldyh0LnZhbHVlLmJ1ZmZlcikuZ2V0QmlnVWludDY0KDAsITApO3QmJnQudmFsdWUgaW5zdGFuY2VvZiBVaW50OEFycmF5JiZlLm9wdGlvbnMucG9ydC5wb3N0TWVzc2FnZSh7cHRzOm59KX19fXYud3JpdGUobi52YWx1ZSksZS5vcHRpb25zLnBvcnQucG9zdE1lc3NhZ2Uoe3RyYW5zZm9ybWVkOiEwfSksdChlKX19KSl9KHIpOiJhdWRpby1tZXRhZGF0YS10eCI9PT1yLm9wdGlvbnMubmFtZSYmZnVuY3Rpb24gdChlKXtVLnJlYWQoKS50aGVuKChuPT57aWYoIW4uZG9uZSl7aWYoZS5vcHRpb25zLnBvcnQucG9zdE1lc3NhZ2Uoe2dldE1ldGFkYXRhOiEwfSksbi52YWx1ZSBpbnN0YW5jZW9mIFJUQ0VuY29kZWRBdWRpb0ZyYW1lKXtjb25zdCB0PWkuc2hpZnQoKTt0JiYobi52YWx1ZS5kYXRhPWZ1bmN0aW9uKHQsZSxuKXtjb25zdCByPW4uYnl0ZUxlbmd0aCxhPXIrZytwLG89dStjK2EsaT1uZXcgQXJyYXlCdWZmZXIodC5ieXRlTGVuZ3RoK28pLHM9bmV3IERhdGFWaWV3KGkpO3Muc2V0VWludDgoMCxsKSxzLnNldFVpbnQxNigxLGEpLHMuc2V0VWludDgoMyxlKSxzLnNldFVpbnQxNig0LHIpO2ZvcihsZXQgdD0wO3Q8cjt0Kyspcy5zZXRVaW50OCg2K3Qsblt0XSk7Y29uc3QgZj1uZXcgVWludDhBcnJheShzLmJ1ZmZlcik7cmV0dXJuIGYuc2V0KG5ldyBVaW50OEFycmF5KHQpLG8pLGYuYnVmZmVyfShuLnZhbHVlLmRhdGEsZC5BVURJT182NF9CSVRfUFRTLHQpKX12LndyaXRlKG4udmFsdWUpLGUub3B0aW9ucy5wb3J0LnBvc3RNZXNzYWdlKHt0cmFuc2Zvcm1lZDohMH0pLHQoZSl9fSkpfShyKX0sc2VsZi5wb3N0TWVzc2FnZSgicmVnaXN0ZXJlZCIpOwo=")],{type:"text/javascript"});return setTimeout((()=>URL.revokeObjectURL(e)),0),new Worker(URL.createObjectURL(e))}const $s=71,eo=1,to=2,io=1,ro=2;var so=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}(so||{});function oo(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const i=e.getUint8(0);if(i!==$s)return;const r=e.getUint16(1),s=eo+to+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=eo+to;for(;a<s;){const i=e.getUint8(a),r=e.getUint16(a+io),s=io+ro;if(i===so.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===so.METADATA||i===so.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 no=new Map;function ao(e,t){const i=t.chunk,r=t.controller,s=so.METADATA;i.data=function(e,t,i){const r=i.byteLength,s=r+io+ro,o=eo+to+s,n=new ArrayBuffer(e.byteLength+o),a=new DataView(n);a.setUint8(0,$s),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 co(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!Se().supportWebRTCEncodedTransform)return void ge.warning("browser not support audio encoded transform");if(no.has(e))return;if(!e.track)return;const i={track:e.track};if(p()){if(!e.createEncodedStreams)return void ge.warning("browser not support createEncodedStreams() API");let s=null;try{s=e.createEncodedStreams()}catch(e){return void ge.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&&(ge.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?ao(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 ge.warning("browser not support RTCRtpScriptTransform");const s=qs(),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)ge.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=no.get(e);if(t){no.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){ge.warning(e&&e.message)}}}no.set(e,i),e.track.addEventListener("ended",r)}const uo=127,ho=1e-10,lo=139/13;const po=new Map;function mo(e,t,i){const r="".concat(e,"-").concat(t,"-").concat(i);let s=0;if(po.has(r))s=po.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,po.set(r,s)}return s<ho&&(s=ho),s}function go(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=po;let _o=0;class To{constructor(e){Mt(this,"id",void 0),Mt(this,"immediates",[]),Mt(this,"lastNonSilence",-1),Mt(this,"immediateSpeechActivityScore",ho),Mt(this,"lastLevelChangedTime",Date.now()),Mt(this,"levels",[]),Mt(this,"longs",[]),Mt(this,"longSpeechActivityScore",ho),Mt(this,"mediums",[]),Mt(this,"mediumSpeechActivityScore",ho),Mt(this,"minLevel",0),Mt(this,"nextMinLevel",0),Mt(this,"nextMinLevelWindowLength",0),Mt(this,"energyScore",0),this.id=e||"".concat(_o++),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+lo;let r=!1;for(let s=0;s<e.length;++s){let o=t[s];o<i&&(o=0);const n=Math.floor(o/lo);e[s]!==n&&(e[s]=n,r=!0)}return r}computeLongs(){return go(this.mediums,this.longs,4)}computeMediums(){return go(this.immediates,this.mediums,7)}evaluateImmediateSpeechActivityScore(){this.immediateSpeechActivityScore=mo(this.immediates[0],13,.78)}evaluateLongSpeechActivityScore(e){this.longSpeechActivityScore=mo(this.longs[0],10,47),this.longSpeechActivityScore>ho&&(this.lastNonSilence=e)}evaluateMediumSpeechActivityScore(){this.mediumSpeechActivityScore=mo(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>uo&&(i=uo),this.levels.unshift(i),this.levels.length>this.immediates.length&&this.levels.pop(),this.updateMinLevel(i),i>=this.minLevel+lo?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>uo&&(e=uo),this.minLevel=e,this.nextMinLevel=0,this.nextMinLevelWindowLength=0}}}}class fo{constructor(e){Mt(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){Mt(this,"isDominant",void 0),Mt(this,"energyRanking",void 0),Mt(this,"energyScore",void 0),this.isDominant=e,this.energyRanking=t,this.energyScore=i}}class vo extends A{constructor(e){super(),Mt(this,"dominantId",null),Mt(this,"lastDecisionTime",0),Mt(this,"lastLevelChangedTime",0),Mt(this,"lastLevelIdleTime",0),Mt(this,"relativeSpeechActivities",[]),Mt(this,"speakers",new Map),Mt(this,"enableSilence",!1),Mt(this,"timeoutToSilenceInterval",0),Mt(this,"decisionMaker",null),Mt(this,"loudest",[]),Mt(this,"numLoudestToTrack",3),Mt(this,"energyExpireTimeMs",250),Mt(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 To(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 fo(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=Ot(o,2),a=n[0],c=n[1];if(c===t)continue;c.evaluateSpeechActivityScores(e);for(let e=0;e<i.length;++e){const r=null==t?ho:t.getSpeechActivityScore(e);i[e]=Math.log(c.getSpeechActivityScore(e)/r)}const d=i[0],u=i[1],h=i[2];d>3&&u>2&&h>0&&u>r&&(r=u,s=a)}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 yo=new Map;let So=null,bo=null;const ko=3;let Io=[];function Ao(e,t){let i=yo.get(e);if(i||(i=function(e){const t=new To;return yo.set(e,t),So||(So=new vo(u("TOPN_SILENCE_THRESHOLD")||500),So.on("ActiveSpeakerChanged",(e=>{null!=e&&(bo=e)}))),So.addSpeakers([t]),t}(e)),yo.size<=ko)return{selected:!0,speaker:i};if(!So)throw new Error("no active speaker detector");So.levelChanged(i.id,t),Io=So.loudest.map((e=>e.id)),bo&&!Io.includes(bo)&&Io.length>=ko&&Io.pop();return{selected:Io.includes(i.id)||i.id===bo,speaker:i}}const Ro=1e3,wo=40,Co=new Map,Mo=new Map;class Do{get samples(){return this.actives+this.inactives}get activeRate(){return this.actives/this.samples}constructor(e,t){Mt(this,"id",void 0),Mt(this,"track",void 0),Mt(this,"score",0),Mt(this,"active",!0),Mt(this,"muted",!1),Mt(this,"timer",0),Mt(this,"actives",0),Mt(this,"inactives",0),this.id=e,this.track=t,this.setActive(Co.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 t=function(){const e=[],t=[];return Array.from(Co.values()).forEach((i=>{i.active?e.push(i):t.push(i)})),{actives:e,inactives:t}}(),i=t.actives,r=t.inactives;if(i.length>3){let e;i.forEach((t=>{(!e||e.score>t.score)&&(e=t)})),e&&e.setActive(!1)}if(i.length<3&&r.length>0){let t;r.forEach((e=>{(!t||t.score<e.score)&&e.id!==this.id&&(t=e)})),t&&e&&!this.active&&(t.samples>wo&&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(Co.values()).forEach((i=>{!i.active||i.id===e||i.samples<wo||(!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(Co.values()).forEach((i=>{i.active||i.id===e||i.samples<wo||(!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()}),Ro)}clearTimer(){this.timer&&(clearTimeout(this.timer),this.timer=0)}}let No;function Oo(e,t,i){const r=Co.get(e)||new Do(e,t);return r.score=i,Co.set(e,r),function(e){if(Mo.set(e,!0),!No)return void(No=Date.now());const t=Date.now();t-No>1e3&&(Mo.get(e)?Mo.set(e,!1):(Po(e),Mo.delete(e)),No=t)}(e),r}function Po(e){const t=Co.get(e);t&&(Co.delete(e),t.clearTimer())}const Lo=new Map,Vo=new Map;function xo(e,t,i,r){const s=new DataView(e.data),o=s.getUint8(0);let n;if(0!=(128&o)&&71!==o){const t=function(e){if(e.byteLength<=0)return[];const t=[];let i=0;for(;i<e.byteLength;){const r=(128&e.getUint8(i))>>7,s=127&e.getUint8(i);if(!(r&&i+4<=e.byteLength)){i++;break}{const r=e.getUint32(i,!1),o=(16776192&r)>>10,n=1023&r;t.push({pt:s,ts_offset:o,length:n,data:new Uint8Array}),i+=4}}let r=e.byteLength-i;for(const s of t){if(s.length>r)return console.warn("Broken red payload"),[];s.length>0&&(s.data=new Uint8Array(e.buffer,e.byteOffset+i,s.length),i+=s.length,r-=s.length)}if(r>0){const s={pt:t.length>0?t[t.length-1].pt:0,ts_offset:0,length:r,data:new Uint8Array(e.buffer,e.byteOffset+i,r)};t.push(s)}return t}(s);if(t.length>0){const i=function(e){let t=0;for(let i=0;i<e.length;i++)t+=i<e.length-1?4:1,t+=e[i].length;const i=new Uint8Array(t);let r=0;for(let t=0;t<e.length;t++)if(t<e.length-1){const s=(2147483648|(127&e[t].pt)<<24|(262143&e[t].ts_offset)<<10|1023&e[t].length)>>>0;i[r++]=s>>24&255,i[r++]=s>>16&255,i[r++]=s>>8&255,i[r++]=255&s}else i[r++]=127&e[t].pt;for(const t of e)i.set(t.data,r),r+=t.length;return i}(t.map((e=>{const t=new Uint8Array(e.length);t.set(e.data);const i=oo(new DataView(t.buffer));return null!=i&&i.frame&&(e.data=null==i?void 0:i.frame),n=i,e})));e.data=i.buffer}}else n=oo(s),n&&(e.data=n.frame.buffer);if(t.enqueue(e),!n)return;const a=n.tlv.find((e=>e.tag===so.METADATA));a&&i&&a.value instanceof Uint8Array&&i(a.value);const c=n.tlv.find((e=>e.tag===so.AUDIO_64_BIT_PTS));if(c&&r&&c.value instanceof Uint8Array&&8==c.value.length){r(new DataView(c.value.buffer).getBigUint64(0,!0))}}async function Uo(e){let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!Se().supportWebRTCEncodedTransform)return void ge.warning("browser not support audio encoded transform");if(Lo.has(e))return;const r={track:e.track,onMetadata:i.onMetadata,onPts:i.onPts};if(p()&&!P()){if(!e.createEncodedStreams)return void ge.warning("browser not support createEncodedStreams() API");de(t.CHROME,87,116)||(i.enableTopn=!1);let o=null;try{o=e.createEncodedStreams()}catch(e){return void ge.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&&(ge.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=oo(new DataView(t.data));if(!s)return i.enqueue(t);const o=e.track.id;Vo.set(o,e.track);const n=null===(r=s.tlv.find((e=>e.tag===so.AUDIO_LEVEL)))||void 0===r?void 0:r.value;let a=0;"number"==typeof n&&(a=127-n);const c=Ao(e,Math.round(Math.pow(10,a/60)-1)),d=c.selected,u=c.speaker,h=Oo(o,e.track,u.energyScore);h.addSample(d),h.active&&(t.data=s.frame.buffer,i.enqueue(t))}(e,t,o):i.enableMetadata||i.enablePts?xo(t,o,i.onMetadata,i.onPts):o.enqueue(t)}});o.readable.pipeThrough(n).pipeTo(o.writable)}else{if("undefined"==typeof RTCRtpScriptTransform)return void ge.warning("browser not support RTCRtpScriptTransform");const t=qs(),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?(ge.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):t.data.pts&&r.onPts&&r.onPts(t.data.pts)},r.worker=t}function s(){e.track.removeEventListener("ended",s),function(e){const t=Lo.get(e);if(t){!function(e){const t=yo.get(e);t&&(yo.delete(e),So&&(So.removeSpeakers([t]),0===yo.size&&(So.destroy(),So=null)))}(e),Po(e.track.id),Lo.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){ge.warning(e&&e.message)}}}(e)}Lo.set(e,r),e.track.addEventListener("ended",s)}const Zo="video/h264",Wo="video/h265";function Go(e,t,i){const r=new Uint8Array(e,t,i),s=[];let 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 Bo(e,t){switch(t){case Zo:return 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=Go(e.data,r,s);return new Uint8Array(n)}i++}return null}(e);case Wo:return function(e){const t=new DataView(e.data);let i=0;for(;i+5<e.data.byteLength;){if(0===t.getUint8(i+0)&&0===t.getUint8(i+1)&&0===t.getUint8(i+2)&&1===t.getUint8(i+3)&&78===t.getUint8(i+4)&&1===t.getUint8(i+5)&&101===t.getUint8(i+6)){let r=i+7,s=0,o=0;for(;255===(o=t.getUint8(r++));)s+=255;s+=o;const n=Go(e.data,r,s);return new Uint8Array(n)}i++}return null}(e);default:return null}}function Fo(e){const t=e.length,i=[];let 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)}function Ko(e,t,i){switch(i){case Zo:return function(e,t){const i=Fo(t),r=i.length,s=Math.floor(r/255),o=r%255,n=new Uint8Array(6+s+1+r+1+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),a+=r,n[6+a]=128,a++,n.set(new Uint8Array(e),6+a),n.buffer}(e,t);case Wo:return function(e,t){const i=Fo(t),r=i.length,s=Math.floor(r/255),o=r%255,n=new Uint8Array(7+s+1+r+1+e.byteLength);n[0]=0,n[1]=0,n[2]=0,n[3]=1,n[4]=78,n[5]=1,n[6]=101;let a=0;for(;a<s;)n[7+a]=255,a++;return n[7+a]=o,a++,n.set(i,7+a),a+=r,n[7+a]=128,a++,n.set(new Uint8Array(e),7+a),n.buffer}(e,t);default:return null}}function Ho(e){if(e.length<5)return"";let t=-1;for(let i=0;i<e.length-3;i++){if(0===e[i]&&0===e[i+1]&&1===e[i+2]){t=i;break}if(i<e.length-4&&0===e[i]&&0===e[i+1]&&0===e[i+2]&&1===e[i+3]){t=i;break}}if(-1===t)return"";const i=t+(0===e[t+2]?4:3);if(i>=e.length)return"";const r=e[i];if(128&r)return"";if((r>>1&63)>=32)return Wo;if(i+1<e.length){if(0==(248&e[i+1]))return Wo}return(31&r)<=31?Zo:""}const Xo=new Map;async function Yo(e,t){if(!Se().supportWebRTCEncodedTransform)return void ge.warning("browser not support video encoded transform");if(Xo.has(e))return;if(!e.track)return;const i={track:e.track};if(p()){if(!e.createEncodedStreams)return void ge.warning("browser not support createEncodedStreams() API");let s=null;try{s=e.createEncodedStreams()}catch(e){return void ge.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&&(ge.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=Ho(new Uint8Array(t.data)),a=o.shift();if(a){const e=Ko(t.data,a,n);e&&(t.data=e)}s.enqueue(t)}});s.readable.pipeThrough(n).pipeTo(s.writable)}else{if(!c())return;{if("undefined"==typeof RTCRtpScriptTransform)return void ge.warning("browser not support RTCRtpScriptTransform");const s=qs(),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&&(ge.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=Xo.get(e);if(t){Xo.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){ge.warning(e&&e.message)}}}Xo.set(e,i),e.track.addEventListener("ended",r)}const zo=new Map;async function jo(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!Se().supportWebRTCEncodedTransform)return void ge.warning("browser not support video encoded transform");if(!e.track)return;if(zo.has(e)){const i=zo.get(e);return void(i&&(i.onSei=t.onSei))}const i={track:e.track,onSei:t.onSei};if(p()){if(!e.createEncodedStreams)return void ge.warning("browser not support createEncodedStreams() API");let s=null;try{s=e.createEncodedStreams()}catch(e){return void ge.error("create video-encoded-streams error",e&&e.message)}const o=new TransformStream({transform(s,o){if(i.controller||(i.controller=o),!i.firstFrameInfo){var n;const e=s.getMetadata()||{};i.firstFrameInfo=Nt({type:s.type,rtpTimestamp:s.timestamp,payloadType:e.payloadType||0,ssrc:e.synchronizationSource||0,length:s.data.byteLength},"mimeType"in e?{mimeType:e.mimeType}:{}),null===(n=t.onFirstFrame)||void 0===n||n.call(t,i.firstFrameInfo)}e.track&&e.track.id!==i.track.id&&(ge.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 a=Bo(s,Ho(new Uint8Array(s.data)));a&&i.onSei&&i.onSei(a,s.timestamp),o.enqueue(s)}});s.readable.pipeThrough(o).pipeTo(s.writable)}else if(c()){if("undefined"==typeof RTCRtpScriptTransform)return void ge.warning("browser not support RTCRtpScriptTransform");const s=qs(),o=new MessageChannel;await new Promise((e=>s.onmessage=t=>{"registered"===t.data&&e(void 0)}));const n=new RTCRtpScriptTransform(s,{name:"sei-rx",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 o;if(s.data.transformed&&e.track&&(null===(o=e.track)||void 0===o?void 0:o.id)!==i.track.id)ge.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);else if(s.data.sei&&i.onSei)i.onSei(s.data.sei,s.data.rtpTimestamp);else if(s.data.firstFrameInfo&&t.onFirstFrame){var n;null===(n=t.onFirstFrame)||void 0===n||n.call(t,s.data.firstFrameInfo)}},i.worker=s}function r(){if(e.track){if(this.id!==e.track.id)return;e.track.removeEventListener("ended",r)}!function(e){const t=zo.get(e);if(t){zo.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){ge.warning(e&&e.message)}}}(e)}zo.set(e,i),e.track.addEventListener("ended",r)}ye();export{Pe as AUDIO_CONTEXT_EVENT,He as AUDIO_ENCODER_CONFIG_SETTINGS,pt as AUDIO_TRACK_EVENT,Vr as AgoraRTCPlayer,bi as AudioProcessorContext,Si as AudioProcessorDestination,lt as AudioSourceEvents,Cr as BufferSourceAudioTrack,Ss as CameraVideoTrack,mt as DEFAULT_LOCAL_AUDIO_TRACK_STATS,gt as DEFAULT_LOCAL_VIDEO_TRACK_STATS,Tt as DEFAULT_NETWORK_QUALITY_STATS,_t as DEFAULT_REMOTE_AUDIO_TRACK_STATS,ft as DEFAULT_REMOTE_VIDEO_TRACK_STATS,js as DataChannel,Rt as DataChannelEvents,hi as DeviceManager,St as DeviceManagerEvent,yt as DeviceManagerState,oi as HAS_GUM_AUDIO,ni as HAS_GUM_VIDEO,Rr as LocalAudioTrack,Qs as LocalDataChannel,Lt as LocalTrack,dt as LocalTrackEvents,ys as LocalVideoTrack,At as MediaElementNumStatus,kt as MediaElementStatus,wr as MicrophoneAudioTrack,Mr as MixingAudioTrack,vt as PROCESSOR_CONTEXT_EVENTS,Et as PROCESSOR_DESTINATION_EVENTS,Ys as RemoteAudioTrack,Js as RemoteDataChannel,at as RemoteStreamFallbackType,nt as RemoteStreamType,Hs as RemoteTrack,ut as RemoteTrackEvents,Xs as RemoteVideoTrack,si as SAFARI_GLOBAL_GUM_LOCK,We as SUPPORT_SCREEN_ENCODER_CONFIG_LIST,Ge as SUPPORT_SVC_CONFIG_LIST,Ze as SUPPORT_VIDEO_ENCODER_CONFIG_LIST,ot as StreamType,Pt as Track,ct as TrackEvents,rt as TrackHint,it as TrackInternalEvent,ht as TrackMediaType,Pr as VideoPlayer,yi as VideoProcessorContext,vi as VideoProcessorDestination,It as VideoState,Ye as __TRACK_LIST__,ze as addTrack,Zt as audioContextState,fi as audioElementPlayCenter,Yt as audioTimerLoop,mi as autoPlayGestureEventEmitter,Zi as blob2Uint8Array,Ai as checkMediaStreamTrackResolution,Ei as checkTrackState,Is as createBufferSourceAudioTrack,ws as createCameraVideoTrack,bs as createCustomAudioTrack,Rs as createCustomVideoTrack,Cs as createMicrophoneAndCameraTracks,ks as createMicrophoneAudioTrack,As as createMixingAudioTrack,Ms as createScreenVideoTrack,Ht as decodeAudioData,be as detectSupportAudioElementSetSinkId,Ce as detectSupportAutCC,Me as detectSupportAutCCFeedback,we as detectSupportInstantVideo,Re as detectSupportPrePc,Ae as detectSupportPreSub,Oe as detectSupportRestrictOwnAudio,Ie as detectSupportSDPEndpoint,Ne as detectSupportSuppressLocalAudioPlayback,li as deviceManager,Ui as emptyImage2TypedArray,xi as frameData2CryptoBuffer,Bt as getAudioContext,Xe as getAudioEncoderConfiguration,Pi as getBitrateConstrainRange,Li as getBitrateFromResAndFps,Se as getCompatibility,Ci as getConstraintsFromAudioConfig,Ri as getConstraintsFromCameraConfig,Di as getConstraintsFromMicrophoneConfig,Mi as getConstraintsFromScreenAudioConfig,wi as getConstraintsFromScreenConfig,ri as getElectronScreenSources,ti as getElectronScreenStream,ii as getElectronScreenStreamByUserSelect,ai as getLocalStream,Oi as getNewNearestVideoProfile,Ni as getNewVideoBitrate,Vi as getOriginSenderConfig,Ke as getScalabilityConfiguration,Fe as getScreenEncoderConfiguration,jt as getSilenceAudioTrack,Qt as getSilenceSamplesDuration,Wi as getStaticTrackStream,Be as getVideoEncoderConfiguration,di as handleGetUserMediaError,Ft as hasAudioContext,Je as hasMicrophoneTrack,co as interceptLocalAudioFrame,Yo as interceptLocalVideoFrame,Uo as interceptRemoteAudioFrame,jo as interceptRemoteVideoFrame,qe as isAudioEncoderConfiguration,et as isAudioEncoderConfigurationOrPreset,bt as isBeautyEffectOptions,st as isLowStreamParameter,ke as isPlanB,tt as isScreenSourceType,Qe as isVideoEncoderConfiguration,$e as isVideoEncoderConfigurationOrPreset,Kt as polyfillAudioNode,je as removeTrack,gi as requestAutoplayGesture,Gt as restartBackgroundTag,Jt as silenceScriptProcessHandler,ye as updateAgoraRTCCompatibility,zs 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 u,isFirefox as h,isChrome as l,isEdge as p,isMobile as m,isBelowChrome as g,isAboveEdge as _,isAboveOpera as f,checkValidConstrainLong as T,checkValidNumber as E,checkValidBoolean as v,checkValidEnum as y,AgoraRTCError as S,AgoraRTCErrorCode as b,isEmpty as k,EventEmitter as I,getRandomString as A,runOnce as R,AgoraAPIName as C,AgoraAPITag as w,PromiseMutex as M,emitAsPromiseNoResponse as D,removeItemFromList as N,isIOS as O,isIpadOS as L,wait as P,showElectronSelectSourceWindow as V,getElectronInstance as x,isElectron as U,recursiveMerge as W,isAndroid as G,isHarmonyOS as Z,detectSecureContext as B,isAndroidChromium as F,domLoadedPromise as H,isIOS15 as K,emitAsPromise as X,noop as Y,isLegacyChrome as j,constrainLongToNumber as z,hexToBytes as J,md5 as Q,atom as q,emitAsInvokerNoResponse as $,isIOS16 as ee,retryable as te,isInPage as ie,sumArray as re,getOSWithVersion as se,isAboveIOS15_1 as oe,jsonClone as ne,isBetweenBrowser as ae,isWindows as ce,elementVisibleChecker as de,safeCloneJson as ue,isAboveIOS15_2 as he,isWechatBrowser as le}from"@agora-js/shared";export{isElectron}from"@agora-js/shared";import{logger as pe,report as me,AgoraRTCEventUploadType as ge,apiInvoke as _e}from"@agora-js/report";import fe 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,supportSuppressLocalAudioPlayback:!1,supportRestrictOwnAudio:!1};function Ee(){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="undefined"!=typeof RTCRtpScriptTransform||"function"==typeof RTCRtpSender.prototype.createEncodedStreams,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,Te.supportSuppressLocalAudioPlayback=Me(),Te.supportRestrictOwnAudio=De(),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"))}(),pe.debug("browser ua: ",navigator.userAgent),pe.info("browser info: ",l),pe.info("browser compatibility: ",Te)}))}function ve(){return Te}function ye(){return"setSinkId"in HTMLAudioElement.prototype&&(!u("RESTRICTION_SET_PLAYBACK_DEVICE")||(l()||p())&&!m())}function Se(){return!Te.supportUnifiedPlan||u("CHROME_FORCE_PLAN_B")&&i()}function be(){return u("ENABLE_JOIN_V4")}function ke(e){return!(h()||g(87)||Se())&&(!!u("ENABLE_PRE_SUB")||!(null==e||!e.autoSubscribe||u("FORCE_DISABLE_AUTO_SUB")))}function Ie(e){return!Se()&&!u("USE_NEW_TOKEN")&&(!!u("ENABLE_PREALLOC_PC")||!(null==e||!e.autoSubscribe||u("FORCE_DISABLE_AUTO_SUB")))}function Ae(e){return u("ENABLE_INSTANT_VIDEO")?u("ENABLE_INSTANT_VIDEO"):!(null==e||!e.autoSubscribe||u("FORCE_DISABLE_AUTO_SUB"))}function Re(){return!!u("FORCE_ENABLE_AUT_CC")||!Se()&&(!!u("ENABLE_AUT_CC")||void 0)}function Ce(){return!!u("FORCE_ENABLE_AUT_CC")||!Se()&&(!!u("ENABLE_AUT_FEEDBACK")||void 0)}function we(){return navigator.mediaDevices&&"getSupportedConstraints"in navigator.mediaDevices}function Me(){if(we()){const e=navigator.mediaDevices.getSupportedConstraints();return!(!("suppressLocalAudioPlayback"in e)||!e.suppressLocalAudioPlayback)}return s(141)||_(141)||f(141)}function De(){if(we()){const e=navigator.mediaDevices.getSupportedConstraints();return!(!("restrictOwnAudio"in e)||!e.restrictOwnAudio)}return s(141)||_(141)||f(125)}let Ne=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 Oe(e,t,i){return{sampleRate:e,stereo:t,bitrate:i}}function Le(e,t,i,r,s){return{width:e,height:t,frameRate:i,bitrateMin:r,bitrateMax:s}}function Pe(e,t,i,r,s){return{width:{max:e},height:{max:t},frameRate:i,bitrateMin:r,bitrateMax:s}}function Ve(e,t){return{numSpatialLayers:e,numTemporalLayers:t}}const xe={"90p":Le(160,90),"90p_1":Le(160,90),"120p":Le(160,120,15,30,65),"120p_1":Le(160,120,15,30,65),"120p_3":Le(120,120,15,30,50),"120p_4":Le(212,120),"180p":Le(320,180,15,30,140),"180p_1":Le(320,180,15,30,140),"180p_3":Le(180,180,15,30,100),"180p_4":Le(240,180,15,30,120),"240p":Le(320,240,15,40,200),"240p_1":Le(320,240,15,40,200),"240p_3":Le(240,240,15,40,140),"240p_4":Le(424,240,15,40,220),"360p":Le(640,360,15,80,400),"360p_1":Le(640,360,15,80,400),"360p_3":Le(360,360,15,80,260),"360p_4":Le(640,360,30,80,600),"360p_6":Le(360,360,30,80,400),"360p_7":Le(480,360,15,80,320),"360p_8":Le(480,360,30,80,490),"360p_9":Le(640,360,15,80,800),"360p_10":Le(640,360,24,80,800),"360p_11":Le(640,360,24,80,1e3),"480p":Le(640,480,15,100,500),"480p_1":Le(640,480,15,100,500),"480p_2":Le(640,480,30,100,1e3),"480p_3":Le(480,480,15,100,400),"480p_4":Le(640,480,30,100,750),"480p_6":Le(480,480,30,100,600),"480p_8":Le(848,480,15,100,610),"480p_9":Le(848,480,30,100,930),"480p_10":Le(640,480,10,100,400),"720p":Le(1280,720,15,120,1130),"720p_auto":Le(1280,720,30,900,3e3),"720p_1":Le(1280,720,15,120,1130),"720p_2":Le(1280,720,30,120,2e3),"720p_3":Le(1280,720,30,120,1710),"720p_5":Le(960,720,15,120,910),"720p_6":Le(960,720,30,120,1380),"1080p":Le(1920,1080,15,120,2080),"1080p_1":Le(1920,1080,15,120,2080),"1080p_2":Le(1920,1080,30,120,3e3),"1080p_3":Le(1920,1080,30,120,3150),"1080p_5":Le(1920,1080,60,120,4780),"1440p":Le(2560,1440,30,120,4850),"1440p_1":Le(2560,1440,30,120,4850),"1440p_2":Le(2560,1440,60,120,7350),"4k":Le(3840,2160,30,120,8910),"4k_1":Le(3840,2160,30,120,8910),"4k_3":Le(3840,2160,60,120,13500)},Ue={"480p":Pe(640,480,5),"480p_1":Pe(640,480,5),"480p_2":Pe(640,480,30),"480p_3":Pe(640,480,15),"720p":Pe(1280,720,5),"720p_auto":Le(1280,720,30,900,3e3),"720p_1":Pe(1280,720,5),"720p_2":Pe(1280,720,30),"720p_3":Pe(1280,720,15),"1080p":Pe(1920,1080,5),"1080p_1":Pe(1920,1080,5),"1080p_2":Pe(1920,1080,30),"1080p_3":Pe(1920,1080,15)},We={"1SL1TL":Ve(1,1),"3SL3TL":Ve(3,3),"2SL3TL":Ve(2,3)};function Ge(e){return e||(e="480p_1"),"string"==typeof e?Object.assign({},xe[e]):e}function Ze(e){return"string"==typeof e?Object.assign({},Ue[e]):e}function Be(e){return"string"==typeof e?Object.assign({},We[e]):e}const Fe={speech_low_quality:Oe(16e3,!1),speech_standard:Oe(32e3,!1,18),music_standard:Oe(48e3,!1),standard_stereo:Oe(48e3,!0,56),high_quality:Oe(48e3,!1,128),high_quality_stereo:Oe(48e3,!0,192)};function He(e){return"string"==typeof e?Object.assign({},Fe[e]):e}const Ke=[];function Xe(e){Ke.includes(e)||Ke.push(e)}function Ye(e){const t=Ke.indexOf(e);-1!==t&&Ke.splice(t,1)}function je(){return Ke.some((e=>function(e){return"__className__"in e&&"MicrophoneAudioTrack"===e.__className__}(e)))}function ze(e){return T(e.width,"config.width"),T(e.height,"config.height"),void 0!==e.frameRate&&T(e.frameRate,"config.frameRate"),void 0!==e.bitrateMax&&E(e.bitrateMax,"config.bitrateMax"),void 0!==e.bitrateMin&&E(e.bitrateMin,"config.bitrateMin"),void 0!==e.minDownscaleWidth&&E(e.minDownscaleWidth,"config.minDownscaleWidth",1,1/0,!0),void 0!==e.minDownscaleHeight&&E(e.minDownscaleHeight,"config.minDownscaleHeight",1,1/0,!0),!0}function Je(e){return void 0!==e.sampleRate&&E(e.sampleRate,"config.sampleRate",0,96e3,!0),void 0!==e.sampleSize&&E(e.sampleRate,"config.sampleSize",0,128,!0),void 0!==e.stereo&&v(e.stereo,"config.stereo"),void 0!==e.bitrate&&E(e.bitrate,"config.bitrate",0,1e4,!1),!0}function Qe(e){return"string"==typeof e?y(e,"profile",Object.keys(xe)):ze(e),!0}function qe(e){return"string"==typeof e?y(e,"profile",Object.keys(Fe)):Je(e),!0}function $e(e){return y(e,"mediaSource",["screen","window","application"]),!0}let et=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}({}),tt=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 it(e){if(!e)throw new S(b.INVALID_PARAMS);return k(e.width)||T(e.width,"streamParameter.width"),k(e.height)||T(e.height,"streamParameter.height"),k(e.framerate)||T(e.framerate,"streamParameter.framerate"),k(e.bitrate)||E(e.bitrate,"streamParameter.bitrate"),!0}let rt=function(e){return e[e.HIGH_STREAM=0]="HIGH_STREAM",e[e.LOW_STREAM=1]="LOW_STREAM",e}({}),st=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}({}),ot=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}({}),nt=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}({}),at=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}({}),ct=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.PLAY_START="play-start",e.PLAY_END="play-end",e.FIRST_FRAME_RENDER="first-frame-render",e}({}),dt=function(e){return e.AUDIO="audio",e.VIDEO="video",e.DATA="data",e}({}),ut=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}({}),ht=function(e){return e.UPDATE_TRACK_SOURCE="update-track-source",e}({});const lt={sendVolumeLevel:0,sendBitrate:0,sendBytes:0,sendPackets:0,sendPacketsLost:0,sendJitterMs:0,sendRttMs:0,currentPacketLossRate:0},pt={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},mt={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},gt={uplinkNetworkQuality:0,downlinkNetworkQuality:0},_t={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 ft=function(e){return e.ON_TRACK="on_track",e.ON_NODE="on_node",e}({}),Tt=function(e){return e.REQUEST_UPDATE_CONSTRAINTS="request_update_constraints",e.REQUEST_CONSTRAINTS="request_constraints",e}({}),Et=function(e){return e.IDLE="IDLE",e.INITING="INITING",e.INITEND="INITEND",e}({}),vt=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 yt(e){return void 0!==e.smoothnessLevel&&E(e.smoothnessLevel,"options.smoothnessLevel",0,1,!1),void 0!==e.lighteningLevel&&E(e.lighteningLevel,"options.lighteningLevel",0,1,!1),void 0!==e.rednessLevel&&E(e.rednessLevel,"options.rednessLevel",0,1,!1),void 0!==e.lighteningContrastLevel&&y(e.lighteningContrastLevel,"options.lighteningContrastLevel",[0,1,2]),!0}let St=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}({}),bt=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 kt={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 It=function(e){return e.OPEN="open",e.MESSAGE="message",e.CLOSE="close",e.CLOSING="closing",e.ERROR="error",e}({});function At(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 Rt(e,t){(null==t||t>e.length)&&(t=e.length);for(var i=0,r=Array(t);i<t;i++)r[i]=e[i];return r}function Ct(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 wt(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 Mt(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?wt(Object(i),!0).forEach((function(t){Ct(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):wt(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function Dt(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var i=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=i){var r,s,o,n,a=[],c=!0,d=!1;try{if(o=(i=i.call(e)).next,0===t){if(Object(i)!==i)return;c=!1}else for(;!(c=(r=o.call(i)).done)&&(a.push(r.value),a.length!==t);c=!0);}catch(e){d=!0,s=e}finally{try{if(!c&&null!=i.return&&(n=i.return(),Object(n)!==n))return}finally{if(d)throw s}}return a}}(e,t)||function(e,t){if(e){if("string"==typeof e)return Rt(e,t);var i={}.toString.call(e).slice(8,-1);return"Object"===i&&e.constructor&&(i=e.constructor.name),"Map"===i||"Set"===i?Array.from(e):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?Rt(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}class Nt extends I{set _mediaStreamTrack(e){e!==this.mediaStreamTrack&&(this.safeEmit(nt.TRACK_UPDATED,e),this.mediaStreamTrack=e)}get _mediaStreamTrack(){return this.mediaStreamTrack}constructor(e,t){super(),Ct(this,"trackMediaType",void 0),Ct(this,"_ID",void 0),Ct(this,"_rtpTransceiver",void 0),Ct(this,"_lowRtpTransceiver",void 0),Ct(this,"_hints",[]),Ct(this,"_isClosed",!1),Ct(this,"_originMediaStreamTrack",void 0),Ct(this,"mediaStreamTrack",void 0),Ct(this,"_external",{}),this._ID=t||A(8,"track-"),this._originMediaStreamTrack=e,this.mediaStreamTrack=e,Xe(this)}toString(){return this._ID}getTrackId(){return this._ID}getMediaStreamTrack(e){return e||R((()=>{var e;me.reportApiInvoke(null,{name:C.GET_MEDIA_STREAM_TRACK,options:[],tag:w.TRACER}).onSuccess((null===(e=this._mediaStreamTrack)||void 0===e?void 0:e.label)||"")}),this.mediaStreamTrack.id||this.getTrackId()),this._mediaStreamTrack}getRTCRtpTransceiver(e){return e===rt.LOW_STREAM?this._lowRtpTransceiver:this._rtpTransceiver}getMediaStreamTrackSettings(){return this.getMediaStreamTrack(!0).getSettings()}close(){this._isClosed=!0,this._lowRtpTransceiver=void 0,this._rtpTransceiver=void 0,Ye(this),this.emit(at.CLOSED),this.removeAllListeners(nt.SEI_RECEIVED)}_updateRtpTransceiver(e,t){if(t===rt.LOW_STREAM){if(this._lowRtpTransceiver===e)return;this._lowRtpTransceiver=e}else{if(this._rtpTransceiver===e)return;this._rtpTransceiver=e}this.emit(nt.TRANSCEIVER_UPDATED,e,t)}}class Ot extends Nt{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),Ct(this,"_enabled",!0),Ct(this,"_muted",!1),Ct(this,"_isExternalTrack",!1),Ct(this,"_isClosed",!1),Ct(this,"_enabledMutex",void 0),Ct(this,"processor",void 0),Ct(this,"_processorContext",void 0),Ct(this,"_handleTrackEnded",(()=>{this.onTrackEnded()})),this._enabledMutex=new M("".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,pe.debug("[".concat(this.getTrackId(),"] close")),this.emit(et.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 D(this,et.NEED_REPLACE_TRACK,this),this.processor&&this._processorContext&&this.processor.updateInput({track:this._originMediaStreamTrack,context:this._processorContext}))}_getDefaultPlayerConfig(){return{}}onTrackEnded(){pe.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(at.TRACK_ENDED)}stateCheck(e,t){if(pe.debug("check track state, [muted: ".concat(this._muted,", enabled: ").concat(this._enabled,"] to [").concat(e,": ").concat(t,"]")),v(t,e),this._enabled&&this._muted&&"enabled"===e&&!1===t)throw new S(b.TRACK_STATE_UNREACHABLE,"cannot set enabled while the track is muted").print("error",pe);if(!this._enabled&&!this._muted&&"muted"===e&&!0===t)throw new S(b.TRACK_STATE_UNREACHABLE,"cannot set muted while the track is disabled").print("error",pe)}getProcessorStats(){return this._processorContext&&this._processorContext.gatherStats()||[]}getProcessorUsage(){return this._processorContext?this._processorContext.gatherUsage():Promise.resolve([])}}const Lt=window.AudioContext||window.webkitAudioContext;let Pt,Vt=null;const xt=new class extends I{constructor(){super(...arguments),Ct(this,"prevState",void 0),Ct(this,"curState",void 0),Ct(this,"currentTime",void 0),Ct(this,"currentTimeStuckAt",void 0),Ct(this,"interruptDetectorTrack",void 0),Ct(this,"onLocalAudioTrackMute",(()=>{pe.info("ios15-interruption-start"),this.emit(Ne.IOS_15_16_INTERRUPTION_START)})),Ct(this,"onLocalAudioTrackUnmute",(async()=>{pe.info("ios15-interruption-end"),"running"!==this.curState||this.duringInterruption?pe.info("ios15-interruption-end-canceled"):(Vt&&await Vt.suspend(),this.emit(Ne.IOS_15_16_INTERRUPTION_END))}))}get duringInterruption(){return"running"===this.prevState&&"interrupted"===this.curState}bindInterruptDetectorTrack(e){pe.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){pe.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 Ut(){if(!Lt)return void pe.error("your browser is not support web audio");pe.info("create audio context");const t=Mt({},u("WEBAUDIO_INIT_OPTIONS"));pe.debug("audio context init option:",JSON.stringify(t)),Vt=new Lt(t),xt.curState=Vt.state,Vt.onstatechange=()=>{xt.prevState=xt.curState,xt.curState=Vt?Vt.state:void 0;const t=xt.prevState,i=xt.curState,r="running"===i,s="interrupted"===i,o="running"===t,n="suspended"===t,a="interrupted"===t,c=e().osVersion;(O()||L())&&o&&s&&(pe.info("ios".concat(c,"-interruption-start")),xt.emit(Ne.IOS_INTERRUPTION_START)),(O()||L())&&(n||a)&&r&&(pe.info("ios".concat(c,"-interruption-end")),xt.emit(Ne.IOS_INTERRUPTION_END)),t!==i&&xt.emit(Ne.STATE_CHANGE,i,t)},setInterval((()=>{var e;const t=null===(e=Vt)||void 0===e?void 0:e.currentTime;if(xt.currentTime!==t)xt.currentTimeStuckAt&&(pe.debug("AudioContext current time resume at ".concat(t)),xt.currentTimeStuckAt=void 0),xt.currentTime=t;else{if(t!==xt.currentTimeStuckAt){me.reportApiInvoke(null,{name:"WEB_AUDIO_CURRENT_TIME_STUCK",options:{currentTime:t},tag:w.TRACER}).onSuccess(),pe.warning("AudioContext current time stuck at ".concat(t))}xt.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):O()||L()?"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 l(){let e;try{e=i.play(),e?e.then(g,g):(i.addEventListener("playing",g),i.addEventListener("abort",g),i.addEventListener("error",g))}catch(e){g()}}function p(e){o||(i.paused?e?(m(!1),o=!0,l()):m(!0):m(!1))}function m(e){if(s!==e){s=e;for(let i=0,r=t;i<r.length;i++){const t=r[i];e?window.addEventListener(t,_,{capture:!0,passive:!0}):window.removeEventListener(t,_,{capture:!0,passive:!0})}}}function g(){i.removeEventListener("playing",g),i.removeEventListener("abort",g),i.removeEventListener("error",g),o=!1,p(!1)}function _(){p(!0)}let f;if(O()&&u("IOS_BG_TAG")){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,f=()=>{if(u("IOS_AUTO_RESTART_BG_TAG")&&i&&i.srcObject&&!o&&(!i.paused||!0!==s)){i.paused||i.pause();try{o=!0,l()}catch(e){o=!1}return!0}},p(!0)}return xt.on(Ne.STATE_CHANGE,c),n(!1),f}(Vt).then((e=>{Pt=e}))}function Wt(){if(Pt){if(Pt()){me.reportApiInvoke(null,{name:"BG_AUDIO_TAG_RESTART",options:{},tag:w.TRACER}).onSuccess(),pe.debug("restart background audio tag success")}}}function Gt(){if(!Vt){if(Ut(),!Vt)throw new S(b.NOT_SUPPORTED,"can not create audio context");return Vt}return Vt}function Zt(){return!!Vt}function Bt(e){if(function(){if(null!==Ht)return Ht;const e=Gt(),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(),Ht=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?N(e._inputNodes,r):e._inputNodes=[];for(const i of e._inputNodes)t.call(e,i)}}function Ft(e){const t=Gt();return new Promise(((i,r)=>{t.decodeAudioData(e,(e=>{i(e)}),(e=>{r(new S(b.DECODE_AUDIO_FILE_FAILED,e.toString()))}))}))}let Ht=null;function Kt(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=Gt();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 Xt=null;function Yt(){if(Xt)return Xt;const e=Gt();if(!e.createMediaStreamDestination)throw new S(b.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),Xt=r.stream.getAudioTracks()[0],Xt}function jt(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 zt(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 Jt{constructor(){Ct(this,"context",void 0),Ct(this,"analyserNode",void 0),Ct(this,"sourceNode",void 0),this.context=Gt(),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||O()||L()||"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){pe.warning("rebuild analyser node failed.")}}destroy(){this.updateSource(void 0)}}class Qt extends I{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(),Ct(this,"outputNode",void 0),Ct(this,"outputTrack",void 0),Ct(this,"isPlayed",!1),Ct(this,"sourceNode",void 0),Ct(this,"context",void 0),Ct(this,"audioBufferNode",void 0),Ct(this,"destNode",void 0),Ct(this,"audioOutputLevel",0),Ct(this,"volumeLevelAnalyser",void 0),Ct(this,"_processedNode",void 0),Ct(this,"playNode",void 0),Ct(this,"isDestroyed",!1),Ct(this,"onNoAudioInput",void 0),Ct(this,"isNoAudioInput",!1),Ct(this,"_noAudioInputCount",0),this.context=Gt(),this.playNode=this.context.destination,this.outputNode=this.context.createGain(),Bt(this.outputNode),this.volumeLevelAnalyser=new Jt}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(ut.ON_AUDIO_BUFFER,jt(e))})}stopGetAudioBuffer(){this.audioBufferNode&&(this.audioBufferNode.onaudioprocess=null,this.outputNode.disconnect(this.audioBufferNode),this.audioBufferNode=void 0)}createOutputTrack(){if(!ve().webAudioMediaStreamDest)throw new S(b.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((()=>{xt.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;O()||L()?"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 P(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 qt extends Qt{get isFreeze(){return!1}constructor(t,i,r){var s;if(super(),Ct(this,"sourceNode",void 0),Ct(this,"track",void 0),Ct(this,"clonedTrack",void 0),Ct(this,"audioElement",void 0),Ct(this,"isCurrentTrackCloned",!1),Ct(this,"isRemoteTrack",!1),Ct(this,"originVolumeLevelAnalyser",void 0),Ct(this,"rebuildWebAudio",(async()=>{if(pe.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 pe.debug("rebuild web audio success, current volume status",this.getAccurateVolumeLevel());this.context.resume().then((()=>pe.info("resume success"))),pe.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),Bt(this.sourceNode),this.volumeLevelAnalyser.rebuildAnalyser();const i=this.outputNode.gain.value;this.outputNode=this.context.createGain(),this.outputNode.gain.setValueAtTime(i,this.context.currentTime),Bt(this.outputNode),this.emit(ut.UPDATE_SOURCE),this.connect(),this.audioElement.srcObject=t,this.isPlayed&&this.play(this.playNode),this.checkHasAudioInput()})),"audio"!==t.kind)throw new S(b.UNEXPECTED_ERROR);this.track=t;const o=new MediaStream([this.track]);if(this.isRemoteTrack=!!i,this.sourceNode=this.context.createMediaStreamSource(o),Bt(this.sourceNode),r){const e=r.clone();e.enabled=!0,this.clonedTrack=e,pe.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]));Bt(t),this.originVolumeLevelAnalyser=new Jt,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&&(xt.on(Ne.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),Bt(this.sourceNode),this.processedNode||this.sourceNode.connect(this.outputNode),this.emit(ut.UPDATE_SOURCE),this.audioElement.srcObject=t}destroy(){var e;this.audioElement.srcObject=null,this.audioElement.remove(),xt.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),pe.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]));Bt(i),this.originVolumeLevelAnalyser&&this.originVolumeLevelAnalyser.updateSource(i)}getOriginVolumeLevel(){return this.originVolumeLevelAnalyser?this.originVolumeLevelAnalyser.getVolumeLevel():this.getAccurateVolumeLevel()}}async function $t(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 ei(e,t){const i=await ti(e.mediaSource),r=await V(i,t),s=r.sourceId,o=r.audio;return await $t(s,e,o)}async function ti(e){let t=["window","screen"];"application"!==e&&"window"!==e||(t=["window"]),"screen"===e&&(t=["screen"]);const i=x();if(!i)throw console.error("failed to fetch electron, please mount it to window"),new S(b.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 S(b.ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR,e.toString())}}const ii=new M("safari");let ri=!1,si=!1;async function oi(e,t){let i=0,r=null;for(;i<2;)try{r=await ni(e,t,i>0);break}catch(e){if(e instanceof S)throw pe.error("[".concat(t,"] ").concat(e.toString())),e;const r=ai(e.name||e.code||e,e.message);if(r.code===b.MEDIA_OPTION_INVALID){pe.debug("[".concat(t,"] detect media option invalid, retry")),i+=1,await P(500);continue}throw pe.error("[".concat(t,"] ").concat(r.toString())),r}if(!r)throw new S(b.UNEXPECTED_ERROR,"can not find stream after getUserMedia");return r}async function ni(t,i,r){if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)throw new S(b.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 pe.debug("Using Video Source/ Audio Source"),o;if(t.screen)if(U())if(t.screen.sourceId){ci(o,await $t(t.screen.sourceId,t.screen,!!t.screenAudio))}else{ci(o,await ei(t.screen,!!t.screenAudio))}else if(l()&&t.screen.extensionId&&t.screen.mandatory){if(!s.getStreamFromExtension)throw new S(b.NOT_SUPPORTED,"This browser does not support screen sharing");pe.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 pe.error("[".concat(p,"] No response from Chrome Plugin. Plugin not installed properly"),i),void t(new S(b.CHROME_PLUGIN_NO_RESPONSE,"No response from Chrome Plugin. Plugin not installed properly"));e(i.streamId)}))}catch(e){pe.error("[".concat(p,"] AgoraRTC screensharing plugin is not accessible(").concat(a,")"),e.toString()),t(new S(b.CHROME_PLUGIN_NOT_INSTALL))}})));t.screen.mandatory.chromeMediaSourceId=e;ci(o,await navigator.mediaDevices.getUserMedia({video:{mandatory:t.screen.mandatory}}))}else if(s.getDisplayMedia){var n;t.screen.mediaSource&&$e(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},r=t.screen,s=r.selfBrowserSurface,a=r.surfaceSwitching,c=r.systemAudio,d=r.preferCurrentTab,u=r.windowAudio,h=r.monitorTypeSurfaces,l={selfBrowserSurface:s,surfaceSwitching:a,systemAudio:c,preferCurrentTab:d,windowAudio:u,monitorTypeSurfaces:h};!s&&delete l.selfBrowserSurface,!a&&delete l.surfaceSwitching,!c&&delete l.systemAudio,!d&&delete l.preferCurrentTab,!u&&delete l.windowAudio,!h&&delete l.monitorTypeSurfaces,pe.debug("[".concat(i,"] getDisplayMedia:"),JSON.stringify({video:e,audio:t.screenAudio,controls:l}));ci(o,await navigator.mediaDevices.getDisplayMedia(Mt({video:e,audio:t.screenAudio},l)))}else{if(!h())throw pe.error("[".concat(i,"] This browser does not support screenSharing")),new S(b.NOT_SUPPORTED,"This browser does not support screen sharing");{t.screen.mediaSource&&$e(t.screen.mediaSource);const e={video:{mediaSource:t.screen.mediaSource,width:t.screen.width,height:t.screen.height,frameRate:t.screen.frameRate}};pe.debug("[".concat(i,"] getUserMedia: ").concat(JSON.stringify(e)));ci(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=W(m,g)}catch(e){}pe.debug("[".concat(i,"] GetUserMedia"),JSON.stringify(m)),e();let _,f=null;(c()||O()||d())&&(f=await ii.lock());try{_=await navigator.mediaDevices.getUserMedia(m)}catch(e){throw f&&f(),e}return m.audio&&(ri=!0),m.video&&(si=!0),ci(o,_),f&&f(),o}function ai(e,t){switch(e){case"Starting video failed":case"OverconstrainedError":case"TrackStartError":return new S(b.MEDIA_OPTION_INVALID,"".concat(e,": ").concat(t));case"NotFoundError":case"DevicesNotFoundError":return new S(b.DEVICE_NOT_FOUND,"".concat(e,": ").concat(t));case"NotSupportedError":return new S(b.NOT_SUPPORTED,"".concat(e,": ").concat(t));case"NotReadableError":return new S(b.NOT_READABLE,"".concat(e,": ").concat(t));case"InvalidStateError":case"NotAllowedError":case"PERMISSION_DENIED":case"PermissionDeniedError":return new S(b.PERMISSION_DENIED,"".concat(e,": ").concat(t));case"ConstraintNotSatisfiedError":return new S(b.CONSTRAINT_NOT_SATISFIED,"".concat(e,": ").concat(t));default:return pe.error("getUserMedia unexpected error",e),new S(b.UNEXPECTED_ERROR,"".concat(e,": ").concat(t))}}function ci(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 di extends I{get state(){return this._state}set state(e){e!==this._state&&(this.emit(vt.STATE_CHANGE,e),this._state=e)}constructor(){super(),Ct(this,"_state",Et.IDLE),Ct(this,"isAccessMicrophonePermission",!1),Ct(this,"isAccessCameraPermission",!1),Ct(this,"lastAccessMicrophonePermission",!1),Ct(this,"lastAccessCameraPermission",!1),Ct(this,"checkdeviceMatched",!1),Ct(this,"deviceInfoMap",new Map),this.init().then((()=>{navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",this.updateDevicesInfo.bind(this)),window.setInterval((()=>{(u("ENUMERATE_DEVICES_INTERVAL")||(G()||Z())&&i())&&this.updateDevicesInfo()}),u("ENUMERATE_DEVICES_INTERVAL_TIME"))})).catch((e=>pe.error(e.toString())))}async enumerateDevices(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices)throw new S(b.NOT_SUPPORTED,"enumerateDevices() not supported.");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(ii.isLocked){pe.debug("[device manager] wait GUM lock");(await ii.lock())(),pe.debug("[device manager] GUM unlock")}if(ri&&(o=!1,this.isAccessMicrophonePermission=!0),si&&(n=!1,this.isAccessCameraPermission=!0),pe.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=ai(e.name||e.code||e,e.message);if(t.code===b.PERMISSION_DENIED)throw t;pe.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=ai(e.name||e.code||e,e.message);if(t.code===b.PERMISSION_DENIED)throw t;pe.warning("getUserMedia failed in getDevices",t)}this.isAccessMicrophonePermission=!0}else if(n){try{c=await navigator.mediaDevices.getUserMedia({video:t})}catch(e){const t=ai(e.name||e.code||e,e.message);if(t.code===b.PERMISSION_DENIED)throw t;pe.warning("getUserMedia failed in getDevices",t)}this.isAccessCameraPermission=!0}pe.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 S(b.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 S(b.DEVICE_NOT_FOUND,"deviceId: ".concat(e));return t}async init(){this.state=Et.INITING;try{await this.updateDevicesInfo(),this.state=Et.INITEND}catch(e){if(this.state=Et.IDLE,!B())throw new S(b.WEB_SECURITY_RESTRICT,"Your context is limited by web security, please try using https protocol or localhost.");throw pe.warning("Device Detection functionality cannot start properly.",e.toString()),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?pe.debug("[device-check] default input ".concat(t.label," and output ").concat(i.label," is the same group")):pe.debug("[device-check] default input ".concat(t.label," and output ").concat(i.label," is not the same group")):pe.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!==Et.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(vt.RECORDING_DEVICE_CHANGED,e);break;case"videoinput":this.lastAccessCameraPermission&&this.isAccessCameraPermission&&this.emit(vt.CAMERA_DEVICE_CHANGED,e);break;case"audiooutput":this.lastAccessMicrophonePermission&&this.isAccessMicrophonePermission&&this.emit(vt.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 ui=new di;let hi=!1;const li=new class extends I{constructor(){super(...arguments),Ct(this,"onAutoplayFailed",void 0),Ct(this,"onAudioAutoplayFailed",void 0)}};function pi(){if(hi)return u("FLS_AUTOPLAY_EMITS")?(li.onAutoplayFailed&&li.onAutoplayFailed(),li.emit("autoplay-failed")):void 0;{const e=t=>{t.preventDefault(),function(){try{const e=Gt();"running"!==e.state&&e.resume().catch((e=>{var t;pe.warning("resume web audio context on autoplay gesture failed",(null==e||null===(t=e.toString)||void 0===t?void 0:t.call(e))||e)}))}catch(t){var e;pe.warning("create web audio context on autoplay gesture failed",(null==t||null===(e=t.toString)||void 0===e?void 0:e.call(t))||t)}}(),hi=!1,F()?document.body.removeEventListener("click",e,!0):(document.body.removeEventListener("touchstart",e,!0),document.body.removeEventListener("mousedown",e,!0))};hi=!0,F()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0)),pe.info("detect media autoplay failed, document: https://docs.agora.io/cn/Voice/autoplay_policy_web_ng?platform=Web"),li.onAutoplayFailed?li.onAutoplayFailed():li.onAudioAutoplayFailed?pe.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 ."):pe.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 ."),li.emit("autoplay-failed")}}function mi(e,t,i,r){if(!e)return;const s=me.getBaseInfoBySessionId(e);if(!s)return;const o=s.info,n=Date.now(),a=Mt(Mt({},o),{},{vid:void 0===o.vid?0:Number(o.vid),lts:n,elapse:n-s.startTime,cbRegistered:li.onAutoplayFailed||li.onAudioAutoplayFailed?1:-1,errorMsg:i,mediaType:t,trackId:r,extend:void 0});me.send({type:ge.AUTOPLAY_FAILED,data:a},!0)}const gi=["play","playing","loadeddata","canplay","pause","stalled","suspend","waiting","abort","emptied","ended","error"],_i=new class{constructor(){Ct(this,"onAutoplayFailed",void 0),Ct(this,"elementMap",new Map),Ct(this,"elementStateMap",new Map),Ct(this,"elementsNeedToResume",[]),Ct(this,"sinkIdMap",new Map),Ct(this,"elementIdMap",new WeakMap),Ct(this,"autoResumeAfterInterruption",(e=>Promise.all(Array.from(this.elementMap.entries()).map((async t=>{let i=Dt(t,2),r=i[0],s=i[1];const o=this.elementStateMap.get(r),n=s.srcObject.getAudioTracks()[0],a=n&&n.readyState;if(pe.debug("resume after interrupted, ele: ".concat(o," audio: ").concat(a," ").concat(e)),"live"===a){if(e)return s.pause(),s.play();if("running"===xt.curState)return K()?(s.pause(),s.play()):o&&"paused"===o?s.play():void 0}}))))),Ct(this,"autoResumeAfterInterruptionOnIOS15_16",(()=>{Array.from(this.elementMap.entries()).forEach((e=>{let t=Dt(e,2);t[0];let i=t[1];const r=i.srcObject.getAudioTracks()[0];r&&"live"===r.readyState&&(pe.debug("auto resume after interruption inside autoResumeAfterInterruptionOnIOS15"),i.pause(),i.play())}))})),this.autoResumeAudioElement(),xt.on(Ne.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),xt.on(Ne.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16),xt.on(Ne.STATE_CHANGE,(()=>{O()&&"suspended"===xt.prevState&&"running"===xt.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 S(b.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.elementIdMap.set(o,{id:t}),this.bindAudioElementEvents(t,o),this.elementMap.set(t,o),this.elementStateMap.set(t,St.INIT),this.setVolume(t,i);const n=this.sinkIdMap.get(t);if(n)try{o.setSinkId(n).catch((e=>{pe.warning("[".concat(t,"] set sink id failed"),e.toString())}))}catch(e){pe.warning("[".concat(t,"] set sink id failed"),e.toString())}const a=o.play();a&&a.then&&a.catch((e=>{s&&mi(s,"audio",e.message,t),pe.warning("audio element play warning",e.toString()),this.elementMap.has(t)&&"NotAllowedError"===e.name&&(pe.warning("detected audio element autoplay failed"),this.elementsNeedToResume.push(o),r((()=>{this.onAutoplayFailed&&this.onAutoplayFailed(),pi()})))}))}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)}getVolume(e){const t=this.elementMap.get(e);return t?t.volume:0}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)}reuseTrackId(e,t){if(e===t)return;const i=this.elementMap.get(e);if(!i)return;this.elementMap.has(t)&&this.stop(t),this.elementMap.delete(e),this.elementMap.set(t,i);const r=this.elementStateMap.get(e);this.elementStateMap.delete(e),void 0!==r&&this.elementStateMap.set(t,r);const s=this.sinkIdMap.get(e);void 0!==s&&(this.sinkIdMap.delete(e),this.sinkIdMap.set(t,s));const o=this.elementIdMap.get(i);o&&(o.id=t)}bindAudioElementEvents(e,t){gi.forEach((i=>{t.addEventListener(i,(i=>{var r,s;const o=null!==(r=null===(s=this.elementIdMap.get(t))||void 0===s?void 0:s.id)&&void 0!==r?r:e,n=this.elementStateMap.get(o),a="pause"===i.type?"paused":i.type;if(pe.debug("[".concat(o,"] audio-element-status change ").concat(n," => ").concat(a)),"error"===i.type){const e=null==t?void 0:t.error;e&&pe.error("[".concat(o,"] media error, code: ").concat(e.code,", message: ").concat(e.message))}this.elementStateMap.set(o,a)}))}))}getPlayerState(e){return this.elementStateMap.get(e)||"uninit"}autoResumeAudioElement(){const e=()=>{this.elementsNeedToResume.forEach((e=>{e.play().then((e=>{pe.debug("Auto resume audio element success")})).catch((e=>{pe.warning("Auto resume audio element failed!",e)}))})),this.elementsNeedToResume=[]};H().then((()=>{F()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0))}))}};function fi(){return function(e,t,i){const r=i.value;return"function"==typeof r&&(i.value=function(){this._isClosed&&new S(b.INVALID_OPERATION,"[".concat(this.getTrackId(),"] cannot operate a closed track")).print("warning",pe);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 Ti extends I{constructor(e){super(),Ct(this,"name","VideoProcessorDestination"),Ct(this,"ID","0"),Ct(this,"_source",void 0),Ct(this,"videoContext",void 0),Ct(this,"inputTrack",void 0),this.videoContext=e}get kind(){return"video"}get enabled(){return!0}pipe(){throw new S(b.NOT_SUPPORTED,"VideoProcessor cannot pipe to any other Processor")}unpipe(){throw new S(b.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(ft.ON_TRACK,e.track))}reset(){this.inputTrack=void 0,this.videoContext.chained=!1,this.emit(ft.ON_TRACK,void 0)}}class Ei extends I{set chained(e){this._chained=e}get chained(){return this._chained}constructor(e,t){super(),Ct(this,"constraintsMap",new Map),Ct(this,"statsRegistry",[]),Ct(this,"usageRegistry",[]),Ct(this,"trackId",void 0),Ct(this,"direction",void 0),Ct(this,"_chained",!1),this.trackId=e,this.direction=t}async getConstraints(){return await X(this,Tt.REQUEST_CONSTRAINTS)}async requestApplyConstraints(e,t){return pe.info("processor ".concat(t.name," requestApplyConstraints for ").concat(this.trackId)),e&&this.constraintsMap.set(t,e),D(this,Tt.REQUEST_UPDATE_CONSTRAINTS,Array.from(this.constraintsMap.values()))}async requestRevertConstraints(e){if(this.constraintsMap.has(e))return pe.info("processor ".concat(e.name," requestRevertConstraints for ").concat(this.trackId)),this.constraintsMap.delete(e),D(this,Tt.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 t of this.statsRegistry){const i=t.processorID,r=t.processorName,s=t.type,o=t.cb;try{const t=o();e.push({processorID:i,processorName:r,type:s,stats:t})}catch(e){pe.error(new S(b.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 t of this.usageRegistry){const i=t.cb;try{let t=i();t instanceof Promise&&(t=await t),e.push(Mt(Mt({},t),{},{direction:this.direction}))}catch(e){pe.error("gather extension usage error",e)}}return e}getDirection(){return this.direction}}class vi extends I{constructor(e){super(),Ct(this,"name","AudioProcessorDestination"),Ct(this,"ID","0"),Ct(this,"inputTrack",void 0),Ct(this,"inputNode",void 0),Ct(this,"audioProcessorContext",void 0),Ct(this,"_source",void 0),this.audioProcessorContext=e}get kind(){return"audio"}get enabled(){return!0}pipe(){throw new S(b.NOT_SUPPORTED,"AudioProcessorDestination cannot pipe to any other Processor")}unpipe(){throw new S(b.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(ft.ON_TRACK,void 0),this.emit(ft.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(ft.ON_TRACK,this.inputTrack)),e.node&&this.inputNode!==e.node&&(this.audioProcessorContext.chained=!0,this.inputNode=e.node,this.emit(ft.ON_NODE,this.inputNode))}}class yi extends I{set chained(e){this._chained=e}get chained(){return this._chained}constructor(e,t,i){super(),Ct(this,"constraintsMap",new Map),Ct(this,"statsRegistry",[]),Ct(this,"audioContext",void 0),Ct(this,"trackId",void 0),Ct(this,"direction",void 0),Ct(this,"usageRegistry",[]),Ct(this,"_chained",!1),this.audioContext=e,this.trackId=t,this.direction=i}async getConstraints(){return X(this,Tt.REQUEST_CONSTRAINTS)}getAudioContext(){return this.audioContext}async requestApplyConstraints(e,t){return pe.info("processor ".concat(t.name," requestApplyConstraints for ").concat(this.trackId)),e&&this.constraintsMap.set(t,e),D(this,Tt.REQUEST_UPDATE_CONSTRAINTS,Array.from(this.constraintsMap.values()))}async requestRevertConstraints(e){if(this.constraintsMap.has(e))return this.constraintsMap.delete(e),D(this,Tt.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 t of this.statsRegistry){const i=t.processorID,r=t.processorName,s=t.type,o=t.cb;try{const t=o();e.push({processorID:i,processorName:r,type:s,stats:t})}catch(e){pe.error(new S(b.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 t of this.usageRegistry){const i=t.cb;try{let t=i();t instanceof Promise&&(t=await t),e.push(Mt(Mt({},t),{},{direction:this.direction}))}catch(e){pe.error("gather extension usage error",e)}}return e}getDirection(){return this.direction}}class Si extends I{get isPlayed(){return!0}get isFreeze(){return!1}constructor(){super(),Ct(this,"context",void 0),Ct(this,"processSourceNode",void 0),Ct(this,"outputTrack",void 0),Ct(this,"processedNode",void 0),Ct(this,"clonedTrack",void 0),Ct(this,"outputNode",void 0),this.outputNode=new bi}setVolume(){}createOutputTrack(){throw new S(b.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 bi{disconnect(){}connect(){}}function ki(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=O()?"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(Y),setTimeout((()=>{r||(s.srcObject=null,s.remove(),t([s.videoWidth,s.videoHeight]))}),4e3)}))}function Ii(e){const t={};e.facingMode&&(t.facingMode=e.facingMode),e.cameraId&&(t.deviceId={exact:e.cameraId});const i=Ge(e.encoderConfig);return null!=i.width&&(t.width=i.width),null!=i.height&&(t.height=i.height),!j()&&i.frameRate&&(t.frameRate=i.frameRate),p()&&"object"==typeof t.frameRate&&(t.frameRate.max=60),h()&&(t.frameRate={ideal:30,max:30}),t}function Ai(e){const t={};e.screenSourceType&&(t.mediaSource=e.screenSourceType),e.extensionId&&l()&&(t.extensionId=e.extensionId);const i=e.displaySurface,r=e.selfBrowserSurface,o=e.surfaceSwitching,n=e.systemAudio,a=e.preferCurrentTab,c=e.windowAudio,d=e.monitorTypeSurfaces;(s(107)||_(107)||f(93))&&(i&&(y(i,"displaySurface",["browser","window","monitor"]),t.displaySurface=i),r?(y(r,"selfBrowserSurface",["exclude","include"]),t.selfBrowserSurface=r):t.selfBrowserSurface="include",o&&(y(o,"surfaceSwitching",["exclude","include"]),t.surfaceSwitching=o)),(s(105)||_(105)||f(91))&&n&&(y(n,"systemAudio",["exclude","include"]),t.systemAudio=n),(s(94)||_(94)||f(80))&&a&&(t.preferCurrentTab=!0),(s(141)||_(141)||f(125))&&c&&(y(c,"windowAudio",["exclude","system"]),t.windowAudio=c),(s(119)||_(119)||f(105))&&d&&(y(d,"monitorTypeSurfaces",["exclude","include"]),t.monitorTypeSurfaces=d),e.electronScreenSourceId&&(t.sourceId=e.electronScreenSourceId);const u=e.encoderConfig?Ze(e.encoderConfig):null;return t.mandatory={chromeMediaSource:"desktop",maxWidth:u?u.width:void 0,maxHeight:u?u.height:void 0},u&&(u.frameRate&&("number"==typeof u.frameRate?(t.mandatory.maxFrameRate=u.frameRate,t.mandatory.minFrameRate=u.frameRate):(t.mandatory.maxFrameRate=u.frameRate.max||u.frameRate.ideal||u.frameRate.exact||void 0,t.mandatory.minFrameRate=u.frameRate.min||u.frameRate.ideal||u.frameRate.exact||void 0),t.frameRate=u.frameRate),u.width&&(t.width=u.width),u.height&&(t.height=u.height)),t}function Ri(e){const t={};return j()||(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 Ci(e){const t=Ri(e);return Me()&&e.suppressLocalAudioPlayback&&(t.suppressLocalAudioPlayback=e.suppressLocalAudioPlayback),De()&&e.restrictOwnAudio&&(t.restrictOwnAudio=!0),t}function wi(e){const t=Ri(e);if(e.encoderConfig){const i=He(e.encoderConfig);t.channelCount=i.stereo?2:1,t.sampleRate=i.sampleRate,t.sampleSize=i.sampleSize}return e.microphoneId&&(t.deviceId={exact:e.microphoneId}),G()&&(t.sampleRate=void 0),t}function Mi(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)=>Dt(e,1)[0]-Dt(t,1)[0])),t=e.find((e=>Dt(e,1)[0]>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)=>Dt(e,1)[0]-Dt(t,1)[0])),t=e.find((e=>Dt(e,1)[0]>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 Di(e,t,i){if(!Array.isArray(u("VIDEO_ENCODER_CONFIG_LIST")))return!1;if(0===u("VIDEO_ENCODER_CONFIG_LIST").length)return!1;const r=Math.min(e,t);if(r>=480)return!1;return Mt(Mt({},u("VIDEO_ENCODER_CONFIG_LIST").find((e=>e.height>r))),{},{frameRate:i})}function Ni(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 Oi(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 Li=e=>{const t=e._encoderConfig;if(!t)return;const i=e.getMediaStreamTrackSettings(),r=i.frameRate,s=i.width,o=i.height;let n=t.frameRate,a=void 0===n?r:n,c=t.width,d=void 0===c?s:c,h=t.height,l=void 0===h?o:h;if(!a||!d||!l)return;d=z(d),l=z(l),a=z(a);const p=Oi(d,l,a),m=p.max,g=p.min,_=t||{},f=_.bitrateMax,T=_.bitrateMin,E=_.minDownscaleWidth,v=_.minDownscaleHeight;f||pe.debug("calculate bitrate: [w: ".concat(d,", h: ").concat(l,", fps: ").concat(a,"] => [brMax: ").concat(f,", brMin: ").concat(T,"]"));const y=u("ENCODER_CONFIG_LIMIT").maxFramerate;return y&&"number"==typeof y&&(a=Math.min(a,y)),{width:d,height:l,frameRate:a,bitrateMax:f||m,bitrateMin:T||g,scaleResolutionDownBy:1,scale:0,minDownscaleWidth:E,minDownscaleHeight:v}},Pi=async(e,t,i)=>await(async(e,t,i)=>{const r=J(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),Vi=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 xi(e);i({buffer:r,width:t.width,height:t.height})}else r(new S(b.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED))}),e,1)}))},xi=async e=>{const t=await e.arrayBuffer();return new Uint8Array(t)};function Ui(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 Wi,Gi,Zi,Bi,Fi,Hi,Ki,Xi,Yi,ji,zi,Ji,Qi,qi,$i,er,tr,ir,rr,sr,or,nr,ar,cr,dr,ur,hr,lr,pr,mr,gr,_r,fr,Tr,Er,vr,yr,Sr,br,kr;let Ir=(Wi=_e({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),Gi=_e({argsMap:(e,t)=>[e.getTrackId(),t]}),Zi=fi(),Bi=q("LocalAudioTrack","_enabledMutex"),Fi=_e({argsMap:(e,t)=>[e.getTrackId(),t]}),Hi=fi(),Ki=q("LocalAudioTrack","_enabledMutex"),Xi=_e({argsMap:(e,t)=>[e.getTrackId(),t]}),Yi=fi(),ji=fi(),zi=fi(),Ji=_e({argsMap:e=>[e.getTrackId()]}),Qi=fi(),qi=_e({argsMap:e=>[e.getTrackId()]}),$i=fi(),er=_e({argsMap:e=>[e.getTrackId()]}),tr=_e({argsMap:(e,t)=>[e.getTrackId(),t.name]}),ir=_e({argsMap:e=>[e.getTrackId()]}),At((rr=class extends Ot{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?_i.isPlaying(this.getTrackId()):this._source.isPlayed}get __className__(){return"LocalAudioTrack"}constructor(e,t,i,r){super(e,i),Ct(this,"trackMediaType",dt.AUDIO),Ct(this,"_encoderConfig",void 0),Ct(this,"_trackSource",void 0),Ct(this,"metadata",[]),Ct(this,"_enabled",!0),Ct(this,"_volume",100),Ct(this,"_useAudioElement",!0),Ct(this,"_bypassWebAudio",!1),Ct(this,"processor",void 0),Ct(this,"_processorContext",void 0),Ct(this,"_processorDestination",void 0),Ct(this,"_getOriginVolumeLevel",void 0),Ct(this,"_usePipeMode",!1),Ct(this,"_useExtensionMode",!1),Ct(this,"_extensionManager",void 0),this._encoderConfig=t,this._getOriginVolumeLevel=!!r,this._trackSource=new Si,u("DISABLE_WEBAUDIO")&&(this._bypassWebAudio=!0),u("LOCAL_AUDIO_TRACK_USES_WEB_AUDIO")&&(this._useAudioElement=!1);c()&&!Zt()?setTimeout((()=>this.initWebAudio())):this.initWebAudio()}setVolume(e){E(e,"volume",0,1e3),this._volume=e,this._source.setVolume(e/100),this._useAudioElement&&_i.setVolume(this.getTrackId(),e);try{if(this._bypassWebAudio)return void pe.debug("[".concat(this.getTrackId(),"] setVolume returned because no pass through WebAudio."));const e=this._source.createOutputTrack();this._mediaStreamTrack!==e&&(this._mediaStreamTrack=e,D(this,et.NEED_REPLACE_TRACK,this).then((()=>{pe.debug("[".concat(this.getTrackId(),"] replace web audio track success"))})).catch((e=>{pe.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||!ye())throw new S(b.NOT_SUPPORTED,"your browser does not support setting the audio output device");await _i.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(pe.info("[".concat(this.getTrackId(),"] start setEnabled"),e),e){this._originMediaStreamTrack.enabled=!0;try{i||(this._enabled=!0),await D(this,et.NEED_ENABLE_TRACK,this),pe.info("[".concat(this.getTrackId(),"] setEnabled to ").concat(e," success"))}catch(e){throw i||(this._enabled=!1),pe.error("[".concat(this.getTrackId(),"] setEnabled to true error"),e.toString()),e}}else{this._originMediaStreamTrack.enabled=!1,i||(this._enabled=!1);try{await D(this,et.NEED_DISABLE_TRACK,this)}catch(e){throw i||(this._enabled=!0),pe.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,pe.debug("[".concat(this.getTrackId(),"] start set muted: ").concat(e)),e?await D(this,et.NEED_MUTE_TRACK,this):await D(this,et.NEED_UNMUTE_TRACK,this))}getStats(){R((()=>{pe.warning("[deprecated] LocalAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalAudioStats instead")}),"localAudioTrackGetStatsWarning");const e=$(this,et.GET_STATS);return e||Mt({},lt)}setAudioFrameCallback(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:4096;if(!e)return this._source.removeAllListeners(ut.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(t),this._source.removeAllListeners(ut.ON_AUDIO_BUFFER),this._source.on(ut.ON_AUDIO_BUFFER,(t=>e(t)))}play(){pe.debug("[".concat(this.getTrackId(),"] start audio playback")),this._useAudioElement?(pe.debug("[".concat(this.getTrackId(),"] start audio playback in element")),_i.play(this._mediaStreamTrack,this.getTrackId(),this._volume)):this._source.play()}stop(){pe.debug("[".concat(this.getTrackId(),"] stop audio playback")),this._useAudioElement?_i.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._extensionManager&&(this._extensionManager.destroy(),this._extensionManager=void 0,this._useExtensionMode=!1),this._source.destroy()}_updatePlayerSource(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];pe.debug("[".concat(this.getTrackId(),"] update player source track")),e&&this._source.updateTrack(this._mediaStreamTrack),this._useAudioElement&&_i.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 D(this,et.NEED_REPLACE_TRACK,this)):this._source.updateTrack(this._originMediaStreamTrack),this._getOriginVolumeLevel&&this._source.updateOriginTrack(e))}renewMediaStreamTrack(e){return Promise.resolve(void 0)}_ensureExtensionManager(e){return this._extensionManager||(this._extensionManager=e.createAudioExtensionManager(this),this._extensionManager.onOutputTrackChanged=e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,D(this,et.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,D(this,et.NEED_REPLACE_TRACK,this))}),this._extensionManager}useExtension(e,t){if(this._usePipeMode)throw new S(b.INVALID_OPERATION,"Cannot use useExtension() when pipe() mode is active. Call unpipe() first.");return this._ensureExtensionManager(e),this._useExtensionMode=!0,this._extensionManager.useExtension(e,t)}removeExtension(e){if(!this._extensionManager)return!1;const t=this._extensionManager.removeExtension(e);return t&&pe.info("[".concat(this.getTrackId(),"] removeExtension: ").concat(e.name)),this._extensionManager.hasExtensions||(this._useExtensionMode=!1),t}addReferenceTrack(e){if(!this._extensionManager)throw new S(b.INVALID_OPERATION,"Call useExtension() before addReferenceTrack().");this._extensionManager.addReferenceTrack(e),pe.info("[".concat(this.getTrackId(),"] addReferenceTrack"))}removeReferenceTrack(e){return!!this._extensionManager&&this._extensionManager.removeReferenceTrack(e)}pipe(e){if(this._useExtensionMode)throw new S(b.INVALID_OPERATION,"Cannot use pipe() when useExtension() mode is active. Call removeExtension() for all extensions first.");if(this._bypassWebAudio)throw new S(b.INVALID_OPERATION,"Can not process AudioTrack when bypassWebAudio set to true.");if(this.processor===e)return e;if(e._source)throw new S(b.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this._usePipeMode=!0,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,this._usePipeMode=!1,t.reset()}bindProcessorDestinationEvents(e){e.on(ft.ON_TRACK,(async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(!1),this._source.processedNode=this._source.createMediaStreamSourceNode(e),await D(this,et.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await D(this,et.NEED_REPLACE_TRACK,this))})),e.on(ft.ON_NODE,(e=>{this._source.processedNode=e}))}unbindProcessorDestinationEvents(e){e.removeAllListeners(ft.ON_TRACK),e.removeAllListeners(ft.ON_NODE)}bindProcessorContextEvents(e){e.on(Tt.REQUEST_CONSTRAINTS,(async e=>{e(this._originMediaStreamTrack.getSettings())}))}unbindProcessorContextEvents(e){e.removeAllListeners(Tt.REQUEST_CONSTRAINTS)}initWebAudio(){return this._trackSource instanceof Si&&(this._trackSource=new qt(this._mediaStreamTrack,!1,this._getOriginVolumeLevel?this._mediaStreamTrack:void 0)),this._trackSource}initProcessor(){const e=new yi(this._source.context,this.getTrackId(),"local"),t=new vi(e);return this._processorContext=e,this._processorDestination=t,this.bindProcessorContextEvents(e),this.bindProcessorDestinationEvents(t),this._source.on(ut.UPDATE_SOURCE,(()=>{this.processor&&this.processor.updateInput({node:this._source.processSourceNode,context:e})})),this._useAudioElement&&(this._useAudioElement=!1,this.isPlaying&&(_i.stop(this.getTrackId()),this._source.play()),D(this,et.NEED_REPLACE_MIXING_TRACK,this).then((()=>{pe.debug("[".concat(this.getTrackId(),"] replace from origin track to web audio track success"))})).catch((e=>{pe.warning("[".concat(this.getTrackId(),"] replace from origin track to web audio track failed"),e)}))),{processorContext:e,processorDestination:t}}}).prototype,"setVolume",[Wi],Object.getOwnPropertyDescriptor(rr.prototype,"setVolume"),rr.prototype),At(rr.prototype,"setPlaybackDevice",[Gi,Zi],Object.getOwnPropertyDescriptor(rr.prototype,"setPlaybackDevice"),rr.prototype),At(rr.prototype,"setEnabled",[Bi,Fi,Hi],Object.getOwnPropertyDescriptor(rr.prototype,"setEnabled"),rr.prototype),At(rr.prototype,"setMuted",[Ki,Xi,Yi],Object.getOwnPropertyDescriptor(rr.prototype,"setMuted"),rr.prototype),At(rr.prototype,"getStats",[ji],Object.getOwnPropertyDescriptor(rr.prototype,"getStats"),rr.prototype),At(rr.prototype,"setAudioFrameCallback",[zi],Object.getOwnPropertyDescriptor(rr.prototype,"setAudioFrameCallback"),rr.prototype),At(rr.prototype,"play",[Ji,Qi],Object.getOwnPropertyDescriptor(rr.prototype,"play"),rr.prototype),At(rr.prototype,"stop",[qi,$i],Object.getOwnPropertyDescriptor(rr.prototype,"stop"),rr.prototype),At(rr.prototype,"close",[er],Object.getOwnPropertyDescriptor(rr.prototype,"close"),rr.prototype),At(rr.prototype,"pipe",[tr],Object.getOwnPropertyDescriptor(rr.prototype,"pipe"),rr.prototype),At(rr.prototype,"unpipe",[ir],Object.getOwnPropertyDescriptor(rr.prototype,"unpipe"),rr.prototype),rr),Ar=(sr=_e({argsMap:(e,t)=>[e.getTrackId(),t]}),or=fi(),nr=q("MicrophoneAudioTrack","_enabledMutex"),ar=_e({argsMap:(e,t,i)=>[e.getTrackId(),t,i]}),cr=fi(),dr=_e({argsMap:e=>[e.getTrackId()]}),At((ur=class extends Ir{get __className__(){return"MicrophoneAudioTrack"}constructor(e,t,i,r){super(e,t.encoderConfig?He(t.encoderConfig):{},r,u("GET_VOLUME_OF_MUTED_AUDIO_TRACK")),Ct(this,"_config",void 0),Ct(this,"_deviceName","default"),Ct(this,"_constraints",void 0),Ct(this,"_originalConstraints",void 0),Ct(this,"_enabled",!0),this._config=t,this._constraints=i,this._originalConstraints=i,this._deviceName=e.label,"boolean"==typeof t.bypassWebAudio&&(this._bypassWebAudio=t.bypassWebAudio),(K()||ee())&&xt.bindInterruptDetectorTrack(this)}async setDevice(e){if(pe.info("[".concat(this.getTrackId(),"] start set device to ").concat(e)),this._enabled)try{const t=await ui.getDeviceById(e),i={};i.audio=Mt({},this._constraints),i.audio.deviceId={exact:e},this._originMediaStreamTrack.stop();let r=null;try{r=await oi(i,this.getTrackId())}catch(e){throw pe.error("[".concat(this.getTrackId(),"] setDevice failed"),e.toString()),r=await oi({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 pe.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}else try{const t=await ui.getDeviceById(e);this._deviceName=t.label,this._config.microphoneId=e,this._constraints.deviceId={exact:e}}catch(e){throw pe.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}pe.info("[".concat(this.getTrackId(),"] set device to ").concat(e," success"))}async setEnabled(e,t,i){if(t)return pe.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(pe.info("[".concat(this.getTrackId(),"] start setEnabled"),e),u("AUTO_RESET_AUDIO_ROUTE")&&(O()||L())){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 D(this,et.NEED_DISABLE_TRACK,this)}catch(e){throw pe.error("[".concat(this.getTrackId(),"] setEnabled false failed"),e.toString()),e}return}const s=Mt({},this._constraints),o=ui.searchDeviceIdByName(this._deviceName);o&&!s.deviceId&&(s.deviceId=o);try{i||(this._enabled=!0);const e=await oi({audio:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getAudioTracks()[0],!1),await D(this,et.NEED_ENABLE_TRACK,this)}catch(e){throw i||(this._enabled=!1),pe.error("[".concat(this.getTrackId(),"] setEnabled true failed"),e.toString()),e}pe.info("[".concat(this.getTrackId(),"] setEnabled success"))}close(){super.close(),(K()||ee())&&xt.unbindInterruptDetectorTrack(this),je()||Wt()}onTrackEnded(){if((O()||L())&&this._enabled&&!this._isClosed&&xt.duringInterruption){const e=async()=>{xt.off(Ne.IOS_INTERRUPTION_END,e),this._enabled&&!this._isClosed&&(pe.debug("[".concat(this.getTrackId(),"] try capture microphone media device for interrupted iOS device.")),await this.setEnabled(!1),await this.setEnabled(!0))};xt.on(Ne.IOS_INTERRUPTION_END,e)}else pe.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(at.TRACK_ENDED)}async renewMediaStreamTrack(e){const t=e||this._constraints,i=ui.searchDeviceIdByName(this._deviceName);if(i&&!t.deviceId&&(t.deviceId=i),this._constraints=t,this._enabled){this._originMediaStreamTrack.stop();const e=await oi({audio:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getAudioTracks()[0],!0)}}bindProcessorContextEvents(e){super.bindProcessorContextEvents(e),e.on(Tt.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(Tt.REQUEST_UPDATE_CONSTRAINTS)}}).prototype,"setDevice",[sr,or],Object.getOwnPropertyDescriptor(ur.prototype,"setDevice"),ur.prototype),At(ur.prototype,"setEnabled",[nr,ar,cr],Object.getOwnPropertyDescriptor(ur.prototype,"setEnabled"),ur.prototype),At(ur.prototype,"close",[dr],Object.getOwnPropertyDescriptor(ur.prototype,"close"),ur.prototype),ur),Rr=(hr=_e({argsMap:(e,t)=>[e.getTrackId(),t,e.duration]}),lr=fi(),pr=_e({argsMap:e=>[e.getTrackId()]}),mr=fi(),gr=_e({argsMap:e=>[e.getTrackId()]}),_r=fi(),fr=_e({argsMap:e=>[e.getTrackId()]}),Tr=fi(),Er=_e({argsMap:e=>[e.getTrackId()]}),vr=fi(),yr=_e({argsMap:e=>[e.getTrackId()]}),Sr=_e({argsMap:e=>[e.getTrackId()]}),br=fi(),At((kr=class extends Ir{get __className__(){return"BufferSourceAudioTrack"}constructor(e,t,i,r){super(t.createOutputTrack(),i,r),Ct(this,"source",void 0),Ct(this,"_bufferSource",void 0),this._useAudioElement=!1,this.source=e,this._bufferSource=t,this._bufferSource.on(ut.AUDIO_SOURCE_STATE_CHANGE,(e=>{this.safeEmit(at.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(e,"speed",0),this._bufferSource.setAudioBufferPlaybackSpeed(e)}}).prototype,"startProcessAudioBuffer",[hr,lr],Object.getOwnPropertyDescriptor(kr.prototype,"startProcessAudioBuffer"),kr.prototype),At(kr.prototype,"pauseProcessAudioBuffer",[pr,mr],Object.getOwnPropertyDescriptor(kr.prototype,"pauseProcessAudioBuffer"),kr.prototype),At(kr.prototype,"seekAudioBuffer",[gr,_r],Object.getOwnPropertyDescriptor(kr.prototype,"seekAudioBuffer"),kr.prototype),At(kr.prototype,"resumeProcessAudioBuffer",[fr,Tr],Object.getOwnPropertyDescriptor(kr.prototype,"resumeProcessAudioBuffer"),kr.prototype),At(kr.prototype,"stopProcessAudioBuffer",[Er,vr],Object.getOwnPropertyDescriptor(kr.prototype,"stopProcessAudioBuffer"),kr.prototype),At(kr.prototype,"close",[yr],Object.getOwnPropertyDescriptor(kr.prototype,"close"),kr.prototype),At(kr.prototype,"setAudioBufferPlaybackSpeed",[Sr,br],Object.getOwnPropertyDescriptor(kr.prototype,"setAudioBufferPlaybackSpeed"),kr.prototype),kr);class Cr extends Ir{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=Gt().createMediaStreamDestination();super(e.stream.getAudioTracks()[0],void 0,A(8,"track-mix-")),Ct(this,"trackList",void 0),Ct(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)?(pe.debug("add ".concat(e.getTrackId()," to mixing track")),e._source.outputNode.connect(this.destNode),this.trackList.push(e),this.updateEncoderConfig()):pe.debug("track ".concat(e.getTrackId()," is already added"))}removeAudioTrack(e){if(-1!==this.trackList.indexOf(e)){pe.debug("remove ".concat(e.getTrackId()," from mixing track"));try{e._source.outputNode.disconnect(this.destNode)}catch(e){}N(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 Cr?t.emit(nt.TRANSCEIVER_UPDATED,e):t._updateRtpTransceiver(e)})))}}class wr extends Qt{set currentState(e){e!==this._currentState&&(this._currentState=e,this.safeEmit(ut.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(),Ct(this,"audioBuffer",void 0),Ct(this,"sourceNode",void 0),Ct(this,"startPlayTime",0),Ct(this,"startPlayOffset",0),Ct(this,"pausePlayTime",0),Ct(this,"options",void 0),Ct(this,"currentLoopCount",0),Ct(this,"currentPlaybackSpeed",100),Ct(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):pe.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 Dr(e,t){if(0===e.length||0===t.length)return 1/0;const i=re(e),r=re(t);return Math.floor(r/i)}class Nr{get rendFrameRate(){const e=Math.max(1,Dr(this._render_interframe_delays_sizes,this._render_interframe_delays));return Math.floor(1e3/e)}get videoElementStatus(){return this._isInPage?this._videoElementStatus:St.DESTROYED}set videoElementStatus(e){e!==this._videoElementStatus&&(pe.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){Ct(this,"trackId",void 0),Ct(this,"config",void 0),Ct(this,"onFirstVideoFrameDecoded",void 0),Ct(this,"onFirstVideoFrameRender",void 0),Ct(this,"onVideoBufferReady",void 0),Ct(this,"onVideoStateChanged",void 0),Ct(this,"freezeTimeCounterList",[]),Ct(this,"renderFreezeAccTime",0),Ct(this,"renderFreezeAccTime2",0),Ct(this,"totalFreezeTime",0),Ct(this,"isKeepLastFrame",!1),Ct(this,"isDestroyed",!1),Ct(this,"timeUpdatedCount",0),Ct(this,"freezeTime",0),Ct(this,"playbackTime",0),Ct(this,"lastTimeUpdatedTime",0),Ct(this,"autoplayFailed",!1),Ct(this,"videoTrack",void 0),Ct(this,"videoElement",void 0),Ct(this,"cacheVideoElement",void 0),Ct(this,"cancelRVFId",void 0),Ct(this,"internal",!1),Ct(this,"_render_interframe_delays",[]),Ct(this,"_render_interframe_delays_sizes",[]),Ct(this,"_videoState",bt.VideoStateStopped),Ct(this,"videoElementCheckInterval",void 0),Ct(this,"videoElementFreezeTimeout",void 0),Ct(this,"_videoElementStatus",St.NONE),Ct(this,"_isInPage",!0),Ct(this,"isGettingVideoDimensions",!1),Ct(this,"startGetVideoDimensions",(()=>{const e=()=>{if(this.isGettingVideoDimensions=!0,this.videoElement.videoWidth*this.videoElement.videoHeight>4)return pe.debug("[".concat(this.trackId,"] current video dimensions:"),this.videoElement.videoWidth,this.videoElement.videoHeight),void(this.isGettingVideoDimensions=!1);setTimeout(e,500)};!this.isGettingVideoDimensions&&e()})),Ct(this,"autoResumeAfterInterruption",(()=>{this.videoTrack&&"live"===this.videoTrack.readyState&&"running"===xt.curState&&(pe.debug("[track-".concat(this.trackId,"] video element paused, auto resume for ").concat(se())),oe()?(this.videoElement.srcObject=null,this.videoElement.srcObject=new MediaStream([this.videoTrack]),this.videoElement.play()):(this.videoElement.pause(),this.videoElement.play()))})),Ct(this,"handleVideoEvents",(e=>{switch(e.type){case"play":case"playing":"play"===e.type&&pe.debug("[".concat(this.trackId,"] video element status: play")),this.startGetVideoDimensions(),this.videoElementStatus=St.PLAYING;break;case"loadeddata":if(this.videoState=bt.VideoStateStarting,this.onFirstVideoFrameRender&&this.onFirstVideoFrameRender(),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=St.CANPLAY;break;case"stalled":this.videoElementStatus=St.STALLED;break;case"suspend":this.videoElementStatus=St.SUSPEND;break;case"pause":this.videoElementStatus=St.PAUSED,O()||L()||c()&&this.autoplayFailed||!this.videoTrack||"live"!==this.videoTrack.readyState||(pe.debug("[track-".concat(this.trackId,"] video element paused, auto resume")),this.videoElement.play());break;case"waiting":this.videoElementStatus=St.WAITING;break;case"abort":this.videoElementStatus=St.ABORT;break;case"ended":this.videoElementStatus=St.ENDED;break;case"emptied":this.videoElementStatus=St.EMPTIED;break;case"error":{const e=this.videoElement.error;e&&(this.videoElementStatus=St.ERROR,pe.error("[".concat(this.trackId,"] media error: ").concat(e.message," (").concat(e.code,")")));break}case"timeupdate":{const e=performance.now();if(this.timeUpdatedCount+=1,this.onVideoBufferReady&&this.timeUpdatedCount>u("BUFFER_READY_FRAMES")&&this.onVideoBufferReady(),this.timeUpdatedCount<10)return void(this.lastTimeUpdatedTime=e);const t=e-this.lastTimeUpdatedTime,i=this.lastTimeUpdatedTime;if(this.lastTimeUpdatedTime=e,Xs.lastVisibleTime<Xs.lastHiddenTime||i<Xs.lastHiddenTime||i<Xs.lastVisibleTime)return;if(this.isSkipCalcRenderFreezeTime())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}}})),Ct(this,"autoResumeAfterInterruptionOnIOS15_16",(()=>{this.videoTrack&&"live"===this.videoTrack.readyState&&(pe.debug("[track-".concat(this.trackId,"] video element paused, auto resume for ").concat(se())),oe()?(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"),xt.on(Ne.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),xt.on(Ne.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&&mi(t,"video",e.message,this.trackId),"NotAllowedError"===e.name?(pe.warning("detected video element autoplay failed",e),this.autoplayFailed=!0,this.handleAutoPlayFailed()):pe.warning("[".concat(this.trackId,"] play warning: "),e)}));const r=e();if(("Safari"===r.name&&15===Number(r.version)||K())&&i&&i.then){const e=()=>{this.config.mirror&&!this.config.noStyle&&(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 pe.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 xi(e);r({buffer:t,width:i.width,height:i.height})}else s(new S(b.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED))}),e,t<0?.1:t>1?1:t)}))):await Vi(e)}destroy(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.isDestroyed=!0,xt.off(Ne.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),xt.off(Ne.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16),e?this.videoElement.pause():this.videoElement.srcObject=null,this.resetVideoElement(),this.freezeTimeCounterList=[],this.videoState=bt.VideoStateStopped}initVideoElement(){if(this._videoElementStatus!==St.NONE&&this._videoElementStatus!==St.DESTROYED||(this.videoElementStatus=St.INIT),!this.videoElementCheckInterval&&(Or.forEach((e=>{this.videoElement.addEventListener(e,this.handleVideoEvents)})),this.videoElementCheckInterval=window.setInterval((()=>{this._isInPage=ie(this.videoElement)}),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===bt.VideoStateDecoding&&("visible"===document.visibilityState?this.videoState=bt.VideoStateFrozen:document.addEventListener("visibilitychange",r))},o=(t,i)=>{if(this.videoElementStatus===St.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=re(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===bt.VideoStateStarting&&(this.videoState=bt.VideoStateDecoding),this.videoState===bt.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===bt.VideoStateFrozen&&(this.videoState=bt.VideoStateDecoding),t>u("VIDEO_FREEZE_DURATION")&&Xs.lastVisibleTime>=Xs.lastHiddenTime&&e.timestamp>Xs.lastVisibleTime&&e.timestamp>Xs.lastHiddenTime){const e=Math.min(66,Dr(this._render_interframe_delays_sizes,this._render_interframe_delays)),i=Math.max(0,t-(r-1)*e),s=i>e?i:0;this.renderFreezeAccTime2+=s,this.totalFreezeTime+=s,this.renderFreezeAccTime+=t}}e=Mt(Mt({},i),{},{timestamp:t})}else this.isSkipCalcRenderFreezeTime()&&(e=Mt(Mt({},i),{},{timestamp:t}));var r,n;u("ENABLE_VIDEO_FRAME_CALLBACK")&&(this.cancelRVFId=null===(r=(n=this.videoElement).requestVideoFrameCallback)||void 0===r?void 0:r.call(n,o))};this.cancelRVFId=null===(t=(i=this.videoElement).requestVideoFrameCallback)||void 0===t?void 0:t.call(i,o)}this.videoElement.controls=!1,this.videoElement.setAttribute("playsinline",""),G()&&!u("HIDE_NO_POSTER")&&(this.videoElement.poster="noposter");const r=e();if(this.config.noStyle||("Safari"===r.name&&15===Number(r.version)||K()||!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=>{pe.debug("[".concat(this.trackId,"] playback interrupted"),e.toString())}))}resetVideoElement(){var e,t;(Or.forEach((e=>{this.videoElement&&this.videoElement.removeEventListener(e,this.handleVideoEvents)})),this.videoElementCheckInterval&&(window.clearInterval(this.videoElementCheckInterval),this.videoElementCheckInterval=void 0),this.cancelRVFId&&this.videoElement)&&(null===(e=(t=this.videoElement).cancelVideoFrameCallback)||void 0===e||e.call(t,this.cancelRVFId),this.cancelRVFId=void 0);this.videoElementStatus=St.NONE}isSkipCalcRenderFreezeTime(){return this.videoElementStatus===St.DESTROYED||this.internal}handleAutoPlayFailed(){const e=t=>{t.preventDefault(),this.videoElement.play().then((()=>{pe.debug("[".concat(this.trackId,"] Video element for trackId:").concat(this.trackId," autoplay resumed."))})).catch((e=>{pe.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)),pi()}}const Or=["play","playing","loadeddata","canplay","pause","stalled","suspend","waiting","abort","emptied","ended","timeupdate","error"];class Lr extends Nr{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];super(e),Ct(this,"container",void 0),Ct(this,"slot",void 0),this.slot=e.element,this.internal=t,this.updateConfig(e)}updateConfig(e){this.config=e,this.trackId=e.trackId;const t=e.element;var i;!this.internal||this.slot?(t!==this.slot&&(this.destroy(),this.slot=t),this.createElements()):(this.slot=t,t&&this.container?(this.internal=!1,this.container.id="agora-video-player-".concat(this.trackId),this.videoElement.id="video_".concat(this.trackId),this.config.fit?this.videoElement.style.objectFit=this.config.fit:this.videoElement.style.objectFit="cover",null===(i=this.slot)||void 0===i||i.appendChild(this.container)):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 Vi(e)}destroy(){if(super.destroy(),this.videoElement.remove(),this.videoElement=document.createElement("video"),this.container){try{var e;this.container.remove(),null===(e=this.slot)||void 0===e||e.removeChild(this.container)}catch(e){}this.container=void 0}}createElements(){var e;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(),null===(e=this.slot)||void 0===e||e.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 Pr,Vr,xr,Ur,Wr,Gr,Zr,Br,Fr,Hr,Kr,Xr,Yr,jr,zr,Jr,Qr,qr,$r,es,ts,is,rs,ss,os,ns,as,cs,ds,us,hs,ls,ps,ms,gs,_s,fs,Ts;let Es=(Pr=_e({argsMap:(e,t,i)=>[e.getTrackId(),"string"==typeof t?t:t instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement",i]}),Vr=fi(),xr=_e({argsMap:e=>[e.getTrackId()]}),Ur=q("LocalVideoTrack","_enabledMutex"),Wr=_e({argsMap:(e,t)=>[e.getTrackId(),t]}),Gr=fi(),Zr=q("LocalVideoTrack","_enabledMutex"),Br=_e({argsMap:(e,t)=>[e.getTrackId(),t]}),Fr=fi(),Hr=_e({argsMap:(e,t)=>[e.getTrackId(),t,e._saveEncodeBitrateRatio]}),Kr=fi(),Xr=_e({argsMap:(e,t)=>[e.getTrackId(),t]}),Yr=fi(),jr=fi(),zr=_e({argsMap:(e,t,i)=>[e.getTrackId(),t,i]}),Jr=fi(),Qr=fi(),qr=fi(),$r=_e({argsMap:e=>[e.getTrackId()]}),es=fi(),ts=fi(),is=fi(),rs=fi(),ss=fi(),os=_e({argsMap:(e,t)=>[e.getTrackId(),t.name]}),ns=_e({argsMap:e=>[e.getTrackId()]}),as=_e({argsMap:e=>[e.getTrackId()]}),cs=_e({argsMap:(e,t,i)=>[e.getTrackId(),t.label,i]}),ds=class e extends Ot{get videoHeight(){if(c()){const e=this._mediaStreamTrack.getSettings().height;return this._videoHeight=e,this._videoHeight}return this._videoHeight}get videoWidth(){if(c()){const e=this._mediaStreamTrack.getSettings().width;return this._videoWidth=e,this._videoWidth}return this._videoWidth}get isPlaying(){return!(!this._player||this._player.videoElementStatus!==St.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),Ct(this,"trackMediaType",dt.VIDEO),Ct(this,"_player",void 0),Ct(this,"isUseScaleResolutionDownBy",!1),Ct(this,"_videoVisibleTimer",null),Ct(this,"_previousVideoVisibleStatus",void 0),Ct(this,"_clearPreviousVideoVisibleStatus",(()=>this._previousVideoVisibleStatus=void 0)),Ct(this,"_encoderConfig",void 0),Ct(this,"_scalabilityMode",{numSpatialLayers:1,numTemporalLayers:1}),Ct(this,"_optimizationMode",void 0),Ct(this,"_saveEncodeBitrateRatio",1),Ct(this,"_videoHeight",void 0),Ct(this,"_videoWidth",void 0),Ct(this,"_forceBitrateLimit",void 0),Ct(this,"_enabled",!0),Ct(this,"_processorDestination",void 0),Ct(this,"_processorContext",void 0),Ct(this,"_usePipeMode",!1),Ct(this,"_useExtensionMode",!1),Ct(this,"_extensionManager",void 0),c()){const t=e.getSettings(),i=t.width,r=t.height;this._videoWidth=i,this._videoHeight=r}else this.updateMediaStreamTrackResolution();if(this._scalabilityMode=r,this._optimizationMode=s,this._hints=n||[],i&&-1!==this._hints.indexOf(tt.CUSTOM_TRACK)?this._encoderConfig=ne(i):this._encoderConfig=i,-1===this._hints.indexOf(tt.SCREEN_TRACK))this.updateBitrateFromProfile();else if(ae(t.CHROME,115)&&ce()){const t=Ui(e);t&&(pe.info("local screen video track begin to inject frame"),this._mediaStreamTrack=t)}i&&-1!==this._hints.indexOf(tt.CUSTOM_TRACK)&&this.setEncoderConfiguration(i),this._processorContext=new Ei(this.getTrackId(),"local"),this._processorDestination=new Ti(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:(pe.warning("[".concat(this.getTrackId(),'] can not find "#').concat(e,'" element, use document.body')),e=document.body)}pe.debug("[".concat(this.getTrackId(),"] start video playback in ").concat(e instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement"),JSON.stringify(t));const i=Mt(Mt(Mt({},this._getDefaultPlayerConfig()),t),{},{trackId:this.getTrackId(),element:e});this._player?this._player.updateConfig(i):(e instanceof HTMLVideoElement?this._player=new Nr(i):this._player=new Lr(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(at.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,pe.debug("[".concat(this.getTrackId(),"] stop video playback")))}async setEnabled(e,t){if(!t){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(pe.info("[".concat(this.getTrackId(),"] start setEnabled"),e),!e){this._originMediaStreamTrack.enabled=!1;try{await D(this,et.NEED_DISABLE_TRACK,this)}catch(e){throw pe.error("[".concat(this.getTrackId(),"] setEnabled to false error"),e.toString()),e}return t||(this._enabled=!1),void pe.info("[".concat(this.getTrackId(),"] setEnabled to false success"))}this._originMediaStreamTrack.enabled=!0;try{await D(this,et.NEED_ENABLE_TRACK,this)}catch(e){throw pe.error("[".concat(this.getTrackId(),"] setEnabled to true error"),e.toString()),e}pe.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,pe.debug("[".concat(this.getTrackId(),"] start set muted: ").concat(e)),e?await D(this,et.NEED_MUTE_TRACK,this):await D(this,et.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),pe.debug("[".concat(this.getTrackId(),"] set save encode bitrate ratio, ").concat(e)),this._saveEncodeBitrateRatio=1;try{await D(this,et.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(pe)}}}async setEncoderConfiguration(e,t){if(!this._enabled)throw new S(b.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");if(e=Ge(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=Ii({encoderConfig:e});(c()||O()||L())&&(t.deviceId=void 0),pe.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 S(b.UNEXPECTED_ERROR,e.toString());throw pe.error("[".concat(this.getTrackId(),"] applyConstraints error"),t.toString()),t}}this._encoderConfig=e,-1===this._hints.indexOf(tt.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await D(this,et.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(pe)}}getStats(){R((()=>{pe.warning("[deprecated] LocalVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalVideoStats instead")}),"localVideoTrackGetStatsWarning");const e=$(this,et.GET_STATS);return e||Mt({},pt)}async setBeautyEffect(e){pe.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 Vi(e)}async findClosestProfile(){const e=this.getMediaStreamTrackSettings(),t=e.width,i=e.height,r=e.frameRate,s=this._encoderConfig||{},o=s.width,n=s.height,a=s.frameRate,c=z(this._videoWidth||t||o||0),d=z(this._videoHeight||i||n||0),u=Di(c,d,z(r||a||15));if(u)return pe.debug("[".concat(this.getTrackId(),"] find closest profile, ").concat(c,"x").concat(d," => ").concat(JSON.stringify(u))),this.setEncoderConfiguration(u)}async setBitrateLimit(e){pe.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 pe.error(b.INVALID_PARAMS,"optimization mode must be motion, detail or balanced");const t=this._optimizationMode;try{this._optimizationMode=e,await D(this,et.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this)}catch(e){throw this._optimizationMode=t,pe.error("[".concat(this.getTrackId(),"] set optimization mode failed"),e.toString()),e}pe.info("[".concat(this.getTrackId(),"] set optimization mode success (").concat(e,")"))}setScalabiltyMode(e){if(1===e.numSpatialLayers&&1!==e.numTemporalLayers)return pe.error(b.INVALID_PARAMS,"scalability mode currently not supported, no SVC."),void(this._scalabilityMode={numSpatialLayers:1,numTemporalLayers:1});this._scalabilityMode=e,pe.info("[".concat(this.getTrackId(),"] set scalability mode success (").concat(e,")"))}updateMediaStreamTrackResolution(){ki(this._originMediaStreamTrack).then((e=>{let t=Dt(e,2),i=t[0],r=t[1];this._videoHeight=r,this._videoWidth=i})).catch(Y)}_updatePlayerSource(){this._player&&this._player.updateVideoTrack(this._mediaStreamTrack)}_getDefaultPlayerConfig(){return{fit:"contain"}}async setSenderConfiguration(e){if(!this._enabled)throw new S(b.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");pe.debug("[".concat(this.getTrackId(),"] setSenderConfiguration applyConstraints"),JSON.stringify(e)),e=Ge(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(tt.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await D(this,et.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(pe)}}updateBitrateFromProfile(){if(!this._encoderConfig)return;const e=this.getMediaStreamTrackSettings(),t=e.width,i=e.height,r=e.frameRate;if(!t||!i||!r)return;const s=this._encoderConfig,o=s.bitrateMax,n=s.bitrateMin;if(null==n||null==o){const e=Ni(t,i,r,n,o),s=e.max,a=e.min;if(this._encoderConfig.bitrateMin=a,this._encoderConfig.bitrateMax=s,u("VIDEO_STANDARD_BITRATE_VERSION")&&null==n&&null==o){const e=Dt(Mi(t,i,r),2),s=e[0],o=e[1];this._encoderConfig.bitrateMax=s,this._encoderConfig.bitrateMin=a?Math.min(a,s):s,this._saveEncodeBitrateRatio=o,pe.debug("[".concat(this.getTrackId(),"] update new bitrate from profile, [w: ").concat(t,", h: ").concat(i,", fps: ").concat(r,"] => [brMax: ").concat(this._encoderConfig.bitrateMax,", brMin: ").concat(this._encoderConfig.bitrateMin,", save_bitrate_ratio: ").concat(this._saveEncodeBitrateRatio,"]"))}else pe.debug("[".concat(this.getTrackId(),"] update bitrate from profile, [w: ").concat(t,", h: ").concat(i,", fps: ").concat(r,"] => [brMax: ").concat(s,", brMin: ").concat(a,"]")),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},s=r.element,o=r.slot;if(this.isPlaying&&s instanceof HTMLVideoElement&&o instanceof HTMLElement){const e=de.checkOneElementVisible(s),t=Object.assign({},e);if(t.visible!==this._previousVideoVisibleStatus){this._previousVideoVisibleStatus=t.visible;const e=me.reportApiInvoke(null,{tag:w.TRACER,name:C.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 S(b.GET_VIDEO_ELEMENT_VISIBLE_ERROR,e.message)}}async renewMediaStreamTrack(e){}_ensureVideoExtensionManager(e){return this._extensionManager||(this._extensionManager=e.createVideoExtensionManager(this),this._extensionManager.onOutputTrackChanged=e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(),D(this,et.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),D(this,et.NEED_REPLACE_TRACK,this))},this._extensionManager.onEmpty=()=>{this._useExtensionMode=!1,this._extensionManager=void 0}),this._extensionManager}useExtension(e,t){if(this._usePipeMode)throw new S(b.INVALID_OPERATION,"Cannot use useExtension() when pipe() mode is active. Call unpipe() first.");return this._ensureVideoExtensionManager(e),this._useExtensionMode=!0,this._extensionManager.useExtension(e,t)}removeExtension(e){if(!this._extensionManager)return!1;const t=this._extensionManager.removeExtension(e);return t&&pe.info("[".concat(this.getTrackId(),"] removeExtension: ").concat(e.name)),this._extensionManager.hasExtensions||(this._useExtensionMode=!1),t}pipe(e){if(this._useExtensionMode)throw new S(b.INVALID_OPERATION,"Cannot use pipe() when useExtension() mode is active. Call removeExtension() for all extensions first.");if(this.processor===e)return e;if(e._source)throw new S(b.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this._usePipeMode=!0,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,this._usePipeMode=!1,e.reset()}close(){super.close(),this.unbindProcessorDestinationEvents(),this.unbindProcessorContextEvents(),this.unpipe(),this.processorDestination._source&&this.processorDestination._source.unpipe(),this._extensionManager&&(this._extensionManager.destroy(),this._extensionManager=void 0,this._useExtensionMode=!1)}clone(t){let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],r=this._encoderConfig;t&&(r=Mt(Mt({},r),Ge(t))),r=ue(r);const s=A(8,"track-video-cloned-"),o=new e(i?this._mediaStreamTrack.clone():this._mediaStreamTrack,r,ue(this._scalabilityMode),this._optimizationMode,s,ue(this._hints));return t&&r&&o.setEncoderConfiguration(r),pe.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 S(b.INVALID_PARAMS,"track should be an instance of MediaStreamTrack");if("video"!==e.kind)throw new S(b.INVALID_PARAMS,"track should be a video MediaStreamTrack");await this._updateOriginMediaStreamTrack(e,t,!0),this.updateMediaStreamTrackResolution()}sendSeiData(e){if(R((()=>{me.reportApiInvoke(null,{name:C.LOCAL_VIDEO_SEND_SEI_DATA,options:[],tag:w.TRACER}).onSuccess("")}),this._mediaStreamTrack.id||this.getTrackId()),!u("ENABLE_VIDEO_SEI")||!u("ENABLE_ENCODED_TRANSFORM"))return void pe.warning('To send/receive SEI, please call AgoraRTC.setParameter("ENABLE_VIDEO_SEI", true) before instantiate IAgoraRtcClient');if(e instanceof Uint8Array==!1)return new S(b.INVALID_PARAMS,"Invalid argument type, ILocalVideoTrack.sendSeiData() only accept Uint8Array argument.").throw();const t=this.getRTCRtpTransceiver();if(!t)return void pe.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||"video/h265"===r?this.safeEmit("sei-to-send",e):pe.warning("SEI is not supported by ".concat(r))}bindProcessorDestinationEvents(){this.processorDestination.on(ft.ON_TRACK,(async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(),await D(this,et.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await D(this,et.NEED_REPLACE_TRACK,this))}))}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(ft.ON_TRACK)}unbindProcessorContextEvents(){this.processorContext.removeAllListeners(Tt.REQUEST_UPDATE_CONSTRAINTS),this.processorContext.removeAllListeners(Tt.REQUEST_CONSTRAINTS)}},At(ds.prototype,"play",[Pr,Vr],Object.getOwnPropertyDescriptor(ds.prototype,"play"),ds.prototype),At(ds.prototype,"stop",[xr],Object.getOwnPropertyDescriptor(ds.prototype,"stop"),ds.prototype),At(ds.prototype,"setEnabled",[Ur,Wr,Gr],Object.getOwnPropertyDescriptor(ds.prototype,"setEnabled"),ds.prototype),At(ds.prototype,"setMuted",[Zr,Br,Fr],Object.getOwnPropertyDescriptor(ds.prototype,"setMuted"),ds.prototype),At(ds.prototype,"setSaveEncodeBitrateRatio",[Hr,Kr],Object.getOwnPropertyDescriptor(ds.prototype,"setSaveEncodeBitrateRatio"),ds.prototype),At(ds.prototype,"setEncoderConfiguration",[Xr,Yr],Object.getOwnPropertyDescriptor(ds.prototype,"setEncoderConfiguration"),ds.prototype),At(ds.prototype,"getStats",[jr],Object.getOwnPropertyDescriptor(ds.prototype,"getStats"),ds.prototype),At(ds.prototype,"setBeautyEffect",[zr,Jr],Object.getOwnPropertyDescriptor(ds.prototype,"setBeautyEffect"),ds.prototype),At(ds.prototype,"getCurrentFrameData",[Qr],Object.getOwnPropertyDescriptor(ds.prototype,"getCurrentFrameData"),ds.prototype),At(ds.prototype,"getCurrentFrameImage",[qr],Object.getOwnPropertyDescriptor(ds.prototype,"getCurrentFrameImage"),ds.prototype),At(ds.prototype,"findClosestProfile",[$r,es],Object.getOwnPropertyDescriptor(ds.prototype,"findClosestProfile"),ds.prototype),At(ds.prototype,"setBitrateLimit",[ts],Object.getOwnPropertyDescriptor(ds.prototype,"setBitrateLimit"),ds.prototype),At(ds.prototype,"setOptimizationMode",[is],Object.getOwnPropertyDescriptor(ds.prototype,"setOptimizationMode"),ds.prototype),At(ds.prototype,"setScalabiltyMode",[rs],Object.getOwnPropertyDescriptor(ds.prototype,"setScalabiltyMode"),ds.prototype),At(ds.prototype,"updateMediaStreamTrackResolution",[ss],Object.getOwnPropertyDescriptor(ds.prototype,"updateMediaStreamTrackResolution"),ds.prototype),At(ds.prototype,"pipe",[os],Object.getOwnPropertyDescriptor(ds.prototype,"pipe"),ds.prototype),At(ds.prototype,"unpipe",[ns],Object.getOwnPropertyDescriptor(ds.prototype,"unpipe"),ds.prototype),At(ds.prototype,"close",[as],Object.getOwnPropertyDescriptor(ds.prototype,"close"),ds.prototype),At(ds.prototype,"replaceTrack",[cs],Object.getOwnPropertyDescriptor(ds.prototype,"replaceTrack"),ds.prototype),ds),vs=(us=_e({argsMap:(e,t)=>[e.getTrackId(),t]}),hs=fi(),ls=q("CameraVideoTrack","_enabledMutex"),ps=_e({argsMap:(e,t)=>[e.getTrackId(),t]}),ms=fi(),gs=_e({argsMap:(e,t)=>[e.getTrackId(),t]}),_s=fi(),fs=_e({argsMap:e=>[e.getTrackId()]}),Ts=class e extends Es{get __className__(){return"CameraVideoTrack"}constructor(e,t,i,r,s,o){super(e,Ge(t.encoderConfig),r,s,o),Ct(this,"_config",void 0),Ct(this,"_originalConstraints",void 0),Ct(this,"_constraints",void 0),Ct(this,"_enabled",!0),Ct(this,"_deviceName","default"),Ct(this,"tryResumeVideoForIOS15_16WeChat",(async()=>{(K()||ee())&&!he()&&le()&&this._enabled&&!this._isClosed&&(pe.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=Ge(this._config.encoderConfig),xt.on(Ne.IOS_15_16_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),xt.on(Ne.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(pe.info("[".concat(this.getTrackId(),"] set device to ").concat(e)),this._enabled)try{const t=await ui.getDeviceById(e),i={};i.video=Mt({},this._constraints),i.video.deviceId={exact:e},i.video.facingMode=void 0,this._originMediaStreamTrack.stop();let r=null;try{r=await oi(i,this.getTrackId())}catch(e){throw pe.error("[".concat(this.getTrackId(),"] setDevice failed"),e.toString()),r=await oi({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 pe.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}else try{const t=await ui.getDeviceById(e);this._deviceName=t.label,this._config.cameraId=e,this._constraints.deviceId={exact:e}}catch(e){throw pe.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}pe.info("[".concat(this.getTrackId(),"] setDevice success"))}async _setDeviceByFacingModel(e){pe.info("[".concat(this.getTrackId(),"] set facingMode ").concat(e));const t={video:Mt(Mt({},this._constraints),{},{deviceId:void 0,facingMode:{exact:e}})};if(this._enabled){this._originMediaStreamTrack.stop();let e=null;try{e=await oi(t,this.getTrackId())}catch(t){throw pe.error("[".concat(this.getTrackId(),"] setDeviceByFacingModel failed"),t.toString()),e=await oi({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=Mt({},t.video),pe.info("[".concat(this.getTrackId(),"] setDeviceByFacingModel success"))}async setEnabled(e,t){if(!t){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(pe.info("[".concat(this.getTrackId(),"] start setEnabled"),e),e){try{if(this.isExternalTrack)this._originMediaStreamTrack.enabled=!0;else{const e=await oi({video:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!1)}await D(this,et.NEED_ENABLE_TRACK,this)}catch(e){throw pe.error("[".concat(this.getTrackId(),"] setEnabled true error"),e.toString()),e}this.updateMediaStreamTrackResolution(),pe.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 D(this,et.NEED_DISABLE_TRACK,this)}catch(e){throw pe.error("[".concat(this.getTrackId(),"] setEnabled to false error"),e.toString()),e}pe.info("[".concat(this.getTrackId(),"] setEnabled to false success"))}}async setEncoderConfiguration(e,t){if(!this._enabled)throw new S(b.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");e=Ge(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=ne(this._config);i.encoderConfig=e;const r=Ii(i);(c()||O()||L())&&(r.deviceId=void 0),pe.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 S(b.UNEXPECTED_ERROR,e.toString());throw pe.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(tt.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await D(this,et.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(pe)}}_getDefaultPlayerConfig(){return{mirror:!0,fit:"cover"}}onTrackEnded(){if((O()||L())&&this._enabled&&!this._isClosed&&xt.duringInterruption){const e=async()=>{xt.off(Ne.IOS_INTERRUPTION_END,e),this._enabled&&!this._isClosed&&(pe.debug("[".concat(this.getTrackId(),"] try capture camera media device for interrupted iOS device.")),await this.setEnabled(!1),await this.setEnabled(!0))};xt.on(Ne.IOS_INTERRUPTION_END,e)}else pe.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(at.TRACK_ENDED)}async renewMediaStreamTrack(e){const t=e||this._constraints,i=ui.searchDeviceIdByName(this._deviceName);if(i&&!t.deviceId&&(t.deviceId={exact:i}),this._enabled){const e=await oi({video:t},this.getTrackId());this._constraints=t,await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!0),this.updateMediaStreamTrackResolution()}}close(){super.close(),xt.off(Ne.IOS_15_16_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),xt.off(Ne.IOS_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat)}clone(t){let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],r=this._encoderConfig;t&&(r=Mt(Mt({},r),Ge(t))),r=ue(r);const s=A(8,"track-cam-cloned-"),o=new e(i?this._mediaStreamTrack.clone():this._mediaStreamTrack,ue(Mt(Mt({},this._config),{},{encoderConfig:r})),ue(this._constraints),ue(this._scalabilityMode),this._optimizationMode,s);return t&&r&&o.setEncoderConfiguration(r),pe.debug("clone track from ".concat(this.getTrackId()," to ").concat(s,", clone ").concat(i)),o}bindProcessorContextEvents(){this.processorContext.on(Tt.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(Tt.REQUEST_CONSTRAINTS,(async e=>{e(this._originMediaStreamTrack.getSettings())}))}},At(Ts.prototype,"setDevice",[us,hs],Object.getOwnPropertyDescriptor(Ts.prototype,"setDevice"),Ts.prototype),At(Ts.prototype,"setEnabled",[ls,ps,ms],Object.getOwnPropertyDescriptor(Ts.prototype,"setEnabled"),Ts.prototype),At(Ts.prototype,"setEncoderConfiguration",[gs,_s],Object.getOwnPropertyDescriptor(Ts.prototype,"setEncoderConfiguration"),Ts.prototype),At(Ts.prototype,"close",[fs],Object.getOwnPropertyDescriptor(Ts.prototype,"close"),Ts.prototype),Ts);function ys(e){const t=A(8,"track-cus-"),i=me.reportApiInvoke(null,{id:t,tag:w.TRACER,name:C.CREATE_CUSTOM_AUDIO_TRACK,options:[e]}),r=new Ir(e.mediaStreamTrack,e.encoderConfig?He(e.encoderConfig):{},t,!1);return pe.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=A(8,"track-mic-"),i=me.reportApiInvoke(null,{id:t,tag:w.TRACER,name:C.CREATE_MIC_AUDIO_TRACK,options:[e]}),r=wi(e);let s=null;pe.info("start create microphone audio track with config",JSON.stringify(e),"trackId",t);try{s=(await oi({audio:r},t)).getAudioTracks()[0]||null}catch(e){throw i.onError(e),e}if(!s){const e=new S(b.UNEXPECTED_ERROR,"can not find track in media stream");return i.onError(e),e.throw(pe)}const o=new Ar(s,e,r,t);return i.onSuccess(o.getTrackId()),pe.info("create microphone audio track success, trackId:",t),o}async function bs(e){var t;const i=e.cacheOnlineFile,r=e.encoderConfig;let s=e.source;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=A(8,"track-buf-"),a=me.reportApiInvoke(null,{id:n,tag:w.TRACER,name:C.CREATE_BUFFER_AUDIO_TRACK,options:[o]});if(u("DISABLE_WEBAUDIO"))throw new S(b.NOT_SUPPORTED,"can not create BufferSourceAudioTrack when WebAudio disabled");pe.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 pe.debug("use cached audio resource: ",e),t;try{i=(await te((()=>fe.get(e,{responseType:"arraybuffer"})),void 0,void 0,{maxRetryCount:3})).data}catch(e){throw new S(b.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 S(b.READ_LOCAL_AUDIO_FILE_ERROR))},r.onerror=()=>{i(new S(b.READ_LOCAL_AUDIO_FILE_ERROR))},r.readAsArrayBuffer(e)}));i=await t}const r=await Ft(i);return"string"==typeof e&&t&&Mr.set(e,r),r}(s,i)}catch(e){return a.onError(e),e.throw(pe)}const d=new wr(s),h=new Rr(c,d,r?He(r):{},n);return pe.info("create buffer source audio track success, trackId:",n),a.onSuccess(h.getTrackId()),h}function ks(e){const t=new Cr;return e.forEach((e=>t.addAudioTrack(e))),t}function Is(e){const t=A(8,"track-cus-"),i=me.reportApiInvoke(null,{id:t,tag:w.TRACER,name:C.CREATE_CUSTOM_VIDEO_TRACK,options:[e]});u("USE_STANDARD_BITRATE_DEFAULT")&&(delete e.bitrateMax,delete e.bitrateMin);const r=new Es(e.mediaStreamTrack,{width:e.width,height:e.height,frameRate:e.frameRate,bitrateMax:e.bitrateMax,bitrateMin:e.bitrateMin,minDownscaleWidth:e.minDownscaleWidth,minDownscaleHeight:e.minDownscaleHeight},e.scalabiltyMode?Be(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,t,[tt.CUSTOM_TRACK]);return i.onSuccess(r.getTrackId()),pe.info("create custom video track success with config",e,"trackId",r.getTrackId()),r}async function As(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const t=u("CAMERA_CAPTURE_CONFIG"),i=A(8,"track-cam-"),r=me.reportApiInvoke(null,{id:i,tag:w.TRACER,name:C.CREATE_CAM_VIDEO_TRACK,options:[Mt({},e),t]});t&&(e.encoderConfig=t);const s=Ii(e);let o=null;pe.info("start create camera video track with config",JSON.stringify(e),"trackId",i);try{o=(await oi({video:s},i)).getVideoTracks()[0]||null}catch(e){throw r.onError(e),e}if(!o){const e=new S(b.UNEXPECTED_ERROR,"can not find track in media stream");return r.onError(e),e.throw(pe)}if(e.optimizationMode&&ws(i,o,e,Ge(e.encoderConfig)),u("USE_STANDARD_BITRATE_DEFAULT")){const t=Ge(e.encoderConfig);e.encoderConfig=t,delete t.bitrateMax,delete t.bitrateMin}const n=new vs(o,e,s,e.scalabiltyMode?Be(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,i);return r.onSuccess(n.getTrackId()),pe.info("create camera video success, trackId:",i),n}async function Rs(){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=A(8,"track-mic-"),s=A(8,"track-cam-"),o=me.reportApiInvoke(null,{id:"".concat(r,"-").concat(s),tag:w.TRACER,name:C.CREATE_MIC_AND_CAM_TRACKS,options:[e,t,i]});i&&(t.encoderConfig=i);const n=Ii(t),a=wi(e);let c=null,d=null;pe.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 oi({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 S(b.UNEXPECTED_ERROR,"can not find tracks in media stream");return o.onError(e),e.throw(pe)}if(t.optimizationMode&&ws(s,d,t,Ge(t.encoderConfig)),u("USE_STANDARD_BITRATE_DEFAULT")){const e=Ge(t.encoderConfig);t.encoderConfig=e,delete e.bitrateMax,delete e.bitrateMin}const h=new Ar(c,e,a,r),l=new vs(d,t,n,t.scalabiltyMode?Be(t.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},t.optimizationMode,s);return o.onSuccess([h.getTrackId(),l.getTrackId()]),pe.info("create camera video track(".concat(s,") and microphone audio track(").concat(r,") success")),[h,l]}async function Cs(){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?Ci(t):void 0;i&&(t="auto");const r=A(8,"track-scr-v-"),s=me.reportApiInvoke(null,{id:r,tag:w.TRACER,name:C.CREATE_SCREEN_VIDEO_TRACK,options:[Mt({},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=Ai(e);let n=null,a=null;const c=ve();if(!c.supportShareAudio&&"enable"===t){const e=new S(b.NOT_SUPPORTED,"your browser or platform is not support share-screen with audio");return s.onError(e),e.throw(pe)}pe.info("start create screen video track with config",e,"withAudio",t,"trackId",r);const d=c.supportShareAudio&&"disable"!==t;try{const e=await oi({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 S(b.UNEXPECTED_ERROR,"can not find track in media stream");return s.onError(e),e.throw(pe)}if(!a&&"enable"===t){n&&n.stop();const e=new S(b.SHARE_AUDIO_NOT_ALLOWED);return s.onError(e),e.throw(pe)}if(e.optimizationMode||(e.optimizationMode="detail"),e.optimizationMode){ws(r,n,e,e.encoderConfig&&Ze(e.encoderConfig)||void 0),e.encoderConfig&&"string"!=typeof e.encoderConfig&&(e.encoderConfig.bitrateMin=e.encoderConfig.bitrateMax)}const u=new Es(n,e.encoderConfig?Ze(e.encoderConfig):{},e.scalabiltyMode?Be(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,r,[tt.SCREEN_TRACK]);if(!a)return s.onSuccess(u.getTrackId()),pe.info("create screen video track success","video:",u.getTrackId()),u;const h=new Ir(a,void 0,A(8,"track-scr-a-"),!1);return s.onSuccess([u.getTrackId(),h.getTrackId()]),pe.info("create screen video track success","video:",u.getTrackId(),"audio:",h.getTrackId()),[u,h]}function ws(e,t,i,r){i.optimizationMode&&(r&&r.width&&r.height?(i.encoderConfig=Mt(Mt({},r),{},{bitrateMin:r.bitrateMin,bitrateMax:r.bitrateMax}),"motion"!==i.optimizationMode&&"detail"!==i.optimizationMode||(t.contentHint=i.optimizationMode,t.contentHint===i.optimizationMode?pe.debug("[".concat(e,"] set content hint to"),i.optimizationMode):pe.debug("[".concat(e,"] set content hint failed")))):pe.warning("[".concat(e,"] can not apply optimization mode bitrate config, no encoderConfig")))}var Ms,Ds,Ns,Os,Ls,Ps,Vs,xs,Us,Ws,Gs,Zs,Bs;class Fs extends Nt{getUserId(){return this._userId}constructor(e,t,i,r){super(e,"track-".concat(e.kind,"-").concat(t,"-").concat(r.clientId,"_").concat(A(5,""))),Ct(this,"_userId",void 0),Ct(this,"_uintId",void 0),Ct(this,"_isDestroyed",!1),Ct(this,"store",void 0),Ct(this,"processor",void 0),Ct(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,pe.info("[".concat(this.getTrackId(),"] is destroyed")),this.stop(),super.close()}getProcessorStats(){return this.processorContext.gatherStats()}getProcessorUsage(){return this.processorContext.gatherUsage()}}let Hs=(Ms=_e({argsMap:(e,t,i)=>[e.getTrackId(),"string"==typeof t?t:t instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement",i]}),Ds=_e({argsMap:e=>[e.getTrackId()]}),Ns=_e({argsMap:(e,t)=>[e.getTrackId(),t.name]}),Os=_e({argsMap:e=>[e.getTrackId()]}),At((Ls=class extends Fs{get isPlaying(){return!(!this._player||this._player.videoElementStatus!==St.PLAYING)}get __className__(){return"RemoteVideoTrack"}constructor(e,t,i,r,s){super(e,t,i,r),Ct(this,"_videoVisibleTimer",null),Ct(this,"_previousVideoVisibleStatus",void 0),Ct(this,"_clearPreviousVideoVisibleStatus",(()=>this._previousVideoVisibleStatus=void 0)),Ct(this,"trackMediaType",dt.VIDEO),Ct(this,"_videoWidth",void 0),Ct(this,"_videoHeight",void 0),Ct(this,"_player",void 0),Ct(this,"_prePlayer",void 0),Ct(this,"processorDestination",void 0),Ct(this,"processorContext",void 0),Ct(this,"_usePipeMode",!1),Ct(this,"_useExtensionMode",!1),Ct(this,"_extensionManager",void 0),this._prePlayer=s,this.updateMediaStreamTrackResolution(),this.processorContext=new Ei(this.getTrackId(),"remote"),this.processorDestination=new Ti(this.processorContext),this.bindProcessorDestinationEvents()}getStats(){R((()=>{pe.warning("[deprecated] RemoteVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteVideoStats instead")}),"remoteVideoTrackGetStatsWarning");return $(this,et.GET_STATS)||Mt({},_t)}play(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.safeEmit(ct.PLAY_START),"string"==typeof e){const t=document.getElementById(e);t?e=t:(pe.warning("[".concat(this.getTrackId(),'] can not find "#').concat(e,'" element, use document.body')),e=document.body)}pe.debug("[".concat(this.getTrackId(),"] start video playback in ").concat(e instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement"),JSON.stringify(t));const i=Mt(Mt({fit:"cover"},t),{},{trackId:this.getTrackId(),element:e});if(this._player)this._player.updateConfig(i);else{let t=!1,r=!1;const s=this._prePlayer&&!this._prePlayer.isDestroyed&&e===this._prePlayer.config.element;this._prePlayer&&!s&&(this._prePlayer.destroy(),r=!0),s?(this._player=this._prePlayer,t=this._player.videoState>0,this._player.updateConfig(i)):this._player=e instanceof HTMLVideoElement?new Nr(i):new Lr(i),this._prePlayer=void 0,this._player.updateVideoTrack(this._mediaStreamTrack),this._player.onFirstVideoFrameDecoded=()=>{this.store.subscribe(this.getUserId(),"video",void 0,void 0,Date.now()),this.safeEmit(ct.FIRST_FRAME_DECODED),r&&this.safeEmit(ct.FIRST_FRAME_RENDER)},this._player.onVideoStateChanged=e=>{this.safeEmit(ct.VIDEO_STATE_CHANGED,e)},t&&(this._player.onFirstVideoFrameDecoded(),this._player.onVideoStateChanged(this._player.videoState))}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(ct.VIDEO_ELEMENT_VISIBLE_STATUS,e)}catch(e){}}),u("CHECK_VIDEO_VISIBLE_INTERVAL")),this.safeEmit(ct.PLAY_END)}stop(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this._player&&(this._videoVisibleTimer&&(window.clearInterval(this._videoVisibleTimer),this._videoVisibleTimer=null),this._clearPreviousVideoVisibleStatus(),this._player.destroy(e),this._player=void 0,pe.debug("[".concat(this.getTrackId(),"] stop video playback")))}getCurrentFrameData(){return this._player?this._player.getCurrentFrame():new ImageData(2,2)}updateMediaStreamTrackResolution(){ki(this._originMediaStreamTrack).then((e=>{let t=Dt(e,2),i=t[0],r=t[1];this._videoHeight=r,this._videoWidth=i})).catch(Y)}_updatePlayerSource(){pe.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},s=r.element,o=r.slot;if(this.isPlaying&&s instanceof HTMLVideoElement&&o instanceof HTMLElement){const e=de.checkOneElementVisible(s),t=Object.assign({},e);if(t.visible!==this._previousVideoVisibleStatus){this._previousVideoVisibleStatus=t.visible;const e=me.reportApiInvoke(null,{tag:w.TRACER,name:C.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 S(b.GET_VIDEO_ELEMENT_VISIBLE_ERROR,e.message)}}_ensureVideoExtensionManager(e){return this._extensionManager||(this._extensionManager=e.createVideoExtensionManager(this),this._extensionManager.onOutputTrackChanged=e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource()):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource())},this._extensionManager.onEmpty=()=>{this._useExtensionMode=!1,this._extensionManager=void 0}),this._extensionManager}useExtension(e,t){if(this._usePipeMode)throw new S(b.INVALID_OPERATION,"Cannot use useExtension() when pipe() mode is active. Call unpipe() first.");return this._ensureVideoExtensionManager(e),this._useExtensionMode=!0,this._extensionManager.useExtension(e,t)}removeExtension(e){if(!this._extensionManager)return!1;const t=this._extensionManager.removeExtension(e);return t&&pe.info("[".concat(this.getTrackId(),"] removeExtension: ").concat(e.name)),this._extensionManager.hasExtensions||(this._useExtensionMode=!1),t}pipe(e){if(this._useExtensionMode)throw new S(b.INVALID_OPERATION,"Cannot use pipe() when useExtension() mode is active. Call removeExtension() for all extensions first.");if(this.processor===e)return e;if(e._source)throw new S(b.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this._usePipeMode=!0,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,this._usePipeMode=!1,e.reset()}bindProcessorDestinationEvents(){this.processorDestination.on(ft.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(ft.ON_TRACK)}_destroy(){this._prePlayer&&(this._prePlayer.destroy(),this._prePlayer=void 0),this._extensionManager&&(this._extensionManager.destroy(),this._extensionManager=void 0,this._useExtensionMode=!1),super._destroy(),this.unbindProcessorDestinationEvents()}_onSei(e,t){this.emit(nt.SEI_RECEIVED,e,t)}}).prototype,"play",[Ms],Object.getOwnPropertyDescriptor(Ls.prototype,"play"),Ls.prototype),At(Ls.prototype,"stop",[Ds],Object.getOwnPropertyDescriptor(Ls.prototype,"stop"),Ls.prototype),At(Ls.prototype,"pipe",[Ns],Object.getOwnPropertyDescriptor(Ls.prototype,"pipe"),Ls.prototype),At(Ls.prototype,"unpipe",[Os],Object.getOwnPropertyDescriptor(Ls.prototype,"unpipe"),Ls.prototype),Ls),Ks=(Ps=_e({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),Vs=_e({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),xs=_e({argsMap:(e,t)=>[e.getTrackId(),t]}),Us=_e({argsMap:e=>[e.getTrackId()]}),Ws=_e({argsMap:e=>[e.getTrackId()]}),Gs=_e({argsMap:(e,t)=>[e.getTrackId(),t.name]}),Zs=_e({argsMap:e=>[e.getTrackId()]}),At((Bs=class extends Fs{get isPlaying(){return this._useAudioElement?_i.isPlaying(this.getTrackId()):this._source.isPlayed}get __className__(){return"RemoteAudioTrack"}constructor(e,t,i,r){super(e,t,i,r),Ct(this,"trackMediaType",dt.AUDIO),Ct(this,"_source",void 0),Ct(this,"_useAudioElement",!0),Ct(this,"_volume",100),Ct(this,"processorContext",void 0),Ct(this,"processorDestination",void 0),Ct(this,"_usePipeMode",!1),Ct(this,"_useExtensionMode",!1),Ct(this,"_extensionManager",void 0),Ct(this,"_played",!1),Ct(this,"_bypassWebAudio",!1),u("DISABLE_WEBAUDIO")?(this._source=new Si,this._bypassWebAudio=!0,this._useAudioElement=!0):(this._source=new qt(e,!0),u("REMOTE_AUDIO_TRACK_USES_WEB_AUDIO")&&(this._useAudioElement=!1)),this._source.once(ut.RECEIVE_TRACK_BUFFER,(()=>{this.safeEmit(ct.FIRST_FRAME_DECODED)})),this.processorContext=new yi(this._source.context,this.getTrackId(),"remote"),this.processorDestination=new vi(this.processorContext),this.bindProcessorDestinationEvents(),this._source.on(ut.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(ut.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(t),this._source.removeAllListeners(ut.ON_AUDIO_BUFFER),this._source.on(ut.ON_AUDIO_BUFFER,(t=>e(t)))}setVolume(e){this._volume=e,this._useAudioElement?_i.setVolume(this.getTrackId(),e):this._source.setVolume(e/100)}setAmplifiedVolume(e){this._useAudioElement&&this._played&&(_i.stop(this.getTrackId()),this._source.play()),this._useAudioElement=!1,e=Math.min(e,u("MAX_WEBAUDIO_VOLUME")),this._volume=e,this._source.setVolume(e/100)}async setPlaybackDevice(e){if(!this._useAudioElement||!ye())throw new S(b.NOT_SUPPORTED,"your browser does not support setting the audio output device");await _i.setSinkID(this.getTrackId(),e)}getVolumeLevel(){return this._source.getAccurateVolumeLevel()}getVolume(){return this._useAudioElement?_i.getVolume(this.getTrackId()):this._source instanceof qt?this._source.getAudioVolume():0}getStats(){R((()=>{pe.warning("[deprecated] RemoteAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteAudioStats instead")}),"remoteAudioTrackGetStatsWarning");return $(this,et.GET_STATS)||Mt({},mt)}play(){if(pe.debug("[".concat(this.getTrackId(),"] start audio playback")),this._played=!0,this._useAudioElement)pe.debug("[".concat(this.getTrackId(),"] use audio element to play")),_i.play(this._mediaStreamTrack,this.getTrackId(),this._volume,this.store.sessionId||void 0);else{var e;pe.debug("[".concat(this.getTrackId(),"] use audio context to play"));const t=null===(e=this._source.context)||void 0===e?void 0:e.state;t&&"running"!==t&&mi(this.store.sessionId||null,"audio","AudioContext state is ".concat(t),this.getTrackId()),this._source.play()}}stop(){pe.debug("[".concat(this.getTrackId(),"] stop audio playback")),this._played=!1,this._useAudioElement?_i.stop(this.getTrackId()):this._source.stop()}_reusePreAudioElement(e,t){this._played=t,this._useAudioElement?(_i.reuseTrackId(e,this.getTrackId()),this._updatePlayerSource()):(_i.stop(e),this._updatePlayerSource(),t&&this._source.play()),this.setVolume(this._volume)}_destroy(){super._destroy(),this._played=!1,this._extensionManager&&(this._extensionManager.destroy(),this._extensionManager=void 0,this._useExtensionMode=!1),this.unbindProcessorDestinationEvents(),this._source.destroy()}_isFreeze(){return this._source.isFreeze}_updatePlayerSource(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];pe.debug("[".concat(this.getTrackId(),"] update player source track")),e&&this._source.updateTrack(this._mediaStreamTrack),this._useAudioElement&&_i.updateTrack(this.getTrackId(),this._mediaStreamTrack)}_ensureAudioExtensionManager(e){return this._extensionManager||(this._extensionManager=e.createAudioExtensionManager(this),this._extensionManager.onOutputTrackChanged=e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(!1)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource())}),this._extensionManager}useExtension(e){if(this._usePipeMode)throw new S(b.INVALID_OPERATION,"Cannot use useExtension() when pipe() mode is active. Call unpipe() first.");return this._ensureAudioExtensionManager(e),this._useExtensionMode=!0,this._extensionManager.useExtension(e)}removeExtension(e){if(!this._extensionManager)return!1;const t=this._extensionManager.removeExtension(e);return t&&pe.info("[".concat(this.getTrackId(),"] removeExtension: ").concat(e.name)),this._extensionManager.hasExtensions||(this._useExtensionMode=!1),t}addReferenceTrack(e){if(!this._extensionManager)throw new S(b.INVALID_OPERATION,"Call useExtension() before addReferenceTrack().");this._extensionManager.addReferenceTrack(e),pe.info("[".concat(this.getTrackId(),"] addReferenceTrack"))}removeReferenceTrack(e){return!!this._extensionManager&&this._extensionManager.removeReferenceTrack(e)}pipe(e){if(this._useExtensionMode)throw new S(b.INVALID_OPERATION,"Cannot use pipe() when useExtension() mode is active.");if(this._bypassWebAudio)throw new S(b.NOT_SUPPORTED,"can not pipe extension when WebAudio disabled");if(this.processor===e)return e;if(e._source)throw new S(b.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this._usePipeMode=!0,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 S(b.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,this._usePipeMode=!1,t.reset()}bindProcessorDestinationEvents(){this.processorDestination.on(ft.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(ft.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(ft.ON_TRACK),this.processorDestination.removeAllListeners(ft.ON_NODE)}}).prototype,"setVolume",[Ps],Object.getOwnPropertyDescriptor(Bs.prototype,"setVolume"),Bs.prototype),At(Bs.prototype,"setAmplifiedVolume",[Vs],Object.getOwnPropertyDescriptor(Bs.prototype,"setAmplifiedVolume"),Bs.prototype),At(Bs.prototype,"setPlaybackDevice",[xs],Object.getOwnPropertyDescriptor(Bs.prototype,"setPlaybackDevice"),Bs.prototype),At(Bs.prototype,"play",[Us],Object.getOwnPropertyDescriptor(Bs.prototype,"play"),Bs.prototype),At(Bs.prototype,"stop",[Ws],Object.getOwnPropertyDescriptor(Bs.prototype,"stop"),Bs.prototype),At(Bs.prototype,"pipe",[Gs],Object.getOwnPropertyDescriptor(Bs.prototype,"pipe"),Bs.prototype),At(Bs.prototype,"unpipe",[Zs],Object.getOwnPropertyDescriptor(Bs.prototype,"unpipe"),Bs.prototype),Bs);const Xs=new class extends I{get visibility(){return document.visibilityState}get lastHiddenTime(){return this._lastHiddenTime}get lastVisibleTime(){return this._lastVisibleTime}constructor(){super(),Ct(this,"_lastHiddenTime",0),Ct(this,"_lastVisibleTime",0),Ct(this,"needUploadStats",[]),Ct(this,"isCollectingStats",!1),document.addEventListener("visibilitychange",(()=>{"hidden"===document.visibilityState?this._lastHiddenTime=performance.now():this._lastVisibleTime=performance.now(),this.isCollectingStats&&this.needUploadStats.push("visible"===document.visibilityState?1:0),pe.debug("current web page is ".concat(document.visibilityState)),this.emit("VISIBILITY_CHANGE",document.visibilityState)}))}startCollectStats(){this.isCollectingStats=!0,this.needUploadStats.push("visible"===this.visibility?1:0)}stopCollectStats(){this.isCollectingStats=!1,this.needUploadStats.length=0}};class Ys extends I{constructor(e,t){super(),Ct(this,"trackMediaType",dt.DATA),Ct(this,"_version",1),Ct(this,"_type",3),Ct(this,"_config",void 0),Ct(this,"_originDataChannel",void 0),Ct(this,"_dataStreamPacketHeader",new ArrayBuffer(4)),Ct(this,"_dataStreamPacketHandler",{serialize:e=>e,deserialize:e=>e}),Ct(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 S(b.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 S(b.DATACHANNEL_CONNECTION_TIMEOUT)}}else t(new S(b.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),[It.OPEN,It.CLOSE,It.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=Dt(t,2),r=i[0],s=i[1];e.removeEventListener(r,s)})),this._datachannelEventMap.clear()}}class js extends Ys{constructor(e){super(e),Ct(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")&&pe.debug("invalid datachannel id: ".concat(i," !== ").concat(this.id)));let r=e.data.slice(this._dataStreamPacketHeader.byteLength);r=this._dataStreamPacketHandler.deserialize(r),this.emit(It.MESSAGE,r)}}_updateDataChannelConfig(e){this._config=e}_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 zs extends Ys{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 Js(){const e=new Blob([atob("ZnVuY3Rpb24gdCh0LGUsbil7cmV0dXJuKGU9ZnVuY3Rpb24odCl7dmFyIGU9ZnVuY3Rpb24odCxlKXtpZigib2JqZWN0IiE9dHlwZW9mIHR8fCF0KXJldHVybiB0O3ZhciBuPXRbU3ltYm9sLnRvUHJpbWl0aXZlXTtpZih2b2lkIDAhPT1uKXt2YXIgcj1uLmNhbGwodCxlfHwiZGVmYXVsdCIpO2lmKCJvYmplY3QiIT10eXBlb2YgcilyZXR1cm4gcjt0aHJvdyBuZXcgVHlwZUVycm9yKCJAQHRvUHJpbWl0aXZlIG11c3QgcmV0dXJuIGEgcHJpbWl0aXZlIHZhbHVlLiIpfXJldHVybigic3RyaW5nIj09PWU/U3RyaW5nOk51bWJlcikodCl9KHQsInN0cmluZyIpO3JldHVybiJzeW1ib2wiPT10eXBlb2YgZT9lOmUrIiJ9KGUpKWluIHQ/T2JqZWN0LmRlZmluZVByb3BlcnR5KHQsZSx7dmFsdWU6bixlbnVtZXJhYmxlOiEwLGNvbmZpZ3VyYWJsZTohMCx3cml0YWJsZTohMH0pOnRbZV09bix0fWZ1bmN0aW9uIGUodCxlKXt2YXIgbj1PYmplY3Qua2V5cyh0KTtpZihPYmplY3QuZ2V0T3duUHJvcGVydHlTeW1ib2xzKXt2YXIgcj1PYmplY3QuZ2V0T3duUHJvcGVydHlTeW1ib2xzKHQpO2UmJihyPXIuZmlsdGVyKChmdW5jdGlvbihlKXtyZXR1cm4gT2JqZWN0LmdldE93blByb3BlcnR5RGVzY3JpcHRvcih0LGUpLmVudW1lcmFibGV9KSkpLG4ucHVzaC5hcHBseShuLHIpfXJldHVybiBufWNvbnN0IG49InZpZGVvL2gyNjQiLHI9InZpZGVvL2gyNjUiO2Z1bmN0aW9uIGEodCxlLG4pe2NvbnN0IHI9bmV3IFVpbnQ4QXJyYXkodCxlLG4pLGE9W107bGV0IG89MDtmb3IoO2EubGVuZ3RoPG47KW8rMzxuJiYwPT09cltvXSYmMD09PXJbbysxXSYmMz09PXJbbysyXSYmKDA9PT1yW28rM118fDE9PT1yW28rM118fDI9PT1yW28rM118fDM9PT1yW28rM10pPyhhLnB1c2gocltvXSxyW28rMV0scltvKzNdKSxvKz00KTooYS5wdXNoKHJbb10pLG8rKyk7cmV0dXJuIG5ldyBVaW50OEFycmF5KGEpfWZ1bmN0aW9uIG8odCxlKXtzd2l0Y2goZSl7Y2FzZSBuOnJldHVybiBmdW5jdGlvbih0KXtjb25zdCBlPW5ldyBEYXRhVmlldyh0LmRhdGEpO2xldCBuPTA7Zm9yKDtuKzQ8dC5kYXRhLmJ5dGVMZW5ndGg7KXtpZigwPT09ZS5nZXRVaW50OChuKzApJiYwPT09ZS5nZXRVaW50OChuKzEpJiYwPT09ZS5nZXRVaW50OChuKzIpJiYxPT09ZS5nZXRVaW50OChuKzMpJiY2PT09ZS5nZXRVaW50OChuKzQpKXtsZXQgcj1uKzYsbz0wLGk9MDtmb3IoOzI1NT09PShpPWUuZ2V0VWludDgocisrKSk7KW8rPTI1NTtvKz1pO2NvbnN0IHM9YSh0LmRhdGEscixvKTtyZXR1cm4gbmV3IFVpbnQ4QXJyYXkocyl9bisrfXJldHVybiBudWxsfSh0KTtjYXNlIHI6cmV0dXJuIGZ1bmN0aW9uKHQpe2NvbnN0IGU9bmV3IERhdGFWaWV3KHQuZGF0YSk7bGV0IG49MDtmb3IoO24rNTx0LmRhdGEuYnl0ZUxlbmd0aDspe2lmKDA9PT1lLmdldFVpbnQ4KG4rMCkmJjA9PT1lLmdldFVpbnQ4KG4rMSkmJjA9PT1lLmdldFVpbnQ4KG4rMikmJjE9PT1lLmdldFVpbnQ4KG4rMykmJjc4PT09ZS5nZXRVaW50OChuKzQpJiYxPT09ZS5nZXRVaW50OChuKzUpJiYxMDE9PT1lLmdldFVpbnQ4KG4rNikpe2xldCByPW4rNyxvPTAsaT0wO2Zvcig7MjU1PT09KGk9ZS5nZXRVaW50OChyKyspKTspbys9MjU1O28rPWk7Y29uc3Qgcz1hKHQuZGF0YSxyLG8pO3JldHVybiBuZXcgVWludDhBcnJheShzKX1uKyt9cmV0dXJuIG51bGx9KHQpO2RlZmF1bHQ6cmV0dXJuIG51bGx9fWZ1bmN0aW9uIGkodCl7Y29uc3QgZT10Lmxlbmd0aCxuPVtdO2xldCByPTA7Zm9yKDtyPGU7KXIrMjxlJiYwPT09dFtyXSYmMD09PXRbcisxXSYmKDA9PT10W3IrMl18fDE9PT10W3IrMl18fDI9PT10W3IrMl18fDM9PT10W3IrMl0pPyhuLnB1c2godFtyXSx0W3IrMV0sMyx0W3IrMl0pLHIrPTMpOihuLnB1c2godFtyXSkscisrKTtyZXR1cm4gbmV3IFVpbnQ4QXJyYXkobil9ZnVuY3Rpb24gcyh0LGUsYSl7c3dpdGNoKGEpe2Nhc2UgbjpyZXR1cm4gZnVuY3Rpb24odCxlKXtjb25zdCBuPWkoZSkscj1uLmxlbmd0aCxhPU1hdGguZmxvb3Ioci8yNTUpLG89ciUyNTUscz1uZXcgVWludDhBcnJheSg2K2ErMStyKzErdC5ieXRlTGVuZ3RoKTtzWzBdPTAsc1sxXT0wLHNbMl09MCxzWzNdPTEsc1s0XT02LHNbNV09MTAxO2xldCBmPTA7Zm9yKDtmPGE7KXNbNitmXT0yNTUsZisrO3JldHVybiBzWzYrZl09byxmKysscy5zZXQobiw2K2YpLGYrPXIsc1s2K2ZdPTEyOCxmKysscy5zZXQobmV3IFVpbnQ4QXJyYXkodCksNitmKSxzLmJ1ZmZlcn0odCxlKTtjYXNlIHI6cmV0dXJuIGZ1bmN0aW9uKHQsZSl7Y29uc3Qgbj1pKGUpLHI9bi5sZW5ndGgsYT1NYXRoLmZsb29yKHIvMjU1KSxvPXIlMjU1LHM9bmV3IFVpbnQ4QXJyYXkoNythKzErcisxK3QuYnl0ZUxlbmd0aCk7c1swXT0wLHNbMV09MCxzWzJdPTAsc1szXT0xLHNbNF09Nzgsc1s1XT0xLHNbNl09MTAxO2xldCBmPTA7Zm9yKDtmPGE7KXNbNytmXT0yNTUsZisrO3JldHVybiBzWzcrZl09byxmKysscy5zZXQobiw3K2YpLGYrPXIsc1s3K2ZdPTEyOCxmKysscy5zZXQobmV3IFVpbnQ4QXJyYXkodCksNytmKSxzLmJ1ZmZlcn0odCxlKTtkZWZhdWx0OnJldHVybiBudWxsfX1mdW5jdGlvbiBmKHQpe2lmKHQubGVuZ3RoPDUpcmV0dXJuIiI7bGV0IGU9LTE7Zm9yKGxldCBuPTA7bjx0Lmxlbmd0aC0zO24rKyl7aWYoMD09PXRbbl0mJjA9PT10W24rMV0mJjE9PT10W24rMl0pe2U9bjticmVha31pZihuPHQubGVuZ3RoLTQmJjA9PT10W25dJiYwPT09dFtuKzFdJiYwPT09dFtuKzJdJiYxPT09dFtuKzNdKXtlPW47YnJlYWt9fWlmKC0xPT09ZSlyZXR1cm4iIjtjb25zdCBhPWUrKDA9PT10W2UrMl0/NDozKTtpZihhPj10Lmxlbmd0aClyZXR1cm4iIjtjb25zdCBvPXRbYV07aWYoMTI4Jm8pcmV0dXJuIiI7aWYoKG8+PjEmNjMpPj0zMilyZXR1cm4gcjtpZihhKzE8dC5sZW5ndGgpe2lmKDA9PSgyNDgmdFthKzFdKSlyZXR1cm4gcn1yZXR1cm4oMzEmbyk8PTMxP246IiJ9Y29uc3QgdT03MSxsPTEsYz0yLGc9MSxwPTI7dmFyIGQ9ZnVuY3Rpb24odCl7cmV0dXJuIHRbdC5BVURJT19MRVZFTD0xXT0iQVVESU9fTEVWRUwiLHRbdC5NRVRBREFUQT0yXT0iTUVUQURBVEEiLHRbdC5BVURJT182NF9CSVRfUFRTPTNdPSJBVURJT182NF9CSVRfUFRTIix0fShkfHx7fSk7ZnVuY3Rpb24geSh0KXtpZih0LmJ5dGVMZW5ndGg8PTApcmV0dXJuW107Y29uc3QgZT1bXTtsZXQgbj0wLHI9MDtmb3IoO248dC5ieXRlTGVuZ3RoOyl7Y29uc3QgYT10LmdldFVpbnQ4KG4pLG89MTI3JmE7aWYoISgoMTI4JmEpPj43KSl7cj1vLG4rKzticmVha317aWYobis0PnQuYnl0ZUxlbmd0aClyZXR1cm5bXTtjb25zdCByPXQuZ2V0VWludDMyKG4sITEpLGE9KDE2Nzc2MTkyJnIpPj4xMCxpPTEwMjMmcjtlLnB1c2goe3B0Om8sdHNfb2Zmc2V0OmEsbGVuZ3RoOmksZGF0YTpuZXcgVWludDhBcnJheX0pLG4rPTR9fWxldCBhPXQuYnl0ZUxlbmd0aC1uO2Zvcihjb25zdCByIG9mIGUpe2lmKHIubGVuZ3RoPmEpcmV0dXJuIGNvbnNvbGUud2FybigiQnJva2VuIHJlZCBwYXlsb2FkIiksW107ci5sZW5ndGg+MCYmKHIuZGF0YT1uZXcgVWludDhBcnJheSh0LmJ1ZmZlcix0LmJ5dGVPZmZzZXQrbixyLmxlbmd0aCksbis9ci5sZW5ndGgsYS09ci5sZW5ndGgpfWlmKGE+MCl7Y29uc3Qgbz17cHQ6cix0c19vZmZzZXQ6MCxsZW5ndGg6YSxkYXRhOm5ldyBVaW50OEFycmF5KHQuYnVmZmVyLHQuYnl0ZU9mZnNldCtuLGEpfTtlLnB1c2gobyl9cmV0dXJuIGV9ZnVuY3Rpb24gaCh0KXtsZXQgZT0wO2ZvcihsZXQgbj0wO248dC5sZW5ndGg7bisrKXtlKz1uPHQubGVuZ3RoLTE/NDoxLGUrPXRbbl0uZGF0YS5ieXRlTGVuZ3RofWNvbnN0IG49bmV3IFVpbnQ4QXJyYXkoZSk7bGV0IHI9MDtmb3IobGV0IGU9MDtlPHQubGVuZ3RoO2UrKyl7aWYoZTx0Lmxlbmd0aC0xKXtjb25zdCBhPSgyMTQ3NDgzNjQ4fCgxMjcmdFtlXS5wdCk8PDI0fCgyNjIxNDMmdFtlXS50c19vZmZzZXQpPDwxMHwxMDIzJnRbZV0uZGF0YS5ieXRlTGVuZ3RoKT4+PjA7bltyKytdPWE+PjI0JjI1NSxuW3IrK109YT4+MTYmMjU1LG5bcisrXT1hPj44JjI1NSxuW3IrK109MjU1JmF9ZWxzZSBuW3IrK109MTI3JnRbZV0ucHR9Zm9yKGNvbnN0IGUgb2YgdCluLnNldChlLmRhdGEscikscis9ZS5kYXRhLmJ5dGVMZW5ndGg7cmV0dXJuIG59ZnVuY3Rpb24gYih0KXtsZXQgZT1hcmd1bWVudHMubGVuZ3RoPjEmJnZvaWQgMCE9PWFyZ3VtZW50c1sxXSYmYXJndW1lbnRzWzFdO2lmKHQuYnl0ZUxlbmd0aDxsKXJldHVybjtjb25zdCBuPXQuZ2V0VWludDgoMCk7aWYobiE9PXUpcmV0dXJuO2NvbnN0IHI9bCtjO2lmKHQuYnl0ZUxlbmd0aDxyKXJldHVybjtjb25zdCBhPXQuZ2V0VWludDE2KDEpO2lmKGE+dC5ieXRlTGVuZ3RoLXIpcmV0dXJuO2NvbnN0IG89cithLGk9dC5ieXRlTGVuZ3RoLW8scz1uZXcgVWludDhBcnJheShpKTtzLnNldChuZXcgVWludDhBcnJheSh0LmJ1ZmZlcix0LmJ5dGVPZmZzZXQrbyxpKSk7Y29uc3QgZj17bTpuLHRsdkxlbjphLHRsdjpbXSxmcmFtZTpzfSx5PWcrcDtsZXQgaD1yO2Zvcig7aCt5PD1vOyl7Y29uc3Qgbj10LmdldFVpbnQ4KGgpLHI9dC5nZXRVaW50MTYoaCtnKTtpZihoK3krcj5vKWJyZWFrO2lmKG49PT1kLkFVRElPX0xFVkVMJiZyPjApe2xldCBhPXQuZ2V0VWludDgoaCt5KTtmb3IobGV0IGU9MTtlPHI7ZSsrKWE9YTw8OHx0LmdldFVpbnQ4KGgreStlKTtmLnRsdi5wdXNoKHt0YWc6bixsZW5ndGg6cix2YWx1ZTplPzEyN15hPj4xOjEyNyZhfSl9ZWxzZSBpZihuPT09ZC5NRVRBREFUQXx8bj09PWQuQVVESU9fNjRfQklUX1BUUyl7Y29uc3QgZT1uZXcgVWludDhBcnJheShyKTtmb3IobGV0IG49MDtuPHI7bisrKWVbbl09dC5nZXRVaW50OChoK3krbik7Zi50bHYucHVzaCh7dGFnOm4sbGVuZ3RoOnIsdmFsdWU6ZX0pfWgrPXkrcn1yZXR1cm4gZn1mdW5jdGlvbiBVKHQsZSxuKXtjb25zdCByPW4uYnl0ZUxlbmd0aCxhPXIrZytwLG89bCtjK2EsaT1uZXcgQXJyYXlCdWZmZXIodC5ieXRlTGVuZ3RoK28pLHM9bmV3IERhdGFWaWV3KGkpO3Muc2V0VWludDgoMCx1KSxzLnNldFVpbnQxNigxLGEpLHMuc2V0VWludDgoMyxlKSxzLnNldFVpbnQxNig0LHIpO2ZvcihsZXQgdD0wO3Q8cjt0Kyspcy5zZXRVaW50OCg2K3Qsblt0XSk7Y29uc3QgZj1uZXcgVWludDhBcnJheShzLmJ1ZmZlcik7cmV0dXJuIGYuc2V0KG5ldyBVaW50OEFycmF5KHQpLG8pLGYuYnVmZmVyfWZ1bmN0aW9uIG0odCxlLG4pe2NvbnN0IHI9ZnVuY3Rpb24odCl7dHJ5e2lmKCJmdW5jdGlvbiIhPXR5cGVvZiB0LmdldE1ldGFkYXRhKXJldHVybnt9O2NvbnN0IGU9dC5nZXRNZXRhZGF0YSgpO3JldHVybnttaW1lVHlwZTplLm1pbWVUeXBlLHBheWxvYWRUeXBlOmUucGF5bG9hZFR5cGV9fWNhdGNoKHQpe3JldHVybnt9fX0odCksYT1yLm1pbWVUeXBlJiZyLm1pbWVUeXBlLnRvTG93ZXJDYXNlKCk7aWYoImF1ZGlvL3JlZCI9PT1hKXJldHVybiEwO2lmKCJudW1iZXIiPT10eXBlb2Ygci5wYXlsb2FkVHlwZSl7aWYoLTEhPT1uLnJlZC5pbmRleE9mKHIucGF5bG9hZFR5cGUpKXJldHVybiEwO2lmKC0xIT09bi5jb2RlYy5pbmRleE9mKHIucGF5bG9hZFR5cGUpKXJldHVybiExfWlmKGEpcmV0dXJuITE7aWYoMD09PWUuYnl0ZUxlbmd0aClyZXR1cm4hMTtjb25zdCBvPWUuZ2V0VWludDgoMCk7cmV0dXJuIG8hPT11JiYoMCE9KDEyOCZvKSYmLTEhPT1uLmNvZGVjLmluZGV4T2YoMTI3Jm8pKX1zZWxmLm9ucnRjdHJhbnNmb3JtPW49Pntjb25zdCByPW4udHJhbnNmb3JtZXIsYT1bXSxpPVtdLHU9ci5vcHRpb25zLnBheWxvYWRUeXBlc3x8e2NvZGVjOltdLHJlZDpbXX07bGV0IGw9bnVsbDtyLm9wdGlvbnMucG9ydC5vbm1lc3NhZ2U9dD0+e3QuZGF0YS5zZWkmJmEucHVzaCh0LmRhdGEuc2VpKSx0LmRhdGEubWV0YWRhdGEmJmkucHVzaCh0LmRhdGEubWV0YWRhdGEpfSxzZWxmLnBvc3RNZXNzYWdlKCJzdGFydGVkIik7Y29uc3QgYz1yLnJlYWRhYmxlLmdldFJlYWRlcigpLGc9ci53cml0YWJsZS5nZXRXcml0ZXIoKTsic2VpLXJ4Ij09PXIub3B0aW9ucy5uYW1lP2Z1bmN0aW9uIG4ocil7Yy5yZWFkKCkudGhlbigoYT0+e2lmKCFhLmRvbmUpe2lmKGEudmFsdWUgaW5zdGFuY2VvZiBSVENFbmNvZGVkVmlkZW9GcmFtZSl7Y29uc3Qgbj1mKG5ldyBVaW50OEFycmF5KGEudmFsdWUuZGF0YSkpLGk9byhhLnZhbHVlLG4pO2lmKGkmJnIub3B0aW9ucy5wb3J0LnBvc3RNZXNzYWdlKHtzZWk6aSxydHBUaW1lc3RhbXA6YS52YWx1ZS50aW1lc3RhbXB9KSwhbCl7Y29uc3Qgbj1hLnZhbHVlLmdldE1ldGFkYXRhKCl8fHt9O2w9ZnVuY3Rpb24obil7Zm9yKHZhciByPTE7cjxhcmd1bWVudHMubGVuZ3RoO3IrKyl7dmFyIGE9bnVsbCE9YXJndW1lbnRzW3JdP2FyZ3VtZW50c1tyXTp7fTtyJTI/ZShPYmplY3QoYSksITApLmZvckVhY2goKGZ1bmN0aW9uKGUpe3QobixlLGFbZV0pfSkpOk9iamVjdC5nZXRPd25Qcm9wZXJ0eURlc2NyaXB0b3JzP09iamVjdC5kZWZpbmVQcm9wZXJ0aWVzKG4sT2JqZWN0LmdldE93blByb3BlcnR5RGVzY3JpcHRvcnMoYSkpOmUoT2JqZWN0KGEpKS5mb3JFYWNoKChmdW5jdGlvbih0KXtPYmplY3QuZGVmaW5lUHJvcGVydHkobix0LE9iamVjdC5nZXRPd25Qcm9wZXJ0eURlc2NyaXB0b3IoYSx0KSl9KSl9cmV0dXJuIG59KHt0eXBlOmEudmFsdWUudHlwZSxydHBUaW1lc3RhbXA6YS52YWx1ZS50aW1lc3RhbXAscGF5bG9hZFR5cGU6bi5wYXlsb2FkVHlwZXx8MCxzc3JjOm4uc3luY2hyb25pemF0aW9uU291cmNlfHwwLGxlbmd0aDphLnZhbHVlLmRhdGEuYnl0ZUxlbmd0aH0sIm1pbWVUeXBlImluIG4/e21pbWVUeXBlOm4ubWltZVR5cGV9Ont9KSxyLm9wdGlvbnMucG9ydC5wb3N0TWVzc2FnZSh7Zmlyc3RGcmFtZUluZm86bH0pfX1nLndyaXRlKGEudmFsdWUpLHIub3B0aW9ucy5wb3J0LnBvc3RNZXNzYWdlKHt0cmFuc2Zvcm1lZDohMH0pLG4ocil9fSkpfShyKToic2VpLXR4Ij09PXIub3B0aW9ucy5uYW1lP2Z1bmN0aW9uIHQoZSl7Yy5yZWFkKCkudGhlbigobj0+e2lmKCFuLmRvbmUpe2lmKG4udmFsdWUgaW5zdGFuY2VvZiBSVENFbmNvZGVkVmlkZW9GcmFtZSl7Y29uc3QgdD1mKG5ldyBVaW50OEFycmF5KG4udmFsdWUuZGF0YSkpLGU9YS5zaGlmdCgpO2lmKGUpe2NvbnN0IHI9cyhuLnZhbHVlLmRhdGEsZSx0KTtyJiYobi52YWx1ZS5kYXRhPXIpfX1nLndyaXRlKG4udmFsdWUpLGUub3B0aW9ucy5wb3J0LnBvc3RNZXNzYWdlKHt0cmFuc2Zvcm1lZDohMH0pLHQoZSl9fSkpfShyKToiYXVkaW8tbWV0YWRhdGEtcngiPT09ci5vcHRpb25zLm5hbWU/ZnVuY3Rpb24gdChlKXtjLnJlYWQoKS50aGVuKChuPT57aWYoIW4uZG9uZSl7aWYobi52YWx1ZSBpbnN0YW5jZW9mIFJUQ0VuY29kZWRBdWRpb0ZyYW1lKXtjb25zdCB0PW5ldyBEYXRhVmlldyhuLnZhbHVlLmRhdGEpO2xldCByLGE7dHJ5e2lmKG0obi52YWx1ZSx0LHUpKXtjb25zdCBlPXkodCk7ZS5sZW5ndGg+MCYmKGE9aChlLm1hcCgodD0+e2NvbnN0IGU9bmV3IFVpbnQ4QXJyYXkodC5kYXRhLmJ5dGVMZW5ndGgpO2Uuc2V0KHQuZGF0YSk7Y29uc3Qgbj1iKG5ldyBEYXRhVmlldyhlLmJ1ZmZlcikpO3JldHVybiBudWxsIT1uJiZuLmZyYW1lJiYodC5kYXRhPW4uZnJhbWUsdC5sZW5ndGg9bi5mcmFtZS5ieXRlTGVuZ3RoKSxyPW4sdH0pKSkuYnVmZmVyKX1lbHNlIHI9Yih0KSxyJiYoYT1yLmZyYW1lLmJ1ZmZlcil9Y2F0Y2godCl7fWlmKGEmJihuLnZhbHVlLmRhdGE9YSkscil7bGV0IHQ9ci50bHYuZmluZCgodD0+dC50YWc9PT1kLk1FVEFEQVRBKSk7aWYodCYmdC52YWx1ZSBpbnN0YW5jZW9mIFVpbnQ4QXJyYXkmJmUub3B0aW9ucy5wb3J0LnBvc3RNZXNzYWdlKHttZXRhZGF0YTp0LnZhbHVlfSksdD1yLnRsdi5maW5kKCh0PT50LnRhZz09PWQuQVVESU9fNjRfQklUX1BUUykpLHQmJnQudmFsdWUgaW5zdGFuY2VvZiBVaW50OEFycmF5JiY4PT10LnZhbHVlLmxlbmd0aCl7Y29uc3Qgbj1uZXcgRGF0YVZpZXcodC52YWx1ZS5idWZmZXIpLmdldEJpZ1VpbnQ2NCgwLCEwKTt0JiZ0LnZhbHVlIGluc3RhbmNlb2YgVWludDhBcnJheSYmZS5vcHRpb25zLnBvcnQucG9zdE1lc3NhZ2Uoe3B0czpufSl9fX1nLndyaXRlKG4udmFsdWUpLGUub3B0aW9ucy5wb3J0LnBvc3RNZXNzYWdlKHt0cmFuc2Zvcm1lZDohMH0pLHQoZSl9fSkpfShyKToiYXVkaW8tbWV0YWRhdGEtdHgiPT09ci5vcHRpb25zLm5hbWUmJmZ1bmN0aW9uIHQoZSl7Yy5yZWFkKCkudGhlbigobj0+e2lmKCFuLmRvbmUpe2lmKGUub3B0aW9ucy5wb3J0LnBvc3RNZXNzYWdlKHtnZXRNZXRhZGF0YTohMH0pLG4udmFsdWUgaW5zdGFuY2VvZiBSVENFbmNvZGVkQXVkaW9GcmFtZSl7Y29uc3QgdD1pLnNoaWZ0KCk7aWYodCl7Y29uc3QgZT1mdW5jdGlvbih0LGUsbixyKXtjb25zdCBhPW5ldyBEYXRhVmlldyh0LmRhdGEpO2lmKCFtKHQsYSxyKSlyZXR1cm4gVSh0LmRhdGEsZSxuKTtjb25zdCBvPXkoYSk7aWYoMD09PW8ubGVuZ3RoKXJldHVybjtjb25zdCBpPW9bby5sZW5ndGgtMV0scz1uZXcgQXJyYXlCdWZmZXIoaS5kYXRhLmJ5dGVMZW5ndGgpO3JldHVybiBuZXcgVWludDhBcnJheShzKS5zZXQoaS5kYXRhKSxpLmRhdGE9bmV3IFVpbnQ4QXJyYXkoVShzLGUsbikpLGkubGVuZ3RoPWkuZGF0YS5ieXRlTGVuZ3RoLGgobykuYnVmZmVyfShuLnZhbHVlLGQuTUVUQURBVEEsdCx1KTtlJiYobi52YWx1ZS5kYXRhPWUpfX1nLndyaXRlKG4udmFsdWUpLGUub3B0aW9ucy5wb3J0LnBvc3RNZXNzYWdlKHt0cmFuc2Zvcm1lZDohMH0pLHQoZSl9fSkpfShyKX0sc2VsZi5wb3N0TWVzc2FnZSgicmVnaXN0ZXJlZCIpOwo=")],{type:"text/javascript"});return setTimeout((()=>URL.revokeObjectURL(e)),0),new Worker(URL.createObjectURL(e))}const Qs=71,qs=1,$s=2,eo=1,to=2;var io=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}(io||{});function ro(e){if(e.byteLength<=0)return[];const t=[];let i=0,r=0;for(;i<e.byteLength;){const s=e.getUint8(i),o=127&s;if(!((128&s)>>7)){r=o,i++;break}{if(i+4>e.byteLength)return[];const r=e.getUint32(i,!1),s=(16776192&r)>>10,n=1023&r;t.push({pt:o,ts_offset:s,length:n,data:new Uint8Array}),i+=4}}let s=e.byteLength-i;for(const r of t){if(r.length>s)return console.warn("Broken red payload"),[];r.length>0&&(r.data=new Uint8Array(e.buffer,e.byteOffset+i,r.length),i+=r.length,s-=r.length)}if(s>0){const o={pt:r,ts_offset:0,length:s,data:new Uint8Array(e.buffer,e.byteOffset+i,s)};t.push(o)}return t}function so(e){let t=0;for(let i=0;i<e.length;i++){t+=i<e.length-1?4:1,t+=e[i].data.byteLength}const i=new Uint8Array(t);let r=0;for(let t=0;t<e.length;t++){if(t<e.length-1){const s=(2147483648|(127&e[t].pt)<<24|(262143&e[t].ts_offset)<<10|1023&e[t].data.byteLength)>>>0;i[r++]=s>>24&255,i[r++]=s>>16&255,i[r++]=s>>8&255,i[r++]=255&s}else i[r++]=127&e[t].pt}for(const t of e)i.set(t.data,r),r+=t.data.byteLength;return i}function oo(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(e.byteLength<qs)return;const i=e.getUint8(0);if(i!==Qs)return;const r=qs+$s;if(e.byteLength<r)return;const s=e.getUint16(1);if(s>e.byteLength-r)return;const o=r+s,n=e.byteLength-o,a=new Uint8Array(n);a.set(new Uint8Array(e.buffer,e.byteOffset+o,n));const c={m:i,tlvLen:s,tlv:[],frame:a},d=eo+to;let u=r;for(;u+d<=o;){const i=e.getUint8(u),r=e.getUint16(u+eo);if(u+d+r>o)break;if(i===io.AUDIO_LEVEL&&r>0){let s=e.getUint8(u+d);for(let t=1;t<r;t++)s=s<<8|e.getUint8(u+d+t);c.tlv.push({tag:i,length:r,value:t?127^s>>1:127&s})}else if(i===io.METADATA||i===io.AUDIO_64_BIT_PTS){const t=new Uint8Array(r);for(let i=0;i<r;i++)t[i]=e.getUint8(u+d+i);c.tlv.push({tag:i,length:r,value:t})}u+=d+r}return c}function no(e,t,i){const r=i.byteLength,s=r+eo+to,o=qs+$s+s,n=new ArrayBuffer(e.byteLength+o),a=new DataView(n);a.setUint8(0,Qs),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}function ao(e){const t={codec:[],red:[]};try{if("function"!=typeof e.getParameters)return t;const i=e.getParameters().codecs||[];for(const e of i){if("number"!=typeof e.payloadType)continue;const i=(e.mimeType||"").toLowerCase();"audio/red"===i?t.red.push(e.payloadType):i.startsWith("audio/")&&t.codec.push(e.payloadType)}}catch(e){}return t}function co(e,t,i){const r=function(e){try{if("function"!=typeof e.getMetadata)return{};const t=e.getMetadata();return{mimeType:t.mimeType,payloadType:t.payloadType}}catch(e){return{}}}(e),s=r.mimeType&&r.mimeType.toLowerCase();if("audio/red"===s)return!0;if("number"==typeof r.payloadType){if(-1!==i.red.indexOf(r.payloadType))return!0;if(-1!==i.codec.indexOf(r.payloadType))return!1}if(s)return!1;if(0===t.byteLength)return!1;const o=t.getUint8(0);return o!==Qs&&(0!=(128&o)&&-1!==i.codec.indexOf(127&o))}const uo=new Map;function ho(e,t){const i=t.chunk,r=t.controller,s=t.payloadTypes,o=function(e,t,i,r){const s=new DataView(e.data);if(!co(e,s,r))return no(e.data,t,i);const o=ro(s);if(0===o.length)return;const n=o[o.length-1],a=new ArrayBuffer(n.data.byteLength);return new Uint8Array(a).set(n.data),n.data=new Uint8Array(no(a,t,i)),n.length=n.data.byteLength,so(o).buffer}(i,io.METADATA,e,s);o&&(i.data=o),r.enqueue(i)}async function lo(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!ve().supportWebRTCEncodedTransform)return void pe.warning("browser not support audio encoded transform");if(uo.has(e))return;if(!e.track)return;const i={track:e.track},r=ao(e);if("function"==typeof RTCRtpSender.prototype.createEncodedStreams){let o=null;try{o=e.createEncodedStreams()}catch(e){return void pe.error("create audio-encoded-streams error",e&&e.message)}const n=new TransformStream({transform(o,n){i.controller||(i.controller=n),e.track&&e.track.id!==i.track.id&&(pe.debug("audio track changed: ".concat(i.track.id," => ").concat(e.track.id)),i.track.removeEventListener("ended",s),i.track=e.track,i.track.addEventListener("ended",s));const a=t.metadata&&t.metadata();a?ho(a,{sender:e,chunk:o,controller:n,payloadTypes:r}):n.enqueue(o)}});o.readable.pipeThrough(n).pipeTo(o.writable)}else{if("undefined"==typeof RTCRtpScriptTransform)return void pe.warning("browser not support encoded transform");{if("undefined"==typeof RTCRtpScriptTransform)return void pe.warning("browser not support RTCRtpScriptTransform");const o=Js(),n=new MessageChannel;await new Promise((e=>o.onmessage=t=>{"registered"===t.data&&e(void 0)}));const a=new RTCRtpScriptTransform(o,{name:"audio-metadata-tx",port:n.port2,payloadTypes:r},[n.port2]);e.transform=a,await new Promise((e=>o.onmessage=t=>{"started"===t.data&&e(void 0)})),n.port1.onmessage=r=>{var o;if(r.data.transformed&&e.track&&(null===(o=e.track)||void 0===o?void 0:o.id)!==i.track.id)pe.debug("audio track changed: ".concat(i.track.id," => ").concat(e.track.id)),i.track.removeEventListener("ended",s),i.track=e.track,i.track.addEventListener("ended",s);else if(r.data.getMetadata){const e=t.metadata&&t.metadata();e&&n.port1.postMessage({metadata:e})}},i.worker=o}}function s(){if(e.track){if(this.id!==e.track.id)return;e.track.removeEventListener("ended",s)}const t=uo.get(e);if(t){uo.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){pe.warning(e&&e.message)}}}uo.set(e,i),e.track.addEventListener("ended",s)}const po=127,mo=1e-10,go=139/13;const _o=new Map;function fo(e,t,i){const r="".concat(e,"-").concat(t,"-").concat(i);let s=0;if(_o.has(r))s=_o.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,_o.set(r,s)}return s<mo&&(s=mo),s}function To(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=_o;let Eo=0;class vo{constructor(e){Ct(this,"id",void 0),Ct(this,"immediates",[]),Ct(this,"lastNonSilence",-1),Ct(this,"immediateSpeechActivityScore",mo),Ct(this,"lastLevelChangedTime",Date.now()),Ct(this,"levels",[]),Ct(this,"longs",[]),Ct(this,"longSpeechActivityScore",mo),Ct(this,"mediums",[]),Ct(this,"mediumSpeechActivityScore",mo),Ct(this,"minLevel",0),Ct(this,"nextMinLevel",0),Ct(this,"nextMinLevelWindowLength",0),Ct(this,"energyScore",0),this.id=e||"".concat(Eo++),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+go;let r=!1;for(let s=0;s<e.length;++s){let o=t[s];o<i&&(o=0);const n=Math.floor(o/go);e[s]!==n&&(e[s]=n,r=!0)}return r}computeLongs(){return To(this.mediums,this.longs,4)}computeMediums(){return To(this.immediates,this.mediums,7)}evaluateImmediateSpeechActivityScore(){this.immediateSpeechActivityScore=fo(this.immediates[0],13,.78)}evaluateLongSpeechActivityScore(e){this.longSpeechActivityScore=fo(this.longs[0],10,47),this.longSpeechActivityScore>mo&&(this.lastNonSilence=e)}evaluateMediumSpeechActivityScore(){this.mediumSpeechActivityScore=fo(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>po&&(i=po),this.levels.unshift(i),this.levels.length>this.immediates.length&&this.levels.pop(),this.updateMinLevel(i),i>=this.minLevel+go?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>po&&(e=po),this.minLevel=e,this.nextMinLevel=0,this.nextMinLevelWindowLength=0}}}}class yo{constructor(e){Ct(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 So{constructor(e,t,i){Ct(this,"isDominant",void 0),Ct(this,"energyRanking",void 0),Ct(this,"energyScore",void 0),this.isDominant=e,this.energyRanking=t,this.energyScore=i}}class bo extends I{constructor(e){super(),Ct(this,"dominantId",null),Ct(this,"lastDecisionTime",0),Ct(this,"lastLevelChangedTime",0),Ct(this,"lastLevelIdleTime",0),Ct(this,"relativeSpeechActivities",[]),Ct(this,"speakers",new Map),Ct(this,"enableSilence",!1),Ct(this,"timeoutToSilenceInterval",0),Ct(this,"decisionMaker",null),Ct(this,"loudest",[]),Ct(this,"numLoudestToTrack",3),Ct(this,"energyExpireTimeMs",250),Ct(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 vo(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 So(r,t,e.energyScore)}if(e.energyScore=Math.floor((this.energyAlphaPct*t+(100-this.energyAlphaPct)*e.energyScore+50)/100),0===this.numLoudestToTrack)return new So(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 So(r,n,e.energyScore)}maybeStartDecisionMaker(){!this.decisionMaker&&this.speakers.size>0&&(this.decisionMaker=new yo(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=Dt(o,2),a=n[0],c=n[1];if(c===t)continue;c.evaluateSpeechActivityScores(e);for(let e=0;e<i.length;++e){const r=null==t?mo:t.getSpeechActivityScore(e);i[e]=Math.log(c.getSpeechActivityScore(e)/r)}const d=i[0],u=i[1],h=i[2];d>3&&u>2&&h>0&&u>r&&(r=u,s=a)}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 ko=new Map;let Io=null,Ao=null;const Ro=3;let Co=[];function wo(e,t){let i=ko.get(e);if(i||(i=function(e){const t=new vo;return ko.set(e,t),Io||(Io=new bo(u("TOPN_SILENCE_THRESHOLD")||500),Io.on("ActiveSpeakerChanged",(e=>{null!=e&&(Ao=e)}))),Io.addSpeakers([t]),t}(e)),ko.size<=Ro)return{selected:!0,speaker:i};if(!Io)throw new Error("no active speaker detector");Io.levelChanged(i.id,t),Co=Io.loudest.map((e=>e.id)),Ao&&!Co.includes(Ao)&&Co.length>=Ro&&Co.pop();return{selected:Co.includes(i.id)||i.id===Ao,speaker:i}}const Mo=1e3,Do=40,No=new Map,Oo=new Map;class Lo{get samples(){return this.actives+this.inactives}get activeRate(){return this.actives/this.samples}constructor(e,t){Ct(this,"id",void 0),Ct(this,"track",void 0),Ct(this,"score",0),Ct(this,"active",!0),Ct(this,"muted",!1),Ct(this,"timer",0),Ct(this,"actives",0),Ct(this,"inactives",0),this.id=e,this.track=t,this.setActive(No.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 t=function(){const e=[],t=[];return Array.from(No.values()).forEach((i=>{i.active?e.push(i):t.push(i)})),{actives:e,inactives:t}}(),i=t.actives,r=t.inactives;if(i.length>3){let e;i.forEach((t=>{(!e||e.score>t.score)&&(e=t)})),e&&e.setActive(!1)}if(i.length<3&&r.length>0){let t;r.forEach((e=>{(!t||t.score<e.score)&&e.id!==this.id&&(t=e)})),t&&e&&!this.active&&(t.samples>Do&&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(No.values()).forEach((i=>{!i.active||i.id===e||i.samples<Do||(!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(No.values()).forEach((i=>{i.active||i.id===e||i.samples<Do||(!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()}),Mo)}clearTimer(){this.timer&&(clearTimeout(this.timer),this.timer=0)}}let Po;function Vo(e,t,i){const r=No.get(e)||new Lo(e,t);return r.score=i,No.set(e,r),function(e){if(Oo.set(e,!0),!Po)return void(Po=Date.now());const t=Date.now();t-Po>1e3&&(Oo.get(e)?Oo.set(e,!1):(xo(e),Oo.delete(e)),Po=t)}(e),r}function xo(e){const t=No.get(e);t&&(No.delete(e),t.clearTimer())}const Uo=new Map,Wo=new Map;async function Go(e){let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!ve().supportWebRTCEncodedTransform)return void pe.warning("browser not support audio encoded transform");if(Uo.has(e))return;const r={track:e.track,onMetadata:i.onMetadata,onPts:i.onPts},s=ao(e);if("function"==typeof RTCRtpSender.prototype.createEncodedStreams){ae(t.CHROME,87,116)||(i.enableTopn=!1);let n=null;try{n=e.createEncodedStreams()}catch(e){return void pe.error("create audio-encoded-streams error",e&&e.message)}const a=new TransformStream({transform(t,n){r.controller||(r.controller=n),e.track&&e.track.id!==r.track.id&&(pe.debug("audio track changed: ".concat(r.track.id," => ").concat(e.track.id)),r.track.removeEventListener("ended",o),r.track=e.track,r.track.addEventListener("ended",o)),i.enableTopn?function(e,t,i){var r;const s=oo(new DataView(t.data));if(!s)return i.enqueue(t);const o=e.track.id;Wo.set(o,e.track);const n=null===(r=s.tlv.find((e=>e.tag===io.AUDIO_LEVEL)))||void 0===r?void 0:r.value;let a=0;"number"==typeof n&&(a=127-n);const c=wo(e,Math.round(Math.pow(10,a/60)-1)),d=c.selected,u=c.speaker,h=Vo(o,e.track,u.energyScore);h.addSample(d),h.active&&(t.data=s.frame.buffer,i.enqueue(t))}(e,t,n):i.enableMetadata||i.enablePts?function(e,t,i,r,s){const o=new DataView(e.data);let n,a;try{if(co(e,o,i)){const e=ro(o);e.length>0&&(a=so(e.map((e=>{const t=new Uint8Array(e.data.byteLength);t.set(e.data);const i=oo(new DataView(t.buffer));return null!=i&&i.frame&&(e.data=i.frame,e.length=i.frame.byteLength),n=i,e}))).buffer)}else n=oo(o),n&&(a=n.frame.buffer)}catch(e){}if(a&&(e.data=a),t.enqueue(e),!n)return;const c=n.tlv.find((e=>e.tag===io.METADATA));c&&r&&c.value instanceof Uint8Array&&r(c.value);const d=n.tlv.find((e=>e.tag===io.AUDIO_64_BIT_PTS));d&&s&&d.value instanceof Uint8Array&&8==d.value.length&&s(new DataView(d.value.buffer).getBigUint64(0,!0))}(t,n,s,i.onMetadata,i.onPts):n.enqueue(t)}});n.readable.pipeThrough(a).pipeTo(n.writable)}else{if("undefined"==typeof RTCRtpScriptTransform)return void pe.warning("browser not support encoded transform");{if("undefined"==typeof RTCRtpScriptTransform)return void pe.warning("browser not support RTCRtpScriptTransform");const t=Js(),i=new MessageChannel;await new Promise((e=>t.onmessage=t=>{"registered"===t.data&&e(void 0)}));const n=new RTCRtpScriptTransform(t,{name:"audio-metadata-rx",port:i.port2,payloadTypes:s},[i.port2]);e.transform=n,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?(pe.debug("audio track changed: ".concat(r.track.id," => ").concat(e.track.id)),r.track.removeEventListener("ended",o),r.track=e.track,r.track.addEventListener("ended",o)):t.data.metadata&&r.onMetadata?r.onMetadata(t.data.metadata):t.data.pts&&r.onPts&&r.onPts(t.data.pts)},r.worker=t}}function o(){e.track.removeEventListener("ended",o),function(e){const t=Uo.get(e);if(t){!function(e){const t=ko.get(e);t&&(ko.delete(e),Io&&(Io.removeSpeakers([t]),0===ko.size&&(Io.destroy(),Io=null)))}(e),xo(e.track.id),Uo.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){pe.warning(e&&e.message)}}}(e)}Uo.set(e,r),e.track.addEventListener("ended",o)}const Zo="video/h264",Bo="video/h265";function Fo(e,t,i){const r=new Uint8Array(e,t,i),s=[];let 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 Ho(e,t){switch(t){case Zo:return 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=Fo(e.data,r,s);return new Uint8Array(n)}i++}return null}(e);case Bo:return function(e){const t=new DataView(e.data);let i=0;for(;i+5<e.data.byteLength;){if(0===t.getUint8(i+0)&&0===t.getUint8(i+1)&&0===t.getUint8(i+2)&&1===t.getUint8(i+3)&&78===t.getUint8(i+4)&&1===t.getUint8(i+5)&&101===t.getUint8(i+6)){let r=i+7,s=0,o=0;for(;255===(o=t.getUint8(r++));)s+=255;s+=o;const n=Fo(e.data,r,s);return new Uint8Array(n)}i++}return null}(e);default:return null}}function Ko(e){const t=e.length,i=[];let 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)}function Xo(e,t,i){switch(i){case Zo:return function(e,t){const i=Ko(t),r=i.length,s=Math.floor(r/255),o=r%255,n=new Uint8Array(6+s+1+r+1+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),a+=r,n[6+a]=128,a++,n.set(new Uint8Array(e),6+a),n.buffer}(e,t);case Bo:return function(e,t){const i=Ko(t),r=i.length,s=Math.floor(r/255),o=r%255,n=new Uint8Array(7+s+1+r+1+e.byteLength);n[0]=0,n[1]=0,n[2]=0,n[3]=1,n[4]=78,n[5]=1,n[6]=101;let a=0;for(;a<s;)n[7+a]=255,a++;return n[7+a]=o,a++,n.set(i,7+a),a+=r,n[7+a]=128,a++,n.set(new Uint8Array(e),7+a),n.buffer}(e,t);default:return null}}function Yo(e){if(e.length<5)return"";let t=-1;for(let i=0;i<e.length-3;i++){if(0===e[i]&&0===e[i+1]&&1===e[i+2]){t=i;break}if(i<e.length-4&&0===e[i]&&0===e[i+1]&&0===e[i+2]&&1===e[i+3]){t=i;break}}if(-1===t)return"";const i=t+(0===e[t+2]?4:3);if(i>=e.length)return"";const r=e[i];if(128&r)return"";if((r>>1&63)>=32)return Bo;if(i+1<e.length){if(0==(248&e[i+1]))return Bo}return(31&r)<=31?Zo:""}const jo=new Map;async function zo(e,t){if(!ve().supportWebRTCEncodedTransform)return void pe.warning("browser not support video encoded transform");if(jo.has(e))return;if(!e.track)return;const i={track:e.track};if("function"==typeof RTCRtpSender.prototype.createEncodedStreams){let s=null;try{s=e.createEncodedStreams()}catch(e){return void pe.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&&(pe.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=Yo(new Uint8Array(t.data)),a=o.shift();if(a){const e=Xo(t.data,a,n);e&&(t.data=e)}s.enqueue(t)}});s.readable.pipeThrough(n).pipeTo(s.writable)}else{if("undefined"==typeof RTCRtpScriptTransform)return void pe.warning("browser not support encoded transform");{if("undefined"==typeof RTCRtpScriptTransform)return void pe.warning("browser not support RTCRtpScriptTransform");const s=Js(),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&&(pe.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=jo.get(e);if(t){jo.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){pe.warning(e&&e.message)}}}jo.set(e,i),e.track.addEventListener("ended",r)}const Jo=new Map;async function Qo(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!ve().supportWebRTCEncodedTransform)return void pe.warning("browser not support video encoded transform");if(!e.track)return;if(Jo.has(e)){const i=Jo.get(e);return void(i&&(i.onSei=t.onSei))}const i={track:e.track,onSei:t.onSei};if("function"==typeof RTCRtpSender.prototype.createEncodedStreams){let s=null;try{s=e.createEncodedStreams()}catch(e){return void pe.error("create video-encoded-streams error",e&&e.message)}const o=new TransformStream({transform(s,o){if(i.controller||(i.controller=o),!i.firstFrameInfo){var n;const e=s.getMetadata()||{};i.firstFrameInfo=Mt({type:s.type,rtpTimestamp:s.timestamp,payloadType:e.payloadType||0,ssrc:e.synchronizationSource||0,length:s.data.byteLength},"mimeType"in e?{mimeType:e.mimeType}:{}),null===(n=t.onFirstFrame)||void 0===n||n.call(t,i.firstFrameInfo)}e.track&&e.track.id!==i.track.id&&(pe.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 a=Ho(s,Yo(new Uint8Array(s.data)));a&&i.onSei&&i.onSei(a,s.timestamp),o.enqueue(s)}});s.readable.pipeThrough(o).pipeTo(s.writable)}else{if("undefined"==typeof RTCRtpScriptTransform)return void pe.warning("browser not support encoded transform");{if("undefined"==typeof RTCRtpScriptTransform)return void pe.warning("browser not support RTCRtpScriptTransform");const s=Js(),o=new MessageChannel;await new Promise((e=>s.onmessage=t=>{"registered"===t.data&&e(void 0)}));const n=new RTCRtpScriptTransform(s,{name:"sei-rx",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 o;if(s.data.transformed&&e.track&&(null===(o=e.track)||void 0===o?void 0:o.id)!==i.track.id)pe.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);else if(s.data.sei&&i.onSei)i.onSei(s.data.sei,s.data.rtpTimestamp);else if(s.data.firstFrameInfo&&t.onFirstFrame){var n;null===(n=t.onFirstFrame)||void 0===n||n.call(t,s.data.firstFrameInfo)}},i.worker=s}}function r(){if(e.track){if(this.id!==e.track.id)return;e.track.removeEventListener("ended",r)}!function(e){const t=Jo.get(e);if(t){Jo.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){pe.warning(e&&e.message)}}}(e)}Jo.set(e,i),e.track.addEventListener("ended",r)}Ee();export{Ne as AUDIO_CONTEXT_EVENT,Fe as AUDIO_ENCODER_CONFIG_SETTINGS,ht as AUDIO_TRACK_EVENT,Lr as AgoraRTCPlayer,yi as AudioProcessorContext,vi as AudioProcessorDestination,ut as AudioSourceEvents,Rr as BufferSourceAudioTrack,vs as CameraVideoTrack,lt as DEFAULT_LOCAL_AUDIO_TRACK_STATS,pt as DEFAULT_LOCAL_VIDEO_TRACK_STATS,gt as DEFAULT_NETWORK_QUALITY_STATS,mt as DEFAULT_REMOTE_AUDIO_TRACK_STATS,_t as DEFAULT_REMOTE_VIDEO_TRACK_STATS,Ys as DataChannel,It as DataChannelEvents,di as DeviceManager,vt as DeviceManagerEvent,Et as DeviceManagerState,ri as HAS_GUM_AUDIO,si as HAS_GUM_VIDEO,Ir as LocalAudioTrack,zs as LocalDataChannel,Ot as LocalTrack,at as LocalTrackEvents,Es as LocalVideoTrack,kt as MediaElementNumStatus,St as MediaElementStatus,Ar as MicrophoneAudioTrack,Cr as MixingAudioTrack,Tt as PROCESSOR_CONTEXT_EVENTS,ft as PROCESSOR_DESTINATION_EVENTS,Ks as RemoteAudioTrack,js as RemoteDataChannel,ot as RemoteStreamFallbackType,st as RemoteStreamType,Fs as RemoteTrack,ct as RemoteTrackEvents,Hs as RemoteVideoTrack,ii as SAFARI_GLOBAL_GUM_LOCK,Ue as SUPPORT_SCREEN_ENCODER_CONFIG_LIST,We as SUPPORT_SVC_CONFIG_LIST,xe as SUPPORT_VIDEO_ENCODER_CONFIG_LIST,rt as StreamType,Nt as Track,nt as TrackEvents,tt as TrackHint,et as TrackInternalEvent,dt as TrackMediaType,Nr as VideoPlayer,Ei as VideoProcessorContext,Ti as VideoProcessorDestination,bt as VideoState,Ke as __TRACK_LIST__,Xe as addTrack,xt as audioContextState,_i as audioElementPlayCenter,Kt as audioTimerLoop,li as autoPlayGestureEventEmitter,xi as blob2Uint8Array,ki as checkMediaStreamTrackResolution,fi as checkTrackState,bs as createBufferSourceAudioTrack,As as createCameraVideoTrack,ys as createCustomAudioTrack,Is as createCustomVideoTrack,Rs as createMicrophoneAndCameraTracks,Ss as createMicrophoneAudioTrack,ks as createMixingAudioTrack,Cs as createScreenVideoTrack,Ft as decodeAudioData,ye as detectSupportAudioElementSetSinkId,Re as detectSupportAutCC,Ce as detectSupportAutCCFeedback,Ae as detectSupportInstantVideo,Ie as detectSupportPrePc,ke as detectSupportPreSub,De as detectSupportRestrictOwnAudio,be as detectSupportSDPEndpoint,Me as detectSupportSuppressLocalAudioPlayback,ui as deviceManager,Vi as emptyImage2TypedArray,Pi as frameData2CryptoBuffer,Gt as getAudioContext,He as getAudioEncoderConfiguration,Ni as getBitrateConstrainRange,Oi as getBitrateFromResAndFps,ve as getCompatibility,Ri as getConstraintsFromAudioConfig,Ii as getConstraintsFromCameraConfig,wi as getConstraintsFromMicrophoneConfig,Ci as getConstraintsFromScreenAudioConfig,Ai as getConstraintsFromScreenConfig,ti as getElectronScreenSources,$t as getElectronScreenStream,ei as getElectronScreenStreamByUserSelect,oi as getLocalStream,Di as getNewNearestVideoProfile,Mi as getNewVideoBitrate,Li as getOriginSenderConfig,Be as getScalabilityConfiguration,Ze as getScreenEncoderConfiguration,Yt as getSilenceAudioTrack,zt as getSilenceSamplesDuration,Ui as getStaticTrackStream,Ge as getVideoEncoderConfiguration,ai as handleGetUserMediaError,Zt as hasAudioContext,je as hasMicrophoneTrack,lo as interceptLocalAudioFrame,zo as interceptLocalVideoFrame,Go as interceptRemoteAudioFrame,Qo as interceptRemoteVideoFrame,Je as isAudioEncoderConfiguration,qe as isAudioEncoderConfigurationOrPreset,yt as isBeautyEffectOptions,it as isLowStreamParameter,Se as isPlanB,$e as isScreenSourceType,ze as isVideoEncoderConfiguration,Qe as isVideoEncoderConfigurationOrPreset,Bt as polyfillAudioNode,Ye as removeTrack,pi as requestAutoplayGesture,Wt as restartBackgroundTag,jt as silenceScriptProcessHandler,Ee as updateAgoraRTCCompatibility,Xs as visibilityWatcher};