>>24,u>>>=S,p-=S,S=T>>>16&255,0===S)y[r++]=65535&T;else{if(!(16&S)){if(0==(64&S)){T=_[(65535&T)+(u&(1<>>=S,p-=S),p<15&&(u+=I[i++]<>>24,u>>>=S,p-=S,S=T>>>16&255,!(16&S)){if(0==(64&S)){T=E[(65535&T)+(u&(1<a){e.msg=\"invalid distance too far back\",A.mode=iM;break e}if(u>>>=S,p-=S,S=r-o,R>S){if(S=R-S,S>d&&A.sane){e.msg=\"invalid distance too far back\",A.mode=iM;break e}if(C=0,v=h,0===l){if(C+=c-S,S2;)y[r++]=v[C++],y[r++]=v[C++],y[r++]=v[C++],g-=3;g&&(y[r++]=v[C++],g>1&&(y[r++]=v[C++]))}else{C=r-R;do{y[r++]=y[C++],y[r++]=y[C++],y[r++]=y[C++],g-=3}while(g>2);g&&(y[r++]=y[C++],g>1&&(y[r++]=y[C++]))}break}}break}}while(i>3,i-=g,p-=g<<3,u&=(1<{const c=a.bits;let d,l,h,u,p,_,E=0,m=0,f=0,T=0,S=0,g=0,R=0,C=0,v=0,I=0,y=null;const A=new Uint16Array(16),b=new Uint16Array(16);let w,O,N,D=null;for(E=0;E<=rM;E++)A[E]=0;for(m=0;m=1&&0===A[T];T--);if(S>T&&(S=T),0===T)return r[o++]=20971520,r[o++]=20971520,a.bits=1,0;for(f=1;f0&&(0===e||1!==T))return-1;for(b[1]=0,E=1;E852||2===e&&v>592)return 1;for(;;){w=E-R,s[m]+1<_?(O=0,N=s[m]):s[m]>=_?(O=D[s[m]-_],N=y[s[m]-_]):(O=96,N=0),d=1<>R)+l]=w<<24|O<<16|N|0}while(0!==l);for(d=1<>=1;if(0!==d?(I&=d-1,I+=d):I=0,m++,0==--A[E]){if(E===T)break;E=t[i+s[m]]}if(E>S&&(I&u)!==h){for(0===R&&(R=S),p+=f,g=E-R,C=1<852||2===e&&v>592)return 1;h=I&u,r[h]=S<<24|g<<16|p-o|0}}return 0!==I&&(r[p+I]=E-R<<24|64<<16|0),a.bits=S,0};const{Z_FINISH:lM,Z_BLOCK:hM,Z_TREES:uM,Z_OK:pM,Z_STREAM_END:_M,Z_NEED_DICT:EM,Z_STREAM_ERROR:mM,Z_DATA_ERROR:fM,Z_MEM_ERROR:TM,Z_BUF_ERROR:SM,Z_DEFLATED:gM}=PL,RM=16180,CM=16190,vM=16191,IM=16192,yM=16194,AM=16199,bM=16200,wM=16206,OM=16209,NM=e=>(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24);function DM(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}const PM=e=>{if(!e)return 1;const t=e.state;return!t||t.strm!==e||t.mode16211?1:0},LM=e=>{if(PM(e))return mM;const t=e.state;return e.total_in=e.total_out=t.total=0,e.msg=\"\",t.wrap&&(e.adler=1&t.wrap),t.mode=RM,t.last=0,t.havedict=0,t.flags=-1,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new Int32Array(852),t.distcode=t.distdyn=new Int32Array(592),t.sane=1,t.back=-1,pM},kM=e=>{if(PM(e))return mM;const t=e.state;return t.wsize=0,t.whave=0,t.wnext=0,LM(e)},MM=(e,t)=>{let i;if(PM(e))return mM;const n=e.state;return t<0?(i=0,t=-t):(i=5+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?mM:(null!==n.window&&n.wbits!==t&&(n.window=null),n.wrap=i,n.wbits=t,kM(e))},UM=(e,t)=>{if(!e)return mM;const i=new DM;e.state=i,i.strm=e,i.window=null,i.mode=RM;const n=MM(e,t);return n!==pM&&(e.state=null),n};let xM,VM,FM=!0;const BM=e=>{if(FM){xM=new Int32Array(512),VM=new Int32Array(32);let t=0;for(;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(dM(1,e.lens,0,288,xM,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;dM(2,e.lens,0,32,VM,0,e.work,{bits:5}),FM=!1}e.lencode=xM,e.lenbits=9,e.distcode=VM,e.distbits=5},jM=(e,t,i,n)=>{let r;const o=e.state;return null===o.window&&(o.wsize=1<=o.wsize?(o.window.set(t.subarray(i-o.wsize,i),0),o.wnext=0,o.whave=o.wsize):(r=o.wsize-o.wnext,r>n&&(r=n),o.window.set(t.subarray(i-n,i-n+r),o.wnext),(n-=r)?(o.window.set(t.subarray(i-n,i),0),o.wnext=n,o.whave=o.wsize):(o.wnext+=r,o.wnext===o.wsize&&(o.wnext=0),o.whave{let i,n,r,o,s,a,c,d,l,h,u,p,_,E,m,f,T,S,g,R,C,v,I=0;const y=new Uint8Array(4);let A,b;const w=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(PM(e)||!e.output||!e.input&&0!==e.avail_in)return mM;i=e.state,i.mode===vM&&(i.mode=IM),s=e.next_out,r=e.output,c=e.avail_out,o=e.next_in,n=e.input,a=e.avail_in,d=i.hold,l=i.bits,h=a,u=c,v=pM;e:for(;;)switch(i.mode){case RM:if(0===i.wrap){i.mode=IM;break}for(;l<16;){if(0===a)break e;a--,d+=n[o++]<>>8&255,i.check=NL(i.check,y,2,0),d=0,l=0,i.mode=16181;break}if(i.head&&(i.head.done=!1),!(1&i.wrap)||(((255&d)<<8)+(d>>8))%31){e.msg=\"incorrect header check\",i.mode=OM;break}if((15&d)!==gM){e.msg=\"unknown compression method\",i.mode=OM;break}if(d>>>=4,l-=4,C=8+(15&d),0===i.wbits&&(i.wbits=C),C>15||C>i.wbits){e.msg=\"invalid window size\",i.mode=OM;break}i.dmax=1<>8&1),512&BP(i)&&4&i.wrap&&(y[0]=255&d,y[1]=d>>>8&255,i.check=NL(i.check,y,2,0)),d=0,l=0,i.mode=16182;case 16182:for(;l<32;){if(0===a)break e;a--,d+=n[o++]<>>8&255,y[2]=d>>>16&255,y[3]=d>>>24&255,i.check=NL(i.check,y,4,0)),d=0,l=0,i.mode=16183;case 16183:for(;l<16;){if(0===a)break e;a--,d+=n[o++]<>8),512&BP(i)&&4&i.wrap&&(y[0]=255&d,y[1]=d>>>8&255,i.check=NL(i.check,y,2,0)),d=0,l=0,i.mode=16184;case 16184:if(1024&BP(i)){for(;l<16;){if(0===a)break e;a--,d+=n[o++]<>>8&255,i.check=NL(i.check,y,2,0)),d=0,l=0}else i.head&&(i.head.extra=null);i.mode=16185;case 16185:if(1024&BP(i)&&(p=i.length,p>a&&(p=a),p&&(i.head&&(C=i.head.extra_len-i.length,i.head.extra||(i.head.extra=new Uint8Array(i.head.extra_len)),i.head.extra.set(n.subarray(o,o+p),C)),512&BP(i)&&4&i.wrap&&(i.check=NL(i.check,n,p,o)),a-=p,o+=p,i.length-=p),i.length))break e;i.length=0,i.mode=16186;case 16186:if(2048&BP(i)){if(0===a)break e;p=0;do{C=n[o+p++],i.head&&C&&i.length<65536&&(i.head.name+=String.fromCharCode(C))}while(C&&p>9&1,i.head.done=!0),e.adler=i.check=0,i.mode=vM;break;case 16189:for(;l<32;){if(0===a)break e;a--,d+=n[o++]<>>=7&l,l-=7&l,i.mode=wM;break}for(;l<3;){if(0===a)break e;a--,d+=n[o++]<>>=1,l-=1,3&d){case 0:i.mode=16193;break;case 1:if(BM(i),i.mode=AM,t===uM){d>>>=2,l-=2;break e}break;case 2:i.mode=16196;break;case 3:e.msg=\"invalid block type\",i.mode=OM}d>>>=2,l-=2;break;case 16193:for(d>>>=7&l,l-=7&l;l<32;){if(0===a)break e;a--,d+=n[o++]<>>16^65535)){e.msg=\"invalid stored block lengths\",i.mode=OM;break}if(i.length=65535&d,d=0,l=0,i.mode=yM,t===uM)break e;case yM:i.mode=16195;case 16195:if(p=i.length,p){if(p>a&&(p=a),p>c&&(p=c),0===p)break e;r.set(n.subarray(o,o+p),s),a-=p,o+=p,c-=p,s+=p,i.length-=p;break}i.mode=vM;break;case 16196:for(;l<14;){if(0===a)break e;a--,d+=n[o++]<>>=5,l-=5,i.ndist=1+(31&d),d>>>=5,l-=5,i.ncode=4+(15&d),d>>>=4,l-=4,i.nlen>286||i.ndist>30){e.msg=\"too many length or distance symbols\",i.mode=OM;break}i.have=0,i.mode=16197;case 16197:for(;i.have>>=3,l-=3}for(;i.have<19;)i.lens[w[i.have++]]=0;if(i.lencode=i.lendyn,i.lenbits=7,A={bits:i.lenbits},v=dM(0,i.lens,0,19,i.lencode,0,i.work,A),i.lenbits=A.bits,v){e.msg=\"invalid code lengths set\",i.mode=OM;break}i.have=0,i.mode=16198;case 16198:for(;i.have>>24,f=I>>>16&255,T=65535&I,!(m<=l);){if(0===a)break e;a--,d+=n[o++]<>>=m,l-=m,i.lens[i.have++]=T;else{if(16===T){for(b=m+2;l>>=m,l-=m,0===i.have){e.msg=\"invalid bit length repeat\",i.mode=OM;break}C=i.lens[i.have-1],p=3+(3&d),d>>>=2,l-=2}else if(17===T){for(b=m+3;l>>=m,l-=m,C=0,p=3+(7&d),d>>>=3,l-=3}else{for(b=m+7;l>>=m,l-=m,C=0,p=11+(127&d),d>>>=7,l-=7}if(i.have+p>i.nlen+i.ndist){e.msg=\"invalid bit length repeat\",i.mode=OM;break}for(;p--;)i.lens[i.have++]=C}}if(i.mode===OM)break;if(0===i.lens[256]){e.msg=\"invalid code -- missing end-of-block\",i.mode=OM;break}if(i.lenbits=9,A={bits:i.lenbits},v=dM(1,i.lens,0,i.nlen,i.lencode,0,i.work,A),i.lenbits=A.bits,v){e.msg=\"invalid literal/lengths set\",i.mode=OM;break}if(i.distbits=6,i.distcode=i.distdyn,A={bits:i.distbits},v=dM(2,i.lens,i.nlen,i.ndist,i.distcode,0,i.work,A),i.distbits=A.bits,v){e.msg=\"invalid distances set\",i.mode=OM;break}if(i.mode=AM,t===uM)break e;case AM:i.mode=bM;case bM:if(a>=6&&c>=258){e.next_out=s,e.avail_out=c,e.next_in=o,e.avail_in=a,i.hold=d,i.bits=l,nM(e,u),s=e.next_out,r=e.output,c=e.avail_out,o=e.next_in,n=e.input,a=e.avail_in,d=i.hold,l=i.bits,i.mode===vM&&(i.back=-1);break}for(i.back=0;I=i.lencode[d&(1<>>24,f=I>>>16&255,T=65535&I,!(m<=l);){if(0===a)break e;a--,d+=n[o++]<>S)],m=I>>>24,f=I>>>16&255,T=65535&I,!(S+m<=l);){if(0===a)break e;a--,d+=n[o++]<>>=S,l-=S,i.back+=S}if(d>>>=m,l-=m,i.back+=m,i.length=T,0===f){i.mode=16205;break}if(32&f){i.back=-1,i.mode=vM;break}if(64&f){e.msg=\"invalid literal/length code\",i.mode=OM;break}i.extra=15&f,i.mode=16201;case 16201:if(i.extra){for(b=i.extra;l>>=i.extra,l-=i.extra,i.back+=i.extra}i.was=i.length,i.mode=16202;case 16202:for(;I=i.distcode[d&(1<>>24,f=I>>>16&255,T=65535&I,!(m<=l);){if(0===a)break e;a--,d+=n[o++]<>S)],m=I>>>24,f=I>>>16&255,T=65535&I,!(S+m<=l);){if(0===a)break e;a--,d+=n[o++]<>>=S,l-=S,i.back+=S}if(d>>>=m,l-=m,i.back+=m,64&f){e.msg=\"invalid distance code\",i.mode=OM;break}i.offset=T,i.extra=15&f,i.mode=16203;case 16203:if(i.extra){for(b=i.extra;l>>=i.extra,l-=i.extra,i.back+=i.extra}if(i.offset>i.dmax){e.msg=\"invalid distance too far back\",i.mode=OM;break}i.mode=16204;case 16204:if(0===c)break e;if(p=u-c,i.offset>p){if(p=i.offset-p,p>i.whave&&i.sane){e.msg=\"invalid distance too far back\",i.mode=OM;break}p>i.wnext?(p-=i.wnext,_=i.wsize-p):_=i.wnext-p,p>i.length&&(p=i.length),E=i.window}else E=r,_=s-i.offset,p=i.length;p>c&&(p=c),c-=p,i.length-=p;do{r[s++]=E[_++]}while(--p);0===i.length&&(i.mode=bM);break;case 16205:if(0===c)break e;r[s++]=i.length,c--,i.mode=bM;break;case wM:if(i.wrap){for(;l<32;){if(0===a)break e;a--,d|=n[o++]<UM(e,15),inflateInit2:UM,inflate:GM,inflateEnd:e=>{if(PM(e))return mM;let t=e.state;return t.window&&(t.window=null),e.state=null,pM},inflateGetHeader:(e,t)=>{if(PM(e))return mM;const i=e.state;return 0==(2&i.wrap)?mM:(i.head=t,t.done=!1,pM)},inflateSetDictionary:(e,t)=>{const i=t.length;let n,r,o;return PM(e)?mM:(n=e.state,0!==n.wrap&&n.mode!==CM?mM:n.mode===CM&&(r=1,r=wL(r,t,i,0),r!==n.check)?fM:(o=jM(e,t,i,i),o?(n.mode=16210,TM):(n.havedict=1,pM)))},inflateInfo:\"pako inflate (from Nodeca project)\"};var HM=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name=\"\",this.comment=\"\",this.hcrc=0,this.done=!1};const KM=Object.prototype.toString,{Z_NO_FLUSH:YM,Z_FINISH:qM,Z_OK:zM,Z_STREAM_END:JM,Z_NEED_DICT:XM,Z_STREAM_ERROR:QM,Z_DATA_ERROR:ZM,Z_MEM_ERROR:$M}=PL;function eU(e){this.options=Vk.assign({chunkSize:65536,windowBits:15,to:\"\"},e||{});const t=this.options;t.raw&&t.windowBits>=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(t.windowBits>=0&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&0==(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg=\"\",this.ended=!1,this.chunks=[],this.strm=new Gk,this.strm.avail_out=0;let i=WM.inflateInit2(this.strm,t.windowBits);if(i!==zM)throw new Error(DL[i]);if(this.header=new HM,WM.inflateGetHeader(this.strm,this.header),t.dictionary&&(\"string\"==typeof t.dictionary?t.dictionary=jk.string2buf(t.dictionary):\"[object ArrayBuffer]\"===KM.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(i=WM.inflateSetDictionary(this.strm,t.dictionary),i!==zM)))throw new Error(DL[i])}function tU(e,t){const i=new eU(t);if(i.push(e),i.err)throw i.msg||DL[i.err];return i.result}eU.prototype.push=function(e,t){const i=this.strm,n=this.options.chunkSize,r=this.options.dictionary;let o,s,a;if(this.ended)return!1;for(s=t===~~t?t:!0===t?qM:YM,\"[object ArrayBuffer]\"===KM.call(e)?i.input=new Uint8Array(e):i.input=e,i.next_in=0,i.avail_in=i.input.length;;){for(0===i.avail_out&&(i.output=new Uint8Array(n),i.next_out=0,i.avail_out=n),o=WM.inflate(i,s),o===XM&&r&&(o=WM.inflateSetDictionary(i,r),o===zM?o=WM.inflate(i,s):o===ZM&&(o=XM));i.avail_in>0&&o===JM&&i.state.wrap>0&&0!==e[i.next_in];)WM.inflateReset(i),o=WM.inflate(i,s);switch(o){case QM:case ZM:case XM:case $M:return this.onEnd(o),this.ended=!0,!1}if(a=i.avail_out,i.next_out&&(0===i.avail_out||o===JM))if(\"string\"===this.options.to){let e=jk.utf8border(i.output,i.next_out),t=i.next_out-e,r=jk.buf2string(i.output,e);i.next_out=t,i.avail_out=n-t,t&&i.output.set(i.output.subarray(e,e+t),0),this.onData(r)}else this.onData(i.output.length===i.next_out?i.output:i.output.subarray(0,i.next_out));if(o!==zM||0!==a){if(o===JM)return o=WM.inflateEnd(this.strm),this.onEnd(o),this.ended=!0,!0;if(0===i.avail_in)break}}return!0},eU.prototype.onData=function(e){this.chunks.push(e)},eU.prototype.onEnd=function(e){e===zM&&(\"string\"===this.options.to?this.result=this.chunks.join(\"\"):this.result=Vk.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var iU={Inflate:eU,inflate:tU,inflateRaw:function(e,t){return(t=t||{}).raw=!0,tU(e,t)},ungzip:tU,constants:PL};const{Deflate:nU,deflate:rU,deflateRaw:oU,gzip:sU}=tM,{Inflate:aU,inflate:cU,inflateRaw:dU,ungzip:lU}=iU;var hU=rU,uU=cU;const pU={getDisplayMedia:!1,getStreamFromExtension:!1,supportUnifiedPlan:!1,supportMinBitrate:!1,supportSetRtpSenderParameters:!1,supportDualStream:!0,webAudioMediaStreamDest:!1,supportReplaceTrack:!1,supportWebGL:!1,webAudioWithAEC:!1,supportRequestFrame:!1,supportShareAudio:!1,supportDualStreamEncoding:!1,supportDataChannel:!1,supportPCSetConfiguration:!1,supportWebRTCEncodedTransform:!1,supportWebRTCInsertableStream:!1,supportRequestVideoFrameCallback:!1,supportWebCrypto:!1};function _U(){return pU}function EU(){return\"setSinkId\"in HTMLAudioElement.prototype&&(!Dy(\"RESTRICTION_SET_PLAYBACK_DEVICE\")||(Ov()||Dv())&&!zv())}let mU=function(e){return e.IOS_15_16_INTERRUPTION_START=\"ios15_16-interruption-start\",e.IOS_15_16_INTERRUPTION_END=\"ios15_16-interruption-end\",e.IOS_INTERRUPTION_START=\"ios-interruption-start\",e.IOS_INTERRUPTION_END=\"ios-interruption-end\",e.STATE_CHANGE=\"state-change\",e}({});function fU(e,t,i){return{sampleRate:e,stereo:t,bitrate:i}}function TU(e,t,i,n,r){return{width:e,height:t,frameRate:i,bitrateMin:n,bitrateMax:r}}function SU(e,t,i,n,r){return{width:{max:e},height:{max:t},frameRate:i,bitrateMin:n,bitrateMax:r}}function gU(e,t){return{numSpatialLayers:e,numTemporalLayers:t}}const RU={\"90p\":TU(160,90),\"90p_1\":TU(160,90),\"120p\":TU(160,120,15,30,65),\"120p_1\":TU(160,120,15,30,65),\"120p_3\":TU(120,120,15,30,50),\"120p_4\":TU(212,120),\"180p\":TU(320,180,15,30,140),\"180p_1\":TU(320,180,15,30,140),\"180p_3\":TU(180,180,15,30,100),\"180p_4\":TU(240,180,15,30,120),\"240p\":TU(320,240,15,40,200),\"240p_1\":TU(320,240,15,40,200),\"240p_3\":TU(240,240,15,40,140),\"240p_4\":TU(424,240,15,40,220),\"360p\":TU(640,360,15,80,400),\"360p_1\":TU(640,360,15,80,400),\"360p_3\":TU(360,360,15,80,260),\"360p_4\":TU(640,360,30,80,600),\"360p_6\":TU(360,360,30,80,400),\"360p_7\":TU(480,360,15,80,320),\"360p_8\":TU(480,360,30,80,490),\"360p_9\":TU(640,360,15,80,800),\"360p_10\":TU(640,360,24,80,800),\"360p_11\":TU(640,360,24,80,1e3),\"480p\":TU(640,480,15,100,500),\"480p_1\":TU(640,480,15,100,500),\"480p_2\":TU(640,480,30,100,1e3),\"480p_3\":TU(480,480,15,100,400),\"480p_4\":TU(640,480,30,100,750),\"480p_6\":TU(480,480,30,100,600),\"480p_8\":TU(848,480,15,100,610),\"480p_9\":TU(848,480,30,100,930),\"480p_10\":TU(640,480,10,100,400),\"720p\":TU(1280,720,15,120,1130),\"720p_auto\":TU(1280,720,30,900,3e3),\"720p_1\":TU(1280,720,15,120,1130),\"720p_2\":TU(1280,720,30,120,2e3),\"720p_3\":TU(1280,720,30,120,1710),\"720p_5\":TU(960,720,15,120,910),\"720p_6\":TU(960,720,30,120,1380),\"1080p\":TU(1920,1080,15,120,2080),\"1080p_1\":TU(1920,1080,15,120,2080),\"1080p_2\":TU(1920,1080,30,120,3e3),\"1080p_3\":TU(1920,1080,30,120,3150),\"1080p_5\":TU(1920,1080,60,120,4780),\"1440p\":TU(2560,1440,30,120,4850),\"1440p_1\":TU(2560,1440,30,120,4850),\"1440p_2\":TU(2560,1440,60,120,7350),\"4k\":TU(3840,2160,30,120,8910),\"4k_1\":TU(3840,2160,30,120,8910),\"4k_3\":TU(3840,2160,60,120,13500)},CU=[{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}],vU={\"480p\":SU(640,480,5),\"480p_1\":SU(640,480,5),\"480p_2\":SU(640,480,30),\"480p_3\":SU(640,480,15),\"720p\":SU(1280,720,5),\"720p_auto\":TU(1280,720,30,900,3e3),\"720p_1\":SU(1280,720,5),\"720p_2\":SU(1280,720,30),\"720p_3\":SU(1280,720,15),\"1080p\":SU(1920,1080,5),\"1080p_1\":SU(1920,1080,5),\"1080p_2\":SU(1920,1080,30),\"1080p_3\":SU(1920,1080,15)},IU={\"1SL1TL\":gU(1,1),\"3SL3TL\":gU(3,3),\"2SL3TL\":gU(2,3)};function yU(e){return e||(e=\"480p_1\"),\"string\"==typeof e?Object.assign({},RU[e]):e}function AU(e){return\"string\"==typeof e?Object.assign({},vU[e]):e}function bU(e){return\"string\"==typeof e?Object.assign({},IU[e]):e}const wU={speech_low_quality:fU(16e3,!1),speech_standard:fU(32e3,!1,18),music_standard:fU(48e3,!1),standard_stereo:fU(48e3,!0,56),high_quality:fU(48e3,!1,128),high_quality_stereo:fU(48e3,!0,192)};function OU(e){return\"string\"==typeof e?Object.assign({},wU[e]):e}const NU=[];function DU(e){return rI(e,\"mediaSource\",[\"screen\",\"window\",\"application\"]),!0}let PU=function(e){return e.NEED_RENEGOTIATE=\"@need_renegotiate\",e.NEED_REPLACE_TRACK=\"@need_replace_track\",e.NEED_REPLACE_MIXING_TRACK=\"@need_replace_mixing_track\",e.NEED_CLOSE=\"@need_close\",e.NEED_ENABLE_TRACK=\"@need_enable_track\",e.NEED_DISABLE_TRACK=\"@need_disable_track\",e.NEED_SESSION_ID=\"@need_sid\",e.SET_OPTIMIZATION_MODE=\"@set_optimization_mode\",e.GET_STATS=\"@get_stats\",e.GET_RTC_STATS=\"@get_rtc_stats\",e.GET_LOW_VIDEO_TRACK=\"@get_low_video_track\",e.NEED_RESET_REMOTE_SDP=\"@need_reset_remote_sdp\",e.NEED_UPDATE_VIDEO_ENCODER=\"@need_update_video_encoder\",e.NEED_UPDATE_VIDEO_SEND_PARAMETERS=\"@need_update_video_send_parameters\",e.NEED_MUTE_TRACK=\"@need_mute_track\",e.NEED_UNMUTE_TRACK=\"@need_unmute_track\",e}({}),LU=function(e){return e.SCREEN_TRACK=\"screen_track\",e.CUSTOM_TRACK=\"custome_track\",e.LOW_STREAM=\"low_stream\",e}({});let kU=function(e){return e[e.HIGH_STREAM=0]=\"HIGH_STREAM\",e[e.LOW_STREAM=1]=\"LOW_STREAM\",e}({}),MU=function(e){return e[e.HIGH_STREAM=0]=\"HIGH_STREAM\",e[e.LOW_STREAM=1]=\"LOW_STREAM\",e}({}),UU=function(e){return e[e.DISABLE=0]=\"DISABLE\",e[e.LOW_STREAM=1]=\"LOW_STREAM\",e[e.AUDIO_ONLY=2]=\"AUDIO_ONLY\",e}({}),xU=function(e){return e.TRANSCEIVER_UPDATED=\"transceiver-updated\",e.SEI_TO_SEND=\"sei-to-send\",e.SEI_RECEIVED=\"sei-received\",e.TRACK_UPDATED=\"track-updated\",e}({}),VU=function(e){return e.SOURCE_STATE_CHANGE=\"source-state-change\",e.TRACK_ENDED=\"track-ended\",e.BEAUTY_EFFECT_OVERLOAD=\"beauty-effect-overload\",e.VIDEO_ELEMENT_VISIBLE_STATUS=\"video-element-visible-status\",e.CLOSED=\"closed\",e}({}),FU=function(e){return e.FIRST_FRAME_DECODED=\"first-frame-decoded\",e.VIDEO_ELEMENT_VISIBLE_STATUS=\"video-element-visible-status\",e.VIDEO_STATE_CHANGED=\"video-state-changed\",e}({}),BU=function(e){return e.AUDIO_SOURCE_STATE_CHANGE=\"audio_source_state_change\",e.RECEIVE_TRACK_BUFFER=\"receive_track_buffer\",e.ON_AUDIO_BUFFER=\"on_audio_buffer\",e.UPDATE_SOURCE=\"update_source\",e}({});!function(e){e.UPDATE_TRACK_SOURCE=\"update-track-source\"}({});const jU={sendVolumeLevel:0,sendBitrate:0,sendBytes:0,sendPackets:0,sendPacketsLost:0,sendJitterMs:0,sendRttMs:0,currentPacketLossRate:0},GU={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},WU={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},HU={uplinkNetworkQuality:0,downlinkNetworkQuality:0},KU={transportDelay:0,end2EndDelay:0,receiveBitrate:0,receiveBytes:0,receiveDelay:0,receivePackets:0,receivePacketsLost:0,receiveResolutionHeight:0,receiveResolutionWidth:0,totalDuration:0,totalFreezeTime:0,freezeRate:0,packetLossRate:0,currentPacketLossRate:0,publishDuration:-1};let YU=function(e){return e.ON_TRACK=\"on_track\",e.ON_NODE=\"on_node\",e}({}),qU=function(e){return e.REQUEST_UPDATE_CONSTRAINTS=\"request_update_constraints\",e.REQUEST_CONSTRAINTS=\"request_constraints\",e}({}),zU=function(e){return e.IDLE=\"IDLE\",e.INITING=\"INITING\",e.INITEND=\"INITEND\",e}({}),JU=function(e){return e.STATE_CHANGE=\"state_change\",e.RECORDING_DEVICE_CHANGED=\"recordingDeviceChanged\",e.PLAYOUT_DEVICE_CHANGED=\"playoutDeviceChanged\",e.CAMERA_DEVICE_CHANGED=\"cameraDeviceChanged\",e}({}),XU=function(e){return e.NONE=\"none\",e.INIT=\"init\",e.CANPLAY=\"canplay\",e.PLAYING=\"playing\",e.PAUSED=\"paused\",e.SUSPEND=\"suspend\",e.STALLED=\"stalled\",e.WAITING=\"waiting\",e.ERROR=\"error\",e.DESTROYED=\"destroyed\",e.ABORT=\"abort\",e.ENDED=\"ended\",e.EMPTIED=\"emptied\",e.LOADEDDATA=\"loadeddata\",e}({}),QU=function(e){return e[e.VideoStateStopped=0]=\"VideoStateStopped\",e[e.VideoStateStarting=1]=\"VideoStateStarting\",e[e.VideoStateDecoding=2]=\"VideoStateDecoding\",e[e.VideoStateFrozen=3]=\"VideoStateFrozen\",e}({});const ZU={uninit:100,none:110,init:120,loadeddata:130,canplay:200,playing:210,paused:220,suspend:300,stalled:310,waiting:320,error:330,destroyed:340,abort:350,ended:360,emptied:370};let $U=function(e){return e.OPEN=\"open\",e.MESSAGE=\"message\",e.CLOSE=\"close\",e.CLOSING=\"closing\",e.ERROR=\"error\",e}({});function ex(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function tx(e){for(var t=1;t{var e;oA.reportApiInvoke(null,{name:CI.GET_MEDIA_STREAM_TRACK,options:[],tag:vI.TRACER}).onSuccess((null===(e=this._mediaStreamTrack)||void 0===e?void 0:e.label)||\"\")}),this.mediaStreamTrack.id||this.getTrackId()),this._mediaStreamTrack}getRTCRtpTransceiver(e){return e===kU.LOW_STREAM?this._lowRtpTransceiver:this._rtpTransceiver}getMediaStreamTrackSettings(){return this.getMediaStreamTrack(!0).getSettings()}close(){this._isClosed=!0,this._lowRtpTransceiver=void 0,this._rtpTransceiver=void 0,function(e){const t=NU.indexOf(e);-1!==t&&NU.splice(t,1)}(this),this.emit(VU.CLOSED),this.removeAllListeners(xU.SEI_RECEIVED)}_updateRtpTransceiver(e,t){if(t===kU.LOW_STREAM){if(this._lowRtpTransceiver===e)return;this._lowRtpTransceiver=e}else{if(this._rtpTransceiver===e)return;this._rtpTransceiver=e}this.emit(xU.TRANSCEIVER_UPDATED,e,t)}}class ox extends rx{get isExternalTrack(){return this._isExternalTrack}get muted(){return this._muted}get enabled(){return this._enabled}get processorContext(){return this._processorContext}constructor(e,t){super(e,t),ix(this,\"_enabled\",!0),ix(this,\"_muted\",!1),ix(this,\"_isExternalTrack\",!1),ix(this,\"_isClosed\",!1),ix(this,\"_enabledMutex\",void 0),ix(this,\"processor\",void 0),ix(this,\"_processorContext\",void 0),ix(this,\"_handleTrackEnded\",(()=>{this.onTrackEnded()})),this._enabledMutex=new uy(\"\".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,Qy.debug(\"[\".concat(this.getTrackId(),\"] close\")),this.emit(PU.NEED_CLOSE),super.close())}async _updateOriginMediaStreamTrack(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];this._isExternalTrack=i,e!==this._originMediaStreamTrack&&(this._originMediaStreamTrack&&(this._originMediaStreamTrack.removeEventListener(\"ended\",this._handleTrackEnded),t&&this._originMediaStreamTrack.stop()),e.addEventListener(\"ended\",this._handleTrackEnded),this._originMediaStreamTrack=e,this._muted&&(this._originMediaStreamTrack.enabled=!1),this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await MI(this,PU.NEED_REPLACE_TRACK,this),this.processor&&this._processorContext&&this.processor.updateInput({track:this._originMediaStreamTrack,context:this._processorContext}))}_getDefaultPlayerConfig(){return{}}onTrackEnded(){Qy.debug(\"[\".concat(this.getTrackId(),\"] track ended\")),this.safeEmit(VU.TRACK_ENDED)}stateCheck(e,t){if(Qy.debug(\"check track state, [muted: \".concat(this._muted,\", enabled: \").concat(this._enabled,\"] to [\").concat(e,\": \").concat(t,\"]\")),nI(t,e),this._enabled&&this._muted&&\"enabled\"===e&&!1===t)throw new iI(tI.TRACK_STATE_UNREACHABLE,\"cannot set enabled while the track is muted\").print(\"error\",Qy);if(!this._enabled&&!this._muted&&\"muted\"===e&&!0===t)throw new iI(tI.TRACK_STATE_UNREACHABLE,\"cannot set muted while the track is disabled\").print(\"error\",Qy)}getProcessorStats(){return this._processorContext&&this._processorContext.gatherStats()||[]}getProcessorUsage(){return this._processorContext?this._processorContext.gatherUsage():Gu.resolve([])}}const sx=window.AudioContext||window.webkitAudioContext;let ax=null;const cx=new class extends SI{constructor(){super(...arguments),ix(this,\"prevState\",void 0),ix(this,\"curState\",void 0),ix(this,\"currentTime\",void 0),ix(this,\"currentTimeStuckAt\",void 0),ix(this,\"interruptDetectorTrack\",void 0),ix(this,\"onLocalAudioTrackMute\",(()=>{Qy.info(\"ios15-interruption-start\"),this.emit(mU.IOS_15_16_INTERRUPTION_START)})),ix(this,\"onLocalAudioTrackUnmute\",(async()=>{Qy.info(\"ios15-interruption-end\"),\"running\"!==this.curState||this.duringInterruption?Qy.info(\"ios15-interruption-end-canceled\"):(ax&&await ax.suspend(),this.emit(mU.IOS_15_16_INTERRUPTION_END))}))}get duringInterruption(){return\"running\"===this.prevState&&\"interrupted\"===this.curState}bindInterruptDetectorTrack(e){Qy.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){Qy.debug(\"webaudio unbindInterruptDetectorTrack \".concat(e.getTrackId())),this.interruptDetectorTrack&&this.interruptDetectorTrack===e&&(this.interruptDetectorTrack._mediaStreamTrack&&(this.interruptDetectorTrack._mediaStreamTrack.onmute=null,this.interruptDetectorTrack._mediaStreamTrack.onunmute=null),this.interruptDetectorTrack=void 0)}};function dx(){if(!ax){if(function(){if(!sx)return void Qy.error(\"your browser is not support web audio\");Qy.info(\"create audio context\");const e=tx({},Dy(\"WEBAUDIO_INIT_OPTIONS\"));Qy.debug(\"audio context init option:\",JSON.stringify(e)),ax=new sx(e),cx.curState=ax.state,ax.onstatechange=()=>{cx.prevState=cx.curState,cx.curState=ax?ax.state:void 0;const{prevState:e,curState:t}=cx,i=\"running\"===t,n=\"interrupted\"===t,r=\"running\"===e,o=\"suspended\"===e,s=\"interrupted\"===e,a=Iv().osVersion;(Lv()||Kv())&&r&&n&&(Qy.info(\"ios\".concat(a,\"-interruption-start\")),cx.emit(mU.IOS_INTERRUPTION_START)),(Lv()||Kv())&&(o||s)&&i&&(Qy.info(\"ios\".concat(a,\"-interruption-end\")),cx.emit(mU.IOS_INTERRUPTION_END)),e!==t&&cx.emit(mU.STATE_CHANGE,t,e)},setInterval((()=>{var e;const t=null===(e=ax)||void 0===e?void 0:e.currentTime;cx.currentTime!==t?(cx.currentTimeStuckAt&&(Qy.debug(\"AudioContext current time resume at \".concat(t)),cx.currentTimeStuckAt=void 0),cx.currentTime=t):(t!==cx.currentTimeStuckAt&&(oA.reportApiInvoke(null,{name:\"WEB_AUDIO_CURRENT_TIME_STUCK\",options:{currentTime:t},tag:vI.TRACER}).onSuccess(),Qy.warning(\"AudioContext current time stuck at \".concat(t))),cx.currentTimeStuckAt=t)}),5e3),async function(e){const t=[\"click\",\"contextmenu\",\"auxclick\",\"dblclick\",\"mousedown\",\"mouseup\",\"touchend\",\"keydown\",\"keyup\"];let i,n=!1,r=!1,o=!1;function s(t){\"running\"===e.state?a(!1):Lv()||Kv()?\"suspended\"===e.state&&(a(!0),t&&e.resume().then(c,c)):\"closed\"!==e.state&&(a(!0),t&&e.resume().then(c,c))}function a(e){if(n!==e){n=e;for(let i=0,n=t;i\",i=n.children.item(0),i.controls=!1,i.disableRemotePlayback=!0,i.preload=\"auto\",i.srcObject=t.stream,l(!0)}cx.on(mU.STATE_CHANGE,(function(){s(!0)})),s(!1)}(ax)}(),!ax)throw new iI(tI.NOT_SUPPORTED,\"can not create audio context\");return ax}return ax}function lx(e){if(function(){if(null!==hx)return hx;const e=dx(),t=e.createBufferSource(),i=e.createGain(),n=e.createGain();t.connect(i),t.connect(n),t.disconnect(i);let r=!1;try{t.disconnect(i)}catch(e){r=!0}return t.disconnect(),hx=r,r}())return;const t=e.connect,i=e.disconnect;e.connect=(i,n,r)=>{var o;return e._inputNodes||(e._inputNodes=[]),Dn(o=e._inputNodes).call(o,i)||(i instanceof AudioNode?(e._inputNodes.push(i),t.call(e,i,n,r)):t.call(e,i,n)),e},e.disconnect=(n,r,o)=>{i.call(e),n?FI(e._inputNodes,n):e._inputNodes=[];for(const i of e._inputNodes)t.call(e,i)}}let hx=null;function ux(e,t){let i=!1;const n=1/t;if(Dy(\"DISABLE_WEBAUDIO\")){const t=window.setInterval((()=>{i?window.clearInterval(t):e(performance.now()/1e3)}),1e3*n)}else{const t=dx();let r=t.createGain();r.gain.value=0,r.connect(t.destination);const o=()=>{if(i)return void(r=null);const s=t.createOscillator();s.onended=o,s.connect(r),s.start(0),s.stop(t.currentTime+n),e(t.currentTime)};o()}return()=>{i=!0}}class px{constructor(){ix(this,\"context\",void 0),ix(this,\"analyserNode\",void 0),ix(this,\"sourceNode\",void 0),this.context=dx(),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||Lv()||Kv()||\"running\"!==this.context.state&&this.context.resume(),!this.analyserNode)return 0;const e=new Float32Array(this.analyserNode.fftSize);if(this.analyserNode.getFloatTimeDomainData)this.analyserNode.getFloatTimeDomainData(e);else{const t=new Uint8Array(this.analyserNode.fftSize);this.analyserNode.getByteTimeDomainData(t);for(let i=0;ie+t*t),0)/e.length;return Math.max(10*Math.log10(t)+100,0)/100}getAnalyserNode(){return this.analyserNode}rebuildAnalyser(){try{var e,t;null===(e=this.sourceNode)||void 0===e||e.disconnect(this.analyserNode),this.analyserNode=this.context.createAnalyser(),this.analyserNode.fftSize=2048,this.analyserNode.smoothingTimeConstant=.4,null===(t=this.sourceNode)||void 0===t||t.connect(this.analyserNode)}catch(e){Qy.warning(\"rebuild analyser node failed.\")}}destroy(){this.updateSource(void 0)}}class _x extends SI{get processSourceNode(){return this.sourceNode}set processedNode(e){var t;if(!this.isDestroyed&&this._processedNode!==e){try{var i;null===(i=this.sourceNode)||void 0===i||i.disconnect(this.outputNode)}catch(e){}null===(t=this._processedNode)||void 0===t||t.disconnect(),this._processedNode=e,this.connect()}}get processedNode(){return this._processedNode}constructor(){super(),ix(this,\"outputNode\",void 0),ix(this,\"outputTrack\",void 0),ix(this,\"isPlayed\",!1),ix(this,\"sourceNode\",void 0),ix(this,\"context\",void 0),ix(this,\"audioBufferNode\",void 0),ix(this,\"destNode\",void 0),ix(this,\"audioOutputLevel\",0),ix(this,\"volumeLevelAnalyser\",void 0),ix(this,\"_processedNode\",void 0),ix(this,\"playNode\",void 0),ix(this,\"isDestroyed\",!1),ix(this,\"onNoAudioInput\",void 0),ix(this,\"isNoAudioInput\",!1),ix(this,\"_noAudioInputCount\",0),this.context=dx(),this.playNode=this.context.destination,this.outputNode=this.context.createGain(),lx(this.outputNode),this.volumeLevelAnalyser=new px}startGetAudioBuffer(e){this.audioBufferNode||(this.audioBufferNode=this.context.createScriptProcessor(e),this.outputNode.connect(this.audioBufferNode),this.audioBufferNode.connect(this.context.destination),this.audioBufferNode.onaudioprocess=e=>{this.emit(BU.ON_AUDIO_BUFFER,function(e){for(let t=0;t{cx.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;Lv()||Kv()?\"suspended\"===this.context.state&&this.context.resume():\"running\"!==this.context.state&&this.context.resume();const t=this.volumeLevelAnalyser.getAnalyserNode();let i;t.getFloatTimeDomainData?(i=new Float32Array(t.fftSize),t.getFloatTimeDomainData(i)):(i=new Uint8Array(t.fftSize),t.getByteTimeDomainData(i));let n=!1;for(let e=0;e{if(Qy.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 Qy.debug(\"rebuild web audio success, current volume status\",this.getAccurateVolumeLevel());this.context.resume().then((()=>Qy.info(\"resume success\"))),Qy.debug(\"rebuild web audio because of ios 12 bugs\"),this.disconnect();const e=this.track;this.track=this.track.clone(),this.isCurrentTrackCloned?e.stop():this.isCurrentTrackCloned=!0;const t=new MediaStream([this.track]);this.sourceNode=this.context.createMediaStreamSource(t),lx(this.sourceNode),this.volumeLevelAnalyser.rebuildAnalyser();const i=this.outputNode.gain.value;this.outputNode=this.context.createGain(),this.outputNode.gain.setValueAtTime(i,this.context.currentTime),lx(this.outputNode),this.emit(BU.UPDATE_SOURCE),this.connect(),this.audioElement.srcObject=t,this.isPlayed&&this.play(this.playNode),this.checkHasAudioInput()})),\"audio\"!==e.kind)throw new iI(tI.UNEXPECTED_ERROR);this.track=e;const r=new MediaStream([this.track]);if(this.isRemoteTrack=!!t,this.sourceNode=this.context.createMediaStreamSource(r),lx(this.sourceNode),i){const e=i.clone();e.enabled=!0,this.clonedTrack=e,Qy.debug(\"create an unmuted track \".concat(e.id,\" from the original track \").concat(i.id,\" to get the volume\"));const t=this.context.createMediaStreamSource(new MediaStream([e]));lx(t),this.originVolumeLevelAnalyser=new px,this.originVolumeLevelAnalyser.updateSource(t)}this.connect(),this.audioElement=document.createElement(\"audio\"),this.audioElement.srcObject=r;const o=Iv();t&&o.os===Sv.IOS&&Number(null===(n=o.osVersion)||void 0===n?void 0:n.split(\".\")[0])<15&&(cx.on(mU.STATE_CHANGE,(()=>{\"suspended\"===this.context.state?document.body.addEventListener(\"click\",this.rebuildWebAudio,!0):\"running\"===this.context.state&&this.rebuildWebAudio()})),this.checkHasAudioInput().then((e=>{e||document.body.addEventListener(\"click\",this.rebuildWebAudio,!0)})))}updateTrack(e){this.sourceNode.disconnect(),this.track=e,this.isCurrentTrackCloned=!1;const t=new MediaStream([e]);this.sourceNode=this.context.createMediaStreamSource(t),lx(this.sourceNode),this.processedNode||this.sourceNode.connect(this.outputNode),this.emit(BU.UPDATE_SOURCE),this.audioElement.srcObject=t}destroy(){var e;this.audioElement.srcObject=null,this.audioElement.remove(),cx.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),Qy.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]));lx(i),this.originVolumeLevelAnalyser&&this.originVolumeLevelAnalyser.updateSource(i)}getOriginVolumeLevel(){return this.originVolumeLevelAnalyser?this.originVolumeLevelAnalyser.getVolumeLevel():this.getAccurateVolumeLevel()}}async function mx(e,t,i){const n=(e,t)=>e?\"number\"!=typeof e?e.max||e.exact||e.ideal||e.min||t:e:t,r={audio:!!i&&{mandatory:{chromeMediaSource:\"desktop\"}},video:{mandatory:{chromeMediaSource:\"desktop\",chromeMediaSourceId:e,maxHeight:n(t.height,1080),maxWidth:n(t.width,1920)}}};return t.frameRate&&\"number\"!=typeof t.frameRate?(r.video.mandatory.maxFrameRate=t.frameRate.max,r.video.mandatory.minFrameRate=t.frameRate.min):\"number\"==typeof t.frameRate&&(r.video.mandatory.maxFrameRate=t.frameRate),await navigator.mediaDevices.getUserMedia(r)}async function fx(e,t){const i=await Tx(e.mediaSource),{sourceId:n,audio:r}=await function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return new Gu(((i,n)=>{const r=document.createElement(\"div\");r.innerText=\"share screen\",r.setAttribute(\"style\",\"text-align: center; height: 25px; line-height: 25px; border-radius: 4px 4px 0 0; background: #D4D2D4; border-bottom: solid 1px #B9B8B9;\");const o=document.createElement(\"div\");o.setAttribute(\"style\",\"width: 100%; height: 500px; padding: 15px 25px ; box-sizing: border-box;\");const s=document.createElement(\"div\");s.innerText=\"Agora Web Screensharing wants to share the contents of your screen with webdemo.agorabeckon.com. Choose what you'd like to share.\",s.setAttribute(\"style\",\"height: 12%;\");const a=document.createElement(\"div\");a.setAttribute(\"style\",\"width: 100%; height: 80%; background: #FFF; border: solid 1px #CBCBCB; display: flex; flex-wrap: wrap; justify-content: space-around; overflow-y: scroll; padding: 0 15px; box-sizing: border-box;\");const c=document.createElement(\"div\");c.setAttribute(\"style\",\"display: flex; justify-content: space-between; padding: 16px 0;\");const d=document.createElement(\"button\");d.innerHTML=\"cancel\",d.setAttribute(\"style\",\"width: 85px;\"),d.onclick=()=>{document.body.removeChild(u);const e=new Error(\"NotAllowedError\");e.name=\"NotAllowedError\",n(e)};let l=t;const h=document.createElement(\"div\");if(t){const e=document.createElement(\"input\");e.setAttribute(\"type\",\"checkbox\");const t=document.createElement(\"span\");e.setAttribute(\"style\",\"margin-right: 6px;\"),t.innerText=\"Share audio\",e.checked=l,e.onchange=()=>{l=e.checked},h.appendChild(e),h.appendChild(t)}c.appendChild(h),c.appendChild(d),o.appendChild(s),o.appendChild(a),o.appendChild(c);const u=document.createElement(\"div\");u.setAttribute(\"style\",\"position: fixed; z-index: 99999999; top: 50%; left: 50%; width: 620px; height: 525px; background: #ECECEC; border-radius: 4px; -webkit-transform: translate(-50%,-50%); transform: translate(-50%,-50%);\"),u.appendChild(r),u.appendChild(o),document.body.appendChild(u),e.map((e=>{if(e.id){const t=document.createElement(\"div\");t.setAttribute(\"style\",\"width: 30%; height: 160px; padding: 20px 0; text-align: center;box-sizing: content-box;\");let n=e.thumbnail;try{const{width:e}=n.getSize();e>1920&&(n=n.resize({width:1920}))}catch(e){throw e&&e.message.startsWith(\"Illegal invocation\")&&console.error(\"Operate thumbnail error, please try to set contextIsolation: false. (https://github.com/electron/electron/issues/34953)\"),e}t.innerHTML=''+e.name.replace(/[\\u00A0-\\u9999<>\\&]/g,(function(e){return\"\"+e.charCodeAt(0)+\";\"}))+\"\",t.onclick=()=>{document.body.removeChild(u),i({sourceId:e.id,audio:l})},a.appendChild(t)}}))}))}(i,t);return await mx(n,e,r)}async function Tx(e){let t=[\"window\",\"screen\"];\"application\"!==e&&\"window\"!==e||(t=[\"window\"]),\"screen\"===e&&(t=[\"screen\"]);const i=RI();if(!i)throw console.error(\"failed to fetch electron, please mount it to window\"),new iI(tI.ELECTRON_IS_NULL);let n=null;try{var r;n=(null===(r=i.desktopCapturer)||void 0===r?void 0:r.getSources({types:t}))||i.ipcRenderer.invoke(\"DESKTOP_CAPTURER_GET_SOURCES\",{types:t})}catch(e){n=null}n&&n.then||(n=new Gu(((e,n)=>{i.desktopCapturer.getSources({types:t},((t,i)=>{t?n(t):e(i)}))})));try{return await n}catch(e){throw new iI(tI.ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR,e.toString())}}const Sx=new uy(\"safari\");let gx=!1,Rx=!1;async function Cx(e,t){let i=0,n=null;for(;i<2;)try{n=await vx(e,t,i>0);break}catch(e){if(e instanceof iI)throw Qy.error(\"[\".concat(t,\"] \").concat(e.toString())),e;const n=Ix(e.name||e.code||e,e.message);if(n.code===tI.MEDIA_OPTION_INVALID){Qy.debug(\"[\".concat(t,\"] detect media option invalid, retry\")),i+=1,await $I(500);continue}throw Qy.error(\"[\".concat(t,\"] \").concat(n.toString())),n}if(!n)throw new iI(tI.UNEXPECTED_ERROR,\"can not find stream after getUserMedia\");return n}async function vx(e,t,i){if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)throw new iI(tI.NOT_SUPPORTED,\"can not find getUserMedia\");i&&(e.video&&(delete e.video.width,delete e.video.height),e.screen&&(delete e.screen.width,delete e.screen.height));const n=_U(),r=new MediaStream;if(e.audioSource&&r.addTrack(e.audioSource),e.videoSource&&r.addTrack(e.videoSource),!e.audio&&!e.video&&!e.screen)return Qy.debug(\"Using Video Source/ Audio Source\"),r;if(e.screen)if(RI())e.screen.sourceId?yx(r,await mx(e.screen.sourceId,e.screen,e.screenAudio)):yx(r,await fx(e.screen,e.screenAudio));else if(Ov()&&e.screen.extensionId&&e.screen.mandatory){if(!n.getStreamFromExtension)throw new iI(tI.NOT_SUPPORTED,\"This browser does not support screen sharing\");Qy.debug(\"[\".concat(t,'] Screen access on chrome stable, looking for extension\"'));const i=await(s=e.screen.extensionId,a=t,new Gu(((e,t)=>{try{chrome.runtime.sendMessage(s,{getStream:!0},(i=>{if(!i||!i.streamId)return Qy.error(\"[\".concat(a,\"] No response from Chrome Plugin. Plugin not installed properly\"),i),void t(new iI(tI.CHROME_PLUGIN_NO_RESPONSE,\"No response from Chrome Plugin. Plugin not installed properly\"));e(i.streamId)}))}catch(e){Qy.error(\"[\".concat(a,\"] AgoraRTC screensharing plugin is not accessible(\").concat(s,\")\"),e.toString()),t(new iI(tI.CHROME_PLUGIN_NOT_INSTALL))}})));e.screen.mandatory.chromeMediaSourceId=i,yx(r,await navigator.mediaDevices.getUserMedia({video:{mandatory:e.screen.mandatory}}))}else if(n.getDisplayMedia){var o;e.screen.mediaSource&&DU(e.screen.mediaSource);const i={width:e.screen.width,height:e.screen.height,frameRate:e.screen.frameRate,displaySurface:null!==(o=e.screen.displaySurface)&&void 0!==o?o:\"screen\"===e.screen.mediaSource?\"monitor\":e.screen.mediaSource},{selfBrowserSurface:n,surfaceSwitching:s,systemAudio:a}=e.screen,c={selfBrowserSurface:n,surfaceSwitching:s,systemAudio:a};!n&&delete c.selfBrowserSurface,!s&&delete c.surfaceSwitching,!a&&delete c.systemAudio,Qy.debug(\"[\".concat(t,\"] getDisplayMedia:\"),JSON.stringify({video:i,audio:!!e.screenAudio,controls:c})),yx(r,await navigator.mediaDevices.getDisplayMedia(tx({video:i,audio:!!e.screenAudio},c)))}else{if(!Pv())throw Qy.error(\"[\".concat(t,\"] This browser does not support screenSharing\")),new iI(tI.NOT_SUPPORTED,\"This browser does not support screen sharing\");{e.screen.mediaSource&&DU(e.screen.mediaSource);const i={video:{mediaSource:e.screen.mediaSource,width:e.screen.width,height:e.screen.height,frameRate:e.screen.frameRate}};Qy.debug(\"[\".concat(t,\"] getUserMedia: \").concat(JSON.stringify(i))),yx(r,await navigator.mediaDevices.getUserMedia(i))}}var s,a;if(!e.video&&!e.audio)return r;let c={video:e.video,audio:e.audio},d=Dy(\"MEDIA_DEVICE_CONSTRAINTS\");if(d)try{\"string\"==typeof d&&(d=JSON.parse(d)),c=sy(c,d)}catch(e){}Qy.debug(\"[\".concat(t,\"] GetUserMedia\"),JSON.stringify(c)),Iv();let l,h=null;(Nv()||Lv()||wv())&&(h=await Sx.lock());try{l=await navigator.mediaDevices.getUserMedia(c)}catch(e){throw h&&h(),e}return c.audio&&(gx=!0),c.video&&(Rx=!0),yx(r,l),h&&h(),r}function Ix(e,t){switch(e){case\"Starting video failed\":case\"OverconstrainedError\":case\"TrackStartError\":return new iI(tI.MEDIA_OPTION_INVALID,\"\".concat(e,\": \").concat(t));case\"NotFoundError\":case\"DevicesNotFoundError\":return new iI(tI.DEVICE_NOT_FOUND,\"\".concat(e,\": \").concat(t));case\"NotSupportedError\":return new iI(tI.NOT_SUPPORTED,\"\".concat(e,\": \").concat(t));case\"NotReadableError\":return new iI(tI.NOT_READABLE,\"\".concat(e,\": \").concat(t));case\"InvalidStateError\":case\"NotAllowedError\":case\"PERMISSION_DENIED\":case\"PermissionDeniedError\":return new iI(tI.PERMISSION_DENIED,\"\".concat(e,\": \").concat(t));case\"ConstraintNotSatisfiedError\":return new iI(tI.CONSTRAINT_NOT_SATISFIED,\"\".concat(e,\": \").concat(t));default:return Qy.error(\"getUserMedia unexpected error\",e),new iI(tI.UNEXPECTED_ERROR,\"\".concat(e,\": \").concat(t))}}function yx(e,t){const i=e.getVideoTracks()[0],n=e.getAudioTracks()[0],r=t.getVideoTracks()[0],o=t.getAudioTracks()[0];o&&(n&&e.removeTrack(n),e.addTrack(o)),r&&(i&&e.removeTrack(i),e.addTrack(r))}const Ax=new class extends SI{get state(){return this._state}set state(e){e!==this._state&&(this.emit(JU.STATE_CHANGE,e),this._state=e)}constructor(){super(),ix(this,\"_state\",zU.IDLE),ix(this,\"isAccessMicrophonePermission\",!1),ix(this,\"isAccessCameraPermission\",!1),ix(this,\"lastAccessMicrophonePermission\",!1),ix(this,\"lastAccessCameraPermission\",!1),ix(this,\"checkdeviceMatched\",!1),ix(this,\"deviceInfoMap\",new Map),this.init().then((()=>{navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener(\"devicechange\",this.updateDevicesInfo.bind(this)),window.setInterval((()=>{(Dy(\"ENUMERATE_DEVICES_INTERVAL\")||(Xv()||Av()===Sv.HARMONY_OS)&&Jv())&&this.updateDevicesInfo()}),Dy(\"ENUMERATE_DEVICES_INTERVAL_TIME\"))})).catch((e=>Qy.error(e.toString())))}async enumerateDevices(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices)return new iI(tI.NOT_SUPPORTED,\"enumerateDevices() not supported.\").throw();const n=await navigator.mediaDevices.enumerateDevices(),r=this.checkMediaDeviceInfoIsOk(n);let o=!this.isAccessMicrophonePermission&&e,s=!this.isAccessCameraPermission&&t;r.audio&&(o=!1),r.video&&(s=!1);let a=null,c=null,d=null;if(!i&&(o||s)){if(Sx.isLocked&&(Qy.debug(\"[device manager] wait GUM lock\"),(await Sx.lock())(),Qy.debug(\"[device manager] GUM unlock\")),gx&&(o=!1,this.isAccessMicrophonePermission=!0),Rx&&(s=!1,this.isAccessCameraPermission=!0),Qy.debug(\"[device manager] check media device permissions\",e,t,o,s),o&&s){try{d=await navigator.mediaDevices.getUserMedia({audio:!0,video:!0})}catch(e){const t=Ix(e.name||e.code||e,e.message);if(t.code===tI.PERMISSION_DENIED)throw t;Qy.warning(\"getUserMedia failed in getDevices\",t)}this.isAccessCameraPermission=!0,this.isAccessMicrophonePermission=!0}else if(o){try{a=await navigator.mediaDevices.getUserMedia({audio:e})}catch(e){const t=Ix(e.name||e.code||e,e.message);if(t.code===tI.PERMISSION_DENIED)throw t;Qy.warning(\"getUserMedia failed in getDevices\",t)}this.isAccessMicrophonePermission=!0}else if(s){try{c=await navigator.mediaDevices.getUserMedia({video:t})}catch(e){const t=Ix(e.name||e.code||e,e.message);if(t.code===tI.PERMISSION_DENIED)throw t;Qy.warning(\"getUserMedia failed in getDevices\",t)}this.isAccessCameraPermission=!0}Qy.debug(\"[device manager] mic permission\",e,\"cam permission\",t)}try{const e=await navigator.mediaDevices.enumerateDevices();return a&&a.getTracks().forEach((e=>e.stop())),c&&c.getTracks().forEach((e=>e.stop())),d&&d.getTracks().forEach((e=>e.stop())),a=null,c=null,d=null,e}catch(e){return a&&a.getTracks().forEach((e=>e.stop())),c&&c.getTracks().forEach((e=>e.stop())),d&&d.getTracks().forEach((e=>e.stop())),a=null,c=null,d=null,new iI(tI.ENUMERATE_DEVICES_FAILED,e.toString()).throw()}}async getRecordingDevices(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return(await this.enumerateDevices(!0,!1,e)).filter((e=>\"audioinput\"===e.kind))}async getCamerasDevices(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return(await this.enumerateDevices(!1,!0,e)).filter((e=>\"videoinput\"===e.kind))}async getSpeakers(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return(await this.enumerateDevices(!0,!1,e)).filter((e=>\"audiooutput\"===e.kind))}searchDeviceIdByName(e){let t=null;return this.deviceInfoMap.forEach((i=>{i.device.label===e&&(t=i.device.deviceId)})),t}async getDeviceById(e){const t=(await this.enumerateDevices(!0,!0,!0)).find((t=>t.deviceId===e));if(!t)throw new iI(tI.DEVICE_NOT_FOUND,\"deviceId: \".concat(e));return t}async init(){this.state=zU.INITING;try{await this.updateDevicesInfo(),this.state=zU.INITEND}catch(e){throw Qy.warning(\"Device Detection functionality cannot start properly.\",e.toString()),this.state=zU.IDLE,(\"boolean\"==typeof isSecureContext?isSecureContext:\"https:\"===location.protocol||\"file:\"===location.protocol||\"localhost\"===location.hostname||\"127.0.0.1\"===location.hostname||\"::1\"===location.hostname)||new iI(tI.WEB_SECURITY_RESTRICT,\"Your context is limited by web security, please try using https protocol or localhost.\").throw(),e}}async updateDevicesInfo(){const e=await this.enumerateDevices(!0,!0,!0),t=Date.now(),i=[];if(e[0]&&e[0].label&&!1===this.checkdeviceMatched){this.checkdeviceMatched=!0;const t=e.find((e=>\"audioinput\"===e.kind&&\"default\"===e.deviceId)),i=e.find((e=>\"audiooutput\"===e.kind&&\"default\"===e.deviceId));t&&i?i.groupId===t.groupId?Qy.debug(\"[device-check] default input \".concat(t.label,\" and output \").concat(i.label,\" is the same group\")):Qy.warning(\"[device-check] default input \".concat(t.label,\" and output \").concat(i.label,\" is not the same group\")):Qy.debug(\"[device-check] default input or output not found\")}const n=this.checkMediaDeviceInfoIsOk(e);if(e.forEach((e=>{if(!e.deviceId)return;const n=this.deviceInfoMap.get(\"\".concat(e.kind,\"_\").concat(e.deviceId));if(\"ACTIVE\"!==(n?n.state:\"INACTIVE\")){const n={initAt:t,updateAt:t,device:e,state:\"ACTIVE\"};this.deviceInfoMap.set(\"\".concat(e.kind,\"_\").concat(e.deviceId),n),i.push(n)}n&&(n.updateAt=t)})),this.deviceInfoMap.forEach(((e,n)=>{\"ACTIVE\"===e.state&&e.updateAt!==t&&(e.state=\"INACTIVE\",i.push(e))})),this.state!==zU.INITEND)return n.audio&&(this.lastAccessMicrophonePermission=!0,this.isAccessMicrophonePermission=!0),void(n.video&&(this.lastAccessCameraPermission=!0,this.isAccessCameraPermission=!0));i.forEach((e=>{switch(e.device.kind){case\"audioinput\":this.lastAccessMicrophonePermission&&this.isAccessMicrophonePermission&&this.emit(JU.RECORDING_DEVICE_CHANGED,e);break;case\"videoinput\":this.lastAccessCameraPermission&&this.isAccessCameraPermission&&this.emit(JU.CAMERA_DEVICE_CHANGED,e);break;case\"audiooutput\":this.lastAccessMicrophonePermission&&this.isAccessMicrophonePermission&&this.emit(JU.PLAYOUT_DEVICE_CHANGED,e)}})),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)),i=e.filter((e=>\"videoinput\"===e.kind)),n={audio:!1,video:!1};for(const e of t)if(e.label&&e.deviceId){n.audio=!0;break}for(const e of i)if(e.label&&e.deviceId){n.video=!0;break}return n}};let bx=!1;const wx=new class extends SI{constructor(){super(...arguments),ix(this,\"onAutoplayFailed\",void 0),ix(this,\"onAudioAutoplayFailed\",void 0)}};function Ox(){if(Iv(),!bx){const e=t=>{t.preventDefault(),bx=!1,Qv()?document.body.removeEventListener(\"click\",e,!0):(document.body.removeEventListener(\"touchstart\",e,!0),document.body.removeEventListener(\"mousedown\",e,!0))};bx=!0,Qv()?document.body.addEventListener(\"click\",e,!0):(document.body.addEventListener(\"touchstart\",e,!0),document.body.addEventListener(\"mousedown\",e,!0)),Qy.info(\"detect media autoplay failed, document: https://docs.agora.io/cn/Voice/autoplay_policy_web_ng?platform=Web\"),wx.onAutoplayFailed?wx.onAutoplayFailed():wx.onAudioAutoplayFailed?Qy.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 .\"):Qy.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 .\"),wx.emit(\"autoplay-failed\")}}function Nx(e,t,i,n){if(!e)return;const r=oA.getBaseInfoBySessionId(e);if(!r)return;const o=r.info,s=Date.now(),a=tx(tx({},o),{},{vid:void 0===o.vid?0:Number(o.vid),lts:s,elapse:s-r.startTime,cbRegistered:wx.onAutoplayFailed||wx.onAudioAutoplayFailed?1:-1,errorMsg:i,mediaType:t,trackId:n,extend:void 0});oA.send({type:iA.AUTOPLAY_FAILED,data:a},!0)}const Dx=[\"play\",\"playing\",\"loadeddata\",\"canplay\",\"pause\",\"stalled\",\"suspend\",\"waiting\",\"abort\",\"emptied\",\"ended\",\"error\"],Px=new class{constructor(){ix(this,\"onAutoplayFailed\",void 0),ix(this,\"elementMap\",new Map),ix(this,\"elementStateMap\",new Map),ix(this,\"elementsNeedToResume\",[]),ix(this,\"sinkIdMap\",new Map),ix(this,\"autoResumeAfterInterruption\",(e=>{Array.from(this.elementMap.entries()).forEach((t=>{let[i,n]=t;const r=this.elementStateMap.get(i),o=n.srcObject.getAudioTracks()[0],s=o&&o.readyState;if(Qy.debug(\"resume after interrupted, ele: \".concat(r,\" audio: \").concat(s,\" \").concat(e)),\"live\"===s){if(e)return n.pause(),void n.play();if(\"running\"===cx.curState)return Gv()?(n.pause(),void n.play()):void(r&&\"paused\"===r&&n.play())}}))})),ix(this,\"autoResumeAfterInterruptionOnIOS15_16\",(()=>{Array.from(this.elementMap.entries()).forEach((e=>{let[t,i]=e;const n=i.srcObject.getAudioTracks()[0];n&&\"live\"===n.readyState&&(Qy.debug(\"auto resume after interruption inside autoResumeAfterInterruptionOnIOS15\"),i.pause(),i.play())}))})),this.autoResumeAudioElement(),cx.on(mU.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),cx.on(mU.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16),cx.on(mU.STATE_CHANGE,(()=>{Lv()&&\"suspended\"===cx.prevState&&\"running\"===cx.curState&&this.autoResumeAfterInterruption()}))}async setSinkID(e,t){const i=this.elementMap.get(e);if(this.sinkIdMap.set(e,t),i)try{await i.setSinkId(t)}catch(e){throw new iI(tI.PERMISSION_DENIED,\"can not set sink id: \"+e.toString())}}play(e,t,i,n){if(this.elementMap.has(t))return;const r=document.createElement(\"audio\");r.autoplay=!0,r.srcObject=new MediaStream([e]),this.bindAudioElementEvents(t,r),this.elementMap.set(t,r),this.elementStateMap.set(t,XU.INIT),this.setVolume(t,i);const o=this.sinkIdMap.get(t);if(o)try{r.setSinkId(o).catch((e=>{Qy.warning(\"[\".concat(t,\"] set sink id failed\"),e.toString())}))}catch(e){Qy.warning(\"[\".concat(t,\"] set sink id failed\"),e.toString())}const s=r.play();s&&s.then&&s.catch((e=>{n&&Nx(n,\"audio\",e.message,t),Qy.warning(\"audio element play warning\",e.toString()),this.elementMap.has(t)&&\"NotAllowedError\"===e.name&&(Qy.warning(\"detected audio element autoplay failed\"),this.elementsNeedToResume.push(r),jI((()=>{this.onAutoplayFailed&&this.onAutoplayFailed(),Ox()})))}))}updateTrack(e,t){const i=this.elementMap.get(e);i&&(i.srcObject=new MediaStream([t]))}isPlaying(e){return this.elementMap.has(e)&&\"playing\"===this.elementStateMap.get(e)}setVolume(e,t){const i=this.elementMap.get(e);i&&(t=Math.max(0,Math.min(100,t)),i.volume=t/100)}stop(e){const t=this.elementMap.get(e);if(this.sinkIdMap.delete(e),!t)return;const i=this.elementsNeedToResume.indexOf(t);this.elementsNeedToResume.splice(i,1),t.srcObject=null,t.remove(),this.elementMap.delete(e),this.elementStateMap.delete(e)}bindAudioElementEvents(e,t){Dx.forEach((i=>{t.addEventListener(i,(i=>{const n=this.elementStateMap.get(e),r=\"pause\"===i.type?\"paused\":i.type;if(Qy.debug(\"[\".concat(e,\"] audio-element-status change \").concat(n,\" => \").concat(r)),\"error\"===i.type){const i=null==t?void 0:t.error;i&&Qy.error(\"[\".concat(e,\"] media error, code: \").concat(i.code,\", message: \").concat(i.message))}this.elementStateMap.set(e,r)}))}))}getPlayerState(e){return this.elementStateMap.get(e)||\"uninit\"}autoResumeAudioElement(){const e=()=>{this.elementsNeedToResume.forEach((e=>{e.play().then((e=>{Qy.debug(\"Auto resume audio element success\")})).catch((e=>{Qy.warning(\"Auto resume audio element failed!\",e)}))})),this.elementsNeedToResume=[]};new Gu((e=>{document.body?e():window.addEventListener(\"load\",(()=>e()))})).then((()=>{Qv()?document.body.addEventListener(\"click\",e,!0):(document.body.addEventListener(\"touchstart\",e,!0),document.body.addEventListener(\"mousedown\",e,!0))}))}};function Lx(){return function(e,t,i){const n=i.value;return\"function\"==typeof n&&(i.value=function(){this._isClosed&&new iI(tI.INVALID_OPERATION,\"[\".concat(this.getTrackId(),\"] cannot operate a closed track\")).print(\"warning\",Qy);for(var e=arguments.length,t=new Array(e),i=0;i{r.then(e).catch(t)})):r}),i}}class kx extends SI{constructor(e){super(),ix(this,\"name\",\"VideoProcessorDestination\"),ix(this,\"ID\",\"0\"),ix(this,\"_source\",void 0),ix(this,\"videoContext\",void 0),ix(this,\"inputTrack\",void 0),this.videoContext=e}get kind(){return\"video\"}get enabled(){return!0}pipe(){throw new iI(tI.NOT_SUPPORTED,\"VideoProcessor cannot pipe to any other Processor\")}unpipe(){throw new iI(tI.NOT_SUPPORTED,\"VideoProcessor cannot unpipe to any other Processor\")}enable(){}disable(){}updateInput(e){if(e.context!==this.videoContext)throw new Error(\"ProcessorContext passed to VideoTrack.processorDestination doesn't match it's belonging VideoTrack's context.\\nProbably you are making pipeline like this:\\nvideoTrack1.pipe(processor).pipe(videoTrack2.processorDestination).\");e.track&&e.track!==this.inputTrack&&(this.videoContext.chained=!0,this.inputTrack=e.track,this.emit(YU.ON_TRACK,e.track))}reset(){this.inputTrack=void 0,this.videoContext.chained=!1,this.emit(YU.ON_TRACK,void 0)}}class Mx extends SI{set chained(e){this._chained=e}get chained(){return this._chained}constructor(e,t){super(),ix(this,\"constraintsMap\",new Map),ix(this,\"statsRegistry\",[]),ix(this,\"usageRegistry\",[]),ix(this,\"trackId\",void 0),ix(this,\"direction\",void 0),ix(this,\"_chained\",!1),this.trackId=e,this.direction=t}async getConstraints(){return await kI(this,qU.REQUEST_CONSTRAINTS)}async requestApplyConstraints(e,t){var i;return Qy.info(\"processor \".concat(t.name,\" requestApplyConstraints for \").concat(this.trackId)),e&&this.constraintsMap.set(t,e),MI(this,qU.REQUEST_UPDATE_CONSTRAINTS,Array.from(ub(i=this.constraintsMap).call(i)))}async requestRevertConstraints(e){var t;if(this.constraintsMap.has(e))return Qy.info(\"processor \".concat(e.name,\" requestRevertConstraints for \").concat(this.trackId)),this.constraintsMap.delete(e),MI(this,qU.REQUEST_UPDATE_CONSTRAINTS,Array.from(ub(t=this.constraintsMap).call(t)))}registerStats(e,t,i){this.statsRegistry.find((i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t))||this.statsRegistry.push({processorName:e.name,processorID:e.ID,type:t,cb:i})}unregisterStats(e,t){const i=this.statsRegistry.findIndex((i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t));-1!==i&&this.statsRegistry.splice(i,1)}gatherStats(){const e=[];for(const{processorID:t,processorName:i,type:n,cb:r}of this.statsRegistry)try{const o=r();e.push({processorID:t,processorName:i,type:n,stats:o})}catch(e){Qy.error(new iI(tI.UNEXPECTED_ERROR,e.message))}return e}registerUsage(e,t){this.usageRegistry.find((t=>t.processorID===e.ID&&t.processorName===e.name))||this.usageRegistry.push({processorID:e.ID,processorName:e.name,cb:t})}unregisterUsage(e){const t=this.usageRegistry.findIndex((t=>t.processorID===e.ID&&t.processorName===e.name));-1!==t&&this.usageRegistry.splice(t,1)}async gatherUsage(){const e=[];if(!this.chained)return[];for(const{cb:t}of this.usageRegistry)try{let i=t();i instanceof Gu&&(i=await i),e.push(tx(tx({},i),{},{direction:this.direction}))}catch(e){Qy.error(\"gather extension usage error\",e)}return e}getDirection(){return this.direction}}class Ux extends SI{constructor(e){super(),ix(this,\"name\",\"AudioProcessorDestination\"),ix(this,\"ID\",\"0\"),ix(this,\"inputTrack\",void 0),ix(this,\"inputNode\",void 0),ix(this,\"audioProcessorContext\",void 0),ix(this,\"_source\",void 0),this.audioProcessorContext=e}get kind(){return\"audio\"}get enabled(){return!0}pipe(){throw new iI(tI.NOT_SUPPORTED,\"AudioProcessorDestination cannot pipe to any other Processor\")}unpipe(){throw new iI(tI.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(YU.ON_TRACK,void 0),this.emit(YU.ON_NODE,void 0)}updateInput(e){if(e.context!==this.audioProcessorContext)throw new Error(\"ProcessorContext passed to AudioTrack.processorDestination doesn't match it's belonging AudioTrack's context.\\n Probably you are making pipeline like this: audioTrack1.pipe(processor).pipe(audioTrack2.processorDestination).\");e.track&&this.inputTrack!==e.track&&(this.audioProcessorContext.chained=!0,this.inputTrack=e.track,this.emit(YU.ON_TRACK,this.inputTrack)),e.node&&this.inputNode!==e.node&&(this.audioProcessorContext.chained=!0,this.inputNode=e.node,this.emit(YU.ON_NODE,this.inputNode))}}class xx extends SI{set chained(e){this._chained=e}get chained(){return this._chained}constructor(e,t,i){super(),ix(this,\"constraintsMap\",new Map),ix(this,\"statsRegistry\",[]),ix(this,\"audioContext\",void 0),ix(this,\"trackId\",void 0),ix(this,\"direction\",void 0),ix(this,\"usageRegistry\",[]),ix(this,\"_chained\",!1),this.audioContext=e,this.trackId=t,this.direction=i}async getConstraints(){return kI(this,qU.REQUEST_CONSTRAINTS)}getAudioContext(){return this.audioContext}async requestApplyConstraints(e,t){var i;return Qy.info(\"processor \".concat(t.name,\" requestApplyConstraints for \").concat(this.trackId)),e&&this.constraintsMap.set(t,e),MI(this,qU.REQUEST_UPDATE_CONSTRAINTS,Array.from(ub(i=this.constraintsMap).call(i)))}async requestRevertConstraints(e){var t;if(this.constraintsMap.has(e))return this.constraintsMap.delete(e),MI(this,qU.REQUEST_UPDATE_CONSTRAINTS,Array.from(ub(t=this.constraintsMap).call(t)))}registerStats(e,t,i){this.statsRegistry.find((i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t))||this.statsRegistry.push({processorName:e.name,processorID:e.ID,type:t,cb:i})}unregisterStats(e,t){const i=this.statsRegistry.findIndex((i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t));-1!==i&&this.statsRegistry.splice(i,1)}gatherStats(){const e=[];for(const{processorID:t,processorName:i,type:n,cb:r}of this.statsRegistry)try{const o=r();e.push({processorID:t,processorName:i,type:n,stats:o})}catch(e){Qy.error(new iI(tI.UNEXPECTED_ERROR,e.message))}return e}registerUsage(e,t){this.usageRegistry.find((t=>t.processorID===e.ID&&t.processorName===e.name))||this.usageRegistry.push({processorID:e.ID,processorName:e.name,cb:t})}unregisterUsage(e){const t=this.usageRegistry.findIndex((t=>t.processorID===e.ID&&t.processorName===e.name));-1!==t&&this.usageRegistry.splice(t,1)}async gatherUsage(){const e=[];if(!this.chained)return[];for(const{cb:t}of this.usageRegistry)try{let i=t();i instanceof Gu&&(i=await i),e.push(tx(tx({},i),{},{direction:this.direction}))}catch(e){Qy.error(\"gather extension usage error\",e)}return e}getDirection(){return this.direction}}class Vx extends SI{get isPlayed(){return!0}get isFreeze(){return!1}constructor(){super(),ix(this,\"context\",void 0),ix(this,\"processSourceNode\",void 0),ix(this,\"outputTrack\",void 0),ix(this,\"processedNode\",void 0),ix(this,\"clonedTrack\",void 0),ix(this,\"outputNode\",void 0),this.outputNode=new Fx}setVolume(){}createOutputTrack(){throw new iI(tI.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 Fx{disconnect(){}connect(){}}function Bx(e){return new Gu(((t,i)=>{let n=!1;const r=document.createElement(\"video\");r.setAttribute(\"autoplay\",\"\"),r.setAttribute(\"muted\",\"\"),r.muted=!0,r.autoplay=!0,r.setAttribute(\"playsinline\",\"\"),r.setAttribute(\"style\",\"position: fixed; top: 0; left: 0; width: 1px; height: 1px\"),document.body.appendChild(r);const o=Lv()?\"canplay\":\"playing\";r.addEventListener(o,(()=>{const e=r.videoWidth,i=r.videoHeight;!e&&Pv()||(n=!0,r.srcObject=null,r.remove(),t([e,i]))})),r.srcObject=new MediaStream([e]),r.play().catch(iy),setTimeout((()=>{n||(r.srcObject=null,r.remove(),t([r.videoWidth,r.videoHeight]))}),4e3)}))}function jx(e){const t={};e.facingMode&&(t.facingMode=e.facingMode),e.cameraId&&(t.deviceId={exact:e.cameraId});const i=yU(e.encoderConfig);return null!=i.width&&(t.width=i.width),null!=i.height&&(t.height=i.height),!qv()&&i.frameRate&&(t.frameRate=i.frameRate),Dv()&&\"object\"==typeof t.frameRate&&(t.frameRate.max=60),Pv()&&(t.frameRate={ideal:30,max:30}),t}function Gx(e){const t={};if(qv()||(void 0!==e.AGC&&(t.autoGainControl=e.AGC),void 0!==e.AEC&&(t.echoCancellation=e.AEC),void 0!==e.ANS&&(t.noiseSuppression=e.ANS,Ov()&&e.ANS&&(t.googHighpassFilter=e.ANS))),e.encoderConfig){const i=OU(e.encoderConfig);t.channelCount=i.stereo?2:1,t.sampleRate=i.sampleRate,t.sampleSize=i.sampleSize}return e.microphoneId&&(t.deviceId={exact:e.microphoneId}),Xv()&&(t.sampleRate=void 0),t}const Wx=e=>{const t=e._encoderConfig;if(!t)return;const{frameRate:i,width:n,height:r}=e.getMediaStreamTrackSettings();let{frameRate:o=i,width:s=n,height:a=r}=t;if(!o||!s||!a)return;s=cy(s),a=cy(a),o=cy(o);const{max:c,min:d}=function(e,t,i){const n=200*Math.pow(i/15,.6)*Math.pow(e*t/640/360,.75);return{min:Math.floor(n),max:Math.floor(4*n)}}(s,a,o),{bitrateMax:l,bitrateMin:h}=t||{};l||Qy.debug(\"calculate bitrate: [w: \".concat(s,\", h: \").concat(a,\", fps: \").concat(o,\"] => [brMax: \").concat(l,\", brMin: \").concat(h,\"]\"));const{maxFramerate:u}=Dy(\"ENCODER_CONFIG_LIMIT\");return u&&\"number\"==typeof u&&(o=Math.min(o,u)),{frameRate:o,bitrateMax:l||c,bitrateMin:h||d,scaleResolutionDownBy:1,scale:0}},Hx=async(e,t,i)=>await(async(e,t,i)=>{const n=function(e){const t=[];for(let i=0;i{const t=document.createElement(\"canvas\");return t.width=2,t.height=2,new Gu(((i,n)=>{t.toBlob((async e=>{if(t.remove(),e){const n=await Yx(e);i({buffer:n,width:t.width,height:t.height})}else n(new iI(tI.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED))}),e,1)}))},Yx=async e=>{const t=await e.arrayBuffer();return new Uint8Array(t)};var qx,zx,Jx,Xx,Qx,Zx,$x,eV,tV,iV,nV,rV,oV,sV,aV,cV,dV,lV,hV,uV,pV,_V,EV,mV,fV,TV,SV,gV,RV,CV,vV,IV,yV,AV,bV,wV,OV,NV,DV,PV;let LV=(qx=rA({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),zx=rA({argsMap:(e,t)=>[e.getTrackId(),t]}),Jx=Lx(),Xx=py(\"LocalAudioTrack\",\"_enabledMutex\"),Qx=rA({argsMap:(e,t)=>[e.getTrackId(),t]}),Zx=Lx(),$x=py(\"LocalAudioTrack\",\"_enabledMutex\"),eV=rA({argsMap:(e,t)=>[e.getTrackId(),t]}),tV=Lx(),iV=Lx(),nV=Lx(),rV=rA({argsMap:e=>[e.getTrackId()]}),oV=Lx(),sV=rA({argsMap:e=>[e.getTrackId()]}),aV=Lx(),cV=rA({argsMap:e=>[e.getTrackId()]}),dV=rA({argsMap:(e,t)=>[e.getTrackId(),t.name]}),lV=rA({argsMap:e=>[e.getTrackId()]}),nx((hV=class extends ox{get _source(){return this.initWebAudio()}set _source(e){this._trackSource=e}get processorContext(){return this._processorContext||(this._processorContext=this.initProcessor().processorContext),this._processorContext}get processorDestination(){return this._processorDestination||(this._processorDestination=this.initProcessor().processorDestination),this._processorDestination}get isPlaying(){return this._useAudioElement?Px.isPlaying(this.getTrackId()):this._source.isPlayed}get __className__(){return\"LocalAudioTrack\"}constructor(e,t,i,n){super(e,i),ix(this,\"trackMediaType\",\"audio\"),ix(this,\"_encoderConfig\",void 0),ix(this,\"_trackSource\",void 0),ix(this,\"_enabled\",!0),ix(this,\"_volume\",100),ix(this,\"_useAudioElement\",!0),ix(this,\"_bypassWebAudio\",!1),ix(this,\"processor\",void 0),ix(this,\"_processorContext\",void 0),ix(this,\"_processorDestination\",void 0),ix(this,\"_getOriginVolumeLevel\",void 0),this._encoderConfig=t,this._getOriginVolumeLevel=!!n,this._trackSource=new Vx,Dy(\"DISABLE_WEBAUDIO\")&&(this._bypassWebAudio=!0),Dy(\"LOCAL_AUDIO_TRACK_USES_WEB_AUDIO\")&&(this._useAudioElement=!1),Nv()&&!ax?setTimeout((()=>this.initWebAudio())):this.initWebAudio()}setVolume(e){oI(e,\"volume\",0,1e3),this._volume=e,this._source.setVolume(e/100),this._useAudioElement&&Px.setVolume(this.getTrackId(),e);try{if(this._bypassWebAudio)return void Qy.debug(\"[\".concat(this.getTrackId(),\"] setVolume returned because no pass through WebAudio.\"));const e=this._source.createOutputTrack();this._mediaStreamTrack!==e&&(this._mediaStreamTrack=e,MI(this,PU.NEED_REPLACE_TRACK,this).then((()=>{Qy.debug(\"[\".concat(this.getTrackId(),\"] replace web audio track success\"))})).catch((e=>{Qy.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||!EU())throw new iI(tI.NOT_SUPPORTED,\"your browser does not support setting the audio output device\");await Px.setSinkID(this.getTrackId(),e)}async setEnabled(e,t,i){return this._setEnabled(e,t,i)}async _setEnabled(e,t,i){if(!i){if(e===this._enabled)return;this.stateCheck(\"enabled\",e)}if(Qy.info(\"[\".concat(this.getTrackId(),\"] start setEnabled\"),e),e){this._originMediaStreamTrack.enabled=!0;try{i||(this._enabled=!0),await MI(this,PU.NEED_ENABLE_TRACK,this),Qy.info(\"[\".concat(this.getTrackId(),\"] setEnabled to \").concat(e,\" success\"))}catch(e){throw i||(this._enabled=!1),Qy.error(\"[\".concat(this.getTrackId(),\"] setEnabled to true error\"),e.toString()),e}}else{this._originMediaStreamTrack.enabled=!1,i||(this._enabled=!1);try{await MI(this,PU.NEED_DISABLE_TRACK,this)}catch(e){throw i||(this._enabled=!0),Qy.error(\"[\".concat(this.getTrackId(),\"] setEnabled to false error\"),e.toString()),e}}}async setMuted(e){e!==this._muted&&(this.stateCheck(\"muted\",e),this._muted=e,this._originMediaStreamTrack.enabled=!e,Qy.debug(\"[\".concat(this.getTrackId(),\"] start set muted: \").concat(e)),e?await MI(this,PU.NEED_MUTE_TRACK,this):await MI(this,PU.NEED_UNMUTE_TRACK,this))}getStats(){KI((()=>{Qy.warning(\"[deprecated] LocalAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalAudioStats instead\")}),\"localAudioTrackGetStatsWarning\");return UI(this,PU.GET_STATS)||tx({},jU)}setAudioFrameCallback(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:4096;if(!e)return this._source.removeAllListeners(BU.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(t),this._source.removeAllListeners(BU.ON_AUDIO_BUFFER),this._source.on(BU.ON_AUDIO_BUFFER,(t=>e(t)))}play(){Qy.debug(\"[\".concat(this.getTrackId(),\"] start audio playback\")),this._useAudioElement?(Qy.debug(\"[\".concat(this.getTrackId(),\"] start audio playback in element\")),Px.play(this._mediaStreamTrack,this.getTrackId(),this._volume)):this._source.play()}stop(){Qy.debug(\"[\".concat(this.getTrackId(),\"] stop audio playback\")),this._useAudioElement?Px.stop(this.getTrackId()):this._source.stop()}close(){super.close(),this._processorDestination&&this.unbindProcessorDestinationEvents(this._processorDestination),this._processorContext&&this.unbindProcessorContextEvents(this._processorContext),this.unpipe(),this._processorDestination&&this._processorDestination._source&&this._processorDestination._source.unpipe(),this._source.destroy()}_updatePlayerSource(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];Qy.debug(\"[\".concat(this.getTrackId(),\"] update player source track\")),e&&this._source.updateTrack(this._mediaStreamTrack),this._useAudioElement&&Px.updateTrack(this.getTrackId(),this._mediaStreamTrack)}async _updateOriginMediaStreamTrack(e,t){this._originMediaStreamTrack!==e&&(this._originMediaStreamTrack&&(this._originMediaStreamTrack.removeEventListener(\"ended\",this._handleTrackEnded),t&&this._originMediaStreamTrack.stop()),e.addEventListener(\"ended\",this._handleTrackEnded),this._originMediaStreamTrack=e,this._muted&&(this._originMediaStreamTrack.enabled=!1),this.processor&&this._processorContext&&this.processor.updateInput({track:e,context:this._processorContext}),this._mediaStreamTrack!==this._source.outputTrack?(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await MI(this,PU.NEED_REPLACE_TRACK,this)):this._source.updateTrack(this._originMediaStreamTrack),this._getOriginVolumeLevel&&this._source.updateOriginTrack(e))}renewMediaStreamTrack(e){return Gu.resolve(void 0)}pipe(e){if(this._bypassWebAudio)throw new iI(tI.INVALID_OPERATION,\"Can not process AudioTrack when bypassWebAudio set to true.\");if(this.processor===e)return e;if(e._source)throw new iI(tI.INVALID_OPERATION,\"Processor \".concat(e.name,\" already piped, please call unpipe beforehand.\"));return this.unpipe(),this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,node:this._source.processSourceNode,context:this.processorContext}),e}unpipe(){var e;if(!this.processor)return;const t=this.processor;null===(e=this._source.processSourceNode)||void 0===e||e.disconnect(),this.processor._source=!1,this.processor=void 0,t.reset()}bindProcessorDestinationEvents(e){e.on(YU.ON_TRACK,(async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(!1),this._source.processedNode=this._source.createMediaStreamSourceNode(e),await MI(this,PU.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await MI(this,PU.NEED_REPLACE_TRACK,this))})),e.on(YU.ON_NODE,(e=>{this._source.processedNode=e}))}unbindProcessorDestinationEvents(e){e.removeAllListeners(YU.ON_TRACK),e.removeAllListeners(YU.ON_NODE)}bindProcessorContextEvents(e){e.on(qU.REQUEST_CONSTRAINTS,(async e=>{e(this._originMediaStreamTrack.getSettings())}))}unbindProcessorContextEvents(e){e.removeAllListeners(qU.REQUEST_CONSTRAINTS)}initWebAudio(){return this._trackSource instanceof Vx&&(this._trackSource=new Ex(this._mediaStreamTrack,!1,this._getOriginVolumeLevel?this._mediaStreamTrack:void 0)),this._trackSource}initProcessor(){const e=new xx(this._source.context,this.getTrackId(),\"local\"),t=new Ux(e);return this._processorContext=e,this._processorDestination=t,this.bindProcessorContextEvents(e),this.bindProcessorDestinationEvents(t),this._source.on(BU.UPDATE_SOURCE,(()=>{this.processor&&this.processor.updateInput({node:this._source.processSourceNode,context:e})})),this._useAudioElement&&(this._useAudioElement=!1,this.isPlaying&&(Px.stop(this.getTrackId()),this._source.play()),MI(this,PU.NEED_REPLACE_MIXING_TRACK,this).then((()=>{Qy.debug(\"[\".concat(this.getTrackId(),\"] replace from origin track to web audio track success\"))})).catch((e=>{Qy.warning(\"[\".concat(this.getTrackId(),\"] replace from origin track to web audio track failed\"),e)}))),{processorContext:e,processorDestination:t}}}).prototype,\"setVolume\",[qx],Object.getOwnPropertyDescriptor(hV.prototype,\"setVolume\"),hV.prototype),nx(hV.prototype,\"setPlaybackDevice\",[zx,Jx],Object.getOwnPropertyDescriptor(hV.prototype,\"setPlaybackDevice\"),hV.prototype),nx(hV.prototype,\"setEnabled\",[Xx,Qx,Zx],Object.getOwnPropertyDescriptor(hV.prototype,\"setEnabled\"),hV.prototype),nx(hV.prototype,\"setMuted\",[$x,eV,tV],Object.getOwnPropertyDescriptor(hV.prototype,\"setMuted\"),hV.prototype),nx(hV.prototype,\"getStats\",[iV],Object.getOwnPropertyDescriptor(hV.prototype,\"getStats\"),hV.prototype),nx(hV.prototype,\"setAudioFrameCallback\",[nV],Object.getOwnPropertyDescriptor(hV.prototype,\"setAudioFrameCallback\"),hV.prototype),nx(hV.prototype,\"play\",[rV,oV],Object.getOwnPropertyDescriptor(hV.prototype,\"play\"),hV.prototype),nx(hV.prototype,\"stop\",[sV,aV],Object.getOwnPropertyDescriptor(hV.prototype,\"stop\"),hV.prototype),nx(hV.prototype,\"close\",[cV],Object.getOwnPropertyDescriptor(hV.prototype,\"close\"),hV.prototype),nx(hV.prototype,\"pipe\",[dV],Object.getOwnPropertyDescriptor(hV.prototype,\"pipe\"),hV.prototype),nx(hV.prototype,\"unpipe\",[lV],Object.getOwnPropertyDescriptor(hV.prototype,\"unpipe\"),hV.prototype),hV),kV=(uV=rA({argsMap:(e,t)=>[e.getTrackId(),t]}),pV=Lx(),_V=py(\"MicrophoneAudioTrack\",\"_enabledMutex\"),EV=rA({argsMap:(e,t,i)=>[e.getTrackId(),t,i]}),mV=Lx(),fV=rA({argsMap:e=>[e.getTrackId()]}),nx((TV=class extends LV{get __className__(){return\"MicrophoneAudioTrack\"}constructor(e,t,i,n){super(e,t.encoderConfig?OU(t.encoderConfig):{},n,Dy(\"GET_VOLUME_OF_MUTED_AUDIO_TRACK\")),ix(this,\"_config\",void 0),ix(this,\"_deviceName\",\"default\"),ix(this,\"_constraints\",void 0),ix(this,\"_originalConstraints\",void 0),ix(this,\"_enabled\",!0),this._config=t,this._constraints=i,this._originalConstraints=i,this._deviceName=e.label,\"boolean\"==typeof t.bypassWebAudio&&(this._bypassWebAudio=t.bypassWebAudio),(Gv()||Wv())&&cx.bindInterruptDetectorTrack(this)}async setDevice(e){if(Qy.info(\"[\".concat(this.getTrackId(),\"] start set device to \").concat(e)),this._enabled)try{const t=await Ax.getDeviceById(e),i={};i.audio=tx({},this._constraints),i.audio.deviceId={exact:e},this._originMediaStreamTrack.stop();let n=null;try{n=await Cx(i,this.getTrackId())}catch(e){throw Qy.error(\"[\".concat(this.getTrackId(),\"] setDevice failed\"),e.toString()),n=await Cx({audio:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(n.getAudioTracks()[0],!1),e}await this._updateOriginMediaStreamTrack(n.getAudioTracks()[0],!1),this._deviceName=t.label,this._config.microphoneId=e,this._constraints.deviceId={exact:e}}catch(e){throw Qy.error(\"[\".concat(this.getTrackId(),\"] setDevice error\"),e.toString()),e}else try{const t=await Ax.getDeviceById(e);this._deviceName=t.label,this._config.microphoneId=e,this._constraints.deviceId={exact:e}}catch(e){throw Qy.error(\"[\".concat(this.getTrackId(),\"] setDevice error\"),e.toString()),e}Qy.info(\"[\".concat(this.getTrackId(),\"] set device to \").concat(e,\" success\"))}async setEnabled(e,t,i){if(t)return Qy.debug(\"[\".concat(this.getTrackId(),\"] setEnabled false (do not close microphone)\")),await super._setEnabled(e);if(!i){if(e===this._enabled)return;this.stateCheck(\"enabled\",e)}if(Qy.info(\"[\".concat(this.getTrackId(),\"] start setEnabled\"),e),Dy(\"AUTO_RESET_AUDIO_ROUTE\")&&(Lv()||Kv())){const t=navigator.audioSession;t&&(e||(t.type=\"playback\"),t.type=\"auto\")}if(!e){var n;this._originMediaStreamTrack.onended=null,this._originMediaStreamTrack.stop(),null===(n=this._source.clonedTrack)||void 0===n||n.stop(),i||(this._enabled=!1);try{await MI(this,PU.NEED_DISABLE_TRACK,this)}catch(e){throw Qy.error(\"[\".concat(this.getTrackId(),\"] setEnabled false failed\"),e.toString()),e}return}const r=tx({},this._constraints),o=Ax.searchDeviceIdByName(this._deviceName);o&&!r.deviceId&&(r.deviceId=o);try{i||(this._enabled=!0);const e=await Cx({audio:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getAudioTracks()[0],!1),await MI(this,PU.NEED_ENABLE_TRACK,this)}catch(e){throw i||(this._enabled=!1),Qy.error(\"[\".concat(this.getTrackId(),\"] setEnabled true failed\"),e.toString()),e}Qy.info(\"[\".concat(this.getTrackId(),\"] setEnabled success\"))}close(){super.close(),(Gv()||Wv())&&cx.unbindInterruptDetectorTrack(this)}onTrackEnded(){if((Lv()||Kv())&&this._enabled&&!this._isClosed&&cx.duringInterruption){const e=async()=>{cx.off(mU.IOS_INTERRUPTION_END,e),this._enabled&&!this._isClosed&&(Qy.debug(\"[\".concat(this.getTrackId(),\"] try capture microphone media device for interrupted iOS device.\")),await this.setEnabled(!1),await this.setEnabled(!0))};cx.on(mU.IOS_INTERRUPTION_END,e)}else Qy.debug(\"[\".concat(this.getTrackId(),\"] track ended\")),this.safeEmit(VU.TRACK_ENDED)}async renewMediaStreamTrack(e){const t=e||this._constraints,i=Ax.searchDeviceIdByName(this._deviceName);if(i&&!t.deviceId&&(t.deviceId=i),this._constraints=t,this._enabled){this._originMediaStreamTrack.stop();const e=await Cx({audio:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getAudioTracks()[0],!0)}}bindProcessorContextEvents(e){super.bindProcessorContextEvents(e),e.on(qU.REQUEST_UPDATE_CONSTRAINTS,(async(e,t,i)=>{try{const i=Object.assign({},this._originalConstraints,...e);await this.renewMediaStreamTrack(i),t()}catch(e){i(e)}}))}unbindProcessorContextEvents(e){super.unbindProcessorContextEvents(e),e.removeAllListeners(qU.REQUEST_UPDATE_CONSTRAINTS)}}).prototype,\"setDevice\",[uV,pV],Object.getOwnPropertyDescriptor(TV.prototype,\"setDevice\"),TV.prototype),nx(TV.prototype,\"setEnabled\",[_V,EV,mV],Object.getOwnPropertyDescriptor(TV.prototype,\"setEnabled\"),TV.prototype),nx(TV.prototype,\"close\",[fV],Object.getOwnPropertyDescriptor(TV.prototype,\"close\"),TV.prototype),TV),MV=(SV=rA({argsMap:(e,t)=>[e.getTrackId(),t,e.duration]}),gV=Lx(),RV=rA({argsMap:e=>[e.getTrackId()]}),CV=Lx(),vV=rA({argsMap:e=>[e.getTrackId()]}),IV=Lx(),yV=rA({argsMap:e=>[e.getTrackId()]}),AV=Lx(),bV=rA({argsMap:e=>[e.getTrackId()]}),wV=Lx(),OV=rA({argsMap:e=>[e.getTrackId()]}),NV=rA({argsMap:e=>[e.getTrackId()]}),DV=Lx(),nx((PV=class extends LV{get __className__(){return\"BufferSourceAudioTrack\"}constructor(e,t,i,n){super(t.createOutputTrack(),i,n),ix(this,\"source\",void 0),ix(this,\"_bufferSource\",void 0),this._useAudioElement=!1,this.source=e,this._bufferSource=t,this._bufferSource.on(BU.AUDIO_SOURCE_STATE_CHANGE,(e=>{this.safeEmit(VU.SOURCE_STATE_CHANGE,e)}));try{this._mediaStreamTrack=this._source.createOutputTrack()}catch(e){}}get currentState(){return this._bufferSource.currentState}get duration(){return this._bufferSource.duration}get playbackSpeed(){return this._bufferSource.playbackSpeed}getCurrentTime(){return this._bufferSource.currentTime}startProcessAudioBuffer(e){e&&this._bufferSource.updateOptions(e),this._bufferSource.startProcessAudioBuffer()}pauseProcessAudioBuffer(){this._bufferSource.pauseProcessAudioBuffer()}seekAudioBuffer(e){this._bufferSource.seekAudioBuffer(e)}resumeProcessAudioBuffer(){this._bufferSource.resumeProcessAudioBuffer()}stopProcessAudioBuffer(){this._bufferSource.stopProcessAudioBuffer()}close(){this.source=null,this._bufferSource.destroy(),super.close()}setAudioBufferPlaybackSpeed(e){oI(e,\"speed\",0),this._bufferSource.setAudioBufferPlaybackSpeed(e)}}).prototype,\"startProcessAudioBuffer\",[SV,gV],Object.getOwnPropertyDescriptor(PV.prototype,\"startProcessAudioBuffer\"),PV.prototype),nx(PV.prototype,\"pauseProcessAudioBuffer\",[RV,CV],Object.getOwnPropertyDescriptor(PV.prototype,\"pauseProcessAudioBuffer\"),PV.prototype),nx(PV.prototype,\"seekAudioBuffer\",[vV,IV],Object.getOwnPropertyDescriptor(PV.prototype,\"seekAudioBuffer\"),PV.prototype),nx(PV.prototype,\"resumeProcessAudioBuffer\",[yV,AV],Object.getOwnPropertyDescriptor(PV.prototype,\"resumeProcessAudioBuffer\"),PV.prototype),nx(PV.prototype,\"stopProcessAudioBuffer\",[bV,wV],Object.getOwnPropertyDescriptor(PV.prototype,\"stopProcessAudioBuffer\"),PV.prototype),nx(PV.prototype,\"close\",[OV],Object.getOwnPropertyDescriptor(PV.prototype,\"close\"),PV.prototype),nx(PV.prototype,\"setAudioBufferPlaybackSpeed\",[NV,DV],Object.getOwnPropertyDescriptor(PV.prototype,\"setAudioBufferPlaybackSpeed\"),PV.prototype),PV);class UV extends LV{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=dx().createMediaStreamDestination();super(e.stream.getAudioTracks()[0],void 0,ey(8,\"track-mix-\")),ix(this,\"trackList\",void 0),ix(this,\"destNode\",void 0),this._useAudioElement=!1;try{this._mediaStreamTrack=this._source.createOutputTrack()}catch(e){}this.destNode=e,this.trackList=[]}hasAudioTrack(e){return-1!==this.trackList.indexOf(e)}addAudioTrack(e){-1===this.trackList.indexOf(e)?(Qy.debug(\"add \".concat(e.getTrackId(),\" to mixing track\")),e._source.outputNode.connect(this.destNode),this.trackList.push(e),this.updateEncoderConfig()):Qy.debug(\"track \".concat(e.getTrackId(),\" is already added\"))}removeAudioTrack(e){if(-1!==this.trackList.indexOf(e)){Qy.debug(\"remove \".concat(e.getTrackId(),\" from mixing track\"));try{e._source.outputNode.disconnect(this.destNode)}catch(e){}FI(this.trackList,e),this.updateEncoderConfig()}}updateEncoderConfig(){const e={};this.trackList.forEach((t=>{t._encoderConfig&&((t._encoderConfig.bitrate||0)>(e.bitrate||0)&&(e.bitrate=t._encoderConfig.bitrate),(t._encoderConfig.sampleRate||0)>(e.sampleRate||0)&&(e.sampleRate=t._encoderConfig.sampleRate),(t._encoderConfig.sampleSize||0)>(e.sampleSize||0)&&(e.sampleSize=t._encoderConfig.sampleSize),t._encoderConfig.stereo&&(e.stereo=!0))})),this._encoderConfig=e}_updateRtpTransceiver(e){this._rtpTransceiver!==e&&(this._rtpTransceiver=e,this.trackList.forEach((t=>{t instanceof UV?t.emit(xU.TRANSCEIVER_UPDATED,e):t._updateRtpTransceiver(e)})))}}class xV extends _x{set currentState(e){e!==this._currentState&&(this._currentState=e,this.safeEmit(BU.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(),ix(this,\"audioBuffer\",void 0),ix(this,\"sourceNode\",void 0),ix(this,\"startPlayTime\",0),ix(this,\"startPlayOffset\",0),ix(this,\"pausePlayTime\",0),ix(this,\"options\",void 0),ix(this,\"currentLoopCount\",0),ix(this,\"currentPlaybackSpeed\",100),ix(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):Qy.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 VV=new Map;class FV{get rendFrameRate(){if(this.renderStats&&this.renderStats.curTs!==this.renderStats.lastTs){const e=this.renderStats.curTs-this.renderStats.lastTs,t=(this.renderStats.renderNum-this.renderStats.lastRenderNum)/e;return this.renderStats.lastRenderNum=this.renderStats.renderNum,this.renderStats.lastTs=this.renderStats.curTs,t}return 0}get videoElementStatus(){return this._videoElementStatus}set videoElementStatus(e){e!==this._videoElementStatus&&(Qy.debug(\"[\".concat(this.trackId,\"] video-element-status change \").concat(this._videoElementStatus,\" => \").concat(e)),this._videoElementStatus=e)}get videoState(){return this._videoState}set videoState(e){var t;e!==this._videoState&&(this._videoState=e,null===(t=this.onVideoStateChanged)||void 0===t||t.call(this,this.videoState))}constructor(e){ix(this,\"trackId\",void 0),ix(this,\"config\",void 0),ix(this,\"onFirstVideoFrameDecoded\",void 0),ix(this,\"onVideoStateChanged\",void 0),ix(this,\"freezeTimeCounterList\",[]),ix(this,\"renderFreezeAccTime\",0),ix(this,\"isKeepLastFrame\",!1),ix(this,\"timeUpdatedCount\",0),ix(this,\"freezeTime\",0),ix(this,\"playbackTime\",0),ix(this,\"lastTimeUpdatedTime\",0),ix(this,\"autoplayFailed\",!1),ix(this,\"videoTrack\",void 0),ix(this,\"videoElement\",void 0),ix(this,\"cacheVideoElement\",void 0),ix(this,\"renderStats\",void 0),ix(this,\"_videoState\",QU.VideoStateStopped),ix(this,\"videoElementCheckInterval\",void 0),ix(this,\"videoElementFreezeTimeout\",void 0),ix(this,\"_videoElementStatus\",XU.NONE),ix(this,\"isGettingVideoDimensions\",!1),ix(this,\"startGetVideoDimensions\",(()=>{const e=()=>{if(this.isGettingVideoDimensions=!0,this.videoElement.videoWidth*this.videoElement.videoHeight>4)return Qy.debug(\"[\".concat(this.trackId,\"] current video dimensions:\"),this.videoElement.videoWidth,this.videoElement.videoHeight),void(this.isGettingVideoDimensions=!1);setTimeout(e,500)};!this.isGettingVideoDimensions&&e()})),ix(this,\"autoResumeAfterInterruption\",(()=>{this.videoTrack&&\"live\"===this.videoTrack.readyState&&\"running\"===cx.curState&&(Qy.debug(\"[track-\".concat(this.trackId,\"] video element paused, auto resume for \").concat(bv())),Hv()?(this.videoElement.srcObject=null,this.videoElement.srcObject=new MediaStream([this.videoTrack]),this.videoElement.play()):(this.videoElement.pause(),this.videoElement.play()))})),ix(this,\"handleVideoEvents\",(e=>{switch(e.type){case\"play\":case\"playing\":this.startGetVideoDimensions(),this.videoElementStatus=XU.PLAYING;break;case\"loadeddata\":if(this.videoState=QU.VideoStateStarting,this.onFirstVideoFrameDecoded&&this.onFirstVideoFrameDecoded(),this.cacheVideoElement){try{this.cacheVideoElement.srcObject=null,this.cacheVideoElement.remove()}catch(e){}this.cacheVideoElement=void 0}break;case\"canplay\":this.videoElementStatus=XU.CANPLAY;break;case\"stalled\":this.videoElementStatus=XU.STALLED;break;case\"suspend\":this.videoElementStatus=XU.SUSPEND;break;case\"pause\":this.videoElementStatus=XU.PAUSED,Lv()||Kv()||Nv()&&this.autoplayFailed||!this.videoTrack||\"live\"!==this.videoTrack.readyState||(Qy.debug(\"[track-\".concat(this.trackId,\"] video element paused, auto resume\")),this.videoElement.play());break;case\"waiting\":this.videoElementStatus=XU.WAITING;break;case\"abort\":this.videoElementStatus=XU.ABORT;break;case\"ended\":this.videoElementStatus=XU.ENDED;break;case\"emptied\":this.videoElementStatus=XU.EMPTIED;break;case\"error\":{const e=this.videoElement.error;e?(this.videoElementStatus=XU.ERROR,Qy.error(\"[\".concat(this.trackId,\"] media error: \").concat(e.message,\" (\").concat(e.code,\")\"))):Qy.debug(\"[\".concat(this.trackId,\"] media not been an error.\"));break}case\"timeupdate\":{const e=performance.now();if(this.timeUpdatedCount+=1,this.timeUpdatedCount<10)return void(this.lastTimeUpdatedTime=e);const t=e-this.lastTimeUpdatedTime,i=this.lastTimeUpdatedTime;if(this.lastTimeUpdatedTime=e,jF.lastVisibleTimeDy(\"VIDEO_FREEZE_DURATION\")&&(this.freezeTime+=t),this.playbackTime+=t;this.playbackTime>=6e3;){this.playbackTime-=6e3;const e=Math.min(6e3,this.freezeTime);this.freezeTimeCounterList.push(e),this.freezeTime=Math.max(0,this.freezeTime-6e3)}break}}})),ix(this,\"autoResumeAfterInterruptionOnIOS15_16\",(()=>{this.videoTrack&&\"live\"===this.videoTrack.readyState&&(Qy.debug(\"[track-\".concat(this.trackId,\"] video element paused, auto resume for \").concat(bv())),Hv()?(this.videoElement.srcObject=null,this.videoElement.srcObject=new MediaStream([this.videoTrack]),this.videoElement.play()):(this.videoElement.pause(),this.videoElement.play()))})),this.trackId=e.trackId,this.config=e,e.element instanceof HTMLVideoElement?this.videoElement=e.element:this.videoElement=document.createElement(\"video\"),cx.on(mU.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),cx.on(mU.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 t=this.videoElement.play();t&&t.catch&&t.catch((t=>{e&&Nx(e,\"video\",t.message,this.trackId),\"NotAllowedError\"===t.name?(Qy.warning(\"detected video element autoplay failed\",t),this.autoplayFailed=!0,this.handleAutoPlayFailed()):Qy.warning(\"[\".concat(this.trackId,\"] play warning: \"),t)}));const i=Iv();if((\"Safari\"===i.name&&15===Number(i.version)||Gv())&&t&&t.then){const e=()=>{this.config.mirror&&(this.videoElement.style.transform=\"rotateY(180deg)\")};t.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 Qy.error(\"create canvas context failed!\"),new ImageData(2,2);t.drawImage(this.videoElement,0,0,e.width,e.height);const i=t.getImageData(0,0,e.width,e.height);return e.remove(),i}async getCurrentFrameToUint8Array(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;const i=document.createElement(\"canvas\");i.width=this.videoElement.videoWidth,i.height=this.videoElement.videoHeight;const n=i.getContext(\"2d\");return n?(n.drawImage(this.videoElement,0,0,i.width,i.height),new Gu(((n,r)=>{i.toBlob((async e=>{if(i.remove(),e){const t=await Yx(e);n({buffer:t,width:i.width,height:i.height})}else r(new iI(tI.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED))}),e,t<0?.1:t>1?1:t)}))):await Kx(e)}destroy(){this.renderStats=void 0,cx.off(mU.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),cx.off(mU.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16),this.videoElement.srcObject=null,this.resetVideoElement(),this.freezeTimeCounterList=[],this.videoState=QU.VideoStateStopped}initVideoElement(){if(this.videoElementStatus=XU.INIT,!this.videoElementCheckInterval&&(BV.forEach((e=>{this.videoElement.addEventListener(e,this.handleVideoEvents)})),this.videoElementCheckInterval=window.setInterval((()=>{(function(e){return e!==document.body&&document.body.contains(e)})(this.videoElement)||(this.videoElementStatus=XU.DESTROYED)}),1e3),Dy(\"ENABLE_VIDEO_FRAME_CALLBACK\"))){var e,t;let i;const n=()=>{\"visible\"===document.visibilityState&&(document.removeEventListener(\"visibilitychange\",n),this.videoElementFreezeTimeout=window.setTimeout(r,Dy(\"VIDEO_FREEZE_DURATION\")))},r=()=>{this.videoElementFreezeTimeout=void 0,this.videoState===QU.VideoStateDecoding&&(\"visible\"===document.visibilityState?this.videoState=QU.VideoStateFrozen:document.addEventListener(\"visibilitychange\",n))},o=(e,t)=>{if(this.videoElementStatus===XU.PLAYING){if(this.renderStats?(this.renderStats.renderNum++,this.renderStats.curTs=t.mediaTime):this.renderStats={lastTs:t.mediaTime,curTs:t.mediaTime,lastRenderNum:0,renderNum:0},i){const e=t.presentationTime-i.presentationTime;this.videoState===QU.VideoStateStarting&&(this.videoState=QU.VideoStateDecoding),this.videoState===QU.VideoStateDecoding&&this.onVideoStateChanged&&(this.videoElementFreezeTimeout&&window.clearTimeout(this.videoElementFreezeTimeout),this.videoElementFreezeTimeout=window.setTimeout(r,Dy(\"VIDEO_FREEZE_DURATION\"))),eDy(\"VIDEO_FREEZE_DURATION\")&&jF.lastVisibleTime>=jF.lastHiddenTime&&i.timestamp>jF.lastVisibleTime&&i.timestamp>jF.lastHiddenTime&&(this.renderFreezeAccTime+=e)}i=tx(tx({},t),{},{timestamp:e})}var n,s;Dy(\"ENABLE_VIDEO_FRAME_CALLBACK\")&&(null===(n=(s=this.videoElement).requestVideoFrameCallback)||void 0===n||n.call(s,o))};null===(e=(t=this.videoElement).requestVideoFrameCallback)||void 0===e||e.call(t,o)}this.videoElement.controls=!1,this.videoElement.setAttribute(\"playsinline\",\"\"),Xv()&&!Dy(\"HIDE_NO_POSTER\")&&(this.videoElement.poster=\"noposter\");const i=Iv();\"Safari\"===i.name&&15===Number(i.version)||Gv()||!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,Pv()&&this.videoElement.load()):(this.videoElement.srcObject=this.videoTrack?new MediaStream([this.videoTrack]):null,Pv()&&this.videoElement.load());const n=this.videoElement.play();void 0!==n&&n.catch((e=>{Qy.debug(\"[\".concat(this.trackId,\"] playback interrupted\"),e.toString())}))}resetVideoElement(){BV.forEach((e=>{this.videoElement&&this.videoElement.removeEventListener(e,this.handleVideoEvents)})),this.videoElementCheckInterval&&(window.clearInterval(this.videoElementCheckInterval),this.videoElementCheckInterval=void 0),this.videoElementStatus=XU.NONE}handleAutoPlayFailed(){const e=t=>{t.preventDefault(),this.videoElement.play().then((()=>{Qy.debug(\"[\".concat(this.trackId,\"] Video element for trackId:\").concat(this.trackId,\" autoplay resumed.\"))})).catch((e=>{Qy.error(e)})),this.autoplayFailed=!1,Qv()?document.body.removeEventListener(\"click\",e,!0):(document.body.removeEventListener(\"touchstart\",e,!0),document.body.removeEventListener(\"mousedown\",e,!0))};Qv()?document.body.addEventListener(\"click\",e,!0):(document.body.addEventListener(\"touchstart\",e,!0),document.body.addEventListener(\"mousedown\",e,!0)),Ox()}}const BV=[\"play\",\"playing\",\"loadeddata\",\"canplay\",\"pause\",\"stalled\",\"suspend\",\"waiting\",\"abort\",\"emptied\",\"ended\",\"timeupdate\",\"error\"];class jV extends FV{constructor(e){super(e),ix(this,\"container\",void 0),ix(this,\"slot\",void 0),this.slot=e.element,this.updateConfig(e)}updateConfig(e){this.config=e,this.trackId=e.trackId;const t=e.element;t!==this.slot&&(this.destroy(),this.slot=t),this.createElements()}updateVideoTrack(e){this.videoTrack!==e&&(this.videoTrack=e,this.createElements())}play(e){var t;null!==(t=this.container)&&void 0!==t&&t.contains(this.videoElement)&&super.play(e)}getCurrentFrame(){var e;return null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)?super.getCurrentFrame():new ImageData(2,2)}async getCurrentFrameToUint8Array(e){var t;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return null!==(t=this.container)&&void 0!==t&&t.contains(this.videoElement)?await super.getCurrentFrameToUint8Array(e,i):await Kx(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\",Dy(\"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}}var GV,WV,HV,KV,YV,qV,zV,JV,XV,QV,ZV,$V,eF,tF,iF,nF,rF,oF,sF,aF,cF,dF,lF,hF,uF,pF,_F,EF,mF,fF,TF,SF,gF,RF,CF;let vF=(GV=rA({argsMap:(e,t,i)=>[e.getTrackId(),\"string\"==typeof t?t:t instanceof HTMLVideoElement?\"HTMLVideoElement\":\"HTMLElement\",i]}),WV=Lx(),HV=rA({argsMap:e=>[e.getTrackId()]}),KV=py(\"LocalVideoTrack\",\"_enabledMutex\"),YV=rA({argsMap:(e,t)=>[e.getTrackId(),t]}),qV=Lx(),zV=py(\"LocalVideoTrack\",\"_enabledMutex\"),JV=rA({argsMap:(e,t)=>[e.getTrackId(),t]}),XV=Lx(),QV=rA({argsMap:(e,t)=>[e.getTrackId(),t]}),ZV=Lx(),$V=Lx(),eF=rA({argsMap:(e,t,i)=>[e.getTrackId(),t,i]}),tF=Lx(),iF=Lx(),nF=Lx(),rF=Lx(),oF=Lx(),sF=Lx(),aF=Lx(),cF=rA({argsMap:(e,t)=>[e.getTrackId(),t.name]}),dF=rA({argsMap:e=>[e.getTrackId()]}),lF=rA({argsMap:e=>[e.getTrackId()]}),hF=rA({argsMap:(e,t,i)=>[e.getTrackId(),t.label,i]}),uF=rA(),pF=class e extends ox{get videoHeight(){if(Nv()){const{height:e}=this._mediaStreamTrack.getSettings();return this._videoHeight=e,this._videoHeight}return this._videoHeight}get videoWidth(){if(Nv()){const{width:e}=this._mediaStreamTrack.getSettings();return this._videoWidth=e,this._videoWidth}return this._videoWidth}get isPlaying(){return!(!this._player||this._player.videoElementStatus!==XU.PLAYING)}get processorDestination(){return this._processorDestination}get processorContext(){return this._processorContext}set processorContext(e){this._processorContext=e}get __className__(){return\"LocalVideoTrack\"}constructor(e,t,i,n,r,o){if(super(e,r),ix(this,\"trackMediaType\",\"video\"),ix(this,\"_player\",void 0),ix(this,\"isUseScaleResolutionDownBy\",!1),ix(this,\"_videoVisibleTimer\",null),ix(this,\"_statsTimer\",null),ix(this,\"_previousVideoVisibleStatus\",void 0),ix(this,\"_clearPreviousVideoVisibleStatus\",(()=>this._previousVideoVisibleStatus=void 0)),ix(this,\"_encoderConfig\",void 0),ix(this,\"_scalabilityMode\",{numSpatialLayers:1,numTemporalLayers:1}),ix(this,\"_optimizationMode\",void 0),ix(this,\"_videoHeight\",void 0),ix(this,\"_videoWidth\",void 0),ix(this,\"_forceBitrateLimit\",void 0),ix(this,\"_enabled\",!0),ix(this,\"_processorDestination\",void 0),ix(this,\"_processorContext\",void 0),Nv()){const{width:t,height:i}=e.getSettings();this._videoWidth=t,this._videoHeight=i}else this.updateMediaStreamTrackResolution();if(this._encoderConfig=t,this._scalabilityMode=i,this._optimizationMode=n,this._hints=o||[],-1===this._hints.indexOf(LU.SCREEN_TRACK))this.updateBitrateFromProfile();else if(function(e,t,i){const n=Iv();return!(n.name!==e||!n.osVersion)&&(i?Number(n.version)>=t&&Number(n.version)<=i:Number(n.version)===t)}(gv.CHROME,115)&&-1!==Av().indexOf(\"Windows\")){const t=function(e,t){if(\"VideoFrame\"in window&&\"TransformStream\"in window&&_U().supportWebRTCInsertableStream){const i=new MediaStreamTrackProcessor(e),n=new MediaStreamTrackGenerator({kind:\"video\"});let r,o,s=Date.now();const a=()=>{c&&(clearInterval(c),c=void 0),r&&(r.close(),r=void 0),e.stop(),o=void 0,n.removeEventListener(\"ended\",a)};let c=window.setInterval((()=>{if(o&&r&&Date.now()-s>(null!=t?t:1e3))try{\"live\"===n.readyState?o.enqueue(r.clone()):a()}catch(e){a()}}),null!=t?t:1e3);const d=new TransformStream({transform:(e,t)=>{\"live\"===n.readyState?(o=t,s=Date.now(),void 0===r?(r=e,t.enqueue(e.clone())):(t.enqueue(r),r=e)):e.close()}});return n.addEventListener(\"ended\",a),i.readable.pipeThrough(d).pipeTo(n.writable),n}}(e);t&&(Qy.info(\"local screen video track begin to inject frame\"),this._mediaStreamTrack=t)}t&&-1!==this._hints.indexOf(LU.CUSTOM_TRACK)&&this.setEncoderConfiguration(t),this._processorContext=new Mx(this.getTrackId(),\"local\"),this._processorDestination=new kx(this.processorContext),this.bindProcessorDestinationEvents()}play(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(\"string\"==typeof e){const t=document.getElementById(e);t?e=t:(Qy.warning(\"[\".concat(this.getTrackId(),'] can not find \"#').concat(e,'\" element, use document.body')),e=document.body)}Qy.debug(\"[\".concat(this.getTrackId(),\"] start video playback in \").concat(e instanceof HTMLVideoElement?\"HTMLVideoElement\":\"HTMLElement\"),JSON.stringify(t));const i=tx(tx(tx({},this._getDefaultPlayerConfig()),t),{},{trackId:this.getTrackId(),element:e});this._player?this._player.updateConfig(i):(e instanceof HTMLVideoElement?this._player=new FV(i):this._player=new jV(i),this._player.updateVideoTrack(this._mediaStreamTrack)),this._player.play(),this._videoVisibleTimer&&window.clearInterval(this._videoVisibleTimer),this._clearPreviousVideoVisibleStatus(),this._videoVisibleTimer=window.setInterval((()=>{try{const e=this.getVideoElementVisibleStatus();this.safeEmit(VU.VIDEO_ELEMENT_VISIBLE_STATUS,e)}catch(e){}}),Dy(\"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,Qy.debug(\"[\".concat(this.getTrackId(),\"] stop video playback\")))}async setEnabled(e,t){if(!t){if(e===this._enabled)return;this.stateCheck(\"enabled\",e)}if(Qy.info(\"[\".concat(this.getTrackId(),\"] start setEnabled\"),e),!e){this._originMediaStreamTrack.enabled=!1;try{await MI(this,PU.NEED_DISABLE_TRACK,this)}catch(e){throw Qy.error(\"[\".concat(this.getTrackId(),\"] setEnabled to false error\"),e.toString()),e}return t||(this._enabled=!1),void Qy.info(\"[\".concat(this.getTrackId(),\"] setEnabled to false success\"))}this._originMediaStreamTrack.enabled=!0;try{await MI(this,PU.NEED_ENABLE_TRACK,this)}catch(e){throw Qy.error(\"[\".concat(this.getTrackId(),\"] setEnabled to true error\"),e.toString()),e}Qy.info(\"[\".concat(this.getTrackId(),\"] setEnabled to true success\")),t||(this._enabled=!0)}async setMuted(e){e!==this._muted&&(this.stateCheck(\"muted\",e),this._muted=e,this._originMediaStreamTrack.enabled=!e,Qy.debug(\"[\".concat(this.getTrackId(),\"] start set muted: \").concat(e)),e?await MI(this,PU.NEED_MUTE_TRACK,this):await MI(this,PU.NEED_UNMUTE_TRACK,this))}async setEncoderConfiguration(e,t){if(!this._enabled)throw new iI(tI.TRACK_IS_DISABLED,\"can not set encoder configuration when track is disabled\");if(\"720p_auto\"===e?this.startMonitorStats():this._statsTimer&&(window.clearInterval(this._statsTimer),this._statsTimer=null),e=yU(e),this._forceBitrateLimit&&(e.bitrateMax=this._forceBitrateLimit.max_bitrate?this._forceBitrateLimit.max_bitrate:e.bitrateMax,e.bitrateMin=this._forceBitrateLimit.min_bitrate?this._forceBitrateLimit.min_bitrate:e.bitrateMin),e.width||e.height||e.frameRate){const t=jx({encoderConfig:e});(Nv()||Lv()||Kv())&&(t.deviceId=void 0),Qy.debug(\"[\".concat(this.getTrackId(),\"] setEncoderConfiguration applyConstraints\"),JSON.stringify(e),JSON.stringify(t));try{await this._originMediaStreamTrack.applyConstraints(t),this.updateMediaStreamTrackResolution()}catch(e){const t=new iI(tI.UNEXPECTED_ERROR,e.toString());throw Qy.error(\"[\".concat(this.getTrackId(),\"] applyConstraints error\"),t.toString()),t}}this._encoderConfig=e,-1===this._hints.indexOf(LU.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await MI(this,PU.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(Qy)}}getStats(){KI((()=>{Qy.warning(\"[deprecated] LocalVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalVideoStats instead\")}),\"localVideoTrackGetStatsWarning\");return UI(this,PU.GET_STATS)||tx({},GU)}async setBeautyEffect(e){Qy.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 Kx(e)}async setBitrateLimit(e){if(Qy.debug(\"[\".concat(this.getTrackId(),\"] set bitrate limit, \").concat(JSON.stringify(e))),e){this._forceBitrateLimit=e,this._encoderConfig&&(this._encoderConfig.bitrateMax?this._encoderConfig.bitrateMax=this._encoderConfig.bitrateMax{let[t,i]=e;this._videoHeight=i,this._videoWidth=t})).catch(iy)}_updatePlayerSource(){this._player&&this._player.updateVideoTrack(this._mediaStreamTrack)}_getDefaultPlayerConfig(){return{fit:\"contain\"}}async setSenderConfiguration(e){if(!this._enabled)throw new iI(tI.TRACK_IS_DISABLED,\"can not set encoder configuration when track is disabled\");Qy.debug(\"[\".concat(this.getTrackId(),\"] setSenderConfiguration applyConstraints\"),JSON.stringify(e)),e=yU(e),this._forceBitrateLimit&&(e.bitrateMax=this._forceBitrateLimit.max_bitrate?this._forceBitrateLimit.max_bitrate:e.bitrateMax,e.bitrateMin=this._forceBitrateLimit.min_bitrate?this._forceBitrateLimit.min_bitrate:e.bitrateMin),this._encoderConfig=e,-1===this._hints.indexOf(LU.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await MI(this,PU.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(Qy)}}updateBitrateFromProfile(){if(!this._encoderConfig)return;const{width:e,height:t,frameRate:i}=this.getMediaStreamTrackSettings();if(!e||!t||!i)return;const{bitrateMax:n,bitrateMin:r}=this._encoderConfig;if(null==r||null==n){const{max:o,min:s}=function(e,t,i,n,r){const o=Dy(\"BITRATE_ADAPTER_TYPE\");if(\"DEFAULT_BITRATE\"===o)return{min:n,max:r};if(void 0===r){var s;const a=Math.floor(200*Math.pow(i/15,.6)*Math.pow(e*t/640/360,.75));r=\"STANDARD_BITRATE\"===o?4*a:2*a,n=null!==(s=n)&&void 0!==s?s:a}else{var a;n=null!==(a=n)&&void 0!==a?a:Math.floor(r/10)}return{min:n,max:r}}(e,t,i,r,n);this._encoderConfig.bitrateMin=s,this._encoderConfig.bitrateMax=o,Qy.debug(\"[\".concat(this.getTrackId(),\"] update bitrate from profile, [w: \").concat(e,\", h: \").concat(t,\", fps: \").concat(i,\"] => [brMax: \").concat(o,\", brMin: \").concat(s,\"]\"))}}getVideoElementVisibleStatus(){try{var e,t;const i=null==this||null===(e=this._player)||void 0===e?void 0:e.getContainerElement(),n={track:this,element:null==this||null===(t=this._player)||void 0===t?void 0:t.getVideoElement(),slot:null==i?void 0:i.parentElement},{element:r,slot:o}=n;if(this.isPlaying&&r instanceof HTMLVideoElement&&o instanceof HTMLElement){const e=EI.checkOneElementVisible(r),t=Object.assign({},e);if(t.visible!==this._previousVideoVisibleStatus){this._previousVideoVisibleStatus=t.visible;const e=oA.reportApiInvoke(null,{tag:vI.TRACER,name:CI.LOCAL_VIDEO_TRACK_GET_VIDEO_VISIBLE,options:[this.getTrackId()]});t.visible?e.onSuccess(\"Video is visible\"):e.onSuccess(\"Invisible because of \".concat(t.reason))}return t}return}catch(e){throw new iI(tI.GET_VIDEO_ELEMENT_VISIBLE_ERROR,e.message)}}async renewMediaStreamTrack(e){}pipe(e){if(this.processor===e)return e;if(e._source)throw new iI(tI.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(t){let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],n=this._encoderConfig;t&&(n=tx(tx({},n),yU(t))),n=WI(n);const r=ey(8,\"track-video-cloned-\"),o=new e(i?this._mediaStreamTrack.clone():this._mediaStreamTrack,n,WI(this._scalabilityMode),this._optimizationMode,r,WI(this._hints));return t&&n&&o.setEncoderConfiguration(n),Qy.debug(\"clone video track from \".concat(this.getTrackId(),\" to \").concat(r,\", clone \").concat(i)),o}async replaceTrack(e,t){if(!(e instanceof MediaStreamTrack))throw new iI(tI.INVALID_PARAMS,\"track should be an instance of MediaStreamTrack\");if(\"video\"!==e.kind)throw new iI(tI.INVALID_PARAMS,\"track should be a video MediaStreamTrack\");await this._updateOriginMediaStreamTrack(e,t,!0),this.updateMediaStreamTrackResolution()}startMonitorStats(){if(!Nv()&&!Lv())return;this._statsTimer&&window.clearInterval(this._statsTimer);let e=2,t=CU[e],i=-1,n=Date.now();const r=e=>{e>2||e<0||(n=Date.now(),t=CU[e],this.setSenderConfiguration(t))};this.isUseScaleResolutionDownBy=!0,this._statsTimer=window.setInterval((()=>{const o=this.getStats(),s=UI(this,PU.GET_RTC_STATS);if(o.sendPackets>0&&s){-1===i&&(i=Date.now());const a=Date.now();if(a-i<1e3||a-n0&&c0&&(e--,r(e),Qy.debug(\"[\".concat(this.getTrackId(),\"] step down for fps \").concat(c,\", switchProfile to \").concat(e))):s.OutgoingAvailableBandwidth0&&(e--,r(e),Qy.debug(\"[\".concat(this.getTrackId(),\"] step down for OutgoingAvailableBandwidth \").concat(s.OutgoingAvailableBandwidth,\", bitrateMin \").concat(t.bitrateMin,\", switchProfile to \").concat(e))):\"number\"==typeof c&&c>l&&e1.2*CU[e+1].bitrateMin&&(e++,r(e),Qy.debug(\"[\".concat(this.getTrackId(),\"] step up for fps \").concat(c,\", OutgoingAvailableBandwidth \").concat(s.OutgoingAvailableBandwidth,\", switchProfile to \").concat(e)))}}),Dy(\"CHECK_LOCAL_STATS_INTERVAL\"))}sendSeiData(e){if(KI((()=>{oA.reportApiInvoke(null,{name:CI.LOCAL_VIDEO_SEND_SEI_DATA,options:[],tag:vI.TRACER}).onSuccess(\"\")}),this._mediaStreamTrack.id||this.getTrackId()),!Dy(\"ENABLE_VIDEO_SEI\")||!Dy(\"ENABLE_ENCODED_TRANSFORM\"))return void Qy.warning('To send/receive SEI, please call AgoraRTC.setParameter(\"ENABLE_VIDEO_SEI\", true) before instantiate IAgoraRtcClient');if(e instanceof Uint8Array==0)return new iI(tI.INVALID_PARAMS,\"Invalid argument type, ILocalVideoTrack.sendSeiData() only accept Uint8Array argument.\").throw();const t=this.getRTCRtpTransceiver();if(!t)return void Qy.warning(\"Video track is not published, SEI can not be send\");const i=t.sender.getParameters();if(0===i.codecs.length)return;const n=i.codecs[0].mimeType.toLocaleLowerCase();\"video/h264\"===n?this.safeEmit(\"sei-to-send\",e):Qy.warning(\"SEI is not supported by \".concat(n))}bindProcessorDestinationEvents(){this.processorDestination.on(YU.ON_TRACK,(async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(),await MI(this,PU.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await MI(this,PU.NEED_REPLACE_TRACK,this))}))}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(YU.ON_TRACK)}unbindProcessorContextEvents(){this.processorContext.removeAllListeners(qU.REQUEST_UPDATE_CONSTRAINTS),this.processorContext.removeAllListeners(qU.REQUEST_CONSTRAINTS)}},nx(pF.prototype,\"play\",[GV,WV],Object.getOwnPropertyDescriptor(pF.prototype,\"play\"),pF.prototype),nx(pF.prototype,\"stop\",[HV],Object.getOwnPropertyDescriptor(pF.prototype,\"stop\"),pF.prototype),nx(pF.prototype,\"setEnabled\",[KV,YV,qV],Object.getOwnPropertyDescriptor(pF.prototype,\"setEnabled\"),pF.prototype),nx(pF.prototype,\"setMuted\",[zV,JV,XV],Object.getOwnPropertyDescriptor(pF.prototype,\"setMuted\"),pF.prototype),nx(pF.prototype,\"setEncoderConfiguration\",[QV,ZV],Object.getOwnPropertyDescriptor(pF.prototype,\"setEncoderConfiguration\"),pF.prototype),nx(pF.prototype,\"getStats\",[$V],Object.getOwnPropertyDescriptor(pF.prototype,\"getStats\"),pF.prototype),nx(pF.prototype,\"setBeautyEffect\",[eF,tF],Object.getOwnPropertyDescriptor(pF.prototype,\"setBeautyEffect\"),pF.prototype),nx(pF.prototype,\"getCurrentFrameData\",[iF],Object.getOwnPropertyDescriptor(pF.prototype,\"getCurrentFrameData\"),pF.prototype),nx(pF.prototype,\"getCurrentFrameImage\",[nF],Object.getOwnPropertyDescriptor(pF.prototype,\"getCurrentFrameImage\"),pF.prototype),nx(pF.prototype,\"setBitrateLimit\",[rF],Object.getOwnPropertyDescriptor(pF.prototype,\"setBitrateLimit\"),pF.prototype),nx(pF.prototype,\"setOptimizationMode\",[oF],Object.getOwnPropertyDescriptor(pF.prototype,\"setOptimizationMode\"),pF.prototype),nx(pF.prototype,\"setScalabiltyMode\",[sF],Object.getOwnPropertyDescriptor(pF.prototype,\"setScalabiltyMode\"),pF.prototype),nx(pF.prototype,\"updateMediaStreamTrackResolution\",[aF],Object.getOwnPropertyDescriptor(pF.prototype,\"updateMediaStreamTrackResolution\"),pF.prototype),nx(pF.prototype,\"pipe\",[cF],Object.getOwnPropertyDescriptor(pF.prototype,\"pipe\"),pF.prototype),nx(pF.prototype,\"unpipe\",[dF],Object.getOwnPropertyDescriptor(pF.prototype,\"unpipe\"),pF.prototype),nx(pF.prototype,\"close\",[lF],Object.getOwnPropertyDescriptor(pF.prototype,\"close\"),pF.prototype),nx(pF.prototype,\"replaceTrack\",[hF],Object.getOwnPropertyDescriptor(pF.prototype,\"replaceTrack\"),pF.prototype),nx(pF.prototype,\"startMonitorStats\",[uF],Object.getOwnPropertyDescriptor(pF.prototype,\"startMonitorStats\"),pF.prototype),pF),IF=(_F=rA({argsMap:(e,t)=>[e.getTrackId(),t]}),EF=Lx(),mF=py(\"CameraVideoTrack\",\"_enabledMutex\"),fF=rA({argsMap:(e,t)=>[e.getTrackId(),t]}),TF=Lx(),SF=rA({argsMap:(e,t)=>[e.getTrackId(),t]}),gF=Lx(),RF=rA({argsMap:e=>[e.getTrackId()]}),CF=class e extends vF{get __className__(){return\"CameraVideoTrack\"}constructor(e,t,i,n,r,o){super(e,yU(t.encoderConfig),n,r,o),ix(this,\"_config\",void 0),ix(this,\"_originalConstraints\",void 0),ix(this,\"_constraints\",void 0),ix(this,\"_enabled\",!0),ix(this,\"_deviceName\",\"default\"),ix(this,\"tryResumeVideoForIOS15_16WeChat\",(async()=>{(Gv()||Wv())&&!function(){const e=Iv();if(e.os!==Sv.IOS||!e.osVersion)return!1;const t=e.osVersion.split(\".\");return 15===Number(t[0])&&Number(t[1])>=2}()&&Yv()&&this._enabled&&!this._isClosed&&(Qy.debug(\"[\".concat(this.getTrackId(),\"] try capture camera media device for interrupted iOS 15 device on WeChat.\")),await this.renewMediaStreamTrack())})),this._config=t,this._originalConstraints=i,this._constraints=i,this._deviceName=e.label,this._encoderConfig=yU(this._config.encoderConfig),cx.on(mU.IOS_15_16_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),cx.on(mU.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(Qy.info(\"[\".concat(this.getTrackId(),\"] set device to \").concat(e)),this._enabled)try{const t=await Ax.getDeviceById(e),i={};i.video=tx({},this._constraints),i.video.deviceId={exact:e},i.video.facingMode=void 0,this._originMediaStreamTrack.stop();let n=null;try{n=await Cx(i,this.getTrackId())}catch(e){throw Qy.error(\"[\".concat(this.getTrackId(),\"] setDevice failed\"),e.toString()),n=await Cx({video:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(n.getVideoTracks()[0],!1),e}await this._updateOriginMediaStreamTrack(n.getVideoTracks()[0],!1),this.updateMediaStreamTrackResolution(),this._deviceName=t.label,this._config.cameraId=e,this._constraints.deviceId={exact:e}}catch(e){throw Qy.error(\"[\".concat(this.getTrackId(),\"] setDevice error\"),e.toString()),e}else try{const t=await Ax.getDeviceById(e);this._deviceName=t.label,this._config.cameraId=e,this._constraints.deviceId={exact:e}}catch(e){throw Qy.error(\"[\".concat(this.getTrackId(),\"] setDevice error\"),e.toString()),e}Qy.info(\"[\".concat(this.getTrackId(),\"] setDevice success\"))}async _setDeviceByFacingModel(e){Qy.info(\"[\".concat(this.getTrackId(),\"] set facingMode \").concat(e));const t={video:tx(tx({},this._constraints),{},{deviceId:void 0,facingMode:{exact:e}})};if(this._enabled){this._originMediaStreamTrack.stop();let e=null;try{e=await Cx(t,this.getTrackId())}catch(t){throw Qy.error(\"[\".concat(this.getTrackId(),\"] setDeviceByFacingModel failed\"),t.toString()),e=await Cx({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=tx({},t.video),Qy.info(\"[\".concat(this.getTrackId(),\"] setDeviceByFacingModel success\"))}async setEnabled(e,t){if(!t){if(e===this._enabled)return;this.stateCheck(\"enabled\",e)}if(Qy.info(\"[\".concat(this.getTrackId(),\"] start setEnabled\"),e),e){try{if(this.isExternalTrack)this._originMediaStreamTrack.enabled=!0;else{const e=await Cx({video:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!1)}await MI(this,PU.NEED_ENABLE_TRACK,this)}catch(e){throw Qy.error(\"[\".concat(this.getTrackId(),\"] setEnabled true error\"),e.toString()),e}this.updateMediaStreamTrackResolution(),Qy.info(\"[\".concat(this.getTrackId(),\"] setEnabled to true success\")),t||(this._enabled=!0)}else{this.isExternalTrack?this._originMediaStreamTrack.enabled=!1:(this._originMediaStreamTrack.onended=null,this._originMediaStreamTrack.stop()),t||(this._enabled=!1);try{await MI(this,PU.NEED_DISABLE_TRACK,this)}catch(e){throw Qy.error(\"[\".concat(this.getTrackId(),\"] setEnabled to false error\"),e.toString()),e}Qy.info(\"[\".concat(this.getTrackId(),\"] setEnabled to false success\"))}}async setEncoderConfiguration(e,t){if(!this._enabled)throw new iI(tI.TRACK_IS_DISABLED,\"can not set encoder configuration when track is disabled\");\"720p_auto\"===e?this.startMonitorStats():this._statsTimer&&(window.clearInterval(this._statsTimer),this._statsTimer=null),e=yU(e),this._forceBitrateLimit&&(e.bitrateMax=this._forceBitrateLimit.max_bitrate||e.bitrateMax,e.bitrateMin=this._forceBitrateLimit.min_bitrate||e.bitrateMin);const i=GI(this._config);i.encoderConfig=e;const n=jx(i);(Nv()||Lv()||Kv())&&(n.deviceId=void 0),Qy.debug(\"[\".concat(this.getTrackId(),\"] setEncoderConfiguration applyConstraints\"),JSON.stringify(e),JSON.stringify(n));try{await this._originMediaStreamTrack.applyConstraints(n),this.updateMediaStreamTrackResolution()}catch(e){const t=new iI(tI.UNEXPECTED_ERROR,e.toString());throw Qy.error(\"[\".concat(this.getTrackId(),\"] applyConstraints error\"),t.toString()),t}this._config=i,this._constraints=n,this._originalConstraints=n,this._encoderConfig=e,-1===this._hints.indexOf(LU.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await MI(this,PU.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(Qy)}}_getDefaultPlayerConfig(){return{mirror:!0,fit:\"cover\"}}onTrackEnded(){if((Lv()||Kv())&&this._enabled&&!this._isClosed&&cx.duringInterruption){const e=async()=>{cx.off(mU.IOS_INTERRUPTION_END,e),this._enabled&&!this._isClosed&&(Qy.debug(\"[\".concat(this.getTrackId(),\"] try capture camera media device for interrupted iOS device.\")),await this.setEnabled(!1),await this.setEnabled(!0))};cx.on(mU.IOS_INTERRUPTION_END,e)}else Qy.debug(\"[\".concat(this.getTrackId(),\"] track ended\")),this.safeEmit(VU.TRACK_ENDED)}async renewMediaStreamTrack(e){const t=e||this._constraints,i=Ax.searchDeviceIdByName(this._deviceName);if(i&&!t.deviceId&&(t.deviceId={exact:i}),this._enabled){const e=await Cx({video:t},this.getTrackId());this._constraints=t,await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!0),this.updateMediaStreamTrackResolution()}}close(){super.close(),cx.off(mU.IOS_15_16_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),cx.off(mU.IOS_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat)}clone(t){let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],n=this._encoderConfig;t&&(n=tx(tx({},n),yU(t))),n=WI(n);const r=ey(8,\"track-cam-cloned-\"),o=new e(i?this._mediaStreamTrack.clone():this._mediaStreamTrack,WI(tx(tx({},this._config),{},{encoderConfig:n})),WI(this._constraints),WI(this._scalabilityMode),this._optimizationMode,r);return t&&n&&o.setEncoderConfiguration(n),Qy.debug(\"clone track from \".concat(this.getTrackId(),\" to \").concat(r,\", clone \").concat(i)),o}bindProcessorContextEvents(){this.processorContext.on(qU.REQUEST_UPDATE_CONSTRAINTS,(async(e,t,i)=>{try{const i=Object.assign({},this._originalConstraints,...e);await this.renewMediaStreamTrack(i),t()}catch(e){i(e)}})),this.processorContext.on(qU.REQUEST_CONSTRAINTS,(async e=>{e(this._originMediaStreamTrack.getSettings())}))}},nx(CF.prototype,\"setDevice\",[_F,EF],Object.getOwnPropertyDescriptor(CF.prototype,\"setDevice\"),CF.prototype),nx(CF.prototype,\"setEnabled\",[mF,fF,TF],Object.getOwnPropertyDescriptor(CF.prototype,\"setEnabled\"),CF.prototype),nx(CF.prototype,\"setEncoderConfiguration\",[SF,gF],Object.getOwnPropertyDescriptor(CF.prototype,\"setEncoderConfiguration\"),CF.prototype),nx(CF.prototype,\"close\",[RF],Object.getOwnPropertyDescriptor(CF.prototype,\"close\"),CF.prototype),CF);function yF(e,t,i,n){i.optimizationMode&&(n&&n.width&&n.height?(i.encoderConfig=tx(tx({},n),{},{bitrateMin:n.bitrateMin,bitrateMax:n.bitrateMax}),\"motion\"!==i.optimizationMode&&\"detail\"!==i.optimizationMode||(t.contentHint=i.optimizationMode,t.contentHint===i.optimizationMode?Qy.debug(\"[\".concat(e,\"] set content hint to\"),i.optimizationMode):Qy.debug(\"[\".concat(e,\"] set content hint failed\")))):Qy.warning(\"[\".concat(e,\"] can not apply optimization mode bitrate config, no encoderConfig\")))}var AF,bF,wF,OF,NF,DF,PF,LF,kF,MF,UF,xF;class VF extends rx{getUserId(){return this._userId}constructor(e,t,i,n){super(e,\"track-\".concat(e.kind,\"-\").concat(t,\"-\").concat(n.clientId,\"_\").concat(ey(5,\"\"))),ix(this,\"_userId\",void 0),ix(this,\"_uintId\",void 0),ix(this,\"_isDestroyed\",!1),ix(this,\"store\",void 0),ix(this,\"processor\",void 0),ix(this,\"processorContext\",void 0),this._userId=t,this._uintId=i,this.store=n}_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,Qy.info(\"[\".concat(this.getTrackId(),\"] is destroyed\")),this.stop(),super.close()}getProcessorStats(){return this.processorContext.gatherStats()}getProcessorUsage(){return this.processorContext.gatherUsage()}}let FF=(AF=rA({argsMap:(e,t,i)=>[e.getTrackId(),\"string\"==typeof t?t:t instanceof HTMLVideoElement?\"HTMLVideoElement\":\"HTMLElement\",i]}),bF=rA({argsMap:e=>[e.getTrackId()]}),wF=rA({argsMap:(e,t)=>[e.getTrackId(),t.name]}),OF=rA({argsMap:e=>[e.getTrackId()]}),nx((NF=class extends VF{get isPlaying(){return!(!this._player||this._player.videoElementStatus!==XU.PLAYING)}get __className__(){return\"RemoteVideoTrack\"}constructor(e,t,i,n){super(e,t,i,n),ix(this,\"_videoVisibleTimer\",null),ix(this,\"_previousVideoVisibleStatus\",void 0),ix(this,\"_clearPreviousVideoVisibleStatus\",(()=>this._previousVideoVisibleStatus=void 0)),ix(this,\"trackMediaType\",\"video\"),ix(this,\"_videoWidth\",void 0),ix(this,\"_videoHeight\",void 0),ix(this,\"_player\",void 0),ix(this,\"processorDestination\",void 0),ix(this,\"processorContext\",void 0),this.updateMediaStreamTrackResolution(),this.processorContext=new Mx(this.getTrackId(),\"remote\"),this.processorDestination=new kx(this.processorContext),this.bindProcessorDestinationEvents()}getStats(){return KI((()=>{Qy.warning(\"[deprecated] RemoteVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteVideoStats instead\")}),\"remoteVideoTrackGetStatsWarning\"),UI(this,PU.GET_STATS)||tx({},KU)}play(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(\"string\"==typeof e){const t=document.getElementById(e);t?e=t:(Qy.warning(\"[\".concat(this.getTrackId(),'] can not find \"#').concat(e,'\" element, use document.body')),e=document.body)}Qy.debug(\"[\".concat(this.getTrackId(),\"] start video playback in \").concat(e instanceof HTMLVideoElement?\"HTMLVideoElement\":\"HTMLElement\"),JSON.stringify(t));const i=tx(tx({fit:\"cover\"},t),{},{trackId:this.getTrackId(),element:e});this._player?this._player.updateConfig(i):(e instanceof HTMLVideoElement?this._player=new FV(i):this._player=new jV(i),this._player.updateVideoTrack(this._mediaStreamTrack),this._player.onFirstVideoFrameDecoded=()=>{this.store.subscribe(this.getUserId(),\"video\",void 0,void 0,Date.now()),this.safeEmit(FU.FIRST_FRAME_DECODED)},this._player.onVideoStateChanged=e=>{this.safeEmit(FU.VIDEO_STATE_CHANGED,e)}),this._player.play(this.store.sessionId||void 0),this._videoVisibleTimer&&window.clearInterval(this._videoVisibleTimer),this._clearPreviousVideoVisibleStatus(),this._videoVisibleTimer=window.setInterval((()=>{try{const e=this.getVideoElementVisibleStatus();this.safeEmit(FU.VIDEO_ELEMENT_VISIBLE_STATUS,e)}catch(e){}}),Dy(\"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,Qy.debug(\"[\".concat(this.getTrackId(),\"] stop video playback\")))}getCurrentFrameData(){return this._player?this._player.getCurrentFrame():new ImageData(2,2)}updateMediaStreamTrackResolution(){Bx(this._originMediaStreamTrack).then((e=>{let[t,i]=e;this._videoHeight=i,this._videoWidth=t})).catch(iy)}_updatePlayerSource(){Qy.debug(\"[\".concat(this.getTrackId(),\"] update player source track\")),this._player&&this._player.updateVideoTrack(this._mediaStreamTrack)}getVideoElementVisibleStatus(){try{var e,t;const i=null==this||null===(e=this._player)||void 0===e?void 0:e.getContainerElement(),n={track:this,element:null==this||null===(t=this._player)||void 0===t?void 0:t.getVideoElement(),slot:null==i?void 0:i.parentElement},{element:r,slot:o}=n;if(this.isPlaying&&r instanceof HTMLVideoElement&&o instanceof HTMLElement){const e=EI.checkOneElementVisible(r),t=Object.assign({},e);if(t.visible!==this._previousVideoVisibleStatus){this._previousVideoVisibleStatus=t.visible;const e=oA.reportApiInvoke(null,{tag:vI.TRACER,name:CI.REMOTE_VIDEO_TRACK_GET_VIDEO_VISIBLE,options:[this.getTrackId()]});t.visible?e.onSuccess(\"Video is visible\"):e.onSuccess(\"Invisible because of \".concat(t.reason))}return t}return}catch(e){throw new iI(tI.GET_VIDEO_ELEMENT_VISIBLE_ERROR,e.message)}}pipe(e){if(this.processor===e)return e;if(e._source)throw new iI(tI.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(YU.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(YU.ON_TRACK)}_destroy(){super._destroy(),this.unbindProcessorDestinationEvents()}_onSei(e){this.emit(xU.SEI_RECEIVED,e)}}).prototype,\"play\",[AF],Object.getOwnPropertyDescriptor(NF.prototype,\"play\"),NF.prototype),nx(NF.prototype,\"stop\",[bF],Object.getOwnPropertyDescriptor(NF.prototype,\"stop\"),NF.prototype),nx(NF.prototype,\"pipe\",[wF],Object.getOwnPropertyDescriptor(NF.prototype,\"pipe\"),NF.prototype),nx(NF.prototype,\"unpipe\",[OF],Object.getOwnPropertyDescriptor(NF.prototype,\"unpipe\"),NF.prototype),NF),BF=(DF=rA({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),PF=rA({argsMap:(e,t)=>[e.getTrackId(),t]}),LF=rA({argsMap:e=>[e.getTrackId()]}),kF=rA({argsMap:e=>[e.getTrackId()]}),MF=rA({argsMap:(e,t)=>[e.getTrackId(),t.name]}),UF=rA({argsMap:e=>[e.getTrackId()]}),nx((xF=class extends VF{get isPlaying(){return this._useAudioElement?Px.isPlaying(this.getTrackId()):this._source.isPlayed}get __className__(){return\"RemoteAudioTrack\"}constructor(e,t,i,n){super(e,t,i,n),ix(this,\"trackMediaType\",\"audio\"),ix(this,\"_source\",void 0),ix(this,\"_useAudioElement\",!0),ix(this,\"_volume\",100),ix(this,\"processorContext\",void 0),ix(this,\"processorDestination\",void 0),ix(this,\"_played\",!1),ix(this,\"_bypassWebAudio\",!1),Dy(\"DISABLE_WEBAUDIO\")?(this._source=new Vx,this._bypassWebAudio=!0,this._useAudioElement=!0):(this._source=new Ex(e,!0),Dy(\"REMOTE_AUDIO_TRACK_USES_WEB_AUDIO\")&&(this._useAudioElement=!1)),this._source.once(BU.RECEIVE_TRACK_BUFFER,(()=>{this.safeEmit(FU.FIRST_FRAME_DECODED)})),this.processorContext=new xx(this._source.context,this.getTrackId(),\"remote\"),this.processorDestination=new Ux(this.processorContext),this.bindProcessorDestinationEvents(),this._source.on(BU.UPDATE_SOURCE,(()=>{this.processor&&this.processor.updateInput({node:this._source.processSourceNode,context:this.processorContext})}))}setAudioFrameCallback(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:4096;if(!e)return this._source.removeAllListeners(BU.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(t),this._source.removeAllListeners(BU.ON_AUDIO_BUFFER),this._source.on(BU.ON_AUDIO_BUFFER,(t=>e(t)))}setVolume(e){this._volume=e,this._useAudioElement?Px.setVolume(this.getTrackId(),e):this._source.setVolume(e/100)}async setPlaybackDevice(e){if(!this._useAudioElement||!EU())throw new iI(tI.NOT_SUPPORTED,\"your browser does not support setting the audio output device\");await Px.setSinkID(this.getTrackId(),e)}getVolumeLevel(){return this._source.getAccurateVolumeLevel()}getStats(){return KI((()=>{Qy.warning(\"[deprecated] RemoteAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteAudioStats instead\")}),\"remoteAudioTrackGetStatsWarning\"),UI(this,PU.GET_STATS)||tx({},WU)}play(){Qy.debug(\"[\".concat(this.getTrackId(),\"] start audio playback\")),this._played=!0,this._useAudioElement?(Qy.debug(\"[\".concat(this.getTrackId(),\"] use audio element to play\")),Px.play(this._mediaStreamTrack,this.getTrackId(),this._volume,this.store.sessionId||void 0)):this._source.play()}stop(){Qy.debug(\"[\".concat(this.getTrackId(),\"] stop audio playback\")),this._played=!1,this._useAudioElement?Px.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];Qy.debug(\"[\".concat(this.getTrackId(),\"] update player source track\")),e&&this._source.updateTrack(this._mediaStreamTrack),this._useAudioElement&&Px.updateTrack(this.getTrackId(),this._mediaStreamTrack)}pipe(e){if(this._bypassWebAudio)throw new iI(tI.NOT_SUPPORTED,\"can not pipe extension when WebAudio disabled\");if(this.processor===e)return e;if(e._source)throw new iI(tI.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 iI(tI.NOT_SUPPORTED,\"can not unpipe extension when WebAudio disabled\");if(!this.processor)return;const t=this.processor;null===(e=this._source.processSourceNode)||void 0===e||e.disconnect(),this.processor._source=!1,this.processor=void 0,t.reset()}bindProcessorDestinationEvents(){this.processorDestination.on(YU.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(YU.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(YU.ON_TRACK),this.processorDestination.removeAllListeners(YU.ON_NODE)}}).prototype,\"setVolume\",[DF],Object.getOwnPropertyDescriptor(xF.prototype,\"setVolume\"),xF.prototype),nx(xF.prototype,\"setPlaybackDevice\",[PF],Object.getOwnPropertyDescriptor(xF.prototype,\"setPlaybackDevice\"),xF.prototype),nx(xF.prototype,\"play\",[LF],Object.getOwnPropertyDescriptor(xF.prototype,\"play\"),xF.prototype),nx(xF.prototype,\"stop\",[kF],Object.getOwnPropertyDescriptor(xF.prototype,\"stop\"),xF.prototype),nx(xF.prototype,\"pipe\",[MF],Object.getOwnPropertyDescriptor(xF.prototype,\"pipe\"),xF.prototype),nx(xF.prototype,\"unpipe\",[UF],Object.getOwnPropertyDescriptor(xF.prototype,\"unpipe\"),xF.prototype),xF);const jF=new class extends SI{get visibility(){return document.visibilityState}get lastHiddenTime(){return this._lastHiddenTime}get lastVisibleTime(){return this._lastVisibleTime}constructor(){super(),ix(this,\"_lastHiddenTime\",0),ix(this,\"_lastVisibleTime\",0),document.addEventListener(\"visibilitychange\",(()=>{\"hidden\"===document.visibilityState?this._lastHiddenTime=performance.now():this._lastVisibleTime=performance.now(),Qy.debug(\"document visibility went \".concat(document.visibilityState)),this.emit(\"VISIBILITY_CHANGE\",document.visibilityState)}))}};var GF=function(e){return e[e.ONE_BYTE=0]=\"ONE_BYTE\",e[e.TWO_BYTE=1]=\"TWO_BYTE\",e}(GF||{});class WF{constructor(){ix(this,\"_sequence\",0),ix(this,\"_startTime\",Date.now()),ix(this,\"isUseOneByte\",!0)}get startTime(){const e=Date.now()-this._startTime;return e128){const i=new Uint8Array(4);i.set([1,0,0,0]);const n={id:0,length:4,data:i.buffer},r={profile:this.isUseOneByte?0:1,length:this.isUseOneByte?5:6,datas:[n]};t.commonPacketHeader.extension=1,t.extension=r,t.payload=this.compress(e),t.commonPacketHeader.length=8+(t.extension.length+2)+t.payload.byteLength}else t.commonPacketHeader.length=8+t.payload.byteLength;Dy(\"SHOW_DATASTREAM2_LOG\")&&Qy.debug(\"send data header: \".concat(JSON.stringify(t.commonPacketHeader)));const i=new ArrayBuffer(t.commonPacketHeader.length),n=new Uint8Array(i),r=new DataView(i);let o=0;if(r.setUint16(o,t.commonPacketHeader.extension<<15|t.commonPacketHeader.reserved<<14|t.commonPacketHeader.length,!0),o+=2,r.setUint32(o,t.commonPacketHeader.sequence,!0),o+=4,r.setUint16(o,t.commonStreamHeader,!0),o+=2,t.extension){const e=this.serializeExtension(t.extension);n.set(new Uint8Array(e),o),o+=e.byteLength}if(n.set(new Uint8Array(t.payload),o),o+=t.payload.byteLength,o!==t.commonPacketHeader.length)throw Error(\"serialize error!\");return i}deserialize(e){if(e.byteLength<4)return new ArrayBuffer(0);const t=new DataView(e);let i=0;const n=t.getUint16(i,!0);i+=2;const r={length:16383&n,reserved:(16384&n)>>14,extension:(32768&n)>>15,sequence:t.getUint16(i+2,!0)<<16|t.getUint16(i,!0)};let o,s;if(i+=4,Dy(\"SHOW_DATASTREAM2_LOG\")&&Qy.debug(\"receive data header: \".concat(JSON.stringify(r))),t.getUint16(i,!0),i+=2,r.extension){s=this.deserializeExtension(e.slice(i)),i+=2+s.length,o=e.slice(i);let t=!1;if(s.datas.length>0){const e=s.datas.find((e=>0===e.id));e&&(t=1==(1&new DataView(e.data).getUint32(0,!0)))}o=t?this.decompress(o):o}else o=e.slice(8);return o}serializeExtension(e){const{profile:t,length:i,datas:n}=e,r=new ArrayBuffer(i+2),o=new Uint8Array(r),s=new DataView(r);let a=0;if(s.setUint8(a++,t),s.setUint8(a++,i),n.forEach((e=>{t?(s.setUint8(a++,e.id),s.setUint8(a++,e.length),o.set(new Uint8Array(e.data),a),a+=e.data.byteLength):(s.setUint8(a++,e.id|e.length<<4),o.set(new Uint8Array(e.data),a),a+=e.data.byteLength)})),a!==i+2)throw Error(\"serialize extension error, is \".concat(a,\"!==\").concat(i+2));return r}deserializeExtension(e){const t=new DataView(e);let i=0;const n=t.getUint8(i);i++;const r=t.getUint8(i);i++;const o=n===GF.TWO_BYTE,s=[],a=new DataView(e,2);let c=0;for(;c>4,c++),t>0&&(i=a.buffer.slice(c+2,c+2+t),c+=i.byteLength),s.push({id:e,length:t,data:i})}if(c!==r)throw Error(\"parse error\");return{profile:n,length:r,datas:s}}decompress(e){return uU(new Uint8Array(e))}compress(e){return hU(new Uint8Array(e))}}class HF extends SI{constructor(e,t){super(),ix(this,\"_version\",1),ix(this,\"_type\",3),ix(this,\"_config\",void 0),ix(this,\"_originDataChannel\",void 0),ix(this,\"_dataStreamPacketHeader\",new ArrayBuffer(4)),ix(this,\"_dataStreamPacketHandler\",void 0),ix(this,\"_datachannelEventMap\",new Map),this._config=e,t&&(this._originDataChannel=t,this._bandDataChannelEvents(t)),this._initPacketHeader(),this._dataStreamPacketHandler=new WF}get id(){return this._config.id}get ordered(){return this._config.ordered}get maxRetransmits(){return Dy(\"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 Gu(((e,t)=>{if(this._originDataChannel){\"open\"===this._originDataChannel.readyState&&e();const i=setTimeout((()=>{var e;t(new iI(tI.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 iI(tI.DATACHANNEL_CONNECTION_TIMEOUT)}}else t(new iI(tI.DATACHANNEL_CONNECTION_TIMEOUT,\"cannot find dataChannel\"))}))}_updateOriginDataChannel(e){this._originDataChannel=e,this._bandDataChannelEvents(e)}_initPacketHeader(){const e=new DataView(this._dataStreamPacketHeader);e.setUint16(0,this._version),e.setUint8(2,this._type),e.setUint8(3,this._config.id)}_bandDataChannelEvents(e){this._unbindDataChannelEvents(e),[$U.OPEN,$U.CLOSE,$U.ERROR].forEach((t=>{const i=()=>{this.emit(t)};this._datachannelEventMap.set(t,i),e.addEventListener(t,i)}))}_unbindDataChannelEvents(e){Array.from(this._datachannelEventMap.entries()).forEach((t=>{let[i,n]=t;e.removeEventListener(i,n)})),this._datachannelEventMap.clear()}}class KF extends HF{constructor(e){super(e),ix(this,\"_messageListener\",void 0),this._messageListener=e=>{if(e.data.byteLengthMP.revokeObjectURL(e)),0),new Worker(MP.createObjectURL(e))}const zF=new Map;const JF=new Map;const XF=new Map;async function QF(e,t){if(!_U().supportWebRTCEncodedTransform)return void Qy.warning(\"browser not support video encoded transform\");if(XF.has(e))return;if(!e.track)return;const i={track:e.track};if(Ov()){if(!e.createEncodedStreams)return void Qy.warning(\"browser not support createEncodedStreams() API\");let r=null;try{r=e.createEncodedStreams()}catch(e){return void Qy.error(\"create video-encoded-streams error\",e&&e.message)}let o=[];t.on(\"sei-to-send\",(e=>{o.push(e)}));const s=new TransformStream({transform(t,r){i.controller||(i.controller=r),e.track&&e.track.id!==i.track.id&&(Qy.debug(\"video track changed: \".concat(i.track.id,\" => \").concat(e.track.id)),i.track.removeEventListener(\"ended\",n),i.track=e.track,i.track.addEventListener(\"ended\",n));const s=o.shift();s&&(t.data=function(e,t){const i=function(e){const t=e.length;let i=[],n=0;for(;nr.onmessage=t=>{\"registered\"===t.data&&e(void 0)}));const s=new RTCRtpScriptTransform(r,{name:\"tx\",port:o.port2},[o.port2]);e.transform=s,await new Gu((e=>r.onmessage=t=>{\"started\"===t.data&&e(void 0)})),t.on(\"sei-to-send\",(e=>{o.port1.postMessage({sei:e})})),o.port1.onmessage=t=>{var r;t.data.transformed&&e.track&&(null===(r=e.track)||void 0===r?void 0:r.id)!==i.track.id&&(Qy.debug(\"video track changed: \".concat(i.track.id,\" => \").concat(e.track.id)),i.track.removeEventListener(\"ended\",n),i.track=e.track,i.track.addEventListener(\"ended\",n))},i.worker=r}}function n(){if(e.track){if(this.id!==e.track.id)return;e.track.removeEventListener(\"ended\",n)}const t=XF.get(e);if(t){XF.delete(e);try{var i,r;null===(i=t.controller)||void 0===i||i.terminate(),null===(r=t.worker)||void 0===r||r.terminate()}catch(e){Qy.warning(e&&e.message)}}}XF.set(e,i),e.track.addEventListener(\"ended\",n)}const ZF=new Map;async function $F(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!_U().supportWebRTCEncodedTransform)return void Qy.warning(\"browser not support video encoded transform\");if(!e.track)return;if(ZF.has(e)){const i=ZF.get(e);return void(i&&(i.onSei=t.onSei))}const i={track:e.track,onSei:t.onSei};if(Ov()){if(!e.createEncodedStreams)return void Qy.warning(\"browser not support createEncodedStreams() API\");let t=null;try{t=e.createEncodedStreams()}catch(e){return void Qy.error(\"create video-encoded-streams error\",e&&e.message)}const r=new TransformStream({transform(t,r){i.controller||(i.controller=r),e.track&&e.track.id!==i.track.id&&(Qy.debug(\"video track changed: \".concat(i.track.id,\" => \").concat(e.track.id)),i.track.removeEventListener(\"ended\",n),i.track=e.track,i.track.addEventListener(\"ended\",n));const o=function(e){const t=new DataView(e.data);if(0===t.getUint8(0)&&0===t.getUint8(1)&&0===t.getUint8(2)&&1===t.getUint8(3)&&6===t.getUint8(4)){let i=6,n=0,r=0;for(;255===(r=t.getUint8(i++));)n+=255;n+=r;const o=function(e,t,i){let n=new Uint8Array(e,t,i),r=[],o=0;for(;ot.onmessage=t=>{\"registered\"===t.data&&e(void 0)}));const o=new RTCRtpScriptTransform(t,{name:\"rx\",port:r.port2},[r.port2]);e.transform=o,await new Gu((e=>t.onmessage=t=>{\"started\"===t.data&&e(void 0)})),r.port1.onmessage=t=>{var r;t.data.transformed&&e.track&&(null===(r=e.track)||void 0===r?void 0:r.id)!==i.track.id?(Qy.debug(\"video track changed: \".concat(i.track.id,\" => \").concat(e.track.id)),i.track.removeEventListener(\"ended\",n),i.track=e.track,i.track.addEventListener(\"ended\",n)):t.data.sei&&i.onSei&&i.onSei(t.data.sei)},i.worker=t}function n(){if(e.track){if(this.id!==e.track.id)return;e.track.removeEventListener(\"ended\",n)}!function(e){const t=ZF.get(e);if(t){ZF.delete(e);try{var i,n;null===(i=t.controller)||void 0===i||i.terminate(),null===(n=t.worker)||void 0===n||n.terminate()}catch(e){Qy.warning(e&&e.message)}}}(e)}ZF.set(e,i),e.track.addEventListener(\"ended\",n)}!function(){const e=Iv();pU.getDisplayMedia=!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia),pU.getStreamFromExtension=e.name===gv.CHROME&&Number(e.version)>34,pU.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}(),pU.supportMinBitrate=e.name===gv.CHROME||e.name===gv.EDGE,pU.supportSetRtpSenderParameters=function(){const e=Iv();return!!(window.RTCRtpSender&&window.RTCRtpSender.prototype.setParameters&&window.RTCRtpSender.prototype.getParameters)&&(!!Jv()||!(!Nv()&&!wv())||e.name===gv.FIREFOX&&Number(e.version)>=64)}(),e.name===gv.SAFARI&&(Number(e.version)>=14?pU.supportDualStream=!0:pU.supportDualStream=!1),pU.webAudioMediaStreamDest=function(){const e=Iv();return!(e.name===gv.SAFARI&&Number(e.version)<12)}(),pU.supportReplaceTrack=!!window.RTCRtpSender&&\"function\"==typeof RTCRtpSender.prototype.replaceTrack,pU.supportWebGL=\"undefined\"!=typeof WebGLRenderingContext,pU.supportRequestFrame=!!window.CanvasCaptureMediaStreamTrack,Jv()||(pU.webAudioWithAEC=!0),pU.supportShareAudio=function(){const e=Iv();return(e.os===Sv.WIN_10||e.os===Sv.WIN_81||e.os===Sv.WIN_7||e.os===Sv.LINUX||e.os===Sv.MAC_OS||e.os===Sv.CHROMIUM_OS)&&e.name===gv.CHROME&&Number(e.version)>=74}(),pU.supportDataChannel=!!(kv(76)||function(e){const t=Iv();return!(t.name!==gv.FIREFOX||!t.osVersion)&&Number(t.version)>=e}(68)||Uv(14)),pU.supportPCSetConfiguration=function(){const e=window.RTCPeerConnection;return!Pv()&&!!e&&e.prototype.setConfiguration instanceof Function}(),pU.supportWebRTCEncodedTransform=function(){const e=Iv();return\"Chrome\"===e.name&&Number(e.version)>=86||\"Safari\"===e.name&&Number(e.version)>=15}(),pU.supportWebRTCInsertableStream=function(){const e=Iv();return(e.name===gv.CHROME||e.name===gv.EDGE)&&Number(e.version)>=94&&\"MediaStreamTrackGenerator\"in window&&\"MediaStreamTrackProcessor\"in window}(),pU.supportRequestVideoFrameCallback=\"requestVideoFrameCallback\"in HTMLVideoElement.prototype,pU.supportWebCrypto=\"undefined\"!=typeof window&&void 0!==window.crypto&&void 0!==window.crypto.subtle,jI((()=>{pU.supportDualStreamEncoding=function(){const e=Iv();return!!Dy(\"DISABLE_WEBAUDIO\")||(\"Safari\"===e.name&&Number(e.version)>=14||!!(\"Chrome\"===e.name&&/Windows/i.test(e.os||\"\")&&Number(e.version)>=100&&Dy(\"CHROME_DUAL_STREAM_USE_ENCODING\")))}(),Qy.info(\"browser compatibility\",JSON.stringify(pU),JSON.stringify(e))}))}();class eB extends SI{constructor(){super(...arguments),ng(this,\"resultStorage\",new Map)}setLocalAudioStats(e,t,i){this.record(\"AUDIO_INPUT_LEVEL_TOO_LOW\",e,this.checkAudioInputLevel(i,t)),this.record(\"SEND_AUDIO_BITRATE_TOO_LOW\",e,this.checkSendAudioBitrate(i,t))}setLocalVideoStats(e,t,i){this.record(\"SEND_VIDEO_BITRATE_TOO_LOW\",e,this.checkSendVideoBitrate(i,t)),this.record(\"FRAMERATE_INPUT_TOO_LOW\",e,this.checkFramerateInput(i,t)),this.record(\"FRAMERATE_SENT_TOO_LOW\",e,this.checkFramerateSent(i))}setRemoteAudioStats(e,t){const i=e.getUserId();this.record(\"AUDIO_OUTPUT_LEVEL_TOO_LOW\",i,this.checkAudioOutputLevel(t))}setRemoteVideoStats(e,t){const i=e.getUserId();this.record(\"RECV_VIDEO_DECODE_FAILED\",i,this.checkVideoDecode(t))}record(e,t,i){if(Dy(\"STATS_UPDATE_INTERVAL\")>500)return;this.resultStorage.has(e)||this.resultStorage.set(e,{result:[],isPrevNormal:!0});const n=this.resultStorage.get(e);if(n&&(n.result.push(i),n.result.length>=5)){var r;const i=Dn(r=n.result).call(r,!0);n.isPrevNormal&&!i&&this.emit(\"exception\",tB[e],e,t),!n.isPrevNormal&&i&&this.emit(\"exception\",tB[e]+2e3,e+\"_RECOVER\",t),n.isPrevNormal=i,n.result=[]}}checkAudioOutputLevel(e){return!(e.receiveBitrate>0&&0===e.receiveLevel)}checkAudioInputLevel(e,t){return t instanceof UV&&!t.isActive||(!!t.muted||0!==e.sendVolumeLevel)}checkFramerateInput(e,t){let i=null;t._encoderConfig&&t._encoderConfig.frameRate&&(i=Yw(t._encoderConfig.frameRate));const n=e.captureFrameRate;return!i||!n||!(i>10&&n<5||i<10&&i>=5&&n<=1)}checkFramerateSent(e){return!(e.captureFrameRate&&e.sendFrameRate&&e.captureFrameRate>5&&e.sendFrameRate<=1)}checkSendVideoBitrate(e,t){return!!t.muted||0!==e.sendBitrate}checkSendAudioBitrate(e,t){return t instanceof UV&&!t.isActive||(!!t.muted||0!==e.sendBitrate)}checkVideoDecode(e){return 0===e.receiveBitrate||0!==e.decodeFrameRate}}const tB={FRAMERATE_INPUT_TOO_LOW:1001,FRAMERATE_SENT_TOO_LOW:1002,SEND_VIDEO_BITRATE_TOO_LOW:1003,RECV_VIDEO_DECODE_FAILED:1005,AUDIO_INPUT_LEVEL_TOO_LOW:2001,AUDIO_OUTPUT_LEVEL_TOO_LOW:2002,SEND_AUDIO_BITRATE_TOO_LOW:2003};const iB=new class{markSubscribeStart(e,t){performance.mark(\"agora-web-sdk/\".concat(e,\"/subscribe-\").concat(t))}markPublishStart(e,t){performance.mark(\"agora-web-sdk/\".concat(e,\"/publish-\").concat(t))}measureFromSubscribeStart(e,t){const i=performance.getEntriesByName(\"agora-web-sdk/\".concat(e,\"/subscribe-\").concat(t));if(i.length>0){const e=i[i.length-1];return Math.round(performance.now()-e.startTime)}return 0}measureFromPublishStart(e,t){const i=performance.getEntriesByName(\"agora-web-sdk/\".concat(e,\"/publish-\").concat(t));if(i.length>0){const e=i[i.length-1];return Math.round(performance.now()-e.startTime)}return 0}};function nB(e,t){this.v=e,this.k=t}function rB(e){return new nB(e,0)}var oB=ju,sB=Sl;wi({target:\"Promise\",stat:!0,forced:!0},{withResolvers:function(){var e=sB.f(this);return{promise:e.promise,resolve:e.resolve,reject:e.reject}}});var aB=Sl,cB=el;wi({target:\"Promise\",stat:!0,forced:!0},{try:function(e){var t=aB.f(this),i=cB(e);return(i.error?t.reject:t.resolve)(i.value),t.promise}});var dB=i(oB),lB=tf.f(\"asyncIterator\"),hB=i(lB);function uB(e){var t,i;function n(t,i){try{var o=e[t](i),s=o.value,a=s instanceof nB;dB.resolve(a?s.v:s).then((function(i){if(a){var c=\"return\"===t?\"return\":\"next\";if(!s.k||i.done)return n(c,i);i=e[c](i).value}r(o.done?\"return\":\"normal\",i)}),(function(e){n(\"throw\",e)}))}catch(e){r(\"throw\",e)}}function r(e,r){switch(e){case\"return\":t.resolve({value:r,done:!0});break;case\"throw\":t.reject(r);break;default:t.resolve({value:r,done:!1})}(t=t.next)?n(t.key,t.arg):i=null}this._invoke=function(e,r){return new dB((function(o,s){var a={key:e,arg:r,resolve:o,reject:s,next:null};i?i=i.next=a:(t=i=a,n(e,r))}))},\"function\"!=typeof e.return&&(this.return=void 0)}function pB(e){return function(){return new uB(e.apply(this,arguments))}}uB.prototype[\"function\"==typeof ZS&&hB||\"@@asyncIterator\"]=function(){return this},uB.prototype.next=function(e){return this._invoke(\"next\",e)},uB.prototype.throw=function(e){return this._invoke(\"throw\",e)},uB.prototype.return=function(e){return this._invoke(\"return\",e)};var _B=i(ie.Object.getOwnPropertySymbols),EB=wi,mB=qi.indexOf,fB=Bn,TB=I([].indexOf),SB=!!TB&&1/TB([1],1,-0)<0;EB({target:\"Array\",proto:!0,forced:SB||!fB(\"indexOf\")},{indexOf:function(e){var t=arguments.length>1?arguments[1]:void 0;return SB?TB(this,e,t)||0:mB(this,e,t)}});var gB=Xi(\"Array\").indexOf,RB=l,CB=gB,vB=Array.prototype,IB=function(e){var t=e.indexOf;return e===vB||RB(vB,e)&&t===vB.indexOf?CB:t},yB=i(IB);function AB(e,t){if(null==e)return{};var i,n,r=function(e,t){if(null==e)return{};var i,n,r={},o=IA(e);for(n=0;n=0||(r[i]=e[i]);return r}(e,t);if(_B){var o=_B(e);for(n=0;n=0||Object.prototype.propertyIsEnumerable.call(e,i)&&(r[i]=e[i])}return r}var bB={exports:{}};!function(e,t){e.exports=(()=>{var e={8:(e,t,i)=>{i.r(t),i.d(t,{Parser:()=>C,Printer:()=>b,parse:()=>D,print:()=>P});const n=\"\\n\",r=\"\".concat(\"\\r\").concat(n),o=\" \";let s;function a(e){return e>=\"0\"&&e<=\"9\"}function c(e){return e>=\"!\"&&e<=\"~\"}function d(e){return c(e)||e>=\"\"&&e<=\"ÿ\"}function l(e){return\"!\"===e||e>=\"#\"&&e<=\"'\"||e>=\"*\"&&e<=\"+\"||e>=\"-\"&&e<=\".\"||e>=\"0\"&&e<=\"9\"||e>=\"A\"&&e<=\"Z\"||e>=\"^\"&&e<=\"~\"}function h(e){return e>=\"1\"&&e<=\"9\"}function u(e){return e>=\"A\"&&e<=\"Z\"||e>=\"a\"&&e<=\"z\"}function p(e){return\"d\"===e||\"h\"===e||\"m\"===e||\"s\"===e}function _(e){return e>\"\u0001\"&&e<\"\\t\"||e>\"\\v\"&&e<\"\\f\"||e>\"\u000e\"&&e<\"ÿ\"}function E(e){return u(e)||a(e)||\"+\"===e||\"/\"===e}function m(e){return a(e)||u(e)||\"+\"===e||\"/\"===e||\"-\"===e||\"_\"===e}function f(e){return u(e)||a(e)||\"+\"===e||\"/\"===e}function T(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function S(e){for(var t=1;t=0&&n<=255)return i;throw new Error(\"Invalid decimal uchar\")}consumeIP6Address(e,t){let i=this.consumeHexpart(e,t);return\":\"===e[i]?(i+=1,i=this.consumeIP4Address(e,i),i):i}consumeHexpart(e,t){let i=t;if(\":\"===e[i]&&\":\"===e[i+1]){i+=2;try{i=this.consumeHexseq(e,i)}catch(e){}return i}if(i=this.consumeHexseq(e,i),\":\"===e[i]&&\":\"===e[i+1]){i+=2;try{i=this.consumeHexseq(e,i)}catch(e){}return i}return i}consumeHexseq(e,t){let i=t;for(;i=this.consumeHex4(e,i),\":\"===e[i]&&\":\"!==e[i+1];)i+=1;return i}consumeHex4(e,t){let i=0;for(;i<4;i++)if(!((n=e[t+i])>=\"0\"&&n<=\"9\"||n>=\"a\"&&n<=\"f\"||n>=\"A\"&&n<=\"F\")){if(0===i)throw new Error(\"Invalid hex 4\");break}var n;return t+i}consumeFQDN(e,t){let i=t;for(;a(e[i])||u(e[i])||\"-\"===e[i]||\".\"===e[i];)i+=1;if(i-t<4)throw new Error(\"Invalid FQDN\");return i}consumeExtnAddr(e,t){return this.consumeOneOrMore(e,t,d)}consumeMulticastAddress(e,t,i){switch(i){case\"IP4\":case\"ip4\":return this.consumeIP4MulticastAddress(e,t);case\"IP6\":case\"ip6\":return this.consumeIP6MulticastAddress(e,t);default:try{return this.consumeFQDN(e,t)}catch(i){return this.consumeExtnAddr(e,t)}}}consumeIP6MulticastAddress(e,t){const i=this.consumeHexpart(e,t);return\"/\"===e[i]?this.consumeInteger(e,i+1):i}consumeIP4MulticastAddress(e,t){let i=t+3;const n=e.slice(t,i),r=parseInt(n);if(r<224||r>239)throw new Error(\"Invalid IP4 multicast address, IPv4 multicast addresses may be in the range 224.0.0.0 to 239.255.255.255.\");for(let t=0;t<3;t++){if(\".\"!==e[i])throw new Error(\"Invalid IP4 multicast address.\");i+=1,i=this.consumeDecimalUChar(e,i)}return\"/\"===e[i]&&(i+=1),i=this.consumeTTL(e,i),\"/\"===e[i]&&(i=this.consumeInteger(e,i)),i}consumeInteger(e,t){if(!h(e[t]))throw new Error(\"Invalid integer.\");for(t+=1;a(e[t]);)t+=1;return t}consumeTTL(e,t){if(\"0\"===e[t])return t+1;if(!h(e[t]))throw new Error(\"Invalid TTL.\");t+=1;for(let i=0;i<2&&a(e[t]);i++)t+=1;return t}consumeToken(e,t){return this.consumeOneOrMore(e,t,l)}consumeTime(e,t){let i=t;if(\"0\"===e[i])return i+1;for(h(e[i])&&(i+=1);a(e[i]);)i++;if(i-t<10)throw new Error(\"Invalid time\");return i}consumeAddress(e,t){return this.consumeTill(e,t,o)}consumeTypedTime(e,t){let i=t;return i=this.consumeOneOrMore(e,i,a),p(e[i])?i+1:i}consumeRepeatInterval(e,t){if(!h(e[t]))throw new Error(\"Invalid repeat interval\");for(t+=1;a(e[t]);)t+=1;return p(e[t])&&(t+=1),t}consumePort(e,t){return this.consumeOneOrMore(e,t,a)}consume(e,t,i){for(let n=0;n=e.length)throw new Error(\"consume exceeding value length\");if(e[t+n]!==i[n])throw new Error(\"consume \".concat(i,\" failed at \").concat(n))}return t+i.length}consumeTill(e,t,i){let n=t;for(;n!!jp(e).call(e))).map(this.parseLine),this.currentLine=0;const i=this.parseVersion(),n=this.parseOrigin(),r=this.parseSessionName(),o=this.parseInformation(),s=this.parseUri(),a=this.parseEmail(),c=this.parsePhone(),d=this.parseConnection(),l=this.parseBandWidth(),h=this.parseTimeFields(),u=this.parseKey(),p=this.parseSessionAttribute(),_=this.parseMediaDescription();if(this.currentLine!==this.records.length)throw new Error(\"parsing failed, non exhaustive sdp lines.\");return{version:i,origin:n,sessionName:r,information:o,uri:s,emails:a,phones:c,connection:d,bandwidths:l,timeFields:h,key:u,attributes:p,mediaDescriptions:_}}getCurrentRecord(){const e=this.records[this.currentLine];if(!e)throw new Error(\"Record doesn't exit.\");return e}probeEOL(e){for(let t=0;t=.\");const i=e[0];if(\"=\"!==e[1])throw new Error('Invalid sdp line, should be a single character followed by an \"=\" sign.');return{type:i,value:e.slice(2),line:t,cur:0}}parseSessionAttribute(){const e=new I;for(;this.currentLinel(e)&&\":\"!==e)),_cur:0};\":\"===t.value[t.cur]&&(t.cur+=1,i.attValue=this.extractOneOrMore(t,_)),e.parse(i),this.currentLine++}return e.digest()}parseMediaAttributes(e){const t=new y(e);for(;this.currentLinel(e)&&\":\"!==e)),_cur:0};\":\"===e.value[e.cur]&&(e.cur+=1,i.attValue=this.extractOneOrMore(e,_)),t.parse(i),this.currentLine++}return t.digest()}parseKey(){const e=this.getCurrentRecord();if(e.type===s.KEY){if(\"prompt\"===e.value||\"clear:\"===e.value||\"base64:\"===e.value||\"uri:\"===e.value)return e.value;throw this.currentLine++,new Error(\"Invalid key.\")}}parseZone(){const e=this.getCurrentRecord();if(e.type===s.ZONE_ADJUSTMENTS){const t=[];for(;;)try{const i=this.extract(e,this.consumeTime);this.consumeSpaceForRecord(e);let n=!1;\"-\"===e.value[e.cur]&&(n=!0,e.cur+=1);const r=this.extract(e,this.consumeTypedTime);t.push({time:i,typedTime:r,back:n})}catch(e){break}if(0===t.length)throw new Error(\"Invalid zone adjustments\");return this.currentLine++,t}return[]}parseRepeat(){const e=[];for(;;){const t=this.getCurrentRecord();if(t.type!==s.REPEAT)break;{const i=this.extract(t,this.consumeRepeatInterval),n=this.parseTypedTime(t);e.push({repeatInterval:i,typedTimes:n}),this.currentLine++}}return e}parseTypedTime(e){const t=[];for(;;)try{this.consumeSpaceForRecord(e),t.push(this.extract(e,this.consumeTypedTime))}catch(e){break}if(0===t.length)throw new Error(\"Invalid typed time.\");return t}parseTime(){const e=this.getCurrentRecord(),t=this.extract(e,this.consumeTime);this.consumeSpaceForRecord(e);const i=this.extract(e,this.consumeTime);return this.currentLine++,{startTime:t,stopTime:i}}parseBandWidth(){const e=[];for(;this.currentLine2?i-2:0),r=2;rs)throw new Error(\"error in length, should be less or equal than \".concat(s,\" characters.\"));return e._cur=n,r}consumeAttributeSpace(e){if(e.attValue[e._cur]!==o)throw new Error(\"Invalid space at \".concat(e._cur,\".\"));e._cur+=1}extract(e,t){if(!e.attValue)throw new Error(\"Nothing to extract from attValue.\");for(var i=arguments.length,n=new Array(i>2?i-2:0),r=2;r=e.attValue.length}peekChar(e){if(!e.attValue)throw new Error;return e.attValue[e._cur]}peek(e,t){if(!e.attValue)throw new Error;for(let i=0;ie!==o&&_(e)));i.push({name:t,value:n})}this.attributes.identities.push({assertionValue:t,extensions:i})}parseMsidSemantic(e){this.peekChar(e)===o&&this.consumeAttributeSpace(e);const t={semantic:this.extract(e,this.consumeToken),identifierList:[]};for(;;){try{this.consumeAttributeSpace(e)}catch(e){break}if(\"*\"===this.peekChar(e)){this.extract(e,this.consume,\"*\"),t.applyForAll=!0;break}{const i=this.extract(e,this.consumeTill,o);t.identifierList.push(i)}}this.attributes.msidSemantic=t}}class y extends v{constructor(e){super(),g(this,\"attributes\",void 0),-1!==e.protos.indexOf(\"RTP\")||e.protos.indexOf(\"rtp\"),this.attributes={unrecognized:[],candidates:[],extmaps:[],fingerprints:[],imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:[],ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:[]}}parse(e){if(this.digested)throw new Error(\"already digested\");try{switch(e.attField){case\"extmap\":this.parseExtmap(e);break;case\"setup\":this.parseSetup(e);break;case\"ice-ufrag\":this.parseIceUfrag(e);break;case\"ice-pwd\":this.parseIcePwd(e);break;case\"ice-options\":this.parseIceOptions(e);break;case\"candidate\":this.parseCandidate(e);break;case\"remote-candidate\":this.parseRemoteCandidate(e);break;case\"end-of-candidates\":this.parseEndOfCandidates();break;case\"fingerprint\":this.parseFingerprint(e);break;case\"rtpmap\":this.parseRtpmap(e);break;case\"ptime\":this.parsePtime(e);break;case\"maxptime\":this.parseMaxPtime(e);break;case\"sendrecv\":case\"recvonly\":case\"sendonly\":case\"inactive\":this.parseDirection(e);break;case\"ssrc\":this.parseSSRC(e);break;case\"fmtp\":this.parseFmtp(e);break;case\"rtcp-fb\":this.parseRtcpFb(e);break;case\"rtcp-mux\":this.parseRTCPMux();break;case\"rtcp-mux-only\":this.parseRTCPMuxOnly();break;case\"rtcp-rsize\":this.parseRTCPRsize();break;case\"rtcp\":this.parseRTCP(e);break;case\"mid\":this.parseMid(e);break;case\"msid\":this.parseMsid(e);break;case\"imageattr\":this.parseImageAttr(e);break;case\"rid\":this.parseRid(e);break;case\"simulcast\":this.parseSimulcast(e);break;case\"sctp-port\":this.parseSctpPort(e);break;case\"max-message-size\":this.parseMaxMessageSize(e);break;case\"ssrc-group\":this.parseSSRCGroup(e);break;default:e.ignored=!0,this.attributes.unrecognized.push(e)}}catch(t){throw console.error(\"parsing media attribute \".concat(e.attField,' error, \"a=').concat(e.attField,\":\").concat(e.attValue,'\"')),t}if(!e.ignored&&e.attValue&&!this.atEnd(e))throw new Error(\"attribute parsing error\")}parseCandidate(e){const t=this.extractOneOrMore(e,E,[1,32]);this.consumeAttributeSpace(e);const i=this.extractOneOrMore(e,a,[1,5]);this.consumeAttributeSpace(e);const n=this.extract(e,this.consumeToken);this.consumeAttributeSpace(e);const r=this.extractOneOrMore(e,a,[1,10]);this.consumeAttributeSpace(e);const s=this.extract(e,this.consumeAddress);this.consumeAttributeSpace(e);const d=this.extract(e,this.consumePort);this.consumeAttributeSpace(e),this.extract(e,this.consume,\"typ\"),this.consumeAttributeSpace(e);const l={foundation:t,componentId:i,transport:n,priority:r,connectionAddress:s,port:d,type:this.extract(e,this.consumeToken),extension:{}};for(this.peek(e,\" raddr\")&&(this.extract(e,this.consume,\" raddr\"),this.consumeAttributeSpace(e),l.relAddr=this.extract(e,this.consumeAddress)),this.peek(e,\" rport\")&&(this.extract(e,this.consume,\" rport\"),this.consumeAttributeSpace(e),l.relPort=this.extract(e,this.consumePort));this.peekChar(e)===o;){this.consumeAttributeSpace(e);const t=this.extract(e,this.consumeToken);this.consumeAttributeSpace(e),l.extension[t]=this.extractOneOrMore(e,c)}this.attributes.candidates.push(l)}parseRemoteCandidate(e){const t=[];for(;;){const i=this.extractOneOrMore(e,a,[1,5]);this.consumeAttributeSpace(e);const n=this.extract(e,this.consumeAddress);this.consumeAttributeSpace(e);const r=this.extract(e,this.consumePort);t.push({componentId:i,connectionAddress:n,port:r});try{this.consumeAttributeSpace(e)}catch(e){break}}this.attributes.remoteCandidatesList.push(t)}parseEndOfCandidates(){if(this.attributes.endOfCandidates)throw new Error(\"must be only one line of end-of-candidates\");this.attributes.endOfCandidates=!0}parseRtpmap(e){const t=this.extract(e,this.consumeToken);this.consumeAttributeSpace(e);const i=this.extract(e,this.consumeTill,\"/\");this.extract(e,this.consume,\"/\");const n={encodingName:i,clockRate:this.extractOneOrMore(e,a)};this.atEnd(e)||\"/\"!==this.peekChar(e)||(this.extract(e,this.consume,\"/\"),n.encodingParameters=parseInt(this.extract(e,this.consumeTill),10));const r=this.attributes.payloads.find((e=>e.payloadType===parseInt(t,10)));r?r.rtpMap=n:this.attributes.payloads.push({payloadType:parseInt(t,10),rtpMap:n,rtcpFeedbacks:[]})}parsePtime(e){if(this.attributes.ptime)throw new Error(\"must be only one line of ptime\");this.attributes.ptime=this.extract(e,this.consumeTill)}parseMaxPtime(e){if(this.attributes.maxPtime)throw new Error(\"must be only one line of ptime\");this.attributes.maxPtime=this.extract(e,this.consumeTill)}parseDirection(e){if(this.attributes.direction)throw new Error(\"must be only one line of direction info\");this.attributes.direction=e.attField}parseSSRC(e){const t=this.extractOneOrMore(e,a);this.consumeAttributeSpace(e);const i=this.extract(e,this.consumeTill,\":\");let n;\":\"===this.peekChar(e)&&(this.extract(e,this.consume,\":\"),n=this.extract(e,this.consumeTill));const r=this.attributes.ssrcs.find((e=>e.ssrcId===parseInt(t,10)));r?r.attributes[i]=n:this.attributes.ssrcs.push({ssrcId:parseInt(t,10),attributes:{[i]:n}})}parseFmtp(e){const t=this.extract(e,this.consumeTill,o);this.consumeAttributeSpace(e);const i=this.extract(e,this.consumeTill),n={};i.split(\";\").forEach((e=>{let[t,i]=e.split(\"=\");t=jp(t).call(t);const r=\"string\"==typeof i?jp(i).call(i):null;\"string\"==typeof t&&t.length>0&&(n[t]=r)}));const r=this.attributes.payloads.find((e=>e.payloadType===parseInt(t,10)));r?r.fmtp={parameters:n}:this.attributes.payloads.push({payloadType:parseInt(t,10),rtcpFeedbacks:[],fmtp:{parameters:n}})}parseFmtParameters(e){const t={},i=this.extract(e,this.consumeTill,\"=\");e._cur++;const n=this.extract(e,this.consumeTill,\";\");for(t[i]=n;\";\"===e.attValue[e._cur];){const i=this.extract(e,this.consumeTill,\"=\");e._cur++;const n=this.extract(e,this.consumeTill,\";\");t[i]=n}return t}parseRtcpFb(e){let t=\"\";t=\"*\"===this.peekChar(e)?this.extract(e,this.consume,\"*\"):this.extract(e,this.consumeTill,o),this.consumeAttributeSpace(e);const i=this.extract(e,this.consumeTill,o);let n;if(\"trr-int\"===i)n={type:i,interval:this.extract(e,this.consumeTill)};else{const t={type:i};this.peekChar(e)===o&&(this.consumeAttributeSpace(e),t.parameter=this.extract(e,this.consumeToken),this.peekChar(e)===o&&(t.additional=this.extract(e,this.consumeTill))),n=t}if(\"*\"===t)this.attributes.rtcpFeedbackWildcards.push(n);else{const e=this.attributes.payloads.find((e=>e.payloadType===parseInt(t,10)));e?e.rtcpFeedbacks.push(n):this.attributes.payloads.push({payloadType:parseInt(t,10),rtcpFeedbacks:[n]})}}parseRTCPMux(){if(this.attributes.rtcpMux)throw new Error(\"must be single line of rtcp-mux\");this.attributes.rtcpMux=!0}parseRTCPMuxOnly(){if(this.attributes.rtcpMuxOnly)throw new Error(\"must be single line of rtcp-only\");this.attributes.rtcpMuxOnly=!0}parseRTCPRsize(){if(this.attributes.rtcpRsize)throw new Error(\"must be single line of rtcp-rsize\");this.attributes.rtcpRsize=!0}parseRTCP(e){if(this.attributes.rtcp)throw new Error(\"must be single line of rtcp\");const t={port:this.extract(e,this.consumePort)};this.peekChar(e)===o&&(this.consumeAttributeSpace(e),t.netType=this.extractOneOrMore(e,l),this.consumeAttributeSpace(e),t.addressType=this.extractOneOrMore(e,l),this.consumeAttributeSpace(e),t.address=this.extract(e,this.consumeAddress)),this.attributes.rtcp=t}parseMsid(e){const t={id:this.extractOneOrMore(e,l,[1,64])};this.peekChar(e)===o&&(this.consumeAttributeSpace(e),t.appdata=this.extractOneOrMore(e,l,[1,64])),this.attributes.msids.push(t)}parseImageAttr(e){this.attributes.imageattr.push(e.attValue)}parseRid(e){const t=this.extractOneOrMore(e,(e=>u(e)||a(e)||\"_\"===e||\"-\"===e));this.consumeAttributeSpace(e);const i={id:t,direction:this.extract(e,this.consumeToken),params:[]};if(this.peekChar(e)===o){if(this.consumeAttributeSpace(e),this.peek(e,\"pt=\")){this.extract(e,this.consume,\"pt=\");const t=[];for(;;){const i=this.extract(e,this.consumeToken);t.push(i);try{this.extract(e,this.consume,\",\")}catch(e){break}}i.payloads=t,this.peekChar(e)===o&&this.extract(e,this.consume,o)}for(;;){const t=this.extract(e,this.consumeToken);switch(t){case\"depend\":{const n={type:t,rids:this.extract(e,this.consume,\"=\").split(\",\")};i.params.push(n);break}default:{const n={type:t};\"=\"===this.peekChar(e)&&(this.extract(e,this.consume,\"=\"),n.val=this.extract(e,this.consumeTill,\";\")),i.params.push(n)}}try{this.extract(e,this.consume,\";\")}catch(e){break}}}this.attributes.rids.push(i)}parseSimulcast(e){if(this.attributes.simulcast)throw new Error(\"must be single line of simulcast\");this.attributes.simulcast=e.attValue,this.extract(e,this.consumeTill)}parseSctpPort(e){this.attributes.sctpPort=this.extractOneOrMore(e,a,[1,5])}parseMaxMessageSize(e){this.attributes.maxMessageSize=this.extractOneOrMore(e,a,[1,void 0])}digest(){return this.digested=!0,this.attributes}parseMid(e){this.attributes.mid=this.extract(e,this.consumeToken)}parseSSRCGroup(e){const t=this.extract(e,this.consumeToken),i=[];for(;;)try{this.consumeAttributeSpace(e);const t=this.extract(e,this.consumeInteger);i.push(parseInt(t,10))}catch(e){break}this.attributes.ssrcGroups.push({semantic:t,ssrcIds:i})}}function A(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}class b{constructor(){A(this,\"eol\",r)}print(e,t){let i=\"\";return t&&(this.eol=t),i+=this.printVersion(e.version),i+=this.printOrigin(e.origin),i+=this.printSessionName(e.sessionName),i+=this.printInformation(e.information),i+=this.printUri(e.uri),i+=this.printEmail(e.emails),i+=this.printPhone(e.phones),i+=this.printConnection(e.connection),i+=this.printBandwidth(e.bandwidths),i+=this.printTimeFields(e.timeFields),i+=this.printKey(e.key),i+=this.printSessionAttributes(e.attributes),i+=this.printMediaDescription(e.mediaDescriptions),i}printVersion(e){return\"v=\".concat(e).concat(this.eol)}printOrigin(e){return\"o=\".concat(e.username,\" \").concat(e.sessId,\" \").concat(e.sessVersion,\" \").concat(e.nettype,\" \").concat(e.addrtype,\" \").concat(e.unicastAddress).concat(this.eol)}printSessionName(e){return e?\"s=\".concat(e).concat(this.eol):\"\"}printInformation(e){return e?\"i=\".concat(e).concat(this.eol):\"\"}printUri(e){return e?\"u=\".concat(e).concat(this.eol):\"\"}printEmail(e){let t=\"\";for(const i of e)t+=\"e=\".concat(i).concat(this.eol);return t}printPhone(e){let t=\"\";for(const i of e)t+=\"e=\".concat(i).concat(this.eol);return t}printConnection(e){return e?\"c=\".concat(e.nettype,\" \").concat(e.addrtype,\" \").concat(e.address).concat(this.eol):\"\"}printBandwidth(e){let t=\"\";for(const i of e)t+=\"b=\".concat(i.bwtype,\":\").concat(i.bandwidth).concat(this.eol);return t}printTimeFields(e){let t=\"\";for(const i of e){t+=\"t=\".concat(i.time.startTime,\" \").concat(i.time.startTime).concat(this.eol);for(const e of i.repeats)t+=\"r=\".concat(e.repeatInterval,\" \").concat(e.typedTimes.join(\" \")).concat(this.eol);i.zoneAdjustments&&(t+=\"z=\",t+=\"z=\".concat(i.zoneAdjustments.map((e=>\"\".concat(e.time,\" \").concat(e.back?\"-\":\"\",\" \").concat(e.typedTime))).join(\" \")).concat(this.eol),t+=this.eol)}return t}printKey(e){return e?\"k=\".concat(e).concat(this.eol):\"\"}printAttributes(e){let t=\"\";for(const i of e)t+=\"a=\".concat(i.attField).concat(i.attValue?\":\".concat(i.attValue):\"\").concat(this.eol);return t}printMediaDescription(e){let t=\"\";for(const i of e)t+=this.printMedia(i.media),t+=this.printInformation(i.information),t+=this.printConnections(i.connections),t+=this.printBandwidth(i.bandwidths),t+=this.printKey(i.key),t+=this.printMediaAttributes(i);return t}printConnections(e){let t=\"\";for(const i of e)t+=this.printConnection(i);return t}printMedia(e){return\"m=\".concat(e.mediaType,\" \").concat(e.port,\" \").concat(e.protos.join(\"/\"),\" \").concat(e.fmts.join(\" \")).concat(this.eol)}printSessionAttributes(e){return new O(this.eol).print(e)}printMediaAttributes(e){return new N(this.eol).print(e)}}class w{constructor(e){A(this,\"eol\",void 0),this.eol=e}printIceUfrag(e){return void 0===e?\"\":\"a=ice-ufrag:\".concat(e).concat(this.eol)}printIcePwd(e){return void 0===e?\"\":\"a=ice-pwd:\".concat(e).concat(this.eol)}printIceOptions(e){return void 0===e?\"\":\"a=ice-options:\".concat(e.join(o)).concat(this.eol)}printFingerprints(e){return e.length>0?e.map((e=>\"a=fingerprint:\".concat(e.hashFunction).concat(o).concat(e.fingerprint))).join(this.eol)+this.eol:\"\"}printExtmap(e){return e.map((e=>\"a=extmap:\".concat(e.entry).concat(e.direction?\"/\".concat(e.direction):\"\").concat(o).concat(e.extensionName).concat(e.extensionAttributes?\"\".concat(o).concat(e.extensionAttributes):\"\").concat(this.eol))).join(\"\")}printSetup(e){return void 0===e?\"\":\"a=setup:\".concat(e).concat(this.eol)}printUnrecognized(e){return e.map((e=>\"a=\".concat(e.attField).concat(e.attValue?\":\".concat(e.attValue):\"\").concat(this.eol))).join(\"\")}}class O extends w{print(e){let t=\"\";return t+=this.printGroups(e.groups),t+=this.printMsidSemantic(e.msidSemantic),t+=this.printIceLite(e.iceLite),t+=this.printIceUfrag(e.iceUfrag),t+=this.printIcePwd(e.icePwd),t+=this.printIceOptions(e.iceOptions),t+=this.printFingerprints(e.fingerprints),t+=this.printSetup(e.setup),t+=this.printTlsId(e.tlsId),t+=this.printIdentity(e.identities),t+=this.printExtmap(e.extmaps),t+=this.printUnrecognized(e.unrecognized),t}printGroups(e){let t=\"\";return e.length>0&&(t+=e.map((e=>\"a=group:\".concat(e.semantic).concat(e.identificationTag.map((e=>\"\".concat(o).concat(e))).join(\"\")).concat(this.eol))).join(\"\")),t}printIceLite(e){return void 0===e?\"\":\"a=ice-lite\"+this.eol}printTlsId(e){return e?\"a=tls-id:\".concat(e).concat(this.eol):\"\"}printIdentity(e){return 0===e.length?\"\":e.map((e=>\"a=identity:\".concat(e.assertionValue).concat(e.extensions.map((e=>\"\".concat(o).concat(e.name).concat(e.value?\"=\".concat(e.value):\"\")))))).join(this.eol)+this.eol}printMsidSemantic(e){if(!e)return\"\";let t=\"a=msid-semantic:\".concat(e.semantic);return e.applyForAll?t+=\"\".concat(o,\"*\"):e.identifierList.length>0&&(t+=e.identifierList.map((e=>\"\".concat(o).concat(e)))),t+this.eol}}class N extends w{print(e){const t=e.attributes;let i=\"\";return i+=this.printRTCP(t.rtcp),i+=this.printIceUfrag(t.iceUfrag),i+=this.printIcePwd(t.icePwd),i+=this.printIceOptions(t.iceOptions),i+=this.printCandidates(t.candidates),i+=this.printRemoteCandidatesList(t.remoteCandidatesList),i+=this.printEndOfCandidates(t.endOfCandidates),i+=this.printFingerprints(t.fingerprints),i+=this.printSetup(t.setup),i+=this.printMid(t.mid),i+=this.printExtmap(t.extmaps),i+=this.printRTPRelated(t),i+=this.printPtime(t.ptime),i+=this.printMaxPtime(t.maxPtime),i+=this.printDirection(t.direction),i+=this.printSSRCGroups(t.ssrcGroups),i+=this.printSSRC(t.ssrcs),i+=this.printRTCPMux(t.rtcpMux),i+=this.printRTCPMuxOnly(t.rtcpMuxOnly),i+=this.printRTCPRsize(t.rtcpRsize),i+=this.printMSId(t.msids),i+=this.printImageattr(t.imageattr),i+=this.printRid(t.rids),i+=this.printSimulcast(t.simulcast),i+=this.printSCTPPort(t.sctpPort),i+=this.printMaxMessageSize(t.maxMessageSize),i+=this.printUnrecognized(t.unrecognized),i}printCandidates(e){return e.map((e=>\"a=candidate:\".concat(e.foundation).concat(o).concat(e.componentId).concat(o).concat(e.transport).concat(o).concat(e.priority).concat(o).concat(e.connectionAddress).concat(o).concat(e.port).concat(o,\"typ\").concat(o).concat(e.type).concat(e.relAddr?\"\".concat(o,\"raddr\").concat(o).concat(e.relAddr):\"\").concat(e.relPort?\"\".concat(o,\"rport\").concat(o).concat(e.relPort):\"\").concat(Object.keys(e.extension).map((t=>\"\".concat(o).concat(t).concat(o).concat(e.extension[t]))).join(\"\")).concat(this.eol))).join(\"\")}printRemoteCandidatesList(e){return e.map((e=>\"a=remote-candidates:\".concat(e.join(o)).concat(this.eol))).join(\"\")}printEndOfCandidates(e){return void 0===e?\"\":\"a=end-of-candidates\"+this.eol}printRTPRelated(e){if(!e.payloads)return\"\";const t=e.payloads;let i=\"\";i+=e.rtcpFeedbackWildcards.map((e=>this.printRTCPFeedback(\"*\",e))).join(\"\");for(const e of t)i+=this.printRtpMap(e.payloadType,e.rtpMap),i+=this.printFmtp(e.payloadType,e.fmtp),i+=e.rtcpFeedbacks.map((t=>this.printRTCPFeedback(e.payloadType,t))).join(\"\");return i}printFmtp(e,t){if(!t)return\"\";const i=Object.keys(t.parameters);return 1===i.length&&null===t.parameters[i[0]]?\"a=fmtp:\".concat(e).concat(o).concat(i[0]).concat(this.eol):\"a=fmtp:\".concat(e).concat(o).concat(Object.keys(t.parameters).map((e=>\"\".concat(e,\"=\").concat(t.parameters[e]))).join(\";\")).concat(this.eol)}printRtpMap(e,t){return t?\"a=rtpmap:\".concat(e).concat(o).concat(t.encodingName,\"/\").concat(t.clockRate).concat(t.encodingParameters?\"/\".concat(t.encodingParameters):\"\").concat(this.eol):\"\"}printRTCPFeedback(e,t){let i=\"a=rtcp-fb:\".concat(e).concat(o),n=t;return\"trr-int\"===n.type?i+=\"ttr-int\".concat(o).concat(n.interval):(i+=\"\".concat(n.type),n.parameter&&(i+=\"\".concat(o).concat(n.parameter),n.additional&&(i+=\"\".concat(o).concat(n.additional)))),i+this.eol}printPtime(e){return void 0===e?\"\":\"a=ptime:\".concat(e).concat(this.eol)}printMaxPtime(e){return void 0===e?\"\":\"a=maxptime:\".concat(e).concat(this.eol)}printDirection(e){return void 0===e?\"\":\"a=\".concat(e).concat(this.eol)}printSSRC(e){return e.map((e=>Object.keys(e.attributes).map((t=>\"a=ssrc:\".concat(e.ssrcId.toString(10)).concat(o).concat(t).concat(e.attributes[t]?\":\".concat(e.attributes[t]):\"\").concat(this.eol))).join(\"\"))).join(\"\")}printRTCPMux(e){return void 0===e?\"\":\"a=rtcp-mux\".concat(this.eol)}printRTCPMuxOnly(e){return void 0===e?\"\":\"a=rtcp-mux-only\".concat(this.eol)}printRTCPRsize(e){return void 0===e?\"\":\"a=rtcp-rsize\".concat(this.eol)}printRTCP(e){if(void 0===e)return\"\";let t=\"a=rtcp:\".concat(e.port);return e.netType&&(t+=\"\".concat(o).concat(e.netType)),e.addressType&&(t+=\"\".concat(o).concat(e.addressType)),e.address&&(t+=\"\".concat(o).concat(e.address)),t+this.eol}printMSId(e){return e.map((e=>\"a=msid:\".concat(e.id).concat(e.appdata?\"\".concat(o).concat(e.appdata):\"\").concat(this.eol))).join(\"\")}printImageattr(e){return e.map((e=>\"a=imageattr:\".concat(e).concat(this.eol))).join(\"\")}printRid(e){return e.map((e=>{let t=\"a=rid:\".concat(e.id).concat(o).concat(e.direction);return e.payloads&&(t+=\"\".concat(o,\"pt=\").concat(e.payloads.join(\",\"))),e.params.length>0&&(t+=\"\".concat(o).concat(e.params.map((e=>\"depend\"===e.type?\"depend=\".concat(e.rids.join(\",\")):\"\".concat(e.type,\"=\").concat(e.val))).join(\";\"))),t+this.eol})).join(\"\")}printSimulcast(e){return void 0===e?\"\":\"a=simulcast:\".concat(e).concat(this.eol)}printSCTPPort(e){return void 0===e?\"\":\"a=sctp-port:\".concat(e).concat(this.eol)}printMaxMessageSize(e){return void 0===e?\"\":\"a=max-message-size:\".concat(e).concat(this.eol)}printMid(e){return void 0===e?\"\":\"a=mid:\".concat(e).concat(this.eol)}printSSRCGroups(e){return e.map((e=>\"a=ssrc-group:\".concat(e.semantic).concat(e.ssrcIds.map((e=>\"\".concat(o).concat(e.toString(10)))).join(\"\")).concat(this.eol))).join(\"\")}}function D(e){return(new C).parse(e)}function P(e,t){return(new b).print(e,t)}}},t={};function i(n){if(t[n])return t[n].exports;var r=t[n]={exports:{}};return e[n](r,r.exports,i),r.exports}return i.d=(e,t)=>{for(var n in t)i.o(t,n)&&!i.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i.r=e=>{\"undefined\"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:\"Module\"}),Object.defineProperty(e,\"__esModule\",{value:!0})},i(8)})()}(bB);var wB=bB.exports;function OB(e){if(Array.isArray(e))return e.map((e=>e));if(!NB(e))return e;const t={};for(const i in e){const n=e[i];NB(n)||Array.isArray(n)?t[i]=OB(n):t[i]=n}return t}function NB(e){return!(\"object\"!=typeof e||Array.isArray(e)||!e)}class DB{constructor(e){ng(this,\"input\",[]),ng(this,\"size\",void 0),this.size=e}add(e){this.input.push(e),this.input.length>this.size&&this.input.splice(0,1)}diffMean(){return 0===this.input.length?0:(this.input[this.input.length-1]-this.input[0])/this.input.length}}const PB={address:\"unknown\",candidateType:\"unknown\",id:\"unknown\",port:0,priority:0,protocol:\"unknown\",type:\"unknown\"},LB={timestamp:0,bitrate:{actualEncoded:0,transmit:0},sendPacketLossRate:0,recvPacketLossRate:0,videoRecv:[],videoSend:[],audioRecv:[],audioSend:[],selectedCandidatePair:{id:\"unknown\",localCandidate:PB,remoteCandidate:PB}},kB={firsCount:0,nacksCount:0,plisCount:0,framesDecodeCount:0,framesDecodeInterval:0,framesDecodeFreezeTime:0,decodeFrameRate:0,bytes:0,packetsLost:0,packetLostRate:0,packets:0,ssrc:0,qpSumPerFrame:0,framesDroppedCount:0,outputFrameRate:0},MB={firsCount:0,nacksCount:0,plisCount:0,frameCount:0,bytes:0,packets:0,packetsLost:0,packetLostRate:0,ssrc:0,rttMs:0,jitterMs:0,qpSumPerFrame:0},UB={bytes:0,packets:0,packetsLost:0,packetLostRate:0,ssrc:0,rttMs:0,jitterMs:0},xB={jitterBufferMs:0,jitterMs:0,bytes:0,packetsLost:0,packetLostRate:0,packets:0,ssrc:0,receivedFrames:0,droppedFrames:0,concealedSamples:0};function VB(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function FB(e){for(var t=1;t{this.updateStats()}),this.options.updateInterval)}getStats(){return this.stats}getSelectedCandidatePair(){return new Gu((e=>{e({local:FB({},PB),remote:FB({},PB)})}))}setVideoIsReady(e){this.videoIsReady=e}setVideoIsReady2(e,t){this.videoIsReady2[e]=t}getVideoIsReady(e){return this.videoIsReady2[e]||!1}setIsFirstAudioDecoded(e){}destroy(){window.clearInterval(this.intervalTimer),this.pc=void 0}calcLossRate(e){this.lossRateWindowStats.push(e),this.lossRateWindowStats.length>this.options.lossRateInterval&&this.lossRateWindowStats.splice(0,1);const t=this.lossRateWindowStats.length,i=[\"videoSend\",\"audioSend\",\"videoRecv\",\"audioRecv\"];let n=0,r=0,o=0,s=0;for(const a of i)e[a].forEach(((e,i)=>{if(!this.lossRateWindowStats[t-1][a][i]||!this.lossRateWindowStats[0][a][i])return;const c=this.lossRateWindowStats[t-1][a][i].packets-this.lossRateWindowStats[0][a][i].packets,d=this.lossRateWindowStats[t-1][a][i].packetsLost-this.lossRateWindowStats[0][a][i].packetsLost;\"videoSend\"===a||\"audioSend\"===a?(n+=c,o+=d):(r+=c,s+=d),Number.isNaN(c)||Number.isNaN(c)?e.packetLostRate=0:e.packetLostRate=c<=0||d<=0?0:d/(c+d)}));e.sendPacketLossRate=n<=0||o<=0?0:o/(n+o),e.recvPacketLossRate=r<=0||s<=0?0:s/(r+s)}}function jB(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function GB(e){for(var t=1;t\"ssrc\"===e.type));this.processSSRCStats(i);const n=t.find((e=>\"VideoBwe\"===e.type));n&&this.processBandwidthStats(n),this._stats.timestamp=Date.now(),this.calcLossRate(this._stats),this.stats=this._stats}processBandwidthStats(e){this._stats.bitrate={actualEncoded:Number(e.googActualEncBitrate),targetEncoded:Number(e.googTargetEncBitrate),retransmit:Number(e.googRetransmitBitrate),transmit:Number(e.googTransmitBitrate)},this._stats.sendBandwidth=Number(e.googAvailableSendBandwidth)}processSSRCStats(e){e.forEach((e=>{var t;const i=Dn(t=e.id).call(t,\"send\");switch(\"\".concat(e.mediaType,\"_\").concat(i?\"send\":\"recv\")){case\"video_send\":{const t=OB(MB);t.codec=e.googCodecName,t.adaptionChangeReason=\"none\",e.googCpuLimitedResolution&&(t.adaptionChangeReason=\"cpu\"),e.googBandwidthLimitedResolution&&(t.adaptionChangeReason=\"bandwidth\"),t.avgEncodeMs=Number(e.googAvgEncodeMs),t.inputFrame={width:Number(e.googFrameWidthInput)||Number(e.googFrameWidthSent),height:Number(e.googFrameHeightInput)||Number(e.googFrameHeightSent),frameRate:Number(e.googFrameRateInput)},t.sentFrame={width:Number(e.googFrameWidthSent),height:Number(e.googFrameHeightSent),frameRate:Number(e.googFrameRateInput)},t.firsCount=Number(e.googFirReceived),t.nacksCount=Number(e.googNacksReceived),t.plisCount=Number(e.googPlisReceived),t.frameCount=Number(e.framesEncoded),t.bytes=Number(e.bytesSent),t.packets=Number(e.packetsSent),t.packetsLost=Number(e.packetsLost),t.ssrc=Number(e.ssrc),t.rttMs=Number(e.googRtt||0),this._stats.videoSend.push(t),this._stats.rtt=t.rttMs;break}case\"video_recv\":{const t=OB(kB),i=this.lastDecodeVideoReceiverStats.get(Number(e.ssrc));if(t.codec=e.googCodecName,t.targetDelayMs=Number(e.googTargetDelayMs),t.renderDelayMs=Number(e.googRenderDelayMs),t.currentDelayMs=Number(e.googCurrentDelayMs),t.minPlayoutDelayMs=Number(e.googMinPlayoutDelayMs),t.decodeMs=Number(e.googDecodeMs),t.maxDecodeMs=Number(e.googMaxDecodeMs),t.receivedFrame={width:Number(e.googFrameWidthReceived),height:Number(e.googFrameHeightReceived),frameRate:Number(e.googFrameRateReceived)},t.decodedFrame={width:Number(e.googFrameWidthReceived),height:Number(e.googFrameHeightReceived),frameRate:Number(e.googFrameRateDecoded)},t.decodeFrameRate=Number(e.googFrameRateDecoded),t.outputFrame={width:Number(e.googFrameWidthReceived),height:Number(e.googFrameHeightReceived),frameRate:Number(e.googFrameRateOutput)},t.jitterBufferMs=Number(e.googJitterBufferMs),t.firsCount=Number(e.googFirsSent),t.nacksCount=Number(e.googNacksSent),t.plisCount=Number(e.googPlisSent),t.framesDecodeCount=Number(e.framesDecoded),t.bytes=Number(e.bytesReceived),t.packets=Number(e.packetsReceived),t.packetsLost=Number(e.packetsLost),t.ssrc=Number(e.ssrc),t.packets>0&&!this.isFirstVideoReceived[t.ssrc]&&(this.onFirstVideoReceived&&this.onFirstVideoReceived(t.ssrc),this.isFirstVideoReceived[t.ssrc]=!0),t.framesDecodeCount>0&&!this.isFirstVideoDecoded[t.ssrc]&&(this.onFirstVideoDecoded&&this.onFirstVideoDecoded(t.ssrc,t.decodedFrame.width,t.decodedFrame.height),this.isFirstVideoDecoded[t.ssrc]=!0),i){const n=i.stats,r=Date.now()-i.lts;t.framesDecodeFreezeTime=n.framesDecodeFreezeTime,t.framesDecodeInterval=n.framesDecodeInterval,t.framesDecodeCount>n.framesDecodeCount&&this.isFirstVideoDecoded[t.ssrc]?(i.lts=Date.now(),t.framesDecodeInterval=r,t.framesDecodeInterval>=this.options.freezeRateLimit&&(this.getVideoIsReady(parseInt(e.ssrc,10))?t.framesDecodeFreezeTime+=t.framesDecodeInterval:this.setVideoIsReady2(parseInt(e.ssrc,10),!0))):t.framesDecodeCount0&&!this.isFirstAudioReceived[t.ssrc]&&(this.onFirstAudioReceived&&this.onFirstAudioReceived(t.ssrc),this.isFirstAudioReceived[t.ssrc]=!0),t.decodingNormal>0&&!this.isFirstAudioDecoded[t.ssrc]&&(this.onFirstAudioDecoded&&this.onFirstAudioDecoded(t.ssrc),this.isFirstAudioDecoded[t.ssrc]=!0),this._stats.audioRecv.push(t);break}case\"audio_send\":{const t=OB(UB);t.codec=e.googCodecName,t.inputLevel=Math.abs(Number(e.audioInputLevel))/32767,t.aecReturnLoss=Number(e.googEchoCancellationReturnLoss||0),t.aecReturnLossEnhancement=Number(e.googEchoCancellationReturnLossEnhancement||0),t.residualEchoLikelihood=Number(e.googResidualEchoLikelihood||0),t.residualEchoLikelihoodRecentMax=Number(e.googResidualEchoLikelihoodRecentMax||0),t.bytes=Number(e.bytesSent),t.packets=Number(e.packetsSent),t.packetsLost=Number(e.packetsLost),t.ssrc=Number(e.ssrc),t.rttMs=Number(e.googRtt||0),this._stats.rtt=t.rttMs,this._stats.audioSend.push(t);break}}}))}_getStats(){return new Gu(((e,t)=>{this.pc.getStats(e,t)}))}statsResponsesToObjects(e){const t=[];return e.result().forEach((e=>{const i={id:e.id,timestamp:e.timestamp.valueOf().toString(),type:e.type};e.names().forEach((t=>{i[t]=e.stat(t)})),t.push(i)})),t}}function HB(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function KB(e){for(var t=1;t{switch(e.type){case _b.OUTBOUND:case _b.INBOUND:{const t=e.mediaType||e.kind,i=!t&&\"frameWidth\"in e,n=!t&&!(\"frameWidth\"in e);e.type===_b.OUTBOUND?\"audio\"===t||n?this.processAudioOutboundStats(e):(\"video\"===t||i)&&this.processVideoOutboundStats(e):e.type===_b.INBOUND&&(\"audio\"===t||n?this.processAudioInboundStats(e):(\"video\"===t||i)&&this.processVideoInboundStats(e));break}case _b.TRANSPORT:{const t=this.report.get(e.selectedCandidatePairId);t&&this.processCandidatePairStats(t);break}case _b.CANDIDATE_PAIR:e.selected&&this.processCandidatePairStats(e)}})),this.updateSendBitrate(),this._stats.timestamp=Date.now(),this.calcLossRate(this._stats),this.stats=this._stats}async getSelectedCandidatePair(){const e=await this.pc.getStats(),t={local:KB({},PB),remote:KB({},PB)};return e.forEach((i=>{let n;if(i.type===_b.TRANSPORT&&(n=e.get(i.selectedCandidatePairId)),i.type===_b.CANDIDATE_PAIR&&i.selected&&(n=i),n){const i=(e,t)=>{e.type=t.type,e.id=t.id,t.address&&(e.address=t.address),t.candidateType&&(e.candidateType=t.candidateType),t.port&&(e.port=t.port),t.priority&&(e.priority=t.priority),t.protocol&&(e.protocol=t.protocol),t.relayProtocol&&(e.relayProtocol=t.relayProtocol)};if(n.localCandidateId){const r=e.get(n.localCandidateId);r&&i(t.local,r)}if(n.remoteCandidateId){const r=e.get(n.remoteCandidateId);r&&i(t.remote,r)}}})),t}processCandidatePairStats(e){if(this._stats.sendBandwidth=e.availableOutgoingBitrate||0,e.currentRoundTripTime&&(this._stats.rtt=1e3*e.currentRoundTripTime),this._stats.videoSend.forEach((t=>{e.currentRoundTripTime&&(t.rttMs=1e3*e.currentRoundTripTime)})),this._stats.audioSend.forEach((t=>{e.currentRoundTripTime&&(t.rttMs=1e3*e.currentRoundTripTime)})),this._stats.selectedCandidatePair.id=e.id,e.localCandidateId){const t=this.report.get(e.localCandidateId);t&&this.processCandidateStats(t)}if(e.remoteCandidateId){const t=this.report.get(e.remoteCandidateId);t&&this.processCandidateStats(t)}}processCandidateStats(e){let t;e.type===_b.LOCAL_CANDIDATE&&(t=this._stats.selectedCandidatePair.localCandidate),e.type===_b.REMOTE_CANDIDATE&&(t=this._stats.selectedCandidatePair.remoteCandidate),t&&(t.type=e.type,t.id=e.id,e.address&&(t.address=e.address),e.candidateType&&(t.candidateType=e.candidateType),e.port&&(t.port=e.port),e.priority&&(t.priority=e.priority),e.protocol&&(t.protocol=e.protocol),e.relayProtocol&&(t.relayProtocol=e.relayProtocol),e.type===_b.LOCAL_CANDIDATE&&this.stats.selectedCandidatePair.localCandidate.id!==t.id&&this.onSelectedLocalCandidateChanged&&this.onSelectedLocalCandidateChanged(KB({},t),KB({},this.stats.selectedCandidatePair.localCandidate)),e.type===_b.REMOTE_CANDIDATE&&this.stats.selectedCandidatePair.remoteCandidate.id!==t.id&&this.onSelectedRemoteCandidateChanged&&this.onSelectedRemoteCandidateChanged(KB({},t),KB({},this.stats.selectedCandidatePair.remoteCandidate)))}processAudioInboundStats(e){let t=this._stats.audioRecv.find((t=>t.ssrc===e.ssrc));t||(t=OB(xB),this._stats.audioRecv.push(t)),t.ssrc=e.ssrc,t.packets=e.packetsReceived,t.packetsLost=e.packetsLost,t.bytes=e.bytesReceived,t.jitterMs=1e3*e.jitter,this.processAudioTrackReceiverStats(e,e.trackId,t),e.codecId&&(t.codec=this.getCodecFromCodecStats(e.codecId)),t.receivedFrames||(t.receivedFrames=e.packetsReceived),t.droppedFrames||(t.droppedFrames=e.packetsLost),t.receivedFrames>0&&!this.isFirstAudioReceived[t.ssrc]&&(this.onFirstAudioReceived&&this.onFirstAudioReceived(t.ssrc),this.isFirstAudioReceived[t.ssrc]=!0),t.outputLevel&&t.outputLevel>0&&!this.isFirstAudioDecoded[t.ssrc]&&(this.onFirstAudioDecoded&&this.onFirstAudioDecoded(t.ssrc),this.isFirstAudioDecoded[t.ssrc]=!0),\"number\"==typeof e.concealedSamples&&(t.concealedSamples=e.concealedSamples)}processVideoInboundStats(e){let t=this._stats.videoRecv.find((t=>t.ssrc===e.ssrc));t||(t=OB(kB),this._stats.videoRecv.push(t)),t.ssrc=e.ssrc,t.packets=e.packetsReceived,t.packetsLost=e.packetsLost,t.bytes=e.bytesReceived,t.firsCount=e.firCount,t.nacksCount=e.nackCount,t.plisCount=e.pliCount,t.framesDecodeCount=e.framesDecoded,t.framesDroppedCount=e.framesDropped,t.totalInterFrameDelay=e.totalInterFrameDelay,t.totalSquaredInterFrameDelay=e.totalSquaredInterFrameDelay,t.totalFreezesDuration=e.totalFreezesDuration;const i=this.lastDecodeVideoReceiverStats.get(t.ssrc),n=this.lastVideoFramesDecode.get(t.ssrc),r=this.lastVideoFramesOutput.get(t.ssrc),o=Date.now();if(t.framesDecodeCount>0&&!this.isFirstVideoDecoded[t.ssrc]){const e=t.decodedFrame?t.decodedFrame.width:0,i=t.decodedFrame?t.decodedFrame.height:0;this.onFirstVideoDecoded&&this.onFirstVideoDecoded(t.ssrc,e,i),this.isFirstVideoDecoded[t.ssrc]=!0}if(i){const n=i.stats,r=o-i.lts;t.framesDecodeFreezeTime=n.framesDecodeFreezeTime,t.framesDecodeInterval=n.framesDecodeInterval,!this.isFirstVideoDecoded[t.ssrc]&&r>this.options.firstVideoDecodedTimeout&&!this.isFirstVideoDecodedTimeout[t.ssrc]&&(this.onFirstVideoDecodedTimeout&&this.onFirstVideoDecodedTimeout(t.ssrc),this.isFirstVideoDecodedTimeout[t.ssrc]=!0),t.framesDecodeCount>n.framesDecodeCount&&this.isFirstVideoDecoded[t.ssrc]?(i.lts=Date.now(),t.framesDecodeInterval=r,t.framesDecodeInterval>=this.options.freezeRateLimit&&(this.getVideoIsReady(parseInt(e.ssrc))?t.framesDecodeFreezeTime+=t.framesDecodeInterval:this.setVideoIsReady2(parseInt(e.ssrc,10),!0))):t.framesDecodeCounte.framesDecoded?t.qpSumPerFrame=e.qpSum/e.framesDecoded:t.qpSumPerFrame=(e.qpSum-i.qpSum)/(e.framesDecoded-i.stats.framesDecodeCount))}n&&o-n.lts>=800?(t.decodeFrameRate=Math.round((t.framesDecodeCount-n.count)/((o-n.lts)/1e3)),this.lastVideoFramesDecode.set(t.ssrc,{count:t.framesDecodeCount,lts:o,rate:t.decodeFrameRate})):n?t.decodeFrameRate=n.rate:this.lastVideoFramesDecode.set(t.ssrc,{count:t.framesDecodeCount,lts:o,rate:0}),t.framesDroppedCount&&e.framesReceived&&(r&&o-r.lts>=800?(t.outputFrameRate=Math.round((e.framesReceived-t.framesDroppedCount-r.count)/((o-r.lts)/1e3)),this.lastVideoFramesOutput.set(t.ssrc,{count:e.framesReceived-t.framesDroppedCount,lts:o,rate:Math.max(t.outputFrameRate,0)})):r?t.outputFrameRate=r.rate:this.lastVideoFramesOutput.set(t.ssrc,{count:e.framesReceived-t.framesDroppedCount,lts:o,rate:0})),e.totalDecodeTime&&(t.decodeMs=1e3*e.totalDecodeTime),this.processVideoTrackReceiverStats(e,e.trackId,t),e.codecId&&(t.codec=this.getCodecFromCodecStats(e.codecId)),e.framerateMean&&(t.framesRateFirefox=e.framerateMean),t.packets>0&&!this.isFirstVideoReceived[t.ssrc]&&(this.onFirstVideoReceived&&this.onFirstVideoReceived(t.ssrc),this.isFirstVideoReceived[t.ssrc]=!0),this.lastDecodeVideoReceiverStats.set(t.ssrc,{stats:KB({},t),lts:i?i.lts:Date.now(),qpSum:e.qpSum})}processVideoOutboundStats(e){let t=this._stats.videoSend.find((t=>t.ssrc===e.ssrc));t||(t=OB(MB),this._stats.videoSend.push(t));const i=this.mediaBytesSent.get(e.ssrc);if(i)i.add(e.bytesSent);else{const t=new DB(10);t.add(e.bytesSent),this.mediaBytesSent.set(e.ssrc,t)}if(void 0!==e.retransmittedBytesSent){const t=this.mediaBytesRetransmit.get(e.ssrc);if(t)t.add(e.retransmittedBytesSent);else{const t=new DB(10);t.add(e.retransmittedBytesSent),this.mediaBytesRetransmit.set(e.ssrc,t)}}if(e.totalEncodedBytesTarget){const t=this.mediaBytesTargetEncode.get(e.ssrc);if(t)t.add(e.totalEncodedBytesTarget);else{const t=new DB(10);t.add(e.totalEncodedBytesTarget),this.mediaBytesTargetEncode.set(e.ssrc,t)}}if(t.ssrc=e.ssrc,t.bytes=e.bytesSent,t.packets=e.packetsSent,t.firsCount=e.firCount,t.nacksCount=e.nackCount,t.plisCount=e.pliCount,t.frameCount=e.framesEncoded,t.adaptionChangeReason=e.qualityLimitationReason,t.scalabilityMode=e.scalabilityMode,e.totalEncodeTime&&e.framesEncoded){const i=this.lastEncoderMs.get(e.ssrc);if(!i||i.lastFrameCount>e.framesEncoded)t.avgEncodeMs=1e3*e.totalEncodeTime/e.framesEncoded;else{const n=e.framesEncoded-i.lastFrameCount,r=e.totalEncodeTime-i.lastEncoderTime;t.avgEncodeMs=1e3*r/n}}if(e.framesEncoded&&e.qpSum){const i=this.lastEncoderMs.get(e.ssrc);!i||i.lastFrameCount>e.framesEncoded?t.qpSumPerFrame=e.qpSum/e.framesEncoded:t.qpSumPerFrame=(e.qpSum-i.lastQpSum)/(e.framesEncoded-i.lastFrameCount)}if(this.lastEncoderMs.set(e.ssrc,{lastFrameCount:e.framesEncoded,lastEncoderTime:e.totalEncodeTime,lastQpSum:e.qpSum,lts:Date.now()}),e.codecId&&(t.codec=this.getCodecFromCodecStats(e.codecId)),e.mediaSourceId&&this.processVideoMediaSource(e.mediaSourceId,t),this.processVideoTrackSenderStats(e,e.trackId,t),e.remoteId)this.processRemoteInboundStats(e.remoteId,t);else{const i=this.findRemoteStatsId(e.ssrc,_b.REMOTE_INBOUND);i&&this.processRemoteInboundStats(i,t)}}processAudioOutboundStats(e){let t=this._stats.audioSend.find((t=>t.ssrc===e.ssrc));if(t||(t=OB(UB),this._stats.audioSend.push(t)),t.ssrc=e.ssrc,t.packets=e.packetsSent,t.bytes=e.bytesSent,e.mediaSourceId&&this.processAudioMediaSource(e.mediaSourceId,t),e.codecId&&(t.codec=this.getCodecFromCodecStats(e.codecId)),this.processAudioTrackSenderStats(e,e.trackId,t),e.remoteId)this.processRemoteInboundStats(e.remoteId,t);else{const i=this.findRemoteStatsId(e.ssrc,_b.REMOTE_INBOUND);i&&this.processRemoteInboundStats(i,t)}}findRemoteStatsId(e,t){var i;const n=Array.from(ub(i=this.report).call(i)).find((i=>i.type===t&&i.ssrc===e));return n?n.id:null}processVideoMediaSource(e,t){const i=this.report.get(e);i&&i.width&&i.height&&i.framesPerSecond&&(t.inputFrame={width:i.width,height:i.height,frameRate:i.framesPerSecond})}processAudioMediaSource(e,t){const i=this.report.get(e);i&&(t.inputLevel=i.audioLevel)}processVideoTrackSenderStats(e,t,i){var n,r,o,s;const a=t?this.report.get(t):void 0,c=null!==(n=null==a?void 0:a.framesSent)&&void 0!==n?n:e.framesSent;if(\"number\"!=typeof c)return;let d=null!==(r=null==a?void 0:a.frameWidth)&&void 0!==r?r:e.frameWidth,l=null!==(o=null==a?void 0:a.frameHeight)&&void 0!==o?o:e.frameHeight,h=null!==(s=null==a?void 0:a.framesPerSecond)&&void 0!==s?s:e.framesPerSecond;if(\"number\"==typeof d&&\"number\"==typeof l||(d=0,l=0),null==h){const e=Date.now(),t=this.lastVideoFramesSent.get(i.ssrc);t&&e-t.lts>=800?(h=Math.round((c-t.count)/((e-t.lts)/1e3)),this.lastVideoFramesSent.set(i.ssrc,{count:c,lts:e,rate:h})):t?h=t.rate:this.lastVideoFramesSent.set(i.ssrc,{count:c,lts:e,rate:0})}i.sentFrame={width:d,height:l,frameRate:Math.max(0,h)}}processVideoTrackReceiverStats(e,t,i){var n,r,o,s,a;const c=t?this.report.get(t):void 0,d=null!==(n=null==c?void 0:c.framesReceived)&&void 0!==n?n:e.framesReceived,l=null!==(r=null==c?void 0:c.frameWidth)&&void 0!==r?r:e.frameWidth,h=null!==(o=null==c?void 0:c.frameHeight)&&void 0!==o?o:e.frameHeight,u=null!==(s=null==c?void 0:c.jitterBufferDelay)&&void 0!==s?s:e.jitterBufferDelay,p=null!==(a=null==c?void 0:c.jitterBufferEmittedCount)&&void 0!==a?a:e.jitterBufferEmittedCount;if(\"number\"==typeof d){const e=this.lastVideoFramesRecv.get(i.ssrc),t=Date.now();i.framesReceivedCount=d;let n=0;e&&t-e.lts>=800?(n=Math.round((d-e.count)/((t-e.lts)/1e3)),this.lastVideoFramesRecv.set(i.ssrc,{count:d,lts:t,rate:n})):e?n=e.rate:this.lastVideoFramesRecv.set(i.ssrc,{count:d,lts:t,rate:0}),i.receivedFrame={width:l||0,height:h||0,frameRate:n||0},i.decodedFrame={width:l||0,height:h||0,frameRate:i.decodeFrameRate||0},i.outputFrame={width:l||0,height:h||0,frameRate:i.outputFrameRate||i.decodeFrameRate||0}}if(u&&p){const e=this.lastVideoJBDelay.get(i.ssrc)||{jitterBufferDelay:0,jitterBufferEmittedCount:0,jitterBufferMs:0};let t=e.jitterBufferMs;const n=p-e.jitterBufferEmittedCount;n>0&&(t=1e3*(u-e.jitterBufferDelay)/n),i.jitterBufferMs=t,i.currentDelayMs=Math.round(t),this.lastVideoJBDelay.set(i.ssrc,{jitterBufferDelay:u,jitterBufferEmittedCount:p,jitterBufferMs:i.currentDelayMs})}}processAudioTrackSenderStats(e,t,i){var n,r,o,s;const a=t?this.report.get(t):void 0,c=null!==(n=null!==(r=null==a?void 0:a.echoReturnLoss)&&void 0!==r?r:e.echoReturnLoss)&&void 0!==n?n:0,d=null!==(o=null!==(s=null==a?void 0:a.echoReturnLossEnhancement)&&void 0!==s?s:e.echoReturnLossEnhancement)&&void 0!==o?o:0;i.aecReturnLoss=c,i.aecReturnLossEnhancement=d}processAudioTrackReceiverStats(e,t,i){var n,r,o,s,a,c,d;const l=t?this.report.get(t):void 0,h=null!==(n=null==l?void 0:l.removedSamplesForAcceleration)&&void 0!==n?n:e.removedSamplesForAcceleration,u=null!==(r=null==l?void 0:l.totalSamplesReceived)&&void 0!==r?r:e.totalSamplesReceived,p=null!==(o=null==l?void 0:l.jitterBufferDelay)&&void 0!==o?o:e.jitterBufferDelay,_=null!==(s=null==l?void 0:l.jitterBufferEmittedCount)&&void 0!==s?s:e.jitterBufferEmittedCount,E=null!==(a=null==l?void 0:l.audioLevel)&&void 0!==a?a:null==e?void 0:e.audioLevel,m=null!==(c=null==l?void 0:l.totalSamplesDuration)&&void 0!==c?c:null==e?void 0:e.totalSamplesDuration,f=null!==(d=null==l?void 0:l.concealedSamples)&&void 0!==d?d:e.concealedSamples;if(h&&u&&(i.accelerateRate=h/u),p&&_){const e=this.lastAudioJBDelay.get(i.ssrc)||{jitterBufferDelay:0,jitterBufferEmittedCount:0,jitterBufferMs:0};let t=e.jitterBufferMs;const n=_-e.jitterBufferEmittedCount;n>0&&(t=1e3*(p-e.jitterBufferDelay)/n),i.jitterBufferMs=Math.round(t),this.lastAudioJBDelay.set(i.ssrc,{jitterBufferDelay:p,jitterBufferEmittedCount:_,jitterBufferMs:i.jitterBufferMs})}i.outputLevel=E;let T=1920;m&&u&&(T=u/m/50,i.receivedFrames=Math.round(u/T)),f&&(i.droppedFrames=Math.round(f/T))}processRemoteInboundStats(e,t){const i=this.report.get(e);i&&(t.packetsLost=i.packetsLost,i.roundTripTime&&(t.rttMs=1e3*i.roundTripTime),i.jitter&&(t.jitterMs=1e3*i.jitter),i.timestamp&&(t.timestamp=i.timestamp))}getCodecFromCodecStats(e){const t=this.report.get(e);if(!t)return\"\";const i=t.mimeType.match(/\\/(.*)$/);return i&&i[1]?i[1]:\"\"}updateSendBitrate(){let e=0,t=null,i=null;this.mediaBytesSent.forEach((t=>{e+=t.diffMean()})),this.mediaBytesRetransmit.forEach((e=>{t=null===t?e.diffMean():t+e.diffMean()})),this.mediaBytesTargetEncode.forEach((e=>{i=null===i?e.diffMean():i+e.diffMean()}));const n=null!==t?e-t:e;this._stats.bitrate={actualEncoded:8*n/(this.options.updateInterval/1e3),transmit:8*e/(this.options.updateInterval/1e3)},null!==t&&(this._stats.bitrate.retransmit=8*t/(this.options.updateInterval/1e3)),null!==i&&(this._stats.bitrate.targetEncoded=8*i/(this.options.updateInterval/1e3))}}class qB extends BB{updateStats(){return Gu.resolve()}}function zB(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:250,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:8,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:500,r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:1e4;const o=function(){const e=navigator.userAgent.toLocaleLowerCase().match(/chrome\\/[\\d]*/i);return e&&e[0]?Number(e[0].split(\"/\")[1]):null}();return o?o<76?new WB(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:n,firstVideoDecodedTimeout:r}):new YB(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:n,firstVideoDecodedTimeout:r}):function(e){return!!window.RTCStatsReport&&e.getStats()instanceof Gu}(e)?new YB(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:n,firstVideoDecodedTimeout:r}):new qB(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:n,firstVideoDecodedTimeout:r})}function JB(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function XB(e){for(var t=1;t1&&void 0!==arguments[1]?arguments[1]:{},i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=arguments.length>3?arguments[3]:void 0;const{filterRTX:r,filterVideoFec:o,filterAudioFec:s,filterAudioCodec:a,filterVideoCodec:c}=t,{useXR:d}=i;let l=[],h=[],u=[],p=[],_=!1,E=!1;if(wB.parse(e).mediaDescriptions.forEach((e=>{n&&n!==e.attributes.direction||(\"video\"!==e.media.mediaType||_||(h=e.attributes.payloads,p=e.attributes.extmaps,_=!0),\"audio\"!==e.media.mediaType||E||(l=e.attributes.payloads,u=e.attributes.extmaps,E=!0))})),!p||0===h.length)throw new Error(\"Cannot get video capabilities from SDP.\");if(!u||0===l.length)throw new Error(\"Cannot get audio capabilities from SDP.\");if(h.forEach((e=>{var t;null!==(t=e.rtpMap)&&void 0!==t&&t.clockRate&&(e.rtpMap.clockRate=parseInt(e.rtpMap.clockRate)),d&&e.rtcpFeedbacks.push({type:\"rrtr\"})})),l.forEach((e=>{var t;null!==(t=e.rtpMap)&&void 0!==t&&t.clockRate&&(e.rtpMap.clockRate=parseInt(e.rtpMap.clockRate)),d&&e.rtcpFeedbacks.push({type:\"rrtr\"})})),r&&(l=l.filter((e=>{var t;return\"rtx\"!==(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())})),h=h.filter((e=>{var t;return\"rtx\"!==(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())}))),o&&(h=h.filter((e=>{var t;return!/(red)|(ulpfec)|(flexfec)/i.test((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName)||\"\")}))),s&&(l=l.filter((e=>{var t;return!/(red)|(ulpfec)|(flexfec)/i.test((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName)||\"\")}))),a&&(null==a?void 0:a.length)>0&&(l=l.filter((e=>{var t;return Dn(a).call(a,(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())||\"\")}))),c&&(null==c?void 0:c.length)>0){const e=h.filter((e=>{var t;return Dn(c).call(c,(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())||\"\")}));h=e.concat(r?[]:Ej(e,h))}const m=Dy(\"UNSUPPORTED_VIDEO_CODEC\");return m&&m.length>0&&(h=h.filter((e=>!(e.rtpMap&&Dn(m).call(m,e.rtpMap.encodingName.toLowerCase()))))),{audioCodecs:l,videoCodecs:h,audioExtensions:u,videoExtensions:p}}function ZB(e){const t=wB.parse(e);let i,n;for(const e of t.mediaDescriptions){if(!i){const t=e.attributes.iceUfrag,n=e.attributes.icePwd;if(!t||!n)throw new Error(\"Cannot get iceUfrag or icePwd from SDP.\");i={iceUfrag:t,icePwd:n}}if(!n){const t=e.attributes.fingerprints;t.length>0&&(n={fingerprints:t})}}if(!n&&t.attributes.fingerprints.length>0&&(n={fingerprints:t.attributes.fingerprints}),!n||!i)throw new Error(\"Cannot get iceParameters or dtlsParameters from SDP.\");return{iceParameters:i,dtlsParameters:n}}function $B(e,t){const i=[],n=e.attributes.ssrcGroups.filter((e=>\"FID\"===e.semantic)),r=e.attributes.ssrcGroups.find((e=>\"SIM\"===e.semantic)),o=e.attributes.ssrcs;if(r)r.ssrcIds.forEach((e=>{var r;const o=null===(r=n.find((t=>t.ssrcIds[0]===e)))||void 0===r?void 0:r.ssrcIds[1];i.push({ssrcId:e,rtx:t?o:void 0})}));else if(n.length>0){const e=n[0].ssrcIds[0],r=n[0].ssrcIds[1];i.push({ssrcId:e,rtx:t?r:void 0})}else{if(0===o.length)throw new Error(\"No ssrcs found on local media description.\");i.push({ssrcId:o[0].ssrcId})}return i}function ej(e,t){const{cname:i}=e;let n;t&&t.ip&&\"number\"==typeof t.port?(n=[{foundation:\"udpcandidate\",componentId:\"1\",transport:\"udp\",priority:\"2103266323\",connectionAddress:t.ip,port:t.port.toString(),type:\"host\",extension:{}}],Qy.debug(\"Using remote candidate from AP \".concat(t.ip,\":\").concat(t.port)),t.ip6&&(n.push({foundation:\"udpcandidate\",componentId:\"1\",transport:\"udp\",priority:\"2103266323\",connectionAddress:t.ip6,port:t.port.toString(),type:\"host\",extension:{}}),Qy.debug(\"Using IPV6 remote candidate from AP \".concat(t.ip6,\":\").concat(t.port)))):n=e.iceParameters.candidates.map((e=>({foundation:e.foundation,componentId:\"1\",transport:e.protocol,priority:e.priority.toString(),connectionAddress:e.ip,port:e.port.toString(),type:e.type,extension:{}})));const r={fingerprints:e.dtlsParameters.fingerprints.map((e=>({hashFunction:e.algorithm,fingerprint:e.fingerprint})))},o={iceUfrag:e.iceParameters.iceUfrag,icePwd:e.iceParameters.icePwd};let s;switch(e.dtlsParameters.role){case\"server\":s=\"passive\";break;case\"client\":s=\"active\";break;case\"auto\":s=\"actpass\"}return{dtlsParameters:r,iceParameters:o,candidates:n,rtpCapabilities:hj(e.rtpCapabilities),setup:s,cname:i}}function tj(e,t,i){const n=[],r=[];return e.forEach((e=>{let{ssrcId:o,rtx:s}=e;const a=ey(8,\"track-\"),c={ssrcId:o,attributes:XB({label:a,mslabel:i=i||ey(10,\"\"),msid:\"\".concat(i,\" \").concat(a)},t&&{cname:t})};if(n.push(c),void 0!==s){const e={ssrcId:s,attributes:XB({label:a,mslabel:i,msid:\"\".concat(i,\" \").concat(a)},t&&{cname:t})};n.push(e),r.push({semantic:\"FID\",ssrcIds:[o,s]})}})),e.length>1&&r.push({semantic:\"SIM\",ssrcIds:e.map((e=>{let{ssrcId:t}=e;return t}))}),{ssrcs:n,ssrcGroups:r}}function ij(e,t){t instanceof LV&&e.attributes.payloads.forEach((e=>{var i;const n=null===(i=e.rtpMap)||void 0===i?void 0:i.encodingName.toLowerCase();if(!n||-1===[\"opus\",\"pcmu\",\"pcma\",\"g722\"].indexOf(n))return;e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters.minptime=\"10\",e.fmtp.parameters.useinbandfec=\"1\";const r=t._encoderConfig;r&&\"pcmu\"!==n&&\"pcma\"!==n&&\"g722\"!==n&&(r.bitrate&&!Pv()&&(e.fmtp.parameters.maxaveragebitrate=\"\".concat(Math.floor(1e3*r.bitrate))),r.sampleRate&&(e.fmtp.parameters.maxplaybackrate=\"\".concat(r.sampleRate),e.fmtp.parameters[\"sprop-maxcapturerate\"]=\"\".concat(r.sampleRate)),r.stereo&&(e.fmtp.parameters.stereo=\"1\",e.fmtp.parameters[\"sprop-stereo\"]=\"1\"))}))}function nj(e){const t=e.attributes.unrecognized.findIndex((e=>\"x-google-flag\"===e.attField&&\"conference\"===e.attValue));-1!==t&&e.attributes.unrecognized.splice(t,1)}function rj(e,t){var i;if(!(t instanceof vF&&t._encoderConfig&&-1===t._hints.indexOf(LU.SCREEN_TRACK)))return;const n=t._encoderConfig;_U().supportMinBitrate&&n.bitrateMin&&e.attributes.payloads.forEach((e=>{var t,i;Dn(t=[\"h264\",\"h265\",\"vp8\",\"vp9\",\"av1\"]).call(t,(null===(i=e.rtpMap)||void 0===i?void 0:i.encodingName.toLowerCase())||\"\")&&(e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters[\"x-google-min-bitrate\"]=\"\".concat(n.bitrateMin))})),_U().supportMinBitrate&&!Dn(i=t._hints).call(i,LU.LOW_STREAM)&&n.bitrateMax&&e.attributes.payloads.forEach((e=>{var t,i;Dn(t=[\"h264\",\"h265\",\"vp8\",\"vp9\",\"av1\"]).call(t,(null===(i=e.rtpMap)||void 0===i?void 0:i.encodingName.toLowerCase())||\"\")&&(e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters[\"x-google-start-bitrate\"]=\"\".concat(Dy(\"X_GOOGLE_START_BITRATE\")||Math.floor(n.bitrateMax)))}))}function oj(e){if(\"video\"!==e.media.mediaType)return;const t=Iv();if(t.name!==gv.SAFARI&&t.os!==Sv.IOS)return;const i=e.attributes.extmaps.findIndex((e=>/video-orientation/g.test(e.extensionName)));-1!==i&&e.attributes.extmaps.splice(i,1)}function sj(e,t,i){if(!t)return;let n,r;if(\"video\"===e.media.mediaType?(n=i.videoExtensions,r=i.videoCodecs):(n=i.audioExtensions,r=i.audioCodecs),!0===t.twcc){const t=n.find((e=>\"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01\"===e.extensionName));if(t){e.attributes.extmaps.find((e=>\"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01\"===e.extensionName))||e.attributes.extmaps.push({entry:t.entry,extensionName:\"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01\"});const i=function(e,t){return t.filter((t=>!!e.find((e=>e.payloadType===t.payloadType&&!!e.rtcpFeedbacks.find((e=>\"transport-cc\"===e.type))))))}(r,e.attributes.payloads);i.forEach((e=>{e.rtcpFeedbacks.find((e=>\"transport-cc\"===e.type))||e.rtcpFeedbacks.push({type:\"transport-cc\"})}))}}else if(!1===t.twcc){const t=e.attributes.extmaps.findIndex((e=>\"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01\"===e.extensionName));-1!==t&&e.attributes.extmaps.splice(t,1),e.attributes.payloads.forEach((e=>{const t=e.rtcpFeedbacks.findIndex((e=>\"transport-cc\"===e.type));-1!==t&&e.rtcpFeedbacks.splice(t,1)}))}if(!0===t.remb){const t=n.find((e=>\"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\"===e.extensionName));if(t){e.attributes.extmaps.find((e=>\"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\"===e.extensionName))||e.attributes.extmaps.push({entry:t.entry,extensionName:\"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\"});const i=function(e,t){return t.filter((t=>!!e.find((e=>e.payloadType===t.payloadType&&!!e.rtcpFeedbacks.find((e=>\"goog-remb\"===e.type))))))}(r,e.attributes.payloads);i.forEach((e=>{e.rtcpFeedbacks.find((e=>\"goog-remb\"===e.type))||e.rtcpFeedbacks.push({type:\"goog-remb\"})}))}}else if(!1===t.remb){const t=e.attributes.extmaps.findIndex((e=>\"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\"===e.extensionName));-1!==t&&e.attributes.extmaps.splice(t,1),e.attributes.payloads.forEach((e=>{const t=e.rtcpFeedbacks.findIndex((e=>\"goog-remb\"===e.type));-1!==t&&e.rtcpFeedbacks.splice(t,1)}))}}function aj(e,t,i){if(Pv())return;if(\"video\"!==e.media.mediaType)return;if(!(t instanceof vF))return;if(\"vp9\"!==i&&\"vp8\"!==i)return;if(\"vp8\"===i&&!Dy(\"SIMULCAST\"))return;if(void 0===t._scalabilityMode||t._scalabilityMode.numSpatialLayers<=1)return;const n=\"vp8\"===i?2:t._scalabilityMode.numSpatialLayers,r=e.attributes.ssrcs[0],o=e.attributes.ssrcGroups.find((e=>\"FID\"===e.semantic&&e.ssrcIds[0]===r.ssrcId)),s={semantic:\"SIM\",ssrcIds:[r.ssrcId]};for(let t=1;t0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=new RTCPeerConnection;i.addTransceiver(\"video\",{direction:\"sendonly\"}),i.addTransceiver(\"audio\",{direction:\"sendonly\"}),i.addTransceiver(\"video\",{direction:\"recvonly\"}),i.addTransceiver(\"audio\",{direction:\"recvonly\"});const n=(await i.createOffer()).sdp,{send:r,recv:o,sendrecv:s}=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=arguments.length>2?arguments[2]:void 0;const n=QB(i,e,t,\"sendonly\"),r=QB(i,e,t,\"recvonly\"),o={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},s={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},a={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]};if(lj(n,r,\"videoExtensions\",o,s,a),lj(n,r,\"videoCodecs\",o,s,a),lj(n,r,\"audioExtensions\",o,s,a),lj(n,r,\"audioCodecs\",o,s,a),Dy(\"RAISE_H264_BASELINE_PRIORITY\")){const e=a.videoCodecs.findIndex((e=>{var t,i;return\"h264\"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLocaleLowerCase())&&\"42001f\"===(null===(i=e.fmtp)||void 0===i?void 0:i.parameters[\"profile-level-id\"])}));if(-1!==e){const t=a.videoCodecs.findIndex((e=>{var t;return\"h264\"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLocaleLowerCase())}));if(t{var t,i;return!(\"h264\"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLocaleLowerCase())&&\"42001f\"!==(null===(i=e.fmtp)||void 0===i?void 0:i.parameters[\"profile-level-id\"]))}))),-1!==t&&Dy(\"FILTER_SEND_H264_BASELINE\")&&(o.videoCodecs=o.videoCodecs.filter((e=>{var t,i;return!(\"h264\"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLocaleLowerCase())&&\"42001f\"!==(null===(i=e.fmtp)||void 0===i?void 0:i.parameters[\"profile-level-id\"]))})))}}return{send:o,recv:s,sendrecv:a}}(e,t,n);try{i.close()}catch(e){}return{send:r,recv:o,sendrecv:s}}function dj(){const e={audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]},t=QB(arguments.length>2?arguments[2]:void 0,arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},\"recvonly\"),i={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},n={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},r={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]};if(lj(e,t,\"videoExtensions\",i,n,r),lj(e,t,\"videoCodecs\",i,n,r),lj(e,t,\"audioExtensions\",i,n,r),lj(e,t,\"audioCodecs\",i,n,r),Dy(\"RAISE_H264_BASELINE_PRIORITY\")){const e=r.videoCodecs.findIndex((e=>e.rtpMap&&\"h264\"===e.rtpMap.encodingName.toLocaleLowerCase()&&e.fmtp&&\"42001f\"===e.fmtp.parameters[\"profile-level-id\"]));if(-1!==e){const t=r.videoCodecs.findIndex((e=>e.rtpMap&&\"h264\"===e.rtpMap.encodingName.toLocaleLowerCase()));if(t!(e.rtpMap&&\"h264\"===e.rtpMap.encodingName.toLocaleLowerCase()&&e.fmtp&&\"42001f\"!==e.fmtp.parameters[\"profile-level-id\"]))))}}return{send:i,recv:n,sendrecv:r}}function lj(e,t,i,n,r,o){if(\"videoExtensions\"===i||\"audioExtensions\"===i){const s=[];return e[i].forEach((e=>{t[i].some(((t,i)=>{if(e.entry===t.entry&&e.extensionName===t.extensionName)return s.push(i),!0}))?o[i].push(e):n[i].push(e)})),void t[i].forEach(((e,t)=>{-1===s.indexOf(t)&&r[i].push(e)}))}if(\"videoCodecs\"===i||\"audioCodecs\"===i){const s=[];return e[i].forEach((e=>{t[i].some(((t,i)=>{if(e.payloadType===t.payloadType&&JSON.stringify(e)===JSON.stringify(t))return s.push(i),!0}))?o[i].push(e):n[i].push(e)})),void t[i].forEach(((e,t)=>{-1===s.indexOf(t)&&r[i].push(e)}))}}function hj(e){const{send:t,recv:i,sendrecv:n}=e;if(!n){if(!t||!i)throw new Error(\"cannot merge rtp capabilities because one of send or recv is empty!\");return{send:t,recv:i}}let r,o;return t?(r={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},r.audioCodecs=[...t.audioCodecs,...n.audioCodecs],r.videoCodecs=[...t.videoCodecs,...n.videoCodecs],r.audioExtensions=[...t.audioExtensions,...n.audioExtensions],r.videoExtensions=[...t.videoExtensions,...n.videoExtensions]):r=n,i?(o={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},o.audioCodecs=[...i.audioCodecs,...n.audioCodecs],o.videoCodecs=[...i.videoCodecs,...n.videoCodecs],o.audioExtensions=[...i.audioExtensions,...n.audioExtensions],o.videoExtensions=[...i.videoExtensions,...n.videoExtensions]):o=n,{send:r,recv:o}}function uj(e){if(\"audio\"!==e.media.mediaType)return;e.attributes.payloads.filter((e=>{var t;return\"opus\"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())})).forEach((e=>{e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters.stereo=\"1\",e.fmtp.parameters[\"sprop-stereo\"]=\"1\"}))}function pj(e){e.mediaDescriptions.forEach((e=>{\"video\"!==e.media.mediaType&&\"audio\"!==e.media.mediaType||e.attributes.payloads.forEach((e=>{-1===e.rtcpFeedbacks.findIndex((e=>\"rrtr\"===e.type))&&e.rtcpFeedbacks.push({type:\"rrtr\"})}))}))}function _j(e,t,i,n){let r=[];if(e===nw.VIDEO){if(Dy(\"H264_PROFILE_LEVEL_ID\")&&\"h264\"===n&&(r=t.videoCodecs.filter((e=>{var t;return Dn(t=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||\"\").call(t,n)&&e&&e.fmtp&&e.fmtp.parameters[\"profile-level-id\"]===Dy(\"H264_PROFILE_LEVEL_ID\")}))),!Array.isArray(r)||0===r.length){let e=[];const o=[],s=[],a=[];if(i.videoCodecs.forEach((t=>{const i=t.rtpMap&&t.rtpMap.encodingName.toLowerCase()||\"\";Dn(i).call(i,n)?e.push(t):Dn(i).call(i,\"vp9\")?o.push(t):Dn(i).call(i,\"vp8\")?s.push(t):Dn(i).call(i,\"h264\")&&a.push(t)})),0===e.length){let t=\"\";0!==o.length?(e=o,t=\"vp9\"):0!==s.length?(e=s,t=\"vp8\"):0!==a.length&&(e=a,t=\"h264\"),Qy.warning(\"codec \".concat(n,\" not included in rtpCapabilities, fallback to default payloads: \").concat(t))}0!==e.length&&(r=t.videoCodecs.filter((t=>e.some((e=>e.payloadType===t.payloadType)))))}if(0===r.length&&(Qy.warning(\"codec \".concat(n,\" not included in rtpCapabilities, fallback to default payloads: \").concat(t.videoCodecs[0].rtpMap&&t.videoCodecs[0].rtpMap.encodingName)),r=t.videoCodecs),Dy(\"USE_PUB_RTX\")||Dy(\"USE_SUB_RTX\")){const e=Ej(r,t.videoCodecs);r=[...r,...e]}}else r=t.audioCodecs.filter((e=>{var t;return Dn(t=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||\"\").call(t,n)})),0===r.length&&(Qy.warning(\"codec \".concat(n,\" not included in rtpCapabilities, fallback to opus\")),r=t.audioCodecs.filter((e=>{var t;return Dn(t=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||\"\").call(t,\"opus\")})));return r}function Ej(e,t){const i=e.map((e=>e.payloadType.toString()));return t.filter((e=>e.rtpMap&&\"rtx\"===e.rtpMap.encodingName&&e.fmtp&&e.fmtp.parameters.apt&&Dn(i).call(i,e.fmtp&&e.fmtp.parameters.apt)))}let mj=class{get localCapabilities(){return GI(this._localCapabilities)}get rtpCapabilities(){return GI(this._rtpCapabilities)}get candidates(){return GI(this._candidates)}get iceParameters(){return GI(this._iceParameters)}get dtlsParameters(){return GI(this._dtlsParameters)}constructor(e){ng(this,\"sessionDesc\",void 0),ng(this,\"_localCapabilities\",void 0),ng(this,\"_rtpCapabilities\",void 0),ng(this,\"_candidates\",void 0),ng(this,\"_iceParameters\",void 0),ng(this,\"_dtlsParameters\",void 0),ng(this,\"setup\",void 0),ng(this,\"currentMidIndex\",void 0),ng(this,\"cname\",\"o/i14u9pJrxRKAsu\"),ng(this,\"firefoxSsrcMidMap\",new Map),e=GI(e);const{remoteIceParameters:t,remoteDtlsParameters:i,candidates:n,remoteRTPCapabilities:r,localCapabilities:o,direction:s,setup:a,videoCodec:c,audioCodec:d}=e;let l;this.setup=a,l=s===yb.RECEIVE_ONLY?wB.parse(\"v=0\\no=- 0 0 IN IP4 127.0.0.1\\ns=AgoraGateway\\nt=0 0\\na=group:BUNDLE 0 1\\na=msid-semantic: WMS\\na=extmap-allow-mixed\\nm=video 9 UDP/TLS/RTP/SAVPF 0\\nc=IN IP4 127.0.0.1\\na=rtcp:9 IN IP4 0.0.0.0\\na=sendonly\\na=rtcp-mux\\na=rtcp-rsize\\na=mid:0\\nm=audio 9 UDP/TLS/RTP/SAVPF 0\\nc=IN IP4 127.0.0.1\\na=rtcp:9 IN IP4 0.0.0.0\\na=sendonly\\na=rtcp-mux\\na=rtcp-rsize\\na=mid:1\\n\"):wB.parse(\"v=0\\no=- 0 0 IN IP4 127.0.0.1\\ns=AgoraGateway\\nt=0 0\\na=group:BUNDLE 0 1\\na=msid-semantic: WMS\\na=extmap-allow-mixed\\nm=video 9 UDP/TLS/RTP/SAVPF 0\\nc=IN IP4 127.0.0.1\\na=rtcp:9 IN IP4 0.0.0.0\\na=recvonly\\na=rtcp-mux\\na=rtcp-rsize\\na=mid:0\\nm=audio 9 UDP/TLS/RTP/SAVPF 0\\nc=IN IP4 127.0.0.1\\na=rtcp:9 IN IP4 0.0.0.0\\na=recvonly\\na=rtcp-mux\\na=rtcp-rsize\\na=mid:1\\n\"),this._rtpCapabilities=r,this._candidates=n,this._iceParameters=t,this._dtlsParameters=i,this._localCapabilities=o;const h=s===yb.RECEIVE_ONLY?this.rtpCapabilities.send:this.rtpCapabilities.recv,u=s===yb.RECEIVE_ONLY?this._localCapabilities.recv:this._localCapabilities.send,p=s===yb.RECEIVE_ONLY?r.send.videoCodecs:_j(nw.VIDEO,h,u,c),_=s===yb.RECEIVE_ONLY?r.send.audioCodecs:_j(nw.AUDIO,h,u,d);for(const e of l.mediaDescriptions)e.attributes.iceUfrag=t.iceUfrag,e.attributes.icePwd=t.icePwd,e.attributes.fingerprints=i.fingerprints,e.attributes.candidates=n,e.attributes.setup=this.setup,\"application\"===e.media.mediaType&&(e.attributes.sctpPort=\"5000\"),\"video\"===e.media.mediaType&&(e.media.fmts=p.map((e=>e.payloadType.toString(10))),e.attributes.payloads=p,e.attributes.extmaps=h.videoExtensions),\"audio\"===e.media.mediaType&&(e.media.fmts=_.map((e=>e.payloadType.toString(10))),e.attributes.payloads=_,e.attributes.extmaps=h.audioExtensions,uj(e));this.sessionDesc=l,this.currentMidIndex=l.mediaDescriptions.length-1}toString(){return wB.print(this.sessionDesc)}hasMid(e){return Array.isArray(e)?e.every((e=>this.hasMid(e))):this.sessionDesc.mediaDescriptions.some((t=>t.attributes.mid===e))}send(e,t,i,n,r){i=i.replace(/ /g,\"-\");const{ssrcs:o,ssrcGroups:s}=tj(t,this.cname,Dy(\"SYNC_GROUP\")?i:void 0),a=this.findPreloadMediaDesc(o);if(a){if(Pv()&&this.firefoxSsrcMidMap.set(o[0].ssrcId,a.attributes.mid),r&&(r.twcc||r.remb)){const e=this.sessionDesc.mediaDescriptions.indexOf(a);return this.sessionDesc.mediaDescriptions[e]=this.mungSendMediaDesc(a,r),{mid:a.attributes.mid,needExchangeSDP:!0}}return{mid:a.attributes.mid,needExchangeSDP:!1}}{const t=this.findAvailableMediaIndex(e,o,n);let i;return-1===t?(i=this.createOrRecycleSendMedia(e,o,s,\"sendonly\",n,r),this.updateBundleMids()):(i=GI(this.sessionDesc.mediaDescriptions[t]),i.attributes.direction=\"sendonly\",i.attributes.ssrcs=o,i.attributes.ssrcGroups=s,this.sessionDesc.mediaDescriptions[t]=this.mungSendMediaDesc(i,r)),Pv()&&this.firefoxSsrcMidMap.set(o[0].ssrcId,i.attributes.mid),{needExchangeSDP:!0,mid:i.attributes.mid}}}stopSending(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>t.attributes.mid&&-1!==e.indexOf(t.attributes.mid)));if(t.length!==e.length)throw new Error(\"mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.stopSending.\");t.forEach((e=>{e.attributes.ssrcs=[]})),this.updateBundleMids()}receive(e,t,i){const n=[];return e.forEach((e=>{const r=e._mediaStreamTrack.kind,o=this.findAvailableRecvMediaIndex(r);let s,a=!1;-1===o?(a=!0,s=this.createOrRecycleRecvMedia(e,[],\"recvonly\",t,i),this.updateBundleMids()):(s=GI(this.sessionDesc.mediaDescriptions[o]),s.attributes.direction=\"recvonly\"),n.push({mid:s.attributes.mid,needCreateTransceiver:a})})),n}stopReceiving(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>-1!==e.indexOf(t.attributes.mid)));if(t.length!==e.length)throw new Error(\"MediaDescriptions' length doesn't match mids's length when calling RemoteSDP.receive.\");t.forEach((e=>{e.media.port=\"0\",e.attributes.direction=\"inactive\"})),this.updateBundleMids()}addRemoteCandidate(e){const{foundation:t,protocol:i,address:n,port:r,type:o,relatedAddress:s,relatedPort:a,priority:c}=new RTCIceCandidate(e),d={foundation:null!=t?t:\"\",componentId:\"1\",transport:null!=i?i:\"\",priority:c?c+\"\":\"\",connectionAddress:null!=n?n:\"\",port:r?r+\"\":\"\",type:o?o+\"\":\"\",relAddr:null!=s?s:\"\",relPort:a?a+\"\":\"\",extension:{}};this.candidates.some((e=>e.priority===d.priority&&e.connectionAddress===d.connectionAddress&&e.port===d.port))||(this._candidates.push(d),this.sessionDesc.mediaDescriptions.forEach((e=>{e.attributes.candidates=this.candidates})))}clearRemoteCandidate(){this._candidates=[],this.sessionDesc.mediaDescriptions[0].attributes.candidates=this._candidates}createOrRecycleRecvMedia(e,t,i,n,r){const o=e._mediaStreamTrack.kind,s=this.rtpCapabilities.recv,a=_j(o,s,this.localCapabilities.send,o===nw.AUDIO?r:n),c=o===nw.VIDEO?s.videoExtensions:s.audioExtensions,d=\"\".concat(++this.currentMidIndex);let l={media:{mediaType:o,port:\"9\",protos:[\"UDP\",\"TLS\",\"RTP\",\"SAVPF\"],fmts:a.map((e=>e.payloadType.toString(10)))},connections:[{nettype:\"IN\",addrtype:\"IP4\",address:\"127.0.0.1\"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:[],extmaps:c,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:a,rtcp:{port:\"9\",netType:\"IN\",addressType:\"IP4\",address:\"0.0.0.0\"},setup:this.setup,direction:i,rtcpMux:!0,rtcpRsize:!0,mid:\"\".concat(d)}};l=this.mungRecvMediaDsec(l,e);const h=this.findFirstClosedMedia(o);if(h){const e=this.sessionDesc.mediaDescriptions.indexOf(h);this.sessionDesc.mediaDescriptions[e]=l}else this.sessionDesc.mediaDescriptions.push(l);return l}muteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>Dn(e).call(e,t.attributes.mid||\"\")));if(t.length!==e.length)throw new Error(\"mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.\");t.forEach((e=>{e.attributes.direction=\"inactive\"}))}unmuteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>Dn(e).call(e,t.attributes.mid||\"\")));if(t.length!==e.length)throw new Error(\"mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.\");t.forEach((e=>{e.attributes.direction=\"recvonly\"}))}findAvailableMediaIndex(e,t,i){return this.sessionDesc.mediaDescriptions.findIndex((n=>{const r=n.media.mediaType===e&&\"0\"!==n.media.port&&(\"sendonly\"===n.attributes.direction||\"sendrecv\"===n.attributes.direction)&&0===n.attributes.ssrcs.length;if(Pv()){if(r){const e=this.firefoxSsrcMidMap.get(t[0].ssrcId);return!(e||\"0\"!==n.attributes.mid&&\"1\"!==n.attributes.mid)||!(!e||e!==n.attributes.mid)}return!1}return r&&n.attributes.mid===i}))}findAvailableRecvMediaIndex(e){return this.sessionDesc.mediaDescriptions.findIndex((t=>{const i=t.media.mediaType===e&&\"0\"!==t.media.port&&(\"recvonly\"===t.attributes.direction||\"sendrecv\"===t.attributes.direction);return\"0\"!==t.attributes.mid&&\"1\"!==t.attributes.mid&&i}))}predictReceivingMids(e){const t=[];for(let i=0;i{t.attributes.iceUfrag=e.iceUfrag,t.attributes.icePwd=e.icePwd}))}createOrRecycleSendMedia(e,t,i,n,r,o){const s=this.rtpCapabilities.send,a=e===nw.VIDEO?s.videoCodecs:s.audioCodecs,c=e===nw.VIDEO?s.videoExtensions:s.audioExtensions;Pv()&&(r=\"\".concat(++this.currentMidIndex));let d={media:{mediaType:e,port:\"9\",protos:[\"UDP\",\"TLS\",\"RTP\",\"SAVPF\"],fmts:a.map((e=>e.payloadType.toString(10)))},connections:[{nettype:\"IN\",addrtype:\"IP4\",address:\"127.0.0.1\"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:[],extmaps:c,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:i,rtcpFeedbackWildcards:[],payloads:a,rtcp:{port:\"9\",netType:\"IN\",addressType:\"IP4\",address:\"0.0.0.0\"},setup:this.setup,direction:n,rtcpMux:!0,rtcpRsize:!0,mid:r}};d=this.mungSendMediaDesc(d,o);const l=this.findFirstClosedMedia(e);if(l){const e=this.sessionDesc.mediaDescriptions.indexOf(l);this.sessionDesc.mediaDescriptions[e]=d}else this.sessionDesc.mediaDescriptions.push(d);return d}mungRecvMediaDsec(e,t,i){const n=GI(e);return nj(n),ij(n,t),rj(n,t),oj(n),sj(n,i,this.localCapabilities.send),n}mungSendMediaDesc(e,t){const i=GI(e);return sj(i,t,this.localCapabilities.recv),uj(i),i}updateRecvMedia(e,t){const i=this.sessionDesc.mediaDescriptions.findIndex((t=>t.attributes.mid===e));if(-1!==i){const e=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[i],t);this.sessionDesc.mediaDescriptions[i]=e}}updateBundleMids(){this.sessionDesc.attributes.groups[0].identificationTag=this.sessionDesc.mediaDescriptions.filter((e=>\"0\"!==e.media.port)).map((e=>e.attributes.mid))}findPreloadMediaDesc(e){return this.sessionDesc.mediaDescriptions.find((t=>{var i;return(null===(i=t.attributes)||void 0===i||null===(i=i.ssrcs[0])||void 0===i?void 0:i.ssrcId)===e[0].ssrcId}))}findFirstClosedMedia(e){return this.sessionDesc.mediaDescriptions.find((t=>Pv()?\"0\"===t.media.port&&t.media.mediaType===e:\"0\"===t.media.port))}};const fj=[\"sdp\"];var Tj;function Sj(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function gj(e){for(var t=1;t2?arguments[2]:void 0,arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},\"sendonly\"),i={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},n={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},r={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]};if(lj(t,e,\"videoExtensions\",i,n,r),lj(t,e,\"videoCodecs\",i,n,r),lj(t,e,\"audioExtensions\",i,n,r),lj(t,e,\"audioCodecs\",i,n,r),Dy(\"RAISE_H264_BASELINE_PRIORITY\")){const e=r.videoCodecs.findIndex((e=>e.rtpMap&&\"h264\"===e.rtpMap.encodingName.toLocaleLowerCase()&&e.fmtp&&\"42001f\"===e.fmtp.parameters[\"profile-level-id\"]));if(-1!==e){const t=r.videoCodecs.findIndex((e=>e.rtpMap&&\"h264\"===e.rtpMap.encodingName.toLocaleLowerCase()));if(t!(e.rtpMap&&\"h264\"===e.rtpMap.encodingName.toLocaleLowerCase()&&e.fmtp&&\"42001f\"!==e.fmtp.parameters[\"profile-level-id\"]))))}}return{send:i,recv:n,sendrecv:r}}({},{},t);this.remoteSDP=new mj({remoteIceParameters:i.iceParameters,remoteDtlsParameters:i.dtlsParameters,candidates:[],remoteRTPCapabilities:n,localCapabilities:this.localCapabilities,direction:this.direction,setup:\"actpass\",videoCodec:this.store.codec,audioCodec:this.store.audioCodec}),await this.setRemoteDescription({type:\"offer\",sdp:this.remoteSDP.toString()}),this.isReady=!0;const r=await this.peerConnection.createAnswer();if(!r.sdp)throw new Error(\"Cannot get answer sdp when trying to establish PeerConnection.\");const o=ZB(r.sdp);await this.peerConnection.setLocalDescription(r);const s=await dj({},{},r.sdp);this.localCapabilities=hj(s);const a=this.peerConnection.getTransceivers()[0];return null!=a&&a.receiver&&a.receiver.transport&&this.tryBindTransportEvents(a.receiver.transport),gj(gj({},o),{},{sdp:r.sdp})}{this.peerConnection.addTransceiver(\"video\",{direction:\"sendonly\"}),this.peerConnection.addTransceiver(\"audio\",{direction:\"sendonly\"});const e=await this.peerConnection.createOffer();if(!e.sdp)throw new Error(\"Cannot get initialOffer.sdp when trying to establish PeerConnection.\");const t=ZB(e.sdp);return this.initialOffer=e,gj(gj({},t),{},{sdp:e.sdp})}}catch(e){throw new iI(tI.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString())}}async connect(e){try{if(!this.initialOffer)throw new Error(\"Cannot establish P2PConnection without initial offer.\");await this.peerConnection.setLocalDescription(this.initialOffer);const{sdp:t,iceParameters:i,dtlsParameters:n}=e,r=await dj({},{},t);this.remoteSDP=new mj({remoteIceParameters:i,remoteDtlsParameters:n,candidates:[],remoteRTPCapabilities:r,localCapabilities:this.localCapabilities,direction:this.direction,setup:\"active\",videoCodec:this.store.codec,audioCodec:this.store.audioCodec}),await this.setRemoteDescription({type:\"answer\",sdp:this.remoteSDP.toString()});const o=this.peerConnection.getTransceivers()[0];null!=o&&o.sender&&o.sender.transport&&this.tryBindTransportEvents(o.sender.transport)}catch(e){throw new iI(tI.EXCHANGE_SDP_FAILED,\"P2PConnection.connect failed; \".concat(e.toString()))}}async addRemoteCandidate(e){try{e&&this.pendingCandidates.push(e),this.peerConnection.remoteDescription&&this.isReady&&(this.pendingCandidates.forEach((e=>{this.peerConnection.addIceCandidate(e)})),this.pendingCandidates=[])}catch(e){throw new iI(tI.ADD_CANDIDATE_FAILED,\"P2PConnection.addRemoteCandidate failed; \".concat(e.toString()))}}send(e,t,i){var n=this;return pB((function*(){const r=yield rB(n.mutex.lock(\"From P2PConnection.send\"));try{if(!n.remoteSDP)throw new Error(\"Cannot call P2PConnection.send before remote SDP created\");const o=[],s=n.remoteSDP.receive(e,t,i);e.forEach(((e,t)=>{if(s[t].needCreateTransceiver){const t=n.peerConnection.addTransceiver(e._mediaStreamTrack,{direction:\"sendonly\"});o.push(t),e._updateRtpTransceiver(t)}else{const i=n.peerConnection.getTransceivers().find((e=>e.mid===s[t].mid));if(!i)throw new Error(\"cannot find transceiver when sendPeerconnection send, mid is \".concat(s[t].mid));o.push(i),e._updateRtpTransceiver(i)}})),Pv()&&!0===Dy(\"SIMULCAST\")&&(yield rB(n.applySimulcastForFirefox(o,e)));const a=s.map((e=>e.mid)),c=yield rB(n.peerConnection.createOffer()),d=n.mungSendOfferSDP(c.sdp,e,a),l=wB.parse(d),h=a.map((e=>{const t=l.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error(\"Cannot extract ssrc from mediaDescription.\");return $B(t,Dy(\"USE_PUB_RTX\"))})),u=o.map(((e,t)=>{const i=a[t];return{localSSRC:h[t],id:i}}));yield rB(n.peerConnection.setLocalDescription({type:\"offer\",sdp:d}));try{yield u}catch(e){const t=n.remoteSDP.toString();throw yield rB(n.peerConnection.setLocalDescription({type:\"offer\",sdp:d})),yield rB(n.peerConnection.setRemoteDescription({type:\"answer\",sdp:t})),yield rB(n.stopSending(a,!0)),e}yield rB(n.applySimulcastEncodings(o,e)),yield rB(n.applySendEncodings(o,e));const p=n.remoteSDP.toString(),_=n.logSDPExchange(d,\"offer\",\"local\",\"send\");return null==_||_(p),yield rB(n.setRemoteDescription({type:\"answer\",sdp:p})),o.map(((e,t)=>{const i=a[t];return{localSSRC:h[t],id:i}}))}catch(e){throw e instanceof iI?e:new iI(tI.EXCHANGE_SDP_FAILED,\"P2PConnection.send failed; \".concat(e.toString()))}finally{r()}}))()}async stopSending(e,t){const i=t?void 0:await this.mutex.lock(\"From P2PConnection.stopSending\");try{if(!this.remoteSDP)throw new Error(\"Cannot call P2PConnection.stopSending before remote SDP created\");const t=this.peerConnection.getTransceivers().filter((t=>-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error(\"Transceivers' length (\".concat(t.length,\") doesn't match mids' length (\").concat(e.length,\") when trying to call P2PConnection.stopSending.\"));t.map((e=>{var t;e.direction=\"inactive\",null===(t=e.stop)||void 0===t||t.call(e)}));const n=await this.peerConnection.createOffer(),r=this.logSDPExchange(n.sdp||\"\",\"offer\",\"local\",\"stopSending\");await this.peerConnection.setLocalDescription(n),this.remoteSDP.stopReceiving(e);const o=this.remoteSDP.toString();null==r||r(o),await this.setRemoteDescription({type:\"answer\",sdp:o})}catch(e){throw new iI(tI.EXCHANGE_SDP_FAILED,\"P2PConnection.stopSending failed; \".concat(e.toString()))}finally{i&&i()}}async receive(e,t,i,n){try{if(!this.remoteSDP)throw new Error(\"Cannot call P2PConnection.receive \".concat(e,\" before remoteSDP created.\"));const{mid:r,needExchangeSDP:o}=this.remoteSDP.send(e,t,i,n);if(o){const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,\"offer\",\"remote\",\"receive\");await this.setRemoteDescription({type:\"offer\",sdp:t});const n=await this.peerConnection.createAnswer(),o=this.mungReceiveAnswerSDP(n.sdp,r,e);null==i||i(o||\"\"),await this.peerConnection.setLocalDescription({type:\"answer\",sdp:o}),Qy.debug(\"[\".concat(this.store.clientId,\"] [P2PConnection] receive \").concat(e,\" by exchanging SDP.\"))}else Qy.debug(\"[\".concat(this.store.clientId,\"] [P2PConnection] receive \").concat(e,\" no need to exchange SDP.\"));const s=this.peerConnection.getTransceivers().find((e=>e.mid===r));if(!s||null===s.mid)throw new Error(\"Cannot get transceiver after setLocalDescription.\");return{track:s.receiver.track,mid:s.mid,transceiver:s}}catch(e){throw new iI(tI.EXCHANGE_SDP_FAILED,\"P2PConnection.receive failed; \".concat(e.toString()))}}async mockReceive(e,t,i,n){try{if(!this.remoteSDP)throw new Error(\"Cannot call P2PConnection.receive \".concat(e,\" before remoteSDP created.\"));const{mid:r,needExchangeSDP:o}=this.remoteSDP.send(e,t,i,n);if(o){const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,\"offer\",\"remote\",\"receive\");await this.setRemoteDescription({type:\"offer\",sdp:t});const n=await this.peerConnection.createAnswer(),o=this.mungReceiveAnswerSDP(n.sdp,r,e);null==i||i(o||\"\"),await this.peerConnection.setLocalDescription({type:\"answer\",sdp:o}),Qy.debug(\"[\".concat(this.store.clientId,\"] [P2PConnection] receive \").concat(e,\" by exchanging SDP.\"))}else Qy.debug(\"[\".concat(this.store.clientId,\"] [P2PConnection] receive \").concat(e,\" no need to exchange SDP.\"))}catch(e){throw new iI(tI.EXCHANGE_SDP_FAILED,\"P2PConnection.receive failed; \".concat(e.toString()))}}async stopReceiving(e){try{if(!this.remoteSDP)throw new Error(\"Cannot call P2PConnection.stopReceiving before remote SDP created.\");this.remoteSDP.stopSending(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,\"offer\",\"remote\",\"stopReceiving\");await this.setRemoteDescription({type:\"offer\",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||\"\"),await this.peerConnection.setLocalDescription(n)}catch(e){throw new iI(tI.EXCHANGE_SDP_FAILED,\"P2PConnection stopReceiving failed; \".concat(e.toString()))}}async restartICE(t){try{if(this.store.p2pTransport===Ay.Auto&&(this.store.p2pTransport=Ay.SdRtn,_U().supportPCSetConfiguration&&this.peerConnection.setConfiguration(e.resolvePCConfiguration(this.spec,this.store.p2pTransport))),this.restartCnt>3&&(this.restartCnt=0,_U().supportPCSetConfiguration&&this.peerConnection.setConfiguration(e.resolvePCConfiguration(this.spec,this.store.p2pTransport,++this.curTurnServerIndex))),!t){this.restartCnt++,this.isReady=!1;const e=await this.peerConnection.createOffer({iceRestart:!0});if(!e.sdp)throw new Error(\"Cannot restartICE because restart offer SDP does not exist.\");const{iceParameters:t}=ZB(e.sdp);return this.store.descriptionStart(),this.direction===yb.SEND_ONLY&&await this.peerConnection.setLocalDescription(e),t}if(!this.remoteSDP)throw new Error(\"Cannot call P2PConnection.stopReceiving before remote SDP created.\");if(this.remoteSDP.restartICE(t),this.store.descriptionStart(),this.direction===yb.RECEIVE_ONLY){this.restartCnt++,await this.setRemoteDescription({type:\"offer\",sdp:this.remoteSDP.toString()});const e=await this.peerConnection.createAnswer();if(!e.sdp)throw new Error(\"Cannot get answer sdp when trying to iceRestart.\");const{iceParameters:t}=ZB(e.sdp);return await this.peerConnection.setLocalDescription(e),t}await this.setRemoteDescription({type:\"answer\",sdp:this.remoteSDP.toString()}),this.isReady=!0}catch(e){throw new iI(tI.EXCHANGE_SDP_FAILED,\"P2PConnection stopReceiving failed; \".concat(e.toString()))}}close(){var e;this.peerConnection.close(),this.peerConnection.onicecandidate=null,null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,\"closed\"),this.tryUnbindTransportEvents(),this.unbindPCEvents(),this.unbindStatsEvents(),this.transport=void 0,this.statsFilter.destroy()}getStats(){return this.statsFilter.getStats()}getRemoteVideoIsReady(e){return this.statsFilter.getVideoIsReady(e)}async updateEncoderConfig(e,t){try{if(!this.remoteSDP)throw new Error(\"Cannot call P2PConnection.updateEncoderConfig before remote SDP created.\");const i=await this.peerConnection.createOffer(),n=this.mungSendOfferSDP(i.sdp,[t],[e]);this.remoteSDP.updateRecvMedia(e,t);const r=this.remoteSDP.toString(),o=this.logSDPExchange(n,\"offer\",\"local\",\"updateEncoderConfig\");await this.peerConnection.setLocalDescription({type:\"offer\",sdp:n}),null==o||o(r),await this.peerConnection.setRemoteDescription({type:\"answer\",sdp:r})}catch(e){throw new iI(tI.EXCHANGE_SDP_FAILED,e.toString())}}async updateSendParameters(e,t){const i=this.peerConnection.getTransceivers().filter((t=>t.mid===e));1===i.length&&(this.isVP8Simulcast(t)?Pv()||await this.applySimulcastEncodings(i,[t]):await this.applySendEncodings(i,[t]))}setStatsRemoteVideoIsReady(e,t){this.statsFilter.setVideoIsReady2(e,t)}async replaceTrack(e,t){const i=this.peerConnection.getTransceivers().find((e=>e.mid===t));i&&await i.sender.replaceTrack(e._mediaStreamTrack)}async getSelectedCandidatePair(){const e=this.peerConnection.getReceivers();if(e.length>0&&e[0].transport&&e[0].transport.iceTransport&&e[0].transport.iceTransport.getSelectedCandidatePair&&e[0].transport.iceTransport.getSelectedCandidatePair()){const t=e[0].transport.iceTransport,{local:i,remote:n}=t.getSelectedCandidatePair();return{local:gj(gj({},PB),{},{candidateType:i.type,protocol:i.protocol,address:i.address,port:i.port}),remote:gj(gj({},PB),{},{candidateType:n.type,protocol:n.protocol,address:n.address,port:n.port})}}return this.statsFilter.getSelectedCandidatePair()}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var e,t;Dn(e=[\"connected\",\"completed\"]).call(e,this.peerConnection.iceConnectionState)&&(this.isReady=!1),null===(t=this.onICEConnectionStateChange)||void 0===t||t.call(this,this.peerConnection.iceConnectionState)},this.peerConnection.onconnectionstatechange=()=>{var e;\"connected\"===this.peerConnection.connectionState&&(this.restartCnt=0),null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.connectionState)},this.startICECandidate()}startICECandidate(){this.peerConnection.onicecandidate||(this.localCandidateCount=0,this.peerConnection.onicecandidate=e=>{if(e.candidate){var t;if(e.candidate.candidate)null===(t=this.onLocalCandidate)||void 0===t||t.call(this,e.candidate.toJSON());this.localCandidateCount+=1}else Qy.debug(\"[\".concat(this.store.clientId,\"] [pc-\").concat(this.store.p2pId,\"] local candidate count\"),this.localCandidateCount)})}unbindPCEvents(){this.peerConnection.oniceconnectionstatechange=null,this.peerConnection.onconnectionstatechange=null,this.peerConnection.onsignalingstatechange=null,this.peerConnection.onicecandidateerror=null,this.peerConnection.onicecandidate=null,this.peerConnection.ontrack=null}static resolvePCConfiguration(t,i){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;const r={iceServers:[]};var o;t.iceServers?r.iceServers=t.iceServers:t.turnServer&&\"off\"!==t.turnServer.mode&&(bI(t.turnServer.servers)?r.iceServers=t.turnServer.servers:(r.iceServers&&r.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers,i,n)),Dy(\"USE_TURN_SERVER_OF_GATEWAY\")&&r.iceServers&&t.turnServer.serversFromGateway&&r.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway,i,n)),Dn(o=[Ay.Relay,Ay.SdRtn]).call(o,i)&&(r.iceTransportPolicy=\"relay\"),Dy(\"FORCE_TURN_TCP\")?r.iceTransportPolicy=\"relay\":t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach((e=>{e.forceturn&&(r.iceTransportPolicy=\"relay\")}))));return Dy(\"ENABLE_ENCODED_TRANSFORM\")&&_U().supportWebRTCEncodedTransform&&(r.encodedInsertableStreams=!0),Qy.debug(\"P2PConnection p2pTransport is \".concat(i)),r}static turnServerConfigToIceServers(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;const n=[],r=e.filter((e=>e.tcpport));Qy.debug(\"P2PConnection turnServers is \".concat(r,\", current index is \").concat(i));const o=r.length>i?r[i]:r[0];switch(t){case Ay.SdRtn:const t=e.filter((e=>{var t;return Dn(t=e.username).call(t,\"glb:\")&&e.turnServerURL==e.turnServerURL})),r=t.length>i?t[i]:t[0];r&&(n.push({username:r.username,credential:r.password,credentialType:\"password\",urls:\"turn:\".concat(Hw(r.turnServerURL),\":\").concat(r.tcpport,\"?transport=udp\")}),n.push({username:r.username,credential:r.password,credentialType:\"password\",urls:\"turns:\".concat(Hw(r.turnServerURL),\":\").concat(r.tcpport,\"?transport=tcp\")}));break;case Ay.Relay:o&&(n.push({username:o.username,credential:o.password,credentialType:\"password\",urls:\"turn:\".concat(o.turnServerURL,\":\").concat(o.tcpport,\"?transport=udp\")}),n.push({username:o.username,credential:o.password,credentialType:\"password\",urls:\"turns:\".concat(Hw(o.turnServerURL),\":\").concat(o.tcpport,\"?transport=tcp\")}));break;default:o&&(n.push({username:o.username,credential:o.password,credentialType:\"password\",urls:\"turn:\".concat(o.turnServerURL,\":\").concat(o.tcpport,\"?transport=udp\")}),n.push({username:o.username,credential:o.password,credentialType:\"password\",urls:\"turns:\".concat(Hw(o.turnServerURL),\":\").concat(o.tcpport,\"?transport=tcp\")}),n.push({username:o.username,credential:o.password,credentialType:\"password\",urls:\"stun:\".concat(o.turnServerURL,\":\").concat(o.tcpport)}))}return n}tryBindTransportEvents(e){if(e){this.transport=e,e.onstatechange=()=>{var t;null!=e&&e.state&&(null===(t=this.onDTLSTransportStateChange)||void 0===t||t.call(this,e.state))},e.onerror=e=>{var t;null===(t=this.onDTLSTransportError)||void 0===t||t.call(this,\"error\"in e?e.error:e)};const t=e.iceTransport;t&&(t.onstatechange=()=>{const t=null==e?void 0:e.iceTransport.state;var i;t&&(null===(i=this.onICETransportStateChange)||void 0===i||i.call(this,t))},t.getSelectedCandidatePair&&(t.onselectedcandidatepairchange=()=>{if(t.getSelectedCandidatePair()){const{local:e,remote:i}=t.getSelectedCandidatePair();Qy.info(\"[\".concat(this.store.clientId,\"] [pc-\").concat(this.store.p2pId,\"] selectedcandidatepairchange: local \").concat(JSON.stringify({candidateType:e.type,protocol:e.protocol}),\", remote \").concat(JSON.stringify({candidateType:i.type,protocol:i.protocol,address:i.address,port:i.port}),\" )\"))}}))}}tryUnbindTransportEvents(){this.transport&&(this.transport.onstatechange=null,this.transport.onerror=null,this.transport.iceTransport&&(this.transport.iceTransport.onstatechange=null))}async updateRtpSenderEncodings(e,t){var i;if(!t){t=this.peerConnection.getSenders().find((t=>t.track===e._mediaStreamTrack))}if(!t)return Qy.warn(\"[\".concat(e.getTrackId(),\"] no rtpSender found}\"));if(this.isVP8Simulcast(e))return Qy.warn(\"[updateRtpSenderEncodings] Track is VP8 simulcast, please apply simulcast encodings\");if(!_U().supportSetRtpSenderParameters)return Qy.warn(\"[updateRtpSenderEncodings] Browser not support set rtp-sender parameters\");const n={},r={};switch(e._optimizationMode){case\"motion\":n.degradationPreference=\"maintain-framerate\";break;case\"detail\":n.degradationPreference=\"maintain-resolution\";break;default:n.degradationPreference=\"balanced\"}if(e._encoderConfig){var o;const{bitrateMax:t,frameRate:i,scaleResolutionDownBy:n}=e._encoderConfig;t&&(r.maxBitrate=1e3*t),Dn(o=e._hints).call(o,LU.LOW_STREAM)&&(i&&(r.maxFramerate=Yw(i)),n&&n>=1&&(r.scaleResolutionDownBy=n))}if(Dy(\"DSCP_TYPE\")&&Jv()){var s;const e=Dy(\"DSCP_TYPE\");Dn(s=[\"very-low\",\"low\",\"medium\",\"high\"]).call(s,e)&&(r.networkPriority=e)}const a=t.getParameters(),c=null===(i=a.encodings)||void 0===i?void 0:i[0];Pv()&&!c&&(n.encodings=[r]),c&&Object.assign(c,r),Object.assign(a,n),Qy.debug(\"[\".concat(e.getTrackId(),\"] updateRtpSenderEncodings: \").concat(JSON.stringify(a.encodings))),await t.setParameters(a)}async applySendEncodings(e,t){try{if(!_U().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let i=0;i{const r=i[t],o=n.mediaDescriptions.find((e=>e.attributes.mid===r));o&&(ij(o,e),aj(o,e,this.store.codec))})),wB.print(n)}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=e=>{var t;null===(t=this.onFirstAudioReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoReceived=e=>{var t;null===(t=this.onFirstVideoReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstAudioDecoded=e=>{var t;null===(t=this.onFirstAudioDecoded)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoDecoded=(e,t,i)=>{var n;null===(n=this.onFirstVideoDecoded)||void 0===n||n.call(this,e,t,i)},this.statsFilter.onSelectedLocalCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedLocalCandidateChanged)||void 0===i||i.call(this,e,t)},this.statsFilter.onSelectedRemoteCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedRemoteCandidateChanged)||void 0===i||i.call(this,e,t)},this.statsFilter.onFirstVideoDecodedTimeout=e=>{var t;null===(t=this.onFirstVideoDecodedTimeout)||void 0===t||t.call(this,e)}}unbindStatsEvents(){this.statsFilter.onFirstAudioReceived=void 0,this.statsFilter.onFirstVideoReceived=void 0,this.statsFilter.onFirstAudioDecoded=void 0,this.statsFilter.onFirstVideoDecoded=void 0,this.statsFilter.onSelectedLocalCandidateChanged=void 0,this.statsFilter.onSelectedRemoteCandidateChanged=void 0,this.statsFilter.onFirstVideoDecodedTimeout=void 0}async applySimulcastForFirefox(e,t){if(e.length===t.length)for(let a=0;a200&&null!==(o=d._scalabilityMode)&&void 0!==o&&o.numSpatialLayers&&(null===(s=d._scalabilityMode)||void 0===s?void 0:s.numSpatialLayers)>1&&\"vp8\"===this.store.codec){const e={},t={high:1e3*(d._encoderConfig.bitrateMax-50),medium:5e4};e.encodings=[{rid:\"m\",active:!0,maxBitrate:t.medium,scaleResolutionDownBy:4},{rid:\"h\",active:!0,maxBitrate:t.high}];const i=c.sender.getParameters();await c.sender.setParameters(Object.assign(i,e))}}}async applySimulcastEncodings(e,t){if(!Pv()&&e.length===t.length)for(let i=0;i200&&null!==(r=e._scalabilityMode)&&void 0!==r&&r.numSpatialLayers&&(null===(o=e._scalabilityMode)||void 0===o?void 0:o.numSpatialLayers)>1)}logSDPExchange(e,t,i,n){if(Dy(\"SDP_LOGGING\"))return Qy.upload(\"[\".concat(this.store.clientId,\"] exchanging \").concat(i,\" \").concat(t,\" SDP during P2PConnection.\").concat(n,\"\\n\"),e),\"offer\"===t?e=>{this.logSDPExchange(e,\"answer\",\"local\"===i?\"remote\":\"local\",n)}:void 0}async muteLocal(e){try{if(!this.remoteSDP)throw new Error(\"Cannot call P2PConnection.muteLocal before remote SDP created.\");const t=this.peerConnection.getTransceivers().filter((t=>t.mid&&-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error(\"Transceivers' length doesn't match mids' length.\");t.map((e=>{e.direction=\"inactive\"}));const i=await this.peerConnection.createOffer(),n=this.logSDPExchange(i.sdp||\"\",\"offer\",\"local\",\"muteLocal\");await this.peerConnection.setLocalDescription(i),this.remoteSDP.muteRemote(e);const r=this.remoteSDP.toString();null==n||n(r),await this.setRemoteDescription({type:\"answer\",sdp:r})}catch(e){throw new iI(tI.EXCHANGE_SDP_FAILED,\"P2PConnection.muteLocal failed; \".concat(e.toString()))}}async unmuteLocal(e){try{if(!this.remoteSDP)throw new Error(\"Cannot call P2PConnection.unmuteLocal before remote SDP created.\");const t=this.peerConnection.getTransceivers().filter((t=>t.mid&&-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error(\"Transceivers' length doesn't match mids' length.\");t.map((async e=>{e.direction=\"sendonly\"}));const i=await this.peerConnection.createOffer(),n=this.logSDPExchange(i.sdp||\"\",\"offer\",\"local\",\"unmuteLocal\");await this.peerConnection.setLocalDescription(i),this.remoteSDP.unmuteRemote(e);const r=this.remoteSDP.toString();null==n||n(r),await this.setRemoteDescription({type:\"answer\",sdp:r})}catch(e){throw new iI(tI.EXCHANGE_SDP_FAILED,\"P2PConnection.unmuteLocal failed; \".concat(e.toString()))}}async getRemoteSSRC(e,t){var i,n;if(t=null!==(i=t)&&void 0!==i?i:null===(n=this.currentRemoteDescription)||void 0===n?void 0:n.sdp){var r;const i=null===(r=wB.parse(t).mediaDescriptions.find((t=>t.attributes.mid===e)))||void 0===r?void 0:r.attributes.ssrcs;return null==i?void 0:i[0].ssrcId}}async setRemoteDescription(e){var t;await this.peerConnection.setRemoteDescription(e),Dn(t=[\"connected\",\"completed\"]).call(t,this.peerConnection.iceConnectionState)||(this.isReady=!0,this.addRemoteCandidate())}mungReceiveAnswerSDP(e,t,i){const n=wB.parse(e),r=n.mediaDescriptions.find((e=>e.attributes.mid===t));return r&&i===nw.AUDIO&&\"audio\"===r.media.mediaType&&uj(r),wB.print(n)}},nb(Tj.prototype,\"establish\",[Cj],Object.getOwnPropertyDescriptor(Tj.prototype,\"establish\"),Tj.prototype),nb(Tj.prototype,\"connect\",[Cj],Object.getOwnPropertyDescriptor(Tj.prototype,\"connect\"),Tj.prototype),nb(Tj.prototype,\"receive\",[Cj],Object.getOwnPropertyDescriptor(Tj.prototype,\"receive\"),Tj.prototype),nb(Tj.prototype,\"mockReceive\",[Cj],Object.getOwnPropertyDescriptor(Tj.prototype,\"mockReceive\"),Tj.prototype),nb(Tj.prototype,\"stopReceiving\",[Cj],Object.getOwnPropertyDescriptor(Tj.prototype,\"stopReceiving\"),Tj.prototype),nb(Tj.prototype,\"restartICE\",[Cj],Object.getOwnPropertyDescriptor(Tj.prototype,\"restartICE\"),Tj.prototype),nb(Tj.prototype,\"close\",[Cj],Object.getOwnPropertyDescriptor(Tj.prototype,\"close\"),Tj.prototype),nb(Tj.prototype,\"updateEncoderConfig\",[Cj],Object.getOwnPropertyDescriptor(Tj.prototype,\"updateEncoderConfig\"),Tj.prototype),nb(Tj.prototype,\"updateSendParameters\",[Cj],Object.getOwnPropertyDescriptor(Tj.prototype,\"updateSendParameters\"),Tj.prototype),nb(Tj.prototype,\"replaceTrack\",[Cj],Object.getOwnPropertyDescriptor(Tj.prototype,\"replaceTrack\"),Tj.prototype),nb(Tj.prototype,\"muteLocal\",[Cj],Object.getOwnPropertyDescriptor(Tj.prototype,\"muteLocal\"),Tj.prototype),nb(Tj.prototype,\"unmuteLocal\",[Cj],Object.getOwnPropertyDescriptor(Tj.prototype,\"unmuteLocal\"),Tj.prototype),Tj);function Cj(e,t,i){const n=e[t];if(\"function\"!=typeof n)throw new Error(\"Cannot use mutex on object property.\");return i.value=async function(){const e=this.mutex,i=await e.lock(\"From P2PConnection.\".concat(t));try{for(var r=arguments.length,o=new Array(r),s=0;s{if(!i)return n.stopCapture&&n.stopCapture();if(i.paused&&i.play(),i.videoHeight>2&&i.videoWidth>2){const e=i.videoWidth,t=i.videoHeight/e,r=n.width*t;Math.abs(r-n.height)>=2&&(Qy.debug(\"adjust low stream resolution\",\"\".concat(n.width,\"x\").concat(n.height,\" -> \").concat(n.width,\"x\").concat(r)),n.height=r)}s.drawImage(i,0,0,n.width,n.height),c.requestFrame&&c.requestFrame(),o!==e._mediaStreamTrack&&(o=e._mediaStreamTrack,i.srcObject=new MediaStream([o]))},n.stopCapture=ux((()=>n.startCapture&&n.startCapture()),r);const d=c.stop;return c.stop=()=>{d.call(c),i&&(i.remove(),i.srcObject=null,i=null),n&&(n.width=0,n.remove(),n.stopCapture&&n.stopCapture(),n.startCapture=void 0,n.stopCapture=void 0,n=null),Qy.debug(\"clean low stream renderer\")},c}var Ij=function(e){return e[e.HEIGHT=2033]=\"HEIGHT\",e[e.FRAME_RATE=2034]=\"FRAME_RATE\",e[e.WIDTH=2035]=\"WIDTH\",e}(Ij||{}),yj=function(e){return e[e.FRAME_RATE=2002]=\"FRAME_RATE\",e[e.WIDTH=2003]=\"WIDTH\",e[e.HEIGHT=2004]=\"HEIGHT\",e[e.PACKAGE_LOST=2005]=\"PACKAGE_LOST\",e[e.AVG_ENCODE=2007]=\"AVG_ENCODE\",e[e.NACKS=2009]=\"NACKS\",e[e.PLIS=2010]=\"PLIS\",e[e.FIRS=2011]=\"FIRS\",e[e.BITRATE=2012]=\"BITRATE\",e[e.PACKAGE_RATE=2031]=\"PACKAGE_RATE\",e[e.ADAPTATION=2032]=\"ADAPTATION\",e[e.ACTUAL_ENCODED=2060]=\"ACTUAL_ENCODED\",e[e.BANDWIDTH=2061]=\"BANDWIDTH\",e[e.RETRANSMIT=2062]=\"RETRANSMIT\",e[e.TARGET_ENCODED=2064]=\"TARGET_ENCODED\",e[e.TRANSMIT=2066]=\"TRANSMIT\",e[e.FREEZE=2082]=\"FREEZE\",e[e.DISABLED=2095]=\"DISABLED\",e[e.PLAYER_STATUS=2128]=\"PLAYER_STATUS\",e[e.QP_SUM=2143]=\"QP_SUM\",e}(yj||{}),Aj=function(e){return e[e.BITRATE=2069]=\"BITRATE\",e[e.PACKAGE_LOST=2070]=\"PACKAGE_LOST\",e[e.PACKAGE_RATE=2071]=\"PACKAGE_RATE\",e[e.HEIGHT=2073]=\"HEIGHT\",e[e.FRAME_RATE=2075]=\"FRAME_RATE\",e[e.WIDTH=2077]=\"WIDTH\",e}(Aj||{}),bj=function(e){return e[e.JITTER=-1]=\"JITTER\",e[e.PACKAGE_LOST=2014]=\"PACKAGE_LOST\",e[e.WIDTH=2018]=\"WIDTH\",e[e.HEIGHT=2019]=\"HEIGHT\",e[e.FRAME_RATE=2020]=\"FRAME_RATE\",e[e.JITTER_BUFFER=2023]=\"JITTER_BUFFER\",e[e.CURRENT_DELAY=2024]=\"CURRENT_DELAY\",e[e.NACKS=2026]=\"NACKS\",e[e.PLIS=2027]=\"PLIS\",e[e.FIRS=2028]=\"FIRS\",e[e.BITRATE=2029]=\"BITRATE\",e[e.PACKAGE_RATE=2078]=\"PACKAGE_RATE\",e[e.FREEZE=2084]=\"FREEZE\",e[e.DISABLED=2101]=\"DISABLED\",e[e.PLAYER_STATUS=2129]=\"PLAYER_STATUS\",e[e.QP_SUM=2144]=\"QP_SUM\",e[e.I_FRAME_DELAY=2149]=\"I_FRAME_DELAY\",e}(bj||{}),wj=function(e){return e[e.FRAME_RATE_DECODE=2021]=\"FRAME_RATE_DECODE\",e[e.FRAME_RATE_RENDER=2022]=\"FRAME_RATE_RENDER\",e[e.FRAME_RATE_OUTPUT=2155]=\"FRAME_RATE_OUTPUT\",e[e.FREEZE_TIME=2109]=\"FREEZE_TIME\",e[e.FREEZE_TIME_RENDER=2147]=\"FREEZE_TIME_RENDER\",e[e.FREEZE_DURATION=2156]=\"FREEZE_DURATION\",e}(wj||{}),Oj=function(e){return e[e.PCM_LEVEL=2104]=\"PCM_LEVEL\",e}(Oj||{}),Nj=function(e){return e[e.PACKAGE_LOST=-1]=\"PACKAGE_LOST\",e[e.LEVEL=2038]=\"LEVEL\",e[e.BITRATE=2039]=\"BITRATE\",e[e.PACKAGE_RATE=2040]=\"PACKAGE_RATE\",e[e.AEC_RETURN_LOSS=2041]=\"AEC_RETURN_LOSS\",e[e.AEC_RETURN_LOSS_ENH=2042]=\"AEC_RETURN_LOSS_ENH\",e[e.FREEZE=2081]=\"FREEZE\",e[e.DISABLED=2096]=\"DISABLED\",e}(Nj||{}),Dj=function(e){return e[e.BITRATE=2044]=\"BITRATE\",e[e.PACKAGE_LOST=2045]=\"PACKAGE_LOST\",e[e.PACKAGE_RATE=2046]=\"PACKAGE_RATE\",e[e.CURRENT_DELAY=2047]=\"CURRENT_DELAY\",e[e.JITTER_BUFFER=2054]=\"JITTER_BUFFER\",e[e.JITTER=2055]=\"JITTER\",e[e.FREEZE=2083]=\"FREEZE\",e[e.DISABLED=2102]=\"DISABLED\",e[e.PCM_LEVEL=2105]=\"PCM_LEVEL\",e[e.PLAYER_STATUS=2130]=\"PLAYER_STATUS\",e[e.CONCEALED_SAMPLES=2148]=\"CONCEALED_SAMPLES\",e}(Dj||{}),Pj=function(e){return e[e.FREEZE_TIME=-1]=\"FREEZE_TIME\",e[e.LEVEL=2043]=\"LEVEL\",e}(Pj||{}),Lj=function(e){return e[e.RTT=2006]=\"RTT\",e[e.CONN_TYPE=801]=\"CONN_TYPE\",e}(Lj||{});const kj=1e3,Mj=3;function Uj(e,t,i){null!=i&&Number.isFinite(i)&&(e[t]=Math.round(Math.max(0,i)))}function xj(e){const t={[Lj.CONN_TYPE]:0,[Lj.RTT]:e.rtt};switch(e.selectedCandidatePair.localCandidate.candidateType){case\"relay\":{const i=e.selectedCandidatePair.localCandidate.relayProtocol;\"udp\"===i&&(t[Lj.CONN_TYPE]=1),\"tcp\"===i&&(t[Lj.CONN_TYPE]=3),\"tls\"===i&&(t[Lj.CONN_TYPE]=4);break}case\"srflx\":t[Lj.CONN_TYPE]=2}return t}function Vj(e){let t=0;switch(e){case\"none\":t=0;break;case\"cpu\":t=1;break;case\"bandwidth\":t=2;break;case\"other\":t=3}return t}class Fj extends SI{constructor(e){super(),ng(this,\"store\",void 0),ng(this,\"uploadWRTCStatsTimer\",void 0),ng(this,\"uploadOutboundDenoiserStatsTimer\",void 0),ng(this,\"uploadExtStatsTimer\",void 0),ng(this,\"uploadExtUsageStatsTimer\",void 0),ng(this,\"uploadInboundExtStatsTimer\",void 0),ng(this,\"requestStats\",void 0),ng(this,\"requestTransportStats\",void 0),ng(this,\"requestLocalMedia\",void 0),ng(this,\"requestRemoteMedia\",void 0),ng(this,\"requestAllTracks\",void 0),ng(this,\"requestVideoIsReady\",void 0),ng(this,\"requestUploadStats\",void 0),ng(this,\"requestUpload\",void 0),ng(this,\"uploadOutboundStarted\",!1),ng(this,\"uploadInboundStarted\",!1),ng(this,\"uploadTransportStarted\",!1),ng(this,\"uploadExtensionUsageStarted\",!1),ng(this,\"lastRecvStats\",void 0),ng(this,\"lastSendStats\",void 0),ng(this,\"lastFullRecvStats\",void 0),ng(this,\"lastFullSendStats\",void 0),ng(this,\"needUploadRenderFreezeTime\",!0),this.store=e}uploadWRTCStats(e){if(!this.requestStats||!this.requestUploadStats)return;let t,i;if(this.uploadTransportStarted&&(t=this.requestStats(),this.store.useP2P&&(i=this.requestStats(!0))),!t&&this.uploadOutboundStarted&&(t=this.requestStats()),!i&&this.uploadInboundStarted&&(i=this.requestStats(!0)),t||i){const n={};if(this.uploadTransportStarted&&t){const r=this.getTransportStats(t,i,e);r&&(n.misc=[r])}if(this.uploadOutboundStarted&&t){const i=this.getOutboundStats(t,e?this.lastSendStats:this.lastFullSendStats,e);i&&(n.outbound=[i])}if(this.uploadInboundStarted&&i){const t=this.getInboundStats(i,e?this.lastRecvStats:this.lastFullRecvStats,e);t&&(n.inbound=t)}this.requestUploadStats(n)}this.lastRecvStats=i,this.lastSendStats=t,e||(this.lastFullRecvStats=i,this.lastFullSendStats=t)}startUploadWRTCStats(){if(this.uploadWRTCStatsTimer)return;let e=1;this.uploadWRTCStatsTimer=window.setInterval((()=>{if(!this.uploadTransportStarted&&!this.uploadInboundStarted&&!this.uploadOutboundStarted)return this.stopUploadWRTCStats();this.uploadWRTCStats(e!==Mj),++e===Mj+1&&(e=1)}),kj)}stopUploadWRTCStats(){window.clearInterval(this.uploadWRTCStatsTimer),this.uploadWRTCStatsTimer=void 0,this.lastSendStats&&(this.lastSendStats.videoSend=[],this.lastSendStats.audioSend=[],this.lastSendStats=void 0),this.lastRecvStats&&(this.lastRecvStats.videoRecv=[],this.lastRecvStats.audioRecv=[],this.lastRecvStats=void 0)}getTransportStats(e,t,i){if(!this.requestStats)return;if(i)return null==e.rtt?void 0:{addition:{[Lj.RTT]:e.rtt,[Lj.CONN_TYPE]:void 0}};const n=xj(e);if(this.store.useP2P){if(t){const e=xj(t);n[Lj.CONN_TYPE]+=e[Lj.CONN_TYPE]<<3}n[Lj.CONN_TYPE]+=110}else n[Lj.CONN_TYPE]+=100;return{addition:n}}getOutboundStats(e,t,i){if(!this.requestUploadStats||!this.requestLocalMedia)return;const n=this.requestLocalMedia();if(!n||0===n.length)return;let r,o,s;return n.forEach((n=>{let[a,{track:c,ssrcs:d}]=n;switch(a){case sw.LocalVideoLowTrack:case sw.LocalVideoTrack:if(a===sw.LocalVideoTrack){const n=function(e,t,i,n,r){const o=t.videoSend.find((t=>t.ssrc===e));if(!o)return;const s={},{sentFrame:a,inputFrame:c}=o;if(c&&a){const e=c.frameRate,t=a.frameRate;s[yj.FREEZE]=function(e,t){let i=!0;return i=!(e<=5)&&(e<=10?t<3:e<=20?t<4:t<5),i}(e,t)?1:0}if(Uj(s,yj.QP_SUM,o.qpSumPerFrame),r)return s;switch(a&&(Uj(s,yj.HEIGHT,a.height),Uj(s,yj.WIDTH,a.width),Uj(s,yj.FRAME_RATE,a.frameRate)),s[yj.DISABLED]=n._originMediaStreamTrack&&!n._originMediaStreamTrack.enabled||n._mediaStreamTrack&&!n._mediaStreamTrack.enabled?1:0,o.adaptionChangeReason){case\"none\":s[yj.ADAPTATION]=0;break;case\"cpu\":s[yj.ADAPTATION]=1;break;case\"bandwidth\":s[yj.ADAPTATION]=2;break;case\"other\":s[yj.ADAPTATION]=3}let d=0;o.adaptionChangeReason&&(d+=Vj(o.adaptionChangeReason)),t.qualityLimitationReason&&(d+=Vj(t.qualityLimitationReason)<<3),s[yj.ADAPTATION]=d,s[yj.PLAYER_STATUS]=ZU[n._player?n._player.videoElementStatus:\"uninit\"],Uj(s,yj.NACKS,o.nacksCount),Uj(s,yj.PLIS,o.plisCount),Uj(s,yj.FIRS,o.firsCount),Uj(s,yj.AVG_ENCODE,o.avgEncodeMs);const l=i&&i.videoSend.find((t=>t.ssrc===e));if(l){let e=r?kj:kj*Mj;l.timestamp&&o.timestamp&&(e=o.timestamp-l.timestamp),null!=l.packets&&null!=o.packets&&Uj(s,yj.PACKAGE_RATE,1e3*(o.packets-l.packets)/e),null!=o.packetsLost&&null!=l.packetsLost&&Uj(s,yj.PACKAGE_LOST,o.packetsLost-l.packetsLost),null!=l.bytes&&null!=o.bytes&&Uj(s,yj.BITRATE,8*(o.bytes-l.bytes)/e)}return s}(d[0].ssrcId,e,t,c,i),r=i?null:function(e,t,i){const n=t.videoSend.find((t=>t.ssrc===e));if(!n)return null;const r={},o=n.inputFrame,s=o&&o.height||i&&i.videoHeight||0,a=o&&o.width||i&&i.videoWidth||0,c=o&&o.frameRate||0;return Uj(r,Ij.HEIGHT,s),Uj(r,Ij.WIDTH,a),Uj(r,Ij.FRAME_RATE,c),r}(d[0].ssrcId,e,c),s=i?null:function(e){const t={};return Uj(t,yj.RETRANSMIT,e.bitrate.retransmit),Uj(t,yj.TARGET_ENCODED,e.bitrate.targetEncoded),Uj(t,yj.ACTUAL_ENCODED,e.bitrate.actualEncoded),Uj(t,yj.TRANSMIT,e.bitrate.transmit),Uj(t,yj.BANDWIDTH,e.sendBandwidth),t}(e);o=Object.assign({},n,r,s)}else s=i?void 0:function(e,t,i){const n=t.videoSend.find((t=>t.ssrc===e));if(!n)return;const r={},o=n.sentFrame;if(o&&(Uj(r,Aj.HEIGHT,o.height),Uj(r,Aj.WIDTH,o.width),Uj(r,Aj.FRAME_RATE,o.frameRate)),i){const t=i.videoSend.find((t=>t.ssrc===e));if(t){let e=kj*Mj;t.timestamp&&n.timestamp&&(e=n.timestamp-t.timestamp),null!=t.packets&&null!=n.packets&&Uj(r,Aj.PACKAGE_RATE,1e3*(n.packets-t.packets)/e),null!=n.packetsLost&&null!=t.packetsLost&&Uj(r,Aj.PACKAGE_LOST,n.packetsLost-t.packetsLost),null!=t.bytes&&null!=n.bytes&&Uj(r,Aj.BITRATE,8*(n.bytes-t.bytes)/e)}}return r}(d[0].ssrcId,e,t);break;case sw.LocalAudioTrack:r=i?void 0:function(e,t,i,n){const r=t.audioSend.find((t=>t.ssrc===e));if(!r)return;const o={};o[Nj.DISABLED]=n._originMediaStreamTrack&&!n._originMediaStreamTrack.enabled||n._mediaStreamTrack&&!n._mediaStreamTrack.enabled?1:0;const s=100*n._source.getAccurateVolumeLevel(),a=r.inputLevel;if(null!=a){const e=Math.ceil(50*Math.log10(100*a+1));Uj(o,Nj.LEVEL,e)}Uj(o,Oj.PCM_LEVEL,s),Uj(o,Nj.AEC_RETURN_LOSS,r.aecReturnLoss),Uj(o,Nj.AEC_RETURN_LOSS_ENH,r.aecReturnLossEnhancement),o[Nj.FREEZE]=0;const c=i&&i.audioSend.find((t=>t.ssrc===e));if(c){let e=kj*Mj;c.timestamp&&r.timestamp&&(e=r.timestamp-c.timestamp),null!=c.bytes&&null!=r.bytes&&Uj(o,Nj.BITRATE,8*(r.bytes-c.bytes)/e),null!=c.packets&&null!=r.packets&&Uj(o,Nj.PACKAGE_RATE,1e3*(r.packets-c.packets)/e)}return o}(d[0].ssrcId,e,t,c)}})),{high:o,low:s,audio:r}}getInboundStats(e,t,i){if(!this.requestRemoteMedia)return;const n=this.requestRemoteMedia()||[],r=[];return n.forEach((n=>{let[o,s]=n;const a={peer:o.uid};if(s.has(nw.VIDEO)&&o.videoTrack){const n=o._videoSSRC&&this.requestVideoIsReady&&this.requestVideoIsReady(o._videoSSRC)||!1,r=o.videoTrack?function(e,t,i,n,r,o,s){var a;const c=t.videoRecv.find((t=>t.ssrc===e));if(!c)return;const d={},{receivedFrame:l,outputFrame:h,decodeFrameRate:u}=c,p=i&&i.videoRecv.find((t=>t.ssrc===e));if(d[bj.FREEZE]=r&&dG.isRemoteVideoFreeze(n,c,p)?1:0,Uj(d,wj.FRAME_RATE_DECODE,u),Uj(d,bj.QP_SUM,c.qpSumPerFrame),c.framesRateFirefox&&Uj(d,bj.FRAME_RATE,c.framesRateFirefox),l&&Uj(d,bj.FRAME_RATE,l.frameRate),p){const e=t.timestamp-i.timestamp||(s?kj:Mj*kj);null!=c.packetsLost&&null!=p.packetsLost&&Uj(d,bj.PACKAGE_LOST,c.packetsLost-p.packetsLost),null!=p.bytes&&null!=c.bytes&&Uj(d,bj.BITRATE,8*(c.bytes-p.bytes)/e),null!=p.packets&&null!=c.packets&&Uj(d,bj.PACKAGE_RATE,1e3*(c.packets-p.packets)/e)}if(s)return d;l?(Uj(d,bj.HEIGHT,l.height),Uj(d,bj.WIDTH,l.width)):n&&(Uj(d,bj.HEIGHT,n._videoHeight||0),Uj(d,bj.WIDTH,n._videoWidth||0)),h&&Uj(d,wj.FRAME_RATE_OUTPUT,h.frameRate);const _=null===(a=n._player)||void 0===a?void 0:a.rendFrameRate.toFixed(0);if(_&&Uj(d,wj.FRAME_RATE_RENDER,+_),Uj(d,bj.JITTER_BUFFER,c.jitterBufferMs),Uj(d,bj.CURRENT_DELAY,c.currentDelayMs),Uj(d,bj.FIRS,c.firsCount),Uj(d,bj.NACKS,c.nacksCount),Uj(d,bj.PLIS,c.plisCount),n){d[bj.DISABLED]=n._originMediaStreamTrack.enabled&&n._mediaStreamTrack.enabled?0:1;const e=n._player;if(e){const{freezeTimeCounterList:t,renderFreezeAccTime:i,videoElementStatus:n}=e;if(t&&t.length>0&&Uj(d,wj.FREEZE_TIME,t.splice(0,1)[0]),o&&\"visible\"===jF.visibility&&n===XU.PLAYING&&_U().supportRequestVideoFrameCallback){const t=Math.min(6e3,i);e.renderFreezeAccTime=Math.max(0,i-t),Uj(d,wj.FREEZE_TIME_RENDER,t)}if(\"number\"==typeof c.totalFreezesDuration){const e=p&&p.totalFreezesDuration?c.totalFreezesDuration-p.totalFreezesDuration:c.totalFreezesDuration;Uj(d,wj.FREEZE_DURATION,1e3*e)}}}if(d[bj.PLAYER_STATUS]=ZU[n._player?n._player.videoElementStatus:\"uninit\"],p&&void 0!==c.totalInterFrameDelay&&void 0!==c.totalSquaredInterFrameDelay&&void 0!==p.totalInterFrameDelay&&void 0!==p.totalSquaredInterFrameDelay){const e=c.totalInterFrameDelay-p.totalInterFrameDelay,t=c.totalSquaredInterFrameDelay-p.totalSquaredInterFrameDelay,i=c.framesDecodeCount-p.framesDecodeCount,n=e/i*1e3,r=Math.round(1e3*Math.sqrt((t-Math.pow(e,2)/i)/i));!isNaN(r)&&n+r>Math.max(3*n,n+150)&&(d[bj.I_FRAME_DELAY]=r)}return d}(o._videoSSRC,e,t,o.videoTrack,!0===n,this.needUploadRenderFreezeTime,i):void 0;r&&(a.video=r)}if(s.has(nw.AUDIO)&&o.audioTrack){const n=o.audioTrack?function(e,t,i,n,r){const o=t.audioRecv.find((t=>t.ssrc===e));if(!o)return;const s={},a=i&&i.audioRecv.find((t=>t.ssrc===e)),{receivedFrames:c,droppedFrames:d}=o;var l,h;if(Uj(s,Dj.JITTER,o.jitterMs),null!=c&&null!=d&&(s[Dj.FREEZE]=(h=d,0===(l=c)||100*h/l>20?1:0)),a){const e=t.timestamp-i.timestamp||(r?kj:kj*Mj);null!=o.packets&&null!=a.packets&&Uj(s,Dj.PACKAGE_RATE,1e3*(o.packets-a.packets)/e),null!=a.bytes&&null!=o.bytes&&Uj(s,Dj.BITRATE,8*(o.bytes-a.bytes)/e),null!=o.packetsLost&&null!=a.packetsLost&&Uj(s,Dj.PACKAGE_LOST,o.packetsLost-a.packetsLost)}if(r)return s;const u=100*n._source.getAccurateVolumeLevel(),p=o.outputLevel;if(null!=p){const e=Math.ceil(50*Math.log10(100*p+1));Uj(s,Pj.LEVEL,e)}if(Uj(s,Dj.PCM_LEVEL,u),n&&(s[Dj.DISABLED]=n._originMediaStreamTrack.enabled&&n._mediaStreamTrack.enabled?0:1),Uj(s,Dj.JITTER_BUFFER,o.jitterBufferMs),Uj(s,Dj.CURRENT_DELAY,o.jitterBufferMs),s[Dj.PLAYER_STATUS]=ZU[Px.getPlayerState(n.getTrackId())],a){const e=o.concealedSamples-a.concealedSamples;e>0&&Uj(s,Dj.CONCEALED_SAMPLES,e)}return s}(o._audioSSRC,e,t,o.audioTrack,i):void 0;n&&(a.audio=n)}(a.video||a.audio)&&r.push(a)})),this.needUploadRenderFreezeTime=!this.needUploadRenderFreezeTime,r}startUploadTransportStats(){this.uploadTransportStarted=!0,this.uploadWRTCStatsTimer||this.startUploadWRTCStats()}stopUploadTransportStats(){this.uploadTransportStarted=!1}startUploadOutboundStats(){this.uploadOutboundStarted||(this.uploadOutboundStarted=!0,this.uploadWRTCStatsTimer||this.startUploadWRTCStats(),this.uploadOutboundDenoiserStatsTimer&&window.clearInterval(this.uploadOutboundDenoiserStatsTimer),this.uploadOutboundDenoiserStatsTimer=window.setInterval((()=>{if(!this.requestAllTracks||!this.requestUpload)return;const e=(this.requestAllTracks()||[]).find((e=>e instanceof kV));if(e&&e._external.getDenoiserStats){const t=e._external.getDenoiserStats();t&&this.requestUpload(vb.DENOISER_STATS,t)}}),2e3),this.uploadExtStatsTimer&&window.clearInterval(this.uploadExtStatsTimer),this.uploadExtStatsTimer=window.setInterval((()=>{if(!this.requestAllTracks||!this.requestUpload)return;this.requestAllTracks().forEach((e=>{e.getProcessorStats().forEach((e=>{this.requestUpload&&this.requestUpload(e.type,e.stats)}))}))}),2e3))}stopUploadOutboundStats(){this.uploadOutboundStarted&&(this.uploadOutboundStarted=!1,this.lastSendStats&&(this.lastSendStats.videoSend=[],this.lastSendStats.audioSend=[],this.lastSendStats=void 0),this.uploadOutboundDenoiserStatsTimer&&window.clearInterval(this.uploadOutboundDenoiserStatsTimer),this.uploadOutboundDenoiserStatsTimer=void 0)}startUploadInboundStats(){this.uploadInboundStarted||(this.uploadInboundStarted=!0,this.uploadWRTCStatsTimer||this.startUploadWRTCStats(),this.uploadInboundExtStatsTimer&&window.clearInterval(this.uploadInboundExtStatsTimer),this.uploadInboundExtStatsTimer=window.setInterval((()=>{if(!this.requestUpload||!this.requestRemoteMedia)return;(this.requestRemoteMedia()||[]).forEach((e=>{let[t,i]=e;if(i.has(nw.VIDEO)&&t.videoTrack){t.videoTrack.getProcessorStats().forEach((e=>{this.requestUpload&&this.requestUpload(e.type,e.stats)}))}if(i.has(nw.AUDIO)&&t.audioTrack){t.audioTrack.getProcessorStats().forEach((e=>{this.requestUpload&&this.requestUpload(e.type,e.stats)}))}}))}),2e3))}stopUploadInboundStats(){this.uploadInboundStarted&&(this.uploadInboundStarted=!1,this.lastRecvStats&&(this.lastRecvStats.videoRecv=[],this.lastRecvStats.audioRecv=[],this.lastRecvStats=void 0))}startUploadExtensionUsageStats(){if(this.uploadExtensionUsageStarted)return;this.uploadExtensionUsageStarted=!0,this.uploadExtUsageStatsTimer&&window.clearInterval(this.uploadExtUsageStatsTimer);const e=new Map;this.uploadExtUsageStatsTimer=window.setInterval((async()=>{const t=Date.now(),i={connectionInterval:Dy(\"EXTENSION_USAGE_UPLOAD_INTERVAL\")/1e3,details:[],lts:t};let n=[];const r=this.requestAllTracks&&this.requestAllTracks()||[];for(const e of r)!e.muted&&e.enabled&&(n=n.concat(await e.getProcessorUsage()));const o=this.requestRemoteMedia&&this.requestRemoteMedia()||[];for(const[e,t]of o)t.has(nw.VIDEO)&&e.videoTrack&&(n=n.concat(await e.videoTrack.getProcessorUsage())),t.has(nw.AUDIO)&&e.audioTrack&&(n=n.concat(await e.audioTrack.getProcessorUsage()));if(0===n.length)return;i.details=function(e,t){const i={};for(const{id:s,value:a,level:c,direction:d}of e){var n;const e=null!==(n=t.get(s))&&void 0!==n?n:0,l=2===a?e+Dy(\"EXTENSION_USAGE_UPLOAD_INTERVAL\")/1e3:e;var r,o;t.set(s,l),i[s]?(2===a&&(i[s].value=a),c>i[s].level&&(i[s].level=c),\"remote\"===d&&(i[s].remoteUidCount+=1),i[s].totalTs=null!==(r=t.get(s))&&void 0!==r?r:0):i[s]={value:a,level:c,remoteUidCount:\"local\"===d?0:1,totalTs:null!==(o=t.get(s))&&void 0!==o?o:0}}return Object.keys(i).map((e=>{const{level:t,value:n,totalTs:r}=i[e];return{id:e,level:t,value:n,totalTs:r}}))}(n,e);const s=Date.now(),a=s>t?s:t+1;this.requestUpload&&this.requestUpload(vb.EXTENSION_USAGE_STATS,{usageStats:i,sendTs:a})}),Dy(\"EXTENSION_USAGE_UPLOAD_INTERVAL\"))}stopUploadExtensionUsageStats(){this.uploadExtensionUsageStarted&&(this.uploadExtensionUsageStarted=!1,this.uploadExtUsageStatsTimer&&window.clearInterval(this.uploadExtUsageStatsTimer),this.uploadExtUsageStatsTimer=void 0)}}class Bj{get hasVideo(){return this._video_enabled_&&!this._video_muted_&&this._video_added_}get hasAudio(){return this._audio_enabled_&&!this._audio_muted_&&this._audio_added_}get audioTrack(){if(this.hasAudio||this._audio_pre_subscribed)return this._audioTrack}get videoTrack(){if(this.hasVideo||this._video_pre_subscribed)return this._videoTrack}get dataChannels(){return this._dataChannels}constructor(e,t){ng(this,\"uid\",void 0),ng(this,\"_uintid\",void 0),ng(this,\"_trust_in_room_\",!0),ng(this,\"_trust_audio_enabled_state_\",!0),ng(this,\"_trust_video_enabled_state_\",!0),ng(this,\"_trust_audio_mute_state_\",!0),ng(this,\"_trust_video_mute_state_\",!0),ng(this,\"_audio_muted_\",!1),ng(this,\"_video_muted_\",!1),ng(this,\"_audio_enabled_\",!0),ng(this,\"_video_enabled_\",!0),ng(this,\"_audio_added_\",!1),ng(this,\"_video_added_\",!1),ng(this,\"_is_pre_created\",!1),ng(this,\"_video_pre_subscribed\",!1),ng(this,\"_audio_pre_subscribed\",!1),ng(this,\"_trust_video_stream_added_state_\",!0),ng(this,\"_trust_audio_stream_added_state_\",!0),ng(this,\"_audioTrack\",void 0),ng(this,\"_videoTrack\",void 0),ng(this,\"_dataChannels\",[]),ng(this,\"_audioSSRC\",void 0),ng(this,\"_videoSSRC\",void 0),ng(this,\"_audioOrtc\",void 0),ng(this,\"_videoOrtc\",void 0),ng(this,\"_cname\",void 0),ng(this,\"_rtxSsrcId\",void 0),ng(this,\"_videoMid\",void 0),ng(this,\"_audioMid\",void 0),this.uid=e,this._uintid=t}}let jj=function(e){return e.SEND_ONLY=\"SEND_ONLY\",e.RECEIVE_ONLY=\"RECEIVE_ONLY\",e}({});function Gj(e,t){var i;let n;switch(t){case sw.LocalAudioTrack:n=Kb.Audio;break;case sw.LocalVideoTrack:n=Dn(i=e._hints).call(i,LU.SCREEN_TRACK)?Kb.Screen:Kb.High;break;case sw.LocalVideoLowTrack:n=Kb.Low}return n}function Wj(e){const t=_U();if(e.some((e=>e._bypassWebAudio)))throw new iI(tI.NOT_SUPPORTED,\"cannot publish multiple tracks which one of them configured with bypassWebAudio\");if(!t.webAudioMediaStreamDest)throw new iI(tI.NOT_SUPPORTED,\"cannot publish multiple tracks because your browser does not support audio mixing\")}function Hj(e,t){Wj(e);const i=t||new UV;return e.forEach((e=>i.addAudioTrack(e))),i}var Kj,Yj,qj,zj,Jj,Xj,Qj,Zj,$j,eG,tG,iG;function nG(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function rG(e){for(var t=1;t{const n=await this.sendMutex.lock(\"Locking from P2PChannel2.handleMuteLocalTrack\");try{if(!this.sendConnection||this.state!==aw.Connected)return void i(new iI(tI.INVALID_OPERATION,\"Cannot call P2PChannel2.handleMuteLocalTrack before sendConnection established.\"));const s=this.filterTobeMutedTracks(e);if(0===s.length)return void t();const a=s.find((e=>\"videoLowTrack\"===e[0]));if(a){a[1].track._originMediaStreamTrack.stop()}await this.sendConnection.muteLocal(s.map((e=>{let[,{id:t}]=e;return t})));let c=!1;var r,o;if(\"video\"===e.trackMediaType)c=!(null===(r=this.localTrackMap.get(sw.LocalAudioTrack))||void 0===r||!r.track._muted);else c=void 0===(null===(o=this.localTrackMap.get(sw.LocalVideoTrack))||void 0===o?void 0:o.id);const d=this.createMuteMessage(s);await MI(this,cw.RequestMuteLocal,d);const l=\"video\"===e.trackMediaType?gw.MUTE_LOCAL_VIDEO:gw.MUTE_LOCAL_AUDIO;await MI(this,cw.RequestP2PMuteLocal,{action:l,message:d,isMuteAll:c}),t()}catch(e){i(e)}finally{n()}})),ng(this,\"handleUnmuteLocalTrack\",(async(e,t,i)=>{const n=await this.sendMutex.lock(\"Locking from P2PChannel2.handleUnmuteLocalTrack\");try{if(!this.sendConnection||this.state!==aw.Connected)return void i(new iI(tI.INVALID_OPERATION,\"Cannot call P2PChannel2.handleUnmuteLocalTrack before sendConnection established.\"));const r=this.filterTobeUnmutedTracks(e);if(0===r.length)return void t();await this.sendConnection.unmuteLocal(r.map((e=>{let[,{id:t}]=e;return t})));const o=this.createUnmuteMessage(r),s=\"video\"===e.trackMediaType?gw.UNMUTE_LOCAL_VIDEO:gw.UNMUTE_LOCAL_AUDIO;await MI(this,cw.RequestP2PMuteLocal,{action:s,message:o}),t()}catch(e){i(e)}finally{n()}})),ng(this,\"handleUpdateVideoEncoder\",(async(e,t,i)=>{const n=await this.sendMutex.lock(\"Locking from P2PChannel2.handleSetVideoEncoder\");try{const i=this.localTrackMap.get(sw.LocalVideoTrack);if(!this.sendConnection||!i||i.track!==e||this.state!==aw.Connected)return void t();const{id:r,track:o}=i;r&&(await this.sendConnection.updateSendParameters(r,o),await this.sendConnection.updateEncoderConfig(r,o),this.emit(cw.UpdateVideoEncoder,o)),t()}catch(e){i(e)}finally{n()}})),ng(this,\"handleUpdateVideoSendParameters\",(async(e,t,i)=>{const n=await this.sendMutex.lock(\"Locking from P2PChannel2.handleUpdateVideoSendParameters\");try{const i=this.localTrackMap.get(sw.LocalVideoTrack);if(!this.sendConnection||!i||i.track!==e||this.state!==aw.Connected)return void t();const{id:r,track:o}=i;r&&await this.sendConnection.updateSendParameters(r,o),t()}catch(e){i(e)}finally{n()}})),ng(this,\"handleReplaceTrack\",(async(e,t,i,n)=>{let r;Qy.debug(\"[\".concat(this.store.clientId,\"] P2PChannel2 handleReplaceTrack for [track-id-\").concat(e.getTrackId(),\"]\")),\"boolean\"==typeof n&&n||(r=await this.sendMutex.lock(\"From P2PChannel2.handleReplaceTrack\"));try{var o;const i=Array.from(this.localTrackMap.entries()).find((t=>{let[,{track:i}]=t;return e===i}));if(!this.sendConnection||!i||void 0===i[1].id||this.state!==aw.Connected)return void t();if(await(null===(o=this.sendConnection)||void 0===o?void 0:o.replaceTrack(e,i[1].id)),i[0]===sw.LocalVideoTrack&&_U().supportDualStreamEncoding){const t=this.localTrackMap.get(sw.LocalVideoLowTrack);if(t){const i=e._mediaStreamTrack.clone();t.track._originMediaStreamTrack.stop(),t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i,await new Gu(((e,i)=>{this.handleReplaceTrack(t.track,e,i,!0)}))}}t()}catch(e){i(e)}finally{var s;null===(s=r)||void 0===s||s()}})),ng(this,\"handleGetLocalVideoStats\",(e=>{e(this.statsCollector.getLocalVideoTrackStats())})),ng(this,\"handleGetLocalAudioStats\",(e=>{e(this.statsCollector.getLocalAudioTrackStats())})),ng(this,\"handleGetRemoteVideoStats\",(e=>this.statsCollector.getRemoteVideoTrackStats(e.uid)[e.uid])),ng(this,\"handleGetRemoteAudioStats\",(e=>this.statsCollector.getRemoteAudioTrackStats(e.uid)[e.uid])),this.store=e,this.statsCollector=t,this.statsCollector.addP2PChannel(this),this.statsUploader=new Fj(e),this.bindStatsUploaderEvents(),this.reconnectInterval=window.setInterval((()=>{[this.sendConnection,this.recvConnection].forEach((e=>{e&&(\"disconnected\"!==e.iceConnectionState&&\"failed\"!==e.iceConnectionState||this.handleDisconnect(e.direction))}))}),Dy(\"ICE_RESTART_INTERVAL\"))}async startP2PConnection(e,t){throw new iI(tI.NOT_SUPPORTED,\"p2p mode does not support startP2PConnection.\")}async connect(e,t,i,n,r,o){throw new iI(tI.NOT_SUPPORTED,\"p2p mode does not support connect.\")}async startP2P(e,t){let i;try{if(t){this.recvConnection&&(Qy.warning(\"[\".concat(this.store.clientId,\"] P2PChannel.startP2P reset recvConnection.\")),this.recvConnection.close(),this.unbindConnectionEvents(this.recvConnection)),i=await this.recvMutex.lock(\"From P2PChannel.startP2P\"),this.recvConnection=new Rj(e,this.store,yb.RECEIVE_ONLY),this.bindConnectionEvents(this.recvConnection);const n=await this.recvConnection.establish(t);return{iceParameters:n.iceParameters,dtlsParameters:n.dtlsParameters,sdp:n.sdp}}{this.state=aw.New,this.sendConnection&&(Qy.warning(\"[\".concat(this.store.clientId,\"] P2PChannel.startP2P reset sendConnection.\")),this.sendConnection.close(),this.unbindConnectionEvents(this.sendConnection)),i=await this.sendMutex.lock(\"From P2PChannel.startP2P\"),this.sendConnection=new Rj(e,this.store),this.store.peerConnectionStart(),this.bindConnectionEvents(this.sendConnection);const t=await this.sendConnection.establish();return{iceParameters:t.iceParameters,dtlsParameters:t.dtlsParameters,sdp:t.sdp}}}finally{i&&i()}}async p2pConnect(e){if(!this.sendConnection)throw new iI(tI.UNEXPECTED_ERROR,\"Cannot P2PChannel2.p2pConnect before P2PChannel2.startP2PConnection .\");this.store.peerConnectionStart(),await this.sendConnection.connect(e),this.statsUploader.startUploadTransportStats(),this.statsUploader.startUploadExtensionUsageStats(),this.state=aw.Connected}async addRemoteCandidate(e,t){if(t===yb.RECEIVE_ONLY){if(!this.sendConnection)throw new iI(tI.UNEXPECTED_ERROR,\"Cannot P2PChannel2.connect before P2PChannel2.addRemoteCandidate .\");await this.sendConnection.addRemoteCandidate(e)}else{if(!this.recvConnection)throw new iI(tI.UNEXPECTED_ERROR,\"Cannot P2PChannel2.connect before P2PChannel2.addRemoteCandidate .\");await this.recvConnection.addRemoteCandidate(e)}}publish(e,t,i){var n=this;return pB((function*(){const r=yield rB(n.sendMutex.lock(\"From P2PChannel.publish\"));try{if(!n.sendConnection||n.state!==aw.Connected){n.throwIfTrackTypeNotMatch(e);const t=e.filter((e=>-1===n.pendingLocalTracks.indexOf(e)));return void(n.pendingLocalTracks=n.pendingLocalTracks.concat(t))}n.store.pubId=n.store.pubId+1,iB.markPublishStart(n.store.clientId,n.store.pubId);const o=n.filterTobePublishedTracks(e,t,i);if(0===o.length)return void(yield rB(n.tryToUnmuteAudio(e)));o.forEach((e=>{let{track:t,type:i}=e;const r=Date.now();n.store.publish(t.getTrackId(),i===sw.LocalAudioTrack?\"audio\":\"video\",r)})),n.bindLocalTrackEvents(o);const s=yield rB(n.sendConnection.send(o.map((e=>{let{track:t}=e;return t})),n.store.codec,n.store.audioCodec)),a=(yield rB(s.next())).value,c=n.createGatewayPublishMessage(o,a);try{yield c}catch(e){throw s.throw(e),(null==e?void 0:e.code)===tI.WS_ABORT&&o.forEach((e=>{let{track:t}=e;-1===n.pendingLocalTracks.indexOf(t)&&n.pendingLocalTracks.push(t)})),n.unbindLocalTrackEvents(o),e}yield rB(s.next()),o.forEach((e=>{let{type:t}=e;n.statsCollector.addLocalStats(t)})),n.statsUploader.startUploadOutboundStats(),n.assignLocalTracks(o,a),o.forEach((e=>{let{track:t,type:i}=e;const r=Date.now();n.store.publish(t.getTrackId(),i===sw.LocalAudioTrack?\"audio\":\"video\",void 0,r)})),n.startUploadUplinkState()}finally{r()}}))()}async unpublish(e){if(!this.sendConnection||this.state!==aw.Connected)return void(0===e.length?this.pendingLocalTracks.length=0:this.pendingLocalTracks=this.pendingLocalTracks.filter((t=>!Dn(e).call(e,t))));const t=this.filterTobeUnpublishedTracks(e);if(0===t.length)return;const i=t.find((e=>\"videoLowTrack\"===e[0]));if(i){i[1].track.close()}const n=this.createGatewayUnpublishMessage(t);if(await this.sendConnection.stopSending(t.map((e=>{let[,{id:t}]=e;return t}))),this.withdrawLocalTracks(t),this.unbindLocalTrackEvents(t.map((e=>{let[t,{track:i}]=e;return{type:t,track:i}}))),t.forEach((e=>{let[t]=e;this.statsCollector.removeLocalStats(t)})),0===this.localTrackMap.size&&(this.statsUploader.stopUploadOutboundStats(),this.stopUploadUplinkState()),this.sendConnection&&this.state===aw.Connected){if(i){i[1].track.close()}return n}e.forEach((e=>{const t=this.pendingLocalTracks.indexOf(e);-1!==t&&this.pendingLocalTracks.splice(t,1)}))}startUploadUplinkState(){if(this.uploadUnplinkStarted)return;this.uploadUnplinkStarted=!0,this.uplinkStateUploadInterval&&window.clearInterval(this.uplinkStateUploadInterval);const e=()=>{const e=[],t=[];Array.from(this.localTrackMap.entries()).forEach((i=>{let[n,{track:r,ssrcs:o}]=i;const s={stream_type:Gj(r,n),ssrcs:o};r._muted||!r._enabled?e.push(s):t.push(s)})),e.length>0&&e.forEach((e=>{MI(this,cw.RequestMuteLocal,[e])})),t.length>0&&t.forEach((e=>{MI(this,cw.RequestUnmuteLocal,[e])}))};e(),this.uplinkStateUploadInterval=window.setInterval((()=>{e()}),3e3)}stopUploadUplinkState(){this.uploadUnplinkStarted&&(this.uploadUnplinkStarted=!1,this.uplinkStateUploadInterval&&window.clearInterval(this.uplinkStateUploadInterval))}publishLowStream(e){return pB((function*(){throw new iI(tI.NOT_SUPPORTED,\"p2p mode does not support publishLowStream.\")}))()}async republish(){this.pendingLocalTracks.length>0&&(Qy.debug(\"[\".concat(this.store.clientId,\"] Emit P2PChannelEvents.RequestRePublish to republish tracks.\")),await kI(this,cw.RequestRePublish,this.pendingLocalTracks),this.emit(cw.MediaReconnectEnd,this.store.uid),this.pendingLocalTracks=[])}async unpublishLowStream(){throw new iI(tI.NOT_SUPPORTED,\"p2p mode does not support unpublishLowStream.\")}async subscribe(e,t,i,n){var r;if(!this.recvConnection)throw new iI(tI.INVALID_OPERATION,\"Cannot subscribe remote user when recvConnection disconnected.\");if(null!==(r=this.remoteUserMap.get(e))&&void 0!==r&&r.has(t))return;const{track:o,mid:s,transceiver:a}=await this.recvConnection.receive(t,[{ssrcId:i}],String(e.uid),n);t===nw.AUDIO?(e._audioTrack?e._audioTrack._updateOriginMediaStreamTrack(o):(e._audioTrack=new BF(o,e.uid,e._uintid,this.store),Qy.info(\"[\".concat(this.store.clientId,\"] [\").concat(this.store.p2pId,\"] create remote audio track: \").concat(e._audioTrack.getTrackId()))),a&&e._audioTrack._updateRtpTransceiver(a),this.bindRemoteTrackEvents(e,e._audioTrack)):(e._videoSSRC=i,e._videoTrack?e._videoTrack._updateOriginMediaStreamTrack(o):(e._videoTrack=new FF(o,e.uid,e._uintid,this.store),Qy.info(\"[\".concat(this.store.clientId,\"] [\").concat(this.store.p2pId,\"] create remote video track: \").concat(e._videoTrack.getTrackId()))),a&&e._videoTrack._updateRtpTransceiver(a),this.bindRemoteTrackEvents(e,e._videoTrack));const c=this.remoteUserMap.get(e);c?c.set(t,s):this.remoteUserMap.set(e,new Map([[t,s]])),this.statsCollector.addRemoteStats(e.uid),this.statsUploader.startUploadInboundStats(),this.startUploadDownlinkState();const d=this.pendingRemoteTracks.findIndex((i=>{let{user:n,kind:r}=i;return n.uid===e.uid&&t===r}));-1!==d&&(this.pendingRemoteTracks.splice(d,1),this.emit(cw.MediaReconnectEnd,e.uid))}async mockSubscribe(e,t,i,n){if(!this.recvConnection)throw new iI(tI.INVALID_OPERATION,\"Cannot subscribe remote user when recvConnection disconnected.\");await this.recvConnection.mockReceive(t,[{ssrcId:i}],String(e.uid),n)}async unsubscribe(e,t,i){const n=this.pendingRemoteTracks.filter((i=>{let{user:n,kind:r}=i;return void 0!==t?n.uid===e.uid&&t===r:n.uid===e.uid}));if(n.forEach((e=>{const t=this.pendingRemoteTracks.indexOf(e);this.pendingRemoteTracks.splice(t,1)})),this.recvConnection||i||n.forEach((t=>{let{kind:i}=t;var n;if(i===nw.AUDIO)null===(n=e._audioTrack)||void 0===n||n._destroy(),e._audioTrack=void 0;else if(i===nw.VIDEO){var r;null===(r=e._videoTrack)||void 0===r||r._destroy(),e._videoTrack=void 0}})),!this.recvConnection)return;const r=this.filterTobeUnSubscribedTracks(e,t);0!==r.length&&(await this.recvConnection.stopReceiving(r.map((e=>{let[,{id:t}]=e;return t}))),this.withdrawRemoteTracks(r),0===this.remoteUserMap.size&&(this.statsUploader.stopUploadInboundStats(),this.stopUploadDownlinkState()),r.forEach((e=>{let[t,{kind:n}]=e;var r,o;n===nw.VIDEO&&t._videoSSRC&&(null===(r=this.recvConnection)||void 0===r||r.setStatsRemoteVideoIsReady(t._videoSSRC,!1));if(n===nw.VIDEO)this.unbindRemoteTrackEvents(t._videoTrack),i||(null===(o=t._videoTrack)||void 0===o||o._destroy(),t._videoTrack=void 0);else if(n===nw.AUDIO){var s;if(this.unbindRemoteTrackEvents(t._audioTrack),!i)null===(s=t._audioTrack)||void 0===s||s._destroy(),t._audioTrack=void 0}})),r.forEach((e=>{let[,{kind:t}]=e;MI(this,cw.RequestP2PMuteRemote,t)})))}startUploadDownlinkState(){if(this.uploadDownlinkStarted)return;this.uploadDownlinkStarted=!0,this.downlinkStatsUploadInterval&&window.clearInterval(this.downlinkStatsUploadInterval);const e=()=>Array.from(this.remoteUserMap.entries()).forEach((e=>{let[,t]=e;[nw.VIDEO,nw.AUDIO].forEach((e=>{t.has(e)?MI(this,cw.RequestP2PUnmuteRemote,e):MI(this,cw.RequestP2PMuteRemote,e)}))}));e(),this.downlinkStatsUploadInterval=window.setInterval((()=>{e()}),3e3)}stopUploadDownlinkState(){this.uploadDownlinkStarted&&(this.uploadDownlinkStarted=!1,this.downlinkStatsUploadInterval&&window.clearInterval(this.downlinkStatsUploadInterval))}getAllDataChannels(){return this.localDataChannels}async massSubscribe(e){throw new iI(tI.NOT_SUPPORTED,\"p2p mode does not support massSubscribe.\")}async massSubscribeNoLock(e){throw new iI(tI.NOT_SUPPORTED,\"p2p mode does not support massSubscribeNoLock.\")}async massUnsubscribe(e){throw new iI(tI.NOT_SUPPORTED,\"p2p mode does not support massUnsubscribe.\")}async massUnsubscribeNoLock(e){throw new iI(tI.NOT_SUPPORTED,\"p2p mode does not support massUnsubscribeNoLock.\")}async muteRemote(e,t){if(!this.recvConnection)return;const i=this.remoteUserMap.get(e);if(!i)return void Qy.warning(\"[\".concat(this.store.clientId,\"] P2PChannel2.muteRemote has no remote user \").concat(e.uid,\".\"));if(!i.get(t))return void Qy.warning(\"[\".concat(this.store.clientId,\"] P2PChannel2.muteRemote has no remote user \").concat(e.uid,\" media type \").concat(t,\".\"));const n=t===nw.VIDEO?e._videoSSRC:e._audioSSRC;void 0!==n&&this.recvConnection.setStatsRemoteVideoIsReady(n,!1)}async unmuteRemote(e,t){return this.unmuteRemoteNoLock(e,t)}async unmuteRemoteNoLock(e,t){if(!this.recvConnection)return;const i=this.remoteUserMap.get(e);if(!i)return void Qy.warning(\"[\".concat(this.store.clientId,\"] P2PChannel2.unmuteRemote has no remote user \").concat(e.uid,\".\"));i.get(t)||Qy.warning(\"[\".concat(this.store.clientId,\"] P2PChannel2.unmuteRemote has no remote user \").concat(e.uid,\" media type \").concat(t,\".\"))}getAllTracks(e){const t=this.localTrackMap.get(sw.LocalAudioTrack);if((null==t?void 0:t.track)instanceof UV){const i=t.track;return Array.from(this.localTrackMap.entries()).filter((e=>{let[t]=e;return t!==sw.LocalAudioTrack})).filter((t=>{let[i]=t;return!(e&&i===sw.LocalVideoLowTrack)})).map((e=>{let[,{track:t}]=e;return t})).concat(i.trackList)}return Array.from(this.localTrackMap.entries()).filter((t=>{let[i]=t;return!(e&&i===sw.LocalVideoLowTrack)})).map((e=>{let[,{track:t}]=e;return t}))}reportPublishEvent(e,t,i,n,r){if(e){const i=this.localTrackMap.get(sw.LocalAudioTrack),o=n?this.localTrackMap.get(sw.LocalVideoLowTrack):this.localTrackMap.get(sw.LocalVideoTrack);oA.publish(this.store.sessionId,{eventElapse:iB.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:e,ec:t,audioName:null==i?void 0:i.track.getTrackLabel(),videoName:null==o?void 0:o.track.getTrackLabel(),screenshare:-1!==(null==o?void 0:o.track._hints.indexOf(LU.SCREEN_TRACK)),audio:!!i,video:!!o,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r})}else{var o;i||(i=[]);const s=i.find((e=>e instanceof LV)),a=n?null===(o=this.localTrackMap.get(sw.LocalVideoTrack))||void 0===o?void 0:o.track:i.find((e=>e instanceof vF));oA.publish(this.store.sessionId,{eventElapse:iB.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:e,ec:t,audioName:null==s?void 0:s.getTrackLabel(),videoName:null==a?void 0:a.getTrackLabel(),screenshare:-1!==(null==a?void 0:a._hints.indexOf(LU.SCREEN_TRACK)),audio:!!s,video:!!a,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r})}}reportSubscribeEvent(e,t,i,n){const r=n===nw.VIDEO?i._videoSSRC:i._audioSSRC;r&&oA.subscribe(this.store.sessionId,{succ:e,ec:t,video:n===nw.VIDEO,audio:n===nw.AUDIO,peerid:i.uid,subscribeRequestid:n===nw.VIDEO?i._videoSSRC:i._audioSSRC,p2pid:this.store.p2pId,eventElapse:iB.measureFromSubscribeStart(this.store.clientId,r)})}reset(){Qy.debug(\"[\".concat(this.store.clientId,\"] P2PChannel2.reset\")),this.sendMutex=new uy(\"P2PChannel2-send-mutex\"),this.sendMutex=new uy(\"P2PChannel2-recv-mutex\"),this.sendConnection&&(this.sendConnection.close(),this.unbindConnectionEvents(this.sendConnection),this.sendConnection=void 0),this.recvConnection&&(this.recvConnection.close(),this.unbindConnectionEvents(this.recvConnection),this.recvConnection=void 0),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),this.statsUploader.stopUploadExtensionUsageStats(),this.stopUploadUplinkState(),this.stopUploadDownlinkState(),this.unbindLocalTrackEvents(),this.unbindAllRemoteTrackEvents(),this.unbindRtpTransceiver();const e=this.localTrackMap.get(sw.LocalAudioTrack);if((null==e?void 0:e.track)instanceof UV){if(e.track.trackList.length>0){const t=e.track;e.track.trackList.forEach((e=>{t.removeAudioTrack(e)}))}e.track.close()}this.localTrackMap.clear(),this.remoteUserMap.clear(),this.statsCollector.removeRemoteStats(),this.statsCollector.removeLocalStats(),this.dtlsFailedCount=0,this.pendingLocalTracks=[],this.pendingRemoteTracks=[],this.reconnectInterval&&(window.clearInterval(this.reconnectInterval),this.reconnectInterval=void 0),this.state=aw.Disconnected}getStats(e){var t,i;return e?null===(i=this.recvConnection)||void 0===i?void 0:i.getStats():null===(t=this.sendConnection)||void 0===t?void 0:t.getStats()}getRemoteVideoIsReady(e){var t;return(null===(t=this.recvConnection)||void 0===t?void 0:t.getRemoteVideoIsReady(e))||!1}getLocalAudioVolume(){const e=this.localTrackMap.get(sw.LocalAudioTrack);if(e)return e.track.getVolumeLevel()}getLocalVideoSize(){const e=this.localTrackMap.get(sw.LocalVideoTrack);if(e)return{width:e.track.videoWidth||0,height:e.track.videoHeight||0}}getEncoderConfig(e){const t=this.localTrackMap.get(e);return t&&t.track instanceof vF||t&&t.track instanceof LV?t.track._encoderConfig:void 0}getLocalMedia(e){return this.localTrackMap.get(e)}hasLocalMedia(){return this.localTrackMap.size>0}hasRemoteMedia(e,t){if(!e)return this.remoteUserMap.size>0;const i=this.remoteUserMap.get(e);return!!i&&(!t||i.has(t))}async hasRemoteMediaWithLock(e,t){if(!e)return this.remoteUserMap.size>0;const i=this.remoteUserMap.get(e);return!!i&&(!t||i.has(t))}getRemoteMedia(e){var t;const i=Array.from(d_(t=this.remoteUserMap).call(t)).find((t=>t.uid===e));return i?{audioTrack:i.audioTrack,audioSSRC:i._audioSSRC,videoTrack:i.videoTrack,videoSSRC:i._videoSSRC}:{}}getAudioLevels(){let e=Array.from(this.remoteUserMap.entries()).map((e=>{let[t]=e;return{uid:t.uid,level:t.audioTrack?100*t.audioTrack._source.getAccurateVolumeLevel():0}}));const t=this.localTrackMap.get(sw.LocalAudioTrack);return t&&e.push({level:100*t.track._source.getAccurateVolumeLevel(),uid:this.store.uid}),e=oE(e).call(e,((e,t)=>e.level-t.level)),e}async disconnectForReconnect(){this.sendConnection&&this.recvConnection&&(Qy.debug(\"[\".concat(this.store.clientId,\"] P2PChannel2.disconnectForReconnect closing P2PConnection\")),this.state=aw.Reconnecting,Dy(\"KEEP_LAST_FRAME\")&&0!==this.remoteUserMap.size&&Array.from(this.remoteUserMap.entries()).forEach((e=>{let[t]=e;var i;t._videoTrack&&t._videoTrack._player&&(null===(i=t._videoTrack._player.getVideoElement())||void 0===i||i.pause(),t._videoTrack._player.isKeepLastFrame=!0,t._videoTrack._originMediaStreamTrack.stop())})),this.sendConnection.close(),this.unbindConnectionEvents(this.sendConnection),this.sendConnection=void 0,this.recvConnection.close(),this.unbindConnectionEvents(this.recvConnection),this.recvConnection=void 0,0!==this.localTrackMap.size&&(Array.from(this.localTrackMap.entries()).forEach((e=>{var t;let[i,{track:n}]=e;switch(i){case sw.LocalVideoTrack:Dn(t=n._hints).call(t,LU.LOW_STREAM)?n.close():this.pendingLocalTracks.push(n);break;case sw.LocalAudioTrack:n instanceof UV?this.pendingLocalTracks=this.pendingLocalTracks.concat(n.trackList):this.pendingLocalTracks.push(n);case sw.LocalVideoLowTrack:}})),this.emit(cw.MediaReconnectStart,this.store.uid)),this.unbindLocalTrackEvents(),this.localTrackMap.clear(),0!==this.remoteUserMap.size&&Array.from(this.remoteUserMap.entries()).forEach((e=>{let[t,i]=e;Array.from(d_(i).call(i)).forEach((e=>{this.setPendingRemoteMedia(t,e)})),this.emit(cw.MediaReconnectStart,t.uid)})),this.unbindAllRemoteTrackEvents(),this.remoteUserMap.clear(),this.stopUploadUplinkState(),this.stopUploadDownlinkState(),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),Qy.debug(\"[\".concat(this.store.clientId,\"] P2PChannel2 disconnected, waiting to reconnect.\")))}hasPendingRemoteMedia(e,t){for(const i of this.pendingRemoteTracks){const{user:n,kind:r}=i;if((e instanceof Bj?e.uid:e)===n.uid&&t===r)return!0}return!1}setPendingRemoteMedia(e,t){this.hasPendingRemoteMedia(e,t)||this.pendingRemoteTracks.push({user:e,kind:t})}async restartICE(e,t){let i,n;if(e===yb.SEND_ONLY){if(!this.sendConnection)throw new iI(tI.INVALID_OPERATION,\"Cannot call P2PChannel2.handleMuteLocalTrack before sendConnection established.\");i=await this.sendMutex.lock(\"From P2PChannel.restartICE\"),n=this.sendConnection}else{if(!this.recvConnection)throw new iI(tI.INVALID_OPERATION,\"Cannot call P2PChannel2.handleMuteLocalTrack before recvConnection established.\");i=await this.recvMutex.lock(\"From P2PChannel.restartICE\"),n=this.recvConnection}try{if(t){const e=await n.restartICE(t);return n.isInRestartIce=!1,e}{const e=await n.restartICE();if(e){const t=await kI(this,cw.RequestP2PRestartICE,{direction:yb.RECEIVE_ONLY,iceParameter:e});await n.restartICE(t),n.isInRestartIce=!1}}}finally{i()}}getUplinkNetworkQuality(){if(!this.sendConnection)return 0;const e=this.sendConnection.getStats(),t=this.localTrackMap.get(sw.LocalVideoTrack),i=this.localTrackMap.get(sw.LocalAudioTrack),n=e.videoSend.find((e=>{var i;return e.ssrc===(null==t||null===(i=t.ssrcs)||void 0===i?void 0:i[0].ssrcId)})),r=e.audioSend.find((e=>{var t;return e.ssrc===(null==i||null===(t=i.ssrcs)||void 0===t?void 0:t[0].ssrcId)}));if(!n||!r)return 1;const o=UI(this,cw.NeedSignalRTT),s=n?n.rttMs:void 0,a=r?r.rttMs:void 0,c=s&&a?(s+a)/2:s||a,d=(c&&o?(c+o)/2:c||o)||0,l=100*e.sendPacketLossRate*.7/50+.3*d/1500,h=l<.17?1:l<.36?2:l<.59?3:l<.1?4:5,u=null==t?void 0:t.track;if(u&&u._encoderConfig&&-1===u._hints.indexOf(LU.SCREEN_TRACK)){const t=u._encoderConfig.bitrateMax,i=e.bitrate.actualEncoded;if(t&&i){const e=(1e3*t-i)/(1e3*t);return cA[e<.15?0:e<.3?1:e<.45?2:e<.6?3:4][h]}}return h}getDownlinkNetworkQuality(){if(!this.recvConnection)return 0;const e=this.recvConnection.getStats();let t=0;return Array.from(this.remoteUserMap.entries()).forEach((i=>{let[n]=i;const r=n._audioSSRC,o=n._videoSSRC,s=e.audioRecv.find((e=>e.ssrc===r)),a=e.videoRecv.find((e=>e.ssrc===o));if(!s&&!a)return void(t+=1);const c=UI(this,cw.NeedSignalRTT),d=e.rtt,l=(d&&c?(d+c)/2:d||c)||0,h=s?s.jitterMs:void 0,u=e.recvPacketLossRate;let p=.7*u*100/50+.3*l/1500;h&&(p=.6*u*100/50+.2*l/1500+.2*h/400);t+=p<.1?1:p<.17?2:p<.36?3:p<.59?4:5})),this.remoteUserMap.size>0?Math.round(t/this.remoteUserMap.size):t}async muteLocalTrack(e){return new Gu(((t,i)=>{this.handleMuteLocalTrack(e,t,i)}))}filterTobePublishedTracks(e,t,i){const n=[],r=_U(),o=this.getAllTracks();e=BI(e=e.filter((e=>-1===o.indexOf(e))));let s=!1,a=!1;for(const o of e){if(o instanceof vF&&(this.localTrackMap.has(sw.LocalVideoTrack)||s?new iI(tI.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS).throw():(n.push({track:o,type:sw.LocalVideoTrack}),s=!0),t)){const e=this.getLowVideoTrack(o,i);n.push({track:e,type:sw.LocalVideoLowTrack})}if(o instanceof LV){const e=this.localTrackMap.get(sw.LocalAudioTrack);if(e){if(!(e.track instanceof UV))throw new iI(tI.NOT_SUPPORTED,\"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser does not support audio mixing\");if(o._bypassWebAudio)throw new iI(tI.NOT_SUPPORTED,\"cannot publish multiple tracks which one of them configured with bypassWebAudio\");e.track.addAudioTrack(o),this.bindLocalAudioTrackEvents(o,!0)}else if(a){const e=n.find((e=>{let{type:t}=e;return t===sw.LocalAudioTrack}));if(!(e.track instanceof UV))throw new iI(tI.NOT_SUPPORTED,\"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser does not support audio mixing\");if(o._bypassWebAudio)throw new iI(tI.NOT_SUPPORTED,\"cannot publish multiple tracks which one of them configured with bypassWebAudio\");e.track.addAudioTrack(o)}else{if(!r.webAudioMediaStreamDest||o instanceof UV||o._bypassWebAudio)n.push({track:o,type:sw.LocalAudioTrack});else{const e=new UV;e.addAudioTrack(o),n.push({track:e,type:sw.LocalAudioTrack})}a=!0}}}return n}filterTobeUnpublishedTracks(e){const t=[],i=this.getAllTracks();e=BI(e=e.filter((e=>-1!==i.indexOf(e))));for(const i of e){if(i instanceof LV){const e=this.localTrackMap.get(sw.LocalAudioTrack);if(!e)continue;e.track instanceof UV?(e.track.removeAudioTrack(i),this.unbindLocalAudioTrackEvents(i),0===e.track.trackList.length&&(t.push([sw.LocalAudioTrack,e]),e.track.close())):t.push([sw.LocalAudioTrack,e])}if(i instanceof vF){const e=this.localTrackMap.get(sw.LocalVideoTrack);if(!e)continue;t.push([sw.LocalVideoTrack,e]);const i=this.localTrackMap.get(sw.LocalVideoLowTrack);i&&t.push([sw.LocalVideoLowTrack,i])}}return t}bindLocalTrackEvents(e){e.forEach((e=>{let{track:t,type:i}=e;switch(i){case sw.LocalVideoTrack:t.addListener(PU.GET_STATS,this.handleGetLocalVideoStats),t.addListener(PU.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.addListener(PU.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.addListener(PU.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.addListener(PU.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this.handleUpdateVideoSendParameters),t.addListener(PU.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.addListener(PU.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.addListener(PU.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case sw.LocalAudioTrack:this.bindLocalAudioTrackEvents(t);case sw.LocalVideoLowTrack:}}))}bindLocalAudioTrackEvents(e,t){e instanceof UV?e.trackList.forEach((e=>{e.addListener(PU.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(PU.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(PU.GET_STATS,this.handleGetLocalAudioStats),e.addListener(PU.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(PU.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)})):(e.addListener(PU.GET_STATS,this.handleGetLocalAudioStats),e.addListener(PU.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(PU.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(PU.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(PU.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack),t||e.addListener(PU.NEED_REPLACE_TRACK,this.handleReplaceTrack))}unbindLocalTrackEvents(e){e||(e=Array.from(this.localTrackMap.entries()).map((e=>{let[t,{track:i}]=e;return{track:i,type:t}}))),e.forEach((e=>{let{track:t,type:i}=e;switch(i){case sw.LocalVideoTrack:t.off(PU.GET_STATS,this.handleGetLocalVideoStats),t.off(PU.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.off(PU.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.off(PU.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.off(PU.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this.handleUpdateVideoSendParameters),t.off(PU.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.off(PU.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.off(PU.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case sw.LocalAudioTrack:this.unbindLocalAudioTrackEvents(t);case sw.LocalVideoLowTrack:}}))}unbindLocalAudioTrackEvents(e){e instanceof UV?e.trackList.forEach((e=>{e.off(PU.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(PU.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(PU.GET_STATS,this.handleGetLocalAudioStats),e.off(PU.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(PU.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)})):(e.off(PU.GET_STATS,this.handleGetLocalAudioStats),e.off(PU.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(PU.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(PU.NEED_REPLACE_TRACK,this.handleReplaceTrack),e.off(PU.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(PU.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack))}bindRemoteTrackEvents(e,t){t instanceof FF&&t.addListener(PU.GET_STATS,(t=>{t(this.handleGetRemoteVideoStats(e))})),t instanceof BF&&t.addListener(PU.GET_STATS,(t=>{t(this.handleGetRemoteAudioStats(e))}))}unbindRemoteTrackEvents(e){e&&e.removeAllListeners(PU.GET_STATS)}unbindAllRemoteTrackEvents(){Array.from(this.remoteUserMap.entries()).forEach((e=>{let[t,i]=e;i.has(nw.AUDIO)&&this.unbindRemoteTrackEvents(t._audioTrack),i.has(nw.VIDEO)&&this.unbindRemoteTrackEvents(t._videoTrack)}))}createGatewayPublishMessage(e,t){return e.map(((e,i)=>{var n;let r,{track:o,type:s}=e;switch(s){case sw.LocalAudioTrack:r=Kb.Audio;break;case sw.LocalVideoTrack:r=Dn(n=o._hints).call(n,LU.SCREEN_TRACK)?Kb.Screen:Kb.High;break;case sw.LocalVideoLowTrack:r=Kb.Low}return{kind:s===sw.LocalAudioTrack?nw.AUDIO:nw.VIDEO,stream_type:r,mid:t[i].id,ssrcs:t[i].localSSRC,isMuted:o.muted||!o.enabled}}))}createGatewayUnpublishMessage(e){return e.map((e=>{var t;let i,[n,{track:r,ssrcs:o,id:s}]=e;switch(n){case sw.LocalVideoTrack:i=Dn(t=r._hints).call(t,LU.SCREEN_TRACK)?Kb.Screen:Kb.High;break;case sw.LocalAudioTrack:i=Kb.Audio;break;case sw.LocalVideoLowTrack:i=Kb.Low}return{stream_type:i,ssrcs:o,mid:s}}))}assignLocalTracks(e,t){e.forEach(((e,i)=>{let{track:n,type:r}=e;this.localTrackMap.set(r,{track:n,id:t[i].id,ssrcs:t[i].localSSRC})}))}withdrawLocalTracks(e){e.forEach((e=>{let[t]=e;this.localTrackMap.delete(t)}))}bindConnectionEvents(e){e.onConnectionStateChange=async t=>{var i;Qy.info(\"[\".concat(this.store.clientId,\"] [p2pId: \").concat(this.store.p2pId,\"]: \").concat(e.name,\".onConnectionStateChange(\").concat(t,\")\")),this.emit(cw.PeerConnectionStateChange,t),\"connected\"!==t||this.store.keyMetrics.peerConnectionEnd||this.store.peerConnectionEnd(),\"connected\"===t&&(e.isInRestartIce=!1),Dn(i=this._restartStates).call(i,t)&&!e.isInRestartIce&&(\"disconnected\"===t&&await $I(800),\"disconnected\"!==e.iceConnectionState&&\"failed\"!==e.iceConnectionState||this.handleDisconnect(e.direction))},e.onICEConnectionStateChange=e=>{\"connected\"!==e||this.store.keyMetrics.iceConnectionEnd||this.store.iceConnectionEnd(),Qy.info(\"[\".concat(this.store.clientId,\"] [p2pId: \").concat(this.store.p2pId,\"]: P2PConnection.onICEConnectionStateChange(\").concat(e,\")\")),oA.reportApiInvoke(this.store.sessionId,{name:\"ICEConnectionStateChange\",options:e,tag:vI.TRACER}).onSuccess(),this.emit(cw.IceConnectionStateChange,e)},e.onICETransportStateChange=e=>{Qy.info(\"[\".concat(this.store.clientId,\"] [p2pId: \").concat(this.store.p2pId,\"]: P2PConnection.onICETransportStateChange(\").concat(e,\")\"))},e.onDTLSTransportStateChange=e=>{Qy.info(\"[\".concat(this.store.clientId,\"] [p2pId: \").concat(this.store.p2pId,\"]: P2PConnection.onDTLSTransportStateChange(\").concat(e,\")\"))},e.onDTLSTransportError=e=>{Qy.info(\"[\".concat(this.store.clientId,\"] [p2pId: \").concat(this.store.p2pId,\"]: P2PConnection.onDTLSTransportError(\").concat(e,\")\"))},e.onFirstAudioDecoded=e=>{var t;const i=Array.from(d_(t=this.remoteUserMap).call(t)).find((t=>t._audioSSRC===e));var n;i&&(this.store.subscribe(i.uid,\"audio\",void 0,void 0,void 0,Date.now()),null===(n=i.audioTrack)||void 0===n||n.emit(FU.FIRST_FRAME_DECODED),oA.firstRemoteFrame(this.store.sessionId,tA.FIRST_AUDIO_DECODE,iA.FIRST_AUDIO_DECODE,{peer:i._uintid,subscribeElapse:iB.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId}))},e.onFirstAudioReceived=e=>{var t;const i=Array.from(d_(t=this.remoteUserMap).call(t)).find((t=>t._audioSSRC===e));i&&oA.firstRemoteFrame(this.store.sessionId,tA.FIRST_AUDIO_RECEIVED,iA.FIRST_AUDIO_RECEIVED,{peer:i._uintid,subscribeElapse:iB.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId})},e.onFirstVideoDecoded=(e,t,i)=>{this.reportVideoFirstFrameDecoded(e,t,i)},e.onFirstVideoReceived=e=>{var t;const i=Array.from(d_(t=this.remoteUserMap).call(t)).find((t=>t._videoSSRC===e));i&&oA.firstRemoteFrame(this.store.sessionId,tA.FIRST_VIDEO_RECEIVED,iA.FIRST_VIDEO_RECEIVED,{peer:i._uintid,subscribeElapse:iB.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId})},e.onSelectedLocalCandidateChanged=(e,t)=>{const i=\"relay\"===e.candidateType,n=\"relay\"===t.candidateType;\"unknown\"!==t.candidateType&&i===n||this.emit(cw.ConnectionTypeChange,i),Qy.info(\"[\".concat(this.store.clientId,\"] [p2pId: \").concat(this.store.p2pId,\"]: P2PConnection.SelectedLocalCandidateChanged(\").concat(JSON.stringify(Zw(t)),\" -> \").concat(JSON.stringify(Zw(e)),\")\"))},e.onSelectedRemoteCandidateChanged=(e,t)=>{Qy.info(\"[\".concat(this.store.clientId,\"] [p2pId: \").concat(this.store.p2pId,\"]: P2PConnection.SelectedRemoteCandidateChanged(\").concat(JSON.stringify(Zw(t)),\" -> \").concat(JSON.stringify(Zw(e)),\")\"))},e.onFirstVideoDecodedTimeout=e=>{this.reportVideoFirstFrameDecoded(e,void 0,void 0,!0)},e.onLocalCandidate=t=>{this.emit(cw.LocalCandidate,{candidate:t,direction:e.direction})}}unbindConnectionEvents(e){e.onConnectionStateChange=void 0,e.onICEConnectionStateChange=void 0,e.onICETransportStateChange=void 0,e.onDTLSTransportStateChange=void 0,e.onDTLSTransportError=void 0,e.onFirstAudioDecoded=void 0,e.onFirstAudioReceived=void 0,e.onFirstVideoDecoded=void 0,e.onFirstVideoReceived=void 0,e.onSelectedLocalCandidateChanged=void 0,e.onSelectedRemoteCandidateChanged=void 0,e.onFirstVideoDecodedTimeout=void 0,e.onLocalCandidate=void 0}async handleDisconnect(e){const t=e===yb.SEND_ONLY?this.sendConnection:this.recvConnection;t&&!t.isInRestartIce&&(t.isInRestartIce=!0,Qy.debug(\"[\".concat(this.store.clientId,\"] [P2PChannel-\").concat(t.name,\"] start use restartICE\")),e===yb.SEND_ONLY?this.restartICE(e):kI(this,cw.RequestP2PRestartICE,{direction:yb.SEND_ONLY}))}filterTobeMutedTracks(e){const t=[];if(-1===this.getAllTracks().indexOf(e))return t;const i=this.localTrackMap.get(sw.LocalAudioTrack);if(e instanceof LV&&(null==i?void 0:i.track)instanceof UV)return i.track.isActive||t.push([sw.LocalAudioTrack,i]),t;const n=Array.from(this.localTrackMap.entries()).find((t=>{let[,{track:i}]=t;return e===i}));if(n&&(t.push(n),n[0]===sw.LocalVideoTrack)){const e=this.localTrackMap.get(sw.LocalVideoLowTrack);e&&t.push([sw.LocalVideoLowTrack,e])}return t}filterTobeUnmutedTracks(e){const t=[],i=this.localTrackMap.get(sw.LocalAudioTrack);if(e instanceof LV&&(null==i?void 0:i.track)instanceof UV)return i.track.isActive&&t.push([sw.LocalAudioTrack,i]),t;const n=Array.from(this.localTrackMap.entries()).find((t=>{let[,{track:i}]=t;return e===i}));if(n)if(n[0]===sw.LocalVideoTrack){t.push(n);const e=this.localTrackMap.get(sw.LocalVideoLowTrack);e&&t.push([sw.LocalVideoLowTrack,e])}else t.push(n);return t}createMuteMessage(e){return e.map((e=>{var t;let i,[n,{track:r,ssrcs:o,id:s}]=e;switch(n){case sw.LocalAudioTrack:i=Kb.Audio;break;case sw.LocalVideoTrack:i=Dn(t=r._hints).call(t,LU.SCREEN_TRACK)?Kb.Screen:Kb.High;break;case sw.LocalVideoLowTrack:i=Kb.Low}return{stream_type:i,ssrcs:o,mid:s}}))}createUnmuteMessage(e){return e.map((e=>{var t;let i,[n,{track:r,ssrcs:o,id:s}]=e;switch(n){case sw.LocalAudioTrack:i=Kb.Audio;break;case sw.LocalVideoTrack:i=Dn(t=r._hints).call(t,LU.SCREEN_TRACK)?Kb.Screen:Kb.High;break;case sw.LocalVideoLowTrack:i=Kb.Low}return{stream_type:i,ssrcs:o,mid:s}}))}filterTobeUnSubscribedTracks(e,t){const i=[],n=this.remoteUserMap.get(e);if(!n)return i;if(t){const r=n.get(t);if(!r)return i;i.push([e,{kind:t,id:r}])}else Array.from(n.entries()).forEach((t=>{let[n,r]=t;i.push([e,{kind:n,id:r}])}));return i}createUnsubscribeMessage(e){const t=[];return e.forEach((e=>{let[i,{kind:n,id:r}]=e;switch(n){case nw.VIDEO:return void(i._videoSSRC&&t.push({stream_type:nw.VIDEO,ssrcId:i._videoSSRC}));case nw.AUDIO:return void(i._audioSSRC&&t.push({stream_type:nw.AUDIO,ssrcId:i._audioSSRC}))}})),t}withdrawRemoteTracks(e){e.forEach((e=>{let[t,{kind:i}]=e;const n=this.remoteUserMap.get(t);n&&(n.delete(i),0===Array.from(n.entries()).length&&this.remoteUserMap.delete(t))}))}async updateBitrateLimit(e){const t=this.localTrackMap.get(sw.LocalVideoTrack),i=this.localTrackMap.get(sw.LocalVideoLowTrack);t&&await t.track.setBitrateLimit(e.uplink),i&&e.low_stream_uplink&&await i.track.setBitrateLimit({max_bitrate:e.low_stream_uplink.bitrate,min_bitrate:e.low_stream_uplink.bitrate||0})}isP2PDisconnected(){if(this.sendConnection&&this.recvConnection){const e=this.sendConnection.peerConnectionState,t=this.recvConnection.peerConnectionState;return\"connected\"!==e&&\"connected\"!==t}return!0}async tryToUnmuteAudio(e){for(let t=0;tthis.getStats(e),this.statsUploader.requestLocalMedia=()=>Array.from(this.localTrackMap.entries()).filter((e=>{let[,{ssrcs:t}]=e;return!!t})),this.statsUploader.requestRemoteMedia=()=>Array.from(this.remoteUserMap.entries()),this.statsUploader.requestVideoIsReady=e=>{var t;return!(null===(t=this.recvConnection)||void 0===t||!t.getRemoteVideoIsReady(e))},this.statsUploader.requestUpload=(e,t)=>this.emit(cw.RequestUpload,e,t),this.statsUploader.requestUploadStats=e=>this.emit(cw.RequestUploadStats,e),this.statsUploader.requestAllTracks=()=>this.getAllTracks()}unbindStatsUploaderEvents(){this.statsUploader.requestStats=void 0,this.statsUploader.requestLocalMedia=void 0,this.statsUploader.requestRemoteMedia=void 0,this.statsUploader.requestVideoIsReady=void 0}async requestReconnect(){this.dtlsFailedCount+=1,await $I(Ey(this.dtlsFailedCount,_y)),this.emit(cw.RequestReconnect)}async reconnectP2P(){}canPublishLowStream(){return this.localTrackMap.has(sw.LocalVideoTrack)||this.pendingLocalTracks.some((e=>e instanceof vF))}throwIfTrackTypeNotMatch(e){if(e.filter((e=>e instanceof vF)).length>1)throw new iI(tI.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(e.filter((e=>e instanceof LV)).length>1&&(e.some((e=>e instanceof LV&&e._bypassWebAudio))||!_U().webAudioMediaStreamDest))throw new iI(tI.NOT_SUPPORTED,\"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode\");for(const t of e){if(t instanceof vF&&this.pendingLocalTracks.some((e=>e instanceof vF)))throw new iI(tI.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(t instanceof LV&&this.pendingLocalTracks.some((e=>e instanceof LV))&&(!_U().webAudioMediaStreamDest||t._bypassWebAudio||this.pendingLocalTracks.some((e=>e instanceof LV&&e._bypassWebAudio))))throw new iI(tI.NOT_SUPPORTED,\"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode\")}}getLowVideoTrack(e,t){const i=!Dy(\"DISABLE_DUAL_STREAM_USE_ENCODING\")&&_U().supportDualStreamEncoding,n=rG(rG({},{width:160,height:120,framerate:15,bitrate:50}),t);let r;r=i?e._mediaStreamTrack.clone():vj(e,n);const o=ey(8,\"track-low-\"),s=new vF(r,rG(rG({},i&&{scaleResolutionDownBy:Qw(n,e)}),{},{frameRate:n.framerate,bitrateMax:n.bitrate,bitrateMin:n.bitrate}),void 0,void 0,o);return s.on(xU.TRANSCEIVER_UPDATED,(t=>{e._updateRtpTransceiver(t,kU.LOW_STREAM)})),s._hints.push(LU.LOW_STREAM),e.addListener(PU.NEED_CLOSE,(()=>{s.close()})),s}async globalLock(){return this.recvMutex.lock(\"From P2PChannel2.globalLock\")}reportVideoFirstFrameDecoded(e,t,i,n){var r;const o=Array.from(d_(r=this.remoteUserMap).call(r)).find((t=>t._videoSSRC===e));if(o){n||this.store.subscribe(o.uid,\"video\",void 0,void 0,void 0,void 0,Date.now());const r=this.store.keyMetrics,s=r.subscribe.find((e=>e.userId===o.uid&&\"video\"===e.type));oA.firstRemoteVideoDecode(this.store.sessionId,tA.FIRST_VIDEO_DECODE,iA.FIRST_VIDEO_DECODE,{peer:o._uintid,videowidth:t,videoheight:i,subscribeElapse:iB.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId,apEnd:r.requestAPEnd||0,apStart:r.requestAPStart||0,joinGwEnd:r.joinGatewayEnd||0,joinGwStart:r.joinGatewayStart||0,pcEnd:r.peerConnectionEnd||0,pcStart:r.peerConnectionStart||0,subscriberEnd:(null==s?void 0:s.subscribeEnd)||0,subscriberStart:(null==s?void 0:s.subscribeStart)||0,videoAddNotify:(null==s?void 0:s.streamAdded)||0,state:n?1:0})}}async remoteMediaSsrcChanged(e,t,i){if(!this.recvConnection)return!1;const n=this.remoteUserMap.get(e);if(!n)return!1;const r=n.get(t);if(!r)return!1;const o=await this.recvConnection.getRemoteSSRC(r);return void 0!==o&&o!==i}resetConnection(e){Qy.debug(\"[\".concat(this.store.clientId,\"] [P2PChannel2] reset connection to \").concat(e)),this.state===aw.Connected?(Qy.debug(\"[\".concat(this.store.clientId,\"] [P2PChannel2] fallback to websocket but P2PChannel2 state still connected, disconnect first\")),this.disconnectForReconnect()):(this.sendConnection&&(this.sendConnection.close(),this.unbindConnectionEvents(this.sendConnection),this.sendConnection=void 0),this.recvConnection&&(this.recvConnection.close(),this.unbindConnectionEvents(this.recvConnection),this.recvConnection=void 0))}async publishDataChannel(e){throw new iI(tI.NOT_SUPPORTED)}async unpublishDataChannel(e){throw new iI(tI.NOT_SUPPORTED)}async subscribeDataChannel(e,t){throw new iI(tI.NOT_SUPPORTED)}async unsubscribeDataChannel(e,t){throw new iI(tI.NOT_SUPPORTED)}hasPendingRemoteDataChannel(e,t){throw new iI(tI.NOT_SUPPORTED)}setPendingRemoteDataChannel(e,t){throw new iI(tI.NOT_SUPPORTED)}async preConnect(e,t,i,n,r,o){throw new iI(tI.NOT_SUPPORTED)}getEstablishParams(){throw new iI(tI.NOT_SUPPORTED)}async reSubscribe(e){throw new iI(tI.NOT_SUPPORTED)}async updateVideoStreamParameter(e,t){throw new iI(tI.NOT_SUPPORTED)}unbindRtpTransceiver(){0!==this.localTrackMap.size&&Array.from(this.localTrackMap.entries()).forEach((e=>{let[t,{track:i}]=e;t===sw.LocalVideoLowTrack?i._updateRtpTransceiver(void 0,kU.LOW_STREAM):i._updateRtpTransceiver(void 0)}))}},nb(iG.prototype,\"p2pConnect\",[Kj],Object.getOwnPropertyDescriptor(iG.prototype,\"p2pConnect\"),iG.prototype),nb(iG.prototype,\"unpublish\",[Yj],Object.getOwnPropertyDescriptor(iG.prototype,\"unpublish\"),iG.prototype),nb(iG.prototype,\"unpublishLowStream\",[qj],Object.getOwnPropertyDescriptor(iG.prototype,\"unpublishLowStream\"),iG.prototype),nb(iG.prototype,\"subscribe\",[zj],Object.getOwnPropertyDescriptor(iG.prototype,\"subscribe\"),iG.prototype),nb(iG.prototype,\"mockSubscribe\",[Jj],Object.getOwnPropertyDescriptor(iG.prototype,\"mockSubscribe\"),iG.prototype),nb(iG.prototype,\"unsubscribe\",[Xj],Object.getOwnPropertyDescriptor(iG.prototype,\"unsubscribe\"),iG.prototype),nb(iG.prototype,\"muteRemote\",[Qj],Object.getOwnPropertyDescriptor(iG.prototype,\"muteRemote\"),iG.prototype),nb(iG.prototype,\"unmuteRemote\",[Zj],Object.getOwnPropertyDescriptor(iG.prototype,\"unmuteRemote\"),iG.prototype),nb(iG.prototype,\"hasRemoteMediaWithLock\",[$j],Object.getOwnPropertyDescriptor(iG.prototype,\"hasRemoteMediaWithLock\"),iG.prototype),nb(iG.prototype,\"disconnectForReconnect\",[eG],Object.getOwnPropertyDescriptor(iG.prototype,\"disconnectForReconnect\"),iG.prototype),nb(iG.prototype,\"remoteMediaSsrcChanged\",[tG],Object.getOwnPropertyDescriptor(iG.prototype,\"remoteMediaSsrcChanged\"),iG.prototype),iG);function sG(e){return function(t,i,n){const r=t[i];if(\"function\"!=typeof r)throw new Error(\"Cannot use mutex on object property.\");return n.value=async function(){for(var t=arguments.length,n=new Array(t),o=0;o{this.p2pChannel&&(this.updateRemoteStats(this.p2pChannel),this.updateLocalStats(this.p2pChannel))})),this.store=e,this.exceptionMonitor=new eB,this.exceptionMonitor.on(\"exception\",((e,t,i)=>{this.onStatsException&&this.onStatsException(e,t,i)}))}startUpdateStats(){this.updateStatsInterval||(this.updateStatsInterval=window.setInterval(this.updateStats,1e3))}stopUpdateStats(){this.updateStatsInterval&&(window.clearInterval(this.updateStatsInterval),this.updateStatsInterval=void 0)}reset(){this.localStats=new Map,this.remoteStats=new Map,this.trafficStats=void 0,this.trafficStatsPeerList=[],this.uplinkStats=void 0}getLocalAudioTrackStats(){return this.localStats.get(sw.LocalAudioTrack)||cG({},jU)}getLocalVideoTrackStats(){return this.localStats.get(sw.LocalVideoTrack)||cG({},GU)}getRemoteAudioTrackStats(e){const t=(e,t)=>{if(!this.trafficStats)return t;const i=this.trafficStats.peer_delay.find((t=>t.peer_uid===e));return i&&(t.publishDuration=i.B_ppad+(Date.now()-this.trafficStats.timestamp)),t},i={};if(e){var n;const r=null===(n=this.remoteStats.get(e))||void 0===n?void 0:n.audioStats;r&&(i[e]=t(e,r))}else Array.from(this.remoteStats.entries()).forEach((e=>{let[n,{audioStats:r}]=e;r&&(i[n]=t(n,r))}));return i}getRemoteNetworkQualityStats(e){const t={};if(e){var i;const n=null===(i=this.remoteStats.get(e))||void 0===i?void 0:i.networkStats;n&&(t[e]=n)}else Array.from(this.remoteStats.entries()).forEach((e=>{let[i,{networkStats:n}]=e;n&&(t[i]=n)}));return t}getRemoteVideoTrackStats(e){const t=(e,t)=>{if(!this.trafficStats)return t;const i=this.trafficStats.peer_delay.find((t=>t.peer_uid===e));return i&&(t.publishDuration=i.B_ppvd+(Date.now()-this.trafficStats.timestamp)),t},i={};if(e){var n;const r=null===(n=this.remoteStats.get(e))||void 0===n?void 0:n.videoStats;r&&(i[e]=t(e,r))}else Array.from(this.remoteStats.entries()).forEach((e=>{let[n,{videoStats:r}]=e;r&&(i[n]=t(n,r))}));return i}getRTCStats(){let e=0,t=0,i=0,n=0;const r=this.localStats.get(sw.LocalAudioTrack);r&&(e+=r.sendBytes,t+=r.sendBitrate);const o=this.localStats.get(sw.LocalVideoTrack);o&&(e+=o.sendBytes,t+=o.sendBitrate);const s=this.localStats.get(sw.LocalVideoLowTrack);s&&(e+=s.sendBytes,t+=s.sendBitrate),this.remoteStats.forEach((e=>{let{audioStats:t,videoStats:r}=e;t&&(i+=t.receiveBytes,n+=t.receiveBitrate),r&&(i+=r.receiveBytes,n+=r.receiveBitrate)}));let a=1;return this.trafficStats&&(a+=this.trafficStats.peer_delay.length),{Duration:0,UserCount:a,SendBitrate:t,SendBytes:e,RecvBytes:i,RecvBitrate:n,OutgoingAvailableBandwidth:this.uplinkStats?this.uplinkStats.B_uab/1e3:0,RTT:this.trafficStats?2*this.trafficStats.B_acd:0}}addLocalStats(e){this.localStats.set(e,void 0)}removeLocalStats(e){e?this.localStats.delete(e):this.localStats.clear()}addRemoteStats(e){this.remoteStats.set(e,{})}removeRemoteStats(e){e?this.remoteStats.delete(e):this.remoteStats.clear()}addP2PChannel(e){this.p2pChannel=e}updateTrafficStats(e){e.peer_delay=e.peer_delay.filter((e=>void 0!==e.B_ppad||void 0!==e.B_ppvd));e.peer_delay.filter((e=>-1===this.trafficStatsPeerList.indexOf(e.peer_uid))).forEach((e=>{var t;const i=null===(t=this.p2pChannel)||void 0===t?void 0:t.getRemoteMedia(e.peer_uid),n=null!=i&&i.videoSSRC?iB.measureFromSubscribeStart(this.store.clientId,i.videoSSRC):0,r=null!=i&&i.audioSSRC?iB.measureFromSubscribeStart(this.store.clientId,i.audioSSRC):0;void 0!==e.B_ppad&&void 0!==e.B_ppvd&&(this.onUploadPublishDuration&&this.onUploadPublishDuration(e.peer_uid,e.B_ppad,e.B_ppvd,n>r?n:r),this.trafficStatsPeerList.push(e.peer_uid))})),this.trafficStats=e}updateUplinkStats(e){this.uplinkStats&&this.uplinkStats.B_fir!==e.B_fir&&Qy.debug(\"[\".concat(this.store.clientId,\"]: Period fir changes to \").concat(e.B_fir)),this.uplinkStats=e}static isRemoteVideoFreeze(e,t,i){if(!e)return!1;const n=!!i&&t.framesDecodeFreezeTime>i.framesDecodeFreezeTime,r=!i||t.framesDecodeCount>i.framesDecodeCount;return n||!r}static isRemoteAudioFreeze(e){return!!e&&e._isFreeze()}isLocalVideoFreeze(e){return!(!e.inputFrame||!e.sentFrame)&&(e.inputFrame.frameRate>5&&e.sentFrame.frameRate<3)}updateLocalStats(e){Array.from(this.localStats.entries()).forEach((t=>{let[i,n]=t;switch(i){case sw.LocalVideoTrack:case sw.LocalVideoLowTrack:{const t=n,o=cG({},GU),s=e.getStats(),a=e.getLocalMedia(i);if(s){const i=s.videoSend.find((e=>e.ssrc===(null==a?void 0:a.ssrcs[0].ssrcId)));if(i){const n=e.getLocalVideoSize(),r=e.getEncoderConfig(sw.LocalVideoTrack);\"H264\"!==i.codec&&\"H265\"!==i.codec&&\"VP8\"!==i.codec&&\"VP9\"!==i.codec&&\"AV1X\"!==i.codec&&\"AV1\"!==i.codec||(o.codecType=i.codec),o.sendBytes=i.bytes,o.sendBitrate=t?8*Math.max(0,o.sendBytes-t.sendBytes):0,i.inputFrame?(o.captureFrameRate=i.inputFrame.frameRate,o.captureResolutionHeight=i.inputFrame.height,o.captureResolutionWidth=i.inputFrame.width):n&&(o.captureResolutionWidth=n.width,o.captureResolutionHeight=n.height),i.sentFrame?(o.sendFrameRate=i.sentFrame.frameRate,o.sendResolutionHeight=i.sentFrame.height,o.sendResolutionWidth=i.sentFrame.width):n&&(o.sendResolutionWidth=n.width,o.sendResolutionHeight=n.height),i.avgEncodeMs&&(o.encodeDelay=i.avgEncodeMs),r&&r.bitrateMax&&(o.targetSendBitrate=1e3*r.bitrateMax),o.sendPackets=i.packets,o.sendPacketsLost=i.packetsLost,o.sendJitterMs=i.jitterMs,o.sendRttMs=i.rttMs,o.totalDuration=t?t.totalDuration+1:1,o.totalFreezeTime=t?t.totalFreezeTime:0,this.isLocalVideoFreeze(i)&&(o.totalFreezeTime+=1),i.scalabilityMode&&this.scalabilityMode!==i.scalabilityMode&&(Qy.debug(\"[\".concat(this.store.clientId,\"]: The scalabilityMode of the video sending stream is \").concat(i.scalabilityMode)),this.scalabilityMode=i.scalabilityMode)}this.trafficStats&&(o.currentPacketLossRate=(this.trafficStats.B_pvlr4||0)/100)}var r;if(this.localStats.set(i,o),(null==t?void 0:t.sendResolutionWidth)!==o.sendResolutionWidth||(null==t?void 0:t.sendResolutionHeight)!==o.sendResolutionHeight)null===(r=this.onStatsChanged)||void 0===r||r.call(this,\"resolution\",{width:o.sendResolutionWidth,height:o.sendResolutionHeight});o&&a&&this.exceptionMonitor.setLocalVideoStats(this.store.uid,a.track,o);break}case sw.LocalAudioTrack:{const t=n,r=cG({},jU),o=e.getStats(),s=e.getLocalMedia(i);if(o){const i=o.audioSend.find((e=>e.ssrc===(null==s?void 0:s.ssrcs[0].ssrcId)));if(i){if(\"opus\"!==i.codec&&\"aac\"!==i.codec&&\"PCMU\"!==i.codec&&\"PCMA\"!==i.codec&&\"G722\"!==i.codec||(r.codecType=i.codec),i.inputLevel)r.sendVolumeLevel=Math.round(32767*i.inputLevel);else{const t=e.getLocalAudioVolume();t&&(r.sendVolumeLevel=Math.round(32767*t))}r.sendBytes=i.bytes,r.sendPackets=i.packets,r.sendPacketsLost=i.packetsLost,r.sendJitterMs=i.jitterMs,r.sendRttMs=i.rttMs,r.sendBitrate=t?8*Math.max(0,r.sendBytes-t.sendBytes):0}}this.trafficStats&&(r.currentPacketLossRate=(this.trafficStats.B_palr4||0)/100),this.localStats.set(sw.LocalAudioTrack,r),r&&s&&this.exceptionMonitor.setLocalAudioStats(this.store.uid,s.track,r);break}}}))}updateRemoteStats(e){Array.from(this.remoteStats.entries()).forEach((t=>{var i,n;let[r,{videoStats:o,audioStats:s,videoPcStats:a}]=t;const c=s,d=o,l=a,h=cG({},WU),u=cG({},KU),p=cG({},HU),{audioTrack:_,videoTrack:E,audioSSRC:m,videoSSRC:f}=e.getRemoteMedia(r);let T;T=e instanceof oG?e.getStats(!0):e.getStats();const S=null===(i=T)||void 0===i?void 0:i.audioRecv.find((e=>e.ssrc===m)),g=null===(n=T)||void 0===n?void 0:n.videoRecv.find((e=>e.ssrc===f)),R=this.trafficStats&&this.trafficStats.peer_delay.find((e=>e.peer_uid===r));if(S&&(\"opus\"!==S.codec&&\"aac\"!==S.codec&&\"PCMU\"!==S.codec&&\"PCMA\"!==S.codec&&\"G722\"!==S.codec||(h.codecType=S.codec),S.outputLevel?h.receiveLevel=Math.round(32767*S.outputLevel):_&&(h.receiveLevel=Math.round(32767*_.getVolumeLevel())),h.receiveBytes=S.bytes,h.receivePackets=S.packets,h.receivePacketsLost=S.packetsLost,h.packetLossRate=h.receivePacketsLost/(h.receivePackets+h.receivePacketsLost),h.receiveBitrate=c?8*Math.max(0,h.receiveBytes-c.receiveBytes):0,h.totalDuration=c?c.totalDuration+1:1,h.totalFreezeTime=c?c.totalFreezeTime:0,h.freezeRate=h.totalFreezeTime/h.totalDuration,h.receiveDelay=S.jitterBufferMs,h.totalDuration>10&&dG.isRemoteAudioFreeze(_)&&(h.totalFreezeTime+=1)),g){\"H264\"!==g.codec&&\"H265\"!==g.codec&&\"VP8\"!==g.codec&&\"VP9\"!==g.codec&&\"AV1X\"!==g.codec&&\"AV1\"!==g.codec||(u.codecType=g.codec),u.receiveBytes=g.bytes,u.receiveBitrate=d?8*Math.max(0,u.receiveBytes-d.receiveBytes):0,u.decodeFrameRate=g.decodeFrameRate<0?0:g.decodeFrameRate,u.renderFrameRate=g.decodeFrameRate<0?0:g.decodeFrameRate,g.outputFrame&&(u.renderFrameRate=g.outputFrame.frameRate),g.receivedFrame?(u.receiveFrameRate=g.receivedFrame.frameRate,u.receiveResolutionHeight=g.receivedFrame.height,u.receiveResolutionWidth=g.receivedFrame.width):E&&(u.receiveResolutionHeight=E._videoHeight||0,u.receiveResolutionWidth=E._videoWidth||0),void 0!==g.framesRateFirefox&&(u.receiveFrameRate=Math.round(g.framesRateFirefox)),u.receivePackets=g.packets,u.receivePacketsLost=g.packetsLost,u.packetLossRate=u.receivePacketsLost/(u.receivePackets+u.receivePacketsLost),u.totalDuration=d?d.totalDuration+1:1,u.totalFreezeTime=d?d.totalFreezeTime:0,u.receiveDelay=g.jitterBufferMs||0;const t=!!f&&e.getRemoteVideoIsReady(f);E&&t&&dG.isRemoteVideoFreeze(E,g,l)&&(u.totalFreezeTime+=1),u.freezeRate=u.totalFreezeTime/u.totalDuration}R&&(h.end2EndDelay=R.B_ad,u.end2EndDelay=R.B_vd,h.transportDelay=R.B_ed,u.transportDelay=R.B_ed,h.currentPacketLossRate=R.B_ealr4/100,u.currentPacketLossRate=R.B_evlr4/100,p.uplinkNetworkQuality=R.B_punq?R.B_punq:0,p.downlinkNetworkQuality=R.B_pdnq?R.B_pdnq:0),this.remoteStats.set(r,{audioStats:h,videoStats:u,videoPcStats:g,networkStats:p}),_&&this.exceptionMonitor.setRemoteAudioStats(_,h),E&&this.exceptionMonitor.setRemoteVideoStats(E,u)}))}}function lG(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function hG(e){for(var t=1;t{this.reconnectMode=\"retry\",this.startPingPong()})),ng(this,\"handleWebSocketMessage\",(e=>{if(!e.data)return;const t=JSON.parse(e.data);t.requestId?this.emit(\"@\".concat(t.requestId,\"-\").concat(t.sid),t):this.serviceMode===Nb.INJECT?this.emit(xb.INJECT_STREAM_STATUS,t):(oA.workerEvent(this.spec.sid,{actionType:\"status\",serverCode:t.code,workerType:this.serviceMode===Nb.TRANSCODE?1:2}),this.emit(xb.PUBLISH_STREAM_STATUS,t))})),this.spec=t,this.token=e,this.serviceMode=n,this.websocket=new Fw(\"live-streaming\",i),this.websocket.on(Ab.CONNECTED,this.handleWebSocketOpen),this.websocket.on(Ab.ON_MESSAGE,this.handleWebSocketMessage),this.websocket.on(Ab.REQUEST_NEW_URLS,((e,t)=>{kI(this,xb.REQUEST_NEW_ADDRESS).then(e).catch(t)})),this.websocket.on(Ab.RECONNECTING,(()=>{this.websocket.reconnectMode=this.reconnectMode}))}init(e){return this.websocket.init(e)}async request(e,t,i,n){this.reqId+=1,\"request\"===e&&(this.commandReqId+=1);const r=this.commandReqId,o=this.reqId;if(!o||!this.websocket)throw new bb(tI.UNEXPECTED_ERROR);const s=hG({command:e,sdkVersion:\"4.21.0\"===Iy?\"0.0.1\":Iy,seq:o,requestId:o,allocate:i,cname:this.spec.cname,appId:this.spec.appId,sid:this.spec.sid,uid:this.spec.uid.toString(),ts:Math.floor(Date.now()/1e3)},t);if(\"closed\"===this.websocket.state)throw new bb(tI.WS_DISCONNECT);const a=()=>new Gu(((e,t)=>{this.websocket.once(Ab.CLOSED,(()=>t(new bb(tI.WS_ABORT)))),this.websocket.once(Ab.CONNECTED,e)}));\"connected\"!==this.websocket.state&&await a(),s.clientRequest&&(s.clientRequest.workerToken=this.token);const c=new Gu(((e,t)=>{const i=()=>{t(new bb(tI.WS_ABORT))};this.websocket.once(Ab.RECONNECTING,i),this.websocket.once(Ab.CLOSED,i),this.once(\"@\".concat(o,\"-\").concat(this.spec.sid),(t=>{e(t)}))}));n&&oA.workerEvent(this.spec.sid,hG(hG({},n),{},{requestId:r,actionType:\"request\",payload:JSON.stringify(t.clientRequest),serverCode:0,code:0}));const d=Date.now();this.websocket.sendMessage(s);let l=null;try{l=await c}catch(n){if(\"closed\"===this.websocket.state)throw n;return await a(),await this.request(e,t,i)}return n&&oA.workerEvent(this.spec.sid,hG(hG({},n),{},{requestId:r,actionType:\"response\",payload:JSON.stringify(l.serverResponse),serverCode:l.code,success:200===l.code,responseTime:Date.now()-d})),200!==l.code&&this.handleResponseError(l),l}tryNextAddress(){this.reconnectMode=\"tryNext\",this.websocket.reconnect(\"tryNext\")}close(){const e=\"4.21.0\"===Iy?\"0.0.1\":Iy;this.reqId+=1,\"connected\"===this.websocket.state?(this.websocket.sendMessage({command:\"request\",appId:this.spec.appId,cname:this.spec.cname,uid:this.spec.uid.toString(),sdkVersion:e,sid:this.spec.sid,seq:this.reqId,ts:Math.floor(Date.now()/1e3),requestId:this.reqId,clientRequest:{command:\"DestroyWorker\"}}),this.websocket.close(!1,!0)):this.websocket.close(!1),this.pingpongTimer&&(window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0)}handleResponseError(e){switch(e.code){case Fb.LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM:return void Qy.warning(\"live stream response already exists stream\");case Fb.LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR:case Fb.LIVE_STREAM_RESPONSE_BAD_STREAM:case Fb.LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR:return new bb(tI.LIVE_STREAMING_INVALID_ARGUMENT,\"\",{code:e.code}).throw();case Fb.LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST:if(\"UnpublishStream\"===e.serverResponse.command||\"UninjectStream\"===e.serverResponse.command)return;throw new bb(tI.LIVE_STREAMING_INTERNAL_SERVER_ERROR,\"live stream response wm worker not exist\",{retry:!0});case Fb.LIVE_STREAM_RESPONSE_NOT_AUTHORIZED:return new bb(tI.LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED,\"\",{code:e.code}).throw();case Fb.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE:{const t=new bb(tI.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE);return this.emit(xb.WARNING,t,e.serverResponse.url)}case Fb.LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN:{const t=new bb(tI.LIVE_STREAMING_WARN_FREQUENT_REQUEST);return this.emit(xb.WARNING,t,e.serverResponse.url)}case Fb.LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH:throw new bb(tI.LIVE_STREAMING_INTERNAL_SERVER_ERROR,\"live stream response wm worker not exist\",{retry:!0});case Fb.LIVE_STREAM_RESPONSE_NOT_SUPPORTED:return new bb(tI.LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED,\"\",{code:e.code}).throw();case Fb.LIVE_STREAM_RESPONSE_MAX_STREAM_NUM:{const t=new bb(tI.LIVE_STREAMING_WARN_STREAM_NUM_REACH_LIMIT);return this.emit(xb.WARNING,t,e.serverResponse.url)}case Fb.LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR:return new bb(tI.LIVE_STREAMING_INTERNAL_SERVER_ERROR,\"\",{code:e.code}).throw();case Fb.LIVE_STREAM_RESPONSE_RESOURCE_LIMIT:throw new bb(tI.LIVE_STREAMING_INTERNAL_SERVER_ERROR,\"live stream resource limit\",{retry:!0,changeAddress:!0});case Fb.LIVE_STREAM_RESPONSE_WORKER_LOST:case Fb.LIVE_STREAM_RESPONSE_WORKER_QUIT:if(\"UnpublishStream\"===e.serverResponse.command||\"UninjectStream\"===e.serverResponse.command)return;throw new bb(tI.LIVE_STREAMING_INTERNAL_SERVER_ERROR,\"error fail send message\",{retry:!0,changeAddress:!0});case Fb.ERROR_FAIL_SEND_MESSAGE:if(\"UnpublishStream\"===e.serverResponse.command||\"UninjectStream\"===e.serverResponse.command)return;if(\"UpdateTranscoding\"===e.serverResponse.command||\"ControlStream\"===e.serverResponse.command)return new bb(tI.LIVE_STREAMING_INTERNAL_SERVER_ERROR,\"error fail send message\",{code:e.code}).throw();throw new bb(tI.LIVE_STREAMING_INTERNAL_SERVER_ERROR,\"error fail send message\",{retry:!0,changeAddress:!0});case Fb.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN:case Fb.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT:case Fb.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE:case Fb.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH:return new bb(tI.LIVE_STREAMING_CDN_ERROR,\"\",{code:e.code}).throw()}}startPingPong(){this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval((()=>{\"connected\"===this.websocket.state&&this.request(\"ping\",{}).catch(iy)}),6e3)}}function pG(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function _G(e){for(var t=1;t1&&void 0!==arguments[1]?arguments[1]:_y,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:_y;super(),ng(this,\"onLiveStreamWarning\",void 0),ng(this,\"onLiveStreamError\",void 0),ng(this,\"onInjectStatusChange\",void 0),ng(this,\"spec\",void 0),ng(this,\"retryTimeout\",1e4),ng(this,\"connection\",void 0),ng(this,\"httpRetryConfig\",void 0),ng(this,\"wsRetryConfig\",void 0),ng(this,\"streamingTasks\",new Map),ng(this,\"isStartingStreamingTask\",!1),ng(this,\"taskMutex\",new uy(\"live-streaming\")),ng(this,\"cancelToken\",pv.CancelToken.source()),ng(this,\"transcodingConfig\",void 0),ng(this,\"injectConfig\",_G({},Ub)),ng(this,\"injectLoopTimes\",0),ng(this,\"uapResponse\",void 0),ng(this,\"lastTaskId\",1),ng(this,\"statusError\",new Map),this.spec=e,this.httpRetryConfig=i,this.wsRetryConfig=t}async setTranscodingConfig(e){const t=_G(_G({},Mb),e);66!==t.videoCodecProfile&&77!==t.videoCodecProfile&&100!==t.videoCodecProfile&&(Qy.debug(\"[\".concat(this.spec.clientId,\"] set transcoding config, fix video codec profile: \").concat(t.videoCodecProfile,\" -> 100\")),t.videoCodecProfile=100),t.transcodingUsers||(t.transcodingUsers=t.userConfigs),t.transcodingUsers&&(t.transcodingUsers=t.transcodingUsers.map((e=>_G(_G(_G({},Pb),e),{},{zOrder:e.zOrder?e.zOrder+1:1})))),function(e){dI(e.width)||oI(e.width,\"config.width\",0,1e4),dI(e.height)||oI(e.height,\"config.height\",0,1e4),dI(e.videoBitrate)||oI(e.videoBitrate,\"config.videoBitrate\",1,1e6),dI(e.videoFrameRate)||oI(e.videoFrameRate,\"config.videoFrameRate\"),dI(e.lowLatency)||nI(e.lowLatency,\"config.lowLatency\"),dI(e.audioSampleRate)||rI(e.audioSampleRate,\"config.audioSampleRate\",[32e3,44100,48e3]),dI(e.audioBitrate)||oI(e.audioBitrate,\"config.audioBitrate\",1,128),dI(e.audioChannels)||rI(e.audioChannels,\"config.audioChannels\",[1,2,3,4,5]),dI(e.videoGop)||oI(e.videoGop,\"config.videoGop\"),dI(e.videoCodecProfile)||rI(e.videoCodecProfile,\"config.videoCodecProfile\",[66,77,100]),dI(e.userCount)||oI(e.userCount,\"config.userCount\",0,17),dI(e.backgroundColor)||oI(e.backgroundColor,\"config.backgroundColor\",0,16777215),dI(e.userConfigExtraInfo)||aI(e.userConfigExtraInfo,\"config.userConfigExtraInfo\",0,4096,!1),e.transcodingUsers&&!dI(e.transcodingUsers)&&(cI(e.transcodingUsers,\"config.transcodingUsers\"),e.transcodingUsers.forEach(((e,t)=>{Ob(e.uid),dI(e.x)||oI(e.x,\"transcodingUser[\".concat(t,\"].x\"),0,1e4),dI(e.y)||oI(e.y,\"transcodingUser[\".concat(t,\"].y\"),0,1e4),dI(e.width)||oI(e.width,\"transcodingUser[\".concat(t,\"].width\"),0,1e4),dI(e.height)||oI(e.height,\"transcodingUser[\".concat(t,\"].height\"),0,1e4),dI(e.zOrder)||oI(e.zOrder-1,\"transcodingUser[\".concat(t,\"].zOrder\"),0,100),dI(e.alpha)||oI(e.alpha,\"transcodingUser[\".concat(t,\"].alpha\"),0,1,!1)}))),dI(e.watermark)||kb(e.watermark,\"watermark\"),dI(e.backgroundImage)||kb(e.backgroundImage,\"backgroundImage\"),e.images&&!dI(e.images)&&(cI(e.images,\"config.images\"),e.images.forEach(((e,t)=>{kb(e,\"images[\".concat(t,\"]\"))})))}(t);const i=[];t.images&&i.push(...t.images.map((e=>_G(_G(_G({},Lb),e),{},{zOrder:255})))),t.backgroundImage&&(i.push(_G(_G(_G({},Lb),t.backgroundImage),{},{zOrder:0})),delete t.backgroundImage),t.watermark&&(i.push(_G(_G(_G({},Lb),t.watermark),{},{zOrder:255})),delete t.watermark),t.images=i,t.transcodingUsers&&(t.userConfigs=t.transcodingUsers.map((e=>_G({},e))),t.userCount=t.transcodingUsers.length,delete t.transcodingUsers);const n=(t.userConfigs||[]).map((e=>\"number\"==typeof e.uid?Gu.resolve(e.uid):jO(e.uid,this.spec,this.cancelToken.token,this.httpRetryConfig)));if((await Gu.all(n)).forEach(((e,i)=>{t.userConfigs&&t.userConfigs[i]&&(t.userConfigs[i].uid=e)})),this.transcodingConfig=t,this.connection)try{var r;const e=await this.connection.request(\"request\",{clientRequest:{command:\"UpdateTranscoding\",transcodingConfig:this.transcodingConfig}},!1,{command:\"UpdateTranscoding\",workerType:1,requestByUser:!0,tid:Array.from(ub(r=this.streamingTasks).call(r)).map((e=>e.taskId)).join(\"#\")});Qy.debug(\"[\".concat(this.spec.clientId,\"] update live transcoding config success, code: \").concat(e.code,\", config:\"),JSON.stringify(this.transcodingConfig))}catch(e){if(!e.data||!e.data.retry)throw e;e.data.changeAddress&&this.connection.tryNextAddress(),this.streamingTasks.forEach((t=>{Qy.warning(\"[\".concat(this.spec.clientId,\"] live streaming receive error\"),e.toString(),\"try to republish\",t.url),this.startLiveStreamingTask(t.url,t.mode,e).then((()=>{Qy.debug(\"[\".concat(this.spec.clientId,\"] live streaming republish \").concat(t.url,\" success\"))})).catch((e=>{Qy.error(\"[\".concat(this.spec.clientId,\"] live streaming republish failed\"),t.url,e.toString()),this.onLiveStreamError&&this.onLiveStreamError(t.url,e)}))}))}}setInjectStreamConfig(e,t){this.injectConfig=Object.assign({},this.injectConfig,e),this.injectLoopTimes=t}async startLiveStreamingTask(e,t,i){var n;const r=Array.from(ub(n=this.streamingTasks).call(n)).find((e=>e.mode===Nb.INJECT));if(r&&t===Nb.INJECT)return new bb(tI.LIVE_STREAMING_TASK_CONFLICT,\"inject stream over limit\").throw();if(!this.transcodingConfig&&t===Nb.TRANSCODE)throw new bb(tI.INVALID_OPERATION,\"[LiveStreaming] no transcoding config found, can not start transcoding streaming task\");let o={command:\"PublishStream\",ts:Date.now(),url:e,uid:this.spec.uid.toString(),autoDestroyTime:100,acceptImageTimeout:!0};Qy.debug(\"[\".concat(this.spec.clientId,\"] start live streaming \").concat(e,\", mode: \").concat(t));const s=await this.taskMutex.lock();if(!this.connection&&i)return void s();if(this.streamingTasks.get(e)&&!i)return s(),new bb(tI.LIVE_STREAMING_TASK_CONFLICT).throw();try{this.connection||(this.connection=await this.connect(t))}catch(e){throw s(),e}switch(t){case Nb.TRANSCODE:o.transcodingConfig=_G({},this.transcodingConfig);break;case Nb.RAW:break;case Nb.INJECT:o={cname:this.spec.cname,command:\"InjectStream\",sid:this.spec.sid,transcodingConfig:this.injectConfig,ts:Date.now(),url:e,loopTimes:this.injectLoopTimes}}this.uapResponse&&this.uapResponse.vid&&(o.vid=this.uapResponse.vid),this.isStartingStreamingTask=!0;const a=this.lastTaskId++;try{const n=new Gu(((t,n)=>{$I(this.retryTimeout).then((()=>{if(i)return n(i);const t=this.statusError.get(e);return t?(this.statusError.delete(e),n(t)):void 0}))})),r=await Gu.race([this.connection.request(\"request\",{clientRequest:o},!0,{url:e,command:\"PublishStream\",workerType:t===Nb.TRANSCODE?1:2,requestByUser:!i,tid:a.toString()}),n]);this.isStartingStreamingTask=!1,Qy.debug(\"[\".concat(this.spec.clientId,\"] live streaming started, code: \").concat(r.code)),this.streamingTasks.set(e,{clientRequest:o,mode:t,url:e,taskId:a}),s()}catch(n){if(s(),this.isStartingStreamingTask=!1,!n.data||!n.data.retry||i)throw n;return n.data.changeAddress?(this.connection.tryNextAddress(),await this.startLiveStreamingTask(e,t,n)):await this.startLiveStreamingTask(e,t,n)}}stopLiveStreamingTask(e){return new Gu(((t,i)=>{const n=this.streamingTasks.get(e);if(!n||!this.connection)return new bb(tI.UNEXPECTED_ERROR,\"can not find streaming task to stop\").throw();const r=n.mode;n.abortTask=()=>{Qy.debug(\"[\".concat(this.spec.clientId,\"] stop live streaming success(worker exception)\")),this.streamingTasks.delete(e),t()},this.connection.request(\"request\",{clientRequest:{command:r===Nb.INJECT?\"UninjectStream\":\"UnpublishStream\",url:n.url}},!1,{url:e,command:\"UnPublishStream\",workerType:r===Nb.TRANSCODE?1:2,requestByUser:!0,tid:(this.lastTaskId++).toString()}).then((i=>{Qy.debug(\"[\".concat(this.spec.clientId,\"] stop live streaming success, code: \").concat(i.code)),this.streamingTasks.delete(e),0===this.streamingTasks.size&&r!==Nb.INJECT&&(this.connection&&this.connection.close(),this.connection=void 0),t(),r===Nb.INJECT&&this.onInjectStatusChange&&this.onInjectStatusChange(Db.INJECT_STREAM_STATUS_STOP_SUCCESS,this.spec.uid,e)})).catch(i)}))}async controlInjectStream(e,t,i,n){const r=this.streamingTasks.get(e);if(!r||!this.connection||r.mode!==Nb.INJECT)throw new bb(tI.INVALID_OPERATION,\"can not find inject stream task to control\");return(await this.connection.request(\"request\",{clientRequest:{command:\"ControlStream\",url:e,control:t,audioVolume:i,position:n}})).serverResponse}resetAllTask(){var e;const t=Array.from(ub(e=this.streamingTasks).call(e));this.terminate();for(const e of t)this.startLiveStreamingTask(e.url,e.mode).catch((t=>{this.onLiveStreamError&&this.onLiveStreamError(e.url,t)}))}terminate(){this.cancelToken&&this.cancelToken.cancel(),this.streamingTasks=new Map,this.isStartingStreamingTask=!1,this.statusError=new Map,this.cancelToken=pv.CancelToken.source(),this.uapResponse=void 0,this.connection&&this.connection.close(),this.connection=void 0}async connect(e){if(this.connection)throw new bb(tI.UNEXPECTED_ERROR,\"live streaming connection has already connected\");const t=await kI(this,Vb.REQUEST_WORKER_MANAGER_LIST,e);return this.uapResponse=t,this.connection=new uG(t.workerToken,this.spec,this.wsRetryConfig,e),this.connection.on(xb.WARNING,((e,t)=>this.onLiveStreamWarning&&this.onLiveStreamWarning(t,e))),this.connection.on(xb.PUBLISH_STREAM_STATUS,(e=>this.handlePublishStreamServer(e))),this.connection.on(xb.INJECT_STREAM_STATUS,(e=>this.handleInjectStreamServerStatus(e))),this.connection.on(xb.REQUEST_NEW_ADDRESS,((t,i)=>{if(!this.connection)return i(new bb(tI.UNEXPECTED_ERROR,\"can not get new live streaming address list\"));kI(this,Vb.REQUEST_WORKER_MANAGER_LIST,e).then((e=>{this.uapResponse=e,t(e.addressList)})).catch(i)})),await this.connection.init(t.addressList),this.connection}handlePublishStreamServer(e){const t=e.serverStatus&&e.serverStatus.url||\"empty_url\",i=this.streamingTasks.get(t),n=e.reason;switch(e.code){case Fb.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN:case Fb.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT:case Fb.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE:case Fb.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH:{const n=new bb(tI.LIVE_STREAMING_CDN_ERROR,\"\",{code:e.code});if(i)return Qy.error(n.toString()),this.onLiveStreamError&&this.onLiveStreamError(t,n);if(!this.isStartingStreamingTask)return;this.statusError.set(t,n)}case Fb.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE:{const e=new bb(tI.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE,n);return this.onLiveStreamWarning&&this.onLiveStreamWarning(t,e)}case Fb.LIVE_STREAM_RESPONSE_WORKER_LOST:case Fb.LIVE_STREAM_RESPONSE_WORKER_QUIT:{var r;if(!this.connection)return;this.connection.tryNextAddress();const t=Array.from(ub(r=this.streamingTasks).call(r));for(const i of t)i.abortTask?i.abortTask():(Qy.warning(\"[\".concat(this.spec.clientId,\"] publish stream status code\"),e.code,\"try to republish\",i.url),this.startLiveStreamingTask(i.url,i.mode,new bb(tI.LIVE_STREAMING_INTERNAL_SERVER_ERROR,\"\",{code:e.code})).then((()=>{Qy.debug(\"[\".concat(this.spec.clientId,\"] republish live stream success\"),i.url)})).catch((e=>{Qy.error(e.toString()),this.onLiveStreamError&&this.onLiveStreamError(i.url,e)})));return}}}handleInjectStreamServerStatus(e){const t=Number(e.uid),i=e.serverStatus&&e.serverStatus.url;switch(e.code){case 200:return void(this.onInjectStatusChange&&this.onInjectStatusChange(Db.INJECT_STREAM_STATUS_START_SUCCESS,t,i));case 451:return this.onInjectStatusChange&&this.onInjectStatusChange(Db.INJECT_STREAM_STATUS_START_ALREADY_EXISTS,t,i),void this.streamingTasks.delete(i);case 453:return this.onInjectStatusChange&&this.onInjectStatusChange(Db.INJECT_STREAM_STATUS_START_UNAUTHORIZED,t,i),void this.streamingTasks.delete(i);case 470:return this.onInjectStatusChange&&this.onInjectStatusChange(Db.INJECT_STREAM_STATUS_BROKEN,t,i),void this.streamingTasks.delete(i);case 499:return this.onInjectStatusChange&&this.onInjectStatusChange(Db.INJECT_STREAM_STATUS_START_TIMEOUT,t,i),void this.streamingTasks.delete(i);default:return void Qy.debug(\"inject stream server status\",e)}}hasUrl(e){return this.streamingTasks.has(e)}}class mG{constructor(){ng(this,\"destChannelMediaInfos\",new Map),ng(this,\"srcChannelMediaInfo\",void 0)}setSrcChannelInfo(e){Bb(e),this.srcChannelMediaInfo=e}addDestChannelInfo(e){Bb(e),this.destChannelMediaInfos.set(e.channelName,e)}removeDestChannelInfo(e){wb(e),this.destChannelMediaInfos.delete(e)}getSrcChannelMediaInfo(){return this.srcChannelMediaInfo}getDestChannelMediaInfo(){return this.destChannelMediaInfos}}function fG(e){if(!(e instanceof mG)){return new bb(tI.INVALID_PARAMS,\"Config should be instance of [ChannelMediaRelayConfiguration]\").throw()}const t=e.getSrcChannelMediaInfo(),i=e.getDestChannelMediaInfo();if(!t){return new bb(tI.INVALID_PARAMS,\"srcChannelMediaInfo should not be empty\").throw()}if(0===i.size){return new bb(tI.INVALID_PARAMS,\"destChannelMediaInfo should not be empty\").throw()}}class TG extends SI{constructor(e,t,i){super(),ng(this,\"ws\",void 0),ng(this,\"requestId\",1),ng(this,\"heartBeatTimer\",void 0),ng(this,\"joinInfo\",void 0),ng(this,\"clientId\",void 0),ng(this,\"onOpen\",(()=>{this.emit(\"open\"),this.startHeartBeatCheck()})),ng(this,\"onClose\",(e=>{this.emit(\"close\"),this.dispose()})),ng(this,\"onMessage\",(e=>{const t=JSON.parse(e.data);if(!t||\"serverResponse\"!==t.command||!t.requestId)return t&&\"serverStatus\"===t.command&&t.serverStatus&&t.serverStatus.command?(this.emit(\"status\",t.serverStatus),void this.emit(t.serverStatus.command,t.serverStatus)):void 0;this.emit(\"req_\".concat(t.requestId),t)})),this.joinInfo=e,this.clientId=t,this.ws=new Fw(\"cross-channel-\".concat(this.clientId),i),this.ws.on(Ab.RECONNECTING,(()=>{this.ws.reconnectMode=\"retry\",this.emit(\"reconnecting\")})),this.ws.on(Ab.CONNECTED,this.onOpen),this.ws.on(Ab.ON_MESSAGE,this.onMessage),this.ws.on(Ab.CLOSED,this.onClose)}isConnect(){return\"connected\"===this.ws.state}sendMessage(e){const t=this.requestId++;return e.requestId=t,e.seq=t,this.ws.sendMessage(e),t}waitStatus(e){return new Gu(((t,i)=>{const n=window.setTimeout((()=>{i(new bb(tI.TIMEOUT,\"wait status timeout, status: \".concat(e)))}),5e3);this.once(e,(r=>{window.clearTimeout(n),r.state&&0!==r.state?i(new bb(tI.CROSS_CHANNEL_WAIT_STATUS_ERROR,\"wait status error, status: \".concat(e))):t(void 0)})),this.once(\"dispose\",(()=>{window.clearTimeout(n),i(new bb(tI.WS_ABORT))}))}))}async request(e){if(\"closed\"===this.ws.state)throw new bb(tI.WS_DISCONNECT);const t=()=>new Gu(((e,t)=>{this.ws.once(Ab.CLOSED,(()=>t(new bb(tI.WS_ABORT)))),this.ws.once(Ab.CONNECTED,e)}));\"connected\"!==this.ws.state&&await t();const i=this.sendMessage(e),n=new Gu(((e,t)=>{const n=()=>{t(new bb(tI.WS_ABORT))};this.ws.once(Ab.RECONNECTING,n),this.ws.once(Ab.CLOSED,n),this.once(\"req_\".concat(i),e),$I(3e3).then((()=>{this.removeAllListeners(\"req_\".concat(i)),this.ws.off(Ab.RECONNECTING,n),this.ws.off(Ab.CLOSED,n),t(new bb(tI.TIMEOUT,\"cross channel ws request timeout\"))}))})),r=await n;if(!r||200!==r.code)throw new bb(tI.CROSS_CHANNEL_SERVER_ERROR_RESPONSE,\"response: \".concat(JSON.stringify(r)));return r}async connect(e){this.ws.removeAllListeners(Ab.REQUEST_NEW_URLS),this.ws.on(Ab.REQUEST_NEW_URLS,(t=>{t(e)})),await this.ws.init(e)}dispose(){this.clearHeartBeatCheck(),this.emit(\"dispose\"),this.removeAllListeners(),this.ws.close()}sendPing(e){const t=this.requestId++;return e.requestId=t,this.ws.sendMessage(e),t}startHeartBeatCheck(){this.heartBeatTimer&&window.clearInterval(this.heartBeatTimer),this.heartBeatTimer=window.setInterval((()=>{this.sendPing({command:\"ping\",appId:this.joinInfo.appId,cname:this.joinInfo.cname,uid:this.joinInfo.uid.toString(),sid:this.joinInfo.sid,ts:+new Date,requestId:0})}),3e3)}clearHeartBeatCheck(){window.clearInterval(this.heartBeatTimer),this.heartBeatTimer=void 0}}class SG extends SI{set state(e){e!==this._state&&(e!==Wb.RELAY_STATE_FAILURE&&(this.errorCode=Hb.RELAY_OK),this.emit(\"state\",e,this.errorCode),this._state=e)}get state(){return this._state}constructor(e,t,i,n,r){super(),ng(this,\"joinInfo\",void 0),ng(this,\"sid\",void 0),ng(this,\"clientId\",void 0),ng(this,\"cancelToken\",pv.CancelToken.source()),ng(this,\"workerToken\",void 0),ng(this,\"requestId\",0),ng(this,\"signal\",void 0),ng(this,\"prevChannelMediaConfig\",void 0),ng(this,\"httpRetryConfig\",void 0),ng(this,\"_resolution\",void 0),ng(this,\"_state\",Wb.RELAY_STATE_IDLE),ng(this,\"errorCode\",Hb.RELAY_OK),ng(this,\"onStatus\",(e=>{Qy.debug(\"[\".concat(this.clientId,\"] ChannelMediaStatus: \").concat(JSON.stringify(e))),e&&e.command&&(\"onAudioPacketReceived\"===e.command&&this.emit(\"event\",Gb.PACKET_RECEIVED_AUDIO_FROM_SRC),\"onVideoPacketReceived\"===e.command&&this.emit(\"event\",Gb.PACKET_RECEIVED_VIDEO_FROM_SRC),\"onSrcTokenPrivilegeDidExpire\"===e.command&&(this.errorCode=Hb.SRC_TOKEN_EXPIRED,this.state=Wb.RELAY_STATE_FAILURE),\"onDestTokenPrivilegeDidExpire\"===e.command&&(this.errorCode=Hb.DEST_TOKEN_EXPIRED,this.state=Wb.RELAY_STATE_FAILURE))})),ng(this,\"onReconnect\",(async()=>{Qy.debug(\"[\".concat(this.clientId,\"] ChannelMediaSocket disconnect, reconnecting\")),this.emit(\"event\",Gb.NETWORK_DISCONNECTED),this.state=Wb.RELAY_STATE_IDLE,this.prevChannelMediaConfig&&this.sendStartRelayMessage(this.prevChannelMediaConfig).catch((e=>{this.state!==Wb.RELAY_STATE_IDLE&&(Qy.error(\"auto restart channel media relay failed\",e.toString()),this.errorCode=Hb.SERVER_CONNECTION_LOST,this.state=Wb.RELAY_STATE_FAILURE)}))})),this.joinInfo=e,this.clientId=t,this.sid=ty(),this.signal=new TG(this.joinInfo,this.clientId,i),this.httpRetryConfig=n,this._resolution=r}async startChannelMediaRelay(e){if(this.state!==Wb.RELAY_STATE_IDLE)throw new bb(tI.INVALID_OPERATION);this.state=Wb.RELAY_STATE_CONNECTING,await this.connect(),Qy.debug(\"[\".concat(this.clientId,\"] startChannelMediaRelay: connect success\"));try{await this.sendStartRelayMessage(e)}catch(e){if(e.data&&e.data.serverResponse&&\"SetSourceChannel\"===e.data.serverResponse.command)throw new bb(tI.CROSS_CHANNEL_FAILED_JOIN_SRC);if(e.data&&e.data.serverResponse&&\"SetDestChannelStatus\"===e.serverResponse.command)throw new bb(tI.CROSS_CHANNEL_FAILED_JOIN_DEST);if(e.data&&e.data.serverResponse&&\"StartPacketTransfer\"===e.serverResponse.command)throw new bb(tI.CROSS_CHANNEL_FAILED_PACKET_SENT_TO_DEST);throw e}this.prevChannelMediaConfig=e}async updateChannelMediaRelay(e){if(this.state!==Wb.RELAY_STATE_RUNNING)throw new bb(tI.INVALID_OPERATION);await this.sendUpdateMessage(e),this.prevChannelMediaConfig=e}async setVideoProfile(e){if(this._resolution=e,this.state!==Wb.RELAY_STATE_RUNNING)throw new bb(tI.INVALID_OPERATION);const t=this.genMessage(jb.SetVideoProfile);await this.signal.request(t),Qy.debug(\"[\".concat(this.clientId,\"] startChannelMediaRelay: setVideoProfile success\"))}async stopChannelMediaRelay(){await this.sendStopRelayMessage(),Qy.debug(\"[\".concat(this.clientId,\"] stopChannelMediaRelay: send stop message success\")),this.state=Wb.RELAY_STATE_IDLE,this.dispose()}dispose(){Qy.debug(\"[\".concat(this.clientId,\"] disposeChannelMediaRelay\")),this.cancelToken.cancel(),this.cancelToken=pv.CancelToken.source(),this.state=Wb.RELAY_STATE_IDLE,this.emit(\"dispose\"),this.signal.dispose(),this.prevChannelMediaConfig=void 0}async connect(){const e=await qO(this.joinInfo,this.cancelToken.token,this.httpRetryConfig);this.workerToken=e.workerToken,await this.signal.connect(e.addressList),this.emit(\"event\",Gb.NETWORK_CONNECTED),this.signal.on(\"status\",this.onStatus),this.signal.on(\"reconnecting\",this.onReconnect)}async sendStartRelayMessage(e){const t=this.genMessage(jb.StopPacketTransfer);await this.signal.request(t),await this.signal.waitStatus(\"Normal Quit\"),Qy.debug(\"[\".concat(this.clientId,\"] startChannelMediaRelay: StopPacketTransfer success\"));const i=this.genMessage(jb.SetSdkProfile,e);await this.signal.request(i),Qy.debug(\"[\".concat(this.clientId,\"] startChannelMediaRelay: SetSdkProfile success\"));const n=this.genMessage(jb.SetSourceChannel,e);await this.signal.request(n),await this.signal.waitStatus(\"SetSourceChannelStatus\"),this.emit(\"event\",Gb.PACKET_JOINED_SRC_CHANNEL),Qy.debug(\"[\".concat(this.clientId,\"] startChannelMediaRelay: SetSourceChannel success\"));const r=this.genMessage(jb.SetSourceUserId,e);await this.signal.request(r),Qy.debug(\"[\".concat(this.clientId,\"] startChannelMediaRelay: SetSourceUserId success\"));const o=this.genMessage(jb.SetDestChannel,e);await this.signal.request(o),await this.signal.waitStatus(\"SetDestChannelStatus\"),this.emit(\"event\",Gb.PACKET_JOINED_DEST_CHANNEL),Qy.debug(\"[\".concat(this.clientId,\"] startChannelMediaRelay: SetDestChannel success\"));const s=this.genMessage(jb.StartPacketTransfer,e);await this.signal.request(s),this.emit(\"event\",Gb.PACKET_SENT_TO_DEST_CHANNEL),this.state=Wb.RELAY_STATE_RUNNING,Qy.debug(\"[\".concat(this.clientId,\"] startChannelMediaRelay: StartPacketTransfer success\")),this.setVideoProfile(this._resolution)}async sendUpdateMessage(e){const t=this.genMessage(jb.UpdateDestChannel,e);await this.signal.request(t),this.emit(\"event\",Gb.PACKET_UPDATE_DEST_CHANNEL),Qy.debug(\"[\".concat(this.clientId,\"] sendUpdateMessage: UpdateDestChannel success\"))}async sendStopRelayMessage(){const e=this.genMessage(jb.StopPacketTransfer);await this.signal.request(e),Qy.debug(\"[\".concat(this.clientId,\"] sendStopRelayMessage: StopPacketTransfer success\"))}genMessage(e,t){const i=[],n=[],r=[];this.requestId+=1;const o={appId:this.joinInfo.appId,cname:this.joinInfo.cname,uid:this.joinInfo.uid.toString(),sdkVersion:Iy,sid:this.sid,ts:Date.now(),requestId:this.requestId,seq:this.requestId,allocate:!0,clientRequest:{}};\"4.21.0\"===o.sdkVersion&&(o.sdkVersion=\"0.0.1\");let s=null,a=null;switch(e){case jb.SetSdkProfile:return o.clientRequest={command:\"SetSdkProfile\",type:\"multi_channel\"},o;case jb.SetSourceChannel:if(a=t&&t.getSrcChannelMediaInfo(),!a)throw new bb(tI.UNEXPECTED_ERROR,\"can not find source config\");return o.clientRequest={command:\"SetSourceChannel\",uid:\"0\",channelName:a.channelName,token:a.token||this.joinInfo.appId},o;case jb.SetSourceUserId:if(a=t&&t.getSrcChannelMediaInfo(),!a)throw new bb(tI.UNEXPECTED_ERROR,\"can not find source config\");return o.clientRequest={command:\"SetSourceUserId\",uid:a.uid+\"\"},o;case jb.SetDestChannel:if(s=t&&t.getDestChannelMediaInfo(),!s)throw new bb(tI.UNEXPECTED_ERROR,\"can not find dest config\");return s.forEach((e=>{i.push(e.channelName),n.push(e.uid+\"\"),r.push(e.token||this.joinInfo.appId)})),o.clientRequest={command:\"SetDestChannel\",channelName:i,uid:n,token:r},o;case jb.StartPacketTransfer:return o.clientRequest={command:\"StartPacketTransfer\"},o;case jb.Reconnect:return o.clientRequest={command:\"Reconnect\"},o;case jb.StopPacketTransfer:return o.clientRequest={command:\"StopPacketTransfer\"},o;case jb.UpdateDestChannel:if(s=t&&t.getDestChannelMediaInfo(),!s)throw new bb(tI.UNEXPECTED_ERROR,\"can not find dest config\");return s.forEach((e=>{i.push(e.channelName),n.push(e.uid+\"\"),r.push(e.token||this.joinInfo.appId)})),o.clientRequest={command:\"UpdateDestChannel\",channelName:i,uid:n,token:r},o;case jb.SetVideoProfile:o.clientRequest={command:\"SetVideoProfile\",width:this._resolution.width,height:this._resolution.height}}return o}}function gG(e){var t={},i=!1;function n(t,n){return i=!0,{done:!1,value:new nB(n=new dB((function(i){i(e[t](n))})),1)}}return t[void 0!==ZS&&$S||\"@@iterator\"]=function(){return this},t.next=function(e){return i?(i=!1,e):n(\"next\",e)},\"function\"==typeof e.throw&&(t.throw=function(e){if(i)throw i=!1,e;return n(\"throw\",e)}),\"function\"==typeof e.return&&(t.return=function(e){return i?(i=!1,e):n(\"return\",e)}),t}var RG=i(lB);function CG(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function vG(e){for(var t=1;te.rtpMap&&e.rtpMap.encodingName.toLowerCase()||\"\")).filter((e=>{var t;return Dn(t=Object.keys(My)).call(t,e)})))]}constructor(t,i){super(t,i),ng(this,\"store\",void 0),ng(this,\"peerConnection\",void 0),ng(this,\"remoteSDP\",void 0),ng(this,\"initialOffer\",void 0),ng(this,\"statsFilter\",void 0),ng(this,\"useRTX\",!1),ng(this,\"localCapabilities\",void 0),ng(this,\"localCandidateCount\",0),ng(this,\"allCandidatesReceived\",!1),ng(this,\"establishPromise\",void 0),ng(this,\"mutex\",new uy(\"P2PConnection-mutex\")),this.store=i,this.peerConnection=new RTCPeerConnection(e.resolvePCConfiguration(t),{optional:[{googDscp:!0}]}),this.statsFilter=zB(this.peerConnection,Dy(\"STATS_UPDATE_INTERVAL\"),void 0,Pv()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1,this.establishPromise=this.establish()}async establish(){try{const e=await this.peerConnection.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0});if(!e.sdp)throw new Error(\"Cannot get initialOffer.sdp when trying to establish PeerConnection.\");const t=ZB(e.sdp),i=QB(e.sdp,{filterRTX:!this.useRTX,filterVideoFec:Dy(\"FILTER_VIDEO_FEC\"),filterAudioFec:Dy(\"FILTER_AUDIO_FEC\"),filterAudioCodec:[\"opus\"]});return this.localCapabilities=i,this.initialOffer=e,AG(AG({},t),{},{rtpCapabilities:{send:{audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},recv:{audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},sendrecv:i},offerSDP:e.sdp})}catch(e){throw new iI(tI.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString())}}async connect(e,t,i,n,r,o){try{if(!this.initialOffer)throw new Error(\"Cannot establish P2PConnection without initial offer.\");this.remoteSDP=new class{constructor(e){ng(this,\"sessionDesc\",void 0),ng(this,\"localCapabilities\",void 0),ng(this,\"rtpCapabilities\",void 0),ng(this,\"candidates\",void 0),ng(this,\"iceParameters\",void 0),ng(this,\"dtlsParameters\",void 0),ng(this,\"setup\",void 0),ng(this,\"currentMidIndex\",void 0),ng(this,\"cname\",void 0),e=GI(e);const{remoteIceParameters:t,remoteDtlsParameters:i,candidates:n,remoteRTPCapabilities:r,remoteSetup:o,localCapabilities:s,sdkCodec:a,cname:c}=e,d=wB.parse(\"v=0\\no=- 0 0 IN IP4 127.0.0.1\\ns=AgoraGateway\\nt=0 0\\na=group:BUNDLE audio video\\na=msid-semantic: WMS\\na=ice-lite\\nm=audio 9 UDP/TLS/RTP/SAVPF 0\\nc=IN IP4 127.0.0.1\\na=rtcp:9 IN IP4 0.0.0.0\\na=sendrecv\\na=rtcp-mux\\na=rtcp-rsize\\na=mid:audio\\nm=video 9 UDP/TLS/RTP/SAVPF 0\\nc=IN IP4 127.0.0.1\\na=rtcp:9 IN IP4 0.0.0.0\\na=sendrecv\\na=rtcp-mux\\na=rtcp-rsize\\na=mid:video\\n\");this.rtpCapabilities=r,this.candidates=n,this.iceParameters=t,this.dtlsParameters=i,this.setup=o,this.localCapabilities=s,this.cname=c;for(let e=0;ee.payloadType.toString(10)));let e=r.videoCodecs.filter((e=>{var t,i;return null===(t=e.rtpMap)||void 0===t?void 0:Dn(i=t.encodingName.toLowerCase()).call(i,a)}));0===e.length&&(e=r.videoCodecs),s.attributes.payloads=e,s.attributes.extmaps=r.videoExtensions}\"audio\"===s.media.mediaType&&(s.media.fmts=r.audioCodecs.map((e=>e.payloadType.toString(10))),s.attributes.payloads=r.audioCodecs,s.attributes.extmaps=r.audioExtensions),d.mediaDescriptions[e]=this.mungMediaDesc(s)}this.sessionDesc=d,this.currentMidIndex=d.mediaDescriptions.length-1}toString(){return wB.print(this.sessionDesc)}send(e,t,i){const{ssrcs:n,ssrcGroups:r}=tj(t,this.cname),o=this.sessionDesc.mediaDescriptions.find((t=>e===nw.VIDEO?\"video\"===t.media.mediaType:\"audio\"===t.media.mediaType)),s=n[0].attributes.label,a=n[0].attributes.mslabel;return o.attributes.ssrcs=o.attributes.ssrcs.concat(n),o.attributes.ssrcGroups=o.attributes.ssrcGroups.concat(r),{id:s,mslabel:a}}batchSend(e){return e.map((e=>{let{kind:t,ssrcMsg:i}=e;return this.send(t,i,void 0)}))}stopSending(e){this.sessionDesc.mediaDescriptions.forEach((t=>{const i=[],n=[],r=[];t.attributes.ssrcs.forEach((t=>{Dn(e).call(e,t.attributes.label||\"\")?r.push(t):i.push(t)})),t.attributes.ssrcGroups.forEach((e=>{var t;Dn(t=r.map((e=>e.ssrcId))).call(t,e.ssrcIds[0])||n.push(e)})),t.attributes.ssrcs=i,t.attributes.ssrcGroups=n}))}mute(e){const t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error(\"mediaDescription not found with \".concat(e,\" in remote SDP when calling RemoteSDP.mute.\"));t.attributes.direction=\"inactive\"}unmute(e){const t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error(\"mediaDescription not found with \".concat(e,\" in remote SDP when calling RemoteSDP.unmute.\"));t.attributes.direction=\"sendonly\"}receive(e,t,i){e.forEach(((e,t)=>{const i=e._mediaStreamTrack,n=this.sessionDesc.mediaDescriptions.findIndex((e=>e.attributes.mid===i.kind)),r=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[n],e);this.sessionDesc.mediaDescriptions[n]=r}))}stopReceiving(e){}updateCandidates(e){e===rw.TCP?this.candidates.forEach((e=>{-1===this.candidates.findIndex((t=>\"tcp\"===t.transport&&t.connectionAddress===e.connectionAddress&&t.port===e.port))&&this.candidates.push(vG(vG({},e),{},{foundation:\"tcpcandidate\",priority:Number(e.priority)-1+\"\",transport:\"tcp\",port:Number(e.port)+90+\"\"}))})):this.candidates=this.candidates.filter((e=>\"tcp\"!==e.transport));for(const e of this.sessionDesc.mediaDescriptions)e.attributes.candidates=this.candidates}restartICE(e){e=GI(e),this.iceParameters=e,this.sessionDesc.mediaDescriptions.forEach((t=>{t.attributes.iceUfrag=e.iceUfrag,t.attributes.icePwd=e.icePwd}))}predictReceivingMids(e){const t=[];for(let i=0;it.attributes.mid===e));if(-1!==i){const e=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[i],t);this.sessionDesc.mediaDescriptions[i]=e}}bumpMid(e){this.currentMidIndex+=e}updateTrackLabel(e,t,i){const n=this.sessionDesc.mediaDescriptions.find((t=>e===nw.VIDEO?\"video\"===t.attributes.mid:\"audio\"===t.attributes.mid));if(n){const e=n.attributes.ssrcs.find((e=>e.attributes.label===t));var r;e&&(e.attributes.label=i,null===(r=e.attributes.msid)||void 0===r||r.replace(t,i))}}mungMediaDesc(e){const t=GI(e);return nj(t),function(e){const t=e.attributes.extmaps.find((e=>\"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01\"===e.extensionName));t&&e.attributes.extmaps.splice(e.attributes.extmaps.indexOf(t),1),e.attributes.payloads.forEach((e=>{const t=e.rtcpFeedbacks.findIndex((e=>\"transport-cc\"===e.type));-1!==t&&e.rtcpFeedbacks.splice(t,1)}))}(t),t}getSSRC(e){for(const t of this.sessionDesc.mediaDescriptions)for(const i of t.attributes.ssrcs)if(i.attributes.label===e)return[i]}}({remoteIceParameters:e,remoteDtlsParameters:t,candidates:i,remoteRTPCapabilities:n.send,remoteSetup:r,localCapabilities:this.localCapabilities,sdkCodec:this.store.codec,cname:o});const s=this.remoteSDP.toString();await this.peerConnection.setLocalDescription(this.initialOffer),await this.peerConnection.setRemoteDescription({type:\"answer\",sdp:s})}catch(e){throw new iI(tI.EXCHANGE_SDP_FAILED,\"P2PConnection.connect failed; \".concat(e.toString()))}}async updateRemoteRTPCapabilities(e,t){throw new iI(tI.NOT_SUPPORTED,\"Planb mode does not support createDataChannels.\")}send(e,t){var i=this;return pB((function*(){const n=yield rB(i.mutex.lock());try{if(!i.remoteSDP)throw new Error(\"Cannot call P2PConnection.send before remote SDP created\");const r=e.map((e=>i.peerConnection.addTrack(e._mediaStreamTrack))),o=yield rB(i.peerConnection.createOffer()),s=wB.parse(o.sdp),a=e.map((e=>{const t=e._mediaStreamTrack,n=s.mediaDescriptions.find((e=>e.attributes.mid===t.kind));if(!n)throw new Error(\"Cannot extract ssrc from mediaDescription.\");return function(e,t,i){const n=e.attributes.ssrcs.filter((e=>e.attributes.label===t)),r=e.attributes.ssrcGroups;if(0===n.length)throw new Error(\"Cannot extract ssrc from plan-b SDP.\");if(r&&n.length>1){const e=r.find((e=>-1!==e.ssrcIds.indexOf(n[0].ssrcId)));return e?[{ssrcId:e.ssrcIds[0],rtx:i?e.ssrcIds[1]:void 0}]:[{ssrcId:n[0].ssrcId}]}return[{ssrcId:n[0].ssrcId}]}(n,t.id,i.useRTX)}));let c;try{c=yield a}catch(e){throw r.forEach((e=>{Nv()&&e.replaceTrack(null),i.peerConnection.removeTrack(e)})),e}const d=i.mungSendOfferSDP(o.sdp,e);i.remoteSDP.receive(e,t,c);const l=i.remoteSDP.toString();return yield rB(i.peerConnection.setLocalDescription({type:\"offer\",sdp:d})),yield rB(i.applySendEncodings(r,e)),yield rB(i.peerConnection.setRemoteDescription({type:\"answer\",sdp:l})),e.map(((e,t)=>{const i=e._mediaStreamTrack.id;return{localSSRC:a[t],id:i}}))}catch(e){throw new iI(tI.EXCHANGE_SDP_FAILED,\"P2PConnection.send failed; \".concat(e.toString()))}finally{n()}}))()}async stopSending(e){try{if(!this.remoteSDP)throw new Error(\"Cannot call P2PConnection.stopSending before remote SDP created\");const t=this.peerConnection.getSenders().filter((t=>{var i;return-1!==e.indexOf((null===(i=t.track)||void 0===i?void 0:i.id)||\"\")}));if(t.length!==e.length)throw new Error(\"Transceivers' length doesn't match mids' length when trying to call P2PConnection.stopSending.\");t.map((e=>{Nv()&&e.replaceTrack(null),this.peerConnection.removeTrack(e)}));const i=await this.peerConnection.createOffer();await this.peerConnection.setLocalDescription(i),this.remoteSDP.stopReceiving(e);const n=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:\"answer\",sdp:n})}catch(e){throw new iI(tI.EXCHANGE_SDP_FAILED,\"P2PConnection.stopSending failed; \".concat(e.toString()))}}async receive(e,t,i,n){try{if(!this.remoteSDP)throw new Error(\"Cannot call P2PConnection.receive \".concat(e,\" before remoteSDP created.\"));const{id:i,mslabel:r}=this.remoteSDP.send(e,t,n),o=new Gu(((t,n)=>{const o=setTimeout((()=>{n(new Error(\"Cannot receive track, id: \".concat(i)))}),1e4),s=n=>{const a=Iv();if((\"Safari\"===a.name&&11===Number(a.version)||Lv())&&n.track.id!==i&&n.streams[0].id===r){var c;const r=n.streams[0].getTracks()[0];return null===(c=this.remoteSDP)||void 0===c||c.updateTrackLabel(e,i,n.track.id),this.peerConnection.removeEventListener(\"track\",s),clearTimeout(o),void t(r)}if(n.track.id===i)return this.peerConnection.removeEventListener(\"track\",s),clearTimeout(o),void t(n.track)};this.peerConnection.addEventListener(\"track\",s)})),s=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:\"offer\",sdp:s});const a=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(a);return{track:await o,id:i}}catch(e){throw new iI(tI.EXCHANGE_SDP_FAILED,\"P2PConnection.receive failed; \".concat(e.toString()))}}async stopReceiving(e){try{if(!this.remoteSDP)throw new Error(\"Cannot call P2PConnection.stopReceiving before remote SDP created.\");this.remoteSDP.stopSending(e);const t=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:\"offer\",sdp:t});const i=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(i)}catch(e){throw new iI(tI.EXCHANGE_SDP_FAILED,\"P2PConnection stopReceiving failed; \".concat(e.toString()))}}async muteRemote(e){}async unmuteRemote(e){}async muteLocal(e){try{if(!this.remoteSDP)throw new Error(\"Cannot call P2PConnection.muteLocal before remote SDP created.\");const t=this.peerConnection.getSenders().filter((t=>{var i;return-1!==e.indexOf((null===(i=t.track)||void 0===i?void 0:i.id)||\"\")}));if(t.length!==e.length)throw new Error(\"sender' length doesn't match mids' length.\");t.map((e=>{if(Nv()&&e.track)e.track.enabled=!1;else{const t=e.getParameters();t.encodings.forEach((e=>e.active=!1)),e.setParameters(t)}}))}catch(e){throw new iI(tI.EXCHANGE_SDP_FAILED,\"P2PConnection.muteLocal failed; \".concat(e.toString()))}}async unmuteLocal(e){try{if(!this.remoteSDP)throw new Error(\"Cannot call P2PConnection.unmuteLocal before remote SDP created.\");const t=this.peerConnection.getSenders().filter((t=>{var i;return-1!==e.indexOf((null===(i=t.track)||void 0===i?void 0:i.id)||\"\")}));if(t.length!==e.length)throw new Error(\"Senders' length doesn't match mids' length.\");t.map((async e=>{if(Nv()&&e.track)e.track.enabled=!0;else{const t=e.getParameters();t.encodings.forEach((e=>e.active=!0)),await e.setParameters(t)}}));const i=await this.peerConnection.createOffer();await this.peerConnection.setLocalDescription(i);const n=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:\"answer\",sdp:n})}catch(e){throw new iI(tI.EXCHANGE_SDP_FAILED,\"P2PConnection.unmuteLocal failed; \".concat(e.toString()))}}restartICE(e){var t=this;return pB((function*(){const i=yield rB(t.mutex.lock(\"From P2PConnection.restartICE\"));try{if(!t.remoteSDP)throw new Error(\"Cannot restartICE before remoteSDP created.\");if(_U().supportPCSetConfiguration){const i=t.peerConnection.getConfiguration(),n=e===rw.RELAY?\"relay\":\"all\";i.iceTransportPolicy!==n&&(Qy.debug(\"[\".concat(t.store.clientId,\"] restartICE change iceTransportPolicy from [\").concat(i.iceTransportPolicy,\"] to [\").concat(n,\"]\")),i.iceTransportPolicy=n,t.peerConnection.setConfiguration(i))}else if(e===rw.RELAY)return;e!==rw.RELAY&&t.remoteSDP.updateCandidates(e);const n=yield rB(t.peerConnection.createOffer({iceRestart:!0}));if(!n.sdp)throw new Error(\"Cannot restartICE because restart offer SDP does not exist.\");const r=ZB(n.sdp),{remoteIceParameters:o}=yield r.iceParameters;t.remoteSDP.restartICE(o);const s=t.remoteSDP.toString();yield rB(t.peerConnection.setLocalDescription(n)),yield rB(t.peerConnection.setRemoteDescription({type:\"answer\",sdp:s}))}catch(e){Qy.warning(\"[\".concat(t.store.clientId,\"] restart ICE failed, abort operation\"),e)}finally{i()}}))()}close(){var e;this.peerConnection.close(),null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,\"closed\"),this.unbindPCEvents(),this.unbindStatsEvents(),this.removeAllListeners(),this.statsFilter.destroy()}getStats(){return this.statsFilter.getStats()}getRemoteVideoIsReady(e){return this.statsFilter.getVideoIsReady(e)}async updateEncoderConfig(e,t){try{if(!this.remoteSDP)throw new Error(\"Cannot call P2PConnection.updateEncoderConfig before remote SDP created.\");const e=await this.peerConnection.createOffer(),i=this.mungSendOfferSDP(e.sdp,[t]);this.remoteSDP.updateRecvMedia(t._mediaStreamTrack.kind,t);const n=this.remoteSDP.toString();await this.peerConnection.setLocalDescription({type:\"offer\",sdp:i}),await this.peerConnection.setRemoteDescription({type:\"answer\",sdp:n})}catch(e){throw new iI(tI.EXCHANGE_SDP_FAILED,e.toString())}}async updateSendParameters(e,t){const i=this.peerConnection.getSenders().filter((t=>{var i;return(null===(i=t.track)||void 0===i?void 0:i.id)===e}));1===i.length&&await this.applySendEncodings(i,[t])}setStatsRemoteVideoIsReady(e,t){this.statsFilter.setVideoIsReady2(e,t)}async replaceTrack(e,t){const i=this.peerConnection.getSenders().find((e=>{var i;return(null===(i=e.track)||void 0===i?void 0:i.id)===t}));i&&await i.replaceTrack(e._mediaStreamTrack)}createDataChannels(e,t){throw new iI(tI.NOT_SUPPORTED,\"Planb mode does not support createDataChannels.\")}stopDataChannels(e){throw new iI(tI.NOT_SUPPORTED,\"Planb mode does not support stopDataChannels.\")}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var e;null===(e=this.onICEConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.iceConnectionState)},this.peerConnection.onconnectionstatechange=()=>{var e;null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.connectionState)},this.peerConnection.onicecandidate=e=>{e.candidate?this.localCandidateCount+=1:(this.peerConnection.onicecandidate=null,this.allCandidatesReceived=!0,Qy.debug(\"[\".concat(this.store.clientId,\"] [pc-\").concat(this.store.p2pId,\"] local candidate count\"),this.localCandidateCount))},setTimeout((()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,Qy.debug(\"[\".concat(this.store.clientId,\"] [pc-\").concat(this.store.p2pId,\"] onicecandidate timeout, local candidate count\"),this.localCandidateCount))}),Dy(\"CANDIDATE_TIMEOUT\"))}unbindPCEvents(){this.peerConnection.oniceconnectionstatechange=null,this.peerConnection.onconnectionstatechange=null,this.peerConnection.onsignalingstatechange=null,this.peerConnection.onicecandidateerror=null,this.peerConnection.onicecandidate=null,this.peerConnection.ontrack=null}static resolvePCConfiguration(t){const i={iceServers:[],sdpSemantics:\"plan-b\"};return t.iceServers?i.iceServers=t.iceServers:t.turnServer&&\"off\"!==t.turnServer.mode&&(bI(t.turnServer.servers)?i.iceServers=t.turnServer.servers:(i.iceServers&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers)),Dy(\"USE_TURN_SERVER_OF_GATEWAY\")&&i.iceServers&&t.turnServer.serversFromGateway&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway)),t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach((e=>{e.forceturn&&(i.iceTransportPolicy=\"relay\")})))),i}static turnServerConfigToIceServers(e){const t=[];return e.forEach((e=>{e.security?e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:\"password\",urls:\"turns:\".concat(e.turnServerURL,\":\").concat(e.tcpport,\"?transport=tcp\")}):(e.udpport&&t.push({username:e.username,credential:e.password,credentialType:\"password\",urls:\"turn:\".concat(e.turnServerURL,\":\").concat(e.udpport,\"?transport=udp\")}),e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:\"password\",urls:\"turn:\".concat(e.turnServerURL,\":\").concat(e.tcpport,\"?transport=tcp\")}))})),t}async updateRtpSenderEncodings(e,t){var i;if(!t){t=this.peerConnection.getSenders().find((t=>{var i;return(null===(i=t.track)||void 0===i?void 0:i.id)===e._mediaStreamTrack.id}))}if(!t)return Qy.warn(\"[\".concat(e.getTrackId(),\"] no rtpSender found}\"));if(!_U().supportSetRtpSenderParameters)return Qy.warn(\"Browser not support set rtp-sender parameters\");const n={},r={};if(e instanceof vF)switch(e._optimizationMode){case\"motion\":n.degradationPreference=\"maintain-framerate\";break;case\"detail\":n.degradationPreference=\"maintain-resolution\";break;default:n.degradationPreference=\"balanced\"}if(Dy(\"DSCP_TYPE\")&&Jv()){var o;const e=Dy(\"DSCP_TYPE\");Dn(o=[\"very-low\",\"low\",\"medium\",\"high\"]).call(o,e)&&(r.networkPriority=e)}const s=t.getParameters(),a=null===(i=s.encodings)||void 0===i?void 0:i[0];a&&Object.assign(a,r),Object.assign(s,n),Qy.debug(\"[\".concat(e.getTrackId(),\"] updateRtpSenderEncodings: \").concat(JSON.stringify(s.encodings))),await t.setParameters(s)}async applySendEncodings(e,t){try{if(!_U().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let i=0;i{const n=e._mediaStreamTrack,r=i.mediaDescriptions.find((e=>e.attributes.mid===n.kind));r&&ij(r,e)})),wB.print(i)}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=e=>{var t;null===(t=this.onFirstAudioReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoReceived=e=>{var t;null===(t=this.onFirstVideoReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstAudioDecoded=e=>{var t;null===(t=this.onFirstAudioDecoded)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoDecoded=(e,t,i)=>{var n;null===(n=this.onFirstVideoDecoded)||void 0===n||n.call(this,e,t,i)},this.statsFilter.onSelectedLocalCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedLocalCandidateChanged)||void 0===i||i.call(this,e,t)},this.statsFilter.onSelectedRemoteCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedRemoteCandidateChanged)||void 0===i||i.call(this,e,t)}}unbindStatsEvents(){this.statsFilter.onFirstAudioReceived=void 0,this.statsFilter.onFirstVideoReceived=void 0,this.statsFilter.onFirstAudioDecoded=void 0,this.statsFilter.onFirstVideoDecoded=void 0,this.statsFilter.onSelectedLocalCandidateChanged=void 0,this.statsFilter.onSelectedRemoteCandidateChanged=void 0}async batchReceive(e){try{if(!this.remoteSDP)throw new Error(\"Cannot call P2PConnection.batchReceive before remoteSDP created.\");const t=this.remoteSDP.batchSend(e).map(((t,i)=>{let{id:n,mslabel:r}=t;const{kind:o}=e[i];return new Gu(((e,t)=>{const i=setTimeout((()=>{t(new Error(\"Cannot receive track, id: \".concat(n)))}),1e4),s=t=>{const a=Iv();if(\"Safari\"===a.name&&11===Number(a.version)&&t.track.id!==n&&t.streams[0].id===r){var c;const r=t.streams[0].getTracks()[0];return null===(c=this.remoteSDP)||void 0===c||c.updateTrackLabel(o,n,t.track.id),this.peerConnection.removeEventListener(\"track\",s),clearTimeout(i),void e({track:r,id:n})}if(t.track.id===n)return this.peerConnection.removeEventListener(\"track\",s),clearTimeout(i),void e({track:t.track,id:n})};this.peerConnection.addEventListener(\"track\",s)}))})),i=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:\"offer\",sdp:i});const n=await this.peerConnection.createAnswer();return await this.peerConnection.setLocalDescription(n),await Gu.all(t)}catch(e){throw new iI(tI.EXCHANGE_SDP_FAILED,\"P2PConnection.receive failed; \".concat(e.toString()))}}async getRemoteSSRC(e){if(!this.remoteSDP)return;const t=this.remoteSDP.getSSRC(e);return null==t?void 0:t[0].ssrcId}setConfiguration(t){if(_U().supportPCSetConfiguration){const i=e.resolvePCConfiguration(t);this.peerConnection.setConfiguration(i)}}},nb(IG.prototype,\"connect\",[wG],Object.getOwnPropertyDescriptor(IG.prototype,\"connect\"),IG.prototype),nb(IG.prototype,\"stopSending\",[wG],Object.getOwnPropertyDescriptor(IG.prototype,\"stopSending\"),IG.prototype),nb(IG.prototype,\"receive\",[wG],Object.getOwnPropertyDescriptor(IG.prototype,\"receive\"),IG.prototype),nb(IG.prototype,\"stopReceiving\",[wG],Object.getOwnPropertyDescriptor(IG.prototype,\"stopReceiving\"),IG.prototype),nb(IG.prototype,\"muteRemote\",[wG],Object.getOwnPropertyDescriptor(IG.prototype,\"muteRemote\"),IG.prototype),nb(IG.prototype,\"unmuteRemote\",[wG],Object.getOwnPropertyDescriptor(IG.prototype,\"unmuteRemote\"),IG.prototype),nb(IG.prototype,\"muteLocal\",[wG],Object.getOwnPropertyDescriptor(IG.prototype,\"muteLocal\"),IG.prototype),nb(IG.prototype,\"unmuteLocal\",[wG],Object.getOwnPropertyDescriptor(IG.prototype,\"unmuteLocal\"),IG.prototype),nb(IG.prototype,\"close\",[wG],Object.getOwnPropertyDescriptor(IG.prototype,\"close\"),IG.prototype),nb(IG.prototype,\"updateEncoderConfig\",[wG],Object.getOwnPropertyDescriptor(IG.prototype,\"updateEncoderConfig\"),IG.prototype),nb(IG.prototype,\"updateSendParameters\",[wG],Object.getOwnPropertyDescriptor(IG.prototype,\"updateSendParameters\"),IG.prototype),nb(IG.prototype,\"replaceTrack\",[wG],Object.getOwnPropertyDescriptor(IG.prototype,\"replaceTrack\"),IG.prototype),nb(IG.prototype,\"getRemoteSSRC\",[wG],Object.getOwnPropertyDescriptor(IG.prototype,\"getRemoteSSRC\"),IG.prototype),IG);function wG(e,t,i){const n=e[t];if(\"function\"!=typeof n)throw new Error(\"Cannot use mutex on object property.\");return i.value=async function(){const e=this.mutex,i=await e.lock(\"Locking from P2PConnection.\".concat(t));try{for(var r=arguments.length,o=new Array(r),s=0;s=t.length-1&&n===UG.DOWN)return e;let o=kG(kG({},e),{},{scale:n===UG.DOWN?++r:--r});switch(i){case\"maintain-framerate\":o=kG(kG({},o),t[r].motion);break;case\"maintain-resolution\":o=kG(kG({},o),t[r].detail);break;case\"balanced\":o=kG(kG({},o),t[r].balanced)}return o}function FG(e,t){if(t){const i={overUse:0,underUse:0,adaptationList:BG(t)};xG.set(e,i)}else xG.delete(e)}function BG(e){const t=kG({},e),{bitrateMax:i,frameRate:n,scaleResolutionDownBy:r,bitrateMin:o}=t,{MIN_FRAME_RATE:s,MAX_THRESHOLD_FRAMERATE:a,MAX_SCALE:c,BITRATE_MIN_THRESHOLD:d,BITRATE_MAX_THRESHOLD:l,BWE_SCALE_UP_THRESHOLD:h,BWE_SCALE_DOWN_THRESHOLD:u,PERF_SCALE_DOWN_THRESHOLD:p,PERF_SCALE_UP_THRESHOLD:_,BALANCE_BITRATE_FACTOR:E,BALANCE_FRAMERATE_FACTOR:m,BALANCE_RESOLUTION_FACTOR:f,MOTION_RESOLUTION_FACTOR:T,MOTION_BITRATE_FACTOR:S,DETAIL_FRAMERATE_FACTOR:g,DETAIL_BITRATE_FACTOR:R}=by,C=Math.min(t.frameRate,a),v=[{scale:0,threshold:{bwe_down:Math.round(Math.pow(u,1)*i),bwe_up:i,fps_down:Math.round(Math.pow(p,1)*C),fps_up:n},balanced:{scaleResolutionDownBy:1,frameRate:n,bitrateMax:i,bitrateMin:o},motion:{scaleResolutionDownBy:1,frameRate:n,bitrateMax:i,bitrateMin:o},detail:{scaleResolutionDownBy:1,frameRate:n,bitrateMax:i,bitrateMin:o}}];for(let e=1;e<=c;e++){const t={bwe_up:Math.round(Math.pow(h,e)*i),bwe_down:Math.round(Math.pow(u,e+1)*i),fps_up:Math.round(Math.pow(_,e)*C),fps_down:Math.round(Math.pow(p,e+1)*C)},a={scaleResolutionDownBy:r/Math.pow(f,e),frameRate:Math.max(Math.round(Math.pow(m,e)*n),s),bitrateMax:Math.max(Math.round(Math.pow(E,e)*i),l),bitrateMin:Math.max(Math.round(Math.pow(E,e)*o),d)},c={scaleResolutionDownBy:r/Math.pow(T,e),frameRate:n,bitrateMax:Math.max(Math.round(Math.pow(S,e)*i),l),bitrateMin:Math.max(Math.round(Math.pow(S,e)*o),d)},I={scaleResolutionDownBy:1,frameRate:Math.max(Math.round(Math.pow(g,e)*n),s),bitrateMax:Math.max(Math.round(Math.pow(R,e)*i),l),bitrateMin:Math.max(Math.round(Math.pow(R,e)*o),d)};v.push({scale:e,threshold:t,balanced:a,motion:c,detail:I})}return v}function jG(e,t,i,n,r,o){const s=xG.get(e)||{overUse:0,underUse:0,adaptationList:BG(r)},{adaptationList:a}=s;xG.set(e,s);const{OVERUSE_TIMES_THRESHOLD:c,UNDERUSE_TIMES_THRESHOLD:d}=by,{scale:l}=n;let h,u;return\"number\"==typeof t&&t>0&&function(e,t,i,n){if(t>=i.length)return!1;let{threshold:{fps_down:r}}=i[t];return Dy(\"FORCE_AG_HIGH_FRAMERATE\")&&\"maintain-framerate\"===n&&(r=i[0].threshold.fps_down),ec)||\"number\"==typeof i&&i>0&&function(e,t,i){if(t>=i.length)return!1;const{threshold:{bwe_down:n}}=i[t];return ec)?(s.overUse=0,s.underUse=0,h=VG(n,a,o,UG.DOWN),[h,u]):(\"number\"==typeof t&&t>0&&\"number\"==typeof i&&i>0&&function(e,t,i,n){if(0===t)return;let{threshold:{fps_up:r}}=i[t];return Dy(\"FORCE_AG_HIGH_FRAMERATE\")&&\"maintain-framerate\"===n&&(r=i[1].threshold.fps_up),e>r}(t,l,a,o)&&function(e,t,i){if(0===t)return;const{threshold:{bwe_up:n}}=i[t];return e>n}(i,l,a)&&(s.underUse++,s.underUse>d&&(s.overUse=0,s.underUse=0,h=VG(n,a,o,UG.UP),0===h.scale&&(u=MG.NONE))),[h,u])}function GG(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function WG(e){for(var t=1;t=e}(14)&&xv(17,4,!0)||Uv(14)&&Vv(17,4,!0))))}const KG=new Map;function YG(e){const t=KG.get(e);if(t){const{timer:i,adaptationFunc:n,originConfig:r}=t;window.clearTimeout(i),n(r),KG.delete(e)}FG(e)}var qG;function zG(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function JG(e){for(var t=1;te.rtpMap&&e.rtpMap.encodingName.toLowerCase()||\"\")).filter((e=>{var t;return Dn(t=Object.keys(My)).call(t,e)})))]}constructor(t,i){super(t,i),ng(this,\"store\",void 0),ng(this,\"peerConnection\",void 0),ng(this,\"id\",ey(5,\"connection-\")),ng(this,\"remoteSDP\",void 0),ng(this,\"initialOffer\",void 0),ng(this,\"transportEventReceiver\",void 0),ng(this,\"statsFilter\",void 0),ng(this,\"useXR\",Dy(\"USE_XR\")),ng(this,\"localCapabilities\",void 0),ng(this,\"remoteCodecs\",void 0),ng(this,\"localCandidateCount\",0),ng(this,\"allCandidatesReceived\",!1),ng(this,\"dataStreamChannelMap\",new Map),ng(this,\"establishPromise\",void 0),ng(this,\"recoveredDataChannelIds\",[]),ng(this,\"currentDataChannelId\",1),ng(this,\"mutex\",new uy(\"P2PConnection-mutex\")),ng(this,\"qualityLimitationReason\",MG.NONE),this.store=i,this.peerConnection=new RTCPeerConnection(e.resolvePCConfiguration(t),{optional:[{googDscp:!0}]}),this.statsFilter=zB(this.peerConnection,Dy(\"STATS_UPDATE_INTERVAL\"),void 0,Pv()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1,this.establishPromise=this.establish()}async updateRemoteRTPCapabilities(e,t){if(this.remoteCodecs=t,!this.remoteSDP)return void Qy.debug(\"[P2PConnection] cannot updateRemoteRTPCapabilities before remote SDP created, local codecs: \".concat(this.localCodecs,\", codecs: \").concat(t));if(this.remoteSDP.updateRemoteCodec(e,t,this.store.codec)){const e=await this.peerConnection.createOffer(),t=this.logSDPExchange(e.sdp||\"\",\"offer\",\"local\",\"muteLocal\");await this.peerConnection.setLocalDescription(e);const i=this.remoteSDP.toString();null==t||t(i),await this.peerConnection.setRemoteDescription({type:\"answer\",sdp:i})}else Qy.debug(\"[P2PConnection] updateRemoteRTPCapabilities no need to exchange SDP.\")}async establish(){try{this.peerConnection.addTransceiver(\"video\",{direction:\"recvonly\"}),this.peerConnection.addTransceiver(\"audio\",{direction:\"recvonly\"});const e=await this.peerConnection.createOffer();if(!e.sdp)throw new Error(\"Cannot get initialOffer.sdp when trying to establish PeerConnection.\");const t=ZB(e.sdp),i=await cj({filterRTX:!Dy(\"USE_PUB_RTX\")&&!Dy(\"USE_SUB_RTX\"),filterVideoFec:Dy(\"FILTER_VIDEO_FEC\"),filterAudioFec:Dy(\"FILTER_AUDIO_FEC\"),filterVideoCodec:Dy(\"FILTER_VIDEO_CODEC\")},{useXR:this.useXR});return this.localCapabilities=hj(i),this.initialOffer=e,JG(JG({},t),{},{rtpCapabilities:i,offerSDP:e.sdp})}catch(e){throw new iI(tI.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString())}}async connect(e,t,i,n,r,o){try{if(!this.initialOffer)throw new Error(\"Cannot establish P2PConnection without initial offer.\");this.remoteSDP=new class{get localCapabilities(){return GI(this._localCapabilities)}get rtpCapabilities(){return GI(this._rtpCapabilities)}get candidates(){return GI(this._candidates)}get iceParameters(){return GI(this._iceParameters)}get dtlsParameters(){return GI(this._dtlsParameters)}constructor(e){ng(this,\"sessionDesc\",void 0),ng(this,\"_localCapabilities\",void 0),ng(this,\"_rtpCapabilities\",void 0),ng(this,\"_candidates\",void 0),ng(this,\"_iceParameters\",void 0),ng(this,\"_dtlsParameters\",void 0),ng(this,\"setup\",void 0),ng(this,\"currentMidIndex\",void 0),ng(this,\"cname\",void 0),ng(this,\"firefoxSsrcMidMap\",new Map),e=GI(e);const{remoteIceParameters:t,remoteDtlsParameters:i,candidates:n,remoteRTPCapabilities:r,remoteSetup:o,localCapabilities:s,cname:a}=e,c=wB.parse(\"v=0\\no=- 0 0 IN IP4 127.0.0.1\\ns=AgoraGateway\\nt=0 0\\na=group:BUNDLE 0 1\\na=msid-semantic: WMS\\na=ice-lite\\nm=video 9 UDP/TLS/RTP/SAVPF 0\\nc=IN IP4 127.0.0.1\\na=rtcp:9 IN IP4 0.0.0.0\\na=sendonly\\na=rtcp-mux\\na=rtcp-rsize\\na=mid:0\\nm=audio 9 UDP/TLS/RTP/SAVPF 0\\nc=IN IP4 127.0.0.1\\na=rtcp:9 IN IP4 0.0.0.0\\na=sendonly\\na=rtcp-mux\\na=rtcp-rsize\\na=mid:1\\n\");this._rtpCapabilities=r,this._candidates=n,this._iceParameters=t,this._dtlsParameters=i,this._localCapabilities=s,this.setup=o,this.cname=a;const d=this.rtpCapabilities.send;for(const e of c.mediaDescriptions){if(e.attributes.iceUfrag=t.iceUfrag,e.attributes.icePwd=t.icePwd,e.attributes.fingerprints=i.fingerprints,e.attributes.candidates=n,e.attributes.setup=o,\"video\"===e.media.mediaType&&(e.media.fmts=d.videoCodecs.map((e=>e.payloadType.toString(10))),e.attributes.payloads=d.videoCodecs,e.attributes.extmaps=d.videoExtensions,Dy(\"PRELOAD_MEDIA_COUNT\")>0)){const{ssrcs:t,ssrcGroups:i}=tj([{ssrcId:PG,rtx:Dy(\"USE_SUB_RTX\")?40001:void 0}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i}if(\"audio\"===e.media.mediaType&&(e.media.fmts=d.audioCodecs.map((e=>e.payloadType.toString(10))),e.attributes.payloads=d.audioCodecs,e.attributes.extmaps=d.audioExtensions,uj(e),Dy(\"PRELOAD_MEDIA_COUNT\")>0)){const{ssrcs:t,ssrcGroups:i}=tj([{ssrcId:2e4}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i}}this.sessionDesc=c,this.currentMidIndex=c.mediaDescriptions.length-1}preloadRemoteMedia(){const e=Dy(\"PRELOAD_MEDIA_COUNT\");this.rtpCapabilities;const t=this.candidates,i=this.dtlsParameters,n=this.iceParameters,r=this.rtpCapabilities.send;for(let o=1;oe.payloadType.toString(10)))},connections:[{nettype:\"IN\",addrtype:\"IP4\",address:\"127.0.0.1\"}],bandwidths:[],attributes:{iceUfrag:n.iceUfrag,icePwd:n.icePwd,unrecognized:[],candidates:t,extmaps:r.videoExtensions,fingerprints:i.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:d,ssrcGroups:l,rtcpFeedbackWildcards:[],payloads:r.videoCodecs,rtcp:{port:\"9\",netType:\"IN\",addressType:\"IP4\",address:\"0.0.0.0\"},setup:this.setup,direction:\"sendonly\",rtcpMux:!0,rtcpRsize:!0,mid:\"\".concat(2*o)}}),this.sessionDesc.mediaDescriptions.push({media:{mediaType:\"audio\",port:DG,protos:[\"UDP\",\"TLS\",\"RTP\",\"SAVPF\"],fmts:r.audioCodecs.map((e=>e.payloadType.toString(10)))},connections:[{nettype:\"IN\",addrtype:\"IP4\",address:\"127.0.0.1\"}],bandwidths:[],attributes:{iceUfrag:n.iceUfrag,icePwd:n.icePwd,unrecognized:[],candidates:t,extmaps:r.audioExtensions,fingerprints:i.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:a,ssrcGroups:c,rtcpFeedbackWildcards:[],payloads:r.audioCodecs,rtcp:{port:\"9\",netType:\"IN\",addressType:\"IP4\",address:\"0.0.0.0\"},setup:this.setup,direction:\"sendonly\",rtcpMux:!0,rtcpRsize:!0,mid:\"\".concat(2*o+1)}}),this.currentMidIndex+=2}this.updateBundleMids()}toString(){return wB.print(this.sessionDesc)}send(e,t,i,n){const{ssrcs:r,ssrcGroups:o}=tj(t,this.cname,Dy(\"SYNC_GROUP\")?i:void 0),s=this.findPreloadMediaDesc(r);if(s){if(Pv()&&this.firefoxSsrcMidMap.set(r[0].ssrcId,s.attributes.mid),n&&(n.twcc||n.remb)){const e=this.sessionDesc.mediaDescriptions.indexOf(s);return this.sessionDesc.mediaDescriptions[e]=this.mungSendMediaDesc(s,n),{mid:s.attributes.mid,needExchangeSDP:!0}}return{mid:s.attributes.mid,needExchangeSDP:!1}}{const t=this.findAvailableMediaIndex(e,r);let i;return-1===t||1===t&&(Nv()||Bv())||0===t&&Dy(\"USE_SUB_RTX\")||jv()?(i=this.createOrRecycleSendMedia(e,r,o,\"sendonly\",n),this.updateBundleMids()):(i=GI(this.sessionDesc.mediaDescriptions[t]),i.attributes.direction=\"sendonly\",i.attributes.ssrcs=r,i.attributes.ssrcGroups=o,this.sessionDesc.mediaDescriptions[t]=this.mungSendMediaDesc(i,n)),Pv()&&this.firefoxSsrcMidMap.set(r[0].ssrcId,i.attributes.mid),{mid:i.attributes.mid,needExchangeSDP:!0}}}sendDataChannel(){const{mediaDesc:e,needExchangeSDP:t}=this.createOrRecycleDataChannel();return this.updateBundleMids(),{mid:e.attributes.mid,needExchangeSDP:t}}batchSend(e){const t=e.map((e=>{let{kind:t,ssrcMsg:i,mslabel:n}=e;return this.send(t,i,n)})),i=[];let n=!1;return t.forEach((e=>{let{mid:t,needExchangeSDP:r}=e;r&&(n=!0),i.push(t)})),{mids:i,needExchangeSDP:n}}stopSending(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>t.attributes.mid&&-1!==e.indexOf(t.attributes.mid)));if(t.length!==e.length)throw new Error(\"mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.stopSending.\");t.forEach((e=>{\"0\"===e.attributes.mid||Pv()||jv()?e.attributes.ssrcs=[]:(e.attributes.ssrcs=[],e.attributes.direction=\"inactive\",e.media.port=\"0\")})),this.updateBundleMids()}mute(e){const t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error(\"mediaDescription not found with \".concat(e,\" in remote SDP when calling RemoteSDP.mute.\"));t.attributes.direction=\"inactive\"}unmute(e){const t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error(\"mediaDescription not found with \".concat(e,\" in remote SDP when calling RemoteSDP.unmute.\"));t.attributes.direction=\"sendonly\"}muteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>Dn(e).call(e,t.attributes.mid||\"\")));if(t.length!==e.length)throw new Error(\"mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.\");t.forEach((e=>{e.attributes.direction=\"inactive\"}))}unmuteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>Dn(e).call(e,t.attributes.mid||\"\")));if(t.length!==e.length)throw new Error(\"mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.\");t.forEach((e=>{e.attributes.direction=\"recvonly\"}))}receive(e,t,i,n){e.forEach(((e,r)=>{this.createOrRecycleRecvMedia(e,[],\"recvonly\",t,i,n[r])})),this.updateBundleMids()}stopReceiving(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>-1!==e.indexOf(t.attributes.mid)));if(t.length!==e.length)throw new Error(\"MediaDescriptions' length doesn't match mids's length when calling RemoteSDP.receive.\");t.forEach((e=>{e.media.port=\"0\",e.attributes.direction=\"inactive\"})),this.updateBundleMids()}updateCandidates(e){const t=this._candidates.filter((e=>\"udp\"===e.transport));if(e===rw.TCP){if(0===t.length)return;if(Dy(\"TCP_CANDIDATE_ONLY\")){const e=this._candidates.filter((e=>\"tcp\"===e.transport));t.forEach((t=>{-1===e.findIndex((e=>e.connectionAddress===t.connectionAddress))&&e.push(NG(NG({},t),{},{foundation:\"tcpcandidate\",priority:Number(t.priority)-1+\"\",transport:\"tcp\",port:Number(t.port)+90+\"\"}))})),this._candidates=e}else{const e=[];t.forEach((t=>{e.push(NG(NG({},t),{},{foundation:\"tcpcandidate\",priority:Number(t.priority)-1+\"\",transport:\"tcp\",port:Number(t.port)+90+\"\"}))})),this._candidates=[...t,...e]}}else if(e===rw.RELAY){if(0!==t.length)return;{const e=this._candidates.filter((e=>\"tcp\"===e.transport));e.forEach((e=>{t.push(NG(NG({},e),{},{foundation:\"udpcandidate\",priority:Number(e.priority)+1+\"\",transport:\"udp\",port:Number(e.port)-90+\"\"}))})),this._candidates=[...t,...e]}}else 0===t.length?(this._candidates.filter((e=>\"tcp\"===e.transport)).forEach((e=>{t.push(NG(NG({},e),{},{foundation:\"udpcandidate\",priority:Number(e.priority)+1+\"\",transport:\"udp\",port:Number(e.port)-90+\"\"}))})),this._candidates=t):this._candidates=this._candidates.filter((e=>\"tcp\"!==e.transport));for(const e of this.sessionDesc.mediaDescriptions)e.attributes.candidates=this.candidates}restartICE(e){e=GI(e),this._iceParameters=e,this.sessionDesc.mediaDescriptions.forEach((t=>{t.attributes.iceUfrag=e.iceUfrag,t.attributes.icePwd=e.icePwd}))}predictReceivingMids(e){const t=[];for(let i=0;i{const n=i.media.mediaType===e&&\"0\"!==i.media.port&&(\"sendonly\"===i.attributes.direction||\"sendrecv\"===i.attributes.direction)&&0===i.attributes.ssrcs.length;if(Pv()){if(n){const e=this.firefoxSsrcMidMap.get(t[0].ssrcId);return!(e||\"0\"!==i.attributes.mid&&\"1\"!==i.attributes.mid)||!(!e||e!==i.attributes.mid)}return!1}return n}))}createOrRecycleDataChannel(){for(const e of this.sessionDesc.mediaDescriptions)if(\"application\"===e.media.mediaType)return{mediaDesc:e,needExchangeSDP:!1};this.currentMidIndex+=1;const e=\"\".concat(this.currentMidIndex),t={media:{mediaType:\"application\",port:DG,protos:[\"UDP\",\"DTLS\",\"SCTP\"],fmts:[\"webrtc-datachannel\"]},connections:[{nettype:\"IN\",addrtype:\"IP4\",address:\"127.0.0.1\"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:[],fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:[],ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:[],rtcp:{port:\"9\",netType:\"IN\",addressType:\"IP4\",address:\"0.0.0.0\"},setup:this.setup,mid:\"\".concat(e),sctpPort:\"5000\"}};return this.sessionDesc.mediaDescriptions.push(t),{mediaDesc:t,needExchangeSDP:!0}}createOrRecycleRecvMedia(e,t,i,n,r,o){const s=e._mediaStreamTrack.kind,a=this.rtpCapabilities.recv,c=_j(s,a,this.localCapabilities.send,s===nw.VIDEO?n:r),d=s===nw.VIDEO?a.videoExtensions:a.audioExtensions;this.currentMidIndex+=1;const l=\"\".concat(this.currentMidIndex);let h={media:{mediaType:s,port:DG,protos:[\"UDP\",\"TLS\",\"RTP\",\"SAVPF\"],fmts:c.map((e=>e.payloadType.toString(10)))},connections:[{nettype:\"IN\",addrtype:\"IP4\",address:\"127.0.0.1\"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:d,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:c,rtcp:{port:\"9\",netType:\"IN\",addressType:\"IP4\",address:\"0.0.0.0\"},setup:this.setup,direction:i,rtcpMux:!0,rtcpRsize:!0,mid:\"\".concat(l)}};h=this.mungRecvMediaDsec(h,e,o);const u=this.findFirstClosedMedia(s);if(u){const e=this.sessionDesc.mediaDescriptions.indexOf(u);this.sessionDesc.mediaDescriptions[e]=h}else this.sessionDesc.mediaDescriptions.push(h);return h}updateRemoteCodec(e,t,i){const n=[...new Set(this._rtpCapabilities.recv.videoCodecs.map((e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||\"\")).filter((e=>{var t;return Dn(t=Object.keys(My)).call(t,e)})))],r=new Set(t);if(n.every((e=>r.has(e))))return Qy.debug(\"codecs has not changed, no need to updateRemoteCodec, codecs: \".concat(t)),!1;const o=this._rtpCapabilities.recv.videoCodecs.filter((e=>t.some((t=>{var i;return Dn(i=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||\"\").call(i,t)}))));if(0===o.length)return Qy.debug(\"updateRemoteCodec failed, because cannot find matched codec, remoteCapabilities codecs: \".concat(n,\" codecs: \").concat(t)),!1;const s=[...new Set(o.map((e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||\"\")))];let a;if(Qy.debug(\"updateRemoteCodec, from \".concat(n,\" to \").concat(s)),0===e.length)a=this.sessionDesc.mediaDescriptions.filter((e=>\"video\"===e.media.mediaType&&\"recvonly\"===e.attributes.direction));else if(a=this.sessionDesc.mediaDescriptions.filter((t=>t.attributes.mid&&Dn(e).call(e,t.attributes.mid)&&\"recvonly\"===t.attributes.direction)),a.length!==e.length)return Qy.debug(\"updateRemoteCodec failed, because cannot find mids, mids: \".concat(e,\", codecs: \").concat(t)),!1;if(Dy(\"USE_PUB_RTX\")||Dy(\"USE_SUB_RTX\")){const e=Ej(o,this.rtpCapabilities.recv.videoCodecs);o.push(...e)}this._rtpCapabilities.recv.videoCodecs=o;const c=this.localCapabilities.send,d=this.rtpCapabilities.recv,l=_j(nw.VIDEO,d,c,i);return a.forEach((e=>{const t=l.map((e=>e.payloadType.toString(10)));Qy.debug(\"updateRemoteCodec mid: \".concat(e.attributes.mid,\", from \").concat(e.attributes.payloads,\" to \").concat(l)),e.attributes.payloads=l,e.media.fmts=t})),!0}createOrRecycleSendMedia(e,t,i,n,r){const o=this.rtpCapabilities.send,s=e===nw.VIDEO?o.videoCodecs:o.audioCodecs,a=e===nw.VIDEO?o.videoExtensions:o.audioExtensions;this.currentMidIndex+=1;const c=\"\".concat(this.currentMidIndex);let d={media:{mediaType:e,port:DG,protos:[\"UDP\",\"TLS\",\"RTP\",\"SAVPF\"],fmts:s.map((e=>e.payloadType.toString(10)))},connections:[{nettype:\"IN\",addrtype:\"IP4\",address:\"127.0.0.1\"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:a,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:i,rtcpFeedbackWildcards:[],payloads:s,rtcp:{port:\"9\",netType:\"IN\",addressType:\"IP4\",address:\"0.0.0.0\"},setup:this.setup,direction:n,rtcpMux:!0,rtcpRsize:!0,mid:\"\".concat(c)}};d=this.mungSendMediaDesc(d,r);const l=this.findFirstClosedMedia(e);if(l){const e=this.sessionDesc.mediaDescriptions.indexOf(l);this.sessionDesc.mediaDescriptions[e]=d}else this.sessionDesc.mediaDescriptions.push(d);return d}updateBundleMids(){this.sessionDesc.attributes.groups[0].identificationTag=this.sessionDesc.mediaDescriptions.filter((e=>\"0\"!==e.media.port)).map((e=>e.attributes.mid))}mungRecvMediaDsec(e,t,i){const n=GI(e);return nj(n),ij(n,t),rj(n,t),oj(n),sj(n,i,this.localCapabilities.send),n}mungSendMediaDesc(e,t){const i=GI(e);return sj(i,t,this.localCapabilities.recv),uj(i),i}updateRecvMedia(e,t){const i=this.sessionDesc.mediaDescriptions.findIndex((t=>t.attributes.mid===e));if(-1!==i){const e=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[i],t);this.sessionDesc.mediaDescriptions[i]=e}}bumpMid(e){this.currentMidIndex+=e}findFirstClosedMedia(e){return this.sessionDesc.mediaDescriptions.find((t=>Pv()?\"0\"===t.media.port&&t.media.mediaType===e:\"0\"===t.media.port))}findPreloadMediaDesc(e){return this.sessionDesc.mediaDescriptions.find((t=>{var i;return(null===(i=t.attributes)||void 0===i||null===(i=i.ssrcs[0])||void 0===i?void 0:i.ssrcId)===e[0].ssrcId}))}getSSRC(e){var t;return null===(t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e)))||void 0===t?void 0:t.attributes.ssrcs}}({remoteIceParameters:e,remoteDtlsParameters:t,candidates:i,remoteRTPCapabilities:n,remoteSetup:r,localCapabilities:this.localCapabilities,cname:o}),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0&&this.remoteSDP.updateRemoteCodec([],this.remoteCodecs,this.store.codec);const s=this.remoteSDP.toString(),a=wB.parse(this.initialOffer.sdp),c=a.mediaDescriptions.find((e=>\"audio\"===e.media.mediaType));c&&uj(c),this.useXR&&pj(a);const d=wB.print(a),l=this.logSDPExchange(d||\"\",\"offer\",\"local\",\"connect\");this.store.descriptionStart(),await this.peerConnection.setLocalDescription({type:\"offer\",sdp:d}),null==l||l(s),await this.peerConnection.setRemoteDescription({type:\"answer\",sdp:s});const h=this.peerConnection.getTransceivers()[0];if(null!=h&&h.receiver&&this.tryBindTransportEvents(h.receiver),Dy(\"PRELOAD_MEDIA_COUNT\")>0){this.remoteSDP.preloadRemoteMedia();const e=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:\"offer\",sdp:e});const t=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(t)}}catch(e){throw new iI(tI.EXCHANGE_SDP_FAILED,\"P2PConnection.connect failed; \".concat(e.toString()))}}send(e,t,i){var n=this;return pB((function*(){const r=yield rB(n.mutex.lock(\"From P2PConnection.send\"));try{if(!n.remoteSDP)throw new Error(\"Cannot call P2PConnection.send before remote SDP created\");const o=[];e.forEach((e=>{const t=n.peerConnection.addTransceiver(e._mediaStreamTrack,{direction:\"sendonly\"});o.push(t),e._updateRtpTransceiver(t)})),Pv()&&!0===Dy(\"SIMULCAST\")&&(yield rB(n.applySimulcastForFirefox(o,e)));const s=yield rB(n.peerConnection.createOffer()),a=n.remoteSDP.predictReceivingMids(e.length),c=n.mungSendOfferSDP(s.sdp,e,a),d=wB.parse(c),l=a.map((e=>{const t=d.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error(\"Cannot extract ssrc from mediaDescription.\");return $B(t,Dy(\"USE_PUB_RTX\"))}));let h;try{h=yield l}catch(r){h=[],n.remoteSDP.receive(e,t,i,h);const o=n.remoteSDP.toString();throw yield rB(n.peerConnection.setLocalDescription({type:\"offer\",sdp:c})),yield rB(n.peerConnection.setRemoteDescription({type:\"answer\",sdp:o})),yield rB(n.stopSending(a,!0)),r}n.remoteSDP.receive(e,t,i,h);const u=n.remoteSDP.toString(),p=n.logSDPExchange(c,\"offer\",\"local\",\"send\");return yield rB(n.peerConnection.setLocalDescription({type:\"offer\",sdp:c})),yield rB(n.applySimulcastEncodings(o,e)),yield rB(n.applySendEncodings(o,e)),null==p||p(u),yield rB(n.peerConnection.setRemoteDescription({type:\"answer\",sdp:u})),o.map(((e,t)=>{const i=a[t];return{localSSRC:l[t],id:i,transceiver:e}}))}catch(e){throw e instanceof iI?e:new iI(tI.EXCHANGE_SDP_FAILED,\"P2PConnection.send failed; \".concat(e.toString()))}finally{r()}}))()}async createDataChannels(e,t){try{if(!this.remoteSDP)throw new Error(\"Cannot call P2PConnection.createDataChannels before remote SDP created\");let i=this.dataStreamChannelMap.get(e);if(i&&\"open\"===i.readyState)Qy.debug(\"[P2PConnection] Channels are already available and can be reused directly.\");else{const t=this.currentDataChannelId<1023?this.currentDataChannelId++:this.recoveredDataChannelIds.shift();if(\"number\"!=typeof t)throw new Error(\"create DataChannel error, because cannot get dc id\");i=this.peerConnection.createDataChannel(\"datastream-channel\",{id:t,negotiated:!0,ordered:!1,maxRetransmits:Dy(\"DATASTREAM_MAX_RETRANSMITS\")}),i.binaryType=\"arraybuffer\",this.dataStreamChannelMap.set(e,i)}t.forEach((e=>{e._updateOriginDataChannel(i)}));const{needExchangeSDP:n}=this.remoteSDP.sendDataChannel();if(n){const e=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:\"offer\",sdp:e});const t=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(t),Qy.debug(\"[P2PConnection] createDataChannels by exchanging SDP.\")}else Qy.debug(\"[P2PConnection] createDataChannels no need to exchange SDP.\");return}catch(e){throw e instanceof iI?e:new iI(tI.EXCHANGE_SDP_FAILED,\"P2PConnection.createDataChannels failed; \".concat(e.toString()))}}async stopDataChannels(e){try{const t=this.dataStreamChannelMap.get(e);return t&&(t.id&&this.recoveredDataChannelIds.push(t.id),t.close()),void this.dataStreamChannelMap.delete(e)}catch(e){throw e instanceof iI?e:new iI(tI.DATACHANNEL_FAILED,\"P2PConnection.stopDataChannels failed; \".concat(e.toString()))}}async stopSending(e,t){const i=t?void 0:await this.mutex.lock(\"From P2PConnection.stopSending\");try{if(!this.remoteSDP)throw new Error(\"Cannot call P2PConnection.stopSending before remote SDP created\");const t=this.peerConnection.getTransceivers().filter((t=>-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error(\"Transceivers' length doesn't match mids' length when trying to call P2PConnection.stopSending.\");t.map((e=>{var t;YG(this.id+e.mid),e.direction=\"inactive\",null===(t=e.stop)||void 0===t||t.call(e)}));const n=await this.peerConnection.createOffer(),r=this.logSDPExchange(n.sdp||\"\",\"offer\",\"local\",\"stopSending\");await this.peerConnection.setLocalDescription(n),this.remoteSDP.stopReceiving(e);const o=this.remoteSDP.toString();null==r||r(o),await this.peerConnection.setRemoteDescription({type:\"answer\",sdp:o})}catch(e){throw new iI(tI.EXCHANGE_SDP_FAILED,\"P2PConnection.stopSending failed; \".concat(e.toString()))}finally{i&&i()}}async receive(e,t,i,n){try{if(!this.remoteSDP)throw new Error(\"Cannot call P2PConnection.receive \".concat(e,\" before remoteSDP created.\"));const{mid:r,needExchangeSDP:o}=this.remoteSDP.send(e,t,i,n);if(o){const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,\"offer\",\"remote\",\"receive\");await this.peerConnection.setRemoteDescription({type:\"offer\",sdp:t});const n=await this.peerConnection.createAnswer(),o=this.mungReceiveAnswerSDP(n.sdp,r,e);null==i||i(o||\"\"),await this.peerConnection.setLocalDescription({type:\"answer\",sdp:o}),Qy.debug(\"[\".concat(this.store.clientId,\"] [P2PConnection] receive \").concat(e,\" by exchanging SDP.\"))}else Qy.debug(\"[\".concat(this.store.clientId,\"] [P2PConnection] receive \").concat(e,\" no need to exchange SDP.\"));const s=this.peerConnection.getTransceivers().find((e=>e.mid===r));if(!s)throw new Error(\"Cannot get transceiver after setLocalDescription.\");return{track:s.receiver.track,id:r,transceiver:s}}catch(e){throw new iI(tI.EXCHANGE_SDP_FAILED,\"P2PConnection.receive failed; \".concat(e.toString()))}}async batchReceive(e){try{if(!this.remoteSDP)throw new Error(\"Cannot call P2PConnection.batchReceive before remoteSDP created.\");const{mids:t,needExchangeSDP:i}=this.remoteSDP.batchSend(e);if(i){const e=this.remoteSDP.toString(),t=this.logSDPExchange(e,\"offer\",\"remote\",\"receive\");await this.peerConnection.setRemoteDescription({type:\"offer\",sdp:e});const i=await this.peerConnection.createAnswer();null==t||t(i.sdp||\"\"),await this.peerConnection.setLocalDescription(i),Qy.debug(\"[\".concat(this.store.clientId,\"] [P2PConnection] batchReceive by exchanging SDP.\"))}else Qy.debug(\"[\".concat(this.store.clientId,\"] [P2PConnection] batchReceive no need to exchange SDP.\"));return t.map((e=>{const t=this.peerConnection.getTransceivers().find((t=>t.mid===e));if(!t)throw new Error(\"Cannot get transceiver after setLocalDescription.\");return{track:t.receiver.track,id:e,transceiver:t}}))}catch(e){throw new iI(tI.EXCHANGE_SDP_FAILED,\"P2PConnection.receive failed; \".concat(e.toString()))}}async stopReceiving(e){try{if(!this.remoteSDP)throw new Error(\"Cannot call P2PConnection.stopReceiving before remote SDP created.\");this.remoteSDP.stopSending(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,\"offer\",\"remote\",\"stopReceiving\");await this.peerConnection.setRemoteDescription({type:\"offer\",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||\"\"),await this.peerConnection.setLocalDescription(n)}catch(e){throw new iI(tI.EXCHANGE_SDP_FAILED,\"P2PConnection stopReceiving failed; \".concat(e.toString()))}}async muteRemote(e){try{if(!this.remoteSDP)throw new Error(\"Cannot call P2PConnection.muteRemote mid=\".concat(e,\" before remote SDP created.\"));this.remoteSDP.mute(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,\"offer\",\"remote\",\"muteRemote\");await this.peerConnection.setRemoteDescription({type:\"offer\",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||\"\"),await this.peerConnection.setLocalDescription(n)}catch(e){throw new iI(tI.EXCHANGE_SDP_FAILED,\"P2PConnection.muteRemote failed; \".concat(e.toString()))}}async unmuteRemote(e){try{if(!this.remoteSDP)throw new Error(\"Cannot call P2PConnection.unmuteRemote mid=\".concat(e,\" before remote SDP created.\"));this.remoteSDP.unmute(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,\"offer\",\"remote\",\"unmuteRemote\");await this.peerConnection.setRemoteDescription({type:\"offer\",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||\"\"),await this.peerConnection.setLocalDescription(n)}catch(e){throw new iI(tI.EXCHANGE_SDP_FAILED,\"P2PConnection.unmuteRemote failed; \".concat(e.toString()))}}async muteLocal(e){try{if(!this.remoteSDP)throw new Error(\"Cannot call P2PConnection.muteLocal before remote SDP created.\");const t=this.peerConnection.getTransceivers().filter((t=>t.mid&&-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error(\"Transceivers' length doesn't match mids' length.\");t.map((e=>{e.direction=\"inactive\"}));const i=await this.peerConnection.createOffer(),n=this.logSDPExchange(i.sdp||\"\",\"offer\",\"local\",\"muteLocal\");await this.peerConnection.setLocalDescription(i),this.remoteSDP.muteRemote(e);const r=this.remoteSDP.toString();null==n||n(r),await this.peerConnection.setRemoteDescription({type:\"answer\",sdp:r})}catch(e){throw new iI(tI.EXCHANGE_SDP_FAILED,\"P2PConnection.muteLocal failed; \".concat(e.toString()))}}async unmuteLocal(e){try{if(!this.remoteSDP)throw new Error(\"Cannot call P2PConnection.unmuteLocal before remote SDP created.\");const t=this.peerConnection.getTransceivers().filter((t=>t.mid&&-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error(\"Transceivers' length doesn't match mids' length.\");t.map((async(e,t)=>{e.direction=\"sendonly\"}));const i=await this.peerConnection.createOffer(),n=this.logSDPExchange(i.sdp||\"\",\"offer\",\"local\",\"unmuteLocal\");await this.peerConnection.setLocalDescription(i),this.remoteSDP.unmuteRemote(e);const r=this.remoteSDP.toString();null==n||n(r),await this.peerConnection.setRemoteDescription({type:\"answer\",sdp:r})}catch(e){throw new iI(tI.EXCHANGE_SDP_FAILED,\"P2PConnection.unmuteLocal failed; \".concat(e.toString()))}}restartICE(e){var t=this;return pB((function*(){const i=yield rB(t.mutex.lock(\"From P2PConnection.restartICE\"));try{if(!t.remoteSDP)throw new Error(\"Cannot restartICE before remoteSDP created.\");if(_U().supportPCSetConfiguration){const i=t.peerConnection.getConfiguration(),n=e===rw.RELAY?\"relay\":\"all\";i.iceTransportPolicy!==n&&(Qy.debug(\"[\".concat(t.store.clientId,\"] restartICE change iceTransportPolicy from [\").concat(i.iceTransportPolicy,\"] to [\").concat(n,\"]\")),i.iceTransportPolicy=n,t.peerConnection.setConfiguration(i))}else if(e===rw.RELAY)return;t.remoteSDP.updateCandidates(e);const n=yield rB(t.peerConnection.createOffer({iceRestart:!0}));if(!n.sdp)throw new Error(\"Cannot restartICE because restart offer SDP does not exist.\");const r=ZB(n.sdp),{remoteIceParameters:o}=yield r.iceParameters;t.remoteSDP.restartICE(o);const s=t.remoteSDP.toString(),a=t.logSDPExchange(n.sdp||\"\",\"offer\",\"local\",\"restartICE\");t.store.descriptionStart(),yield rB(t.peerConnection.setLocalDescription(n)),null==a||a(s),yield rB(t.peerConnection.setRemoteDescription({type:\"answer\",sdp:s}))}catch(e){Qy.warning(\"[\".concat(t.store.clientId,\"] restart ICE failed, abort operation\"),e)}finally{i()}}))()}close(){var e;this.peerConnection.getTransceivers().forEach((e=>{YG(this.id+e.mid)})),this.peerConnection.close(),null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,\"closed\"),this.tryUnbindTransportEvents(),this.unbindPCEvents(),this.unbindStatsEvents(),this.removeAllListeners(),this.transportEventReceiver=void 0,this.statsFilter.destroy(),this.dataStreamChannelMap.clear(),this.recoveredDataChannelIds=[],this.currentDataChannelId=1}getStats(){return JG(JG({},this.statsFilter.getStats()),{},{qualityLimitationReason:this.qualityLimitationReason})}getRemoteVideoIsReady(e){return this.statsFilter.getVideoIsReady(e)}async updateEncoderConfig(e,t){try{if(!this.remoteSDP)throw new Error(\"Cannot call P2PConnection.updateEncoderConfig before remote SDP created.\");const i=await this.peerConnection.createOffer(),n=this.mungSendOfferSDP(i.sdp,[t],[e]);this.remoteSDP.updateRecvMedia(e,t);const r=this.remoteSDP.toString(),o=this.logSDPExchange(n,\"offer\",\"local\",\"updateEncoderConfig\");await this.peerConnection.setLocalDescription({type:\"offer\",sdp:n}),null==o||o(r),await this.peerConnection.setRemoteDescription({type:\"answer\",sdp:r})}catch(e){throw new iI(tI.EXCHANGE_SDP_FAILED,e.toString())}}async updateSendParameters(e,t){const i=this.peerConnection.getTransceivers().filter((t=>t.mid===e));1===i.length&&(this.isVP8Simulcast(t)?Pv()||await this.applySimulcastEncodings(i,[t]):await this.applySendEncodings(i,[t]))}setStatsRemoteVideoIsReady(e,t){this.statsFilter.setVideoIsReady2(e,t)}async replaceTrack(e,t){const i=this.peerConnection.getTransceivers().find((e=>e.mid===t));i&&await i.sender.replaceTrack(e._mediaStreamTrack)}async getSelectedCandidatePair(){const e=this.peerConnection.getReceivers();if(e.length>0&&e[0].transport&&e[0].transport.iceTransport&&e[0].transport.iceTransport.getSelectedCandidatePair&&e[0].transport.iceTransport.getSelectedCandidatePair()){const t=e[0].transport.iceTransport,{local:i,remote:n}=t.getSelectedCandidatePair();return{local:JG(JG({},PB),{},{candidateType:i.type,protocol:i.protocol,address:i.address,port:i.port}),remote:JG(JG({},PB),{},{candidateType:n.type,protocol:n.protocol,address:n.address,port:n.port})}}return this.statsFilter.getSelectedCandidatePair()}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var e;null===(e=this.onICEConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.iceConnectionState)},this.peerConnection.onconnectionstatechange=()=>{var e;null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.connectionState)},this.peerConnection.onicecandidate=e=>{e.candidate?this.localCandidateCount+=1:(this.peerConnection.onicecandidate=null,this.allCandidatesReceived=!0,Qy.debug(\"[\".concat(this.store.clientId,\"] [pc-\").concat(this.store.p2pId,\"] local candidate count\"),this.localCandidateCount))},setTimeout((()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,Qy.debug(\"[\".concat(this.store.clientId,\"] [pc-\").concat(this.store.p2pId,\"] onicecandidate timeout, local candidate count\"),this.localCandidateCount))}),Dy(\"CANDIDATE_TIMEOUT\"))}unbindPCEvents(){this.peerConnection.oniceconnectionstatechange=null,this.peerConnection.onconnectionstatechange=null,this.peerConnection.onsignalingstatechange=null,this.peerConnection.onicecandidateerror=null,this.peerConnection.onicecandidate=null,this.peerConnection.ontrack=null}static resolvePCConfiguration(t){const i={iceServers:[]};return t.iceServers?i.iceServers=t.iceServers:t.turnServer&&\"off\"!==t.turnServer.mode&&(bI(t.turnServer.servers)?i.iceServers=t.turnServer.servers:(i.iceServers&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers)),Dy(\"USE_TURN_SERVER_OF_GATEWAY\")&&i.iceServers&&t.turnServer.serversFromGateway&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway)),Dy(\"FORCE_TURN_TCP\")?i.iceTransportPolicy=\"relay\":t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach((e=>{e.forceturn&&(i.iceTransportPolicy=\"relay\")})))),Dy(\"ENABLE_ENCODED_TRANSFORM\")&&_U().supportWebRTCEncodedTransform&&(i.encodedInsertableStreams=!0),i}static turnServerConfigToIceServers(e){const t=[];return e.forEach((e=>{e.security?e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:\"password\",urls:\"turns:\".concat(Hw(e.turnServerURL),\":\").concat(e.tcpport,\"?transport=tcp\")}):(e.udpport&&!Dy(\"FORCE_TURN_TCP\")&&t.push({username:e.username,credential:e.password,credentialType:\"password\",urls:\"turn:\".concat(e.turnServerURL,\":\").concat(e.udpport,\"?transport=udp\")}),e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:\"password\",urls:\"turn:\".concat(e.turnServerURL,\":\").concat(e.tcpport,\"?transport=tcp\")}))})),t}tryBindTransportEvents(e){const t=e.transport;if(t){this.transportEventReceiver=e,t.onstatechange=()=>{var e;null!=t&&t.state&&(null===(e=this.onDTLSTransportStateChange)||void 0===e||e.call(this,t.state))},t.onerror=e=>{var t;null===(t=this.onDTLSTransportError)||void 0===t||t.call(this,\"error\"in e?e.error:e)};const i=t.iceTransport;i&&(i.onstatechange=()=>{const e=null==t?void 0:t.iceTransport.state;var i;e&&(null===(i=this.onICETransportStateChange)||void 0===i||i.call(this,e))},i.getSelectedCandidatePair&&(i.onselectedcandidatepairchange=()=>{if(i.getSelectedCandidatePair()){const{local:e,remote:t}=i.getSelectedCandidatePair();Qy.info(\"[\".concat(this.store.clientId,\"] [pc-\").concat(this.store.p2pId,\"] selectedcandidatepairchange: local \").concat(JSON.stringify({candidateType:e.type,protocol:e.protocol}),\", remote \").concat(JSON.stringify({candidateType:t.type,protocol:t.protocol,address:t.address,port:t.port}),\" )\"))}}))}}tryUnbindTransportEvents(){this.transportEventReceiver&&this.transportEventReceiver.transport&&(this.transportEventReceiver.transport.onstatechange=null,this.transportEventReceiver.transport.onerror=null,this.transportEventReceiver.transport.iceTransport&&(this.transportEventReceiver.transport.iceTransport.onstatechange=null))}async updateRtpSenderEncodings(e,t){var i,n;if(!t){const i=this.peerConnection.getSenders();t=i.find((t=>t.track===e._mediaStreamTrack))}if(!t)return Qy.warn(\"[\".concat(e.getTrackId(),\"] no rtpSender found}\"));if(this.isVP8Simulcast(e))return Qy.warn(\"[updateRtpSenderEncodings] Track is VP8 simulcast, please apply simulcast encodings\");if(!_U().supportSetRtpSenderParameters)return Qy.warn(\"[updateRtpSenderEncodings] Browser not support set rtp-sender parameters\");const r={},o={};switch(e._optimizationMode){case\"motion\":r.degradationPreference=\"maintain-framerate\";break;case\"detail\":r.degradationPreference=\"maintain-resolution\";break;case\"balanced\":r.degradationPreference=\"balanced\"}const s=function(e,t){return e.getTransceivers().find((e=>e.sender.track===t||e.receiver.track===t))}(this.peerConnection,e._mediaStreamTrack),a=Wx(e);if(HG(e)&&s&&t&&a&&this.getLocalVideoStats&&Dn(i=[\"vp8\",\"vp9\"]).call(i,this.store.codec)){var c;const i=r.degradationPreference||(Dn(c=e._hints).call(c,LU.CUSTOM_TRACK)?Dy(\"CUSTOM_ADAPTATION_DEFAULT_MODE\"):\"maintain-framerate\");!function(e,t,i,n,r,o){if(YG(e),\"balanced\"!==n&&\"maintain-framerate\"!==n&&\"maintain-resolution\"!==n)return;let s=-1;FG(e,t);const a=window.setInterval((()=>{const a=KG.get(e);if(!Dy(\"ENABLE_AG_ADAPTATION\")||!a)return void YG(e);const c=o();if(c.sendPackets>0&&c.OutgoingAvailableBandwidth>0){if(-1===s)return void(s=Date.now());if(Date.now()-s<1e3)return;const o=c.sendFrameRate,d=c.OutgoingAvailableBandwidth,[l,h]=jG(e,o,d,a.adaptationConfig,t,n);h&&(i.qualityLimitationReason=h),l&&a.adaptationConfig.scale!==l.scale&&(Qy.debug(\"[\".concat(e,\"] applyAdaptation: \").concat(i.qualityLimitationReason,\"\\n sendFps \").concat(o,\", bwe \").concat(d,\", switch from \").concat(a.adaptationConfig.scale,\" to \").concat(l.scale,\" \")),a.adaptationConfig=WG(WG({},a.adaptationConfig),l),r(l))}}),Dy(\"CHECK_LOCAL_STATS_INTERVAL\")),c=WG({},t);KG.set(e,{timer:a,adaptationConfig:c,originConfig:t,adaptationFunc:r}),Qy.debug(\"[\".concat(e,\"] start adaptation, originConfig: \").concat(JSON.stringify(t),\", degradationPreference: \").concat(n))}(this.id+s.mid,a,this,i,(e=>{t&&this.updateAdaptation(t,e)}),this.getLocalVideoStats.bind(this))}if(e._encoderConfig){var d;const{bitrateMax:t,frameRate:i,scaleResolutionDownBy:n}=e._encoderConfig;t&&(o.maxBitrate=1e3*t),(Dn(d=e._hints).call(d,LU.LOW_STREAM)||e.isUseScaleResolutionDownBy)&&(i&&(o.maxFramerate=Yw(i)),n&&n>=1&&(o.scaleResolutionDownBy=n))}const{maxFramerate:l}=Dy(\"ENCODER_CONFIG_LIMIT\");if(l&&\"number\"==typeof l&&(o.maxFramerate=o.maxFramerate?Math.min(o.maxFramerate,l):l),Dy(\"DSCP_TYPE\")&&Jv()){var h;const e=Dy(\"DSCP_TYPE\");Dn(h=[\"very-low\",\"low\",\"medium\",\"high\"]).call(h,e)&&(o.networkPriority=e)}const u=t.getParameters(),p=null===(n=u.encodings)||void 0===n?void 0:n[0];Pv()&&!p&&(r.encodings=[o]),p&&Object.assign(p,o),Object.assign(u,r),Qy.debug(\"[\".concat(e.getTrackId(),\"] updateRtpSenderEncodings: \").concat(JSON.stringify(u.encodings))),await t.setParameters(u)}async updateAdaptation(e,t){var i,n;if(!e)return Qy.debug(\"[updateAdaptation] no rtpSender found\");if(!_U().supportSetRtpSenderParameters)return Qy.debug(\"[updateAdaptation] Browser not support set rtp-sender parameters\");const r={},{bitrateMax:o,frameRate:s,scaleResolutionDownBy:a}=t;o&&(r.maxBitrate=1e3*o),s&&(r.maxFramerate=Yw(s)),a&&a>=1&&Dn(i=[\"vp8\",\"vp9\"]).call(i,this.store.codec)&&(r.scaleResolutionDownBy=a);const c=e.getParameters(),d=null===(n=c.encodings)||void 0===n?void 0:n[0];d&&Object.assign(d,r),Object.assign(c,{});try{await e.setParameters(c),Qy.debug(\"[updateAdaptation] updateRtpSenderEncodings: \".concat(JSON.stringify(c.encodings)))}catch(t){!(\"transport\"in e)||e.transport&&\"connected\"===e.transport.state?\"connected\"!==this.peerConnectionState?Qy.debug(\"[updateAdaptation] peerConnection not connected}\"):Qy.debug(\"[updateAdaptation] updateRtpSenderEncodings failed\",t):Qy.debug(\"[updateAdaptation] rtpSender transport not connected}\")}}async applySendEncodings(e,t){try{if(!_U().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let i=0;i{const r=i[t],o=n.mediaDescriptions.find((e=>e.attributes.mid===r));o&&(ij(o,e),aj(o,e,this.store.codec))})),wB.print(n)}mungReceiveAnswerSDP(e,t,i){const n=wB.parse(e),r=n.mediaDescriptions.find((e=>e.attributes.mid===t));return r&&(i===nw.AUDIO&&\"audio\"===r.media.mediaType&&uj(r),this.useXR&&pj(n)),wB.print(n)}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=e=>{var t;null===(t=this.onFirstAudioReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoReceived=e=>{var t;null===(t=this.onFirstVideoReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstAudioDecoded=e=>{var t;null===(t=this.onFirstAudioDecoded)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoDecoded=(e,t,i)=>{var n;null===(n=this.onFirstVideoDecoded)||void 0===n||n.call(this,e,t,i)},this.statsFilter.onSelectedLocalCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedLocalCandidateChanged)||void 0===i||i.call(this,e,t)},this.statsFilter.onSelectedRemoteCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedRemoteCandidateChanged)||void 0===i||i.call(this,e,t)},this.statsFilter.onFirstVideoDecodedTimeout=e=>{var t;null===(t=this.onFirstVideoDecodedTimeout)||void 0===t||t.call(this,e)}}unbindStatsEvents(){this.statsFilter.onFirstAudioReceived=void 0,this.statsFilter.onFirstVideoReceived=void 0,this.statsFilter.onFirstAudioDecoded=void 0,this.statsFilter.onFirstVideoDecoded=void 0,this.statsFilter.onSelectedLocalCandidateChanged=void 0,this.statsFilter.onSelectedRemoteCandidateChanged=void 0,this.statsFilter.onFirstVideoDecodedTimeout=void 0}async applySimulcastForFirefox(e,t){if(e.length===t.length)for(let a=0;a200&&null!==(o=d._scalabilityMode)&&void 0!==o&&o.numSpatialLayers&&(null===(s=d._scalabilityMode)||void 0===s?void 0:s.numSpatialLayers)>1&&\"vp8\"===this.store.codec){const e={},t={high:1e3*(d._encoderConfig.bitrateMax-50),medium:5e4};e.encodings=[{rid:\"m\",active:!0,maxBitrate:t.medium,scaleResolutionDownBy:4},{rid:\"h\",active:!0,maxBitrate:t.high}];const i=c.sender.getParameters();await c.sender.setParameters(Object.assign(i,e))}}}async applySimulcastEncodings(e,t){if(!Pv()&&e.length===t.length)for(let i=0;i200&&null!==(r=e._scalabilityMode)&&void 0!==r&&r.numSpatialLayers&&(null===(o=e._scalabilityMode)||void 0===o?void 0:o.numSpatialLayers)>1)}logSDPExchange(e,t,i,n){if(Dy(\"SDP_LOGGING\"))return Qy.upload(\"[\".concat(this.store.clientId,\"] exchanging \").concat(i,\" \").concat(t,\" SDP during P2PConnection.\").concat(n,\"\\n\"),e),\"offer\"===t?e=>{this.logSDPExchange(e,\"answer\",\"local\"===i?\"remote\":\"local\",n)}:void 0}async getRemoteSSRC(e){if(!this.remoteSDP)return;const t=this.remoteSDP.getSSRC(e);return null==t?void 0:t[0].ssrcId}setConfiguration(t){if(_U().supportPCSetConfiguration){const i=e.resolvePCConfiguration(t);this.peerConnection.setConfiguration(i)}}},nb(qG.prototype,\"updateRemoteRTPCapabilities\",[QG],Object.getOwnPropertyDescriptor(qG.prototype,\"updateRemoteRTPCapabilities\"),qG.prototype),nb(qG.prototype,\"connect\",[QG],Object.getOwnPropertyDescriptor(qG.prototype,\"connect\"),qG.prototype),nb(qG.prototype,\"createDataChannels\",[QG],Object.getOwnPropertyDescriptor(qG.prototype,\"createDataChannels\"),qG.prototype),nb(qG.prototype,\"receive\",[QG],Object.getOwnPropertyDescriptor(qG.prototype,\"receive\"),qG.prototype),nb(qG.prototype,\"batchReceive\",[QG],Object.getOwnPropertyDescriptor(qG.prototype,\"batchReceive\"),qG.prototype),nb(qG.prototype,\"stopReceiving\",[QG],Object.getOwnPropertyDescriptor(qG.prototype,\"stopReceiving\"),qG.prototype),nb(qG.prototype,\"muteRemote\",[QG],Object.getOwnPropertyDescriptor(qG.prototype,\"muteRemote\"),qG.prototype),nb(qG.prototype,\"unmuteRemote\",[QG],Object.getOwnPropertyDescriptor(qG.prototype,\"unmuteRemote\"),qG.prototype),nb(qG.prototype,\"muteLocal\",[QG],Object.getOwnPropertyDescriptor(qG.prototype,\"muteLocal\"),qG.prototype),nb(qG.prototype,\"unmuteLocal\",[QG],Object.getOwnPropertyDescriptor(qG.prototype,\"unmuteLocal\"),qG.prototype),nb(qG.prototype,\"close\",[QG],Object.getOwnPropertyDescriptor(qG.prototype,\"close\"),qG.prototype),nb(qG.prototype,\"updateEncoderConfig\",[QG],Object.getOwnPropertyDescriptor(qG.prototype,\"updateEncoderConfig\"),qG.prototype),nb(qG.prototype,\"updateSendParameters\",[QG],Object.getOwnPropertyDescriptor(qG.prototype,\"updateSendParameters\"),qG.prototype),nb(qG.prototype,\"replaceTrack\",[QG],Object.getOwnPropertyDescriptor(qG.prototype,\"replaceTrack\"),qG.prototype),nb(qG.prototype,\"updateAdaptation\",[QG],Object.getOwnPropertyDescriptor(qG.prototype,\"updateAdaptation\"),qG.prototype),nb(qG.prototype,\"getRemoteSSRC\",[QG],Object.getOwnPropertyDescriptor(qG.prototype,\"getRemoteSSRC\"),qG.prototype),qG);function QG(e,t,i){const n=e[t];if(\"function\"!=typeof n)throw new Error(\"Cannot use mutex on object property.\");return i.value=async function(){const e=this.mutex,i=await e.lock(\"From P2PConnection.\".concat(t));try{for(var r=arguments.length,o=new Array(r),s=0;se.payloadType.toString(10))),e.attributes.payloads=d.videoCodecs,e.attributes.extmaps=d.videoExtensions,Dy(\"PRELOAD_MEDIA_COUNT\")>0)){const{ssrcs:t,ssrcGroups:i}=tj([{ssrcId:nW,rtx:Dy(\"USE_SUB_RTX\")?40001:void 0}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i}if(\"audio\"===e.media.mediaType&&(e.media.fmts=d.audioCodecs.map((e=>e.payloadType.toString(10))),e.attributes.payloads=d.audioCodecs,e.attributes.extmaps=d.audioExtensions,uj(e),Dy(\"PRELOAD_MEDIA_COUNT\")>0)){const{ssrcs:t,ssrcGroups:i}=tj([{ssrcId:iW}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i}}this.sessionDesc=c,this.currentMidIndex=c.mediaDescriptions.length-1}updateRemoteRTPCapabilities(e){const t=wB.parse(eW);this._rtpCapabilities=e;const i=this.rtpCapabilities.send;for(const e of t.mediaDescriptions){if(e.attributes.iceUfrag=this._iceParameters.iceUfrag,e.attributes.icePwd=this._iceParameters.icePwd,e.attributes.fingerprints=this._dtlsParameters.fingerprints,e.attributes.candidates=this._candidates,e.attributes.setup=this.setup,\"application\"===e.media.mediaType&&(e.attributes.sctpPort=\"5000\"),\"video\"===e.media.mediaType&&(e.media.fmts=i.videoCodecs.map((e=>e.payloadType.toString(10))),e.attributes.payloads=i.videoCodecs,e.attributes.extmaps=i.videoExtensions,Dy(\"PRELOAD_MEDIA_COUNT\")>0)){const{ssrcs:t,ssrcGroups:i}=tj([{ssrcId:nW,rtx:Dy(\"USE_SUB_RTX\")?40001:void 0}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i}if(\"audio\"===e.media.mediaType&&(e.media.fmts=i.audioCodecs.map((e=>e.payloadType.toString(10))),e.attributes.payloads=i.audioCodecs,e.attributes.extmaps=i.audioExtensions,Dy(\"PRELOAD_MEDIA_COUNT\")>0)){const{ssrcs:t,ssrcGroups:i}=tj([{ssrcId:iW}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i}}this.sessionDesc=t,this.currentMidIndex=t.mediaDescriptions.length-1}preloadRemoteMedia(e){this.rtpCapabilities;const t=this.candidates,i=this.dtlsParameters,n=this.iceParameters,r=this.rtpCapabilities.send;for(let o=1;oe.payloadType.toString(10)))},connections:[{nettype:\"IN\",addrtype:\"IP4\",address:\"127.0.0.1\"}],bandwidths:[],attributes:{iceUfrag:n.iceUfrag,icePwd:n.icePwd,unrecognized:[],candidates:t,extmaps:r.videoExtensions,fingerprints:i.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:d,ssrcGroups:l,rtcpFeedbackWildcards:[],payloads:r.videoCodecs,rtcp:{port:\"9\",netType:\"IN\",addressType:\"IP4\",address:\"0.0.0.0\"},setup:this.setup,direction:\"sendonly\",rtcpMux:!0,rtcpRsize:!0,mid:\"\".concat(2*o-1)}}),this.sessionDesc.mediaDescriptions.push({media:{mediaType:\"audio\",port:tW,protos:[\"UDP\",\"TLS\",\"RTP\",\"SAVPF\"],fmts:r.audioCodecs.map((e=>e.payloadType.toString(10)))},connections:[{nettype:\"IN\",addrtype:\"IP4\",address:\"127.0.0.1\"}],bandwidths:[],attributes:{iceUfrag:n.iceUfrag,icePwd:n.icePwd,unrecognized:[],candidates:t,extmaps:r.audioExtensions,fingerprints:i.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:a,ssrcGroups:c,rtcpFeedbackWildcards:[],payloads:r.audioCodecs,rtcp:{port:\"9\",netType:\"IN\",addressType:\"IP4\",address:\"0.0.0.0\"},setup:this.setup,direction:\"sendonly\",rtcpMux:!0,rtcpRsize:!0,mid:\"\".concat(2*o)}}),this.currentMidIndex+=2}this.updateBundleMids()}toString(){return wB.print(this.sessionDesc)}send(e,t,i,n){const{ssrcs:r,ssrcGroups:o}=tj(t,this.cname,Dy(\"SYNC_GROUP\")?i:void 0),s=this.findPreloadMediaDesc(r);if(s){if(Pv()&&this.firefoxSsrcMidMap.set(r[0].ssrcId,s.attributes.mid),n&&(n.twcc||n.remb)){const e=this.sessionDesc.mediaDescriptions.indexOf(s);return this.sessionDesc.mediaDescriptions[e]=this.mungSendMediaDesc(s,n),{mid:s.attributes.mid,needExchangeSDP:!0}}return{mid:s.attributes.mid,needExchangeSDP:!1}}{const t=this.findAvailableMediaIndex(e,r);let i;return-1===t||Nv()||Lv()||Bv()||0===t&&Dy(\"USE_SUB_RTX\")?(i=this.createOrRecycleSendMedia(e,r,o,\"sendonly\",n),this.updateBundleMids()):(i=GI(this.sessionDesc.mediaDescriptions[t]),i.attributes.direction=\"sendonly\",i.attributes.ssrcs=r,i.attributes.ssrcGroups=o,this.sessionDesc.mediaDescriptions[t]=this.mungSendMediaDesc(i,n)),Pv()&&this.firefoxSsrcMidMap.set(r[0].ssrcId,i.attributes.mid),{mid:i.attributes.mid,needExchangeSDP:!0}}}batchSend(e){const t=e.map((e=>{let{kind:t,ssrcMsg:i,mslabel:n}=e;return this.send(t,i,n)})),i=[];let n=!1;return t.forEach((e=>{let{mid:t,needExchangeSDP:r}=e;r&&(n=!0),i.push(t)})),{mids:i,needExchangeSDP:n}}stopSending(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>t.attributes.mid&&-1!==e.indexOf(t.attributes.mid)));if(t.length!==e.length)throw new Error(\"mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.stopSending.\");t.forEach((e=>{\"0\"===e.attributes.mid||Pv()||Nv()||Lv()?e.attributes.ssrcs=[]:(e.attributes.ssrcs=[],e.attributes.direction=\"inactive\",e.media.port=\"0\")})),this.updateBundleMids()}mute(e){const t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error(\"mediaDescription not found with \".concat(e,\" in remote SDP when calling RemoteSDP.mute.\"));t.attributes.direction=\"inactive\"}unmute(e){const t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error(\"mediaDescription not found with \".concat(e,\" in remote SDP when calling RemoteSDP.unmute.\"));t.attributes.direction=\"sendonly\"}muteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>Dn(e).call(e,t.attributes.mid||\"\")));if(t.length!==e.length)throw new Error(\"mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.\");t.forEach((e=>{e.attributes.direction=\"inactive\"}))}unmuteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>Dn(e).call(e,t.attributes.mid||\"\")));if(t.length!==e.length)throw new Error(\"mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.\");t.forEach((e=>{e.attributes.direction=\"recvonly\"}))}receive(e,t,i,n){e.forEach(((e,r)=>{this.createOrRecycleRecvMedia(e,[],\"recvonly\",t,i,n[r])})),this.updateBundleMids()}stopReceiving(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>-1!==e.indexOf(t.attributes.mid)));if(t.length!==e.length)throw new Error(\"MediaDescriptions' length doesn't match mids's length when calling RemoteSDP.receive.\");t.forEach((e=>{e.media.port=\"0\",e.attributes.direction=\"inactive\"})),this.updateBundleMids()}updateCandidates(e){e===rw.TCP?this._candidates.forEach((e=>{-1===this._candidates.findIndex((t=>\"tcp\"===t.transport&&t.connectionAddress===e.connectionAddress&&t.port===e.port))&&this._candidates.push($G($G({},e),{},{foundation:\"tcpcandidate\",priority:Number(e.priority)-1+\"\",transport:\"tcp\",port:Number(e.port)+90+\"\"}))})):this._candidates=this._candidates.filter((e=>\"tcp\"!==e.transport));for(const e of this.sessionDesc.mediaDescriptions)e.attributes.candidates=this.candidates}restartICE(e){e=GI(e),this._iceParameters=e,this.sessionDesc.mediaDescriptions.forEach((t=>{t.attributes.iceUfrag=e.iceUfrag,t.attributes.icePwd=e.icePwd}))}predictReceivingMids(e){const t=[];for(let i=0;i{const n=i.media.mediaType===e&&\"0\"!==i.media.port&&(\"sendonly\"===i.attributes.direction||\"sendrecv\"===i.attributes.direction)&&0===i.attributes.ssrcs.length;if(Pv()){if(n){const e=this.firefoxSsrcMidMap.get(t[0].ssrcId);return!(e||\"0\"!==i.attributes.mid&&\"1\"!==i.attributes.mid)||!(!e||e!==i.attributes.mid)}return!1}return n}))}createOrRecycleRecvMedia(e,t,i,n,r,o){const s=e._mediaStreamTrack.kind,a=this.rtpCapabilities.recv,c=_j(s,a,this.localCapabilities.send,s===nw.VIDEO?n:r),d=s===nw.VIDEO?a.videoExtensions:a.audioExtensions;this.currentMidIndex+=1;const l=\"\".concat(this.currentMidIndex);let h={media:{mediaType:s,port:tW,protos:[\"UDP\",\"TLS\",\"RTP\",\"SAVPF\"],fmts:c.map((e=>e.payloadType.toString(10)))},connections:[{nettype:\"IN\",addrtype:\"IP4\",address:\"127.0.0.1\"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:d,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:c,rtcp:{port:\"9\",netType:\"IN\",addressType:\"IP4\",address:\"0.0.0.0\"},setup:this.setup,direction:i,rtcpMux:!0,rtcpRsize:!0,mid:\"\".concat(l)}};h=this.mungRecvMediaDsec(h,e,o);const u=this.findFirstClosedMedia(s);if(u){const e=this.sessionDesc.mediaDescriptions.indexOf(u);this.sessionDesc.mediaDescriptions[e]=h}else this.sessionDesc.mediaDescriptions.push(h);return h}updateRemoteCodec(e,t,i){const n=[...new Set(this._rtpCapabilities.recv.videoCodecs.map((e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||\"\")).filter((e=>{var t;return Dn(t=Object.keys(My)).call(t,e)})))],r=new Set(t);if(n.every((e=>r.has(e))))return Qy.debug(\"codecs has not changed, no need to updateRemoteCodec, codecs: \".concat(t)),!1;const o=this._rtpCapabilities.recv.videoCodecs.filter((e=>t.some((t=>{var i;return Dn(i=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||\"\").call(i,t)}))));if(0===o.length)return Qy.debug(\"updateRemoteCodec failed, because cannot find matched codec, remoteCapabilities codecs: \".concat(n,\" codecs: \").concat(t)),!1;const s=[...new Set(o.map((e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||\"\")))];let a;if(Qy.debug(\"updateRemoteCodec, from \".concat(n,\" to \").concat(s)),0===e.length)a=this.sessionDesc.mediaDescriptions.filter((e=>\"video\"===e.media.mediaType&&\"recvonly\"===e.attributes.direction));else if(a=this.sessionDesc.mediaDescriptions.filter((t=>t.attributes.mid&&Dn(e).call(e,t.attributes.mid)&&\"recvonly\"===t.attributes.direction)),a.length!==e.length)return Qy.debug(\"updateRemoteCodec failed, because cannot find mids, mids: \".concat(e,\", codecs: \").concat(t)),!1;this._rtpCapabilities.recv.videoCodecs=o;const c=this.localCapabilities.send,d=this.rtpCapabilities.recv,l=_j(nw.VIDEO,d,c,i);return a.forEach((e=>{const t=l.map((e=>e.payloadType.toString(10)));Qy.debug(\"updateRemoteCodec mid: \".concat(e.attributes.mid,\", from \").concat(e.attributes.payloads,\" to \").concat(l)),e.attributes.payloads=l,e.media.fmts=t})),!0}createOrRecycleSendMedia(e,t,i,n,r){const o=this.rtpCapabilities.send,s=e===nw.VIDEO?o.videoCodecs:o.audioCodecs,a=e===nw.VIDEO?o.videoExtensions:o.audioExtensions;this.currentMidIndex+=1;const c=\"\".concat(this.currentMidIndex);let d={media:{mediaType:e,port:tW,protos:[\"UDP\",\"TLS\",\"RTP\",\"SAVPF\"],fmts:s.map((e=>e.payloadType.toString(10)))},connections:[{nettype:\"IN\",addrtype:\"IP4\",address:\"127.0.0.1\"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:a,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:i,rtcpFeedbackWildcards:[],payloads:s,rtcp:{port:\"9\",netType:\"IN\",addressType:\"IP4\",address:\"0.0.0.0\"},setup:this.setup,direction:n,rtcpMux:!0,rtcpRsize:!0,mid:\"\".concat(c)}};d=this.mungSendMediaDesc(d,r);const l=this.findFirstClosedMedia(e);if(l){const e=this.sessionDesc.mediaDescriptions.indexOf(l);this.sessionDesc.mediaDescriptions[e]=d}else this.sessionDesc.mediaDescriptions.push(d);return d}updateBundleMids(){this.sessionDesc.attributes.groups[0].identificationTag=this.sessionDesc.mediaDescriptions.filter((e=>\"0\"!==e.media.port)).map((e=>e.attributes.mid))}mungRecvMediaDsec(e,t,i){const n=GI(e);return nj(n),ij(n,t),rj(n,t),oj(n),sj(n,i,this.localCapabilities.send),n}mungSendMediaDesc(e,t){const i=GI(e);return sj(i,t,this.localCapabilities.recv),uj(i),i}updateRecvMedia(e,t){const i=this.sessionDesc.mediaDescriptions.findIndex((t=>t.attributes.mid===e));if(-1!==i){const e=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[i],t);this.sessionDesc.mediaDescriptions[i]=e}}bumpMid(e){this.currentMidIndex+=e}findFirstClosedMedia(e){return this.sessionDesc.mediaDescriptions.find((t=>Pv()?\"0\"===t.media.port&&t.media.mediaType===e:\"0\"===t.media.port))}findPreloadMediaDesc(e){return this.sessionDesc.mediaDescriptions.find((t=>{var i;return(null===(i=t.attributes)||void 0===i||null===(i=i.ssrcs[0])||void 0===i?void 0:i.ssrcId)===e[0].ssrcId}))}getSSRC(e){var t;return null===(t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e)))||void 0===t?void 0:t.attributes.ssrcs}}var oW;function sW(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function aW(e){for(var t=1;te.rtpMap&&e.rtpMap.encodingName.toLowerCase()||\"\")).filter((e=>{var t;return Dn(t=Object.keys(My)).call(t,e)})))]}constructor(e,t,i){super(e,t),ng(this,\"store\",void 0),ng(this,\"peerConnection\",void 0),ng(this,\"remoteSDP\",void 0),ng(this,\"initialOffer\",void 0),ng(this,\"transportEventReceiver\",void 0),ng(this,\"statsFilter\",void 0),ng(this,\"useXR\",Dy(\"USE_XR\")),ng(this,\"localCapabilities\",void 0),ng(this,\"localCandidateCount\",0),ng(this,\"allCandidatesReceived\",!1),ng(this,\"remoteCodecs\",void 0),ng(this,\"dataStreamChannelMap\",new Map),ng(this,\"establishPromise\",void 0),ng(this,\"mutex\",new uy(\"NVExtentionsConnection-mutex\")),ng(this,\"rtcMedia\",void 0),this.store=t,this.peerConnection=i,this.statsFilter=zB(this.peerConnection,Dy(\"STATS_UPDATE_INTERVAL\"),void 0,Pv()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1,this.establishPromise=this.establish()}async establish(e){try{const e=await this.peerConnection.createOffer();if(!e.sdp)throw new Error(\"Cannot get initialOffer.sdp when trying to establish PeerConnection.\");const t=ZB(e.sdp),i=await cj({filterRTX:!Dy(\"USE_PUB_RTX\")&&!Dy(\"USE_SUB_RTX\"),filterVideoFec:Dy(\"FILTER_VIDEO_FEC\"),filterAudioFec:Dy(\"FILTER_AUDIO_FEC\"),filterVideoCodec:Dy(\"FILTER_VIDEO_CODEC\")},{useXR:this.useXR});return this.localCapabilities=i,this.initialOffer=e,aW(aW({},t),{},{rtpCapabilities:i,offerSDP:e.sdp})}catch(e){throw new bb(tI.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString())}}async connect(e,t,i,n,r,o){try{if(!this.initialOffer)throw new Error(\"Cannot establish NVConnection without initial offer.\");this.remoteSDP=new rW({remoteIceParameters:e,remoteDtlsParameters:t,candidates:i,remoteRTPCapabilities:n,remoteSetup:r,localCapabilities:hj(this.localCapabilities),cname:o});const s=this.remoteSDP.toString(),a=wB.parse(this.initialOffer.sdp),c=a.mediaDescriptions.find((e=>\"audio\"===e.media.mediaType));c&&uj(c),this.useXR&&pj(a);const d=wB.print(a),l=this.logSDPExchange(d||\"\",\"offer\",\"local\",\"connect\");await this.peerConnection.setLocalDescription({type:\"offer\",sdp:d}),null==l||l(s),await this.peerConnection.setRemoteDescription({type:\"answer\",sdp:s})}catch(e){throw new bb(tI.EXCHANGE_SDP_FAILED,\"NV.connect failed; \".concat(e.toString()))}}async updateRemoteRTPCapabilities(e,t){if(this.remoteCodecs=t,!this.remoteSDP)return void Qy.debug(\"[P2PConnection] cannot updateRemoteRTPCapabilities before remote SDP created, local codecs: \".concat(this.localCodecs,\", codecs: \").concat(t));if(this.remoteSDP.updateRemoteCodec(e,t,this.store.codec)){const e=await this.peerConnection.createOffer(),t=this.logSDPExchange(e.sdp||\"\",\"offer\",\"local\",\"muteLocal\");await this.peerConnection.setLocalDescription(e);const i=this.remoteSDP.toString();null==t||t(i),await this.peerConnection.setRemoteDescription({type:\"answer\",sdp:i})}else Qy.debug(\"[P2PConnection] updateRemoteRTPCapabilities no need to exchange SDP.\")}async updateRemoteConnect(e){var t,i,n,r;(null===(t=this.remoteSDP)||void 0===t||t.updateRemoteRTPCapabilities(e),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0)&&(null===(r=this.remoteSDP)||void 0===r||r.updateRemoteCodec([],this.remoteCodecs,this.store.codec));null===(i=this.remoteSDP)||void 0===i||i.preloadRemoteMedia(2);const o=null===(n=this.remoteSDP)||void 0===n?void 0:n.toString();await this.peerConnection.setRemoteDescription({type:\"offer\",sdp:o});const s=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(s),Qy.debug(\"[NVExtentionsConnection] updateRemoteRTPCapabilities by exchanging SDP.\")}send(e,t,i){var n=this;return pB((function*(){const r=yield rB(n.mutex.lock(\"From NVExtentionsConnection.send\"));try{if(!n.remoteSDP)throw new Error(\"Cannot call NVExtentionsConnection.send before remote SDP created\");const o=[];e.forEach((e=>{const t=n.peerConnection.addTransceiver(e._mediaStreamTrack,{direction:\"sendonly\"});o.push(t)})),Pv()&&!0===Dy(\"SIMULCAST\")&&(yield rB(n.applySimulcastForFirefox(o,e)));const s=yield rB(n.peerConnection.createOffer()),a=n.remoteSDP.predictReceivingMids(e.length),c=n.mungSendOfferSDP(s.sdp,e,a),d=wB.parse(c),l=a.map((e=>{const t=d.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error(\"Cannot extract ssrc from mediaDescription.\");return $B(t,Dy(\"USE_PUB_RTX\"))}));let h;try{h=yield l}catch(r){h=[],n.remoteSDP.receive(e,t,i,h);const o=n.remoteSDP.toString();throw yield rB(n.peerConnection.setLocalDescription({type:\"offer\",sdp:c})),yield rB(n.peerConnection.setRemoteDescription({type:\"answer\",sdp:o})),yield rB(n.stopSending(a,!0)),r}n.remoteSDP.receive(e,t,i,h);const u=n.remoteSDP.toString(),p=n.logSDPExchange(c,\"offer\",\"local\",\"send\");return yield rB(n.peerConnection.setLocalDescription({type:\"offer\",sdp:c})),yield rB(n.applySimulcastEncodings(o,e)),yield rB(n.applySendEncodings(o,e)),null==p||p(u),yield rB(n.peerConnection.setRemoteDescription({type:\"answer\",sdp:u})),o.map(((e,t)=>{const i=a[t];return{localSSRC:l[t],id:i,transceiver:e}}))}catch(e){throw e instanceof bb?e:new bb(tI.EXCHANGE_SDP_FAILED,\"NVExtentionsConnection.send failed; \".concat(e.toString()))}finally{r()}}))()}async stopSending(e,t){const i=t?void 0:await this.mutex.lock(\"From NVExtentionsConnection.stopSending\");try{if(!this.remoteSDP)throw new Error(\"Cannot call NVExtentionsConnection.stopSending before remote SDP created\");const t=this.peerConnection.getTransceivers().filter((t=>-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error(\"Transceivers' length doesn't match mids' length when trying to call NVExtentionsConnection.stopSending.\");t.map((e=>{var t;e.direction=\"inactive\",null===(t=e.stop)||void 0===t||t.call(e)}));const n=await this.peerConnection.createOffer(),r=this.logSDPExchange(n.sdp||\"\",\"offer\",\"local\",\"stopSending\");await this.peerConnection.setLocalDescription(n),this.remoteSDP.stopReceiving(e);const o=this.remoteSDP.toString();null==r||r(o),await this.peerConnection.setRemoteDescription({type:\"answer\",sdp:o})}catch(e){throw new bb(tI.EXCHANGE_SDP_FAILED,\"NVExtentionsConnection.stopSending failed; \".concat(e.toString()))}finally{i&&i()}}async createDataChannels(e,t){try{if(!this.remoteSDP)throw new Error(\"Cannot call NVExtentionsConnection.createDataChannels before remote SDP created\");let i=this.dataStreamChannelMap.get(e);return i&&\"open\"===i.readyState?Qy.debug(\"[P2PConnection] Channels are already available and can be reused directly.\"):(i=this.peerConnection.createDataChannel(\"datastream-channel\",{ordered:!1,maxRetransmits:Dy(\"DATASTREAM_MAX_RETRANSMITS\")}),i.binaryType=\"arraybuffer\",this.dataStreamChannelMap.set(e,i)),void t.forEach((e=>{e._updateOriginDataChannel(i)}))}catch(e){throw e instanceof bb?e:new bb(tI.DATACHANNEL_FAILED,\"NVExtentionsConnection.createDataChannels failed; \".concat(e.toString()))}}async stopDataChannels(e){try{const t=this.dataStreamChannelMap.get(e);return null==t||t.close(),void this.dataStreamChannelMap.delete(e)}catch(e){throw e instanceof bb?e:new bb(tI.DATACHANNEL_FAILED,\"NVExtentionsConnection.stopDataChannels failed; \".concat(e.toString()))}}async receive(e,t,i,n){try{if(!this.remoteSDP)throw new Error(\"Cannot call NVExtentionsConnection.receive \".concat(e,\" before remoteSDP created.\"));const{mid:r,needExchangeSDP:o}=this.remoteSDP.send(e,t,i,n);if(o){const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,\"offer\",\"remote\",\"receive\");await this.peerConnection.setRemoteDescription({type:\"offer\",sdp:t});const n=await this.peerConnection.createAnswer(),o=this.mungReceiveAnswerSDP(n.sdp,r,e);null==i||i(o||\"\"),await this.peerConnection.setLocalDescription({type:\"answer\",sdp:o}),Qy.debug(\"[NVExtentionsConnection] receive \".concat(e,\" by exchanging SDP.\"))}else Qy.debug(\"[NVExtentionsConnection] receive \".concat(e,\" no need to exchange SDP.\"));const s=this.peerConnection.getTransceivers().find((e=>e.mid===r));if(!s)throw new Error(\"Cannot get transceiver after setLocalDescription.\");return{track:s.receiver.track,id:r}}catch(e){throw new bb(tI.EXCHANGE_SDP_FAILED,\"NVExtentionsConnection.receive failed; \".concat(e.toString()))}}async batchReceive(e){try{if(!this.remoteSDP)throw new Error(\"Cannot call NVExtentionsConnection.batchReceive before remoteSDP created.\");const{mids:t,needExchangeSDP:i}=this.remoteSDP.batchSend(e);if(i){const e=this.remoteSDP.toString(),t=this.logSDPExchange(e,\"offer\",\"remote\",\"receive\");await this.peerConnection.setRemoteDescription({type:\"offer\",sdp:e});const i=await this.peerConnection.createAnswer();null==t||t(i.sdp||\"\"),await this.peerConnection.setLocalDescription(i),Qy.debug(\"[NVExtentionsConnection] batchReceive by exchanging SDP.\")}else Qy.debug(\"[NVExtentionsConnection] batchReceive no need to exchange SDP.\");return t.map((e=>{const t=this.peerConnection.getTransceivers().find((t=>t.mid===e));if(!t)throw new Error(\"Cannot get transceiver after setLocalDescription.\");return{track:t.receiver.track,id:e}}))}catch(e){throw new bb(tI.EXCHANGE_SDP_FAILED,\"NVExtentionsConnection.receive failed; \".concat(e.toString()))}}async stopReceiving(e){try{if(!this.remoteSDP)throw new Error(\"Cannot call NVExtentionsConnection.stopReceiving before remote SDP created.\");this.remoteSDP.stopSending(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,\"offer\",\"remote\",\"stopReceiving\");await this.peerConnection.setRemoteDescription({type:\"offer\",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||\"\"),await this.peerConnection.setLocalDescription(n)}catch(e){throw new bb(tI.EXCHANGE_SDP_FAILED,\"NVExtentionsConnection stopReceiving failed; \".concat(e.toString()))}}async muteRemote(e){try{if(!this.remoteSDP)throw new Error(\"Cannot call NVExtentionsConnection.muteRemote mid=\".concat(e,\" before remote SDP created.\"));this.remoteSDP.mute(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,\"offer\",\"remote\",\"muteRemote\");await this.peerConnection.setRemoteDescription({type:\"offer\",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||\"\"),await this.peerConnection.setLocalDescription(n)}catch(e){throw new bb(tI.EXCHANGE_SDP_FAILED,\"NVExtentionsConnection.muteRemote failed; \".concat(e.toString()))}}async unmuteRemote(e){try{if(!this.remoteSDP)throw new Error(\"Cannot call NVExtentionsConnection.unmuteRemote mid=\".concat(e,\" before remote SDP created.\"));this.remoteSDP.unmute(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,\"offer\",\"remote\",\"unmuteRemote\");await this.peerConnection.setRemoteDescription({type:\"offer\",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||\"\"),await this.peerConnection.setLocalDescription(n)}catch(e){throw new bb(tI.EXCHANGE_SDP_FAILED,\"NVExtentionsConnection.unmuteRemote failed; \".concat(e.toString()))}}async muteLocal(e){try{if(!this.remoteSDP)throw new Error(\"Cannot call NVExtentionsConnection.muteLocal before remote SDP created.\");const t=this.peerConnection.getTransceivers().filter((t=>t.mid&&-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error(\"Transceivers' length doesn't match mids' length.\");t.map((e=>{e.direction=\"inactive\"}));const i=await this.peerConnection.createOffer(),n=this.logSDPExchange(i.sdp||\"\",\"offer\",\"local\",\"muteLocal\");await this.peerConnection.setLocalDescription(i),this.remoteSDP.muteRemote(e);const r=this.remoteSDP.toString();null==n||n(r),await this.peerConnection.setRemoteDescription({type:\"answer\",sdp:r})}catch(e){throw new bb(tI.EXCHANGE_SDP_FAILED,\"NVExtentionsConnection.muteLocal failed; \".concat(e.toString()))}}async unmuteLocal(e){try{if(!this.remoteSDP)throw new Error(\"Cannot call NVExtentionsConnection.unmuteLocal before remote SDP created.\");const t=this.peerConnection.getTransceivers().filter((t=>t.mid&&-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error(\"Transceivers' length doesn't match mids' length.\");t.map((async(e,t)=>{e.direction=\"sendonly\"}));const i=await this.peerConnection.createOffer(),n=this.logSDPExchange(i.sdp||\"\",\"offer\",\"local\",\"unmuteLocal\");await this.peerConnection.setLocalDescription(i),this.remoteSDP.unmuteRemote(e);const r=this.remoteSDP.toString();null==n||n(r),await this.peerConnection.setRemoteDescription({type:\"answer\",sdp:r})}catch(e){throw new bb(tI.EXCHANGE_SDP_FAILED,\"NVExtentionsConnection.unmuteLocal failed; \".concat(e.toString()))}}restartICE(e){var t=this;return pB((function*(){const i=yield rB(t.mutex.lock(\"From NVExtentionsConnection.restartICE\"));try{if(!t.remoteSDP)throw new Error(\"Cannot restartICE before remoteSDP created.\");if(_U().supportPCSetConfiguration){const i=t.peerConnection.getConfiguration(),n=e===rw.RELAY?\"relay\":\"all\";i.iceTransportPolicy!==n&&(Qy.debug(\"restartICE change iceTransportPolicy from [\".concat(i.iceTransportPolicy,\"] to [\").concat(n,\"]\")),i.iceTransportPolicy=n,t.peerConnection.setConfiguration(i))}else if(e===rw.RELAY)return;e!==rw.RELAY&&t.remoteSDP.updateCandidates(e);const n=yield rB(t.peerConnection.createOffer({iceRestart:!0}));if(!n.sdp)throw new Error(\"Cannot restartICE because restart offer SDP does not exist.\");const r=ZB(n.sdp),{remoteIceParameters:o}=yield r.iceParameters;t.remoteSDP.restartICE(o);const s=t.remoteSDP.toString(),a=t.logSDPExchange(n.sdp||\"\",\"offer\",\"local\",\"restartICE\");yield rB(t.peerConnection.setLocalDescription(n)),null==a||a(s),yield rB(t.peerConnection.setRemoteDescription({type:\"answer\",sdp:s}))}catch(e){Qy.warning(\"restart ICE failed, abort operation\",e)}finally{i()}}))()}close(){var e;null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,\"closed\"),this.unbindPCEvents(),this.unbindStatsEvents(),this.removeAllListeners(),this.transportEventReceiver=void 0,this.statsFilter.destroy(),this.dataStreamChannelMap.clear()}getStats(){return this.statsFilter.getStats()}getRemoteVideoIsReady(e){return this.statsFilter.getVideoIsReady(e)}async updateEncoderConfig(e,t){try{if(!this.remoteSDP)throw new Error(\"Cannot call NVExtentionsConnection.updateEncoderConfig before remote SDP created.\");const i=await this.peerConnection.createOffer(),n=this.mungSendOfferSDP(i.sdp,[t],[e]);this.remoteSDP.updateRecvMedia(e,t);const r=this.remoteSDP.toString(),o=this.logSDPExchange(n,\"offer\",\"local\",\"updateEncoderConfig\");await this.peerConnection.setLocalDescription({type:\"offer\",sdp:n}),null==o||o(r),await this.peerConnection.setRemoteDescription({type:\"answer\",sdp:r})}catch(e){throw new bb(tI.EXCHANGE_SDP_FAILED,e.toString())}}async updateSendParameters(e,t){const i=this.peerConnection.getTransceivers().filter((t=>t.mid===e));1===i.length&&(this.isVP8Simulcast(t)?Pv()||await this.applySimulcastEncodings(i,[t]):await this.applySendEncodings(i,[t]))}setStatsRemoteVideoIsReady(e,t){this.statsFilter.setVideoIsReady2(e,t)}async replaceTrack(e,t){const i=this.peerConnection.getTransceivers().find((e=>e.mid===t));i&&await i.sender.replaceTrack(e._mediaStreamTrack)}getP2PConnectionParams(){var e;if(null===(e=this.peerConnection.currentLocalDescription)||void 0===e||!e.sdp||!this.localCapabilities)throw new Error;return aW(aW({},ZB(this.peerConnection.currentLocalDescription.sdp)),{},{rtpCapabilities:this.localCapabilities})}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var e;null===(e=this.onICEConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.iceConnectionState)},this.peerConnection.onconnectionstatechange=()=>{var e;null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.connectionState)},this.peerConnection.onicecandidate=e=>{e.candidate?this.localCandidateCount+=1:(this.peerConnection.onicecandidate=null,this.allCandidatesReceived=!0,Qy.debug(\"[pc-\".concat(this.store.p2pId,\"] local candidate count\"),this.localCandidateCount))},setTimeout((()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,Qy.debug(\"[pc-\".concat(this.store.p2pId,\"] onicecandidate timeout, local candidate count\"),this.localCandidateCount))}),Dy(\"CANDIDATE_TIMEOUT\"))}unbindPCEvents(){this.peerConnection.oniceconnectionstatechange=null,this.peerConnection.onconnectionstatechange=null,this.peerConnection.onsignalingstatechange=null,this.peerConnection.onicecandidateerror=null,this.peerConnection.onicecandidate=null,this.peerConnection.ontrack=null}static resolvePCConfiguration(t){const i={iceServers:[]};return t.iceServers?i.iceServers=t.iceServers:t.turnServer&&\"off\"!==t.turnServer.mode&&(bI(t.turnServer.servers)?i.iceServers=t.turnServer.servers:(i.iceServers&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers)),Dy(\"USE_TURN_SERVER_OF_GATEWAY\")&&i.iceServers&&t.turnServer.serversFromGateway&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway)),Dy(\"FORCE_TURN_TCP\")?i.iceTransportPolicy=\"relay\":t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach((e=>{e.forceturn&&(i.iceTransportPolicy=\"relay\")})))),i}static turnServerConfigToIceServers(e){const t=[];return e.forEach((e=>{e.security?e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:\"password\",urls:\"turns:\".concat(Hw(e.turnServerURL),\":\").concat(e.tcpport,\"?transport=tcp\")}):(e.udpport&&!Dy(\"FORCE_TURN_TCP\")&&t.push({username:e.username,credential:e.password,credentialType:\"password\",urls:\"turn:\".concat(e.turnServerURL,\":\").concat(e.udpport,\"?transport=udp\")}),e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:\"password\",urls:\"turn:\".concat(e.turnServerURL,\":\").concat(e.tcpport,\"?transport=tcp\")}))})),t}async applySendEncodings(e,t){try{if(!_U().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let l=0;l1&&(t.scaleResolutionDownBy=u._encoderConfig.scaleResolutionDownBy);if(Dy(\"DSCP_TYPE\")&&Jv()){var d;const e=Dy(\"DSCP_TYPE\");Dn(d=[\"very-low\",\"low\",\"medium\",\"high\"]).call(d,e)&&(t.networkPriority=e)}const l=h.sender.getParameters(),p=null===(r=l.encodings)||void 0===r?void 0:r[0];Pv()&&!p&&(e.encodings=[t]),p&&Object.assign(p,t),Object.assign(l,e),await h.sender.setParameters(l)}}}catch(e){Qy.debug(\"Apply RTPSendEncodings failed.\")}}mungSendOfferSDP(e,t,i){const n=wB.parse(e);return t.forEach(((e,t)=>{const r=i[t],o=n.mediaDescriptions.find((e=>e.attributes.mid===r));o&&(ij(o,e),aj(o,e,this.store.codec))})),wB.print(n)}mungReceiveAnswerSDP(e,t,i){const n=wB.parse(e),r=n.mediaDescriptions.find((e=>e.attributes.mid===t));return r&&i===nw.AUDIO&&\"audio\"===r.media.mediaType&&uj(r),this.useXR&&pj(n),wB.print(n)}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=e=>{var t;null===(t=this.onFirstAudioReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoReceived=e=>{var t;null===(t=this.onFirstVideoReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstAudioDecoded=e=>{var t;null===(t=this.onFirstAudioDecoded)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoDecoded=(e,t,i)=>{var n;null===(n=this.onFirstVideoDecoded)||void 0===n||n.call(this,e,t,i)},this.statsFilter.onSelectedLocalCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedLocalCandidateChanged)||void 0===i||i.call(this,e,t)},this.statsFilter.onSelectedRemoteCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedRemoteCandidateChanged)||void 0===i||i.call(this,e,t)},this.statsFilter.onFirstVideoDecodedTimeout=e=>{var t;null===(t=this.onFirstVideoDecodedTimeout)||void 0===t||t.call(this,e)}}unbindStatsEvents(){this.statsFilter.onFirstAudioReceived=void 0,this.statsFilter.onFirstVideoReceived=void 0,this.statsFilter.onFirstAudioDecoded=void 0,this.statsFilter.onFirstVideoDecoded=void 0,this.statsFilter.onSelectedLocalCandidateChanged=void 0,this.statsFilter.onSelectedRemoteCandidateChanged=void 0,this.statsFilter.onFirstVideoDecodedTimeout=void 0}async applySimulcastForFirefox(e,t){if(e.length===t.length)for(let a=0;a200&&null!==(o=d._scalabilityMode)&&void 0!==o&&o.numSpatialLayers&&(null===(s=d._scalabilityMode)||void 0===s?void 0:s.numSpatialLayers)>1&&\"vp8\"===this.store.codec){const e={},t={high:1e3*(d._encoderConfig.bitrateMax-50),medium:5e4};e.encodings=[{rid:\"m\",active:!0,maxBitrate:t.medium,scaleResolutionDownBy:4},{rid:\"h\",active:!0,maxBitrate:t.high}];const i=c.sender.getParameters();await c.sender.setParameters(Object.assign(i,e))}}}async applySimulcastEncodings(e,t){if(!Pv()&&e.length===t.length)for(let i=0;i200&&null!==(r=e._scalabilityMode)&&void 0!==r&&r.numSpatialLayers&&(null===(o=e._scalabilityMode)||void 0===o?void 0:o.numSpatialLayers)>1)}logSDPExchange(e,t,i,n){if(Dy(\"SDP_LOGGING\"))return Qy.upload(\"exchanging \".concat(i,\" \").concat(t,\" SDP during NVExtentionsConnection.\").concat(n,\"\\n\"),e),\"offer\"===t?e=>{this.logSDPExchange(e,\"answer\",\"local\"===i?\"remote\":\"local\",n)}:void 0}async getRemoteSSRC(e){if(!this.remoteSDP)return;const t=this.remoteSDP.getSSRC(e);return null==t?void 0:t[0].ssrcId}setConfiguration(t){if(_U().supportPCSetConfiguration){const i=e.resolvePCConfiguration(t);this.peerConnection.setConfiguration(i)}}},nb(oW.prototype,\"connect\",[dW],Object.getOwnPropertyDescriptor(oW.prototype,\"connect\"),oW.prototype),nb(oW.prototype,\"updateRemoteRTPCapabilities\",[dW],Object.getOwnPropertyDescriptor(oW.prototype,\"updateRemoteRTPCapabilities\"),oW.prototype),nb(oW.prototype,\"updateRemoteConnect\",[dW],Object.getOwnPropertyDescriptor(oW.prototype,\"updateRemoteConnect\"),oW.prototype),nb(oW.prototype,\"createDataChannels\",[dW],Object.getOwnPropertyDescriptor(oW.prototype,\"createDataChannels\"),oW.prototype),nb(oW.prototype,\"receive\",[dW],Object.getOwnPropertyDescriptor(oW.prototype,\"receive\"),oW.prototype),nb(oW.prototype,\"batchReceive\",[dW],Object.getOwnPropertyDescriptor(oW.prototype,\"batchReceive\"),oW.prototype),nb(oW.prototype,\"stopReceiving\",[dW],Object.getOwnPropertyDescriptor(oW.prototype,\"stopReceiving\"),oW.prototype),nb(oW.prototype,\"muteRemote\",[dW],Object.getOwnPropertyDescriptor(oW.prototype,\"muteRemote\"),oW.prototype),nb(oW.prototype,\"unmuteRemote\",[dW],Object.getOwnPropertyDescriptor(oW.prototype,\"unmuteRemote\"),oW.prototype),nb(oW.prototype,\"muteLocal\",[dW],Object.getOwnPropertyDescriptor(oW.prototype,\"muteLocal\"),oW.prototype),nb(oW.prototype,\"unmuteLocal\",[dW],Object.getOwnPropertyDescriptor(oW.prototype,\"unmuteLocal\"),oW.prototype),nb(oW.prototype,\"close\",[dW],Object.getOwnPropertyDescriptor(oW.prototype,\"close\"),oW.prototype),nb(oW.prototype,\"updateEncoderConfig\",[dW],Object.getOwnPropertyDescriptor(oW.prototype,\"updateEncoderConfig\"),oW.prototype),nb(oW.prototype,\"updateSendParameters\",[dW],Object.getOwnPropertyDescriptor(oW.prototype,\"updateSendParameters\"),oW.prototype),nb(oW.prototype,\"replaceTrack\",[dW],Object.getOwnPropertyDescriptor(oW.prototype,\"replaceTrack\"),oW.prototype),nb(oW.prototype,\"getRemoteSSRC\",[dW],Object.getOwnPropertyDescriptor(oW.prototype,\"getRemoteSSRC\"),oW.prototype),oW);function dW(e,t,i){const n=e[t];if(\"function\"!=typeof n)throw new Error(\"Cannot use mutex on object property.\");return i.value=async function(){const e=this.mutex,i=await e.lock(\"From NVExtentionsConnection.\".concat(t));try{for(var r=arguments.length,o=new Array(r),s=0;s{const n=setTimeout((()=>{this.closeSignal(),t(new bb(tI.DATACHANNEL_CONNECTION_TIMEOUT,\"Datachannel connection timed out, candidates: \".concat(JSON.stringify(i))))}),2e3);this.dataChannel.onopen=()=>{if(\"open\"===this.dataChannel.readyState)return clearTimeout(n),void e()},this.dataChannel.onerror=e=>{this.closeSignal(),t(e)}})),{transmitter:this.dataChannel,close:this.closeSignal.bind(this)}}async updateRemoteRTPCapabilities(e,t){return this._p2pConnection.updateRemoteRTPCapabilities(e,t)}send(e,t,i){var n=this;return pB((function*(){const r=yield rB(n.mutex.lock(\"From DataChannelConnection.send\"));try{return yield*gG(hW(n._p2pConnection.send(e,t,i)))}finally{r()}}))()}async stopSending(e,t){return this._p2pConnection.stopSending(e,t)}async createDataChannels(e,t){return this._p2pConnection.createDataChannels(e,t)}async stopDataChannels(e){return this._p2pConnection.stopDataChannels(e)}async receive(e,t,i,n){return this._nvMedia?(Qy.debug(\"[DataChannelConnection] receive \".concat(e,\" by DataChannel.\")),await this._nvMedia.reveiveByRTCMedia(e,t,this.cname)):(Qy.debug(\"[DataChannelConnection] receive \".concat(e,\" by WebRTC.\")),await this._p2pConnection.receive(e,t,i,n))}async batchReceive(e){return[...await this._p2pConnection.batchReceive(e)]}async stopReceiving(e){return await this._p2pConnection.stopReceiving(e)}async muteRemote(e){return await this._p2pConnection.muteRemote(e)}async unmuteRemote(e){return await this._p2pConnection.unmuteRemote(e)}async muteLocal(e){return await this._p2pConnection.muteLocal(e)}async unmuteLocal(e){return await this._p2pConnection.unmuteLocal(e)}restartICE(e){var t=this;return pB((function*(){return yield*gG(hW(t._p2pConnection.restartICE(e)))}))()}close(){var e;null===(e=this._nvMedia)||void 0===e||e.close(),this._p2pConnection.close(),this.unbindConnectionEvents(this._p2pConnection)}getStats(){return this._p2pConnection.getStats()}getRemoteVideoIsReady(e){return this._p2pConnection.getRemoteVideoIsReady(e)}updateRemoteConnect(e){var t;null===(t=this._nvMedia)||void 0===t||t.setRemoteRtpCapabilities(e),this._p2pConnection.updateRemoteConnect(e)}async updateEncoderConfig(e,t){return await this._p2pConnection.updateEncoderConfig(e,t)}async updateSendParameters(e,t){return await this._p2pConnection.updateSendParameters(e,t)}setStatsRemoteVideoIsReady(e,t){this._p2pConnection.setStatsRemoteVideoIsReady(e,t)}async replaceTrack(e,t){return await this._p2pConnection.replaceTrack(e,t)}async getRemoteSSRC(e){return this._p2pConnection.getRemoteSSRC(e)}logSDPExchange(e,t,i,n){if(Dy(\"SDP_LOGGING\"))return Qy.upload(\"exchanging \".concat(i,\" \").concat(t,\" SDP during DataChannelConnection.\").concat(n,\"\\n\"),e),\"offer\"===t?e=>{this.logSDPExchange(e,\"answer\",\"local\"===i?\"remote\":\"local\",n)}:void 0}static resolvePCConfiguration(t){const i={iceServers:[]};return t.iceServers?i.iceServers=t.iceServers:t.turnServer&&\"off\"!==t.turnServer.mode&&(bI(t.turnServer.servers)?i.iceServers=t.turnServer.servers:(i.iceServers&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers)),Dy(\"USE_TURN_SERVER_OF_GATEWAY\")&&i.iceServers&&t.turnServer.serversFromGateway&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway)),Dy(\"FORCE_TURN_TCP\")?i.iceTransportPolicy=\"relay\":t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach((e=>{e.forceturn&&(i.iceTransportPolicy=\"relay\")})))),i}static turnServerConfigToIceServers(e){const t=[];return e.forEach((e=>{e.security?e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:\"password\",urls:\"turns:\".concat(Hw(e.turnServerURL),\":\").concat(e.tcpport,\"?transport=tcp\")}):(e.udpport&&!Dy(\"FORCE_TURN_TCP\")&&t.push({username:e.username,credential:e.password,credentialType:\"password\",urls:\"turn:\".concat(e.turnServerURL,\":\").concat(e.udpport,\"?transport=udp\")}),e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:\"password\",urls:\"turn:\".concat(e.turnServerURL,\":\").concat(e.tcpport,\"?transport=tcp\")}))})),t}bindPCEvents(){this._p2pConnection.onICEConnectionStateChange=e=>{var t;return null===(t=this.onICEConnectionStateChange)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onConnectionStateChange=e=>{var t;return null===(t=this.onConnectionStateChange)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onDTLSTransportStateChange=e=>{var t;return null===(t=this.onDTLSTransportStateChange)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onDTLSTransportError=e=>{var t;return null===(t=this.onDTLSTransportError)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onICETransportStateChange=e=>{var t;return null===(t=this.onICETransportStateChange)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onFirstAudioReceived=e=>{var t;return null===(t=this.onFirstAudioReceived)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onFirstVideoReceived=e=>{var t;return null===(t=this.onFirstVideoReceived)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onFirstAudioDecoded=e=>{var t;return null===(t=this.onFirstAudioDecoded)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onFirstVideoDecoded=(e,t,i)=>{var n;return null===(n=this.onFirstVideoDecoded)||void 0===n?void 0:n.call(this,e,t,i)},this._p2pConnection.onFirstVideoDecodedTimeout=e=>{var t;return null===(t=this.onFirstVideoDecodedTimeout)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onSelectedLocalCandidateChanged=(e,t)=>{var i;return null===(i=this.onSelectedLocalCandidateChanged)||void 0===i?void 0:i.call(this,e,t)},this._p2pConnection.onSelectedRemoteCandidateChanged=(e,t)=>{var i;return null===(i=this.onSelectedRemoteCandidateChanged)||void 0===i?void 0:i.call(this,e,t)}}closeSignal(){this.dataChannel.close(),this.peerConnection.close()}unbindConnectionEvents(e){e.onConnectionStateChange=void 0,e.onICEConnectionStateChange=void 0,e.onICETransportStateChange=void 0,e.onDTLSTransportStateChange=void 0,e.onDTLSTransportError=void 0,e.onFirstAudioDecoded=void 0,e.onFirstAudioReceived=void 0,e.onFirstVideoDecoded=void 0,e.onFirstVideoReceived=void 0,e.onSelectedLocalCandidateChanged=void 0,e.onSelectedRemoteCandidateChanged=void 0,e.onFirstVideoDecodedTimeout=void 0}setConfiguration(e){this._p2pConnection.setConfiguration(e)}},nb(lW.prototype,\"connect\",[_W],Object.getOwnPropertyDescriptor(lW.prototype,\"connect\"),lW.prototype),nb(lW.prototype,\"updateRemoteRTPCapabilities\",[_W],Object.getOwnPropertyDescriptor(lW.prototype,\"updateRemoteRTPCapabilities\"),lW.prototype),nb(lW.prototype,\"createDataChannels\",[_W],Object.getOwnPropertyDescriptor(lW.prototype,\"createDataChannels\"),lW.prototype),nb(lW.prototype,\"receive\",[_W],Object.getOwnPropertyDescriptor(lW.prototype,\"receive\"),lW.prototype),nb(lW.prototype,\"stopReceiving\",[_W],Object.getOwnPropertyDescriptor(lW.prototype,\"stopReceiving\"),lW.prototype),nb(lW.prototype,\"muteRemote\",[_W],Object.getOwnPropertyDescriptor(lW.prototype,\"muteRemote\"),lW.prototype),nb(lW.prototype,\"unmuteRemote\",[_W],Object.getOwnPropertyDescriptor(lW.prototype,\"unmuteRemote\"),lW.prototype),nb(lW.prototype,\"muteLocal\",[_W],Object.getOwnPropertyDescriptor(lW.prototype,\"muteLocal\"),lW.prototype),nb(lW.prototype,\"unmuteLocal\",[_W],Object.getOwnPropertyDescriptor(lW.prototype,\"unmuteLocal\"),lW.prototype),nb(lW.prototype,\"close\",[_W],Object.getOwnPropertyDescriptor(lW.prototype,\"close\"),lW.prototype),nb(lW.prototype,\"updateEncoderConfig\",[_W],Object.getOwnPropertyDescriptor(lW.prototype,\"updateEncoderConfig\"),lW.prototype),nb(lW.prototype,\"updateSendParameters\",[_W],Object.getOwnPropertyDescriptor(lW.prototype,\"updateSendParameters\"),lW.prototype),nb(lW.prototype,\"replaceTrack\",[_W],Object.getOwnPropertyDescriptor(lW.prototype,\"replaceTrack\"),lW.prototype),nb(lW.prototype,\"getRemoteSSRC\",[_W],Object.getOwnPropertyDescriptor(lW.prototype,\"getRemoteSSRC\"),lW.prototype),lW);function _W(e,t,i){const n=e[t];if(\"function\"!=typeof n)throw new Error(\"Cannot use mutex on object property.\");return i.value=async function(){const e=this.mutex,i=await e.lock(\"From DataChannelConnection.\".concat(t));try{for(var r=arguments.length,o=new Array(r),s=0;s{const n=await this.mutex.lock(\"Locking from P2PChannel.handleMuteLocalTrack\");try{if(!this.connection||this.state!==aw.Connected)return void i(new iI(tI.INVALID_OPERATION,\"Cannot call P2PChannel.handleMuteLocalTrack before connection established.\"));const r=this.filterTobeMutedTracks(e);if(0===r.length)return void t();const o=r.find((e=>\"videoLowTrack\"===e[0]));if(o){o[1].track._originMediaStreamTrack.stop()}await this.connection.muteLocal(r.map((e=>{let[,{id:t}]=e;return t})));const s=this.createMuteMessage(r);await MI(this,cw.RequestMuteLocal,s),t()}catch(e){i(e)}finally{n()}})),ng(this,\"handleUnmuteLocalTrack\",(async(e,t,i)=>{const n=await this.mutex.lock(\"Locking from P2PChannel.handleUnmuteLocalTrack\");try{if(!this.connection||this.state!==aw.Connected)return void i(new iI(tI.INVALID_OPERATION,\"Cannot call P2PChannel.handleUnmuteLocalTrack before connection established.\"));const r=this.filterTobeUnmutedTracks(e);if(0===r.length)return void t();const o=r.find((e=>\"videoLowTrack\"===e[0]));if(o){const t=o[1];if(t.track._originMediaStreamTrack.stop(),!Dy(\"DISABLE_DUAL_STREAM_USE_ENCODING\")&&_U().supportDualStreamEncoding){const i=e._mediaStreamTrack.clone();t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i}else{const i=vj(e,xI(this,cw.RequestLowStreamParameter));t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i}await new Gu(((e,i)=>{this.handleReplaceTrack(t.track,e,i,!0)}))}await this.connection.unmuteLocal(r.map((e=>{let[,{id:t}]=e;return t})));const s=this.createUnmuteMessage(r);await MI(this,cw.RequestUnmuteLocal,s),t()}catch(e){i(e)}finally{n()}})),ng(this,\"handleUpdateVideoEncoder\",(async(e,t,i)=>{const n=await this.mutex.lock(\"Locking from P2PChannel.handleSetVideoEncoder\");try{const i=this.localTrackMap.get(sw.LocalVideoTrack);if(!this.connection||!i||i.track!==e||this.state!==aw.Connected)return void t();const{id:r,track:o}=i;await this.connection.updateSendParameters(r,o),await this.connection.updateEncoderConfig(r,o),this.emit(cw.UpdateVideoEncoder,o),t()}catch(e){i(e)}finally{n()}})),ng(this,\"handleUpdateVideoSendParameters\",(async(e,t,i)=>{const n=await this.mutex.lock(\"Locking from P2PChannel.handleUpdateVideoSendParameters\");try{const i=this.localTrackMap.get(sw.LocalVideoTrack);if(!this.connection||!i||i.track!==e||this.state!==aw.Connected)return void t();const{id:r,track:o}=i;await this.connection.updateSendParameters(r,o),t()}catch(e){i(e)}finally{n()}})),ng(this,\"handleReplaceMixingTrack\",(async(e,t,i,n)=>{if(!this.connection||this.state!==aw.Connected)return void t();const r=Hj([e]);let o;Qy.debug(\"[\".concat(this.store.clientId,\"] [p2pId: \").concat(this.store.p2pId,\"]: P2PConnection will replace audioTrack [\").concat(r.getTrackId(),\"]\")),\"boolean\"==typeof n&&n||(o=await this.mutex.lock(\"From P2PChannel.handleReplaceMixingTrack\"));try{await this.replaceTrack(e,r),t()}catch(e){i(e)}finally{var s;null===(s=o)||void 0===s||s()}})),ng(this,\"handleReplaceTrack\",(async(e,t,i,n)=>{let r;Qy.debug(\"[\".concat(this.store.clientId,\"] P2PChannel handleReplaceTrack for [track-id-\").concat(e.getTrackId(),\"]\")),\"boolean\"==typeof n&&n||(r=await this.mutex.lock(\"From P2PChannel.handleReplaceTrack\"));try{var o;const i=Array.from(this.localTrackMap.entries()).find((t=>{let[,{track:i}]=t;return e===i}));if(!this.connection||!i||this.state!==aw.Connected)return void t();if(await(null===(o=this.connection)||void 0===o?void 0:o.replaceTrack(e,i[1].id)),this.isPlanB){const t=i[1];t.id=e._mediaStreamTrack.id,this.localTrackMap.set(i[0],t)}if(i[0]===sw.LocalVideoTrack&&!Dy(\"DISABLE_DUAL_STREAM_USE_ENCODING\")&&_U().supportDualStreamEncoding){const t=this.localTrackMap.get(sw.LocalVideoLowTrack);if(t){const i=e._mediaStreamTrack.clone();t.track._originMediaStreamTrack.stop(),t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i,await new Gu(((e,i)=>{this.handleReplaceTrack(t.track,e,i,!0)}))}}t()}catch(e){i(e)}finally{var s;null===(s=r)||void 0===s||s()}})),ng(this,\"handleGetRTCStats\",(e=>{e(this.statsCollector.getRTCStats())})),ng(this,\"handleGetLocalVideoStats\",(e=>{e(this.statsCollector.getLocalVideoTrackStats())})),ng(this,\"handleGetLocalAudioStats\",(e=>{e(this.statsCollector.getLocalAudioTrackStats())})),ng(this,\"handleGetRemoteVideoStats\",(e=>this.statsCollector.getRemoteVideoTrackStats(e.uid)[e.uid])),ng(this,\"handleGetRemoteAudioStats\",(e=>this.statsCollector.getRemoteAudioTrackStats(e.uid)[e.uid])),this.store=e,this.statsCollector=t,this.statsCollector.addP2PChannel(this),this.statsUploader=new Fj(this.store),this.bindStatsUploaderEvents(),this.isPlanB=!_U().supportUnifiedPlan||Dy(\"CHROME_FORCE_PLAN_B\")&&Jv(),this.shouldForwardP2PCreation=Dy(\"FORWARD_P2P_CREATION\")&&_U().supportPCSetConfiguration&&zv(),this.shouldForwardP2PCreation&&(this.connection=this.store.useDataChannel?new pW({},this.store):this.isPlanB?new bG({},this.store):new XG({},this.store),this.bindConnectionEvents(this.connection))}async startP2PConnection(e,t){var i;this.state=aw.New;const n=this.shouldForwardP2PCreation&&\"closed\"===(null===(i=this.connection)||void 0===i?void 0:i.peerConnectionState);if(this.shouldForwardP2PCreation&&!n||(n&&this.connection&&(Qy.warning(\"[\".concat(this.store.clientId,\"] P2PChannel.startP2PConnection ForwardP2P closed.\")),this.connection.close(),this.unbindConnectionEvents(this.connection)),this.connection=this.store.useDataChannel?new pW(e,this.store):this.isPlanB?new bG(e,this.store):new XG(e,this.store),this.bindConnectionEvents(this.connection)),!this.connection)throw new iI(tI.UNEXPECTED_ERROR,\"Cannot P2PChannel.startConnection before P2PConnection initialization .\");return this._pcStatsUploadType=Dy(\"NEW_ICE_RESTART\")?ow.FIRST_CONNECTION:ow.OLD_FIRST_CONNECTION,this._isFirstConnected=!0,this._isInRestartIce=!1,this._isStartRestartIce=!1,this.connection.setConfiguration(e),this.connection.establishPromise}async connect(e,t,i,n,r,o){if(!this.connection)throw new iI(tI.UNEXPECTED_ERROR,\"Cannot P2PChannel.connect before P2PChannel.startP2PConnection .\");this.connection instanceof pW?this.connection.updateRemoteConnect(n):(this.store.peerConnectionStart(),await this.connection.connect(e,t,i,n,r,o),this.statsUploader.startUploadTransportStats(),this.statsUploader.startUploadExtensionUsageStats(),this.state=aw.Connected)}updateRemoteRTPCapabilities(e){const t=Array.from(this.localTrackMap.entries()).filter((e=>{var t;let[i]=e;return Dn(t=[sw.LocalVideoLowTrack,sw.LocalVideoTrack]).call(t,i)})),i=t.map((e=>{let[,{id:t}]=e;return t})),n=t.map((e=>{let[t]=e;return t}));if(this.connection instanceof XG){if(oA.updateRemoteRTPCapabilities(this.store.sessionId,{trackTypes:JSON.stringify(n),localCodecs:JSON.stringify(this.connection.localCodecs),remoteCodecs:JSON.stringify(e)}),!Dn(e).call(e,this.store.codec)){const t=[\"vp9\",\"vp8\",\"h264\"].find((t=>Dn(e).call(e,t)));t&&(this.store.codec=t,Qy.debug(\"[\".concat(this.store.clientId,\"] [\").concat(this.store.p2pId,\" updateRemoteRTPCapabilities] default codec is not available, hence the fallback to \").concat(t,\".\")))}this.connection.updateRemoteRTPCapabilities(i,e)}}async preConnect(e,t,i,n,r,o){if(!this.connection)throw new iI(tI.UNEXPECTED_ERROR,\"Cannot P2PChannel.connect before P2PChannel.startP2PConnection .\");this.store.peerConnectionStart();const s=await this.connection.connect(e,t,i,n,r,o);return this.statsUploader.startUploadTransportStats(),this.statsUploader.startUploadExtensionUsageStats(),this.state=aw.Connected,s}getEstablishParams(){if(this.connection instanceof pW)return this.connection.getP2PConnectionParams();throw new Error(\"Only DataChannelConnection needs to obtain establishParams\")}async publishDataChannel(e){if(!this.connection||this.state!==aw.Connected){if(this.state===aw.Disconnected)throw new iI(tI.UNEXPECTED_ERROR,\"PeerConnection already disconnected.\");return void e.forEach((e=>{var t;Dn(t=this.pendingLocalDataChannels).call(t,e)||this.pendingLocalDataChannels.push(e)}))}const t=this.filterTobePublishedDataChannels(e);0!==t.length&&(t.forEach((e=>{const t=Date.now();this.store.publish(e.id.toString(),\"datachannel\",t)})),await this.connection.createDataChannels(this.store.uid,t),t.forEach((e=>{this.localDataChannels.push(e);const t=Date.now();this.store.publish(e.id+\"\",\"datachannel\",void 0,t)})))}publish(e,t,i){var n=this;return pB((function*(){const r=yield rB(n.mutex.lock(\"From P2PChannel.publish\"));try{if(!n.connection||n.state!==aw.Connected){if(n.state===aw.Disconnected)throw new iI(tI.UNEXPECTED_ERROR,\"PeerConnection already disconnected.\");n.throwIfTrackTypeNotMatch(e);const t=e.filter((e=>-1===n.pendingLocalTracks.indexOf(e)));return void(n.pendingLocalTracks=n.pendingLocalTracks.concat(t))}n.store.pubId=n.store.pubId+1,iB.markPublishStart(n.store.clientId,n.store.pubId);const o=n.filterTobePublishedTracks(e,t,i);if(0===o.length)return void(yield rB(n.tryToUnmuteAudio(e)));yield*gG(TW(n.doPublish(n.connection,o)))}finally{r()}}))()}doPublish(e,t){var i=this;return pB((function*(){t.forEach((e=>{let{track:t,type:n}=e;const r=Date.now();i.store.publish(t.getTrackId(),n===sw.LocalAudioTrack?\"audio\":\"video\",r)})),i.bindLocalTrackEvents(t);const n=t.map((e=>{let{track:t}=e;return t})),r=yield rB(e.send(t.map((e=>{let{track:t}=e;return t})),i.store.codec,i.store.audioCodec)),o=(yield rB(r.next())).value,s=i.createGatewayPublishMessage(t,o);let a;try{a=yield s}catch(e){throw r.throw(e),(null==e?void 0:e.code)===tI.WS_ABORT&&t.forEach((e=>{let{track:t}=e;-1===i.pendingLocalTracks.indexOf(t)&&i.pendingLocalTracks.push(t)})),i.unbindLocalTrackEvents(t),e}const c=i.mapPubResToRemoteConfig(s,a),d=(yield rB(r.next(c))).value,l=Dy(\"ENABLE_VIDEO_SEI\");n.forEach((async e=>{const t=e.getRTCRtpTransceiver();t&&l&&(e.trackMediaType===nw.VIDEO?await QF(t.sender,e):e.trackMediaType===nw.AUDIO&&await async function(e){if(!_U().supportWebRTCEncodedTransform)return void Qy.warning(\"browser not support audio encoded transform\");if(zF.has(e))return;if(!e.track)return;const t={track:e.track};if(Ov()){if(!e.createEncodedStreams)return void Qy.warning(\"browser not support createEncodedStreams() API\");let n=null;try{n=e.createEncodedStreams()}catch(e){return void Qy.error(\"create audio-encoded-streams error\",e&&e.message)}const r=new TransformStream({transform(n,r){t.controller||(t.controller=r),e.track&&e.track.id!==t.track.id&&(Qy.debug(\"audio track changed: \".concat(t.track.id,\" => \").concat(e.track.id)),t.track.removeEventListener(\"ended\",i),t.track=e.track,t.track.addEventListener(\"ended\",i)),r.enqueue(n)}});n.readable.pipeThrough(r).pipeTo(n.writable)}else if(Nv()){if(\"undefined\"==typeof RTCRtpScriptTransform)return void Qy.warning(\"browser not support RTCRtpScriptTransform\");const n=qF(),r=new MessageChannel;await new Gu((e=>n.onmessage=t=>{\"registered\"===t.data&&e(void 0)}));const o=new RTCRtpScriptTransform(n,{name:\"tx\",port:r.port2},[r.port2]);e.transform=o,await new Gu((e=>n.onmessage=t=>{\"started\"===t.data&&e(void 0)})),r.port1.onmessage=n=>{var r;n.data.transformed&&e.track&&(null===(r=e.track)||void 0===r?void 0:r.id)!==t.track.id&&(Qy.debug(\"audio track changed: \".concat(t.track.id,\" => \").concat(e.track.id)),t.track.removeEventListener(\"ended\",i),t.track=e.track,t.track.addEventListener(\"ended\",i))},t.worker=n}function i(){if(e.track){if(this.id!==e.track.id)return;e.track.removeEventListener(\"ended\",i)}const t=zF.get(e);if(t){zF.delete(e);try{var n,r;null===(n=t.controller)||void 0===n||n.terminate(),null===(r=t.worker)||void 0===r||r.terminate()}catch(e){Qy.warning(e&&e.message)}}}zF.set(e,t),e.track.addEventListener(\"ended\",i)}(t.sender))})),t.forEach((e=>{let{type:t}=e;i.statsCollector.addLocalStats(t)})),i.assignLocalTracks(t,d),i.statsUploader.startUploadOutboundStats(),t.forEach((e=>{let{track:t,type:n}=e;const r=Date.now();i.store.publish(t.getTrackId(),n===sw.LocalAudioTrack?\"audio\":\"video\",void 0,r)}))}))()}async updateVideoStreamParameter(e,t){const i=this.localTrackMap.get(t);if(!i)return;if(!(i.track instanceof vF))return Qy.warn(\"[updateVideoStreamParameter]: track is not an instance of LocalVideoTrack\");if(!(this.connection instanceof XG||this.connection instanceof bG))return Qy.warn(\"[updateVideoStreamParameter]: connection is not P2PConnection or P2PConnectionPlanB\");const{track:n}=i,r=function(e,t){const i={};return e.height&&e.width&&(i.scaleResolutionDownBy=Qw(e,t)),i.maxFramerate=e.framerate?Yw(e.framerate):void 0,i.maxBitrate=e.bitrate?1e3*e.bitrate:void 0,i}(e,n);if(n._encoderConfig||(n._encoderConfig={}),t!==sw.LocalVideoLowTrack||!Dy(\"DISABLE_DUAL_STREAM_USE_ENCODING\")&&_U().supportDualStreamEncoding)null!=r.scaleResolutionDownBy&&(n._encoderConfig.scaleResolutionDownBy=r.scaleResolutionDownBy);else{const t=n._originMediaStreamTrack;if(!t.canvas)return Qy.warn(\"[\".concat(n.getTrackId(),\"] no canvas on track\"));!function(e,t){const i=e.canvas;t.width&&(i.width=Yw(t.width)),t.height&&(i.height=Yw(t.height)),t.framerate&&(i.stopCapture&&i.stopCapture(),i.stopCapture=ux((()=>{!i.startCapture&&i.stopCapture&&i.stopCapture(),i.startCapture&&i.startCapture()}),Yw(t.framerate)))}(t,e)}null!=r.maxBitrate&&(n._encoderConfig.bitrateMax=r.maxBitrate/1e3),null!=r.maxFramerate&&(n._encoderConfig.frameRate&&\"object\"==typeof n._encoderConfig.frameRate?n._encoderConfig.frameRate.max=r.maxFramerate:n._encoderConfig.frameRate={max:r.maxFramerate}),Qy.debug(\"[\".concat(n.getTrackId(),\"] LowStreamEncoderConfig: , \").concat(JSON.stringify(n._encoderConfig))),await this.connection.updateRtpSenderEncodings(n)}publishLowStream(e){var t=this;return pB((function*(){if(!t.connection||t.state!==aw.Connected)return;const i=yield rB(t.mutex.lock(\"Locking from P2PChannel.publishLowStream\"));try{const r=t.localTrackMap.get(sw.LocalVideoTrack);if(!r)throw new iI(tI.UNEXPECTED_ERROR,\"Could not find high stream\");if(t.localTrackMap.has(sw.LocalVideoLowTrack))throw new iI(tI.UNEXPECTED_ERROR,\"[\".concat(t.store.clientId,\"] Can't publish low stream when stream already publish\"));const o=[{track:t.getLowVideoTrack(r.track,e),type:sw.LocalVideoLowTrack}];if(yield*gG(TW(t.doPublish(t.connection,o))),r.track.muted||!r.track.enabled){var n;const e=null===(n=t.localTrackMap.get(sw.LocalVideoLowTrack))||void 0===n?void 0:n.id;void 0!==e&&(yield rB(t.connection.muteLocal([e])))}}finally{i()}}))()}async republish(){this.pendingLocalTracks.length>0&&(Qy.debug(\"[\".concat(this.store.clientId,\"] Emit P2PChannelEvents.RequestRePublish to republish tracks.\")),await kI(this,cw.RequestRePublish,this.pendingLocalTracks),this.emit(cw.MediaReconnectEnd,this.store.uid),this.pendingLocalTracks=[]),this.pendingLocalDataChannels.length>0&&(Qy.debug(\"Emit P2PChannelEvents.RequestRePublishDataChannel to republish datachannels.\"),await kI(this,cw.RequestRePublishDataChannel,this.pendingLocalDataChannels),this.pendingLocalDataChannels=[])}async reSubscribe(e){for(let e=this.pendingRemoteTracks.length-1;e>=0;e--){const{user:t,kind:i}=this.pendingRemoteTracks[e];(i!==nw.AUDIO||t._audio_added_&&t._audioSSRC)&&(i!==nw.VIDEO||t._video_added_&&t._videoSSRC)||this.pendingRemoteTracks.splice(e,1)}if(e)await kI(this,cw.RequestReSubscribe,this.pendingRemoteTracks);else for(const{user:e,kind:t}of this.pendingRemoteTracks)await this.subscribe(e,t,t===nw.VIDEO?e._videoSSRC:e._audioSSRC);this.pendingRemoteTracks.forEach((e=>{let{user:t}=e;this.emit(cw.MediaReconnectEnd,t.uid)})),this.pendingRemoteTracks=[]}async unpublish(e){if(!this.connection||this.state!==aw.Connected)return void e.forEach((e=>{const t=this.pendingLocalTracks.indexOf(e);-1!==t&&this.pendingLocalTracks.splice(t,1)}));const t=this.filterTobeUnpublishedTracks(e);if(0===t.length)return;const i=t.find((e=>\"videoLowTrack\"===e[0]));if(i){i[1].track.close()}return this.doUnpublish(this.connection,t)}async unpublishDataChannel(e){if(!this.connection||this.state!==aw.Connected)return void e.forEach((e=>{const t=this.pendingLocalDataChannels.indexOf(e);-1!==t&&this.pendingLocalDataChannels.splice(t,1)}));const t=this.filterTobeUnpublishedDataChannels(e);return 0!==t.length?(t.forEach((e=>{const t=this.localDataChannels.indexOf(e);-1!==t&&this.localDataChannels.splice(t,1)})),0===this.localDataChannels.length&&await this.connection.stopDataChannels(this.store.uid),t.map((e=>e.id))):void 0}async unpublishLowStream(){if(!this.connection||this.state!==aw.Connected)return;const e=this.localTrackMap.get(sw.LocalVideoLowTrack);if(!e)return;e.track.close();const t=[[sw.LocalVideoLowTrack,e]];return this.doUnpublish(this.connection,t)}async doUnpublish(e,t){const i=this.createGatewayUnpublishMessage(t);return await e.stopSending(t.map((e=>{let[,{id:t}]=e;return t}))),this.withdrawLocalTracks(t),this.unbindLocalTrackEvents(t.map((e=>{let[t,{track:i}]=e;return{type:t,track:i}}))),t.forEach((e=>{let[t]=e;this.statsCollector.removeLocalStats(t)})),0===this.localTrackMap.size&&this.statsUploader.stopUploadOutboundStats(),i}async subscribeDataChannel(e,t){if(!this.connection||this.state!==aw.Connected)throw new iI(tI.INVALID_OPERATION,\"Cannot subscribe remote user when peerConnection disconnected.\");const i=t.filter((t=>{var i;return!(null!==(i=this.remoteDataChannelMap.get(e))&&void 0!==i&&i.get(t.id))}));if(0!==i.length)return await this.connection.createDataChannels(e.uid,i),i.forEach((t=>{var i;this.remoteDataChannelMap.has(e)?null===(i=this.remoteDataChannelMap.get(e))||void 0===i||i.set(t.id,t):this.remoteDataChannelMap.set(e,new Map([[t.id,t]]));const n=this.pendingRemoteDataChannels.findIndex((i=>{let{user:n,id:r}=i;return n.uid===e.uid&&r===t.id}));-1!==n&&this.pendingRemoteDataChannels.splice(n,1)})),i.map((e=>e.id))}async subscribe(e,t,i,n,r){var o;if(!this.connection||this.state!==aw.Connected)throw new iI(tI.INVALID_OPERATION,\"Cannot subscribe remote user when peerConnection disconnected.\");if(null!==(o=this.remoteUserMap.get(e))&&void 0!==o&&o.has(t))return;let s,a,c;if(r){const i=r.find((e=>{let{stream_type:i}=e;return i===t}));if(!i)throw new iI(tI.UNEXPECTED_ERROR,\"Cannot subscribe to remote \".concat(t,\" for user: \").concat(e.uid,\" because subscribe answer from gateway does not contain stream_type: \").concat(t,\".\"));const n=await this.connection.receive(t,i.ssrcs,String(e._uintid),i.attributes);this.connection instanceof XG&&(c=n.transceiver),s=n.track,a=n.id}else{const r=await this.connection.receive(t,[{ssrcId:i,rtx:n}],String(e._uintid),void 0);this.connection instanceof XG&&(c=r.transceiver),s=r.track,a=r.id}t===nw.AUDIO?(e._audioTrack?e._audioTrack._updateOriginMediaStreamTrack(s):(e._audioTrack=new BF(s,e.uid,e._uintid,this.store),Qy.info(\"[\".concat(this.store.clientId,\"] [\").concat(this.store.p2pId,\"] create remote audio track: \").concat(e._audioTrack.getTrackId()))),c&&e._audioTrack._updateRtpTransceiver(c),this.bindRemoteTrackEvents(e,e._audioTrack)):(e._videoTrack?e._videoTrack._updateOriginMediaStreamTrack(s):(e._videoTrack=new FF(s,e.uid,e._uintid,this.store),Qy.info(\"[\".concat(this.store.clientId,\"] [\").concat(this.store.p2pId,\"] create remote video track: \").concat(e._videoTrack.getTrackId()))),c&&e._videoTrack._updateRtpTransceiver(c),this.bindRemoteTrackEvents(e,e._videoTrack)),Dy(\"ENABLE_VIDEO_SEI\")&&c&&(t==nw.VIDEO?await $F(c.receiver,{onSei:t=>{var i;null===(i=e._videoTrack)||void 0===i||i._onSei(t)}}):t==nw.AUDIO&&await async function(e){if(!_U().supportWebRTCEncodedTransform)return void Qy.warning(\"browser not support audio encoded transform\");if(JF.has(e))return;const t={track:e.track};if(Ov()){if(!e.createEncodedStreams)return void Qy.warning(\"browser not support createEncodedStreams() API\");let n=null;try{n=e.createEncodedStreams()}catch(e){return void Qy.error(\"create audio-encoded-streams error\",e&&e.message)}const r=new TransformStream({transform(n,r){t.controller||(t.controller=r),e.track&&e.track.id!==t.track.id&&(Qy.debug(\"audio track changed: \".concat(t.track.id,\" => \").concat(e.track.id)),t.track.removeEventListener(\"ended\",i),t.track=e.track,t.track.addEventListener(\"ended\",i)),r.enqueue(n)}});n.readable.pipeThrough(r).pipeTo(n.writable)}else if(Nv()){if(\"undefined\"==typeof RTCRtpScriptTransform)return void Qy.warning(\"browser not support RTCRtpScriptTransform\");const n=qF(),r=new MessageChannel;await new Gu((e=>n.onmessage=t=>{\"registered\"===t.data&&e(void 0)}));const o=new RTCRtpScriptTransform(n,{name:\"rx\",port:r.port2},[r.port2]);e.transform=o,await new Gu((e=>n.onmessage=t=>{\"started\"===t.data&&e(void 0)})),r.port1.onmessage=n=>{var r;n.data.transformed&&e.track&&(null===(r=e.track)||void 0===r?void 0:r.id)!==t.track.id&&(Qy.debug(\"audio track changed: \".concat(t.track.id,\" => \").concat(e.track.id)),t.track.removeEventListener(\"ended\",i),t.track=e.track,t.track.addEventListener(\"ended\",i))},t.worker=n}function i(){e.track.removeEventListener(\"ended\",i),function(e){const t=JF.get(e);if(t){JF.delete(e);try{var i,n;null===(i=t.controller)||void 0===i||i.terminate(),null===(n=t.worker)||void 0===n||n.terminate()}catch(e){Qy.warning(e&&e.message)}}}(e)}JF.set(e,t),e.track.addEventListener(\"ended\",i)}(c.receiver));const d=this.remoteUserMap.get(e);d?d.set(t,a):this.remoteUserMap.set(e,new Map([[t,a]])),this.statsCollector.addRemoteStats(e.uid),this.statsUploader.startUploadInboundStats();const l=this.pendingRemoteTracks.findIndex((i=>{let{user:n,kind:r}=i;return n.uid===e.uid&&t===r}));-1!==l&&(this.pendingRemoteTracks.splice(l,1),this.emit(cw.MediaReconnectEnd,e.uid))}async massSubscribe(e){return this.massSubscribeNoLock(e)}async massSubscribeNoLock(e){if(!this.connection||this.state!==aw.Connected)throw new iI(tI.INVALID_OPERATION,\"Cannot subscribeAll remote users when peerConnection disconnected.\");e=e.filter((e=>{var t;let{user:i,mediaType:n}=e;return!(null!==(t=this.remoteUserMap.get(i))&&void 0!==t&&t.has(n))}));const t=await this.connection.batchReceive(e.map((e=>{let{user:t,mediaType:i,ssrcId:n,rtxSsrcId:r}=e;return{kind:i,ssrcMsg:[{ssrcId:n,rtx:r}],mslabel:String(t._uintid)}})));e.forEach(((e,i)=>{let{user:n,mediaType:r}=e;const{track:o,id:s,transceiver:a}=t[i];r===nw.AUDIO?(n._audioTrack?n._audioTrack._updateOriginMediaStreamTrack(o):(n._audioTrack=new BF(o,n.uid,n._uintid,this.store),Qy.info(\"[\".concat(this.store.clientId,\"] [\").concat(this.store.p2pId,\"] create remote audio track: \").concat(n._audioTrack.getTrackId()))),a&&n._audioTrack._updateRtpTransceiver(a),this.bindRemoteTrackEvents(n,n._audioTrack)):(n._videoTrack?n._videoTrack._updateOriginMediaStreamTrack(o):(n._videoTrack=new FF(o,n.uid,n._uintid,this.store),Qy.info(\"[\".concat(this.store.clientId,\"] [\").concat(this.store.p2pId,\"] create remote video track: \").concat(n._videoTrack.getTrackId()))),a&&n._videoTrack._updateRtpTransceiver(a),this.bindRemoteTrackEvents(n,n._videoTrack));const c=this.remoteUserMap.get(n);c?c.set(r,s):this.remoteUserMap.set(n,new Map([[r,s]])),this.statsCollector.addRemoteStats(n.uid),this.statsUploader.startUploadInboundStats();const d=this.pendingRemoteTracks.findIndex((e=>{let{user:t,kind:i}=e;return t.uid===n.uid&&r===i}));-1!==d&&(this.pendingRemoteTracks.splice(d,1),this.emit(cw.MediaReconnectEnd,n.uid))}))}async unsubscribe(e,t,i){const n=this.pendingRemoteTracks.filter((i=>{let{user:n,kind:r}=i;return void 0!==t?n.uid===e.uid&&t===r:n.uid===e.uid}));if(n.forEach((e=>{const t=this.pendingRemoteTracks.indexOf(e);this.pendingRemoteTracks.splice(t,1)})),this.connection&&this.state===aw.Connected||i||n.forEach((t=>{let{kind:i}=t;var n;if(i===nw.AUDIO)null===(n=e._audioTrack)||void 0===n||n._destroy(),e._audioTrack=void 0;else if(i===nw.VIDEO){var r;null===(r=e._videoTrack)||void 0===r||r._destroy(),e._videoTrack=void 0}})),!this.connection||this.state!==aw.Connected)return;const r=this.filterTobeUnSubscribedTracks(e,t);if(0===r.length)return;await this.connection.stopReceiving(r.map((e=>{let[,{id:t}]=e;return t})));const o=this.createUnsubscribeMessage(r);return this.withdrawRemoteTracks(r),0===this.remoteUserMap.size&&this.statsUploader.stopUploadInboundStats(),r.forEach((e=>{let[t,{kind:n}]=e;var r,o;n===nw.VIDEO&&t._videoSSRC&&(null===(r=this.connection)||void 0===r||r.setStatsRemoteVideoIsReady(t._videoSSRC,!1));if(n===nw.VIDEO)this.unbindRemoteTrackEvents(t._videoTrack),i||(null===(o=t._videoTrack)||void 0===o||o._destroy(),t._videoTrack=void 0);else if(n===nw.AUDIO){var s;if(this.unbindRemoteTrackEvents(t._audioTrack),!i)null===(s=t._audioTrack)||void 0===s||s._destroy(),t._audioTrack=void 0}})),o}async unsubscribeDataChannel(e,t){if(t.forEach((e=>{const t=this.pendingRemoteDataChannels.findIndex((t=>t.id===e.id));-1!==t&&this.pendingRemoteDataChannels.splice(t,1)})),!this.connection)return;const i=this.filterTobeUnSubscribedDataChannels(e,t);if(0===i.length)return;t.forEach((e=>{e._close()}));const n=this.remoteDataChannelMap.get(e);return i.forEach((e=>{n&&n.delete(e.id)})),n&&0===n.size&&(this.remoteDataChannelMap.delete(e),await this.connection.stopDataChannels(e.uid)),i.map((e=>e.id))}async massUnsubscribe(e){return this.massUnsubscribeNoLock(e)}async massUnsubscribeNoLock(e){let t=[];for(const{user:i,mediaType:n}of e){const e=this.pendingRemoteTracks.filter((e=>{let{user:t,kind:r}=e;return void 0!==n?t.uid===i.uid&&n===r:t.uid===i.uid}));e.forEach((e=>{const t=this.pendingRemoteTracks.indexOf(e);this.pendingRemoteTracks.splice(t,1)})),t=t.concat(e)}if(!this.connection||this.state!==aw.Connected)return void t.forEach((e=>{let{user:t,kind:i}=e;var n;if(i===nw.AUDIO)null===(n=t._audioTrack)||void 0===n||n._destroy(),t._audioTrack=void 0;else if(i===nw.VIDEO){var r;null===(r=t._videoTrack)||void 0===r||r._destroy(),t._videoTrack=void 0}}));const i=Jn(e).call(e,((e,t)=>{let{user:i,mediaType:n}=t;const r=this.filterTobeUnSubscribedTracks(i,n);return e.concat(r)}),[]);if(0===i.length)return;await this.connection.stopReceiving(i.map((e=>{let[,{id:t}]=e;return t})));const n=this.createUnsubscribeAllMessage(i);return this.withdrawRemoteTracks(i),0===this.remoteUserMap.size&&this.statsUploader.stopUploadInboundStats(),i.forEach((e=>{let[t,{kind:i}]=e;var n,r;i===nw.VIDEO&&t._videoSSRC&&(null===(n=this.connection)||void 0===n||n.setStatsRemoteVideoIsReady(t._videoSSRC,!1));if(i===nw.VIDEO)this.unbindRemoteTrackEvents(t._videoTrack),null===(r=t._videoTrack)||void 0===r||r._destroy(),t._videoTrack=void 0;else if(i===nw.AUDIO){var o;this.unbindRemoteTrackEvents(t._audioTrack),null===(o=t._audioTrack)||void 0===o||o._destroy(),t._audioTrack=void 0}})),n}async muteRemote(e,t){if(!this.connection)return;const i=this.remoteUserMap.get(e);if(!i)return void Qy.warning(\"[\".concat(this.store.clientId,\"] P2PChannel.muteRemote has no remote user \").concat(e.uid,\".\"));if(!i.get(t))return void Qy.warning(\"[\".concat(this.store.clientId,\"] P2PChannel.muteRemote has no remote user \").concat(e.uid,\" media type \").concat(t,\".\"));const n=t===nw.VIDEO?e._videoSSRC:e._audioSSRC;void 0!==n&&this.connection.setStatsRemoteVideoIsReady(n,!1)}async unmuteRemote(e,t){return this.unmuteRemoteNoLock(e,t)}async unmuteRemoteNoLock(e,t){if(!this.connection)return;const i=this.remoteUserMap.get(e);if(!i)return void Qy.warning(\"[\".concat(this.store.clientId,\"] P2PChannel.unmuteRemote has no remote user \").concat(e.uid,\".\"));i.get(t)||Qy.warning(\"[\".concat(this.store.clientId,\"] P2PChannel.unmuteRemote has no remote user \").concat(e.uid,\" media type \").concat(t,\".\"))}getAllTracks(e){const t=this.localTrackMap.get(sw.LocalAudioTrack);if((null==t?void 0:t.track)instanceof UV){const i=t.track;return Array.from(this.localTrackMap.entries()).filter((e=>{let[t]=e;return t!==sw.LocalAudioTrack})).filter((t=>{let[i]=t;return!(e&&i===sw.LocalVideoLowTrack)})).map((e=>{let[,{track:t}]=e;return t})).concat(i.trackList)}return Array.from(this.localTrackMap.entries()).filter((t=>{let[i]=t;return!(e&&i===sw.LocalVideoLowTrack)})).map((e=>{let[,{track:t}]=e;return t}))}getAllDataChannels(){return this.localDataChannels}reportPublishEvent(e,t,i,n,r){if(e){const i=this.localTrackMap.get(sw.LocalAudioTrack),o=n?this.localTrackMap.get(sw.LocalVideoLowTrack):this.localTrackMap.get(sw.LocalVideoTrack);oA.publish(this.store.sessionId,{eventElapse:iB.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:e,ec:t,audioName:null==i?void 0:i.track.getTrackLabel(),videoName:null==o?void 0:o.track.getTrackLabel(),screenshare:-1!==(null==o?void 0:o.track._hints.indexOf(LU.SCREEN_TRACK)),audio:!!i,video:!!o,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r})}else{var o;i||(i=[]);const s=i.find((e=>e instanceof LV)),a=n?null===(o=this.localTrackMap.get(sw.LocalVideoTrack))||void 0===o?void 0:o.track:i.find((e=>e instanceof vF));oA.publish(this.store.sessionId,{eventElapse:iB.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:e,ec:t,audioName:null==s?void 0:s.getTrackLabel(),videoName:null==a?void 0:a.getTrackLabel(),screenshare:-1!==(null==a?void 0:a._hints.indexOf(LU.SCREEN_TRACK)),audio:!!s,video:!!a,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r})}}reportSubscribeEvent(e,t,i,n){const r=n===nw.VIDEO?i._videoSSRC:i._audioSSRC;r&&oA.subscribe(this.store.sessionId,{succ:e,ec:t,video:n===nw.VIDEO,audio:n===nw.AUDIO,peerid:i.uid,subscribeRequestid:n===nw.VIDEO?i._videoSSRC:i._audioSSRC,p2pid:this.store.p2pId,eventElapse:iB.measureFromSubscribeStart(this.store.clientId,r)})}reset(){Qy.debug(\"[\".concat(this.store.clientId,\"] P2PChannel.reset\")),this.mutex=new uy(\"P2PChannel-mutex\"),this.connection&&(this.connection.close(),this.unbindConnectionEvents(this.connection),this.connection=void 0),this.shouldForwardP2PCreation&&(this.connection=this.store.useDataChannel?new pW({},this.store):this.isPlanB?new bG({},this.store):new XG({},this.store),this.bindConnectionEvents(this.connection)),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),this.statsUploader.stopUploadExtensionUsageStats(),this.unbindLocalTrackEvents(),this.unbindAllRemoteTrackEvents(),this.unbindRtpTransceiver();const e=this.localTrackMap.get(sw.LocalAudioTrack);if((null==e?void 0:e.track)instanceof UV){if(e.track.trackList.length>0){const t=e.track;e.track.trackList.forEach((e=>{t.removeAudioTrack(e)}))}e.track.close()}this.localTrackMap.clear(),this.remoteUserMap.clear(),this.statsCollector.removeRemoteStats(),this.statsCollector.removeLocalStats(),this.iceFailedCount=0,this.dtlsFailedCount=0,this.pendingLocalTracks=[],this.pendingRemoteTracks=[],this.localDataChannels=[],this.remoteDataChannelMap.clear(),this.pendingLocalDataChannels=[],this.pendingRemoteDataChannels=[],this.state=aw.Disconnected}getStats(){var e;return null===(e=this.connection)||void 0===e?void 0:e.getStats()}getRemoteVideoIsReady(e){var t;return(null===(t=this.connection)||void 0===t?void 0:t.getRemoteVideoIsReady(e))||!1}getLocalAudioVolume(){const e=this.localTrackMap.get(sw.LocalAudioTrack);if(e)return e.track.getVolumeLevel()}getLocalVideoSize(){const e=this.localTrackMap.get(sw.LocalVideoTrack);if(e)return{width:e.track.videoWidth||0,height:e.track.videoHeight||0}}getEncoderConfig(e){const t=this.localTrackMap.get(e);return t&&t.track instanceof vF||t&&t.track instanceof LV?t.track._encoderConfig:void 0}getLocalMedia(e){return this.localTrackMap.get(e)}hasLocalMedia(){return this.localTrackMap.size>0}hasRemoteMedia(e,t){if(!e)return this.remoteUserMap.size>0;const i=this.remoteUserMap.get(e);return!!i&&(!t||i.has(t))}async hasRemoteMediaWithLock(e,t){if(!e)return this.remoteUserMap.size>0;const i=this.remoteUserMap.get(e);return!!i&&(!t||i.has(t))}getRemoteMedia(e){var t;const i=Array.from(d_(t=this.remoteUserMap).call(t)).find((t=>t.uid===e));return i?{audioTrack:i.audioTrack,audioSSRC:i._audioSSRC,videoTrack:i.videoTrack,videoSSRC:i._videoSSRC}:{}}getAudioLevels(){let e=Array.from(this.remoteUserMap.entries()).map((e=>{let[t]=e;return{uid:t.uid,level:t.audioTrack?100*t.audioTrack._source.getAccurateVolumeLevel():0}}));const t=this.localTrackMap.get(sw.LocalAudioTrack);return t&&e.push({level:100*t.track._source.getAccurateVolumeLevel(),uid:this.store.uid}),e=oE(e).call(e,((e,t)=>e.level-t.level)),e}async disconnectForReconnect(){this.connection&&(Qy.debug(\"[\".concat(this.store.clientId,\"] P2PChannel.disconnectForReconnect closing P2PConnection\")),this.state=aw.Reconnecting,Dy(\"KEEP_LAST_FRAME\")&&0!==this.remoteUserMap.size&&Array.from(this.remoteUserMap.entries()).forEach((e=>{let[t]=e;var i;t._videoTrack&&t._videoTrack._player&&(null===(i=t._videoTrack._player.getVideoElement())||void 0===i||i.pause(),t._videoTrack._player.isKeepLastFrame=!0,t._videoTrack._originMediaStreamTrack.stop())})),this.connection.close(),this.unbindConnectionEvents(this.connection),this.connection=void 0,this.shouldForwardP2PCreation&&(this.connection=this.store.useDataChannel?new pW({},this.store):this.isPlanB?new bG({},this.store):new XG({},this.store),this.bindConnectionEvents(this.connection)),0!==this.localTrackMap.size&&(Array.from(this.localTrackMap.entries()).forEach((e=>{var t;let[i,{track:n}]=e;switch(i){case sw.LocalVideoTrack:Dn(t=n._hints).call(t,LU.LOW_STREAM)?n.close():this.pendingLocalTracks.push(n);break;case sw.LocalAudioTrack:n instanceof UV?this.pendingLocalTracks=this.pendingLocalTracks.concat(n.trackList):this.pendingLocalTracks.push(n);case sw.LocalVideoLowTrack:}})),this.emit(cw.MediaReconnectStart,this.store.uid)),this.unbindLocalTrackEvents(),this.localTrackMap.clear(),0!==this.remoteUserMap.size&&Array.from(this.remoteUserMap.entries()).forEach((e=>{let[t,i]=e;Array.from(d_(i).call(i)).forEach((e=>{this.setPendingRemoteMedia(t,e)})),this.emit(cw.MediaReconnectStart,t.uid)})),this.unbindAllRemoteTrackEvents(),this.remoteUserMap.clear(),0!==this.localDataChannels.length&&(this.localDataChannels.forEach((e=>{this.pendingLocalDataChannels.push(e)})),this.localDataChannels.length=0),0!==this.remoteDataChannelMap.size&&(Array.from(this.remoteDataChannelMap.entries()).forEach((e=>{let[t,i]=e;Array.from(d_(i).call(i)).forEach((e=>{this.setPendingRemoteDataChannel(t,e)}))})),this.remoteDataChannelMap.clear()),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),Qy.debug(\"[\".concat(this.store.clientId,\"] P2PChannel disconnected, waiting to reconnect.\")))}hasPendingRemoteDataChannel(e,t){for(const i of this.pendingRemoteDataChannels){const{user:n,id:r}=i;if((e instanceof Bj?e.uid:e)===n.uid&&r===t)return!0}return!1}setPendingRemoteDataChannel(e,t){this.hasPendingRemoteDataChannel(e,t)||this.pendingRemoteDataChannels.push({user:e,id:t})}hasPendingRemoteMedia(e,t){for(const i of this.pendingRemoteTracks){const{user:n,kind:r}=i;if((e instanceof Bj?e.uid:e)===n.uid&&t===r)return!0}return!1}setPendingRemoteMedia(e,t){this.hasPendingRemoteMedia(e,t)||this.pendingRemoteTracks.push({user:e,kind:t})}restartICE(e){var t=this;return pB((function*(){if(!t.connection||t.state!==aw.Connected||t.connection instanceof pW)return;const i=yield rB(t.mutex.lock(\"From P2PChannel.restartICE\"));let n;try{n=yield rB(t.connection.restartICE(e));const r=yield rB(n.next());if(r.done)return;const o=r.value,s=yield o;switch(t.reportPCDisconnectedOrFailed(e),e){case rw.TCP:t._pcStatsUploadType=ow.TCP_RESTART;break;case rw.RELAY:t._pcStatsUploadType=ow.RELAY_RESTART;break;default:t._pcStatsUploadType=ow.OLD_RESTART}t._isInRestartIce=!0,n.next(s)}catch(e){var r;null===(r=n)||void 0===r||r.throw(e)}finally{i()}}))()}getUplinkNetworkQuality(){if(!this.connection)return 0;const e=this.connection.getStats(),t=this.localTrackMap.get(sw.LocalVideoTrack),i=this.localTrackMap.get(sw.LocalAudioTrack),n=e.videoSend.find((e=>e.ssrc===(null==t?void 0:t.ssrcs[0].ssrcId))),r=e.audioSend.find((e=>e.ssrc===(null==i?void 0:i.ssrcs[0].ssrcId)));if(!n||!r)return 1;const o=UI(this,cw.NeedSignalRTT),s=n?n.rttMs:void 0,a=r?r.rttMs:void 0,c=s&&a?(s+a)/2:s||a,d=(c&&o?(c+o)/2:c||o)||0,l=100*e.sendPacketLossRate*.7/50+.3*d/1500,h=l<.17?1:l<.36?2:l<.59?3:l<.1?4:5,u=null==t?void 0:t.track;if(u&&u._encoderConfig&&-1===u._hints.indexOf(LU.SCREEN_TRACK)){const t=u._encoderConfig.bitrateMax,i=e.bitrate.actualEncoded;if(t&&i){const e=(1e3*t-i)/(1e3*t);return cA[e<.15?0:e<.3?1:e<.45?2:e<.6?3:4][h]}}return h}getDownlinkNetworkQuality(){if(!this.connection)return 0;const e=this.connection.getStats();let t=0;return Array.from(this.remoteUserMap.entries()).forEach((i=>{let[n]=i;const r=n._audioSSRC,o=n._videoSSRC,s=e.audioRecv.find((e=>e.ssrc===r)),a=e.videoRecv.find((e=>e.ssrc===o));if(!s&&!a)return void(t+=1);const c=UI(this,cw.NeedSignalRTT),d=e.rtt,l=(d&&c?(d+c)/2:d||c)||0,h=s?s.jitterMs:void 0,u=e.recvPacketLossRate;let p=.7*u*100/50+.3*l/1500;h&&(p=.6*u*100/50+.2*l/1500+.2*h/400);t+=p<.1?1:p<.17?2:p<.36?3:p<.59?4:5})),this.remoteUserMap.size>0?Math.round(t/this.remoteUserMap.size):t}async muteLocalTrack(e){return new Gu(((t,i)=>{this.handleMuteLocalTrack(e,t,i)}))}async replaceTrack(e,t){var i;if(Qy.debug(\"[\".concat(this.store.clientId,\"] P2PChannel replaceTrack from [\").concat(e.getTrackId(),\"] to [\").concat(t.getTrackId(),\"]\")),!this.connection||this.state!==aw.Connected)return;const n=Array.from(this.localTrackMap.entries()).find((t=>{let[,{track:i}]=t;return e===i}));if(!n)return;const r=n[0];if(e!==t&&(this.unbindLocalTrackEvents([{track:e,type:r}]),this.bindLocalTrackEvents([{track:t,type:r}]),n[1].track=t),await(null===(i=this.connection)||void 0===i?void 0:i.replaceTrack(t,n[1].id)),this.isPlanB){const e=n[1];e.id=t._mediaStreamTrack.id,this.localTrackMap.set(r,e)}if(r===sw.LocalVideoTrack&&!Dy(\"DISABLE_DUAL_STREAM_USE_ENCODING\")&&_U().supportDualStreamEncoding){const t=this.localTrackMap.get(sw.LocalVideoLowTrack);if(t){const i=e._mediaStreamTrack.clone();t.track._originMediaStreamTrack.stop(),t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i,await new Gu(((e,i)=>{this.handleReplaceTrack(t.track,e,i,!0)}))}}}filterTobePublishedTracks(e,t,i){const n=[],r=this.getAllTracks();e=BI(e=e.filter((e=>-1===r.indexOf(e))));let o,s=!1;const a=this.localTrackMap.get(sw.LocalAudioTrack);for(const r of e){if(r instanceof vF&&(this.localTrackMap.has(sw.LocalVideoTrack)||s?new iI(tI.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS).throw():(n.push({track:r,type:sw.LocalVideoTrack}),s=!0),t)){const e=this.getLowVideoTrack(r,i);n.push({track:e,type:sw.LocalVideoLowTrack})}if(r instanceof LV)if(a){const e=a.track;if(e instanceof UV)Wj([r]),e.addAudioTrack(r),this.bindLocalAudioTrackEvents(r,!0);else{const t=Hj([e,r]);Qy.debug(\"[\".concat(this.store.clientId,\"] [p2pId: \").concat(this.store.p2pId,\"]: P2PConnection will replace audioTrack [\").concat(t.getTrackId(),\"]\")),this.replaceTrack(e,t)}}else if(o instanceof UV)Wj([r]),o.addAudioTrack(r);else if(o||!r._useAudioElement&&_U().webAudioMediaStreamDest&&!r._bypassWebAudio){o=Hj(o?[r,o]:[r])}else o=r}return o&&(Qy.debug(\"[\".concat(this.store.clientId,\"] [p2pId: \").concat(this.store.p2pId,\"]: P2PConnection will send audioTrack [\").concat(o.getTrackId(),\"]\")),n.push({track:o,type:sw.LocalAudioTrack})),n}filterTobeUnpublishedTracks(e){const t=[],i=this.getAllTracks();e=BI(e=e.filter((e=>-1!==i.indexOf(e))));for(const i of e){if(i instanceof LV){const e=this.localTrackMap.get(sw.LocalAudioTrack);if(!e)continue;e.track instanceof UV?(e.track.removeAudioTrack(i),this.unbindLocalAudioTrackEvents(i),0===e.track.trackList.length&&(t.push([sw.LocalAudioTrack,e]),e.track.close())):t.push([sw.LocalAudioTrack,e])}if(i instanceof vF){const e=this.localTrackMap.get(sw.LocalVideoTrack);if(!e)continue;t.push([sw.LocalVideoTrack,e]);const i=this.localTrackMap.get(sw.LocalVideoLowTrack);i&&t.push([sw.LocalVideoLowTrack,i])}}return t}filterTobePublishedDataChannels(e){return e=(e=BI(e)).filter((e=>-1===this.localDataChannels.findIndex((t=>t.id===e.id))))}filterTobeUnpublishedDataChannels(e){return e=(e=(e=BI(e)).filter((e=>-1!==this.localDataChannels.indexOf(e)))).filter((e=>e._originDataChannel))}bindLocalTrackEvents(e){e.forEach((e=>{let{track:t,type:i}=e;switch(i){case sw.LocalVideoTrack:t.addListener(PU.GET_STATS,this.handleGetLocalVideoStats),t.addListener(PU.GET_RTC_STATS,this.handleGetRTCStats),t.addListener(PU.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.addListener(PU.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.addListener(PU.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.addListener(PU.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this.handleUpdateVideoSendParameters),t.addListener(PU.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.addListener(PU.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.addListener(PU.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case sw.LocalAudioTrack:this.bindLocalAudioTrackEvents(t);case sw.LocalVideoLowTrack:}}))}bindLocalAudioTrackEvents(e,t){e instanceof UV?e.trackList.forEach((e=>{e.addListener(PU.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(PU.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(PU.GET_STATS,this.handleGetLocalAudioStats),e.addListener(PU.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(PU.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)})):(e.addListener(PU.GET_STATS,this.handleGetLocalAudioStats),e.addListener(PU.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(PU.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(PU.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(PU.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack),t||(e.addListener(PU.NEED_REPLACE_TRACK,this.handleReplaceTrack),e.addListener(PU.NEED_REPLACE_MIXING_TRACK,this.handleReplaceMixingTrack)))}unbindLocalTrackEvents(e){e||(e=Array.from(this.localTrackMap.entries()).map((e=>{let[t,{track:i}]=e;return{track:i,type:t}}))),e.forEach((e=>{let{track:t,type:i}=e;switch(i){case sw.LocalVideoTrack:t.off(PU.GET_STATS,this.handleGetLocalVideoStats),t.off(PU.GET_RTC_STATS,this.handleGetRTCStats),t.off(PU.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.off(PU.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.off(PU.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.off(PU.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this.handleUpdateVideoSendParameters),t.off(PU.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.off(PU.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.off(PU.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case sw.LocalAudioTrack:this.unbindLocalAudioTrackEvents(t);case sw.LocalVideoLowTrack:}}))}unbindLocalAudioTrackEvents(e){e instanceof UV?e.trackList.forEach((e=>{e.off(PU.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(PU.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(PU.GET_STATS,this.handleGetLocalAudioStats),e.off(PU.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(PU.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)})):(e.off(PU.GET_STATS,this.handleGetLocalAudioStats),e.off(PU.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(PU.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(PU.NEED_REPLACE_TRACK,this.handleReplaceTrack),e.off(PU.NEED_REPLACE_MIXING_TRACK,this.handleReplaceMixingTrack),e.off(PU.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(PU.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack))}bindRemoteTrackEvents(e,t){t instanceof FF&&t.addListener(PU.GET_STATS,(t=>{t(this.handleGetRemoteVideoStats(e))})),t instanceof BF&&t.addListener(PU.GET_STATS,(t=>{t(this.handleGetRemoteAudioStats(e))}))}unbindRemoteTrackEvents(e){e&&e.removeAllListeners(PU.GET_STATS)}unbindAllRemoteTrackEvents(){Array.from(this.remoteUserMap.entries()).forEach((e=>{let[t,i]=e;i.has(nw.AUDIO)&&this.unbindRemoteTrackEvents(t._audioTrack),i.has(nw.VIDEO)&&this.unbindRemoteTrackEvents(t._videoTrack)}))}createGatewayPublishMessage(e,t){return e.map(((e,i)=>{var n;let r,o,{track:s,type:a}=e;switch(a){case sw.LocalAudioTrack:r=Kb.Audio,o={dtx:s instanceof kV&&s._config.DTX,hq:!1,lq:!1,stereo:!1,speech:!1};break;case sw.LocalVideoTrack:r=Dn(n=s._hints).call(n,LU.SCREEN_TRACK)?Kb.Screen:Kb.High,o=fW(fW({},qw(s)),{},{codec:this.store.codec});break;case sw.LocalVideoLowTrack:r=Kb.Low,o=fW(fW({},qw(s)),{},{codec:this.store.codec})}return{stream_type:r,attributes:o,ssrcs:t[i]}}))}createGatewayUnpublishMessage(e){return e.map((e=>{var t;let i,[n,{track:r,ssrcs:o,id:s}]=e;switch(n){case sw.LocalVideoTrack:i=Dn(t=r._hints).call(t,LU.SCREEN_TRACK)?Kb.Screen:Kb.High;break;case sw.LocalAudioTrack:i=Kb.Audio;break;case sw.LocalVideoLowTrack:i=Kb.Low}return{stream_type:i,ssrcs:o,mid:s}}))}assignLocalTracks(e,t){e.forEach(((e,i)=>{let{track:n,type:r}=e;this.localTrackMap.set(r,{track:n,id:t[i].id,ssrcs:t[i].localSSRC})}))}withdrawLocalTracks(e){e.forEach((e=>{let[t]=e;this.localTrackMap.delete(t)}))}bindConnectionEvents(e){e.onConnectionStateChange=async t=>{if(Qy.info(\"[\".concat(this.store.clientId,\"] [p2pId: \").concat(this.store.p2pId,\"]: P2PConnection.onConnectionStateChange(\").concat(t,\")\")),this.emit(cw.PeerConnectionStateChange,t),\"connected\"!==t||this.store.keyMetrics.peerConnectionEnd||this.store.peerConnectionEnd(),\"connected\"===t&&(this._restartTimer&&(clearTimeout(this._restartTimer),this._restartTimer=void 0),(this._isFirstConnected||this._isInRestartIce)&&this.reportPCStats(Date.now(),!0,this._pcStatsUploadType),this._isInRestartIce=!1,this._isFirstConnected=!1,this._isStartRestartIce=!1),Dy(\"NEW_ICE_RESTART\")){var i;if(Dn(i=this._restartStates).call(i,t)){if(this._isStartRestartIce)return;this._isStartRestartIce=!0;const t=t=>{if(\"disconnected\"===e.iceConnectionState||\"checking\"===e.iceConnectionState||\"failed\"===e.iceConnectionState){Qy.debug(\"[\".concat(this.store.clientId,\"] [P2PChannel] start use restartICE, type is \").concat(t));\"CONNECTED\"===UI(this,cw.QueryClientConnectionState)&&this.emit(cw.RequestRestartICE,t)}},i=()=>{\"disconnected\"!==e.iceConnectionState&&\"checking\"!==e.iceConnectionState&&\"failed\"!==e.iceConnectionState||(this.reportPCStats(Date.now(),!1,this._pcStatsUploadType),Qy.debug(\"[\".concat(this.store.clientId,\"] P2PConnection disconnected timeout, force reconnect\")),setTimeout((()=>this.emit(cw.P2PLost)),0),this.iceFailedCount+=1,this.requestReconnect())},n=Dy(\"ICE_RESTART_INTERVAL\");return void(this._restartTimer=window.setTimeout((()=>{if(Dy(\"JOIN_WITH_FALLBACK_MEDIA_PROXY_FORCE\")&&_U().supportPCSetConfiguration)t(rw.RELAY),this._restartTimer=window.setTimeout(i,n);else if(Pv())t(rw.UDP),this._restartTimer=window.setTimeout(i,4e3);else{if(t(rw.TCP),_U().supportPCSetConfiguration)return void(this._restartTimer=window.setTimeout((()=>{t(rw.RELAY),this._restartTimer=window.setTimeout(i,n)}),n));this._restartTimer=window.setTimeout(i,n)}}),800))}}else{if(\"disconnected\"===t&&\"disconnected\"===e.iceConnectionState)return setTimeout((()=>{if(\"disconnected\"===e.iceConnectionState&&Dy(\"ICE_RESTART\")){\"CONNECTED\"===UI(this,cw.QueryClientConnectionState)&&this.emit(cw.RequestRestartICE)}}),800),void setTimeout((()=>{\"disconnected\"===e.peerConnectionState&&(Qy.debug(\"[\".concat(this.store.clientId,\"] [p2pId: \").concat(this.store.p2pId,\"]: P2PConnection disconnected timeout 4000ms, force reconnect\")),this.reportPCStats(Date.now(),!1,this._pcStatsUploadType),this._isInRestartIce=!1,setTimeout((()=>this.emit(cw.P2PLost)),0),this.iceFailedCount+=1,this.requestReconnect())}),4e3);\"failed\"===t&&(Qy.debug(\"[\".concat(this.store.clientId,\"] [p2pId: \").concat(this.store.p2pId,\"]: P2PConnection state failed, force reconnect\")),this.reportPCDisconnectedOrFailed(),setTimeout((()=>this.emit(cw.P2PLost)),0),this.iceFailedCount+=1,await this.requestReconnect())}},e.onICEConnectionStateChange=e=>{\"connected\"!==e||this.store.keyMetrics.iceConnectionEnd||this.store.iceConnectionEnd(),Qy.info(\"[\".concat(this.store.clientId,\"] [p2pId: \").concat(this.store.p2pId,\"]: P2PConnection.onICEConnectionStateChange(\").concat(e,\")\")),oA.reportApiInvoke(this.store.sessionId,{name:\"ICEConnectionStateChange\",options:e,tag:vI.TRACER}).onSuccess(),this.emit(cw.IceConnectionStateChange,e)},e.onICETransportStateChange=e=>{Qy.info(\"[\".concat(this.store.clientId,\"] [p2pId: \").concat(this.store.p2pId,\"]: P2PConnection.onICETransportStateChange(\").concat(e,\")\"))},e.onDTLSTransportStateChange=e=>{Qy.info(\"[\".concat(this.store.clientId,\"] [p2pId: \").concat(this.store.p2pId,\"]: P2PConnection.onDTLSTransportStateChange(\").concat(e,\")\"))},e.onDTLSTransportError=e=>{Qy.info(\"[\".concat(this.store.clientId,\"] [p2pId: \").concat(this.store.p2pId,\"]: P2PConnection.onDTLSTransportError(\").concat(e,\")\"))},e.onFirstAudioDecoded=e=>{var t;const i=Array.from(d_(t=this.remoteUserMap).call(t)).find((t=>t._audioSSRC===e));var n;i&&(this.store.subscribe(i.uid,\"audio\",void 0,void 0,void 0,Date.now()),null===(n=i.audioTrack)||void 0===n||n.emit(FU.FIRST_FRAME_DECODED),oA.firstRemoteFrame(this.store.sessionId,tA.FIRST_AUDIO_DECODE,iA.FIRST_AUDIO_DECODE,{peer:i._uintid,subscribeElapse:iB.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId}))},e.onFirstAudioReceived=e=>{var t;const i=Array.from(d_(t=this.remoteUserMap).call(t)).find((t=>t._audioSSRC===e));i&&oA.firstRemoteFrame(this.store.sessionId,tA.FIRST_AUDIO_RECEIVED,iA.FIRST_AUDIO_RECEIVED,{peer:i._uintid,subscribeElapse:iB.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId})},e.onFirstVideoDecoded=(e,t,i)=>{this.reportVideoFirstFrameDecoded(e,t,i)},e.onFirstVideoReceived=e=>{var t;const i=Array.from(d_(t=this.remoteUserMap).call(t)).find((t=>t._videoSSRC===e));i&&oA.firstRemoteFrame(this.store.sessionId,tA.FIRST_VIDEO_RECEIVED,iA.FIRST_VIDEO_RECEIVED,{peer:i._uintid,subscribeElapse:iB.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId})},e.onSelectedLocalCandidateChanged=(e,t)=>{const i=\"relay\"===e.candidateType,n=\"relay\"===t.candidateType;\"unknown\"!==t.candidateType&&i===n||this.emit(cw.ConnectionTypeChange,i),Qy.info(\"[\".concat(this.store.clientId,\"] [p2pId: \").concat(this.store.p2pId,\"]: P2PConnection.SelectedLocalCandidateChanged(\").concat(JSON.stringify(Zw(t)),\" -> \").concat(JSON.stringify(Zw(e)),\")\"))},e.onSelectedRemoteCandidateChanged=(e,t)=>{Qy.info(\"[\".concat(this.store.clientId,\"] [p2pId: \").concat(this.store.p2pId,\"]: P2PConnection.SelectedRemoteCandidateChanged(\").concat(JSON.stringify(Zw(t)),\" -> \").concat(JSON.stringify(Zw(e)),\")\"))},e.onFirstVideoDecodedTimeout=e=>{this.reportVideoFirstFrameDecoded(e,void 0,void 0,!0)},e.getLocalVideoStats=()=>{const e=this.statsCollector.getLocalVideoTrackStats(),t=this.statsCollector.getRTCStats();return fW(fW({},e),t)}}unbindConnectionEvents(e){e.onConnectionStateChange=void 0,e.onICEConnectionStateChange=void 0,e.onICETransportStateChange=void 0,e.onDTLSTransportStateChange=void 0,e.onDTLSTransportError=void 0,e.onFirstAudioDecoded=void 0,e.onFirstAudioReceived=void 0,e.onFirstVideoDecoded=void 0,e.onFirstVideoReceived=void 0,e.onSelectedLocalCandidateChanged=void 0,e.onSelectedRemoteCandidateChanged=void 0,e.onFirstVideoDecodedTimeout=void 0,e.getLocalVideoStats=void 0}filterTobeMutedTracks(e){const t=[];if(-1===this.getAllTracks().indexOf(e))return t;const i=this.localTrackMap.get(sw.LocalAudioTrack);if(e instanceof LV&&(null==i?void 0:i.track)instanceof UV)return i.track.isActive||t.push([sw.LocalAudioTrack,i]),t;const n=Array.from(this.localTrackMap.entries()).find((t=>{let[,{track:i}]=t;return e===i}));if(n&&(t.push(n),n[0]===sw.LocalVideoTrack)){const e=this.localTrackMap.get(sw.LocalVideoLowTrack);e&&t.push([sw.LocalVideoLowTrack,e])}return t}filterTobeUnmutedTracks(e){const t=[],i=this.localTrackMap.get(sw.LocalAudioTrack);if(e instanceof LV&&(null==i?void 0:i.track)instanceof UV)return i.track.isActive&&t.push([sw.LocalAudioTrack,i]),t;const n=Array.from(this.localTrackMap.entries()).find((t=>{let[,{track:i}]=t;return e===i}));if(n)if(n[0]===sw.LocalVideoTrack){t.push(n);const e=this.localTrackMap.get(sw.LocalVideoLowTrack);e&&t.push([sw.LocalVideoLowTrack,e])}else t.push(n);return t}createMuteMessage(e){return e.map((e=>{var t;let i,[n,{track:r,ssrcs:o,id:s}]=e;switch(n){case sw.LocalAudioTrack:i=Kb.Audio;break;case sw.LocalVideoTrack:i=Dn(t=r._hints).call(t,LU.SCREEN_TRACK)?Kb.Screen:Kb.High;break;case sw.LocalVideoLowTrack:i=Kb.Low}return{stream_type:i,ssrcs:o,mid:s}}))}createUnmuteMessage(e){return e.map((e=>{var t;let i,[n,{track:r,ssrcs:o,id:s}]=e;switch(n){case sw.LocalAudioTrack:i=Kb.Audio;break;case sw.LocalVideoTrack:i=Dn(t=r._hints).call(t,LU.SCREEN_TRACK)?Kb.Screen:Kb.High;break;case sw.LocalVideoLowTrack:i=Kb.Low}return{stream_type:i,ssrcs:o,mid:s}}))}filterTobeUnSubscribedTracks(e,t){const i=[],n=this.remoteUserMap.get(e);if(!n)return i;if(t){const r=n.get(t);if(!r)return i;i.push([e,{kind:t,id:r}])}else Array.from(n.entries()).forEach((t=>{let[n,r]=t;i.push([e,{kind:n,id:r}])}));return i}filterTobeUnSubscribedDataChannels(e,t){const i=[];return t.forEach((t=>{var n;null!==(n=this.remoteDataChannelMap.get(e))&&void 0!==n&&n.has(t.id)&&i.push(t)})),i}createUnsubscribeMessage(e){const t=[];return e.forEach((e=>{let[i,{kind:n,id:r}]=e;switch(n){case nw.VIDEO:return void(i._videoSSRC&&t.push({stream_type:nw.VIDEO,ssrcId:i._videoSSRC}));case nw.AUDIO:return void(i._audioSSRC&&t.push({stream_type:nw.AUDIO,ssrcId:i._audioSSRC}))}})),t}createUnsubscribeAllMessage(e){const t=new Map;return e.forEach((e=>{let[i,{kind:n}]=e;if(t.has(i)){let e=t.get(i);n===nw.VIDEO?e|=zb.Video:e|=zb.Audio,t.set(i,e)}else n===nw.VIDEO?t.set(i,zb.Video):t.set(i,zb.Audio)})),{users:Array.from(t.entries()).map((e=>{let[t,i]=e;return{stream_id:t.uid,stream_type:i}}))}}withdrawRemoteTracks(e){e.forEach((e=>{let[t,{kind:i}]=e;const n=this.remoteUserMap.get(t);n&&(n.delete(i),0===Array.from(n.entries()).length&&this.remoteUserMap.delete(t))}))}async updateBitrateLimit(e){const t=this.localTrackMap.get(sw.LocalVideoTrack),i=this.localTrackMap.get(sw.LocalVideoLowTrack);t&&await t.track.setBitrateLimit(e.uplink),i&&e.low_stream_uplink&&await i.track.setBitrateLimit({max_bitrate:e.low_stream_uplink.bitrate,min_bitrate:e.low_stream_uplink.bitrate||0})}isP2PDisconnected(){if(this.connection){return\"connected\"!==this.connection.peerConnectionState}return!0}mapPubResToRemoteConfig(e,t){return e.map(((e,i)=>{var n;let{stream_type:r}=e;return null===(n=t.find((e=>{let{stream_type:t}=e;return r===t})))||void 0===n?void 0:n.attributes}))}async tryToUnmuteAudio(e){for(let i=0;i{let[,{id:t}]=e;return t}))));const r=this.createUnmuteMessage(n);return void await MI(this,cw.RequestUnmuteLocal,r)}}bindStatsUploaderEvents(){this.statsUploader.requestStats=()=>this.getStats(),this.statsUploader.requestLocalMedia=()=>Array.from(this.localTrackMap.entries()),this.statsUploader.requestRemoteMedia=()=>Array.from(this.remoteUserMap.entries()),this.statsUploader.requestVideoIsReady=e=>{var t;return!(null===(t=this.connection)||void 0===t||!t.getRemoteVideoIsReady(e))},this.statsUploader.requestUpload=(e,t)=>this.emit(cw.RequestUpload,e,t),this.statsUploader.requestUploadStats=e=>this.emit(cw.RequestUploadStats,e),this.statsUploader.requestAllTracks=()=>this.getAllTracks()}unbindStatsUploaderEvents(){this.statsUploader.requestStats=void 0,this.statsUploader.requestLocalMedia=void 0,this.statsUploader.requestRemoteMedia=void 0,this.statsUploader.requestVideoIsReady=void 0}async requestReconnect(){this.dtlsFailedCount+=1,await $I(Ey(this.dtlsFailedCount,_y)),this.emit(cw.RequestReconnect)}async reconnectP2P(){const e=Array.from(this.localTrackMap.entries()),t=this.createGatewayUnpublishMessage(e);Array.from(this.remoteUserMap.entries()),t.length>0&&await kI(this,cw.RequestUnpublishForReconnectPC,t),this.disconnectForReconnect(),this.emit(cw.RequestReconnectPC)}canPublishLowStream(){return this.localTrackMap.has(sw.LocalVideoTrack)||this.pendingLocalTracks.some((e=>e instanceof vF))}throwIfTrackTypeNotMatch(e){if(e.filter((e=>e instanceof vF)).length>1)throw new iI(tI.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(e.filter((e=>e instanceof LV)).length>1&&(e.some((e=>e instanceof LV&&e._bypassWebAudio))||!_U().webAudioMediaStreamDest))throw new iI(tI.NOT_SUPPORTED,\"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode\");for(const t of e){if(t instanceof vF&&this.pendingLocalTracks.some((e=>e instanceof vF)))throw new iI(tI.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(t instanceof LV&&this.pendingLocalTracks.some((e=>e instanceof LV))&&(!_U().webAudioMediaStreamDest||t._bypassWebAudio||this.pendingLocalTracks.some((e=>e instanceof LV&&e._bypassWebAudio))))throw new iI(tI.NOT_SUPPORTED,\"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode\")}}getLowVideoTrack(e,t){const i=!Dy(\"DISABLE_DUAL_STREAM_USE_ENCODING\")&&_U().supportDualStreamEncoding,n=fW(fW({},{width:160,height:120,framerate:15,bitrate:50}),t);let r;r=i?e._mediaStreamTrack.clone():vj(e,n);const o=ey(8,\"track-low-\"),s=new vF(r,fW(fW({},i&&{scaleResolutionDownBy:Qw(n,e)}),{},{frameRate:n.framerate,bitrateMax:n.bitrate,bitrateMin:n.bitrate}),void 0,void 0,o);return s.on(xU.TRANSCEIVER_UPDATED,(t=>{e._updateRtpTransceiver(t,kU.LOW_STREAM)})),s._hints.push(LU.LOW_STREAM),e.on(\"sei-to-send\",(e=>{s.emit(\"sei-to-send\",e)})),e.addListener(PU.NEED_CLOSE,(()=>{s.close()})),s}async globalLock(){return this.mutex.lock(\"From P2PChannel.globalLock\")}async reportPCStats(e,t,i){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null;if(this.connection&&this.connection instanceof XG){var r,o,s,a;const c=this.store.keyMetrics.descriptionStart||0,{iceConnectionState:d,dtlsTransportState:l,peerConnectionState:h}=this.connection,{local:u,remote:p}=await this.connection.getSelectedCandidatePair();oA.pcStats(this.store.sessionId,{startTime:c,eventElapse:e-c||0,iceconnectionsate:d,dtlsstate:l,connectionstate:h,intSucc:t?1:2,error:n,selectedLocalCandidateProtocol:null!==(r=null==u?void 0:u.protocol)&&void 0!==r?r:\"\",selectedLocalCandidateType:null!==(o=u.candidateType)&&void 0!==o?o:\"\",selectedLocalCandidateAddress:\"\".concat(u.address,\":\").concat(u.port),selectedRemoteCandidateProtocol:null!==(s=p.protocol)&&void 0!==s?s:\"\",selectedRemoteCandidateType:null!==(a=p.candidateType)&&void 0!==a?a:\"\",selectedRemoteCandidateAddress:\"\".concat(p.address,\":\").concat(p.port),restartCnt:i})}}reportVideoFirstFrameDecoded(e,t,i,n){var r;const o=Array.from(d_(r=this.remoteUserMap).call(r)).find((t=>t._videoSSRC===e));if(o){n||this.store.subscribe(o.uid,\"video\",void 0,void 0,void 0,void 0,Date.now());const r=this.store.keyMetrics,s=r.subscribe.find((e=>e.userId===o.uid&&\"video\"===e.type));oA.firstRemoteVideoDecode(this.store.sessionId,tA.FIRST_VIDEO_DECODE,iA.FIRST_VIDEO_DECODE,{peer:o._uintid,videowidth:t,videoheight:i,subscribeElapse:iB.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId,apEnd:r.requestAPEnd||0,apStart:r.requestAPStart||0,joinGwEnd:r.joinGatewayEnd||0,joinGwStart:r.joinGatewayStart||0,pcEnd:r.peerConnectionEnd||0,pcStart:r.peerConnectionStart||0,subscriberEnd:(null==s?void 0:s.subscribeEnd)||0,subscriberStart:(null==s?void 0:s.subscribeStart)||0,videoAddNotify:(null==s?void 0:s.streamAdded)||0,state:n?1:0})}}async remoteMediaSsrcChanged(e,t,i){if(!this.connection)return!1;const n=this.remoteUserMap.get(e);if(!n)return!1;const r=n.get(t);if(!r)return!1;const o=await this.connection.getRemoteSSRC(r);return void 0!==o&&o!==i}resetConnection(e){Qy.debug(\"[\".concat(this.store.clientId,\"] [P2PChannel] reset connection to \").concat(e)),this.state===aw.Connected?(Qy.debug(\"[\".concat(this.store.clientId,\"] [P2PChannel] fallback to websocket but P2PChannel state still connected, disconnect first\")),this.disconnectForReconnect()):(this.connection&&(this.connection.close(),this.unbindConnectionEvents(this.connection),this.connection=void 0),this.shouldForwardP2PCreation&&(this.connection=e===Jb.datachannel?new pW({},this.store):this.isPlanB?new bG({},this.store):new XG({},this.store),this.bindConnectionEvents(this.connection)))}unbindRtpTransceiver(){0!==this.localTrackMap.size&&Array.from(this.localTrackMap.entries()).forEach((e=>{let[t,{track:i}]=e;t===sw.LocalVideoLowTrack?i._updateRtpTransceiver(void 0,kU.LOW_STREAM):i._updateRtpTransceiver(void 0)}))}reportPCDisconnectedOrFailed(e){this.connection&&this.connection instanceof XG&&(\"disconnected\"!==this.connection.iceConnectionState&&\"checking\"!==this.connection.iceConnectionState&&\"failed\"!==this.connection.iceConnectionState||(this._isFirstConnected?(this.reportPCStats(Date.now(),!1,this._pcStatsUploadType),this._isFirstConnected=!1):this._pcStatsUploadType===ow.TCP_RESTART&&e===rw.RELAY?this.reportPCStats(Date.now(),!1,this._pcStatsUploadType):this.reportPCStats(Date.now(),!1,ow.DISCONNECTED_OR_FAILED)))}},nb(EW.prototype,\"startP2PConnection\",[RW],Object.getOwnPropertyDescriptor(EW.prototype,\"startP2PConnection\"),EW.prototype),nb(EW.prototype,\"connect\",[RW],Object.getOwnPropertyDescriptor(EW.prototype,\"connect\"),EW.prototype),nb(EW.prototype,\"updateRemoteRTPCapabilities\",[RW],Object.getOwnPropertyDescriptor(EW.prototype,\"updateRemoteRTPCapabilities\"),EW.prototype),nb(EW.prototype,\"preConnect\",[RW],Object.getOwnPropertyDescriptor(EW.prototype,\"preConnect\"),EW.prototype),nb(EW.prototype,\"publishDataChannel\",[RW],Object.getOwnPropertyDescriptor(EW.prototype,\"publishDataChannel\"),EW.prototype),nb(EW.prototype,\"unpublish\",[RW],Object.getOwnPropertyDescriptor(EW.prototype,\"unpublish\"),EW.prototype),nb(EW.prototype,\"unpublishDataChannel\",[RW],Object.getOwnPropertyDescriptor(EW.prototype,\"unpublishDataChannel\"),EW.prototype),nb(EW.prototype,\"unpublishLowStream\",[RW],Object.getOwnPropertyDescriptor(EW.prototype,\"unpublishLowStream\"),EW.prototype),nb(EW.prototype,\"subscribeDataChannel\",[RW],Object.getOwnPropertyDescriptor(EW.prototype,\"subscribeDataChannel\"),EW.prototype),nb(EW.prototype,\"subscribe\",[RW],Object.getOwnPropertyDescriptor(EW.prototype,\"subscribe\"),EW.prototype),nb(EW.prototype,\"massSubscribe\",[RW],Object.getOwnPropertyDescriptor(EW.prototype,\"massSubscribe\"),EW.prototype),nb(EW.prototype,\"unsubscribe\",[RW],Object.getOwnPropertyDescriptor(EW.prototype,\"unsubscribe\"),EW.prototype),nb(EW.prototype,\"unsubscribeDataChannel\",[RW],Object.getOwnPropertyDescriptor(EW.prototype,\"unsubscribeDataChannel\"),EW.prototype),nb(EW.prototype,\"massUnsubscribe\",[RW],Object.getOwnPropertyDescriptor(EW.prototype,\"massUnsubscribe\"),EW.prototype),nb(EW.prototype,\"muteRemote\",[RW],Object.getOwnPropertyDescriptor(EW.prototype,\"muteRemote\"),EW.prototype),nb(EW.prototype,\"unmuteRemote\",[RW],Object.getOwnPropertyDescriptor(EW.prototype,\"unmuteRemote\"),EW.prototype),nb(EW.prototype,\"hasRemoteMediaWithLock\",[RW],Object.getOwnPropertyDescriptor(EW.prototype,\"hasRemoteMediaWithLock\"),EW.prototype),nb(EW.prototype,\"disconnectForReconnect\",[RW],Object.getOwnPropertyDescriptor(EW.prototype,\"disconnectForReconnect\"),EW.prototype),nb(EW.prototype,\"updateBitrateLimit\",[RW],Object.getOwnPropertyDescriptor(EW.prototype,\"updateBitrateLimit\"),EW.prototype),nb(EW.prototype,\"remoteMediaSsrcChanged\",[RW],Object.getOwnPropertyDescriptor(EW.prototype,\"remoteMediaSsrcChanged\"),EW.prototype),EW);function RW(e,t,i){const n=e[t];if(\"function\"!=typeof n)throw new Error(\"Cannot use mutex on object property.\");return i.value=async function(){const e=this.mutex,i=await e.lock(\"From P2PChannel.\".concat(t));try{for(var r=arguments.length,o=new Array(r),s=0;s>>3){case 0:break e;case 1:t.code=YW(e);break;case 2:t.msg=FW(e,YW(e));break;case 3:{let i=AW(e);t.data=IW(e),e.limit=i;break}default:bW(e,7&i)}}return t}({bytes:t=e,offset:0,limit:t.length});var t}function IW(e){let t={};e:for(;!UW(e);){let i=YW(e);switch(i>>>3){case 0:break e;case 1:t.requestId=FW(e,YW(e));break;case 2:t.requestType=YW(e)>>>0;break;case 3:t.scorePorn=HW(e);break;case 4:t.scoreSexy=HW(e);break;case 5:t.scoreNeutral=HW(e);break;case 6:t.requestScene=YW(e)>>>0;break;case 7:t.scene=YW(e)>>>0;break;default:bW(e,7&i)}}return t}function yW(e,t){let i=e.service;void 0!==i&&(qW(t,8),qW(t,i));let n=e.vendor;void 0!==n&&(qW(t,16),qW(t,n));let r=e.token;void 0!==r&&(qW(t,26),BW(t,r));let o=e.callbackUrl;void 0!==o&&(qW(t,34),BW(t,o))}function AW(e){let t=YW(e),i=e.limit;return e.limit=e.offset+t,i}function bW(e,t){switch(t){case 0:for(;128&GW(e););break;case 2:MW(e,YW(e));break;case 5:MW(e,4);break;case 1:MW(e,8);break;default:throw new Error(\"Unimplemented type: \"+t)}}let wW=new Float32Array(1);new Uint8Array(wW.buffer);let OW=new Float64Array(1),NW=new Uint8Array(OW.buffer);function DW(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}let PW=[];function LW(){const e=PW.pop();return e?(e.offset=e.limit=0,e):{bytes:new Uint8Array(64),offset:0,limit:0}}function kW(e){PW.push(e)}function MW(e,t){if(e.offset+t>e.limit)throw new Error(\"Skip past limit\");e.offset+=t}function UW(e){return e.offset>=e.limit}function xW(e,t){let i=e.bytes,n=e.offset,r=e.limit,o=n+t;if(o>i.length){let t=new Uint8Array(2*o);t.set(i),e.bytes=t}return e.offset=o,o>r&&(e.limit=o),n}function VW(e,t){let i=e.offset;if(i+t>e.limit)throw new Error(\"Read past limit\");return e.offset+=t,i}function FW(e,t){let i=VW(e,t),n=String.fromCharCode,r=e.bytes,o=\"�\",s=\"\";for(let e=0;e=t?s+=o:(a=r[e+i+1],128!=(192&a)?s+=o:(l=(31&h)<<6|63&a,l<128?s+=o:(s+=n(l),e++))):224==(240&h)?e+2>=t?s+=o:(a=r[e+i+1],c=r[e+i+2],32896!=(49344&(a|c<<8))?s+=o:(l=(15&h)<<12|(63&a)<<6|63&c,l<2048||l>=55296&&l<=57343?s+=o:(s+=n(l),e+=2))):240==(248&h)?e+3>=t?s+=o:(a=r[e+i+1],c=r[e+i+2],d=r[e+i+3],8421504!=(12632256&(a|c<<8|d<<16))?s+=o:(l=(7&h)<<18|(63&a)<<12|(63&c)<<6|63&d,l<65536||l>1114111?s+=o:(l-=65536,s+=n(55296+(l>>10),56320+(1023&l)),e+=3))):s+=o}return s}function BW(e,t){let i=t.length,n=0;for(let e=0;e=55296&&r<=56319&&e+1=55296&&n<=56319&&e+1>6&31|192:(n<65536?o[r++]=n>>12&15|224:(o[r++]=n>>18&7|240,o[r++]=n>>12&63|128),o[r++]=n>>6&63|128),o[r++]=63&n|128)}}function jW(e,t){let i=xW(e,t.limit),n=e.bytes,r=t.bytes;for(let e=0,o=t.limit;e>>=0;t>=128;)WW(e,127&t|128),t>>>=7;WW(e,t)}function zW(e,t){let i=t.low>>>0,n=(t.low>>>28|t.high<<4)>>>0,r=t.high>>>24,o=0===r?0===n?i<16384?i<128?1:2:i<1<<21?3:4:n<16384?n<128?5:6:n<1<<21?7:8:r<128?9:10,s=xW(e,o),a=e.bytes;switch(o){case 10:a[s+9]=r>>>7&1;case 9:a[s+8]=9!==o?128|r:127&r;case 8:a[s+7]=8!==o?n>>>21|128:n>>>21&127;case 7:a[s+6]=7!==o?n>>>14|128:n>>>14&127;case 6:a[s+5]=6!==o?n>>>7|128:n>>>7&127;case 5:a[s+4]=5!==o?128|n:127&n;case 4:a[s+3]=4!==o?i>>>21|128:i>>>21&127;case 3:a[s+2]=3!==o?i>>>14|128:i>>>14&127;case 2:a[s+1]=2!==o?i>>>7|128:i>>>7&127;case 1:a[s]=1!==o?128|i:127&i}}function JW(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}const XW=new Map([[\"moderation\",1],[\"supervise\",2]]);class QW extends SI{get connectionState(){return this._connectionState}set connectionState(e){if(this._connectionState===e)return;const t=this._connectionState;this._connectionState=e,this.emit(hw.CONNECTION_STATE_CHANGE,t,e)}get inspectType(){return this._inspectType}set inspectType(e){var t;this._inspectMode=Jn(t=e.map((e=>XW.get(e)||0))).call(t,((e,t)=>e+t)),this._inspectType=e}get quality(){return this._quality}set quality(e){this._quality=e>1?1:e<.1?.1:e,this.qualityTimer&&(window.clearTimeout(this.qualityTimer),this.qualityTimer=null),this._quality>=1||(this.qualityTimer=window.setTimeout((()=>{this.quality=this._quality/this.qualityRatio}),6e4))}constructor(e){super(),ng(this,\"name\",\"AgoraRTCVideoContentInspect\"),ng(this,\"_connectionState\",dw.CONNECTING),ng(this,\"_innerConnectionState\",void 0),ng(this,\"sequence\",0),ng(this,\"inspectStartTime\",void 0),ng(this,\"workerManagerConnection\",void 0),ng(this,\"workerConnection\",void 0),ng(this,\"workerMessageLengthLimit\",void 0),ng(this,\"inspectIntervalMinimum\",void 0),ng(this,\"qualityRatio\",void 0),ng(this,\"_connectInfo\",void 0),ng(this,\"_cancelTokenSource\",pv.CancelToken.source()),ng(this,\"_retryConfig\",void 0),ng(this,\"wmSequence\",0),ng(this,\"inspectInterval\",void 0),ng(this,\"inspectTimer\",null),ng(this,\"ossFilePrefix\",void 0),ng(this,\"extraInfo\",void 0),ng(this,\"_inspectType\",void 0),ng(this,\"_inspectMode\",void 0),ng(this,\"_quality\",1),ng(this,\"qualityTimer\",null),ng(this,\"_inspectId\",void 0),ng(this,\"_needWorkUrlOnly\",!1),ng(this,\"inspectImage\",(()=>{if(this.connectionState!==dw.CONNECTED)throw new bb(tI.OPERATION_ABORTED,\"content inspect service connection status is \".concat(this.connectionState));this.inspectTimer&&(window.clearInterval(this.inspectTimer),this.inspectTimer=null),this.inspectTimer=window.setInterval((()=>{this.connectionState===dw.CONNECTED?this.requestToInspectImage():Qy.debug(\"[\".concat(this._inspectId,\"] Inspect State is not connected , \"),this.connectionState)}),this.inspectInterval{this._innerConnectionState=e,Qy.debug(\"[\".concat(this._inspectId,\"] Inspect operation :\").concat(lw[e],\" \").concat(t||\"\"))})),this.handleWorkerManagerEvents(),this.workerConnection=new Fw(\"worker-\"+this._inspectId,_y),this.handleWorkerEvents()}async init(e,t){this.emit(hw.STATE_CHANGE,lw.CONNECT_AP),this._connectInfo=e;const i=this._cancelTokenSource.token;return this._retryConfig=t,new Gu(((n,r)=>{this.on(hw.CONNECTION_STATE_CHANGE,((e,t)=>{t===dw.CONNECTED&&n()})),this.requestAP(e,i,t).then((e=>{this.connectWorkerManager(e)})).catch((e=>{r(e)}))}))}async requestAP(e,t,i){const n=Dy(\"WEBCS_DOMAIN\").map((e=>\"https://\".concat(e,\"/api/v1\"))),r=await function(e,t,i,n){let{appId:r,areaCode:o,cname:s,sid:a,token:c,uid:d}=t;MO++;const l=\"image_moderation_api\",h={service_name:l,json_body:JSON.stringify({appId:r,areaCode:o,cname:s,command:\"allocateEdge\",requestId:MO,seq:MO,sid:a,token:c,ts:Date.now(),uid:d+\"\"})};let u,p,_=e[0];return my((async()=>{u=Date.now();const e=await pO(_,{data:h,cancelToken:i,headers:{\"X-Packet-Service-Type\":\"0\",\"X-Packet-URI\":\"61\"},params:{action:\"wrtc_gateway\"}});if(p=Date.now()-u,0!==e.code){const t=new bb(tI.UNEXPECTED_RESPONSE,\"image inspect ap error, code\"+e.code,{retry:!0,responseTime:p});throw Qy.error(t.toString()),t}const t=JSON.parse(e.json_body);if(200!==t.code){const e=new bb(tI.UNEXPECTED_RESPONSE,\"image inspect ap error, code: \".concat(t.code,\", reason: \").concat(t.reason),{code:t.code,responseTime:p});throw Qy.error(e.toString()),e}if(!t.servers||!Array.isArray(t.servers)||0===t.servers.length){const e=new bb(tI.UNEXPECTED_RESPONSE,\"image inspect ap empty server\",{code:t.code,responseTime:p});throw Qy.error(e.toString()),e}const n=Dy(\"VIDEO_INSPECT_WORKER_MANAGER_HOST\"),r=Dy(\"VIDEO_INSPECT_WORKER_MANAGER_PORT\");return{addressList:t.servers.map((e=>{let{address:t,wss:i}=e;if(t&&i)return\"wss://\".concat(t.replace(/\\./g,\"-\"),\".\").concat(n,\":\").concat(r||i)})).filter((e=>!!e)),workerToken:t.workerToken,vid:t.vid,responseTime:p}}),((t,i)=>(oA.apworkerEvent(a,{success:!0,sc:200,serviceName:l,responseDetail:JSON.stringify(t.addressList),firstSuccess:0===i,responseTime:p,serverIp:e[i%e.length]}),!1)),((t,i)=>(oA.apworkerEvent(a,{success:!1,sc:t.data&&t.data.code||200,serviceName:l,responseTime:p,serverIp:e[i%e.length]}),!!(t.code!==tI.OPERATION_ABORTED&&t.code!==tI.UNEXPECTED_RESPONSE||t.data&&t.data.retry)&&(_=e[(i+1)%e.length],!0))),n)}(n,e,t,i);this.emit(hw.STATE_CHANGE,lw.AP_CONNECTED);const{addressList:o}=r;return this.wmSequence++,o}async connectWorkerManager(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this._needWorkUrlOnly=t,this.emit(hw.STATE_CHANGE,lw.CONNECT_WORKER_MANAGER),await this.workerManagerConnection.init(e,1e4)}async connectWorker(e){await this.workerConnection.init([e])}handleWorkerManagerEvents(){this.workerManagerConnection.on(Ab.CONNECTED,(async()=>{this.emit(hw.STATE_CHANGE,lw.WORKER_MANAGER_CONNECTED,this.workerManagerConnection.url),this.workerManagerConnection.sendMessage({appId:this._connectInfo.appId,cname:this._connectInfo.cname,uid:this._connectInfo.uid+\"\",sdkVersion:\"4.21.0\",sid:this._connectInfo.sid,seq:this.wmSequence,ts:Number(Date.now()),requestId:Math.floor(1e12*Math.random()),allocate:!0,clientRequest:{command:\"join\"}},!0)})),this.workerManagerConnection.on(Ab.CLOSED,(()=>{this._innerConnectionState{this._innerConnectionState{this._innerConnectionState{this.emit(hw.STATE_CHANGE,lw.GET_WORKER_MANAGER_RESPONSE);const t=this.workerManagerConnection.url;this.workerManagerConnection.close();const i=JSON.parse(e.data);if(200!==i.code)throw Qy.error(\"[\".concat(this._inspectId,\"] Unexpected code \").concat(i.code,\" from worker manager\")),new bb(tI.UNEXPECTED_RESPONSE,\"response code of worker is unexpected\",i);if(!(i.serverResponse&&i.serverResponse.portWss&&t))throw Qy.error(\"[\".concat(this._inspectId,\"] Unexpected content from worker manager : \").concat(JSON.stringify(i))),new bb(tI.UNEXPECTED_RESPONSE,\"response content of worker is unexpected\",i);{const e=Dy(\"VIDEO_INSPECT_WORKER_PORT\")||i.serverResponse.portWss,n=t.replace(/:\\d+\\/?$/,\":\".concat(e));this.emit(hw.STATE_CHANGE,lw.CONNECT_WORKER,n),this._needWorkUrlOnly?this.emit(hw.REQUEST_NEW_WORKER_URL,n):await this.connectWorker(n)}})),this.workerManagerConnection.on(Ab.WILL_RECONNECT,((e,t,i)=>{i(e)})),this.workerManagerConnection.on(Ab.REQUEST_NEW_URLS,((e,t)=>{this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then(e).catch(t)}))}handleWorkerEvents(){this.workerConnection.on(Ab.CONNECTED,(async()=>{this.emit(hw.STATE_CHANGE,lw.WORKER_CONNECTED,this.workerConnection.url),this.connectionState=dw.CONNECTED})),this.workerConnection.on(Ab.ON_MESSAGE,(async e=>{if(e.data instanceof ArrayBuffer){const i=vW(new Uint8Array(e.data));if(Dy(\"SHOW_VIDEO_INSPECT_WORKER_MESSAGE\")&&Qy.debug(\"[\".concat(this._inspectId,\"] Response message for worker of inspect content \"),JSON.stringify(i)),200===i.code){if(Array.isArray(this.inspectType)&&1===this.inspectType.length&&\"supervise\"===this.inspectType[0])return void this.emit(hw.INSPECT_RESULT,void 0,void 0);if(i.data&&i.data.scorePorn&&i.data.scoreSexy&&i.data.scoreNeutral){var t;const e={porn:i.data.scorePorn,sexy:i.data.scoreSexy,neutral:i.data.scoreNeutral},n=Jn(t=Object.keys(e)).call(t,((t,i)=>e[t]>e[i]?t:i),\"porn\"),r=Object.keys(e).find((e=>e===n));this.emit(hw.INSPECT_RESULT,r)}else this.emit(hw.INSPECT_RESULT,void 0,new bb(tI.UNEXPECTED_RESPONSE,i.code+\"\",\"There is an unexpected data on message\"))}else this.emit(hw.INSPECT_RESULT,void 0,new bb(tI.UNEXPECTED_RESPONSE,i.code+\"\",i.msg))}else Qy.error(\"[\".concat(this._inspectId,\"] Unexpected message type from worker\")),this.emit(hw.INSPECT_RESULT,void 0,new bb(tI.UNEXPECTED_RESPONSE,\"invalid worker message type\"))})),this.workerConnection.on(Ab.CLOSED,(()=>{this.connectionState=dw.CLOSED})),this.workerConnection.on(Ab.FAILED,(()=>{this.connectionState=dw.CLOSED})),this.workerConnection.on(Ab.RECONNECTING,(()=>{this.connectionState=this.connectionState===dw.CONNECTED?dw.RECONNECTING:dw.CONNECTING})),this.workerConnection.on(Ab.WILL_RECONNECT,((e,t,i)=>{\"recover\"===e&&i(e),i(\"tryNext\")})),this.workerConnection.on(Ab.REQUEST_NEW_URLS,((e,t)=>{this.workerManagerConnection.close(),this.once(hw.REQUEST_NEW_WORKER_URL,(t=>{e([t])})),this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then((e=>{this.connectWorkerManager(e,!0)})).catch((e=>{t(e)}))}))}static intToLong(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}async requestToInspectImage(){this.sequence++;const e=UI(this,hw.CLIENT_LOCAL_VIDEO_TRACK),t={appId:this._connectInfo.appId,cname:this._connectInfo.cname,cid:this._connectInfo.cid,sid:this._connectInfo.sid,uid:this._connectInfo.uid,vid:this._connectInfo.vid};if(e){if(!e.isPlaying)return void this.emit(hw.INSPECT_RESULT,void 0,new bb(tI.INVALID_OPERATION,\"Only the track being played can be inspected\"));const i=await this.generateRequestData(e,t);this.workerConnection.sendMessage(i,!0,!0)}else this.emit(hw.INSPECT_RESULT,void 0,new bb(tI.INVALID_OPERATION,\"Only the track being published can be inspected\"))}async generateRequestData(e,t){let{appId:i,cname:n,cid:r,vid:o,sid:s,uid:a}=t;const c=Date.now(),d=await e.getCurrentFrameImage(\"image/jpeg\",this.quality),l=await Hx(d,i,n),h=this.sequence+\"-\"+r+\"-\"+a+\"-\"+c+\"-\"+ey(12,\"\"),u={appId:i,cid:r,cname:n,deviceId:\"\",elapse:QW.intToLong(Number(c-this.inspectStartTime)),fileSize:l.byteLength,jpgEncryption:2,height:d.height,width:d.width,jpg:l,networkType:6,osType:7,requestId:h,sdkVersion:\"4.21.0\",sequence:this.sequence,sid:s,timestamp:QW.intToLong(c),uid:a,vid:o,service:this._inspectMode,callbackData:this.extraInfo,ossFilePrefix:this.ossFilePrefix};void 0===this.extraInfo&&delete u.callbackData,void 0===this.ossFilePrefix&&delete u.ossFilePrefix;const p=CW(u);if(p.byteLength>>3){case 0:break e;case 1:t.code=uH(e);break;case 2:t.msg=cH(e,uH(e));break;case 3:t.requestId=cH(e,uH(e));break;case 4:t.timestamp=_H(e,!1);break;default:eH(e,7&i)}}return t}({bytes:t=e,offset:0,limit:t.length});var t}function eH(e,t){switch(t){case 0:for(;128&lH(e););break;case 2:nH(e,uH(e));break;case 5:nH(e,4);break;case 1:nH(e,8);break;default:throw new Error(\"Unimplemented type: \"+t)}}function tH(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}let iH=[];function nH(e,t){if(e.offset+t>e.limit)throw new Error(\"Skip past limit\");e.offset+=t}function rH(e){return e.offset>=e.limit}function oH(e,t){let i=e.bytes,n=e.offset,r=e.limit,o=n+t;if(o>i.length){let t=new Uint8Array(2*o);t.set(i),e.bytes=t}return e.offset=o,o>r&&(e.limit=o),n}function sH(e,t){let i=e.offset;if(i+t>e.limit)throw new Error(\"Read past limit\");return e.offset+=t,i}function aH(e,t){let i=oH(e,t.length);e.bytes.set(t,i)}function cH(e,t){let i=sH(e,t),n=String.fromCharCode,r=e.bytes,o=\"�\",s=\"\";for(let e=0;e=t?s+=o:(a=r[e+i+1],128!=(192&a)?s+=o:(l=(31&h)<<6|63&a,l<128?s+=o:(s+=n(l),e++))):224==(240&h)?e+2>=t?s+=o:(a=r[e+i+1],c=r[e+i+2],32896!=(49344&(a|c<<8))?s+=o:(l=(15&h)<<12|(63&a)<<6|63&c,l<2048||l>=55296&&l<=57343?s+=o:(s+=n(l),e+=2))):240==(248&h)?e+3>=t?s+=o:(a=r[e+i+1],c=r[e+i+2],d=r[e+i+3],8421504!=(12632256&(a|c<<8|d<<16))?s+=o:(l=(7&h)<<18|(63&a)<<12|(63&c)<<6|63&d,l<65536||l>1114111?s+=o:(l-=65536,s+=n(55296+(l>>10),56320+(1023&l)),e+=3))):s+=o}return s}function dH(e,t){let i=t.length,n=0;for(let e=0;e=55296&&r<=56319&&e+1=55296&&n<=56319&&e+1>6&31|192:(n<65536?o[r++]=n>>12&15|224:(o[r++]=n>>18&7|240,o[r++]=n>>12&63|128),o[r++]=n>>6&63|128),o[r++]=63&n|128)}}function lH(e){return e.bytes[sH(e,1)]}function hH(e,t){let i=oH(e,1);e.bytes[i]=t}function uH(e){let t,i=0,n=0;do{t=lH(e),i<32&&(n|=(127&t)<>>=0;t>=128;)hH(e,127&t|128),t>>>=7;hH(e,t)}function _H(e,t){let i,n=0,r=0,o=0;return i=lH(e),n=127&i,128&i&&(i=lH(e),n|=(127&i)<<7,128&i&&(i=lH(e),n|=(127&i)<<14,128&i&&(i=lH(e),n|=(127&i)<<21,128&i&&(i=lH(e),r=127&i,128&i&&(i=lH(e),r|=(127&i)<<7,128&i&&(i=lH(e),r|=(127&i)<<14,128&i&&(i=lH(e),r|=(127&i)<<21,128&i&&(i=lH(e),o=127&i,128&i&&(i=lH(e),o|=(127&i)<<7))))))))),{low:n|r<<28,high:r>>>4|o<<24,unsigned:t}}function EH(e,t){let i=t.low>>>0,n=(t.low>>>28|t.high<<4)>>>0,r=t.high>>>24,o=0===r?0===n?i<16384?i<128?1:2:i<1<<21?3:4:n<16384?n<128?5:6:n<1<<21?7:8:r<128?9:10,s=oH(e,o),a=e.bytes;switch(o){case 10:a[s+9]=r>>>7&1;case 9:a[s+8]=9!==o?128|r:127&r;case 8:a[s+7]=8!==o?n>>>21|128:n>>>21&127;case 7:a[s+6]=7!==o?n>>>14|128:n>>>14&127;case 6:a[s+5]=6!==o?n>>>7|128:n>>>7&127;case 5:a[s+4]=5!==o?128|n:127&n;case 4:a[s+3]=4!==o?i>>>21|128:i>>>21&127;case 3:a[s+2]=3!==o?i>>>14|128:i>>>14&127;case 2:a[s+1]=2!==o?i>>>7|128:i>>>7&127;case 1:a[s]=1!==o?128|i:127&i}}const mH={},fH={},TH=4294967296,SH=TH*TH,gH=SH/2,RH=AH(0,!0),CH=AH(0),vH=bH(0,-2147483648,!1),IH=bH(-1,2147483647,!1),yH=bH(-1,-1,!0);function AH(e,t){let i,n,r;return t?(r=0<=(e>>>=0)&&e<256)&&(n=fH[e],n)?n:(i=bH(e,0,!0),r&&(fH[e]=i),i):(r=-128<=(e|=0)&&e<128)&&(n=mH[e],n)?n:(i=bH(e,e<0?-1:0,!1),r&&(mH[e]=i),i)}function bH(e,t,i){return{low:0|e,high:0|t,unsigned:!!i}}function wH(e,t){if(isNaN(e))return t?RH:CH;if(t){if(e<0)return RH;if(e>=SH)return yH}else{if(e<=-gH)return vH;if(e+1>=gH)return IH}return e<0?t?RH:CH:bH(e%TH|0,e/TH|0,t)}function OH(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}class NH extends SI{get connectionState(){return this._connectionState}set connectionState(e){if(this._connectionState===e)return;const t=this._connectionState;this._connectionState=e,this.emit(mw.CONNECTION_STATE_CHANGE,e,t)}get quality(){return this._quality}set quality(e){this._quality=e>1?1:e<.1?.1:e,this._qualityTimer&&(window.clearTimeout(this._qualityTimer),this._qualityTimer=null),this._quality>=1||(this._qualityTimer=window.setTimeout((()=>{this.quality=this._quality/this._qualityRatio}),6e4))}constructor(e){var t;super(),ng(this,\"name\",\"AgoraRTCImageModeration\"),ng(this,\"_connectionState\",Ew.CONNECTING),ng(this,\"_sequence\",0),ng(this,\"_moderationStartTime\",void 0),ng(this,\"_workerConnection\",void 0),ng(this,\"_workerMessageLengthLimit\",void 0),ng(this,\"_qualityRatio\",void 0),ng(this,\"_connectInfo\",void 0),ng(this,\"_cancelTokenSource\",pv.CancelToken.source()),ng(this,\"_retryConfig\",void 0),ng(this,\"_moderationInterval\",void 0),ng(this,\"_moderationTimer\",null),ng(this,\"_moderationMode\",1),ng(this,\"_quality\",1),ng(this,\"_qualityTimer\",null),ng(this,\"_ticket\",void 0),ng(this,\"_moderationIntervalMinimum\",void 0),ng(this,\"_uploadFailedNum\",0),ng(this,\"_uploadNum\",0),ng(this,\"_uploadTimer\",null),ng(this,\"_extraInfo\",void 0),ng(this,\"_vendor\",\"\"),ng(this,\"_encoder\",new TextEncoder),ng(this,\"_moderationId\",void 0),ng(this,\"inspectImage\",(()=>{if(this.connectionState!==Ew.CONNECTED)throw new bb(tI.OPERATION_ABORTED,\"image moderation service connection status is \".concat(this.connectionState));this._moderationTimer&&(window.clearInterval(this._moderationTimer),this._moderationTimer=null),this._moderationTimer=window.setInterval((()=>{this.connectionState===Ew.CONNECTED?this.requestToInspectImage():Qy.debug(\"[\".concat(this._moderationId,\"] Moderation State is not connected , \"),this.connectionState)}),this._moderationInterval{Qy.debug(\"[\".concat(this._moderationId,\"] Moderation operation :\").concat(fw[e],\" \").concat(t||\"\"))})),this.handleWorkerEvents()}async init(e,t){this.emit(mw.STATE_CHANGE,fw.CONNECT_AP),this._connectInfo=e;const i=this._cancelTokenSource.token;return this._retryConfig=t,new Gu(((n,r)=>{this.on(mw.CONNECTION_STATE_CHANGE,((e,t)=>{e===Ew.CONNECTED&&n()})),this.requestAP(e,i,t).then((e=>{this.connectWorker(e)})).catch((e=>{r(e)}))}))}updateConfig(e){var t;this._moderationInterval=null!==(t=e.interval)&&void 0!==t?t:1e3,e.extraInfo&&(this._extraInfo=this._encoder.encode(e.extraInfo)),e.vendor&&(this._vendor=e.vendor),Qy.debug(\"[\".concat(this._moderationId,\"] updateConfig: \").concat(JSON.stringify(e))),this.connectionState===Ew.CONNECTED&&this.inspectImage()}async requestAP(e,t,i){const n=Dy(\"WEBCS_DOMAIN\").map((e=>\"https://\".concat(e,\"/api/v1\"))),r=await function(e,t,i,n){let{appId:r,areaCode:o,cname:s,sid:a,token:c,uid:d}=t;MO++;const l=\"moderation_plugin\",h={service_name:l,json_body:JSON.stringify({appId:r,areaCode:o,cname:s,command:\"allocateEdge\",requestId:MO,seq:MO,sid:a,appToken:c,ts:Date.now(),uid:d+\"\"})};let u,p,_=e[0];return my((async()=>{u=Date.now();const e=await pO(_,{data:h,cancelToken:i,headers:{\"X-Packet-Service-Type\":\"0\",\"X-Packet-URI\":\"61\"},params:{action:\"wrtc_gateway\"}});if(p=Date.now()-u,0!==e.code){const t=new bb(tI.UNEXPECTED_RESPONSE,\"moderation plugin ap error, code\"+e.code,{retry:!0,responseTime:p});throw Qy.error(t.toString()),t}const t=JSON.parse(e.json_body);if(200!==t.code){const e=new bb(tI.UNEXPECTED_RESPONSE,\"moderation plugin ap error, code: \".concat(t.code,\", reason: \").concat(t.reason),{code:t.code,responseTime:p});throw Qy.error(e.toString()),e}if(!t.servers||!Array.isArray(t.servers)||0===t.servers.length){const e=new bb(tI.UNEXPECTED_RESPONSE,\"moderation plugin ap empty server\",{code:t.code,responseTime:p});throw Qy.error(e.toString()),e}if(!t.servers.some((e=>!!e.wss))){const e=new bb(tI.UNEXPECTED_RESPONSE,\"moderation plugin ap empty port\",{code:t.code,responseTime:p});throw Qy.error(e.toString()),e}const n=Dy(\"IMAGE_MODERATION_WORKER_HOST\");return{addressList:t.servers.map((e=>{let{address:t,wss:i}=e;if(t&&i)return\"wss://\".concat(t.replace(/\\./g,\"-\"),\".\").concat(n,\":\").concat(i,\"/moderation\")})).filter((e=>!!e)),workerToken:t.workerToken,vid:t.vid,ticket:t.appTicket,responseTime:p}}),((t,i)=>(oA.apworkerEvent(a,{success:!0,sc:200,serviceName:l,responseDetail:JSON.stringify(t.addressList),firstSuccess:0===i,responseTime:p,serverIp:e[i%e.length]}),!1)),((t,i)=>(oA.apworkerEvent(a,{success:!1,sc:t.data&&t.data.code||200,serviceName:l,responseTime:p,serverIp:e[i%e.length]}),!!(t.code!==tI.OPERATION_ABORTED&&t.code!==tI.UNEXPECTED_RESPONSE||t.data&&t.data.retry)&&(_=e[(i+1)%e.length],!0))),n)}(n,e,t,i);this.emit(mw.STATE_CHANGE,fw.AP_CONNECTED);const{addressList:o,ticket:s}=r;return this._ticket=s,o}async connectWorker(e){this.emit(mw.STATE_CHANGE,fw.CONNECT_WORKER),await this._workerConnection.init(e,1e4)}handleWorkerEvents(){this._workerConnection.on(Ab.CONNECTED,(async()=>{this.emit(mw.STATE_CHANGE,fw.WORKER_CONNECTED,this._workerConnection.url),this.connectionState=Ew.CONNECTED})),this._workerConnection.on(Ab.CLOSED,(()=>{this.connectionState=Ew.CLOSED})),this._workerConnection.on(Ab.FAILED,(()=>{this.connectionState=Ew.CLOSED})),this._workerConnection.on(Ab.RECONNECTING,(()=>{this.connectionState=this.connectionState===Ew.CONNECTED?Ew.RECONNECTING:Ew.CONNECTING})),this._workerConnection.on(Ab.ON_MESSAGE,(async e=>{if(e.data instanceof ArrayBuffer){const t=$W(new Uint8Array(e.data));Dy(\"SHOW_IMAGE_MODERATION_WORKER_MESSAGE\")&&Qy.debug(\"[\".concat(this._moderationId,\"] Response message for worker of image moderation \"),JSON.stringify(t)),this._uploadNum++,void 0===t.code||0===t.code||(this._uploadFailedNum++,Qy.error(\"[\".concat(this._moderationId,\"] Error response from worke, code is \").concat(t.code,\", msg is \").concat(t.msg)),this._uploadTimer||(this._uploadTimer=window.setTimeout((()=>{oA.reportApiInvoke(this._connectInfo.sid||null,{name:CI.IMAGE_MODERATION_UPLOAD,options:[this._uploadFailedNum,this._uploadNum,t.code],tag:vI.TRACER}).onError(new bb(tI.IMAGE_MODERATION_UPLOAD_FAILED,t.msg)),this._uploadTimer=null}),Dy(\"IMAGE_MODERATION_UPLOAD_REPORT_INTERVAL\"))))}else Qy.error(\"[\".concat(this._moderationId,\"] Unexpected message type from worker\"))})),this._workerConnection.on(Ab.WILL_RECONNECT,((e,t,i)=>{\"recover\"===e&&i(e),i(\"tryNext\")})),this._workerConnection.on(Ab.REQUEST_NEW_URLS,((e,t)=>{this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then(e).catch(t)}))}static intToLong(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}async requestToInspectImage(){const e=UI(this,mw.CLIENT_LOCAL_VIDEO_TRACK),t={appId:this._connectInfo.appId,cname:this._connectInfo.cname,cid:this._connectInfo.cid,sid:this._connectInfo.sid,uid:this._connectInfo.uid,vid:this._connectInfo.vid};if(e){if(!e.isPlaying)return void(Dy(\"SHOW_IMAGE_MODERATION_WORKER_MESSAGE\")&&Qy.debug(\"Only the track being played can be inspected\"));this._sequence++;const i=await this.generateRequestData(e,t);this._workerConnection.sendMessage(i,!0,!0)}else Dy(\"SHOW_IMAGE_MODERATION_WORKER_MESSAGE\")&&Qy.debug(\"Only the track being published can be inspected\")}async generateRequestData(e,t){let{appId:i,cname:n,cid:r,vid:o,sid:s,uid:a}=t;const c=Date.now(),d=await e.getCurrentFrameImage(\"image/jpeg\",this.quality),l=await Hx(d,i,n),h=this._sequence+\"-\"+r+\"-\"+a+\"-\"+c+\"-\"+ey(12,\"\"),u={appId:i,cid:r,cname:n,deviceId:\"\",elapse:NH.intToLong(Number(c-this._moderationStartTime)),fileSize:d.buffer.byteLength,height:d.height,width:d.width,jpg:l,networkType:6,osType:7,requestId:h,sdkVersion:\"4.21.0\",sequence:this._sequence,sid:s,timestamp:wH(c),uid:a,vid:o,service:this._moderationMode,ticket:this._ticket,callbackData:this._extraInfo,vendorConfigs:this._vendor};void 0===this._extraInfo&&delete u.callbackData;const p=ZW(u);if(p.byteLength0&&(n.firstRecvTs=Date.now()-o);let a=i.mediaDelay+s;a<=0?(t.pop(),VH(i.context,r),a=0):a=Math.min(a,kH),setTimeout((()=>t.length&&xH(e)),a)}function VH(e,t){e.safeEmit(NI.STREAM_MESSAGE,t.uid,t.payload),e.onStreamMessage&&e.onStreamMessage(t)}function FH(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2?arguments[2]:void 0;if(!e.syncWithAudio)return VH(i,{uid:e.uid,payload:e.payload});const n=\"\".concat(i.id,\"-\").concat(e.uid),r=MH.get(n)||[],o=r.findIndex((t=>e.sendTs>=t.sendTs)),s=PH(PH({},e),{},{context:i,mediaDelay:t,recvTs:Date.now()});-1===o?r.push(s):r.splice(o,0,s),MH.set(n,r);let a=!1;var c;UH.has(n)?a=!(null===(c=UH.get(n))||void 0===c||!c.isSyncing):UH.set(n,{isSyncing:a,firstRecvTs:0,firstSendTs:0});a||xH(n)}const BH=Iv().name;function jH(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function GH(e){for(var t=1;t