@agora-js/media 4.24.2 → 4.24.3

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