UNPKG

@agora-js/media

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