UNPKG

@agora-js/media

Version:
5 lines (4 loc) 178 kB
/** * AgoraWebSDK_N-v4.23.4-0-g17410532-dirty Copyright AgoraInc. */ import"webrtc-adapter";import{getBrowserInfo as e,BrowserName as t,isChromeKernel as i,nextTick as r,isAboveChrome as s,isAboveFirefox as o,isAboveSafari as n,BrowserOS as a,isSafari as c,isWkWebview as d,getParameter as u,isFirefox as h,isChrome as l,isEdge as p,isMobile as m,checkValidConstrainLong as g,checkValidNumber as _,checkValidBoolean as T,checkValidEnum as v,AgoraRTCError as f,AgoraRTCErrorCode as E,isEmpty as S,EventEmitter as y,getRandomString as k,runOnce as b,AgoraAPIName as I,AgoraAPITag as A,PromiseMutex as R,emitAsPromiseNoResponse as w,removeItemFromList as D,isIOS as C,isIpadOS as M,wait as N,showElectronSelectSourceWindow as O,getElectronInstance as L,isElectron as P,recursiveMerge as V,isAndroid as x,isHarmonyOS as U,detectSecureContext as B,isAndroidChromium as F,domLoadedPromise as G,isIOS15 as W,emitAsPromise as H,noop as K,isLegacyChrome as Z,isAboveEdge as Y,isAboveOpera as z,constrainLongToNumber as j,hexToBytes as X,md5 as Q,atom as J,emitAsInvokerNoResponse as q,isIOS16 as $,retryable as ee,getOSWithVersion as te,isAboveIOS15_1 as ie,isInPage as re,sumArray as se,jsonClone as oe,isBetweenBrowser as ne,isWindows as ae,elementVisibleChecker as ce,safeCloneJson as de,isAboveIOS15_2 as ue,isWechatBrowser as he}from"@agora-js/shared";export{isElectron}from"@agora-js/shared";import{logger as le,report as pe,AgoraRTCEventUploadType as me,apiInvoke as ge}from"@agora-js/report";import _e from"axios";const Te={getDisplayMedia:!1,getStreamFromExtension:!1,supportUnifiedPlan:!1,supportMinBitrate:!1,supportSetRtpSenderParameters:!1,supportDualStream:!0,webAudioMediaStreamDest:!1,supportReplaceTrack:!1,supportWebGL:!1,webAudioWithAEC:!1,supportRequestFrame:!1,supportShareAudio:!1,supportDualStreamEncoding:!1,supportDataChannel:!1,supportPCSetConfiguration:!1,supportWebRTCEncodedTransform:!1,supportWebRTCInsertableStream:!1,supportRequestVideoFrameCallback:!1,supportWebCrypto:!1};function ve(){const l=e();Te.getDisplayMedia=function(e){if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)return!0;return!1}(),Te.getStreamFromExtension=l.name===t.CHROME&&Number(l.version)>34,Te.supportUnifiedPlan=function(){if(!window.RTCRtpTransceiver)return!1;if(!("currentDirection"in RTCRtpTransceiver.prototype))return!1;const e=new RTCPeerConnection;let t=!1;try{e.addTransceiver("audio"),t=!0}catch(e){}return e.close(),t}(),Te.supportMinBitrate=l.name===t.CHROME||l.name===t.EDGE,Te.supportSetRtpSenderParameters=function(){const r=e();if(!window.RTCRtpSender||!window.RTCRtpSender.prototype.setParameters||!window.RTCRtpSender.prototype.getParameters)return!1;return!!i()||(!(!c()&&!d())||r.name===t.FIREFOX&&Number(r.version)>=64)}(),l.name===t.SAFARI&&(Number(l.version)>=14?Te.supportDualStream=!0:Te.supportDualStream=!1),Te.webAudioMediaStreamDest=function(){const i=e();if(i.name===t.SAFARI&&Number(i.version)<12)return!1;return!0}(),Te.supportReplaceTrack=function(){if(!window.RTCRtpSender)return!1;if("function"==typeof RTCRtpSender.prototype.replaceTrack)return!0;return!1}(),Te.supportWebGL="undefined"!=typeof WebGLRenderingContext,Te.supportRequestFrame=!!window.CanvasCaptureMediaStreamTrack,i()||(Te.webAudioWithAEC=!0),Te.supportShareAudio=function(){const i=e();if((i.os===a.WIN_10||i.os===a.WIN_81||i.os===a.WIN_7||i.os===a.LINUX||i.os===a.MAC_OS||i.os===a.CHROMIUM_OS)&&i.name===t.CHROME&&Number(i.version)>=74)return!0;return!1}(),Te.supportDataChannel=function(){if(s(76)||o(68)||n(14))return!0;return!1}(),Te.supportPCSetConfiguration=function(){const e=window.RTCPeerConnection;return!h()&&!!e&&e.prototype.setConfiguration instanceof Function}(),Te.supportWebRTCEncodedTransform=function(){const t=e();return"Chrome"===t.name&&Number(t.version)>=87||"Safari"===t.name&&Number(t.version)>=15}(),Te.supportWebRTCInsertableStream=function(){const i=e();return(i.name===t.CHROME||i.name===t.EDGE)&&Number(i.version)>=94&&"MediaStreamTrackGenerator"in window&&"MediaStreamTrackProcessor"in window}(),Te.supportRequestVideoFrameCallback=function(){if("requestVideoFrameCallback"in HTMLVideoElement.prototype)return!0;return!1}(),Te.supportWebCrypto="undefined"!=typeof window&&void 0!==window.crypto&&void 0!==window.crypto.subtle,r((()=>{Te.supportDualStreamEncoding=function(){const t=e();if(u("DISABLE_WEBAUDIO"))return!0;return"Safari"===t.name&&Number(t.version)>=14||!!("Chrome"===t.name&&/Windows/i.test(t.os||"")&&Number(t.version)>=100&&u("CHROME_DUAL_STREAM_USE_ENCODING"))}(),le.debug("browser ua: ",navigator.userAgent),le.info("browser info: ",l),le.info("browser compatibility: ",Te)}))}function fe(){return Te}function Ee(){return"setSinkId"in HTMLAudioElement.prototype&&(!u("RESTRICTION_SET_PLAYBACK_DEVICE")||(l()||p())&&!m())}function Se(){return!Te.supportUnifiedPlan||u("CHROME_FORCE_PLAN_B")&&i()}let ye=function(e){return e.IOS_15_16_INTERRUPTION_START="ios15_16-interruption-start",e.IOS_15_16_INTERRUPTION_END="ios15_16-interruption-end",e.IOS_INTERRUPTION_START="ios-interruption-start",e.IOS_INTERRUPTION_END="ios-interruption-end",e.STATE_CHANGE="state-change",e}({});function ke(e,t,i){return{sampleRate:e,stereo:t,bitrate:i}}function be(e,t,i,r,s){return{width:e,height:t,frameRate:i,bitrateMin:r,bitrateMax:s}}function Ie(e,t,i,r,s){return{width:{max:e},height:{max:t},frameRate:i,bitrateMin:r,bitrateMax:s}}function Ae(e,t){return{numSpatialLayers:e,numTemporalLayers:t}}const Re={"90p":be(160,90),"90p_1":be(160,90),"120p":be(160,120,15,30,65),"120p_1":be(160,120,15,30,65),"120p_3":be(120,120,15,30,50),"120p_4":be(212,120),"180p":be(320,180,15,30,140),"180p_1":be(320,180,15,30,140),"180p_3":be(180,180,15,30,100),"180p_4":be(240,180,15,30,120),"240p":be(320,240,15,40,200),"240p_1":be(320,240,15,40,200),"240p_3":be(240,240,15,40,140),"240p_4":be(424,240,15,40,220),"360p":be(640,360,15,80,400),"360p_1":be(640,360,15,80,400),"360p_3":be(360,360,15,80,260),"360p_4":be(640,360,30,80,600),"360p_6":be(360,360,30,80,400),"360p_7":be(480,360,15,80,320),"360p_8":be(480,360,30,80,490),"360p_9":be(640,360,15,80,800),"360p_10":be(640,360,24,80,800),"360p_11":be(640,360,24,80,1e3),"480p":be(640,480,15,100,500),"480p_1":be(640,480,15,100,500),"480p_2":be(640,480,30,100,1e3),"480p_3":be(480,480,15,100,400),"480p_4":be(640,480,30,100,750),"480p_6":be(480,480,30,100,600),"480p_8":be(848,480,15,100,610),"480p_9":be(848,480,30,100,930),"480p_10":be(640,480,10,100,400),"720p":be(1280,720,15,120,1130),"720p_auto":be(1280,720,30,900,3e3),"720p_1":be(1280,720,15,120,1130),"720p_2":be(1280,720,30,120,2e3),"720p_3":be(1280,720,30,120,1710),"720p_5":be(960,720,15,120,910),"720p_6":be(960,720,30,120,1380),"1080p":be(1920,1080,15,120,2080),"1080p_1":be(1920,1080,15,120,2080),"1080p_2":be(1920,1080,30,120,3e3),"1080p_3":be(1920,1080,30,120,3150),"1080p_5":be(1920,1080,60,120,4780),"1440p":be(2560,1440,30,120,4850),"1440p_1":be(2560,1440,30,120,4850),"1440p_2":be(2560,1440,60,120,7350),"4k":be(3840,2160,30,120,8910),"4k_1":be(3840,2160,30,120,8910),"4k_3":be(3840,2160,60,120,13500)},we={"480p":Ie(640,480,5),"480p_1":Ie(640,480,5),"480p_2":Ie(640,480,30),"480p_3":Ie(640,480,15),"720p":Ie(1280,720,5),"720p_auto":be(1280,720,30,900,3e3),"720p_1":Ie(1280,720,5),"720p_2":Ie(1280,720,30),"720p_3":Ie(1280,720,15),"1080p":Ie(1920,1080,5),"1080p_1":Ie(1920,1080,5),"1080p_2":Ie(1920,1080,30),"1080p_3":Ie(1920,1080,15)},De={"1SL1TL":Ae(1,1),"3SL3TL":Ae(3,3),"2SL3TL":Ae(2,3)};function Ce(e){return e||(e="480p_1"),"string"==typeof e?Object.assign({},Re[e]):e}function Me(e){return"string"==typeof e?Object.assign({},we[e]):e}function Ne(e){return"string"==typeof e?Object.assign({},De[e]):e}const Oe={speech_low_quality:ke(16e3,!1),speech_standard:ke(32e3,!1,18),music_standard:ke(48e3,!1),standard_stereo:ke(48e3,!0,56),high_quality:ke(48e3,!1,128),high_quality_stereo:ke(48e3,!0,192)};function Le(e){return"string"==typeof e?Object.assign({},Oe[e]):e}const Pe=[];function Ve(e){Pe.includes(e)||Pe.push(e)}function xe(e){const t=Pe.indexOf(e);-1!==t&&Pe.splice(t,1)}function Ue(e){return g(e.width,"config.width"),g(e.height,"config.height"),void 0!==e.frameRate&&g(e.frameRate,"config.frameRate"),void 0!==e.bitrateMax&&_(e.bitrateMax,"config.bitrateMax"),void 0!==e.bitrateMin&&_(e.bitrateMin,"config.bitrateMin"),!0}function Be(e){return void 0!==e.sampleRate&&_(e.sampleRate,"config.sampleRate",0,96e3,!0),void 0!==e.sampleSize&&_(e.sampleRate,"config.sampleSize",0,128,!0),void 0!==e.stereo&&T(e.stereo,"config.stereo"),void 0!==e.bitrate&&_(e.bitrate,"config.bitrate",0,1e4,!1),!0}function Fe(e){return"string"==typeof e?v(e,"profile",Object.keys(Re)):Ue(e),!0}function Ge(e){return"string"==typeof e?v(e,"profile",Object.keys(Oe)):Be(e),!0}function We(e){return v(e,"mediaSource",["screen","window","application"]),!0}let He=function(e){return e.NEED_RENEGOTIATE="@need_renegotiate",e.NEED_REPLACE_TRACK="@need_replace_track",e.NEED_REPLACE_MIXING_TRACK="@need_replace_mixing_track",e.NEED_CLOSE="@need_close",e.NEED_ENABLE_TRACK="@need_enable_track",e.NEED_DISABLE_TRACK="@need_disable_track",e.NEED_SESSION_ID="@need_sid",e.SET_OPTIMIZATION_MODE="@set_optimization_mode",e.GET_STATS="@get_stats",e.GET_RTC_STATS="@get_rtc_stats",e.GET_LOW_VIDEO_TRACK="@get_low_video_track",e.NEED_RESET_REMOTE_SDP="@need_reset_remote_sdp",e.NEED_UPDATE_VIDEO_ENCODER="@need_update_video_encoder",e.NEED_UPDATE_VIDEO_SEND_PARAMETERS="@need_update_video_send_parameters",e.NEED_MUTE_TRACK="@need_mute_track",e.NEED_UNMUTE_TRACK="@need_unmute_track",e}({}),Ke=function(e){return e.SCREEN_TRACK="screen_track",e.CUSTOM_TRACK="custome_track",e.LOW_STREAM="low_stream",e.SCREEN_LOW_TRACK="screen_low_track",e}({});function Ze(e){if(!e)throw new f(E.INVALID_PARAMS);return S(e.width)||g(e.width,"streamParameter.width"),S(e.height)||g(e.height,"streamParameter.height"),S(e.framerate)||g(e.framerate,"streamParameter.framerate"),S(e.bitrate)||_(e.bitrate,"streamParameter.bitrate"),!0}let Ye=function(e){return e[e.HIGH_STREAM=0]="HIGH_STREAM",e[e.LOW_STREAM=1]="LOW_STREAM",e}({}),ze=function(e){return e[e.HIGH_STREAM=0]="HIGH_STREAM",e[e.LOW_STREAM=1]="LOW_STREAM",e[e.HIGH_STREAM_LAYER1=4]="HIGH_STREAM_LAYER1",e[e.HIGH_STREAM_LAYER2=5]="HIGH_STREAM_LAYER2",e[e.HIGH_STREAM_LAYER3=6]="HIGH_STREAM_LAYER3",e[e.HIGH_STREAM_LAYER4=7]="HIGH_STREAM_LAYER4",e[e.HIGH_STREAM_LAYER5=8]="HIGH_STREAM_LAYER5",e[e.HIGH_STREAM_LAYER6=9]="HIGH_STREAM_LAYER6",e}({}),je=function(e){return e[e.DISABLE=0]="DISABLE",e[e.LOW_STREAM=1]="LOW_STREAM",e[e.AUDIO_ONLY=2]="AUDIO_ONLY",e[e.HIGH_STREAM_LAYER1=3]="HIGH_STREAM_LAYER1",e[e.HIGH_STREAM_LAYER2=4]="HIGH_STREAM_LAYER2",e[e.HIGH_STREAM_LAYER3=5]="HIGH_STREAM_LAYER3",e[e.HIGH_STREAM_LAYER4=6]="HIGH_STREAM_LAYER4",e[e.HIGH_STREAM_LAYER5=7]="HIGH_STREAM_LAYER5",e[e.HIGH_STREAM_LAYER6=8]="HIGH_STREAM_LAYER6",e}({}),Xe=function(e){return e.TRANSCEIVER_UPDATED="transceiver-updated",e.SEI_TO_SEND="sei-to-send",e.SEI_RECEIVED="sei-received",e.TRACK_UPDATED="track-updated",e}({}),Qe=function(e){return e.SOURCE_STATE_CHANGE="source-state-change",e.TRACK_ENDED="track-ended",e.BEAUTY_EFFECT_OVERLOAD="beauty-effect-overload",e.VIDEO_ELEMENT_VISIBLE_STATUS="video-element-visible-status",e.CLOSED="closed",e}({}),Je=function(e){return e.FIRST_FRAME_DECODED="first-frame-decoded",e.VIDEO_ELEMENT_VISIBLE_STATUS="video-element-visible-status",e.VIDEO_STATE_CHANGED="video-state-changed",e}({}),qe=function(e){return e.AUDIO="audio",e.VIDEO="video",e.DATA="data",e}({}),$e=function(e){return e.AUDIO_SOURCE_STATE_CHANGE="audio_source_state_change",e.RECEIVE_TRACK_BUFFER="receive_track_buffer",e.ON_AUDIO_BUFFER="on_audio_buffer",e.UPDATE_SOURCE="update_source",e}({}),et=function(e){return e.UPDATE_TRACK_SOURCE="update-track-source",e}({});const tt={sendVolumeLevel:0,sendBitrate:0,sendBytes:0,sendPackets:0,sendPacketsLost:0,sendJitterMs:0,sendRttMs:0,currentPacketLossRate:0},it={sendBytes:0,sendBitrate:0,sendPackets:0,sendPacketsLost:0,sendJitterMs:0,sendRttMs:0,sendResolutionHeight:0,sendResolutionWidth:0,captureResolutionHeight:0,captureResolutionWidth:0,targetSendBitrate:0,totalDuration:0,totalFreezeTime:0,currentPacketLossRate:0},rt={transportDelay:0,end2EndDelay:0,receiveBitrate:0,receiveLevel:0,receiveBytes:0,receiveDelay:0,receivePackets:0,receivePacketsLost:0,receivePacketsDiscarded:0,totalDuration:0,totalFreezeTime:0,freezeRate:0,packetLossRate:0,currentPacketLossRate:0,publishDuration:-1},st={uplinkNetworkQuality:0,downlinkNetworkQuality:0},ot={transportDelay:0,end2EndDelay:0,receiveBitrate:0,receiveBytes:0,receiveDelay:0,receivePackets:0,receivePacketsLost:0,receiveResolutionHeight:0,receiveResolutionWidth:0,totalDuration:0,totalFreezeTime:0,freezeRate:0,packetLossRate:0,currentPacketLossRate:0,publishDuration:-1};let nt=function(e){return e.ON_TRACK="on_track",e.ON_NODE="on_node",e}({}),at=function(e){return e.REQUEST_UPDATE_CONSTRAINTS="request_update_constraints",e.REQUEST_CONSTRAINTS="request_constraints",e}({}),ct=function(e){return e.IDLE="IDLE",e.INITING="INITING",e.INITEND="INITEND",e}({}),dt=function(e){return e.STATE_CHANGE="state_change",e.RECORDING_DEVICE_CHANGED="recordingDeviceChanged",e.PLAYOUT_DEVICE_CHANGED="playoutDeviceChanged",e.CAMERA_DEVICE_CHANGED="cameraDeviceChanged",e}({});function ut(e){return void 0!==e.smoothnessLevel&&_(e.smoothnessLevel,"options.smoothnessLevel",0,1,!1),void 0!==e.lighteningLevel&&_(e.lighteningLevel,"options.lighteningLevel",0,1,!1),void 0!==e.rednessLevel&&_(e.rednessLevel,"options.rednessLevel",0,1,!1),void 0!==e.lighteningContrastLevel&&v(e.lighteningContrastLevel,"options.lighteningContrastLevel",[0,1,2]),!0}let ht=function(e){return e.NONE="none",e.INIT="init",e.CANPLAY="canplay",e.PLAYING="playing",e.PAUSED="paused",e.SUSPEND="suspend",e.STALLED="stalled",e.WAITING="waiting",e.ERROR="error",e.DESTROYED="destroyed",e.ABORT="abort",e.ENDED="ended",e.EMPTIED="emptied",e.LOADEDDATA="loadeddata",e}({}),lt=function(e){return e[e.VideoStateStopped=0]="VideoStateStopped",e[e.VideoStateStarting=1]="VideoStateStarting",e[e.VideoStateDecoding=2]="VideoStateDecoding",e[e.VideoStateFrozen=3]="VideoStateFrozen",e}({});const pt={uninit:100,none:110,init:120,loadeddata:130,canplay:200,playing:210,paused:220,suspend:300,stalled:310,waiting:320,error:330,destroyed:340,abort:350,ended:360,emptied:370};let mt=function(e){return e.OPEN="open",e.MESSAGE="message",e.CLOSE="close",e.CLOSING="closing",e.ERROR="error",e}({});function gt(e,t,i,r,s){var o={};return Object.keys(r).forEach((function(e){o[e]=r[e]})),o.enumerable=!!o.enumerable,o.configurable=!!o.configurable,("value"in o||o.initializer)&&(o.writable=!0),o=i.slice().reverse().reduce((function(i,r){return r(e,t,i)||i}),o),s&&void 0!==o.initializer&&(o.value=o.initializer?o.initializer.call(s):void 0,o.initializer=void 0),void 0===o.initializer?(Object.defineProperty(e,t,o),null):o}function _t(e,t,i){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var r=i.call(e,t||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function Tt(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,r)}return i}function vt(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Tt(Object(i),!0).forEach((function(t){_t(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Tt(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}class ft extends y{set _mediaStreamTrack(e){e!==this.mediaStreamTrack&&(this.safeEmit(Xe.TRACK_UPDATED,e),this.mediaStreamTrack=e)}get _mediaStreamTrack(){return this.mediaStreamTrack}constructor(e,t){super(),_t(this,"trackMediaType",void 0),_t(this,"_ID",void 0),_t(this,"_rtpTransceiver",void 0),_t(this,"_lowRtpTransceiver",void 0),_t(this,"_hints",[]),_t(this,"_isClosed",!1),_t(this,"_originMediaStreamTrack",void 0),_t(this,"mediaStreamTrack",void 0),_t(this,"_external",{}),this._ID=t||k(8,"track-"),this._originMediaStreamTrack=e,this.mediaStreamTrack=e,Ve(this)}toString(){return this._ID}getTrackId(){return this._ID}getMediaStreamTrack(e){return e||b((()=>{var e;pe.reportApiInvoke(null,{name:I.GET_MEDIA_STREAM_TRACK,options:[],tag:A.TRACER}).onSuccess((null===(e=this._mediaStreamTrack)||void 0===e?void 0:e.label)||"")}),this.mediaStreamTrack.id||this.getTrackId()),this._mediaStreamTrack}getRTCRtpTransceiver(e){return e===Ye.LOW_STREAM?this._lowRtpTransceiver:this._rtpTransceiver}getMediaStreamTrackSettings(){return this.getMediaStreamTrack(!0).getSettings()}close(){this._isClosed=!0,this._lowRtpTransceiver=void 0,this._rtpTransceiver=void 0,xe(this),this.emit(Qe.CLOSED),this.removeAllListeners(Xe.SEI_RECEIVED)}_updateRtpTransceiver(e,t){if(t===Ye.LOW_STREAM){if(this._lowRtpTransceiver===e)return;this._lowRtpTransceiver=e}else{if(this._rtpTransceiver===e)return;this._rtpTransceiver=e}this.emit(Xe.TRANSCEIVER_UPDATED,e,t)}}class Et extends ft{get isExternalTrack(){return this._isExternalTrack}get muted(){return this._muted}get enabled(){return this._enabled}get processorContext(){return this._processorContext}constructor(e,t){super(e,t),_t(this,"_enabled",!0),_t(this,"_muted",!1),_t(this,"_isExternalTrack",!1),_t(this,"_isClosed",!1),_t(this,"_enabledMutex",void 0),_t(this,"processor",void 0),_t(this,"_processorContext",void 0),_t(this,"_handleTrackEnded",(()=>{this.onTrackEnded()})),this._enabledMutex=new R("".concat(this.getTrackId())),e.addEventListener("ended",this._handleTrackEnded)}getTrackLabel(){var e,t;return null!==(e=null===(t=this._originMediaStreamTrack)||void 0===t?void 0:t.label)&&void 0!==e?e:""}close(){this._isClosed||(this.stop(),this._originMediaStreamTrack.stop(),this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack.stop(),this._mediaStreamTrack=null),this._originMediaStreamTrack=null,this._enabledMutex=null,le.debug("[".concat(this.getTrackId(),"] close")),this.emit(He.NEED_CLOSE),super.close())}async _updateOriginMediaStreamTrack(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];this._isExternalTrack=i,e!==this._originMediaStreamTrack&&(this._originMediaStreamTrack&&(this._originMediaStreamTrack.removeEventListener("ended",this._handleTrackEnded),t&&this._originMediaStreamTrack.stop()),e.addEventListener("ended",this._handleTrackEnded),this._originMediaStreamTrack=e,this._muted&&(this._originMediaStreamTrack.enabled=!1),this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await w(this,He.NEED_REPLACE_TRACK,this),this.processor&&this._processorContext&&this.processor.updateInput({track:this._originMediaStreamTrack,context:this._processorContext}))}_getDefaultPlayerConfig(){return{}}onTrackEnded(){le.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(Qe.TRACK_ENDED)}stateCheck(e,t){if(le.debug("check track state, [muted: ".concat(this._muted,", enabled: ").concat(this._enabled,"] to [").concat(e,": ").concat(t,"]")),T(t,e),this._enabled&&this._muted&&"enabled"===e&&!1===t)throw new f(E.TRACK_STATE_UNREACHABLE,"cannot set enabled while the track is muted").print("error",le);if(!this._enabled&&!this._muted&&"muted"===e&&!0===t)throw new f(E.TRACK_STATE_UNREACHABLE,"cannot set muted while the track is disabled").print("error",le)}getProcessorStats(){return this._processorContext&&this._processorContext.gatherStats()||[]}getProcessorUsage(){return this._processorContext?this._processorContext.gatherUsage():Promise.resolve([])}}const St=window.AudioContext||window.webkitAudioContext;let yt=null;const kt=new class extends y{constructor(){super(...arguments),_t(this,"prevState",void 0),_t(this,"curState",void 0),_t(this,"currentTime",void 0),_t(this,"currentTimeStuckAt",void 0),_t(this,"interruptDetectorTrack",void 0),_t(this,"onLocalAudioTrackMute",(()=>{le.info("ios15-interruption-start"),this.emit(ye.IOS_15_16_INTERRUPTION_START)})),_t(this,"onLocalAudioTrackUnmute",(async()=>{le.info("ios15-interruption-end"),"running"!==this.curState||this.duringInterruption?le.info("ios15-interruption-end-canceled"):(yt&&await yt.suspend(),this.emit(ye.IOS_15_16_INTERRUPTION_END))}))}get duringInterruption(){return"running"===this.prevState&&"interrupted"===this.curState}bindInterruptDetectorTrack(e){le.debug("webaudio bindInterruptDetectorTrack ".concat(e.getTrackId())),this.interruptDetectorTrack||(this.interruptDetectorTrack=e,this.interruptDetectorTrack._mediaStreamTrack.onmute=this.onLocalAudioTrackMute,this.interruptDetectorTrack._mediaStreamTrack.onunmute=this.onLocalAudioTrackUnmute)}unbindInterruptDetectorTrack(e){le.debug("webaudio unbindInterruptDetectorTrack ".concat(e.getTrackId())),this.interruptDetectorTrack&&this.interruptDetectorTrack===e&&(this.interruptDetectorTrack._mediaStreamTrack&&(this.interruptDetectorTrack._mediaStreamTrack.onmute=null,this.interruptDetectorTrack._mediaStreamTrack.onunmute=null),this.interruptDetectorTrack=void 0)}};function bt(){if(!St)return void le.error("your browser is not support web audio");le.info("create audio context");const t=vt({},u("WEBAUDIO_INIT_OPTIONS"));le.debug("audio context init option:",JSON.stringify(t)),yt=new St(t),kt.curState=yt.state,yt.onstatechange=()=>{kt.prevState=kt.curState,kt.curState=yt?yt.state:void 0;const{prevState:t,curState:i}=kt,r="running"===i,s="interrupted"===i,o="running"===t,n="suspended"===t,a="interrupted"===t,c=e().osVersion;(C()||M())&&o&&s&&(le.info("ios".concat(c,"-interruption-start")),kt.emit(ye.IOS_INTERRUPTION_START)),(C()||M())&&(n||a)&&r&&(le.info("ios".concat(c,"-interruption-end")),kt.emit(ye.IOS_INTERRUPTION_END)),t!==i&&kt.emit(ye.STATE_CHANGE,i,t)},setInterval((()=>{var e;const t=null===(e=yt)||void 0===e?void 0:e.currentTime;if(kt.currentTime!==t)kt.currentTimeStuckAt&&(le.debug("AudioContext current time resume at ".concat(t)),kt.currentTimeStuckAt=void 0),kt.currentTime=t;else{if(t!==kt.currentTimeStuckAt){pe.reportApiInvoke(null,{name:"WEB_AUDIO_CURRENT_TIME_STUCK",options:{currentTime:t},tag:A.TRACER}).onSuccess(),le.warning("AudioContext current time stuck at ".concat(t))}kt.currentTimeStuckAt=t}}),5e3),async function(e){const t=["click","contextmenu","auxclick","dblclick","mousedown","mouseup","touchend","keydown","keyup"];let i,r=!1,s=!1,o=!1;function n(t){"running"===e.state?a(!1):C()||M()?"suspended"===e.state&&(a(!0),t&&e.resume().then(d,d)):"closed"!==e.state&&(a(!0),t&&e.resume().then(d,d))}function a(e){if(r!==e){r=e;for(let i=0,r=t;i<r.length;i+=1){const t=r[i];e?window.addEventListener(t,u,{capture:!0,passive:!0}):window.removeEventListener(t,u,{capture:!0,passive:!0})}}}function c(){n(!0)}function d(){n(!1)}function u(){n(!0)}function h(e){if(!o)if(i.paused)if(e){let e;l(!1),o=!0;try{e=i.play(),e?e.then(p,p):(i.addEventListener("playing",p),i.addEventListener("abort",p),i.addEventListener("error",p))}catch(e){p()}}else l(!0);else l(!1)}function l(e){if(s!==e){s=e;for(let i=0,r=t;i<r.length;i++){const t=r[i];e?window.addEventListener(t,m,{capture:!0,passive:!0}):window.removeEventListener(t,m,{capture:!0,passive:!0})}}}function p(){i.removeEventListener("playing",p),i.removeEventListener("abort",p),i.removeEventListener("error",p),o=!1,h(!1)}function m(){h(!0)}if(C()){const t=e.createMediaStreamDestination(),r=document.createElement("div");r.innerHTML="<audio x-webkit-airplay='deny'></audio>",i=r.children.item(0),i.controls=!1,i.disableRemotePlayback=!0,i.preload="auto",i.srcObject=t.stream,h(!0)}kt.on(ye.STATE_CHANGE,c),n(!1)}(yt)}function It(){if(!yt){if(bt(),!yt)throw new f(E.NOT_SUPPORTED,"can not create audio context");return yt}return yt}function At(){return!!yt}function Rt(e){if(function(){if(null!==Dt)return Dt;const e=It(),t=e.createBufferSource(),i=e.createGain(),r=e.createGain();t.connect(i),t.connect(r),t.disconnect(i);let s=!1;try{t.disconnect(i)}catch(e){s=!0}return t.disconnect(),Dt=s,s}())return;const t=e.connect,i=e.disconnect;e.connect=(i,r,s)=>(e._inputNodes||(e._inputNodes=[]),e._inputNodes.includes(i)||(i instanceof AudioNode?(e._inputNodes.push(i),t.call(e,i,r,s)):t.call(e,i,r)),e),e.disconnect=(r,s,o)=>{i.call(e),r?D(e._inputNodes,r):e._inputNodes=[];for(const i of e._inputNodes)t.call(e,i)}}function wt(e){const t=It();return new Promise(((i,r)=>{t.decodeAudioData(e,(e=>{i(e)}),(e=>{r(new f(E.DECODE_AUDIO_FILE_FAILED,e.toString()))}))}))}let Dt=null;function Ct(e,t){let i=!1;const r=1/t;if(u("DISABLE_WEBAUDIO")){const t=window.setInterval((()=>{i?window.clearInterval(t):e(performance.now()/1e3)}),1e3*r)}else{const t=It();let s=t.createGain();s.gain.value=0,s.connect(t.destination);const o=()=>{if(i)return void(s=null);const n=t.createOscillator();n.onended=o,n.connect(s),n.start(0),n.stop(t.currentTime+r),e(t.currentTime)};o()}return()=>{i=!0}}let Mt=null;function Nt(){if(Mt)return Mt;const e=It();if(!e.createMediaStreamDestination)throw new f(E.NOT_SUPPORTED,"can not create silence audio track");const t=e.createBufferSource(),i=e.createBuffer(1,44100,44100);t.loop=!0,t.buffer=i;const r=e.createMediaStreamDestination();return t.connect(r),Mt=r.stream.getAudioTracks()[0],Mt}function Ot(e){for(let t=0;t<e.outputBuffer.numberOfChannels;t+=1){const i=e.outputBuffer.getChannelData(t);for(let e=0;e<i.length;e+=1)i[e]=0}return e.inputBuffer}function Lt(e){const t=e.getChannelData(0);let i=0,r=0;for(let e=0;e<t.length;e+=1)0===t[e]?(i+=1,i>r&&(r=i)):i=0;return r/t.length*e.duration}class Pt{constructor(){_t(this,"context",void 0),_t(this,"analyserNode",void 0),_t(this,"sourceNode",void 0),this.context=It(),this.analyserNode=this.context.createAnalyser(),this.analyserNode.fftSize=2048,this.analyserNode.smoothingTimeConstant=.4}updateSource(e){if(e!==this.sourceNode){if(this.sourceNode)try{this.sourceNode.disconnect(this.analyserNode)}catch(e){}this.sourceNode=e,null==e||e.connect(this.analyserNode)}}getVolumeLevel(){if(!this.sourceNode)return 0;if(!this.context||C()||M()||"running"!==this.context.state&&this.context.resume(),!this.analyserNode)return 0;const e=new Float32Array(this.analyserNode.fftSize);if(this.analyserNode.getFloatTimeDomainData)this.analyserNode.getFloatTimeDomainData(e);else{const t=new Uint8Array(this.analyserNode.fftSize);this.analyserNode.getByteTimeDomainData(t);for(let i=0;i<e.length;++i)e[i]=t[i]/128-1}const t=e.reduce(((e,t)=>e+t*t),0)/e.length;return Math.max(10*Math.log10(t)+100,0)/100}getAnalyserNode(){return this.analyserNode}rebuildAnalyser(){try{var e,t;null===(e=this.sourceNode)||void 0===e||e.disconnect(this.analyserNode),this.analyserNode=this.context.createAnalyser(),this.analyserNode.fftSize=2048,this.analyserNode.smoothingTimeConstant=.4,null===(t=this.sourceNode)||void 0===t||t.connect(this.analyserNode)}catch(e){le.warning("rebuild analyser node failed.")}}destroy(){this.updateSource(void 0)}}class Vt extends y{get processSourceNode(){return this.sourceNode}set processedNode(e){var t;if(!this.isDestroyed&&this._processedNode!==e){try{var i;null===(i=this.sourceNode)||void 0===i||i.disconnect(this.outputNode)}catch(e){}null===(t=this._processedNode)||void 0===t||t.disconnect(),this._processedNode=e,this.connect()}}get processedNode(){return this._processedNode}constructor(){super(),_t(this,"outputNode",void 0),_t(this,"outputTrack",void 0),_t(this,"isPlayed",!1),_t(this,"sourceNode",void 0),_t(this,"context",void 0),_t(this,"audioBufferNode",void 0),_t(this,"destNode",void 0),_t(this,"audioOutputLevel",0),_t(this,"volumeLevelAnalyser",void 0),_t(this,"_processedNode",void 0),_t(this,"playNode",void 0),_t(this,"isDestroyed",!1),_t(this,"onNoAudioInput",void 0),_t(this,"isNoAudioInput",!1),_t(this,"_noAudioInputCount",0),this.context=It(),this.playNode=this.context.destination,this.outputNode=this.context.createGain(),Rt(this.outputNode),this.volumeLevelAnalyser=new Pt}startGetAudioBuffer(e){this.audioBufferNode||(this.audioBufferNode=this.context.createScriptProcessor(e),this.outputNode.connect(this.audioBufferNode),this.audioBufferNode.connect(this.context.destination),this.audioBufferNode.onaudioprocess=e=>{this.emit($e.ON_AUDIO_BUFFER,Ot(e))})}stopGetAudioBuffer(){this.audioBufferNode&&(this.audioBufferNode.onaudioprocess=null,this.outputNode.disconnect(this.audioBufferNode),this.audioBufferNode=void 0)}createOutputTrack(){if(!fe().webAudioMediaStreamDest)throw new f(E.NOT_SUPPORTED,"your browser is not support audio processor");return this.destNode&&this.outputTrack||(this.destNode=this.context.createMediaStreamDestination(),this.outputNode.connect(this.destNode),this.outputTrack=this.destNode.stream.getAudioTracks()[0]),this.outputTrack}play(e){"running"!==this.context.state&&r((()=>{kt.emit("autoplay-failed")})),this.isPlayed=!0,this.playNode=e||this.context.destination,this.outputNode.connect(this.playNode)}stop(){if(this.isPlayed)try{this.outputNode.disconnect(this.playNode)}catch(e){}this.isPlayed=!1}getAccurateVolumeLevel(){return this.volumeLevelAnalyser.getVolumeLevel()}async checkHasAudioInput(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;if(e>5)return this.isNoAudioInput=!0,this.onNoAudioInput&&this.onNoAudioInput(),!1;C()||M()?"suspended"===this.context.state&&this.context.resume():"running"!==this.context.state&&this.context.resume();const t=this.volumeLevelAnalyser.getAnalyserNode();let i;t.getFloatTimeDomainData?(i=new Float32Array(t.fftSize),t.getFloatTimeDomainData(i)):(i=new Uint8Array(t.fftSize),t.getByteTimeDomainData(i));let r=!1;for(let e=0;e<i.length;e++)0!==i[e]&&(r=!0);return r?(this.isNoAudioInput=!1,!0):(await N(200),await this.checkHasAudioInput(e?e+1:1)&&r)}getAudioVolume(){return this.outputNode.gain.value}setVolume(e){this.outputNode.gain.setValueAtTime(e,this.context.currentTime)}destroy(){this.disconnect(),this.stop(),this.isDestroyed=!0,this.onNoAudioInput=void 0}disconnect(){var e,t;null===(e=this.processedNode)||void 0===e||e.disconnect(),null===(t=this.sourceNode)||void 0===t||t.disconnect(),this.outputNode&&this.outputNode.disconnect()}connect(){var e;this.processedNode?null===(e=this.processedNode)||void 0===e||e.connect(this.outputNode):this.sourceNode&&this.sourceNode.connect(this.outputNode);this.volumeLevelAnalyser.updateSource(this.outputNode)}}class xt extends Vt{get isFreeze(){return!1}constructor(t,i,r){var s;if(super(),_t(this,"sourceNode",void 0),_t(this,"track",void 0),_t(this,"clonedTrack",void 0),_t(this,"audioElement",void 0),_t(this,"isCurrentTrackCloned",!1),_t(this,"isRemoteTrack",!1),_t(this,"originVolumeLevelAnalyser",void 0),_t(this,"rebuildWebAudio",(async()=>{if(le.debug("ready to rebuild web audio, state:",this.context.state),this.isNoAudioInput&&await this.checkHasAudioInput(),!this.isNoAudioInput||this.isDestroyed)return document.body.removeEventListener("click",this.rebuildWebAudio,!0),void le.debug("rebuild web audio success, current volume status",this.getAccurateVolumeLevel());this.context.resume().then((()=>le.info("resume success"))),le.debug("rebuild web audio because of ios 12 bugs"),this.disconnect();const e=this.track;this.track=this.track.clone(),this.isCurrentTrackCloned?e.stop():this.isCurrentTrackCloned=!0;const t=new MediaStream([this.track]);this.sourceNode=this.context.createMediaStreamSource(t),Rt(this.sourceNode),this.volumeLevelAnalyser.rebuildAnalyser();const i=this.outputNode.gain.value;this.outputNode=this.context.createGain(),this.outputNode.gain.setValueAtTime(i,this.context.currentTime),Rt(this.outputNode),this.emit($e.UPDATE_SOURCE),this.connect(),this.audioElement.srcObject=t,this.isPlayed&&this.play(this.playNode),this.checkHasAudioInput()})),"audio"!==t.kind)throw new f(E.UNEXPECTED_ERROR);this.track=t;const o=new MediaStream([this.track]);if(this.isRemoteTrack=!!i,this.sourceNode=this.context.createMediaStreamSource(o),Rt(this.sourceNode),r){const e=r.clone();e.enabled=!0,this.clonedTrack=e,le.debug("create an unmuted track ".concat(e.id," from the original track ").concat(r.id," to get the volume"));const t=this.context.createMediaStreamSource(new MediaStream([e]));Rt(t),this.originVolumeLevelAnalyser=new Pt,this.originVolumeLevelAnalyser.updateSource(t)}this.connect(),this.audioElement=document.createElement("audio"),this.audioElement.srcObject=o;const n=e();i&&n.os===a.IOS&&Number(null===(s=n.osVersion)||void 0===s?void 0:s.split(".")[0])<15&&(kt.on(ye.STATE_CHANGE,(()=>{"suspended"===this.context.state?document.body.addEventListener("click",this.rebuildWebAudio,!0):"running"===this.context.state&&this.rebuildWebAudio()})),this.checkHasAudioInput().then((e=>{e||document.body.addEventListener("click",this.rebuildWebAudio,!0)})))}updateTrack(e){this.sourceNode.disconnect(),this.track=e,this.isCurrentTrackCloned=!1;const t=new MediaStream([e]);this.sourceNode=this.context.createMediaStreamSource(t),Rt(this.sourceNode),this.processedNode||this.sourceNode.connect(this.outputNode),this.emit($e.UPDATE_SOURCE),this.audioElement.srcObject=t}destroy(){var e;this.audioElement.srcObject=null,this.audioElement.remove(),kt.off("state-change",this.rebuildWebAudio),null===(e=this.originVolumeLevelAnalyser)||void 0===e||e.destroy(),this.clonedTrack=void 0,super.destroy()}createMediaStreamSourceNode(e){return this.context.createMediaStreamSource(new MediaStream([e]))}updateOriginTrack(e){const t=e.clone();t.enabled=!0,this.clonedTrack&&(this.clonedTrack.stop(),this.clonedTrack=t),le.debug("create an unmuted track ".concat(t.id," from the original track ").concat(e.id," to get the volume"));const i=this.context.createMediaStreamSource(new MediaStream([t]));Rt(i),this.originVolumeLevelAnalyser&&this.originVolumeLevelAnalyser.updateSource(i)}getOriginVolumeLevel(){return this.originVolumeLevelAnalyser?this.originVolumeLevelAnalyser.getVolumeLevel():this.getAccurateVolumeLevel()}}async function Ut(e,t,i){const r=(e,t)=>e?"number"!=typeof e?e.max||e.exact||e.ideal||e.min||t:e:t,s={audio:!!i&&{mandatory:{chromeMediaSource:"desktop"}},video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:e,maxHeight:r(t.height,1080),maxWidth:r(t.width,1920)}}};return t.frameRate&&"number"!=typeof t.frameRate?(s.video.mandatory.maxFrameRate=t.frameRate.max,s.video.mandatory.minFrameRate=t.frameRate.min):"number"==typeof t.frameRate&&(s.video.mandatory.maxFrameRate=t.frameRate),await navigator.mediaDevices.getUserMedia(s)}async function Bt(e,t){const i=await Ft(e.mediaSource),{sourceId:r,audio:s}=await O(i,t);return await Ut(r,e,s)}async function Ft(e){let t=["window","screen"];"application"!==e&&"window"!==e||(t=["window"]),"screen"===e&&(t=["screen"]);const i=L();if(!i)throw console.error("failed to fetch electron, please mount it to window"),new f(E.ELECTRON_IS_NULL);let r=null;try{var s;r=(null===(s=i.desktopCapturer)||void 0===s?void 0:s.getSources({types:t}))||i.ipcRenderer.invoke("DESKTOP_CAPTURER_GET_SOURCES",{types:t})}catch(e){r=null}r&&r.then||(r=new Promise(((e,r)=>{i.desktopCapturer.getSources({types:t},((t,i)=>{t?r(t):e(i)}))})));try{return await r}catch(e){throw new f(E.ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR,e.toString())}}const Gt=new R("safari");let Wt=!1,Ht=!1;async function Kt(e,t){let i=0,r=null;for(;i<2;)try{r=await Zt(e,t,i>0);break}catch(e){if(e instanceof f)throw le.error("[".concat(t,"] ").concat(e.toString())),e;const r=Yt(e.name||e.code||e,e.message);if(r.code===E.MEDIA_OPTION_INVALID){le.debug("[".concat(t,"] detect media option invalid, retry")),i+=1,await N(500);continue}throw le.error("[".concat(t,"] ").concat(r.toString())),r}if(!r)throw new f(E.UNEXPECTED_ERROR,"can not find stream after getUserMedia");return r}async function Zt(t,i,r){if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)throw new f(E.NOT_SUPPORTED,"can not find getUserMedia");r&&(t.video&&(delete t.video.width,delete t.video.height),t.screen&&(delete t.screen.width,delete t.screen.height));const s=fe(),o=new MediaStream;if(t.audioSource&&o.addTrack(t.audioSource),t.videoSource&&o.addTrack(t.videoSource),!t.audio&&!t.video&&!t.screen)return le.debug("Using Video Source/ Audio Source"),o;if(t.screen)if(P())if(t.screen.sourceId){zt(o,await Ut(t.screen.sourceId,t.screen,!!t.screenAudio))}else{zt(o,await Bt(t.screen,!!t.screenAudio))}else if(l()&&t.screen.extensionId&&t.screen.mandatory){if(!s.getStreamFromExtension)throw new f(E.NOT_SUPPORTED,"This browser does not support screen sharing");le.debug("[".concat(i,'] Screen access on chrome stable, looking for extension"'));const e=await(a=t.screen.extensionId,p=i,new Promise(((e,t)=>{try{chrome.runtime.sendMessage(a,{getStream:!0},(i=>{if(!i||!i.streamId)return le.error("[".concat(p,"] No response from Chrome Plugin. Plugin not installed properly"),i),void t(new f(E.CHROME_PLUGIN_NO_RESPONSE,"No response from Chrome Plugin. Plugin not installed properly"));e(i.streamId)}))}catch(e){le.error("[".concat(p,"] AgoraRTC screensharing plugin is not accessible(").concat(a,")"),e.toString()),t(new f(E.CHROME_PLUGIN_NOT_INSTALL))}})));t.screen.mandatory.chromeMediaSourceId=e;zt(o,await navigator.mediaDevices.getUserMedia({video:{mandatory:t.screen.mandatory}}))}else if(s.getDisplayMedia){var n;t.screen.mediaSource&&We(t.screen.mediaSource);const e={width:t.screen.width,height:t.screen.height,frameRate:t.screen.frameRate,displaySurface:null!==(n=t.screen.displaySurface)&&void 0!==n?n:"screen"===t.screen.mediaSource?"monitor":t.screen.mediaSource},{selfBrowserSurface:r,surfaceSwitching:s,systemAudio:a,preferCurrentTab:c}=t.screen,d={selfBrowserSurface:r,surfaceSwitching:s,systemAudio:a,preferCurrentTab:c};!r&&delete d.selfBrowserSurface,!s&&delete d.surfaceSwitching,!a&&delete d.systemAudio,!c&&delete d.preferCurrentTab,le.debug("[".concat(i,"] getDisplayMedia:"),JSON.stringify({video:e,audio:t.screenAudio,controls:d}));zt(o,await navigator.mediaDevices.getDisplayMedia(vt({video:e,audio:t.screenAudio},d)))}else{if(!h())throw le.error("[".concat(i,"] This browser does not support screenSharing")),new f(E.NOT_SUPPORTED,"This browser does not support screen sharing");{t.screen.mediaSource&&We(t.screen.mediaSource);const e={video:{mediaSource:t.screen.mediaSource,width:t.screen.width,height:t.screen.height,frameRate:t.screen.frameRate}};le.debug("[".concat(i,"] getUserMedia: ").concat(JSON.stringify(e)));zt(o,await navigator.mediaDevices.getUserMedia(e))}}var a,p;if(!t.video&&!t.audio)return o;let m={video:t.video,audio:t.audio},g=u("MEDIA_DEVICE_CONSTRAINTS");if(g)try{"string"==typeof g&&(g=JSON.parse(g)),m=V(m,g)}catch(e){}le.debug("[".concat(i,"] GetUserMedia"),JSON.stringify(m)),e();let _,T=null;(c()||C()||d())&&(T=await Gt.lock());try{_=await navigator.mediaDevices.getUserMedia(m)}catch(e){throw T&&T(),e}return m.audio&&(Wt=!0),m.video&&(Ht=!0),zt(o,_),T&&T(),o}function Yt(e,t){switch(e){case"Starting video failed":case"OverconstrainedError":case"TrackStartError":return new f(E.MEDIA_OPTION_INVALID,"".concat(e,": ").concat(t));case"NotFoundError":case"DevicesNotFoundError":return new f(E.DEVICE_NOT_FOUND,"".concat(e,": ").concat(t));case"NotSupportedError":return new f(E.NOT_SUPPORTED,"".concat(e,": ").concat(t));case"NotReadableError":return new f(E.NOT_READABLE,"".concat(e,": ").concat(t));case"InvalidStateError":case"NotAllowedError":case"PERMISSION_DENIED":case"PermissionDeniedError":return new f(E.PERMISSION_DENIED,"".concat(e,": ").concat(t));case"ConstraintNotSatisfiedError":return new f(E.CONSTRAINT_NOT_SATISFIED,"".concat(e,": ").concat(t));default:return le.error("getUserMedia unexpected error",e),new f(E.UNEXPECTED_ERROR,"".concat(e,": ").concat(t))}}function zt(e,t){const i=e.getVideoTracks()[0],r=e.getAudioTracks()[0],s=t.getVideoTracks()[0],o=t.getAudioTracks()[0];o&&(r&&e.removeTrack(r),e.addTrack(o)),s&&(i&&e.removeTrack(i),e.addTrack(s))}class jt extends y{get state(){return this._state}set state(e){e!==this._state&&(this.emit(dt.STATE_CHANGE,e),this._state=e)}constructor(){super(),_t(this,"_state",ct.IDLE),_t(this,"isAccessMicrophonePermission",!1),_t(this,"isAccessCameraPermission",!1),_t(this,"lastAccessMicrophonePermission",!1),_t(this,"lastAccessCameraPermission",!1),_t(this,"checkdeviceMatched",!1),_t(this,"deviceInfoMap",new Map),this.init().then((()=>{navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",this.updateDevicesInfo.bind(this)),window.setInterval((()=>{(u("ENUMERATE_DEVICES_INTERVAL")||(x()||U())&&i())&&this.updateDevicesInfo()}),u("ENUMERATE_DEVICES_INTERVAL_TIME"))})).catch((e=>le.error(e.toString())))}async enumerateDevices(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices){return new f(E.NOT_SUPPORTED,"enumerateDevices() not supported.").throw()}const r=await navigator.mediaDevices.enumerateDevices(),s=this.checkMediaDeviceInfoIsOk(r);let o=!this.isAccessMicrophonePermission&&e,n=!this.isAccessCameraPermission&&t;s.audio&&(o=!1),s.video&&(n=!1);let a=null,c=null,d=null;if(!i&&(o||n)){if(Gt.isLocked){le.debug("[device manager] wait GUM lock");(await Gt.lock())(),le.debug("[device manager] GUM unlock")}if(Wt&&(o=!1,this.isAccessMicrophonePermission=!0),Ht&&(n=!1,this.isAccessCameraPermission=!0),le.debug("[device manager] check media device permissions",e,t,o,n),o&&n){try{d=await navigator.mediaDevices.getUserMedia({audio:!0,video:!0})}catch(e){const t=Yt(e.name||e.code||e,e.message);if(t.code===E.PERMISSION_DENIED)throw t;le.warning("getUserMedia failed in getDevices",t)}this.isAccessCameraPermission=!0,this.isAccessMicrophonePermission=!0}else if(o){try{a=await navigator.mediaDevices.getUserMedia({audio:e})}catch(e){const t=Yt(e.name||e.code||e,e.message);if(t.code===E.PERMISSION_DENIED)throw t;le.warning("getUserMedia failed in getDevices",t)}this.isAccessMicrophonePermission=!0}else if(n){try{c=await navigator.mediaDevices.getUserMedia({video:t})}catch(e){const t=Yt(e.name||e.code||e,e.message);if(t.code===E.PERMISSION_DENIED)throw t;le.warning("getUserMedia failed in getDevices",t)}this.isAccessCameraPermission=!0}le.debug("[device manager] mic permission",e,"cam permission",t)}try{const e=await navigator.mediaDevices.enumerateDevices();return a&&a.getTracks().forEach((e=>e.stop())),c&&c.getTracks().forEach((e=>e.stop())),d&&d.getTracks().forEach((e=>e.stop())),a=null,c=null,d=null,e}catch(e){a&&a.getTracks().forEach((e=>e.stop())),c&&c.getTracks().forEach((e=>e.stop())),d&&d.getTracks().forEach((e=>e.stop())),a=null,c=null,d=null;return new f(E.ENUMERATE_DEVICES_FAILED,e.toString()).throw()}}async getRecordingDevices(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return(await this.enumerateDevices(!0,!1,e)).filter((e=>"audioinput"===e.kind))}async getCamerasDevices(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return(await this.enumerateDevices(!1,!0,e)).filter((e=>"videoinput"===e.kind))}async getSpeakers(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return(await this.enumerateDevices(!0,!1,e)).filter((e=>"audiooutput"===e.kind))}searchDeviceIdByName(e){let t=null;return this.deviceInfoMap.forEach((i=>{i.device.label===e&&(t=i.device.deviceId)})),t}async getDeviceById(e){const t=(await this.enumerateDevices(!0,!0,!0)).find((t=>t.deviceId===e));if(!t)throw new f(E.DEVICE_NOT_FOUND,"deviceId: ".concat(e));return t}async init(){this.state=ct.INITING;try{await this.updateDevicesInfo(),this.state=ct.INITEND}catch(e){if(le.warning("Device Detection functionality cannot start properly.",e.toString()),this.state=ct.IDLE,!B()){new f(E.WEB_SECURITY_RESTRICT,"Your context is limited by web security, please try using https protocol or localhost.").throw()}throw e}}async updateDevicesInfo(){const e=await this.enumerateDevices(!0,!0,!0),t=Date.now(),i=[];if(e[0]&&e[0].label&&!1===this.checkdeviceMatched){this.checkdeviceMatched=!0;const t=e.find((e=>"audioinput"===e.kind&&"default"===e.deviceId)),i=e.find((e=>"audiooutput"===e.kind&&"default"===e.deviceId));t&&i?i.groupId===t.groupId?le.debug("[device-check] default input ".concat(t.label," and output ").concat(i.label," is the same group")):le.debug("[device-check] default input ".concat(t.label," and output ").concat(i.label," is not the same group")):le.debug("[device-check] default input or output not found")}const r=this.checkMediaDeviceInfoIsOk(e);if(e.forEach((e=>{if(!e.deviceId)return;const r=this.deviceInfoMap.get("".concat(e.kind,"_").concat(e.deviceId));if("ACTIVE"!==(r?r.state:"INACTIVE")){const r={initAt:t,updateAt:t,device:e,state:"ACTIVE"};this.deviceInfoMap.set("".concat(e.kind,"_").concat(e.deviceId),r),i.push(r)}r&&(r.updateAt=t)})),this.deviceInfoMap.forEach(((e,r)=>{"ACTIVE"===e.state&&e.updateAt!==t&&(e.state="INACTIVE",i.push(e))})),this.state!==ct.INITEND)return r.audio&&(this.lastAccessMicrophonePermission=!0,this.isAccessMicrophonePermission=!0),void(r.video&&(this.lastAccessCameraPermission=!0,this.isAccessCameraPermission=!0));i.forEach((e=>{switch(e.device.kind){case"audioinput":this.lastAccessMicrophonePermission&&this.isAccessMicrophonePermission&&this.emit(dt.RECORDING_DEVICE_CHANGED,e);break;case"videoinput":this.lastAccessCameraPermission&&this.isAccessCameraPermission&&this.emit(dt.CAMERA_DEVICE_CHANGED,e);break;case"audiooutput":this.lastAccessMicrophonePermission&&this.isAccessMicrophonePermission&&this.emit(dt.PLAYOUT_DEVICE_CHANGED,e)}})),r.audio&&(this.lastAccessMicrophonePermission=!0,this.isAccessMicrophonePermission=!0),r.video&&(this.lastAccessCameraPermission=!0,this.isAccessCameraPermission=!0)}checkMediaDeviceInfoIsOk(e){const t=e.filter((e=>"audioinput"===e.kind)),i=e.filter((e=>"videoinput"===e.kind)),r={audio:!1,video:!1};for(const e of t)if(e.label&&e.deviceId){r.audio=!0;break}for(const e of i)if(e.label&&e.deviceId){r.video=!0;break}return r}}const Xt=new jt;let Qt=!1;const Jt=new class extends y{constructor(){super(...arguments),_t(this,"onAutoplayFailed",void 0),_t(this,"onAudioAutoplayFailed",void 0)}};function qt(){if(e(),!Qt){const e=t=>{t.preventDefault(),Qt=!1,F()?document.body.removeEventListener("click",e,!0):(document.body.removeEventListener("touchstart",e,!0),document.body.removeEventListener("mousedown",e,!0))};Qt=!0,F()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0)),le.info("detect media autoplay failed, document: https://docs.agora.io/cn/Voice/autoplay_policy_web_ng?platform=Web"),Jt.onAutoplayFailed?Jt.onAutoplayFailed():Jt.onAudioAutoplayFailed?le.warning("AgoraRTC.onAudioAutoplayFailed has been deprecated in favor of AgoraRTC.onAutoplayFailed.\n\n Please refer to the Agora document to migrate the newer API, https://docs.agora.io/en/Voice/autoplay_policy_web_ng?platform=Web ."):le.warning("We have detected a media autoplay failed event, and found out that you haven't implemented AgoraRTC.onAutoplayFailed callback yet.\n\n It will cause audio/video element not playing automatically on some browsers without user interaction, possibly hurting user experiences.\n\n Please refer to the Agora document to properly handle autoplay failed event, https://docs.agora.io/en/Voice/autoplay_policy_web_ng?platform=Web ."),Jt.emit("autoplay-failed")}}function $t(e,t,i,r){if(!e)return;const s=pe.getBaseInfoBySessionId(e);if(!s)return;const o=s.info,n=Date.now(),a=vt(vt({},o),{},{vid:void 0===o.vid?0:Number(o.vid),lts:n,elapse:n-s.startTime,cbRegistered:Jt.onAutoplayFailed||Jt.onAudioAutoplayFailed?1:-1,errorMsg:i,mediaType:t,trackId:r,extend:void 0});pe.send({type:me.AUTOPLAY_FAILED,data:a},!0)}const ei=["play","playing","loadeddata","canplay","pause","stalled","suspend","waiting","abort","emptied","ended","error"],ti=new class{constructor(){_t(this,"onAutoplayFailed",void 0),_t(this,"elementMap",new Map),_t(this,"elementStateMap",new Map),_t(this,"elementsNeedToResume",[]),_t(this,"sinkIdMap",new Map),_t(this,"autoResumeAfterInterruption",(e=>{Array.from(this.elementMap.entries()).forEach((t=>{let[i,r]=t;const s=this.elementStateMap.get(i),o=r.srcObject.getAudioTracks()[0],n=o&&o.readyState;if(le.debug("resume after interrupted, ele: ".concat(s," audio: ").concat(n," ").concat(e)),"live"===n){if(e)return r.pause(),void r.play();if("running"===kt.curState)return W()?(r.pause(),void r.play()):void(s&&"paused"===s&&r.play())}}))})),_t(this,"autoResumeAfterInterruptionOnIOS15_16",(()=>{Array.from(this.elementMap.entries()).forEach((e=>{let[t,i]=e;const r=i.srcObject.getAudioTracks()[0];r&&"live"===r.readyState&&(le.debug("auto resume after interruption inside autoResumeAfterInterruptionOnIOS15"),i.pause(),i.play())}))})),this.autoResumeAudioElement(),kt.on(ye.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),kt.on(ye.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16),kt.on(ye.STATE_CHANGE,(()=>{C()&&"suspended"===kt.prevState&&"running"===kt.curState&&this.autoResumeAfterInterruption()}))}async setSinkID(e,t){const i=this.elementMap.get(e);if(this.sinkIdMap.set(e,t),i)try{await i.setSinkId(t)}catch(e){throw new f(E.PERMISSION_DENIED,"can not set sink id: "+e.toString())}}play(e,t,i,s){if(this.elementMap.has(t))return;const o=document.createElement("audio");o.autoplay=!0,o.srcObject=new MediaStream([e]),this.bindAudioElementEvents(t,o),this.elementMap.set(t,o),this.elementStateMap.set(t,ht.INIT),this.setVolume(t,i);const n=this.sinkIdMap.get(t);if(n)try{o.setSinkId(n).catch((e=>{le.warning("[".concat(t,"] set sink id failed"),e.toString())}))}catch(e){le.warning("[".concat(t,"] set sink id failed"),e.toString())}const a=o.play();a&&a.then&&a.catch((e=>{s&&$t(s,"audio",e.message,t),le.warning("audio element play warning",e.toString()),this.elementMap.has(t)&&"NotAllowedError"===e.name&&(le.warning("detected audio element autoplay failed"),this.elements