@agora-js/media
Version:
media module across @agora-js packages
5 lines (4 loc) • 188 kB
JavaScript
/**
* AgoraWebSDK_N-v4.24.0-0-gf2267710-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,isAboveSafari15_4 as l,isChrome as p,isEdge as m,isMobile as g,isBelowChrome as _,checkValidConstrainLong as T,checkValidNumber as f,checkValidBoolean as E,checkValidEnum as v,AgoraRTCError as y,AgoraRTCErrorCode as S,isEmpty as b,EventEmitter as k,getRandomString as I,runOnce as A,AgoraAPIName as R,AgoraAPITag as w,PromiseMutex as C,emitAsPromiseNoResponse as D,removeItemFromList as N,isIOS as M,isIpadOS as O,wait as L,showElectronSelectSourceWindow as P,getElectronInstance as V,isElectron as x,recursiveMerge as U,isAndroid as F,isHarmonyOS as B,detectSecureContext as G,isAndroidChromium as W,domLoadedPromise as Z,isIOS15 as K,emitAsPromise as H,noop as Y,isLegacyChrome as j,isAboveEdge as X,isAboveOpera as z,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 Te}from"@agora-js/report";import fe 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};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,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(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")||!(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)}let Ce=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 De(e,t,i){return{sampleRate:e,stereo:t,bitrate:i}}function Ne(e,t,i,r,s){return{width:e,height:t,frameRate:i,bitrateMin:r,bitrateMax:s}}function Me(e,t,i,r,s){return{width:{max:e},height:{max:t},frameRate:i,bitrateMin:r,bitrateMax:s}}function Oe(e,t){return{numSpatialLayers:e,numTemporalLayers:t}}const Le={"90p":Ne(160,90),"90p_1":Ne(160,90),"120p":Ne(160,120,15,30,65),"120p_1":Ne(160,120,15,30,65),"120p_3":Ne(120,120,15,30,50),"120p_4":Ne(212,120),"180p":Ne(320,180,15,30,140),"180p_1":Ne(320,180,15,30,140),"180p_3":Ne(180,180,15,30,100),"180p_4":Ne(240,180,15,30,120),"240p":Ne(320,240,15,40,200),"240p_1":Ne(320,240,15,40,200),"240p_3":Ne(240,240,15,40,140),"240p_4":Ne(424,240,15,40,220),"360p":Ne(640,360,15,80,400),"360p_1":Ne(640,360,15,80,400),"360p_3":Ne(360,360,15,80,260),"360p_4":Ne(640,360,30,80,600),"360p_6":Ne(360,360,30,80,400),"360p_7":Ne(480,360,15,80,320),"360p_8":Ne(480,360,30,80,490),"360p_9":Ne(640,360,15,80,800),"360p_10":Ne(640,360,24,80,800),"360p_11":Ne(640,360,24,80,1e3),"480p":Ne(640,480,15,100,500),"480p_1":Ne(640,480,15,100,500),"480p_2":Ne(640,480,30,100,1e3),"480p_3":Ne(480,480,15,100,400),"480p_4":Ne(640,480,30,100,750),"480p_6":Ne(480,480,30,100,600),"480p_8":Ne(848,480,15,100,610),"480p_9":Ne(848,480,30,100,930),"480p_10":Ne(640,480,10,100,400),"720p":Ne(1280,720,15,120,1130),"720p_auto":Ne(1280,720,30,900,3e3),"720p_1":Ne(1280,720,15,120,1130),"720p_2":Ne(1280,720,30,120,2e3),"720p_3":Ne(1280,720,30,120,1710),"720p_5":Ne(960,720,15,120,910),"720p_6":Ne(960,720,30,120,1380),"1080p":Ne(1920,1080,15,120,2080),"1080p_1":Ne(1920,1080,15,120,2080),"1080p_2":Ne(1920,1080,30,120,3e3),"1080p_3":Ne(1920,1080,30,120,3150),"1080p_5":Ne(1920,1080,60,120,4780),"1440p":Ne(2560,1440,30,120,4850),"1440p_1":Ne(2560,1440,30,120,4850),"1440p_2":Ne(2560,1440,60,120,7350),"4k":Ne(3840,2160,30,120,8910),"4k_1":Ne(3840,2160,30,120,8910),"4k_3":Ne(3840,2160,60,120,13500)},Pe={"480p":Me(640,480,5),"480p_1":Me(640,480,5),"480p_2":Me(640,480,30),"480p_3":Me(640,480,15),"720p":Me(1280,720,5),"720p_auto":Ne(1280,720,30,900,3e3),"720p_1":Me(1280,720,5),"720p_2":Me(1280,720,30),"720p_3":Me(1280,720,15),"1080p":Me(1920,1080,5),"1080p_1":Me(1920,1080,5),"1080p_2":Me(1920,1080,30),"1080p_3":Me(1920,1080,15)},Ve={"1SL1TL":Oe(1,1),"3SL3TL":Oe(3,3),"2SL3TL":Oe(2,3)};function xe(e){return e||(e="480p_1"),"string"==typeof e?Object.assign({},Le[e]):e}function Ue(e){return"string"==typeof e?Object.assign({},Pe[e]):e}function Fe(e){return"string"==typeof e?Object.assign({},Ve[e]):e}const Be={speech_low_quality:De(16e3,!1),speech_standard:De(32e3,!1,18),music_standard:De(48e3,!1),standard_stereo:De(48e3,!0,56),high_quality:De(48e3,!1,128),high_quality_stereo:De(48e3,!0,192)};function Ge(e){return"string"==typeof e?Object.assign({},Be[e]):e}const We=[];function Ze(e){We.includes(e)||We.push(e)}function Ke(e){const t=We.indexOf(e);-1!==t&&We.splice(t,1)}function He(e){return T(e.width,"config.width"),T(e.height,"config.height"),void 0!==e.frameRate&&T(e.frameRate,"config.frameRate"),void 0!==e.bitrateMax&&f(e.bitrateMax,"config.bitrateMax"),void 0!==e.bitrateMin&&f(e.bitrateMin,"config.bitrateMin"),!0}function Ye(e){return void 0!==e.sampleRate&&f(e.sampleRate,"config.sampleRate",0,96e3,!0),void 0!==e.sampleSize&&f(e.sampleRate,"config.sampleSize",0,128,!0),void 0!==e.stereo&&E(e.stereo,"config.stereo"),void 0!==e.bitrate&&f(e.bitrate,"config.bitrate",0,1e4,!1),!0}function je(e){return"string"==typeof e?v(e,"profile",Object.keys(Le)):He(e),!0}function Xe(e){return"string"==typeof e?v(e,"profile",Object.keys(Be)):Ye(e),!0}function ze(e){return v(e,"mediaSource",["screen","window","application"]),!0}let Qe=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}({}),Je=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 qe(e){if(!e)throw new y(S.INVALID_PARAMS);return b(e.width)||T(e.width,"streamParameter.width"),b(e.height)||T(e.height,"streamParameter.height"),b(e.framerate)||T(e.framerate,"streamParameter.framerate"),b(e.bitrate)||f(e.bitrate,"streamParameter.bitrate"),!0}let $e=function(e){return e[e.HIGH_STREAM=0]="HIGH_STREAM",e[e.LOW_STREAM=1]="LOW_STREAM",e}({}),et=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}({}),tt=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}({}),it=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}({}),rt=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}({}),st=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}({}),ot=function(e){return e.AUDIO="audio",e.VIDEO="video",e.DATA="data",e}({}),nt=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}({}),at=function(e){return e.UPDATE_TRACK_SOURCE="update-track-source",e}({});const ct={sendVolumeLevel:0,sendBitrate:0,sendBytes:0,sendPackets:0,sendPacketsLost:0,sendJitterMs:0,sendRttMs:0,currentPacketLossRate:0},dt={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},ut={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},ht={uplinkNetworkQuality:0,downlinkNetworkQuality:0},lt={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 pt=function(e){return e.ON_TRACK="on_track",e.ON_NODE="on_node",e}({}),mt=function(e){return e.REQUEST_UPDATE_CONSTRAINTS="request_update_constraints",e.REQUEST_CONSTRAINTS="request_constraints",e}({}),gt=function(e){return e.IDLE="IDLE",e.INITING="INITING",e.INITEND="INITEND",e}({}),_t=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 Tt(e){return void 0!==e.smoothnessLevel&&f(e.smoothnessLevel,"options.smoothnessLevel",0,1,!1),void 0!==e.lighteningLevel&&f(e.lighteningLevel,"options.lighteningLevel",0,1,!1),void 0!==e.rednessLevel&&f(e.rednessLevel,"options.rednessLevel",0,1,!1),void 0!==e.lighteningContrastLevel&&v(e.lighteningContrastLevel,"options.lighteningContrastLevel",[0,1,2]),!0}let ft=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}({}),Et=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 vt={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 yt=function(e){return e.OPEN="open",e.MESSAGE="message",e.CLOSE="close",e.CLOSING="closing",e.ERROR="error",e}({});function St(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 bt(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 kt(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 It(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?kt(Object(i),!0).forEach((function(t){bt(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):kt(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}class At extends k{set _mediaStreamTrack(e){e!==this.mediaStreamTrack&&(this.safeEmit(it.TRACK_UPDATED,e),this.mediaStreamTrack=e)}get _mediaStreamTrack(){return this.mediaStreamTrack}constructor(e,t){super(),bt(this,"trackMediaType",void 0),bt(this,"_ID",void 0),bt(this,"_rtpTransceiver",void 0),bt(this,"_lowRtpTransceiver",void 0),bt(this,"_hints",[]),bt(this,"_isClosed",!1),bt(this,"_originMediaStreamTrack",void 0),bt(this,"mediaStreamTrack",void 0),bt(this,"_external",{}),this._ID=t||I(8,"track-"),this._originMediaStreamTrack=e,this.mediaStreamTrack=e,Ze(this)}toString(){return this._ID}getTrackId(){return this._ID}getMediaStreamTrack(e){return e||A((()=>{var e;ge.reportApiInvoke(null,{name:R.GET_MEDIA_STREAM_TRACK,options:[],tag:w.TRACER}).onSuccess((null===(e=this._mediaStreamTrack)||void 0===e?void 0:e.label)||"")}),this.mediaStreamTrack.id||this.getTrackId()),this._mediaStreamTrack}getRTCRtpTransceiver(e){return e===$e.LOW_STREAM?this._lowRtpTransceiver:this._rtpTransceiver}getMediaStreamTrackSettings(){return this.getMediaStreamTrack(!0).getSettings()}close(){this._isClosed=!0,this._lowRtpTransceiver=void 0,this._rtpTransceiver=void 0,Ke(this),this.emit(rt.CLOSED),this.removeAllListeners(it.SEI_RECEIVED)}_updateRtpTransceiver(e,t){if(t===$e.LOW_STREAM){if(this._lowRtpTransceiver===e)return;this._lowRtpTransceiver=e}else{if(this._rtpTransceiver===e)return;this._rtpTransceiver=e}this.emit(it.TRANSCEIVER_UPDATED,e,t)}}class Rt extends At{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),bt(this,"_enabled",!0),bt(this,"_muted",!1),bt(this,"_isExternalTrack",!1),bt(this,"_isClosed",!1),bt(this,"_enabledMutex",void 0),bt(this,"processor",void 0),bt(this,"_processorContext",void 0),bt(this,"_handleTrackEnded",(()=>{this.onTrackEnded()})),this._enabledMutex=new C("".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(Qe.NEED_CLOSE),super.close())}async _updateOriginMediaStreamTrack(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];this._isExternalTrack=i,e!==this._originMediaStreamTrack&&(this._originMediaStreamTrack&&(this._originMediaStreamTrack.removeEventListener("ended",this._handleTrackEnded),t&&this._originMediaStreamTrack.stop()),e.addEventListener("ended",this._handleTrackEnded),this._originMediaStreamTrack=e,this._muted&&(this._originMediaStreamTrack.enabled=!1),this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await D(this,Qe.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(rt.TRACK_ENDED)}stateCheck(e,t){if(me.debug("check track state, [muted: ".concat(this._muted,", enabled: ").concat(this._enabled,"] to [").concat(e,": ").concat(t,"]")),E(t,e),this._enabled&&this._muted&&"enabled"===e&&!1===t)throw new y(S.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 y(S.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 wt=window.AudioContext||window.webkitAudioContext;let Ct=null;const Dt=new class extends k{constructor(){super(...arguments),bt(this,"prevState",void 0),bt(this,"curState",void 0),bt(this,"currentTime",void 0),bt(this,"currentTimeStuckAt",void 0),bt(this,"interruptDetectorTrack",void 0),bt(this,"onLocalAudioTrackMute",(()=>{me.info("ios15-interruption-start"),this.emit(Ce.IOS_15_16_INTERRUPTION_START)})),bt(this,"onLocalAudioTrackUnmute",(async()=>{me.info("ios15-interruption-end"),"running"!==this.curState||this.duringInterruption?me.info("ios15-interruption-end-canceled"):(Ct&&await Ct.suspend(),this.emit(Ce.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 Nt(){if(!wt)return void me.error("your browser is not support web audio");me.info("create audio context");const t=It({},u("WEBAUDIO_INIT_OPTIONS"));me.debug("audio context init option:",JSON.stringify(t)),Ct=new wt(t),Dt.curState=Ct.state,Ct.onstatechange=()=>{Dt.prevState=Dt.curState,Dt.curState=Ct?Ct.state:void 0;const{prevState:t,curState:i}=Dt,r="running"===i,s="interrupted"===i,o="running"===t,n="suspended"===t,a="interrupted"===t,c=e().osVersion;(M()||O())&&o&&s&&(me.info("ios".concat(c,"-interruption-start")),Dt.emit(Ce.IOS_INTERRUPTION_START)),(M()||O())&&(n||a)&&r&&(me.info("ios".concat(c,"-interruption-end")),Dt.emit(Ce.IOS_INTERRUPTION_END)),t!==i&&Dt.emit(Ce.STATE_CHANGE,i,t)},setInterval((()=>{var e;const t=null===(e=Ct)||void 0===e?void 0:e.currentTime;if(Dt.currentTime!==t)Dt.currentTimeStuckAt&&(me.debug("AudioContext current time resume at ".concat(t)),Dt.currentTimeStuckAt=void 0),Dt.currentTime=t;else{if(t!==Dt.currentTimeStuckAt){ge.reportApiInvoke(null,{name:"WEB_AUDIO_CURRENT_TIME_STUCK",options:{currentTime:t},tag:w.TRACER}).onSuccess(),me.warning("AudioContext current time stuck at ".concat(t))}Dt.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):M()||O()?"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(M()){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)}Dt.on(Ce.STATE_CHANGE,c),n(!1)}(Ct)}function Mt(){if(!Ct){if(Nt(),!Ct)throw new y(S.NOT_SUPPORTED,"can not create audio context");return Ct}return Ct}function Ot(){return!!Ct}function Lt(e){if(function(){if(null!==Vt)return Vt;const e=Mt(),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(),Vt=s,s}())return;const t=e.connect,i=e.disconnect;e.connect=(i,r,s)=>(e._inputNodes||(e._inputNodes=[]),e._inputNodes.includes(i)||(i instanceof AudioNode?(e._inputNodes.push(i),t.call(e,i,r,s)):t.call(e,i,r)),e),e.disconnect=(r,s,o)=>{i.call(e),r?N(e._inputNodes,r):e._inputNodes=[];for(const i of e._inputNodes)t.call(e,i)}}function Pt(e){const t=Mt();return new Promise(((i,r)=>{t.decodeAudioData(e,(e=>{i(e)}),(e=>{r(new y(S.DECODE_AUDIO_FILE_FAILED,e.toString()))}))}))}let Vt=null;function xt(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=Mt();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 Ut=null;function Ft(){if(Ut)return Ut;const e=Mt();if(!e.createMediaStreamDestination)throw new y(S.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),Ut=r.stream.getAudioTracks()[0],Ut}function Bt(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 Gt(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 Wt{constructor(){bt(this,"context",void 0),bt(this,"analyserNode",void 0),bt(this,"sourceNode",void 0),this.context=Mt(),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||M()||O()||"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 Zt extends k{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(),bt(this,"outputNode",void 0),bt(this,"outputTrack",void 0),bt(this,"isPlayed",!1),bt(this,"sourceNode",void 0),bt(this,"context",void 0),bt(this,"audioBufferNode",void 0),bt(this,"destNode",void 0),bt(this,"audioOutputLevel",0),bt(this,"volumeLevelAnalyser",void 0),bt(this,"_processedNode",void 0),bt(this,"playNode",void 0),bt(this,"isDestroyed",!1),bt(this,"onNoAudioInput",void 0),bt(this,"isNoAudioInput",!1),bt(this,"_noAudioInputCount",0),this.context=Mt(),this.playNode=this.context.destination,this.outputNode=this.context.createGain(),Lt(this.outputNode),this.volumeLevelAnalyser=new Wt}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(nt.ON_AUDIO_BUFFER,Bt(e))})}stopGetAudioBuffer(){this.audioBufferNode&&(this.audioBufferNode.onaudioprocess=null,this.outputNode.disconnect(this.audioBufferNode),this.audioBufferNode=void 0)}createOutputTrack(){if(!ye().webAudioMediaStreamDest)throw new y(S.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((()=>{Dt.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;M()||O()?"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 L(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 Kt extends Zt{get isFreeze(){return!1}constructor(t,i,r){var s;if(super(),bt(this,"sourceNode",void 0),bt(this,"track",void 0),bt(this,"clonedTrack",void 0),bt(this,"audioElement",void 0),bt(this,"isCurrentTrackCloned",!1),bt(this,"isRemoteTrack",!1),bt(this,"originVolumeLevelAnalyser",void 0),bt(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),Lt(this.sourceNode),this.volumeLevelAnalyser.rebuildAnalyser();const i=this.outputNode.gain.value;this.outputNode=this.context.createGain(),this.outputNode.gain.setValueAtTime(i,this.context.currentTime),Lt(this.outputNode),this.emit(nt.UPDATE_SOURCE),this.connect(),this.audioElement.srcObject=t,this.isPlayed&&this.play(this.playNode),this.checkHasAudioInput()})),"audio"!==t.kind)throw new y(S.UNEXPECTED_ERROR);this.track=t;const o=new MediaStream([this.track]);if(this.isRemoteTrack=!!i,this.sourceNode=this.context.createMediaStreamSource(o),Lt(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]));Lt(t),this.originVolumeLevelAnalyser=new Wt,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&&(Dt.on(Ce.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),Lt(this.sourceNode),this.processedNode||this.sourceNode.connect(this.outputNode),this.emit(nt.UPDATE_SOURCE),this.audioElement.srcObject=t}destroy(){var e;this.audioElement.srcObject=null,this.audioElement.remove(),Dt.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]));Lt(i),this.originVolumeLevelAnalyser&&this.originVolumeLevelAnalyser.updateSource(i)}getOriginVolumeLevel(){return this.originVolumeLevelAnalyser?this.originVolumeLevelAnalyser.getVolumeLevel():this.getAccurateVolumeLevel()}}async function Ht(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 Yt(e,t){const i=await jt(e.mediaSource),{sourceId:r,audio:s}=await P(i,t);return await Ht(r,e,s)}async function jt(e){let t=["window","screen"];"application"!==e&&"window"!==e||(t=["window"]),"screen"===e&&(t=["screen"]);const i=V();if(!i)throw console.error("failed to fetch electron, please mount it to window"),new y(S.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 y(S.ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR,e.toString())}}const Xt=new C("safari");let zt=!1,Qt=!1;async function Jt(e,t){let i=0,r=null;for(;i<2;)try{r=await qt(e,t,i>0);break}catch(e){if(e instanceof y)throw me.error("[".concat(t,"] ").concat(e.toString())),e;const r=$t(e.name||e.code||e,e.message);if(r.code===S.MEDIA_OPTION_INVALID){me.debug("[".concat(t,"] detect media option invalid, retry")),i+=1,await L(500);continue}throw me.error("[".concat(t,"] ").concat(r.toString())),r}if(!r)throw new y(S.UNEXPECTED_ERROR,"can not find stream after getUserMedia");return r}async function qt(t,i,r){if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)throw new y(S.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(x())if(t.screen.sourceId){ei(o,await Ht(t.screen.sourceId,t.screen,!!t.screenAudio))}else{ei(o,await Yt(t.screen,!!t.screenAudio))}else if(p()&&t.screen.extensionId&&t.screen.mandatory){if(!s.getStreamFromExtension)throw new y(S.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 y(S.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 y(S.CHROME_PLUGIN_NOT_INSTALL))}})));t.screen.mandatory.chromeMediaSourceId=e;ei(o,await navigator.mediaDevices.getUserMedia({video:{mandatory:t.screen.mandatory}}))}else if(s.getDisplayMedia){var n;t.screen.mediaSource&&ze(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,me.debug("[".concat(i,"] getDisplayMedia:"),JSON.stringify({video:e,audio:t.screenAudio,controls:d}));ei(o,await navigator.mediaDevices.getDisplayMedia(It({video:e,audio:t.screenAudio},d)))}else{if(!h())throw me.error("[".concat(i,"] This browser does not support screenSharing")),new y(S.NOT_SUPPORTED,"This browser does not support screen sharing");{t.screen.mediaSource&&ze(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)));ei(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=U(m,g)}catch(e){}me.debug("[".concat(i,"] GetUserMedia"),JSON.stringify(m)),e();let _,T=null;(c()||M()||d())&&(T=await Xt.lock());try{_=await navigator.mediaDevices.getUserMedia(m)}catch(e){throw T&&T(),e}return m.audio&&(zt=!0),m.video&&(Qt=!0),ei(o,_),T&&T(),o}function $t(e,t){switch(e){case"Starting video failed":case"OverconstrainedError":case"TrackStartError":return new y(S.MEDIA_OPTION_INVALID,"".concat(e,": ").concat(t));case"NotFoundError":case"DevicesNotFoundError":return new y(S.DEVICE_NOT_FOUND,"".concat(e,": ").concat(t));case"NotSupportedError":return new y(S.NOT_SUPPORTED,"".concat(e,": ").concat(t));case"NotReadableError":return new y(S.NOT_READABLE,"".concat(e,": ").concat(t));case"InvalidStateError":case"NotAllowedError":case"PERMISSION_DENIED":case"PermissionDeniedError":return new y(S.PERMISSION_DENIED,"".concat(e,": ").concat(t));case"ConstraintNotSatisfiedError":return new y(S.CONSTRAINT_NOT_SATISFIED,"".concat(e,": ").concat(t));default:return me.error("getUserMedia unexpected error",e),new y(S.UNEXPECTED_ERROR,"".concat(e,": ").concat(t))}}function ei(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 ti extends k{get state(){return this._state}set state(e){e!==this._state&&(this.emit(_t.STATE_CHANGE,e),this._state=e)}constructor(){super(),bt(this,"_state",gt.IDLE),bt(this,"isAccessMicrophonePermission",!1),bt(this,"isAccessCameraPermission",!1),bt(this,"lastAccessMicrophonePermission",!1),bt(this,"lastAccessCameraPermission",!1),bt(this,"checkdeviceMatched",!1),bt(this,"deviceInfoMap",new Map),this.init().then((()=>{navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",this.updateDevicesInfo.bind(this)),window.setInterval((()=>{(u("ENUMERATE_DEVICES_INTERVAL")||(F()||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){return new y(S.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(Xt.isLocked){me.debug("[device manager] wait GUM lock");(await Xt.lock())(),me.debug("[device manager] GUM unlock")}if(zt&&(o=!1,this.isAccessMicrophonePermission=!0),Qt&&(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=$t(e.name||e.code||e,e.message);if(t.code===S.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=$t(e.name||e.code||e,e.message);if(t.code===S.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=$t(e.name||e.code||e,e.message);if(t.code===S.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 y(S.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 y(S.DEVICE_NOT_FOUND,"deviceId: ".concat(e));return t}async init(){this.state=gt.INITING;try{await this.updateDevicesInfo(),this.state=gt.INITEND}catch(e){if(me.warning("Device Detection functionality cannot start properly.",e.toString()),this.state=gt.IDLE,!G()){new y(S.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?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!==gt.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(_t.RECORDING_DEVICE_CHANGED,e);break;case"videoinput":this.lastAccessCameraPermission&&this.isAccessCameraPermission&&this.emit(_t.CAMERA_DEVICE_CHANGED,e);break;case"audiooutput":this.lastAccessMicrophonePermission&&this.isAccessMicrophonePermission&&this.emit(_t.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 ii=new ti;let ri=!1;const si=new class extends k{constructor(){super(...arguments),bt(this,"onAutoplayFailed",void 0),bt(this,"onAudioAutoplayFailed",void 0)}};function oi(){if(e(),!ri){const e=t=>{t.preventDefault(),ri=!1,W()?document.body.removeEventListener("click",e,!0):(document.body.removeEventListener("touchstart",e,!0),document.body.removeEventListener("mousedown",e,!0))};ri=!0,W()?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"),si.onAutoplayFailed?si.onAutoplayFailed():si.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 ."),si.emit("autoplay-failed")}}function ni(e,t,i,r){if(!e)return;const s=ge.getBaseInfoBySessionId(e);if(!s)return;const o=s.info,n=Date.now(),a=It(It({},o),{},{vid:void 0===o.vid?0:Number(o.vid),lts:n,elapse:n-s.startTime,cbRegistered:si.onAutoplayFailed||si.onAudioAutoplayFailed?1:-1,errorMsg:i,mediaType:t,trackId:r,extend:void 0});ge.send({type:_e.AUTOPLAY_FAILED,data:a},!0)}const ai=["play","playing","loadeddata","canplay","pause","stalled","suspend","waiting","abort","emptied","ended","error"],ci=new class{constructor(){bt(this,"onAutoplayFailed",void 0),bt(this,"elementMap",new Map),bt(this,"elementStateMap",new Map),bt(this,"elementsNeedToResume",[]),bt(this,"sinkIdMap",new Map),bt(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(me.debug("resume after interrupted, ele: ".concat(s," audio: ").concat(n," ").concat(e)),"live"===n){if(e)return r.pause(),void r.play();if("running"===Dt.curState)return K()?(r.pause(),void r.play()):void(s&&"paused"===s&&r.play())}}))})),bt(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(),Dt.on(Ce.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),Dt.on(Ce.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16),Dt.on(Ce.STATE_CHANGE,(()=>{M()&&"suspended"===Dt.prevState&&"running"===Dt.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 y(S.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.srcO