@agora-js/media 4.19.1 → 4.19.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  /**
2
- * AgoraWebSDK_N-v4.19.1-0-g605286cc Copyright AgoraInc.
2
+ * AgoraWebSDK_N-v4.19.2-0-g791c0f00 Copyright AgoraInc.
3
3
  */
4
4
 
5
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@agora-js/shared"),require("@agora-js/report"),require("axios"),require("webrtc-adapter"),require("pako")):"function"==typeof define&&define.amd?define(["exports","@agora-js/shared","@agora-js/report","axios","webrtc-adapter","pako"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).AgoraRTCMedia={},e.shared$8,e.report,e.Axios,null,e.pako)}(this,(function(e,t,r,i,o,n){"use strict";var a;e.AUDIO_CONTEXT_EVENT=void 0,(a=e.AUDIO_CONTEXT_EVENT||(e.AUDIO_CONTEXT_EVENT={})).IOS_15_16_INTERRUPTION_START="ios15_16-interruption-start",a.IOS_15_16_INTERRUPTION_END="ios15_16-interruption-end",a.IOS_INTERRUPTION_START="ios-interruption-start",a.IOS_INTERRUPTION_END="ios-interruption-end",a.STATE_CHANGE="state-change";var s="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function c(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var d=function(e){try{return!!e()}catch(e){return!0}},u=!d((function(){var e=function(){}.bind();return"function"!=typeof e||e.hasOwnProperty("prototype")})),l=u,h=Function.prototype,p=h.call,g=l&&h.bind.bind(p,p),m=l?g:function(e){return function(){return p.apply(e,arguments)}},f=m({}.isPrototypeOf),E=function(e){return e&&e.Math==Math&&e},T=E("object"==typeof globalThis&&globalThis)||E("object"==typeof window&&window)||E("object"==typeof self&&self)||E("object"==typeof s&&s)||function(){return this}()||s||Function("return this")(),v=u,_=Function.prototype,y=_.apply,S=_.call,A="object"==typeof Reflect&&Reflect.apply||(v?S.bind(y):function(){return S.apply(y,arguments)}),b=m,k=b({}.toString),I=b("".slice),C=function(e){return I(k(e),8,-1)},O=C,R=m,N=function(e){if("Function"===O(e))return R(e)},w="object"==typeof document&&document.all,D={all:w,IS_HTMLDDA:void 0===w&&void 0!==w},P=D.all,M=D.IS_HTMLDDA?function(e){return"function"==typeof e||e===P}:function(e){return"function"==typeof e},L={},V=!d((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})),x=u,U=Function.prototype.call,B=x?U.bind(U):function(){return U.apply(U,arguments)},F={},j={}.propertyIsEnumerable,H=Object.getOwnPropertyDescriptor,G=H&&!j.call({1:2},1);F.f=G?function(e){var t=H(this,e);return!!t&&t.enumerable}:j;var W,K,z=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},X=d,q=C,J=Object,Y=m("".split),Q=X((function(){return!J("z").propertyIsEnumerable(0)}))?function(e){return"String"==q(e)?Y(e,""):J(e)}:J,Z=function(e){return null==e},$=Z,ee=TypeError,te=function(e){if($(e))throw ee("Can't call method on "+e);return e},re=Q,ie=te,oe=function(e){return re(ie(e))},ne=M,ae=D.all,se=D.IS_HTMLDDA?function(e){return"object"==typeof e?null!==e:ne(e)||e===ae}:function(e){return"object"==typeof e?null!==e:ne(e)},ce={},de=ce,ue=T,le=M,he=function(e){return le(e)?e:void 0},pe=function(e,t){return arguments.length<2?he(de[e])||he(ue[e]):de[e]&&de[e][t]||ue[e]&&ue[e][t]},ge="undefined"!=typeof navigator&&String(navigator.userAgent)||"",me=T,fe=ge,Ee=me.process,Te=me.Deno,ve=Ee&&Ee.versions||Te&&Te.version,_e=ve&&ve.v8;_e&&(K=(W=_e.split("."))[0]>0&&W[0]<4?1:+(W[0]+W[1])),!K&&fe&&(!(W=fe.match(/Edge\/(\d+)/))||W[1]>=74)&&(W=fe.match(/Chrome\/(\d+)/))&&(K=+W[1]);var ye=K,Se=ye,Ae=d,be=T.String,ke=!!Object.getOwnPropertySymbols&&!Ae((function(){var e=Symbol();return!be(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&Se&&Se<41})),Ie=ke&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,Ce=pe,Oe=M,Re=f,Ne=Object,we=Ie?function(e){return"symbol"==typeof e}:function(e){var t=Ce("Symbol");return Oe(t)&&Re(t.prototype,Ne(e))},De=String,Pe=function(e){try{return De(e)}catch(e){return"Object"}},Me=M,Le=Pe,Ve=TypeError,xe=function(e){if(Me(e))return e;throw Ve(Le(e)+" is not a function")},Ue=xe,Be=Z,Fe=function(e,t){var r=e[t];return Be(r)?void 0:Ue(r)},je=B,He=M,Ge=se,We=TypeError,Ke={exports:{}},ze=T,Xe=Object.defineProperty,qe=function(e,t){try{Xe(ze,e,{value:t,configurable:!0,writable:!0})}catch(r){ze[e]=t}return t},Je="__core-js_shared__",Ye=T[Je]||qe(Je,{}),Qe=Ye;(Ke.exports=function(e,t){return Qe[e]||(Qe[e]=void 0!==t?t:{})})("versions",[]).push({version:"3.31.1",mode:"pure",copyright:"© 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.31.1/LICENSE",source:"https://github.com/zloirock/core-js"});var Ze=Ke.exports,$e=te,et=Object,tt=function(e){return et($e(e))},rt=tt,it=m({}.hasOwnProperty),ot=Object.hasOwn||function(e,t){return it(rt(e),t)},nt=m,at=0,st=Math.random(),ct=nt(1..toString),dt=function(e){return"Symbol("+(void 0===e?"":e)+")_"+ct(++at+st,36)},ut=Ze,lt=ot,ht=dt,pt=ke,gt=Ie,mt=T.Symbol,ft=ut("wks"),Et=gt?mt.for||mt:mt&&mt.withoutSetter||ht,Tt=function(e){return lt(ft,e)||(ft[e]=pt&&lt(mt,e)?mt[e]:Et("Symbol."+e)),ft[e]},vt=B,_t=se,yt=we,St=Fe,At=function(e,t){var r,i;if("string"===t&&He(r=e.toString)&&!Ge(i=je(r,e)))return i;if(He(r=e.valueOf)&&!Ge(i=je(r,e)))return i;if("string"!==t&&He(r=e.toString)&&!Ge(i=je(r,e)))return i;throw We("Can't convert object to primitive value")},bt=TypeError,kt=Tt("toPrimitive"),It=function(e,t){if(!_t(e)||yt(e))return e;var r,i=St(e,kt);if(i){if(void 0===t&&(t="default"),r=vt(i,e,t),!_t(r)||yt(r))return r;throw bt("Can't convert object to primitive value")}return void 0===t&&(t="number"),At(e,t)},Ct=we,Ot=function(e){var t=It(e,"string");return Ct(t)?t:t+""},Rt=se,Nt=T.document,wt=Rt(Nt)&&Rt(Nt.createElement),Dt=function(e){return wt?Nt.createElement(e):{}},Pt=Dt,Mt=!V&&!d((function(){return 7!=Object.defineProperty(Pt("div"),"a",{get:function(){return 7}}).a})),Lt=V,Vt=B,xt=F,Ut=z,Bt=oe,Ft=Ot,jt=ot,Ht=Mt,Gt=Object.getOwnPropertyDescriptor;L.f=Lt?Gt:function(e,t){if(e=Bt(e),t=Ft(t),Ht)try{return Gt(e,t)}catch(e){}if(jt(e,t))return Ut(!Vt(xt.f,e,t),e[t])};var Wt=d,Kt=M,zt=/#|\.prototype\./,Xt=function(e,t){var r=Jt[qt(e)];return r==Qt||r!=Yt&&(Kt(t)?Wt(t):!!t)},qt=Xt.normalize=function(e){return String(e).replace(zt,".").toLowerCase()},Jt=Xt.data={},Yt=Xt.NATIVE="N",Qt=Xt.POLYFILL="P",Zt=Xt,$t=xe,er=u,tr=N(N.bind),rr=function(e,t){return $t(e),void 0===t?e:er?tr(e,t):function(){return e.apply(t,arguments)}},ir={},or=V&&d((function(){return 42!=Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype})),nr=se,ar=String,sr=TypeError,cr=function(e){if(nr(e))return e;throw sr(ar(e)+" is not an object")},dr=V,ur=Mt,lr=or,hr=cr,pr=Ot,gr=TypeError,mr=Object.defineProperty,fr=Object.getOwnPropertyDescriptor,Er="enumerable",Tr="configurable",vr="writable";ir.f=dr?lr?function(e,t,r){if(hr(e),t=pr(t),hr(r),"function"==typeof e&&"prototype"===t&&"value"in r&&vr in r&&!r[vr]){var i=fr(e,t);i&&i[vr]&&(e[t]=r.value,r={configurable:Tr in r?r[Tr]:i[Tr],enumerable:Er in r?r[Er]:i[Er],writable:!1})}return mr(e,t,r)}:mr:function(e,t,r){if(hr(e),t=pr(t),hr(r),ur)try{return mr(e,t,r)}catch(e){}if("get"in r||"set"in r)throw gr("Accessors not supported");return"value"in r&&(e[t]=r.value),e};var _r=ir,yr=z,Sr=V?function(e,t,r){return _r.f(e,t,yr(1,r))}:function(e,t,r){return e[t]=r,e},Ar=T,br=A,kr=N,Ir=M,Cr=L.f,Or=Zt,Rr=ce,Nr=rr,wr=Sr,Dr=ot,Pr=function(e){var t=function(r,i,o){if(this instanceof t){switch(arguments.length){case 0:return new e;case 1:return new e(r);case 2:return new e(r,i)}return new e(r,i,o)}return br(e,this,arguments)};return t.prototype=e.prototype,t},Mr=function(e,t){var r,i,o,n,a,s,c,d,u,l=e.target,h=e.global,p=e.stat,g=e.proto,m=h?Ar:p?Ar[l]:(Ar[l]||{}).prototype,f=h?Rr:Rr[l]||wr(Rr,l,{})[l],E=f.prototype;for(n in t)i=!(r=Or(h?n:l+(p?".":"#")+n,e.forced))&&m&&Dr(m,n),s=f[n],i&&(c=e.dontCallGetSet?(u=Cr(m,n))&&u.value:m[n]),a=i&&c?c:t[n],i&&typeof s==typeof a||(d=e.bind&&i?Nr(a,Ar):e.wrap&&i?Pr(a):g&&Ir(a)?kr(a):a,(e.sham||a&&a.sham||s&&s.sham)&&wr(d,"sham",!0),wr(f,n,d),g&&(Dr(Rr,o=l+"Prototype")||wr(Rr,o,{}),wr(Rr[o],n,a),e.real&&E&&(r||!E[n])&&wr(E,n,a)))},Lr=Math.ceil,Vr=Math.floor,xr=Math.trunc||function(e){var t=+e;return(t>0?Vr:Lr)(t)},Ur=function(e){var t=+e;return t!=t||0===t?0:xr(t)},Br=Ur,Fr=Math.max,jr=Math.min,Hr=function(e,t){var r=Br(e);return r<0?Fr(r+t,0):jr(r,t)},Gr=Ur,Wr=Math.min,Kr=function(e){return e>0?Wr(Gr(e),9007199254740991):0},zr=function(e){return Kr(e.length)},Xr=oe,qr=Hr,Jr=zr,Yr=function(e){return function(t,r,i){var o,n=Xr(t),a=Jr(n),s=qr(i,a);if(e&&r!=r){for(;a>s;)if((o=n[s++])!=o)return!0}else for(;a>s;s++)if((e||s in n)&&n[s]===r)return e||s||0;return!e&&-1}},Qr={includes:Yr(!0),indexOf:Yr(!1)},Zr=Qr.includes;Mr({target:"Array",proto:!0,forced:d((function(){return!Array(1).includes()}))},{includes:function(e){return Zr(this,e,arguments.length>1?arguments[1]:void 0)}});var $r=ce,ei=function(e){return $r[e+"Prototype"]},ti=ei("Array").includes,ri=se,ii=C,oi=Tt("match"),ni=function(e){var t;return ri(e)&&(void 0!==(t=e[oi])?!!t:"RegExp"==ii(e))},ai=TypeError,si={};si[Tt("toStringTag")]="z";var ci="[object z]"===String(si),di=ci,ui=M,li=C,hi=Tt("toStringTag"),pi=Object,gi="Arguments"==li(function(){return arguments}()),mi=di?li:function(e){var t,r,i;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(r=function(e,t){try{return e[t]}catch(e){}}(t=pi(e),hi))?r:gi?li(t):"Object"==(i=li(t))&&ui(t.callee)?"Arguments":i},fi=mi,Ei=String,Ti=function(e){if("Symbol"===fi(e))throw TypeError("Cannot convert a Symbol value to a string");return Ei(e)},vi=Tt("match"),_i=Mr,yi=function(e){if(ni(e))throw ai("The method doesn't accept regular expressions");return e},Si=te,Ai=Ti,bi=function(e){var t=/./;try{"/./"[e](t)}catch(r){try{return t[vi]=!1,"/./"[e](t)}catch(e){}}return!1},ki=m("".indexOf);_i({target:"String",proto:!0,forced:!bi("includes")},{includes:function(e){return!!~ki(Ai(Si(this)),Ai(yi(e)),arguments.length>1?arguments[1]:void 0)}});var Ii=ei("String").includes,Ci=f,Oi=ti,Ri=Ii,Ni=Array.prototype,wi=String.prototype,Di=c((function(e){var t=e.includes;return e===Ni||Ci(Ni,e)&&t===Ni.includes?Oi:"string"==typeof e||e===wi||Ci(wi,e)&&t===wi.includes?Ri:t}));function Pi(e,t,r){return{sampleRate:e,stereo:t,bitrate:r}}function Mi(e,t,r,i,o){return{width:e,height:t,frameRate:r,bitrateMin:i,bitrateMax:o}}function Li(e,t,r,i,o){return{width:{max:e},height:{max:t},frameRate:r,bitrateMin:i,bitrateMax:o}}function Vi(e,t){return{numSpatialLayers:e,numTemporalLayers:t}}const xi={"90p":Mi(160,90),"90p_1":Mi(160,90),"120p":Mi(160,120,15,30,65),"120p_1":Mi(160,120,15,30,65),"120p_3":Mi(120,120,15,30,50),"120p_4":Mi(212,120),"180p":Mi(320,180,15,30,140),"180p_1":Mi(320,180,15,30,140),"180p_3":Mi(180,180,15,30,100),"180p_4":Mi(240,180,15,30,120),"240p":Mi(320,240,15,40,200),"240p_1":Mi(320,240,15,40,200),"240p_3":Mi(240,240,15,40,140),"240p_4":Mi(424,240,15,40,220),"360p":Mi(640,360,15,80,400),"360p_1":Mi(640,360,15,80,400),"360p_3":Mi(360,360,15,80,260),"360p_4":Mi(640,360,30,80,600),"360p_6":Mi(360,360,30,80,400),"360p_7":Mi(480,360,15,80,320),"360p_8":Mi(480,360,30,80,490),"360p_9":Mi(640,360,15,80,800),"360p_10":Mi(640,360,24,80,800),"360p_11":Mi(640,360,24,80,1e3),"480p":Mi(640,480,15,100,500),"480p_1":Mi(640,480,15,100,500),"480p_2":Mi(640,480,30,100,1e3),"480p_3":Mi(480,480,15,100,400),"480p_4":Mi(640,480,30,100,750),"480p_6":Mi(480,480,30,100,600),"480p_8":Mi(848,480,15,100,610),"480p_9":Mi(848,480,30,100,930),"480p_10":Mi(640,480,10,100,400),"720p":Mi(1280,720,15,120,1130),"720p_1":Mi(1280,720,15,120,1130),"720p_2":Mi(1280,720,30,120,2e3),"720p_3":Mi(1280,720,30,120,1710),"720p_5":Mi(960,720,15,120,910),"720p_6":Mi(960,720,30,120,1380),"1080p":Mi(1920,1080,15,120,2080),"1080p_1":Mi(1920,1080,15,120,2080),"1080p_2":Mi(1920,1080,30,120,3e3),"1080p_3":Mi(1920,1080,30,120,3150),"1080p_5":Mi(1920,1080,60,120,4780),"1440p":Mi(2560,1440,30,120,4850),"1440p_1":Mi(2560,1440,30,120,4850),"1440p_2":Mi(2560,1440,60,120,7350),"4k":Mi(3840,2160,30,120,8910),"4k_1":Mi(3840,2160,30,120,8910),"4k_3":Mi(3840,2160,60,120,13500)},Ui={"480p":Li(640,480,5),"480p_1":Li(640,480,5),"480p_2":Li(640,480,30),"480p_3":Li(640,480,15),"720p":Li(1280,720,5),"720p_1":Li(1280,720,5),"720p_2":Li(1280,720,30),"720p_3":Li(1280,720,15),"1080p":Li(1920,1080,5),"1080p_1":Li(1920,1080,5),"1080p_2":Li(1920,1080,30),"1080p_3":Li(1920,1080,15)},Bi={"1SL1TL":Vi(1,1),"3SL3TL":Vi(3,3),"2SL3TL":Vi(2,3)};function Fi(e){return e||(e="480p_1"),"string"==typeof e?Object.assign({},xi[e]):e}function ji(e){return"string"==typeof e?Object.assign({},Ui[e]):e}function Hi(e){return"string"==typeof e?Object.assign({},Bi[e]):e}const Gi={speech_low_quality:Pi(16e3,!1),speech_standard:Pi(32e3,!1,18),music_standard:Pi(48e3,!1),standard_stereo:Pi(48e3,!0,56),high_quality:Pi(48e3,!1,128),high_quality_stereo:Pi(48e3,!0,192)};function Wi(e){return"string"==typeof e?Object.assign({},Gi[e]):e}const Ki=[];function zi(e){Di(Ki).call(Ki,e)||Ki.push(e)}function Xi(e){const t=Ki.indexOf(e);-1!==t&&Ki.splice(t,1)}function qi(e){return t.checkValidConstrainLong(e.width,"config.width"),t.checkValidConstrainLong(e.height,"config.height"),void 0!==e.frameRate&&t.checkValidConstrainLong(e.frameRate,"config.frameRate"),void 0!==e.bitrateMax&&t.checkValidNumber(e.bitrateMax,"config.bitrateMax"),void 0!==e.bitrateMin&&t.checkValidNumber(e.bitrateMin,"config.bitrateMin"),!0}function Ji(e){return void 0!==e.sampleRate&&t.checkValidNumber(e.sampleRate,"config.sampleRate",0,96e3,!0),void 0!==e.sampleSize&&t.checkValidNumber(e.sampleRate,"config.sampleSize",0,128,!0),void 0!==e.stereo&&t.checkValidBoolean(e.stereo,"config.stereo"),void 0!==e.bitrate&&t.checkValidNumber(e.bitrate,"config.bitrate",0,1e4,!1),!0}function Yi(e){return t.checkValidEnum(e,"mediaSource",["screen","window","application"]),!0}var Qi,Zi,$i,eo,to,ro,io,oo;e.TrackInternalEvent=void 0,(Qi=e.TrackInternalEvent||(e.TrackInternalEvent={})).NEED_RENEGOTIATE="@need_renegotiate",Qi.NEED_REPLACE_TRACK="@need_replace_track",Qi.NEED_CLOSE="@need_close",Qi.NEED_ENABLE_TRACK="@need_enable_track",Qi.NEED_DISABLE_TRACK="@need_disable_track",Qi.NEED_SESSION_ID="@need_sid",Qi.SET_OPTIMIZATION_MODE="@set_optimization_mode",Qi.GET_STATS="@get_stats",Qi.GET_LOW_VIDEO_TRACK="@get_low_video_track",Qi.NEED_RESET_REMOTE_SDP="@need_reset_remote_sdp",Qi.NEED_UPDATE_VIDEO_ENCODER="@need_update_video_encoder",Qi.NEED_MUTE_TRACK="@need_mute_track",Qi.NEED_UNMUTE_TRACK="@need_unmute_track",e.TrackHint=void 0,(Zi=e.TrackHint||(e.TrackHint={})).SCREEN_TRACK="screen_track",Zi.CUSTOM_TRACK="custome_track",Zi.LOW_STREAM="low_stream",e.StreamType=void 0,($i=e.StreamType||(e.StreamType={}))[$i.HIGH_STREAM=0]="HIGH_STREAM",$i[$i.LOW_STREAM=1]="LOW_STREAM",e.RemoteStreamType=void 0,(eo=e.RemoteStreamType||(e.RemoteStreamType={}))[eo.HIGH_STREAM=0]="HIGH_STREAM",eo[eo.LOW_STREAM=1]="LOW_STREAM",e.RemoteStreamFallbackType=void 0,(to=e.RemoteStreamFallbackType||(e.RemoteStreamFallbackType={}))[to.DISABLE=0]="DISABLE",to[to.LOW_STREAM=1]="LOW_STREAM",to[to.AUDIO_ONLY=2]="AUDIO_ONLY",e.TrackEvents=void 0,(e.TrackEvents||(e.TrackEvents={})).TRANSCEIVER_UPDATED="transceiver-updated",e.LocalTrackEvents=void 0,(ro=e.LocalTrackEvents||(e.LocalTrackEvents={})).SOURCE_STATE_CHANGE="source-state-change",ro.TRACK_ENDED="track-ended",ro.BEAUTY_EFFECT_OVERLOAD="beauty-effect-overload",ro.VIDEO_ELEMENT_VISIBLE_STATUS="video-element-visible-status",ro.CLOSED="closed",e.RemoteTrackEvents=void 0,(io=e.RemoteTrackEvents||(e.RemoteTrackEvents={})).FIRST_FRAME_DECODED="first-frame-decoded",io.VIDEO_ELEMENT_VISIBLE_STATUS="video-element-visible-status",e.AudioSourceEvents=void 0,(oo=e.AudioSourceEvents||(e.AudioSourceEvents={})).AUDIO_SOURCE_STATE_CHANGE="audio_source_state_change",oo.RECEIVE_TRACK_BUFFER="receive_track_buffer",oo.ON_AUDIO_BUFFER="on_audio_buffer",oo.UPDATE_SOURCE="update_source",e.AUDIO_TRACK_EVENT=void 0,(e.AUDIO_TRACK_EVENT||(e.AUDIO_TRACK_EVENT={})).UPDATE_TRACK_SOURCE="update-track-source";const no={sendVolumeLevel:0,sendBitrate:0,sendBytes:0,sendPackets:0,sendPacketsLost:0,sendJitterMs:0,sendRttMs:0,currentPacketLossRate:0},ao={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},so={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},co={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 uo,lo,ho,po,go;e.PROCESSOR_DESTINATION_EVENTS=void 0,(uo=e.PROCESSOR_DESTINATION_EVENTS||(e.PROCESSOR_DESTINATION_EVENTS={})).ON_TRACK="on_track",uo.ON_NODE="on_node",e.PROCESSOR_CONTEXT_EVENTS=void 0,(lo=e.PROCESSOR_CONTEXT_EVENTS||(e.PROCESSOR_CONTEXT_EVENTS={})).REQUEST_UPDATE_CONSTRAINTS="request_update_constraints",lo.REQUEST_CONSTRAINTS="request_constraints",e.DeviceManagerState=void 0,(ho=e.DeviceManagerState||(e.DeviceManagerState={})).IDLE="IDLE",ho.INITING="INITING",ho.INITEND="INITEND",e.DeviceManagerEvent=void 0,(po=e.DeviceManagerEvent||(e.DeviceManagerEvent={})).STATE_CHANGE="state_change",po.RECORDING_DEVICE_CHANGED="recordingDeviceChanged",po.PLAYOUT_DEVICE_CHANGED="playoutDeviceChanged",po.CAMERA_DEVICE_CHANGED="cameraDeviceChanged",e.MediaElementStatus=void 0,(go=e.MediaElementStatus||(e.MediaElementStatus={})).NONE="none",go.INIT="init",go.CANPLAY="canplay",go.PLAYING="playing",go.PAUSED="paused",go.SUSPEND="suspend",go.STALLED="stalled",go.WAITING="waiting",go.ERROR="error",go.DESTROYED="destroyed",go.ABORT="abort",go.ENDED="ended",go.EMPTIED="emptied",go.LOADEDDATA="loadeddata";var mo;e.DataChannelEvents=void 0,(mo=e.DataChannelEvents||(e.DataChannelEvents={})).OPEN="open",mo.MESSAGE="message",mo.CLOSE="close",mo.CLOSING="closing",mo.ERROR="error";var fo={exports:{}},Eo=Mr,To=V,vo=ir.f;Eo({target:"Object",stat:!0,forced:Object.defineProperty!==vo,sham:!To},{defineProperty:vo});var _o=ce.Object,yo=fo.exports=function(e,t,r){return _o.defineProperty(e,t,r)};_o.defineProperty.sham&&(yo.sham=!0);var So=c(fo.exports),Ao=C,bo=Array.isArray||function(e){return"Array"==Ao(e)},ko=TypeError,Io=Ot,Co=ir,Oo=z,Ro=function(e,t,r){var i=Io(t);i in e?Co.f(e,i,Oo(0,r)):e[i]=r},No=M,wo=Ye,Do=m(Function.toString);No(wo.inspectSource)||(wo.inspectSource=function(e){return Do(e)});var Po=wo.inspectSource,Mo=m,Lo=d,Vo=M,xo=mi,Uo=Po,Bo=function(){},Fo=[],jo=pe("Reflect","construct"),Ho=/^\s*(?:class|function)\b/,Go=Mo(Ho.exec),Wo=!Ho.exec(Bo),Ko=function(e){if(!Vo(e))return!1;try{return jo(Bo,Fo,e),!0}catch(e){return!1}},zo=function(e){if(!Vo(e))return!1;switch(xo(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Wo||!!Go(Ho,Uo(e))}catch(e){return!0}};zo.sham=!0;var Xo=!jo||Lo((function(){var e;return Ko(Ko.call)||!Ko(Object)||!Ko((function(){e=!0}))||e}))?zo:Ko,qo=bo,Jo=Xo,Yo=se,Qo=Tt("species"),Zo=Array,$o=function(e){var t;return qo(e)&&(t=e.constructor,(Jo(t)&&(t===Zo||qo(t.prototype))||Yo(t)&&null===(t=t[Qo]))&&(t=void 0)),void 0===t?Zo:t},en=function(e,t){return new($o(e))(0===t?0:t)},tn=d,rn=ye,on=Tt("species"),nn=Mr,an=d,sn=bo,cn=se,dn=tt,un=zr,ln=function(e){if(e>9007199254740991)throw ko("Maximum allowed index exceeded");return e},hn=Ro,pn=en,gn=function(e){return rn>=51||!tn((function(){var t=[];return(t.constructor={})[on]=function(){return{foo:1}},1!==t[e](Boolean).foo}))},mn=ye,fn=Tt("isConcatSpreadable"),En=mn>=51||!an((function(){var e=[];return e[fn]=!1,e.concat()[0]!==e})),Tn=function(e){if(!cn(e))return!1;var t=e[fn];return void 0!==t?!!t:sn(e)};nn({target:"Array",proto:!0,arity:1,forced:!En||!gn("concat")},{concat:function(e){var t,r,i,o,n,a=dn(this),s=pn(a,0),c=0;for(t=-1,i=arguments.length;t<i;t++)if(Tn(n=-1===t?a:arguments[t]))for(o=un(n),ln(c+o),r=0;r<o;r++,c++)r in n&&hn(s,c,n[r]);else ln(c+1),hn(s,c++,n);return s.length=c,s}});var vn={},_n={},yn=ot,Sn=oe,An=Qr.indexOf,bn=_n,kn=m([].push),In=function(e,t){var r,i=Sn(e),o=0,n=[];for(r in i)!yn(bn,r)&&yn(i,r)&&kn(n,r);for(;t.length>o;)yn(i,r=t[o++])&&(~An(n,r)||kn(n,r));return n},Cn=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],On=In,Rn=Cn,Nn=Object.keys||function(e){return On(e,Rn)},wn=V,Dn=or,Pn=ir,Mn=cr,Ln=oe,Vn=Nn;vn.f=wn&&!Dn?Object.defineProperties:function(e,t){Mn(e);for(var r,i=Ln(t),o=Vn(t),n=o.length,a=0;n>a;)Pn.f(e,r=o[a++],i[r]);return e};var xn,Un=pe("document","documentElement"),Bn=dt,Fn=Ze("keys"),jn=function(e){return Fn[e]||(Fn[e]=Bn(e))},Hn=cr,Gn=vn,Wn=Cn,Kn=_n,zn=Un,Xn=Dt,qn="prototype",Jn="script",Yn=jn("IE_PROTO"),Qn=function(){},Zn=function(e){return"<"+Jn+">"+e+"</"+Jn+">"},$n=function(e){e.write(Zn("")),e.close();var t=e.parentWindow.Object;return e=null,t},ea=function(){try{xn=new ActiveXObject("htmlfile")}catch(e){}var e,t,r;ea="undefined"!=typeof document?document.domain&&xn?$n(xn):(t=Xn("iframe"),r="java"+Jn+":",t.style.display="none",zn.appendChild(t),t.src=String(r),(e=t.contentWindow.document).open(),e.write(Zn("document.F=Object")),e.close(),e.F):$n(xn);for(var i=Wn.length;i--;)delete ea[qn][Wn[i]];return ea()};Kn[Yn]=!0;var ta=Object.create||function(e,t){var r;return null!==e?(Qn[qn]=Hn(e),r=new Qn,Qn[qn]=null,r[Yn]=e):r=ea(),void 0===t?r:Gn.f(r,t)},ra={},ia=In,oa=Cn.concat("length","prototype");ra.f=Object.getOwnPropertyNames||function(e){return ia(e,oa)};var na={},aa=Hr,sa=zr,ca=Ro,da=Array,ua=Math.max,la=C,ha=oe,pa=ra.f,ga=function(e,t,r){for(var i=sa(e),o=aa(t,i),n=aa(void 0===r?i:r,i),a=da(ua(n-o,0)),s=0;o<n;o++,s++)ca(a,s,e[o]);return a.length=s,a},ma="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[];na.f=function(e){return ma&&"Window"==la(e)?function(e){try{return pa(e)}catch(e){return ga(ma)}}(e):pa(ha(e))};var fa={};fa.f=Object.getOwnPropertySymbols;var Ea=Sr,Ta=function(e,t,r,i){return i&&i.enumerable?e[t]=r:Ea(e,t,r),e},va=ir,_a=function(e,t,r){return va.f(e,t,r)},ya={},Sa=Tt;ya.f=Sa;var Aa,ba,ka,Ia=ce,Ca=ot,Oa=ya,Ra=ir.f,Na=function(e){var t=Ia.Symbol||(Ia.Symbol={});Ca(t,e)||Ra(t,e,{value:Oa.f(e)})},wa=B,Da=pe,Pa=Tt,Ma=Ta,La=function(){var e=Da("Symbol"),t=e&&e.prototype,r=t&&t.valueOf,i=Pa("toPrimitive");t&&!t[i]&&Ma(t,i,(function(e){return wa(r,this)}),{arity:1})},Va=mi,xa=ci?{}.toString:function(){return"[object "+Va(this)+"]"},Ua=ci,Ba=ir.f,Fa=Sr,ja=ot,Ha=xa,Ga=Tt("toStringTag"),Wa=function(e,t,r,i){if(e){var o=r?e:e.prototype;ja(o,Ga)||Ba(o,Ga,{configurable:!0,value:t}),i&&!Ua&&Fa(o,"toString",Ha)}},Ka=M,za=T.WeakMap,Xa=Ka(za)&&/native code/.test(String(za)),qa=T,Ja=se,Ya=Sr,Qa=ot,Za=Ye,$a=jn,es=_n,ts="Object already initialized",rs=qa.TypeError,is=qa.WeakMap;if(Xa||Za.state){var os=Za.state||(Za.state=new is);os.get=os.get,os.has=os.has,os.set=os.set,Aa=function(e,t){if(os.has(e))throw rs(ts);return t.facade=e,os.set(e,t),t},ba=function(e){return os.get(e)||{}},ka=function(e){return os.has(e)}}else{var ns=$a("state");es[ns]=!0,Aa=function(e,t){if(Qa(e,ns))throw rs(ts);return t.facade=e,Ya(e,ns,t),t},ba=function(e){return Qa(e,ns)?e[ns]:{}},ka=function(e){return Qa(e,ns)}}var as={set:Aa,get:ba,has:ka,enforce:function(e){return ka(e)?ba(e):Aa(e,{})},getterFor:function(e){return function(t){var r;if(!Ja(t)||(r=ba(t)).type!==e)throw rs("Incompatible receiver, "+e+" required");return r}}},ss=rr,cs=Q,ds=tt,us=zr,ls=en,hs=m([].push),ps=function(e){var t=1==e,r=2==e,i=3==e,o=4==e,n=6==e,a=7==e,s=5==e||n;return function(c,d,u,l){for(var h,p,g=ds(c),m=cs(g),f=ss(d,u),E=us(m),T=0,v=l||ls,_=t?v(c,E):r||a?v(c,0):void 0;E>T;T++)if((s||T in m)&&(p=f(h=m[T],T,g),e))if(t)_[T]=p;else if(p)switch(e){case 3:return!0;case 5:return h;case 6:return T;case 2:hs(_,h)}else switch(e){case 4:return!1;case 7:hs(_,h)}return n?-1:i||o?o:_}},gs={forEach:ps(0),map:ps(1),filter:ps(2),some:ps(3),every:ps(4),find:ps(5),findIndex:ps(6),filterReject:ps(7)},ms=Mr,fs=T,Es=B,Ts=m,vs=V,_s=ke,ys=d,Ss=ot,As=f,bs=cr,ks=oe,Is=Ot,Cs=Ti,Os=z,Rs=ta,Ns=Nn,ws=ra,Ds=na,Ps=fa,Ms=L,Ls=ir,Vs=vn,xs=F,Us=Ta,Bs=_a,Fs=Ze,js=_n,Hs=dt,Gs=Tt,Ws=ya,Ks=Na,zs=La,Xs=Wa,qs=as,Js=gs.forEach,Ys=jn("hidden"),Qs="Symbol",Zs="prototype",$s=qs.set,ec=qs.getterFor(Qs),tc=Object[Zs],rc=fs.Symbol,ic=rc&&rc[Zs],oc=fs.TypeError,nc=fs.QObject,ac=Ms.f,sc=Ls.f,cc=Ds.f,dc=xs.f,uc=Ts([].push),lc=Fs("symbols"),hc=Fs("op-symbols"),pc=Fs("wks"),gc=!nc||!nc[Zs]||!nc[Zs].findChild,mc=vs&&ys((function(){return 7!=Rs(sc({},"a",{get:function(){return sc(this,"a",{value:7}).a}})).a}))?function(e,t,r){var i=ac(tc,t);i&&delete tc[t],sc(e,t,r),i&&e!==tc&&sc(tc,t,i)}:sc,fc=function(e,t){var r=lc[e]=Rs(ic);return $s(r,{type:Qs,tag:e,description:t}),vs||(r.description=t),r},Ec=function(e,t,r){e===tc&&Ec(hc,t,r),bs(e);var i=Is(t);return bs(r),Ss(lc,i)?(r.enumerable?(Ss(e,Ys)&&e[Ys][i]&&(e[Ys][i]=!1),r=Rs(r,{enumerable:Os(0,!1)})):(Ss(e,Ys)||sc(e,Ys,Os(1,{})),e[Ys][i]=!0),mc(e,i,r)):sc(e,i,r)},Tc=function(e,t){bs(e);var r=ks(t),i=Ns(r).concat(Sc(r));return Js(i,(function(t){vs&&!Es(vc,r,t)||Ec(e,t,r[t])})),e},vc=function(e){var t=Is(e),r=Es(dc,this,t);return!(this===tc&&Ss(lc,t)&&!Ss(hc,t))&&(!(r||!Ss(this,t)||!Ss(lc,t)||Ss(this,Ys)&&this[Ys][t])||r)},_c=function(e,t){var r=ks(e),i=Is(t);if(r!==tc||!Ss(lc,i)||Ss(hc,i)){var o=ac(r,i);return!o||!Ss(lc,i)||Ss(r,Ys)&&r[Ys][i]||(o.enumerable=!0),o}},yc=function(e){var t=cc(ks(e)),r=[];return Js(t,(function(e){Ss(lc,e)||Ss(js,e)||uc(r,e)})),r},Sc=function(e){var t=e===tc,r=cc(t?hc:ks(e)),i=[];return Js(r,(function(e){!Ss(lc,e)||t&&!Ss(tc,e)||uc(i,lc[e])})),i};_s||(rc=function(){if(As(ic,this))throw oc("Symbol is not a constructor");var e=arguments.length&&void 0!==arguments[0]?Cs(arguments[0]):void 0,t=Hs(e),r=function(e){this===tc&&Es(r,hc,e),Ss(this,Ys)&&Ss(this[Ys],t)&&(this[Ys][t]=!1),mc(this,t,Os(1,e))};return vs&&gc&&mc(tc,t,{configurable:!0,set:r}),fc(t,e)},Us(ic=rc[Zs],"toString",(function(){return ec(this).tag})),Us(rc,"withoutSetter",(function(e){return fc(Hs(e),e)})),xs.f=vc,Ls.f=Ec,Vs.f=Tc,Ms.f=_c,ws.f=Ds.f=yc,Ps.f=Sc,Ws.f=function(e){return fc(Gs(e),e)},vs&&Bs(ic,"description",{configurable:!0,get:function(){return ec(this).description}})),ms({global:!0,constructor:!0,wrap:!0,forced:!_s,sham:!_s},{Symbol:rc}),Js(Ns(pc),(function(e){Ks(e)})),ms({target:Qs,stat:!0,forced:!_s},{useSetter:function(){gc=!0},useSimple:function(){gc=!1}}),ms({target:"Object",stat:!0,forced:!_s,sham:!vs},{create:function(e,t){return void 0===t?Rs(e):Tc(Rs(e),t)},defineProperty:Ec,defineProperties:Tc,getOwnPropertyDescriptor:_c}),ms({target:"Object",stat:!0,forced:!_s},{getOwnPropertyNames:yc}),zs(),Xs(rc,Qs),js[Ys]=!0;var Ac=ke&&!!Symbol.for&&!!Symbol.keyFor,bc=Mr,kc=pe,Ic=ot,Cc=Ti,Oc=Ze,Rc=Ac,Nc=Oc("string-to-symbol-registry"),wc=Oc("symbol-to-string-registry");bc({target:"Symbol",stat:!0,forced:!Rc},{for:function(e){var t=Cc(e);if(Ic(Nc,t))return Nc[t];var r=kc("Symbol")(t);return Nc[t]=r,wc[r]=t,r}});var Dc=Mr,Pc=ot,Mc=we,Lc=Pe,Vc=Ac,xc=Ze("symbol-to-string-registry");Dc({target:"Symbol",stat:!0,forced:!Vc},{keyFor:function(e){if(!Mc(e))throw TypeError(Lc(e)+" is not a symbol");if(Pc(xc,e))return xc[e]}});var Uc=m([].slice),Bc=bo,Fc=M,jc=C,Hc=Ti,Gc=m([].push),Wc=Mr,Kc=pe,zc=A,Xc=B,qc=m,Jc=d,Yc=M,Qc=we,Zc=Uc,$c=function(e){if(Fc(e))return e;if(Bc(e)){for(var t=e.length,r=[],i=0;i<t;i++){var o=e[i];"string"==typeof o?Gc(r,o):"number"!=typeof o&&"Number"!=jc(o)&&"String"!=jc(o)||Gc(r,Hc(o))}var n=r.length,a=!0;return function(e,t){if(a)return a=!1,t;if(Bc(this))return t;for(var i=0;i<n;i++)if(r[i]===e)return t}}},ed=ke,td=String,rd=Kc("JSON","stringify"),id=qc(/./.exec),od=qc("".charAt),nd=qc("".charCodeAt),ad=qc("".replace),sd=qc(1..toString),cd=/[\uD800-\uDFFF]/g,dd=/^[\uD800-\uDBFF]$/,ud=/^[\uDC00-\uDFFF]$/,ld=!ed||Jc((function(){var e=Kc("Symbol")();return"[null]"!=rd([e])||"{}"!=rd({a:e})||"{}"!=rd(Object(e))})),hd=Jc((function(){return'"\\udf06\\ud834"'!==rd("\udf06\ud834")||'"\\udead"'!==rd("\udead")})),pd=function(e,t){var r=Zc(arguments),i=$c(t);if(Yc(i)||void 0!==e&&!Qc(e))return r[1]=function(e,t){if(Yc(i)&&(t=Xc(i,this,td(e),t)),!Qc(t))return t},zc(rd,null,r)},gd=function(e,t,r){var i=od(r,t-1),o=od(r,t+1);return id(dd,e)&&!id(ud,o)||id(ud,e)&&!id(dd,i)?"\\u"+sd(nd(e,0),16):e};rd&&Wc({target:"JSON",stat:!0,arity:3,forced:ld||hd},{stringify:function(e,t,r){var i=Zc(arguments),o=zc(ld?pd:rd,null,i);return hd&&"string"==typeof o?ad(o,cd,gd):o}});var md=fa,fd=tt;Mr({target:"Object",stat:!0,forced:!ke||d((function(){md.f(1)}))},{getOwnPropertySymbols:function(e){var t=md.f;return t?t(fd(e)):[]}}),Na("asyncIterator"),Na("hasInstance"),Na("isConcatSpreadable"),Na("iterator"),Na("match"),Na("matchAll"),Na("replace"),Na("search"),Na("species"),Na("split");var Ed=La;Na("toPrimitive"),Ed();var Td=pe,vd=Wa;Na("toStringTag"),vd(Td("Symbol"),"Symbol"),Na("unscopables"),Wa(T.JSON,"JSON",!0);var _d,yd,Sd,Ad=ce.Symbol,bd={},kd=V,Id=ot,Cd=Function.prototype,Od=kd&&Object.getOwnPropertyDescriptor,Rd=Id(Cd,"name"),Nd={EXISTS:Rd,PROPER:Rd&&"something"===function(){}.name,CONFIGURABLE:Rd&&(!kd||kd&&Od(Cd,"name").configurable)},wd=!d((function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype})),Dd=ot,Pd=M,Md=tt,Ld=wd,Vd=jn("IE_PROTO"),xd=Object,Ud=xd.prototype,Bd=Ld?xd.getPrototypeOf:function(e){var t=Md(e);if(Dd(t,Vd))return t[Vd];var r=t.constructor;return Pd(r)&&t instanceof r?r.prototype:t instanceof xd?Ud:null},Fd=d,jd=M,Hd=se,Gd=ta,Wd=Bd,Kd=Ta,zd=Tt("iterator"),Xd=!1;[].keys&&("next"in(Sd=[].keys())?(yd=Wd(Wd(Sd)))!==Object.prototype&&(_d=yd):Xd=!0);var qd=!Hd(_d)||Fd((function(){var e={};return _d[zd].call(e)!==e}));jd((_d=qd?{}:Gd(_d))[zd])||Kd(_d,zd,(function(){return this}));var Jd={IteratorPrototype:_d,BUGGY_SAFARI_ITERATORS:Xd},Yd=Jd.IteratorPrototype,Qd=ta,Zd=z,$d=Wa,eu=bd,tu=function(){return this},ru=m,iu=xe,ou=M,nu=String,au=TypeError,su=function(e,t,r){try{return ru(iu(Object.getOwnPropertyDescriptor(e,t)[r]))}catch(e){}},cu=cr,du=function(e){if("object"==typeof e||ou(e))return e;throw au("Can't set "+nu(e)+" as a prototype")},uu=Object.setPrototypeOf||("__proto__"in{}?function(){var e,t=!1,r={};try{(e=su(Object.prototype,"__proto__","set"))(r,[]),t=r instanceof Array}catch(e){}return function(r,i){return cu(r),du(i),t?e(r,i):r.__proto__=i,r}}():void 0),lu=Mr,hu=B,pu=Nd,gu=function(e,t,r,i){var o=t+" Iterator";return e.prototype=Qd(Yd,{next:Zd(+!i,r)}),$d(e,o,!1,!0),eu[o]=tu,e},mu=Bd,fu=Wa,Eu=Ta,Tu=bd,vu=Jd,_u=pu.PROPER,yu=vu.BUGGY_SAFARI_ITERATORS,Su=Tt("iterator"),Au="keys",bu="values",ku="entries",Iu=function(){return this},Cu=function(e,t,r,i,o,n,a){gu(r,t,i);var s,c,d,u=function(e){if(e===o&&m)return m;if(!yu&&e in p)return p[e];switch(e){case Au:case bu:case ku:return function(){return new r(this,e)}}return function(){return new r(this)}},l=t+" Iterator",h=!1,p=e.prototype,g=p[Su]||p["@@iterator"]||o&&p[o],m=!yu&&g||u(o),f="Array"==t&&p.entries||g;if(f&&(s=mu(f.call(new e)))!==Object.prototype&&s.next&&(fu(s,l,!0,!0),Tu[l]=Iu),_u&&o==bu&&g&&g.name!==bu&&(h=!0,m=function(){return hu(g,this)}),o)if(c={values:u(bu),keys:n?m:u(Au),entries:u(ku)},a)for(d in c)(yu||h||!(d in p))&&Eu(p,d,c[d]);else lu({target:t,proto:!0,forced:yu||h},c);return a&&p[Su]!==m&&Eu(p,Su,m,{name:o}),Tu[t]=m,c},Ou=function(e,t){return{value:e,done:t}},Ru=oe,Nu=bd,wu=as;ir.f;var Du=Cu,Pu=Ou,Mu="Array Iterator",Lu=wu.set,Vu=wu.getterFor(Mu);Du(Array,"Array",(function(e,t){Lu(this,{type:Mu,target:Ru(e),index:0,kind:t})}),(function(){var e=Vu(this),t=e.target,r=e.kind,i=e.index++;return!t||i>=t.length?(e.target=void 0,Pu(void 0,!0)):Pu("keys"==r?i:"values"==r?t[i]:[i,t[i]],!1)}),"values"),Nu.Arguments=Nu.Array;var xu={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0},Uu=T,Bu=mi,Fu=Sr,ju=bd,Hu=Tt("toStringTag");for(var Gu in xu){var Wu=Uu[Gu],Ku=Wu&&Wu.prototype;Ku&&Bu(Ku)!==Hu&&Fu(Ku,Hu,Gu),ju[Gu]=ju.Array}var zu=Ad,Xu=Tt,qu=ir.f,Ju=Xu("metadata"),Yu=Function.prototype;void 0===Yu[Ju]&&qu(Yu,Ju,{value:null}),Na("dispose"),Na("metadata");var Qu=zu;Na("asyncDispose");var Zu=m,$u=pe("Symbol"),el=$u.keyFor,tl=Zu($u.prototype.valueOf),rl=$u.isRegisteredSymbol||function(e){try{return void 0!==el(tl(e))}catch(e){return!1}};Mr({target:"Symbol",stat:!0},{isRegisteredSymbol:rl});for(var il=Ze,ol=pe,nl=m,al=we,sl=Tt,cl=ol("Symbol"),dl=cl.isWellKnownSymbol,ul=ol("Object","getOwnPropertyNames"),ll=nl(cl.prototype.valueOf),hl=il("wks"),pl=0,gl=ul(cl),ml=gl.length;pl<ml;pl++)try{var fl=gl[pl];al(cl[fl])&&sl(fl)}catch(e){}var El=function(e){if(dl&&dl(e))return!0;try{for(var t=ll(e),r=0,i=ul(hl),o=i.length;r<o;r++)if(hl[i[r]]==t)return!0}catch(e){}return!1};Mr({target:"Symbol",stat:!0,forced:!0},{isWellKnownSymbol:El}),Na("matcher"),Na("observable"),Mr({target:"Symbol",stat:!0,name:"isRegisteredSymbol"},{isRegistered:rl}),Mr({target:"Symbol",stat:!0,name:"isWellKnownSymbol",forced:!0},{isWellKnown:El}),Na("metadataKey"),Na("patternMatch"),Na("replaceAll");var Tl=c(Qu),vl=m,_l=Ur,yl=Ti,Sl=te,Al=vl("".charAt),bl=vl("".charCodeAt),kl=vl("".slice),Il=function(e){return function(t,r){var i,o,n=yl(Sl(t)),a=_l(r),s=n.length;return a<0||a>=s?e?"":void 0:(i=bl(n,a))<55296||i>56319||a+1===s||(o=bl(n,a+1))<56320||o>57343?e?Al(n,a):i:e?kl(n,a,a+2):o-56320+(i-55296<<10)+65536}},Cl={codeAt:Il(!1),charAt:Il(!0)}.charAt,Ol=Ti,Rl=as,Nl=Cu,wl=Ou,Dl="String Iterator",Pl=Rl.set,Ml=Rl.getterFor(Dl);Nl(String,"String",(function(e){Pl(this,{type:Dl,string:Ol(e),index:0})}),(function(){var e,t=Ml(this),r=t.string,i=t.index;return i>=r.length?wl(void 0,!0):(e=Cl(r,i),t.index+=e.length,wl(e,!1))}));var Ll=c(ya.f("iterator"));function Vl(e){return Vl="function"==typeof Tl&&"symbol"==typeof Ll?function(e){return typeof e}:function(e){return e&&"function"==typeof Tl&&e.constructor===Tl&&e!==Tl.prototype?"symbol":typeof e},Vl(e)}var xl=c(ya.f("toPrimitive"));function Ul(e){var t=function(e,t){if("object"!==Vl(e)||null===e)return e;var r=e[xl];if(void 0!==r){var i=r.call(e,t||"default");if("object"!==Vl(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"===Vl(t)?t:String(t)}function Bl(e,t,r){return(t=Ul(t))in e?So(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}var Fl=pe,jl=ra,Hl=fa,Gl=cr,Wl=m([].concat),Kl=Fl("Reflect","ownKeys")||function(e){var t=jl.f(Gl(e)),r=Hl.f;return r?Wl(t,r(e)):t},zl=ot,Xl=Kl,ql=L,Jl=ir,Yl=se,Ql=Sr,Zl=Error,$l=m("".replace),eh=String(Zl("zxcasd").stack),th=/\n\s*at [^:]*:[^\n]*/,rh=th.test(eh),ih=z,oh=!d((function(){var e=Error("a");return!("stack"in e)||(Object.defineProperty(e,"stack",ih(1,7)),7!==e.stack)})),nh=Sr,ah=function(e,t){if(rh&&"string"==typeof e&&!Zl.prepareStackTrace)for(;t--;)e=$l(e,th,"");return e},sh=oh,ch=Error.captureStackTrace,dh=bd,uh=Tt("iterator"),lh=Array.prototype,hh=mi,ph=Fe,gh=Z,mh=bd,fh=Tt("iterator"),Eh=function(e){if(!gh(e))return ph(e,fh)||ph(e,"@@iterator")||mh[hh(e)]},Th=B,vh=xe,_h=cr,yh=Pe,Sh=Eh,Ah=TypeError,bh=B,kh=cr,Ih=Fe,Ch=rr,Oh=B,Rh=cr,Nh=Pe,wh=function(e){return void 0!==e&&(dh.Array===e||lh[uh]===e)},Dh=zr,Ph=f,Mh=function(e,t){var r=arguments.length<2?Sh(e):t;if(vh(r))return _h(Th(r,e));throw Ah(yh(e)+" is not iterable")},Lh=Eh,Vh=function(e,t,r){var i,o;kh(e);try{if(!(i=Ih(e,"return"))){if("throw"===t)throw r;return r}i=bh(i,e)}catch(e){o=!0,i=e}if("throw"===t)throw r;if(o)throw i;return kh(i),r},xh=TypeError,Uh=function(e,t){this.stopped=e,this.result=t},Bh=Uh.prototype,Fh=function(e,t,r){var i,o,n,a,s,c,d,u=r&&r.that,l=!(!r||!r.AS_ENTRIES),h=!(!r||!r.IS_RECORD),p=!(!r||!r.IS_ITERATOR),g=!(!r||!r.INTERRUPTED),m=Ch(t,u),f=function(e){return i&&Vh(i,"normal",e),new Uh(!0,e)},E=function(e){return l?(Rh(e),g?m(e[0],e[1],f):m(e[0],e[1])):g?m(e,f):m(e)};if(h)i=e.iterator;else if(p)i=e;else{if(!(o=Lh(e)))throw xh(Nh(e)+" is not iterable");if(wh(o)){for(n=0,a=Dh(e);a>n;n++)if((s=E(e[n]))&&Ph(Bh,s))return s;return new Uh(!1)}i=Mh(e,o)}for(c=h?e.next:i.next;!(d=Oh(c,i)).done;){try{s=E(d.value)}catch(e){Vh(i,"throw",e)}if("object"==typeof s&&s&&Ph(Bh,s))return s}return new Uh(!1)},jh=Ti,Hh=Mr,Gh=f,Wh=Bd,Kh=uu,zh=function(e,t,r){for(var i=Xl(t),o=Jl.f,n=ql.f,a=0;a<i.length;a++){var s=i[a];zl(e,s)||r&&zl(r,s)||o(e,s,n(t,s))}},Xh=ta,qh=Sr,Jh=z,Yh=function(e,t){Yl(t)&&"cause"in t&&Ql(e,"cause",t.cause)},Qh=function(e,t,r,i){sh&&(ch?ch(e,t):nh(e,"stack",ah(r,i)))},Zh=Fh,$h=function(e,t){return void 0===e?arguments.length<2?"":t:jh(e)},ep=Tt("toStringTag"),tp=Error,rp=[].push,ip=function(e,t){var r,i=Gh(op,this);Kh?r=Kh(tp(),i?Wh(this):op):(r=i?this:Xh(op),qh(r,ep,"Error")),void 0!==t&&qh(r,"message",$h(t)),Qh(r,ip,r.stack,1),arguments.length>2&&Yh(r,arguments[2]);var o=[];return Zh(e,rp,{that:o}),qh(r,"errors",o),r};Kh?Kh(ip,tp):zh(ip,tp,{name:!0});var op=ip.prototype=Xh(tp.prototype,{constructor:Jh(1,ip),message:Jh(1,""),name:Jh(1,"AggregateError")});Hh({global:!0,constructor:!0,arity:2},{AggregateError:ip});var np,ap,sp,cp,dp="undefined"!=typeof process&&"process"==C(process),up=pe,lp=_a,hp=V,pp=Tt("species"),gp=f,mp=TypeError,fp=Xo,Ep=Pe,Tp=TypeError,vp=cr,_p=function(e){if(fp(e))return e;throw Tp(Ep(e)+" is not a constructor")},yp=Z,Sp=Tt("species"),Ap=function(e,t){var r,i=vp(e).constructor;return void 0===i||yp(r=vp(i)[Sp])?t:_p(r)},bp=TypeError,kp=/(?:ipad|iphone|ipod).*applewebkit/i.test(ge),Ip=T,Cp=A,Op=rr,Rp=M,Np=ot,wp=d,Dp=Un,Pp=Uc,Mp=Dt,Lp=function(e,t){if(e<t)throw bp("Not enough arguments");return e},Vp=kp,xp=dp,Up=Ip.setImmediate,Bp=Ip.clearImmediate,Fp=Ip.process,jp=Ip.Dispatch,Hp=Ip.Function,Gp=Ip.MessageChannel,Wp=Ip.String,Kp=0,zp={},Xp="onreadystatechange";wp((function(){np=Ip.location}));var qp=function(e){if(Np(zp,e)){var t=zp[e];delete zp[e],t()}},Jp=function(e){return function(){qp(e)}},Yp=function(e){qp(e.data)},Qp=function(e){Ip.postMessage(Wp(e),np.protocol+"//"+np.host)};Up&&Bp||(Up=function(e){Lp(arguments.length,1);var t=Rp(e)?e:Hp(e),r=Pp(arguments,1);return zp[++Kp]=function(){Cp(t,void 0,r)},ap(Kp),Kp},Bp=function(e){delete zp[e]},xp?ap=function(e){Fp.nextTick(Jp(e))}:jp&&jp.now?ap=function(e){jp.now(Jp(e))}:Gp&&!Vp?(cp=(sp=new Gp).port2,sp.port1.onmessage=Yp,ap=Op(cp.postMessage,cp)):Ip.addEventListener&&Rp(Ip.postMessage)&&!Ip.importScripts&&np&&"file:"!==np.protocol&&!wp(Qp)?(ap=Qp,Ip.addEventListener("message",Yp,!1)):ap=Xp in Mp("script")?function(e){Dp.appendChild(Mp("script"))[Xp]=function(){Dp.removeChild(this),qp(e)}}:function(e){setTimeout(Jp(e),0)});var Zp={set:Up,clear:Bp},$p=function(){this.head=null,this.tail=null};$p.prototype={add:function(e){var t={item:e,next:null},r=this.tail;r?r.next=t:this.head=t,this.tail=t},get:function(){var e=this.head;if(e)return null===(this.head=e.next)&&(this.tail=null),e.item}};var eg,tg,rg,ig,og,ng=$p,ag=/ipad|iphone|ipod/i.test(ge)&&"undefined"!=typeof Pebble,sg=/web0s(?!.*chrome)/i.test(ge),cg=T,dg=rr,ug=L.f,lg=Zp.set,hg=ng,pg=kp,gg=ag,mg=sg,fg=dp,Eg=cg.MutationObserver||cg.WebKitMutationObserver,Tg=cg.document,vg=cg.process,_g=cg.Promise,yg=ug(cg,"queueMicrotask"),Sg=yg&&yg.value;if(!Sg){var Ag=new hg,bg=function(){var e,t;for(fg&&(e=vg.domain)&&e.exit();t=Ag.get();)try{t()}catch(e){throw Ag.head&&eg(),e}e&&e.enter()};pg||fg||mg||!Eg||!Tg?!gg&&_g&&_g.resolve?((ig=_g.resolve(void 0)).constructor=_g,og=dg(ig.then,ig),eg=function(){og(bg)}):fg?eg=function(){vg.nextTick(bg)}:(lg=dg(lg,cg),eg=function(){lg(bg)}):(tg=!0,rg=Tg.createTextNode(""),new Eg(bg).observe(rg,{characterData:!0}),eg=function(){rg.data=tg=!tg}),Sg=function(e){Ag.head||eg(),Ag.add(e)}}var kg=Sg,Ig=function(e){try{return{error:!1,value:e()}}catch(e){return{error:!0,value:e}}},Cg=T.Promise,Og="object"==typeof Deno&&Deno&&"object"==typeof Deno.version,Rg=!Og&&!dp&&"object"==typeof window&&"object"==typeof document,Ng=T,wg=Cg,Dg=M,Pg=Zt,Mg=Po,Lg=Tt,Vg=Rg,xg=Og,Ug=ye,Bg=wg&&wg.prototype,Fg=Lg("species"),jg=!1,Hg=Dg(Ng.PromiseRejectionEvent),Gg=Pg("Promise",(function(){var e=Mg(wg),t=e!==String(wg);if(!t&&66===Ug)return!0;if(!Bg.catch||!Bg.finally)return!0;if(!Ug||Ug<51||!/native code/.test(e)){var r=new wg((function(e){e(1)})),i=function(e){e((function(){}),(function(){}))};if((r.constructor={})[Fg]=i,!(jg=r.then((function(){}))instanceof i))return!0}return!t&&(Vg||xg)&&!Hg})),Wg={CONSTRUCTOR:Gg,REJECTION_EVENT:Hg,SUBCLASSING:jg},Kg={},zg=xe,Xg=TypeError,qg=function(e){var t,r;this.promise=new e((function(e,i){if(void 0!==t||void 0!==r)throw Xg("Bad Promise constructor");t=e,r=i})),this.resolve=zg(t),this.reject=zg(r)};Kg.f=function(e){return new qg(e)};var Jg,Yg,Qg=Mr,Zg=dp,$g=T,em=B,tm=Ta,rm=Wa,im=function(e){var t=up(e);hp&&t&&!t[pp]&&lp(t,pp,{configurable:!0,get:function(){return this}})},om=xe,nm=M,am=se,sm=function(e,t){if(gp(t,e))return e;throw mp("Incorrect invocation")},cm=Ap,dm=Zp.set,um=kg,lm=function(e,t){try{1==arguments.length?console.error(e):console.error(e,t)}catch(e){}},hm=Ig,pm=ng,gm=as,mm=Cg,fm=Wg,Em=Kg,Tm="Promise",vm=fm.CONSTRUCTOR,_m=fm.REJECTION_EVENT,ym=gm.getterFor(Tm),Sm=gm.set,Am=mm&&mm.prototype,bm=mm,km=Am,Im=$g.TypeError,Cm=$g.document,Om=$g.process,Rm=Em.f,Nm=Rm,wm=!!(Cm&&Cm.createEvent&&$g.dispatchEvent),Dm="unhandledrejection",Pm=function(e){var t;return!(!am(e)||!nm(t=e.then))&&t},Mm=function(e,t){var r,i,o,n=t.value,a=1==t.state,s=a?e.ok:e.fail,c=e.resolve,d=e.reject,u=e.domain;try{s?(a||(2===t.rejection&&Bm(t),t.rejection=1),!0===s?r=n:(u&&u.enter(),r=s(n),u&&(u.exit(),o=!0)),r===e.promise?d(Im("Promise-chain cycle")):(i=Pm(r))?em(i,r,c,d):c(r)):d(n)}catch(e){u&&!o&&u.exit(),d(e)}},Lm=function(e,t){e.notified||(e.notified=!0,um((function(){for(var r,i=e.reactions;r=i.get();)Mm(r,e);e.notified=!1,t&&!e.rejection&&xm(e)})))},Vm=function(e,t,r){var i,o;wm?((i=Cm.createEvent("Event")).promise=t,i.reason=r,i.initEvent(e,!1,!0),$g.dispatchEvent(i)):i={promise:t,reason:r},!_m&&(o=$g["on"+e])?o(i):e===Dm&&lm("Unhandled promise rejection",r)},xm=function(e){em(dm,$g,(function(){var t,r=e.facade,i=e.value;if(Um(e)&&(t=hm((function(){Zg?Om.emit("unhandledRejection",i,r):Vm(Dm,r,i)})),e.rejection=Zg||Um(e)?2:1,t.error))throw t.value}))},Um=function(e){return 1!==e.rejection&&!e.parent},Bm=function(e){em(dm,$g,(function(){var t=e.facade;Zg?Om.emit("rejectionHandled",t):Vm("rejectionhandled",t,e.value)}))},Fm=function(e,t,r){return function(i){e(t,i,r)}},jm=function(e,t,r){e.done||(e.done=!0,r&&(e=r),e.value=t,e.state=2,Lm(e,!0))},Hm=function(e,t,r){if(!e.done){e.done=!0,r&&(e=r);try{if(e.facade===t)throw Im("Promise can't be resolved itself");var i=Pm(t);i?um((function(){var r={done:!1};try{em(i,t,Fm(Hm,r,e),Fm(jm,r,e))}catch(t){jm(r,t,e)}})):(e.value=t,e.state=1,Lm(e,!1))}catch(t){jm({done:!1},t,e)}}};vm&&(km=(bm=function(e){sm(this,km),om(e),em(Jg,this);var t=ym(this);try{e(Fm(Hm,t),Fm(jm,t))}catch(e){jm(t,e)}}).prototype,(Jg=function(e){Sm(this,{type:Tm,done:!1,notified:!1,parent:!1,reactions:new pm,rejection:!1,state:0,value:void 0})}).prototype=tm(km,"then",(function(e,t){var r=ym(this),i=Rm(cm(this,bm));return r.parent=!0,i.ok=!nm(e)||e,i.fail=nm(t)&&t,i.domain=Zg?Om.domain:void 0,0==r.state?r.reactions.add(i):um((function(){Mm(i,r)})),i.promise})),Yg=function(){var e=new Jg,t=ym(e);this.promise=e,this.resolve=Fm(Hm,t),this.reject=Fm(jm,t)},Em.f=Rm=function(e){return e===bm||undefined===e?new Yg(e):Nm(e)}),Qg({global:!0,constructor:!0,wrap:!0,forced:vm},{Promise:bm}),rm(bm,Tm,!1,!0),im(Tm);var Gm=Tt("iterator"),Wm=!1;try{var Km=0,zm={next:function(){return{done:!!Km++}},return:function(){Wm=!0}};zm[Gm]=function(){return this},Array.from(zm,(function(){throw 2}))}catch(e){}var Xm=Cg,qm=function(e,t){if(!t&&!Wm)return!1;var r=!1;try{var i={};i[Gm]=function(){return{next:function(){return{done:r=!0}}}},e(i)}catch(e){}return r},Jm=Wg.CONSTRUCTOR||!qm((function(e){Xm.all(e).then(void 0,(function(){}))})),Ym=B,Qm=xe,Zm=Kg,$m=Ig,ef=Fh;Mr({target:"Promise",stat:!0,forced:Jm},{all:function(e){var t=this,r=Zm.f(t),i=r.resolve,o=r.reject,n=$m((function(){var r=Qm(t.resolve),n=[],a=0,s=1;ef(e,(function(e){var c=a++,d=!1;s++,Ym(r,t,e).then((function(e){d||(d=!0,n[c]=e,--s||i(n))}),o)})),--s||i(n)}));return n.error&&o(n.value),r.promise}});var tf=Mr,rf=Wg.CONSTRUCTOR;Cg&&Cg.prototype,tf({target:"Promise",proto:!0,forced:rf,real:!0},{catch:function(e){return this.then(void 0,e)}});var of=B,nf=xe,af=Kg,sf=Ig,cf=Fh;Mr({target:"Promise",stat:!0,forced:Jm},{race:function(e){var t=this,r=af.f(t),i=r.reject,o=sf((function(){var o=nf(t.resolve);cf(e,(function(e){of(o,t,e).then(r.resolve,i)}))}));return o.error&&i(o.value),r.promise}});var df=B,uf=Kg;Mr({target:"Promise",stat:!0,forced:Wg.CONSTRUCTOR},{reject:function(e){var t=uf.f(this);return df(t.reject,void 0,e),t.promise}});var lf=cr,hf=se,pf=Kg,gf=function(e,t){if(lf(e),hf(t)&&t.constructor===e)return t;var r=pf.f(e);return(0,r.resolve)(t),r.promise},mf=Mr,ff=Cg,Ef=Wg.CONSTRUCTOR,Tf=gf,vf=pe("Promise"),_f=!Ef;mf({target:"Promise",stat:!0,forced:true},{resolve:function(e){return Tf(_f&&this===vf?ff:this,e)}});var yf=B,Sf=xe,Af=Kg,bf=Ig,kf=Fh;Mr({target:"Promise",stat:!0,forced:Jm},{allSettled:function(e){var t=this,r=Af.f(t),i=r.resolve,o=r.reject,n=bf((function(){var r=Sf(t.resolve),o=[],n=0,a=1;kf(e,(function(e){var s=n++,c=!1;a++,yf(r,t,e).then((function(e){c||(c=!0,o[s]={status:"fulfilled",value:e},--a||i(o))}),(function(e){c||(c=!0,o[s]={status:"rejected",reason:e},--a||i(o))}))})),--a||i(o)}));return n.error&&o(n.value),r.promise}});var If=B,Cf=xe,Of=pe,Rf=Kg,Nf=Ig,wf=Fh,Df="No one promise resolved";Mr({target:"Promise",stat:!0,forced:Jm},{any:function(e){var t=this,r=Of("AggregateError"),i=Rf.f(t),o=i.resolve,n=i.reject,a=Nf((function(){var i=Cf(t.resolve),a=[],s=0,c=1,d=!1;wf(e,(function(e){var u=s++,l=!1;c++,If(i,t,e).then((function(e){l||d||(d=!0,o(e))}),(function(e){l||d||(l=!0,a[u]=e,--c||n(new r(a,Df)))}))})),--c||n(new r(a,Df))}));return a.error&&n(a.value),i.promise}});var Pf=Mr,Mf=Cg,Lf=d,Vf=pe,xf=M,Uf=Ap,Bf=gf,Ff=Mf&&Mf.prototype;Pf({target:"Promise",proto:!0,real:!0,forced:!!Mf&&Lf((function(){Ff.finally.call({then:function(){}},(function(){}))}))},{finally:function(e){var t=Uf(this,Vf("Promise")),r=xf(e);return this.then(r?function(r){return Bf(t,e()).then((function(){return r}))}:e,r?function(r){return Bf(t,e()).then((function(){throw r}))}:e)}});var jf=c(ce.Promise);function Hf(e,t,r,i){var o,n=arguments.length,a=n<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,r,i);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(n<3?o(a):n>3?o(t,r,a):o(t,r))||a);return n>3&&a&&Object.defineProperty(t,r,a),a}function Gf(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}class Wf extends t.EventEmitter{constructor(e,r){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=r||t.getRandomString(8,"track-"),this._originMediaStreamTrack=e,this._mediaStreamTrack=e,zi(this)}toString(){return this._ID}getTrackId(){return this._ID}getMediaStreamTrack(e){if(!e){const e=r.report.reportApiInvoke(null,{name:t.AgoraAPIName.GET_MEDIA_STREAM_TRACK,options:[],tag:t.AgoraAPITag.TRACER});this._mediaStreamTrack&&"string"==typeof this._mediaStreamTrack.label?e.onSuccess(this._mediaStreamTrack.label):e.onSuccess("")}return this._mediaStreamTrack}getRTCRtpTransceiver(t){return t===e.StreamType.LOW_STREAM?this._lowRtpTransceiver:this._rtpTransceiver}getMediaStreamTrackSettings(){return this.getMediaStreamTrack(!0).getSettings()}close(){this._isClosed=!0,this._lowRtpTransceiver=void 0,this._rtpTransceiver=void 0,Xi(this),this.emit(e.LocalTrackEvents.CLOSED)}_updateRtpTransceiver(t,r){if(r===e.StreamType.LOW_STREAM){if(this._lowRtpTransceiver===t)return;this._lowRtpTransceiver=t}else{if(this._rtpTransceiver===t)return;this._rtpTransceiver=t}this.emit(e.TrackEvents.TRANSCEIVER_UPDATED,t,r)}}class Kf extends Wf{get isExternalTrack(){return this._isExternalTrack}get muted(){return this._muted}get enabled(){return this._enabled}get processorContext(){return this._processorContext}set processorContext(e){this._processorContext=e}constructor(e,r){super(e,r),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 t.PromiseMutex("".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,r.logger.debug("[".concat(this.getTrackId(),"] close")),this.emit(e.TrackInternalEvent.NEED_CLOSE),super.close())}async _updateOriginMediaStreamTrack(r,i){let o=arguments.length>2&&void 0!==arguments[2]&&arguments[2];this._isExternalTrack=o,r!==this._originMediaStreamTrack&&(this._originMediaStreamTrack&&(this._originMediaStreamTrack.removeEventListener("ended",this._handleTrackEnded),i&&this._originMediaStreamTrack.stop()),r.addEventListener("ended",this._handleTrackEnded),this._originMediaStreamTrack=r,this._muted&&(this._originMediaStreamTrack.enabled=!1),this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await t.emitAsPromiseNoResponse(this,e.TrackInternalEvent.NEED_REPLACE_TRACK,this),this.processor&&this.processor.updateInput({track:this._originMediaStreamTrack,context:this.processorContext}))}_getDefaultPlayerConfig(){return{}}onTrackEnded(){r.logger.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(e.LocalTrackEvents.TRACK_ENDED)}stateCheck(e,i){if(r.logger.debug("check track state, [muted: ".concat(this._muted,", enabled: ").concat(this._enabled,"] to [").concat(e,": ").concat(i,"]")),t.checkValidBoolean(i,e),this._enabled&&this._muted&&"enabled"===e&&!1===i)throw new t.AgoraRTCError(t.AgoraRTCErrorCode.TRACK_STATE_UNREACHABLE,"cannot set enabled while the track is muted").print("error",r.logger);if(!this._enabled&&!this._muted&&"muted"===e&&!0===i)throw new t.AgoraRTCError(t.AgoraRTCErrorCode.TRACK_STATE_UNREACHABLE,"cannot set muted while the track is disabled").print("error",r.logger)}getProcessorStats(){return this.processorContext.gatherStats()}getProcessorUsage(){return this.processorContext.gatherUsage()}}function zf(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}const Xf=window.AudioContext||window.webkitAudioContext;let qf=null;class Jf extends t.EventEmitter{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=()=>{r.logger.info("ios15-interruption-start"),this.emit(e.AUDIO_CONTEXT_EVENT.IOS_15_16_INTERRUPTION_START)},this.onLocalAudioTrackUnmute=async()=>{r.logger.info("ios15-interruption-end"),"running"!==this.curState||this.duringInterruption?r.logger.info("ios15-interruption-end-canceled"):(qf&&await qf.suspend(),this.emit(e.AUDIO_CONTEXT_EVENT.IOS_15_16_INTERRUPTION_END))}}get duringInterruption(){return"running"===this.prevState&&"interrupted"===this.curState}bindInterruptDetectorTrack(e){r.logger.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){r.logger.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)}}const Yf=new Jf;function Qf(){if(!Xf)return void r.logger.error("your browser is not support web audio");r.logger.info("create audio context");const i=function(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?zf(Object(r),!0).forEach((function(t){Bl(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):zf(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}({},t.getParameter("WEBAUDIO_INIT_OPTIONS"));r.logger.debug("audio context init option:",JSON.stringify(i)),qf=new Xf(i),Yf.curState=qf.state,qf.onstatechange=()=>{Yf.prevState=Yf.curState,Yf.curState=qf?qf.state:void 0;const{prevState:i,curState:o}=Yf,n="running"===o,a="interrupted"===o,s="running"===i,c="suspended"===i,d="interrupted"===i,u=t.getBrowserInfo().osVersion;(t.isIOS()||t.isIpadOS())&&s&&a&&(r.logger.info("ios".concat(u,"-interruption-start")),Yf.emit(e.AUDIO_CONTEXT_EVENT.IOS_INTERRUPTION_START)),(t.isIOS()||t.isIpadOS())&&(c||d)&&n&&(r.logger.info("ios".concat(u,"-interruption-end")),Yf.emit(e.AUDIO_CONTEXT_EVENT.IOS_INTERRUPTION_END)),i!==o&&(r.logger.debug("AudioContext State Change","".concat(i,"=>").concat(o)),Yf.emit(e.AUDIO_CONTEXT_EVENT.STATE_CHANGE))},setInterval((()=>{var e;const i=null===(e=qf)||void 0===e?void 0:e.currentTime;if(Yf.currentTime!==i)Yf.currentTimeStuckAt&&(r.logger.debug("AudioContext current time resume at ".concat(i)),Yf.currentTimeStuckAt=void 0),Yf.currentTime=i;else{if(i!==Yf.currentTimeStuckAt){r.report.reportApiInvoke(null,{name:"WEB_AUDIO_CURRENT_TIME_STUCK",options:{currentTime:i},tag:t.AgoraAPITag.TRACER}).onSuccess(),r.logger.warning("AudioContext current time stuck at ".concat(i))}Yf.currentTimeStuckAt=i}}),5e3),async function(r){const i=["click","contextmenu","auxclick","dblclick","mousedown","mouseup","touchend","keydown","keyup"];let o,n=!1,a=!1,s=!1;function c(e){"running"===r.state?d(!1):t.isIOS()||t.isIpadOS()?"suspended"===r.state&&(d(!0),e&&r.resume().then(l,l)):"closed"!==r.state&&(d(!0),e&&r.resume().then(l,l))}function d(e){if(n!==e){n=e;for(let t=0,r=i;t<r.length;t+=1){const i=r[t];e?window.addEventListener(i,h,{capture:!0,passive:!0}):window.removeEventListener(i,h,{capture:!0,passive:!0})}}}function u(){c(!0)}function l(){c(!1)}function h(){c(!0)}function p(e){if(!s)if(o.paused)if(e){let e;g(!1),s=!0;try{e=o.play(),e?e.then(m,m):(o.addEventListener("playing",m),o.addEventListener("abort",m),o.addEventListener("error",m))}catch(e){m()}}else g(!0);else g(!1)}function g(e){if(a!==e){a=e;for(let t=0,r=i;t<r.length;t++){const i=r[t];e?window.addEventListener(i,f,{capture:!0,passive:!0}):window.removeEventListener(i,f,{capture:!0,passive:!0})}}}function m(){o.removeEventListener("playing",m),o.removeEventListener("abort",m),o.removeEventListener("error",m),s=!1,p(!1)}function f(){p(!0)}if(t.isIOS()){const e=r.createMediaStreamDestination(),t=document.createElement("div");t.innerHTML="<audio x-webkit-airplay='deny'></audio>",o=t.children.item(0),o.controls=!1,o.disableRemotePlayback=!0,o.preload="auto",o.srcObject=e.stream,p(!0)}Yf.on(e.AUDIO_CONTEXT_EVENT.STATE_CHANGE,u),c(!1)}(qf)}function Zf(){if(!qf){if(Qf(),!qf)throw new t.AgoraRTCError(t.AgoraRTCErrorCode.NOT_SUPPORTED,"can not create audio context");return qf}return qf}function $f(){return!!qf}function eE(e){if(function(){if(null!==rE)return rE;const e=Zf(),t=e.createBufferSource(),r=e.createGain(),i=e.createGain();t.connect(r),t.connect(i),t.disconnect(r);let o=!1;try{t.disconnect(r)}catch(e){o=!0}return t.disconnect(),rE=o,o}())return;const r=e.connect,i=e.disconnect;e.connect=(t,i,o)=>{var n;return e._inputNodes||(e._inputNodes=[]),Di(n=e._inputNodes).call(n,t)||(t instanceof AudioNode?(e._inputNodes.push(t),r.call(e,t,i,o)):r.call(e,t,i)),e},e.disconnect=(o,n,a)=>{i.call(e),o?t.removeItemFromList(e._inputNodes,o):e._inputNodes=[];for(const t of e._inputNodes)r.call(e,t)}}function tE(e){const r=Zf();return new jf(((i,o)=>{r.decodeAudioData(e,(e=>{i(e)}),(e=>{o(new t.AgoraRTCError(t.AgoraRTCErrorCode.DECODE_AUDIO_FILE_FAILED,e.toString()))}))}))}let rE=null;let iE=null;function oE(e){for(let t=0;t<e.outputBuffer.numberOfChannels;t+=1){const r=e.outputBuffer.getChannelData(t);for(let e=0;e<r.length;e+=1)r[e]=0}return e.inputBuffer}const nE={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 aE(){return nE}var sE=xe,cE=tt,dE=Q,uE=zr,lE=TypeError,hE=function(e){return function(t,r,i,o){sE(r);var n=cE(t),a=dE(n),s=uE(n),c=e?s-1:0,d=e?-1:1;if(i<2)for(;;){if(c in a){o=a[c],c+=d;break}if(c+=d,e?c<0:s<=c)throw lE("Reduce of empty array with no initial value")}for(;e?c>=0:s>c;c+=d)c in a&&(o=r(o,a[c],c,n));return o}},pE={left:hE(!1),right:hE(!0)},gE=d,mE=pE.left,fE=function(e,t){var r=[][e];return!!r&&gE((function(){r.call(null,t||function(){return 1},1)}))};Mr({target:"Array",proto:!0,forced:!dp&&ye>79&&ye<83||!fE("reduce")},{reduce:function(e){var t=arguments.length;return mE(this,e,t,t>1?arguments[1]:void 0)}});var EE=ei("Array").reduce,TE=f,vE=EE,_E=Array.prototype,yE=c((function(e){var t=e.reduce;return e===_E||TE(_E,e)&&t===_E.reduce?vE:t}));class SE{constructor(){this.context=void 0,this.analyserNode=void 0,this.sourceNode=void 0,this.context=Zf(),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||t.isIOS()||t.isIpadOS()||"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 r=0;r<e.length;++r)e[r]=t[r]/128-1}const r=yE(e).call(e,((e,t)=>e+t*t),0)/e.length;return Math.max(10*Math.log10(r)+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){r.logger.warning("rebuild analyser node failed.")}}destroy(){this.updateSource(void 0)}}class AE extends t.EventEmitter{get processSourceNode(){return this.sourceNode}set processedNode(e){var t;if(!this.isDestroyed&&this._processedNode!==e){try{var r;null===(r=this.sourceNode)||void 0===r||r.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=Zf(),this.playNode=this.context.destination,this.outputNode=this.context.createGain(),eE(this.outputNode),this.volumeLevelAnalyser=new SE}startGetAudioBuffer(t){this.audioBufferNode||(this.audioBufferNode=this.context.createScriptProcessor(t),this.outputNode.connect(this.audioBufferNode),this.audioBufferNode.connect(this.context.destination),this.audioBufferNode.onaudioprocess=t=>{this.emit(e.AudioSourceEvents.ON_AUDIO_BUFFER,oE(t))})}stopGetAudioBuffer(){this.audioBufferNode&&(this.audioBufferNode.onaudioprocess=null,this.outputNode.disconnect(this.audioBufferNode),this.audioBufferNode=void 0)}createOutputTrack(){if(!aE().webAudioMediaStreamDest)throw new t.AgoraRTCError(t.AgoraRTCErrorCode.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&&t.nextTick((()=>{Yf.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;t.isIOS()||t.isIpadOS()?"suspended"===this.context.state&&this.context.resume():"running"!==this.context.state&&this.context.resume();const r=this.volumeLevelAnalyser.getAnalyserNode();let i;r.getFloatTimeDomainData?(i=new Float32Array(r.fftSize),r.getFloatTimeDomainData(i)):(i=new Uint8Array(r.fftSize),r.getByteTimeDomainData(i));let o=!1;for(let e=0;e<i.length;e++)0!==i[e]&&(o=!0);return o?(this.isNoAudioInput=!1,!0):(await t.wait(200),await this.checkHasAudioInput(e?e+1:1)&&o)}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 bE extends AE{get isFreeze(){return!1}constructor(i,o,n){var a;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(r.logger.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 r.logger.debug("rebuild web audio success, current volume status",this.getAccurateVolumeLevel());this.context.resume().then((()=>r.logger.info("resume success"))),r.logger.debug("rebuild web audio because of ios 12 bugs"),this.disconnect();const t=this.track;this.track=this.track.clone(),this.isCurrentTrackCloned?t.stop():this.isCurrentTrackCloned=!0;const i=new MediaStream([this.track]);this.sourceNode=this.context.createMediaStreamSource(i),eE(this.sourceNode),this.volumeLevelAnalyser.rebuildAnalyser();const o=this.outputNode.gain.value;this.outputNode=this.context.createGain(),this.outputNode.gain.setValueAtTime(o,this.context.currentTime),eE(this.outputNode),this.emit(e.AudioSourceEvents.UPDATE_SOURCE),this.connect(),this.audioElement.srcObject=i,this.isPlayed&&this.play(this.playNode),this.checkHasAudioInput()},"audio"!==i.kind)throw new t.AgoraRTCError(t.AgoraRTCErrorCode.UNEXPECTED_ERROR);this.track=i;const s=new MediaStream([this.track]);if(this.isRemoteTrack=!!o,this.sourceNode=this.context.createMediaStreamSource(s),eE(this.sourceNode),n){const e=n.clone();e.enabled=!0,this.clonedTrack=e,r.logger.debug("create an unmuted track ".concat(e.id," from the original track ").concat(n.id," to get the volume"));const t=this.context.createMediaStreamSource(new MediaStream([e]));eE(t),this.originVolumeLevelAnalyser=new SE,this.originVolumeLevelAnalyser.updateSource(t)}this.connect(),this.audioElement=document.createElement("audio"),this.audioElement.srcObject=s;const c=t.getBrowserInfo();o&&c.os===t.BrowserOS.IOS&&Number(null===(a=c.osVersion)||void 0===a?void 0:a.split(".")[0])<15&&(Yf.on(e.AUDIO_CONTEXT_EVENT.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(t){this.sourceNode.disconnect(),this.track=t,this.isCurrentTrackCloned=!1;const r=new MediaStream([t]);this.sourceNode=this.context.createMediaStreamSource(r),eE(this.sourceNode),this.processedNode||this.sourceNode.connect(this.outputNode),this.emit(e.AudioSourceEvents.UPDATE_SOURCE),this.audioElement.srcObject=r}destroy(){var e;this.audioElement.srcObject=null,this.audioElement.remove(),Yf.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),r.logger.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]));eE(i),this.originVolumeLevelAnalyser&&this.originVolumeLevelAnalyser.updateSource(i)}getOriginVolumeLevel(){return this.originVolumeLevelAnalyser?this.originVolumeLevelAnalyser.getVolumeLevel():this.getAccurateVolumeLevel()}}async function kE(e,t,r){const i=(e,t)=>e?"number"!=typeof e?e.max||e.exact||e.ideal||e.min||t:e:t,o={audio:!!r&&{mandatory:{chromeMediaSource:"desktop"}},video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:e,maxHeight:i(t.height,1080),maxWidth:i(t.width,1920)}}};return t.frameRate&&"number"!=typeof t.frameRate?(o.video.mandatory.maxFrameRate=t.frameRate.max,o.video.mandatory.minFrameRate=t.frameRate.min):"number"==typeof t.frameRate&&(o.video.mandatory.maxFrameRate=t.frameRate),await navigator.mediaDevices.getUserMedia(o)}async function IE(e,r){const i=await CE(e.mediaSource),{sourceId:o,audio:n}=await t.showElectronSelectSourceWindow(i,r);return await kE(o,e,n)}async function CE(e){let r=["window","screen"];"application"!==e&&"window"!==e||(r=["window"]),"screen"===e&&(r=["screen"]);const i=t.getElectronInstance();if(!i)throw console.error("failed to fetch electron, please mount it to window"),new t.AgoraRTCError(t.AgoraRTCErrorCode.ELECTRON_IS_NULL);let o=null;try{var n;o=(null===(n=i.desktopCapturer)||void 0===n?void 0:n.getSources({types:r}))||i.ipcRenderer.invoke("DESKTOP_CAPTURER_GET_SOURCES",{types:r})}catch(e){o=null}o&&o.then||(o=new jf(((e,t)=>{i.desktopCapturer.getSources({types:r},((r,i)=>{r?t(r):e(i)}))})));try{return await o}catch(e){throw new t.AgoraRTCError(t.AgoraRTCErrorCode.ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR,e.toString())}}function OE(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}const RE=new t.PromiseMutex("safari");async function NE(e,i){let o=0,n=null;for(;o<2;)try{n=await wE(e,i,o>0);break}catch(e){if(e instanceof t.AgoraRTCError)throw r.logger.error("[".concat(i,"] ").concat(e.toString())),e;const n=DE(e.name||e.code||e,e.message);if(n.code===t.AgoraRTCErrorCode.MEDIA_OPTION_INVALID){r.logger.debug("[".concat(i,"] detect media option invalid, retry")),o+=1,await t.wait(500);continue}throw r.logger.error("[".concat(i,"] ").concat(n.toString())),n}if(!n)throw new t.AgoraRTCError(t.AgoraRTCErrorCode.UNEXPECTED_ERROR,"can not find stream after getUserMedia");return n}async function wE(i,o,n){if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)throw new t.AgoraRTCError(t.AgoraRTCErrorCode.NOT_SUPPORTED,"can not find getUserMedia");n&&(i.video&&(delete i.video.width,delete i.video.height),i.screen&&(delete i.screen.width,delete i.screen.height));const a=aE(),s=new MediaStream;if(i.audioSource&&s.addTrack(i.audioSource),i.videoSource&&s.addTrack(i.videoSource),!i.audio&&!i.video&&!i.screen)return r.logger.debug("Using Video Source/ Audio Source"),s;if(i.screen)if(t.isElectron())if(i.screen.sourceId){PE(s,await kE(i.screen.sourceId,i.screen,i.screenAudio))}else{PE(s,await IE(i.screen,i.screenAudio))}else if(t.isChrome()&&i.screen.extensionId&&i.screen.mandatory){if(!a.getStreamFromExtension)throw new t.AgoraRTCError(t.AgoraRTCErrorCode.NOT_SUPPORTED,"This browser does not support screen sharing");r.logger.debug("[".concat(o,'] Screen access on chrome stable, looking for extension"'));const e=await(d=i.screen.extensionId,u=o,new jf(((e,i)=>{try{chrome.runtime.sendMessage(d,{getStream:!0},(o=>{if(!o||!o.streamId)return r.logger.error("[".concat(u,"] No response from Chrome Plugin. Plugin not installed properly"),o),void i(new t.AgoraRTCError(t.AgoraRTCErrorCode.CHROME_PLUGIN_NO_RESPONSE,"No response from Chrome Plugin. Plugin not installed properly"));e(o.streamId)}))}catch(e){r.logger.error("[".concat(u,"] AgoraRTC screensharing plugin is not accessible(").concat(d,")"),e.toString()),i(new t.AgoraRTCError(t.AgoraRTCErrorCode.CHROME_PLUGIN_NOT_INSTALL))}})));i.screen.mandatory.chromeMediaSourceId=e;PE(s,await navigator.mediaDevices.getUserMedia({video:{mandatory:i.screen.mandatory}}))}else if(a.getDisplayMedia){var c;i.screen.mediaSource&&Yi(i.screen.mediaSource);const e={width:i.screen.width,height:i.screen.height,frameRate:i.screen.frameRate,displaySurface:null!==(c=i.screen.displaySurface)&&void 0!==c?c:"screen"===i.screen.mediaSource?"monitor":i.screen.mediaSource},{selfBrowserSurface:t,surfaceSwitching:n,systemAudio:a}=i.screen,d={selfBrowserSurface:t,surfaceSwitching:n,systemAudio:a};!t&&delete d.selfBrowserSurface,!n&&delete d.surfaceSwitching,!a&&delete d.systemAudio,r.logger.debug("[".concat(o,"] getDisplayMedia:"),JSON.stringify({video:e,audio:!!i.screenAudio,controls:d}));const u=await navigator.mediaDevices.getDisplayMedia(function(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?OE(Object(r),!0).forEach((function(t){Bl(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):OE(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}({video:e,audio:!!i.screenAudio},d));PE(s,u)}else{if(!t.isFirefox())throw r.logger.error("[".concat(o,"] This browser does not support screenSharing")),new t.AgoraRTCError(t.AgoraRTCErrorCode.NOT_SUPPORTED,"This browser does not support screen sharing");{i.screen.mediaSource&&Yi(i.screen.mediaSource);const e={video:{mediaSource:i.screen.mediaSource,width:i.screen.width,height:i.screen.height,frameRate:i.screen.frameRate}};r.logger.debug("[".concat(o,"] getUserMedia: ").concat(JSON.stringify(e)));PE(s,await navigator.mediaDevices.getUserMedia(e))}}var d,u;if(!i.video&&!i.audio)return s;let l={video:i.video,audio:i.audio},h=t.getParameter("MEDIA_DEVICE_CONSTRAINTS");if(h)try{"string"==typeof h&&(h=JSON.parse(h)),l=t.recursiveMerge(l,h)}catch(e){}r.logger.debug("[".concat(o,"] GetUserMedia"),JSON.stringify(l)),t.getBrowserInfo();let p,g=null;(t.isSafari()||t.isIOS()||t.isWkWebview())&&(g=await RE.lock());try{p=await navigator.mediaDevices.getUserMedia(l)}catch(e){throw g&&g(),e}return l.audio&&(e.HAS_GUM_AUDIO=!0),l.video&&(e.HAS_GUM_VIDEO=!0),PE(s,p),g&&g(),s}function DE(e,i){switch(e){case"Starting video failed":case"OverconstrainedError":case"TrackStartError":return new t.AgoraRTCError(t.AgoraRTCErrorCode.MEDIA_OPTION_INVALID,"".concat(e,": ").concat(i));case"NotFoundError":case"DevicesNotFoundError":return new t.AgoraRTCError(t.AgoraRTCErrorCode.DEVICE_NOT_FOUND,"".concat(e,": ").concat(i));case"NotSupportedError":return new t.AgoraRTCError(t.AgoraRTCErrorCode.NOT_SUPPORTED,"".concat(e,": ").concat(i));case"NotReadableError":return new t.AgoraRTCError(t.AgoraRTCErrorCode.NOT_READABLE,"".concat(e,": ").concat(i));case"InvalidStateError":case"NotAllowedError":case"PERMISSION_DENIED":case"PermissionDeniedError":return new t.AgoraRTCError(t.AgoraRTCErrorCode.PERMISSION_DENIED,"".concat(e,": ").concat(i));case"ConstraintNotSatisfiedError":return new t.AgoraRTCError(t.AgoraRTCErrorCode.CONSTRAINT_NOT_SATISFIED,"".concat(e,": ").concat(i));default:return r.logger.error("getUserMedia unexpected error",e),new t.AgoraRTCError(t.AgoraRTCErrorCode.UNEXPECTED_ERROR,"".concat(e,": ").concat(i))}}function PE(e,t){const r=e.getVideoTracks()[0],i=e.getAudioTracks()[0],o=t.getVideoTracks()[0],n=t.getAudioTracks()[0];n&&(i&&e.removeTrack(i),e.addTrack(n)),o&&(r&&e.removeTrack(r),e.addTrack(o))}e.HAS_GUM_AUDIO=!1,e.HAS_GUM_VIDEO=!1;class ME extends t.EventEmitter{get state(){return this._state}set state(t){t!==this._state&&(this.emit(e.DeviceManagerEvent.STATE_CHANGE,t),this._state=t)}constructor(){super(),this._state=e.DeviceManagerState.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((()=>{(t.getParameter("ENUMERATE_DEVICES_INTERVAL")||(t.isAndroid()||t.isHarmonyOS())&&t.isChromeKernel())&&this.updateDevicesInfo()}),t.getParameter("ENUMERATE_DEVICES_INTERVAL_TIME"))})).catch((e=>r.logger.error(e.toString())))}async enumerateDevices(i,o){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices){return new t.AgoraRTCError(t.AgoraRTCErrorCode.NOT_SUPPORTED,"enumerateDevices() not supported.").throw()}const a=await navigator.mediaDevices.enumerateDevices(),s=this.checkMediaDeviceInfoIsOk(a);let c=!this.isAccessMicrophonePermission&&i,d=!this.isAccessCameraPermission&&o;s.audio&&(c=!1),s.video&&(d=!1);let u=null,l=null,h=null;if(!n&&(c||d)){if(RE.isLocked){r.logger.debug("[device manager] wait GUM lock");(await RE.lock())(),r.logger.debug("[device manager] GUM unlock")}if(e.HAS_GUM_AUDIO&&(c=!1,this.isAccessMicrophonePermission=!0),e.HAS_GUM_VIDEO&&(d=!1,this.isAccessCameraPermission=!0),r.logger.debug("[device manager] check media device permissions",i,o,c,d),c&&d){try{h=await navigator.mediaDevices.getUserMedia({audio:!0,video:!0})}catch(e){const i=DE(e.name||e.code||e,e.message);if(i.code===t.AgoraRTCErrorCode.PERMISSION_DENIED)throw i;r.logger.warning("getUserMedia failed in getDevices",i)}this.isAccessCameraPermission=!0,this.isAccessMicrophonePermission=!0}else if(c){try{u=await navigator.mediaDevices.getUserMedia({audio:i})}catch(e){const i=DE(e.name||e.code||e,e.message);if(i.code===t.AgoraRTCErrorCode.PERMISSION_DENIED)throw i;r.logger.warning("getUserMedia failed in getDevices",i)}this.isAccessMicrophonePermission=!0}else if(d){try{l=await navigator.mediaDevices.getUserMedia({video:o})}catch(e){const i=DE(e.name||e.code||e,e.message);if(i.code===t.AgoraRTCErrorCode.PERMISSION_DENIED)throw i;r.logger.warning("getUserMedia failed in getDevices",i)}this.isAccessCameraPermission=!0}r.logger.debug("[device manager] mic permission",i,"cam permission",o)}try{const e=await navigator.mediaDevices.enumerateDevices();return u&&u.getTracks().forEach((e=>e.stop())),l&&l.getTracks().forEach((e=>e.stop())),h&&h.getTracks().forEach((e=>e.stop())),u=null,l=null,h=null,e}catch(e){u&&u.getTracks().forEach((e=>e.stop())),l&&l.getTracks().forEach((e=>e.stop())),h&&h.getTracks().forEach((e=>e.stop())),u=null,l=null,h=null;return new t.AgoraRTCError(t.AgoraRTCErrorCode.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((r=>{r.device.label===e&&(t=r.device.deviceId)})),t}async getDeviceById(e){const r=(await this.enumerateDevices(!0,!0,!0)).find((t=>t.deviceId===e));if(!r)throw new t.AgoraRTCError(t.AgoraRTCErrorCode.DEVICE_NOT_FOUND,"deviceId: ".concat(e));return r}async init(){this.state=e.DeviceManagerState.INITING;try{await this.updateDevicesInfo(),this.state=e.DeviceManagerState.INITEND}catch(i){if(r.logger.warning("Device Detection functionality cannot start properly.",i.toString()),this.state=e.DeviceManagerState.IDLE,!t.detectSecureContext()){new t.AgoraRTCError(t.AgoraRTCErrorCode.WEB_SECURITY_RESTRICT,"Your context is limited by web security, please try using https protocol or localhost.").throw()}throw i}}async updateDevicesInfo(){const t=await this.enumerateDevices(!0,!0,!0),i=Date.now(),o=[];if(t[0]&&t[0].label&&!1===this.checkdeviceMatched){this.checkdeviceMatched=!0;const e=t.find((e=>"audioinput"===e.kind&&"default"===e.deviceId)),i=t.find((e=>"audiooutput"===e.kind&&"default"===e.deviceId));e&&i?i.groupId===e.groupId?r.logger.debug("[device-check] default input ".concat(e.label," and output ").concat(i.label," is the same group")):r.logger.warning("[device-check] default input ".concat(e.label," and output ").concat(i.label," is not the same group")):r.logger.debug("[device-check] default input or output not found")}const n=this.checkMediaDeviceInfoIsOk(t);if(t.forEach((e=>{if(!e.deviceId)return;const t=this.deviceInfoMap.get("".concat(e.kind,"_").concat(e.deviceId));if("ACTIVE"!==(t?t.state:"INACTIVE")){const t={initAt:i,updateAt:i,device:e,state:"ACTIVE"};this.deviceInfoMap.set("".concat(e.kind,"_").concat(e.deviceId),t),o.push(t)}t&&(t.updateAt=i)})),this.deviceInfoMap.forEach(((e,t)=>{"ACTIVE"===e.state&&e.updateAt!==i&&(e.state="INACTIVE",o.push(e))})),this.state!==e.DeviceManagerState.INITEND)return n.audio&&(this.lastAccessMicrophonePermission=!0,this.isAccessMicrophonePermission=!0),void(n.video&&(this.lastAccessCameraPermission=!0,this.isAccessCameraPermission=!0));o.forEach((t=>{switch(t.device.kind){case"audioinput":this.lastAccessMicrophonePermission&&this.isAccessMicrophonePermission&&this.emit(e.DeviceManagerEvent.RECORDING_DEVICE_CHANGED,t);break;case"videoinput":this.lastAccessCameraPermission&&this.isAccessCameraPermission&&this.emit(e.DeviceManagerEvent.CAMERA_DEVICE_CHANGED,t);break;case"audiooutput":this.lastAccessMicrophonePermission&&this.isAccessMicrophonePermission&&this.emit(e.DeviceManagerEvent.PLAYOUT_DEVICE_CHANGED,t)}})),n.audio&&(this.lastAccessMicrophonePermission=!0,this.isAccessMicrophonePermission=!0),n.video&&(this.lastAccessCameraPermission=!0,this.isAccessCameraPermission=!0)}checkMediaDeviceInfoIsOk(e){const t=e.filter((e=>"audioinput"===e.kind)),r=e.filter((e=>"videoinput"===e.kind)),i={audio:!1,video:!1};for(const e of t)if(e.label&&e.deviceId){i.audio=!0;break}for(const e of r)if(e.label&&e.deviceId){i.video=!0;break}return i}}const LE=new ME;class VE extends t.EventEmitter{constructor(){super(...arguments),this.onAutoplayFailed=void 0,this.onAudioAutoplayFailed=void 0}}let xE=!1;const UE=new VE;function BE(){if(t.getBrowserInfo(),!xE){const e=r=>{r.preventDefault(),xE=!1,t.isAndroidChromium()?document.body.removeEventListener("click",e,!0):(document.body.removeEventListener("touchstart",e,!0),document.body.removeEventListener("mousedown",e,!0))};xE=!0,t.isAndroidChromium()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0)),r.logger.info("detect media autoplay failed, document: https://docs.agora.io/cn/Voice/autoplay_policy_web_ng?platform=Web"),UE.onAutoplayFailed?UE.onAutoplayFailed():UE.onAudioAutoplayFailed?r.logger.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 ."):r.logger.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 ."),UE.emit("autoplay-failed")}}function FE(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}function jE(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?FE(Object(r),!0).forEach((function(t){Bl(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):FE(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function HE(e,t,i,o){if(!e)return;const n=r.report.getBaseInfoBySessionId(e);if(!n)return;const a=n.info,s=Date.now(),c=jE(jE({},a),{},{vid:void 0===a.vid?0:Number(a.vid),lts:s,elapse:s-n.startTime,cbRegistered:UE.onAutoplayFailed||UE.onAudioAutoplayFailed?1:-1,errorMsg:i,mediaType:t,trackId:o,extend:void 0});r.report.send({type:r.AgoraRTCEventUploadType.AUTOPLAY_FAILED,data:c},!0)}const GE=["play","playing","loadeddata","canplay","pause","stalled","suspend","waiting","abort","emptied","ended","error"],WE=new class{constructor(){this.onAutoplayFailed=void 0,this.elementMap=new Map,this.elementStateMap=new Map,this.elementsNeedToResume=[],this.sinkIdMap=new Map,this.autoResumeAfterInterruption=()=>{Array.from(this.elementMap.entries()).forEach((e=>{let[i,o]=e;const n=this.elementStateMap.get(i),a=o.srcObject.getAudioTracks()[0];t.isIOS15()?a&&"live"===a.readyState&&"running"===Yf.curState&&(r.logger.debug("auto resume after interruption for iOS 15"),o.pause(),o.play()):n&&"paused"===n&&a&&"live"===a.readyState&&"running"===Yf.curState&&(r.logger.debug("auto resume after interruption for iOS"),o.play())}))},this.autoResumeAfterInterruptionOnIOS15_16=()=>{Array.from(this.elementMap.entries()).forEach((e=>{let[t,i]=e;const o=i.srcObject.getAudioTracks()[0];o&&"live"===o.readyState&&(r.logger.debug("auto resume after interruption inside autoResumeAfterInterruptionOnIOS15"),i.pause(),i.play())}))},this.autoResumeAudioElement(),Yf.on(e.AUDIO_CONTEXT_EVENT.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),Yf.on(e.AUDIO_CONTEXT_EVENT.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16),Yf.on(e.AUDIO_CONTEXT_EVENT.STATE_CHANGE,(()=>{t.isIOS()&&"suspended"===Yf.prevState&&"running"===Yf.curState&&this.autoResumeAfterInterruption()}))}async setSinkID(e,r){const i=this.elementMap.get(e);if(this.sinkIdMap.set(e,r),i)try{await i.setSinkId(r)}catch(e){throw new t.AgoraRTCError(t.AgoraRTCErrorCode.PERMISSION_DENIED,"can not set sink id: "+e.toString())}}play(i,o,n,a){if(this.elementMap.has(o))return;const s=document.createElement("audio");s.autoplay=!0,s.srcObject=new MediaStream([i]),this.bindAudioElementEvents(o,s),this.elementMap.set(o,s),this.elementStateMap.set(o,e.MediaElementStatus.INIT),this.setVolume(o,n);const c=this.sinkIdMap.get(o);if(c)try{s.setSinkId(c).catch((e=>{r.logger.warning("[".concat(o,"] set sink id failed"),e.toString())}))}catch(e){r.logger.warning("[".concat(o,"] set sink id failed"),e.toString())}const d=s.play();d&&d.then&&d.catch((e=>{a&&HE(a,"audio",e.message,o),r.logger.warning("audio element play warning",e.toString()),this.elementMap.has(o)&&"NotAllowedError"===e.name&&(r.logger.warning("detected audio element autoplay failed"),this.elementsNeedToResume.push(s),t.nextTick((()=>{this.onAutoplayFailed&&this.onAutoplayFailed(),BE()})))}))}updateTrack(e,t){const r=this.elementMap.get(e);r&&(r.srcObject=new MediaStream([t]))}isPlaying(e){return this.elementMap.has(e)&&"playing"===this.elementStateMap.get(e)}setVolume(e,t){const r=this.elementMap.get(e);r&&(t=Math.max(0,Math.min(100,t)),r.volume=t/100)}stop(e){const t=this.elementMap.get(e);if(this.sinkIdMap.delete(e),!t)return;const r=this.elementsNeedToResume.indexOf(t);this.elementsNeedToResume.splice(r,1),t.srcObject=null,t.remove(),this.elementMap.delete(e),this.elementStateMap.delete(e)}bindAudioElementEvents(e,t){GE.forEach((i=>{t.addEventListener(i,(i=>{const o=this.elementStateMap.get(e),n="pause"===i.type?"paused":i.type;if(r.logger.debug("[".concat(e,"] audio-element-status change ").concat(o," => ").concat(n)),"error"===i.type){const i=null==t?void 0:t.error;i&&r.logger.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=>{r.logger.debug("Auto resume audio element success")})).catch((e=>{r.logger.warning("Auto resume audio element failed!",e)}))})),this.elementsNeedToResume=[]};t.domLoadedPromise().then((()=>{t.isAndroidChromium()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0))}))}};function KE(){return function(e,i,o){const n=o.value;return"function"==typeof n&&(o.value=function(){this._isClosed&&new t.AgoraRTCError(t.AgoraRTCErrorCode.INVALID_OPERATION,"[".concat(this.getTrackId(),"] cannot operate a closed track")).print("warning",r.logger);for(var e=arguments.length,i=new Array(e),o=0;o<e;o++)i[o]=arguments[o];const a=n.apply(this,i);return a instanceof jf?new jf(((e,t)=>{a.then(e).catch(t)})):a}),o}}var zE=ei("Array").values,XE=mi,qE=ot,JE=f,YE=zE,QE=Array.prototype,ZE={DOMTokenList:!0,NodeList:!0},$E=c((function(e){var t=e.values;return e===QE||JE(QE,e)&&t===QE.values||qE(ZE,XE(e))?YE:t}));function eT(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}function tT(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?eT(Object(r),!0).forEach((function(t){Bl(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):eT(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}class rT extends t.EventEmitter{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.AgoraRTCError(t.AgoraRTCErrorCode.NOT_SUPPORTED,"VideoProcessor cannot pipe to any other Processor")}unpipe(){throw new t.AgoraRTCError(t.AgoraRTCErrorCode.NOT_SUPPORTED,"VideoProcessor cannot unpipe to any other Processor")}enable(){}disable(){}updateInput(t){if(t.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).");t.track&&t.track!==this.inputTrack&&(this.videoContext.chained=!0,this.inputTrack=t.track,this.emit(e.PROCESSOR_DESTINATION_EVENTS.ON_TRACK,t.track))}reset(){this.inputTrack=void 0,this.videoContext.chained=!1,this.emit(e.PROCESSOR_DESTINATION_EVENTS.ON_TRACK,void 0)}}class iT extends t.EventEmitter{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.emitAsPromise(this,e.PROCESSOR_CONTEXT_EVENTS.REQUEST_CONSTRAINTS)}async requestApplyConstraints(i,o){var n;return r.logger.info("processor ".concat(o.name," requestApplyConstraints for ").concat(this.trackId)),i&&this.constraintsMap.set(o,i),t.emitAsPromiseNoResponse(this,e.PROCESSOR_CONTEXT_EVENTS.REQUEST_UPDATE_CONSTRAINTS,Array.from($E(n=this.constraintsMap).call(n)))}async requestRevertConstraints(i){var o;if(this.constraintsMap.has(i))return r.logger.info("processor ".concat(i.name," requestRevertConstraints for ").concat(this.trackId)),this.constraintsMap.delete(i),t.emitAsPromiseNoResponse(this,e.PROCESSOR_CONTEXT_EVENTS.REQUEST_UPDATE_CONSTRAINTS,Array.from($E(o=this.constraintsMap).call(o)))}registerStats(e,t,r){this.statsRegistry.find((r=>r.processorID===e.ID&&r.processorName===e.name&&r.type===t))||this.statsRegistry.push({processorName:e.name,processorID:e.ID,type:t,cb:r})}unregisterStats(e,t){const r=this.statsRegistry.findIndex((r=>r.processorID===e.ID&&r.processorName===e.name&&r.type===t));-1!==r&&this.statsRegistry.splice(r,1)}gatherStats(){const e=[];for(const{processorID:i,processorName:o,type:n,cb:a}of this.statsRegistry)try{const t=a();e.push({processorID:i,processorName:o,type:n,stats:t})}catch(e){r.logger.error(new t.AgoraRTCError(t.AgoraRTCErrorCode.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 r=t();r instanceof jf&&(r=await r),e.push(tT(tT({},r),{},{direction:this.direction}))}catch(e){r.logger.error("gather extension usage error",e)}return e}getDirection(){return this.direction}}class oT extends t.EventEmitter{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.AgoraRTCError(t.AgoraRTCErrorCode.NOT_SUPPORTED,"AudioProcessorDestination cannot pipe to any other Processor")}unpipe(){throw new t.AgoraRTCError(t.AgoraRTCErrorCode.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(e.PROCESSOR_DESTINATION_EVENTS.ON_TRACK,void 0),this.emit(e.PROCESSOR_DESTINATION_EVENTS.ON_NODE,void 0)}updateInput(t){if(t.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).");t.track&&this.inputTrack!==t.track&&(this.audioProcessorContext.chained=!0,this.inputTrack=t.track,this.emit(e.PROCESSOR_DESTINATION_EVENTS.ON_TRACK,this.inputTrack)),t.node&&this.inputNode!==t.node&&(this.audioProcessorContext.chained=!0,this.inputNode=t.node,this.emit(e.PROCESSOR_DESTINATION_EVENTS.ON_NODE,this.inputNode))}}class nT extends t.EventEmitter{set chained(e){this._chained=e}get chained(){return this._chained}constructor(e,t,r){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=r}async getConstraints(){return t.emitAsPromise(this,e.PROCESSOR_CONTEXT_EVENTS.REQUEST_CONSTRAINTS)}getAudioContext(){return this.audioContext}async requestApplyConstraints(i,o){var n;return r.logger.info("processor ".concat(o.name," requestApplyConstraints for ").concat(this.trackId)),i&&this.constraintsMap.set(o,i),t.emitAsPromiseNoResponse(this,e.PROCESSOR_CONTEXT_EVENTS.REQUEST_UPDATE_CONSTRAINTS,Array.from($E(n=this.constraintsMap).call(n)))}async requestRevertConstraints(r){var i;if(this.constraintsMap.has(r))return this.constraintsMap.delete(r),t.emitAsPromiseNoResponse(this,e.PROCESSOR_CONTEXT_EVENTS.REQUEST_UPDATE_CONSTRAINTS,Array.from($E(i=this.constraintsMap).call(i)))}registerStats(e,t,r){this.statsRegistry.find((r=>r.processorID===e.ID&&r.processorName===e.name&&r.type===t))||this.statsRegistry.push({processorName:e.name,processorID:e.ID,type:t,cb:r})}unregisterStats(e,t){const r=this.statsRegistry.findIndex((r=>r.processorID===e.ID&&r.processorName===e.name&&r.type===t));-1!==r&&this.statsRegistry.splice(r,1)}gatherStats(){const e=[];for(const{processorID:i,processorName:o,type:n,cb:a}of this.statsRegistry)try{const t=a();e.push({processorID:i,processorName:o,type:n,stats:t})}catch(e){r.logger.error(new t.AgoraRTCError(t.AgoraRTCErrorCode.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 r=t();r instanceof jf&&(r=await r),e.push(tT(tT({},r),{},{direction:this.direction}))}catch(e){r.logger.error("gather extension usage error",e)}return e}getDirection(){return this.direction}}class aT extends t.EventEmitter{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 sT}setVolume(){}createOutputTrack(){throw new t.AgoraRTCError(t.AgoraRTCErrorCode.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 sT{disconnect(){}connect(){}}let cT=null;class dT{constructor(){this.state="open",this.trigger=void 0,this.tasks=[],r.logger.debug("[macro-task-queue] is created."),this.trigger=window.setTimeout((()=>{this.state="closed",r.logger.debug("[macro-task-queue] will be closed, all remaining tasks will execute. [".concat(this.tasks.map((e=>e.key)),"]")),this.trigger=void 0,this.tasks.forEach((e=>{let{func:t}=e;return t()})),this.tasks.length=0,r.logger.debug("[macro-task-queue] is closed.")}))}enqueue(e,t){"closed"!==this.state&&(this.tasks.push({key:e,func:t}),r.logger.debug("[macro-task-queue] is queued, current queue ".concat(this.tasks.length,". ").concat("string"==typeof e?e:"")))}runTask(e){if("closed"===this.state)return;const t=this.tasks.findIndex((t=>t.key===e));if(-1!==t){const i=this.tasks.splice(t,1);r.logger.debug("[macro-task-queue] is unqueued, current queue ".concat(this.tasks.length,". ").concat("string"==typeof e?e:"")),i[0].func()}}release(){this.trigger&&(this.state="closed",clearTimeout(this.trigger),this.trigger=void 0,this.tasks.length=0,r.logger.debug("[macro-task-queue] is closed."))}}function uT(e){return function(t,r,i){var o;const n=null!==(o=i.value)&&void 0!==o?o:i.get,a=function(){cT&&"open"===cT.state&&cT.runTask(e);for(var t=arguments.length,r=new Array(t),i=0;i<t;i++)r[i]=arguments[i];return null==n?void 0:n.apply(this,...r)};return i.value?i.value=a:i.get=a,i}}function lT(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}function hT(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?lT(Object(r),!0).forEach((function(t){Bl(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):lT(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}class pT extends Kf{get _source(){return this._trackSource}set _source(e){this._trackSource=e}get processorContext(){return this._processorContext}set processorContext(e){this._processorContext=e}get processorDestination(){return this._processorDestination}set processorDestination(e){this._processorDestination=e}get isPlaying(){return this._useAudioElement?WE.isPlaying(this.getTrackId()):this._source.isPlayed}get __className__(){return"LocalAudioTrack"}constructor(r,i,o,n,a){super(r,o),this.trackMediaType="audio",this._encoderConfig=void 0,this._trackSource=void 0,this._enabled=!0,this._volume=100,this._useAudioElement=!1,this._bypassWebAudio=!1,this.processor=void 0,this._processorContext=void 0,this._processorDestination=void 0,this._getOriginVolumeLevel=void 0,this._encoderConfig=i,this._getOriginVolumeLevel=!!n;const s=()=>{this.processorContext=new nT(this._source.context,this.getTrackId(),"local"),this.processorDestination=new oT(this.processorContext),this.bindProcessorDestinationEvents(),this._source.on(e.AudioSourceEvents.UPDATE_SOURCE,(()=>{this.processor&&this.processor.updateInput({node:this._source.processSourceNode,context:this.processorContext})}))},c=a&&t.isSafari()&&!$f();if(t.getParameter("DISABLE_WEBAUDIO")?(this._source=new aT,this._useAudioElement=!0,this._bypassWebAudio=!0):c?this._source=new aT:(this._source=new bE(r,!1,this._getOriginVolumeLevel?r:void 0),t.getParameter("LOCAL_AUDIO_TRACK_USES_WEB_AUDIO")||(this._useAudioElement=!0)),s(),!t.getParameter("DISABLE_WEBAUDIO")&&c){(cT||(cT=new dT),cT).enqueue("INIT_WEBAUDIO",(()=>{this._source=new bE(r,!1,this._getOriginVolumeLevel?r:void 0),t.getParameter("LOCAL_AUDIO_TRACK_USES_WEB_AUDIO")||(this._useAudioElement=!0),s(),this.emit(e.AUDIO_TRACK_EVENT.UPDATE_TRACK_SOURCE)}))}}setVolume(i){t.checkValidNumber(i,"volume",0,1e3),this._volume=i,this._source.setVolume(i/100),this._useAudioElement&&WE.setVolume(this.getTrackId(),i);try{if(this._bypassWebAudio)return void r.logger.debug("[".concat(this.getTrackId(),"] setVolume returned because no pass through WebAudio."));const i=this._source.createOutputTrack();this._mediaStreamTrack!==i&&(this._mediaStreamTrack=i,t.emitAsPromiseNoResponse(this,e.TrackInternalEvent.NEED_REPLACE_TRACK,this).then((()=>{r.logger.debug("[".concat(this.getTrackId(),"] replace web audio track success"))})).catch((e=>{r.logger.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)throw new t.AgoraRTCError(t.AgoraRTCErrorCode.NOT_SUPPORTED,"your browser does not support setting the audio output device");await WE.setSinkID(this.getTrackId(),e)}async setEnabled(e,t,r){return this._setEnabled(e,t,r)}async _setEnabled(i,o,n){if(!n){if(i===this._enabled)return;this.stateCheck("enabled",i)}if(r.logger.info("[".concat(this.getTrackId(),"] start setEnabled"),i),i){this._originMediaStreamTrack.enabled=!0;try{n||(this._enabled=!0),await t.emitAsPromiseNoResponse(this,e.TrackInternalEvent.NEED_ENABLE_TRACK,this),r.logger.info("[".concat(this.getTrackId(),"] setEnabled to ").concat(i," success"))}catch(e){throw n||(this._enabled=!1),r.logger.error("[".concat(this.getTrackId(),"] setEnabled to true error"),e.toString()),e}}else{this._originMediaStreamTrack.enabled=!1,n||(this._enabled=!1);try{await t.emitAsPromiseNoResponse(this,e.TrackInternalEvent.NEED_DISABLE_TRACK,this)}catch(e){throw n||(this._enabled=!0),r.logger.error("[".concat(this.getTrackId(),"] setEnabled to false error"),e.toString()),e}}}async setMuted(i){i!==this._muted&&(this.stateCheck("muted",i),this._muted=i,this._originMediaStreamTrack.enabled=!i,r.logger.debug("[".concat(this.getTrackId(),"] start set muted: ").concat(i)),i?await t.emitAsPromiseNoResponse(this,e.TrackInternalEvent.NEED_MUTE_TRACK,this):await t.emitAsPromiseNoResponse(this,e.TrackInternalEvent.NEED_UNMUTE_TRACK,this))}getStats(){t.runOnce((()=>{r.logger.warning("[deprecated] LocalAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalAudioStats instead")}),"localAudioTrackGetStatsWarning");const i=t.emitAsInvokerNoResponse(this,e.TrackInternalEvent.GET_STATS);return i||hT({},no)}setAudioFrameCallback(t){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:4096;if(!t)return this._source.removeAllListeners(e.AudioSourceEvents.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(r),this._source.removeAllListeners(e.AudioSourceEvents.ON_AUDIO_BUFFER),this._source.on(e.AudioSourceEvents.ON_AUDIO_BUFFER,(e=>t(e)))}play(){r.logger.debug("[".concat(this.getTrackId(),"] start audio playback")),this._useAudioElement?(r.logger.debug("[".concat(this.getTrackId(),"] start audio playback in element")),WE.play(this._mediaStreamTrack,this.getTrackId(),this._volume)):this._source.play()}stop(){r.logger.debug("[".concat(this.getTrackId(),"] stop audio playback")),this._useAudioElement?WE.stop(this.getTrackId()):this._source.stop()}close(){super.close(),this.unbindProcessorDestinationEvents(),this.unbindProcessorContextEvents(),this.unpipe(),this.processorDestination._source&&this.processorDestination._source.unpipe(),this._source.destroy()}_updatePlayerSource(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];r.logger.debug("[".concat(this.getTrackId(),"] update player source track")),e&&this._source.updateTrack(this._mediaStreamTrack),this._useAudioElement&&WE.updateTrack(this.getTrackId(),this._mediaStreamTrack)}async _updateOriginMediaStreamTrack(r,i){this._originMediaStreamTrack!==r&&(this._originMediaStreamTrack&&(this._originMediaStreamTrack.removeEventListener("ended",this._handleTrackEnded),i&&this._originMediaStreamTrack.stop()),r.addEventListener("ended",this._handleTrackEnded),this._originMediaStreamTrack=r,this._muted&&(this._originMediaStreamTrack.enabled=!1),this.processor&&this.processor.updateInput({track:r,context:this.processorContext}),this._mediaStreamTrack!==this._source.outputTrack?(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await t.emitAsPromiseNoResponse(this,e.TrackInternalEvent.NEED_REPLACE_TRACK,this)):this._source.updateTrack(this._originMediaStreamTrack),this._getOriginVolumeLevel&&this._source.updateOriginTrack(r))}renewMediaStreamTrack(e){return jf.resolve(void 0)}pipe(e){if(this._bypassWebAudio)throw new t.AgoraRTCError(t.AgoraRTCErrorCode.INVALID_OPERATION,"Can not process AudioTrack when bypassWebAudio set to true.");if(this.processor===e)return e;if(e._source)throw new t.AgoraRTCError(t.AgoraRTCErrorCode.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(){this.processorDestination.on(e.PROCESSOR_DESTINATION_EVENTS.ON_TRACK,(async r=>{r?r!==this._mediaStreamTrack&&(this._mediaStreamTrack=r,this._updatePlayerSource(!1),this._source.processedNode=this._source.createMediaStreamSourceNode(r),await t.emitAsPromiseNoResponse(this,e.TrackInternalEvent.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await t.emitAsPromiseNoResponse(this,e.TrackInternalEvent.NEED_REPLACE_TRACK,this))})),this.processorDestination.on(e.PROCESSOR_DESTINATION_EVENTS.ON_NODE,(e=>{this._source.processedNode=e}))}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(e.PROCESSOR_DESTINATION_EVENTS.ON_TRACK),this.processorDestination.removeAllListeners(e.PROCESSOR_DESTINATION_EVENTS.ON_NODE)}unbindProcessorContextEvents(){this.processorContext.removeAllListeners(e.PROCESSOR_CONTEXT_EVENTS.REQUEST_UPDATE_CONSTRAINTS),this.processorContext.removeAllListeners(e.PROCESSOR_CONTEXT_EVENTS.REQUEST_CONSTRAINTS)}}Hf([uT("INIT_WEBAUDIO"),Gf("design:type",Object),Gf("design:paramtypes",[Object])],pT.prototype,"_source",null),Hf([uT("INIT_WEBAUDIO"),Gf("design:type",nT),Gf("design:paramtypes",[nT])],pT.prototype,"processorContext",null),Hf([uT("INIT_WEBAUDIO"),Gf("design:type",oT),Gf("design:paramtypes",[oT])],pT.prototype,"processorDestination",null),Hf([r.apiInvoke({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),Gf("design:type",Function),Gf("design:paramtypes",[Number]),Gf("design:returntype",void 0)],pT.prototype,"setVolume",null),Hf([r.apiInvoke({argsMap:(e,t)=>[e.getTrackId(),t]}),KE(),Gf("design:type",Function),Gf("design:paramtypes",[String]),Gf("design:returntype",jf)],pT.prototype,"setPlaybackDevice",null),Hf([t.atom("LocalAudioTrack","_enabledMutex"),r.apiInvoke({argsMap:(e,t)=>[e.getTrackId(),t]}),KE(),Gf("design:type",Function),Gf("design:paramtypes",[Boolean,Object,Boolean]),Gf("design:returntype",jf)],pT.prototype,"setEnabled",null),Hf([t.atom("LocalAudioTrack","_enabledMutex"),r.apiInvoke({argsMap:(e,t)=>[e.getTrackId(),t]}),KE(),Gf("design:type",Function),Gf("design:paramtypes",[Boolean]),Gf("design:returntype",jf)],pT.prototype,"setMuted",null),Hf([KE(),Gf("design:type",Function),Gf("design:paramtypes",[]),Gf("design:returntype",Object)],pT.prototype,"getStats",null),Hf([KE(),Gf("design:type",Function),Gf("design:paramtypes",[Object,Number]),Gf("design:returntype",void 0)],pT.prototype,"setAudioFrameCallback",null),Hf([r.apiInvoke({argsMap:e=>[e.getTrackId()]}),KE(),Gf("design:type",Function),Gf("design:paramtypes",[]),Gf("design:returntype",void 0)],pT.prototype,"play",null),Hf([r.apiInvoke({argsMap:e=>[e.getTrackId()]}),KE(),Gf("design:type",Function),Gf("design:paramtypes",[]),Gf("design:returntype",void 0)],pT.prototype,"stop",null),Hf([r.apiInvoke({argsMap:e=>[e.getTrackId()]}),Gf("design:type",Function),Gf("design:paramtypes",[]),Gf("design:returntype",void 0)],pT.prototype,"close",null),Hf([r.apiInvoke({argsMap:(e,t)=>[e.getTrackId(),t.name]}),Gf("design:type",Function),Gf("design:paramtypes",[Object]),Gf("design:returntype",Object)],pT.prototype,"pipe",null),Hf([r.apiInvoke({argsMap:e=>[e.getTrackId()]}),Gf("design:type",Function),Gf("design:paramtypes",[]),Gf("design:returntype",void 0)],pT.prototype,"unpipe",null);class gT extends pT{get __className__(){return"MicrophoneAudioTrack"}constructor(r,i,o,n){super(r,i.encoderConfig?Wi(i.encoderConfig):{},n,t.getParameter("GET_VOLUME_OF_MUTED_AUDIO_TRACK"),!0),this._config=void 0,this._deviceName="default",this._constraints=void 0,this._originalConstraints=void 0,this._enabled=!0,this._config=i,this._constraints=o,this._originalConstraints=o,this._deviceName=r.label,"boolean"==typeof i.bypassWebAudio&&(this._bypassWebAudio=i.bypassWebAudio),(t.isIOS15()||t.isIOS16())&&Yf.bindInterruptDetectorTrack(this),this.on(e.AUDIO_TRACK_EVENT.UPDATE_TRACK_SOURCE,(()=>{this.bindProcessorContextEvents()})),$f()&&this.bindProcessorContextEvents()}async setDevice(e){if(r.logger.info("[".concat(this.getTrackId(),"] start set device to ").concat(e)),this._enabled)try{const t=await LE.getDeviceById(e),i={};i.audio=hT({},this._constraints),i.audio.deviceId={exact:e},this._originMediaStreamTrack.stop();let o=null;try{o=await NE(i,this.getTrackId())}catch(e){throw r.logger.error("[".concat(this.getTrackId(),"] setDevice failed"),e.toString()),o=await NE({audio:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(o.getAudioTracks()[0],!1),e}await this._updateOriginMediaStreamTrack(o.getAudioTracks()[0],!1),this._deviceName=t.label,this._config.microphoneId=e,this._constraints.deviceId={exact:e}}catch(e){throw r.logger.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}else try{const t=await LE.getDeviceById(e);this._deviceName=t.label,this._config.microphoneId=e,this._constraints.deviceId={exact:e}}catch(e){throw r.logger.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}r.logger.info("[".concat(this.getTrackId(),"] set device to ").concat(e," success"))}async setEnabled(i,o,n){if(o)return r.logger.debug("[".concat(this.getTrackId(),"] setEnabled false (do not close microphone)")),await super._setEnabled(i);if(!n){if(i===this._enabled)return;this.stateCheck("enabled",i)}if(r.logger.info("[".concat(this.getTrackId(),"] start setEnabled"),i),!i){var a;this._originMediaStreamTrack.onended=null,this._originMediaStreamTrack.stop(),null===(a=this._source.clonedTrack)||void 0===a||a.stop(),n||(this._enabled=!1);try{await t.emitAsPromiseNoResponse(this,e.TrackInternalEvent.NEED_DISABLE_TRACK,this)}catch(e){throw r.logger.error("[".concat(this.getTrackId(),"] setEnabled false failed"),e.toString()),e}return}const s=hT({},this._constraints),c=LE.searchDeviceIdByName(this._deviceName);c&&!s.deviceId&&(s.deviceId=c);try{n||(this._enabled=!0);const r=await NE({audio:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(r.getAudioTracks()[0],!1),await t.emitAsPromiseNoResponse(this,e.TrackInternalEvent.NEED_ENABLE_TRACK,this)}catch(e){throw n||(this._enabled=!1),r.logger.error("[".concat(this.getTrackId(),"] setEnabled true failed"),e.toString()),e}r.logger.info("[".concat(this.getTrackId(),"] setEnabled success"))}close(){super.close(),(t.isIOS15()||t.isIOS16())&&Yf.unbindInterruptDetectorTrack(this)}onTrackEnded(){if((t.isIOS()||t.isIpadOS())&&this._enabled&&!this._isClosed&&Yf.duringInterruption){const t=async()=>{Yf.off(e.AUDIO_CONTEXT_EVENT.IOS_INTERRUPTION_END,t),this._enabled&&!this._isClosed&&(r.logger.debug("[".concat(this.getTrackId(),"] try capture microphone media device for interrupted iOS device.")),await this.setEnabled(!1),await this.setEnabled(!0))};Yf.on(e.AUDIO_CONTEXT_EVENT.IOS_INTERRUPTION_END,t)}else r.logger.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(e.LocalTrackEvents.TRACK_ENDED)}async renewMediaStreamTrack(e){const t=e||this._constraints,r=LE.searchDeviceIdByName(this._deviceName);if(r&&!t.deviceId&&(t.deviceId=r),this._constraints=t,this._enabled){this._originMediaStreamTrack.stop();const e=await NE({audio:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getAudioTracks()[0],!0)}}bindProcessorContextEvents(){this.processorContext.on(e.PROCESSOR_CONTEXT_EVENTS.REQUEST_UPDATE_CONSTRAINTS,(async(e,t,r)=>{try{const r=Object.assign({},this._originalConstraints,...e);await this.renewMediaStreamTrack(r),t()}catch(e){r(e)}})),this.processorContext.on(e.PROCESSOR_CONTEXT_EVENTS.REQUEST_CONSTRAINTS,(async e=>{e(this._originMediaStreamTrack.getSettings())}))}}Hf([r.apiInvoke({argsMap:(e,t)=>[e.getTrackId(),t]}),KE(),Gf("design:type",Function),Gf("design:paramtypes",[String]),Gf("design:returntype",jf)],gT.prototype,"setDevice",null),Hf([t.atom("MicrophoneAudioTrack","_enabledMutex"),r.apiInvoke({argsMap:(e,t,r)=>[e.getTrackId(),t,r]}),KE(),Gf("design:type",Function),Gf("design:paramtypes",[Boolean,Boolean,Boolean]),Gf("design:returntype",jf)],gT.prototype,"setEnabled",null),Hf([r.apiInvoke({argsMap:e=>[e.getTrackId()]}),Gf("design:type",Function),Gf("design:paramtypes",[]),Gf("design:returntype",void 0)],gT.prototype,"close",null);class mT extends pT{get __className__(){return"BufferSourceAudioTrack"}constructor(t,r,i,o){super(r.createOutputTrack(),i,o),this.source=void 0,this._bufferSource=void 0,this.source=t,this._bufferSource=r,this._bufferSource.on(e.AudioSourceEvents.AUDIO_SOURCE_STATE_CHANGE,(t=>{this.safeEmit(e.LocalTrackEvents.SOURCE_STATE_CHANGE,t)}));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){t.checkValidNumber(e,"speed",0),this._bufferSource.setAudioBufferPlaybackSpeed(e)}}Hf([r.apiInvoke({argsMap:(e,t)=>[e.getTrackId(),t,e.duration]}),KE(),Gf("design:type",Function),Gf("design:paramtypes",[Object]),Gf("design:returntype",void 0)],mT.prototype,"startProcessAudioBuffer",null),Hf([r.apiInvoke({argsMap:e=>[e.getTrackId()]}),KE(),Gf("design:type",Function),Gf("design:paramtypes",[]),Gf("design:returntype",void 0)],mT.prototype,"pauseProcessAudioBuffer",null),Hf([r.apiInvoke({argsMap:e=>[e.getTrackId()]}),KE(),Gf("design:type",Function),Gf("design:paramtypes",[Number]),Gf("design:returntype",void 0)],mT.prototype,"seekAudioBuffer",null),Hf([r.apiInvoke({argsMap:e=>[e.getTrackId()]}),KE(),Gf("design:type",Function),Gf("design:paramtypes",[]),Gf("design:returntype",void 0)],mT.prototype,"resumeProcessAudioBuffer",null),Hf([r.apiInvoke({argsMap:e=>[e.getTrackId()]}),KE(),Gf("design:type",Function),Gf("design:paramtypes",[]),Gf("design:returntype",void 0)],mT.prototype,"stopProcessAudioBuffer",null),Hf([r.apiInvoke({argsMap:e=>[e.getTrackId()]}),Gf("design:type",Function),Gf("design:paramtypes",[]),Gf("design:returntype",void 0)],mT.prototype,"close",null),Hf([r.apiInvoke({argsMap:e=>[e.getTrackId()]}),KE(),Gf("design:type",Function),Gf("design:paramtypes",[Number]),Gf("design:returntype",void 0)],mT.prototype,"setAudioBufferPlaybackSpeed",null);class fT extends pT{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=Zf().createMediaStreamDestination();super(e.stream.getAudioTracks()[0],void 0,t.getRandomString(8,"track-mix-")),this.trackList=void 0,this.destNode=void 0;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)?(r.logger.debug("add ".concat(e.getTrackId()," to mixing track")),e._source.outputNode.connect(this.destNode),this.trackList.push(e),this.updateEncoderConfig()):r.logger.debug("track ".concat(e.getTrackId()," is already added"))}removeAudioTrack(e){if(-1!==this.trackList.indexOf(e)){r.logger.debug("remove ".concat(e.getTrackId()," from mixing track"));try{e._source.outputNode.disconnect(this.destNode)}catch(e){}t.removeItemFromList(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(t){this._rtpTransceiver!==t&&(this._rtpTransceiver=t,this.trackList.forEach((r=>{r instanceof fT?r.emit(e.TrackEvents.TRANSCEIVER_UPDATED,t):r._updateRtpTransceiver(t)})))}}function ET(e){const r={};e.facingMode&&(r.facingMode=e.facingMode),e.cameraId&&(r.deviceId={exact:e.cameraId});const i=Fi(e.encoderConfig);return null!=i.width&&(r.width=i.width),null!=i.height&&(r.height=i.height),!t.isLegacyChrome()&&i.frameRate&&(r.frameRate=i.frameRate),t.isEdge()&&"object"==typeof r.frameRate&&(r.frameRate.max=60),t.isFirefox()&&(r.frameRate={ideal:30,max:30}),r}function TT(e){const r={};e.screenSourceType&&(r.mediaSource=e.screenSourceType),e.extensionId&&t.isChrome()&&(r.extensionId=e.extensionId);const{displaySurface:i,selfBrowserSurface:o,surfaceSwitching:n,systemAudio:a}=e;(t.isAboveChrome(107)||t.isAboveEdge(107)||t.isAboveOpera(93))&&(i&&(t.checkValidEnum(i,"displaySurface",["browser","window","monitor"]),r.displaySurface=i),o?(t.checkValidEnum(o,"selfBrowserSurface",["exclude","include"]),r.selfBrowserSurface=o):r.selfBrowserSurface="include",n&&(t.checkValidEnum(n,"surfaceSwitching",["exclude","include"]),r.surfaceSwitching=n)),(t.isAboveChrome(105)||t.isAboveEdge(105)||t.isAboveOpera(91))&&a&&(t.checkValidEnum(a,"systemAudio",["exclude","include"]),r.systemAudio=a),e.electronScreenSourceId&&(r.sourceId=e.electronScreenSourceId);const s=e.encoderConfig?ji(e.encoderConfig):null;return r.mandatory={chromeMediaSource:"desktop",maxWidth:s?s.width:void 0,maxHeight:s?s.height:void 0},s&&(s.frameRate&&("number"==typeof s.frameRate?(r.mandatory.maxFrameRate=s.frameRate,r.mandatory.minFrameRate=s.frameRate):(r.mandatory.maxFrameRate=s.frameRate.max||s.frameRate.ideal||s.frameRate.exact||void 0,r.mandatory.minFrameRate=s.frameRate.min||s.frameRate.ideal||s.frameRate.exact||void 0),r.frameRate=s.frameRate),s.width&&(r.width=s.width),s.height&&(r.height=s.height)),r}function vT(e){const r={};if(t.isLegacyChrome()||(void 0!==e.AGC&&(r.autoGainControl=e.AGC),void 0!==e.AEC&&(r.echoCancellation=e.AEC),void 0!==e.ANS&&(r.noiseSuppression=e.ANS,t.isChrome()&&e.ANS&&(r.googHighpassFilter=e.ANS))),e.encoderConfig){const t=Wi(e.encoderConfig);r.channelCount=t.stereo?2:1,r.sampleRate=t.sampleRate,r.sampleSize=t.sampleSize}return e.microphoneId&&(r.deviceId={exact:e.microphoneId}),t.isAndroid()&&(r.sampleRate=void 0),r}class _T extends AE{set currentState(t){t!==this._currentState&&(this._currentState=t,this.safeEmit(e.AudioSourceEvents.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):r.logger.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 yT=new Map;const ST=e=>{const r=document.createElement("canvas");return r.width=2,r.height=2,new jf(((i,o)=>{r.toBlob((async e=>{if(r.remove(),e){const t=await AT(e);i({buffer:t,width:r.width,height:r.height})}else o(new t.AgoraRTCError(t.AgoraRTCErrorCode.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED))}),e,1)}))},AT=async e=>{const t=await e.arrayBuffer();return new Uint8Array(t)};class bT extends t.EventEmitter{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(),r.logger.debug("document visibility went ".concat(document.visibilityState)),this.emit("VISIBILITY_CHANGE",document.visibilityState)}))}}const kT=new bT;function IT(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}function CT(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?IT(Object(r),!0).forEach((function(t){Bl(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):IT(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}class OT{get videoElementStatus(){return this._videoElementStatus}set videoElementStatus(e){e!==this._videoElementStatus&&(r.logger.debug("[".concat(this.trackId,"] video-element-status change ").concat(this._videoElementStatus," => ").concat(e)),this._videoElementStatus=e)}constructor(i){this.trackId=void 0,this.config=void 0,this.onFirstVideoFrameDecoded=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.videoElementCheckInterval=void 0,this._videoElementStatus=e.MediaElementStatus.NONE,this.isGettingVideoDimensions=!1,this.startGetVideoDimensions=()=>{const e=()=>{if(this.isGettingVideoDimensions=!0,this.videoElement.videoWidth*this.videoElement.videoHeight>4)return r.logger.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"===Yf.curState&&(r.logger.debug("[track-".concat(this.trackId,"] video element paused, auto resume for ").concat(t.getOSWithVersion())),t.isAboveIOS15_1()?(this.videoElement.srcObject=null,this.videoElement.srcObject=new MediaStream([this.videoTrack]),this.videoElement.play()):(this.videoElement.pause(),this.videoElement.play()))},this.handleVideoEvents=i=>{switch(i.type){case"play":case"playing":this.startGetVideoDimensions(),this.videoElementStatus=e.MediaElementStatus.PLAYING;break;case"loadeddata":if(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=e.MediaElementStatus.CANPLAY;break;case"stalled":this.videoElementStatus=e.MediaElementStatus.STALLED;break;case"suspend":this.videoElementStatus=e.MediaElementStatus.SUSPEND;break;case"pause":this.videoElementStatus=e.MediaElementStatus.PAUSED,t.isIOS()||t.isIpadOS()||t.isSafari()&&this.autoplayFailed||!this.videoTrack||"live"!==this.videoTrack.readyState||(r.logger.debug("[track-".concat(this.trackId,"] video element paused, auto resume")),this.videoElement.play());break;case"waiting":this.videoElementStatus=e.MediaElementStatus.WAITING;break;case"abort":this.videoElementStatus=e.MediaElementStatus.ABORT;break;case"ended":this.videoElementStatus=e.MediaElementStatus.ENDED;break;case"emptied":this.videoElementStatus=e.MediaElementStatus.EMPTIED;break;case"error":{this.videoElementStatus=e.MediaElementStatus.ERROR;const t=this.videoElement.error;t&&r.logger.error("[".concat(this.trackId,"] media error, code: ").concat(t.code,", message: ").concat(t.message));break}case"timeupdate":{const e=performance.now();if(this.timeUpdatedCount+=1,this.timeUpdatedCount<10)return void(this.lastTimeUpdatedTime=e);const r=e-this.lastTimeUpdatedTime,i=this.lastTimeUpdatedTime;if(this.lastTimeUpdatedTime=e,kT.lastVisibleTime<kT.lastHiddenTime||i<kT.lastHiddenTime||i<kT.lastVisibleTime)return;for(r>t.getParameter("VIDEO_FREEZE_DURATION")&&(this.freezeTime+=r),this.playbackTime+=r;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&&(r.logger.debug("[track-".concat(this.trackId,"] video element paused, auto resume for ").concat(t.getOSWithVersion())),t.isAboveIOS15_1()?(this.videoElement.srcObject=null,this.videoElement.srcObject=new MediaStream([this.videoTrack]),this.videoElement.play()):(this.videoElement.pause(),this.videoElement.play()))},this.trackId=i.trackId,this.config=i,i.element instanceof HTMLVideoElement?this.videoElement=i.element:this.videoElement=document.createElement("video"),Yf.on(e.AUDIO_CONTEXT_EVENT.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),Yf.on(e.AUDIO_CONTEXT_EVENT.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(e){const i=this.videoElement.play();i&&i.catch&&i.catch((t=>{e&&HE(e,"video",t.message,this.trackId),"NotAllowedError"===t.name?(r.logger.warning("detected video element autoplay failed",t),this.autoplayFailed=!0,this.handleAutoPlayFailed()):r.logger.warning("[".concat(this.trackId,"] play warning: "),t)}));const o=t.getBrowserInfo();if(("Safari"===o.name&&15===Number(o.version)||t.isIOS15())&&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 r.logger.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 r=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 o=i.getContext("2d");return o?(o.drawImage(this.videoElement,0,0,i.width,i.height),new jf(((o,n)=>{i.toBlob((async e=>{if(i.remove(),e){const t=await AT(e);o({buffer:t,width:i.width,height:i.height})}else n(new t.AgoraRTCError(t.AgoraRTCErrorCode.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED))}),e,r<0?.1:r>1?1:r)}))):await ST(e)}destroy(){Yf.off(e.AUDIO_CONTEXT_EVENT.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),Yf.off(e.AUDIO_CONTEXT_EVENT.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16),this.videoElement.srcObject=null,this.resetVideoElement(),this.freezeTimeCounterList=[]}initVideoElement(){if(this.videoElementStatus=e.MediaElementStatus.INIT,!this.videoElementCheckInterval&&(RT.forEach((e=>{this.videoElement.addEventListener(e,this.handleVideoEvents)})),this.videoElementCheckInterval=window.setInterval((()=>{t.isInPage(this.videoElement)||(this.videoElementStatus=e.MediaElementStatus.DESTROYED)}),1e3),t.getParameter("ENABLE_VIDEO_FRAME_CALLBACK"))){var i,o;let r;const n=(i,o)=>{if(this.videoElementStatus===e.MediaElementStatus.PLAYING){if(r){const e=o.presentationTime-r.presentationTime;e>t.getParameter("VIDEO_FREEZE_DURATION")&&kT.lastVisibleTime>=kT.lastHiddenTime&&r.timestamp>kT.lastVisibleTime&&r.timestamp>kT.lastHiddenTime&&(this.renderFreezeAccTime+=e)}r=CT(CT({},o),{},{timestamp:i})}var a,s;t.getParameter("ENABLE_VIDEO_FRAME_CALLBACK")&&(null===(a=(s=this.videoElement).requestVideoFrameCallback)||void 0===a||a.call(s,n))};null===(i=(o=this.videoElement).requestVideoFrameCallback)||void 0===i||i.call(o,n)}this.videoElement.controls=!1,this.videoElement.setAttribute("playsinline",""),t.isAndroid()&&(this.videoElement.poster="noposter");const n=t.getBrowserInfo();if("Safari"===n.name&&15===Number(n.version)||t.isIOS15()||!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,t.isFirefox()&&this.videoElement.load())}else this.videoElement.srcObject=this.videoTrack?new MediaStream([this.videoTrack]):null,t.isFirefox()&&this.videoElement.load();const a=this.videoElement.play();void 0!==a&&a.catch((e=>{r.logger.debug("[".concat(this.trackId,"] playback interrupted"),e.toString())}))}resetVideoElement(){RT.forEach((e=>{this.videoElement&&this.videoElement.removeEventListener(e,this.handleVideoEvents)})),this.videoElementCheckInterval&&(window.clearInterval(this.videoElementCheckInterval),this.videoElementCheckInterval=void 0),this.videoElementStatus=e.MediaElementStatus.NONE}handleAutoPlayFailed(){const e=i=>{i.preventDefault(),this.videoElement.play().then((()=>{r.logger.debug("[".concat(this.trackId,"] Video element for trackId:").concat(this.trackId," autoplay resumed."))})).catch((e=>{r.logger.error(e)})),this.autoplayFailed=!1,t.isAndroidChromium()?document.body.removeEventListener("click",e,!0):(document.body.removeEventListener("touchstart",e,!0),document.body.removeEventListener("mousedown",e,!0))};t.isAndroidChromium()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0)),BE()}}const RT=["play","playing","loadeddata","canplay","pause","stalled","suspend","waiting","abort","emptied","ended","timeupdate","error"];class NT extends OT{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 r=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,r):await ST(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",t.getParameter("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 wT(e){return new jf(((r,i)=>{let o=!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 a=t.isIOS()?"canplay":"playing";n.addEventListener(a,(()=>{const e=n.videoWidth,i=n.videoHeight;!e&&t.isFirefox()||(o=!0,n.srcObject=null,n.remove(),r([e,i]))})),n.srcObject=new MediaStream([e]),n.play().catch(t.noop),setTimeout((()=>{o||(n.srcObject=null,n.remove(),r([n.videoWidth,n.videoHeight]))}),4e3)}))}function DT(e,t,r,i){let o;const n=200*Math.pow(r/15,.6)*Math.pow(e*t/640/360,.75),a=n;if("STANDARD_BITRATE"===i)o=4*n;else{if("COMPATIABLE_BITRATE"!==i)return;o=2*n}return[Math.floor(o),Math.floor(a)]}function PT(e,t){if("VideoFrame"in window&&"TransformStream"in window&&aE().supportWebRTCInsertableStream){const r=new MediaStreamTrackProcessor(e),i=new MediaStreamTrackGenerator({kind:"video"});let o,n,a=Date.now();const s=()=>{c&&(clearInterval(c),c=void 0),o&&(o.close(),o=void 0),e.stop(),n=void 0,i.removeEventListener("ended",s)};let c=window.setInterval((()=>{if(n&&o&&Date.now()-a>(null!=t?t:1e3))try{"live"===i.readyState?n.enqueue(o.clone()):s()}catch(e){s()}}),null!=t?t:1e3);const d=new TransformStream({transform:(e,t)=>{"live"===i.readyState?(n=t,a=Date.now(),void 0===o?(o=e,t.enqueue(e.clone())):(t.enqueue(o),o=e)):e.close()}});return i.addEventListener("ended",s),r.readable.pipeThrough(d).pipeTo(i.writable),i}}function MT(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}function LT(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?MT(Object(r),!0).forEach((function(t){Bl(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):MT(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}class VT extends Kf{get isPlaying(){return!(!this._player||this._player.videoElementStatus!==e.MediaElementStatus.PLAYING)}get processorContext(){return this._processorContext}set processorContext(e){this._processorContext=e}get __className__(){return"LocalVideoTrack"}constructor(i,o,n,a,s,c){if(super(i,s),this.trackMediaType="video",this._player=void 0,this._videoVisibleTimer=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,t.isSafari()){const{width:e,height:t}=i.getSettings();this._videoWidth=e,this._videoHeight=t}else this.updateMediaStreamTrackResolution();if(this._encoderConfig=o,this._scalabilityMode=n,this._optimizationMode=a,this._hints=c||[],-1===this._hints.indexOf(e.TrackHint.SCREEN_TRACK))this.updateBitrateFromProfile();else if(t.isBetweenBrowser(t.BrowserName.CHROME,115)&&t.isWindows()){const e=PT(i);e&&(r.logger.info("local screen video track begin to inject frame"),this._mediaStreamTrack=e)}o&&-1!==this._hints.indexOf(e.TrackHint.CUSTOM_TRACK)&&this.setEncoderConfiguration(o),this.processorContext=new iT(this.getTrackId(),"local"),this.processorDestination=new rT(this.processorContext),this.bindProcessorDestinationEvents()}play(i){let o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("string"==typeof i){const e=document.getElementById(i);e?i=e:(r.logger.warning("[".concat(this.getTrackId(),'] can not find "#').concat(i,'" element, use document.body')),i=document.body)}r.logger.debug("[".concat(this.getTrackId(),"] start video playback in ").concat(i instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement"),JSON.stringify(o));const n=LT(LT(LT({},this._getDefaultPlayerConfig()),o),{},{trackId:this.getTrackId(),element:i});this._player?this._player.updateConfig(n):(i instanceof HTMLVideoElement?this._player=new OT(n):this._player=new NT(n),this._player.updateVideoTrack(this._mediaStreamTrack)),this._player.play(),this._videoVisibleTimer&&window.clearInterval(this._videoVisibleTimer),this._clearPreviousVideoVisibleStatus(),this._videoVisibleTimer=window.setInterval((()=>{try{const t=this.getVideoElementVisibleStatus();this.safeEmit(e.LocalTrackEvents.VIDEO_ELEMENT_VISIBLE_STATUS,t)}catch(e){}}),t.getParameter("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,r.logger.debug("[".concat(this.getTrackId(),"] stop video playback")))}async setEnabled(i,o){if(!o){if(i===this._enabled)return;this.stateCheck("enabled",i)}if(r.logger.info("[".concat(this.getTrackId(),"] start setEnabled"),i),!i){this._originMediaStreamTrack.enabled=!1;try{await t.emitAsPromiseNoResponse(this,e.TrackInternalEvent.NEED_DISABLE_TRACK,this)}catch(e){throw r.logger.error("[".concat(this.getTrackId(),"] setEnabled to false error"),e.toString()),e}return o||(this._enabled=!1),void r.logger.info("[".concat(this.getTrackId(),"] setEnabled to false success"))}this._originMediaStreamTrack.enabled=!0;try{await t.emitAsPromiseNoResponse(this,e.TrackInternalEvent.NEED_ENABLE_TRACK,this)}catch(e){throw r.logger.error("[".concat(this.getTrackId(),"] setEnabled to true error"),e.toString()),e}r.logger.info("[".concat(this.getTrackId(),"] setEnabled to true success")),o||(this._enabled=!0)}async setMuted(i){i!==this._muted&&(this.stateCheck("muted",i),this._muted=i,this._originMediaStreamTrack.enabled=!i,r.logger.debug("[".concat(this.getTrackId(),"] start set muted: ").concat(i)),i?await t.emitAsPromiseNoResponse(this,e.TrackInternalEvent.NEED_MUTE_TRACK,this):await t.emitAsPromiseNoResponse(this,e.TrackInternalEvent.NEED_UNMUTE_TRACK,this))}async setEncoderConfiguration(i,o){if(!this._enabled)throw new t.AgoraRTCError(t.AgoraRTCErrorCode.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");if(i=Fi(i),this._forceBitrateLimit&&(i.bitrateMax=this._forceBitrateLimit.max_bitrate?this._forceBitrateLimit.max_bitrate:i.bitrateMax,i.bitrateMin=this._forceBitrateLimit.min_bitrate?this._forceBitrateLimit.min_bitrate:i.bitrateMin),i.width||i.height||i.frameRate){const e=ET({encoderConfig:i});(t.isSafari()||t.isIOS()||t.isIpadOS())&&(e.deviceId=void 0),r.logger.debug("[".concat(this.getTrackId(),"] setEncoderConfiguration applyConstraints"),JSON.stringify(i),JSON.stringify(e));try{await this._originMediaStreamTrack.applyConstraints(e),this.updateMediaStreamTrackResolution()}catch(e){const i=new t.AgoraRTCError(t.AgoraRTCErrorCode.UNEXPECTED_ERROR,e.toString());throw r.logger.error("[".concat(this.getTrackId(),"] applyConstraints error"),i.toString()),i}}this._encoderConfig=i,-1===this._hints.indexOf(e.TrackHint.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await t.emitAsPromiseNoResponse(this,e.TrackInternalEvent.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(r.logger)}}getStats(){t.runOnce((()=>{r.logger.warning("[deprecated] LocalVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalVideoStats instead")}),"localVideoTrackGetStatsWarning");const i=t.emitAsInvokerNoResponse(this,e.TrackInternalEvent.GET_STATS);return i||LT({},ao)}async setBeautyEffect(e){r.logger.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 ST(e)}async setBitrateLimit(i){if(r.logger.debug("[".concat(this.getTrackId(),"] set bitrate limit, ").concat(JSON.stringify(i))),i){this._forceBitrateLimit=i,this._encoderConfig&&(this._encoderConfig.bitrateMax?this._encoderConfig.bitrateMax=this._encoderConfig.bitrateMax<i.max_bitrate?this._encoderConfig.bitrateMax:i.max_bitrate:this._encoderConfig.bitrateMax=i.max_bitrate,this._encoderConfig.bitrateMin,this._encoderConfig.bitrateMin=i.min_bitrate);try{await t.emitAsPromiseNoResponse(this,e.TrackInternalEvent.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(r.logger)}}}async setOptimizationMode(i){if("motion"!==i&&"detail"!==i&&"balanced"!==i)return void r.logger.error(t.AgoraRTCErrorCode.INVALID_PARAMS,"optimization mode must be motion, detail or balanced");const o=this._optimizationMode;try{this._optimizationMode=i,await t.emitAsPromiseNoResponse(this,e.TrackInternalEvent.SET_OPTIMIZATION_MODE,this)}catch(e){throw this._optimizationMode=o,r.logger.error("[".concat(this.getTrackId(),"] set optimization mode failed"),e.toString()),e}r.logger.info("[".concat(this.getTrackId(),"] set optimization mode success (").concat(i,")"))}setScalabiltyMode(e){if(1===e.numSpatialLayers&&1!==e.numTemporalLayers)return r.logger.error(t.AgoraRTCErrorCode.INVALID_PARAMS,"scalability mode currently not supported, no SVC."),void(this._scalabilityMode={numSpatialLayers:1,numTemporalLayers:1});this._scalabilityMode=e,r.logger.info("[".concat(this.getTrackId(),"] set scalability mode success (").concat(e,")"))}updateMediaStreamTrackResolution(){wT(this._originMediaStreamTrack).then((e=>{let[t,r]=e;this._videoHeight=r,this._videoWidth=t})).catch(t.noop)}_updatePlayerSource(){this._player&&this._player.updateVideoTrack(this._mediaStreamTrack)}_getDefaultPlayerConfig(){return{fit:"contain"}}updateBitrateFromProfile(){if(!this._encoderConfig)return;const{width:e,height:i,frameRate:o}=this.getMediaStreamTrackSettings();if(!e||!i||!o)return;const[n,a]=DT(e,i,o,t.getParameter("BITRATE_ADAPTER_TYPE"))||[void 0,void 0];this._encoderConfig.bitrateMin||this._encoderConfig.bitrateMax||(this._encoderConfig.bitrateMin=a,this._encoderConfig.bitrateMax=n,r.logger.debug("[".concat(this.getTrackId(),"] update bitrate from profile, [w: ").concat(e,", h: ").concat(i,", fps: ").concat(o,"] => [brMax: ").concat(n,", brMin: ").concat(a,"]")))}getVideoElementVisibleStatus(){try{var e,i;const o=null==this||null===(e=this._player)||void 0===e?void 0:e.getContainerElement(),n={track:this,element:null==this||null===(i=this._player)||void 0===i?void 0:i.getVideoElement(),slot:null==o?void 0:o.parentElement},{element:a,slot:s}=n;if(this.isPlaying&&a instanceof HTMLVideoElement&&s instanceof HTMLElement){const e=t.elementVisibleChecker.checkOneElementVisible(a),i=Object.assign({},e);if(i.visible!==this._previousVideoVisibleStatus){this._previousVideoVisibleStatus=i.visible;const e=r.report.reportApiInvoke(null,{tag:t.AgoraAPITag.TRACER,name:t.AgoraAPIName.LOCAL_VIDEO_TRACK_GET_VIDEO_VISIBLE,options:[this.getTrackId()]});i.visible?e.onSuccess("Video is visible"):e.onSuccess("Invisible because of ".concat(i.reason))}return i}return}catch(e){throw new t.AgoraRTCError(t.AgoraRTCErrorCode.GET_VIDEO_ELEMENT_VISIBLE_ERROR,e.message)}}async renewMediaStreamTrack(e){}pipe(e){if(this.processor===e)return e;if(e._source)throw new t.AgoraRTCError(t.AgoraRTCErrorCode.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 i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],o=this._encoderConfig;e&&(o=LT(LT({},o),Fi(e))),o=t.safeCloneJson(o);const n=t.getRandomString(8,"track-video-cloned-"),a=new VT(i?this._mediaStreamTrack.clone():this._mediaStreamTrack,o,t.safeCloneJson(this._scalabilityMode),this._optimizationMode,n,t.safeCloneJson(this._hints));return e&&o&&a.setEncoderConfiguration(o),r.logger.debug("clone video track from ".concat(this.getTrackId()," to ").concat(n,", clone ").concat(i)),a}async replaceTrack(e,r){if(!(e instanceof MediaStreamTrack))throw new t.AgoraRTCError(t.AgoraRTCErrorCode.INVALID_PARAMS,"track should be an instance of MediaStreamTrack");if("video"!==e.kind)throw new t.AgoraRTCError(t.AgoraRTCErrorCode.INVALID_PARAMS,"track should be a video MediaStreamTrack");await this._updateOriginMediaStreamTrack(e,r,!0),this.updateMediaStreamTrackResolution()}bindProcessorDestinationEvents(){this.processorDestination.on(e.PROCESSOR_DESTINATION_EVENTS.ON_TRACK,(async r=>{r?r!==this._mediaStreamTrack&&(this._mediaStreamTrack=r,this._updatePlayerSource(),await t.emitAsPromiseNoResponse(this,e.TrackInternalEvent.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await t.emitAsPromiseNoResponse(this,e.TrackInternalEvent.NEED_REPLACE_TRACK,this))}))}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(e.PROCESSOR_DESTINATION_EVENTS.ON_TRACK)}unbindProcessorContextEvents(){this.processorContext.removeAllListeners(e.PROCESSOR_CONTEXT_EVENTS.REQUEST_UPDATE_CONSTRAINTS),this.processorContext.removeAllListeners(e.PROCESSOR_CONTEXT_EVENTS.REQUEST_CONSTRAINTS)}}Hf([r.apiInvoke({argsMap:(e,t,r)=>[e.getTrackId(),"string"==typeof t?t:t instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement",r]}),KE(),Gf("design:type",Function),Gf("design:paramtypes",[Object,Object]),Gf("design:returntype",void 0)],VT.prototype,"play",null),Hf([r.apiInvoke({argsMap:e=>[e.getTrackId()]}),Gf("design:type",Function),Gf("design:paramtypes",[]),Gf("design:returntype",void 0)],VT.prototype,"stop",null),Hf([t.atom("LocalVideoTrack","_enabledMutex"),r.apiInvoke({argsMap:(e,t)=>[e.getTrackId(),t]}),KE(),Gf("design:type",Function),Gf("design:paramtypes",[Boolean,Boolean]),Gf("design:returntype",jf)],VT.prototype,"setEnabled",null),Hf([t.atom("LocalVideoTrack","_enabledMutex"),r.apiInvoke({argsMap:(e,t)=>[e.getTrackId(),t]}),KE(),Gf("design:type",Function),Gf("design:paramtypes",[Boolean]),Gf("design:returntype",jf)],VT.prototype,"setMuted",null),Hf([r.apiInvoke({argsMap:(e,t)=>[e.getTrackId(),t]}),KE(),Gf("design:type",Function),Gf("design:paramtypes",[Object,Boolean]),Gf("design:returntype",jf)],VT.prototype,"setEncoderConfiguration",null),Hf([KE(),Gf("design:type",Function),Gf("design:paramtypes",[]),Gf("design:returntype",Object)],VT.prototype,"getStats",null),Hf([r.apiInvoke({argsMap:(e,t,r)=>[e.getTrackId(),t,r]}),KE(),Gf("design:type",Function),Gf("design:paramtypes",[Boolean,Object]),Gf("design:returntype",jf)],VT.prototype,"setBeautyEffect",null),Hf([KE(),Gf("design:type",Function),Gf("design:paramtypes",[]),Gf("design:returntype",ImageData)],VT.prototype,"getCurrentFrameData",null),Hf([KE(),Gf("design:type",Function),Gf("design:paramtypes",[String,Number]),Gf("design:returntype",jf)],VT.prototype,"getCurrentFrameImage",null),Hf([KE(),Gf("design:type",Function),Gf("design:paramtypes",[Object]),Gf("design:returntype",jf)],VT.prototype,"setBitrateLimit",null),Hf([KE(),Gf("design:type",Function),Gf("design:paramtypes",[String]),Gf("design:returntype",jf)],VT.prototype,"setOptimizationMode",null),Hf([KE(),Gf("design:type",Function),Gf("design:paramtypes",[Object]),Gf("design:returntype",void 0)],VT.prototype,"setScalabiltyMode",null),Hf([KE(),Gf("design:type",Function),Gf("design:paramtypes",[]),Gf("design:returntype",void 0)],VT.prototype,"updateMediaStreamTrackResolution",null),Hf([r.apiInvoke({argsMap:(e,t)=>[e.getTrackId(),t.name]}),Gf("design:type",Function),Gf("design:paramtypes",[Object]),Gf("design:returntype",Object)],VT.prototype,"pipe",null),Hf([r.apiInvoke({argsMap:e=>[e.getTrackId()]}),Gf("design:type",Function),Gf("design:paramtypes",[]),Gf("design:returntype",void 0)],VT.prototype,"unpipe",null),Hf([r.apiInvoke({argsMap:e=>[e.getTrackId()]}),Gf("design:type",Function),Gf("design:paramtypes",[]),Gf("design:returntype",void 0)],VT.prototype,"close",null),Hf([r.apiInvoke({argsMap:(e,t,r)=>[e.getTrackId(),t.label,r]}),Gf("design:type",Function),Gf("design:paramtypes",[MediaStreamTrack,Boolean]),Gf("design:returntype",jf)],VT.prototype,"replaceTrack",null);class xT extends VT{get __className__(){return"CameraVideoTrack"}constructor(i,o,n,a,s,c){super(i,Fi(o.encoderConfig),a,s,c),this._config=void 0,this._originalConstraints=void 0,this._constraints=void 0,this._enabled=!0,this._deviceName="default",this.tryResumeVideoForIOS15_16WeChat=async()=>{(t.isIOS15()||t.isIOS16())&&!t.isAboveIOS15_2()&&t.isWechatBrowser()&&this._enabled&&!this._isClosed&&(r.logger.debug("[".concat(this.getTrackId(),"] try capture camera media device for interrupted iOS 15 device on WeChat.")),await this.renewMediaStreamTrack())},this._config=o,this._originalConstraints=n,this._constraints=n,this._deviceName=i.label,this._encoderConfig=Fi(this._config.encoderConfig),Yf.on(e.AUDIO_CONTEXT_EVENT.IOS_15_16_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),Yf.on(e.AUDIO_CONTEXT_EVENT.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(r.logger.info("[".concat(this.getTrackId(),"] set device to ").concat(e)),this._enabled)try{const t=await LE.getDeviceById(e),i={};i.video=LT({},this._constraints),i.video.deviceId={exact:e},i.video.facingMode=void 0,this._originMediaStreamTrack.stop();let o=null;try{o=await NE(i,this.getTrackId())}catch(e){throw r.logger.error("[".concat(this.getTrackId(),"] setDevice failed"),e.toString()),o=await NE({video:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(o.getVideoTracks()[0],!1),e}await this._updateOriginMediaStreamTrack(o.getVideoTracks()[0],!1),this.updateMediaStreamTrackResolution(),this._deviceName=t.label,this._config.cameraId=e,this._constraints.deviceId={exact:e}}catch(e){throw r.logger.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}else try{const t=await LE.getDeviceById(e);this._deviceName=t.label,this._config.cameraId=e,this._constraints.deviceId={exact:e}}catch(e){throw r.logger.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}r.logger.info("[".concat(this.getTrackId(),"] setDevice success"))}async _setDeviceByFacingModel(e){r.logger.info("[".concat(this.getTrackId(),"] set facingMode ").concat(e));const t={video:LT(LT({},this._constraints),{},{deviceId:void 0,facingMode:{exact:e}})};if(this._enabled){this._originMediaStreamTrack.stop();let e=null;try{e=await NE(t,this.getTrackId())}catch(t){throw r.logger.error("[".concat(this.getTrackId(),"] setDeviceByFacingModel failed"),t.toString()),e=await NE({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=LT({},t.video),r.logger.info("[".concat(this.getTrackId(),"] setDeviceByFacingModel success"))}async setEnabled(i,o){if(!o){if(i===this._enabled)return;this.stateCheck("enabled",i)}if(r.logger.info("[".concat(this.getTrackId(),"] start setEnabled"),i),i){try{if(this.isExternalTrack)this._originMediaStreamTrack.enabled=!0;else{const e=await NE({video:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!1)}await t.emitAsPromiseNoResponse(this,e.TrackInternalEvent.NEED_ENABLE_TRACK,this)}catch(e){throw r.logger.error("[".concat(this.getTrackId(),"] setEnabled true error"),e.toString()),e}this.updateMediaStreamTrackResolution(),r.logger.info("[".concat(this.getTrackId(),"] setEnabled to true success")),o||(this._enabled=!0)}else{this.isExternalTrack?this._originMediaStreamTrack.enabled=!1:(this._originMediaStreamTrack.onended=null,this._originMediaStreamTrack.stop()),o||(this._enabled=!1);try{await t.emitAsPromiseNoResponse(this,e.TrackInternalEvent.NEED_DISABLE_TRACK,this)}catch(e){throw r.logger.error("[".concat(this.getTrackId(),"] setEnabled to false error"),e.toString()),e}r.logger.info("[".concat(this.getTrackId(),"] setEnabled to false success"))}}async setEncoderConfiguration(i,o){if(!this._enabled)throw new t.AgoraRTCError(t.AgoraRTCErrorCode.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");i=Fi(i),this._forceBitrateLimit&&(i.bitrateMax=this._forceBitrateLimit.max_bitrate?this._forceBitrateLimit.max_bitrate:i.bitrateMax,i.bitrateMin=this._forceBitrateLimit.min_bitrate?this._forceBitrateLimit.min_bitrate:i.bitrateMin);const n=t.jsonClone(this._config);n.encoderConfig=i;const a=ET(n);(t.isSafari()||t.isIOS()||t.isIpadOS())&&(a.deviceId=void 0),r.logger.debug("[".concat(this.getTrackId(),"] setEncoderConfiguration applyConstraints"),JSON.stringify(i),JSON.stringify(a));try{await this._originMediaStreamTrack.applyConstraints(a),this.updateMediaStreamTrackResolution()}catch(e){const i=new t.AgoraRTCError(t.AgoraRTCErrorCode.UNEXPECTED_ERROR,e.toString());throw r.logger.error("[".concat(this.getTrackId(),"] applyConstraints error"),i.toString()),i}this._config=n,this._constraints=a,this._originalConstraints=a,this._encoderConfig=i,-1===this._hints.indexOf(e.TrackHint.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await t.emitAsPromiseNoResponse(this,e.TrackInternalEvent.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(r.logger)}}_getDefaultPlayerConfig(){return{mirror:!0,fit:"cover"}}onTrackEnded(){if((t.isIOS()||t.isIpadOS())&&this._enabled&&!this._isClosed&&Yf.duringInterruption){const t=async()=>{Yf.off(e.AUDIO_CONTEXT_EVENT.IOS_INTERRUPTION_END,t),this._enabled&&!this._isClosed&&(r.logger.debug("[".concat(this.getTrackId(),"] try capture camera media device for interrupted iOS device.")),await this.setEnabled(!1),await this.setEnabled(!0))};Yf.on(e.AUDIO_CONTEXT_EVENT.IOS_INTERRUPTION_END,t)}else r.logger.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(e.LocalTrackEvents.TRACK_ENDED)}async renewMediaStreamTrack(e){const t=e||this._constraints,r=LE.searchDeviceIdByName(this._deviceName);if(r&&!t.deviceId&&(t.deviceId={exact:r}),this._enabled){const e=await NE({video:t},this.getTrackId());this._constraints=t,await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!0),this.updateMediaStreamTrackResolution()}}close(){super.close(),Yf.off(e.AUDIO_CONTEXT_EVENT.IOS_15_16_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),Yf.off(e.AUDIO_CONTEXT_EVENT.IOS_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat)}clone(e){let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],o=this._encoderConfig;e&&(o=LT(LT({},o),Fi(e))),o=t.safeCloneJson(o);const n=t.getRandomString(8,"track-cam-cloned-"),a=new xT(i?this._mediaStreamTrack.clone():this._mediaStreamTrack,t.safeCloneJson(LT(LT({},this._config),{},{encoderConfig:o})),t.safeCloneJson(this._constraints),t.safeCloneJson(this._scalabilityMode),this._optimizationMode,n);return e&&o&&a.setEncoderConfiguration(o),r.logger.debug("clone track from ".concat(this.getTrackId()," to ").concat(n,", clone ").concat(i)),a}bindProcessorContextEvents(){this.processorContext.on(e.PROCESSOR_CONTEXT_EVENTS.REQUEST_UPDATE_CONSTRAINTS,(async(e,t,r)=>{try{const r=Object.assign({},this._originalConstraints,...e);await this.renewMediaStreamTrack(r),t()}catch(e){r(e)}})),this.processorContext.on(e.PROCESSOR_CONTEXT_EVENTS.REQUEST_CONSTRAINTS,(async e=>{e(this._originMediaStreamTrack.getSettings())}))}}function UT(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}function BT(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?UT(Object(r),!0).forEach((function(t){Bl(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):UT(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function FT(e,t,i,o){i.optimizationMode&&(o&&o.width&&o.height?(i.encoderConfig=BT(BT({},o),{},{bitrateMin:o.bitrateMin,bitrateMax:o.bitrateMax}),"motion"!==i.optimizationMode&&"detail"!==i.optimizationMode||(t.contentHint=i.optimizationMode,t.contentHint===i.optimizationMode?r.logger.debug("[".concat(e,"] set content hint to"),i.optimizationMode):r.logger.debug("[".concat(e,"] set content hint failed")))):r.logger.warning("[".concat(e,"] can not apply optimization mode bitrate config, no encoderConfig")))}function jT(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}function HT(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?jT(Object(r),!0).forEach((function(t){Bl(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):jT(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}Hf([r.apiInvoke({argsMap:(e,t)=>[e.getTrackId(),t]}),KE(),Gf("design:type",Function),Gf("design:paramtypes",[Object]),Gf("design:returntype",jf)],xT.prototype,"setDevice",null),Hf([t.atom("CameraVideoTrack","_enabledMutex"),r.apiInvoke({argsMap:(e,t)=>[e.getTrackId(),t]}),KE(),Gf("design:type",Function),Gf("design:paramtypes",[Boolean,Boolean]),Gf("design:returntype",jf)],xT.prototype,"setEnabled",null),Hf([r.apiInvoke({argsMap:(e,t)=>[e.getTrackId(),t]}),KE(),Gf("design:type",Function),Gf("design:paramtypes",[Object,Boolean]),Gf("design:returntype",jf)],xT.prototype,"setEncoderConfiguration",null),Hf([r.apiInvoke({argsMap:e=>[e.getTrackId()]}),Gf("design:type",Function),Gf("design:paramtypes",[]),Gf("design:returntype",void 0)],xT.prototype,"close",null);class GT extends Wf{getUserId(){return this._userId}constructor(e,r,i,o){super(e,"track-".concat(e.kind,"-").concat(r,"-").concat(o.clientId,"_").concat(t.getRandomString(5,""))),this._userId=void 0,this._uintId=void 0,this._isDestroyed=!1,this.store=void 0,this.processor=void 0,this._userId=r,this._uintId=i,this.store=o}_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,r.logger.info("[".concat(this.getTrackId(),"] is destroyed")),this.stop(),super.close()}getProcessorStats(){return this.processorContext.gatherStats()}getProcessorUsage(){return this.processorContext.gatherUsage()}}class WT extends GT{get isPlaying(){return!(!this._player||this._player.videoElementStatus!==e.MediaElementStatus.PLAYING)}get __className__(){return"RemoteVideoTrack"}constructor(e,t,r,i){super(e,t,r,i),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 iT(this.getTrackId(),"remote"),this.processorDestination=new rT(this.processorContext),this.bindProcessorDestinationEvents()}getStats(){t.runOnce((()=>{r.logger.warning("[deprecated] RemoteVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteVideoStats instead")}),"remoteVideoTrackGetStatsWarning");return t.emitAsInvokerNoResponse(this,e.TrackInternalEvent.GET_STATS)||HT({},co)}play(i){let o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("string"==typeof i){const e=document.getElementById(i);e?i=e:(r.logger.warning("[".concat(this.getTrackId(),'] can not find "#').concat(i,'" element, use document.body')),i=document.body)}r.logger.debug("[".concat(this.getTrackId(),"] start video playback in ").concat(i instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement"),JSON.stringify(o));const n=HT(HT({fit:"cover"},o),{},{trackId:this.getTrackId(),element:i});this._player?this._player.updateConfig(n):(i instanceof HTMLVideoElement?this._player=new OT(n):this._player=new NT(n),this._player.updateVideoTrack(this._mediaStreamTrack),this._player.onFirstVideoFrameDecoded=()=>{this.store.subscribe(this.getUserId(),"video",void 0,void 0,Date.now()),this.safeEmit(e.RemoteTrackEvents.FIRST_FRAME_DECODED)}),this._player.play(this.store.sessionId||void 0),this._videoVisibleTimer&&window.clearInterval(this._videoVisibleTimer),this._clearPreviousVideoVisibleStatus(),this._videoVisibleTimer=window.setInterval((()=>{try{const t=this.getVideoElementVisibleStatus();this.safeEmit(e.RemoteTrackEvents.VIDEO_ELEMENT_VISIBLE_STATUS,t)}catch(e){}}),t.getParameter("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,r.logger.debug("[".concat(this.getTrackId(),"] stop video playback")))}getCurrentFrameData(){return this._player?this._player.getCurrentFrame():new ImageData(2,2)}updateMediaStreamTrackResolution(){wT(this._originMediaStreamTrack).then((e=>{let[t,r]=e;this._videoHeight=r,this._videoWidth=t})).catch(t.noop)}_updatePlayerSource(){r.logger.debug("[".concat(this.getTrackId(),"] update player source track")),this._player&&this._player.updateVideoTrack(this._mediaStreamTrack)}getVideoElementVisibleStatus(){try{var e,i;const o=null==this||null===(e=this._player)||void 0===e?void 0:e.getContainerElement(),n={track:this,element:null==this||null===(i=this._player)||void 0===i?void 0:i.getVideoElement(),slot:null==o?void 0:o.parentElement},{element:a,slot:s}=n;if(this.isPlaying&&a instanceof HTMLVideoElement&&s instanceof HTMLElement){const e=t.elementVisibleChecker.checkOneElementVisible(a),i=Object.assign({},e);if(i.visible!==this._previousVideoVisibleStatus){this._previousVideoVisibleStatus=i.visible;const e=r.report.reportApiInvoke(null,{tag:t.AgoraAPITag.TRACER,name:t.AgoraAPIName.REMOTE_VIDEO_TRACK_GET_VIDEO_VISIBLE,options:[this.getTrackId()]});i.visible?e.onSuccess("Video is visible"):e.onSuccess("Invisible because of ".concat(i.reason))}return i}return}catch(e){throw new t.AgoraRTCError(t.AgoraRTCErrorCode.GET_VIDEO_ELEMENT_VISIBLE_ERROR,e.message)}}pipe(e){if(this.processor===e)return e;if(e._source)throw new t.AgoraRTCError(t.AgoraRTCErrorCode.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(e.PROCESSOR_DESTINATION_EVENTS.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(e.PROCESSOR_DESTINATION_EVENTS.ON_TRACK)}_destroy(){super._destroy(),this.unbindProcessorDestinationEvents()}}Hf([r.apiInvoke({argsMap:(e,t,r)=>[e.getTrackId(),"string"==typeof t?t:t instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement",r]}),Gf("design:type",Function),Gf("design:paramtypes",[Object,Object]),Gf("design:returntype",void 0)],WT.prototype,"play",null),Hf([r.apiInvoke({argsMap:e=>[e.getTrackId()]}),Gf("design:type",Function),Gf("design:paramtypes",[]),Gf("design:returntype",void 0)],WT.prototype,"stop",null),Hf([r.apiInvoke({argsMap:(e,t)=>[e.getTrackId(),t.name]}),Gf("design:type",Function),Gf("design:paramtypes",[Object]),Gf("design:returntype",Object)],WT.prototype,"pipe",null),Hf([r.apiInvoke({argsMap:e=>[e.getTrackId()]}),Gf("design:type",Function),Gf("design:paramtypes",[]),Gf("design:returntype",void 0)],WT.prototype,"unpipe",null);class KT extends GT{get isPlaying(){return this._useAudioElement?WE.isPlaying(this.getTrackId()):this._source.isPlayed}get __className__(){return"RemoteAudioTrack"}constructor(r,i,o,n){super(r,i,o,n),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,t.getParameter("DISABLE_WEBAUDIO")?(this._source=new aT,this._bypassWebAudio=!0,this._useAudioElement=!0):(this._source=new bE(r,!0),t.getParameter("REMOTE_AUDIO_TRACK_USES_WEB_AUDIO")&&(this._useAudioElement=!1)),this._source.once(e.AudioSourceEvents.RECEIVE_TRACK_BUFFER,(()=>{this.safeEmit(e.RemoteTrackEvents.FIRST_FRAME_DECODED)})),this.processorContext=new nT(this._source.context,this.getTrackId(),"remote"),this.processorDestination=new oT(this.processorContext),this.bindProcessorDestinationEvents(),this._source.on(e.AudioSourceEvents.UPDATE_SOURCE,(()=>{this.processor&&this.processor.updateInput({node:this._source.processSourceNode,context:this.processorContext})}))}setAudioFrameCallback(t){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:4096;if(!t)return this._source.removeAllListeners(e.AudioSourceEvents.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(r),this._source.removeAllListeners(e.AudioSourceEvents.ON_AUDIO_BUFFER),this._source.on(e.AudioSourceEvents.ON_AUDIO_BUFFER,(e=>t(e)))}setVolume(e){this._volume=e,this._useAudioElement?WE.setVolume(this.getTrackId(),e):this._source.setVolume(e/100)}async setPlaybackDevice(e){if(!this._useAudioElement)throw new t.AgoraRTCError(t.AgoraRTCErrorCode.NOT_SUPPORTED,"your browser does not support setting the audio output device");await WE.setSinkID(this.getTrackId(),e)}getVolumeLevel(){return this._source.getAccurateVolumeLevel()}getStats(){t.runOnce((()=>{r.logger.warning("[deprecated] RemoteAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteAudioStats instead")}),"remoteAudioTrackGetStatsWarning");return t.emitAsInvokerNoResponse(this,e.TrackInternalEvent.GET_STATS)||HT({},so)}play(){r.logger.debug("[".concat(this.getTrackId(),"] start audio playback")),this._played=!0,this._useAudioElement?(r.logger.debug("[".concat(this.getTrackId(),"] use audio element to play")),WE.play(this._mediaStreamTrack,this.getTrackId(),this._volume,this.store.sessionId||void 0)):this._source.play()}stop(){r.logger.debug("[".concat(this.getTrackId(),"] stop audio playback")),this._played=!1,this._useAudioElement?WE.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];r.logger.debug("[".concat(this.getTrackId(),"] update player source track")),e&&this._source.updateTrack(this._mediaStreamTrack),this._useAudioElement&&WE.updateTrack(this.getTrackId(),this._mediaStreamTrack)}pipe(e){if(this._bypassWebAudio)throw new t.AgoraRTCError(t.AgoraRTCErrorCode.NOT_SUPPORTED,"can not pipe extension when WebAudio disabled");if(this.processor===e)return e;if(e._source)throw new t.AgoraRTCError(t.AgoraRTCErrorCode.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.AgoraRTCError(t.AgoraRTCErrorCode.NOT_SUPPORTED,"can not unpipe extension when WebAudio disabled");if(!this.processor)return;const r=this.processor;null===(e=this._source.processSourceNode)||void 0===e||e.disconnect(),this.processor._source=!1,this.processor=void 0,r.reset()}bindProcessorDestinationEvents(){this.processorDestination.on(e.PROCESSOR_DESTINATION_EVENTS.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(e.PROCESSOR_DESTINATION_EVENTS.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(e.PROCESSOR_DESTINATION_EVENTS.ON_TRACK),this.processorDestination.removeAllListeners(e.PROCESSOR_DESTINATION_EVENTS.ON_NODE)}}var zT;Hf([r.apiInvoke({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),Gf("design:type",Function),Gf("design:paramtypes",[Number]),Gf("design:returntype",void 0)],KT.prototype,"setVolume",null),Hf([r.apiInvoke({argsMap:(e,t)=>[e.getTrackId(),t]}),Gf("design:type",Function),Gf("design:paramtypes",[String]),Gf("design:returntype",jf)],KT.prototype,"setPlaybackDevice",null),Hf([r.apiInvoke({argsMap:e=>[e.getTrackId()]}),Gf("design:type",Function),Gf("design:paramtypes",[]),Gf("design:returntype",void 0)],KT.prototype,"play",null),Hf([r.apiInvoke({argsMap:e=>[e.getTrackId()]}),Gf("design:type",Function),Gf("design:paramtypes",[]),Gf("design:returntype",void 0)],KT.prototype,"stop",null),Hf([r.apiInvoke({argsMap:(e,t)=>[e.getTrackId(),t.name]}),Gf("design:type",Function),Gf("design:paramtypes",[Object]),Gf("design:returntype",Object)],KT.prototype,"pipe",null),Hf([r.apiInvoke({argsMap:e=>[e.getTrackId()]}),Gf("design:type",Function),Gf("design:paramtypes",[]),Gf("design:returntype",void 0)],KT.prototype,"unpipe",null),function(e){e[e.ONE_BYTE=0]="ONE_BYTE",e[e.TWO_BYTE=1]="TWO_BYTE"}(zT||(zT={}));class XT{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 r=new Uint8Array(4);r.set([1,0,0,0]);const i={id:0,length:4,data:r.buffer},o={profile:this.isUseOneByte?0:1,length:this.isUseOneByte?5:6,datas:[i]};t.commonPacketHeader.extension=1,t.extension=o,t.payload=this.compress(e),t.commonPacketHeader.length=8+(t.extension.length+2)+t.payload.byteLength}else t.commonPacketHeader.length=8+t.payload.byteLength;const r=new ArrayBuffer(t.commonPacketHeader.length),i=new Uint8Array(r),o=new DataView(r);let n=0;if(o.setUint16(n,t.commonPacketHeader.extension<<15|t.commonPacketHeader.reserved<<14|t.commonPacketHeader.length,!0),n+=2,o.setUint32(n,t.commonPacketHeader.sequence,!0),n+=4,o.setUint16(n,t.commonStreamHeader,!0),n+=2,t.extension){const e=this.serializeExtension(t.extension);i.set(new Uint8Array(e),n),n+=e.byteLength}if(i.set(new Uint8Array(t.payload),n),n+=t.payload.byteLength,n!==t.commonPacketHeader.length)throw Error("serialize error!");return r}deserialize(e){if(e.byteLength<4)return new ArrayBuffer(0);const t=new DataView(e);let r=0;const i=t.getUint16(r,!0);r+=2;const o=(32768&i)>>15;t.getUint16(r+2,!0),t.getUint16(r,!0);let n,a;if(r+=4,t.getUint16(r,!0),r+=2,o){a=this.deserializeExtension(e.slice(r)),r+=2+a.length,n=e.slice(r);let t=!1;if(a.datas.length>0){const e=a.datas.find((e=>0===e.id));if(e){t=1==(1&new DataView(e.data).getUint32(0,!0))}}n=t?this.decompress(n):n}else n=e.slice(8);return n}serializeExtension(e){const{profile:t,length:r,datas:i}=e,o=new ArrayBuffer(r+2),n=new Uint8Array(o),a=new DataView(o);let s=0;if(a.setUint8(s++,t),a.setUint8(s++,r),i.forEach((e=>{t?(a.setUint8(s++,e.id),a.setUint8(s++,e.length),n.set(new Uint8Array(e.data),s),s+=e.data.byteLength):(a.setUint8(s++,e.id|e.length<<4),n.set(new Uint8Array(e.data),s),s+=e.data.byteLength)})),s!==r+2)throw Error("serialize extension error, is ".concat(s,"!==").concat(r+2));return o}deserializeExtension(e){const t=new DataView(e);let r=0;const i=t.getUint8(r);r++;const o=t.getUint8(r);r++;const n=i===zT.TWO_BYTE,a=[],s=new DataView(e,2);let c=0;for(;c<o;){let e=0,t=0,r=new ArrayBuffer(0);n?(e=s.getUint8(c),c++,t=s.getUint8(c),c++):(e=15&s.getUint8(c),t=s.getUint8(c)>>4,c++),t>0&&(r=s.buffer.slice(c+2,c+2+t),c+=r.byteLength),a.push({id:e,length:t,data:r})}if(c!==o)throw Error("parse error");return{profile:i,length:o,datas:a}}decompress(e){return n.inflate(new Uint8Array(e))}compress(e){return n.deflate(new Uint8Array(e))}}class qT extends t.EventEmitter{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 XT}get id(){return this._config.id}get ordered(){return this._config.ordered}get maxRetransmits(){return t.getParameter("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 jf(((e,r)=>{if(this._originDataChannel){"open"===this._originDataChannel.readyState&&e();const i=setTimeout((()=>{var e;r(new t.AgoraRTCError(t.AgoraRTCErrorCode.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.AgoraRTCError(t.AgoraRTCErrorCode.DATACHANNEL_CONNECTION_TIMEOUT)}}else r(new t.AgoraRTCError(t.AgoraRTCErrorCode.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(t){this._unbindDataChannelEvents(t),[e.DataChannelEvents.OPEN,e.DataChannelEvents.CLOSE,e.DataChannelEvents.ERROR].forEach((e=>{const r=()=>{this.emit(e)};this._datachannelEventMap.set(e,r),t.addEventListener(e,r)}))}_unbindDataChannelEvents(e){Array.from(this._datachannelEventMap.entries()).forEach((t=>{let[r,i]=t;e.removeEventListener(r,i)})),this._datachannelEventMap.clear()}}Object.defineProperty(e,"isElectron",{enumerable:!0,get:function(){return t.isElectron}}),e.AUDIO_ENCODER_CONFIG_SETTINGS=Gi,e.AudioProcessorContext=nT,e.AudioProcessorDestination=oT,e.BufferSourceAudioTrack=mT,e.CameraVideoTrack=xT,e.DEFAULT_LOCAL_AUDIO_TRACK_STATS=no,e.DEFAULT_LOCAL_VIDEO_TRACK_STATS=ao,e.DEFAULT_NETWORK_QUALITY_STATS={uplinkNetworkQuality:0,downlinkNetworkQuality:0},e.DEFAULT_REMOTE_AUDIO_TRACK_STATS=so,e.DEFAULT_REMOTE_VIDEO_TRACK_STATS=co,e.DataChannel=qT,e.DeviceManager=ME,e.LocalAudioTrack=pT,e.LocalDataChannel=class extends qT{send(e){if(this._originDataChannel){let t=e;t=this._dataStreamPacketHandler.serialize(e);const r=new Uint8Array(this._dataStreamPacketHeader.byteLength+t.byteLength);r.set(new Uint8Array(this._dataStreamPacketHeader),0),r.set(new Uint8Array(t),this._dataStreamPacketHeader.byteLength),this._originDataChannel.send(r.buffer)}}},e.LocalTrack=Kf,e.LocalVideoTrack=VT,e.MediaElementNumStatus={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},e.MicrophoneAudioTrack=gT,e.MixingAudioTrack=fT,e.RemoteAudioTrack=KT,e.RemoteDataChannel=class extends qT{constructor(t){super(t),this._messageListener=void 0,this._messageListener=t=>{if(t.data.byteLength<this._dataStreamPacketHeader.byteLength)throw Error("invalid byteLength: the byte length must exceed "+this._dataStreamPacketHeader.byteLength);const r=t.data.slice(0,this._dataStreamPacketHeader.byteLength);if(new DataView(r).getUint8(3)!==this.id)return;let i=t.data.slice(this._dataStreamPacketHeader.byteLength);i=this._dataStreamPacketHandler.deserialize(i),this.emit(e.DataChannelEvents.MESSAGE,i)}}_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)}},e.RemoteTrack=GT,e.RemoteVideoTrack=WT,e.SAFARI_GLOBAL_GUM_LOCK=RE,e.SUPPORT_SCREEN_ENCODER_CONFIG_LIST=Ui,e.SUPPORT_SVC_CONFIG_LIST=Bi,e.SUPPORT_VIDEO_ENCODER_CONFIG_LIST=xi,e.Track=Wf,e.VideoProcessorContext=iT,e.VideoProcessorDestination=rT,e.__TRACK_LIST__=Ki,e.addTrack=zi,e.audioContextState=Yf,e.audioElementPlayCenter=WE,e.audioTimerLoop=function(e,r){let i=!1;const o=1/r;if(t.getParameter("DISABLE_WEBAUDIO")){const t=window.setInterval((()=>{i?window.clearInterval(t):e(performance.now()/1e3)}),1e3*o)}else{const t=Zf();let r=t.createGain();r.gain.value=0,r.connect(t.destination);const n=()=>{if(i)return void(r=null);const a=t.createOscillator();a.onended=n,a.connect(r),a.start(0),a.stop(t.currentTime+o),e(t.currentTime)};n()}return()=>{i=!0}},e.autoPlayGestureEventEmitter=UE,e.blob2Uint8Array=AT,e.checkMediaStreamTrackResolution=wT,e.checkTrackState=KE,e.createBufferSourceAudioTrack=async function(e){var o;const{cacheOnlineFile:n,encoderConfig:a}=e;let{source:s}=e;const c={source:s instanceof AudioBuffer?"AudioBuffer":s instanceof File?null!==(o=File.name)&&void 0!==o?o:"File":s,cacheOnlineFile:n,encoderConfig:a},d=r.report.reportApiInvoke(null,{tag:t.AgoraAPITag.TRACER,name:t.AgoraAPIName.CREATE_BUFFER_AUDIO_TRACK,options:[c]});if(t.getParameter("DISABLE_WEBAUDIO"))throw new t.AgoraRTCError(t.AgoraRTCErrorCode.NOT_SUPPORTED,"can not create BufferSourceAudioTrack when WebAudio disabled");const u=t.getRandomString(8,"track-buf-");r.logger.info("start create buffer source audio track with config",JSON.stringify(c),"trackId",u);const l=s;if(!(s instanceof AudioBuffer))try{s=await async function(e,o){let n=null;if("string"==typeof e){const o=yT.get(e);if(o)return r.logger.debug("use cached audio resource: ",e),o;try{n=(await t.retryable((()=>i.get(e,{responseType:"arraybuffer"})),void 0,void 0,{maxRetryCount:3})).data}catch(e){throw new t.AgoraRTCError(t.AgoraRTCErrorCode.FETCH_AUDIO_FILE_FAILED,e.toString())}}else{const r=new jf(((r,i)=>{const o=new FileReader;o.onload=e=>{e.target?r(e.target.result):i(new t.AgoraRTCError(t.AgoraRTCErrorCode.READ_LOCAL_AUDIO_FILE_ERROR))},o.onerror=()=>{i(new t.AgoraRTCError(t.AgoraRTCErrorCode.READ_LOCAL_AUDIO_FILE_ERROR))},o.readAsArrayBuffer(e)}));n=await r}const a=await tE(n);return"string"==typeof e&&o&&yT.set(e,a),a}(s,n)}catch(e){return d.onError(e),e.throw(r.logger)}const h=new _T(s),p=new mT(l,h,a?Wi(a):{},u);return r.logger.info("create buffer source audio track success, trackId:",u),d.onSuccess(p.getTrackId()),p},e.createCameraVideoTrack=async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const i=r.report.reportApiInvoke(null,{tag:t.AgoraAPITag.TRACER,name:t.AgoraAPIName.CREATE_CAM_VIDEO_TRACK,options:[BT({},e)]}),o=ET(e),n=t.getRandomString(8,"track-cam-");let a=null;r.logger.info("start create camera video track with config",JSON.stringify(e),"trackId",n);try{a=(await NE({video:o},n)).getVideoTracks()[0]||null}catch(e){throw i.onError(e),e}if(!a){const e=new t.AgoraRTCError(t.AgoraRTCErrorCode.UNEXPECTED_ERROR,"can not find track in media stream");return i.onError(e),e.throw(r.logger)}e.optimizationMode&&FT(n,a,e,Fi(e.encoderConfig));const s=new xT(a,e,o,e.scalabiltyMode?Hi(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,n);return i.onSuccess(s.getTrackId()),r.logger.info("create camera video success, trackId:",n),s},e.createCustomAudioTrack=function(e){const i=r.report.reportApiInvoke(null,{tag:t.AgoraAPITag.TRACER,name:t.AgoraAPIName.CREATE_CUSTOM_AUDIO_TRACK,options:[e]}),o=new pT(e.mediaStreamTrack,e.encoderConfig?Wi(e.encoderConfig):{},t.getRandomString(8,"track-cus-"),!1,!0);return r.logger.info("create custom audio track success with config",e,"trackId",o.getTrackId()),i.onSuccess(o.getTrackId()),o},e.createCustomVideoTrack=function(i){const o=r.report.reportApiInvoke(null,{tag:t.AgoraAPITag.TRACER,name:t.AgoraAPIName.CREATE_CUSTOM_VIDEO_TRACK,options:[i]}),n=new VT(i.mediaStreamTrack,{width:i.width,height:i.height,frameRate:i.frameRate,bitrateMax:i.bitrateMax,bitrateMin:i.bitrateMin},i.scalabiltyMode?Hi(i.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},i.optimizationMode,t.getRandomString(8,"track-cus-"),[e.TrackHint.CUSTOM_TRACK]);return o.onSuccess(n.getTrackId()),r.logger.info("create custom video track success with config",i,"trackId",n.getTrackId()),n},e.createMicrophoneAndCameraTracks=async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const o=r.report.reportApiInvoke(null,{tag:t.AgoraAPITag.TRACER,name:t.AgoraAPIName.CREATE_MIC_AND_CAM_TRACKS,options:[e,i]}),n=ET(i),a=vT(e),s=t.getRandomString(8,"track-mic-"),c=t.getRandomString(8,"track-cam-");let d=null,u=null;r.logger.info("start create camera video track(".concat(c,") and microphone audio track(").concat(s,") with config, audio: ").concat(JSON.stringify(e),", video: ").concat(JSON.stringify(i)));try{const e=await NE({audio:a,video:n},"".concat(s,"-").concat(c));d=e.getAudioTracks()[0],u=e.getVideoTracks()[0]}catch(e){throw o.onError(e),e}if(!d||!u){const e=new t.AgoraRTCError(t.AgoraRTCErrorCode.UNEXPECTED_ERROR,"can not find tracks in media stream");return o.onError(e),e.throw(r.logger)}i.optimizationMode&&FT(c,u,i,Fi(i.encoderConfig));const l=new gT(d,e,a,s),h=new xT(u,i,n,i.scalabiltyMode?Hi(i.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},i.optimizationMode,c);return o.onSuccess([l.getTrackId(),h.getTrackId()]),r.logger.info("create camera video track(".concat(c,") and microphone audio track(").concat(s,") success")),[l,h]},e.createMicrophoneAudioTrack=async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const i=r.report.reportApiInvoke(null,{tag:t.AgoraAPITag.TRACER,name:t.AgoraAPIName.CREATE_MIC_AUDIO_TRACK,options:[e]}),o=vT(e),n=t.getRandomString(8,"track-mic-");let a=null;r.logger.info("start create microphone audio track with config",JSON.stringify(e),"trackId",n);try{a=(await NE({audio:o},n)).getAudioTracks()[0]||null}catch(e){throw i.onError(e),e}if(!a){const e=new t.AgoraRTCError(t.AgoraRTCErrorCode.UNEXPECTED_ERROR,"can not find track in media stream");return i.onError(e),e.throw(r.logger)}const s=new gT(a,e,o,n);return i.onSuccess(s.getTrackId()),r.logger.info("create microphone audio track success, trackId:",n),s},e.createMixingAudioTrack=function(e){const t=new fT;return e.forEach((e=>t.addAudioTrack(e))),t},e.createScreenVideoTrack=async function(){let i=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"disable";const n=r.report.reportApiInvoke(null,{tag:t.AgoraAPITag.TRACER,name:t.AgoraAPIName.CREATE_SCREEN_VIDEO_TRACK,options:[BT({},i),o]});i.encoderConfig?"string"==typeof i.encoderConfig||i.encoderConfig.width&&i.encoderConfig.height||(i.encoderConfig.width={max:1920},i.encoderConfig.height={max:1080}):i.encoderConfig="1080p_2";const a=TT(i),s=t.getRandomString(8,"track-scr-v-");let c=null,d=null;const u=aE();if(!u.supportShareAudio&&"enable"===o){const e=new t.AgoraRTCError(t.AgoraRTCErrorCode.NOT_SUPPORTED,"your browser or platform is not support share-screen with audio");return n.onError(e),e.throw(r.logger)}r.logger.info("start create screen video track with config",i,"withAudio",o,"trackId",s);try{const e=await NE({screen:a,screenAudio:"auto"===o?u.supportShareAudio:"enable"===o},s);c=e.getVideoTracks()[0]||null,d=e.getAudioTracks()[0]||null}catch(e){throw n.onError(e),e}if(!c){const e=new t.AgoraRTCError(t.AgoraRTCErrorCode.UNEXPECTED_ERROR,"can not find track in media stream");return n.onError(e),e.throw(r.logger)}if(!d&&"enable"===o){c&&c.stop();const e=new t.AgoraRTCError(t.AgoraRTCErrorCode.SHARE_AUDIO_NOT_ALLOWED);return n.onError(e),e.throw(r.logger)}if(i.optimizationMode||(i.optimizationMode="detail"),i.optimizationMode){FT(s,c,i,i.encoderConfig&&ji(i.encoderConfig)||void 0),i.encoderConfig&&"string"!=typeof i.encoderConfig&&(i.encoderConfig.bitrateMin=i.encoderConfig.bitrateMax)}const l=new VT(c,i.encoderConfig?ji(i.encoderConfig):{},i.scalabiltyMode?Hi(i.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},i.optimizationMode,s,[e.TrackHint.SCREEN_TRACK]);if(!d)return n.onSuccess(l.getTrackId()),r.logger.info("create screen video track success","video:",l.getTrackId()),l;const h=new pT(d,void 0,t.getRandomString(8,"track-scr-a-"),!1,!0);return n.onSuccess([l.getTrackId(),h.getTrackId()]),r.logger.info("create screen video track success","video:",l.getTrackId(),"audio:",h.getTrackId()),[l,h]},e.decodeAudioData=tE,e.deviceManager=LE,e.emptyImage2TypedArray=ST,e.frameData2CryptoBuffer=async(e,r,i)=>await(async(e,r,i)=>{const o=""+r+i,n=t.hexToBytes(t.md5(o)).slice(0,16),a=n.slice(0,12),s=await window.crypto.subtle.importKey("raw",n,"AES-GCM",!0,["encrypt"]);return new Uint8Array(await window.crypto.subtle.encrypt({name:"AES-GCM",iv:a},s,e))})(e.buffer,r,i),e.getAudioContext=Zf,e.getAudioEncoderConfiguration=Wi,e.getBitrateFromResAndFps=DT,e.getCompatibility=aE,e.getConstraintsFromCameraConfig=ET,e.getConstraintsFromMicrophoneConfig=vT,e.getConstraintsFromScreenConfig=TT,e.getElectronScreenSources=CE,e.getElectronScreenStream=kE,e.getElectronScreenStreamByUserSelect=IE,e.getLocalStream=NE,e.getScalabilityConfiguration=Hi,e.getScreenEncoderConfiguration=ji,e.getSilenceAudioTrack=function(){if(iE)return iE;const e=Zf();if(!e.createMediaStreamDestination)throw new t.AgoraRTCError(t.AgoraRTCErrorCode.NOT_SUPPORTED,"can not create silence audio track");const r=e.createBufferSource(),i=e.createBuffer(1,44100,44100);r.loop=!0,r.buffer=i;const o=e.createMediaStreamDestination();return r.connect(o),iE=o.stream.getAudioTracks()[0],iE},e.getSilenceSamplesDuration=function(e){const t=e.getChannelData(0);let r=0,i=0;for(let e=0;e<t.length;e+=1)0===t[e]?(r+=1,r>i&&(i=r)):r=0;return i/t.length*e.duration},e.getStaticTrackStream=PT,e.getVideoEncoderConfiguration=Fi,e.handleGetUserMediaError=DE,e.hasAudioContext=$f,e.isAudioEncoderConfiguration=Ji,e.isAudioEncoderConfigurationOrPreset=function(e){return"string"==typeof e?t.checkValidEnum(e,"profile",Object.keys(Gi)):Ji(e),!0},e.isBeautyEffectOptions=function(e){return void 0!==e.smoothnessLevel&&t.checkValidNumber(e.smoothnessLevel,"options.smoothnessLevel",0,1,!1),void 0!==e.lighteningLevel&&t.checkValidNumber(e.lighteningLevel,"options.lighteningLevel",0,1,!1),void 0!==e.rednessLevel&&t.checkValidNumber(e.rednessLevel,"options.rednessLevel",0,1,!1),void 0!==e.lighteningContrastLevel&&t.checkValidEnum(e.lighteningContrastLevel,"options.lighteningContrastLevel",[0,1,2]),!0},e.isLowStreamParameter=function(e){if(!e)throw new t.AgoraRTCError(t.AgoraRTCErrorCode.INVALID_PARAMS);return t.isEmpty(e.width)||t.checkValidConstrainLong(e.width,"streamParameter.width"),t.isEmpty(e.height)||t.checkValidConstrainLong(e.height,"streamParameter.height"),t.isEmpty(e.framerate)||t.checkValidConstrainLong(e.framerate,"streamParameter.framerate"),t.isEmpty(e.bitrate)||t.checkValidNumber(e.bitrate,"streamParameter.bitrate"),!0},e.isScreenSourceType=Yi,e.isVideoEncoderConfiguration=qi,e.isVideoEncoderConfigurationOrPreset=function(e){return"string"==typeof e?t.checkValidEnum(e,"profile",Object.keys(xi)):qi(e),!0},e.polyfillAudioNode=eE,e.removeTrack=Xi,e.requestAutoplayGesture=BE,e.silenceScriptProcessHandler=oE,e.updateAgoraRTCCompatibility=function(){const e=t.getBrowserInfo();nE.getDisplayMedia=function(e){if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)return!0;return!1}(),nE.getStreamFromExtension=e.name===t.BrowserName.CHROME&&Number(e.version)>34,nE.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}(),nE.supportMinBitrate=e.name===t.BrowserName.CHROME||e.name===t.BrowserName.EDGE,nE.supportSetRtpSenderParameters=function(){const e=t.getBrowserInfo();if(!window.RTCRtpSender||!window.RTCRtpSender.prototype.setParameters||!window.RTCRtpSender.prototype.getParameters)return!1;return!!t.isChromeKernel()||(!(!t.isSafari()&&!t.isWkWebview())||e.name===t.BrowserName.FIREFOX&&Number(e.version)>=64)}(),e.name===t.BrowserName.SAFARI&&(Number(e.version)>=14?nE.supportDualStream=!0:nE.supportDualStream=!1),nE.webAudioMediaStreamDest=function(){const e=t.getBrowserInfo();if(e.name===t.BrowserName.SAFARI&&Number(e.version)<12)return!1;return!0}(),nE.supportReplaceTrack=function(){if(!window.RTCRtpSender)return!1;if("function"==typeof RTCRtpSender.prototype.replaceTrack)return!0;return!1}(),nE.supportWebGL="undefined"!=typeof WebGLRenderingContext,nE.supportRequestFrame=!!window.CanvasCaptureMediaStreamTrack,t.isChromeKernel()||(nE.webAudioWithAEC=!0),nE.supportShareAudio=function(){const e=t.getBrowserInfo();if((e.os===t.BrowserOS.WIN_10||e.os===t.BrowserOS.WIN_81||e.os===t.BrowserOS.WIN_7||e.os===t.BrowserOS.LINUX||e.os===t.BrowserOS.MAC_OS)&&e.name===t.BrowserName.CHROME&&Number(e.version)>=74)return!0;return!1}(),nE.supportDataChannel=function(){if(t.isAboveChrome(76)||t.isAboveFirefox(68)||t.isAboveSafari(14))return!0;return!1}(),nE.supportPCSetConfiguration=function(){const e=window.RTCPeerConnection;return!t.isFirefox()&&!!e&&e.prototype.setConfiguration instanceof Function}(),nE.supportWebRTCEncodedTransform=function(){const e=t.getBrowserInfo();return"Chrome"===e.name&&Number(e.version)>=86}(),nE.supportWebRTCInsertableStream=function(){const e=t.getBrowserInfo();return(e.name===t.BrowserName.CHROME||e.name===t.BrowserName.EDGE)&&Number(e.version)>=94&&"MediaStreamTrackGenerator"in window&&"MediaStreamTrackProcessor"in window}(),t.nextTick((()=>{nE.supportDualStreamEncoding=function(){const e=t.getBrowserInfo();if(t.getParameter("DISABLE_WEBAUDIO"))return!0;return"Safari"===e.name&&Number(e.version)>=14||!!("Chrome"===e.name&&/Windows/i.test(e.os||"")&&Number(e.version)>=100&&t.getParameter("CHROME_DUAL_STREAM_USE_ENCODING"))}(),r.logger.info("browser compatibility",JSON.stringify(nE),JSON.stringify(e))}))},e.visibilityWatcher=kT}));
5
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@agora-js/shared"),require("@agora-js/report"),require("axios"),require("webrtc-adapter"),require("pako")):"function"==typeof define&&define.amd?define(["exports","@agora-js/shared","@agora-js/report","axios","webrtc-adapter","pako"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).AgoraRTCMedia={},e.shared$8,e.report,e.Axios,null,e.pako)}(this,(function(e,t,r,i,o,n){"use strict";var a;e.AUDIO_CONTEXT_EVENT=void 0,(a=e.AUDIO_CONTEXT_EVENT||(e.AUDIO_CONTEXT_EVENT={})).IOS_15_16_INTERRUPTION_START="ios15_16-interruption-start",a.IOS_15_16_INTERRUPTION_END="ios15_16-interruption-end",a.IOS_INTERRUPTION_START="ios-interruption-start",a.IOS_INTERRUPTION_END="ios-interruption-end",a.STATE_CHANGE="state-change";var s="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function c(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var d=function(e){try{return!!e()}catch(e){return!0}},u=!d((function(){var e=function(){}.bind();return"function"!=typeof e||e.hasOwnProperty("prototype")})),l=u,h=Function.prototype,p=h.call,g=l&&h.bind.bind(p,p),m=l?g:function(e){return function(){return p.apply(e,arguments)}},f=m({}.isPrototypeOf),E=function(e){return e&&e.Math==Math&&e},T=E("object"==typeof globalThis&&globalThis)||E("object"==typeof window&&window)||E("object"==typeof self&&self)||E("object"==typeof s&&s)||function(){return this}()||s||Function("return this")(),v=u,_=Function.prototype,y=_.apply,S=_.call,A="object"==typeof Reflect&&Reflect.apply||(v?S.bind(y):function(){return S.apply(y,arguments)}),b=m,I=b({}.toString),k=b("".slice),C=function(e){return k(I(e),8,-1)},O=C,R=m,N=function(e){if("Function"===O(e))return R(e)},w="object"==typeof document&&document.all,D={all:w,IS_HTMLDDA:void 0===w&&void 0!==w},P=D.all,M=D.IS_HTMLDDA?function(e){return"function"==typeof e||e===P}:function(e){return"function"==typeof e},L={},V=!d((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})),x=u,U=Function.prototype.call,B=x?U.bind(U):function(){return U.apply(U,arguments)},F={},j={}.propertyIsEnumerable,H=Object.getOwnPropertyDescriptor,G=H&&!j.call({1:2},1);F.f=G?function(e){var t=H(this,e);return!!t&&t.enumerable}:j;var W,K,z=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},X=d,q=C,J=Object,Y=m("".split),Q=X((function(){return!J("z").propertyIsEnumerable(0)}))?function(e){return"String"==q(e)?Y(e,""):J(e)}:J,Z=function(e){return null==e},$=Z,ee=TypeError,te=function(e){if($(e))throw ee("Can't call method on "+e);return e},re=Q,ie=te,oe=function(e){return re(ie(e))},ne=M,ae=D.all,se=D.IS_HTMLDDA?function(e){return"object"==typeof e?null!==e:ne(e)||e===ae}:function(e){return"object"==typeof e?null!==e:ne(e)},ce={},de=ce,ue=T,le=M,he=function(e){return le(e)?e:void 0},pe=function(e,t){return arguments.length<2?he(de[e])||he(ue[e]):de[e]&&de[e][t]||ue[e]&&ue[e][t]},ge="undefined"!=typeof navigator&&String(navigator.userAgent)||"",me=T,fe=ge,Ee=me.process,Te=me.Deno,ve=Ee&&Ee.versions||Te&&Te.version,_e=ve&&ve.v8;_e&&(K=(W=_e.split("."))[0]>0&&W[0]<4?1:+(W[0]+W[1])),!K&&fe&&(!(W=fe.match(/Edge\/(\d+)/))||W[1]>=74)&&(W=fe.match(/Chrome\/(\d+)/))&&(K=+W[1]);var ye=K,Se=ye,Ae=d,be=T.String,Ie=!!Object.getOwnPropertySymbols&&!Ae((function(){var e=Symbol();return!be(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&Se&&Se<41})),ke=Ie&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,Ce=pe,Oe=M,Re=f,Ne=Object,we=ke?function(e){return"symbol"==typeof e}:function(e){var t=Ce("Symbol");return Oe(t)&&Re(t.prototype,Ne(e))},De=String,Pe=function(e){try{return De(e)}catch(e){return"Object"}},Me=M,Le=Pe,Ve=TypeError,xe=function(e){if(Me(e))return e;throw Ve(Le(e)+" is not a function")},Ue=xe,Be=Z,Fe=function(e,t){var r=e[t];return Be(r)?void 0:Ue(r)},je=B,He=M,Ge=se,We=TypeError,Ke={exports:{}},ze=T,Xe=Object.defineProperty,qe=function(e,t){try{Xe(ze,e,{value:t,configurable:!0,writable:!0})}catch(r){ze[e]=t}return t},Je="__core-js_shared__",Ye=T[Je]||qe(Je,{}),Qe=Ye;(Ke.exports=function(e,t){return Qe[e]||(Qe[e]=void 0!==t?t:{})})("versions",[]).push({version:"3.31.1",mode:"pure",copyright:"© 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.31.1/LICENSE",source:"https://github.com/zloirock/core-js"});var Ze=Ke.exports,$e=te,et=Object,tt=function(e){return et($e(e))},rt=tt,it=m({}.hasOwnProperty),ot=Object.hasOwn||function(e,t){return it(rt(e),t)},nt=m,at=0,st=Math.random(),ct=nt(1..toString),dt=function(e){return"Symbol("+(void 0===e?"":e)+")_"+ct(++at+st,36)},ut=Ze,lt=ot,ht=dt,pt=Ie,gt=ke,mt=T.Symbol,ft=ut("wks"),Et=gt?mt.for||mt:mt&&mt.withoutSetter||ht,Tt=function(e){return lt(ft,e)||(ft[e]=pt&&lt(mt,e)?mt[e]:Et("Symbol."+e)),ft[e]},vt=B,_t=se,yt=we,St=Fe,At=function(e,t){var r,i;if("string"===t&&He(r=e.toString)&&!Ge(i=je(r,e)))return i;if(He(r=e.valueOf)&&!Ge(i=je(r,e)))return i;if("string"!==t&&He(r=e.toString)&&!Ge(i=je(r,e)))return i;throw We("Can't convert object to primitive value")},bt=TypeError,It=Tt("toPrimitive"),kt=function(e,t){if(!_t(e)||yt(e))return e;var r,i=St(e,It);if(i){if(void 0===t&&(t="default"),r=vt(i,e,t),!_t(r)||yt(r))return r;throw bt("Can't convert object to primitive value")}return void 0===t&&(t="number"),At(e,t)},Ct=we,Ot=function(e){var t=kt(e,"string");return Ct(t)?t:t+""},Rt=se,Nt=T.document,wt=Rt(Nt)&&Rt(Nt.createElement),Dt=function(e){return wt?Nt.createElement(e):{}},Pt=Dt,Mt=!V&&!d((function(){return 7!=Object.defineProperty(Pt("div"),"a",{get:function(){return 7}}).a})),Lt=V,Vt=B,xt=F,Ut=z,Bt=oe,Ft=Ot,jt=ot,Ht=Mt,Gt=Object.getOwnPropertyDescriptor;L.f=Lt?Gt:function(e,t){if(e=Bt(e),t=Ft(t),Ht)try{return Gt(e,t)}catch(e){}if(jt(e,t))return Ut(!Vt(xt.f,e,t),e[t])};var Wt=d,Kt=M,zt=/#|\.prototype\./,Xt=function(e,t){var r=Jt[qt(e)];return r==Qt||r!=Yt&&(Kt(t)?Wt(t):!!t)},qt=Xt.normalize=function(e){return String(e).replace(zt,".").toLowerCase()},Jt=Xt.data={},Yt=Xt.NATIVE="N",Qt=Xt.POLYFILL="P",Zt=Xt,$t=xe,er=u,tr=N(N.bind),rr=function(e,t){return $t(e),void 0===t?e:er?tr(e,t):function(){return e.apply(t,arguments)}},ir={},or=V&&d((function(){return 42!=Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype})),nr=se,ar=String,sr=TypeError,cr=function(e){if(nr(e))return e;throw sr(ar(e)+" is not an object")},dr=V,ur=Mt,lr=or,hr=cr,pr=Ot,gr=TypeError,mr=Object.defineProperty,fr=Object.getOwnPropertyDescriptor,Er="enumerable",Tr="configurable",vr="writable";ir.f=dr?lr?function(e,t,r){if(hr(e),t=pr(t),hr(r),"function"==typeof e&&"prototype"===t&&"value"in r&&vr in r&&!r[vr]){var i=fr(e,t);i&&i[vr]&&(e[t]=r.value,r={configurable:Tr in r?r[Tr]:i[Tr],enumerable:Er in r?r[Er]:i[Er],writable:!1})}return mr(e,t,r)}:mr:function(e,t,r){if(hr(e),t=pr(t),hr(r),ur)try{return mr(e,t,r)}catch(e){}if("get"in r||"set"in r)throw gr("Accessors not supported");return"value"in r&&(e[t]=r.value),e};var _r=ir,yr=z,Sr=V?function(e,t,r){return _r.f(e,t,yr(1,r))}:function(e,t,r){return e[t]=r,e},Ar=T,br=A,Ir=N,kr=M,Cr=L.f,Or=Zt,Rr=ce,Nr=rr,wr=Sr,Dr=ot,Pr=function(e){var t=function(r,i,o){if(this instanceof t){switch(arguments.length){case 0:return new e;case 1:return new e(r);case 2:return new e(r,i)}return new e(r,i,o)}return br(e,this,arguments)};return t.prototype=e.prototype,t},Mr=function(e,t){var r,i,o,n,a,s,c,d,u,l=e.target,h=e.global,p=e.stat,g=e.proto,m=h?Ar:p?Ar[l]:(Ar[l]||{}).prototype,f=h?Rr:Rr[l]||wr(Rr,l,{})[l],E=f.prototype;for(n in t)i=!(r=Or(h?n:l+(p?".":"#")+n,e.forced))&&m&&Dr(m,n),s=f[n],i&&(c=e.dontCallGetSet?(u=Cr(m,n))&&u.value:m[n]),a=i&&c?c:t[n],i&&typeof s==typeof a||(d=e.bind&&i?Nr(a,Ar):e.wrap&&i?Pr(a):g&&kr(a)?Ir(a):a,(e.sham||a&&a.sham||s&&s.sham)&&wr(d,"sham",!0),wr(f,n,d),g&&(Dr(Rr,o=l+"Prototype")||wr(Rr,o,{}),wr(Rr[o],n,a),e.real&&E&&(r||!E[n])&&wr(E,n,a)))},Lr=Math.ceil,Vr=Math.floor,xr=Math.trunc||function(e){var t=+e;return(t>0?Vr:Lr)(t)},Ur=function(e){var t=+e;return t!=t||0===t?0:xr(t)},Br=Ur,Fr=Math.max,jr=Math.min,Hr=function(e,t){var r=Br(e);return r<0?Fr(r+t,0):jr(r,t)},Gr=Ur,Wr=Math.min,Kr=function(e){return e>0?Wr(Gr(e),9007199254740991):0},zr=function(e){return Kr(e.length)},Xr=oe,qr=Hr,Jr=zr,Yr=function(e){return function(t,r,i){var o,n=Xr(t),a=Jr(n),s=qr(i,a);if(e&&r!=r){for(;a>s;)if((o=n[s++])!=o)return!0}else for(;a>s;s++)if((e||s in n)&&n[s]===r)return e||s||0;return!e&&-1}},Qr={includes:Yr(!0),indexOf:Yr(!1)},Zr=Qr.includes;Mr({target:"Array",proto:!0,forced:d((function(){return!Array(1).includes()}))},{includes:function(e){return Zr(this,e,arguments.length>1?arguments[1]:void 0)}});var $r=ce,ei=function(e){return $r[e+"Prototype"]},ti=ei("Array").includes,ri=se,ii=C,oi=Tt("match"),ni=function(e){var t;return ri(e)&&(void 0!==(t=e[oi])?!!t:"RegExp"==ii(e))},ai=TypeError,si={};si[Tt("toStringTag")]="z";var ci="[object z]"===String(si),di=ci,ui=M,li=C,hi=Tt("toStringTag"),pi=Object,gi="Arguments"==li(function(){return arguments}()),mi=di?li:function(e){var t,r,i;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(r=function(e,t){try{return e[t]}catch(e){}}(t=pi(e),hi))?r:gi?li(t):"Object"==(i=li(t))&&ui(t.callee)?"Arguments":i},fi=mi,Ei=String,Ti=function(e){if("Symbol"===fi(e))throw TypeError("Cannot convert a Symbol value to a string");return Ei(e)},vi=Tt("match"),_i=Mr,yi=function(e){if(ni(e))throw ai("The method doesn't accept regular expressions");return e},Si=te,Ai=Ti,bi=function(e){var t=/./;try{"/./"[e](t)}catch(r){try{return t[vi]=!1,"/./"[e](t)}catch(e){}}return!1},Ii=m("".indexOf);_i({target:"String",proto:!0,forced:!bi("includes")},{includes:function(e){return!!~Ii(Ai(Si(this)),Ai(yi(e)),arguments.length>1?arguments[1]:void 0)}});var ki=ei("String").includes,Ci=f,Oi=ti,Ri=ki,Ni=Array.prototype,wi=String.prototype,Di=c((function(e){var t=e.includes;return e===Ni||Ci(Ni,e)&&t===Ni.includes?Oi:"string"==typeof e||e===wi||Ci(wi,e)&&t===wi.includes?Ri:t}));function Pi(e,t,r){return{sampleRate:e,stereo:t,bitrate:r}}function Mi(e,t,r,i,o){return{width:e,height:t,frameRate:r,bitrateMin:i,bitrateMax:o}}function Li(e,t,r,i,o){return{width:{max:e},height:{max:t},frameRate:r,bitrateMin:i,bitrateMax:o}}function Vi(e,t){return{numSpatialLayers:e,numTemporalLayers:t}}const xi={"90p":Mi(160,90),"90p_1":Mi(160,90),"120p":Mi(160,120,15,30,65),"120p_1":Mi(160,120,15,30,65),"120p_3":Mi(120,120,15,30,50),"120p_4":Mi(212,120),"180p":Mi(320,180,15,30,140),"180p_1":Mi(320,180,15,30,140),"180p_3":Mi(180,180,15,30,100),"180p_4":Mi(240,180,15,30,120),"240p":Mi(320,240,15,40,200),"240p_1":Mi(320,240,15,40,200),"240p_3":Mi(240,240,15,40,140),"240p_4":Mi(424,240,15,40,220),"360p":Mi(640,360,15,80,400),"360p_1":Mi(640,360,15,80,400),"360p_3":Mi(360,360,15,80,260),"360p_4":Mi(640,360,30,80,600),"360p_6":Mi(360,360,30,80,400),"360p_7":Mi(480,360,15,80,320),"360p_8":Mi(480,360,30,80,490),"360p_9":Mi(640,360,15,80,800),"360p_10":Mi(640,360,24,80,800),"360p_11":Mi(640,360,24,80,1e3),"480p":Mi(640,480,15,100,500),"480p_1":Mi(640,480,15,100,500),"480p_2":Mi(640,480,30,100,1e3),"480p_3":Mi(480,480,15,100,400),"480p_4":Mi(640,480,30,100,750),"480p_6":Mi(480,480,30,100,600),"480p_8":Mi(848,480,15,100,610),"480p_9":Mi(848,480,30,100,930),"480p_10":Mi(640,480,10,100,400),"720p":Mi(1280,720,15,120,1130),"720p_auto":Mi(1280,720,30,900,3e3),"720p_1":Mi(1280,720,15,120,1130),"720p_2":Mi(1280,720,30,120,2e3),"720p_3":Mi(1280,720,30,120,1710),"720p_5":Mi(960,720,15,120,910),"720p_6":Mi(960,720,30,120,1380),"1080p":Mi(1920,1080,15,120,2080),"1080p_1":Mi(1920,1080,15,120,2080),"1080p_2":Mi(1920,1080,30,120,3e3),"1080p_3":Mi(1920,1080,30,120,3150),"1080p_5":Mi(1920,1080,60,120,4780),"1440p":Mi(2560,1440,30,120,4850),"1440p_1":Mi(2560,1440,30,120,4850),"1440p_2":Mi(2560,1440,60,120,7350),"4k":Mi(3840,2160,30,120,8910),"4k_1":Mi(3840,2160,30,120,8910),"4k_3":Mi(3840,2160,60,120,13500)},Ui=[{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}],Bi={"480p":Li(640,480,5),"480p_1":Li(640,480,5),"480p_2":Li(640,480,30),"480p_3":Li(640,480,15),"720p":Li(1280,720,5),"720p_auto":Mi(1280,720,30,900,3e3),"720p_1":Li(1280,720,5),"720p_2":Li(1280,720,30),"720p_3":Li(1280,720,15),"1080p":Li(1920,1080,5),"1080p_1":Li(1920,1080,5),"1080p_2":Li(1920,1080,30),"1080p_3":Li(1920,1080,15)},Fi={"1SL1TL":Vi(1,1),"3SL3TL":Vi(3,3),"2SL3TL":Vi(2,3)};function ji(e){return e||(e="480p_1"),"string"==typeof e?Object.assign({},xi[e]):e}function Hi(e){return"string"==typeof e?Object.assign({},Bi[e]):e}function Gi(e){return"string"==typeof e?Object.assign({},Fi[e]):e}const Wi={speech_low_quality:Pi(16e3,!1),speech_standard:Pi(32e3,!1,18),music_standard:Pi(48e3,!1),standard_stereo:Pi(48e3,!0,56),high_quality:Pi(48e3,!1,128),high_quality_stereo:Pi(48e3,!0,192)};function Ki(e){return"string"==typeof e?Object.assign({},Wi[e]):e}const zi=[];function Xi(e){Di(zi).call(zi,e)||zi.push(e)}function qi(e){const t=zi.indexOf(e);-1!==t&&zi.splice(t,1)}function Ji(e){return t.checkValidConstrainLong(e.width,"config.width"),t.checkValidConstrainLong(e.height,"config.height"),void 0!==e.frameRate&&t.checkValidConstrainLong(e.frameRate,"config.frameRate"),void 0!==e.bitrateMax&&t.checkValidNumber(e.bitrateMax,"config.bitrateMax"),void 0!==e.bitrateMin&&t.checkValidNumber(e.bitrateMin,"config.bitrateMin"),!0}function Yi(e){return void 0!==e.sampleRate&&t.checkValidNumber(e.sampleRate,"config.sampleRate",0,96e3,!0),void 0!==e.sampleSize&&t.checkValidNumber(e.sampleRate,"config.sampleSize",0,128,!0),void 0!==e.stereo&&t.checkValidBoolean(e.stereo,"config.stereo"),void 0!==e.bitrate&&t.checkValidNumber(e.bitrate,"config.bitrate",0,1e4,!1),!0}function Qi(e){return t.checkValidEnum(e,"mediaSource",["screen","window","application"]),!0}var Zi,$i,eo,to,ro,io,oo,no;e.TrackInternalEvent=void 0,(Zi=e.TrackInternalEvent||(e.TrackInternalEvent={})).NEED_RENEGOTIATE="@need_renegotiate",Zi.NEED_REPLACE_TRACK="@need_replace_track",Zi.NEED_CLOSE="@need_close",Zi.NEED_ENABLE_TRACK="@need_enable_track",Zi.NEED_DISABLE_TRACK="@need_disable_track",Zi.NEED_SESSION_ID="@need_sid",Zi.SET_OPTIMIZATION_MODE="@set_optimization_mode",Zi.GET_STATS="@get_stats",Zi.GET_RTC_STATS="@get_rtc_stats",Zi.GET_LOW_VIDEO_TRACK="@get_low_video_track",Zi.NEED_RESET_REMOTE_SDP="@need_reset_remote_sdp",Zi.NEED_UPDATE_VIDEO_ENCODER="@need_update_video_encoder",Zi.NEED_MUTE_TRACK="@need_mute_track",Zi.NEED_UNMUTE_TRACK="@need_unmute_track",e.TrackHint=void 0,($i=e.TrackHint||(e.TrackHint={})).SCREEN_TRACK="screen_track",$i.CUSTOM_TRACK="custome_track",$i.LOW_STREAM="low_stream",e.StreamType=void 0,(eo=e.StreamType||(e.StreamType={}))[eo.HIGH_STREAM=0]="HIGH_STREAM",eo[eo.LOW_STREAM=1]="LOW_STREAM",e.RemoteStreamType=void 0,(to=e.RemoteStreamType||(e.RemoteStreamType={}))[to.HIGH_STREAM=0]="HIGH_STREAM",to[to.LOW_STREAM=1]="LOW_STREAM",e.RemoteStreamFallbackType=void 0,(ro=e.RemoteStreamFallbackType||(e.RemoteStreamFallbackType={}))[ro.DISABLE=0]="DISABLE",ro[ro.LOW_STREAM=1]="LOW_STREAM",ro[ro.AUDIO_ONLY=2]="AUDIO_ONLY",e.TrackEvents=void 0,(e.TrackEvents||(e.TrackEvents={})).TRANSCEIVER_UPDATED="transceiver-updated",e.LocalTrackEvents=void 0,(io=e.LocalTrackEvents||(e.LocalTrackEvents={})).SOURCE_STATE_CHANGE="source-state-change",io.TRACK_ENDED="track-ended",io.BEAUTY_EFFECT_OVERLOAD="beauty-effect-overload",io.VIDEO_ELEMENT_VISIBLE_STATUS="video-element-visible-status",io.CLOSED="closed",e.RemoteTrackEvents=void 0,(oo=e.RemoteTrackEvents||(e.RemoteTrackEvents={})).FIRST_FRAME_DECODED="first-frame-decoded",oo.VIDEO_ELEMENT_VISIBLE_STATUS="video-element-visible-status",e.AudioSourceEvents=void 0,(no=e.AudioSourceEvents||(e.AudioSourceEvents={})).AUDIO_SOURCE_STATE_CHANGE="audio_source_state_change",no.RECEIVE_TRACK_BUFFER="receive_track_buffer",no.ON_AUDIO_BUFFER="on_audio_buffer",no.UPDATE_SOURCE="update_source",e.AUDIO_TRACK_EVENT=void 0,(e.AUDIO_TRACK_EVENT||(e.AUDIO_TRACK_EVENT={})).UPDATE_TRACK_SOURCE="update-track-source";const ao={sendVolumeLevel:0,sendBitrate:0,sendBytes:0,sendPackets:0,sendPacketsLost:0,sendJitterMs:0,sendRttMs:0,currentPacketLossRate:0},so={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},co={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},uo={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 lo,ho,po,go,mo;e.PROCESSOR_DESTINATION_EVENTS=void 0,(lo=e.PROCESSOR_DESTINATION_EVENTS||(e.PROCESSOR_DESTINATION_EVENTS={})).ON_TRACK="on_track",lo.ON_NODE="on_node",e.PROCESSOR_CONTEXT_EVENTS=void 0,(ho=e.PROCESSOR_CONTEXT_EVENTS||(e.PROCESSOR_CONTEXT_EVENTS={})).REQUEST_UPDATE_CONSTRAINTS="request_update_constraints",ho.REQUEST_CONSTRAINTS="request_constraints",e.DeviceManagerState=void 0,(po=e.DeviceManagerState||(e.DeviceManagerState={})).IDLE="IDLE",po.INITING="INITING",po.INITEND="INITEND",e.DeviceManagerEvent=void 0,(go=e.DeviceManagerEvent||(e.DeviceManagerEvent={})).STATE_CHANGE="state_change",go.RECORDING_DEVICE_CHANGED="recordingDeviceChanged",go.PLAYOUT_DEVICE_CHANGED="playoutDeviceChanged",go.CAMERA_DEVICE_CHANGED="cameraDeviceChanged",e.MediaElementStatus=void 0,(mo=e.MediaElementStatus||(e.MediaElementStatus={})).NONE="none",mo.INIT="init",mo.CANPLAY="canplay",mo.PLAYING="playing",mo.PAUSED="paused",mo.SUSPEND="suspend",mo.STALLED="stalled",mo.WAITING="waiting",mo.ERROR="error",mo.DESTROYED="destroyed",mo.ABORT="abort",mo.ENDED="ended",mo.EMPTIED="emptied",mo.LOADEDDATA="loadeddata";var fo;e.DataChannelEvents=void 0,(fo=e.DataChannelEvents||(e.DataChannelEvents={})).OPEN="open",fo.MESSAGE="message",fo.CLOSE="close",fo.CLOSING="closing",fo.ERROR="error";var Eo={exports:{}},To=Mr,vo=V,_o=ir.f;To({target:"Object",stat:!0,forced:Object.defineProperty!==_o,sham:!vo},{defineProperty:_o});var yo=ce.Object,So=Eo.exports=function(e,t,r){return yo.defineProperty(e,t,r)};yo.defineProperty.sham&&(So.sham=!0);var Ao=c(Eo.exports),bo=C,Io=Array.isArray||function(e){return"Array"==bo(e)},ko=TypeError,Co=Ot,Oo=ir,Ro=z,No=function(e,t,r){var i=Co(t);i in e?Oo.f(e,i,Ro(0,r)):e[i]=r},wo=M,Do=Ye,Po=m(Function.toString);wo(Do.inspectSource)||(Do.inspectSource=function(e){return Po(e)});var Mo=Do.inspectSource,Lo=m,Vo=d,xo=M,Uo=mi,Bo=Mo,Fo=function(){},jo=[],Ho=pe("Reflect","construct"),Go=/^\s*(?:class|function)\b/,Wo=Lo(Go.exec),Ko=!Go.exec(Fo),zo=function(e){if(!xo(e))return!1;try{return Ho(Fo,jo,e),!0}catch(e){return!1}},Xo=function(e){if(!xo(e))return!1;switch(Uo(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Ko||!!Wo(Go,Bo(e))}catch(e){return!0}};Xo.sham=!0;var qo=!Ho||Vo((function(){var e;return zo(zo.call)||!zo(Object)||!zo((function(){e=!0}))||e}))?Xo:zo,Jo=Io,Yo=qo,Qo=se,Zo=Tt("species"),$o=Array,en=function(e){var t;return Jo(e)&&(t=e.constructor,(Yo(t)&&(t===$o||Jo(t.prototype))||Qo(t)&&null===(t=t[Zo]))&&(t=void 0)),void 0===t?$o:t},tn=function(e,t){return new(en(e))(0===t?0:t)},rn=d,on=ye,nn=Tt("species"),an=Mr,sn=d,cn=Io,dn=se,un=tt,ln=zr,hn=function(e){if(e>9007199254740991)throw ko("Maximum allowed index exceeded");return e},pn=No,gn=tn,mn=function(e){return on>=51||!rn((function(){var t=[];return(t.constructor={})[nn]=function(){return{foo:1}},1!==t[e](Boolean).foo}))},fn=ye,En=Tt("isConcatSpreadable"),Tn=fn>=51||!sn((function(){var e=[];return e[En]=!1,e.concat()[0]!==e})),vn=function(e){if(!dn(e))return!1;var t=e[En];return void 0!==t?!!t:cn(e)};an({target:"Array",proto:!0,arity:1,forced:!Tn||!mn("concat")},{concat:function(e){var t,r,i,o,n,a=un(this),s=gn(a,0),c=0;for(t=-1,i=arguments.length;t<i;t++)if(vn(n=-1===t?a:arguments[t]))for(o=ln(n),hn(c+o),r=0;r<o;r++,c++)r in n&&pn(s,c,n[r]);else hn(c+1),pn(s,c++,n);return s.length=c,s}});var _n={},yn={},Sn=ot,An=oe,bn=Qr.indexOf,In=yn,kn=m([].push),Cn=function(e,t){var r,i=An(e),o=0,n=[];for(r in i)!Sn(In,r)&&Sn(i,r)&&kn(n,r);for(;t.length>o;)Sn(i,r=t[o++])&&(~bn(n,r)||kn(n,r));return n},On=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Rn=Cn,Nn=On,wn=Object.keys||function(e){return Rn(e,Nn)},Dn=V,Pn=or,Mn=ir,Ln=cr,Vn=oe,xn=wn;_n.f=Dn&&!Pn?Object.defineProperties:function(e,t){Ln(e);for(var r,i=Vn(t),o=xn(t),n=o.length,a=0;n>a;)Mn.f(e,r=o[a++],i[r]);return e};var Un,Bn=pe("document","documentElement"),Fn=dt,jn=Ze("keys"),Hn=function(e){return jn[e]||(jn[e]=Fn(e))},Gn=cr,Wn=_n,Kn=On,zn=yn,Xn=Bn,qn=Dt,Jn="prototype",Yn="script",Qn=Hn("IE_PROTO"),Zn=function(){},$n=function(e){return"<"+Yn+">"+e+"</"+Yn+">"},ea=function(e){e.write($n("")),e.close();var t=e.parentWindow.Object;return e=null,t},ta=function(){try{Un=new ActiveXObject("htmlfile")}catch(e){}var e,t,r;ta="undefined"!=typeof document?document.domain&&Un?ea(Un):(t=qn("iframe"),r="java"+Yn+":",t.style.display="none",Xn.appendChild(t),t.src=String(r),(e=t.contentWindow.document).open(),e.write($n("document.F=Object")),e.close(),e.F):ea(Un);for(var i=Kn.length;i--;)delete ta[Jn][Kn[i]];return ta()};zn[Qn]=!0;var ra=Object.create||function(e,t){var r;return null!==e?(Zn[Jn]=Gn(e),r=new Zn,Zn[Jn]=null,r[Qn]=e):r=ta(),void 0===t?r:Wn.f(r,t)},ia={},oa=Cn,na=On.concat("length","prototype");ia.f=Object.getOwnPropertyNames||function(e){return oa(e,na)};var aa={},sa=Hr,ca=zr,da=No,ua=Array,la=Math.max,ha=C,pa=oe,ga=ia.f,ma=function(e,t,r){for(var i=ca(e),o=sa(t,i),n=sa(void 0===r?i:r,i),a=ua(la(n-o,0)),s=0;o<n;o++,s++)da(a,s,e[o]);return a.length=s,a},fa="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[];aa.f=function(e){return fa&&"Window"==ha(e)?function(e){try{return ga(e)}catch(e){return ma(fa)}}(e):ga(pa(e))};var Ea={};Ea.f=Object.getOwnPropertySymbols;var Ta=Sr,va=function(e,t,r,i){return i&&i.enumerable?e[t]=r:Ta(e,t,r),e},_a=ir,ya=function(e,t,r){return _a.f(e,t,r)},Sa={},Aa=Tt;Sa.f=Aa;var ba,Ia,ka,Ca=ce,Oa=ot,Ra=Sa,Na=ir.f,wa=function(e){var t=Ca.Symbol||(Ca.Symbol={});Oa(t,e)||Na(t,e,{value:Ra.f(e)})},Da=B,Pa=pe,Ma=Tt,La=va,Va=function(){var e=Pa("Symbol"),t=e&&e.prototype,r=t&&t.valueOf,i=Ma("toPrimitive");t&&!t[i]&&La(t,i,(function(e){return Da(r,this)}),{arity:1})},xa=mi,Ua=ci?{}.toString:function(){return"[object "+xa(this)+"]"},Ba=ci,Fa=ir.f,ja=Sr,Ha=ot,Ga=Ua,Wa=Tt("toStringTag"),Ka=function(e,t,r,i){if(e){var o=r?e:e.prototype;Ha(o,Wa)||Fa(o,Wa,{configurable:!0,value:t}),i&&!Ba&&ja(o,"toString",Ga)}},za=M,Xa=T.WeakMap,qa=za(Xa)&&/native code/.test(String(Xa)),Ja=T,Ya=se,Qa=Sr,Za=ot,$a=Ye,es=Hn,ts=yn,rs="Object already initialized",is=Ja.TypeError,os=Ja.WeakMap;if(qa||$a.state){var ns=$a.state||($a.state=new os);ns.get=ns.get,ns.has=ns.has,ns.set=ns.set,ba=function(e,t){if(ns.has(e))throw is(rs);return t.facade=e,ns.set(e,t),t},Ia=function(e){return ns.get(e)||{}},ka=function(e){return ns.has(e)}}else{var as=es("state");ts[as]=!0,ba=function(e,t){if(Za(e,as))throw is(rs);return t.facade=e,Qa(e,as,t),t},Ia=function(e){return Za(e,as)?e[as]:{}},ka=function(e){return Za(e,as)}}var ss={set:ba,get:Ia,has:ka,enforce:function(e){return ka(e)?Ia(e):ba(e,{})},getterFor:function(e){return function(t){var r;if(!Ya(t)||(r=Ia(t)).type!==e)throw is("Incompatible receiver, "+e+" required");return r}}},cs=rr,ds=Q,us=tt,ls=zr,hs=tn,ps=m([].push),gs=function(e){var t=1==e,r=2==e,i=3==e,o=4==e,n=6==e,a=7==e,s=5==e||n;return function(c,d,u,l){for(var h,p,g=us(c),m=ds(g),f=cs(d,u),E=ls(m),T=0,v=l||hs,_=t?v(c,E):r||a?v(c,0):void 0;E>T;T++)if((s||T in m)&&(p=f(h=m[T],T,g),e))if(t)_[T]=p;else if(p)switch(e){case 3:return!0;case 5:return h;case 6:return T;case 2:ps(_,h)}else switch(e){case 4:return!1;case 7:ps(_,h)}return n?-1:i||o?o:_}},ms={forEach:gs(0),map:gs(1),filter:gs(2),some:gs(3),every:gs(4),find:gs(5),findIndex:gs(6),filterReject:gs(7)},fs=Mr,Es=T,Ts=B,vs=m,_s=V,ys=Ie,Ss=d,As=ot,bs=f,Is=cr,ks=oe,Cs=Ot,Os=Ti,Rs=z,Ns=ra,ws=wn,Ds=ia,Ps=aa,Ms=Ea,Ls=L,Vs=ir,xs=_n,Us=F,Bs=va,Fs=ya,js=Ze,Hs=yn,Gs=dt,Ws=Tt,Ks=Sa,zs=wa,Xs=Va,qs=Ka,Js=ss,Ys=ms.forEach,Qs=Hn("hidden"),Zs="Symbol",$s="prototype",ec=Js.set,tc=Js.getterFor(Zs),rc=Object[$s],ic=Es.Symbol,oc=ic&&ic[$s],nc=Es.TypeError,ac=Es.QObject,sc=Ls.f,cc=Vs.f,dc=Ps.f,uc=Us.f,lc=vs([].push),hc=js("symbols"),pc=js("op-symbols"),gc=js("wks"),mc=!ac||!ac[$s]||!ac[$s].findChild,fc=_s&&Ss((function(){return 7!=Ns(cc({},"a",{get:function(){return cc(this,"a",{value:7}).a}})).a}))?function(e,t,r){var i=sc(rc,t);i&&delete rc[t],cc(e,t,r),i&&e!==rc&&cc(rc,t,i)}:cc,Ec=function(e,t){var r=hc[e]=Ns(oc);return ec(r,{type:Zs,tag:e,description:t}),_s||(r.description=t),r},Tc=function(e,t,r){e===rc&&Tc(pc,t,r),Is(e);var i=Cs(t);return Is(r),As(hc,i)?(r.enumerable?(As(e,Qs)&&e[Qs][i]&&(e[Qs][i]=!1),r=Ns(r,{enumerable:Rs(0,!1)})):(As(e,Qs)||cc(e,Qs,Rs(1,{})),e[Qs][i]=!0),fc(e,i,r)):cc(e,i,r)},vc=function(e,t){Is(e);var r=ks(t),i=ws(r).concat(Ac(r));return Ys(i,(function(t){_s&&!Ts(_c,r,t)||Tc(e,t,r[t])})),e},_c=function(e){var t=Cs(e),r=Ts(uc,this,t);return!(this===rc&&As(hc,t)&&!As(pc,t))&&(!(r||!As(this,t)||!As(hc,t)||As(this,Qs)&&this[Qs][t])||r)},yc=function(e,t){var r=ks(e),i=Cs(t);if(r!==rc||!As(hc,i)||As(pc,i)){var o=sc(r,i);return!o||!As(hc,i)||As(r,Qs)&&r[Qs][i]||(o.enumerable=!0),o}},Sc=function(e){var t=dc(ks(e)),r=[];return Ys(t,(function(e){As(hc,e)||As(Hs,e)||lc(r,e)})),r},Ac=function(e){var t=e===rc,r=dc(t?pc:ks(e)),i=[];return Ys(r,(function(e){!As(hc,e)||t&&!As(rc,e)||lc(i,hc[e])})),i};ys||(ic=function(){if(bs(oc,this))throw nc("Symbol is not a constructor");var e=arguments.length&&void 0!==arguments[0]?Os(arguments[0]):void 0,t=Gs(e),r=function(e){this===rc&&Ts(r,pc,e),As(this,Qs)&&As(this[Qs],t)&&(this[Qs][t]=!1),fc(this,t,Rs(1,e))};return _s&&mc&&fc(rc,t,{configurable:!0,set:r}),Ec(t,e)},Bs(oc=ic[$s],"toString",(function(){return tc(this).tag})),Bs(ic,"withoutSetter",(function(e){return Ec(Gs(e),e)})),Us.f=_c,Vs.f=Tc,xs.f=vc,Ls.f=yc,Ds.f=Ps.f=Sc,Ms.f=Ac,Ks.f=function(e){return Ec(Ws(e),e)},_s&&Fs(oc,"description",{configurable:!0,get:function(){return tc(this).description}})),fs({global:!0,constructor:!0,wrap:!0,forced:!ys,sham:!ys},{Symbol:ic}),Ys(ws(gc),(function(e){zs(e)})),fs({target:Zs,stat:!0,forced:!ys},{useSetter:function(){mc=!0},useSimple:function(){mc=!1}}),fs({target:"Object",stat:!0,forced:!ys,sham:!_s},{create:function(e,t){return void 0===t?Ns(e):vc(Ns(e),t)},defineProperty:Tc,defineProperties:vc,getOwnPropertyDescriptor:yc}),fs({target:"Object",stat:!0,forced:!ys},{getOwnPropertyNames:Sc}),Xs(),qs(ic,Zs),Hs[Qs]=!0;var bc=Ie&&!!Symbol.for&&!!Symbol.keyFor,Ic=Mr,kc=pe,Cc=ot,Oc=Ti,Rc=Ze,Nc=bc,wc=Rc("string-to-symbol-registry"),Dc=Rc("symbol-to-string-registry");Ic({target:"Symbol",stat:!0,forced:!Nc},{for:function(e){var t=Oc(e);if(Cc(wc,t))return wc[t];var r=kc("Symbol")(t);return wc[t]=r,Dc[r]=t,r}});var Pc=Mr,Mc=ot,Lc=we,Vc=Pe,xc=bc,Uc=Ze("symbol-to-string-registry");Pc({target:"Symbol",stat:!0,forced:!xc},{keyFor:function(e){if(!Lc(e))throw TypeError(Vc(e)+" is not a symbol");if(Mc(Uc,e))return Uc[e]}});var Bc=m([].slice),Fc=Io,jc=M,Hc=C,Gc=Ti,Wc=m([].push),Kc=Mr,zc=pe,Xc=A,qc=B,Jc=m,Yc=d,Qc=M,Zc=we,$c=Bc,ed=function(e){if(jc(e))return e;if(Fc(e)){for(var t=e.length,r=[],i=0;i<t;i++){var o=e[i];"string"==typeof o?Wc(r,o):"number"!=typeof o&&"Number"!=Hc(o)&&"String"!=Hc(o)||Wc(r,Gc(o))}var n=r.length,a=!0;return function(e,t){if(a)return a=!1,t;if(Fc(this))return t;for(var i=0;i<n;i++)if(r[i]===e)return t}}},td=Ie,rd=String,id=zc("JSON","stringify"),od=Jc(/./.exec),nd=Jc("".charAt),ad=Jc("".charCodeAt),sd=Jc("".replace),cd=Jc(1..toString),dd=/[\uD800-\uDFFF]/g,ud=/^[\uD800-\uDBFF]$/,ld=/^[\uDC00-\uDFFF]$/,hd=!td||Yc((function(){var e=zc("Symbol")();return"[null]"!=id([e])||"{}"!=id({a:e})||"{}"!=id(Object(e))})),pd=Yc((function(){return'"\\udf06\\ud834"'!==id("\udf06\ud834")||'"\\udead"'!==id("\udead")})),gd=function(e,t){var r=$c(arguments),i=ed(t);if(Qc(i)||void 0!==e&&!Zc(e))return r[1]=function(e,t){if(Qc(i)&&(t=qc(i,this,rd(e),t)),!Zc(t))return t},Xc(id,null,r)},md=function(e,t,r){var i=nd(r,t-1),o=nd(r,t+1);return od(ud,e)&&!od(ld,o)||od(ld,e)&&!od(ud,i)?"\\u"+cd(ad(e,0),16):e};id&&Kc({target:"JSON",stat:!0,arity:3,forced:hd||pd},{stringify:function(e,t,r){var i=$c(arguments),o=Xc(hd?gd:id,null,i);return pd&&"string"==typeof o?sd(o,dd,md):o}});var fd=Ea,Ed=tt;Mr({target:"Object",stat:!0,forced:!Ie||d((function(){fd.f(1)}))},{getOwnPropertySymbols:function(e){var t=fd.f;return t?t(Ed(e)):[]}}),wa("asyncIterator"),wa("hasInstance"),wa("isConcatSpreadable"),wa("iterator"),wa("match"),wa("matchAll"),wa("replace"),wa("search"),wa("species"),wa("split");var Td=Va;wa("toPrimitive"),Td();var vd=pe,_d=Ka;wa("toStringTag"),_d(vd("Symbol"),"Symbol"),wa("unscopables"),Ka(T.JSON,"JSON",!0);var yd,Sd,Ad,bd=ce.Symbol,Id={},kd=V,Cd=ot,Od=Function.prototype,Rd=kd&&Object.getOwnPropertyDescriptor,Nd=Cd(Od,"name"),wd={EXISTS:Nd,PROPER:Nd&&"something"===function(){}.name,CONFIGURABLE:Nd&&(!kd||kd&&Rd(Od,"name").configurable)},Dd=!d((function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype})),Pd=ot,Md=M,Ld=tt,Vd=Dd,xd=Hn("IE_PROTO"),Ud=Object,Bd=Ud.prototype,Fd=Vd?Ud.getPrototypeOf:function(e){var t=Ld(e);if(Pd(t,xd))return t[xd];var r=t.constructor;return Md(r)&&t instanceof r?r.prototype:t instanceof Ud?Bd:null},jd=d,Hd=M,Gd=se,Wd=ra,Kd=Fd,zd=va,Xd=Tt("iterator"),qd=!1;[].keys&&("next"in(Ad=[].keys())?(Sd=Kd(Kd(Ad)))!==Object.prototype&&(yd=Sd):qd=!0);var Jd=!Gd(yd)||jd((function(){var e={};return yd[Xd].call(e)!==e}));Hd((yd=Jd?{}:Wd(yd))[Xd])||zd(yd,Xd,(function(){return this}));var Yd={IteratorPrototype:yd,BUGGY_SAFARI_ITERATORS:qd},Qd=Yd.IteratorPrototype,Zd=ra,$d=z,eu=Ka,tu=Id,ru=function(){return this},iu=m,ou=xe,nu=M,au=String,su=TypeError,cu=function(e,t,r){try{return iu(ou(Object.getOwnPropertyDescriptor(e,t)[r]))}catch(e){}},du=cr,uu=function(e){if("object"==typeof e||nu(e))return e;throw su("Can't set "+au(e)+" as a prototype")},lu=Object.setPrototypeOf||("__proto__"in{}?function(){var e,t=!1,r={};try{(e=cu(Object.prototype,"__proto__","set"))(r,[]),t=r instanceof Array}catch(e){}return function(r,i){return du(r),uu(i),t?e(r,i):r.__proto__=i,r}}():void 0),hu=Mr,pu=B,gu=wd,mu=function(e,t,r,i){var o=t+" Iterator";return e.prototype=Zd(Qd,{next:$d(+!i,r)}),eu(e,o,!1,!0),tu[o]=ru,e},fu=Fd,Eu=Ka,Tu=va,vu=Id,_u=Yd,yu=gu.PROPER,Su=_u.BUGGY_SAFARI_ITERATORS,Au=Tt("iterator"),bu="keys",Iu="values",ku="entries",Cu=function(){return this},Ou=function(e,t,r,i,o,n,a){mu(r,t,i);var s,c,d,u=function(e){if(e===o&&m)return m;if(!Su&&e in p)return p[e];switch(e){case bu:case Iu:case ku:return function(){return new r(this,e)}}return function(){return new r(this)}},l=t+" Iterator",h=!1,p=e.prototype,g=p[Au]||p["@@iterator"]||o&&p[o],m=!Su&&g||u(o),f="Array"==t&&p.entries||g;if(f&&(s=fu(f.call(new e)))!==Object.prototype&&s.next&&(Eu(s,l,!0,!0),vu[l]=Cu),yu&&o==Iu&&g&&g.name!==Iu&&(h=!0,m=function(){return pu(g,this)}),o)if(c={values:u(Iu),keys:n?m:u(bu),entries:u(ku)},a)for(d in c)(Su||h||!(d in p))&&Tu(p,d,c[d]);else hu({target:t,proto:!0,forced:Su||h},c);return a&&p[Au]!==m&&Tu(p,Au,m,{name:o}),vu[t]=m,c},Ru=function(e,t){return{value:e,done:t}},Nu=oe,wu=Id,Du=ss;ir.f;var Pu=Ou,Mu=Ru,Lu="Array Iterator",Vu=Du.set,xu=Du.getterFor(Lu);Pu(Array,"Array",(function(e,t){Vu(this,{type:Lu,target:Nu(e),index:0,kind:t})}),(function(){var e=xu(this),t=e.target,r=e.kind,i=e.index++;return!t||i>=t.length?(e.target=void 0,Mu(void 0,!0)):Mu("keys"==r?i:"values"==r?t[i]:[i,t[i]],!1)}),"values"),wu.Arguments=wu.Array;var Uu={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0},Bu=T,Fu=mi,ju=Sr,Hu=Id,Gu=Tt("toStringTag");for(var Wu in Uu){var Ku=Bu[Wu],zu=Ku&&Ku.prototype;zu&&Fu(zu)!==Gu&&ju(zu,Gu,Wu),Hu[Wu]=Hu.Array}var Xu=bd,qu=Tt,Ju=ir.f,Yu=qu("metadata"),Qu=Function.prototype;void 0===Qu[Yu]&&Ju(Qu,Yu,{value:null}),wa("dispose"),wa("metadata");var Zu=Xu;wa("asyncDispose");var $u=m,el=pe("Symbol"),tl=el.keyFor,rl=$u(el.prototype.valueOf),il=el.isRegisteredSymbol||function(e){try{return void 0!==tl(rl(e))}catch(e){return!1}};Mr({target:"Symbol",stat:!0},{isRegisteredSymbol:il});for(var ol=Ze,nl=pe,al=m,sl=we,cl=Tt,dl=nl("Symbol"),ul=dl.isWellKnownSymbol,ll=nl("Object","getOwnPropertyNames"),hl=al(dl.prototype.valueOf),pl=ol("wks"),gl=0,ml=ll(dl),fl=ml.length;gl<fl;gl++)try{var El=ml[gl];sl(dl[El])&&cl(El)}catch(e){}var Tl=function(e){if(ul&&ul(e))return!0;try{for(var t=hl(e),r=0,i=ll(pl),o=i.length;r<o;r++)if(pl[i[r]]==t)return!0}catch(e){}return!1};Mr({target:"Symbol",stat:!0,forced:!0},{isWellKnownSymbol:Tl}),wa("matcher"),wa("observable"),Mr({target:"Symbol",stat:!0,name:"isRegisteredSymbol"},{isRegistered:il}),Mr({target:"Symbol",stat:!0,name:"isWellKnownSymbol",forced:!0},{isWellKnown:Tl}),wa("metadataKey"),wa("patternMatch"),wa("replaceAll");var vl=c(Zu),_l=m,yl=Ur,Sl=Ti,Al=te,bl=_l("".charAt),Il=_l("".charCodeAt),kl=_l("".slice),Cl=function(e){return function(t,r){var i,o,n=Sl(Al(t)),a=yl(r),s=n.length;return a<0||a>=s?e?"":void 0:(i=Il(n,a))<55296||i>56319||a+1===s||(o=Il(n,a+1))<56320||o>57343?e?bl(n,a):i:e?kl(n,a,a+2):o-56320+(i-55296<<10)+65536}},Ol={codeAt:Cl(!1),charAt:Cl(!0)}.charAt,Rl=Ti,Nl=ss,wl=Ou,Dl=Ru,Pl="String Iterator",Ml=Nl.set,Ll=Nl.getterFor(Pl);wl(String,"String",(function(e){Ml(this,{type:Pl,string:Rl(e),index:0})}),(function(){var e,t=Ll(this),r=t.string,i=t.index;return i>=r.length?Dl(void 0,!0):(e=Ol(r,i),t.index+=e.length,Dl(e,!1))}));var Vl=c(Sa.f("iterator"));function xl(e){return xl="function"==typeof vl&&"symbol"==typeof Vl?function(e){return typeof e}:function(e){return e&&"function"==typeof vl&&e.constructor===vl&&e!==vl.prototype?"symbol":typeof e},xl(e)}var Ul=c(Sa.f("toPrimitive"));function Bl(e){var t=function(e,t){if("object"!==xl(e)||null===e)return e;var r=e[Ul];if(void 0!==r){var i=r.call(e,t||"default");if("object"!==xl(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"===xl(t)?t:String(t)}function Fl(e,t,r){return(t=Bl(t))in e?Ao(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}var jl=pe,Hl=ia,Gl=Ea,Wl=cr,Kl=m([].concat),zl=jl("Reflect","ownKeys")||function(e){var t=Hl.f(Wl(e)),r=Gl.f;return r?Kl(t,r(e)):t},Xl=ot,ql=zl,Jl=L,Yl=ir,Ql=se,Zl=Sr,$l=Error,eh=m("".replace),th=String($l("zxcasd").stack),rh=/\n\s*at [^:]*:[^\n]*/,ih=rh.test(th),oh=z,nh=!d((function(){var e=Error("a");return!("stack"in e)||(Object.defineProperty(e,"stack",oh(1,7)),7!==e.stack)})),ah=Sr,sh=function(e,t){if(ih&&"string"==typeof e&&!$l.prepareStackTrace)for(;t--;)e=eh(e,rh,"");return e},ch=nh,dh=Error.captureStackTrace,uh=Id,lh=Tt("iterator"),hh=Array.prototype,ph=mi,gh=Fe,mh=Z,fh=Id,Eh=Tt("iterator"),Th=function(e){if(!mh(e))return gh(e,Eh)||gh(e,"@@iterator")||fh[ph(e)]},vh=B,_h=xe,yh=cr,Sh=Pe,Ah=Th,bh=TypeError,Ih=B,kh=cr,Ch=Fe,Oh=rr,Rh=B,Nh=cr,wh=Pe,Dh=function(e){return void 0!==e&&(uh.Array===e||hh[lh]===e)},Ph=zr,Mh=f,Lh=function(e,t){var r=arguments.length<2?Ah(e):t;if(_h(r))return yh(vh(r,e));throw bh(Sh(e)+" is not iterable")},Vh=Th,xh=function(e,t,r){var i,o;kh(e);try{if(!(i=Ch(e,"return"))){if("throw"===t)throw r;return r}i=Ih(i,e)}catch(e){o=!0,i=e}if("throw"===t)throw r;if(o)throw i;return kh(i),r},Uh=TypeError,Bh=function(e,t){this.stopped=e,this.result=t},Fh=Bh.prototype,jh=function(e,t,r){var i,o,n,a,s,c,d,u=r&&r.that,l=!(!r||!r.AS_ENTRIES),h=!(!r||!r.IS_RECORD),p=!(!r||!r.IS_ITERATOR),g=!(!r||!r.INTERRUPTED),m=Oh(t,u),f=function(e){return i&&xh(i,"normal",e),new Bh(!0,e)},E=function(e){return l?(Nh(e),g?m(e[0],e[1],f):m(e[0],e[1])):g?m(e,f):m(e)};if(h)i=e.iterator;else if(p)i=e;else{if(!(o=Vh(e)))throw Uh(wh(e)+" is not iterable");if(Dh(o)){for(n=0,a=Ph(e);a>n;n++)if((s=E(e[n]))&&Mh(Fh,s))return s;return new Bh(!1)}i=Lh(e,o)}for(c=h?e.next:i.next;!(d=Rh(c,i)).done;){try{s=E(d.value)}catch(e){xh(i,"throw",e)}if("object"==typeof s&&s&&Mh(Fh,s))return s}return new Bh(!1)},Hh=Ti,Gh=Mr,Wh=f,Kh=Fd,zh=lu,Xh=function(e,t,r){for(var i=ql(t),o=Yl.f,n=Jl.f,a=0;a<i.length;a++){var s=i[a];Xl(e,s)||r&&Xl(r,s)||o(e,s,n(t,s))}},qh=ra,Jh=Sr,Yh=z,Qh=function(e,t){Ql(t)&&"cause"in t&&Zl(e,"cause",t.cause)},Zh=function(e,t,r,i){ch&&(dh?dh(e,t):ah(e,"stack",sh(r,i)))},$h=jh,ep=function(e,t){return void 0===e?arguments.length<2?"":t:Hh(e)},tp=Tt("toStringTag"),rp=Error,ip=[].push,op=function(e,t){var r,i=Wh(np,this);zh?r=zh(rp(),i?Kh(this):np):(r=i?this:qh(np),Jh(r,tp,"Error")),void 0!==t&&Jh(r,"message",ep(t)),Zh(r,op,r.stack,1),arguments.length>2&&Qh(r,arguments[2]);var o=[];return $h(e,ip,{that:o}),Jh(r,"errors",o),r};zh?zh(op,rp):Xh(op,rp,{name:!0});var np=op.prototype=qh(rp.prototype,{constructor:Yh(1,op),message:Yh(1,""),name:Yh(1,"AggregateError")});Gh({global:!0,constructor:!0,arity:2},{AggregateError:op});var ap,sp,cp,dp,up="undefined"!=typeof process&&"process"==C(process),lp=pe,hp=ya,pp=V,gp=Tt("species"),mp=f,fp=TypeError,Ep=qo,Tp=Pe,vp=TypeError,_p=cr,yp=function(e){if(Ep(e))return e;throw vp(Tp(e)+" is not a constructor")},Sp=Z,Ap=Tt("species"),bp=function(e,t){var r,i=_p(e).constructor;return void 0===i||Sp(r=_p(i)[Ap])?t:yp(r)},Ip=TypeError,kp=/(?:ipad|iphone|ipod).*applewebkit/i.test(ge),Cp=T,Op=A,Rp=rr,Np=M,wp=ot,Dp=d,Pp=Bn,Mp=Bc,Lp=Dt,Vp=function(e,t){if(e<t)throw Ip("Not enough arguments");return e},xp=kp,Up=up,Bp=Cp.setImmediate,Fp=Cp.clearImmediate,jp=Cp.process,Hp=Cp.Dispatch,Gp=Cp.Function,Wp=Cp.MessageChannel,Kp=Cp.String,zp=0,Xp={},qp="onreadystatechange";Dp((function(){ap=Cp.location}));var Jp=function(e){if(wp(Xp,e)){var t=Xp[e];delete Xp[e],t()}},Yp=function(e){return function(){Jp(e)}},Qp=function(e){Jp(e.data)},Zp=function(e){Cp.postMessage(Kp(e),ap.protocol+"//"+ap.host)};Bp&&Fp||(Bp=function(e){Vp(arguments.length,1);var t=Np(e)?e:Gp(e),r=Mp(arguments,1);return Xp[++zp]=function(){Op(t,void 0,r)},sp(zp),zp},Fp=function(e){delete Xp[e]},Up?sp=function(e){jp.nextTick(Yp(e))}:Hp&&Hp.now?sp=function(e){Hp.now(Yp(e))}:Wp&&!xp?(dp=(cp=new Wp).port2,cp.port1.onmessage=Qp,sp=Rp(dp.postMessage,dp)):Cp.addEventListener&&Np(Cp.postMessage)&&!Cp.importScripts&&ap&&"file:"!==ap.protocol&&!Dp(Zp)?(sp=Zp,Cp.addEventListener("message",Qp,!1)):sp=qp in Lp("script")?function(e){Pp.appendChild(Lp("script"))[qp]=function(){Pp.removeChild(this),Jp(e)}}:function(e){setTimeout(Yp(e),0)});var $p={set:Bp,clear:Fp},eg=function(){this.head=null,this.tail=null};eg.prototype={add:function(e){var t={item:e,next:null},r=this.tail;r?r.next=t:this.head=t,this.tail=t},get:function(){var e=this.head;if(e)return null===(this.head=e.next)&&(this.tail=null),e.item}};var tg,rg,ig,og,ng,ag=eg,sg=/ipad|iphone|ipod/i.test(ge)&&"undefined"!=typeof Pebble,cg=/web0s(?!.*chrome)/i.test(ge),dg=T,ug=rr,lg=L.f,hg=$p.set,pg=ag,gg=kp,mg=sg,fg=cg,Eg=up,Tg=dg.MutationObserver||dg.WebKitMutationObserver,vg=dg.document,_g=dg.process,yg=dg.Promise,Sg=lg(dg,"queueMicrotask"),Ag=Sg&&Sg.value;if(!Ag){var bg=new pg,Ig=function(){var e,t;for(Eg&&(e=_g.domain)&&e.exit();t=bg.get();)try{t()}catch(e){throw bg.head&&tg(),e}e&&e.enter()};gg||Eg||fg||!Tg||!vg?!mg&&yg&&yg.resolve?((og=yg.resolve(void 0)).constructor=yg,ng=ug(og.then,og),tg=function(){ng(Ig)}):Eg?tg=function(){_g.nextTick(Ig)}:(hg=ug(hg,dg),tg=function(){hg(Ig)}):(rg=!0,ig=vg.createTextNode(""),new Tg(Ig).observe(ig,{characterData:!0}),tg=function(){ig.data=rg=!rg}),Ag=function(e){bg.head||tg(),bg.add(e)}}var kg=Ag,Cg=function(e){try{return{error:!1,value:e()}}catch(e){return{error:!0,value:e}}},Og=T.Promise,Rg="object"==typeof Deno&&Deno&&"object"==typeof Deno.version,Ng=!Rg&&!up&&"object"==typeof window&&"object"==typeof document,wg=T,Dg=Og,Pg=M,Mg=Zt,Lg=Mo,Vg=Tt,xg=Ng,Ug=Rg,Bg=ye,Fg=Dg&&Dg.prototype,jg=Vg("species"),Hg=!1,Gg=Pg(wg.PromiseRejectionEvent),Wg=Mg("Promise",(function(){var e=Lg(Dg),t=e!==String(Dg);if(!t&&66===Bg)return!0;if(!Fg.catch||!Fg.finally)return!0;if(!Bg||Bg<51||!/native code/.test(e)){var r=new Dg((function(e){e(1)})),i=function(e){e((function(){}),(function(){}))};if((r.constructor={})[jg]=i,!(Hg=r.then((function(){}))instanceof i))return!0}return!t&&(xg||Ug)&&!Gg})),Kg={CONSTRUCTOR:Wg,REJECTION_EVENT:Gg,SUBCLASSING:Hg},zg={},Xg=xe,qg=TypeError,Jg=function(e){var t,r;this.promise=new e((function(e,i){if(void 0!==t||void 0!==r)throw qg("Bad Promise constructor");t=e,r=i})),this.resolve=Xg(t),this.reject=Xg(r)};zg.f=function(e){return new Jg(e)};var Yg,Qg,Zg=Mr,$g=up,em=T,tm=B,rm=va,im=Ka,om=function(e){var t=lp(e);pp&&t&&!t[gp]&&hp(t,gp,{configurable:!0,get:function(){return this}})},nm=xe,am=M,sm=se,cm=function(e,t){if(mp(t,e))return e;throw fp("Incorrect invocation")},dm=bp,um=$p.set,lm=kg,hm=function(e,t){try{1==arguments.length?console.error(e):console.error(e,t)}catch(e){}},pm=Cg,gm=ag,mm=ss,fm=Og,Em=Kg,Tm=zg,vm="Promise",_m=Em.CONSTRUCTOR,ym=Em.REJECTION_EVENT,Sm=mm.getterFor(vm),Am=mm.set,bm=fm&&fm.prototype,Im=fm,km=bm,Cm=em.TypeError,Om=em.document,Rm=em.process,Nm=Tm.f,wm=Nm,Dm=!!(Om&&Om.createEvent&&em.dispatchEvent),Pm="unhandledrejection",Mm=function(e){var t;return!(!sm(e)||!am(t=e.then))&&t},Lm=function(e,t){var r,i,o,n=t.value,a=1==t.state,s=a?e.ok:e.fail,c=e.resolve,d=e.reject,u=e.domain;try{s?(a||(2===t.rejection&&Fm(t),t.rejection=1),!0===s?r=n:(u&&u.enter(),r=s(n),u&&(u.exit(),o=!0)),r===e.promise?d(Cm("Promise-chain cycle")):(i=Mm(r))?tm(i,r,c,d):c(r)):d(n)}catch(e){u&&!o&&u.exit(),d(e)}},Vm=function(e,t){e.notified||(e.notified=!0,lm((function(){for(var r,i=e.reactions;r=i.get();)Lm(r,e);e.notified=!1,t&&!e.rejection&&Um(e)})))},xm=function(e,t,r){var i,o;Dm?((i=Om.createEvent("Event")).promise=t,i.reason=r,i.initEvent(e,!1,!0),em.dispatchEvent(i)):i={promise:t,reason:r},!ym&&(o=em["on"+e])?o(i):e===Pm&&hm("Unhandled promise rejection",r)},Um=function(e){tm(um,em,(function(){var t,r=e.facade,i=e.value;if(Bm(e)&&(t=pm((function(){$g?Rm.emit("unhandledRejection",i,r):xm(Pm,r,i)})),e.rejection=$g||Bm(e)?2:1,t.error))throw t.value}))},Bm=function(e){return 1!==e.rejection&&!e.parent},Fm=function(e){tm(um,em,(function(){var t=e.facade;$g?Rm.emit("rejectionHandled",t):xm("rejectionhandled",t,e.value)}))},jm=function(e,t,r){return function(i){e(t,i,r)}},Hm=function(e,t,r){e.done||(e.done=!0,r&&(e=r),e.value=t,e.state=2,Vm(e,!0))},Gm=function(e,t,r){if(!e.done){e.done=!0,r&&(e=r);try{if(e.facade===t)throw Cm("Promise can't be resolved itself");var i=Mm(t);i?lm((function(){var r={done:!1};try{tm(i,t,jm(Gm,r,e),jm(Hm,r,e))}catch(t){Hm(r,t,e)}})):(e.value=t,e.state=1,Vm(e,!1))}catch(t){Hm({done:!1},t,e)}}};_m&&(km=(Im=function(e){cm(this,km),nm(e),tm(Yg,this);var t=Sm(this);try{e(jm(Gm,t),jm(Hm,t))}catch(e){Hm(t,e)}}).prototype,(Yg=function(e){Am(this,{type:vm,done:!1,notified:!1,parent:!1,reactions:new gm,rejection:!1,state:0,value:void 0})}).prototype=rm(km,"then",(function(e,t){var r=Sm(this),i=Nm(dm(this,Im));return r.parent=!0,i.ok=!am(e)||e,i.fail=am(t)&&t,i.domain=$g?Rm.domain:void 0,0==r.state?r.reactions.add(i):lm((function(){Lm(i,r)})),i.promise})),Qg=function(){var e=new Yg,t=Sm(e);this.promise=e,this.resolve=jm(Gm,t),this.reject=jm(Hm,t)},Tm.f=Nm=function(e){return e===Im||undefined===e?new Qg(e):wm(e)}),Zg({global:!0,constructor:!0,wrap:!0,forced:_m},{Promise:Im}),im(Im,vm,!1,!0),om(vm);var Wm=Tt("iterator"),Km=!1;try{var zm=0,Xm={next:function(){return{done:!!zm++}},return:function(){Km=!0}};Xm[Wm]=function(){return this},Array.from(Xm,(function(){throw 2}))}catch(e){}var qm=Og,Jm=function(e,t){if(!t&&!Km)return!1;var r=!1;try{var i={};i[Wm]=function(){return{next:function(){return{done:r=!0}}}},e(i)}catch(e){}return r},Ym=Kg.CONSTRUCTOR||!Jm((function(e){qm.all(e).then(void 0,(function(){}))})),Qm=B,Zm=xe,$m=zg,ef=Cg,tf=jh;Mr({target:"Promise",stat:!0,forced:Ym},{all:function(e){var t=this,r=$m.f(t),i=r.resolve,o=r.reject,n=ef((function(){var r=Zm(t.resolve),n=[],a=0,s=1;tf(e,(function(e){var c=a++,d=!1;s++,Qm(r,t,e).then((function(e){d||(d=!0,n[c]=e,--s||i(n))}),o)})),--s||i(n)}));return n.error&&o(n.value),r.promise}});var rf=Mr,of=Kg.CONSTRUCTOR;Og&&Og.prototype,rf({target:"Promise",proto:!0,forced:of,real:!0},{catch:function(e){return this.then(void 0,e)}});var nf=B,af=xe,sf=zg,cf=Cg,df=jh;Mr({target:"Promise",stat:!0,forced:Ym},{race:function(e){var t=this,r=sf.f(t),i=r.reject,o=cf((function(){var o=af(t.resolve);df(e,(function(e){nf(o,t,e).then(r.resolve,i)}))}));return o.error&&i(o.value),r.promise}});var uf=B,lf=zg;Mr({target:"Promise",stat:!0,forced:Kg.CONSTRUCTOR},{reject:function(e){var t=lf.f(this);return uf(t.reject,void 0,e),t.promise}});var hf=cr,pf=se,gf=zg,mf=function(e,t){if(hf(e),pf(t)&&t.constructor===e)return t;var r=gf.f(e);return(0,r.resolve)(t),r.promise},ff=Mr,Ef=Og,Tf=Kg.CONSTRUCTOR,vf=mf,_f=pe("Promise"),yf=!Tf;ff({target:"Promise",stat:!0,forced:true},{resolve:function(e){return vf(yf&&this===_f?Ef:this,e)}});var Sf=B,Af=xe,bf=zg,If=Cg,kf=jh;Mr({target:"Promise",stat:!0,forced:Ym},{allSettled:function(e){var t=this,r=bf.f(t),i=r.resolve,o=r.reject,n=If((function(){var r=Af(t.resolve),o=[],n=0,a=1;kf(e,(function(e){var s=n++,c=!1;a++,Sf(r,t,e).then((function(e){c||(c=!0,o[s]={status:"fulfilled",value:e},--a||i(o))}),(function(e){c||(c=!0,o[s]={status:"rejected",reason:e},--a||i(o))}))})),--a||i(o)}));return n.error&&o(n.value),r.promise}});var Cf=B,Of=xe,Rf=pe,Nf=zg,wf=Cg,Df=jh,Pf="No one promise resolved";Mr({target:"Promise",stat:!0,forced:Ym},{any:function(e){var t=this,r=Rf("AggregateError"),i=Nf.f(t),o=i.resolve,n=i.reject,a=wf((function(){var i=Of(t.resolve),a=[],s=0,c=1,d=!1;Df(e,(function(e){var u=s++,l=!1;c++,Cf(i,t,e).then((function(e){l||d||(d=!0,o(e))}),(function(e){l||d||(l=!0,a[u]=e,--c||n(new r(a,Pf)))}))})),--c||n(new r(a,Pf))}));return a.error&&n(a.value),i.promise}});var Mf=Mr,Lf=Og,Vf=d,xf=pe,Uf=M,Bf=bp,Ff=mf,jf=Lf&&Lf.prototype;Mf({target:"Promise",proto:!0,real:!0,forced:!!Lf&&Vf((function(){jf.finally.call({then:function(){}},(function(){}))}))},{finally:function(e){var t=Bf(this,xf("Promise")),r=Uf(e);return this.then(r?function(r){return Ff(t,e()).then((function(){return r}))}:e,r?function(r){return Ff(t,e()).then((function(){throw r}))}:e)}});var Hf=c(ce.Promise);function Gf(e,t,r,i){var o,n=arguments.length,a=n<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,r,i);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(n<3?o(a):n>3?o(t,r,a):o(t,r))||a);return n>3&&a&&Object.defineProperty(t,r,a),a}function Wf(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}class Kf extends t.EventEmitter{constructor(e,r){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=r||t.getRandomString(8,"track-"),this._originMediaStreamTrack=e,this._mediaStreamTrack=e,Xi(this)}toString(){return this._ID}getTrackId(){return this._ID}getMediaStreamTrack(e){if(!e){const e=r.report.reportApiInvoke(null,{name:t.AgoraAPIName.GET_MEDIA_STREAM_TRACK,options:[],tag:t.AgoraAPITag.TRACER});this._mediaStreamTrack&&"string"==typeof this._mediaStreamTrack.label?e.onSuccess(this._mediaStreamTrack.label):e.onSuccess("")}return this._mediaStreamTrack}getRTCRtpTransceiver(t){return t===e.StreamType.LOW_STREAM?this._lowRtpTransceiver:this._rtpTransceiver}getMediaStreamTrackSettings(){return this.getMediaStreamTrack(!0).getSettings()}close(){this._isClosed=!0,this._lowRtpTransceiver=void 0,this._rtpTransceiver=void 0,qi(this),this.emit(e.LocalTrackEvents.CLOSED)}_updateRtpTransceiver(t,r){if(r===e.StreamType.LOW_STREAM){if(this._lowRtpTransceiver===t)return;this._lowRtpTransceiver=t}else{if(this._rtpTransceiver===t)return;this._rtpTransceiver=t}this.emit(e.TrackEvents.TRANSCEIVER_UPDATED,t,r)}}class zf extends Kf{get isExternalTrack(){return this._isExternalTrack}get muted(){return this._muted}get enabled(){return this._enabled}get processorContext(){return this._processorContext}set processorContext(e){this._processorContext=e}constructor(e,r){super(e,r),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 t.PromiseMutex("".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,r.logger.debug("[".concat(this.getTrackId(),"] close")),this.emit(e.TrackInternalEvent.NEED_CLOSE),super.close())}async _updateOriginMediaStreamTrack(r,i){let o=arguments.length>2&&void 0!==arguments[2]&&arguments[2];this._isExternalTrack=o,r!==this._originMediaStreamTrack&&(this._originMediaStreamTrack&&(this._originMediaStreamTrack.removeEventListener("ended",this._handleTrackEnded),i&&this._originMediaStreamTrack.stop()),r.addEventListener("ended",this._handleTrackEnded),this._originMediaStreamTrack=r,this._muted&&(this._originMediaStreamTrack.enabled=!1),this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await t.emitAsPromiseNoResponse(this,e.TrackInternalEvent.NEED_REPLACE_TRACK,this),this.processor&&this.processor.updateInput({track:this._originMediaStreamTrack,context:this.processorContext}))}_getDefaultPlayerConfig(){return{}}onTrackEnded(){r.logger.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(e.LocalTrackEvents.TRACK_ENDED)}stateCheck(e,i){if(r.logger.debug("check track state, [muted: ".concat(this._muted,", enabled: ").concat(this._enabled,"] to [").concat(e,": ").concat(i,"]")),t.checkValidBoolean(i,e),this._enabled&&this._muted&&"enabled"===e&&!1===i)throw new t.AgoraRTCError(t.AgoraRTCErrorCode.TRACK_STATE_UNREACHABLE,"cannot set enabled while the track is muted").print("error",r.logger);if(!this._enabled&&!this._muted&&"muted"===e&&!0===i)throw new t.AgoraRTCError(t.AgoraRTCErrorCode.TRACK_STATE_UNREACHABLE,"cannot set muted while the track is disabled").print("error",r.logger)}getProcessorStats(){return this.processorContext.gatherStats()}getProcessorUsage(){return this.processorContext.gatherUsage()}}function Xf(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}const qf=window.AudioContext||window.webkitAudioContext;let Jf=null;class Yf extends t.EventEmitter{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=()=>{r.logger.info("ios15-interruption-start"),this.emit(e.AUDIO_CONTEXT_EVENT.IOS_15_16_INTERRUPTION_START)},this.onLocalAudioTrackUnmute=async()=>{r.logger.info("ios15-interruption-end"),"running"!==this.curState||this.duringInterruption?r.logger.info("ios15-interruption-end-canceled"):(Jf&&await Jf.suspend(),this.emit(e.AUDIO_CONTEXT_EVENT.IOS_15_16_INTERRUPTION_END))}}get duringInterruption(){return"running"===this.prevState&&"interrupted"===this.curState}bindInterruptDetectorTrack(e){r.logger.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){r.logger.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)}}const Qf=new Yf;function Zf(){if(!qf)return void r.logger.error("your browser is not support web audio");r.logger.info("create audio context");const i=function(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Xf(Object(r),!0).forEach((function(t){Fl(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Xf(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}({},t.getParameter("WEBAUDIO_INIT_OPTIONS"));r.logger.debug("audio context init option:",JSON.stringify(i)),Jf=new qf(i),Qf.curState=Jf.state,Jf.onstatechange=()=>{Qf.prevState=Qf.curState,Qf.curState=Jf?Jf.state:void 0;const{prevState:i,curState:o}=Qf,n="running"===o,a="interrupted"===o,s="running"===i,c="suspended"===i,d="interrupted"===i,u=t.getBrowserInfo().osVersion;(t.isIOS()||t.isIpadOS())&&s&&a&&(r.logger.info("ios".concat(u,"-interruption-start")),Qf.emit(e.AUDIO_CONTEXT_EVENT.IOS_INTERRUPTION_START)),(t.isIOS()||t.isIpadOS())&&(c||d)&&n&&(r.logger.info("ios".concat(u,"-interruption-end")),Qf.emit(e.AUDIO_CONTEXT_EVENT.IOS_INTERRUPTION_END)),i!==o&&(r.logger.debug("AudioContext State Change","".concat(i,"=>").concat(o)),Qf.emit(e.AUDIO_CONTEXT_EVENT.STATE_CHANGE))},setInterval((()=>{var e;const i=null===(e=Jf)||void 0===e?void 0:e.currentTime;if(Qf.currentTime!==i)Qf.currentTimeStuckAt&&(r.logger.debug("AudioContext current time resume at ".concat(i)),Qf.currentTimeStuckAt=void 0),Qf.currentTime=i;else{if(i!==Qf.currentTimeStuckAt){r.report.reportApiInvoke(null,{name:"WEB_AUDIO_CURRENT_TIME_STUCK",options:{currentTime:i},tag:t.AgoraAPITag.TRACER}).onSuccess(),r.logger.warning("AudioContext current time stuck at ".concat(i))}Qf.currentTimeStuckAt=i}}),5e3),async function(r){const i=["click","contextmenu","auxclick","dblclick","mousedown","mouseup","touchend","keydown","keyup"];let o,n=!1,a=!1,s=!1;function c(e){"running"===r.state?d(!1):t.isIOS()||t.isIpadOS()?"suspended"===r.state&&(d(!0),e&&r.resume().then(l,l)):"closed"!==r.state&&(d(!0),e&&r.resume().then(l,l))}function d(e){if(n!==e){n=e;for(let t=0,r=i;t<r.length;t+=1){const i=r[t];e?window.addEventListener(i,h,{capture:!0,passive:!0}):window.removeEventListener(i,h,{capture:!0,passive:!0})}}}function u(){c(!0)}function l(){c(!1)}function h(){c(!0)}function p(e){if(!s)if(o.paused)if(e){let e;g(!1),s=!0;try{e=o.play(),e?e.then(m,m):(o.addEventListener("playing",m),o.addEventListener("abort",m),o.addEventListener("error",m))}catch(e){m()}}else g(!0);else g(!1)}function g(e){if(a!==e){a=e;for(let t=0,r=i;t<r.length;t++){const i=r[t];e?window.addEventListener(i,f,{capture:!0,passive:!0}):window.removeEventListener(i,f,{capture:!0,passive:!0})}}}function m(){o.removeEventListener("playing",m),o.removeEventListener("abort",m),o.removeEventListener("error",m),s=!1,p(!1)}function f(){p(!0)}if(t.isIOS()){const e=r.createMediaStreamDestination(),t=document.createElement("div");t.innerHTML="<audio x-webkit-airplay='deny'></audio>",o=t.children.item(0),o.controls=!1,o.disableRemotePlayback=!0,o.preload="auto",o.srcObject=e.stream,p(!0)}Qf.on(e.AUDIO_CONTEXT_EVENT.STATE_CHANGE,u),c(!1)}(Jf)}function $f(){if(!Jf){if(Zf(),!Jf)throw new t.AgoraRTCError(t.AgoraRTCErrorCode.NOT_SUPPORTED,"can not create audio context");return Jf}return Jf}function eE(){return!!Jf}function tE(e){if(function(){if(null!==iE)return iE;const e=$f(),t=e.createBufferSource(),r=e.createGain(),i=e.createGain();t.connect(r),t.connect(i),t.disconnect(r);let o=!1;try{t.disconnect(r)}catch(e){o=!0}return t.disconnect(),iE=o,o}())return;const r=e.connect,i=e.disconnect;e.connect=(t,i,o)=>{var n;return e._inputNodes||(e._inputNodes=[]),Di(n=e._inputNodes).call(n,t)||(t instanceof AudioNode?(e._inputNodes.push(t),r.call(e,t,i,o)):r.call(e,t,i)),e},e.disconnect=(o,n,a)=>{i.call(e),o?t.removeItemFromList(e._inputNodes,o):e._inputNodes=[];for(const t of e._inputNodes)r.call(e,t)}}function rE(e){const r=$f();return new Hf(((i,o)=>{r.decodeAudioData(e,(e=>{i(e)}),(e=>{o(new t.AgoraRTCError(t.AgoraRTCErrorCode.DECODE_AUDIO_FILE_FAILED,e.toString()))}))}))}let iE=null;let oE=null;function nE(e){for(let t=0;t<e.outputBuffer.numberOfChannels;t+=1){const r=e.outputBuffer.getChannelData(t);for(let e=0;e<r.length;e+=1)r[e]=0}return e.inputBuffer}const aE={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 sE(){return aE}var cE=xe,dE=tt,uE=Q,lE=zr,hE=TypeError,pE=function(e){return function(t,r,i,o){cE(r);var n=dE(t),a=uE(n),s=lE(n),c=e?s-1:0,d=e?-1:1;if(i<2)for(;;){if(c in a){o=a[c],c+=d;break}if(c+=d,e?c<0:s<=c)throw hE("Reduce of empty array with no initial value")}for(;e?c>=0:s>c;c+=d)c in a&&(o=r(o,a[c],c,n));return o}},gE={left:pE(!1),right:pE(!0)},mE=d,fE=gE.left,EE=function(e,t){var r=[][e];return!!r&&mE((function(){r.call(null,t||function(){return 1},1)}))};Mr({target:"Array",proto:!0,forced:!up&&ye>79&&ye<83||!EE("reduce")},{reduce:function(e){var t=arguments.length;return fE(this,e,t,t>1?arguments[1]:void 0)}});var TE=ei("Array").reduce,vE=f,_E=TE,yE=Array.prototype,SE=c((function(e){var t=e.reduce;return e===yE||vE(yE,e)&&t===yE.reduce?_E:t}));class AE{constructor(){this.context=void 0,this.analyserNode=void 0,this.sourceNode=void 0,this.context=$f(),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||t.isIOS()||t.isIpadOS()||"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 r=0;r<e.length;++r)e[r]=t[r]/128-1}const r=SE(e).call(e,((e,t)=>e+t*t),0)/e.length;return Math.max(10*Math.log10(r)+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){r.logger.warning("rebuild analyser node failed.")}}destroy(){this.updateSource(void 0)}}class bE extends t.EventEmitter{get processSourceNode(){return this.sourceNode}set processedNode(e){var t;if(!this.isDestroyed&&this._processedNode!==e){try{var r;null===(r=this.sourceNode)||void 0===r||r.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=$f(),this.playNode=this.context.destination,this.outputNode=this.context.createGain(),tE(this.outputNode),this.volumeLevelAnalyser=new AE}startGetAudioBuffer(t){this.audioBufferNode||(this.audioBufferNode=this.context.createScriptProcessor(t),this.outputNode.connect(this.audioBufferNode),this.audioBufferNode.connect(this.context.destination),this.audioBufferNode.onaudioprocess=t=>{this.emit(e.AudioSourceEvents.ON_AUDIO_BUFFER,nE(t))})}stopGetAudioBuffer(){this.audioBufferNode&&(this.audioBufferNode.onaudioprocess=null,this.outputNode.disconnect(this.audioBufferNode),this.audioBufferNode=void 0)}createOutputTrack(){if(!sE().webAudioMediaStreamDest)throw new t.AgoraRTCError(t.AgoraRTCErrorCode.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&&t.nextTick((()=>{Qf.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;t.isIOS()||t.isIpadOS()?"suspended"===this.context.state&&this.context.resume():"running"!==this.context.state&&this.context.resume();const r=this.volumeLevelAnalyser.getAnalyserNode();let i;r.getFloatTimeDomainData?(i=new Float32Array(r.fftSize),r.getFloatTimeDomainData(i)):(i=new Uint8Array(r.fftSize),r.getByteTimeDomainData(i));let o=!1;for(let e=0;e<i.length;e++)0!==i[e]&&(o=!0);return o?(this.isNoAudioInput=!1,!0):(await t.wait(200),await this.checkHasAudioInput(e?e+1:1)&&o)}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 IE extends bE{get isFreeze(){return!1}constructor(i,o,n){var a;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(r.logger.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 r.logger.debug("rebuild web audio success, current volume status",this.getAccurateVolumeLevel());this.context.resume().then((()=>r.logger.info("resume success"))),r.logger.debug("rebuild web audio because of ios 12 bugs"),this.disconnect();const t=this.track;this.track=this.track.clone(),this.isCurrentTrackCloned?t.stop():this.isCurrentTrackCloned=!0;const i=new MediaStream([this.track]);this.sourceNode=this.context.createMediaStreamSource(i),tE(this.sourceNode),this.volumeLevelAnalyser.rebuildAnalyser();const o=this.outputNode.gain.value;this.outputNode=this.context.createGain(),this.outputNode.gain.setValueAtTime(o,this.context.currentTime),tE(this.outputNode),this.emit(e.AudioSourceEvents.UPDATE_SOURCE),this.connect(),this.audioElement.srcObject=i,this.isPlayed&&this.play(this.playNode),this.checkHasAudioInput()},"audio"!==i.kind)throw new t.AgoraRTCError(t.AgoraRTCErrorCode.UNEXPECTED_ERROR);this.track=i;const s=new MediaStream([this.track]);if(this.isRemoteTrack=!!o,this.sourceNode=this.context.createMediaStreamSource(s),tE(this.sourceNode),n){const e=n.clone();e.enabled=!0,this.clonedTrack=e,r.logger.debug("create an unmuted track ".concat(e.id," from the original track ").concat(n.id," to get the volume"));const t=this.context.createMediaStreamSource(new MediaStream([e]));tE(t),this.originVolumeLevelAnalyser=new AE,this.originVolumeLevelAnalyser.updateSource(t)}this.connect(),this.audioElement=document.createElement("audio"),this.audioElement.srcObject=s;const c=t.getBrowserInfo();o&&c.os===t.BrowserOS.IOS&&Number(null===(a=c.osVersion)||void 0===a?void 0:a.split(".")[0])<15&&(Qf.on(e.AUDIO_CONTEXT_EVENT.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(t){this.sourceNode.disconnect(),this.track=t,this.isCurrentTrackCloned=!1;const r=new MediaStream([t]);this.sourceNode=this.context.createMediaStreamSource(r),tE(this.sourceNode),this.processedNode||this.sourceNode.connect(this.outputNode),this.emit(e.AudioSourceEvents.UPDATE_SOURCE),this.audioElement.srcObject=r}destroy(){var e;this.audioElement.srcObject=null,this.audioElement.remove(),Qf.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),r.logger.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]));tE(i),this.originVolumeLevelAnalyser&&this.originVolumeLevelAnalyser.updateSource(i)}getOriginVolumeLevel(){return this.originVolumeLevelAnalyser?this.originVolumeLevelAnalyser.getVolumeLevel():this.getAccurateVolumeLevel()}}async function kE(e,t,r){const i=(e,t)=>e?"number"!=typeof e?e.max||e.exact||e.ideal||e.min||t:e:t,o={audio:!!r&&{mandatory:{chromeMediaSource:"desktop"}},video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:e,maxHeight:i(t.height,1080),maxWidth:i(t.width,1920)}}};return t.frameRate&&"number"!=typeof t.frameRate?(o.video.mandatory.maxFrameRate=t.frameRate.max,o.video.mandatory.minFrameRate=t.frameRate.min):"number"==typeof t.frameRate&&(o.video.mandatory.maxFrameRate=t.frameRate),await navigator.mediaDevices.getUserMedia(o)}async function CE(e,r){const i=await OE(e.mediaSource),{sourceId:o,audio:n}=await t.showElectronSelectSourceWindow(i,r);return await kE(o,e,n)}async function OE(e){let r=["window","screen"];"application"!==e&&"window"!==e||(r=["window"]),"screen"===e&&(r=["screen"]);const i=t.getElectronInstance();if(!i)throw console.error("failed to fetch electron, please mount it to window"),new t.AgoraRTCError(t.AgoraRTCErrorCode.ELECTRON_IS_NULL);let o=null;try{var n;o=(null===(n=i.desktopCapturer)||void 0===n?void 0:n.getSources({types:r}))||i.ipcRenderer.invoke("DESKTOP_CAPTURER_GET_SOURCES",{types:r})}catch(e){o=null}o&&o.then||(o=new Hf(((e,t)=>{i.desktopCapturer.getSources({types:r},((r,i)=>{r?t(r):e(i)}))})));try{return await o}catch(e){throw new t.AgoraRTCError(t.AgoraRTCErrorCode.ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR,e.toString())}}function RE(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}const NE=new t.PromiseMutex("safari");async function wE(e,i){let o=0,n=null;for(;o<2;)try{n=await DE(e,i,o>0);break}catch(e){if(e instanceof t.AgoraRTCError)throw r.logger.error("[".concat(i,"] ").concat(e.toString())),e;const n=PE(e.name||e.code||e,e.message);if(n.code===t.AgoraRTCErrorCode.MEDIA_OPTION_INVALID){r.logger.debug("[".concat(i,"] detect media option invalid, retry")),o+=1,await t.wait(500);continue}throw r.logger.error("[".concat(i,"] ").concat(n.toString())),n}if(!n)throw new t.AgoraRTCError(t.AgoraRTCErrorCode.UNEXPECTED_ERROR,"can not find stream after getUserMedia");return n}async function DE(i,o,n){if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)throw new t.AgoraRTCError(t.AgoraRTCErrorCode.NOT_SUPPORTED,"can not find getUserMedia");n&&(i.video&&(delete i.video.width,delete i.video.height),i.screen&&(delete i.screen.width,delete i.screen.height));const a=sE(),s=new MediaStream;if(i.audioSource&&s.addTrack(i.audioSource),i.videoSource&&s.addTrack(i.videoSource),!i.audio&&!i.video&&!i.screen)return r.logger.debug("Using Video Source/ Audio Source"),s;if(i.screen)if(t.isElectron())if(i.screen.sourceId){ME(s,await kE(i.screen.sourceId,i.screen,i.screenAudio))}else{ME(s,await CE(i.screen,i.screenAudio))}else if(t.isChrome()&&i.screen.extensionId&&i.screen.mandatory){if(!a.getStreamFromExtension)throw new t.AgoraRTCError(t.AgoraRTCErrorCode.NOT_SUPPORTED,"This browser does not support screen sharing");r.logger.debug("[".concat(o,'] Screen access on chrome stable, looking for extension"'));const e=await(d=i.screen.extensionId,u=o,new Hf(((e,i)=>{try{chrome.runtime.sendMessage(d,{getStream:!0},(o=>{if(!o||!o.streamId)return r.logger.error("[".concat(u,"] No response from Chrome Plugin. Plugin not installed properly"),o),void i(new t.AgoraRTCError(t.AgoraRTCErrorCode.CHROME_PLUGIN_NO_RESPONSE,"No response from Chrome Plugin. Plugin not installed properly"));e(o.streamId)}))}catch(e){r.logger.error("[".concat(u,"] AgoraRTC screensharing plugin is not accessible(").concat(d,")"),e.toString()),i(new t.AgoraRTCError(t.AgoraRTCErrorCode.CHROME_PLUGIN_NOT_INSTALL))}})));i.screen.mandatory.chromeMediaSourceId=e;ME(s,await navigator.mediaDevices.getUserMedia({video:{mandatory:i.screen.mandatory}}))}else if(a.getDisplayMedia){var c;i.screen.mediaSource&&Qi(i.screen.mediaSource);const e={width:i.screen.width,height:i.screen.height,frameRate:i.screen.frameRate,displaySurface:null!==(c=i.screen.displaySurface)&&void 0!==c?c:"screen"===i.screen.mediaSource?"monitor":i.screen.mediaSource},{selfBrowserSurface:t,surfaceSwitching:n,systemAudio:a}=i.screen,d={selfBrowserSurface:t,surfaceSwitching:n,systemAudio:a};!t&&delete d.selfBrowserSurface,!n&&delete d.surfaceSwitching,!a&&delete d.systemAudio,r.logger.debug("[".concat(o,"] getDisplayMedia:"),JSON.stringify({video:e,audio:!!i.screenAudio,controls:d}));const u=await navigator.mediaDevices.getDisplayMedia(function(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?RE(Object(r),!0).forEach((function(t){Fl(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):RE(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}({video:e,audio:!!i.screenAudio},d));ME(s,u)}else{if(!t.isFirefox())throw r.logger.error("[".concat(o,"] This browser does not support screenSharing")),new t.AgoraRTCError(t.AgoraRTCErrorCode.NOT_SUPPORTED,"This browser does not support screen sharing");{i.screen.mediaSource&&Qi(i.screen.mediaSource);const e={video:{mediaSource:i.screen.mediaSource,width:i.screen.width,height:i.screen.height,frameRate:i.screen.frameRate}};r.logger.debug("[".concat(o,"] getUserMedia: ").concat(JSON.stringify(e)));ME(s,await navigator.mediaDevices.getUserMedia(e))}}var d,u;if(!i.video&&!i.audio)return s;let l={video:i.video,audio:i.audio},h=t.getParameter("MEDIA_DEVICE_CONSTRAINTS");if(h)try{"string"==typeof h&&(h=JSON.parse(h)),l=t.recursiveMerge(l,h)}catch(e){}r.logger.debug("[".concat(o,"] GetUserMedia"),JSON.stringify(l)),t.getBrowserInfo();let p,g=null;(t.isSafari()||t.isIOS()||t.isWkWebview())&&(g=await NE.lock());try{p=await navigator.mediaDevices.getUserMedia(l)}catch(e){throw g&&g(),e}return l.audio&&(e.HAS_GUM_AUDIO=!0),l.video&&(e.HAS_GUM_VIDEO=!0),ME(s,p),g&&g(),s}function PE(e,i){switch(e){case"Starting video failed":case"OverconstrainedError":case"TrackStartError":return new t.AgoraRTCError(t.AgoraRTCErrorCode.MEDIA_OPTION_INVALID,"".concat(e,": ").concat(i));case"NotFoundError":case"DevicesNotFoundError":return new t.AgoraRTCError(t.AgoraRTCErrorCode.DEVICE_NOT_FOUND,"".concat(e,": ").concat(i));case"NotSupportedError":return new t.AgoraRTCError(t.AgoraRTCErrorCode.NOT_SUPPORTED,"".concat(e,": ").concat(i));case"NotReadableError":return new t.AgoraRTCError(t.AgoraRTCErrorCode.NOT_READABLE,"".concat(e,": ").concat(i));case"InvalidStateError":case"NotAllowedError":case"PERMISSION_DENIED":case"PermissionDeniedError":return new t.AgoraRTCError(t.AgoraRTCErrorCode.PERMISSION_DENIED,"".concat(e,": ").concat(i));case"ConstraintNotSatisfiedError":return new t.AgoraRTCError(t.AgoraRTCErrorCode.CONSTRAINT_NOT_SATISFIED,"".concat(e,": ").concat(i));default:return r.logger.error("getUserMedia unexpected error",e),new t.AgoraRTCError(t.AgoraRTCErrorCode.UNEXPECTED_ERROR,"".concat(e,": ").concat(i))}}function ME(e,t){const r=e.getVideoTracks()[0],i=e.getAudioTracks()[0],o=t.getVideoTracks()[0],n=t.getAudioTracks()[0];n&&(i&&e.removeTrack(i),e.addTrack(n)),o&&(r&&e.removeTrack(r),e.addTrack(o))}e.HAS_GUM_AUDIO=!1,e.HAS_GUM_VIDEO=!1;class LE extends t.EventEmitter{get state(){return this._state}set state(t){t!==this._state&&(this.emit(e.DeviceManagerEvent.STATE_CHANGE,t),this._state=t)}constructor(){super(),this._state=e.DeviceManagerState.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((()=>{(t.getParameter("ENUMERATE_DEVICES_INTERVAL")||(t.isAndroid()||t.isHarmonyOS())&&t.isChromeKernel())&&this.updateDevicesInfo()}),t.getParameter("ENUMERATE_DEVICES_INTERVAL_TIME"))})).catch((e=>r.logger.error(e.toString())))}async enumerateDevices(i,o){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices){return new t.AgoraRTCError(t.AgoraRTCErrorCode.NOT_SUPPORTED,"enumerateDevices() not supported.").throw()}const a=await navigator.mediaDevices.enumerateDevices(),s=this.checkMediaDeviceInfoIsOk(a);let c=!this.isAccessMicrophonePermission&&i,d=!this.isAccessCameraPermission&&o;s.audio&&(c=!1),s.video&&(d=!1);let u=null,l=null,h=null;if(!n&&(c||d)){if(NE.isLocked){r.logger.debug("[device manager] wait GUM lock");(await NE.lock())(),r.logger.debug("[device manager] GUM unlock")}if(e.HAS_GUM_AUDIO&&(c=!1,this.isAccessMicrophonePermission=!0),e.HAS_GUM_VIDEO&&(d=!1,this.isAccessCameraPermission=!0),r.logger.debug("[device manager] check media device permissions",i,o,c,d),c&&d){try{h=await navigator.mediaDevices.getUserMedia({audio:!0,video:!0})}catch(e){const i=PE(e.name||e.code||e,e.message);if(i.code===t.AgoraRTCErrorCode.PERMISSION_DENIED)throw i;r.logger.warning("getUserMedia failed in getDevices",i)}this.isAccessCameraPermission=!0,this.isAccessMicrophonePermission=!0}else if(c){try{u=await navigator.mediaDevices.getUserMedia({audio:i})}catch(e){const i=PE(e.name||e.code||e,e.message);if(i.code===t.AgoraRTCErrorCode.PERMISSION_DENIED)throw i;r.logger.warning("getUserMedia failed in getDevices",i)}this.isAccessMicrophonePermission=!0}else if(d){try{l=await navigator.mediaDevices.getUserMedia({video:o})}catch(e){const i=PE(e.name||e.code||e,e.message);if(i.code===t.AgoraRTCErrorCode.PERMISSION_DENIED)throw i;r.logger.warning("getUserMedia failed in getDevices",i)}this.isAccessCameraPermission=!0}r.logger.debug("[device manager] mic permission",i,"cam permission",o)}try{const e=await navigator.mediaDevices.enumerateDevices();return u&&u.getTracks().forEach((e=>e.stop())),l&&l.getTracks().forEach((e=>e.stop())),h&&h.getTracks().forEach((e=>e.stop())),u=null,l=null,h=null,e}catch(e){u&&u.getTracks().forEach((e=>e.stop())),l&&l.getTracks().forEach((e=>e.stop())),h&&h.getTracks().forEach((e=>e.stop())),u=null,l=null,h=null;return new t.AgoraRTCError(t.AgoraRTCErrorCode.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((r=>{r.device.label===e&&(t=r.device.deviceId)})),t}async getDeviceById(e){const r=(await this.enumerateDevices(!0,!0,!0)).find((t=>t.deviceId===e));if(!r)throw new t.AgoraRTCError(t.AgoraRTCErrorCode.DEVICE_NOT_FOUND,"deviceId: ".concat(e));return r}async init(){this.state=e.DeviceManagerState.INITING;try{await this.updateDevicesInfo(),this.state=e.DeviceManagerState.INITEND}catch(i){if(r.logger.warning("Device Detection functionality cannot start properly.",i.toString()),this.state=e.DeviceManagerState.IDLE,!t.detectSecureContext()){new t.AgoraRTCError(t.AgoraRTCErrorCode.WEB_SECURITY_RESTRICT,"Your context is limited by web security, please try using https protocol or localhost.").throw()}throw i}}async updateDevicesInfo(){const t=await this.enumerateDevices(!0,!0,!0),i=Date.now(),o=[];if(t[0]&&t[0].label&&!1===this.checkdeviceMatched){this.checkdeviceMatched=!0;const e=t.find((e=>"audioinput"===e.kind&&"default"===e.deviceId)),i=t.find((e=>"audiooutput"===e.kind&&"default"===e.deviceId));e&&i?i.groupId===e.groupId?r.logger.debug("[device-check] default input ".concat(e.label," and output ").concat(i.label," is the same group")):r.logger.warning("[device-check] default input ".concat(e.label," and output ").concat(i.label," is not the same group")):r.logger.debug("[device-check] default input or output not found")}const n=this.checkMediaDeviceInfoIsOk(t);if(t.forEach((e=>{if(!e.deviceId)return;const t=this.deviceInfoMap.get("".concat(e.kind,"_").concat(e.deviceId));if("ACTIVE"!==(t?t.state:"INACTIVE")){const t={initAt:i,updateAt:i,device:e,state:"ACTIVE"};this.deviceInfoMap.set("".concat(e.kind,"_").concat(e.deviceId),t),o.push(t)}t&&(t.updateAt=i)})),this.deviceInfoMap.forEach(((e,t)=>{"ACTIVE"===e.state&&e.updateAt!==i&&(e.state="INACTIVE",o.push(e))})),this.state!==e.DeviceManagerState.INITEND)return n.audio&&(this.lastAccessMicrophonePermission=!0,this.isAccessMicrophonePermission=!0),void(n.video&&(this.lastAccessCameraPermission=!0,this.isAccessCameraPermission=!0));o.forEach((t=>{switch(t.device.kind){case"audioinput":this.lastAccessMicrophonePermission&&this.isAccessMicrophonePermission&&this.emit(e.DeviceManagerEvent.RECORDING_DEVICE_CHANGED,t);break;case"videoinput":this.lastAccessCameraPermission&&this.isAccessCameraPermission&&this.emit(e.DeviceManagerEvent.CAMERA_DEVICE_CHANGED,t);break;case"audiooutput":this.lastAccessMicrophonePermission&&this.isAccessMicrophonePermission&&this.emit(e.DeviceManagerEvent.PLAYOUT_DEVICE_CHANGED,t)}})),n.audio&&(this.lastAccessMicrophonePermission=!0,this.isAccessMicrophonePermission=!0),n.video&&(this.lastAccessCameraPermission=!0,this.isAccessCameraPermission=!0)}checkMediaDeviceInfoIsOk(e){const t=e.filter((e=>"audioinput"===e.kind)),r=e.filter((e=>"videoinput"===e.kind)),i={audio:!1,video:!1};for(const e of t)if(e.label&&e.deviceId){i.audio=!0;break}for(const e of r)if(e.label&&e.deviceId){i.video=!0;break}return i}}const VE=new LE;class xE extends t.EventEmitter{constructor(){super(...arguments),this.onAutoplayFailed=void 0,this.onAudioAutoplayFailed=void 0}}let UE=!1;const BE=new xE;function FE(){if(t.getBrowserInfo(),!UE){const e=r=>{r.preventDefault(),UE=!1,t.isAndroidChromium()?document.body.removeEventListener("click",e,!0):(document.body.removeEventListener("touchstart",e,!0),document.body.removeEventListener("mousedown",e,!0))};UE=!0,t.isAndroidChromium()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0)),r.logger.info("detect media autoplay failed, document: https://docs.agora.io/cn/Voice/autoplay_policy_web_ng?platform=Web"),BE.onAutoplayFailed?BE.onAutoplayFailed():BE.onAudioAutoplayFailed?r.logger.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 ."):r.logger.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 ."),BE.emit("autoplay-failed")}}function jE(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}function HE(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?jE(Object(r),!0).forEach((function(t){Fl(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):jE(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function GE(e,t,i,o){if(!e)return;const n=r.report.getBaseInfoBySessionId(e);if(!n)return;const a=n.info,s=Date.now(),c=HE(HE({},a),{},{vid:void 0===a.vid?0:Number(a.vid),lts:s,elapse:s-n.startTime,cbRegistered:BE.onAutoplayFailed||BE.onAudioAutoplayFailed?1:-1,errorMsg:i,mediaType:t,trackId:o,extend:void 0});r.report.send({type:r.AgoraRTCEventUploadType.AUTOPLAY_FAILED,data:c},!0)}const WE=["play","playing","loadeddata","canplay","pause","stalled","suspend","waiting","abort","emptied","ended","error"],KE=new class{constructor(){this.onAutoplayFailed=void 0,this.elementMap=new Map,this.elementStateMap=new Map,this.elementsNeedToResume=[],this.sinkIdMap=new Map,this.autoResumeAfterInterruption=()=>{Array.from(this.elementMap.entries()).forEach((e=>{let[i,o]=e;const n=this.elementStateMap.get(i),a=o.srcObject.getAudioTracks()[0];t.isIOS15()?a&&"live"===a.readyState&&"running"===Qf.curState&&(r.logger.debug("auto resume after interruption for iOS 15"),o.pause(),o.play()):n&&"paused"===n&&a&&"live"===a.readyState&&"running"===Qf.curState&&(r.logger.debug("auto resume after interruption for iOS"),o.play())}))},this.autoResumeAfterInterruptionOnIOS15_16=()=>{Array.from(this.elementMap.entries()).forEach((e=>{let[t,i]=e;const o=i.srcObject.getAudioTracks()[0];o&&"live"===o.readyState&&(r.logger.debug("auto resume after interruption inside autoResumeAfterInterruptionOnIOS15"),i.pause(),i.play())}))},this.autoResumeAudioElement(),Qf.on(e.AUDIO_CONTEXT_EVENT.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),Qf.on(e.AUDIO_CONTEXT_EVENT.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16),Qf.on(e.AUDIO_CONTEXT_EVENT.STATE_CHANGE,(()=>{t.isIOS()&&"suspended"===Qf.prevState&&"running"===Qf.curState&&this.autoResumeAfterInterruption()}))}async setSinkID(e,r){const i=this.elementMap.get(e);if(this.sinkIdMap.set(e,r),i)try{await i.setSinkId(r)}catch(e){throw new t.AgoraRTCError(t.AgoraRTCErrorCode.PERMISSION_DENIED,"can not set sink id: "+e.toString())}}play(i,o,n,a){if(this.elementMap.has(o))return;const s=document.createElement("audio");s.autoplay=!0,s.srcObject=new MediaStream([i]),this.bindAudioElementEvents(o,s),this.elementMap.set(o,s),this.elementStateMap.set(o,e.MediaElementStatus.INIT),this.setVolume(o,n);const c=this.sinkIdMap.get(o);if(c)try{s.setSinkId(c).catch((e=>{r.logger.warning("[".concat(o,"] set sink id failed"),e.toString())}))}catch(e){r.logger.warning("[".concat(o,"] set sink id failed"),e.toString())}const d=s.play();d&&d.then&&d.catch((e=>{a&&GE(a,"audio",e.message,o),r.logger.warning("audio element play warning",e.toString()),this.elementMap.has(o)&&"NotAllowedError"===e.name&&(r.logger.warning("detected audio element autoplay failed"),this.elementsNeedToResume.push(s),t.nextTick((()=>{this.onAutoplayFailed&&this.onAutoplayFailed(),FE()})))}))}updateTrack(e,t){const r=this.elementMap.get(e);r&&(r.srcObject=new MediaStream([t]))}isPlaying(e){return this.elementMap.has(e)&&"playing"===this.elementStateMap.get(e)}setVolume(e,t){const r=this.elementMap.get(e);r&&(t=Math.max(0,Math.min(100,t)),r.volume=t/100)}stop(e){const t=this.elementMap.get(e);if(this.sinkIdMap.delete(e),!t)return;const r=this.elementsNeedToResume.indexOf(t);this.elementsNeedToResume.splice(r,1),t.srcObject=null,t.remove(),this.elementMap.delete(e),this.elementStateMap.delete(e)}bindAudioElementEvents(e,t){WE.forEach((i=>{t.addEventListener(i,(i=>{const o=this.elementStateMap.get(e),n="pause"===i.type?"paused":i.type;if(r.logger.debug("[".concat(e,"] audio-element-status change ").concat(o," => ").concat(n)),"error"===i.type){const i=null==t?void 0:t.error;i&&r.logger.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=>{r.logger.debug("Auto resume audio element success")})).catch((e=>{r.logger.warning("Auto resume audio element failed!",e)}))})),this.elementsNeedToResume=[]};t.domLoadedPromise().then((()=>{t.isAndroidChromium()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0))}))}};function zE(){return function(e,i,o){const n=o.value;return"function"==typeof n&&(o.value=function(){this._isClosed&&new t.AgoraRTCError(t.AgoraRTCErrorCode.INVALID_OPERATION,"[".concat(this.getTrackId(),"] cannot operate a closed track")).print("warning",r.logger);for(var e=arguments.length,i=new Array(e),o=0;o<e;o++)i[o]=arguments[o];const a=n.apply(this,i);return a instanceof Hf?new Hf(((e,t)=>{a.then(e).catch(t)})):a}),o}}var XE=ei("Array").values,qE=mi,JE=ot,YE=f,QE=XE,ZE=Array.prototype,$E={DOMTokenList:!0,NodeList:!0},eT=c((function(e){var t=e.values;return e===ZE||YE(ZE,e)&&t===ZE.values||JE($E,qE(e))?QE:t}));function tT(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}function rT(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?tT(Object(r),!0).forEach((function(t){Fl(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):tT(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}class iT extends t.EventEmitter{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.AgoraRTCError(t.AgoraRTCErrorCode.NOT_SUPPORTED,"VideoProcessor cannot pipe to any other Processor")}unpipe(){throw new t.AgoraRTCError(t.AgoraRTCErrorCode.NOT_SUPPORTED,"VideoProcessor cannot unpipe to any other Processor")}enable(){}disable(){}updateInput(t){if(t.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).");t.track&&t.track!==this.inputTrack&&(this.videoContext.chained=!0,this.inputTrack=t.track,this.emit(e.PROCESSOR_DESTINATION_EVENTS.ON_TRACK,t.track))}reset(){this.inputTrack=void 0,this.videoContext.chained=!1,this.emit(e.PROCESSOR_DESTINATION_EVENTS.ON_TRACK,void 0)}}class oT extends t.EventEmitter{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.emitAsPromise(this,e.PROCESSOR_CONTEXT_EVENTS.REQUEST_CONSTRAINTS)}async requestApplyConstraints(i,o){var n;return r.logger.info("processor ".concat(o.name," requestApplyConstraints for ").concat(this.trackId)),i&&this.constraintsMap.set(o,i),t.emitAsPromiseNoResponse(this,e.PROCESSOR_CONTEXT_EVENTS.REQUEST_UPDATE_CONSTRAINTS,Array.from(eT(n=this.constraintsMap).call(n)))}async requestRevertConstraints(i){var o;if(this.constraintsMap.has(i))return r.logger.info("processor ".concat(i.name," requestRevertConstraints for ").concat(this.trackId)),this.constraintsMap.delete(i),t.emitAsPromiseNoResponse(this,e.PROCESSOR_CONTEXT_EVENTS.REQUEST_UPDATE_CONSTRAINTS,Array.from(eT(o=this.constraintsMap).call(o)))}registerStats(e,t,r){this.statsRegistry.find((r=>r.processorID===e.ID&&r.processorName===e.name&&r.type===t))||this.statsRegistry.push({processorName:e.name,processorID:e.ID,type:t,cb:r})}unregisterStats(e,t){const r=this.statsRegistry.findIndex((r=>r.processorID===e.ID&&r.processorName===e.name&&r.type===t));-1!==r&&this.statsRegistry.splice(r,1)}gatherStats(){const e=[];for(const{processorID:i,processorName:o,type:n,cb:a}of this.statsRegistry)try{const t=a();e.push({processorID:i,processorName:o,type:n,stats:t})}catch(e){r.logger.error(new t.AgoraRTCError(t.AgoraRTCErrorCode.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 r=t();r instanceof Hf&&(r=await r),e.push(rT(rT({},r),{},{direction:this.direction}))}catch(e){r.logger.error("gather extension usage error",e)}return e}getDirection(){return this.direction}}class nT extends t.EventEmitter{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.AgoraRTCError(t.AgoraRTCErrorCode.NOT_SUPPORTED,"AudioProcessorDestination cannot pipe to any other Processor")}unpipe(){throw new t.AgoraRTCError(t.AgoraRTCErrorCode.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(e.PROCESSOR_DESTINATION_EVENTS.ON_TRACK,void 0),this.emit(e.PROCESSOR_DESTINATION_EVENTS.ON_NODE,void 0)}updateInput(t){if(t.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).");t.track&&this.inputTrack!==t.track&&(this.audioProcessorContext.chained=!0,this.inputTrack=t.track,this.emit(e.PROCESSOR_DESTINATION_EVENTS.ON_TRACK,this.inputTrack)),t.node&&this.inputNode!==t.node&&(this.audioProcessorContext.chained=!0,this.inputNode=t.node,this.emit(e.PROCESSOR_DESTINATION_EVENTS.ON_NODE,this.inputNode))}}class aT extends t.EventEmitter{set chained(e){this._chained=e}get chained(){return this._chained}constructor(e,t,r){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=r}async getConstraints(){return t.emitAsPromise(this,e.PROCESSOR_CONTEXT_EVENTS.REQUEST_CONSTRAINTS)}getAudioContext(){return this.audioContext}async requestApplyConstraints(i,o){var n;return r.logger.info("processor ".concat(o.name," requestApplyConstraints for ").concat(this.trackId)),i&&this.constraintsMap.set(o,i),t.emitAsPromiseNoResponse(this,e.PROCESSOR_CONTEXT_EVENTS.REQUEST_UPDATE_CONSTRAINTS,Array.from(eT(n=this.constraintsMap).call(n)))}async requestRevertConstraints(r){var i;if(this.constraintsMap.has(r))return this.constraintsMap.delete(r),t.emitAsPromiseNoResponse(this,e.PROCESSOR_CONTEXT_EVENTS.REQUEST_UPDATE_CONSTRAINTS,Array.from(eT(i=this.constraintsMap).call(i)))}registerStats(e,t,r){this.statsRegistry.find((r=>r.processorID===e.ID&&r.processorName===e.name&&r.type===t))||this.statsRegistry.push({processorName:e.name,processorID:e.ID,type:t,cb:r})}unregisterStats(e,t){const r=this.statsRegistry.findIndex((r=>r.processorID===e.ID&&r.processorName===e.name&&r.type===t));-1!==r&&this.statsRegistry.splice(r,1)}gatherStats(){const e=[];for(const{processorID:i,processorName:o,type:n,cb:a}of this.statsRegistry)try{const t=a();e.push({processorID:i,processorName:o,type:n,stats:t})}catch(e){r.logger.error(new t.AgoraRTCError(t.AgoraRTCErrorCode.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 r=t();r instanceof Hf&&(r=await r),e.push(rT(rT({},r),{},{direction:this.direction}))}catch(e){r.logger.error("gather extension usage error",e)}return e}getDirection(){return this.direction}}class sT extends t.EventEmitter{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 cT}setVolume(){}createOutputTrack(){throw new t.AgoraRTCError(t.AgoraRTCErrorCode.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 cT{disconnect(){}connect(){}}let dT=null;class uT{constructor(){this.state="open",this.trigger=void 0,this.tasks=[],r.logger.debug("[macro-task-queue] is created."),this.trigger=window.setTimeout((()=>{this.state="closed",r.logger.debug("[macro-task-queue] will be closed, all remaining tasks will execute. [".concat(this.tasks.map((e=>e.key)),"]")),this.trigger=void 0,this.tasks.forEach((e=>{let{func:t}=e;return t()})),this.tasks.length=0,r.logger.debug("[macro-task-queue] is closed.")}))}enqueue(e,t){"closed"!==this.state&&(this.tasks.push({key:e,func:t}),r.logger.debug("[macro-task-queue] is queued, current queue ".concat(this.tasks.length,". ").concat("string"==typeof e?e:"")))}runTask(e){if("closed"===this.state)return;const t=this.tasks.findIndex((t=>t.key===e));if(-1!==t){const i=this.tasks.splice(t,1);r.logger.debug("[macro-task-queue] is unqueued, current queue ".concat(this.tasks.length,". ").concat("string"==typeof e?e:"")),i[0].func()}}release(){this.trigger&&(this.state="closed",clearTimeout(this.trigger),this.trigger=void 0,this.tasks.length=0,r.logger.debug("[macro-task-queue] is closed."))}}function lT(e){return function(t,r,i){var o;const n=null!==(o=i.value)&&void 0!==o?o:i.get,a=function(){dT&&"open"===dT.state&&dT.runTask(e);for(var t=arguments.length,r=new Array(t),i=0;i<t;i++)r[i]=arguments[i];return null==n?void 0:n.apply(this,...r)};return i.value?i.value=a:i.get=a,i}}function hT(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}function pT(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?hT(Object(r),!0).forEach((function(t){Fl(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):hT(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}class gT extends zf{get _source(){return this._trackSource}set _source(e){this._trackSource=e}get processorContext(){return this._processorContext}set processorContext(e){this._processorContext=e}get processorDestination(){return this._processorDestination}set processorDestination(e){this._processorDestination=e}get isPlaying(){return this._useAudioElement?KE.isPlaying(this.getTrackId()):this._source.isPlayed}get __className__(){return"LocalAudioTrack"}constructor(r,i,o,n,a){super(r,o),this.trackMediaType="audio",this._encoderConfig=void 0,this._trackSource=void 0,this._enabled=!0,this._volume=100,this._useAudioElement=!1,this._bypassWebAudio=!1,this.processor=void 0,this._processorContext=void 0,this._processorDestination=void 0,this._getOriginVolumeLevel=void 0,this._encoderConfig=i,this._getOriginVolumeLevel=!!n;const s=()=>{this.processorContext=new aT(this._source.context,this.getTrackId(),"local"),this.processorDestination=new nT(this.processorContext),this.bindProcessorDestinationEvents(),this._source.on(e.AudioSourceEvents.UPDATE_SOURCE,(()=>{this.processor&&this.processor.updateInput({node:this._source.processSourceNode,context:this.processorContext})}))},c=a&&t.isSafari()&&!eE();if(t.getParameter("DISABLE_WEBAUDIO")?(this._source=new sT,this._useAudioElement=!0,this._bypassWebAudio=!0):c?this._source=new sT:(this._source=new IE(r,!1,this._getOriginVolumeLevel?r:void 0),t.getParameter("LOCAL_AUDIO_TRACK_USES_WEB_AUDIO")||(this._useAudioElement=!0)),s(),!t.getParameter("DISABLE_WEBAUDIO")&&c){(dT||(dT=new uT),dT).enqueue("INIT_WEBAUDIO",(()=>{this._source=new IE(r,!1,this._getOriginVolumeLevel?r:void 0),t.getParameter("LOCAL_AUDIO_TRACK_USES_WEB_AUDIO")||(this._useAudioElement=!0),s(),this.emit(e.AUDIO_TRACK_EVENT.UPDATE_TRACK_SOURCE)}))}}setVolume(i){t.checkValidNumber(i,"volume",0,1e3),this._volume=i,this._source.setVolume(i/100),this._useAudioElement&&KE.setVolume(this.getTrackId(),i);try{if(this._bypassWebAudio)return void r.logger.debug("[".concat(this.getTrackId(),"] setVolume returned because no pass through WebAudio."));const i=this._source.createOutputTrack();this._mediaStreamTrack!==i&&(this._mediaStreamTrack=i,t.emitAsPromiseNoResponse(this,e.TrackInternalEvent.NEED_REPLACE_TRACK,this).then((()=>{r.logger.debug("[".concat(this.getTrackId(),"] replace web audio track success"))})).catch((e=>{r.logger.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)throw new t.AgoraRTCError(t.AgoraRTCErrorCode.NOT_SUPPORTED,"your browser does not support setting the audio output device");await KE.setSinkID(this.getTrackId(),e)}async setEnabled(e,t,r){return this._setEnabled(e,t,r)}async _setEnabled(i,o,n){if(!n){if(i===this._enabled)return;this.stateCheck("enabled",i)}if(r.logger.info("[".concat(this.getTrackId(),"] start setEnabled"),i),i){this._originMediaStreamTrack.enabled=!0;try{n||(this._enabled=!0),await t.emitAsPromiseNoResponse(this,e.TrackInternalEvent.NEED_ENABLE_TRACK,this),r.logger.info("[".concat(this.getTrackId(),"] setEnabled to ").concat(i," success"))}catch(e){throw n||(this._enabled=!1),r.logger.error("[".concat(this.getTrackId(),"] setEnabled to true error"),e.toString()),e}}else{this._originMediaStreamTrack.enabled=!1,n||(this._enabled=!1);try{await t.emitAsPromiseNoResponse(this,e.TrackInternalEvent.NEED_DISABLE_TRACK,this)}catch(e){throw n||(this._enabled=!0),r.logger.error("[".concat(this.getTrackId(),"] setEnabled to false error"),e.toString()),e}}}async setMuted(i){i!==this._muted&&(this.stateCheck("muted",i),this._muted=i,this._originMediaStreamTrack.enabled=!i,r.logger.debug("[".concat(this.getTrackId(),"] start set muted: ").concat(i)),i?await t.emitAsPromiseNoResponse(this,e.TrackInternalEvent.NEED_MUTE_TRACK,this):await t.emitAsPromiseNoResponse(this,e.TrackInternalEvent.NEED_UNMUTE_TRACK,this))}getStats(){t.runOnce((()=>{r.logger.warning("[deprecated] LocalAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalAudioStats instead")}),"localAudioTrackGetStatsWarning");const i=t.emitAsInvokerNoResponse(this,e.TrackInternalEvent.GET_STATS);return i||pT({},ao)}setAudioFrameCallback(t){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:4096;if(!t)return this._source.removeAllListeners(e.AudioSourceEvents.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(r),this._source.removeAllListeners(e.AudioSourceEvents.ON_AUDIO_BUFFER),this._source.on(e.AudioSourceEvents.ON_AUDIO_BUFFER,(e=>t(e)))}play(){r.logger.debug("[".concat(this.getTrackId(),"] start audio playback")),this._useAudioElement?(r.logger.debug("[".concat(this.getTrackId(),"] start audio playback in element")),KE.play(this._mediaStreamTrack,this.getTrackId(),this._volume)):this._source.play()}stop(){r.logger.debug("[".concat(this.getTrackId(),"] stop audio playback")),this._useAudioElement?KE.stop(this.getTrackId()):this._source.stop()}close(){super.close(),this.unbindProcessorDestinationEvents(),this.unbindProcessorContextEvents(),this.unpipe(),this.processorDestination._source&&this.processorDestination._source.unpipe(),this._source.destroy()}_updatePlayerSource(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];r.logger.debug("[".concat(this.getTrackId(),"] update player source track")),e&&this._source.updateTrack(this._mediaStreamTrack),this._useAudioElement&&KE.updateTrack(this.getTrackId(),this._mediaStreamTrack)}async _updateOriginMediaStreamTrack(r,i){this._originMediaStreamTrack!==r&&(this._originMediaStreamTrack&&(this._originMediaStreamTrack.removeEventListener("ended",this._handleTrackEnded),i&&this._originMediaStreamTrack.stop()),r.addEventListener("ended",this._handleTrackEnded),this._originMediaStreamTrack=r,this._muted&&(this._originMediaStreamTrack.enabled=!1),this.processor&&this.processor.updateInput({track:r,context:this.processorContext}),this._mediaStreamTrack!==this._source.outputTrack?(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await t.emitAsPromiseNoResponse(this,e.TrackInternalEvent.NEED_REPLACE_TRACK,this)):this._source.updateTrack(this._originMediaStreamTrack),this._getOriginVolumeLevel&&this._source.updateOriginTrack(r))}renewMediaStreamTrack(e){return Hf.resolve(void 0)}pipe(e){if(this._bypassWebAudio)throw new t.AgoraRTCError(t.AgoraRTCErrorCode.INVALID_OPERATION,"Can not process AudioTrack when bypassWebAudio set to true.");if(this.processor===e)return e;if(e._source)throw new t.AgoraRTCError(t.AgoraRTCErrorCode.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(){this.processorDestination.on(e.PROCESSOR_DESTINATION_EVENTS.ON_TRACK,(async r=>{r?r!==this._mediaStreamTrack&&(this._mediaStreamTrack=r,this._updatePlayerSource(!1),this._source.processedNode=this._source.createMediaStreamSourceNode(r),await t.emitAsPromiseNoResponse(this,e.TrackInternalEvent.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await t.emitAsPromiseNoResponse(this,e.TrackInternalEvent.NEED_REPLACE_TRACK,this))})),this.processorDestination.on(e.PROCESSOR_DESTINATION_EVENTS.ON_NODE,(e=>{this._source.processedNode=e}))}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(e.PROCESSOR_DESTINATION_EVENTS.ON_TRACK),this.processorDestination.removeAllListeners(e.PROCESSOR_DESTINATION_EVENTS.ON_NODE)}unbindProcessorContextEvents(){this.processorContext.removeAllListeners(e.PROCESSOR_CONTEXT_EVENTS.REQUEST_UPDATE_CONSTRAINTS),this.processorContext.removeAllListeners(e.PROCESSOR_CONTEXT_EVENTS.REQUEST_CONSTRAINTS)}}Gf([lT("INIT_WEBAUDIO"),Wf("design:type",Object),Wf("design:paramtypes",[Object])],gT.prototype,"_source",null),Gf([lT("INIT_WEBAUDIO"),Wf("design:type",aT),Wf("design:paramtypes",[aT])],gT.prototype,"processorContext",null),Gf([lT("INIT_WEBAUDIO"),Wf("design:type",nT),Wf("design:paramtypes",[nT])],gT.prototype,"processorDestination",null),Gf([r.apiInvoke({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),Wf("design:type",Function),Wf("design:paramtypes",[Number]),Wf("design:returntype",void 0)],gT.prototype,"setVolume",null),Gf([r.apiInvoke({argsMap:(e,t)=>[e.getTrackId(),t]}),zE(),Wf("design:type",Function),Wf("design:paramtypes",[String]),Wf("design:returntype",Hf)],gT.prototype,"setPlaybackDevice",null),Gf([t.atom("LocalAudioTrack","_enabledMutex"),r.apiInvoke({argsMap:(e,t)=>[e.getTrackId(),t]}),zE(),Wf("design:type",Function),Wf("design:paramtypes",[Boolean,Object,Boolean]),Wf("design:returntype",Hf)],gT.prototype,"setEnabled",null),Gf([t.atom("LocalAudioTrack","_enabledMutex"),r.apiInvoke({argsMap:(e,t)=>[e.getTrackId(),t]}),zE(),Wf("design:type",Function),Wf("design:paramtypes",[Boolean]),Wf("design:returntype",Hf)],gT.prototype,"setMuted",null),Gf([zE(),Wf("design:type",Function),Wf("design:paramtypes",[]),Wf("design:returntype",Object)],gT.prototype,"getStats",null),Gf([zE(),Wf("design:type",Function),Wf("design:paramtypes",[Object,Number]),Wf("design:returntype",void 0)],gT.prototype,"setAudioFrameCallback",null),Gf([r.apiInvoke({argsMap:e=>[e.getTrackId()]}),zE(),Wf("design:type",Function),Wf("design:paramtypes",[]),Wf("design:returntype",void 0)],gT.prototype,"play",null),Gf([r.apiInvoke({argsMap:e=>[e.getTrackId()]}),zE(),Wf("design:type",Function),Wf("design:paramtypes",[]),Wf("design:returntype",void 0)],gT.prototype,"stop",null),Gf([r.apiInvoke({argsMap:e=>[e.getTrackId()]}),Wf("design:type",Function),Wf("design:paramtypes",[]),Wf("design:returntype",void 0)],gT.prototype,"close",null),Gf([r.apiInvoke({argsMap:(e,t)=>[e.getTrackId(),t.name]}),Wf("design:type",Function),Wf("design:paramtypes",[Object]),Wf("design:returntype",Object)],gT.prototype,"pipe",null),Gf([r.apiInvoke({argsMap:e=>[e.getTrackId()]}),Wf("design:type",Function),Wf("design:paramtypes",[]),Wf("design:returntype",void 0)],gT.prototype,"unpipe",null);class mT extends gT{get __className__(){return"MicrophoneAudioTrack"}constructor(r,i,o,n){super(r,i.encoderConfig?Ki(i.encoderConfig):{},n,t.getParameter("GET_VOLUME_OF_MUTED_AUDIO_TRACK"),!0),this._config=void 0,this._deviceName="default",this._constraints=void 0,this._originalConstraints=void 0,this._enabled=!0,this._config=i,this._constraints=o,this._originalConstraints=o,this._deviceName=r.label,"boolean"==typeof i.bypassWebAudio&&(this._bypassWebAudio=i.bypassWebAudio),(t.isIOS15()||t.isIOS16())&&Qf.bindInterruptDetectorTrack(this),this.on(e.AUDIO_TRACK_EVENT.UPDATE_TRACK_SOURCE,(()=>{this.bindProcessorContextEvents()})),eE()&&this.bindProcessorContextEvents()}async setDevice(e){if(r.logger.info("[".concat(this.getTrackId(),"] start set device to ").concat(e)),this._enabled)try{const t=await VE.getDeviceById(e),i={};i.audio=pT({},this._constraints),i.audio.deviceId={exact:e},this._originMediaStreamTrack.stop();let o=null;try{o=await wE(i,this.getTrackId())}catch(e){throw r.logger.error("[".concat(this.getTrackId(),"] setDevice failed"),e.toString()),o=await wE({audio:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(o.getAudioTracks()[0],!1),e}await this._updateOriginMediaStreamTrack(o.getAudioTracks()[0],!1),this._deviceName=t.label,this._config.microphoneId=e,this._constraints.deviceId={exact:e}}catch(e){throw r.logger.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}else try{const t=await VE.getDeviceById(e);this._deviceName=t.label,this._config.microphoneId=e,this._constraints.deviceId={exact:e}}catch(e){throw r.logger.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}r.logger.info("[".concat(this.getTrackId(),"] set device to ").concat(e," success"))}async setEnabled(i,o,n){if(o)return r.logger.debug("[".concat(this.getTrackId(),"] setEnabled false (do not close microphone)")),await super._setEnabled(i);if(!n){if(i===this._enabled)return;this.stateCheck("enabled",i)}if(r.logger.info("[".concat(this.getTrackId(),"] start setEnabled"),i),!i){var a;this._originMediaStreamTrack.onended=null,this._originMediaStreamTrack.stop(),null===(a=this._source.clonedTrack)||void 0===a||a.stop(),n||(this._enabled=!1);try{await t.emitAsPromiseNoResponse(this,e.TrackInternalEvent.NEED_DISABLE_TRACK,this)}catch(e){throw r.logger.error("[".concat(this.getTrackId(),"] setEnabled false failed"),e.toString()),e}return}const s=pT({},this._constraints),c=VE.searchDeviceIdByName(this._deviceName);c&&!s.deviceId&&(s.deviceId=c);try{n||(this._enabled=!0);const r=await wE({audio:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(r.getAudioTracks()[0],!1),await t.emitAsPromiseNoResponse(this,e.TrackInternalEvent.NEED_ENABLE_TRACK,this)}catch(e){throw n||(this._enabled=!1),r.logger.error("[".concat(this.getTrackId(),"] setEnabled true failed"),e.toString()),e}r.logger.info("[".concat(this.getTrackId(),"] setEnabled success"))}close(){super.close(),(t.isIOS15()||t.isIOS16())&&Qf.unbindInterruptDetectorTrack(this)}onTrackEnded(){if((t.isIOS()||t.isIpadOS())&&this._enabled&&!this._isClosed&&Qf.duringInterruption){const t=async()=>{Qf.off(e.AUDIO_CONTEXT_EVENT.IOS_INTERRUPTION_END,t),this._enabled&&!this._isClosed&&(r.logger.debug("[".concat(this.getTrackId(),"] try capture microphone media device for interrupted iOS device.")),await this.setEnabled(!1),await this.setEnabled(!0))};Qf.on(e.AUDIO_CONTEXT_EVENT.IOS_INTERRUPTION_END,t)}else r.logger.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(e.LocalTrackEvents.TRACK_ENDED)}async renewMediaStreamTrack(e){const t=e||this._constraints,r=VE.searchDeviceIdByName(this._deviceName);if(r&&!t.deviceId&&(t.deviceId=r),this._constraints=t,this._enabled){this._originMediaStreamTrack.stop();const e=await wE({audio:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getAudioTracks()[0],!0)}}bindProcessorContextEvents(){this.processorContext.on(e.PROCESSOR_CONTEXT_EVENTS.REQUEST_UPDATE_CONSTRAINTS,(async(e,t,r)=>{try{const r=Object.assign({},this._originalConstraints,...e);await this.renewMediaStreamTrack(r),t()}catch(e){r(e)}})),this.processorContext.on(e.PROCESSOR_CONTEXT_EVENTS.REQUEST_CONSTRAINTS,(async e=>{e(this._originMediaStreamTrack.getSettings())}))}}Gf([r.apiInvoke({argsMap:(e,t)=>[e.getTrackId(),t]}),zE(),Wf("design:type",Function),Wf("design:paramtypes",[String]),Wf("design:returntype",Hf)],mT.prototype,"setDevice",null),Gf([t.atom("MicrophoneAudioTrack","_enabledMutex"),r.apiInvoke({argsMap:(e,t,r)=>[e.getTrackId(),t,r]}),zE(),Wf("design:type",Function),Wf("design:paramtypes",[Boolean,Boolean,Boolean]),Wf("design:returntype",Hf)],mT.prototype,"setEnabled",null),Gf([r.apiInvoke({argsMap:e=>[e.getTrackId()]}),Wf("design:type",Function),Wf("design:paramtypes",[]),Wf("design:returntype",void 0)],mT.prototype,"close",null);class fT extends gT{get __className__(){return"BufferSourceAudioTrack"}constructor(t,r,i,o){super(r.createOutputTrack(),i,o),this.source=void 0,this._bufferSource=void 0,this.source=t,this._bufferSource=r,this._bufferSource.on(e.AudioSourceEvents.AUDIO_SOURCE_STATE_CHANGE,(t=>{this.safeEmit(e.LocalTrackEvents.SOURCE_STATE_CHANGE,t)}));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){t.checkValidNumber(e,"speed",0),this._bufferSource.setAudioBufferPlaybackSpeed(e)}}Gf([r.apiInvoke({argsMap:(e,t)=>[e.getTrackId(),t,e.duration]}),zE(),Wf("design:type",Function),Wf("design:paramtypes",[Object]),Wf("design:returntype",void 0)],fT.prototype,"startProcessAudioBuffer",null),Gf([r.apiInvoke({argsMap:e=>[e.getTrackId()]}),zE(),Wf("design:type",Function),Wf("design:paramtypes",[]),Wf("design:returntype",void 0)],fT.prototype,"pauseProcessAudioBuffer",null),Gf([r.apiInvoke({argsMap:e=>[e.getTrackId()]}),zE(),Wf("design:type",Function),Wf("design:paramtypes",[Number]),Wf("design:returntype",void 0)],fT.prototype,"seekAudioBuffer",null),Gf([r.apiInvoke({argsMap:e=>[e.getTrackId()]}),zE(),Wf("design:type",Function),Wf("design:paramtypes",[]),Wf("design:returntype",void 0)],fT.prototype,"resumeProcessAudioBuffer",null),Gf([r.apiInvoke({argsMap:e=>[e.getTrackId()]}),zE(),Wf("design:type",Function),Wf("design:paramtypes",[]),Wf("design:returntype",void 0)],fT.prototype,"stopProcessAudioBuffer",null),Gf([r.apiInvoke({argsMap:e=>[e.getTrackId()]}),Wf("design:type",Function),Wf("design:paramtypes",[]),Wf("design:returntype",void 0)],fT.prototype,"close",null),Gf([r.apiInvoke({argsMap:e=>[e.getTrackId()]}),zE(),Wf("design:type",Function),Wf("design:paramtypes",[Number]),Wf("design:returntype",void 0)],fT.prototype,"setAudioBufferPlaybackSpeed",null);class ET extends gT{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=$f().createMediaStreamDestination();super(e.stream.getAudioTracks()[0],void 0,t.getRandomString(8,"track-mix-")),this.trackList=void 0,this.destNode=void 0;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)?(r.logger.debug("add ".concat(e.getTrackId()," to mixing track")),e._source.outputNode.connect(this.destNode),this.trackList.push(e),this.updateEncoderConfig()):r.logger.debug("track ".concat(e.getTrackId()," is already added"))}removeAudioTrack(e){if(-1!==this.trackList.indexOf(e)){r.logger.debug("remove ".concat(e.getTrackId()," from mixing track"));try{e._source.outputNode.disconnect(this.destNode)}catch(e){}t.removeItemFromList(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(t){this._rtpTransceiver!==t&&(this._rtpTransceiver=t,this.trackList.forEach((r=>{r instanceof ET?r.emit(e.TrackEvents.TRANSCEIVER_UPDATED,t):r._updateRtpTransceiver(t)})))}}function TT(e){const r={};e.facingMode&&(r.facingMode=e.facingMode),e.cameraId&&(r.deviceId={exact:e.cameraId});const i=ji(e.encoderConfig);return null!=i.width&&(r.width=i.width),null!=i.height&&(r.height=i.height),!t.isLegacyChrome()&&i.frameRate&&(r.frameRate=i.frameRate),t.isEdge()&&"object"==typeof r.frameRate&&(r.frameRate.max=60),t.isFirefox()&&(r.frameRate={ideal:30,max:30}),r}function vT(e){const r={};e.screenSourceType&&(r.mediaSource=e.screenSourceType),e.extensionId&&t.isChrome()&&(r.extensionId=e.extensionId);const{displaySurface:i,selfBrowserSurface:o,surfaceSwitching:n,systemAudio:a}=e;(t.isAboveChrome(107)||t.isAboveEdge(107)||t.isAboveOpera(93))&&(i&&(t.checkValidEnum(i,"displaySurface",["browser","window","monitor"]),r.displaySurface=i),o?(t.checkValidEnum(o,"selfBrowserSurface",["exclude","include"]),r.selfBrowserSurface=o):r.selfBrowserSurface="include",n&&(t.checkValidEnum(n,"surfaceSwitching",["exclude","include"]),r.surfaceSwitching=n)),(t.isAboveChrome(105)||t.isAboveEdge(105)||t.isAboveOpera(91))&&a&&(t.checkValidEnum(a,"systemAudio",["exclude","include"]),r.systemAudio=a),e.electronScreenSourceId&&(r.sourceId=e.electronScreenSourceId);const s=e.encoderConfig?Hi(e.encoderConfig):null;return r.mandatory={chromeMediaSource:"desktop",maxWidth:s?s.width:void 0,maxHeight:s?s.height:void 0},s&&(s.frameRate&&("number"==typeof s.frameRate?(r.mandatory.maxFrameRate=s.frameRate,r.mandatory.minFrameRate=s.frameRate):(r.mandatory.maxFrameRate=s.frameRate.max||s.frameRate.ideal||s.frameRate.exact||void 0,r.mandatory.minFrameRate=s.frameRate.min||s.frameRate.ideal||s.frameRate.exact||void 0),r.frameRate=s.frameRate),s.width&&(r.width=s.width),s.height&&(r.height=s.height)),r}function _T(e){const r={};if(t.isLegacyChrome()||(void 0!==e.AGC&&(r.autoGainControl=e.AGC),void 0!==e.AEC&&(r.echoCancellation=e.AEC),void 0!==e.ANS&&(r.noiseSuppression=e.ANS,t.isChrome()&&e.ANS&&(r.googHighpassFilter=e.ANS))),e.encoderConfig){const t=Ki(e.encoderConfig);r.channelCount=t.stereo?2:1,r.sampleRate=t.sampleRate,r.sampleSize=t.sampleSize}return e.microphoneId&&(r.deviceId={exact:e.microphoneId}),t.isAndroid()&&(r.sampleRate=void 0),r}class yT extends bE{set currentState(t){t!==this._currentState&&(this._currentState=t,this.safeEmit(e.AudioSourceEvents.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):r.logger.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 ST=new Map;const AT=e=>{const r=document.createElement("canvas");return r.width=2,r.height=2,new Hf(((i,o)=>{r.toBlob((async e=>{if(r.remove(),e){const t=await bT(e);i({buffer:t,width:r.width,height:r.height})}else o(new t.AgoraRTCError(t.AgoraRTCErrorCode.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED))}),e,1)}))},bT=async e=>{const t=await e.arrayBuffer();return new Uint8Array(t)};class IT extends t.EventEmitter{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(),r.logger.debug("document visibility went ".concat(document.visibilityState)),this.emit("VISIBILITY_CHANGE",document.visibilityState)}))}}const kT=new IT;function CT(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}function OT(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?CT(Object(r),!0).forEach((function(t){Fl(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):CT(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}class RT{get videoElementStatus(){return this._videoElementStatus}set videoElementStatus(e){e!==this._videoElementStatus&&(r.logger.debug("[".concat(this.trackId,"] video-element-status change ").concat(this._videoElementStatus," => ").concat(e)),this._videoElementStatus=e)}constructor(i){this.trackId=void 0,this.config=void 0,this.onFirstVideoFrameDecoded=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.videoElementCheckInterval=void 0,this._videoElementStatus=e.MediaElementStatus.NONE,this.isGettingVideoDimensions=!1,this.startGetVideoDimensions=()=>{const e=()=>{if(this.isGettingVideoDimensions=!0,this.videoElement.videoWidth*this.videoElement.videoHeight>4)return r.logger.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"===Qf.curState&&(r.logger.debug("[track-".concat(this.trackId,"] video element paused, auto resume for ").concat(t.getOSWithVersion())),t.isAboveIOS15_1()?(this.videoElement.srcObject=null,this.videoElement.srcObject=new MediaStream([this.videoTrack]),this.videoElement.play()):(this.videoElement.pause(),this.videoElement.play()))},this.handleVideoEvents=i=>{switch(i.type){case"play":case"playing":this.startGetVideoDimensions(),this.videoElementStatus=e.MediaElementStatus.PLAYING;break;case"loadeddata":if(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=e.MediaElementStatus.CANPLAY;break;case"stalled":this.videoElementStatus=e.MediaElementStatus.STALLED;break;case"suspend":this.videoElementStatus=e.MediaElementStatus.SUSPEND;break;case"pause":this.videoElementStatus=e.MediaElementStatus.PAUSED,t.isIOS()||t.isIpadOS()||t.isSafari()&&this.autoplayFailed||!this.videoTrack||"live"!==this.videoTrack.readyState||(r.logger.debug("[track-".concat(this.trackId,"] video element paused, auto resume")),this.videoElement.play());break;case"waiting":this.videoElementStatus=e.MediaElementStatus.WAITING;break;case"abort":this.videoElementStatus=e.MediaElementStatus.ABORT;break;case"ended":this.videoElementStatus=e.MediaElementStatus.ENDED;break;case"emptied":this.videoElementStatus=e.MediaElementStatus.EMPTIED;break;case"error":{this.videoElementStatus=e.MediaElementStatus.ERROR;const t=this.videoElement.error;t&&r.logger.error("[".concat(this.trackId,"] media error, code: ").concat(t.code,", message: ").concat(t.message));break}case"timeupdate":{const e=performance.now();if(this.timeUpdatedCount+=1,this.timeUpdatedCount<10)return void(this.lastTimeUpdatedTime=e);const r=e-this.lastTimeUpdatedTime,i=this.lastTimeUpdatedTime;if(this.lastTimeUpdatedTime=e,kT.lastVisibleTime<kT.lastHiddenTime||i<kT.lastHiddenTime||i<kT.lastVisibleTime)return;for(r>t.getParameter("VIDEO_FREEZE_DURATION")&&(this.freezeTime+=r),this.playbackTime+=r;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&&(r.logger.debug("[track-".concat(this.trackId,"] video element paused, auto resume for ").concat(t.getOSWithVersion())),t.isAboveIOS15_1()?(this.videoElement.srcObject=null,this.videoElement.srcObject=new MediaStream([this.videoTrack]),this.videoElement.play()):(this.videoElement.pause(),this.videoElement.play()))},this.trackId=i.trackId,this.config=i,i.element instanceof HTMLVideoElement?this.videoElement=i.element:this.videoElement=document.createElement("video"),Qf.on(e.AUDIO_CONTEXT_EVENT.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),Qf.on(e.AUDIO_CONTEXT_EVENT.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(e){const i=this.videoElement.play();i&&i.catch&&i.catch((t=>{e&&GE(e,"video",t.message,this.trackId),"NotAllowedError"===t.name?(r.logger.warning("detected video element autoplay failed",t),this.autoplayFailed=!0,this.handleAutoPlayFailed()):r.logger.warning("[".concat(this.trackId,"] play warning: "),t)}));const o=t.getBrowserInfo();if(("Safari"===o.name&&15===Number(o.version)||t.isIOS15())&&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 r.logger.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 r=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 o=i.getContext("2d");return o?(o.drawImage(this.videoElement,0,0,i.width,i.height),new Hf(((o,n)=>{i.toBlob((async e=>{if(i.remove(),e){const t=await bT(e);o({buffer:t,width:i.width,height:i.height})}else n(new t.AgoraRTCError(t.AgoraRTCErrorCode.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED))}),e,r<0?.1:r>1?1:r)}))):await AT(e)}destroy(){Qf.off(e.AUDIO_CONTEXT_EVENT.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),Qf.off(e.AUDIO_CONTEXT_EVENT.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16),this.videoElement.srcObject=null,this.resetVideoElement(),this.freezeTimeCounterList=[]}initVideoElement(){if(this.videoElementStatus=e.MediaElementStatus.INIT,!this.videoElementCheckInterval&&(NT.forEach((e=>{this.videoElement.addEventListener(e,this.handleVideoEvents)})),this.videoElementCheckInterval=window.setInterval((()=>{t.isInPage(this.videoElement)||(this.videoElementStatus=e.MediaElementStatus.DESTROYED)}),1e3),t.getParameter("ENABLE_VIDEO_FRAME_CALLBACK"))){var i,o;let r;const n=(i,o)=>{if(this.videoElementStatus===e.MediaElementStatus.PLAYING){if(r){const e=o.presentationTime-r.presentationTime;e>t.getParameter("VIDEO_FREEZE_DURATION")&&kT.lastVisibleTime>=kT.lastHiddenTime&&r.timestamp>kT.lastVisibleTime&&r.timestamp>kT.lastHiddenTime&&(this.renderFreezeAccTime+=e)}r=OT(OT({},o),{},{timestamp:i})}var a,s;t.getParameter("ENABLE_VIDEO_FRAME_CALLBACK")&&(null===(a=(s=this.videoElement).requestVideoFrameCallback)||void 0===a||a.call(s,n))};null===(i=(o=this.videoElement).requestVideoFrameCallback)||void 0===i||i.call(o,n)}this.videoElement.controls=!1,this.videoElement.setAttribute("playsinline",""),t.isAndroid()&&(this.videoElement.poster="noposter");const n=t.getBrowserInfo();if("Safari"===n.name&&15===Number(n.version)||t.isIOS15()||!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,t.isFirefox()&&this.videoElement.load())}else this.videoElement.srcObject=this.videoTrack?new MediaStream([this.videoTrack]):null,t.isFirefox()&&this.videoElement.load();const a=this.videoElement.play();void 0!==a&&a.catch((e=>{r.logger.debug("[".concat(this.trackId,"] playback interrupted"),e.toString())}))}resetVideoElement(){NT.forEach((e=>{this.videoElement&&this.videoElement.removeEventListener(e,this.handleVideoEvents)})),this.videoElementCheckInterval&&(window.clearInterval(this.videoElementCheckInterval),this.videoElementCheckInterval=void 0),this.videoElementStatus=e.MediaElementStatus.NONE}handleAutoPlayFailed(){const e=i=>{i.preventDefault(),this.videoElement.play().then((()=>{r.logger.debug("[".concat(this.trackId,"] Video element for trackId:").concat(this.trackId," autoplay resumed."))})).catch((e=>{r.logger.error(e)})),this.autoplayFailed=!1,t.isAndroidChromium()?document.body.removeEventListener("click",e,!0):(document.body.removeEventListener("touchstart",e,!0),document.body.removeEventListener("mousedown",e,!0))};t.isAndroidChromium()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0)),FE()}}const NT=["play","playing","loadeddata","canplay","pause","stalled","suspend","waiting","abort","emptied","ended","timeupdate","error"];class wT extends RT{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 r=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,r):await AT(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",t.getParameter("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 DT(e){return new Hf(((r,i)=>{let o=!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 a=t.isIOS()?"canplay":"playing";n.addEventListener(a,(()=>{const e=n.videoWidth,i=n.videoHeight;!e&&t.isFirefox()||(o=!0,n.srcObject=null,n.remove(),r([e,i]))})),n.srcObject=new MediaStream([e]),n.play().catch(t.noop),setTimeout((()=>{o||(n.srcObject=null,n.remove(),r([n.videoWidth,n.videoHeight]))}),4e3)}))}function PT(e,t,r,i){let o;const n=200*Math.pow(r/15,.6)*Math.pow(e*t/640/360,.75),a=n;if("STANDARD_BITRATE"===i)o=4*n;else{if("COMPATIABLE_BITRATE"!==i)return;o=2*n}return[Math.floor(o),Math.floor(a)]}function MT(e,t){if("VideoFrame"in window&&"TransformStream"in window&&sE().supportWebRTCInsertableStream){const r=new MediaStreamTrackProcessor(e),i=new MediaStreamTrackGenerator({kind:"video"});let o,n,a=Date.now();const s=()=>{c&&(clearInterval(c),c=void 0),o&&(o.close(),o=void 0),e.stop(),n=void 0,i.removeEventListener("ended",s)};let c=window.setInterval((()=>{if(n&&o&&Date.now()-a>(null!=t?t:1e3))try{"live"===i.readyState?n.enqueue(o.clone()):s()}catch(e){s()}}),null!=t?t:1e3);const d=new TransformStream({transform:(e,t)=>{"live"===i.readyState?(n=t,a=Date.now(),void 0===o?(o=e,t.enqueue(e.clone())):(t.enqueue(o),o=e)):e.close()}});return i.addEventListener("ended",s),r.readable.pipeThrough(d).pipeTo(i.writable),i}}function LT(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}function VT(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?LT(Object(r),!0).forEach((function(t){Fl(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):LT(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}class xT extends zf{get isPlaying(){return!(!this._player||this._player.videoElementStatus!==e.MediaElementStatus.PLAYING)}get processorContext(){return this._processorContext}set processorContext(e){this._processorContext=e}get __className__(){return"LocalVideoTrack"}constructor(i,o,n,a,s,c){if(super(i,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,t.isSafari()){const{width:e,height:t}=i.getSettings();this._videoWidth=e,this._videoHeight=t}else this.updateMediaStreamTrackResolution();if(this._encoderConfig=o,this._scalabilityMode=n,this._optimizationMode=a,this._hints=c||[],-1===this._hints.indexOf(e.TrackHint.SCREEN_TRACK))this.updateBitrateFromProfile();else if(t.isBetweenBrowser(t.BrowserName.CHROME,115)&&t.isWindows()){const e=MT(i);e&&(r.logger.info("local screen video track begin to inject frame"),this._mediaStreamTrack=e)}o&&-1!==this._hints.indexOf(e.TrackHint.CUSTOM_TRACK)&&this.setEncoderConfiguration(o),this.processorContext=new oT(this.getTrackId(),"local"),this.processorDestination=new iT(this.processorContext),this.bindProcessorDestinationEvents()}play(i){let o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("string"==typeof i){const e=document.getElementById(i);e?i=e:(r.logger.warning("[".concat(this.getTrackId(),'] can not find "#').concat(i,'" element, use document.body')),i=document.body)}r.logger.debug("[".concat(this.getTrackId(),"] start video playback in ").concat(i instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement"),JSON.stringify(o));const n=VT(VT(VT({},this._getDefaultPlayerConfig()),o),{},{trackId:this.getTrackId(),element:i});this._player?this._player.updateConfig(n):(i instanceof HTMLVideoElement?this._player=new RT(n):this._player=new wT(n),this._player.updateVideoTrack(this._mediaStreamTrack)),this._player.play(),this._videoVisibleTimer&&window.clearInterval(this._videoVisibleTimer),this._clearPreviousVideoVisibleStatus(),this._videoVisibleTimer=window.setInterval((()=>{try{const t=this.getVideoElementVisibleStatus();this.safeEmit(e.LocalTrackEvents.VIDEO_ELEMENT_VISIBLE_STATUS,t)}catch(e){}}),t.getParameter("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,r.logger.debug("[".concat(this.getTrackId(),"] stop video playback")))}async setEnabled(i,o){if(!o){if(i===this._enabled)return;this.stateCheck("enabled",i)}if(r.logger.info("[".concat(this.getTrackId(),"] start setEnabled"),i),!i){this._originMediaStreamTrack.enabled=!1;try{await t.emitAsPromiseNoResponse(this,e.TrackInternalEvent.NEED_DISABLE_TRACK,this)}catch(e){throw r.logger.error("[".concat(this.getTrackId(),"] setEnabled to false error"),e.toString()),e}return o||(this._enabled=!1),void r.logger.info("[".concat(this.getTrackId(),"] setEnabled to false success"))}this._originMediaStreamTrack.enabled=!0;try{await t.emitAsPromiseNoResponse(this,e.TrackInternalEvent.NEED_ENABLE_TRACK,this)}catch(e){throw r.logger.error("[".concat(this.getTrackId(),"] setEnabled to true error"),e.toString()),e}r.logger.info("[".concat(this.getTrackId(),"] setEnabled to true success")),o||(this._enabled=!0)}async setMuted(i){i!==this._muted&&(this.stateCheck("muted",i),this._muted=i,this._originMediaStreamTrack.enabled=!i,r.logger.debug("[".concat(this.getTrackId(),"] start set muted: ").concat(i)),i?await t.emitAsPromiseNoResponse(this,e.TrackInternalEvent.NEED_MUTE_TRACK,this):await t.emitAsPromiseNoResponse(this,e.TrackInternalEvent.NEED_UNMUTE_TRACK,this))}async setEncoderConfiguration(i,o){if(!this._enabled)throw new t.AgoraRTCError(t.AgoraRTCErrorCode.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");if("720p_auto"===i?this.startMonitorStats():this._statsTimer&&(window.clearInterval(this._statsTimer),this._statsTimer=null),i=ji(i),this._forceBitrateLimit&&(i.bitrateMax=this._forceBitrateLimit.max_bitrate?this._forceBitrateLimit.max_bitrate:i.bitrateMax,i.bitrateMin=this._forceBitrateLimit.min_bitrate?this._forceBitrateLimit.min_bitrate:i.bitrateMin),i.width||i.height||i.frameRate){const e=TT({encoderConfig:i});(t.isSafari()||t.isIOS()||t.isIpadOS())&&(e.deviceId=void 0),r.logger.debug("[".concat(this.getTrackId(),"] setEncoderConfiguration applyConstraints"),JSON.stringify(i),JSON.stringify(e));try{await this._originMediaStreamTrack.applyConstraints(e),this.updateMediaStreamTrackResolution()}catch(e){const i=new t.AgoraRTCError(t.AgoraRTCErrorCode.UNEXPECTED_ERROR,e.toString());throw r.logger.error("[".concat(this.getTrackId(),"] applyConstraints error"),i.toString()),i}}this._encoderConfig=i,-1===this._hints.indexOf(e.TrackHint.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await t.emitAsPromiseNoResponse(this,e.TrackInternalEvent.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(r.logger)}}getStats(){t.runOnce((()=>{r.logger.warning("[deprecated] LocalVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalVideoStats instead")}),"localVideoTrackGetStatsWarning");const i=t.emitAsInvokerNoResponse(this,e.TrackInternalEvent.GET_STATS);return i||VT({},so)}async setBeautyEffect(e){r.logger.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 AT(e)}async setBitrateLimit(i){if(r.logger.debug("[".concat(this.getTrackId(),"] set bitrate limit, ").concat(JSON.stringify(i))),i){this._forceBitrateLimit=i,this._encoderConfig&&(this._encoderConfig.bitrateMax?this._encoderConfig.bitrateMax=this._encoderConfig.bitrateMax<i.max_bitrate?this._encoderConfig.bitrateMax:i.max_bitrate:this._encoderConfig.bitrateMax=i.max_bitrate,this._encoderConfig.bitrateMin,this._encoderConfig.bitrateMin=i.min_bitrate);try{await t.emitAsPromiseNoResponse(this,e.TrackInternalEvent.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(r.logger)}}}async setOptimizationMode(i){if("motion"!==i&&"detail"!==i&&"balanced"!==i)return void r.logger.error(t.AgoraRTCErrorCode.INVALID_PARAMS,"optimization mode must be motion, detail or balanced");const o=this._optimizationMode;try{this._optimizationMode=i,await t.emitAsPromiseNoResponse(this,e.TrackInternalEvent.SET_OPTIMIZATION_MODE,this)}catch(e){throw this._optimizationMode=o,r.logger.error("[".concat(this.getTrackId(),"] set optimization mode failed"),e.toString()),e}r.logger.info("[".concat(this.getTrackId(),"] set optimization mode success (").concat(i,")"))}setScalabiltyMode(e){if(1===e.numSpatialLayers&&1!==e.numTemporalLayers)return r.logger.error(t.AgoraRTCErrorCode.INVALID_PARAMS,"scalability mode currently not supported, no SVC."),void(this._scalabilityMode={numSpatialLayers:1,numTemporalLayers:1});this._scalabilityMode=e,r.logger.info("[".concat(this.getTrackId(),"] set scalability mode success (").concat(e,")"))}updateMediaStreamTrackResolution(){DT(this._originMediaStreamTrack).then((e=>{let[t,r]=e;this._videoHeight=r,this._videoWidth=t})).catch(t.noop)}_updatePlayerSource(){this._player&&this._player.updateVideoTrack(this._mediaStreamTrack)}_getDefaultPlayerConfig(){return{fit:"contain"}}async setSenderConfiguration(i){if(!this._enabled)throw new t.AgoraRTCError(t.AgoraRTCErrorCode.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");r.logger.debug("[".concat(this.getTrackId(),"] setSenderConfiguration applyConstraints"),JSON.stringify(i)),i=ji(i),this._forceBitrateLimit&&(i.bitrateMax=this._forceBitrateLimit.max_bitrate?this._forceBitrateLimit.max_bitrate:i.bitrateMax,i.bitrateMin=this._forceBitrateLimit.min_bitrate?this._forceBitrateLimit.min_bitrate:i.bitrateMin),this._encoderConfig=i,-1===this._hints.indexOf(e.TrackHint.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await t.emitAsPromiseNoResponse(this,e.TrackInternalEvent.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(r.logger)}}updateBitrateFromProfile(){if(!this._encoderConfig)return;const{width:e,height:i,frameRate:o}=this.getMediaStreamTrackSettings();if(!e||!i||!o)return;const[n,a]=PT(e,i,o,t.getParameter("BITRATE_ADAPTER_TYPE"))||[void 0,void 0];this._encoderConfig.bitrateMin||this._encoderConfig.bitrateMax||(this._encoderConfig.bitrateMin=a,this._encoderConfig.bitrateMax=n,r.logger.debug("[".concat(this.getTrackId(),"] update bitrate from profile, [w: ").concat(e,", h: ").concat(i,", fps: ").concat(o,"] => [brMax: ").concat(n,", brMin: ").concat(a,"]")))}getVideoElementVisibleStatus(){try{var e,i;const o=null==this||null===(e=this._player)||void 0===e?void 0:e.getContainerElement(),n={track:this,element:null==this||null===(i=this._player)||void 0===i?void 0:i.getVideoElement(),slot:null==o?void 0:o.parentElement},{element:a,slot:s}=n;if(this.isPlaying&&a instanceof HTMLVideoElement&&s instanceof HTMLElement){const e=t.elementVisibleChecker.checkOneElementVisible(a),i=Object.assign({},e);if(i.visible!==this._previousVideoVisibleStatus){this._previousVideoVisibleStatus=i.visible;const e=r.report.reportApiInvoke(null,{tag:t.AgoraAPITag.TRACER,name:t.AgoraAPIName.LOCAL_VIDEO_TRACK_GET_VIDEO_VISIBLE,options:[this.getTrackId()]});i.visible?e.onSuccess("Video is visible"):e.onSuccess("Invisible because of ".concat(i.reason))}return i}return}catch(e){throw new t.AgoraRTCError(t.AgoraRTCErrorCode.GET_VIDEO_ELEMENT_VISIBLE_ERROR,e.message)}}async renewMediaStreamTrack(e){}pipe(e){if(this.processor===e)return e;if(e._source)throw new t.AgoraRTCError(t.AgoraRTCErrorCode.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 i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],o=this._encoderConfig;e&&(o=VT(VT({},o),ji(e))),o=t.safeCloneJson(o);const n=t.getRandomString(8,"track-video-cloned-"),a=new xT(i?this._mediaStreamTrack.clone():this._mediaStreamTrack,o,t.safeCloneJson(this._scalabilityMode),this._optimizationMode,n,t.safeCloneJson(this._hints));return e&&o&&a.setEncoderConfiguration(o),r.logger.debug("clone video track from ".concat(this.getTrackId()," to ").concat(n,", clone ").concat(i)),a}async replaceTrack(e,r){if(!(e instanceof MediaStreamTrack))throw new t.AgoraRTCError(t.AgoraRTCErrorCode.INVALID_PARAMS,"track should be an instance of MediaStreamTrack");if("video"!==e.kind)throw new t.AgoraRTCError(t.AgoraRTCErrorCode.INVALID_PARAMS,"track should be a video MediaStreamTrack");await this._updateOriginMediaStreamTrack(e,r,!0),this.updateMediaStreamTrackResolution()}startMonitorStats(){if(!t.isSafari()&&!t.isIOS())return;this._statsTimer&&window.clearInterval(this._statsTimer);let i=2,o=Ui[i];let n=-1;let a=Date.now();const s=e=>{e>2||e<0||(a=Date.now(),o=Ui[e],this.setSenderConfiguration(o))};this.isUseScaleResolutionDownBy=!0,this._statsTimer=window.setInterval((()=>{const c=this.getStats(),d=t.emitAsInvokerNoResponse(this,e.TrackInternalEvent.GET_RTC_STATS);if(c.sendPackets>0&&d){-1===n&&(n=Date.now());const e=Date.now();if(e-n<1e3||e-a<t.getParameter("PROFILE_SWITCH_INTERVAL"))return;const u=c.sendFrameRate,l=.6*o.frameRate,h=.9*o.frameRate;"number"==typeof u&&u>0&&u<l?i>0&&(i--,s(i),r.logger.debug("[".concat(this.getTrackId(),"] step down for fps ").concat(u,", switchProfile to ").concat(i))):d.OutgoingAvailableBandwidth<o.bitrateMin?i>0&&(i--,s(i),r.logger.debug("[".concat(this.getTrackId(),"] step down for OutgoingAvailableBandwidth ").concat(d.OutgoingAvailableBandwidth,", bitrateMin ").concat(o.bitrateMin,", switchProfile to ").concat(i))):"number"==typeof u&&u>h&&i<Ui.length-1&&d.OutgoingAvailableBandwidth>1.2*Ui[i+1].bitrateMin&&(i++,s(i),r.logger.debug("[".concat(this.getTrackId(),"] step up for fps ").concat(u,", OutgoingAvailableBandwidth ").concat(d.OutgoingAvailableBandwidth,", switchProfile to ").concat(i)))}}),t.getParameter("CHECK_LOCAL_STATS_INTERVAL"))}bindProcessorDestinationEvents(){this.processorDestination.on(e.PROCESSOR_DESTINATION_EVENTS.ON_TRACK,(async r=>{r?r!==this._mediaStreamTrack&&(this._mediaStreamTrack=r,this._updatePlayerSource(),await t.emitAsPromiseNoResponse(this,e.TrackInternalEvent.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await t.emitAsPromiseNoResponse(this,e.TrackInternalEvent.NEED_REPLACE_TRACK,this))}))}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(e.PROCESSOR_DESTINATION_EVENTS.ON_TRACK)}unbindProcessorContextEvents(){this.processorContext.removeAllListeners(e.PROCESSOR_CONTEXT_EVENTS.REQUEST_UPDATE_CONSTRAINTS),this.processorContext.removeAllListeners(e.PROCESSOR_CONTEXT_EVENTS.REQUEST_CONSTRAINTS)}}Gf([r.apiInvoke({argsMap:(e,t,r)=>[e.getTrackId(),"string"==typeof t?t:t instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement",r]}),zE(),Wf("design:type",Function),Wf("design:paramtypes",[Object,Object]),Wf("design:returntype",void 0)],xT.prototype,"play",null),Gf([r.apiInvoke({argsMap:e=>[e.getTrackId()]}),Wf("design:type",Function),Wf("design:paramtypes",[]),Wf("design:returntype",void 0)],xT.prototype,"stop",null),Gf([t.atom("LocalVideoTrack","_enabledMutex"),r.apiInvoke({argsMap:(e,t)=>[e.getTrackId(),t]}),zE(),Wf("design:type",Function),Wf("design:paramtypes",[Boolean,Boolean]),Wf("design:returntype",Hf)],xT.prototype,"setEnabled",null),Gf([t.atom("LocalVideoTrack","_enabledMutex"),r.apiInvoke({argsMap:(e,t)=>[e.getTrackId(),t]}),zE(),Wf("design:type",Function),Wf("design:paramtypes",[Boolean]),Wf("design:returntype",Hf)],xT.prototype,"setMuted",null),Gf([r.apiInvoke({argsMap:(e,t)=>[e.getTrackId(),t]}),zE(),Wf("design:type",Function),Wf("design:paramtypes",[Object,Boolean]),Wf("design:returntype",Hf)],xT.prototype,"setEncoderConfiguration",null),Gf([zE(),Wf("design:type",Function),Wf("design:paramtypes",[]),Wf("design:returntype",Object)],xT.prototype,"getStats",null),Gf([r.apiInvoke({argsMap:(e,t,r)=>[e.getTrackId(),t,r]}),zE(),Wf("design:type",Function),Wf("design:paramtypes",[Boolean,Object]),Wf("design:returntype",Hf)],xT.prototype,"setBeautyEffect",null),Gf([zE(),Wf("design:type",Function),Wf("design:paramtypes",[]),Wf("design:returntype",ImageData)],xT.prototype,"getCurrentFrameData",null),Gf([zE(),Wf("design:type",Function),Wf("design:paramtypes",[String,Number]),Wf("design:returntype",Hf)],xT.prototype,"getCurrentFrameImage",null),Gf([zE(),Wf("design:type",Function),Wf("design:paramtypes",[Object]),Wf("design:returntype",Hf)],xT.prototype,"setBitrateLimit",null),Gf([zE(),Wf("design:type",Function),Wf("design:paramtypes",[String]),Wf("design:returntype",Hf)],xT.prototype,"setOptimizationMode",null),Gf([zE(),Wf("design:type",Function),Wf("design:paramtypes",[Object]),Wf("design:returntype",void 0)],xT.prototype,"setScalabiltyMode",null),Gf([zE(),Wf("design:type",Function),Wf("design:paramtypes",[]),Wf("design:returntype",void 0)],xT.prototype,"updateMediaStreamTrackResolution",null),Gf([r.apiInvoke({argsMap:(e,t)=>[e.getTrackId(),t.name]}),Wf("design:type",Function),Wf("design:paramtypes",[Object]),Wf("design:returntype",Object)],xT.prototype,"pipe",null),Gf([r.apiInvoke({argsMap:e=>[e.getTrackId()]}),Wf("design:type",Function),Wf("design:paramtypes",[]),Wf("design:returntype",void 0)],xT.prototype,"unpipe",null),Gf([r.apiInvoke({argsMap:e=>[e.getTrackId()]}),Wf("design:type",Function),Wf("design:paramtypes",[]),Wf("design:returntype",void 0)],xT.prototype,"close",null),Gf([r.apiInvoke({argsMap:(e,t,r)=>[e.getTrackId(),t.label,r]}),Wf("design:type",Function),Wf("design:paramtypes",[MediaStreamTrack,Boolean]),Wf("design:returntype",Hf)],xT.prototype,"replaceTrack",null),Gf([r.apiInvoke(),Wf("design:type",Function),Wf("design:paramtypes",[]),Wf("design:returntype",void 0)],xT.prototype,"startMonitorStats",null);class UT extends xT{get __className__(){return"CameraVideoTrack"}constructor(i,o,n,a,s,c){super(i,ji(o.encoderConfig),a,s,c),this._config=void 0,this._originalConstraints=void 0,this._constraints=void 0,this._enabled=!0,this._deviceName="default",this.tryResumeVideoForIOS15_16WeChat=async()=>{(t.isIOS15()||t.isIOS16())&&!t.isAboveIOS15_2()&&t.isWechatBrowser()&&this._enabled&&!this._isClosed&&(r.logger.debug("[".concat(this.getTrackId(),"] try capture camera media device for interrupted iOS 15 device on WeChat.")),await this.renewMediaStreamTrack())},this._config=o,this._originalConstraints=n,this._constraints=n,this._deviceName=i.label,this._encoderConfig=ji(this._config.encoderConfig),Qf.on(e.AUDIO_CONTEXT_EVENT.IOS_15_16_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),Qf.on(e.AUDIO_CONTEXT_EVENT.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(r.logger.info("[".concat(this.getTrackId(),"] set device to ").concat(e)),this._enabled)try{const t=await VE.getDeviceById(e),i={};i.video=VT({},this._constraints),i.video.deviceId={exact:e},i.video.facingMode=void 0,this._originMediaStreamTrack.stop();let o=null;try{o=await wE(i,this.getTrackId())}catch(e){throw r.logger.error("[".concat(this.getTrackId(),"] setDevice failed"),e.toString()),o=await wE({video:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(o.getVideoTracks()[0],!1),e}await this._updateOriginMediaStreamTrack(o.getVideoTracks()[0],!1),this.updateMediaStreamTrackResolution(),this._deviceName=t.label,this._config.cameraId=e,this._constraints.deviceId={exact:e}}catch(e){throw r.logger.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}else try{const t=await VE.getDeviceById(e);this._deviceName=t.label,this._config.cameraId=e,this._constraints.deviceId={exact:e}}catch(e){throw r.logger.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}r.logger.info("[".concat(this.getTrackId(),"] setDevice success"))}async _setDeviceByFacingModel(e){r.logger.info("[".concat(this.getTrackId(),"] set facingMode ").concat(e));const t={video:VT(VT({},this._constraints),{},{deviceId:void 0,facingMode:{exact:e}})};if(this._enabled){this._originMediaStreamTrack.stop();let e=null;try{e=await wE(t,this.getTrackId())}catch(t){throw r.logger.error("[".concat(this.getTrackId(),"] setDeviceByFacingModel failed"),t.toString()),e=await wE({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=VT({},t.video),r.logger.info("[".concat(this.getTrackId(),"] setDeviceByFacingModel success"))}async setEnabled(i,o){if(!o){if(i===this._enabled)return;this.stateCheck("enabled",i)}if(r.logger.info("[".concat(this.getTrackId(),"] start setEnabled"),i),i){try{if(this.isExternalTrack)this._originMediaStreamTrack.enabled=!0;else{const e=await wE({video:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!1)}await t.emitAsPromiseNoResponse(this,e.TrackInternalEvent.NEED_ENABLE_TRACK,this)}catch(e){throw r.logger.error("[".concat(this.getTrackId(),"] setEnabled true error"),e.toString()),e}this.updateMediaStreamTrackResolution(),r.logger.info("[".concat(this.getTrackId(),"] setEnabled to true success")),o||(this._enabled=!0)}else{this.isExternalTrack?this._originMediaStreamTrack.enabled=!1:(this._originMediaStreamTrack.onended=null,this._originMediaStreamTrack.stop()),o||(this._enabled=!1);try{await t.emitAsPromiseNoResponse(this,e.TrackInternalEvent.NEED_DISABLE_TRACK,this)}catch(e){throw r.logger.error("[".concat(this.getTrackId(),"] setEnabled to false error"),e.toString()),e}r.logger.info("[".concat(this.getTrackId(),"] setEnabled to false success"))}}async setEncoderConfiguration(i,o){if(!this._enabled)throw new t.AgoraRTCError(t.AgoraRTCErrorCode.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");"720p_auto"===i?this.startMonitorStats():this._statsTimer&&(window.clearInterval(this._statsTimer),this._statsTimer=null),i=ji(i),this._forceBitrateLimit&&(i.bitrateMax=this._forceBitrateLimit.max_bitrate?this._forceBitrateLimit.max_bitrate:i.bitrateMax,i.bitrateMin=this._forceBitrateLimit.min_bitrate?this._forceBitrateLimit.min_bitrate:i.bitrateMin);const n=t.jsonClone(this._config);n.encoderConfig=i;const a=TT(n);(t.isSafari()||t.isIOS()||t.isIpadOS())&&(a.deviceId=void 0),r.logger.debug("[".concat(this.getTrackId(),"] setEncoderConfiguration applyConstraints"),JSON.stringify(i),JSON.stringify(a));try{await this._originMediaStreamTrack.applyConstraints(a),this.updateMediaStreamTrackResolution()}catch(e){const i=new t.AgoraRTCError(t.AgoraRTCErrorCode.UNEXPECTED_ERROR,e.toString());throw r.logger.error("[".concat(this.getTrackId(),"] applyConstraints error"),i.toString()),i}this._config=n,this._constraints=a,this._originalConstraints=a,this._encoderConfig=i,-1===this._hints.indexOf(e.TrackHint.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await t.emitAsPromiseNoResponse(this,e.TrackInternalEvent.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(r.logger)}}_getDefaultPlayerConfig(){return{mirror:!0,fit:"cover"}}onTrackEnded(){if((t.isIOS()||t.isIpadOS())&&this._enabled&&!this._isClosed&&Qf.duringInterruption){const t=async()=>{Qf.off(e.AUDIO_CONTEXT_EVENT.IOS_INTERRUPTION_END,t),this._enabled&&!this._isClosed&&(r.logger.debug("[".concat(this.getTrackId(),"] try capture camera media device for interrupted iOS device.")),await this.setEnabled(!1),await this.setEnabled(!0))};Qf.on(e.AUDIO_CONTEXT_EVENT.IOS_INTERRUPTION_END,t)}else r.logger.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(e.LocalTrackEvents.TRACK_ENDED)}async renewMediaStreamTrack(e){const t=e||this._constraints,r=VE.searchDeviceIdByName(this._deviceName);if(r&&!t.deviceId&&(t.deviceId={exact:r}),this._enabled){const e=await wE({video:t},this.getTrackId());this._constraints=t,await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!0),this.updateMediaStreamTrackResolution()}}close(){super.close(),Qf.off(e.AUDIO_CONTEXT_EVENT.IOS_15_16_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),Qf.off(e.AUDIO_CONTEXT_EVENT.IOS_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat)}clone(e){let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],o=this._encoderConfig;e&&(o=VT(VT({},o),ji(e))),o=t.safeCloneJson(o);const n=t.getRandomString(8,"track-cam-cloned-"),a=new UT(i?this._mediaStreamTrack.clone():this._mediaStreamTrack,t.safeCloneJson(VT(VT({},this._config),{},{encoderConfig:o})),t.safeCloneJson(this._constraints),t.safeCloneJson(this._scalabilityMode),this._optimizationMode,n);return e&&o&&a.setEncoderConfiguration(o),r.logger.debug("clone track from ".concat(this.getTrackId()," to ").concat(n,", clone ").concat(i)),a}bindProcessorContextEvents(){this.processorContext.on(e.PROCESSOR_CONTEXT_EVENTS.REQUEST_UPDATE_CONSTRAINTS,(async(e,t,r)=>{try{const r=Object.assign({},this._originalConstraints,...e);await this.renewMediaStreamTrack(r),t()}catch(e){r(e)}})),this.processorContext.on(e.PROCESSOR_CONTEXT_EVENTS.REQUEST_CONSTRAINTS,(async e=>{e(this._originMediaStreamTrack.getSettings())}))}}function BT(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}function FT(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?BT(Object(r),!0).forEach((function(t){Fl(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):BT(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function jT(e,t,i,o){i.optimizationMode&&(o&&o.width&&o.height?(i.encoderConfig=FT(FT({},o),{},{bitrateMin:o.bitrateMin,bitrateMax:o.bitrateMax}),"motion"!==i.optimizationMode&&"detail"!==i.optimizationMode||(t.contentHint=i.optimizationMode,t.contentHint===i.optimizationMode?r.logger.debug("[".concat(e,"] set content hint to"),i.optimizationMode):r.logger.debug("[".concat(e,"] set content hint failed")))):r.logger.warning("[".concat(e,"] can not apply optimization mode bitrate config, no encoderConfig")))}function HT(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}function GT(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?HT(Object(r),!0).forEach((function(t){Fl(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):HT(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}Gf([r.apiInvoke({argsMap:(e,t)=>[e.getTrackId(),t]}),zE(),Wf("design:type",Function),Wf("design:paramtypes",[Object]),Wf("design:returntype",Hf)],UT.prototype,"setDevice",null),Gf([t.atom("CameraVideoTrack","_enabledMutex"),r.apiInvoke({argsMap:(e,t)=>[e.getTrackId(),t]}),zE(),Wf("design:type",Function),Wf("design:paramtypes",[Boolean,Boolean]),Wf("design:returntype",Hf)],UT.prototype,"setEnabled",null),Gf([r.apiInvoke({argsMap:(e,t)=>[e.getTrackId(),t]}),zE(),Wf("design:type",Function),Wf("design:paramtypes",[Object,Boolean]),Wf("design:returntype",Hf)],UT.prototype,"setEncoderConfiguration",null),Gf([r.apiInvoke({argsMap:e=>[e.getTrackId()]}),Wf("design:type",Function),Wf("design:paramtypes",[]),Wf("design:returntype",void 0)],UT.prototype,"close",null);class WT extends Kf{getUserId(){return this._userId}constructor(e,r,i,o){super(e,"track-".concat(e.kind,"-").concat(r,"-").concat(o.clientId,"_").concat(t.getRandomString(5,""))),this._userId=void 0,this._uintId=void 0,this._isDestroyed=!1,this.store=void 0,this.processor=void 0,this._userId=r,this._uintId=i,this.store=o}_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,r.logger.info("[".concat(this.getTrackId(),"] is destroyed")),this.stop(),super.close()}getProcessorStats(){return this.processorContext.gatherStats()}getProcessorUsage(){return this.processorContext.gatherUsage()}}class KT extends WT{get isPlaying(){return!(!this._player||this._player.videoElementStatus!==e.MediaElementStatus.PLAYING)}get __className__(){return"RemoteVideoTrack"}constructor(e,t,r,i){super(e,t,r,i),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 oT(this.getTrackId(),"remote"),this.processorDestination=new iT(this.processorContext),this.bindProcessorDestinationEvents()}getStats(){t.runOnce((()=>{r.logger.warning("[deprecated] RemoteVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteVideoStats instead")}),"remoteVideoTrackGetStatsWarning");return t.emitAsInvokerNoResponse(this,e.TrackInternalEvent.GET_STATS)||GT({},uo)}play(i){let o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("string"==typeof i){const e=document.getElementById(i);e?i=e:(r.logger.warning("[".concat(this.getTrackId(),'] can not find "#').concat(i,'" element, use document.body')),i=document.body)}r.logger.debug("[".concat(this.getTrackId(),"] start video playback in ").concat(i instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement"),JSON.stringify(o));const n=GT(GT({fit:"cover"},o),{},{trackId:this.getTrackId(),element:i});this._player?this._player.updateConfig(n):(i instanceof HTMLVideoElement?this._player=new RT(n):this._player=new wT(n),this._player.updateVideoTrack(this._mediaStreamTrack),this._player.onFirstVideoFrameDecoded=()=>{this.store.subscribe(this.getUserId(),"video",void 0,void 0,Date.now()),this.safeEmit(e.RemoteTrackEvents.FIRST_FRAME_DECODED)}),this._player.play(this.store.sessionId||void 0),this._videoVisibleTimer&&window.clearInterval(this._videoVisibleTimer),this._clearPreviousVideoVisibleStatus(),this._videoVisibleTimer=window.setInterval((()=>{try{const t=this.getVideoElementVisibleStatus();this.safeEmit(e.RemoteTrackEvents.VIDEO_ELEMENT_VISIBLE_STATUS,t)}catch(e){}}),t.getParameter("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,r.logger.debug("[".concat(this.getTrackId(),"] stop video playback")))}getCurrentFrameData(){return this._player?this._player.getCurrentFrame():new ImageData(2,2)}updateMediaStreamTrackResolution(){DT(this._originMediaStreamTrack).then((e=>{let[t,r]=e;this._videoHeight=r,this._videoWidth=t})).catch(t.noop)}_updatePlayerSource(){r.logger.debug("[".concat(this.getTrackId(),"] update player source track")),this._player&&this._player.updateVideoTrack(this._mediaStreamTrack)}getVideoElementVisibleStatus(){try{var e,i;const o=null==this||null===(e=this._player)||void 0===e?void 0:e.getContainerElement(),n={track:this,element:null==this||null===(i=this._player)||void 0===i?void 0:i.getVideoElement(),slot:null==o?void 0:o.parentElement},{element:a,slot:s}=n;if(this.isPlaying&&a instanceof HTMLVideoElement&&s instanceof HTMLElement){const e=t.elementVisibleChecker.checkOneElementVisible(a),i=Object.assign({},e);if(i.visible!==this._previousVideoVisibleStatus){this._previousVideoVisibleStatus=i.visible;const e=r.report.reportApiInvoke(null,{tag:t.AgoraAPITag.TRACER,name:t.AgoraAPIName.REMOTE_VIDEO_TRACK_GET_VIDEO_VISIBLE,options:[this.getTrackId()]});i.visible?e.onSuccess("Video is visible"):e.onSuccess("Invisible because of ".concat(i.reason))}return i}return}catch(e){throw new t.AgoraRTCError(t.AgoraRTCErrorCode.GET_VIDEO_ELEMENT_VISIBLE_ERROR,e.message)}}pipe(e){if(this.processor===e)return e;if(e._source)throw new t.AgoraRTCError(t.AgoraRTCErrorCode.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(e.PROCESSOR_DESTINATION_EVENTS.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(e.PROCESSOR_DESTINATION_EVENTS.ON_TRACK)}_destroy(){super._destroy(),this.unbindProcessorDestinationEvents()}}Gf([r.apiInvoke({argsMap:(e,t,r)=>[e.getTrackId(),"string"==typeof t?t:t instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement",r]}),Wf("design:type",Function),Wf("design:paramtypes",[Object,Object]),Wf("design:returntype",void 0)],KT.prototype,"play",null),Gf([r.apiInvoke({argsMap:e=>[e.getTrackId()]}),Wf("design:type",Function),Wf("design:paramtypes",[]),Wf("design:returntype",void 0)],KT.prototype,"stop",null),Gf([r.apiInvoke({argsMap:(e,t)=>[e.getTrackId(),t.name]}),Wf("design:type",Function),Wf("design:paramtypes",[Object]),Wf("design:returntype",Object)],KT.prototype,"pipe",null),Gf([r.apiInvoke({argsMap:e=>[e.getTrackId()]}),Wf("design:type",Function),Wf("design:paramtypes",[]),Wf("design:returntype",void 0)],KT.prototype,"unpipe",null);class zT extends WT{get isPlaying(){return this._useAudioElement?KE.isPlaying(this.getTrackId()):this._source.isPlayed}get __className__(){return"RemoteAudioTrack"}constructor(r,i,o,n){super(r,i,o,n),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,t.getParameter("DISABLE_WEBAUDIO")?(this._source=new sT,this._bypassWebAudio=!0,this._useAudioElement=!0):(this._source=new IE(r,!0),t.getParameter("REMOTE_AUDIO_TRACK_USES_WEB_AUDIO")&&(this._useAudioElement=!1)),this._source.once(e.AudioSourceEvents.RECEIVE_TRACK_BUFFER,(()=>{this.safeEmit(e.RemoteTrackEvents.FIRST_FRAME_DECODED)})),this.processorContext=new aT(this._source.context,this.getTrackId(),"remote"),this.processorDestination=new nT(this.processorContext),this.bindProcessorDestinationEvents(),this._source.on(e.AudioSourceEvents.UPDATE_SOURCE,(()=>{this.processor&&this.processor.updateInput({node:this._source.processSourceNode,context:this.processorContext})}))}setAudioFrameCallback(t){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:4096;if(!t)return this._source.removeAllListeners(e.AudioSourceEvents.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(r),this._source.removeAllListeners(e.AudioSourceEvents.ON_AUDIO_BUFFER),this._source.on(e.AudioSourceEvents.ON_AUDIO_BUFFER,(e=>t(e)))}setVolume(e){this._volume=e,this._useAudioElement?KE.setVolume(this.getTrackId(),e):this._source.setVolume(e/100)}async setPlaybackDevice(e){if(!this._useAudioElement)throw new t.AgoraRTCError(t.AgoraRTCErrorCode.NOT_SUPPORTED,"your browser does not support setting the audio output device");await KE.setSinkID(this.getTrackId(),e)}getVolumeLevel(){return this._source.getAccurateVolumeLevel()}getStats(){t.runOnce((()=>{r.logger.warning("[deprecated] RemoteAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteAudioStats instead")}),"remoteAudioTrackGetStatsWarning");return t.emitAsInvokerNoResponse(this,e.TrackInternalEvent.GET_STATS)||GT({},co)}play(){r.logger.debug("[".concat(this.getTrackId(),"] start audio playback")),this._played=!0,this._useAudioElement?(r.logger.debug("[".concat(this.getTrackId(),"] use audio element to play")),KE.play(this._mediaStreamTrack,this.getTrackId(),this._volume,this.store.sessionId||void 0)):this._source.play()}stop(){r.logger.debug("[".concat(this.getTrackId(),"] stop audio playback")),this._played=!1,this._useAudioElement?KE.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];r.logger.debug("[".concat(this.getTrackId(),"] update player source track")),e&&this._source.updateTrack(this._mediaStreamTrack),this._useAudioElement&&KE.updateTrack(this.getTrackId(),this._mediaStreamTrack)}pipe(e){if(this._bypassWebAudio)throw new t.AgoraRTCError(t.AgoraRTCErrorCode.NOT_SUPPORTED,"can not pipe extension when WebAudio disabled");if(this.processor===e)return e;if(e._source)throw new t.AgoraRTCError(t.AgoraRTCErrorCode.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.AgoraRTCError(t.AgoraRTCErrorCode.NOT_SUPPORTED,"can not unpipe extension when WebAudio disabled");if(!this.processor)return;const r=this.processor;null===(e=this._source.processSourceNode)||void 0===e||e.disconnect(),this.processor._source=!1,this.processor=void 0,r.reset()}bindProcessorDestinationEvents(){this.processorDestination.on(e.PROCESSOR_DESTINATION_EVENTS.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(e.PROCESSOR_DESTINATION_EVENTS.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(e.PROCESSOR_DESTINATION_EVENTS.ON_TRACK),this.processorDestination.removeAllListeners(e.PROCESSOR_DESTINATION_EVENTS.ON_NODE)}}var XT;Gf([r.apiInvoke({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),Wf("design:type",Function),Wf("design:paramtypes",[Number]),Wf("design:returntype",void 0)],zT.prototype,"setVolume",null),Gf([r.apiInvoke({argsMap:(e,t)=>[e.getTrackId(),t]}),Wf("design:type",Function),Wf("design:paramtypes",[String]),Wf("design:returntype",Hf)],zT.prototype,"setPlaybackDevice",null),Gf([r.apiInvoke({argsMap:e=>[e.getTrackId()]}),Wf("design:type",Function),Wf("design:paramtypes",[]),Wf("design:returntype",void 0)],zT.prototype,"play",null),Gf([r.apiInvoke({argsMap:e=>[e.getTrackId()]}),Wf("design:type",Function),Wf("design:paramtypes",[]),Wf("design:returntype",void 0)],zT.prototype,"stop",null),Gf([r.apiInvoke({argsMap:(e,t)=>[e.getTrackId(),t.name]}),Wf("design:type",Function),Wf("design:paramtypes",[Object]),Wf("design:returntype",Object)],zT.prototype,"pipe",null),Gf([r.apiInvoke({argsMap:e=>[e.getTrackId()]}),Wf("design:type",Function),Wf("design:paramtypes",[]),Wf("design:returntype",void 0)],zT.prototype,"unpipe",null),function(e){e[e.ONE_BYTE=0]="ONE_BYTE",e[e.TWO_BYTE=1]="TWO_BYTE"}(XT||(XT={}));class qT{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 r=new Uint8Array(4);r.set([1,0,0,0]);const i={id:0,length:4,data:r.buffer},o={profile:this.isUseOneByte?0:1,length:this.isUseOneByte?5:6,datas:[i]};t.commonPacketHeader.extension=1,t.extension=o,t.payload=this.compress(e),t.commonPacketHeader.length=8+(t.extension.length+2)+t.payload.byteLength}else t.commonPacketHeader.length=8+t.payload.byteLength;const r=new ArrayBuffer(t.commonPacketHeader.length),i=new Uint8Array(r),o=new DataView(r);let n=0;if(o.setUint16(n,t.commonPacketHeader.extension<<15|t.commonPacketHeader.reserved<<14|t.commonPacketHeader.length,!0),n+=2,o.setUint32(n,t.commonPacketHeader.sequence,!0),n+=4,o.setUint16(n,t.commonStreamHeader,!0),n+=2,t.extension){const e=this.serializeExtension(t.extension);i.set(new Uint8Array(e),n),n+=e.byteLength}if(i.set(new Uint8Array(t.payload),n),n+=t.payload.byteLength,n!==t.commonPacketHeader.length)throw Error("serialize error!");return r}deserialize(e){if(e.byteLength<4)return new ArrayBuffer(0);const t=new DataView(e);let r=0;const i=t.getUint16(r,!0);r+=2;const o=(32768&i)>>15;t.getUint16(r+2,!0),t.getUint16(r,!0);let n,a;if(r+=4,t.getUint16(r,!0),r+=2,o){a=this.deserializeExtension(e.slice(r)),r+=2+a.length,n=e.slice(r);let t=!1;if(a.datas.length>0){const e=a.datas.find((e=>0===e.id));if(e){t=1==(1&new DataView(e.data).getUint32(0,!0))}}n=t?this.decompress(n):n}else n=e.slice(8);return n}serializeExtension(e){const{profile:t,length:r,datas:i}=e,o=new ArrayBuffer(r+2),n=new Uint8Array(o),a=new DataView(o);let s=0;if(a.setUint8(s++,t),a.setUint8(s++,r),i.forEach((e=>{t?(a.setUint8(s++,e.id),a.setUint8(s++,e.length),n.set(new Uint8Array(e.data),s),s+=e.data.byteLength):(a.setUint8(s++,e.id|e.length<<4),n.set(new Uint8Array(e.data),s),s+=e.data.byteLength)})),s!==r+2)throw Error("serialize extension error, is ".concat(s,"!==").concat(r+2));return o}deserializeExtension(e){const t=new DataView(e);let r=0;const i=t.getUint8(r);r++;const o=t.getUint8(r);r++;const n=i===XT.TWO_BYTE,a=[],s=new DataView(e,2);let c=0;for(;c<o;){let e=0,t=0,r=new ArrayBuffer(0);n?(e=s.getUint8(c),c++,t=s.getUint8(c),c++):(e=15&s.getUint8(c),t=s.getUint8(c)>>4,c++),t>0&&(r=s.buffer.slice(c+2,c+2+t),c+=r.byteLength),a.push({id:e,length:t,data:r})}if(c!==o)throw Error("parse error");return{profile:i,length:o,datas:a}}decompress(e){return n.inflate(new Uint8Array(e))}compress(e){return n.deflate(new Uint8Array(e))}}class JT extends t.EventEmitter{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 qT}get id(){return this._config.id}get ordered(){return this._config.ordered}get maxRetransmits(){return t.getParameter("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 Hf(((e,r)=>{if(this._originDataChannel){"open"===this._originDataChannel.readyState&&e();const i=setTimeout((()=>{var e;r(new t.AgoraRTCError(t.AgoraRTCErrorCode.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.AgoraRTCError(t.AgoraRTCErrorCode.DATACHANNEL_CONNECTION_TIMEOUT)}}else r(new t.AgoraRTCError(t.AgoraRTCErrorCode.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(t){this._unbindDataChannelEvents(t),[e.DataChannelEvents.OPEN,e.DataChannelEvents.CLOSE,e.DataChannelEvents.ERROR].forEach((e=>{const r=()=>{this.emit(e)};this._datachannelEventMap.set(e,r),t.addEventListener(e,r)}))}_unbindDataChannelEvents(e){Array.from(this._datachannelEventMap.entries()).forEach((t=>{let[r,i]=t;e.removeEventListener(r,i)})),this._datachannelEventMap.clear()}}Object.defineProperty(e,"isElectron",{enumerable:!0,get:function(){return t.isElectron}}),e.AUDIO_ENCODER_CONFIG_SETTINGS=Wi,e.AudioProcessorContext=aT,e.AudioProcessorDestination=nT,e.BufferSourceAudioTrack=fT,e.CameraVideoTrack=UT,e.DEFAULT_LOCAL_AUDIO_TRACK_STATS=ao,e.DEFAULT_LOCAL_VIDEO_TRACK_STATS=so,e.DEFAULT_NETWORK_QUALITY_STATS={uplinkNetworkQuality:0,downlinkNetworkQuality:0},e.DEFAULT_REMOTE_AUDIO_TRACK_STATS=co,e.DEFAULT_REMOTE_VIDEO_TRACK_STATS=uo,e.DataChannel=JT,e.DeviceManager=LE,e.LocalAudioTrack=gT,e.LocalDataChannel=class extends JT{send(e){if(this._originDataChannel){let t=e;t=this._dataStreamPacketHandler.serialize(e);const r=new Uint8Array(this._dataStreamPacketHeader.byteLength+t.byteLength);r.set(new Uint8Array(this._dataStreamPacketHeader),0),r.set(new Uint8Array(t),this._dataStreamPacketHeader.byteLength),this._originDataChannel.send(r.buffer)}}},e.LocalTrack=zf,e.LocalVideoTrack=xT,e.MediaElementNumStatus={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},e.MicrophoneAudioTrack=mT,e.MixingAudioTrack=ET,e.RemoteAudioTrack=zT,e.RemoteDataChannel=class extends JT{constructor(t){super(t),this._messageListener=void 0,this._messageListener=t=>{if(t.data.byteLength<this._dataStreamPacketHeader.byteLength)throw Error("invalid byteLength: the byte length must exceed "+this._dataStreamPacketHeader.byteLength);const r=t.data.slice(0,this._dataStreamPacketHeader.byteLength);if(new DataView(r).getUint8(3)!==this.id)return;let i=t.data.slice(this._dataStreamPacketHeader.byteLength);i=this._dataStreamPacketHandler.deserialize(i),this.emit(e.DataChannelEvents.MESSAGE,i)}}_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)}},e.RemoteTrack=WT,e.RemoteVideoTrack=KT,e.SAFARI_GLOBAL_GUM_LOCK=NE,e.SUPPORT_720P_AUTO_CONFIG_LIST=Ui,e.SUPPORT_SCREEN_ENCODER_CONFIG_LIST=Bi,e.SUPPORT_SVC_CONFIG_LIST=Fi,e.SUPPORT_VIDEO_ENCODER_CONFIG_LIST=xi,e.Track=Kf,e.VideoProcessorContext=oT,e.VideoProcessorDestination=iT,e.__TRACK_LIST__=zi,e.addTrack=Xi,e.audioContextState=Qf,e.audioElementPlayCenter=KE,e.audioTimerLoop=function(e,r){let i=!1;const o=1/r;if(t.getParameter("DISABLE_WEBAUDIO")){const t=window.setInterval((()=>{i?window.clearInterval(t):e(performance.now()/1e3)}),1e3*o)}else{const t=$f();let r=t.createGain();r.gain.value=0,r.connect(t.destination);const n=()=>{if(i)return void(r=null);const a=t.createOscillator();a.onended=n,a.connect(r),a.start(0),a.stop(t.currentTime+o),e(t.currentTime)};n()}return()=>{i=!0}},e.autoPlayGestureEventEmitter=BE,e.blob2Uint8Array=bT,e.checkMediaStreamTrackResolution=DT,e.checkTrackState=zE,e.createBufferSourceAudioTrack=async function(e){var o;const{cacheOnlineFile:n,encoderConfig:a}=e;let{source:s}=e;const c={source:s instanceof AudioBuffer?"AudioBuffer":s instanceof File?null!==(o=File.name)&&void 0!==o?o:"File":s,cacheOnlineFile:n,encoderConfig:a},d=r.report.reportApiInvoke(null,{tag:t.AgoraAPITag.TRACER,name:t.AgoraAPIName.CREATE_BUFFER_AUDIO_TRACK,options:[c]});if(t.getParameter("DISABLE_WEBAUDIO"))throw new t.AgoraRTCError(t.AgoraRTCErrorCode.NOT_SUPPORTED,"can not create BufferSourceAudioTrack when WebAudio disabled");const u=t.getRandomString(8,"track-buf-");r.logger.info("start create buffer source audio track with config",JSON.stringify(c),"trackId",u);const l=s;if(!(s instanceof AudioBuffer))try{s=await async function(e,o){let n=null;if("string"==typeof e){const o=ST.get(e);if(o)return r.logger.debug("use cached audio resource: ",e),o;try{n=(await t.retryable((()=>i.get(e,{responseType:"arraybuffer"})),void 0,void 0,{maxRetryCount:3})).data}catch(e){throw new t.AgoraRTCError(t.AgoraRTCErrorCode.FETCH_AUDIO_FILE_FAILED,e.toString())}}else{const r=new Hf(((r,i)=>{const o=new FileReader;o.onload=e=>{e.target?r(e.target.result):i(new t.AgoraRTCError(t.AgoraRTCErrorCode.READ_LOCAL_AUDIO_FILE_ERROR))},o.onerror=()=>{i(new t.AgoraRTCError(t.AgoraRTCErrorCode.READ_LOCAL_AUDIO_FILE_ERROR))},o.readAsArrayBuffer(e)}));n=await r}const a=await rE(n);return"string"==typeof e&&o&&ST.set(e,a),a}(s,n)}catch(e){return d.onError(e),e.throw(r.logger)}const h=new yT(s),p=new fT(l,h,a?Ki(a):{},u);return r.logger.info("create buffer source audio track success, trackId:",u),d.onSuccess(p.getTrackId()),p},e.createCameraVideoTrack=async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const i=r.report.reportApiInvoke(null,{tag:t.AgoraAPITag.TRACER,name:t.AgoraAPIName.CREATE_CAM_VIDEO_TRACK,options:[FT({},e)]}),o=TT(e),n=t.getRandomString(8,"track-cam-");let a=null;const s="720p_auto"===e.encoderConfig;r.logger.info("start create camera video track with config",JSON.stringify(e),"trackId",n);try{a=(await wE({video:o},n)).getVideoTracks()[0]||null}catch(e){throw i.onError(e),e}if(!a){const e=new t.AgoraRTCError(t.AgoraRTCErrorCode.UNEXPECTED_ERROR,"can not find track in media stream");return i.onError(e),e.throw(r.logger)}e.optimizationMode&&jT(n,a,e,ji(e.encoderConfig));const c=new UT(a,e,o,e.scalabiltyMode?Gi(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,n);return s&&c.startMonitorStats(),i.onSuccess(c.getTrackId()),r.logger.info("create camera video success, trackId:",n),c},e.createCustomAudioTrack=function(e){const i=r.report.reportApiInvoke(null,{tag:t.AgoraAPITag.TRACER,name:t.AgoraAPIName.CREATE_CUSTOM_AUDIO_TRACK,options:[e]}),o=new gT(e.mediaStreamTrack,e.encoderConfig?Ki(e.encoderConfig):{},t.getRandomString(8,"track-cus-"),!1,!0);return r.logger.info("create custom audio track success with config",e,"trackId",o.getTrackId()),i.onSuccess(o.getTrackId()),o},e.createCustomVideoTrack=function(i){const o=r.report.reportApiInvoke(null,{tag:t.AgoraAPITag.TRACER,name:t.AgoraAPIName.CREATE_CUSTOM_VIDEO_TRACK,options:[i]}),n=new xT(i.mediaStreamTrack,{width:i.width,height:i.height,frameRate:i.frameRate,bitrateMax:i.bitrateMax,bitrateMin:i.bitrateMin},i.scalabiltyMode?Gi(i.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},i.optimizationMode,t.getRandomString(8,"track-cus-"),[e.TrackHint.CUSTOM_TRACK]);return o.onSuccess(n.getTrackId()),r.logger.info("create custom video track success with config",i,"trackId",n.getTrackId()),n},e.createMicrophoneAndCameraTracks=async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const o=r.report.reportApiInvoke(null,{tag:t.AgoraAPITag.TRACER,name:t.AgoraAPIName.CREATE_MIC_AND_CAM_TRACKS,options:[e,i]}),n="720p_auto"===i.encoderConfig,a=TT(i),s=_T(e),c=t.getRandomString(8,"track-mic-"),d=t.getRandomString(8,"track-cam-");let u=null,l=null;r.logger.info("start create camera video track(".concat(d,") and microphone audio track(").concat(c,") with config, audio: ").concat(JSON.stringify(e),", video: ").concat(JSON.stringify(i)));try{const e=await wE({audio:s,video:a},"".concat(c,"-").concat(d));u=e.getAudioTracks()[0],l=e.getVideoTracks()[0]}catch(e){throw o.onError(e),e}if(!u||!l){const e=new t.AgoraRTCError(t.AgoraRTCErrorCode.UNEXPECTED_ERROR,"can not find tracks in media stream");return o.onError(e),e.throw(r.logger)}i.optimizationMode&&jT(d,l,i,ji(i.encoderConfig));const h=new mT(u,e,s,c),p=new UT(l,i,a,i.scalabiltyMode?Gi(i.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},i.optimizationMode,d);return n&&p.startMonitorStats(),o.onSuccess([h.getTrackId(),p.getTrackId()]),r.logger.info("create camera video track(".concat(d,") and microphone audio track(").concat(c,") success")),[h,p]},e.createMicrophoneAudioTrack=async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const i=r.report.reportApiInvoke(null,{tag:t.AgoraAPITag.TRACER,name:t.AgoraAPIName.CREATE_MIC_AUDIO_TRACK,options:[e]}),o=_T(e),n=t.getRandomString(8,"track-mic-");let a=null;r.logger.info("start create microphone audio track with config",JSON.stringify(e),"trackId",n);try{a=(await wE({audio:o},n)).getAudioTracks()[0]||null}catch(e){throw i.onError(e),e}if(!a){const e=new t.AgoraRTCError(t.AgoraRTCErrorCode.UNEXPECTED_ERROR,"can not find track in media stream");return i.onError(e),e.throw(r.logger)}const s=new mT(a,e,o,n);return i.onSuccess(s.getTrackId()),r.logger.info("create microphone audio track success, trackId:",n),s},e.createMixingAudioTrack=function(e){const t=new ET;return e.forEach((e=>t.addAudioTrack(e))),t},e.createScreenVideoTrack=async function(){let i=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"disable";const n=r.report.reportApiInvoke(null,{tag:t.AgoraAPITag.TRACER,name:t.AgoraAPIName.CREATE_SCREEN_VIDEO_TRACK,options:[FT({},i),o]}),a="720p_auto"===i.encoderConfig;i.encoderConfig?"string"==typeof i.encoderConfig||i.encoderConfig.width&&i.encoderConfig.height||(i.encoderConfig.width={max:1920},i.encoderConfig.height={max:1080}):i.encoderConfig="1080p_2";const s=vT(i),c=t.getRandomString(8,"track-scr-v-");let d=null,u=null;const l=sE();if(!l.supportShareAudio&&"enable"===o){const e=new t.AgoraRTCError(t.AgoraRTCErrorCode.NOT_SUPPORTED,"your browser or platform is not support share-screen with audio");return n.onError(e),e.throw(r.logger)}r.logger.info("start create screen video track with config",i,"withAudio",o,"trackId",c);try{const e=await wE({screen:s,screenAudio:"auto"===o?l.supportShareAudio:"enable"===o},c);d=e.getVideoTracks()[0]||null,u=e.getAudioTracks()[0]||null}catch(e){throw n.onError(e),e}if(!d){const e=new t.AgoraRTCError(t.AgoraRTCErrorCode.UNEXPECTED_ERROR,"can not find track in media stream");return n.onError(e),e.throw(r.logger)}if(!u&&"enable"===o){d&&d.stop();const e=new t.AgoraRTCError(t.AgoraRTCErrorCode.SHARE_AUDIO_NOT_ALLOWED);return n.onError(e),e.throw(r.logger)}if(i.optimizationMode||(i.optimizationMode="detail"),i.optimizationMode){jT(c,d,i,i.encoderConfig&&Hi(i.encoderConfig)||void 0),i.encoderConfig&&"string"!=typeof i.encoderConfig&&(i.encoderConfig.bitrateMin=i.encoderConfig.bitrateMax)}const h=new xT(d,i.encoderConfig?Hi(i.encoderConfig):{},i.scalabiltyMode?Gi(i.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},i.optimizationMode,c,[e.TrackHint.SCREEN_TRACK]);if(a&&h.startMonitorStats(),!u)return n.onSuccess(h.getTrackId()),r.logger.info("create screen video track success","video:",h.getTrackId()),h;const p=new gT(u,void 0,t.getRandomString(8,"track-scr-a-"),!1,!0);return n.onSuccess([h.getTrackId(),p.getTrackId()]),r.logger.info("create screen video track success","video:",h.getTrackId(),"audio:",p.getTrackId()),[h,p]},e.decodeAudioData=rE,e.deviceManager=VE,e.emptyImage2TypedArray=AT,e.frameData2CryptoBuffer=async(e,r,i)=>await(async(e,r,i)=>{const o=""+r+i,n=t.hexToBytes(t.md5(o)).slice(0,16),a=n.slice(0,12),s=await window.crypto.subtle.importKey("raw",n,"AES-GCM",!0,["encrypt"]);return new Uint8Array(await window.crypto.subtle.encrypt({name:"AES-GCM",iv:a},s,e))})(e.buffer,r,i),e.getAudioContext=$f,e.getAudioEncoderConfiguration=Ki,e.getBitrateFromResAndFps=PT,e.getCompatibility=sE,e.getConstraintsFromCameraConfig=TT,e.getConstraintsFromMicrophoneConfig=_T,e.getConstraintsFromScreenConfig=vT,e.getElectronScreenSources=OE,e.getElectronScreenStream=kE,e.getElectronScreenStreamByUserSelect=CE,e.getLocalStream=wE,e.getScalabilityConfiguration=Gi,e.getScreenEncoderConfiguration=Hi,e.getSilenceAudioTrack=function(){if(oE)return oE;const e=$f();if(!e.createMediaStreamDestination)throw new t.AgoraRTCError(t.AgoraRTCErrorCode.NOT_SUPPORTED,"can not create silence audio track");const r=e.createBufferSource(),i=e.createBuffer(1,44100,44100);r.loop=!0,r.buffer=i;const o=e.createMediaStreamDestination();return r.connect(o),oE=o.stream.getAudioTracks()[0],oE},e.getSilenceSamplesDuration=function(e){const t=e.getChannelData(0);let r=0,i=0;for(let e=0;e<t.length;e+=1)0===t[e]?(r+=1,r>i&&(i=r)):r=0;return i/t.length*e.duration},e.getStaticTrackStream=MT,e.getVideoEncoderConfiguration=ji,e.handleGetUserMediaError=PE,e.hasAudioContext=eE,e.isAudioEncoderConfiguration=Yi,e.isAudioEncoderConfigurationOrPreset=function(e){return"string"==typeof e?t.checkValidEnum(e,"profile",Object.keys(Wi)):Yi(e),!0},e.isBeautyEffectOptions=function(e){return void 0!==e.smoothnessLevel&&t.checkValidNumber(e.smoothnessLevel,"options.smoothnessLevel",0,1,!1),void 0!==e.lighteningLevel&&t.checkValidNumber(e.lighteningLevel,"options.lighteningLevel",0,1,!1),void 0!==e.rednessLevel&&t.checkValidNumber(e.rednessLevel,"options.rednessLevel",0,1,!1),void 0!==e.lighteningContrastLevel&&t.checkValidEnum(e.lighteningContrastLevel,"options.lighteningContrastLevel",[0,1,2]),!0},e.isLowStreamParameter=function(e){if(!e)throw new t.AgoraRTCError(t.AgoraRTCErrorCode.INVALID_PARAMS);return t.isEmpty(e.width)||t.checkValidConstrainLong(e.width,"streamParameter.width"),t.isEmpty(e.height)||t.checkValidConstrainLong(e.height,"streamParameter.height"),t.isEmpty(e.framerate)||t.checkValidConstrainLong(e.framerate,"streamParameter.framerate"),t.isEmpty(e.bitrate)||t.checkValidNumber(e.bitrate,"streamParameter.bitrate"),!0},e.isScreenSourceType=Qi,e.isVideoEncoderConfiguration=Ji,e.isVideoEncoderConfigurationOrPreset=function(e){return"string"==typeof e?t.checkValidEnum(e,"profile",Object.keys(xi)):Ji(e),!0},e.polyfillAudioNode=tE,e.removeTrack=qi,e.requestAutoplayGesture=FE,e.silenceScriptProcessHandler=nE,e.updateAgoraRTCCompatibility=function(){const e=t.getBrowserInfo();aE.getDisplayMedia=function(e){if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)return!0;return!1}(),aE.getStreamFromExtension=e.name===t.BrowserName.CHROME&&Number(e.version)>34,aE.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}(),aE.supportMinBitrate=e.name===t.BrowserName.CHROME||e.name===t.BrowserName.EDGE,aE.supportSetRtpSenderParameters=function(){const e=t.getBrowserInfo();if(!window.RTCRtpSender||!window.RTCRtpSender.prototype.setParameters||!window.RTCRtpSender.prototype.getParameters)return!1;return!!t.isChromeKernel()||(!(!t.isSafari()&&!t.isWkWebview())||e.name===t.BrowserName.FIREFOX&&Number(e.version)>=64)}(),e.name===t.BrowserName.SAFARI&&(Number(e.version)>=14?aE.supportDualStream=!0:aE.supportDualStream=!1),aE.webAudioMediaStreamDest=function(){const e=t.getBrowserInfo();if(e.name===t.BrowserName.SAFARI&&Number(e.version)<12)return!1;return!0}(),aE.supportReplaceTrack=function(){if(!window.RTCRtpSender)return!1;if("function"==typeof RTCRtpSender.prototype.replaceTrack)return!0;return!1}(),aE.supportWebGL="undefined"!=typeof WebGLRenderingContext,aE.supportRequestFrame=!!window.CanvasCaptureMediaStreamTrack,t.isChromeKernel()||(aE.webAudioWithAEC=!0),aE.supportShareAudio=function(){const e=t.getBrowserInfo();if((e.os===t.BrowserOS.WIN_10||e.os===t.BrowserOS.WIN_81||e.os===t.BrowserOS.WIN_7||e.os===t.BrowserOS.LINUX||e.os===t.BrowserOS.MAC_OS)&&e.name===t.BrowserName.CHROME&&Number(e.version)>=74)return!0;return!1}(),aE.supportDataChannel=function(){if(t.isAboveChrome(76)||t.isAboveFirefox(68)||t.isAboveSafari(14))return!0;return!1}(),aE.supportPCSetConfiguration=function(){const e=window.RTCPeerConnection;return!t.isFirefox()&&!!e&&e.prototype.setConfiguration instanceof Function}(),aE.supportWebRTCEncodedTransform=function(){const e=t.getBrowserInfo();return"Chrome"===e.name&&Number(e.version)>=86}(),aE.supportWebRTCInsertableStream=function(){const e=t.getBrowserInfo();return(e.name===t.BrowserName.CHROME||e.name===t.BrowserName.EDGE)&&Number(e.version)>=94&&"MediaStreamTrackGenerator"in window&&"MediaStreamTrackProcessor"in window}(),t.nextTick((()=>{aE.supportDualStreamEncoding=function(){const e=t.getBrowserInfo();if(t.getParameter("DISABLE_WEBAUDIO"))return!0;return"Safari"===e.name&&Number(e.version)>=14||!!("Chrome"===e.name&&/Windows/i.test(e.os||"")&&Number(e.version)>=100&&t.getParameter("CHROME_DUAL_STREAM_USE_ENCODING"))}(),r.logger.info("browser compatibility",JSON.stringify(aE),JSON.stringify(e))}))},e.visibilityWatcher=kT}));