@agora-js/media 4.20.2-200 → 4.20.2-300
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AgoraRTC_N-media.esm.mjs +2 -2
- package/AgoraRTC_N-media.js +2 -3
- package/media.d.ts +424 -3756
- package/package.json +4 -5
- package/rtc-sdk-media_en.d.ts +178 -2173
package/AgoraRTC_N-media.esm.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* AgoraWebSDK_N-v4.20.2-
|
|
2
|
+
* AgoraWebSDK_N-v4.20.2-300-0-g79f50841 Copyright AgoraInc.
|
|
3
3
|
*/
|
|
4
4
|
|
|
5
|
-
import"webrtc-adapter";import{getBrowserInfo as e,BrowserName as t,isChromeKernel as i,nextTick as r,isAboveChrome as n,isAboveFirefox as s,isAboveSafari as o,BrowserOS as a,isSafari as c,isWkWebview as d,getParameter as u,isFirefox as h,checkValidConstrainLong as l,checkValidNumber as p,checkValidBoolean as m,checkValidEnum as g,AgoraRTCError as _,AgoraRTCErrorCode as T,isEmpty as f,EventEmitter as E,getRandomString as v,AgoraAPIName as y,AgoraAPITag as S,PromiseMutex as k,emitAsPromiseNoResponse as b,removeItemFromList as I,isIOS as A,isIpadOS as w,wait as N,showElectronSelectSourceWindow as R,getElectronInstance as C,isElectron as D,isChrome as O,recursiveMerge as M,detectSecureContext as P,isAndroid as L,isHarmonyOS as V,isAndroidChromium as x,isIOS15 as U,domLoadedPromise as F,emitAsPromise as B,atom as W,runOnce as K,emitAsInvokerNoResponse as G,isIOS16 as H,isLegacyChrome as z,isEdge as j,isAboveEdge as Z,isAboveOpera as J,retryable as Y,getOSWithVersion as X,isAboveIOS15_1 as Q,isInPage as q,noop as $,hexToBytes as ee,md5 as te,isBetweenBrowser as ie,isWindows as re,elementVisibleChecker as ne,safeCloneJson as se,isAboveIOS15_2 as oe,isWechatBrowser as ae,jsonClone as ce}from"@agora-js/shared";export{isElectron}from"@agora-js/shared";import{logger as de,report as ue,AgoraRTCEventUploadType as he,apiInvoke as le}from"@agora-js/report";import pe from"axios";import{inflate as me,deflate as ge}from"pako";const _e={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};function Te(){const l=e();_e.getDisplayMedia=function(e){if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)return!0;return!1}(),_e.getStreamFromExtension=l.name===t.CHROME&&Number(l.version)>34,_e.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}(),_e.supportMinBitrate=l.name===t.CHROME||l.name===t.EDGE,_e.supportSetRtpSenderParameters=function(){const r=e();if(!window.RTCRtpSender||!window.RTCRtpSender.prototype.setParameters||!window.RTCRtpSender.prototype.getParameters)return!1;return!!i()||(!(!c()&&!d())||r.name===t.FIREFOX&&Number(r.version)>=64)}(),l.name===t.SAFARI&&(Number(l.version)>=14?_e.supportDualStream=!0:_e.supportDualStream=!1),_e.webAudioMediaStreamDest=function(){const i=e();if(i.name===t.SAFARI&&Number(i.version)<12)return!1;return!0}(),_e.supportReplaceTrack=function(){if(!window.RTCRtpSender)return!1;if("function"==typeof RTCRtpSender.prototype.replaceTrack)return!0;return!1}(),_e.supportWebGL="undefined"!=typeof WebGLRenderingContext,_e.supportRequestFrame=!!window.CanvasCaptureMediaStreamTrack,i()||(_e.webAudioWithAEC=!0),_e.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}(),_e.supportDataChannel=function(){if(n(76)||s(68)||o(14))return!0;return!1}(),_e.supportPCSetConfiguration=function(){const e=window.RTCPeerConnection;return!h()&&!!e&&e.prototype.setConfiguration instanceof Function}(),_e.supportWebRTCEncodedTransform=function(){const t=e();return"Chrome"===t.name&&Number(t.version)>=86||"Safari"===t.name&&Number(t.version)>=15}(),_e.supportWebRTCInsertableStream=function(){const i=e();return(i.name===t.CHROME||i.name===t.EDGE)&&Number(i.version)>=94&&"MediaStreamTrackGenerator"in window&&"MediaStreamTrackProcessor"in window}(),r((()=>{_e.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"))}(),de.info("browser compatibility",JSON.stringify(_e),JSON.stringify(l))}))}function fe(){return _e}var Ee;function ve(e,t,i){return{sampleRate:e,stereo:t,bitrate:i}}function ye(e,t,i,r,n){return{width:e,height:t,frameRate:i,bitrateMin:r,bitrateMax:n}}function Se(e,t,i,r,n){return{width:{max:e},height:{max:t},frameRate:i,bitrateMin:r,bitrateMax:n}}function ke(e,t){return{numSpatialLayers:e,numTemporalLayers:t}}!function(e){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"}(Ee||(Ee={}));const be={"90p":ye(160,90),"90p_1":ye(160,90),"120p":ye(160,120,15,30,65),"120p_1":ye(160,120,15,30,65),"120p_3":ye(120,120,15,30,50),"120p_4":ye(212,120),"180p":ye(320,180,15,30,140),"180p_1":ye(320,180,15,30,140),"180p_3":ye(180,180,15,30,100),"180p_4":ye(240,180,15,30,120),"240p":ye(320,240,15,40,200),"240p_1":ye(320,240,15,40,200),"240p_3":ye(240,240,15,40,140),"240p_4":ye(424,240,15,40,220),"360p":ye(640,360,15,80,400),"360p_1":ye(640,360,15,80,400),"360p_3":ye(360,360,15,80,260),"360p_4":ye(640,360,30,80,600),"360p_6":ye(360,360,30,80,400),"360p_7":ye(480,360,15,80,320),"360p_8":ye(480,360,30,80,490),"360p_9":ye(640,360,15,80,800),"360p_10":ye(640,360,24,80,800),"360p_11":ye(640,360,24,80,1e3),"480p":ye(640,480,15,100,500),"480p_1":ye(640,480,15,100,500),"480p_2":ye(640,480,30,100,1e3),"480p_3":ye(480,480,15,100,400),"480p_4":ye(640,480,30,100,750),"480p_6":ye(480,480,30,100,600),"480p_8":ye(848,480,15,100,610),"480p_9":ye(848,480,30,100,930),"480p_10":ye(640,480,10,100,400),"720p":ye(1280,720,15,120,1130),"720p_auto":ye(1280,720,30,900,3e3),"720p_1":ye(1280,720,15,120,1130),"720p_2":ye(1280,720,30,120,2e3),"720p_3":ye(1280,720,30,120,1710),"720p_5":ye(960,720,15,120,910),"720p_6":ye(960,720,30,120,1380),"1080p":ye(1920,1080,15,120,2080),"1080p_1":ye(1920,1080,15,120,2080),"1080p_2":ye(1920,1080,30,120,3e3),"1080p_3":ye(1920,1080,30,120,3150),"1080p_5":ye(1920,1080,60,120,4780),"1440p":ye(2560,1440,30,120,4850),"1440p_1":ye(2560,1440,30,120,4850),"1440p_2":ye(2560,1440,60,120,7350),"4k":ye(3840,2160,30,120,8910),"4k_1":ye(3840,2160,30,120,8910),"4k_3":ye(3840,2160,60,120,13500)},Ie=[{scaleResolutionDownBy:2,width:1280,height:720,frameRate:30,bitrateMin:300,bitrateMax:900},{scaleResolutionDownBy:1.333333,width:1280,height:720,frameRate:30,bitrateMin:600,bitrateMax:2e3},{scaleResolutionDownBy:1,width:1280,height:720,frameRate:30,bitrateMin:900,bitrateMax:3e3}],Ae={"480p":Se(640,480,5),"480p_1":Se(640,480,5),"480p_2":Se(640,480,30),"480p_3":Se(640,480,15),"720p":Se(1280,720,5),"720p_auto":ye(1280,720,30,900,3e3),"720p_1":Se(1280,720,5),"720p_2":Se(1280,720,30),"720p_3":Se(1280,720,15),"1080p":Se(1920,1080,5),"1080p_1":Se(1920,1080,5),"1080p_2":Se(1920,1080,30),"1080p_3":Se(1920,1080,15)},we={"1SL1TL":ke(1,1),"3SL3TL":ke(3,3),"2SL3TL":ke(2,3)};function Ne(e){return e||(e="480p_1"),"string"==typeof e?Object.assign({},be[e]):e}function Re(e){return"string"==typeof e?Object.assign({},Ae[e]):e}function Ce(e){return"string"==typeof e?Object.assign({},we[e]):e}const De={speech_low_quality:ve(16e3,!1),speech_standard:ve(32e3,!1,18),music_standard:ve(48e3,!1),standard_stereo:ve(48e3,!0,56),high_quality:ve(48e3,!1,128),high_quality_stereo:ve(48e3,!0,192)};function Oe(e){return"string"==typeof e?Object.assign({},De[e]):e}const Me=[];function Pe(e){Me.includes(e)||Me.push(e)}function Le(e){const t=Me.indexOf(e);-1!==t&&Me.splice(t,1)}function Ve(e){return l(e.width,"config.width"),l(e.height,"config.height"),void 0!==e.frameRate&&l(e.frameRate,"config.frameRate"),void 0!==e.bitrateMax&&p(e.bitrateMax,"config.bitrateMax"),void 0!==e.bitrateMin&&p(e.bitrateMin,"config.bitrateMin"),!0}function xe(e){return void 0!==e.sampleRate&&p(e.sampleRate,"config.sampleRate",0,96e3,!0),void 0!==e.sampleSize&&p(e.sampleRate,"config.sampleSize",0,128,!0),void 0!==e.stereo&&m(e.stereo,"config.stereo"),void 0!==e.bitrate&&p(e.bitrate,"config.bitrate",0,1e4,!1),!0}function Ue(e){return"string"==typeof e?g(e,"profile",Object.keys(be)):Ve(e),!0}function Fe(e){return"string"==typeof e?g(e,"profile",Object.keys(De)):xe(e),!0}function Be(e){return g(e,"mediaSource",["screen","window","application"]),!0}var We,Ke,Ge,He,ze,je,Ze,Je,Ye,Xe;function Qe(e){if(!e)throw new _(T.INVALID_PARAMS);return f(e.width)||l(e.width,"streamParameter.width"),f(e.height)||l(e.height,"streamParameter.height"),f(e.framerate)||l(e.framerate,"streamParameter.framerate"),f(e.bitrate)||p(e.bitrate,"streamParameter.bitrate"),!0}!function(e){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_MUTE_TRACK="@need_mute_track",e.NEED_UNMUTE_TRACK="@need_unmute_track"}(We||(We={})),function(e){e.SCREEN_TRACK="screen_track",e.CUSTOM_TRACK="custome_track",e.LOW_STREAM="low_stream"}(Ke||(Ke={})),function(e){e[e.HIGH_STREAM=0]="HIGH_STREAM",e[e.LOW_STREAM=1]="LOW_STREAM"}(Ge||(Ge={})),function(e){e[e.HIGH_STREAM=0]="HIGH_STREAM",e[e.LOW_STREAM=1]="LOW_STREAM"}(He||(He={})),function(e){e[e.DISABLE=0]="DISABLE",e[e.LOW_STREAM=1]="LOW_STREAM",e[e.AUDIO_ONLY=2]="AUDIO_ONLY"}(ze||(ze={})),function(e){e.TRANSCEIVER_UPDATED="transceiver-updated",e.SEI_TO_SEND="sei-to-send",e.SEI_RECEIVED="sei-received"}(je||(je={})),function(e){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"}(Ze||(Ze={})),function(e){e.FIRST_FRAME_DECODED="first-frame-decoded",e.VIDEO_ELEMENT_VISIBLE_STATUS="video-element-visible-status",e.VIDEO_STATE_CHANGED="video-state-changed"}(Je||(Je={})),function(e){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"}(Ye||(Ye={})),function(e){e.UPDATE_TRACK_SOURCE="update-track-source"}(Xe||(Xe={}));const qe={sendVolumeLevel:0,sendBitrate:0,sendBytes:0,sendPackets:0,sendPacketsLost:0,sendJitterMs:0,sendRttMs:0,currentPacketLossRate:0},$e={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},et={transportDelay:0,end2EndDelay:0,receiveBitrate:0,receiveLevel:0,receiveBytes:0,receiveDelay:0,receivePackets:0,receivePacketsLost:0,totalDuration:0,totalFreezeTime:0,freezeRate:0,packetLossRate:0,currentPacketLossRate:0,publishDuration:-1},tt={uplinkNetworkQuality:0,downlinkNetworkQuality:0},it={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};var rt,nt,st,ot,at,ct;function dt(e){return void 0!==e.smoothnessLevel&&p(e.smoothnessLevel,"options.smoothnessLevel",0,1,!1),void 0!==e.lighteningLevel&&p(e.lighteningLevel,"options.lighteningLevel",0,1,!1),void 0!==e.rednessLevel&&p(e.rednessLevel,"options.rednessLevel",0,1,!1),void 0!==e.lighteningContrastLevel&&g(e.lighteningContrastLevel,"options.lighteningContrastLevel",[0,1,2]),!0}!function(e){e.ON_TRACK="on_track",e.ON_NODE="on_node"}(rt||(rt={})),function(e){e.REQUEST_UPDATE_CONSTRAINTS="request_update_constraints",e.REQUEST_CONSTRAINTS="request_constraints"}(nt||(nt={})),function(e){e.IDLE="IDLE",e.INITING="INITING",e.INITEND="INITEND"}(st||(st={})),function(e){e.STATE_CHANGE="state_change",e.RECORDING_DEVICE_CHANGED="recordingDeviceChanged",e.PLAYOUT_DEVICE_CHANGED="playoutDeviceChanged",e.CAMERA_DEVICE_CHANGED="cameraDeviceChanged"}(ot||(ot={})),function(e){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"}(at||(at={})),function(e){e[e.VideoStateStopped=0]="VideoStateStopped",e[e.VideoStateStarting=1]="VideoStateStarting",e[e.VideoStateDecoding=2]="VideoStateDecoding",e[e.VideoStateFrozen=3]="VideoStateFrozen"}(ct||(ct={}));const ut={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};var ht;function lt(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 pt(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?lt(Object(i),!0).forEach((function(t){mt(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):lt(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function mt(e,t,i){return(t=function(e){var t=function(e,t){if("object"!=typeof e||null===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:String(t)}(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function gt(e,t,i,r){var n,s=arguments.length,o=s<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,i):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,r);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(o=(s<3?n(o):s>3?n(t,i,o):n(t,i))||o);return s>3&&o&&Object.defineProperty(t,i,o),o}function _t(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}!function(e){e.OPEN="open",e.MESSAGE="message",e.CLOSE="close",e.CLOSING="closing",e.ERROR="error"}(ht||(ht={}));class Tt extends E{constructor(e,t){super(),this._ID=void 0,this._rtpTransceiver=void 0,this._lowRtpTransceiver=void 0,this._hints=[],this._isClosed=!1,this._originMediaStreamTrack=void 0,this._mediaStreamTrack=void 0,this._external={},this._ID=t||v(8,"track-"),this._originMediaStreamTrack=e,this._mediaStreamTrack=e,Pe(this)}toString(){return this._ID}getTrackId(){return this._ID}getMediaStreamTrack(e){if(!e){const e=ue.reportApiInvoke(null,{name:y.GET_MEDIA_STREAM_TRACK,options:[],tag:S.TRACER});this._mediaStreamTrack&&"string"==typeof this._mediaStreamTrack.label?e.onSuccess(this._mediaStreamTrack.label):e.onSuccess("")}return this._mediaStreamTrack}getRTCRtpTransceiver(e){return e===Ge.LOW_STREAM?this._lowRtpTransceiver:this._rtpTransceiver}getMediaStreamTrackSettings(){return this.getMediaStreamTrack(!0).getSettings()}close(){this._isClosed=!0,this._lowRtpTransceiver=void 0,this._rtpTransceiver=void 0,Le(this),this.emit(Ze.CLOSED),this.removeAllListeners(je.SEI_RECEIVED)}_updateRtpTransceiver(e,t){if(t===Ge.LOW_STREAM){if(this._lowRtpTransceiver===e)return;this._lowRtpTransceiver=e}else{if(this._rtpTransceiver===e)return;this._rtpTransceiver=e}this.emit(je.TRANSCEIVER_UPDATED,e,t)}}class ft extends Tt{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),this._enabled=!0,this._muted=!1,this._isExternalTrack=!1,this._isClosed=!1,this._enabledMutex=void 0,this.processor=void 0,this._handleTrackEnded=()=>{this.onTrackEnded()},this._enabledMutex=new k("".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,de.debug("[".concat(this.getTrackId(),"] close")),this.emit(We.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 b(this,We.NEED_REPLACE_TRACK,this),this.processor&&this._processorContext&&this.processor.updateInput({track:this._originMediaStreamTrack,context:this._processorContext}))}_getDefaultPlayerConfig(){return{}}onTrackEnded(){de.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(Ze.TRACK_ENDED)}stateCheck(e,t){if(de.debug("check track state, [muted: ".concat(this._muted,", enabled: ").concat(this._enabled,"] to [").concat(e,": ").concat(t,"]")),m(t,e),this._enabled&&this._muted&&"enabled"===e&&!1===t)throw new _(T.TRACK_STATE_UNREACHABLE,"cannot set enabled while the track is muted").print("error",de);if(!this._enabled&&!this._muted&&"muted"===e&&!0===t)throw new _(T.TRACK_STATE_UNREACHABLE,"cannot set muted while the track is disabled").print("error",de)}getProcessorStats(){return this._processorContext&&this._processorContext.gatherStats()||[]}getProcessorUsage(){return this._processorContext?this._processorContext.gatherUsage():Promise.resolve([])}}const Et=window.AudioContext||window.webkitAudioContext;let vt=null;const yt=new class extends E{constructor(){super(...arguments),this.prevState=void 0,this.curState=void 0,this.currentTime=void 0,this.currentTimeStuckAt=void 0,this.interruptDetectorTrack=void 0,this.onLocalAudioTrackMute=()=>{de.info("ios15-interruption-start"),this.emit(Ee.IOS_15_16_INTERRUPTION_START)},this.onLocalAudioTrackUnmute=async()=>{de.info("ios15-interruption-end"),"running"!==this.curState||this.duringInterruption?de.info("ios15-interruption-end-canceled"):(vt&&await vt.suspend(),this.emit(Ee.IOS_15_16_INTERRUPTION_END))}}get duringInterruption(){return"running"===this.prevState&&"interrupted"===this.curState}bindInterruptDetectorTrack(e){de.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){de.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 St(){if(!Et)return void de.error("your browser is not support web audio");de.info("create audio context");const t=pt({},u("WEBAUDIO_INIT_OPTIONS"));de.debug("audio context init option:",JSON.stringify(t)),vt=new Et(t),yt.curState=vt.state,vt.onstatechange=()=>{yt.prevState=yt.curState,yt.curState=vt?vt.state:void 0;const{prevState:t,curState:i}=yt,r="running"===i,n="interrupted"===i,s="running"===t,o="suspended"===t,a="interrupted"===t,c=e().osVersion;(A()||w())&&s&&n&&(de.info("ios".concat(c,"-interruption-start")),yt.emit(Ee.IOS_INTERRUPTION_START)),(A()||w())&&(o||a)&&r&&(de.info("ios".concat(c,"-interruption-end")),yt.emit(Ee.IOS_INTERRUPTION_END)),t!==i&&yt.emit(Ee.STATE_CHANGE,i,t)},setInterval((()=>{var e;const t=null===(e=vt)||void 0===e?void 0:e.currentTime;if(yt.currentTime!==t)yt.currentTimeStuckAt&&(de.debug("AudioContext current time resume at ".concat(t)),yt.currentTimeStuckAt=void 0),yt.currentTime=t;else{if(t!==yt.currentTimeStuckAt){ue.reportApiInvoke(null,{name:"WEB_AUDIO_CURRENT_TIME_STUCK",options:{currentTime:t},tag:S.TRACER}).onSuccess(),de.warning("AudioContext current time stuck at ".concat(t))}yt.currentTimeStuckAt=t}}),5e3),async function(e){const t=["click","contextmenu","auxclick","dblclick","mousedown","mouseup","touchend","keydown","keyup"];let i,r=!1,n=!1,s=!1;function o(t){"running"===e.state?a(!1):A()||w()?"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(){o(!0)}function d(){o(!1)}function u(){o(!0)}function h(e){if(!s)if(i.paused)if(e){let e;l(!1),s=!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(n!==e){n=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),s=!1,h(!1)}function m(){h(!0)}if(A()){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)}yt.on(Ee.STATE_CHANGE,c),o(!1)}(vt)}function kt(){if(!vt){if(St(),!vt)throw new _(T.NOT_SUPPORTED,"can not create audio context");return vt}return vt}function bt(){return!!vt}function It(e){if(function(){if(null!==wt)return wt;const e=kt(),t=e.createBufferSource(),i=e.createGain(),r=e.createGain();t.connect(i),t.connect(r),t.disconnect(i);let n=!1;try{t.disconnect(i)}catch(e){n=!0}return t.disconnect(),wt=n,n}())return;const t=e.connect,i=e.disconnect;e.connect=(i,r,n)=>(e._inputNodes||(e._inputNodes=[]),e._inputNodes.includes(i)||(i instanceof AudioNode?(e._inputNodes.push(i),t.call(e,i,r,n)):t.call(e,i,r)),e),e.disconnect=(r,n,s)=>{i.call(e),r?I(e._inputNodes,r):e._inputNodes=[];for(const i of e._inputNodes)t.call(e,i)}}function At(e){const t=kt();return new Promise(((i,r)=>{t.decodeAudioData(e,(e=>{i(e)}),(e=>{r(new _(T.DECODE_AUDIO_FILE_FAILED,e.toString()))}))}))}let wt=null;function Nt(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=kt();let n=t.createGain();n.gain.value=0,n.connect(t.destination);const s=()=>{if(i)return void(n=null);const o=t.createOscillator();o.onended=s,o.connect(n),o.start(0),o.stop(t.currentTime+r),e(t.currentTime)};s()}return()=>{i=!0}}let Rt=null;function Ct(){if(Rt)return Rt;const e=kt();if(!e.createMediaStreamDestination)throw new _(T.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),Rt=r.stream.getAudioTracks()[0],Rt}function Dt(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 Ot(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 Mt{constructor(){this.context=void 0,this.analyserNode=void 0,this.sourceNode=void 0,this.context=kt(),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||A()||w()||"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){de.warning("rebuild analyser node failed.")}}destroy(){this.updateSource(void 0)}}class Pt extends E{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(),this.outputNode=void 0,this.outputTrack=void 0,this.isPlayed=!1,this.context=void 0,this.audioBufferNode=void 0,this.destNode=void 0,this.audioOutputLevel=0,this.volumeLevelAnalyser=void 0,this._processedNode=void 0,this.playNode=void 0,this.isDestroyed=!1,this.onNoAudioInput=void 0,this.isNoAudioInput=!1,this._noAudioInputCount=0,this.context=kt(),this.playNode=this.context.destination,this.outputNode=this.context.createGain(),It(this.outputNode),this.volumeLevelAnalyser=new Mt}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(Ye.ON_AUDIO_BUFFER,Dt(e))})}stopGetAudioBuffer(){this.audioBufferNode&&(this.audioBufferNode.onaudioprocess=null,this.outputNode.disconnect(this.audioBufferNode),this.audioBufferNode=void 0)}createOutputTrack(){if(!fe().webAudioMediaStreamDest)throw new _(T.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((()=>{yt.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;A()||w()?"suspended"===this.context.state&&this.context.resume():"running"!==this.context.state&&this.context.resume();const t=this.volumeLevelAnalyser.getAnalyserNode();let i;t.getFloatTimeDomainData?(i=new Float32Array(t.fftSize),t.getFloatTimeDomainData(i)):(i=new Uint8Array(t.fftSize),t.getByteTimeDomainData(i));let r=!1;for(let e=0;e<i.length;e++)0!==i[e]&&(r=!0);return r?(this.isNoAudioInput=!1,!0):(await N(200),await this.checkHasAudioInput(e?e+1:1)&&r)}getAudioVolume(){return this.outputNode.gain.value}setVolume(e){this.outputNode.gain.setValueAtTime(e,this.context.currentTime)}destroy(){this.disconnect(),this.stop(),this.isDestroyed=!0,this.onNoAudioInput=void 0}disconnect(){var e,t;null===(e=this.processedNode)||void 0===e||e.disconnect(),null===(t=this.sourceNode)||void 0===t||t.disconnect(),this.outputNode&&this.outputNode.disconnect()}connect(){var e;this.processedNode?null===(e=this.processedNode)||void 0===e||e.connect(this.outputNode):this.sourceNode&&this.sourceNode.connect(this.outputNode);this.volumeLevelAnalyser.updateSource(this.outputNode)}}class Lt extends Pt{get isFreeze(){return!1}constructor(t,i,r){var n;if(super(),this.sourceNode=void 0,this.track=void 0,this.clonedTrack=void 0,this.audioElement=void 0,this.isCurrentTrackCloned=!1,this.isRemoteTrack=!1,this.originVolumeLevelAnalyser=void 0,this.rebuildWebAudio=async()=>{if(de.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 de.debug("rebuild web audio success, current volume status",this.getAccurateVolumeLevel());this.context.resume().then((()=>de.info("resume success"))),de.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),It(this.sourceNode),this.volumeLevelAnalyser.rebuildAnalyser();const i=this.outputNode.gain.value;this.outputNode=this.context.createGain(),this.outputNode.gain.setValueAtTime(i,this.context.currentTime),It(this.outputNode),this.emit(Ye.UPDATE_SOURCE),this.connect(),this.audioElement.srcObject=t,this.isPlayed&&this.play(this.playNode),this.checkHasAudioInput()},"audio"!==t.kind)throw new _(T.UNEXPECTED_ERROR);this.track=t;const s=new MediaStream([this.track]);if(this.isRemoteTrack=!!i,this.sourceNode=this.context.createMediaStreamSource(s),It(this.sourceNode),r){const e=r.clone();e.enabled=!0,this.clonedTrack=e,de.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]));It(t),this.originVolumeLevelAnalyser=new Mt,this.originVolumeLevelAnalyser.updateSource(t)}this.connect(),this.audioElement=document.createElement("audio"),this.audioElement.srcObject=s;const o=e();i&&o.os===a.IOS&&Number(null===(n=o.osVersion)||void 0===n?void 0:n.split(".")[0])<15&&(yt.on(Ee.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),It(this.sourceNode),this.processedNode||this.sourceNode.connect(this.outputNode),this.emit(Ye.UPDATE_SOURCE),this.audioElement.srcObject=t}destroy(){var e;this.audioElement.srcObject=null,this.audioElement.remove(),yt.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),de.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]));It(i),this.originVolumeLevelAnalyser&&this.originVolumeLevelAnalyser.updateSource(i)}getOriginVolumeLevel(){return this.originVolumeLevelAnalyser?this.originVolumeLevelAnalyser.getVolumeLevel():this.getAccurateVolumeLevel()}}async function Vt(e,t,i){const r=(e,t)=>e?"number"!=typeof e?e.max||e.exact||e.ideal||e.min||t:e:t,n={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?(n.video.mandatory.maxFrameRate=t.frameRate.max,n.video.mandatory.minFrameRate=t.frameRate.min):"number"==typeof t.frameRate&&(n.video.mandatory.maxFrameRate=t.frameRate),await navigator.mediaDevices.getUserMedia(n)}async function xt(e,t){const i=await Ut(e.mediaSource),{sourceId:r,audio:n}=await R(i,t);return await Vt(r,e,n)}async function Ut(e){let t=["window","screen"];"application"!==e&&"window"!==e||(t=["window"]),"screen"===e&&(t=["screen"]);const i=C();if(!i)throw console.error("failed to fetch electron, please mount it to window"),new _(T.ELECTRON_IS_NULL);let r=null;try{var n;r=(null===(n=i.desktopCapturer)||void 0===n?void 0:n.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 _(T.ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR,e.toString())}}const Ft=new k("safari");let Bt=!1,Wt=!1;async function Kt(e,t){let i=0,r=null;for(;i<2;)try{r=await Gt(e,t,i>0);break}catch(e){if(e instanceof _)throw de.error("[".concat(t,"] ").concat(e.toString())),e;const r=Ht(e.name||e.code||e,e.message);if(r.code===T.MEDIA_OPTION_INVALID){de.debug("[".concat(t,"] detect media option invalid, retry")),i+=1,await N(500);continue}throw de.error("[".concat(t,"] ").concat(r.toString())),r}if(!r)throw new _(T.UNEXPECTED_ERROR,"can not find stream after getUserMedia");return r}async function Gt(t,i,r){if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)throw new _(T.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 n=fe(),s=new MediaStream;if(t.audioSource&&s.addTrack(t.audioSource),t.videoSource&&s.addTrack(t.videoSource),!t.audio&&!t.video&&!t.screen)return de.debug("Using Video Source/ Audio Source"),s;if(t.screen)if(D())if(t.screen.sourceId){zt(s,await Vt(t.screen.sourceId,t.screen,t.screenAudio))}else{zt(s,await xt(t.screen,t.screenAudio))}else if(O()&&t.screen.extensionId&&t.screen.mandatory){if(!n.getStreamFromExtension)throw new _(T.NOT_SUPPORTED,"This browser does not support screen sharing");de.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 de.error("[".concat(l,"] No response from Chrome Plugin. Plugin not installed properly"),i),void t(new _(T.CHROME_PLUGIN_NO_RESPONSE,"No response from Chrome Plugin. Plugin not installed properly"));e(i.streamId)}))}catch(e){de.error("[".concat(l,"] AgoraRTC screensharing plugin is not accessible(").concat(a,")"),e.toString()),t(new _(T.CHROME_PLUGIN_NOT_INSTALL))}})));t.screen.mandatory.chromeMediaSourceId=e;zt(s,await navigator.mediaDevices.getUserMedia({video:{mandatory:t.screen.mandatory}}))}else if(n.getDisplayMedia){var o;t.screen.mediaSource&&Be(t.screen.mediaSource);const e={width:t.screen.width,height:t.screen.height,frameRate:t.screen.frameRate,displaySurface:null!==(o=t.screen.displaySurface)&&void 0!==o?o:"screen"===t.screen.mediaSource?"monitor":t.screen.mediaSource},{selfBrowserSurface:r,surfaceSwitching:n,systemAudio:a}=t.screen,c={selfBrowserSurface:r,surfaceSwitching:n,systemAudio:a};!r&&delete c.selfBrowserSurface,!n&&delete c.surfaceSwitching,!a&&delete c.systemAudio,de.debug("[".concat(i,"] getDisplayMedia:"),JSON.stringify({video:e,audio:!!t.screenAudio,controls:c}));zt(s,await navigator.mediaDevices.getDisplayMedia(pt({video:e,audio:!!t.screenAudio},c)))}else{if(!h())throw de.error("[".concat(i,"] This browser does not support screenSharing")),new _(T.NOT_SUPPORTED,"This browser does not support screen sharing");{t.screen.mediaSource&&Be(t.screen.mediaSource);const e={video:{mediaSource:t.screen.mediaSource,width:t.screen.width,height:t.screen.height,frameRate:t.screen.frameRate}};de.debug("[".concat(i,"] getUserMedia: ").concat(JSON.stringify(e)));zt(s,await navigator.mediaDevices.getUserMedia(e))}}var a,l;if(!t.video&&!t.audio)return s;let p={video:t.video,audio:t.audio},m=u("MEDIA_DEVICE_CONSTRAINTS");if(m)try{"string"==typeof m&&(m=JSON.parse(m)),p=M(p,m)}catch(e){}de.debug("[".concat(i,"] GetUserMedia"),JSON.stringify(p)),e();let g,f=null;(c()||A()||d())&&(f=await Ft.lock());try{g=await navigator.mediaDevices.getUserMedia(p)}catch(e){throw f&&f(),e}return p.audio&&(Bt=!0),p.video&&(Wt=!0),zt(s,g),f&&f(),s}function Ht(e,t){switch(e){case"Starting video failed":case"OverconstrainedError":case"TrackStartError":return new _(T.MEDIA_OPTION_INVALID,"".concat(e,": ").concat(t));case"NotFoundError":case"DevicesNotFoundError":return new _(T.DEVICE_NOT_FOUND,"".concat(e,": ").concat(t));case"NotSupportedError":return new _(T.NOT_SUPPORTED,"".concat(e,": ").concat(t));case"NotReadableError":return new _(T.NOT_READABLE,"".concat(e,": ").concat(t));case"InvalidStateError":case"NotAllowedError":case"PERMISSION_DENIED":case"PermissionDeniedError":return new _("Permission dismissed"===t?T.PERMISSION_DISMISSED:T.PERMISSION_DENIED,"".concat(e,": ").concat(t));case"ConstraintNotSatisfiedError":return new _(T.CONSTRAINT_NOT_SATISFIED,"".concat(e,": ").concat(t));default:return de.error("getUserMedia unexpected error",e),new _(T.UNEXPECTED_ERROR,"".concat(e,": ").concat(t))}}function zt(e,t){const i=e.getVideoTracks()[0],r=e.getAudioTracks()[0],n=t.getVideoTracks()[0],s=t.getAudioTracks()[0];s&&(r&&e.removeTrack(r),e.addTrack(s)),n&&(i&&e.removeTrack(i),e.addTrack(n))}var jt;!function(e){e.UNKNOWN="UNKNOWN",e.NO="NO",e.GRANTED="GRANTED",e.DENIED="DENIED"}(jt||(jt={}));const Zt={audio:jt.UNKNOWN,video:jt.UNKNOWN},Jt={audio:!1,video:!1};let Yt=!1;function Xt(e){return"audiooutput"===e.kind}function Qt(e){return"audioinput"===e.kind}function qt(e){return"videoinput"===e.kind}function $t(e){return"default"===e.deviceId}async function ei(){if(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices)return new _(T.NOT_SUPPORTED,"enumerateDevices() not supported.").throw();let e;try{e=await navigator.mediaDevices.enumerateDevices()}catch(e){return new _(T.ENUMERATE_DEVICES_FAILED,e.toString()).throw()}return e}async function ti(e,t){if(!e&&!t)return[Zt.audio,Zt.video];const i=e&&t;let r,n=!1;try{(await navigator.mediaDevices.getUserMedia({audio:e,video:t})).getTracks().forEach((e=>e.stop())),r=jt.GRANTED}catch(e){const t=Ht(e.name||e.code||e,e.message);if(de.warning("request media permission error: ",t.message),t.code===T.PERMISSION_DENIED?r=jt.DENIED:t.code===T.PERMISSION_DISMISSED?(n=!0,r=jt.NO):r=(t.code,T.DEVICE_NOT_FOUND,jt.NO),i&&!n)return Promise.all([ti(!0,!1),ti(!1,!0)]).then((e=>{let[t,i]=e;return[t[0],i[1]]}))}return e&&ii(r,"audio"),t&&ii(r,"video"),[Zt.audio,Zt.video]}function ii(e,t){const i=Zt[t];i!==e&&(i===jt.UNKNOWN&&e!==jt.DENIED&&(Zt[t]=e),i===jt.NO&&e!==jt.UNKNOWN&&(Zt[t]=e),i===jt.GRANTED&&e!==jt.UNKNOWN&&(Zt[t]=e),i===jt.DENIED&&e===jt.GRANTED&&(Zt[t]=e),i!==Zt[t]&&de.debug("".concat(t," permission changed: ").concat(i," => ").concat(e)))}const ri=new Map;async function ni(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"user",r=await ei();await async function(e){e=e||await ei();let t=jt.UNKNOWN,i=jt.UNKNOWN;e.forEach((e=>{const r=e.label&&e.deviceId;switch(!0){case Qt(e):case Xt(e):t=r?jt.GRANTED:jt.NO;break;case qt(e):i=r?jt.GRANTED:jt.NO;break;default:de.warning("unknown device: ".concat(e.kind," "))}})),ii(t,"audio"),ii(i,"video")}(r),e&&Zt.audio===jt.GRANTED&&(e=!1),t&&Zt.video===jt.GRANTED&&(t=!1);const n=e||t;if(n){if(Ft.isLocked){de.debug("[device manager] wait GUM lock");(await Ft.lock())(),de.debug("[device manager] GUM unlock")}Bt&&(e=!1),Wt&&(t=!1)}return(e||t)&&await ti(e,t),e&&(Jt.audio=!0),t&&(Jt.video=!0),n&&(r=await ei(),"event"!==i&&await si(r)),r}async function si(e){e=e||await ei();const t=Date.now(),i=[];return e.forEach((e=>{if(!e.deviceId)return;const r="".concat(e.kind,"_").concat(e.deviceId),n=ri.get(r);if("ACTIVE"!==(n?n.state:"INACTIVE")){const n={initAt:t,updateAt:t,device:e,state:"ACTIVE"};ri.set(r,n),i.push(n)}n&&(n.updateAt=t)})),ri.forEach((e=>{"ACTIVE"===e.state&&e.updateAt!==t&&(e.state="INACTIVE",i.push(e))})),i}async function oi(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"user";const t=await ni(Jt.audio,Jt.video,e);t[0]&&t[0].label&&!Yt&&(!function(e){const t=e.find((e=>Qt(e)&&$t(e))),i=e.find((e=>Xt(e)&&$t(e))),r=t&&i&&i.groupId===t.groupId;de.debug("[device-check] default input ".concat(t&&t.label,", output ").concat(i&&i.label,", in the same group: ").concat(r))}(t),Yt=!0);const i=await si(t);if("event"===e){const e=Zt.audio===jt.GRANTED,t=Zt.video===jt.GRANTED;i.forEach((i=>{switch(!0){case Qt(i.device):e&&ai&&ai(i);break;case Xt(i.device):e&&ci&&ci(i);break;case qt(i.device):t&&di&&di(i);break;default:de.warn("unknown device: ".concat(i.device.kind," "))}}))}}let ai,ci,di;function ui(e){ai=e}function hi(e){ci=e}function li(e){di=e}async function pi(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return(await ni(e,!1)).filter(Xt)}async function mi(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return(await ni(!1,e)).filter(qt)}async function gi(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return(await ni(e,!1)).filter(Qt)}async function _i(e){const t=(await ni(!0,!0)).find((t=>t.deviceId===e));if(t)return t;throw new _(T.DEVICE_NOT_FOUND,"deviceId: ".concat(e))}function Ti(e){for(const[t,{device:i}]of ri)if(i.label===e)return i.deviceId}(async function(){if(P())try{await oi("init")}catch(e){de.warning("init device manager error: ",e&&e.toString())}else de.error("Insecure web context, please try using https protocol or localhost.")})().then((function(){if(!navigator.mediaDevices||!navigator.mediaDevices.addEventListener)return;navigator.mediaDevices.addEventListener("devicechange",(()=>oi("event")));const e=window.setInterval((()=>{u("ENUMERATE_DEVICES_INTERVAL")||(L()||V())&&i()?oi("event"):clearInterval(e)}),u("ENUMERATE_DEVICES_INTERVAL_TIME"))}));let fi=!1;const Ei=new class extends E{constructor(){super(...arguments),this.onAutoplayFailed=void 0,this.onAudioAutoplayFailed=void 0}};function vi(){if(e(),!fi){const e=t=>{t.preventDefault(),fi=!1,x()?document.body.removeEventListener("click",e,!0):(document.body.removeEventListener("touchstart",e,!0),document.body.removeEventListener("mousedown",e,!0))};fi=!0,x()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0)),de.info("detect media autoplay failed, document: https://docs.agora.io/cn/Voice/autoplay_policy_web_ng?platform=Web"),Ei.onAutoplayFailed?Ei.onAutoplayFailed():Ei.onAudioAutoplayFailed?de.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 ."):de.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 ."),Ei.emit("autoplay-failed")}}function yi(e,t,i,r){if(!e)return;const n=ue.getBaseInfoBySessionId(e);if(!n)return;const s=n.info,o=Date.now(),a=pt(pt({},s),{},{vid:void 0===s.vid?0:Number(s.vid),lts:o,elapse:o-n.startTime,cbRegistered:Ei.onAutoplayFailed||Ei.onAudioAutoplayFailed?1:-1,errorMsg:i,mediaType:t,trackId:r,extend:void 0});ue.send({type:he.AUTOPLAY_FAILED,data:a},!0)}const Si=["play","playing","loadeddata","canplay","pause","stalled","suspend","waiting","abort","emptied","ended","error"],ki=new class{constructor(){this.onAutoplayFailed=void 0,this.elementMap=new Map,this.elementStateMap=new Map,this.elementsNeedToResume=[],this.sinkIdMap=new Map,this.autoResumeAfterInterruption=e=>{Array.from(this.elementMap.entries()).forEach((t=>{let[i,r]=t;const n=this.elementStateMap.get(i),s=r.srcObject.getAudioTracks()[0],o=s&&s.readyState;if(de.debug("resume after interrupted, ele: ".concat(n," audio: ").concat(o," ").concat(e)),"live"===o){if(e)return r.pause(),void r.play();if("running"===yt.curState)return U()?(r.pause(),void r.play()):void(n&&"paused"===n&&r.play())}}))},this.autoResumeAfterInterruptionOnIOS15_16=()=>{Array.from(this.elementMap.entries()).forEach((e=>{let[t,i]=e;const r=i.srcObject.getAudioTracks()[0];r&&"live"===r.readyState&&(de.debug("auto resume after interruption inside autoResumeAfterInterruptionOnIOS15"),i.pause(),i.play())}))},this.autoResumeAudioElement(),yt.on(Ee.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),yt.on(Ee.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16),yt.on(Ee.STATE_CHANGE,(()=>{A()&&"suspended"===yt.prevState&&"running"===yt.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 _(T.PERMISSION_DENIED,"can not set sink id: "+e.toString())}}play(e,t,i,n){if(this.elementMap.has(t))return;const s=document.createElement("audio");s.autoplay=!0,s.srcObject=new MediaStream([e]),this.bindAudioElementEvents(t,s),this.elementMap.set(t,s),this.elementStateMap.set(t,at.INIT),this.setVolume(t,i);const o=this.sinkIdMap.get(t);if(o)try{s.setSinkId(o).catch((e=>{de.warning("[".concat(t,"] set sink id failed"),e.toString())}))}catch(e){de.warning("[".concat(t,"] set sink id failed"),e.toString())}const a=s.play();a&&a.then&&a.catch((e=>{n&&yi(n,"audio",e.message,t),de.warning("audio element play warning",e.toString()),this.elementMap.has(t)&&"NotAllowedError"===e.name&&(de.warning("detected audio element autoplay failed"),this.elementsNeedToResume.push(s),r((()=>{this.onAutoplayFailed&&this.onAutoplayFailed(),vi()})))}))}updateTrack(e,t){const i=this.elementMap.get(e);i&&(i.srcObject=new MediaStream([t]))}isPlaying(e){return this.elementMap.has(e)&&"playing"===this.elementStateMap.get(e)}setVolume(e,t){const i=this.elementMap.get(e);i&&(t=Math.max(0,Math.min(100,t)),i.volume=t/100)}stop(e){const t=this.elementMap.get(e);if(this.sinkIdMap.delete(e),!t)return;const i=this.elementsNeedToResume.indexOf(t);this.elementsNeedToResume.splice(i,1),t.srcObject=null,t.remove(),this.elementMap.delete(e),this.elementStateMap.delete(e)}bindAudioElementEvents(e,t){Si.forEach((i=>{t.addEventListener(i,(i=>{const r=this.elementStateMap.get(e),n="pause"===i.type?"paused":i.type;if(de.debug("[".concat(e,"] audio-element-status change ").concat(r," => ").concat(n)),"error"===i.type){const i=null==t?void 0:t.error;i&&de.error("[".concat(e,"] media error, code: ").concat(i.code,", message: ").concat(i.message))}this.elementStateMap.set(e,n)}))}))}getPlayerState(e){return this.elementStateMap.get(e)||"uninit"}autoResumeAudioElement(){const e=()=>{this.elementsNeedToResume.forEach((e=>{e.play().then((e=>{de.debug("Auto resume audio element success")})).catch((e=>{de.warning("Auto resume audio element failed!",e)}))})),this.elementsNeedToResume=[]};F().then((()=>{x()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0))}))}};function bi(){return function(e,t,i){const r=i.value;return"function"==typeof r&&(i.value=function(){this._isClosed&&new _(T.INVALID_OPERATION,"[".concat(this.getTrackId(),"] cannot operate a closed track")).print("warning",de);for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];const n=r.apply(this,t);return n instanceof Promise?new Promise(((e,t)=>{n.then(e).catch(t)})):n}),i}}class Ii extends E{constructor(e){super(),this.name="VideoProcessorDestination",this.ID="0",this._source=void 0,this.videoContext=void 0,this.inputTrack=void 0,this.videoContext=e}get kind(){return"video"}get enabled(){return!0}pipe(){throw new _(T.NOT_SUPPORTED,"VideoProcessor cannot pipe to any other Processor")}unpipe(){throw new _(T.NOT_SUPPORTED,"VideoProcessor cannot unpipe to any other Processor")}enable(){}disable(){}updateInput(e){if(e.context!==this.videoContext)throw new Error("ProcessorContext passed to VideoTrack.processorDestination doesn't match it's belonging VideoTrack's context.\nProbably you are making pipeline like this:\nvideoTrack1.pipe(processor).pipe(videoTrack2.processorDestination).");e.track&&e.track!==this.inputTrack&&(this.videoContext.chained=!0,this.inputTrack=e.track,this.emit(rt.ON_TRACK,e.track))}reset(){this.inputTrack=void 0,this.videoContext.chained=!1,this.emit(rt.ON_TRACK,void 0)}}class Ai extends E{set chained(e){this._chained=e}get chained(){return this._chained}constructor(e,t){super(),this.constraintsMap=new Map,this.statsRegistry=[],this.usageRegistry=[],this.trackId=void 0,this.direction=void 0,this._chained=!1,this.trackId=e,this.direction=t}async getConstraints(){return await B(this,nt.REQUEST_CONSTRAINTS)}async requestApplyConstraints(e,t){return de.info("processor ".concat(t.name," requestApplyConstraints for ").concat(this.trackId)),e&&this.constraintsMap.set(t,e),b(this,nt.REQUEST_UPDATE_CONSTRAINTS,Array.from(this.constraintsMap.values()))}async requestRevertConstraints(e){if(this.constraintsMap.has(e))return de.info("processor ".concat(e.name," requestRevertConstraints for ").concat(this.trackId)),this.constraintsMap.delete(e),b(this,nt.REQUEST_UPDATE_CONSTRAINTS,Array.from(this.constraintsMap.values()))}registerStats(e,t,i){this.statsRegistry.find((i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t))||this.statsRegistry.push({processorName:e.name,processorID:e.ID,type:t,cb:i})}unregisterStats(e,t){const i=this.statsRegistry.findIndex((i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t));-1!==i&&this.statsRegistry.splice(i,1)}gatherStats(){const e=[];for(const{processorID:t,processorName:i,type:r,cb:n}of this.statsRegistry)try{const s=n();e.push({processorID:t,processorName:i,type:r,stats:s})}catch(e){de.error(new _(T.UNEXPECTED_ERROR,e.message))}return e}registerUsage(e,t){this.usageRegistry.find((t=>t.processorID===e.ID&&t.processorName===e.name))||this.usageRegistry.push({processorID:e.ID,processorName:e.name,cb:t})}unregisterUsage(e){const t=this.usageRegistry.findIndex((t=>t.processorID===e.ID&&t.processorName===e.name));-1!==t&&this.usageRegistry.splice(t,1)}async gatherUsage(){const e=[];if(!this.chained)return[];for(const{cb:t}of this.usageRegistry)try{let i=t();i instanceof Promise&&(i=await i),e.push(pt(pt({},i),{},{direction:this.direction}))}catch(e){de.error("gather extension usage error",e)}return e}getDirection(){return this.direction}}class wi extends E{constructor(e){super(),this.name="AudioProcessorDestination",this.ID="0",this.inputTrack=void 0,this.inputNode=void 0,this.audioProcessorContext=void 0,this._source=void 0,this.audioProcessorContext=e}get kind(){return"audio"}get enabled(){return!0}pipe(){throw new _(T.NOT_SUPPORTED,"AudioProcessorDestination cannot pipe to any other Processor")}unpipe(){throw new _(T.NOT_SUPPORTED,"AudioProcessor cannot unpipe to any other Processor")}enable(){}disable(){}reset(){this.inputTrack=void 0,this.inputNode=void 0,this.audioProcessorContext.chained=!1,this.emit(rt.ON_TRACK,void 0),this.emit(rt.ON_NODE,void 0)}updateInput(e){if(e.context!==this.audioProcessorContext)throw new Error("ProcessorContext passed to AudioTrack.processorDestination doesn't match it's belonging AudioTrack's context.\n Probably you are making pipeline like this: audioTrack1.pipe(processor).pipe(audioTrack2.processorDestination).");e.track&&this.inputTrack!==e.track&&(this.audioProcessorContext.chained=!0,this.inputTrack=e.track,this.emit(rt.ON_TRACK,this.inputTrack)),e.node&&this.inputNode!==e.node&&(this.audioProcessorContext.chained=!0,this.inputNode=e.node,this.emit(rt.ON_NODE,this.inputNode))}}class Ni extends E{set chained(e){this._chained=e}get chained(){return this._chained}constructor(e,t,i){super(),this.constraintsMap=new Map,this.statsRegistry=[],this.audioContext=void 0,this.trackId=void 0,this.direction=void 0,this.usageRegistry=[],this._chained=!1,this.audioContext=e,this.trackId=t,this.direction=i}async getConstraints(){return B(this,nt.REQUEST_CONSTRAINTS)}getAudioContext(){return this.audioContext}async requestApplyConstraints(e,t){return de.info("processor ".concat(t.name," requestApplyConstraints for ").concat(this.trackId)),e&&this.constraintsMap.set(t,e),b(this,nt.REQUEST_UPDATE_CONSTRAINTS,Array.from(this.constraintsMap.values()))}async requestRevertConstraints(e){if(this.constraintsMap.has(e))return this.constraintsMap.delete(e),b(this,nt.REQUEST_UPDATE_CONSTRAINTS,Array.from(this.constraintsMap.values()))}registerStats(e,t,i){this.statsRegistry.find((i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t))||this.statsRegistry.push({processorName:e.name,processorID:e.ID,type:t,cb:i})}unregisterStats(e,t){const i=this.statsRegistry.findIndex((i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t));-1!==i&&this.statsRegistry.splice(i,1)}gatherStats(){const e=[];for(const{processorID:t,processorName:i,type:r,cb:n}of this.statsRegistry)try{const s=n();e.push({processorID:t,processorName:i,type:r,stats:s})}catch(e){de.error(new _(T.UNEXPECTED_ERROR,e.message))}return e}registerUsage(e,t){this.usageRegistry.find((t=>t.processorID===e.ID&&t.processorName===e.name))||this.usageRegistry.push({processorID:e.ID,processorName:e.name,cb:t})}unregisterUsage(e){const t=this.usageRegistry.findIndex((t=>t.processorID===e.ID&&t.processorName===e.name));-1!==t&&this.usageRegistry.splice(t,1)}async gatherUsage(){const e=[];if(!this.chained)return[];for(const{cb:t}of this.usageRegistry)try{let i=t();i instanceof Promise&&(i=await i),e.push(pt(pt({},i),{},{direction:this.direction}))}catch(e){de.error("gather extension usage error",e)}return e}getDirection(){return this.direction}}class Ri extends E{get isPlayed(){return!0}get isFreeze(){return!1}constructor(){super(),this.context=void 0,this.processSourceNode=void 0,this.outputTrack=void 0,this.processedNode=void 0,this.clonedTrack=void 0,this.outputNode=void 0,this.outputNode=new Ci}setVolume(){}createOutputTrack(){throw new _(T.NOT_SUPPORTED,"can not create output MediaStreamTrack when WebAudio disabled")}getOriginVolumeLevel(){return 0}getAccurateVolumeLevel(){return 0}stopGetAudioBuffer(){}startGetAudioBuffer(){}play(){}stop(){}destroy(){}updateTrack(){}updateOriginTrack(){}createMediaStreamSourceNode(){}}class Ci{disconnect(){}connect(){}}class Di extends ft{get _source(){return this.initWebAudio()}set _source(e){this._trackSource=e}get processorContext(){return this._processorContext||(this._processorContext=this.initProcessor().processorContext),this._processorContext}get processorDestination(){return this._processorDestination||(this._processorDestination=this.initProcessor().processorDestination),this._processorDestination}get isPlaying(){return this._useAudioElement?ki.isPlaying(this.getTrackId()):this._source.isPlayed}get __className__(){return"LocalAudioTrack"}constructor(e,t,i,r){super(e,i),this.trackMediaType="audio",this._encoderConfig=void 0,this._trackSource=void 0,this._enabled=!0,this._volume=100,this._useAudioElement=!0,this._bypassWebAudio=!1,this.processor=void 0,this._processorContext=void 0,this._processorDestination=void 0,this._getOriginVolumeLevel=void 0,this._encoderConfig=t,this._getOriginVolumeLevel=!!r,this._trackSource=new Ri,u("DISABLE_WEBAUDIO")&&(this._bypassWebAudio=!0),u("LOCAL_AUDIO_TRACK_USES_WEB_AUDIO")&&(this._useAudioElement=!1);c()&&!bt()?setTimeout((()=>this.initWebAudio())):this.initWebAudio()}setVolume(e){p(e,"volume",0,1e3),this._volume=e,this._source.setVolume(e/100),this._useAudioElement&&ki.setVolume(this.getTrackId(),e);try{if(this._bypassWebAudio)return void de.debug("[".concat(this.getTrackId(),"] setVolume returned because no pass through WebAudio."));const e=this._source.createOutputTrack();this._mediaStreamTrack!==e&&(this._mediaStreamTrack=e,b(this,We.NEED_REPLACE_TRACK,this).then((()=>{de.debug("[".concat(this.getTrackId(),"] replace web audio track success"))})).catch((e=>{de.warning("[".concat(this.getTrackId(),"] replace web audio track failed"),e)})))}catch(e){}}getVolumeLevel(){return this._muted&&this.enabled&&this._getOriginVolumeLevel?this._source.getOriginVolumeLevel():this._source.getAccurateVolumeLevel()}async setPlaybackDevice(e){if(!this._useAudioElement||!O()&&u("RESTRICTION_SET_PLAYBACK_DEVICE"))throw new _(T.NOT_SUPPORTED,"your browser does not support setting the audio output device");await ki.setSinkID(this.getTrackId(),e)}async setEnabled(e,t,i){return this._setEnabled(e,t,i)}async _setEnabled(e,t,i){if(!i){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(de.info("[".concat(this.getTrackId(),"] start setEnabled"),e),e){this._originMediaStreamTrack.enabled=!0;try{i||(this._enabled=!0),await b(this,We.NEED_ENABLE_TRACK,this),de.info("[".concat(this.getTrackId(),"] setEnabled to ").concat(e," success"))}catch(e){throw i||(this._enabled=!1),de.error("[".concat(this.getTrackId(),"] setEnabled to true error"),e.toString()),e}}else{this._originMediaStreamTrack.enabled=!1,i||(this._enabled=!1);try{await b(this,We.NEED_DISABLE_TRACK,this)}catch(e){throw i||(this._enabled=!0),de.error("[".concat(this.getTrackId(),"] setEnabled to false error"),e.toString()),e}}}async setMuted(e){e!==this._muted&&(this.stateCheck("muted",e),this._muted=e,this._originMediaStreamTrack.enabled=!e,de.debug("[".concat(this.getTrackId(),"] start set muted: ").concat(e)),e?await b(this,We.NEED_MUTE_TRACK,this):await b(this,We.NEED_UNMUTE_TRACK,this))}getStats(){K((()=>{de.warning("[deprecated] LocalAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalAudioStats instead")}),"localAudioTrackGetStatsWarning");const e=G(this,We.GET_STATS);return e||pt({},qe)}setAudioFrameCallback(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:4096;if(!e)return this._source.removeAllListeners(Ye.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(t),this._source.removeAllListeners(Ye.ON_AUDIO_BUFFER),this._source.on(Ye.ON_AUDIO_BUFFER,(t=>e(t)))}play(){de.debug("[".concat(this.getTrackId(),"] start audio playback")),this._useAudioElement?(de.debug("[".concat(this.getTrackId(),"] start audio playback in element")),ki.play(this._mediaStreamTrack,this.getTrackId(),this._volume)):this._source.play()}stop(){de.debug("[".concat(this.getTrackId(),"] stop audio playback")),this._useAudioElement?ki.stop(this.getTrackId()):this._source.stop()}close(){super.close(),this._processorDestination&&this.unbindProcessorDestinationEvents(this._processorDestination),this._processorContext&&this.unbindProcessorContextEvents(this._processorContext),this.unpipe(),this._processorDestination&&this._processorDestination._source&&this._processorDestination._source.unpipe(),this._source.destroy()}_updatePlayerSource(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];de.debug("[".concat(this.getTrackId(),"] update player source track")),e&&this._source.updateTrack(this._mediaStreamTrack),this._useAudioElement&&ki.updateTrack(this.getTrackId(),this._mediaStreamTrack)}async _updateOriginMediaStreamTrack(e,t){this._originMediaStreamTrack!==e&&(this._originMediaStreamTrack&&(this._originMediaStreamTrack.removeEventListener("ended",this._handleTrackEnded),t&&this._originMediaStreamTrack.stop()),e.addEventListener("ended",this._handleTrackEnded),this._originMediaStreamTrack=e,this._muted&&(this._originMediaStreamTrack.enabled=!1),this.processor&&this._processorContext&&this.processor.updateInput({track:e,context:this._processorContext}),this._mediaStreamTrack!==this._source.outputTrack?(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await b(this,We.NEED_REPLACE_TRACK,this)):this._source.updateTrack(this._originMediaStreamTrack),this._getOriginVolumeLevel&&this._source.updateOriginTrack(e))}renewMediaStreamTrack(e){return Promise.resolve(void 0)}pipe(e){if(this._bypassWebAudio)throw new _(T.INVALID_OPERATION,"Can not process AudioTrack when bypassWebAudio set to true.");if(this.processor===e)return e;if(e._source)throw new _(T.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,node:this._source.processSourceNode,context:this.processorContext}),e}unpipe(){var e;if(!this.processor)return;const t=this.processor;null===(e=this._source.processSourceNode)||void 0===e||e.disconnect(),this.processor._source=!1,this.processor=void 0,t.reset()}bindProcessorDestinationEvents(e){e.on(rt.ON_TRACK,(async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(!1),this._source.processedNode=this._source.createMediaStreamSourceNode(e),await b(this,We.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await b(this,We.NEED_REPLACE_TRACK,this))})),e.on(rt.ON_NODE,(e=>{this._source.processedNode=e}))}unbindProcessorDestinationEvents(e){e.removeAllListeners(rt.ON_TRACK),e.removeAllListeners(rt.ON_NODE)}bindProcessorContextEvents(e){e.on(nt.REQUEST_CONSTRAINTS,(async e=>{e(this._originMediaStreamTrack.getSettings())}))}unbindProcessorContextEvents(e){e.removeAllListeners(nt.REQUEST_CONSTRAINTS)}initWebAudio(){return this._trackSource instanceof Ri&&(this._trackSource=new Lt(this._mediaStreamTrack,!1,this._getOriginVolumeLevel?this._mediaStreamTrack:void 0)),this._trackSource}initProcessor(){const e=new Ni(this._source.context,this.getTrackId(),"local"),t=new wi(e);return this._processorContext=e,this._processorDestination=t,this.bindProcessorContextEvents(e),this.bindProcessorDestinationEvents(t),this._source.on(Ye.UPDATE_SOURCE,(()=>{this.processor&&this.processor.updateInput({node:this._source.processSourceNode,context:e})})),this._useAudioElement&&(this._useAudioElement=!1,this.isPlaying&&(ki.stop(this.getTrackId()),this._source.play()),b(this,We.NEED_REPLACE_MIXING_TRACK,this).then((()=>{de.debug("[".concat(this.getTrackId(),"] replace from origin track to web audio track success"))})).catch((e=>{de.warning("[".concat(this.getTrackId(),"] replace from origin track to web audio track failed"),e)}))),{processorContext:e,processorDestination:t}}}gt([le({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),_t("design:type",Function),_t("design:paramtypes",[Number]),_t("design:returntype",void 0)],Di.prototype,"setVolume",null),gt([le({argsMap:(e,t)=>[e.getTrackId(),t]}),bi(),_t("design:type",Function),_t("design:paramtypes",[String]),_t("design:returntype",Promise)],Di.prototype,"setPlaybackDevice",null),gt([W("LocalAudioTrack","_enabledMutex"),le({argsMap:(e,t)=>[e.getTrackId(),t]}),bi(),_t("design:type",Function),_t("design:paramtypes",[Boolean,Object,Boolean]),_t("design:returntype",Promise)],Di.prototype,"setEnabled",null),gt([W("LocalAudioTrack","_enabledMutex"),le({argsMap:(e,t)=>[e.getTrackId(),t]}),bi(),_t("design:type",Function),_t("design:paramtypes",[Boolean]),_t("design:returntype",Promise)],Di.prototype,"setMuted",null),gt([bi(),_t("design:type",Function),_t("design:paramtypes",[]),_t("design:returntype",Object)],Di.prototype,"getStats",null),gt([bi(),_t("design:type",Function),_t("design:paramtypes",[Object,Number]),_t("design:returntype",void 0)],Di.prototype,"setAudioFrameCallback",null),gt([le({argsMap:e=>[e.getTrackId()]}),bi(),_t("design:type",Function),_t("design:paramtypes",[]),_t("design:returntype",void 0)],Di.prototype,"play",null),gt([le({argsMap:e=>[e.getTrackId()]}),bi(),_t("design:type",Function),_t("design:paramtypes",[]),_t("design:returntype",void 0)],Di.prototype,"stop",null),gt([le({argsMap:e=>[e.getTrackId()]}),_t("design:type",Function),_t("design:paramtypes",[]),_t("design:returntype",void 0)],Di.prototype,"close",null),gt([le({argsMap:(e,t)=>[e.getTrackId(),t.name]}),_t("design:type",Function),_t("design:paramtypes",[Object]),_t("design:returntype",Object)],Di.prototype,"pipe",null),gt([le({argsMap:e=>[e.getTrackId()]}),_t("design:type",Function),_t("design:paramtypes",[]),_t("design:returntype",void 0)],Di.prototype,"unpipe",null);class Oi extends Di{get __className__(){return"MicrophoneAudioTrack"}constructor(e,t,i,r){super(e,t.encoderConfig?Oe(t.encoderConfig):{},r,u("GET_VOLUME_OF_MUTED_AUDIO_TRACK")),this._config=void 0,this._deviceName="default",this._constraints=void 0,this._originalConstraints=void 0,this._enabled=!0,this._config=t,this._constraints=i,this._originalConstraints=i,this._deviceName=e.label,"boolean"==typeof t.bypassWebAudio&&(this._bypassWebAudio=t.bypassWebAudio),(U()||H())&&yt.bindInterruptDetectorTrack(this)}async setDevice(e){if(de.info("[".concat(this.getTrackId(),"] start set device to ").concat(e)),this._enabled)try{const t=await _i(e),i={};i.audio=pt({},this._constraints),i.audio.deviceId={exact:e},this._originMediaStreamTrack.stop();let r=null;try{r=await Kt(i,this.getTrackId())}catch(e){throw de.error("[".concat(this.getTrackId(),"] setDevice failed"),e.toString()),r=await Kt({audio:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(r.getAudioTracks()[0],!1),e}await this._updateOriginMediaStreamTrack(r.getAudioTracks()[0],!1),this._deviceName=t.label,this._config.microphoneId=e,this._constraints.deviceId={exact:e}}catch(e){throw de.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}else try{const t=await _i(e);this._deviceName=t.label,this._config.microphoneId=e,this._constraints.deviceId={exact:e}}catch(e){throw de.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}de.info("[".concat(this.getTrackId(),"] set device to ").concat(e," success"))}async setEnabled(e,t,i){if(t)return de.debug("[".concat(this.getTrackId(),"] setEnabled false (do not close microphone)")),await super._setEnabled(e);if(!i){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(de.info("[".concat(this.getTrackId(),"] start setEnabled"),e),!e){var r;this._originMediaStreamTrack.onended=null,this._originMediaStreamTrack.stop(),null===(r=this._source.clonedTrack)||void 0===r||r.stop(),i||(this._enabled=!1);try{await b(this,We.NEED_DISABLE_TRACK,this)}catch(e){throw de.error("[".concat(this.getTrackId(),"] setEnabled false failed"),e.toString()),e}return}const n=pt({},this._constraints),s=Ti(this._deviceName);s&&!n.deviceId&&(n.deviceId=s);try{i||(this._enabled=!0);const e=await Kt({audio:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getAudioTracks()[0],!1),await b(this,We.NEED_ENABLE_TRACK,this)}catch(e){throw i||(this._enabled=!1),de.error("[".concat(this.getTrackId(),"] setEnabled true failed"),e.toString()),e}de.info("[".concat(this.getTrackId(),"] setEnabled success"))}close(){super.close(),(U()||H())&&yt.unbindInterruptDetectorTrack(this)}onTrackEnded(){if((A()||w())&&this._enabled&&!this._isClosed&&yt.duringInterruption){const e=async()=>{yt.off(Ee.IOS_INTERRUPTION_END,e),this._enabled&&!this._isClosed&&(de.debug("[".concat(this.getTrackId(),"] try capture microphone media device for interrupted iOS device.")),await this.setEnabled(!1),await this.setEnabled(!0))};yt.on(Ee.IOS_INTERRUPTION_END,e)}else de.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(Ze.TRACK_ENDED)}async renewMediaStreamTrack(e){const t=e||this._constraints,i=Ti(this._deviceName);if(i&&!t.deviceId&&(t.deviceId=i),this._constraints=t,this._enabled){this._originMediaStreamTrack.stop();const e=await Kt({audio:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getAudioTracks()[0],!0)}}bindProcessorContextEvents(e){super.bindProcessorContextEvents(e),e.on(nt.REQUEST_UPDATE_CONSTRAINTS,(async(e,t,i)=>{try{const i=Object.assign({},this._originalConstraints,...e);await this.renewMediaStreamTrack(i),t()}catch(e){i(e)}}))}unbindProcessorContextEvents(e){super.unbindProcessorContextEvents(e),e.removeAllListeners(nt.REQUEST_UPDATE_CONSTRAINTS)}}gt([le({argsMap:(e,t)=>[e.getTrackId(),t]}),bi(),_t("design:type",Function),_t("design:paramtypes",[String]),_t("design:returntype",Promise)],Oi.prototype,"setDevice",null),gt([W("MicrophoneAudioTrack","_enabledMutex"),le({argsMap:(e,t,i)=>[e.getTrackId(),t,i]}),bi(),_t("design:type",Function),_t("design:paramtypes",[Boolean,Boolean,Boolean]),_t("design:returntype",Promise)],Oi.prototype,"setEnabled",null),gt([le({argsMap:e=>[e.getTrackId()]}),_t("design:type",Function),_t("design:paramtypes",[]),_t("design:returntype",void 0)],Oi.prototype,"close",null);class Mi extends Di{get __className__(){return"BufferSourceAudioTrack"}constructor(e,t,i,r){super(t.createOutputTrack(),i,r),this.source=void 0,this._bufferSource=void 0,this._useAudioElement=!1,this.source=e,this._bufferSource=t,this._bufferSource.on(Ye.AUDIO_SOURCE_STATE_CHANGE,(e=>{this.safeEmit(Ze.SOURCE_STATE_CHANGE,e)}));try{this._mediaStreamTrack=this._source.createOutputTrack()}catch(e){}}get currentState(){return this._bufferSource.currentState}get duration(){return this._bufferSource.duration}get playbackSpeed(){return this._bufferSource.playbackSpeed}getCurrentTime(){return this._bufferSource.currentTime}startProcessAudioBuffer(e){e&&this._bufferSource.updateOptions(e),this._bufferSource.startProcessAudioBuffer()}pauseProcessAudioBuffer(){this._bufferSource.pauseProcessAudioBuffer()}seekAudioBuffer(e){this._bufferSource.seekAudioBuffer(e)}resumeProcessAudioBuffer(){this._bufferSource.resumeProcessAudioBuffer()}stopProcessAudioBuffer(){this._bufferSource.stopProcessAudioBuffer()}close(){this.source=null,this._bufferSource.destroy(),super.close()}setAudioBufferPlaybackSpeed(e){p(e,"speed",0),this._bufferSource.setAudioBufferPlaybackSpeed(e)}}gt([le({argsMap:(e,t)=>[e.getTrackId(),t,e.duration]}),bi(),_t("design:type",Function),_t("design:paramtypes",[Object]),_t("design:returntype",void 0)],Mi.prototype,"startProcessAudioBuffer",null),gt([le({argsMap:e=>[e.getTrackId()]}),bi(),_t("design:type",Function),_t("design:paramtypes",[]),_t("design:returntype",void 0)],Mi.prototype,"pauseProcessAudioBuffer",null),gt([le({argsMap:e=>[e.getTrackId()]}),bi(),_t("design:type",Function),_t("design:paramtypes",[Number]),_t("design:returntype",void 0)],Mi.prototype,"seekAudioBuffer",null),gt([le({argsMap:e=>[e.getTrackId()]}),bi(),_t("design:type",Function),_t("design:paramtypes",[]),_t("design:returntype",void 0)],Mi.prototype,"resumeProcessAudioBuffer",null),gt([le({argsMap:e=>[e.getTrackId()]}),bi(),_t("design:type",Function),_t("design:paramtypes",[]),_t("design:returntype",void 0)],Mi.prototype,"stopProcessAudioBuffer",null),gt([le({argsMap:e=>[e.getTrackId()]}),_t("design:type",Function),_t("design:paramtypes",[]),_t("design:returntype",void 0)],Mi.prototype,"close",null),gt([le({argsMap:e=>[e.getTrackId()]}),bi(),_t("design:type",Function),_t("design:paramtypes",[Number]),_t("design:returntype",void 0)],Mi.prototype,"setAudioBufferPlaybackSpeed",null);class Pi extends Di{get __className__(){return"MixingAudioTrack"}get isActive(){for(const e of this.trackList)if(e._enabled&&!e._isClosed&&!e.muted)return!0;return!1}constructor(){const e=kt().createMediaStreamDestination();super(e.stream.getAudioTracks()[0],void 0,v(8,"track-mix-")),this.trackList=void 0,this.destNode=void 0,this._useAudioElement=!1;try{this._mediaStreamTrack=this._source.createOutputTrack()}catch(e){}this.destNode=e,this.trackList=[]}hasAudioTrack(e){return-1!==this.trackList.indexOf(e)}addAudioTrack(e){-1===this.trackList.indexOf(e)?(de.debug("add ".concat(e.getTrackId()," to mixing track")),e._source.outputNode.connect(this.destNode),this.trackList.push(e),this.updateEncoderConfig()):de.debug("track ".concat(e.getTrackId()," is already added"))}removeAudioTrack(e){if(-1!==this.trackList.indexOf(e)){de.debug("remove ".concat(e.getTrackId()," from mixing track"));try{e._source.outputNode.disconnect(this.destNode)}catch(e){}I(this.trackList,e),this.updateEncoderConfig()}}updateEncoderConfig(){const e={};this.trackList.forEach((t=>{t._encoderConfig&&((t._encoderConfig.bitrate||0)>(e.bitrate||0)&&(e.bitrate=t._encoderConfig.bitrate),(t._encoderConfig.sampleRate||0)>(e.sampleRate||0)&&(e.sampleRate=t._encoderConfig.sampleRate),(t._encoderConfig.sampleSize||0)>(e.sampleSize||0)&&(e.sampleSize=t._encoderConfig.sampleSize),t._encoderConfig.stereo&&(e.stereo=!0))})),this._encoderConfig=e}_updateRtpTransceiver(e){this._rtpTransceiver!==e&&(this._rtpTransceiver=e,this.trackList.forEach((t=>{t instanceof Pi?t.emit(je.TRANSCEIVER_UPDATED,e):t._updateRtpTransceiver(e)})))}}function Li(e){const t={};e.facingMode&&(t.facingMode=e.facingMode),e.cameraId&&(t.deviceId={exact:e.cameraId});const i=Ne(e.encoderConfig);return null!=i.width&&(t.width=i.width),null!=i.height&&(t.height=i.height),!z()&&i.frameRate&&(t.frameRate=i.frameRate),j()&&"object"==typeof t.frameRate&&(t.frameRate.max=60),h()&&(t.frameRate={ideal:30,max:30}),t}function Vi(e){const t={};e.screenSourceType&&(t.mediaSource=e.screenSourceType),e.extensionId&&O()&&(t.extensionId=e.extensionId);const{displaySurface:i,selfBrowserSurface:r,surfaceSwitching:s,systemAudio:o}=e;(n(107)||Z(107)||J(93))&&(i&&(g(i,"displaySurface",["browser","window","monitor"]),t.displaySurface=i),r?(g(r,"selfBrowserSurface",["exclude","include"]),t.selfBrowserSurface=r):t.selfBrowserSurface="include",s&&(g(s,"surfaceSwitching",["exclude","include"]),t.surfaceSwitching=s)),(n(105)||Z(105)||J(91))&&o&&(g(o,"systemAudio",["exclude","include"]),t.systemAudio=o),e.electronScreenSourceId&&(t.sourceId=e.electronScreenSourceId);const a=e.encoderConfig?Re(e.encoderConfig):null;return t.mandatory={chromeMediaSource:"desktop",maxWidth:a?a.width:void 0,maxHeight:a?a.height:void 0},a&&(a.frameRate&&("number"==typeof a.frameRate?(t.mandatory.maxFrameRate=a.frameRate,t.mandatory.minFrameRate=a.frameRate):(t.mandatory.maxFrameRate=a.frameRate.max||a.frameRate.ideal||a.frameRate.exact||void 0,t.mandatory.minFrameRate=a.frameRate.min||a.frameRate.ideal||a.frameRate.exact||void 0),t.frameRate=a.frameRate),a.width&&(t.width=a.width),a.height&&(t.height=a.height)),t}function xi(e){const t={};if(z()||(void 0!==e.AGC&&(t.autoGainControl=e.AGC),void 0!==e.AEC&&(t.echoCancellation=e.AEC),void 0!==e.ANS&&(t.noiseSuppression=e.ANS,O()&&e.ANS&&(t.googHighpassFilter=e.ANS))),e.encoderConfig){const i=Oe(e.encoderConfig);t.channelCount=i.stereo?2:1,t.sampleRate=i.sampleRate,t.sampleSize=i.sampleSize}return e.microphoneId&&(t.deviceId={exact:e.microphoneId}),L()&&(t.sampleRate=void 0),t}class Ui extends Pt{set currentState(e){e!==this._currentState&&(this._currentState=e,this.safeEmit(Ye.AUDIO_SOURCE_STATE_CHANGE,this._currentState))}get currentState(){return this._currentState}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),this.audioBuffer=void 0,this.sourceNode=void 0,this.startPlayTime=0,this.startPlayOffset=0,this.pausePlayTime=0,this.options=void 0,this.currentLoopCount=0,this.currentPlaybackSpeed=100,this._currentState="stopped",this.audioBuffer=e,this.options=t,this.startPlayOffset=this.options.startPlayTime||0}createWebAudioDiagram(){return this.context.createGain()}get duration(){return this.audioBuffer?this.audioBuffer.duration:0}get playbackSpeed(){return this.currentPlaybackSpeed}get currentTime(){return this.audioBuffer?"stopped"===this.currentState?0:"paused"===this.currentState?this.pausePlayTime:((this.context.currentTime-this.startPlayTime)*(this.playbackSpeed/100)+this.startPlayOffset)%this.audioBuffer.duration:0}updateOptions(e){"stopped"===this.currentState?(this.options=e,this.startPlayOffset=this.options.startPlayTime||0):de.warning("can not set audio source options")}startProcessAudioBuffer(){this.sourceNode&&this.stopProcessAudioBuffer(),this.sourceNode=this.createSourceNode(),this.startSourceNode(),this.currentState="playing"}pauseProcessAudioBuffer(){this.sourceNode&&"playing"===this.currentState&&(this.pausePlayTime=this.currentTime,this.sourceNode.onended=null,this.sourceNode.stop(),this.sourceNode.buffer=null,this.sourceNode=this.createSourceNode(),this.currentState="paused")}seekAudioBuffer(e){this.sourceNode&&(this.sourceNode.onended=null,"playing"===this.currentState&&this.sourceNode.stop(),this.sourceNode=this.createSourceNode(),"playing"===this.currentState?(this.startPlayOffset=e,this.startSourceNode()):"paused"===this.currentState&&(this.pausePlayTime=e))}resumeProcessAudioBuffer(){"paused"===this.currentState&&this.sourceNode&&(this.startPlayOffset=this.pausePlayTime,this.pausePlayTime=0,this.startSourceNode(),this.currentState="playing")}stopProcessAudioBuffer(){if(this.sourceNode){this.sourceNode.onended=null;try{this.sourceNode.stop()}catch(e){}this.reset()}}destroy(){this.audioBuffer=null,super.destroy()}setAudioBufferPlaybackSpeed(e){this.sourceNode&&("playing"===this.currentState&&(this.startPlayOffset=this.currentTime,this.startPlayTime=this.context.currentTime),this.sourceNode.playbackRate.value=e/100),this.currentPlaybackSpeed=e}startSourceNode(){this.sourceNode&&this.sourceNode.buffer&&(this.sourceNode.start(0,this.startPlayOffset),this.startPlayTime=this.context.currentTime,this.sourceNode.onended=this.handleSourceNodeEnded.bind(this))}createSourceNode(){const e=this.context.createBufferSource();return e.buffer=this.audioBuffer,e.loop=!!this.options.loop,e.connect(this.outputNode),e.playbackRate.value=this.currentPlaybackSpeed/100,e}handleSourceNodeEnded(){if(this.currentLoopCount+=1,this.options.cycle&&this.options.cycle>this.currentLoopCount)return this.startPlayOffset=0,this.sourceNode=void 0,void this.startProcessAudioBuffer();this.reset()}reset(){this.startPlayOffset=this.options.startPlayTime||0,this.currentState="stopped",this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=void 0),this.currentLoopCount=0}}const Fi=new Map;const Bi=e=>{const t=document.createElement("canvas");return t.width=2,t.height=2,new Promise(((i,r)=>{t.toBlob((async e=>{if(t.remove(),e){const r=await Wi(e);i({buffer:r,width:t.width,height:t.height})}else r(new _(T.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED))}),e,1)}))},Wi=async e=>{const t=await e.arrayBuffer();return new Uint8Array(t)};class Ki{get videoElementStatus(){return this._videoElementStatus}set videoElementStatus(e){e!==this._videoElementStatus&&(de.debug("[".concat(this.trackId,"] video-element-status change ").concat(this._videoElementStatus," => ").concat(e)),this._videoElementStatus=e)}get videoState(){return this._videoState}set videoState(e){var t;e!==this._videoState&&(de.debug("[".concat(this.trackId,"] video-status change ").concat(this._videoState," => ").concat(e)),this._videoState=e,null===(t=this.onVideoStateChanged)||void 0===t||t.call(this,this.videoState))}constructor(e){this.trackId=void 0,this.config=void 0,this.onFirstVideoFrameDecoded=void 0,this.onVideoStateChanged=void 0,this.freezeTimeCounterList=[],this.renderFreezeAccTime=0,this.isKeepLastFrame=!1,this.timeUpdatedCount=0,this.freezeTime=0,this.playbackTime=0,this.lastTimeUpdatedTime=0,this.autoplayFailed=!1,this.videoTrack=void 0,this.videoElement=void 0,this.cacheVideoElement=void 0,this._videoState=ct.VideoStateStopped,this.videoElementCheckInterval=void 0,this.videoElementFreezeTimeout=void 0,this._videoElementStatus=at.NONE,this.isGettingVideoDimensions=!1,this.startGetVideoDimensions=()=>{const e=()=>{if(this.isGettingVideoDimensions=!0,this.videoElement.videoWidth*this.videoElement.videoHeight>4)return de.debug("[".concat(this.trackId,"] current video dimensions:"),this.videoElement.videoWidth,this.videoElement.videoHeight),void(this.isGettingVideoDimensions=!1);setTimeout(e,500)};!this.isGettingVideoDimensions&&e()},this.autoResumeAfterInterruption=()=>{this.videoTrack&&"live"===this.videoTrack.readyState&&"running"===yt.curState&&(de.debug("[track-".concat(this.trackId,"] video element paused, auto resume for ").concat(X())),Q()?(this.videoElement.srcObject=null,this.videoElement.srcObject=new MediaStream([this.videoTrack]),this.videoElement.play()):(this.videoElement.pause(),this.videoElement.play()))},this.handleVideoEvents=e=>{switch(e.type){case"play":case"playing":this.startGetVideoDimensions(),this.videoElementStatus=at.PLAYING;break;case"loadeddata":if(this.videoState=ct.VideoStateStarting,this.onFirstVideoFrameDecoded&&this.onFirstVideoFrameDecoded(),this.cacheVideoElement){try{this.cacheVideoElement.srcObject=null,this.cacheVideoElement.remove()}catch(e){}this.cacheVideoElement=void 0}break;case"canplay":this.videoElementStatus=at.CANPLAY;break;case"stalled":this.videoElementStatus=at.STALLED;break;case"suspend":this.videoElementStatus=at.SUSPEND;break;case"pause":this.videoElementStatus=at.PAUSED,A()||w()||c()&&this.autoplayFailed||!this.videoTrack||"live"!==this.videoTrack.readyState||(de.debug("[track-".concat(this.trackId,"] video element paused, auto resume")),this.videoElement.play());break;case"waiting":this.videoElementStatus=at.WAITING;break;case"abort":this.videoElementStatus=at.ABORT;break;case"ended":this.videoElementStatus=at.ENDED;break;case"emptied":this.videoElementStatus=at.EMPTIED;break;case"error":{this.videoElementStatus=at.ERROR;const e=this.videoElement.error;e&&de.error("[".concat(this.trackId,"] media error, code: ").concat(e.code,", message: ").concat(e.message));break}case"timeupdate":{const e=performance.now();if(this.timeUpdatedCount+=1,this.timeUpdatedCount<10)return void(this.lastTimeUpdatedTime=e);const t=e-this.lastTimeUpdatedTime,i=this.lastTimeUpdatedTime;if(this.lastTimeUpdatedTime=e,dr.lastVisibleTime<dr.lastHiddenTime||i<dr.lastHiddenTime||i<dr.lastVisibleTime)return;for(t>u("VIDEO_FREEZE_DURATION")&&(this.freezeTime+=t),this.playbackTime+=t;this.playbackTime>=6e3;){this.playbackTime-=6e3;const e=Math.min(6e3,this.freezeTime);this.freezeTimeCounterList.push(e),this.freezeTime=Math.max(0,this.freezeTime-6e3)}break}}},this.autoResumeAfterInterruptionOnIOS15_16=()=>{this.videoTrack&&"live"===this.videoTrack.readyState&&(de.debug("[track-".concat(this.trackId,"] video element paused, auto resume for ").concat(X())),Q()?(this.videoElement.srcObject=null,this.videoElement.srcObject=new MediaStream([this.videoTrack]),this.videoElement.play()):(this.videoElement.pause(),this.videoElement.play()))},this.trackId=e.trackId,this.config=e,e.element instanceof HTMLVideoElement?this.videoElement=e.element:this.videoElement=document.createElement("video"),yt.on(Ee.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),yt.on(Ee.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16)}getVideoElement(){return this.videoElement}getContainerElement(){var e;return null!==(e=this.videoElement.parentElement)&&void 0!==e?e:void 0}updateConfig(e){this.config=e,this.trackId=e.trackId,e.element!==this.videoElement&&(this.destroy(),this.videoElement=e.element),this.videoTrack&&this.initVideoElement()}updateVideoTrack(e){this.videoTrack!==e&&(this.videoTrack=e,this.initVideoElement())}play(t){const i=this.videoElement.play();i&&i.catch&&i.catch((e=>{t&&yi(t,"video",e.message,this.trackId),"NotAllowedError"===e.name?(de.warning("detected video element autoplay failed",e),this.autoplayFailed=!0,this.handleAutoPlayFailed()):de.warning("[".concat(this.trackId,"] play warning: "),e)}));const r=e();if(("Safari"===r.name&&15===Number(r.version)||U())&&i&&i.then){const e=()=>{this.config.mirror&&(this.videoElement.style.transform="rotateY(180deg)")};i.then(e).catch(e)}}getCurrentFrame(){const e=document.createElement("canvas");e.width=this.videoElement.videoWidth,e.height=this.videoElement.videoHeight;const t=e.getContext("2d");if(!t)return de.error("create canvas context failed!"),new ImageData(2,2);t.drawImage(this.videoElement,0,0,e.width,e.height);const i=t.getImageData(0,0,e.width,e.height);return e.remove(),i}async getCurrentFrameToUint8Array(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;const i=document.createElement("canvas");i.width=this.videoElement.videoWidth,i.height=this.videoElement.videoHeight;const r=i.getContext("2d");return r?(r.drawImage(this.videoElement,0,0,i.width,i.height),new Promise(((r,n)=>{i.toBlob((async e=>{if(i.remove(),e){const t=await Wi(e);r({buffer:t,width:i.width,height:i.height})}else n(new _(T.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED))}),e,t<0?.1:t>1?1:t)}))):await Bi(e)}destroy(){yt.off(Ee.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),yt.off(Ee.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16),this.videoElement.srcObject=null,this.resetVideoElement(),this.freezeTimeCounterList=[],this.videoState=ct.VideoStateStopped}initVideoElement(){if(this.videoElementStatus=at.INIT,!this.videoElementCheckInterval&&(Gi.forEach((e=>{this.videoElement.addEventListener(e,this.handleVideoEvents)})),this.videoElementCheckInterval=window.setInterval((()=>{q(this.videoElement)||(this.videoElementStatus=at.DESTROYED)}),1e3),u("ENABLE_VIDEO_FRAME_CALLBACK"))){var t,i;let e;const r=()=>{"visible"===document.visibilityState&&(document.removeEventListener("visibilitychange",r),this.videoElementFreezeTimeout=window.setTimeout(n,u("VIDEO_FREEZE_DURATION")))},n=()=>{this.videoElementFreezeTimeout=void 0,this.videoState===ct.VideoStateDecoding&&("visible"===document.visibilityState?this.videoState=ct.VideoStateFrozen:document.addEventListener("visibilitychange",r))},s=(t,i)=>{if(this.videoElementStatus===at.PLAYING){if(e){const t=i.presentationTime-e.presentationTime;this.videoState===ct.VideoStateStarting&&(this.videoState=ct.VideoStateDecoding),this.videoState===ct.VideoStateDecoding&&this.onVideoStateChanged&&(this.videoElementFreezeTimeout&&window.clearTimeout(this.videoElementFreezeTimeout),this.videoElementFreezeTimeout=window.setTimeout(n,u("VIDEO_FREEZE_DURATION"))),t<u("VIDEO_FREEZE_DURATION")&&this.videoState===ct.VideoStateFrozen&&(this.videoState=ct.VideoStateDecoding),t>u("VIDEO_FREEZE_DURATION")&&dr.lastVisibleTime>=dr.lastHiddenTime&&e.timestamp>dr.lastVisibleTime&&e.timestamp>dr.lastHiddenTime&&(this.renderFreezeAccTime+=t)}e=pt(pt({},i),{},{timestamp:t})}var r,o;u("ENABLE_VIDEO_FRAME_CALLBACK")&&(null===(r=(o=this.videoElement).requestVideoFrameCallback)||void 0===r||r.call(o,s))};null===(t=(i=this.videoElement).requestVideoFrameCallback)||void 0===t||t.call(i,s)}this.videoElement.controls=!1,this.videoElement.setAttribute("playsinline",""),L()&&(this.videoElement.poster="noposter");const r=e();if("Safari"===r.name&&15===Number(r.version)||U()||!this.config.mirror||(this.videoElement.style.transform="rotateY(180deg)"),this.config.fit?this.videoElement.style.objectFit=this.config.fit:this.videoElement.style.objectFit="cover",this.videoElement.setAttribute("muted",""),this.videoElement.muted=!0,this.videoElement.srcObject&&this.videoElement.srcObject instanceof MediaStream){this.videoElement.srcObject.getVideoTracks()[0]!==this.videoTrack&&(this.videoElement.srcObject=this.videoTrack?new MediaStream([this.videoTrack]):null,h()&&this.videoElement.load())}else this.videoElement.srcObject=this.videoTrack?new MediaStream([this.videoTrack]):null,h()&&this.videoElement.load();const n=this.videoElement.play();void 0!==n&&n.catch((e=>{de.debug("[".concat(this.trackId,"] playback interrupted"),e.toString())}))}resetVideoElement(){Gi.forEach((e=>{this.videoElement&&this.videoElement.removeEventListener(e,this.handleVideoEvents)})),this.videoElementCheckInterval&&(window.clearInterval(this.videoElementCheckInterval),this.videoElementCheckInterval=void 0),this.videoElementStatus=at.NONE}handleAutoPlayFailed(){const e=t=>{t.preventDefault(),this.videoElement.play().then((()=>{de.debug("[".concat(this.trackId,"] Video element for trackId:").concat(this.trackId," autoplay resumed."))})).catch((e=>{de.error(e)})),this.autoplayFailed=!1,x()?document.body.removeEventListener("click",e,!0):(document.body.removeEventListener("touchstart",e,!0),document.body.removeEventListener("mousedown",e,!0))};x()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0)),vi()}}const Gi=["play","playing","loadeddata","canplay","pause","stalled","suspend","waiting","abort","emptied","ended","timeupdate","error"];class Hi extends Ki{constructor(e){super(e),this.container=void 0,this.slot=void 0,this.slot=e.element,this.updateConfig(e)}updateConfig(e){this.config=e,this.trackId=e.trackId;const t=e.element;t!==this.slot&&(this.destroy(),this.slot=t),this.createElements()}updateVideoTrack(e){this.videoTrack!==e&&(this.videoTrack=e,this.createElements())}play(e){var t;null!==(t=this.container)&&void 0!==t&&t.contains(this.videoElement)&&super.play(e)}getCurrentFrame(){var e;return null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)?super.getCurrentFrame():new ImageData(2,2)}async getCurrentFrameToUint8Array(e){var t;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return null!==(t=this.container)&&void 0!==t&&t.contains(this.videoElement)?await super.getCurrentFrameToUint8Array(e,i):await Bi(e)}destroy(){if(super.destroy(),this.videoElement.remove(),this.videoElement=document.createElement("video"),this.container){try{this.container.remove(),this.slot.removeChild(this.container)}catch(e){}this.container=void 0}}createElements(){this.container||(this.container=document.createElement("div")),this.container.id="agora-video-player-".concat(this.trackId),this.container.style.width="100%",this.container.style.height="100%",this.container.style.position="relative",this.container.style.overflow="hidden",this.videoTrack?(this.container.style.backgroundColor="black",u("KEEP_LAST_FRAME")&&this.isKeepLastFrame&&this.videoElement.paused&&this.resetVideoElement(),this.mountedVideoElement()):this.unmountedVideoElement(),this.slot.appendChild(this.container)}mountedVideoElement(){var e;!this.container||null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)||this.container.appendChild(this.videoElement),super.initVideoElement(),this.videoElement.id="video_".concat(this.trackId),this.videoElement.className="agora_video_player",this.videoElement.style.width="100%",this.videoElement.style.height="100%",this.videoElement.style.position="absolute",this.videoElement.style.left="0",this.videoElement.style.top="0"}unmountedVideoElement(){var e;if(null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)){super.resetVideoElement();try{this.container&&this.container.removeChild(this.videoElement)}catch(e){}this.videoElement=document.createElement("video")}}resetVideoElement(){var e;null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)&&(super.resetVideoElement(),this.cacheVideoElement=this.videoElement,this.videoElement=document.createElement("video"))}getContainerElement(){return this.container}}function zi(e){return new Promise(((t,i)=>{let r=!1;const n=document.createElement("video");n.setAttribute("autoplay",""),n.setAttribute("muted",""),n.muted=!0,n.autoplay=!0,n.setAttribute("playsinline",""),n.setAttribute("style","position: fixed; top: 0; left: 0; width: 1px; height: 1px"),document.body.appendChild(n);const s=A()?"canplay":"playing";n.addEventListener(s,(()=>{const e=n.videoWidth,i=n.videoHeight;!e&&h()||(r=!0,n.srcObject=null,n.remove(),t([e,i]))})),n.srcObject=new MediaStream([e]),n.play().catch($),setTimeout((()=>{r||(n.srcObject=null,n.remove(),t([n.videoWidth,n.videoHeight]))}),4e3)}))}function ji(e,t,i,r,n){const s=u("BITRATE_ADAPTER_TYPE");if("DEFAULT_BITRATE"===s)return{min:r,max:n};if(void 0===n){var o;const a=Math.floor(200*Math.pow(i/15,.6)*Math.pow(e*t/640/360,.75));n="STANDARD_BITRATE"===s?4*a:2*a,r=null!==(o=r)&&void 0!==o?o:a}else{var a;r=null!==(a=r)&&void 0!==a?a:Math.floor(n/10)}return{min:r,max:n}}const Zi=async(e,t,i)=>await(async(e,t,i)=>{const r=ee(te(""+t+i)).slice(0,16),n=r.slice(0,12),s=await window.crypto.subtle.importKey("raw",r,"AES-GCM",!0,["encrypt"]);return new Uint8Array(await window.crypto.subtle.encrypt({name:"AES-GCM",iv:n},s,e))})(e.buffer,t,i);function Ji(e,t){if("VideoFrame"in window&&"TransformStream"in window&&fe().supportWebRTCInsertableStream){const i=new MediaStreamTrackProcessor(e),r=new MediaStreamTrackGenerator({kind:"video"});let n,s,o=Date.now();const a=()=>{c&&(clearInterval(c),c=void 0),n&&(n.close(),n=void 0),e.stop(),s=void 0,r.removeEventListener("ended",a)};let c=window.setInterval((()=>{if(s&&n&&Date.now()-o>(null!=t?t:1e3))try{"live"===r.readyState?s.enqueue(n.clone()):a()}catch(e){a()}}),null!=t?t:1e3);const d=new TransformStream({transform:(e,t)=>{"live"===r.readyState?(s=t,o=Date.now(),void 0===n?(n=e,t.enqueue(e.clone())):(t.enqueue(n),n=e)):e.close()}});return r.addEventListener("ended",a),i.readable.pipeThrough(d).pipeTo(r.writable),r}}class Yi extends ft{get isPlaying(){return!(!this._player||this._player.videoElementStatus!==at.PLAYING)}get processorContext(){return this._processorContext}set processorContext(e){this._processorContext=e}get __className__(){return"LocalVideoTrack"}constructor(e,i,r,n,s,o){if(super(e,s),this.trackMediaType="video",this._player=void 0,this.isUseScaleResolutionDownBy=!1,this._videoVisibleTimer=null,this._statsTimer=null,this._previousVideoVisibleStatus=void 0,this._clearPreviousVideoVisibleStatus=()=>this._previousVideoVisibleStatus=void 0,this._encoderConfig=void 0,this._scalabilityMode={numSpatialLayers:1,numTemporalLayers:1},this._optimizationMode=void 0,this._videoHeight=void 0,this._videoWidth=void 0,this._forceBitrateLimit=void 0,this._enabled=!0,this.processorDestination=void 0,this._processorContext=void 0,c()){const{width:t,height:i}=e.getSettings();this._videoWidth=t,this._videoHeight=i}else this.updateMediaStreamTrackResolution();if(this._encoderConfig=i,this._scalabilityMode=r,this._optimizationMode=n,this._hints=o||[],-1===this._hints.indexOf(Ke.SCREEN_TRACK))this.updateBitrateFromProfile();else if(ie(t.CHROME,115)&&re()){const t=Ji(e);t&&(de.info("local screen video track begin to inject frame"),this._mediaStreamTrack=t)}i&&-1!==this._hints.indexOf(Ke.CUSTOM_TRACK)&&this.setEncoderConfiguration(i),this._processorContext=new Ai(this.getTrackId(),"local"),this.processorDestination=new Ii(this.processorContext),this.bindProcessorDestinationEvents()}play(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("string"==typeof e){const t=document.getElementById(e);t?e=t:(de.warning("[".concat(this.getTrackId(),'] can not find "#').concat(e,'" element, use document.body')),e=document.body)}de.debug("[".concat(this.getTrackId(),"] start video playback in ").concat(e instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement"),JSON.stringify(t));const i=pt(pt(pt({},this._getDefaultPlayerConfig()),t),{},{trackId:this.getTrackId(),element:e});this._player?this._player.updateConfig(i):(e instanceof HTMLVideoElement?this._player=new Ki(i):this._player=new Hi(i),this._player.updateVideoTrack(this._mediaStreamTrack)),this._player.play(),this._videoVisibleTimer&&window.clearInterval(this._videoVisibleTimer),this._clearPreviousVideoVisibleStatus(),this._videoVisibleTimer=window.setInterval((()=>{try{const e=this.getVideoElementVisibleStatus();this.safeEmit(Ze.VIDEO_ELEMENT_VISIBLE_STATUS,e)}catch(e){}}),u("CHECK_VIDEO_VISIBLE_INTERVAL"))}stop(){this._player&&(this._videoVisibleTimer&&(window.clearInterval(this._videoVisibleTimer),this._videoVisibleTimer=null),this._statsTimer&&(this.isUseScaleResolutionDownBy=!1,window.clearInterval(this._statsTimer),this._statsTimer=null),this._clearPreviousVideoVisibleStatus(),this._player.destroy(),this._player=void 0,de.debug("[".concat(this.getTrackId(),"] stop video playback")))}async setEnabled(e,t){if(!t){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(de.info("[".concat(this.getTrackId(),"] start setEnabled"),e),!e){this._originMediaStreamTrack.enabled=!1;try{await b(this,We.NEED_DISABLE_TRACK,this)}catch(e){throw de.error("[".concat(this.getTrackId(),"] setEnabled to false error"),e.toString()),e}return t||(this._enabled=!1),void de.info("[".concat(this.getTrackId(),"] setEnabled to false success"))}this._originMediaStreamTrack.enabled=!0;try{await b(this,We.NEED_ENABLE_TRACK,this)}catch(e){throw de.error("[".concat(this.getTrackId(),"] setEnabled to true error"),e.toString()),e}de.info("[".concat(this.getTrackId(),"] setEnabled to true success")),t||(this._enabled=!0)}async setMuted(e){e!==this._muted&&(this.stateCheck("muted",e),this._muted=e,this._originMediaStreamTrack.enabled=!e,de.debug("[".concat(this.getTrackId(),"] start set muted: ").concat(e)),e?await b(this,We.NEED_MUTE_TRACK,this):await b(this,We.NEED_UNMUTE_TRACK,this))}async setEncoderConfiguration(e,t){if(!this._enabled)throw new _(T.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");if("720p_auto"===e?this.startMonitorStats():this._statsTimer&&(window.clearInterval(this._statsTimer),this._statsTimer=null),e=Ne(e),this._forceBitrateLimit&&(e.bitrateMax=this._forceBitrateLimit.max_bitrate?this._forceBitrateLimit.max_bitrate:e.bitrateMax,e.bitrateMin=this._forceBitrateLimit.min_bitrate?this._forceBitrateLimit.min_bitrate:e.bitrateMin),e.width||e.height||e.frameRate){const t=Li({encoderConfig:e});(c()||A()||w())&&(t.deviceId=void 0),de.debug("[".concat(this.getTrackId(),"] setEncoderConfiguration applyConstraints"),JSON.stringify(e),JSON.stringify(t));try{await this._originMediaStreamTrack.applyConstraints(t),this.updateMediaStreamTrackResolution()}catch(e){const t=new _(T.UNEXPECTED_ERROR,e.toString());throw de.error("[".concat(this.getTrackId(),"] applyConstraints error"),t.toString()),t}}this._encoderConfig=e,-1===this._hints.indexOf(Ke.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await b(this,We.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(de)}}getStats(){K((()=>{de.warning("[deprecated] LocalVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalVideoStats instead")}),"localVideoTrackGetStatsWarning");const e=G(this,We.GET_STATS);return e||pt({},$e)}async setBeautyEffect(e){de.error("LocalVideoTrack.setBeautyEffect was deprecated, please migrate to agora-extension-beauty-effect")}getCurrentFrameData(){return this._player?this._player.getCurrentFrame():new ImageData(2,2)}async getCurrentFrameImage(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return this._player?this._player.getCurrentFrameToUint8Array(e,t):await Bi(e)}async setBitrateLimit(e){if(de.debug("[".concat(this.getTrackId(),"] set bitrate limit, ").concat(JSON.stringify(e))),e){this._forceBitrateLimit=e,this._encoderConfig&&(this._encoderConfig.bitrateMax?this._encoderConfig.bitrateMax=this._encoderConfig.bitrateMax<e.max_bitrate?this._encoderConfig.bitrateMax:e.max_bitrate:this._encoderConfig.bitrateMax=e.max_bitrate,this._encoderConfig.bitrateMin,this._encoderConfig.bitrateMin=e.min_bitrate);try{await b(this,We.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(de)}}}async setOptimizationMode(e){if("motion"!==e&&"detail"!==e&&"balanced"!==e)return void de.error(T.INVALID_PARAMS,"optimization mode must be motion, detail or balanced");const t=this._optimizationMode;try{this._optimizationMode=e,await b(this,We.SET_OPTIMIZATION_MODE,this)}catch(e){throw this._optimizationMode=t,de.error("[".concat(this.getTrackId(),"] set optimization mode failed"),e.toString()),e}de.info("[".concat(this.getTrackId(),"] set optimization mode success (").concat(e,")"))}setScalabiltyMode(e){if(1===e.numSpatialLayers&&1!==e.numTemporalLayers)return de.error(T.INVALID_PARAMS,"scalability mode currently not supported, no SVC."),void(this._scalabilityMode={numSpatialLayers:1,numTemporalLayers:1});this._scalabilityMode=e,de.info("[".concat(this.getTrackId(),"] set scalability mode success (").concat(e,")"))}updateMediaStreamTrackResolution(){zi(this._originMediaStreamTrack).then((e=>{let[t,i]=e;this._videoHeight=i,this._videoWidth=t})).catch($)}_updatePlayerSource(){this._player&&this._player.updateVideoTrack(this._mediaStreamTrack)}_getDefaultPlayerConfig(){return{fit:"contain"}}async setSenderConfiguration(e){if(!this._enabled)throw new _(T.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");de.debug("[".concat(this.getTrackId(),"] setSenderConfiguration applyConstraints"),JSON.stringify(e)),e=Ne(e),this._forceBitrateLimit&&(e.bitrateMax=this._forceBitrateLimit.max_bitrate?this._forceBitrateLimit.max_bitrate:e.bitrateMax,e.bitrateMin=this._forceBitrateLimit.min_bitrate?this._forceBitrateLimit.min_bitrate:e.bitrateMin),this._encoderConfig=e,-1===this._hints.indexOf(Ke.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await b(this,We.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(de)}}updateBitrateFromProfile(){if(!this._encoderConfig)return;const{width:e,height:t,frameRate:i}=this.getMediaStreamTrackSettings();if(!e||!t||!i)return;const{bitrateMax:r,bitrateMin:n}=this._encoderConfig;if(null==n||null==r){const{max:s,min:o}=ji(e,t,i,n,r);this._encoderConfig.bitrateMin=o,this._encoderConfig.bitrateMax=s,de.debug("[".concat(this.getTrackId(),"] update bitrate from profile, [w: ").concat(e,", h: ").concat(t,", fps: ").concat(i,"] => [brMax: ").concat(s,", brMin: ").concat(o,"]"))}}getVideoElementVisibleStatus(){try{var e,t;const i=null==this||null===(e=this._player)||void 0===e?void 0:e.getContainerElement(),r={track:this,element:null==this||null===(t=this._player)||void 0===t?void 0:t.getVideoElement(),slot:null==i?void 0:i.parentElement},{element:n,slot:s}=r;if(this.isPlaying&&n instanceof HTMLVideoElement&&s instanceof HTMLElement){const e=ne.checkOneElementVisible(n),t=Object.assign({},e);if(t.visible!==this._previousVideoVisibleStatus){this._previousVideoVisibleStatus=t.visible;const e=ue.reportApiInvoke(null,{tag:S.TRACER,name:y.LOCAL_VIDEO_TRACK_GET_VIDEO_VISIBLE,options:[this.getTrackId()]});t.visible?e.onSuccess("Video is visible"):e.onSuccess("Invisible because of ".concat(t.reason))}return t}return}catch(e){throw new _(T.GET_VIDEO_ELEMENT_VISIBLE_ERROR,e.message)}}async renewMediaStreamTrack(e){}pipe(e){if(this.processor===e)return e;if(e._source)throw new _(T.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,context:this.processorContext}),e}unpipe(){if(!this.processor)return;const e=this.processor;this.processor._source=void 0,this.processor=void 0,e.reset()}close(){super.close(),this.unbindProcessorDestinationEvents(),this.unbindProcessorContextEvents(),this.unpipe(),this.processorDestination._source&&this.processorDestination._source.unpipe()}clone(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],i=this._encoderConfig;e&&(i=pt(pt({},i),Ne(e))),i=se(i);const r=v(8,"track-video-cloned-"),n=new Yi(t?this._mediaStreamTrack.clone():this._mediaStreamTrack,i,se(this._scalabilityMode),this._optimizationMode,r,se(this._hints));return e&&i&&n.setEncoderConfiguration(i),de.debug("clone video track from ".concat(this.getTrackId()," to ").concat(r,", clone ").concat(t)),n}async replaceTrack(e,t){if(!(e instanceof MediaStreamTrack))throw new _(T.INVALID_PARAMS,"track should be an instance of MediaStreamTrack");if("video"!==e.kind)throw new _(T.INVALID_PARAMS,"track should be a video MediaStreamTrack");await this._updateOriginMediaStreamTrack(e,t,!0),this.updateMediaStreamTrackResolution()}startMonitorStats(){if(!c()&&!A())return;this._statsTimer&&window.clearInterval(this._statsTimer);let e=2,t=Ie[e];let i=-1;let r=Date.now();const n=e=>{e>2||e<0||(r=Date.now(),t=Ie[e],this.setSenderConfiguration(t))};this.isUseScaleResolutionDownBy=!0,this._statsTimer=window.setInterval((()=>{const s=this.getStats(),o=G(this,We.GET_RTC_STATS);if(s.sendPackets>0&&o){-1===i&&(i=Date.now());const a=Date.now();if(a-i<1e3||a-r<u("PROFILE_SWITCH_INTERVAL"))return;const c=s.sendFrameRate,d=.6*t.frameRate,h=.9*t.frameRate;"number"==typeof c&&c>0&&c<d?e>0&&(e--,n(e),de.debug("[".concat(this.getTrackId(),"] step down for fps ").concat(c,", switchProfile to ").concat(e))):o.OutgoingAvailableBandwidth<t.bitrateMin?e>0&&(e--,n(e),de.debug("[".concat(this.getTrackId(),"] step down for OutgoingAvailableBandwidth ").concat(o.OutgoingAvailableBandwidth,", bitrateMin ").concat(t.bitrateMin,", switchProfile to ").concat(e))):"number"==typeof c&&c>h&&e<Ie.length-1&&o.OutgoingAvailableBandwidth>1.2*Ie[e+1].bitrateMin&&(e++,n(e),de.debug("[".concat(this.getTrackId(),"] step up for fps ").concat(c,", OutgoingAvailableBandwidth ").concat(o.OutgoingAvailableBandwidth,", switchProfile to ").concat(e)))}}),u("CHECK_LOCAL_STATS_INTERVAL"))}sendSeiData(e){if(K((()=>{ue.reportApiInvoke(null,{name:y.LOCAL_VIDEO_SEND_SEI_DATA,options:[],tag:S.TRACER}).onSuccess("")}),this._mediaStreamTrack.id||this.getTrackId()),!u("ENABLE_VIDEO_SEI")||!u("ENABLE_ENCODED_TRANSFORM"))return void de.warning('To send/receive SEI, please call AgoraRTC.setParameter("ENABLE_VIDEO_SEI", true) before instantiate IAgoraRtcClient');if(e instanceof Uint8Array==!1)return new _(T.INVALID_PARAMS,"Invalid argument type, ILocalVideoTrack.sendSeiData() only accept Uint8Array argument.").throw();const t=this.getRTCRtpTransceiver();if(!t)return void de.warning("Video track is not published, SEI can not be send");const i=t.sender.getParameters();if(0===i.codecs.length)return;const r=i.codecs[0].mimeType.toLocaleLowerCase();"video/h264"===r?this.safeEmit("sei-to-send",e):de.warning("SEI is not supported by ".concat(r))}bindProcessorDestinationEvents(){this.processorDestination.on(rt.ON_TRACK,(async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(),await b(this,We.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await b(this,We.NEED_REPLACE_TRACK,this))}))}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(rt.ON_TRACK)}unbindProcessorContextEvents(){this.processorContext.removeAllListeners(nt.REQUEST_UPDATE_CONSTRAINTS),this.processorContext.removeAllListeners(nt.REQUEST_CONSTRAINTS)}}gt([le({argsMap:(e,t,i)=>[e.getTrackId(),"string"==typeof t?t:t instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement",i]}),bi(),_t("design:type",Function),_t("design:paramtypes",[Object,Object]),_t("design:returntype",void 0)],Yi.prototype,"play",null),gt([le({argsMap:e=>[e.getTrackId()]}),_t("design:type",Function),_t("design:paramtypes",[]),_t("design:returntype",void 0)],Yi.prototype,"stop",null),gt([W("LocalVideoTrack","_enabledMutex"),le({argsMap:(e,t)=>[e.getTrackId(),t]}),bi(),_t("design:type",Function),_t("design:paramtypes",[Boolean,Boolean]),_t("design:returntype",Promise)],Yi.prototype,"setEnabled",null),gt([W("LocalVideoTrack","_enabledMutex"),le({argsMap:(e,t)=>[e.getTrackId(),t]}),bi(),_t("design:type",Function),_t("design:paramtypes",[Boolean]),_t("design:returntype",Promise)],Yi.prototype,"setMuted",null),gt([le({argsMap:(e,t)=>[e.getTrackId(),t]}),bi(),_t("design:type",Function),_t("design:paramtypes",[Object,Boolean]),_t("design:returntype",Promise)],Yi.prototype,"setEncoderConfiguration",null),gt([bi(),_t("design:type",Function),_t("design:paramtypes",[]),_t("design:returntype",Object)],Yi.prototype,"getStats",null),gt([le({argsMap:(e,t,i)=>[e.getTrackId(),t,i]}),bi(),_t("design:type",Function),_t("design:paramtypes",[Boolean,Object]),_t("design:returntype",Promise)],Yi.prototype,"setBeautyEffect",null),gt([bi(),_t("design:type",Function),_t("design:paramtypes",[]),_t("design:returntype",ImageData)],Yi.prototype,"getCurrentFrameData",null),gt([bi(),_t("design:type",Function),_t("design:paramtypes",[String,Number]),_t("design:returntype",Promise)],Yi.prototype,"getCurrentFrameImage",null),gt([bi(),_t("design:type",Function),_t("design:paramtypes",[Object]),_t("design:returntype",Promise)],Yi.prototype,"setBitrateLimit",null),gt([bi(),_t("design:type",Function),_t("design:paramtypes",[String]),_t("design:returntype",Promise)],Yi.prototype,"setOptimizationMode",null),gt([bi(),_t("design:type",Function),_t("design:paramtypes",[Object]),_t("design:returntype",void 0)],Yi.prototype,"setScalabiltyMode",null),gt([bi(),_t("design:type",Function),_t("design:paramtypes",[]),_t("design:returntype",void 0)],Yi.prototype,"updateMediaStreamTrackResolution",null),gt([le({argsMap:(e,t)=>[e.getTrackId(),t.name]}),_t("design:type",Function),_t("design:paramtypes",[Object]),_t("design:returntype",Object)],Yi.prototype,"pipe",null),gt([le({argsMap:e=>[e.getTrackId()]}),_t("design:type",Function),_t("design:paramtypes",[]),_t("design:returntype",void 0)],Yi.prototype,"unpipe",null),gt([le({argsMap:e=>[e.getTrackId()]}),_t("design:type",Function),_t("design:paramtypes",[]),_t("design:returntype",void 0)],Yi.prototype,"close",null),gt([le({argsMap:(e,t,i)=>[e.getTrackId(),t.label,i]}),_t("design:type",Function),_t("design:paramtypes",[MediaStreamTrack,Boolean]),_t("design:returntype",Promise)],Yi.prototype,"replaceTrack",null),gt([le(),_t("design:type",Function),_t("design:paramtypes",[]),_t("design:returntype",void 0)],Yi.prototype,"startMonitorStats",null);class Xi extends Yi{get __className__(){return"CameraVideoTrack"}constructor(e,t,i,r,n,s){super(e,Ne(t.encoderConfig),r,n,s),this._config=void 0,this._originalConstraints=void 0,this._constraints=void 0,this._enabled=!0,this._deviceName="default",this.tryResumeVideoForIOS15_16WeChat=async()=>{(U()||H())&&!oe()&&ae()&&this._enabled&&!this._isClosed&&(de.debug("[".concat(this.getTrackId(),"] try capture camera media device for interrupted iOS 15 device on WeChat.")),await this.renewMediaStreamTrack())},this._config=t,this._originalConstraints=i,this._constraints=i,this._deviceName=e.label,this._encoderConfig=Ne(this._config.encoderConfig),yt.on(Ee.IOS_15_16_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),yt.on(Ee.IOS_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),this.bindProcessorContextEvents()}async setDevice(e){return"string"==typeof e?this._setDeviceById(e):e.deviceId?this._setDeviceById(e.deviceId):e.facingMode?this._setDeviceByFacingModel(e.facingMode):void 0}async _setDeviceById(e){if(de.info("[".concat(this.getTrackId(),"] set device to ").concat(e)),this._enabled)try{const t=await _i(e),i={};i.video=pt({},this._constraints),i.video.deviceId={exact:e},i.video.facingMode=void 0,this._originMediaStreamTrack.stop();let r=null;try{r=await Kt(i,this.getTrackId())}catch(e){throw de.error("[".concat(this.getTrackId(),"] setDevice failed"),e.toString()),r=await Kt({video:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(r.getVideoTracks()[0],!1),e}await this._updateOriginMediaStreamTrack(r.getVideoTracks()[0],!1),this.updateMediaStreamTrackResolution(),this._deviceName=t.label,this._config.cameraId=e,this._constraints.deviceId={exact:e}}catch(e){throw de.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}else try{const t=await _i(e);this._deviceName=t.label,this._config.cameraId=e,this._constraints.deviceId={exact:e}}catch(e){throw de.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}de.info("[".concat(this.getTrackId(),"] setDevice success"))}async _setDeviceByFacingModel(e){de.info("[".concat(this.getTrackId(),"] set facingMode ").concat(e));const t={video:pt(pt({},this._constraints),{},{deviceId:void 0,facingMode:{exact:e}})};if(this._enabled){this._originMediaStreamTrack.stop();let e=null;try{e=await Kt(t,this.getTrackId())}catch(t){throw de.error("[".concat(this.getTrackId(),"] setDeviceByFacingModel failed"),t.toString()),e=await Kt({video:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!1),t}await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!1),this.updateMediaStreamTrackResolution()}this._deviceName="",this._config.facingMode=e,this._config.cameraId=void 0,this._constraints=pt({},t.video),de.info("[".concat(this.getTrackId(),"] setDeviceByFacingModel success"))}async setEnabled(e,t){if(!t){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(de.info("[".concat(this.getTrackId(),"] start setEnabled"),e),e){try{if(this.isExternalTrack)this._originMediaStreamTrack.enabled=!0;else{const e=await Kt({video:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!1)}await b(this,We.NEED_ENABLE_TRACK,this)}catch(e){throw de.error("[".concat(this.getTrackId(),"] setEnabled true error"),e.toString()),e}this.updateMediaStreamTrackResolution(),de.info("[".concat(this.getTrackId(),"] setEnabled to true success")),t||(this._enabled=!0)}else{this.isExternalTrack?this._originMediaStreamTrack.enabled=!1:(this._originMediaStreamTrack.onended=null,this._originMediaStreamTrack.stop()),t||(this._enabled=!1);try{await b(this,We.NEED_DISABLE_TRACK,this)}catch(e){throw de.error("[".concat(this.getTrackId(),"] setEnabled to false error"),e.toString()),e}de.info("[".concat(this.getTrackId(),"] setEnabled to false success"))}}async setEncoderConfiguration(e,t){if(!this._enabled)throw new _(T.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");"720p_auto"===e?this.startMonitorStats():this._statsTimer&&(window.clearInterval(this._statsTimer),this._statsTimer=null),e=Ne(e),this._forceBitrateLimit&&(e.bitrateMax=this._forceBitrateLimit.max_bitrate?this._forceBitrateLimit.max_bitrate:e.bitrateMax,e.bitrateMin=this._forceBitrateLimit.min_bitrate?this._forceBitrateLimit.min_bitrate:e.bitrateMin);const i=ce(this._config);i.encoderConfig=e;const r=Li(i);(c()||A()||w())&&(r.deviceId=void 0),de.debug("[".concat(this.getTrackId(),"] setEncoderConfiguration applyConstraints"),JSON.stringify(e),JSON.stringify(r));try{await this._originMediaStreamTrack.applyConstraints(r),this.updateMediaStreamTrackResolution()}catch(e){const t=new _(T.UNEXPECTED_ERROR,e.toString());throw de.error("[".concat(this.getTrackId(),"] applyConstraints error"),t.toString()),t}this._config=i,this._constraints=r,this._originalConstraints=r,this._encoderConfig=e,-1===this._hints.indexOf(Ke.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await b(this,We.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(de)}}_getDefaultPlayerConfig(){return{mirror:!0,fit:"cover"}}onTrackEnded(){if((A()||w())&&this._enabled&&!this._isClosed&&yt.duringInterruption){const e=async()=>{yt.off(Ee.IOS_INTERRUPTION_END,e),this._enabled&&!this._isClosed&&(de.debug("[".concat(this.getTrackId(),"] try capture camera media device for interrupted iOS device.")),await this.setEnabled(!1),await this.setEnabled(!0))};yt.on(Ee.IOS_INTERRUPTION_END,e)}else de.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(Ze.TRACK_ENDED)}async renewMediaStreamTrack(e){const t=e||this._constraints,i=Ti(this._deviceName);if(i&&!t.deviceId&&(t.deviceId={exact:i}),this._enabled){const e=await Kt({video:t},this.getTrackId());this._constraints=t,await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!0),this.updateMediaStreamTrackResolution()}}close(){super.close(),yt.off(Ee.IOS_15_16_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),yt.off(Ee.IOS_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat)}clone(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],i=this._encoderConfig;e&&(i=pt(pt({},i),Ne(e))),i=se(i);const r=v(8,"track-cam-cloned-"),n=new Xi(t?this._mediaStreamTrack.clone():this._mediaStreamTrack,se(pt(pt({},this._config),{},{encoderConfig:i})),se(this._constraints),se(this._scalabilityMode),this._optimizationMode,r);return e&&i&&n.setEncoderConfiguration(i),de.debug("clone track from ".concat(this.getTrackId()," to ").concat(r,", clone ").concat(t)),n}bindProcessorContextEvents(){this.processorContext.on(nt.REQUEST_UPDATE_CONSTRAINTS,(async(e,t,i)=>{try{const i=Object.assign({},this._originalConstraints,...e);await this.renewMediaStreamTrack(i),t()}catch(e){i(e)}})),this.processorContext.on(nt.REQUEST_CONSTRAINTS,(async e=>{e(this._originMediaStreamTrack.getSettings())}))}}function Qi(e){const t=ue.reportApiInvoke(null,{tag:S.TRACER,name:y.CREATE_CUSTOM_AUDIO_TRACK,options:[e]}),i=new Di(e.mediaStreamTrack,e.encoderConfig?Oe(e.encoderConfig):{},v(8,"track-cus-"),!1);return de.info("create custom audio track success with config",e,"trackId",i.getTrackId()),t.onSuccess(i.getTrackId()),i}async function qi(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const t=ue.reportApiInvoke(null,{tag:S.TRACER,name:y.CREATE_MIC_AUDIO_TRACK,options:[e]}),i=xi(e),r=v(8,"track-mic-");let n=null;de.info("start create microphone audio track with config",JSON.stringify(e),"trackId",r);try{n=(await Kt({audio:i},r)).getAudioTracks()[0]||null}catch(e){throw t.onError(e),e}if(!n){const e=new _(T.UNEXPECTED_ERROR,"can not find track in media stream");return t.onError(e),e.throw(de)}const s=new Oi(n,e,i,r);return t.onSuccess(s.getTrackId()),de.info("create microphone audio track success, trackId:",r),s}async function $i(e){var t;const{cacheOnlineFile:i,encoderConfig:r}=e;let{source:n}=e;const s={source:n instanceof AudioBuffer?"AudioBuffer":n instanceof File?null!==(t=File.name)&&void 0!==t?t:"File":n,cacheOnlineFile:i,encoderConfig:r},o=ue.reportApiInvoke(null,{tag:S.TRACER,name:y.CREATE_BUFFER_AUDIO_TRACK,options:[s]});if(u("DISABLE_WEBAUDIO"))throw new _(T.NOT_SUPPORTED,"can not create BufferSourceAudioTrack when WebAudio disabled");const a=v(8,"track-buf-");de.info("start create buffer source audio track with config",JSON.stringify(s),"trackId",a);const c=n;if(!(n instanceof AudioBuffer))try{n=await async function(e,t){let i=null;if("string"==typeof e){const t=Fi.get(e);if(t)return de.debug("use cached audio resource: ",e),t;try{i=(await Y((()=>pe.get(e,{responseType:"arraybuffer"})),void 0,void 0,{maxRetryCount:3})).data}catch(e){throw new _(T.FETCH_AUDIO_FILE_FAILED,e.toString())}}else{const t=new Promise(((t,i)=>{const r=new FileReader;r.onload=e=>{e.target?t(e.target.result):i(new _(T.READ_LOCAL_AUDIO_FILE_ERROR))},r.onerror=()=>{i(new _(T.READ_LOCAL_AUDIO_FILE_ERROR))},r.readAsArrayBuffer(e)}));i=await t}const r=await At(i);return"string"==typeof e&&t&&Fi.set(e,r),r}(n,i)}catch(e){return o.onError(e),e.throw(de)}const d=new Ui(n),h=new Mi(c,d,r?Oe(r):{},a);return de.info("create buffer source audio track success, trackId:",a),o.onSuccess(h.getTrackId()),h}function er(e){const t=new Pi;return e.forEach((e=>t.addAudioTrack(e))),t}function tr(e){const t=ue.reportApiInvoke(null,{tag:S.TRACER,name:y.CREATE_CUSTOM_VIDEO_TRACK,options:[e]}),i=new Yi(e.mediaStreamTrack,{width:e.width,height:e.height,frameRate:e.frameRate,bitrateMax:e.bitrateMax,bitrateMin:e.bitrateMin},e.scalabiltyMode?Ce(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,v(8,"track-cus-"),[Ke.CUSTOM_TRACK]);return t.onSuccess(i.getTrackId()),de.info("create custom video track success with config",e,"trackId",i.getTrackId()),i}async function ir(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const t=ue.reportApiInvoke(null,{tag:S.TRACER,name:y.CREATE_CAM_VIDEO_TRACK,options:[pt({},e)]}),i=Li(e),r=v(8,"track-cam-");let n=null;const s="720p_auto"===e.encoderConfig;de.info("start create camera video track with config",JSON.stringify(e),"trackId",r);try{n=(await Kt({video:i},r)).getVideoTracks()[0]||null}catch(e){throw t.onError(e),e}if(!n){const e=new _(T.UNEXPECTED_ERROR,"can not find track in media stream");return t.onError(e),e.throw(de)}e.optimizationMode&&sr(r,n,e,Ne(e.encoderConfig));const o=new Xi(n,e,i,e.scalabiltyMode?Ce(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,r);return s&&o.startMonitorStats(),t.onSuccess(o.getTrackId()),de.info("create camera video success, trackId:",r),o}async function rr(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=ue.reportApiInvoke(null,{tag:S.TRACER,name:y.CREATE_MIC_AND_CAM_TRACKS,options:[e,t]}),r="720p_auto"===t.encoderConfig,n=Li(t),s=xi(e),o=v(8,"track-mic-"),a=v(8,"track-cam-");let c=null,d=null;de.info("start create camera video track(".concat(a,") and microphone audio track(").concat(o,") with config, audio: ").concat(JSON.stringify(e),", video: ").concat(JSON.stringify(t)));try{const e=await Kt({audio:s,video:n},"".concat(o,"-").concat(a));c=e.getAudioTracks()[0],d=e.getVideoTracks()[0]}catch(e){throw i.onError(e),e}if(!c||!d){const e=new _(T.UNEXPECTED_ERROR,"can not find tracks in media stream");return i.onError(e),e.throw(de)}t.optimizationMode&&sr(a,d,t,Ne(t.encoderConfig));const u=new Oi(c,e,s,o),h=new Xi(d,t,n,t.scalabiltyMode?Ce(t.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},t.optimizationMode,a);return r&&h.startMonitorStats(),i.onSuccess([u.getTrackId(),h.getTrackId()]),de.info("create camera video track(".concat(a,") and microphone audio track(").concat(o,") success")),[u,h]}async function nr(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"disable";const i=ue.reportApiInvoke(null,{tag:S.TRACER,name:y.CREATE_SCREEN_VIDEO_TRACK,options:[pt({},e),t]}),r="720p_auto"===e.encoderConfig;e.encoderConfig?"string"==typeof e.encoderConfig||e.encoderConfig.width&&e.encoderConfig.height||(e.encoderConfig.width={max:1920},e.encoderConfig.height={max:1080}):e.encoderConfig="1080p_2";const n=Vi(e),s=v(8,"track-scr-v-");let o=null,a=null;const c=fe();if(!c.supportShareAudio&&"enable"===t){const e=new _(T.NOT_SUPPORTED,"your browser or platform is not support share-screen with audio");return i.onError(e),e.throw(de)}de.info("start create screen video track with config",e,"withAudio",t,"trackId",s);try{const e=await Kt({screen:n,screenAudio:"auto"===t?c.supportShareAudio:"enable"===t},s);o=e.getVideoTracks()[0]||null,a=e.getAudioTracks()[0]||null}catch(e){throw i.onError(e),e}if(!o){const e=new _(T.UNEXPECTED_ERROR,"can not find track in media stream");return i.onError(e),e.throw(de)}if(!a&&"enable"===t){o&&o.stop();const e=new _(T.SHARE_AUDIO_NOT_ALLOWED);return i.onError(e),e.throw(de)}if(e.optimizationMode||(e.optimizationMode="detail"),e.optimizationMode){sr(s,o,e,e.encoderConfig&&Re(e.encoderConfig)||void 0),e.encoderConfig&&"string"!=typeof e.encoderConfig&&(e.encoderConfig.bitrateMin=e.encoderConfig.bitrateMax)}const d=new Yi(o,e.encoderConfig?Re(e.encoderConfig):{},e.scalabiltyMode?Ce(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,s,[Ke.SCREEN_TRACK]);if(r&&d.startMonitorStats(),!a)return i.onSuccess(d.getTrackId()),de.info("create screen video track success","video:",d.getTrackId()),d;const u=new Di(a,void 0,v(8,"track-scr-a-"),!1);return i.onSuccess([d.getTrackId(),u.getTrackId()]),de.info("create screen video track success","video:",d.getTrackId(),"audio:",u.getTrackId()),[d,u]}function sr(e,t,i,r){i.optimizationMode&&(r&&r.width&&r.height?(i.encoderConfig=pt(pt({},r),{},{bitrateMin:r.bitrateMin,bitrateMax:r.bitrateMax}),"motion"!==i.optimizationMode&&"detail"!==i.optimizationMode||(t.contentHint=i.optimizationMode,t.contentHint===i.optimizationMode?de.debug("[".concat(e,"] set content hint to"),i.optimizationMode):de.debug("[".concat(e,"] set content hint failed")))):de.warning("[".concat(e,"] can not apply optimization mode bitrate config, no encoderConfig")))}gt([le({argsMap:(e,t)=>[e.getTrackId(),t]}),bi(),_t("design:type",Function),_t("design:paramtypes",[Object]),_t("design:returntype",Promise)],Xi.prototype,"setDevice",null),gt([W("CameraVideoTrack","_enabledMutex"),le({argsMap:(e,t)=>[e.getTrackId(),t]}),bi(),_t("design:type",Function),_t("design:paramtypes",[Boolean,Boolean]),_t("design:returntype",Promise)],Xi.prototype,"setEnabled",null),gt([le({argsMap:(e,t)=>[e.getTrackId(),t]}),bi(),_t("design:type",Function),_t("design:paramtypes",[Object,Boolean]),_t("design:returntype",Promise)],Xi.prototype,"setEncoderConfiguration",null),gt([le({argsMap:e=>[e.getTrackId()]}),_t("design:type",Function),_t("design:paramtypes",[]),_t("design:returntype",void 0)],Xi.prototype,"close",null);class or extends Tt{getUserId(){return this._userId}constructor(e,t,i,r){super(e,"track-".concat(e.kind,"-").concat(t,"-").concat(r.clientId,"_").concat(v(5,""))),this._userId=void 0,this._uintId=void 0,this._isDestroyed=!1,this.store=void 0,this.processor=void 0,this._userId=t,this._uintId=i,this.store=r}_updateOriginMediaStreamTrack(e){this._originMediaStreamTrack=e,this._mediaStreamTrack=e,this._updatePlayerSource(),this.processor&&this.processor.updateInput({track:this._originMediaStreamTrack,context:this.processorContext})}_destroy(){this._isDestroyed=!0,de.info("[".concat(this.getTrackId(),"] is destroyed")),this.stop(),super.close()}getProcessorStats(){return this.processorContext.gatherStats()}getProcessorUsage(){return this.processorContext.gatherUsage()}}class ar extends or{get isPlaying(){return!(!this._player||this._player.videoElementStatus!==at.PLAYING)}get __className__(){return"RemoteVideoTrack"}constructor(e,t,i,r){super(e,t,i,r),this._videoVisibleTimer=null,this._previousVideoVisibleStatus=void 0,this._clearPreviousVideoVisibleStatus=()=>this._previousVideoVisibleStatus=void 0,this.trackMediaType="video",this._videoWidth=void 0,this._videoHeight=void 0,this._player=void 0,this.processorDestination=void 0,this.processorContext=void 0,this.updateMediaStreamTrackResolution(),this.processorContext=new Ai(this.getTrackId(),"remote"),this.processorDestination=new Ii(this.processorContext),this.bindProcessorDestinationEvents()}getStats(){K((()=>{de.warning("[deprecated] RemoteVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteVideoStats instead")}),"remoteVideoTrackGetStatsWarning");return G(this,We.GET_STATS)||pt({},it)}play(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("string"==typeof e){const t=document.getElementById(e);t?e=t:(de.warning("[".concat(this.getTrackId(),'] can not find "#').concat(e,'" element, use document.body')),e=document.body)}de.debug("[".concat(this.getTrackId(),"] start video playback in ").concat(e instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement"),JSON.stringify(t));const i=pt(pt({fit:"cover"},t),{},{trackId:this.getTrackId(),element:e});this._player?this._player.updateConfig(i):(e instanceof HTMLVideoElement?this._player=new Ki(i):this._player=new Hi(i),this._player.updateVideoTrack(this._mediaStreamTrack),this._player.onFirstVideoFrameDecoded=()=>{this.store.subscribe(this.getUserId(),"video",void 0,void 0,Date.now()),this.safeEmit(Je.FIRST_FRAME_DECODED)},this._player.onVideoStateChanged=e=>{this.safeEmit(Je.VIDEO_STATE_CHANGED,e)}),this._player.play(this.store.sessionId||void 0),this._videoVisibleTimer&&window.clearInterval(this._videoVisibleTimer),this._clearPreviousVideoVisibleStatus(),this._videoVisibleTimer=window.setInterval((()=>{try{const e=this.getVideoElementVisibleStatus();this.safeEmit(Je.VIDEO_ELEMENT_VISIBLE_STATUS,e)}catch(e){}}),u("CHECK_VIDEO_VISIBLE_INTERVAL"))}stop(){this._player&&(this._videoVisibleTimer&&(window.clearInterval(this._videoVisibleTimer),this._videoVisibleTimer=null),this._clearPreviousVideoVisibleStatus(),this._player.destroy(),this._player=void 0,de.debug("[".concat(this.getTrackId(),"] stop video playback")))}getCurrentFrameData(){return this._player?this._player.getCurrentFrame():new ImageData(2,2)}updateMediaStreamTrackResolution(){zi(this._originMediaStreamTrack).then((e=>{let[t,i]=e;this._videoHeight=i,this._videoWidth=t})).catch($)}_updatePlayerSource(){de.debug("[".concat(this.getTrackId(),"] update player source track")),this._player&&this._player.updateVideoTrack(this._mediaStreamTrack)}getVideoElementVisibleStatus(){try{var e,t;const i=null==this||null===(e=this._player)||void 0===e?void 0:e.getContainerElement(),r={track:this,element:null==this||null===(t=this._player)||void 0===t?void 0:t.getVideoElement(),slot:null==i?void 0:i.parentElement},{element:n,slot:s}=r;if(this.isPlaying&&n instanceof HTMLVideoElement&&s instanceof HTMLElement){const e=ne.checkOneElementVisible(n),t=Object.assign({},e);if(t.visible!==this._previousVideoVisibleStatus){this._previousVideoVisibleStatus=t.visible;const e=ue.reportApiInvoke(null,{tag:S.TRACER,name:y.REMOTE_VIDEO_TRACK_GET_VIDEO_VISIBLE,options:[this.getTrackId()]});t.visible?e.onSuccess("Video is visible"):e.onSuccess("Invisible because of ".concat(t.reason))}return t}return}catch(e){throw new _(T.GET_VIDEO_ELEMENT_VISIBLE_ERROR,e.message)}}pipe(e){if(this.processor===e)return e;if(e._source)throw new _(T.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,context:this.processorContext}),e}unpipe(){if(!this.processor)return;const e=this.processor;this.processor._source=void 0,this.processor=void 0,e.reset()}bindProcessorDestinationEvents(){this.processorDestination.on(rt.ON_TRACK,(async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource()):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource())}))}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(rt.ON_TRACK)}_destroy(){super._destroy(),this.unbindProcessorDestinationEvents()}_onSei(e){this.emit(je.SEI_RECEIVED,e)}}gt([le({argsMap:(e,t,i)=>[e.getTrackId(),"string"==typeof t?t:t instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement",i]}),_t("design:type",Function),_t("design:paramtypes",[Object,Object]),_t("design:returntype",void 0)],ar.prototype,"play",null),gt([le({argsMap:e=>[e.getTrackId()]}),_t("design:type",Function),_t("design:paramtypes",[]),_t("design:returntype",void 0)],ar.prototype,"stop",null),gt([le({argsMap:(e,t)=>[e.getTrackId(),t.name]}),_t("design:type",Function),_t("design:paramtypes",[Object]),_t("design:returntype",Object)],ar.prototype,"pipe",null),gt([le({argsMap:e=>[e.getTrackId()]}),_t("design:type",Function),_t("design:paramtypes",[]),_t("design:returntype",void 0)],ar.prototype,"unpipe",null);class cr extends or{get isPlaying(){return this._useAudioElement?ki.isPlaying(this.getTrackId()):this._source.isPlayed}get __className__(){return"RemoteAudioTrack"}constructor(e,t,i,r){super(e,t,i,r),this.trackMediaType="audio",this._source=void 0,this._useAudioElement=!0,this._volume=100,this.processorContext=void 0,this.processorDestination=void 0,this._played=!1,this._bypassWebAudio=!1,u("DISABLE_WEBAUDIO")?(this._source=new Ri,this._bypassWebAudio=!0,this._useAudioElement=!0):(this._source=new Lt(e,!0),u("REMOTE_AUDIO_TRACK_USES_WEB_AUDIO")&&(this._useAudioElement=!1)),this._source.once(Ye.RECEIVE_TRACK_BUFFER,(()=>{this.safeEmit(Je.FIRST_FRAME_DECODED)})),this.processorContext=new Ni(this._source.context,this.getTrackId(),"remote"),this.processorDestination=new wi(this.processorContext),this.bindProcessorDestinationEvents(),this._source.on(Ye.UPDATE_SOURCE,(()=>{this.processor&&this.processor.updateInput({node:this._source.processSourceNode,context:this.processorContext})}))}setAudioFrameCallback(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:4096;if(!e)return this._source.removeAllListeners(Ye.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(t),this._source.removeAllListeners(Ye.ON_AUDIO_BUFFER),this._source.on(Ye.ON_AUDIO_BUFFER,(t=>e(t)))}setVolume(e){this._volume=e,this._useAudioElement?ki.setVolume(this.getTrackId(),e):this._source.setVolume(e/100)}async setPlaybackDevice(e){if(!this._useAudioElement||!O()&&u("RESTRICTION_SET_PLAYBACK_DEVICE"))throw new _(T.NOT_SUPPORTED,"your browser does not support setting the audio output device");await ki.setSinkID(this.getTrackId(),e)}getVolumeLevel(){return this._source.getAccurateVolumeLevel()}getStats(){K((()=>{de.warning("[deprecated] RemoteAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteAudioStats instead")}),"remoteAudioTrackGetStatsWarning");return G(this,We.GET_STATS)||pt({},et)}play(){de.debug("[".concat(this.getTrackId(),"] start audio playback")),this._played=!0,this._useAudioElement?(de.debug("[".concat(this.getTrackId(),"] use audio element to play")),ki.play(this._mediaStreamTrack,this.getTrackId(),this._volume,this.store.sessionId||void 0)):this._source.play()}stop(){de.debug("[".concat(this.getTrackId(),"] stop audio playback")),this._played=!1,this._useAudioElement?ki.stop(this.getTrackId()):this._source.stop()}_destroy(){super._destroy(),this._played=!1,this.unbindProcessorDestinationEvents(),this._source.destroy()}_isFreeze(){return this._source.isFreeze}_updatePlayerSource(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];de.debug("[".concat(this.getTrackId(),"] update player source track")),e&&this._source.updateTrack(this._mediaStreamTrack),this._useAudioElement&&ki.updateTrack(this.getTrackId(),this._mediaStreamTrack)}pipe(e){if(this._bypassWebAudio)throw new _(T.NOT_SUPPORTED,"can not pipe extension when WebAudio disabled");if(this.processor===e)return e;if(e._source)throw new _(T.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,node:this._source.processSourceNode,context:this.processorContext}),e}unpipe(){var e;if(this._bypassWebAudio)throw new _(T.NOT_SUPPORTED,"can not unpipe extension when WebAudio disabled");if(!this.processor)return;const t=this.processor;null===(e=this._source.processSourceNode)||void 0===e||e.disconnect(),this.processor._source=!1,this.processor=void 0,t.reset()}bindProcessorDestinationEvents(){this.processorDestination.on(rt.ON_TRACK,(async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(!1),this._source.processedNode=this._source.createMediaStreamSourceNode(e)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource())})),this.processorDestination.on(rt.ON_NODE,(e=>{this._source.processedNode=e;const t=!e;this._useAudioElement!==t&&(this._played?(this.stop(),this._useAudioElement=t,this.play()):this._useAudioElement=t)}))}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(rt.ON_TRACK),this.processorDestination.removeAllListeners(rt.ON_NODE)}}gt([le({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),_t("design:type",Function),_t("design:paramtypes",[Number]),_t("design:returntype",void 0)],cr.prototype,"setVolume",null),gt([le({argsMap:(e,t)=>[e.getTrackId(),t]}),_t("design:type",Function),_t("design:paramtypes",[String]),_t("design:returntype",Promise)],cr.prototype,"setPlaybackDevice",null),gt([le({argsMap:e=>[e.getTrackId()]}),_t("design:type",Function),_t("design:paramtypes",[]),_t("design:returntype",void 0)],cr.prototype,"play",null),gt([le({argsMap:e=>[e.getTrackId()]}),_t("design:type",Function),_t("design:paramtypes",[]),_t("design:returntype",void 0)],cr.prototype,"stop",null),gt([le({argsMap:(e,t)=>[e.getTrackId(),t.name]}),_t("design:type",Function),_t("design:paramtypes",[Object]),_t("design:returntype",Object)],cr.prototype,"pipe",null),gt([le({argsMap:e=>[e.getTrackId()]}),_t("design:type",Function),_t("design:paramtypes",[]),_t("design:returntype",void 0)],cr.prototype,"unpipe",null);const dr=new class extends E{get visibility(){return document.visibilityState}get lastHiddenTime(){return this._lastHiddenTime}get lastVisibleTime(){return this._lastVisibleTime}constructor(){super(),this._lastHiddenTime=0,this._lastVisibleTime=0,document.addEventListener("visibilitychange",(()=>{"hidden"===document.visibilityState?this._lastHiddenTime=performance.now():this._lastVisibleTime=performance.now(),de.debug("document visibility went ".concat(document.visibilityState)),this.emit("VISIBILITY_CHANGE",document.visibilityState)}))}};var ur;!function(e){e[e.ONE_BYTE=0]="ONE_BYTE",e[e.TWO_BYTE=1]="TWO_BYTE"}(ur||(ur={}));class hr{constructor(){this._sequence=0,this._startTime=Date.now(),this.isUseOneByte=!0}get startTime(){const e=Date.now()-this._startTime;return e<Math.pow(2,16)?e:(this._startTime+=Math.pow(2,16),this.startTime)}get sequence(){return this._sequence<Math.pow(2,32)?this._sequence++:(this._sequence-=Math.pow(2,32),this.sequence)}serialize(e){const t={commonPacketHeader:{length:0,reserved:0,extension:0,sequence:this.sequence},commonStreamHeader:this.startTime,extension:void 0,payload:e};if(e.byteLength>128){const i=new Uint8Array(4);i.set([1,0,0,0]);const r={id:0,length:4,data:i.buffer},n={profile:this.isUseOneByte?0:1,length:this.isUseOneByte?5:6,datas:[r]};t.commonPacketHeader.extension=1,t.extension=n,t.payload=this.compress(e),t.commonPacketHeader.length=8+(t.extension.length+2)+t.payload.byteLength}else t.commonPacketHeader.length=8+t.payload.byteLength;u("SHOW_DATASTREAM2_LOG")&&de.debug("send data header: ".concat(JSON.stringify(t.commonPacketHeader)));const i=new ArrayBuffer(t.commonPacketHeader.length),r=new Uint8Array(i),n=new DataView(i);let s=0;if(n.setUint16(s,t.commonPacketHeader.extension<<15|t.commonPacketHeader.reserved<<14|t.commonPacketHeader.length,!0),s+=2,n.setUint32(s,t.commonPacketHeader.sequence,!0),s+=4,n.setUint16(s,t.commonStreamHeader,!0),s+=2,t.extension){const e=this.serializeExtension(t.extension);r.set(new Uint8Array(e),s),s+=e.byteLength}if(r.set(new Uint8Array(t.payload),s),s+=t.payload.byteLength,s!==t.commonPacketHeader.length)throw Error("serialize error!");return i}deserialize(e){if(e.byteLength<4)return new ArrayBuffer(0);const t=new DataView(e);let i=0;const r=t.getUint16(i,!0);i+=2;const n={length:16383&r,reserved:(16384&r)>>14,extension:(32768&r)>>15,sequence:t.getUint16(i+2,!0)<<16|t.getUint16(i,!0)};let s,o;if(i+=4,u("SHOW_DATASTREAM2_LOG")&&de.debug("receive data header: ".concat(JSON.stringify(n))),t.getUint16(i,!0),i+=2,n.extension){o=this.deserializeExtension(e.slice(i)),i+=2+o.length,s=e.slice(i);let t=!1;if(o.datas.length>0){const e=o.datas.find((e=>0===e.id));if(e){t=1==(1&new DataView(e.data).getUint32(0,!0))}}s=t?this.decompress(s):s}else s=e.slice(8);return s}serializeExtension(e){const{profile:t,length:i,datas:r}=e,n=new ArrayBuffer(i+2),s=new Uint8Array(n),o=new DataView(n);let a=0;if(o.setUint8(a++,t),o.setUint8(a++,i),r.forEach((e=>{t?(o.setUint8(a++,e.id),o.setUint8(a++,e.length),s.set(new Uint8Array(e.data),a),a+=e.data.byteLength):(o.setUint8(a++,e.id|e.length<<4),s.set(new Uint8Array(e.data),a),a+=e.data.byteLength)})),a!==i+2)throw Error("serialize extension error, is ".concat(a,"!==").concat(i+2));return n}deserializeExtension(e){const t=new DataView(e);let i=0;const r=t.getUint8(i);i++;const n=t.getUint8(i);i++;const s=r===ur.TWO_BYTE,o=[],a=new DataView(e,2);let c=0;for(;c<n;){let e=0,t=0,i=new ArrayBuffer(0);s?(e=a.getUint8(c),c++,t=a.getUint8(c),c++):(e=15&a.getUint8(c),t=a.getUint8(c)>>4,c++),t>0&&(i=a.buffer.slice(c+2,c+2+t),c+=i.byteLength),o.push({id:e,length:t,data:i})}if(c!==n)throw Error("parse error");return{profile:r,length:n,datas:o}}decompress(e){return me(new Uint8Array(e))}compress(e){return ge(new Uint8Array(e))}}class lr extends E{constructor(e,t){super(),this._version=1,this._type=3,this._config=void 0,this._originDataChannel=void 0,this._dataStreamPacketHeader=new ArrayBuffer(4),this._dataStreamPacketHandler=void 0,this._datachannelEventMap=new Map,this._config=e,t&&(this._originDataChannel=t,this._bandDataChannelEvents(t)),this._initPacketHeader(),this._dataStreamPacketHandler=new hr}get id(){return this._config.id}get ordered(){return this._config.ordered}get maxRetransmits(){return u("DATASTREAM_MAX_RETRANSMITS")}get metadata(){return this._config.metadata}get readyState(){var e,t;return null!==(e=null===(t=this._originDataChannel)||void 0===t?void 0:t.readyState)&&void 0!==e?e:"connecting"}get _originDataChannelId(){var e,t;return null!==(e=null===(t=this._originDataChannel)||void 0===t?void 0:t.id)&&void 0!==e?e:null}getChannelId(){return this.id}getConfig(){return this._config}_close(){this._originDataChannel&&(this._unbindDataChannelEvents(this._originDataChannel),this._originDataChannel=void 0)}async _waitTillOpen(){return new Promise(((e,t)=>{if(this._originDataChannel){"open"===this._originDataChannel.readyState&&e();const i=setTimeout((()=>{var e;t(new _(T.DATACHANNEL_CONNECTION_TIMEOUT,"Cannot create datachannel, id: ".concat(null===(e=this._originDataChannel)||void 0===e?void 0:e.id)))}),1e4);this._originDataChannel.onopen=()=>{clearTimeout(i),this._originDataChannel&&this._bandDataChannelEvents(this._originDataChannel),e()},this._originDataChannel.onerror=()=>{throw clearTimeout(i),new _(T.DATACHANNEL_CONNECTION_TIMEOUT)}}else t(new _(T.DATACHANNEL_CONNECTION_TIMEOUT,"cannot find dataChannel"))}))}_updateOriginDataChannel(e){this._originDataChannel=e,this._bandDataChannelEvents(e)}_initPacketHeader(){const e=new DataView(this._dataStreamPacketHeader);e.setUint16(0,this._version),e.setUint8(2,this._type),e.setUint8(3,this._config.id)}_bandDataChannelEvents(e){this._unbindDataChannelEvents(e),[ht.OPEN,ht.CLOSE,ht.ERROR].forEach((t=>{const i=()=>{this.emit(t)};this._datachannelEventMap.set(t,i),e.addEventListener(t,i)}))}_unbindDataChannelEvents(e){Array.from(this._datachannelEventMap.entries()).forEach((t=>{let[i,r]=t;e.removeEventListener(i,r)})),this._datachannelEventMap.clear()}}class pr extends lr{constructor(e){super(e),this._messageListener=void 0,this._messageListener=e=>{if(e.data.byteLength<this._dataStreamPacketHeader.byteLength)throw Error("invalid byteLength: the byte length must exceed "+this._dataStreamPacketHeader.byteLength);const t=e.data.slice(0,this._dataStreamPacketHeader.byteLength),i=new DataView(t).getUint8(3);if(i!==this.id)return void(u("SHOW_DATASTREAM2_LOG")&&de.debug("invalid datachannel id: ".concat(i," !== ").concat(this.id)));let r=e.data.slice(this._dataStreamPacketHeader.byteLength);r=this._dataStreamPacketHandler.deserialize(r),this.emit(ht.MESSAGE,r)}}_updateOriginDataChannel(e){super._updateOriginDataChannel(e),this._bandRemoteDataChannelEvents()}_close(){this._originDataChannel&&(this._originDataChannel.removeEventListener("message",this._messageListener),super._close())}_bandRemoteDataChannelEvents(){this._originDataChannel&&this._originDataChannel.addEventListener("message",this._messageListener)}}class mr extends lr{send(e){if(this._originDataChannel){let t=e;t=this._dataStreamPacketHandler.serialize(e);const i=new Uint8Array(this._dataStreamPacketHeader.byteLength+t.byteLength);i.set(new Uint8Array(this._dataStreamPacketHeader),0),i.set(new Uint8Array(t),this._dataStreamPacketHeader.byteLength),this._originDataChannel.send(i.buffer)}}}function gr(){const e=new Blob([atob("ZnVuY3Rpb24gZShlKXtjb25zdCB0PW5ldyBEYXRhVmlldyhlLmRhdGEpO2lmKDA9PT10LmdldFVpbnQ4KDApJiYwPT09dC5nZXRVaW50OCgxKSYmMD09PXQuZ2V0VWludDgoMikmJjE9PT10LmdldFVpbnQ4KDMpJiY2PT09dC5nZXRVaW50OCg0KSl7bGV0IG49NixyPTAsbz0wO2Zvcig7MjU1PT09KG89dC5nZXRVaW50OChuKyspKTspcis9MjU1O3IrPW87Y29uc3QgYT1mdW5jdGlvbihlLHQsbil7bGV0IHI9bmV3IFVpbnQ4QXJyYXkoZSx0LG4pLG89W10sYT0wO2Zvcig7YTxuOylhKzM8biYmMD09PXJbYV0mJjA9PT1yW2ErMV0mJjM9PT1yW2ErMl0mJigwPT09clthKzNdfHwxPT09clthKzNdfHwyPT09clthKzNdfHwzPT09clthKzNdKT8oby5wdXNoKHJbYV0sclthKzFdLHJbYSszXSksYSs9NCk6KG8ucHVzaChyW2FdKSxhKyspO3JldHVybiBuZXcgVWludDhBcnJheShvKX0oZS5kYXRhLG4scik7cmV0dXJuIG5ldyBVaW50OEFycmF5KGEpfXJldHVybiBudWxsfWZ1bmN0aW9uIHQoZSx0KXtjb25zdCBuPWZ1bmN0aW9uKGUpe2NvbnN0IHQ9ZS5sZW5ndGg7bGV0IG49W10scj0wO2Zvcig7cjx0OylyKzI8dCYmMD09PWVbcl0mJjA9PT1lW3IrMV0mJigwPT09ZVtyKzJdfHwxPT09ZVtyKzJdfHwyPT09ZVtyKzJdfHwzPT09ZVtyKzJdKT8obi5wdXNoKGVbcl0sZVtyKzFdLDMsZVtyKzJdKSxyKz0zKToobi5wdXNoKGVbcl0pLHIrKyk7cmV0dXJuIG5ldyBVaW50OEFycmF5KG4pfSh0KSxyPW4ubGVuZ3RoLG89TWF0aC5mbG9vcihyLzI1NSksYT1yJTI1NSxzPW5ldyBVaW50OEFycmF5KDYrbysxK3IrZS5ieXRlTGVuZ3RoKTtzWzBdPTAsc1sxXT0wLHNbMl09MCxzWzNdPTEsc1s0XT02LHNbNV09MTAxO2xldCBpPTA7Zm9yKDtpPG87KXNbNitpXT0yNTUsaSsrO3JldHVybiBzWzYraV09YSxpKysscy5zZXQobiw2K2kpLHMuc2V0KG5ldyBVaW50OEFycmF5KGUpLDYraStyKSxzLmJ1ZmZlcn1uYXZpZ2F0b3IudXNlckFnZW50LmluZGV4T2YoIlNhZmFyaSIpPi0xJiYtMT09PW5hdmlnYXRvci51c2VyQWdlbnQuaW5kZXhPZigiQ2hyb21lIikmJihzZWxmLm9ucnRjdHJhbnNmb3JtPW49Pntjb25zdCByPW4udHJhbnNmb3JtZXI7bGV0IG89W107ci5vcHRpb25zLnBvcnQub25tZXNzYWdlPWU9PntlLmRhdGEuc2VpJiZvLnB1c2goZS5kYXRhLnNlaSl9LHNlbGYucG9zdE1lc3NhZ2UoInN0YXJ0ZWQiKTtjb25zdCBhPXIucmVhZGFibGUuZ2V0UmVhZGVyKCkscz1yLndyaXRhYmxlLmdldFdyaXRlcigpOyJyeCI9PT1yLm9wdGlvbnMubmFtZT9mdW5jdGlvbiB0KG4pe2EucmVhZCgpLnRoZW4oKHI9PntpZighci5kb25lKXtpZihyLnZhbHVlIGluc3RhbmNlb2YgUlRDRW5jb2RlZFZpZGVvRnJhbWUpe2NvbnN0IHQ9ZShyLnZhbHVlKTt0JiZuLm9wdGlvbnMucG9ydC5wb3N0TWVzc2FnZSh7c2VpOnR9KX1zLndyaXRlKHIudmFsdWUpLG4ub3B0aW9ucy5wb3J0LnBvc3RNZXNzYWdlKHt0cmFuc2Zvcm1lZDohMH0pLHQobil9fSkpfShyKToidHgiPT09ci5vcHRpb25zLm5hbWUmJmZ1bmN0aW9uIGUobil7YS5yZWFkKCkudGhlbigocj0+e2lmKCFyLmRvbmUpe2lmKHIudmFsdWUgaW5zdGFuY2VvZiBSVENFbmNvZGVkVmlkZW9GcmFtZSl7Y29uc3QgZT1vLnNoaWZ0KCk7ZSYmKHIudmFsdWUuZGF0YT10KHIudmFsdWUuZGF0YSxlKSl9cy53cml0ZShyLnZhbHVlKSxuLm9wdGlvbnMucG9ydC5wb3N0TWVzc2FnZSh7dHJhbnNmb3JtZWQ6ITB9KSxlKG4pfX0pKX0ocil9LHNlbGYucG9zdE1lc3NhZ2UoInJlZ2lzdGVyZWQiKSk7Cg==")],{type:"text/javascript"});return setTimeout((()=>URL.revokeObjectURL(e)),0),new Worker(URL.createObjectURL(e))}const _r=new Map;async function Tr(e){if(!fe().supportWebRTCEncodedTransform)return void de.warning("browser not support audio encoded transform");if(_r.has(e))return;if(!e.track)return;const t={track:e.track};if(O()){if(!e.createEncodedStreams)return void de.warning("browser not support createEncodedStreams() API");let r=null;try{r=e.createEncodedStreams()}catch(e){return void de.error("create audio-encoded-streams error",e&&e.message)}const n=new TransformStream({transform(r,n){t.controller||(t.controller=n),e.track&&e.track.id!==t.track.id&&(de.debug("audio track changed: ".concat(t.track.id," => ").concat(e.track.id)),t.track.removeEventListener("ended",i),t.track=e.track,t.track.addEventListener("ended",i)),n.enqueue(r)}});r.readable.pipeThrough(n).pipeTo(r.writable)}else if(c()){if("undefined"==typeof RTCRtpScriptTransform)return void de.warning("browser not support RTCRtpScriptTransform");const r=gr(),n=new MessageChannel;await new Promise((e=>r.onmessage=t=>{"registered"===t.data&&e(void 0)}));const s=new RTCRtpScriptTransform(r,{name:"tx",port:n.port2},[n.port2]);e.transform=s,await new Promise((e=>r.onmessage=t=>{"started"===t.data&&e(void 0)})),n.port1.onmessage=r=>{var n;r.data.transformed&&e.track&&(null===(n=e.track)||void 0===n?void 0:n.id)!==t.track.id&&(de.debug("audio track changed: ".concat(t.track.id," => ").concat(e.track.id)),t.track.removeEventListener("ended",i),t.track=e.track,t.track.addEventListener("ended",i))},t.worker=r}function i(){if(e.track){if(this.id!==e.track.id)return;e.track.removeEventListener("ended",i)}const t=_r.get(e);if(t){_r.delete(e);try{var r,n;null===(r=t.controller)||void 0===r||r.terminate(),null===(n=t.worker)||void 0===n||n.terminate()}catch(e){de.warning(e&&e.message)}}}_r.set(e,t),e.track.addEventListener("ended",i)}const fr=new Map;async function Er(e){if(!fe().supportWebRTCEncodedTransform)return void de.warning("browser not support audio encoded transform");if(fr.has(e))return;const t={track:e.track};if(O()){if(!e.createEncodedStreams)return void de.warning("browser not support createEncodedStreams() API");let r=null;try{r=e.createEncodedStreams()}catch(e){return void de.error("create audio-encoded-streams error",e&&e.message)}const n=new TransformStream({transform(r,n){t.controller||(t.controller=n),e.track&&e.track.id!==t.track.id&&(de.debug("audio track changed: ".concat(t.track.id," => ").concat(e.track.id)),t.track.removeEventListener("ended",i),t.track=e.track,t.track.addEventListener("ended",i)),n.enqueue(r)}});r.readable.pipeThrough(n).pipeTo(r.writable)}else if(c()){if("undefined"==typeof RTCRtpScriptTransform)return void de.warning("browser not support RTCRtpScriptTransform");const r=gr(),n=new MessageChannel;await new Promise((e=>r.onmessage=t=>{"registered"===t.data&&e(void 0)}));const s=new RTCRtpScriptTransform(r,{name:"rx",port:n.port2},[n.port2]);e.transform=s,await new Promise((e=>r.onmessage=t=>{"started"===t.data&&e(void 0)})),n.port1.onmessage=r=>{var n;r.data.transformed&&e.track&&(null===(n=e.track)||void 0===n?void 0:n.id)!==t.track.id&&(de.debug("audio track changed: ".concat(t.track.id," => ").concat(e.track.id)),t.track.removeEventListener("ended",i),t.track=e.track,t.track.addEventListener("ended",i))},t.worker=r}function i(){e.track.removeEventListener("ended",i),function(e){const t=fr.get(e);if(t){fr.delete(e);try{var i,r;null===(i=t.controller)||void 0===i||i.terminate(),null===(r=t.worker)||void 0===r||r.terminate()}catch(e){de.warning(e&&e.message)}}}(e)}fr.set(e,t),e.track.addEventListener("ended",i)}function vr(e){const t=new DataView(e.data);if(0===t.getUint8(0)&&0===t.getUint8(1)&&0===t.getUint8(2)&&1===t.getUint8(3)&&6===t.getUint8(4)){let i=6,r=0,n=0;for(;255===(n=t.getUint8(i++));)r+=255;r+=n;const s=function(e,t,i){let r=new Uint8Array(e,t,i),n=[],s=0;for(;s<i;)s+3<i&&0===r[s]&&0===r[s+1]&&3===r[s+2]&&(0===r[s+3]||1===r[s+3]||2===r[s+3]||3===r[s+3])?(n.push(r[s],r[s+1],r[s+3]),s+=4):(n.push(r[s]),s++);return new Uint8Array(n)}(e.data,i,r);return new Uint8Array(s)}return null}function yr(e,t){const i=function(e){const t=e.length;let i=[],r=0;for(;r<t;)r+2<t&&0===e[r]&&0===e[r+1]&&(0===e[r+2]||1===e[r+2]||2===e[r+2]||3===e[r+2])?(i.push(e[r],e[r+1],3,e[r+2]),r+=3):(i.push(e[r]),r++);return new Uint8Array(i)}(t),r=i.length,n=Math.floor(r/255),s=r%255,o=new Uint8Array(6+n+1+r+e.byteLength);o[0]=0,o[1]=0,o[2]=0,o[3]=1,o[4]=6,o[5]=101;let a=0;for(;a<n;)o[6+a]=255,a++;return o[6+a]=s,a++,o.set(i,6+a),o.set(new Uint8Array(e),6+a+r),o.buffer}const Sr=new Map;async function kr(e,t){if(!fe().supportWebRTCEncodedTransform)return void de.warning("browser not support video encoded transform");if(Sr.has(e))return;if(!e.track)return;const i={track:e.track};if(O()){if(!e.createEncodedStreams)return void de.warning("browser not support createEncodedStreams() API");let n=null;try{n=e.createEncodedStreams()}catch(e){return void de.error("create video-encoded-streams error",e&&e.message)}let s=[];t.on("sei-to-send",(e=>{s.push(e)}));const o=new TransformStream({transform(t,n){i.controller||(i.controller=n),e.track&&e.track.id!==i.track.id&&(de.debug("video track changed: ".concat(i.track.id," => ").concat(e.track.id)),i.track.removeEventListener("ended",r),i.track=e.track,i.track.addEventListener("ended",r));const o=s.shift();o&&(t.data=yr(t.data,o)),n.enqueue(t)}});n.readable.pipeThrough(o).pipeTo(n.writable)}else{if(!c())return;{if("undefined"==typeof RTCRtpScriptTransform)return void de.warning("browser not support RTCRtpScriptTransform");const n=gr(),s=new MessageChannel;await new Promise((e=>n.onmessage=t=>{"registered"===t.data&&e(void 0)}));const o=new RTCRtpScriptTransform(n,{name:"tx",port:s.port2},[s.port2]);e.transform=o,await new Promise((e=>n.onmessage=t=>{"started"===t.data&&e(void 0)})),t.on("sei-to-send",(e=>{s.port1.postMessage({sei:e})})),s.port1.onmessage=t=>{var n;t.data.transformed&&e.track&&(null===(n=e.track)||void 0===n?void 0:n.id)!==i.track.id&&(de.debug("video track changed: ".concat(i.track.id," => ").concat(e.track.id)),i.track.removeEventListener("ended",r),i.track=e.track,i.track.addEventListener("ended",r))},i.worker=n}}function r(){if(e.track){if(this.id!==e.track.id)return;e.track.removeEventListener("ended",r)}const t=Sr.get(e);if(t){Sr.delete(e);try{var i,n;null===(i=t.controller)||void 0===i||i.terminate(),null===(n=t.worker)||void 0===n||n.terminate()}catch(e){de.warning(e&&e.message)}}}Sr.set(e,i),e.track.addEventListener("ended",r)}const br=new Map;async function Ir(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!fe().supportWebRTCEncodedTransform)return void de.warning("browser not support video encoded transform");if(!e.track)return;if(br.has(e)){const i=br.get(e);return void(i&&(i.onSei=t.onSei))}const i={track:e.track,onSei:t.onSei};if(O()){if(!e.createEncodedStreams)return void de.warning("browser not support createEncodedStreams() API");let t=null;try{t=e.createEncodedStreams()}catch(e){return void de.error("create video-encoded-streams error",e&&e.message)}const n=new TransformStream({transform(t,n){i.controller||(i.controller=n),e.track&&e.track.id!==i.track.id&&(de.debug("video track changed: ".concat(i.track.id," => ").concat(e.track.id)),i.track.removeEventListener("ended",r),i.track=e.track,i.track.addEventListener("ended",r));const s=vr(t);s&&i.onSei&&i.onSei(s),n.enqueue(t)}});t.readable.pipeThrough(n).pipeTo(t.writable)}else if(c()){if("undefined"==typeof RTCRtpScriptTransform)return void de.warning("browser not support RTCRtpScriptTransform");const t=gr(),n=new MessageChannel;await new Promise((e=>t.onmessage=t=>{"registered"===t.data&&e(void 0)}));const s=new RTCRtpScriptTransform(t,{name:"rx",port:n.port2},[n.port2]);e.transform=s,await new Promise((e=>t.onmessage=t=>{"started"===t.data&&e(void 0)})),n.port1.onmessage=t=>{var n;t.data.transformed&&e.track&&(null===(n=e.track)||void 0===n?void 0:n.id)!==i.track.id?(de.debug("video track changed: ".concat(i.track.id," => ").concat(e.track.id)),i.track.removeEventListener("ended",r),i.track=e.track,i.track.addEventListener("ended",r)):t.data.sei&&i.onSei&&i.onSei(t.data.sei)},i.worker=t}function r(){if(e.track){if(this.id!==e.track.id)return;e.track.removeEventListener("ended",r)}!function(e){const t=br.get(e);if(t){br.delete(e);try{var i,r;null===(i=t.controller)||void 0===i||i.terminate(),null===(r=t.worker)||void 0===r||r.terminate()}catch(e){de.warning(e&&e.message)}}}(e)}br.set(e,i),e.track.addEventListener("ended",r)}Te();export{Ee as AUDIO_CONTEXT_EVENT,De as AUDIO_ENCODER_CONFIG_SETTINGS,Xe as AUDIO_TRACK_EVENT,Ni as AudioProcessorContext,wi as AudioProcessorDestination,Ye as AudioSourceEvents,Mi as BufferSourceAudioTrack,Xi as CameraVideoTrack,qe as DEFAULT_LOCAL_AUDIO_TRACK_STATS,$e as DEFAULT_LOCAL_VIDEO_TRACK_STATS,tt as DEFAULT_NETWORK_QUALITY_STATS,et as DEFAULT_REMOTE_AUDIO_TRACK_STATS,it as DEFAULT_REMOTE_VIDEO_TRACK_STATS,lr as DataChannel,ht as DataChannelEvents,ot as DeviceManagerEvent,st as DeviceManagerState,Bt as HAS_GUM_AUDIO,Wt as HAS_GUM_VIDEO,Di as LocalAudioTrack,mr as LocalDataChannel,ft as LocalTrack,Ze as LocalTrackEvents,Yi as LocalVideoTrack,ut as MediaElementNumStatus,at as MediaElementStatus,Oi as MicrophoneAudioTrack,Pi as MixingAudioTrack,nt as PROCESSOR_CONTEXT_EVENTS,rt as PROCESSOR_DESTINATION_EVENTS,cr as RemoteAudioTrack,pr as RemoteDataChannel,ze as RemoteStreamFallbackType,He as RemoteStreamType,or as RemoteTrack,Je as RemoteTrackEvents,ar as RemoteVideoTrack,Ft as SAFARI_GLOBAL_GUM_LOCK,Ie as SUPPORT_720P_AUTO_CONFIG_LIST,Ae as SUPPORT_SCREEN_ENCODER_CONFIG_LIST,we as SUPPORT_SVC_CONFIG_LIST,be as SUPPORT_VIDEO_ENCODER_CONFIG_LIST,Ge as StreamType,Tt as Track,je as TrackEvents,Ke as TrackHint,We as TrackInternalEvent,Ai as VideoProcessorContext,Ii as VideoProcessorDestination,ct as VideoState,Me as __TRACK_LIST__,Pe as addTrack,yt as audioContextState,ki as audioElementPlayCenter,Nt as audioTimerLoop,Ei as autoPlayGestureEventEmitter,Wi as blob2Uint8Array,zi as checkMediaStreamTrackResolution,bi as checkTrackState,$i as createBufferSourceAudioTrack,ir as createCameraVideoTrack,Qi as createCustomAudioTrack,tr as createCustomVideoTrack,rr as createMicrophoneAndCameraTracks,qi as createMicrophoneAudioTrack,er as createMixingAudioTrack,nr as createScreenVideoTrack,At as decodeAudioData,Bi as emptyImage2TypedArray,Zi as frameData2CryptoBuffer,kt as getAudioContext,Oe as getAudioEncoderConfiguration,gi as getAudioInputs,pi as getAudioOutputs,ji as getBitrateConstrainRange,fe as getCompatibility,Li as getConstraintsFromCameraConfig,xi as getConstraintsFromMicrophoneConfig,Vi as getConstraintsFromScreenConfig,_i as getDeviceById,Ti as getDeviceIdByLabel,Ut as getElectronScreenSources,Vt as getElectronScreenStream,xt as getElectronScreenStreamByUserSelect,Kt as getLocalStream,ni as getMediaDevices,Ce as getScalabilityConfiguration,Re as getScreenEncoderConfiguration,Ct as getSilenceAudioTrack,Ot as getSilenceSamplesDuration,Ji as getStaticTrackStream,Ne as getVideoEncoderConfiguration,mi as getVideoInputs,Ht as handleGetUserMediaError,bt as hasAudioContext,Tr as interceptLocalAudioFrame,kr as interceptLocalVideoFrame,Er as interceptRemoteAudioFrame,Ir as interceptRemoteVideoFrame,xe as isAudioEncoderConfiguration,Fe as isAudioEncoderConfigurationOrPreset,dt as isBeautyEffectOptions,Qe as isLowStreamParameter,Be as isScreenSourceType,Ve as isVideoEncoderConfiguration,Ue as isVideoEncoderConfigurationOrPreset,ui as onAudioInputChanged,hi as onAudioOutputChanged,li as onVideoInputChanged,It as polyfillAudioNode,Le as removeTrack,vi as requestAutoplayGesture,Dt as silenceScriptProcessHandler,Te as updateAgoraRTCCompatibility,dr as visibilityWatcher};
|
|
5
|
+
import"webrtc-adapter";import{getBrowserInfo as e,BrowserName as t,isChromeKernel as i,nextTick as s,isAboveChrome as o,isAboveFirefox as n,isAboveSafari as r,BrowserOS as a,isSafari as c,isWkWebview as d,getParameter as u,isFirefox as h,EventEmitter as l,getRandomString as p,AgoraAPIName as m,AgoraAPITag as v,AgoraRTCError as E,AgoraRTCErrorCode as g,emitAsPromise as T,emitAsPromiseNoResponse as _,isAndroidChromium as y,removeItemFromList as f,isIOS as S,isIpadOS as I,getOSWithVersion as A,isAboveIOS15_1 as N,isIOS15 as D,isInPage as k,isAndroid as b,wait as R,domLoadedPromise as w,noop as O,runOnce as C,emitAsInvokerNoResponse as M,elementVisibleChecker as P,isChrome as V,PromiseMutex as L,isHarmonyOS as U,detectSecureContext as x}from"@agora-js/shared";import{logger as F,report as B,AgoraRTCEventUploadType as G,apiInvoke as H}from"@agora-js/report";const W={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};function j(){const l=e();W.getDisplayMedia=function(e){if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)return!0;return!1}(),W.getStreamFromExtension=l.name===t.CHROME&&Number(l.version)>34,W.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}(),W.supportMinBitrate=l.name===t.CHROME||l.name===t.EDGE,W.supportSetRtpSenderParameters=function(){const s=e();if(!window.RTCRtpSender||!window.RTCRtpSender.prototype.setParameters||!window.RTCRtpSender.prototype.getParameters)return!1;return!!i()||(!(!c()&&!d())||s.name===t.FIREFOX&&Number(s.version)>=64)}(),l.name===t.SAFARI&&(Number(l.version)>=14?W.supportDualStream=!0:W.supportDualStream=!1),W.webAudioMediaStreamDest=function(){const i=e();if(i.name===t.SAFARI&&Number(i.version)<12)return!1;return!0}(),W.supportReplaceTrack=function(){if(!window.RTCRtpSender)return!1;if("function"==typeof RTCRtpSender.prototype.replaceTrack)return!0;return!1}(),W.supportWebGL="undefined"!=typeof WebGLRenderingContext,W.supportRequestFrame=!!window.CanvasCaptureMediaStreamTrack,i()||(W.webAudioWithAEC=!0),W.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}(),W.supportDataChannel=function(){if(o(76)||n(68)||r(14))return!0;return!1}(),W.supportPCSetConfiguration=function(){const e=window.RTCPeerConnection;return!h()&&!!e&&e.prototype.setConfiguration instanceof Function}(),W.supportWebRTCEncodedTransform=function(){const t=e();return"Chrome"===t.name&&Number(t.version)>=86||"Safari"===t.name&&Number(t.version)>=15}(),W.supportWebRTCInsertableStream=function(){const i=e();return(i.name===t.CHROME||i.name===t.EDGE)&&Number(i.version)>=94&&"MediaStreamTrackGenerator"in window&&"MediaStreamTrackProcessor"in window}(),s((()=>{W.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"))}(),F.info("browser compatibility",JSON.stringify(W),JSON.stringify(l))}))}function z(){return W}var K,Y,q,Q,X,Z,J,$,ee;!function(e){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"}(K||(K={})),function(e){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_MUTE_TRACK="@need_mute_track",e.NEED_UNMUTE_TRACK="@need_unmute_track"}(Y||(Y={})),function(e){e.SCREEN_TRACK="screen_track",e.CUSTOM_TRACK="custome_track",e.LOW_STREAM="low_stream"}(q||(q={})),function(e){e[e.HIGH_STREAM=0]="HIGH_STREAM",e[e.LOW_STREAM=1]="LOW_STREAM"}(Q||(Q={})),function(e){e[e.HIGH_STREAM=0]="HIGH_STREAM",e[e.LOW_STREAM=1]="LOW_STREAM"}(X||(X={})),function(e){e[e.DISABLE=0]="DISABLE",e[e.LOW_STREAM=1]="LOW_STREAM",e[e.AUDIO_ONLY=2]="AUDIO_ONLY"}(Z||(Z={})),function(e){e.TRANSCEIVER_UPDATED="transceiver-updated",e.SEI_TO_SEND="sei-to-send",e.SEI_RECEIVED="sei-received",e.CLOSED="closed"}(J||(J={})),function(e){e.FIRST_FRAME_DECODED="first-frame-decoded",e.VIDEO_ELEMENT_VISIBLE_STATUS="video-element-visible-status",e.VIDEO_STATE_CHANGED="video-state-changed"}($||($={})),function(e){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"}(ee||(ee={}));const te={transportDelay:0,end2EndDelay:0,receiveBitrate:0,receiveLevel:0,receiveBytes:0,receiveDelay:0,receivePackets:0,receivePacketsLost:0,totalDuration:0,totalFreezeTime:0,freezeRate:0,packetLossRate:0,currentPacketLossRate:0,publishDuration:-1},ie={uplinkNetworkQuality:0,downlinkNetworkQuality:0},se={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};var oe,ne,re,ae,ce,de;!function(e){e.ON_TRACK="on_track",e.ON_NODE="on_node"}(oe||(oe={})),function(e){e.REQUEST_UPDATE_CONSTRAINTS="request_update_constraints",e.REQUEST_CONSTRAINTS="request_constraints"}(ne||(ne={})),function(e){e.IDLE="IDLE",e.INITING="INITING",e.INITEND="INITEND"}(re||(re={})),function(e){e.STATE_CHANGE="state_change",e.RECORDING_DEVICE_CHANGED="recordingDeviceChanged",e.PLAYOUT_DEVICE_CHANGED="playoutDeviceChanged",e.CAMERA_DEVICE_CHANGED="cameraDeviceChanged"}(ae||(ae={})),function(e){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"}(ce||(ce={})),function(e){e[e.VideoStateStopped=0]="VideoStateStopped",e[e.VideoStateStarting=1]="VideoStateStarting",e[e.VideoStateDecoding=2]="VideoStateDecoding",e[e.VideoStateFrozen=3]="VideoStateFrozen"}(de||(de={}));const ue={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},he=[];function le(e){he.includes(e)||he.push(e)}function pe(e){const t=he.indexOf(e);-1!==t&&he.splice(t,1)}class me extends l{constructor(e,t){super(),this._ID=void 0,this._rtpTransceiver=void 0,this._lowRtpTransceiver=void 0,this._hints=[],this._isClosed=!1,this._originMediaStreamTrack=void 0,this._mediaStreamTrack=void 0,this._external={},this._ID=t||p(8,"track-"),this._originMediaStreamTrack=e,this._mediaStreamTrack=e,le(this)}toString(){return this._ID}getTrackId(){return this._ID}getMediaStreamTrack(e){if(!e){const e=B.reportApiInvoke(null,{name:m.GET_MEDIA_STREAM_TRACK,options:[],tag:v.TRACER});this._mediaStreamTrack&&"string"==typeof this._mediaStreamTrack.label?e.onSuccess(this._mediaStreamTrack.label):e.onSuccess("")}return this._mediaStreamTrack}getRTCRtpTransceiver(e){return e===Q.LOW_STREAM?this._lowRtpTransceiver:this._rtpTransceiver}getMediaStreamTrackSettings(){return this.getMediaStreamTrack(!0).getSettings()}close(){this._isClosed=!0,this._lowRtpTransceiver=void 0,this._rtpTransceiver=void 0,pe(this),this.emit(J.CLOSED),this.removeAllListeners(J.SEI_RECEIVED)}_updateRtpTransceiver(e,t){if(t===Q.LOW_STREAM){if(this._lowRtpTransceiver===e)return;this._lowRtpTransceiver=e}else{if(this._rtpTransceiver===e)return;this._rtpTransceiver=e}this.emit(J.TRANSCEIVER_UPDATED,e,t)}}function ve(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,s)}return i}function Ee(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?ve(Object(i),!0).forEach((function(t){ge(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):ve(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function ge(e,t,i){return(t=function(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var s=i.call(e,t||"default");if("object"!=typeof s)return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:String(t)}(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}class Te extends l{constructor(e){super(),this.name="VideoProcessorDestination",this.ID="0",this._source=void 0,this.videoContext=void 0,this.inputTrack=void 0,this.videoContext=e}get kind(){return"video"}get enabled(){return!0}pipe(){throw new E(g.NOT_SUPPORTED,"VideoProcessor cannot pipe to any other Processor")}unpipe(){throw new E(g.NOT_SUPPORTED,"VideoProcessor cannot unpipe to any other Processor")}enable(){}disable(){}updateInput(e){if(e.context!==this.videoContext)throw new Error("ProcessorContext passed to VideoTrack.processorDestination doesn't match it's belonging VideoTrack's context.\nProbably you are making pipeline like this:\nvideoTrack1.pipe(processor).pipe(videoTrack2.processorDestination).");e.track&&e.track!==this.inputTrack&&(this.videoContext.chained=!0,this.inputTrack=e.track,this.emit(oe.ON_TRACK,e.track))}reset(){this.inputTrack=void 0,this.videoContext.chained=!1,this.emit(oe.ON_TRACK,void 0)}}class _e extends l{set chained(e){this._chained=e}get chained(){return this._chained}constructor(e,t){super(),this.constraintsMap=new Map,this.statsRegistry=[],this.usageRegistry=[],this.trackId=void 0,this.direction=void 0,this._chained=!1,this.trackId=e,this.direction=t}async getConstraints(){return await T(this,ne.REQUEST_CONSTRAINTS)}async requestApplyConstraints(e,t){return F.info("processor ".concat(t.name," requestApplyConstraints for ").concat(this.trackId)),e&&this.constraintsMap.set(t,e),_(this,ne.REQUEST_UPDATE_CONSTRAINTS,Array.from(this.constraintsMap.values()))}async requestRevertConstraints(e){if(this.constraintsMap.has(e))return F.info("processor ".concat(e.name," requestRevertConstraints for ").concat(this.trackId)),this.constraintsMap.delete(e),_(this,ne.REQUEST_UPDATE_CONSTRAINTS,Array.from(this.constraintsMap.values()))}registerStats(e,t,i){this.statsRegistry.find((i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t))||this.statsRegistry.push({processorName:e.name,processorID:e.ID,type:t,cb:i})}unregisterStats(e,t){const i=this.statsRegistry.findIndex((i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t));-1!==i&&this.statsRegistry.splice(i,1)}gatherStats(){const e=[];for(const{processorID:t,processorName:i,type:s,cb:o}of this.statsRegistry)try{const n=o();e.push({processorID:t,processorName:i,type:s,stats:n})}catch(e){F.error(new E(g.UNEXPECTED_ERROR,e.message))}return e}registerUsage(e,t){this.usageRegistry.find((t=>t.processorID===e.ID&&t.processorName===e.name))||this.usageRegistry.push({processorID:e.ID,processorName:e.name,cb:t})}unregisterUsage(e){const t=this.usageRegistry.findIndex((t=>t.processorID===e.ID&&t.processorName===e.name));-1!==t&&this.usageRegistry.splice(t,1)}async gatherUsage(){const e=[];if(!this.chained)return[];for(const{cb:t}of this.usageRegistry)try{let i=t();i instanceof Promise&&(i=await i),e.push(Ee(Ee({},i),{},{direction:this.direction}))}catch(e){F.error("gather extension usage error",e)}return e}getDirection(){return this.direction}}class ye extends l{constructor(e){super(),this.name="AudioProcessorDestination",this.ID="0",this.inputTrack=void 0,this.inputNode=void 0,this.audioProcessorContext=void 0,this._source=void 0,this.audioProcessorContext=e}get kind(){return"audio"}get enabled(){return!0}pipe(){throw new E(g.NOT_SUPPORTED,"AudioProcessorDestination cannot pipe to any other Processor")}unpipe(){throw new E(g.NOT_SUPPORTED,"AudioProcessor cannot unpipe to any other Processor")}enable(){}disable(){}reset(){this.inputTrack=void 0,this.inputNode=void 0,this.audioProcessorContext.chained=!1,this.emit(oe.ON_TRACK,void 0),this.emit(oe.ON_NODE,void 0)}updateInput(e){if(e.context!==this.audioProcessorContext)throw new Error("ProcessorContext passed to AudioTrack.processorDestination doesn't match it's belonging AudioTrack's context.\n Probably you are making pipeline like this: audioTrack1.pipe(processor).pipe(audioTrack2.processorDestination).");e.track&&this.inputTrack!==e.track&&(this.audioProcessorContext.chained=!0,this.inputTrack=e.track,this.emit(oe.ON_TRACK,this.inputTrack)),e.node&&this.inputNode!==e.node&&(this.audioProcessorContext.chained=!0,this.inputNode=e.node,this.emit(oe.ON_NODE,this.inputNode))}}class fe extends l{set chained(e){this._chained=e}get chained(){return this._chained}constructor(e,t,i){super(),this.constraintsMap=new Map,this.statsRegistry=[],this.audioContext=void 0,this.trackId=void 0,this.direction=void 0,this.usageRegistry=[],this._chained=!1,this.audioContext=e,this.trackId=t,this.direction=i}async getConstraints(){return T(this,ne.REQUEST_CONSTRAINTS)}getAudioContext(){return this.audioContext}async requestApplyConstraints(e,t){return F.info("processor ".concat(t.name," requestApplyConstraints for ").concat(this.trackId)),e&&this.constraintsMap.set(t,e),_(this,ne.REQUEST_UPDATE_CONSTRAINTS,Array.from(this.constraintsMap.values()))}async requestRevertConstraints(e){if(this.constraintsMap.has(e))return this.constraintsMap.delete(e),_(this,ne.REQUEST_UPDATE_CONSTRAINTS,Array.from(this.constraintsMap.values()))}registerStats(e,t,i){this.statsRegistry.find((i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t))||this.statsRegistry.push({processorName:e.name,processorID:e.ID,type:t,cb:i})}unregisterStats(e,t){const i=this.statsRegistry.findIndex((i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t));-1!==i&&this.statsRegistry.splice(i,1)}gatherStats(){const e=[];for(const{processorID:t,processorName:i,type:s,cb:o}of this.statsRegistry)try{const n=o();e.push({processorID:t,processorName:i,type:s,stats:n})}catch(e){F.error(new E(g.UNEXPECTED_ERROR,e.message))}return e}registerUsage(e,t){this.usageRegistry.find((t=>t.processorID===e.ID&&t.processorName===e.name))||this.usageRegistry.push({processorID:e.ID,processorName:e.name,cb:t})}unregisterUsage(e){const t=this.usageRegistry.findIndex((t=>t.processorID===e.ID&&t.processorName===e.name));-1!==t&&this.usageRegistry.splice(t,1)}async gatherUsage(){const e=[];if(!this.chained)return[];for(const{cb:t}of this.usageRegistry)try{let i=t();i instanceof Promise&&(i=await i),e.push(Ee(Ee({},i),{},{direction:this.direction}))}catch(e){F.error("gather extension usage error",e)}return e}getDirection(){return this.direction}}function Se(e,t,i,s){var o,n=arguments.length,r=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)r=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(r=(n<3?o(r):n>3?o(t,i,r):o(t,i))||r);return n>3&&r&&Object.defineProperty(t,i,r),r}function Ie(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}const Ae=e=>{const t=document.createElement("canvas");return t.width=2,t.height=2,new Promise(((i,s)=>{t.toBlob((async e=>{if(t.remove(),e){const s=await Ne(e);i({buffer:s,width:t.width,height:t.height})}else s(new E(g.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED))}),e,1)}))},Ne=async e=>{const t=await e.arrayBuffer();return new Uint8Array(t)};let De=!1;const ke=new class extends l{constructor(){super(...arguments),this.onAutoplayFailed=void 0,this.onAudioAutoplayFailed=void 0}};function be(){if(e(),!De){const e=t=>{t.preventDefault(),De=!1,y()?document.body.removeEventListener("click",e,!0):(document.body.removeEventListener("touchstart",e,!0),document.body.removeEventListener("mousedown",e,!0))};De=!0,y()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0)),F.info("detect media autoplay failed, document: https://docs.agora.io/cn/Voice/autoplay_policy_web_ng?platform=Web"),ke.onAutoplayFailed?ke.onAutoplayFailed():ke.onAudioAutoplayFailed?F.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 ."):F.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 ."),ke.emit("autoplay-failed")}}const Re=window.AudioContext||window.webkitAudioContext;let we=null;const Oe=new class extends l{constructor(){super(...arguments),this.prevState=void 0,this.curState=void 0,this.currentTime=void 0,this.currentTimeStuckAt=void 0}get duringInterruption(){return"running"===this.prevState&&"interrupted"===this.curState}};function Ce(){if(!Re)return void F.error("your browser is not support web audio");F.info("create audio context");const t=Ee({},u("WEBAUDIO_INIT_OPTIONS"));F.debug("audio context init option:",JSON.stringify(t)),we=new Re(t),Oe.curState=we.state,we.onstatechange=()=>{Oe.prevState=Oe.curState,Oe.curState=we?we.state:void 0;const{prevState:t,curState:i}=Oe,s="running"===i,o="interrupted"===i,n="running"===t,r="suspended"===t,a="interrupted"===t,c=e().osVersion;(S()||I())&&n&&o&&(F.info("ios".concat(c,"-interruption-start")),Oe.emit(K.IOS_INTERRUPTION_START)),(S()||I())&&(r||a)&&s&&(F.info("ios".concat(c,"-interruption-end")),Oe.emit(K.IOS_INTERRUPTION_END)),t!==i&&Oe.emit(K.STATE_CHANGE,i,t)},setInterval((()=>{var e;const t=null===(e=we)||void 0===e?void 0:e.currentTime;if(Oe.currentTime!==t)Oe.currentTimeStuckAt&&(F.debug("AudioContext current time resume at ".concat(t)),Oe.currentTimeStuckAt=void 0),Oe.currentTime=t;else{if(t!==Oe.currentTimeStuckAt){B.reportApiInvoke(null,{name:"WEB_AUDIO_CURRENT_TIME_STUCK",options:{currentTime:t},tag:v.TRACER}).onSuccess(),F.warning("AudioContext current time stuck at ".concat(t))}Oe.currentTimeStuckAt=t}}),5e3),async function(e){const t=["click","contextmenu","auxclick","dblclick","mousedown","mouseup","touchend","keydown","keyup"];let i,s=!1,o=!1,n=!1;function r(t){"running"===e.state?a(!1):S()||I()?"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(s!==e){s=e;for(let i=0,s=t;i<s.length;i+=1){const t=s[i];e?window.addEventListener(t,u,{capture:!0,passive:!0}):window.removeEventListener(t,u,{capture:!0,passive:!0})}}}function c(){r(!0)}function d(){r(!1)}function u(){r(!0)}function h(e){if(!n)if(i.paused)if(e){let e;l(!1),n=!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(o!==e){o=e;for(let i=0,s=t;i<s.length;i++){const t=s[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),n=!1,h(!1)}function m(){h(!0)}if(S()){const t=e.createMediaStreamDestination(),s=document.createElement("div");s.innerHTML="<audio x-webkit-airplay='deny'></audio>",i=s.children.item(0),i.controls=!1,i.disableRemotePlayback=!0,i.preload="auto",i.srcObject=t.stream,h(!0)}Oe.on(K.STATE_CHANGE,c),r(!1)}(we)}function Me(){if(!we){if(Ce(),!we)throw new E(g.NOT_SUPPORTED,"can not create audio context");return we}return we}function Pe(){return!!we}function Ve(e){if(function(){if(null!==Ue)return Ue;const e=Me(),t=e.createBufferSource(),i=e.createGain(),s=e.createGain();t.connect(i),t.connect(s),t.disconnect(i);let o=!1;try{t.disconnect(i)}catch(e){o=!0}return t.disconnect(),Ue=o,o}())return;const t=e.connect,i=e.disconnect;e.connect=(i,s,o)=>(e._inputNodes||(e._inputNodes=[]),e._inputNodes.includes(i)||(i instanceof AudioNode?(e._inputNodes.push(i),t.call(e,i,s,o)):t.call(e,i,s)),e),e.disconnect=(s,o,n)=>{i.call(e),s?f(e._inputNodes,s):e._inputNodes=[];for(const i of e._inputNodes)t.call(e,i)}}function Le(e){const t=Me();return new Promise(((i,s)=>{t.decodeAudioData(e,(e=>{i(e)}),(e=>{s(new E(g.DECODE_AUDIO_FILE_FAILED,e.toString()))}))}))}let Ue=null;function xe(e,t){let i=!1;const s=1/t;if(u("DISABLE_WEBAUDIO")){const t=window.setInterval((()=>{i?window.clearInterval(t):e(performance.now()/1e3)}),1e3*s)}else{const t=Me();let o=t.createGain();o.gain.value=0,o.connect(t.destination);const n=()=>{if(i)return void(o=null);const r=t.createOscillator();r.onended=n,r.connect(o),r.start(0),r.stop(t.currentTime+s),e(t.currentTime)};n()}return()=>{i=!0}}let Fe=null;function Be(){if(Fe)return Fe;const e=Me();if(!e.createMediaStreamDestination)throw new E(g.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 s=e.createMediaStreamDestination();return t.connect(s),Fe=s.stream.getAudioTracks()[0],Fe}function Ge(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 He(e){const t=e.getChannelData(0);let i=0,s=0;for(let e=0;e<t.length;e+=1)0===t[e]?(i+=1,i>s&&(s=i)):i=0;return s/t.length*e.duration}function We(e,t,i,s){if(!e)return;const o=B.getBaseInfoBySessionId(e);if(!o)return;const n=o.info,r=Date.now(),a=Ee(Ee({},n),{},{vid:void 0===n.vid?0:Number(n.vid),lts:r,elapse:r-o.startTime,cbRegistered:ke.onAutoplayFailed||ke.onAudioAutoplayFailed?1:-1,errorMsg:i,mediaType:t,trackId:s,extend:void 0});B.send({type:G.AUTOPLAY_FAILED,data:a},!0)}class je{get videoElementStatus(){return this._videoElementStatus}set videoElementStatus(e){e!==this._videoElementStatus&&(F.debug("[".concat(this.trackId,"] video-element-status change ").concat(this._videoElementStatus," => ").concat(e)),this._videoElementStatus=e)}get videoState(){return this._videoState}set videoState(e){var t;e!==this._videoState&&(F.debug("[".concat(this.trackId,"] video-status change ").concat(this._videoState," => ").concat(e)),this._videoState=e,null===(t=this.onVideoStateChanged)||void 0===t||t.call(this,this.videoState))}constructor(e){this.trackId=void 0,this.config=void 0,this.onFirstVideoFrameDecoded=void 0,this.onVideoStateChanged=void 0,this.freezeTimeCounterList=[],this.renderFreezeAccTime=0,this.isKeepLastFrame=!1,this.timeUpdatedCount=0,this.freezeTime=0,this.playbackTime=0,this.lastTimeUpdatedTime=0,this.autoplayFailed=!1,this.videoTrack=void 0,this.videoElement=void 0,this.cacheVideoElement=void 0,this._videoState=de.VideoStateStopped,this.videoElementCheckInterval=void 0,this.videoElementFreezeTimeout=void 0,this._videoElementStatus=ce.NONE,this.isGettingVideoDimensions=!1,this.startGetVideoDimensions=()=>{const e=()=>{if(this.isGettingVideoDimensions=!0,this.videoElement.videoWidth*this.videoElement.videoHeight>4)return F.debug("[".concat(this.trackId,"] current video dimensions:"),this.videoElement.videoWidth,this.videoElement.videoHeight),void(this.isGettingVideoDimensions=!1);setTimeout(e,500)};!this.isGettingVideoDimensions&&e()},this.autoResumeAfterInterruption=()=>{this.videoTrack&&"live"===this.videoTrack.readyState&&"running"===Oe.curState&&(F.debug("[track-".concat(this.trackId,"] video element paused, auto resume for ").concat(A())),N()?(this.videoElement.srcObject=null,this.videoElement.srcObject=new MediaStream([this.videoTrack]),this.videoElement.play()):(this.videoElement.pause(),this.videoElement.play()))},this.handleVideoEvents=e=>{switch(e.type){case"play":case"playing":this.startGetVideoDimensions(),this.videoElementStatus=ce.PLAYING;break;case"loadeddata":if(this.videoState=de.VideoStateStarting,this.onFirstVideoFrameDecoded&&this.onFirstVideoFrameDecoded(),this.cacheVideoElement){try{this.cacheVideoElement.srcObject=null,this.cacheVideoElement.remove()}catch(e){}this.cacheVideoElement=void 0}break;case"canplay":this.videoElementStatus=ce.CANPLAY;break;case"stalled":this.videoElementStatus=ce.STALLED;break;case"suspend":this.videoElementStatus=ce.SUSPEND;break;case"pause":this.videoElementStatus=ce.PAUSED,S()||I()||c()&&this.autoplayFailed||!this.videoTrack||"live"!==this.videoTrack.readyState||(F.debug("[track-".concat(this.trackId,"] video element paused, auto resume")),this.videoElement.play());break;case"waiting":this.videoElementStatus=ce.WAITING;break;case"abort":this.videoElementStatus=ce.ABORT;break;case"ended":this.videoElementStatus=ce.ENDED;break;case"emptied":this.videoElementStatus=ce.EMPTIED;break;case"error":{this.videoElementStatus=ce.ERROR;const e=this.videoElement.error;e&&F.error("[".concat(this.trackId,"] media error, code: ").concat(e.code,", message: ").concat(e.message));break}case"timeupdate":{const e=performance.now();if(this.timeUpdatedCount+=1,this.timeUpdatedCount<10)return void(this.lastTimeUpdatedTime=e);const t=e-this.lastTimeUpdatedTime,i=this.lastTimeUpdatedTime;if(this.lastTimeUpdatedTime=e,ut.lastVisibleTime<ut.lastHiddenTime||i<ut.lastHiddenTime||i<ut.lastVisibleTime)return;for(t>u("VIDEO_FREEZE_DURATION")&&(this.freezeTime+=t),this.playbackTime+=t;this.playbackTime>=6e3;){this.playbackTime-=6e3;const e=Math.min(6e3,this.freezeTime);this.freezeTimeCounterList.push(e),this.freezeTime=Math.max(0,this.freezeTime-6e3)}break}}},this.autoResumeAfterInterruptionOnIOS15_16=()=>{this.videoTrack&&"live"===this.videoTrack.readyState&&(F.debug("[track-".concat(this.trackId,"] video element paused, auto resume for ").concat(A())),N()?(this.videoElement.srcObject=null,this.videoElement.srcObject=new MediaStream([this.videoTrack]),this.videoElement.play()):(this.videoElement.pause(),this.videoElement.play()))},this.trackId=e.trackId,this.config=e,e.element instanceof HTMLVideoElement?this.videoElement=e.element:this.videoElement=document.createElement("video"),Oe.on(K.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),Oe.on(K.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16)}getVideoElement(){return this.videoElement}getContainerElement(){var e;return null!==(e=this.videoElement.parentElement)&&void 0!==e?e:void 0}updateConfig(e){this.config=e,this.trackId=e.trackId,e.element!==this.videoElement&&(this.destroy(),this.videoElement=e.element),this.videoTrack&&this.initVideoElement()}updateVideoTrack(e){this.videoTrack!==e&&(this.videoTrack=e,this.initVideoElement())}play(t){const i=this.videoElement.play();i&&i.catch&&i.catch((e=>{t&&We(t,"video",e.message,this.trackId),"NotAllowedError"===e.name?(F.warning("detected video element autoplay failed",e),this.autoplayFailed=!0,this.handleAutoPlayFailed()):F.warning("[".concat(this.trackId,"] play warning: "),e)}));const s=e();if(("Safari"===s.name&&15===Number(s.version)||D())&&i&&i.then){const e=()=>{this.config.mirror&&(this.videoElement.style.transform="rotateY(180deg)")};i.then(e).catch(e)}}getCurrentFrame(){const e=document.createElement("canvas");e.width=this.videoElement.videoWidth,e.height=this.videoElement.videoHeight;const t=e.getContext("2d");if(!t)return F.error("create canvas context failed!"),new ImageData(2,2);t.drawImage(this.videoElement,0,0,e.width,e.height);const i=t.getImageData(0,0,e.width,e.height);return e.remove(),i}async getCurrentFrameToUint8Array(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;const i=document.createElement("canvas");i.width=this.videoElement.videoWidth,i.height=this.videoElement.videoHeight;const s=i.getContext("2d");return s?(s.drawImage(this.videoElement,0,0,i.width,i.height),new Promise(((s,o)=>{i.toBlob((async e=>{if(i.remove(),e){const t=await Ne(e);s({buffer:t,width:i.width,height:i.height})}else o(new E(g.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED))}),e,t<0?.1:t>1?1:t)}))):await Ae(e)}destroy(){Oe.off(K.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),Oe.off(K.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16),this.videoElement.srcObject=null,this.resetVideoElement(),this.freezeTimeCounterList=[],this.videoState=de.VideoStateStopped}initVideoElement(){if(this.videoElementStatus=ce.INIT,!this.videoElementCheckInterval&&(ze.forEach((e=>{this.videoElement.addEventListener(e,this.handleVideoEvents)})),this.videoElementCheckInterval=window.setInterval((()=>{k(this.videoElement)||(this.videoElementStatus=ce.DESTROYED)}),1e3),u("ENABLE_VIDEO_FRAME_CALLBACK"))){var t,i;let e;const s=()=>{"visible"===document.visibilityState&&(document.removeEventListener("visibilitychange",s),this.videoElementFreezeTimeout=window.setTimeout(o,u("VIDEO_FREEZE_DURATION")))},o=()=>{this.videoElementFreezeTimeout=void 0,this.videoState===de.VideoStateDecoding&&("visible"===document.visibilityState?this.videoState=de.VideoStateFrozen:document.addEventListener("visibilitychange",s))},n=(t,i)=>{if(this.videoElementStatus===ce.PLAYING){if(e){const t=i.presentationTime-e.presentationTime;this.videoState===de.VideoStateStarting&&(this.videoState=de.VideoStateDecoding),this.videoState===de.VideoStateDecoding&&this.onVideoStateChanged&&(this.videoElementFreezeTimeout&&window.clearTimeout(this.videoElementFreezeTimeout),this.videoElementFreezeTimeout=window.setTimeout(o,u("VIDEO_FREEZE_DURATION"))),t<u("VIDEO_FREEZE_DURATION")&&this.videoState===de.VideoStateFrozen&&(this.videoState=de.VideoStateDecoding),t>u("VIDEO_FREEZE_DURATION")&&ut.lastVisibleTime>=ut.lastHiddenTime&&e.timestamp>ut.lastVisibleTime&&e.timestamp>ut.lastHiddenTime&&(this.renderFreezeAccTime+=t)}e=Ee(Ee({},i),{},{timestamp:t})}var s,r;u("ENABLE_VIDEO_FRAME_CALLBACK")&&(null===(s=(r=this.videoElement).requestVideoFrameCallback)||void 0===s||s.call(r,n))};null===(t=(i=this.videoElement).requestVideoFrameCallback)||void 0===t||t.call(i,n)}this.videoElement.controls=!1,this.videoElement.setAttribute("playsinline",""),b()&&(this.videoElement.poster="noposter");const s=e();if("Safari"===s.name&&15===Number(s.version)||D()||!this.config.mirror||(this.videoElement.style.transform="rotateY(180deg)"),this.config.fit?this.videoElement.style.objectFit=this.config.fit:this.videoElement.style.objectFit="cover",this.videoElement.setAttribute("muted",""),this.videoElement.muted=!0,this.videoElement.srcObject&&this.videoElement.srcObject instanceof MediaStream){this.videoElement.srcObject.getVideoTracks()[0]!==this.videoTrack&&(this.videoElement.srcObject=this.videoTrack?new MediaStream([this.videoTrack]):null,h()&&this.videoElement.load())}else this.videoElement.srcObject=this.videoTrack?new MediaStream([this.videoTrack]):null,h()&&this.videoElement.load();const o=this.videoElement.play();void 0!==o&&o.catch((e=>{F.debug("[".concat(this.trackId,"] playback interrupted"),e.toString())}))}resetVideoElement(){ze.forEach((e=>{this.videoElement&&this.videoElement.removeEventListener(e,this.handleVideoEvents)})),this.videoElementCheckInterval&&(window.clearInterval(this.videoElementCheckInterval),this.videoElementCheckInterval=void 0),this.videoElementStatus=ce.NONE}handleAutoPlayFailed(){const e=t=>{t.preventDefault(),this.videoElement.play().then((()=>{F.debug("[".concat(this.trackId,"] Video element for trackId:").concat(this.trackId," autoplay resumed."))})).catch((e=>{F.error(e)})),this.autoplayFailed=!1,y()?document.body.removeEventListener("click",e,!0):(document.body.removeEventListener("touchstart",e,!0),document.body.removeEventListener("mousedown",e,!0))};y()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0)),be()}}const ze=["play","playing","loadeddata","canplay","pause","stalled","suspend","waiting","abort","emptied","ended","timeupdate","error"];class Ke extends je{constructor(e){super(e),this.container=void 0,this.slot=void 0,this.slot=e.element,this.updateConfig(e)}updateConfig(e){this.config=e,this.trackId=e.trackId;const t=e.element;t!==this.slot&&(this.destroy(),this.slot=t),this.createElements()}updateVideoTrack(e){this.videoTrack!==e&&(this.videoTrack=e,this.createElements())}play(e){var t;null!==(t=this.container)&&void 0!==t&&t.contains(this.videoElement)&&super.play(e)}getCurrentFrame(){var e;return null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)?super.getCurrentFrame():new ImageData(2,2)}async getCurrentFrameToUint8Array(e){var t;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return null!==(t=this.container)&&void 0!==t&&t.contains(this.videoElement)?await super.getCurrentFrameToUint8Array(e,i):await Ae(e)}destroy(){if(super.destroy(),this.videoElement.remove(),this.videoElement=document.createElement("video"),this.container){try{this.container.remove(),this.slot.removeChild(this.container)}catch(e){}this.container=void 0}}createElements(){this.container||(this.container=document.createElement("div")),this.container.id="agora-video-player-".concat(this.trackId),this.container.style.width="100%",this.container.style.height="100%",this.container.style.position="relative",this.container.style.overflow="hidden",this.videoTrack?(this.container.style.backgroundColor="black",u("KEEP_LAST_FRAME")&&this.isKeepLastFrame&&this.videoElement.paused&&this.resetVideoElement(),this.mountedVideoElement()):this.unmountedVideoElement(),this.slot.appendChild(this.container)}mountedVideoElement(){var e;!this.container||null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)||this.container.appendChild(this.videoElement),super.initVideoElement(),this.videoElement.id="video_".concat(this.trackId),this.videoElement.className="agora_video_player",this.videoElement.style.width="100%",this.videoElement.style.height="100%",this.videoElement.style.position="absolute",this.videoElement.style.left="0",this.videoElement.style.top="0"}unmountedVideoElement(){var e;if(null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)){super.resetVideoElement();try{this.container&&this.container.removeChild(this.videoElement)}catch(e){}this.videoElement=document.createElement("video")}}resetVideoElement(){var e;null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)&&(super.resetVideoElement(),this.cacheVideoElement=this.videoElement,this.videoElement=document.createElement("video"))}getContainerElement(){return this.container}}class Ye{constructor(){this.context=void 0,this.analyserNode=void 0,this.sourceNode=void 0,this.context=Me(),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||S()||I()||"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){F.warning("rebuild analyser node failed.")}}destroy(){this.updateSource(void 0)}}class qe extends l{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(),this.outputNode=void 0,this.outputTrack=void 0,this.isPlayed=!1,this.context=void 0,this.audioBufferNode=void 0,this.destNode=void 0,this.audioOutputLevel=0,this.volumeLevelAnalyser=void 0,this._processedNode=void 0,this.playNode=void 0,this.isDestroyed=!1,this.onNoAudioInput=void 0,this.isNoAudioInput=!1,this._noAudioInputCount=0,this.context=Me(),this.playNode=this.context.destination,this.outputNode=this.context.createGain(),Ve(this.outputNode),this.volumeLevelAnalyser=new Ye}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(ee.ON_AUDIO_BUFFER,Ge(e))})}stopGetAudioBuffer(){this.audioBufferNode&&(this.audioBufferNode.onaudioprocess=null,this.outputNode.disconnect(this.audioBufferNode),this.audioBufferNode=void 0)}createOutputTrack(){if(!z().webAudioMediaStreamDest)throw new E(g.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&&s((()=>{Oe.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;S()||I()?"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 s=!1;for(let e=0;e<i.length;e++)0!==i[e]&&(s=!0);return s?(this.isNoAudioInput=!1,!0):(await R(200),await this.checkHasAudioInput(e?e+1:1)&&s)}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 Qe extends qe{get isFreeze(){return!1}constructor(t,i,s){var o;if(super(),this.sourceNode=void 0,this.track=void 0,this.clonedTrack=void 0,this.audioElement=void 0,this.isCurrentTrackCloned=!1,this.isRemoteTrack=!1,this.originVolumeLevelAnalyser=void 0,this.rebuildWebAudio=async()=>{if(F.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 F.debug("rebuild web audio success, current volume status",this.getAccurateVolumeLevel());this.context.resume().then((()=>F.info("resume success"))),F.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),Ve(this.sourceNode),this.volumeLevelAnalyser.rebuildAnalyser();const i=this.outputNode.gain.value;this.outputNode=this.context.createGain(),this.outputNode.gain.setValueAtTime(i,this.context.currentTime),Ve(this.outputNode),this.emit(ee.UPDATE_SOURCE),this.connect(),this.audioElement.srcObject=t,this.isPlayed&&this.play(this.playNode),this.checkHasAudioInput()},"audio"!==t.kind)throw new E(g.UNEXPECTED_ERROR);this.track=t;const n=new MediaStream([this.track]);if(this.isRemoteTrack=!!i,this.sourceNode=this.context.createMediaStreamSource(n),Ve(this.sourceNode),s){const e=s.clone();e.enabled=!0,this.clonedTrack=e,F.debug("create an unmuted track ".concat(e.id," from the original track ").concat(s.id," to get the volume"));const t=this.context.createMediaStreamSource(new MediaStream([e]));Ve(t),this.originVolumeLevelAnalyser=new Ye,this.originVolumeLevelAnalyser.updateSource(t)}this.connect(),this.audioElement=document.createElement("audio"),this.audioElement.srcObject=n;const r=e();i&&r.os===a.IOS&&Number(null===(o=r.osVersion)||void 0===o?void 0:o.split(".")[0])<15&&(Oe.on(K.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),Ve(this.sourceNode),this.processedNode||this.sourceNode.connect(this.outputNode),this.emit(ee.UPDATE_SOURCE),this.audioElement.srcObject=t}destroy(){var e;this.audioElement.srcObject=null,this.audioElement.remove(),Oe.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),F.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]));Ve(i),this.originVolumeLevelAnalyser&&this.originVolumeLevelAnalyser.updateSource(i)}getOriginVolumeLevel(){return this.originVolumeLevelAnalyser?this.originVolumeLevelAnalyser.getVolumeLevel():this.getAccurateVolumeLevel()}}const Xe=["play","playing","loadeddata","canplay","pause","stalled","suspend","waiting","abort","emptied","ended","error"],Ze=new class{constructor(){this.onAutoplayFailed=void 0,this.elementMap=new Map,this.elementStateMap=new Map,this.elementsNeedToResume=[],this.sinkIdMap=new Map,this.autoResumeAfterInterruption=e=>{Array.from(this.elementMap.entries()).forEach((t=>{let[i,s]=t;const o=this.elementStateMap.get(i),n=s.srcObject.getAudioTracks()[0],r=n&&n.readyState;if(F.debug("resume after interrupted, ele: ".concat(o," audio: ").concat(r," ").concat(e)),"live"===r){if(e)return s.pause(),void s.play();if("running"===Oe.curState)return D()?(s.pause(),void s.play()):void(o&&"paused"===o&&s.play())}}))},this.autoResumeAfterInterruptionOnIOS15_16=()=>{Array.from(this.elementMap.entries()).forEach((e=>{let[t,i]=e;const s=i.srcObject.getAudioTracks()[0];s&&"live"===s.readyState&&(F.debug("auto resume after interruption inside autoResumeAfterInterruptionOnIOS15"),i.pause(),i.play())}))},this.autoResumeAudioElement(),Oe.on(K.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),Oe.on(K.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16),Oe.on(K.STATE_CHANGE,(()=>{S()&&"suspended"===Oe.prevState&&"running"===Oe.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 E(g.PERMISSION_DENIED,"can not set sink id: "+e.toString())}}play(e,t,i,o){if(this.elementMap.has(t))return;const n=document.createElement("audio");n.autoplay=!0,n.srcObject=new MediaStream([e]),this.bindAudioElementEvents(t,n),this.elementMap.set(t,n),this.elementStateMap.set(t,ce.INIT),this.setVolume(t,i);const r=this.sinkIdMap.get(t);if(r)try{n.setSinkId(r).catch((e=>{F.warning("[".concat(t,"] set sink id failed"),e.toString())}))}catch(e){F.warning("[".concat(t,"] set sink id failed"),e.toString())}const a=n.play();a&&a.then&&a.catch((e=>{o&&We(o,"audio",e.message,t),F.warning("audio element play warning",e.toString()),this.elementMap.has(t)&&"NotAllowedError"===e.name&&(F.warning("detected audio element autoplay failed"),this.elementsNeedToResume.push(n),s((()=>{this.onAutoplayFailed&&this.onAutoplayFailed(),be()})))}))}updateTrack(e,t){const i=this.elementMap.get(e);i&&(i.srcObject=new MediaStream([t]))}isPlaying(e){return this.elementMap.has(e)&&"playing"===this.elementStateMap.get(e)}setVolume(e,t){const i=this.elementMap.get(e);i&&(t=Math.max(0,Math.min(100,t)),i.volume=t/100)}stop(e){const t=this.elementMap.get(e);if(this.sinkIdMap.delete(e),!t)return;const i=this.elementsNeedToResume.indexOf(t);this.elementsNeedToResume.splice(i,1),t.srcObject=null,t.remove(),this.elementMap.delete(e),this.elementStateMap.delete(e)}bindAudioElementEvents(e,t){Xe.forEach((i=>{t.addEventListener(i,(i=>{const s=this.elementStateMap.get(e),o="pause"===i.type?"paused":i.type;if(F.debug("[".concat(e,"] audio-element-status change ").concat(s," => ").concat(o)),"error"===i.type){const i=null==t?void 0:t.error;i&&F.error("[".concat(e,"] media error, code: ").concat(i.code,", message: ").concat(i.message))}this.elementStateMap.set(e,o)}))}))}getPlayerState(e){return this.elementStateMap.get(e)||"uninit"}autoResumeAudioElement(){const e=()=>{this.elementsNeedToResume.forEach((e=>{e.play().then((e=>{F.debug("Auto resume audio element success")})).catch((e=>{F.warning("Auto resume audio element failed!",e)}))})),this.elementsNeedToResume=[]};w().then((()=>{y()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0))}))}};class Je extends l{get isPlayed(){return!0}get isFreeze(){return!1}constructor(){super(),this.context=void 0,this.processSourceNode=void 0,this.outputTrack=void 0,this.processedNode=void 0,this.clonedTrack=void 0,this.outputNode=void 0,this.outputNode=new $e}setVolume(){}createOutputTrack(){throw new E(g.NOT_SUPPORTED,"can not create output MediaStreamTrack when WebAudio disabled")}getOriginVolumeLevel(){return 0}getAccurateVolumeLevel(){return 0}stopGetAudioBuffer(){}startGetAudioBuffer(){}play(){}stop(){}destroy(){}updateTrack(){}updateOriginTrack(){}createMediaStreamSourceNode(){}}class $e{disconnect(){}connect(){}}function et(e){return new Promise(((t,i)=>{let s=!1;const o=document.createElement("video");o.setAttribute("autoplay",""),o.setAttribute("muted",""),o.muted=!0,o.autoplay=!0,o.setAttribute("playsinline",""),o.setAttribute("style","position: fixed; top: 0; left: 0; width: 1px; height: 1px"),document.body.appendChild(o);const n=S()?"canplay":"playing";o.addEventListener(n,(()=>{const e=o.videoWidth,i=o.videoHeight;!e&&h()||(s=!0,o.srcObject=null,o.remove(),t([e,i]))})),o.srcObject=new MediaStream([e]),o.play().catch(O),setTimeout((()=>{s||(o.srcObject=null,o.remove(),t([o.videoWidth,o.videoHeight]))}),4e3)}))}class tt extends me{getUserId(){return this._userId}constructor(e,t,i,s){super(e,"track-".concat(e.kind,"-").concat(t,"-").concat(s.clientId,"_").concat(p(5,""))),this._userId=void 0,this._uintId=void 0,this._isDestroyed=!1,this.store=void 0,this.processor=void 0,this._userId=t,this._uintId=i,this.store=s}_updateOriginMediaStreamTrack(e){this._originMediaStreamTrack=e,this._mediaStreamTrack=e,this._updatePlayerSource(),this.processor&&this.processor.updateInput({track:this._originMediaStreamTrack,context:this.processorContext})}_destroy(){this._isDestroyed=!0,F.info("[".concat(this.getTrackId(),"] is destroyed")),this.stop(),super.close()}getProcessorStats(){return this.processorContext.gatherStats()}getProcessorUsage(){return this.processorContext.gatherUsage()}}class it extends tt{get isPlaying(){return!(!this._player||this._player.videoElementStatus!==ce.PLAYING)}get __className__(){return"RemoteVideoTrack"}constructor(e,t,i,s){super(e,t,i,s),this._videoVisibleTimer=null,this._previousVideoVisibleStatus=void 0,this._clearPreviousVideoVisibleStatus=()=>this._previousVideoVisibleStatus=void 0,this.trackMediaType="video",this._videoWidth=void 0,this._videoHeight=void 0,this._player=void 0,this.processorDestination=void 0,this.processorContext=void 0,this.updateMediaStreamTrackResolution(),this.processorContext=new _e(this.getTrackId(),"remote"),this.processorDestination=new Te(this.processorContext),this.bindProcessorDestinationEvents()}getStats(){C((()=>{F.warning("[deprecated] RemoteVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteVideoStats instead")}),"remoteVideoTrackGetStatsWarning");return M(this,Y.GET_STATS)||Ee({},se)}play(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("string"==typeof e){const t=document.getElementById(e);t?e=t:(F.warning("[".concat(this.getTrackId(),'] can not find "#').concat(e,'" element, use document.body')),e=document.body)}F.debug("[".concat(this.getTrackId(),"] start video playback in ").concat(e instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement"),JSON.stringify(t));const i=Ee(Ee({fit:"cover"},t),{},{trackId:this.getTrackId(),element:e});this._player?this._player.updateConfig(i):(e instanceof HTMLVideoElement?this._player=new je(i):this._player=new Ke(i),this._player.updateVideoTrack(this._mediaStreamTrack),this._player.onFirstVideoFrameDecoded=()=>{this.store.subscribe(this.getUserId(),"video",void 0,void 0,Date.now()),this.safeEmit($.FIRST_FRAME_DECODED)},this._player.onVideoStateChanged=e=>{this.safeEmit($.VIDEO_STATE_CHANGED,e)}),this._player.play(this.store.sessionId||void 0),this._videoVisibleTimer&&window.clearInterval(this._videoVisibleTimer),this._clearPreviousVideoVisibleStatus(),this._videoVisibleTimer=window.setInterval((()=>{try{const e=this.getVideoElementVisibleStatus();this.safeEmit($.VIDEO_ELEMENT_VISIBLE_STATUS,e)}catch(e){}}),u("CHECK_VIDEO_VISIBLE_INTERVAL"))}stop(){this._player&&(this._videoVisibleTimer&&(window.clearInterval(this._videoVisibleTimer),this._videoVisibleTimer=null),this._clearPreviousVideoVisibleStatus(),this._player.destroy(),this._player=void 0,F.debug("[".concat(this.getTrackId(),"] stop video playback")))}getCurrentFrameData(){return this._player?this._player.getCurrentFrame():new ImageData(2,2)}updateMediaStreamTrackResolution(){et(this._originMediaStreamTrack).then((e=>{let[t,i]=e;this._videoHeight=i,this._videoWidth=t})).catch(O)}_updatePlayerSource(){F.debug("[".concat(this.getTrackId(),"] update player source track")),this._player&&this._player.updateVideoTrack(this._mediaStreamTrack)}getVideoElementVisibleStatus(){try{var e,t;const i=null==this||null===(e=this._player)||void 0===e?void 0:e.getContainerElement(),s={track:this,element:null==this||null===(t=this._player)||void 0===t?void 0:t.getVideoElement(),slot:null==i?void 0:i.parentElement},{element:o,slot:n}=s;if(this.isPlaying&&o instanceof HTMLVideoElement&&n instanceof HTMLElement){const e=P.checkOneElementVisible(o),t=Object.assign({},e);if(t.visible!==this._previousVideoVisibleStatus){this._previousVideoVisibleStatus=t.visible;const e=B.reportApiInvoke(null,{tag:v.TRACER,name:m.REMOTE_VIDEO_TRACK_GET_VIDEO_VISIBLE,options:[this.getTrackId()]});t.visible?e.onSuccess("Video is visible"):e.onSuccess("Invisible because of ".concat(t.reason))}return t}return}catch(e){throw new E(g.GET_VIDEO_ELEMENT_VISIBLE_ERROR,e.message)}}pipe(e){if(this.processor===e)return e;if(e._source)throw new E(g.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,context:this.processorContext}),e}unpipe(){if(!this.processor)return;const e=this.processor;this.processor._source=void 0,this.processor=void 0,e.reset()}bindProcessorDestinationEvents(){this.processorDestination.on(oe.ON_TRACK,(async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource()):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource())}))}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(oe.ON_TRACK)}_destroy(){super._destroy(),this.unbindProcessorDestinationEvents()}_onSei(e){this.emit(J.SEI_RECEIVED,e)}}Se([H({argsMap:(e,t,i)=>[e.getTrackId(),"string"==typeof t?t:t instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement",i]}),Ie("design:type",Function),Ie("design:paramtypes",[Object,Object]),Ie("design:returntype",void 0)],it.prototype,"play",null),Se([H({argsMap:e=>[e.getTrackId()]}),Ie("design:type",Function),Ie("design:paramtypes",[]),Ie("design:returntype",void 0)],it.prototype,"stop",null),Se([H({argsMap:(e,t)=>[e.getTrackId(),t.name]}),Ie("design:type",Function),Ie("design:paramtypes",[Object]),Ie("design:returntype",Object)],it.prototype,"pipe",null),Se([H({argsMap:e=>[e.getTrackId()]}),Ie("design:type",Function),Ie("design:paramtypes",[]),Ie("design:returntype",void 0)],it.prototype,"unpipe",null);class st extends tt{get isPlaying(){return this._useAudioElement?Ze.isPlaying(this.getTrackId()):this._source.isPlayed}get __className__(){return"RemoteAudioTrack"}constructor(e,t,i,s){super(e,t,i,s),this.trackMediaType="audio",this._source=void 0,this._useAudioElement=!0,this._volume=100,this.processorContext=void 0,this.processorDestination=void 0,this._played=!1,this._bypassWebAudio=!1,u("DISABLE_WEBAUDIO")?(this._source=new Je,this._bypassWebAudio=!0,this._useAudioElement=!0):(this._source=new Qe(e,!0),u("REMOTE_AUDIO_TRACK_USES_WEB_AUDIO")&&(this._useAudioElement=!1)),this._source.once(ee.RECEIVE_TRACK_BUFFER,(()=>{this.safeEmit($.FIRST_FRAME_DECODED)})),this.processorContext=new fe(this._source.context,this.getTrackId(),"remote"),this.processorDestination=new ye(this.processorContext),this.bindProcessorDestinationEvents(),this._source.on(ee.UPDATE_SOURCE,(()=>{this.processor&&this.processor.updateInput({node:this._source.processSourceNode,context:this.processorContext})}))}setAudioFrameCallback(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:4096;if(!e)return this._source.removeAllListeners(ee.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(t),this._source.removeAllListeners(ee.ON_AUDIO_BUFFER),this._source.on(ee.ON_AUDIO_BUFFER,(t=>e(t)))}setVolume(e){this._volume=e,this._useAudioElement?Ze.setVolume(this.getTrackId(),e):this._source.setVolume(e/100)}async setPlaybackDevice(e){if(!this._useAudioElement||!V()&&u("RESTRICTION_SET_PLAYBACK_DEVICE"))throw new E(g.NOT_SUPPORTED,"your browser does not support setting the audio output device");await Ze.setSinkID(this.getTrackId(),e)}getVolumeLevel(){return this._source.getAccurateVolumeLevel()}getStats(){C((()=>{F.warning("[deprecated] RemoteAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteAudioStats instead")}),"remoteAudioTrackGetStatsWarning");return M(this,Y.GET_STATS)||Ee({},te)}play(){F.debug("[".concat(this.getTrackId(),"] start audio playback")),this._played=!0,this._useAudioElement?(F.debug("[".concat(this.getTrackId(),"] use audio element to play")),Ze.play(this._mediaStreamTrack,this.getTrackId(),this._volume,this.store.sessionId||void 0)):this._source.play()}stop(){F.debug("[".concat(this.getTrackId(),"] stop audio playback")),this._played=!1,this._useAudioElement?Ze.stop(this.getTrackId()):this._source.stop()}_destroy(){super._destroy(),this._played=!1,this.unbindProcessorDestinationEvents(),this._source.destroy()}_isFreeze(){return this._source.isFreeze}_updatePlayerSource(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];F.debug("[".concat(this.getTrackId(),"] update player source track")),e&&this._source.updateTrack(this._mediaStreamTrack),this._useAudioElement&&Ze.updateTrack(this.getTrackId(),this._mediaStreamTrack)}pipe(e){if(this._bypassWebAudio)throw new E(g.NOT_SUPPORTED,"can not pipe extension when WebAudio disabled");if(this.processor===e)return e;if(e._source)throw new E(g.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,node:this._source.processSourceNode,context:this.processorContext}),e}unpipe(){var e;if(this._bypassWebAudio)throw new E(g.NOT_SUPPORTED,"can not unpipe extension when WebAudio disabled");if(!this.processor)return;const t=this.processor;null===(e=this._source.processSourceNode)||void 0===e||e.disconnect(),this.processor._source=!1,this.processor=void 0,t.reset()}bindProcessorDestinationEvents(){this.processorDestination.on(oe.ON_TRACK,(async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(!1),this._source.processedNode=this._source.createMediaStreamSourceNode(e)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource())})),this.processorDestination.on(oe.ON_NODE,(e=>{this._source.processedNode=e;const t=!e;this._useAudioElement!==t&&(this._played?(this.stop(),this._useAudioElement=t,this.play()):this._useAudioElement=t)}))}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(oe.ON_TRACK),this.processorDestination.removeAllListeners(oe.ON_NODE)}}Se([H({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),Ie("design:type",Function),Ie("design:paramtypes",[Number]),Ie("design:returntype",void 0)],st.prototype,"setVolume",null),Se([H({argsMap:(e,t)=>[e.getTrackId(),t]}),Ie("design:type",Function),Ie("design:paramtypes",[String]),Ie("design:returntype",Promise)],st.prototype,"setPlaybackDevice",null),Se([H({argsMap:e=>[e.getTrackId()]}),Ie("design:type",Function),Ie("design:paramtypes",[]),Ie("design:returntype",void 0)],st.prototype,"play",null),Se([H({argsMap:e=>[e.getTrackId()]}),Ie("design:type",Function),Ie("design:paramtypes",[]),Ie("design:returntype",void 0)],st.prototype,"stop",null),Se([H({argsMap:(e,t)=>[e.getTrackId(),t.name]}),Ie("design:type",Function),Ie("design:paramtypes",[Object]),Ie("design:returntype",Object)],st.prototype,"pipe",null),Se([H({argsMap:e=>[e.getTrackId()]}),Ie("design:type",Function),Ie("design:paramtypes",[]),Ie("design:returntype",void 0)],st.prototype,"unpipe",null);const ot=new L("safari"),nt=!1,rt=!1;function at(e,t){switch(e){case"Starting video failed":case"OverconstrainedError":case"TrackStartError":return new E(g.MEDIA_OPTION_INVALID,"".concat(e,": ").concat(t));case"NotFoundError":case"DevicesNotFoundError":return new E(g.DEVICE_NOT_FOUND,"".concat(e,": ").concat(t));case"NotSupportedError":return new E(g.NOT_SUPPORTED,"".concat(e,": ").concat(t));case"NotReadableError":return new E(g.NOT_READABLE,"".concat(e,": ").concat(t));case"InvalidStateError":case"NotAllowedError":case"PERMISSION_DENIED":case"PermissionDeniedError":return new E(g.PERMISSION_DENIED,"".concat(e,": ").concat(t));case"ConstraintNotSatisfiedError":return new E(g.CONSTRAINT_NOT_SATISFIED,"".concat(e,": ").concat(t));default:return F.error("getUserMedia unexpected error",e),new E(g.UNEXPECTED_ERROR,"".concat(e,": ").concat(t))}}class ct extends l{get state(){return this._state}set state(e){e!==this._state&&(this.emit(ae.STATE_CHANGE,e),this._state=e)}constructor(){super(),this._state=re.IDLE,this.isAccessMicrophonePermission=!1,this.isAccessCameraPermission=!1,this.lastAccessMicrophonePermission=!1,this.lastAccessCameraPermission=!1,this.checkdeviceMatched=!1,this.deviceInfoMap=new Map,this.init().then((()=>{navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",this.updateDevicesInfo.bind(this)),window.setInterval((()=>{(u("ENUMERATE_DEVICES_INTERVAL")||(b()||U())&&i())&&this.updateDevicesInfo()}),u("ENUMERATE_DEVICES_INTERVAL_TIME"))})).catch((e=>F.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 E(g.NOT_SUPPORTED,"enumerateDevices() not supported.").throw()}const s=await navigator.mediaDevices.enumerateDevices(),o=this.checkMediaDeviceInfoIsOk(s);let n=!this.isAccessMicrophonePermission&&e,r=!this.isAccessCameraPermission&&t;o.audio&&(n=!1),o.video&&(r=!1);let a=null,c=null,d=null;if(!i&&(n||r)){if(ot.isLocked){F.debug("[device manager] wait GUM lock");(await ot.lock())(),F.debug("[device manager] GUM unlock")}if(F.debug("[device manager] check media device permissions",e,t,n,r),n&&r){try{d=await navigator.mediaDevices.getUserMedia({audio:!0,video:!0})}catch(e){const t=at(e.name||e.code||e,e.message);if(t.code===g.PERMISSION_DENIED)throw t;F.warning("getUserMedia failed in getDevices",t)}this.isAccessCameraPermission=!0,this.isAccessMicrophonePermission=!0}else if(n){try{a=await navigator.mediaDevices.getUserMedia({audio:e})}catch(e){const t=at(e.name||e.code||e,e.message);if(t.code===g.PERMISSION_DENIED)throw t;F.warning("getUserMedia failed in getDevices",t)}this.isAccessMicrophonePermission=!0}else if(r){try{c=await navigator.mediaDevices.getUserMedia({video:t})}catch(e){const t=at(e.name||e.code||e,e.message);if(t.code===g.PERMISSION_DENIED)throw t;F.warning("getUserMedia failed in getDevices",t)}this.isAccessCameraPermission=!0}F.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 E(g.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 E(g.DEVICE_NOT_FOUND,"deviceId: ".concat(e));return t}async init(){this.state=re.INITING;try{await this.updateDevicesInfo(),this.state=re.INITEND}catch(e){if(F.warning("Device Detection functionality cannot start properly.",e.toString()),this.state=re.IDLE,!x()){new E(g.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?F.debug("[device-check] default input ".concat(t.label," and output ").concat(i.label," is the same group")):F.warning("[device-check] default input ".concat(t.label," and output ").concat(i.label," is not the same group")):F.debug("[device-check] default input or output not found")}const s=this.checkMediaDeviceInfoIsOk(e);if(e.forEach((e=>{if(!e.deviceId)return;const s=this.deviceInfoMap.get("".concat(e.kind,"_").concat(e.deviceId));if("ACTIVE"!==(s?s.state:"INACTIVE")){const s={initAt:t,updateAt:t,device:e,state:"ACTIVE"};this.deviceInfoMap.set("".concat(e.kind,"_").concat(e.deviceId),s),i.push(s)}s&&(s.updateAt=t)})),this.deviceInfoMap.forEach(((e,s)=>{"ACTIVE"===e.state&&e.updateAt!==t&&(e.state="INACTIVE",i.push(e))})),this.state!==re.INITEND)return s.audio&&(this.lastAccessMicrophonePermission=!0,this.isAccessMicrophonePermission=!0),void(s.video&&(this.lastAccessCameraPermission=!0,this.isAccessCameraPermission=!0));i.forEach((e=>{switch(e.device.kind){case"audioinput":this.lastAccessMicrophonePermission&&this.isAccessMicrophonePermission&&this.emit(ae.RECORDING_DEVICE_CHANGED,e);break;case"videoinput":this.lastAccessCameraPermission&&this.isAccessCameraPermission&&this.emit(ae.CAMERA_DEVICE_CHANGED,e);break;case"audiooutput":this.lastAccessMicrophonePermission&&this.isAccessMicrophonePermission&&this.emit(ae.PLAYOUT_DEVICE_CHANGED,e)}})),s.audio&&(this.lastAccessMicrophonePermission=!0,this.isAccessMicrophonePermission=!0),s.video&&(this.lastAccessCameraPermission=!0,this.isAccessCameraPermission=!0)}checkMediaDeviceInfoIsOk(e){const t=e.filter((e=>"audioinput"===e.kind)),i=e.filter((e=>"videoinput"===e.kind)),s={audio:!1,video:!1};for(const e of t)if(e.label&&e.deviceId){s.audio=!0;break}for(const e of i)if(e.label&&e.deviceId){s.video=!0;break}return s}}const dt=new ct;const ut=new class extends l{get visibility(){return document.visibilityState}get lastHiddenTime(){return this._lastHiddenTime}get lastVisibleTime(){return this._lastVisibleTime}constructor(){super(),this._lastHiddenTime=0,this._lastVisibleTime=0,document.addEventListener("visibilitychange",(()=>{"hidden"===document.visibilityState?this._lastHiddenTime=performance.now():this._lastVisibleTime=performance.now(),F.debug("document visibility went ".concat(document.visibilityState)),this.emit("VISIBILITY_CHANGE",document.visibilityState)}))}};j();export{K as AUDIO_CONTEXT_EVENT,fe as AudioProcessorContext,ye as AudioProcessorDestination,ee as AudioSourceEvents,ie as DEFAULT_NETWORK_QUALITY_STATS,te as DEFAULT_REMOTE_AUDIO_TRACK_STATS,se as DEFAULT_REMOTE_VIDEO_TRACK_STATS,ct as DeviceManager,ae as DeviceManagerEvent,re as DeviceManagerState,nt as HAS_GUM_AUDIO,rt as HAS_GUM_VIDEO,ue as MediaElementNumStatus,ce as MediaElementStatus,ne as PROCESSOR_CONTEXT_EVENTS,oe as PROCESSOR_DESTINATION_EVENTS,st as RemoteAudioTrack,Z as RemoteStreamFallbackType,X as RemoteStreamType,tt as RemoteTrack,$ as RemoteTrackEvents,it as RemoteVideoTrack,ot as SAFARI_GLOBAL_GUM_LOCK,Q as StreamType,me as Track,J as TrackEvents,q as TrackHint,Y as TrackInternalEvent,_e as VideoProcessorContext,Te as VideoProcessorDestination,de as VideoState,he as __TRACK_LIST__,le as addTrack,Oe as audioContextState,Ze as audioElementPlayCenter,xe as audioTimerLoop,ke as autoPlayGestureEventEmitter,Ne as blob2Uint8Array,et as checkMediaStreamTrackResolution,Le as decodeAudioData,dt as deviceManager,Ae as emptyImage2TypedArray,Me as getAudioContext,z as getCompatibility,Be as getSilenceAudioTrack,He as getSilenceSamplesDuration,at as handleGetUserMediaError,Pe as hasAudioContext,Ve as polyfillAudioNode,pe as removeTrack,be as requestAutoplayGesture,Ge as silenceScriptProcessHandler,j as updateAgoraRTCCompatibility,ut as visibilityWatcher};
|