>>=T,p-=T),p<15&&(h+=v[i++]<>>24,h>>>=T,p-=T,T=g>>>16&255,!(16&T)){if(0==(64&T)){g=E[(65535&g)+(h&(1<a){e.msg="invalid distance too far back",A.mode=YN;break e;}if(h>>>=T,p-=T,T=r-s,R>T){if(T=R-T,T>d&&A.sane){e.msg="invalid distance too far back",A.mode=YN;break e;}if(C=0,I=u,0===l){if(C+=c-T,T2;)y[r++]=I[C++],y[r++]=I[C++],y[r++]=I[C++],S-=3;S&&(y[r++]=I[C++],S>1&&(y[r++]=I[C++]));}else {C=r-R;do{y[r++]=y[C++],y[r++]=y[C++],y[r++]=y[C++],S-=3;}while(S>2);S&&(y[r++]=y[C++],S>1&&(y[r++]=y[C++]));}break;}}break;}}while(i>3,i-=S,p-=S<<3,h&=(1<{const c=a.bits;let d,l,u,h,p,_,E=0,m=0,f=0,g=0,T=0,S=0,R=0,C=0,I=0,v=0,y=null;const A=new Uint16Array(16),b=new Uint16Array(16);let w,O,N,D=null;for(E=0;E<=zN;E++)A[E]=0;for(m=0;m=1&&0===A[g];g--);if(T>g&&(T=g),0===g)return r[s++]=20971520,r[s++]=20971520,a.bits=1,0;for(f=1;f0&&(0===e||1!==g))return -1;for(b[1]=0,E=1;E852||2===e&&I>592)return 1;for(;;){w=E-R,o[m]+1<_?(O=0,N=o[m]):o[m]>=_?(O=D[o[m]-_],N=y[o[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?(v&=d-1,v+=d):v=0,m++,0==--A[E]){if(E===g)break;E=t[i+o[m]];}if(E>T&&(v&h)!==u){for(0===R&&(R=T),p+=f,S=E-R,C=1<852||2===e&&I>592)return 1;u=v&h,r[u]=T<<24|S<<16|p-s|0;}}return 0!==v&&(r[p+v]=E-R<<24|64<<16|0),a.bits=T,0;};const{Z_FINISH:eD,Z_BLOCK:tD,Z_TREES:iD,Z_OK:nD,Z_STREAM_END:rD,Z_NEED_DICT:sD,Z_STREAM_ERROR:oD,Z_DATA_ERROR:aD,Z_MEM_ERROR:cD,Z_BUF_ERROR:dD,Z_DEFLATED:lD}=CO,uD=16180,hD=16190,pD=16191,_D=16192,ED=16194,mD=16199,fD=16200,gD=16206,TD=16209,SD=e=>(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24);function RD(){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 CD=e=>{if(!e)return 1;const t=e.state;return !t||t.strm!==e||t.mode16211?1:0;},ID=e=>{if(CD(e))return oD;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=uD,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,nD;},vD=e=>{if(CD(e))return oD;const t=e.state;return t.wsize=0,t.whave=0,t.wnext=0,ID(e);},yD=(e,t)=>{let i;if(CD(e))return oD;const n=e.state;return t<0?(i=0,t=-t):(i=5+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?oD:(null!==n.window&&n.wbits!==t&&(n.window=null),n.wrap=i,n.wbits=t,vD(e));},AD=(e,t)=>{if(!e)return oD;const i=new RD();e.state=i,i.strm=e,i.window=null,i.mode=uD;const n=yD(e,t);return n!==nD&&(e.state=null),n;};let bD,wD,OD=!0;const ND=e=>{if(OD){bD=new Int32Array(512),wD=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($N(1,e.lens,0,288,bD,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;$N(2,e.lens,0,32,wD,0,e.work,{bits:5}),OD=!1;}e.lencode=bD,e.lenbits=9,e.distcode=wD,e.distbits=5;},DD=(e,t,i,n)=>{let r;const s=e.state;return null===s.window&&(s.wsize=1<=s.wsize?(s.window.set(t.subarray(i-s.wsize,i),0),s.wnext=0,s.whave=s.wsize):(r=s.wsize-s.wnext,r>n&&(r=n),s.window.set(t.subarray(i-n,i-n+r),s.wnext),(n-=r)?(s.window.set(t.subarray(i-n,i),0),s.wnext=n,s.whave=s.wsize):(s.wnext+=r,s.wnext===s.wsize&&(s.wnext=0),s.whave{let i,n,r,s,o,a,c,d,l,u,h,p,_,E,m,f,g,T,S,R,C,I,v=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(CD(e)||!e.output||!e.input&&0!==e.avail_in)return oD;i=e.state,i.mode===pD&&(i.mode=_D),o=e.next_out,r=e.output,c=e.avail_out,s=e.next_in,n=e.input,a=e.avail_in,d=i.hold,l=i.bits,u=a,h=c,I=nD;e:for(;;)switch(i.mode){case uD:if(0===i.wrap){i.mode=_D;break;}for(;l<16;){if(0===a)break e;a--,d+=n[s++]<>>8&255,i.check=SO(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=TD;break;}if((15&d)!==lD){e.msg="unknown compression method",i.mode=TD;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=TD;break;}i.dmax=1<>8&1),512&i.flags&&4&i.wrap&&(y[0]=255&d,y[1]=d>>>8&255,i.check=SO(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[s++]<>>8&255,y[2]=d>>>16&255,y[3]=d>>>24&255,i.check=SO(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[s++]<>8),512&i.flags&&4&i.wrap&&(y[0]=255&d,y[1]=d>>>8&255,i.check=SO(i.check,y,2,0)),d=0,l=0,i.mode=16184;case 16184:if(1024&i.flags){for(;l<16;){if(0===a)break e;a--,d+=n[s++]<>>8&255,i.check=SO(i.check,y,2,0)),d=0,l=0;}else i.head&&(i.head.extra=null);i.mode=16185;case 16185:if(1024&i.flags&&(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(s,s+p),C)),512&i.flags&&4&i.wrap&&(i.check=SO(i.check,n,p,s)),a-=p,s+=p,i.length-=p),i.length))break e;i.length=0,i.mode=16186;case 16186:if(2048&i.flags){if(0===a)break e;p=0;do{C=n[s+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=pD;break;case 16189:for(;l<32;){if(0===a)break e;a--,d+=n[s++]<>>=7&l,l-=7&l,i.mode=gD;break;}for(;l<3;){if(0===a)break e;a--,d+=n[s++]<>>=1,l-=1,3&d){case 0:i.mode=16193;break;case 1:if(ND(i),i.mode=mD,t===iD){d>>>=2,l-=2;break e;}break;case 2:i.mode=16196;break;case 3:e.msg="invalid block type",i.mode=TD;}d>>>=2,l-=2;break;case 16193:for(d>>>=7&l,l-=7&l;l<32;){if(0===a)break e;a--,d+=n[s++]<>>16^65535)){e.msg="invalid stored block lengths",i.mode=TD;break;}if(i.length=65535&d,d=0,l=0,i.mode=ED,t===iD)break e;case ED: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(s,s+p),o),a-=p,s+=p,c-=p,o+=p,i.length-=p;break;}i.mode=pD;break;case 16196:for(;l<14;){if(0===a)break e;a--,d+=n[s++]<>>=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=TD;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},I=$N(0,i.lens,0,19,i.lencode,0,i.work,A),i.lenbits=A.bits,I){e.msg="invalid code lengths set",i.mode=TD;break;}i.have=0,i.mode=16198;case 16198:for(;i.have>>24,f=v>>>16&255,g=65535&v,!(m<=l);){if(0===a)break e;a--,d+=n[s++]<>>=m,l-=m,i.lens[i.have++]=g;else {if(16===g){for(b=m+2;l>>=m,l-=m,0===i.have){e.msg="invalid bit length repeat",i.mode=TD;break;}C=i.lens[i.have-1],p=3+(3&d),d>>>=2,l-=2;}else if(17===g){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=TD;break;}for(;p--;)i.lens[i.have++]=C;}}if(i.mode===TD)break;if(0===i.lens[256]){e.msg="invalid code -- missing end-of-block",i.mode=TD;break;}if(i.lenbits=9,A={bits:i.lenbits},I=$N(1,i.lens,0,i.nlen,i.lencode,0,i.work,A),i.lenbits=A.bits,I){e.msg="invalid literal/lengths set",i.mode=TD;break;}if(i.distbits=6,i.distcode=i.distdyn,A={bits:i.distbits},I=$N(2,i.lens,i.nlen,i.ndist,i.distcode,0,i.work,A),i.distbits=A.bits,I){e.msg="invalid distances set",i.mode=TD;break;}if(i.mode=mD,t===iD)break e;case mD:i.mode=fD;case fD:if(a>=6&&c>=258){e.next_out=o,e.avail_out=c,e.next_in=s,e.avail_in=a,i.hold=d,i.bits=l,qN(e,h),o=e.next_out,r=e.output,c=e.avail_out,s=e.next_in,n=e.input,a=e.avail_in,d=i.hold,l=i.bits,i.mode===pD&&(i.back=-1);break;}for(i.back=0;v=i.lencode[d&(1<>>24,f=v>>>16&255,g=65535&v,!(m<=l);){if(0===a)break e;a--,d+=n[s++]<>T)],m=v>>>24,f=v>>>16&255,g=65535&v,!(T+m<=l);){if(0===a)break e;a--,d+=n[s++]<>>=T,l-=T,i.back+=T;}if(d>>>=m,l-=m,i.back+=m,i.length=g,0===f){i.mode=16205;break;}if(32&f){i.back=-1,i.mode=pD;break;}if(64&f){e.msg="invalid literal/length code",i.mode=TD;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(;v=i.distcode[d&(1<>>24,f=v>>>16&255,g=65535&v,!(m<=l);){if(0===a)break e;a--,d+=n[s++]<>T)],m=v>>>24,f=v>>>16&255,g=65535&v,!(T+m<=l);){if(0===a)break e;a--,d+=n[s++]<>>=T,l-=T,i.back+=T;}if(d>>>=m,l-=m,i.back+=m,64&f){e.msg="invalid distance code",i.mode=TD;break;}i.offset=g,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=TD;break;}i.mode=16204;case 16204:if(0===c)break e;if(p=h-c,i.offset>p){if(p=i.offset-p,p>i.whave&&i.sane){e.msg="invalid distance too far back",i.mode=TD;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,_=o-i.offset,p=i.length;p>c&&(p=c),c-=p,i.length-=p;do{r[o++]=E[_++];}while(--p);0===i.length&&(i.mode=fD);break;case 16205:if(0===c)break e;r[o++]=i.length,c--,i.mode=fD;break;case gD:if(i.wrap){for(;l<32;){if(0===a)break e;a--,d|=n[s++]<AD(e,15),inflateInit2:AD,inflate:PD,inflateEnd:e=>{if(CD(e))return oD;let t=e.state;return t.window&&(t.window=null),e.state=null,nD;},inflateGetHeader:(e,t)=>{if(CD(e))return oD;const i=e.state;return 0==(2&i.wrap)?oD:(i.head=t,t.done=!1,nD);},inflateSetDictionary:(e,t)=>{const i=t.length;let n,r,s;return CD(e)?oD:(n=e.state,0!==n.wrap&&n.mode!==hD?oD:n.mode===hD&&(r=1,r=gO(r,t,i,0),r!==n.check)?aD:(s=DD(e,t,i,i),s?(n.mode=16210,cD):(n.havedict=1,nD)));},inflateInfo:"pako inflate (from Nodeca project)"};var kD=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 MD=Object.prototype.toString,{Z_NO_FLUSH:UD,Z_FINISH:xD,Z_OK:VD,Z_STREAM_END:FD,Z_NEED_DICT:BD,Z_STREAM_ERROR:jD,Z_DATA_ERROR:GD,Z_MEM_ERROR:WD}=CO;function HD(e){this.options=wN.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 PN(),this.strm.avail_out=0;let i=LD.inflateInit2(this.strm,t.windowBits);if(i!==VD)throw new Error(RO[i]);if(this.header=new kD(),LD.inflateGetHeader(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=DN.string2buf(t.dictionary):"[object ArrayBuffer]"===MD.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(i=LD.inflateSetDictionary(this.strm,t.dictionary),i!==VD)))throw new Error(RO[i]);}function KD(e,t){const i=new HD(t);if(i.push(e),i.err)throw i.msg||RO[i.err];return i.result;}HD.prototype.push=function(e,t){const i=this.strm,n=this.options.chunkSize,r=this.options.dictionary;let s,o,a;if(this.ended)return !1;for(o=t===~~t?t:!0===t?xD:UD,"[object ArrayBuffer]"===MD.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),s=LD.inflate(i,o),s===BD&&r&&(s=LD.inflateSetDictionary(i,r),s===VD?s=LD.inflate(i,o):s===GD&&(s=BD));i.avail_in>0&&s===FD&&i.state.wrap>0&&0!==e[i.next_in];)LD.inflateReset(i),s=LD.inflate(i,o);switch(s){case jD:case GD:case BD:case WD:return this.onEnd(s),this.ended=!0,!1;}if(a=i.avail_out,i.next_out&&(0===i.avail_out||s===FD))if("string"===this.options.to){let e=DN.utf8border(i.output,i.next_out),t=i.next_out-e,r=DN.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(s!==VD||0!==a){if(s===FD)return s=LD.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,!0;if(0===i.avail_in)break;}}return !0;},HD.prototype.onData=function(e){this.chunks.push(e);},HD.prototype.onEnd=function(e){e===VD&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=wN.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg;};var YD={Inflate:HD,inflate:KD,inflateRaw:function(e,t){return (t=t||{}).raw=!0,KD(e,t);},ungzip:KD,constants:CO};const{Deflate:qD,deflate:zD,deflateRaw:JD,gzip:XD}=KN,{Inflate:QD,inflate:ZD,inflateRaw:$D,ungzip:eP}=YD;var tP,iP=zD,nP=ZD;!function(e){e[e.ONE_BYTE=0]="ONE_BYTE",e[e.TWO_BYTE=1]="TWO_BYTE";}(tP||(tP={}));class rP{constructor(){sh(this,"_sequence",0),sh(this,"_startTime",Date.now()),sh(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;RC("SHOW_DATASTREAM2_LOG")&&jC.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 s=0;if(r.setUint16(s,t.commonPacketHeader.extension<<15|t.commonPacketHeader.reserved<<14|t.commonPacketHeader.length,!0),s+=2,r.setUint32(s,t.commonPacketHeader.sequence,!0),s+=4,r.setUint16(s,t.commonStreamHeader,!0),s+=2,t.extension){const e=this.serializeExtension(t.extension);n.set(new Uint8Array(e),s),s+=e.byteLength;}if(n.set(new Uint8Array(t.payload),s),s+=t.payload.byteLength,s!==t.commonPacketHeader.length)throw Error("serialize error!");return i;}deserialize(e){if(e.byteLength<4)return new ArrayBuffer(0);const t=new DataView(e);let i=0;const 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 s,o;if(i+=4,RC("SHOW_DATASTREAM2_LOG")&&jC.debug("receive data header: ".concat(JSON.stringify(r))),t.getUint16(i,!0),i+=2,r.extension){o=this.deserializeExtension(e.slice(i)),i+=2+o.length,s=e.slice(i);let t=!1;if(o.datas.length>0){const e=o.datas.find(e=>0===e.id);if(e){t=1==(1&new DataView(e.data).getUint32(0,!0));}}s=t?this.decompress(s):s;}else s=e.slice(8);return s;}serializeExtension(e){const{profile:t,length:i,datas:n}=e,r=new ArrayBuffer(i+2),s=new Uint8Array(r),o=new DataView(r);let a=0;if(o.setUint8(a++,t),o.setUint8(a++,i),n.forEach(e=>{t?(o.setUint8(a++,e.id),o.setUint8(a++,e.length),s.set(new Uint8Array(e.data),a),a+=e.data.byteLength):(o.setUint8(a++,e.id|e.length<<4),s.set(new Uint8Array(e.data),a),a+=e.data.byteLength);}),a!==i+2)throw Error("serialize extension error, is ".concat(a,"!==").concat(i+2));return r;}deserializeExtension(e){const t=new DataView(e);let i=0;const n=t.getUint8(i);i++;const r=t.getUint8(i);i++;const s=n===tP.TWO_BYTE,o=[],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),o.push({id:e,length:t,data:i});}if(c!==r)throw Error("parse error");return {profile:n,length:r,datas:o};}decompress(e){return nP(new Uint8Array(e));}compress(e){return iP(new Uint8Array(e));}}class sP extends dT{constructor(e,t){super(),sh(this,"_version",1),sh(this,"_type",3),sh(this,"_config",void 0),sh(this,"_originDataChannel",void 0),sh(this,"_dataStreamPacketHeader",new ArrayBuffer(4)),sh(this,"_dataStreamPacketHandler",void 0),sh(this,"_datachannelEventMap",new Map()),this._config=e,t&&(this._originDataChannel=t,this._bandDataChannelEvents(t)),this._initPacketHeader(),this._dataStreamPacketHandler=new rP();}get id(){return this._config.id;}get ordered(){return this._config.ordered;}get maxRetransmits(){return RC("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 cg((e,t)=>{if(this._originDataChannel){"open"===this._originDataChannel.readyState&&e();const i=setTimeout(()=>{var e;t(new Kg(Hg.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 Kg(Hg.DATACHANNEL_CONNECTION_TIMEOUT);};}else t(new Kg(Hg.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),[cb.OPEN,cb.CLOSE,cb.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 oP extends sP{constructor(e){super(e),sh(this,"_messageListener",void 0),this._messageListener=e=>{if(e.data.byteLength0?arguments[0]:void 0));mP||(this.size=e.entries.length);},RL=SL.prototype;if(SP(RL,{append:function(e,t){var i=GP(this);UP(arguments.length,2),nL(i.entries,{key:DP(e),value:DP(t)}),mP||this.length++,i.updateURL();},delete:function(e){for(var t=GP(this),i=UP(arguments.length,1),n=t.entries,r=DP(e),s=i<2?void 0:arguments[1],o=void 0===s?s:DP(s),a=0;at.key?1:-1;}),e.updateURL();},forEach:function(e){for(var t,i=GP(this).entries,n=bP(e,arguments.length>1?arguments[1]:void 0),r=0;r1?vL(arguments[1]):{});}}),yP(qP)){var yL=function(e){return vP(this,JP),new qP(e,arguments.length>1?vL(arguments[1]):{});};JP.constructor=yL,yL.prototype=JP,hP({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:yL});}}var AL,bL={URLSearchParams:SL,getState:GP},wL=N,OL=d,NL=L,DL=n,PL=Ys,LL=ko,kL=k,ML=Je,UL=K,xL=Object.assign,VL=Object.defineProperty,FL=OL([].concat),BL=!xL||DL(function(){if(wL&&1!==xL({b:1},xL(VL({},"a",{enumerable:!0,get:function(){VL(this,"b",{value:3,enumerable:!1});}}),{b:2})).b)return !0;var e={},t={},i=Symbol(),n="abcdefghijklmnopqrst";return e[i]=7,n.split("").forEach(function(e){t[e]=e;}),7!=xL({},e)[i]||PL(xL({},t)).join("")!=n;})?function(e,t){for(var i=ML(e),n=arguments.length,r=1,s=LL.f,o=kL.f;n>r;)for(var a,c=UL(arguments[r++]),d=s?FL(PL(c),s(c)):PL(c),l=d.length,u=0;l>u;)a=d[u++],wL&&!NL(o,c,a)||(i[a]=c[a]);return i;}:xL,jL=ii,GL=Hp,WL=Xt,HL=L,KL=Je,YL=function(e,t,i,n){try{return n?t(jL(i)[0],i[1]):t(i);}catch(t){GL(e,"throw",t);}},qL=bp,zL=ls,JL=Bi,XL=Yr,QL=Bp,ZL=Lp,$L=Array,ek=d,tk=2147483647,ik=/[^\0-\u007E]/,nk=/[.\u3002\uFF0E\uFF61]/g,rk="Overflow: input needs wider integers to process",sk=RangeError,ok=ek(nk.exec),ak=Math.floor,ck=String.fromCharCode,dk=ek("".charCodeAt),lk=ek([].join),uk=ek([].push),hk=ek("".replace),pk=ek("".split),_k=ek("".toLowerCase),Ek=function(e){return e+22+75*(e<26);},mk=function(e,t,i){var n=0;for(e=i?ak(e/700):e>>1,e+=ak(e/t);e>455;)e=ak(e/35),n+=36;return ak(n+36*e/(e+38));},fk=function(e){var t=[];e=function(e){for(var t=[],i=0,n=e.length;i=55296&&r<=56319&&i=s&&nak((tk-o)/u))throw sk(rk);for(o+=(l-s)*u,s=l,i=0;itk)throw sk(rk);if(n==s){for(var h=o,p=36;;){var _=p<=a?1:p>=a+26?26:p-a;if(h<_)break;var E=h-_,m=36-_;uk(t,ck(Ek(_+E%m))),h=ak(E/m),p+=36;}uk(t,ck(Ek(h))),a=mk(o,u,d==c),o=0,d++;}}o++,s++;}return lk(t,"");},gk=wi,Tk=N,Sk=lP,Rk=h,Ck=Xt,Ik=d,vk=Uo,yk=Vo,Ak=k_,bk=Ze,wk=BL,Ok=function(e){var t=KL(e),i=zL(this),n=arguments.length,r=n>1?arguments[1]:void 0,s=void 0!==r;s&&(r=WL(r,n>2?arguments[2]:void 0));var o,a,c,d,l,u,h=ZL(t),p=0;if(!h||this===$L&&qL(h))for(o=JL(t),a=i?new this(o):$L(o);o>p;p++)u=s?r(t[p],p):t[p],XL(a,p,u);else for(l=(d=QL(t,h)).next,a=i?new this():[];!(c=HL(l,d)).done;p++)u=s?YL(d,r,[c.value,p],!0):c.value,XL(a,p,u);return a.length=p,a;},Nk=wo,Dk=Yu.codeAt,Pk=function(e){var t,i,n=[],r=pk(hk(_k(e),nk,"."),".");for(t=0;t?@[\\\]^|]/,mM=/[\0\t\n\r #/:<>?@[\\\]^|]/,fM=/^[\u0000-\u0020]+/,gM=/(^|[^\u0000-\u0020])[\u0000-\u0020]+$/,TM=/[\t\n\r]/g,SM=function(e){var t,i,n,r;if("number"==typeof e){for(t=[],i=0;i<4;i++)rM(t,e%256),e=Kk(e/256);return Jk(t,".");}if("object"==typeof e){for(t="",n=function(e){for(var t=null,i=1,n=null,r=0,s=0;s<8;s++)0!==e[s]?(r>i&&(t=n,i=r),n=null,r=0):(null===n&&(n=s),++r);return r>i&&(t=n,i=r),t;}(e),i=0;i<8;i++)r&&0===e[i]||(r&&(r=!1),n===i?(t+=i?":":"::",r=!0):(t+=Xk(e[i],16),i<7&&(t+=":")));return "["+t+"]";}return e;},RM={},CM=wk({},RM,{" ":1,'"':1,"<":1,">":1,"`":1}),IM=wk({},CM,{"#":1,"?":1,"{":1,"}":1}),vM=wk({},IM,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),yM=function(e,t){var i=Dk(e,0);return i>32&&i<127&&!bk(t,e)?e:encodeURIComponent(e);},AM={ftp:21,file:null,http:80,https:443,ws:80,wss:443},bM=function(e,t){var i;return 2==e.length&&zk(cM,qk(e,0))&&(":"==(i=qk(e,1))||!t&&"|"==i);},wM=function(e){var t;return e.length>1&&bM(iM(e,0,2))&&(2==e.length||"/"===(t=qk(e,2))||"\\"===t||"?"===t||"#"===t);},OM=function(e){return "."===e||"%2e"===nM(e);},NM={},DM={},PM={},LM={},kM={},MM={},UM={},xM={},VM={},FM={},BM={},jM={},GM={},WM={},HM={},KM={},YM={},qM={},zM={},JM={},XM={},QM=function(e,t,i){var n,r,s,o=Lk(e);if(t){if(r=this.parse(o))throw Wk(r);this.searchParams=null;}else {if(void 0!==i&&(n=new QM(i,!0)),r=this.parse(o,null,n))throw Wk(r);(s=jk(new Bk())).bindURL(this),this.searchParams=s;}};QM.prototype={type:"URL",parse:function(e,t,i){var n,r,s,o,a,c=this,d=t||NM,l=0,u="",h=!1,p=!1,_=!1;for(e=Lk(e),t||(c.scheme="",c.username="",c.password="",c.host=null,c.port=null,c.path=[],c.query=null,c.fragment=null,c.cannotBeABaseURL=!1,e=$k(e,fM,""),e=$k(e,gM,"$1")),e=$k(e,TM,""),n=Ok(e);l<=n.length;){switch(r=n[l],d){case NM:if(!r||!zk(cM,r)){if(t)return sM;d=PM;continue;}u+=nM(r),d=DM;break;case DM:if(r&&(zk(dM,r)||"+"==r||"-"==r||"."==r))u+=nM(r);else {if(":"!=r){if(t)return sM;u="",d=PM,l=0;continue;}if(t&&(c.isSpecial()!=bk(AM,u)||"file"==u&&(c.includesCredentials()||null!==c.port)||"file"==c.scheme&&!c.host))return;if(c.scheme=u,t)return void(c.isSpecial()&&AM[c.scheme]==c.port&&(c.port=null));u="","file"==c.scheme?d=WM:c.isSpecial()&&i&&i.scheme==c.scheme?d=LM:c.isSpecial()?d=xM:"/"==n[l+1]?(d=kM,l++):(c.cannotBeABaseURL=!0,Zk(c.path,""),d=zM);}break;case PM:if(!i||i.cannotBeABaseURL&&"#"!=r)return sM;if(i.cannotBeABaseURL&&"#"==r){c.scheme=i.scheme,c.path=Nk(i.path),c.query=i.query,c.fragment="",c.cannotBeABaseURL=!0,d=XM;break;}d="file"==i.scheme?WM:MM;continue;case LM:if("/"!=r||"/"!=n[l+1]){d=MM;continue;}d=VM,l++;break;case kM:if("/"==r){d=FM;break;}d=qM;continue;case MM:if(c.scheme=i.scheme,r==AL)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=Nk(i.path),c.query=i.query;else if("/"==r||"\\"==r&&c.isSpecial())d=UM;else if("?"==r)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=Nk(i.path),c.query="",d=JM;else {if("#"!=r){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=Nk(i.path),c.path.length--,d=qM;continue;}c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=Nk(i.path),c.query=i.query,c.fragment="",d=XM;}break;case UM:if(!c.isSpecial()||"/"!=r&&"\\"!=r){if("/"!=r){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,d=qM;continue;}d=FM;}else d=VM;break;case xM:if(d=VM,"/"!=r||"/"!=qk(u,l+1))continue;l++;break;case VM:if("/"!=r&&"\\"!=r){d=FM;continue;}break;case FM:if("@"==r){h&&(u="%40"+u),h=!0,s=Ok(u);for(var E=0;E65535)return aM;c.port=c.isSpecial()&&g===AM[c.scheme]?null:g,u="";}if(t)return;d=YM;continue;}return aM;}u+=r;break;case WM:if(c.scheme="file","/"==r||"\\"==r)d=HM;else {if(!i||"file"!=i.scheme){d=qM;continue;}if(r==AL)c.host=i.host,c.path=Nk(i.path),c.query=i.query;else if("?"==r)c.host=i.host,c.path=Nk(i.path),c.query="",d=JM;else {if("#"!=r){wM(Jk(Nk(n,l),""))||(c.host=i.host,c.path=Nk(i.path),c.shortenPath()),d=qM;continue;}c.host=i.host,c.path=Nk(i.path),c.query=i.query,c.fragment="",d=XM;}}break;case HM:if("/"==r||"\\"==r){d=KM;break;}i&&"file"==i.scheme&&!wM(Jk(Nk(n,l),""))&&(bM(i.path[0],!0)?Zk(c.path,i.path[0]):c.host=i.host),d=qM;continue;case KM:if(r==AL||"/"==r||"\\"==r||"?"==r||"#"==r){if(!t&&bM(u))d=qM;else if(""==u){if(c.host="",t)return;d=YM;}else {if(o=c.parseHost(u))return o;if("localhost"==c.host&&(c.host=""),t)return;u="",d=YM;}continue;}u+=r;break;case YM:if(c.isSpecial()){if(d=qM,"/"!=r&&"\\"!=r)continue;}else if(t||"?"!=r){if(t||"#"!=r){if(r!=AL&&(d=qM,"/"!=r))continue;}else c.fragment="",d=XM;}else c.query="",d=JM;break;case qM:if(r==AL||"/"==r||"\\"==r&&c.isSpecial()||!t&&("?"==r||"#"==r)){if(".."===(a=nM(a=u))||"%2e."===a||".%2e"===a||"%2e%2e"===a?(c.shortenPath(),"/"==r||"\\"==r&&c.isSpecial()||Zk(c.path,"")):OM(u)?"/"==r||"\\"==r&&c.isSpecial()||Zk(c.path,""):("file"==c.scheme&&!c.path.length&&bM(u)&&(c.host&&(c.host=""),u=qk(u,0)+":"),Zk(c.path,u)),u="","file"==c.scheme&&(r==AL||"?"==r||"#"==r))for(;c.path.length>1&&""===c.path[0];)eM(c.path);"?"==r?(c.query="",d=JM):"#"==r&&(c.fragment="",d=XM);}else u+=yM(r,IM);break;case zM:"?"==r?(c.query="",d=JM):"#"==r?(c.fragment="",d=XM):r!=AL&&(c.path[0]+=yM(r,RM));break;case JM:t||"#"!=r?r!=AL&&("'"==r&&c.isSpecial()?c.query+="%27":c.query+="#"==r?"%23":yM(r,RM)):(c.fragment="",d=XM);break;case XM:r!=AL&&(c.fragment+=yM(r,CM));}l++;}},parseHost:function(e){var t,i,n;if("["==qk(e,0)){if("]"!=qk(e,e.length-1))return oM;if(t=function(e){var t,i,n,r,s,o,a,c=[0,0,0,0,0,0,0,0],d=0,l=null,u=0,h=function(){return qk(e,u);};if(":"==h()){if(":"!=qk(e,1))return;u+=2,l=++d;}for(;h();){if(8==d)return;if(":"!=h()){for(t=i=0;i<4&&zk(_M,h());)t=16*t+Hk(h(),16),u++,i++;if("."==h()){if(0==i)return;if(u-=i,d>6)return;for(n=0;h();){if(r=null,n>0){if(!("."==h()&&n<4))return;u++;}if(!zk(lM,h()))return;for(;zk(lM,h());){if(s=Hk(h(),10),null===r)r=s;else {if(0==r)return;r=10*r+s;}if(r>255)return;u++;}c[d]=256*c[d]+r,2!=++n&&4!=n||d++;}if(4!=n)return;break;}if(":"==h()){if(u++,!h())return;}else if(h())return;c[d++]=t;}else {if(null!==l)return;u++,l=++d;}}if(null!==l)for(o=d-l,d=7;0!=d&&o>0;)a=c[d],c[d--]=c[l+o-1],c[l+--o]=a;else if(8!=d)return;return c;}(iM(e,1,-1)),!t)return oM;this.host=t;}else if(this.isSpecial()){if(e=Pk(e),zk(EM,e))return oM;if(t=function(e){var t,i,n,r,s,o,a,c=tM(e,".");if(c.length&&""==c[c.length-1]&&c.length--,(t=c.length)>4)return e;for(i=[],n=0;n1&&"0"==qk(r,0)&&(s=zk(uM,r)?16:8,r=iM(r,8==s?1:2)),""===r)o=0;else {if(!zk(10==s?pM:8==s?hM:_M,r))return e;o=Hk(r,s);}Zk(i,o);}for(n=0;n=Yk(256,5-t))return null;}else if(o>255)return null;for(a=Qk(i),n=0;n1?arguments[1]:void 0,n=Vk(t,new QM(e,!1,i));Tk||(t.href=n.serialize(),t.origin=n.getOrigin(),t.protocol=n.getProtocol(),t.username=n.getUsername(),t.password=n.getPassword(),t.host=n.getHost(),t.hostname=n.getHostname(),t.port=n.getPort(),t.pathname=n.getPathname(),t.search=n.getSearch(),t.searchParams=n.getSearchParams(),t.hash=n.getHash());},$M=ZM.prototype,eU=function(e,t){return {get:function(){return Fk(this)[e]();},set:t&&function(e){return Fk(this)[t](e);},configurable:!0,enumerable:!0};};if(Tk&&(yk($M,"href",eU("serialize","setHref")),yk($M,"origin",eU("getOrigin")),yk($M,"protocol",eU("getProtocol","setProtocol")),yk($M,"username",eU("getUsername","setUsername")),yk($M,"password",eU("getPassword","setPassword")),yk($M,"host",eU("getHost","setHost")),yk($M,"hostname",eU("getHostname","setHostname")),yk($M,"port",eU("getPort","setPort")),yk($M,"pathname",eU("getPathname","setPathname")),yk($M,"search",eU("getSearch","setSearch")),yk($M,"searchParams",eU("getSearchParams")),yk($M,"hash",eU("getHash","setHash"))),vk($M,"toJSON",function(){return Fk(this).serialize();},{enumerable:!0}),vk($M,"toString",function(){return Fk(this).serialize();},{enumerable:!0}),Gk){var tU=Gk.createObjectURL,iU=Gk.revokeObjectURL;tU&&vk(ZM,"createObjectURL",Ck(tU,Gk)),iU&&vk(ZM,"revokeObjectURL",Ck(iU,Gk));}kk(ZM,"URL"),gk({global:!0,constructor:!0,forced:!Sk,sham:!Tk},{URL:ZM});var nU=wi,rU=n,sU=H_,oU=pn,aU=lP,cU=ae("URL");nU({target:"URL",stat:!0,forced:!(aU&&rU(function(){cU.canParse();}))},{canParse:function(e){var t=sU(arguments.length,1),i=oU(e),n=t<2||void 0===arguments[1]?void 0:oU(arguments[1]);try{return !!new cU(i,n);}catch(e){return !1;}}});var dU=i(ie.URL);function lU(){const e=new Blob([atob("ZnVuY3Rpb24gZShlKXtjb25zdCB0PW5ldyBEYXRhVmlldyhlLmRhdGEpO2lmKDA9PT10LmdldFVpbnQ4KDApJiYwPT09dC5nZXRVaW50OCgxKSYmMD09PXQuZ2V0VWludDgoMikmJjE9PT10LmdldFVpbnQ4KDMpJiY2PT09dC5nZXRVaW50OCg0KSl7bGV0IG49NixyPTAsbz0wO2Zvcig7MjU1PT09KG89dC5nZXRVaW50OChuKyspKTspcis9MjU1O3IrPW87Y29uc3QgYT1mdW5jdGlvbihlLHQsbil7bGV0IHI9bmV3IFVpbnQ4QXJyYXkoZSx0LG4pLG89W10sYT0wO2Zvcig7YTxuOylhKzM8biYmMD09PXJbYV0mJjA9PT1yW2ErMV0mJjM9PT1yW2ErMl0mJigwPT09clthKzNdfHwxPT09clthKzNdfHwyPT09clthKzNdfHwzPT09clthKzNdKT8oby5wdXNoKHJbYV0sclthKzFdLHJbYSszXSksYSs9NCk6KG8ucHVzaChyW2FdKSxhKyspO3JldHVybiBuZXcgVWludDhBcnJheShvKX0oZS5kYXRhLG4scik7cmV0dXJuIG5ldyBVaW50OEFycmF5KGEpfXJldHVybiBudWxsfWZ1bmN0aW9uIHQoZSx0KXtjb25zdCBuPWZ1bmN0aW9uKGUpe2NvbnN0IHQ9ZS5sZW5ndGg7bGV0IG49W10scj0wO2Zvcig7cjx0OylyKzI8dCYmMD09PWVbcl0mJjA9PT1lW3IrMV0mJigwPT09ZVtyKzJdfHwxPT09ZVtyKzJdfHwyPT09ZVtyKzJdfHwzPT09ZVtyKzJdKT8obi5wdXNoKGVbcl0sZVtyKzFdLDMsZVtyKzJdKSxyKz0zKToobi5wdXNoKGVbcl0pLHIrKyk7cmV0dXJuIG5ldyBVaW50OEFycmF5KG4pfSh0KSxyPW4ubGVuZ3RoLG89TWF0aC5mbG9vcihyLzI1NSksYT1yJTI1NSxzPW5ldyBVaW50OEFycmF5KDYrbysxK3IrZS5ieXRlTGVuZ3RoKTtzWzBdPTAsc1sxXT0wLHNbMl09MCxzWzNdPTEsc1s0XT02LHNbNV09MTAxO2xldCBpPTA7Zm9yKDtpPG87KXNbNitpXT0yNTUsaSsrO3JldHVybiBzWzYraV09YSxpKysscy5zZXQobiw2K2kpLHMuc2V0KG5ldyBVaW50OEFycmF5KGUpLDYraStyKSxzLmJ1ZmZlcn1uYXZpZ2F0b3IudXNlckFnZW50LmluZGV4T2YoIlNhZmFyaSIpPi0xJiYtMT09PW5hdmlnYXRvci51c2VyQWdlbnQuaW5kZXhPZigiQ2hyb21lIikmJihzZWxmLm9ucnRjdHJhbnNmb3JtPW49Pntjb25zdCByPW4udHJhbnNmb3JtZXI7bGV0IG89W107ci5vcHRpb25zLnBvcnQub25tZXNzYWdlPWU9PntlLmRhdGEuc2VpJiZvLnB1c2goZS5kYXRhLnNlaSl9LHNlbGYucG9zdE1lc3NhZ2UoInN0YXJ0ZWQiKTtjb25zdCBhPXIucmVhZGFibGUuZ2V0UmVhZGVyKCkscz1yLndyaXRhYmxlLmdldFdyaXRlcigpOyJyeCI9PT1yLm9wdGlvbnMubmFtZT9mdW5jdGlvbiB0KG4pe2EucmVhZCgpLnRoZW4oKHI9PntpZighci5kb25lKXtpZihyLnZhbHVlIGluc3RhbmNlb2YgUlRDRW5jb2RlZFZpZGVvRnJhbWUpe2NvbnN0IHQ9ZShyLnZhbHVlKTt0JiZuLm9wdGlvbnMucG9ydC5wb3N0TWVzc2FnZSh7c2VpOnR9KX1zLndyaXRlKHIudmFsdWUpLG4ub3B0aW9ucy5wb3J0LnBvc3RNZXNzYWdlKHt0cmFuc2Zvcm1lZDohMH0pLHQobil9fSkpfShyKToidHgiPT09ci5vcHRpb25zLm5hbWUmJmZ1bmN0aW9uIGUobil7YS5yZWFkKCkudGhlbigocj0+e2lmKCFyLmRvbmUpe2lmKHIudmFsdWUgaW5zdGFuY2VvZiBSVENFbmNvZGVkVmlkZW9GcmFtZSl7Y29uc3QgZT1vLnNoaWZ0KCk7ZSYmKHIudmFsdWUuZGF0YT10KHIudmFsdWUuZGF0YSxlKSl9cy53cml0ZShyLnZhbHVlKSxuLm9wdGlvbnMucG9ydC5wb3N0TWVzc2FnZSh7dHJhbnNmb3JtZWQ6ITB9KSxlKG4pfX0pKX0ocil9LHNlbGYucG9zdE1lc3NhZ2UoInJlZ2lzdGVyZWQiKSk7Cg==")],{type:"text/javascript"});return setTimeout(()=>dU.revokeObjectURL(e),0),new Worker(dU.createObjectURL(e));}const uU=new Map();const hU=new Map();async function pU(e){if(!IA().supportWebRTCEncodedTransform)return void jC.warning("browser not support audio encoded transform");if(hU.has(e))return;const t={track:e.track};if(Ag()){if(!e.createEncodedStreams)return void jC.warning("browser not support createEncodedStreams() API");let n=null;try{n=e.createEncodedStreams();}catch(e){return void jC.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&&(jC.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(bg()){if("undefined"==typeof RTCRtpScriptTransform)return void jC.warning("browser not support RTCRtpScriptTransform");const n=lU(),r=new MessageChannel();await new cg(e=>n.onmessage=t=>{"registered"===t.data&&e(void 0);});const s=new RTCRtpScriptTransform(n,{name:"rx",port:r.port2},[r.port2]);e.transform=s,await new cg(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&&(jC.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=hU.get(e);if(t){hU.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){jC.warning(e&&e.message);}}}(e);}hU.set(e,t),e.track.addEventListener("ended",i);}function _U(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 s=function(e,t,i){let n=new Uint8Array(e,t,i),r=[],s=0;for(;s1&&void 0!==arguments[1]?arguments[1]:{};if(!IA().supportWebRTCEncodedTransform)return void jC.warning("browser not support video encoded transform");if(!e.track)return;if(fU.has(e)){const i=fU.get(e);return void(i&&(i.onSei=t.onSei));}const i={track:e.track,onSei:t.onSei};if(Ag()){if(!e.createEncodedStreams)return void jC.warning("browser not support createEncodedStreams() API");let t=null;try{t=e.createEncodedStreams();}catch(e){return void jC.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&&(jC.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=_U(t);s&&i.onSei&&i.onSei(s),r.enqueue(t);}});t.readable.pipeThrough(r).pipeTo(t.writable);}else if(bg()){if("undefined"==typeof RTCRtpScriptTransform)return void jC.warning("browser not support RTCRtpScriptTransform");const t=lU(),r=new MessageChannel();await new cg(e=>t.onmessage=t=>{"registered"===t.data&&e(void 0);});const s=new RTCRtpScriptTransform(t,{name:"rx",port:r.port2},[r.port2]);e.transform=s,await new cg(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?(jC.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=fU.get(e);if(t){fU.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){jC.warning(e&&e.message);}}}(e);}fU.set(e,i),e.track.addEventListener("ended",n);}!function(){const e=Sg();CA.getDisplayMedia=function(e){if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)return !0;return !1;}(),CA.getStreamFromExtension=e.name===Eg.CHROME&&Number(e.version)>34,CA.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;}(),CA.supportMinBitrate=e.name===Eg.CHROME||e.name===Eg.EDGE,CA.supportSetRtpSenderParameters=function(){const e=Sg();if(!window.RTCRtpSender||!window.RTCRtpSender.prototype.setParameters||!window.RTCRtpSender.prototype.getParameters)return !1;return !!jg()||!(!bg()&&!Ig())||e.name===Eg.FIREFOX&&Number(e.version)>=64;}(),e.name===Eg.SAFARI&&(Number(e.version)>=14?CA.supportDualStream=!0:CA.supportDualStream=!1),CA.webAudioMediaStreamDest=function(){const e=Sg();if(e.name===Eg.SAFARI&&Number(e.version)<12)return !1;return !0;}(),CA.supportReplaceTrack=function(){if(!window.RTCRtpSender)return !1;if("function"==typeof RTCRtpSender.prototype.replaceTrack)return !0;return !1;}(),CA.supportWebGL="undefined"!=typeof WebGLRenderingContext,CA.supportRequestFrame=!!window.CanvasCaptureMediaStreamTrack,jg()||(CA.webAudioWithAEC=!0),CA.supportShareAudio=function(){const e=Sg();if((e.os===_g.WIN_10||e.os===_g.WIN_81||e.os===_g.WIN_7||e.os===_g.LINUX||e.os===_g.MAC_OS||e.os===_g.CHROMIUM_OS)&&e.name===Eg.CHROME&&Number(e.version)>=74)return !0;return !1;}(),CA.supportDataChannel=function(){if(Ng(76)||function(e){const t=Sg();return !(t.name!==Eg.FIREFOX||!t.osVersion)&&Number(t.version)>=e;}(68)||function(e){const t=Sg();return !(t.name!==Eg.SAFARI||!t.osVersion)&&Number(t.version)>=e;}(14))return !0;return !1;}(),CA.supportPCSetConfiguration=function(){const e=window.RTCPeerConnection;return !wg()&&!!e&&e.prototype.setConfiguration instanceof Function;}(),CA.supportWebRTCEncodedTransform=function(){const e=Sg();return "Chrome"===e.name&&Number(e.version)>=86||"Safari"===e.name&&Number(e.version)>=15;}(),CA.supportWebRTCInsertableStream=function(){const e=Sg();return (e.name===Eg.CHROME||e.name===Eg.EDGE)&&Number(e.version)>=94&&"MediaStreamTrackGenerator"in window&&"MediaStreamTrackProcessor"in window;}(),KT(()=>{CA.supportDualStreamEncoding=function(){const e=Sg();if(RC("DISABLE_WEBAUDIO"))return !0;return "Safari"===e.name&&Number(e.version)>=14||!!("Chrome"===e.name&&/Windows/i.test(e.os||"")&&Number(e.version)>=100&&RC("CHROME_DUAL_STREAM_USE_ENCODING"));}(),jC.info("browser compatibility",JSON.stringify(CA),JSON.stringify(e));});}();class TU extends dT{constructor(){super(...arguments),sh(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(RC("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=bn(r=n.result).call(r,!0);n.isPrevNormal&&!i&&this.emit("exception",SU[e],e,t),!n.isPrevNormal&&i&&this.emit("exception",SU[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 nw&&!t.isActive||!!t.muted||0!==e.sendVolumeLevel;}checkFramerateInput(e,t){let i=null;t._encoderConfig&&t._encoderConfig.frameRate&&(i=Sy(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 nw&&!t.isActive||!!t.muted||0!==e.sendBitrate;}checkVideoDecode(e){return 0===e.receiveBitrate||0!==e.decodeFrameRate;}}const SU={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 RU=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 CU(e,t){this.v=e,this.k=t;}function IU(e){return new CU(e,0);}var vU=ag,yU=um;wi({target:"Promise",stat:!0,forced:!0},{withResolvers:function(){var e=yU.f(this);return {promise:e.promise,resolve:e.resolve,reject:e.reject};}});var AU=um,bU=YE;wi({target:"Promise",stat:!0,forced:!0},{try:function(e){var t=AU.f(this),i=bU(e);return (i.error?t.reject:t.resolve)(i.value),t.promise;}});var wU=i(vU),OU=Fo.f("asyncIterator"),NU=i(OU);function DU(e){var t,i;function n(t,i){try{var s=e[t](i),o=s.value,a=o instanceof CU;wU.resolve(a?o.v:o).then(function(i){if(a){var c="return"===t?"return":"next";if(!o.k||i.done)return n(c,i);i=e[c](i).value;}r(s.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 wU(function(s,o){var a={key:e,arg:r,resolve:s,reject:o,next:null};i?i=i.next=a:(t=i=a,n(e,r));});},"function"!=typeof e.return&&(this.return=void 0);}function PU(e){return function(){return new DU(e.apply(this,arguments));};}DU.prototype["function"==typeof xu&&NU||"@@asyncIterator"]=function(){return this;},DU.prototype.next=function(e){return this._invoke("next",e);},DU.prototype.throw=function(e){return this._invoke("throw",e);},DU.prototype.return=function(e){return this._invoke("return",e);};var LU=i(ie.Object.getOwnPropertySymbols),kU=wi,MU=Ki.indexOf,UU=Ih,xU=v([].indexOf),VU=!!xU&&1/xU([1],1,-0)<0;kU({target:"Array",proto:!0,forced:VU||!UU("indexOf")},{indexOf:function(e){var t=arguments.length>1?arguments[1]:void 0;return VU?xU(this,e,t)||0:MU(this,e,t);}});var FU=zi("Array").indexOf,BU=l,jU=FU,GU=Array.prototype,WU=i(function(e){var t=e.indexOf;return e===GU||BU(GU,e)&&t===GU.indexOf?jU:t;}),HU=Je,KU=Ys;wi({target:"Object",stat:!0,forced:n(function(){KU(1);})},{keys:function(e){return KU(HU(e));}});var YU=i(ie.Object.keys);function qU(e,t){if(null==e)return {};var i,n,r=function(e,t){if(null==e)return {};var i,n,r={},s=YU(e);for(n=0;n=0||(r[i]=e[i]);return r;}(e,t);if(LU){var s=LU(e);for(n=0;n=0||Object.prototype.propertyIsEnumerable.call(e,i)&&(r[i]=e[i]);}return r;}var zU={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),s=" ";let o;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 u(e){return e>="1"&&e<="9";}function h(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>""&&e<"\t"||e>"\v"&&e<"\f"||e>""&&e<"ÿ";}function E(e){return h(e)||a(e)||"+"===e||"/"===e;}function m(e){return a(e)||h(e)||"+"===e||"/"===e||"-"===e||"_"===e;}function f(e){return h(e)||a(e)||"+"===e||"/"===e;}function g(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 T(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])||h(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(!u(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(!u(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(u(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,s);}consumeTypedTime(e,t){let i=t;return i=this.consumeOneOrMore(e,i,a),p(e[i])?i+1:i;}consumeRepeatInterval(e,t){if(!u(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!!e.trim()).map(this.parseLine),this.currentLine=0;const i=this.parseVersion(),n=this.parseOrigin(),r=this.parseSessionName(),s=this.parseInformation(),o=this.parseUri(),a=this.parseEmail(),c=this.parsePhone(),d=this.parseConnection(),l=this.parseBandWidth(),u=this.parseTimeFields(),h=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:s,uri:o,emails:a,phones:c,connection:d,bandwidths:l,timeFields:u,key:h,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 v();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===o.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===o.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!==o.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.currentLineo)throw new Error("error in length, should be less or equal than ".concat(o," characters."));return e._cur=n,r;}consumeAttributeSpace(e){if(e.attValue[e._cur]!==s)throw new Error("Invalid space at ".concat(e._cur,"."));e._cur+=1;}extract(e,t,...i){if(!e.attValue)throw new Error("Nothing to extract from attValue.");const n=t.call(this,e.attValue,e._cur,...i),r=e.attValue.slice(e._cur,n);return e._cur=n,r;}atEnd(e){if(!e.attValue)throw new Error();return e._cur>=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!==s&&_(e));i.push({name:t,value:n});}this.attributes.identities.push({assertionValue:t,extensions:i});}parseMsidSemantic(e){this.peekChar(e)===s&&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,s);t.identifierList.push(i);}}this.attributes.msidSemantic=t;}}class y extends I{constructor(e){super(),S(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 o=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:o,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)===s;){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,s);this.consumeAttributeSpace(e);const i=this.extract(e,this.consumeTill),n={};i.split(";").forEach(e=>{let[t,i]=e.split("=");t=t.trim();const r="string"==typeof i?i.trim():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,s),this.consumeAttributeSpace(e);const i=this.extract(e,this.consumeTill,s);let n;if("trr-int"===i)n={type:i,interval:this.extract(e,this.consumeTill)};else {const t={type:i};this.peekChar(e)===s&&(this.consumeAttributeSpace(e),t.parameter=this.extract(e,this.consumeToken),this.peekChar(e)===s&&(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)===s&&(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)===s&&(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=>h(e)||a(e)||"_"===e||"-"===e);this.consumeAttributeSpace(e);const i={id:t,direction:this.extract(e,this.consumeToken),params:[]};if(this.peekChar(e)===s){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)===s&&this.extract(e,this.consume,s);}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(s)).concat(this.eol);}printFingerprints(e){return e.length>0?e.map(e=>"a=fingerprint:".concat(e.hashFunction).concat(s).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(s).concat(e.extensionName).concat(e.extensionAttributes?"".concat(s).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(s).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(s).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(s,"*"):e.identifierList.length>0&&(t+=e.identifierList.map(e=>"".concat(s).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(s).concat(e.componentId).concat(s).concat(e.transport).concat(s).concat(e.priority).concat(s).concat(e.connectionAddress).concat(s).concat(e.port).concat(s,"typ").concat(s).concat(e.type).concat(e.relAddr?"".concat(s,"raddr").concat(s).concat(e.relAddr):"").concat(e.relPort?"".concat(s,"rport").concat(s).concat(e.relPort):"").concat(Object.keys(e.extension).map(t=>"".concat(s).concat(t).concat(s).concat(e.extension[t])).join("")).concat(this.eol)).join("");}printRemoteCandidatesList(e){return e.map(e=>"a=remote-candidates:".concat(e.join(s)).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(s).concat(i[0]).concat(this.eol):"a=fmtp:".concat(e).concat(s).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(s).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(s),n=t;return "trr-int"===n.type?i+="ttr-int".concat(s).concat(n.interval):(i+="".concat(n.type),n.parameter&&(i+="".concat(s).concat(n.parameter),n.additional&&(i+="".concat(s).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(s).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(s).concat(e.netType)),e.addressType&&(t+="".concat(s).concat(e.addressType)),e.address&&(t+="".concat(s).concat(e.address)),t+this.eol;}printMSId(e){return e.map(e=>"a=msid:".concat(e.id).concat(e.appdata?"".concat(s).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(s).concat(e.direction);return e.payloads&&(t+="".concat(s,"pt=").concat(e.payloads.join(","))),e.params.length>0&&(t+="".concat(s).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(s).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);})();}(zU);var JU=zU.exports;function XU(e){if(Array.isArray(e))return e.map(e=>e);if(!QU(e))return e;const t={};for(const i in e){const n=e[i];QU(n)||Array.isArray(n)?t[i]=XU(n):t[i]=n;}return t;}function QU(e){return !("object"!=typeof e||Array.isArray(e)||!e);}class ZU{constructor(e){sh(this,"input",[]),sh(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 $U={address:"unknown",candidateType:"unknown",id:"unknown",port:0,priority:0,protocol:"unknown",type:"unknown"},ex={timestamp:0,bitrate:{actualEncoded:0,transmit:0},sendPacketLossRate:0,recvPacketLossRate:0,videoRecv:[],videoSend:[],audioRecv:[],audioSend:[],selectedCandidatePair:{id:"unknown",localCandidate:$U,remoteCandidate:$U}},tx={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},ix={firsCount:0,nacksCount:0,plisCount:0,frameCount:0,bytes:0,packets:0,packetsLost:0,packetLostRate:0,ssrc:0,rttMs:0,jitterMs:0,qpSumPerFrame:0},nx={bytes:0,packets:0,packetsLost:0,packetLostRate:0,ssrc:0,rttMs:0,jitterMs:0},rx={jitterBufferMs:0,jitterMs:0,bytes:0,packetsLost:0,packetLostRate:0,packets:0,ssrc:0,receivedFrames:0,droppedFrames:0,concealedSamples:0};function sx(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 ox(e){for(var t=1;t{this.updateStats();},this.options.updateInterval);}getStats(){return this.stats;}getSelectedCandidatePair(){return new cg(e=>{e({local:ox({},$U),remote:ox({},$U)});});}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,s=0,o=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,s+=d):(r+=c,o+=d),Number.isNaN(c)||Number.isNaN(c)?e.packetLostRate=0:e.packetLostRate=c<=0||d<=0?0:d/(c+d);});e.sendPacketLossRate=n<=0||s<=0?0:s/(n+s),e.recvPacketLossRate=r<=0||o<=0?0:o/(r+o);}}function cx(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 dx(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=bn(t=e.id).call(t,"send");switch("".concat(e.mediaType,"_").concat(i?"send":"recv")){case"video_send":{const t=XU(ix);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=XU(tx),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=XU(nx);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 cg((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 ux(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 hx(e){for(var t=1;t{switch(e.type){case aI.OUTBOUND:case aI.INBOUND:{const t=e.mediaType||e.kind,i=!t&&"frameWidth"in e,n=!t&&!("frameWidth"in e);e.type===aI.OUTBOUND?"audio"===t||n?this.processAudioOutboundStats(e):("video"===t||i)&&this.processVideoOutboundStats(e):e.type===aI.INBOUND&&("audio"===t||n?this.processAudioInboundStats(e):("video"===t||i)&&this.processVideoInboundStats(e));break;}case aI.TRANSPORT:{const t=this.report.get(e.selectedCandidatePairId);t&&this.processCandidatePairStats(t);break;}case aI.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:hx({},$U),remote:hx({},$U)};return e.forEach(i=>{let n;if(i.type===aI.TRANSPORT&&(n=e.get(i.selectedCandidatePairId)),i.type===aI.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===aI.LOCAL_CANDIDATE&&(t=this._stats.selectedCandidatePair.localCandidate),e.type===aI.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===aI.LOCAL_CANDIDATE&&this.stats.selectedCandidatePair.localCandidate.id!==t.id&&this.onSelectedLocalCandidateChanged&&this.onSelectedLocalCandidateChanged(hx({},t),hx({},this.stats.selectedCandidatePair.localCandidate)),e.type===aI.REMOTE_CANDIDATE&&this.stats.selectedCandidatePair.remoteCandidate.id!==t.id&&this.onSelectedRemoteCandidateChanged&&this.onSelectedRemoteCandidateChanged(hx({},t),hx({},this.stats.selectedCandidatePair.remoteCandidate)));}processAudioInboundStats(e){let t=this._stats.audioRecv.find(t=>t.ssrc===e.ssrc);t||(t=XU(rx),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=XU(tx),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.totalInterFrameDelay=e.totalInterFrameDelay,t.totalSquaredInterFrameDelay=e.totalSquaredInterFrameDelay;const i=this.lastDecodeVideoReceiverStats.get(t.ssrc),n=this.lastVideoFramesDecode.get(t.ssrc),r=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,s=r-i.lts;t.framesDecodeFreezeTime=n.framesDecodeFreezeTime,t.framesDecodeInterval=n.framesDecodeInterval,!this.isFirstVideoDecoded[t.ssrc]&&s>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=s,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&&r-n.lts>=800?(t.decodeFrameRate=Math.round((t.framesDecodeCount-n.count)/((r-n.lts)/1e3)),this.lastVideoFramesDecode.set(t.ssrc,{count:t.framesDecodeCount,lts:r,rate:t.decodeFrameRate})):n?t.decodeFrameRate=n.rate:this.lastVideoFramesDecode.set(t.ssrc,{count:t.framesDecodeCount,lts:r,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:hx({},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=XU(ix),this._stats.videoSend.push(t));const i=this.mediaBytesSent.get(e.ssrc);if(i)i.add(e.bytesSent);else {const t=new ZU(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 ZU(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 ZU(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,aI.REMOTE_INBOUND);i&&this.processRemoteInboundStats(i,t);}}processAudioOutboundStats(e){let t=this._stats.audioSend.find(t=>t.ssrc===e.ssrc);if(t||(t=XU(nx),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,aI.REMOTE_INBOUND);i&&this.processRemoteInboundStats(i,t);}}findRemoteStatsId(e,t){var i;const n=Array.from(NI(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,s,o;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!==(s=null==a?void 0:a.frameHeight)&&void 0!==s?s:e.frameHeight,u=null!==(o=null==a?void 0:a.framesPerSecond)&&void 0!==o?o:e.framesPerSecond;if("number"==typeof d&&"number"==typeof l||(d=0,l=0),null==u){const e=Date.now(),t=this.lastVideoFramesSent.get(i.ssrc);t&&e-t.lts>=800?(u=Math.round((c-t.count)/((e-t.lts)/1e3)),this.lastVideoFramesSent.set(i.ssrc,{count:c,lts:e,rate:u})):t?u=t.rate:this.lastVideoFramesSent.set(i.ssrc,{count:c,lts:e,rate:0});}i.sentFrame={width:d,height:l,frameRate:Math.max(0,u)};}processVideoTrackReceiverStats(e,t,i){var n,r,s,o,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,u=null!==(s=null==c?void 0:c.frameHeight)&&void 0!==s?s:e.frameHeight,h=null!==(o=null==c?void 0:c.jitterBufferDelay)&&void 0!==o?o: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:u||0,frameRate:n||0},i.decodedFrame={width:l||0,height:u||0,frameRate:i.decodeFrameRate||0},i.outputFrame={width:l||0,height:u||0,frameRate:i.decodeFrameRate||0};}if(h&&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*(h-e.jitterBufferDelay)/n),i.jitterBufferMs=t,i.currentDelayMs=Math.round(t),this.lastVideoJBDelay.set(i.ssrc,{jitterBufferDelay:h,jitterBufferEmittedCount:p,jitterBufferMs:i.currentDelayMs});}}processAudioTrackSenderStats(e,t,i){var n,r,s,o;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!==(s=null!==(o=null==a?void 0:a.echoReturnLossEnhancement)&&void 0!==o?o:e.echoReturnLossEnhancement)&&void 0!==s?s:0;i.aecReturnLoss=c,i.aecReturnLossEnhancement=d;}processAudioTrackReceiverStats(e,t,i){var n,r,s,o,a,c,d;const l=t?this.report.get(t):void 0,u=null!==(n=null==l?void 0:l.removedSamplesForAcceleration)&&void 0!==n?n:e.removedSamplesForAcceleration,h=null!==(r=null==l?void 0:l.totalSamplesReceived)&&void 0!==r?r:e.totalSamplesReceived,p=null!==(s=null==l?void 0:l.jitterBufferDelay)&&void 0!==s?s:e.jitterBufferDelay,_=null!==(o=null==l?void 0:l.jitterBufferEmittedCount)&&void 0!==o?o: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(u&&h&&(i.accelerateRate=u/h),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 g=1920;m&&h&&(g=h/m/50,i.receivedFrames=Math.round(h/g)),f&&(i.droppedFrames=Math.round(f/g));}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 _x extends ax{updateStats(){return cg.resolve();}}function Ex(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 s=function(){const e=navigator.userAgent.toLocaleLowerCase().match(/chrome\/[\d]*/i);return e&&e[0]?Number(e[0].split("/")[1]):null;}();return s?s<76?new lx(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:n,firstVideoDecodedTimeout:r}):new px(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:n,firstVideoDecodedTimeout:r}):function(e){return !!window.RTCStatsReport&&e.getStats()instanceof cg;}(e)?new px(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:n,firstVideoDecodedTimeout:r}):new _x(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:n,firstVideoDecodedTimeout:r});}function mx(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 fx(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:s,filterAudioFec:o,filterAudioCodec:a,filterVideoCodec:c}=t,{useXR:d}=i;let l=[],u=[],h=[],p=[],_=!1,E=!1;if(JU.parse(e).mediaDescriptions.forEach(e=>{n&&n!==e.attributes.direction||("video"!==e.media.mediaType||_||(u=e.attributes.payloads,p=e.attributes.extmaps,_=!0),"audio"!==e.media.mediaType||E||(l=e.attributes.payloads,h=e.attributes.extmaps,E=!0));}),!p||0===u.length)throw new Error("Cannot get video capabilities from SDP.");if(!h||0===l.length)throw new Error("Cannot get audio capabilities from SDP.");u.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());}),u=u.filter(e=>{var t;return "rtx"!==(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase());})),s&&(u=u.filter(e=>{var t;return !/(red)|(ulpfec)|(flexfec)/i.test((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName)||"");})),o&&(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 bn(a).call(a,(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())||"");})),c&&(null==c?void 0:c.length)>0&&(u=u.filter(e=>{var t;return bn(c).call(c,(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())||"");}));const m=RC("UNSUPPORTED_VIDEO_CODEC");return m&&m.length>0&&(u=u.filter(e=>!(e.rtpMap&&bn(m).call(m,e.rtpMap.encodingName.toLowerCase())))),{audioCodecs:l,videoCodecs:u,audioExtensions:h,videoExtensions:p};}function Tx(e){const t=JU.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 Sx(e,t){const i=[],n=e.attributes.ssrcGroups.filter(e=>"FID"===e.semantic),r=e.attributes.ssrcGroups.find(e=>"SIM"===e.semantic),s=e.attributes.ssrcs;if(r)r.ssrcIds.forEach(e=>{var r;const s=null===(r=n.find(t=>t.ssrcIds[0]===e))||void 0===r?void 0:r.ssrcIds[1];i.push({ssrcId:e,rtx:t?s: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===s.length)throw new Error("No ssrcs found on local media description.");i.push({ssrcId:s[0].ssrcId});}return i;}function Rx(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:{}}],jC.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:{}}),jC.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}))},s={iceUfrag:e.iceParameters.iceUfrag,icePwd:e.iceParameters.icePwd};let o;switch(e.dtlsParameters.role){case"server":o="passive";break;case"client":o="active";break;case"auto":o="actpass";}return {dtlsParameters:r,iceParameters:s,candidates:n,rtpCapabilities:Px(e.rtpCapabilities),setup:o,cname:i};}function Cx(e,t,i){const n=[],r=[];return e.forEach(e=>{let{ssrcId:s,rtx:o}=e;const a=nS(8,"track-"),c={ssrcId:s,attributes:fx({label:a,mslabel:i=i||nS(10,""),msid:"".concat(i," ").concat(a)},t&&{cname:t})};if(n.push(c),void 0!==o){const e={ssrcId:o,attributes:fx({label:a,mslabel:i,msid:"".concat(i," ").concat(a)},t&&{cname:t})};n.push(e),r.push({semantic:"FID",ssrcIds:[s,o]});}}),e.length>1&&r.push({semantic:"SIM",ssrcIds:e.map(e=>{let{ssrcId:t}=e;return t;})}),{ssrcs:n,ssrcGroups:r};}function Ix(e,t){t instanceof ew&&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&&!wg()&&(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 vx(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 yx(e,t){var i;if(!(t instanceof Rw&&t._encoderConfig&&-1===t._hints.indexOf(jA.SCREEN_TRACK)))return;const n=t._encoderConfig;IA().supportMinBitrate&&n.bitrateMin&&e.attributes.payloads.forEach(e=>{var t,i;bn(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));}),IA().supportMinBitrate&&!bn(i=t._hints).call(i,jA.LOW_STREAM)&&n.bitrateMax&&e.attributes.payloads.forEach(e=>{var t,i;bn(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(RC("X_GOOGLE_START_BITRATE")||Math.floor(n.bitrateMax)));});}function Ax(e){if("video"!==e.media.mediaType)return;const t=Sg();if(t.name!==Eg.SAFARI&&t.os!==_g.IOS)return;const i=e.attributes.extmaps.findIndex(e=>/video-orientation/g.test(e.extensionName));-1!==i&&e.attributes.extmaps.splice(i,1);}function bx(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 wx(e,t,i){if(wg())return;if("video"!==e.media.mediaType)return;if(!(t instanceof Rw))return;if("vp9"!==i&&"vp8"!==i)return;if("vp8"===i&&!RC("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],s=e.attributes.ssrcGroups.find(e=>"FID"===e.semantic&&e.ssrcIds[0]===r.ssrcId),o={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:s,sendrecv:o}=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=gx(i,e,t,"sendonly"),r=gx(i,e,t,"recvonly"),s={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},o={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},a={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]};if(Dx(n,r,"videoExtensions",s,o,a),Dx(n,r,"videoCodecs",s,o,a),Dx(n,r,"audioExtensions",s,o,a),Dx(n,r,"audioCodecs",s,o,a),RC("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&&RC("FILTER_SEND_H264_BASELINE")&&(s.videoCodecs=s.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:s,recv:o,sendrecv:a};}(e,t,n);try{i.close();}catch(e){}return {send:r,recv:s,sendrecv:o};}function Nx(){const e={audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]},t=gx(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(Dx(e,t,"videoExtensions",i,n,r),Dx(e,t,"videoCodecs",i,n,r),Dx(e,t,"audioExtensions",i,n,r),Dx(e,t,"audioCodecs",i,n,r),RC("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 Dx(e,t,i,n,r,s){if("videoExtensions"===i||"audioExtensions"===i){const o=[];return e[i].forEach(e=>{t[i].some((t,i)=>{if(e.entry===t.entry&&e.extensionName===t.extensionName)return o.push(i),!0;})?s[i].push(e):n[i].push(e);}),void t[i].forEach((e,t)=>{-1===o.indexOf(t)&&r[i].push(e);});}if("videoCodecs"===i||"audioCodecs"===i){const o=[];return e[i].forEach(e=>{t[i].some((t,i)=>{if(e.payloadType===t.payloadType&&JSON.stringify(e)===JSON.stringify(t))return o.push(i),!0;})?s[i].push(e):n[i].push(e);}),void t[i].forEach((e,t)=>{-1===o.indexOf(t)&&r[i].push(e);});}}function Px(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,s;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?(s={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},s.audioCodecs=[...i.audioCodecs,...n.audioCodecs],s.videoCodecs=[...i.videoCodecs,...n.videoCodecs],s.audioExtensions=[...i.audioExtensions,...n.audioExtensions],s.videoExtensions=[...i.videoExtensions,...n.videoExtensions]):s=n,{send:r,recv:s};}function Lx(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 kx(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 Mx(e,t,i,n){let r=[];if(e===av.VIDEO){if(RC("H264_PROFILE_LEVEL_ID")&&"h264"===n&&(r=t.videoCodecs.filter(e=>{var t;return bn(t=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").call(t,n)&&e&&e.fmtp&&e.fmtp.parameters["profile-level-id"]===RC("H264_PROFILE_LEVEL_ID");})),!Array.isArray(r)||0===r.length){let e=[];const s=[],o=[];i.videoCodecs.forEach(t=>{var i,r,a;bn(i=t.rtpMap&&t.rtpMap.encodingName.toLowerCase()||"").call(i,n)&&e.push(t),bn(r=t.rtpMap&&t.rtpMap.encodingName.toLowerCase()||"").call(r,"vp8")&&s.push(t),bn(a=t.rtpMap&&t.rtpMap.encodingName.toLowerCase()||"").call(a,"h264")&&o.push(t);}),0===e.length&&(0!==s.length?(e=s,jC.warning("codec ".concat(n," not included in rtpCapabilities, fallback to default payloads: vp8"))):0!==o.length&&(e=o,jC.warning("codec ".concat(n," not included in rtpCapabilities, fallback to default payloads: h264")))),0!==e.length&&(r=t.videoCodecs.filter(t=>e.some(e=>e.payloadType===t.payloadType)));}if(RC("USE_PUB_RTX")){const e=r.map(e=>e.payloadType.toString()),i=t.videoCodecs.filter(t=>t.rtpMap&&"rtx"===t.rtpMap.encodingName&&bn(e).call(e,t.fmtp&&t.fmtp.parameters.apt||""));r=[...r,...i];}0===r.length&&(jC.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);}else r=t.audioCodecs.filter(e=>{var t;return bn(t=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").call(t,n);}),0===r.length&&(jC.warning("codec ".concat(n," not included in rtpCapabilities, fallback to opus")),r=t.audioCodecs.filter(e=>{var t;return bn(t=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").call(t,"opus");}));return r;}let Ux=class{get localCapabilities(){return YT(this._localCapabilities);}get rtpCapabilities(){return YT(this._rtpCapabilities);}get candidates(){return YT(this._candidates);}get iceParameters(){return YT(this._iceParameters);}get dtlsParameters(){return YT(this._dtlsParameters);}constructor(e){sh(this,"sessionDesc",void 0),sh(this,"_localCapabilities",void 0),sh(this,"_rtpCapabilities",void 0),sh(this,"_candidates",void 0),sh(this,"_iceParameters",void 0),sh(this,"_dtlsParameters",void 0),sh(this,"setup",void 0),sh(this,"currentMidIndex",void 0),sh(this,"cname","o/i14u9pJrxRKAsu"),sh(this,"firefoxSsrcMidMap",new Map()),e=YT(e);const{remoteIceParameters:t,remoteDtlsParameters:i,candidates:n,remoteRTPCapabilities:r,localCapabilities:s,direction:o,setup:a,videoCodec:c,audioCodec:d}=e;let l;this.setup=a,l=o===TI.RECEIVE_ONLY?JU.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"):JU.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=s;const u=o===TI.RECEIVE_ONLY?this.rtpCapabilities.send:this.rtpCapabilities.recv,h=o===TI.RECEIVE_ONLY?this._localCapabilities.recv:this._localCapabilities.send,p=o===TI.RECEIVE_ONLY?r.send.videoCodecs:Mx(av.VIDEO,u,h,c),_=o===TI.RECEIVE_ONLY?r.send.audioCodecs:Mx(av.AUDIO,u,h,d);for(const e of l.mediaDescriptions){if(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=u.videoExtensions,RC("PRELOAD_MEDIA_COUNT")>0)){const{ssrcs:t,ssrcGroups:i}=Cx([{ssrcId:4e4,rtx:RC("USE_SUB_RTX")?40001:void 0}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i;}if("audio"===e.media.mediaType&&(e.media.fmts=_.map(e=>e.payloadType.toString(10)),e.attributes.payloads=_,e.attributes.extmaps=u.audioExtensions,Lx(e),RC("PRELOAD_MEDIA_COUNT")>0)){const{ssrcs:t,ssrcGroups:i}=Cx([{ssrcId:2e4}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i;}}this.sessionDesc=l,this.currentMidIndex=l.mediaDescriptions.length-1;}toString(){return JU.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:s,ssrcGroups:o}=Cx(t,this.cname,RC("SYNC_GROUP")?i:void 0),a=this.findPreloadMediaDesc(s);if(a){if(wg()&&this.firefoxSsrcMidMap.set(s[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,s,n);let i;return -1===t?(i=this.createOrRecycleSendMedia(e,s,o,"sendonly",n,r),this.updateBundleMids()):(i=YT(this.sessionDesc.mediaDescriptions[t]),i.attributes.direction="sendonly",i.attributes.ssrcs=s,i.attributes.ssrcGroups=o,this.sessionDesc.mediaDescriptions[t]=this.mungSendMediaDesc(i,r)),wg()&&this.firefoxSsrcMidMap.set(s[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,s=this.findAvailableRecvMediaIndex(r);let o,a=!1;-1===s?(a=!0,o=this.createOrRecycleRecvMedia(e,[],"recvonly",t,i),this.updateBundleMids()):(o=YT(this.sessionDesc.mediaDescriptions[s]),o.attributes.direction="recvonly"),n.push({mid:o.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:s,relatedAddress:o,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:s?s+"":"",relAddr:null!=o?o:"",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 s=e._mediaStreamTrack.kind,o=this.rtpCapabilities.recv,a=Mx(s,o,this.localCapabilities.send,s===av.AUDIO?r:n),c=s===av.VIDEO?o.videoExtensions:o.audioExtensions,d="".concat(++this.currentMidIndex);let l={media:{mediaType:s,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 u=this.findFirstClosedMedia(s);if(u){const e=this.sessionDesc.mediaDescriptions.indexOf(u);this.sessionDesc.mediaDescriptions[e]=l;}else this.sessionDesc.mediaDescriptions.push(l);return l;}muteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter(t=>bn(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=>bn(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(wg()){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,s){const o=this.rtpCapabilities.send,a=e===av.VIDEO?o.videoCodecs:o.audioCodecs,c=e===av.VIDEO?o.videoExtensions:o.audioExtensions;wg()&&(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,s);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=YT(e);return vx(n),Ix(n,t),yx(n,t),Ax(n),bx(n,i,this.localCapabilities.send),n;}mungSendMediaDesc(e,t){const i=YT(e);return bx(i,t,this.localCapabilities.recv),Lx(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=>wg()?"0"===t.media.port&&t.media.mediaType===e:"0"===t.media.port);}};const xx=["sdp"];function Vx(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 Fx(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(Dx(t,e,"videoExtensions",i,n,r),Dx(t,e,"videoCodecs",i,n,r),Dx(t,e,"audioExtensions",i,n,r),Dx(t,e,"audioCodecs",i,n,r),RC("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};}(this.filter,this.extension,t);this.remoteSDP=new Ux({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 s=Tx(r.sdp);await this.peerConnection.setLocalDescription(r);const o=await Nx(this.filter,this.extension,r.sdp);this.localCapabilities=Px(o);const a=this.peerConnection.getTransceivers()[0];return null!=a&&a.receiver&&a.receiver.transport&&this.tryBindTransportEvents(a.receiver.transport),Fx(Fx({},s),{},{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=Tx(e.sdp);return this.initialOffer=e,Fx(Fx({},t),{},{sdp:e.sdp});}}catch(e){throw new Kg(Hg.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 Nx(this.filter,this.extension,t);this.remoteSDP=new Ux({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 s=this.peerConnection.getTransceivers()[0];null!=s&&s.sender&&s.sender.transport&&this.tryBindTransportEvents(s.sender.transport);}catch(e){throw new Kg(Hg.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 Kg(Hg.ADD_CANDIDATE_FAILED,"P2PConnection.addRemoteCandidate failed; ".concat(e.toString()));}}send(e,t,i){var n=this;return PU(function*(){const r=yield IU(n.mutex.lock("From P2PConnection.send"));try{if(!n.remoteSDP)throw new Error("Cannot call P2PConnection.send before remote SDP created");const s=[],o=n.remoteSDP.receive(e,t,i);e.forEach((e,t)=>{if(o[t].needCreateTransceiver){const t=n.peerConnection.addTransceiver(e._mediaStreamTrack,{direction:"sendonly"});s.push(t),e._updateRtpTransceiver(t);}else {const i=n.peerConnection.getTransceivers().find(e=>e.mid===o[t].mid);if(!i)throw new Error("cannot find transceiver when sendPeerconnection send, mid is ".concat(o[t].mid));s.push(i),e._updateRtpTransceiver(i);}}),wg()&&!0===RC("SIMULCAST")&&(yield IU(n.applySimulcastForFirefox(s,e)));const a=o.map(e=>e.mid),c=yield IU(n.peerConnection.createOffer()),d=n.mungSendOfferSDP(c.sdp,e,a),l=JU.parse(d),u=a.map(e=>{const t=l.mediaDescriptions.find(t=>t.attributes.mid===e);if(!t)throw new Error("Cannot extract ssrc from mediaDescription.");return Sx(t,RC("USE_PUB_RTX"));}),h=s.map((e,t)=>{const i=a[t];return {localSSRC:u[t],id:i};});yield IU(n.peerConnection.setLocalDescription({type:"offer",sdp:d}));try{yield h;}catch(e){const t=n.remoteSDP.toString();throw yield IU(n.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield IU(n.peerConnection.setRemoteDescription({type:"answer",sdp:t})),yield IU(n.stopSending(a,!0)),e;}yield IU(n.applySimulcastEncodings(s,e)),yield IU(n.applySendEncodings(s,e));const p=n.remoteSDP.toString(),_=n.logSDPExchange(d,"offer","local","send");return null==_||_(p),yield IU(n.setRemoteDescription({type:"answer",sdp:p})),s.map((e,t)=>{const i=a[t];return {localSSRC:u[t],id:i};});}catch(e){throw e instanceof Kg?e:new Kg(Hg.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 s=this.remoteSDP.toString();null==r||r(s),await this.setRemoteDescription({type:"answer",sdp:s});}catch(e){throw new Kg(Hg.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:s}=this.remoteSDP.send(e,t,i,n);if(s){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(),s=this.mungReceiveAnswerSDP(n.sdp,r,e);null==i||i(s||""),await this.peerConnection.setLocalDescription({type:"answer",sdp:s}),jC.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," by exchanging SDP."));}else jC.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," no need to exchange SDP."));const o=this.peerConnection.getTransceivers().find(e=>e.mid===r);if(!o||null===o.mid)throw new Error("Cannot get transceiver after setLocalDescription.");return {track:o.receiver.track,mid:o.mid,transceiver:o};}catch(e){throw new Kg(Hg.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:s}=this.remoteSDP.send(e,t,i,n);if(s){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(),s=this.mungReceiveAnswerSDP(n.sdp,r,e);null==i||i(s||""),await this.peerConnection.setLocalDescription({type:"answer",sdp:s}),jC.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," by exchanging SDP."));}else jC.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," no need to exchange SDP."));}catch(e){throw new Kg(Hg.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 Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(e.toString()));}}async restartICE(t){try{if(this.store.p2pTransport===fC.Auto&&(this.store.p2pTransport=fC.SdRtn,IA().supportPCSetConfiguration&&this.peerConnection.setConfiguration(e.resolvePCConfiguration(this.spec,this.store.p2pTransport))),this.restartCnt>3&&(this.restartCnt=0,IA().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}=Tx(e.sdp);return this.store.descriptionStart(),this.direction===TI.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===TI.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}=Tx(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 Kg(Hg.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(),s=this.logSDPExchange(n,"offer","local","updateEncoderConfig");await this.peerConnection.setLocalDescription({type:"offer",sdp:n}),null==s||s(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r});}catch(e){throw new Kg(Hg.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)?wg()||(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:Fx(Fx({},$U),{},{candidateType:i.type,protocol:i.protocol,address:i.address,port:i.port}),remote:Fx(Fx({},$U),{},{candidateType:n.type,protocol:n.protocol,address:n.address,port:n.port})};}return this.statsFilter.getSelectedCandidatePair();}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var e,t;bn(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)this.localCandidateAddress=e.candidate.address,null===(t=this.onLocalCandidate)||void 0===t||t.call(this,e.candidate.toJSON());this.localCandidateCount+=1;}else this.allCandidatesReceived=!0,jC.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 s;t.iceServers?r.iceServers=t.iceServers:t.turnServer&&"off"!==t.turnServer.mode&&(RT(t.turnServer.servers)?r.iceServers=t.turnServer.servers:(r.iceServers&&r.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers,i,n)),RC("USE_TURN_SERVER_OF_GATEWAY")&&r.iceServers&&t.turnServer.serversFromGateway&&r.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway,i,n)),bn(s=[fC.Relay,fC.SdRtn]).call(s,i)&&(r.iceTransportPolicy="relay"),RC("FORCE_TURN_TCP")?r.iceTransportPolicy="relay":t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach(e=>{e.forceturn&&(r.iceTransportPolicy="relay");})));return RC("ENABLE_ENCODED_TRANSFORM")&&IA().supportWebRTCEncodedTransform&&(r.encodedInsertableStreams=!0),jC.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);jC.debug("P2PConnection turnServers is ".concat(r,", current index is ").concat(i));const s=r.length>i?r[i]:r[0];switch(t){case fC.SdRtn:const t=e.filter(e=>{var t;return bn(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(gy(r.turnServerURL),":").concat(r.tcpport,"?transport=udp")}),n.push({username:r.username,credential:r.password,credentialType:"password",urls:"turns:".concat(gy(r.turnServerURL),":").concat(r.tcpport,"?transport=tcp")}));break;case fC.Relay:s&&(n.push({username:s.username,credential:s.password,credentialType:"password",urls:"turn:".concat(s.turnServerURL,":").concat(s.tcpport,"?transport=udp")}),n.push({username:s.username,credential:s.password,credentialType:"password",urls:"turns:".concat(gy(s.turnServerURL),":").concat(s.tcpport,"?transport=tcp")}));break;default:s&&(n.push({username:s.username,credential:s.password,credentialType:"password",urls:"turn:".concat(s.turnServerURL,":").concat(s.tcpport,"?transport=udp")}),n.push({username:s.username,credential:s.password,credentialType:"password",urls:"turns:".concat(gy(s.turnServerURL),":").concat(s.tcpport,"?transport=tcp")}),n.push({username:s.username,credential:s.password,credentialType:"password",urls:"stun:".concat(s.turnServerURL,":").concat(s.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();jC.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 jC.warn("[".concat(e.getTrackId(),"] no rtpSender found}"));if(this.isVP8Simulcast(e))return jC.warn("[updateRtpSenderEncodings] Track is VP8 simulcast, please apply simulcast encodings");if(!IA().supportSetRtpSenderParameters)return jC.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 s;const{bitrateMax:t,frameRate:i,scaleResolutionDownBy:n}=e._encoderConfig;t&&(r.maxBitrate=1e3*t),bn(s=e._hints).call(s,jA.LOW_STREAM)&&(i&&(r.maxFramerate=Sy(i)),n&&n>=1&&(r.scaleResolutionDownBy=n));}if(RC("DSCP_TYPE")&&jg()){var o;const e=RC("DSCP_TYPE");bn(o=["very-low","low","medium","high"]).call(o,e)&&(r.networkPriority=e);}const a=t.getParameters(),c=null===(i=a.encodings)||void 0===i?void 0:i[0];wg()&&!c&&(n.encodings=[r]),c&&Object.assign(c,r),Object.assign(a,n),jC.debug("[".concat(e.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(a.encodings))),await t.setParameters(a);}async applySendEncodings(e,t){try{if(!IA().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let i=0;i{const r=i[t],s=n.mediaDescriptions.find(e=>e.attributes.mid===r);s&&(Ix(s,e),wx(s,e,this.store.codec));}),JU.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!==(s=d._scalabilityMode)&&void 0!==s&&s.numSpatialLayers&&(null===(o=d._scalabilityMode)||void 0===o?void 0:o.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(!wg()&&e.length===t.length)for(let i=0;i200&&null!==(r=e._scalabilityMode)&&void 0!==r&&r.numSpatialLayers&&(null===(s=e._scalabilityMode)||void 0===s?void 0:s.numSpatialLayers)>1);}logSDPExchange(e,t,i,n){if(RC("SDP_LOGGING"))return jC.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 Kg(Hg.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 Kg(Hg.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=JU.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),bn(t=["connected","completed"]).call(t,this.peerConnection.iceConnectionState)||(this.isReady=!0,this.addRemoteCandidate());}mungReceiveAnswerSDP(e,t,i){const n=JU.parse(e),r=n.mediaDescriptions.find(e=>e.attributes.mid===t);return r&&(i===av.AUDIO&&"audio"===r.media.mediaType&&Lx(r),this.useXR&&kx(n)),JU.print(n);}};function jx(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,s=new Array(r),o=0;o{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&&(jC.debug("adjust low stream resolution","".concat(n.width,"x").concat(n.height," -> ").concat(n.width,"x").concat(r)),n.height=r);}o.drawImage(i,0,0,n.width,n.height),c.requestFrame&&c.requestFrame(),s!==e._mediaStreamTrack&&(s=e._mediaStreamTrack,i.srcObject=new MediaStream([s]));},n.stopCapture=Tb(()=>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),jC.debug("clean low stream renderer");},c;}var Wx,Hx,Kx,Yx,qx,zx,Jx,Xx,Qx,Zx,$x;DI([jx,PI("design:type",Function),PI("design:paramtypes",[Object]),PI("design:returntype",cg)],Bx.prototype,"establish",null),DI([jx,PI("design:type",Function),PI("design:paramtypes",[Object]),PI("design:returntype",cg)],Bx.prototype,"connect",null),DI([jx,PI("design:type",Function),PI("design:paramtypes",[String,Array,String,String]),PI("design:returntype",cg)],Bx.prototype,"receive",null),DI([jx,PI("design:type",Function),PI("design:paramtypes",[String,Array,String,String]),PI("design:returntype",cg)],Bx.prototype,"mockReceive",null),DI([jx,PI("design:type",Function),PI("design:paramtypes",[Array]),PI("design:returntype",cg)],Bx.prototype,"stopReceiving",null),DI([jx,PI("design:type",Function),PI("design:paramtypes",[Object]),PI("design:returntype",cg)],Bx.prototype,"restartICE",null),DI([jx,PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",void 0)],Bx.prototype,"close",null),DI([jx,PI("design:type",Function),PI("design:paramtypes",[String,lb]),PI("design:returntype",cg)],Bx.prototype,"updateEncoderConfig",null),DI([jx,PI("design:type",Function),PI("design:paramtypes",[String,lb]),PI("design:returntype",cg)],Bx.prototype,"updateSendParameters",null),DI([jx,PI("design:type",Function),PI("design:paramtypes",[lb,String]),PI("design:returntype",cg)],Bx.prototype,"replaceTrack",null),DI([jx,PI("design:type",Function),PI("design:paramtypes",[Array]),PI("design:returntype",cg)],Bx.prototype,"muteLocal",null),DI([jx,PI("design:type",Function),PI("design:paramtypes",[Array]),PI("design:returntype",cg)],Bx.prototype,"unmuteLocal",null),function(e){e[e.HEIGHT=2033]="HEIGHT",e[e.FRAME_RATE=2034]="FRAME_RATE",e[e.WIDTH=2035]="WIDTH";}(Wx||(Wx={})),function(e){e[e.HEIGHT=2072]="HEIGHT",e[e.FRAME_RATE=2074]="FRAME_RATE",e[e.WIDTH=2076]="WIDTH";}(Hx||(Hx={})),function(e){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";}(Kx||(Kx={})),function(e){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";}(Yx||(Yx={})),function(e){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";}(qx||(qx={})),function(e){e[e.FRAME_RATE_DECODE=2021]="FRAME_RATE_DECODE",e[e.FRAME_RATE_RENDER=2022]="FRAME_RATE_RENDER",e[e.FREEZE_TIME=2109]="FREEZE_TIME",e[e.FREEZE_TIME_RENDER=2147]="FREEZE_TIME_RENDER";}(zx||(zx={})),function(e){e[e.PCM_LEVEL=2104]="PCM_LEVEL";}(Jx||(Jx={})),function(e){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";}(Xx||(Xx={})),function(e){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";}(Qx||(Qx={})),function(e){e[e.FREEZE_TIME=-1]="FREEZE_TIME",e[e.LEVEL=2043]="LEVEL";}(Zx||(Zx={})),function(e){e[e.RTT=2006]="RTT",e[e.CONN_TYPE=801]="CONN_TYPE";}($x||($x={}));const eV=1e3,tV=3;function iV(e,t,i){null!=i&&Number.isFinite(i)&&(e[t]=Math.round(Math.max(0,i)));}function nV(e){const t={[$x.CONN_TYPE]:0,[$x.RTT]:e.rtt};switch(e.selectedCandidatePair.localCandidate.candidateType){case"relay":{const i=e.selectedCandidatePair.localCandidate.relayProtocol;"udp"===i&&(t[$x.CONN_TYPE]=1),"tcp"===i&&(t[$x.CONN_TYPE]=3),"tls"===i&&(t[$x.CONN_TYPE]=4);break;}case"srflx":t[$x.CONN_TYPE]=2;}return t;}class rV extends dT{constructor(e){super(),sh(this,"store",void 0),sh(this,"uploadWRTCStatsTimer",void 0),sh(this,"uploadOutboundDenoiserStatsTimer",void 0),sh(this,"uploadExtStatsTimer",void 0),sh(this,"uploadExtUsageStatsTimer",void 0),sh(this,"uploadInboundExtStatsTimer",void 0),sh(this,"requestStats",void 0),sh(this,"requestTransportStats",void 0),sh(this,"requestLocalMedia",void 0),sh(this,"requestRemoteMedia",void 0),sh(this,"requestAllTracks",void 0),sh(this,"requestVideoIsReady",void 0),sh(this,"requestUploadStats",void 0),sh(this,"requestUpload",void 0),sh(this,"uploadOutboundStarted",!1),sh(this,"uploadInboundStarted",!1),sh(this,"uploadTransportStarted",!1),sh(this,"uploadExtensionUsageStarted",!1),sh(this,"lastRecvStats",void 0),sh(this,"lastSendStats",void 0),sh(this,"lastFullRecvStats",void 0),sh(this,"lastFullSendStats",void 0),sh(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!==tV),++e===tV+1&&(e=1);},eV);}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:{[$x.RTT]:e.rtt,[$x.CONN_TYPE]:void 0}};const n=nV(e);if(this.store.useP2P){if(t){const e=nV(t);n[$x.CONN_TYPE]+=e[$x.CONN_TYPE]<<3;}n[$x.CONN_TYPE]+=110;}else n[$x.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,s,o;return n.forEach(n=>{let[a,{track:c,ssrcs:d}]=n;switch(a){case lv.LocalVideoLowTrack:case lv.LocalVideoTrack:if(a===lv.LocalVideoTrack){const n=function(e,t,i,n,r){const s=t.videoSend.find(t=>t.ssrc===e);if(!s)return;const o={},{sentFrame:a,inputFrame:c}=s;if(c&&a){const e=c.frameRate,t=a.frameRate;o[Kx.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(iV(o,Kx.QP_SUM,s.qpSumPerFrame),r)return o;switch(a&&(iV(o,Kx.HEIGHT,a.height),iV(o,Kx.WIDTH,a.width),iV(o,Kx.FRAME_RATE,a.frameRate)),o[Kx.DISABLED]=n._originMediaStreamTrack&&!n._originMediaStreamTrack.enabled||n._mediaStreamTrack&&!n._mediaStreamTrack.enabled?1:0,s.adaptionChangeReason){case"none":o[Kx.ADAPTATION]=0;break;case"cpu":o[Kx.ADAPTATION]=1;break;case"bandwidth":o[Kx.ADAPTATION]=2;break;case"other":o[Kx.ADAPTATION]=3;}o[Kx.PLAYER_STATUS]=ab[n._player?n._player.videoElementStatus:"uninit"],iV(o,Kx.NACKS,s.nacksCount),iV(o,Kx.PLIS,s.plisCount),iV(o,Kx.FIRS,s.firsCount),iV(o,Kx.AVG_ENCODE,s.avgEncodeMs);const d=i&&i.videoSend.find(t=>t.ssrc===e);if(d){let e=r?eV:eV*tV;d.timestamp&&s.timestamp&&(e=s.timestamp-d.timestamp),null!=d.packets&&null!=s.packets&&iV(o,Kx.PACKAGE_RATE,1e3*(s.packets-d.packets)/e),null!=s.packetsLost&&null!=d.packetsLost&&iV(o,Kx.PACKAGE_LOST,s.packetsLost-d.packetsLost),null!=d.bytes&&null!=s.bytes&&iV(o,Kx.BITRATE,8*(s.bytes-d.bytes)/e);}return o;}(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={},s=n.inputFrame,o=s&&s.height||i&&i._videoHeight||0,a=s&&s.width||i&&i._videoWidth||0,c=s&&s.frameRate||0;return iV(r,Wx.HEIGHT,o),iV(r,Wx.WIDTH,a),iV(r,Wx.FRAME_RATE,c),r;}(d[0].ssrcId,e,c),o=i?null:function(e){const t={};return iV(t,Kx.RETRANSMIT,e.bitrate.retransmit),iV(t,Kx.TARGET_ENCODED,e.bitrate.targetEncoded),iV(t,Kx.ACTUAL_ENCODED,e.bitrate.actualEncoded),iV(t,Kx.TRANSMIT,e.bitrate.transmit),iV(t,Kx.BANDWIDTH,e.sendBandwidth),t;}(e);s=Object.assign({},n,r,o);}else o=i?void 0:function(e,t,i){const n=t.videoSend.find(t=>t.ssrc===e);if(!n)return;const r={},s=n.sentFrame;if(s&&(iV(r,Yx.HEIGHT,s.height),iV(r,Yx.WIDTH,s.width),iV(r,Yx.FRAME_RATE,s.frameRate)),i){const t=i.videoSend.find(t=>t.ssrc===e);if(t){let e=eV*tV;t.timestamp&&n.timestamp&&(e=n.timestamp-t.timestamp),null!=t.packets&&null!=n.packets&&iV(r,Yx.PACKAGE_RATE,1e3*(n.packets-t.packets)/e),null!=n.packetsLost&&null!=t.packetsLost&&iV(r,Yx.PACKAGE_LOST,n.packetsLost-t.packetsLost),null!=t.bytes&&null!=n.bytes&&iV(r,Yx.BITRATE,8*(n.bytes-t.bytes)/e);}}return r;}(d[0].ssrcId,e,t);break;case lv.LocalAudioTrack:r=i?void 0:function(e,t,i,n){const r=t.audioSend.find(t=>t.ssrc===e);if(!r)return;const s={};s[Xx.DISABLED]=n._originMediaStreamTrack&&!n._originMediaStreamTrack.enabled||n._mediaStreamTrack&&!n._mediaStreamTrack.enabled?1:0;const o=n._source.getAccurateVolumeLevel(),a=r.inputLevel;iV(s,Xx.LEVEL,100*(null==a?o:a)),iV(s,Jx.PCM_LEVEL,100*o),iV(s,Xx.AEC_RETURN_LOSS,r.aecReturnLoss),iV(s,Xx.AEC_RETURN_LOSS_ENH,r.aecReturnLossEnhancement),s[Xx.FREEZE]=0;const c=i&&i.audioSend.find(t=>t.ssrc===e);if(c){let e=eV*tV;c.timestamp&&r.timestamp&&(e=r.timestamp-c.timestamp),null!=c.bytes&&null!=r.bytes&&iV(s,Xx.BITRATE,8*(r.bytes-c.bytes)/e),null!=c.packets&&null!=r.packets&&iV(s,Xx.PACKAGE_RATE,1e3*(r.packets-c.packets)/e);}return s;}(d[0].ssrcId,e,t,c);}}),{high:s,low:o,audio:r};}getInboundStats(e,t,i){if(!this.requestRemoteMedia)return;const n=this.requestRemoteMedia()||[],r=[];return n.forEach(n=>{let[s,o]=n;const a={peer:s.uid};if(o.has(av.VIDEO)&&s.videoTrack){const n=s._videoSSRC&&this.requestVideoIsReady&&this.requestVideoIsReady(s._videoSSRC)||!1,r=s.videoTrack?function(e,t,i,n,r,s,o){const a=t.videoRecv.find(t=>t.ssrc===e);if(!a)return;const c={},{receivedFrame:d,outputFrame:l,decodeFrameRate:u}=a,h=i&&i.videoRecv.find(t=>t.ssrc===e);if(c[qx.FREEZE]=r&&mV.isRemoteVideoFreeze(n,a,h)?1:0,iV(c,zx.FRAME_RATE_DECODE,u),iV(c,qx.QP_SUM,a.qpSumPerFrame),a.framesRateFirefox&&iV(c,qx.FRAME_RATE,a.framesRateFirefox),d&&iV(c,qx.FRAME_RATE,d.frameRate),h){const e=t.timestamp-i.timestamp||(o?eV:tV*eV);null!=a.packetsLost&&null!=h.packetsLost&&iV(c,qx.PACKAGE_LOST,a.packetsLost-h.packetsLost),null!=h.bytes&&null!=a.bytes&&iV(c,qx.BITRATE,8*(a.bytes-h.bytes)/e),null!=h.packets&&null!=a.packets&&iV(c,qx.PACKAGE_RATE,1e3*(a.packets-h.packets)/e);}if(o)return c;if(d?(iV(c,qx.HEIGHT,d.height),iV(c,qx.WIDTH,d.width)):n&&(iV(c,qx.HEIGHT,n._videoHeight||0),iV(c,qx.WIDTH,n._videoWidth||0)),l&&iV(c,zx.FRAME_RATE_RENDER,l.frameRate),iV(c,qx.JITTER_BUFFER,a.jitterBufferMs),iV(c,qx.CURRENT_DELAY,a.currentDelayMs),iV(c,qx.FIRS,a.firsCount),iV(c,qx.NACKS,a.nacksCount),iV(c,qx.PLIS,a.plisCount),n){c[qx.DISABLED]=n._originMediaStreamTrack.enabled&&n._mediaStreamTrack.enabled?0:1;const e=n._player;if(e){const{freezeTimeCounterList:t,renderFreezeAccTime:i}=e;if(t&&t.length>0&&iV(c,zx.FREEZE_TIME,t.splice(0,1)[0]),s&&"visible"===Dw.visibility){const t=Math.min(6e3,i);e.renderFreezeAccTime=Math.max(0,i-t),iV(c,zx.FREEZE_TIME_RENDER,t);}}}if(c[qx.PLAYER_STATUS]=ab[n._player?n._player.videoElementStatus:"uninit"],h&&void 0!==a.totalInterFrameDelay&&void 0!==a.totalSquaredInterFrameDelay&&void 0!==h.totalInterFrameDelay&&void 0!==h.totalSquaredInterFrameDelay){const e=a.totalInterFrameDelay-h.totalInterFrameDelay,t=a.totalSquaredInterFrameDelay-h.totalSquaredInterFrameDelay,i=a.framesDecodeCount-h.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)&&(c[qx.I_FRAME_DELAY]=r);}return c;}(s._videoSSRC,e,t,s.videoTrack,!0===n,this.needUploadRenderFreezeTime,i):void 0;r&&(a.video=r);}if(o.has(av.AUDIO)&&s.audioTrack){const n=s.audioTrack?function(e,t,i,n,r){const s=t.audioRecv.find(t=>t.ssrc===e);if(!s)return;const o={},a=i&&i.audioRecv.find(t=>t.ssrc===e),{receivedFrames:c,droppedFrames:d}=s;var l,u;if(iV(o,Qx.JITTER,s.jitterMs),null!=c&&null!=d&&(o[Qx.FREEZE]=(u=d,0===(l=c)||100*u/l>20?1:0)),a){const e=t.timestamp-i.timestamp||(r?eV:eV*tV);null!=s.packets&&null!=a.packets&&iV(o,Qx.PACKAGE_RATE,1e3*(s.packets-a.packets)/e),null!=a.bytes&&null!=s.bytes&&iV(o,Qx.BITRATE,8*(s.bytes-a.bytes)/e),null!=s.packetsLost&&null!=a.packetsLost&&iV(o,Qx.PACKAGE_LOST,s.packetsLost-a.packetsLost);}if(r)return o;const h=n._source.getAccurateVolumeLevel(),p=s.outputLevel;if(iV(o,Zx.LEVEL,100*(null==p?h:p)),iV(o,Qx.PCM_LEVEL,100*h),n&&(o[Qx.DISABLED]=n._originMediaStreamTrack.enabled&&n._mediaStreamTrack.enabled?0:1),iV(o,Qx.JITTER_BUFFER,s.jitterBufferMs),iV(o,Qx.CURRENT_DELAY,s.jitterBufferMs),o[Qx.PLAYER_STATUS]=ab[Gb.getPlayerState(n.getTrackId())],a){const e=s.concealedSamples-a.concealedSamples;e>0&&iV(o,Qx.CONCEALED_SAMPLES,e);}return o;}(s._audioSSRC,e,t,s.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 tw);if(e&&e._external.getDenoiserStats){const t=e._external.getDenoiserStats();t&&this.requestUpload(mI.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(av.VIDEO)&&t.videoTrack){t.videoTrack.getProcessorStats().forEach(e=>{this.requestUpload&&this.requestUpload(e.type,e.stats);});}if(i.has(av.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:RC("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 s=this.requestRemoteMedia&&this.requestRemoteMedia()||[];for(const[e,t]of s)t.has(av.VIDEO)&&e.videoTrack&&(n=n.concat(await e.videoTrack.getProcessorUsage())),t.has(av.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:o,value:a,level:c,direction:d}of e){var n;const e=null!==(n=t.get(o))&&void 0!==n?n:0,l=2===a?e+RC("EXTENSION_USAGE_UPLOAD_INTERVAL")/1e3:e;var r,s;t.set(o,l),i[o]?(2===a&&(i[o].value=a),c>i[o].level&&(i[o].level=c),"remote"===d&&(i[o].remoteUidCount+=1),i[o].totalTs=null!==(r=t.get(o))&&void 0!==r?r:0):i[o]={value:a,level:c,remoteUidCount:"local"===d?0:1,totalTs:null!==(s=t.get(o))&&void 0!==s?s: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 o=Date.now(),a=o>t?o:t+1;this.requestUpload&&this.requestUpload(mI.EXTENSION_USAGE_STATS,{usageStats:i,sendTs:a});},RC("EXTENSION_USAGE_UPLOAD_INTERVAL"));}stopUploadExtensionUsageStats(){this.uploadExtensionUsageStarted&&(this.uploadExtensionUsageStarted=!1,this.uploadExtUsageStatsTimer&&window.clearInterval(this.uploadExtUsageStatsTimer),this.uploadExtUsageStatsTimer=void 0);}}class sV{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){sh(this,"uid",void 0),sh(this,"_uintid",void 0),sh(this,"_trust_in_room_",!0),sh(this,"_trust_audio_enabled_state_",!0),sh(this,"_trust_video_enabled_state_",!0),sh(this,"_trust_audio_mute_state_",!0),sh(this,"_trust_video_mute_state_",!0),sh(this,"_audio_muted_",!1),sh(this,"_video_muted_",!1),sh(this,"_audio_enabled_",!0),sh(this,"_video_enabled_",!0),sh(this,"_audio_added_",!1),sh(this,"_video_added_",!1),sh(this,"_is_pre_created",!1),sh(this,"_video_pre_subscribed",!1),sh(this,"_audio_pre_subscribed",!1),sh(this,"_trust_video_stream_added_state_",!0),sh(this,"_trust_audio_stream_added_state_",!0),sh(this,"_audioTrack",void 0),sh(this,"_videoTrack",void 0),sh(this,"_dataChannels",[]),sh(this,"_audioSSRC",void 0),sh(this,"_videoSSRC",void 0),sh(this,"_audioOrtc",void 0),sh(this,"_videoOrtc",void 0),sh(this,"_cname",void 0),sh(this,"_rtxSsrcId",void 0),sh(this,"_videoMid",void 0),sh(this,"_audioMid",void 0),this.uid=e,this._uintid=t;}}var oV;function aV(e,t){var i;let n;switch(t){case lv.LocalAudioTrack:n=JI.Audio;break;case lv.LocalVideoTrack:n=bn(i=e._hints).call(i,jA.SCREEN_TRACK)?JI.Screen:JI.High;break;case lv.LocalVideoLowTrack:n=JI.Low;}return n;}function cV(e){const t=IA();if(e.some(e=>e._bypassWebAudio))throw new Kg(Hg.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio");if(!t.webAudioMediaStreamDest)throw new Kg(Hg.NOT_SUPPORTED,"cannot publish multiple tracks because your browser does not support audio mixing");}function dV(e,t){cV(e);const i=t||new nw();return e.forEach(e=>i.addAudioTrack(e)),i;}function lV(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 uV(e){for(var t=1;t{const n=await this.sendMutex.lock("Locking from P2PChannel2.handleMuteLocalTrack");try{if(!this.sendConnection||this.state!==uv.Connected)return void i(new Kg(Hg.INVALID_OPERATION,"Cannot call P2PChannel2.handleMuteLocalTrack before sendConnection established."));const o=this.filterTobeMutedTracks(e);if(0===o.length)return void t();const a=o.find(e=>"videoLowTrack"===e[0]);if(a){a[1].track._originMediaStreamTrack.stop();}await this.sendConnection.muteLocal(o.map(e=>{let[,{id:t}]=e;return t;}));let c=!1;var r,s;if("video"===e.trackMediaType)c=!(null===(r=this.localTrackMap.get(lv.LocalAudioTrack))||void 0===r||!r.track._muted);else c=void 0===(null===(s=this.localTrackMap.get(lv.LocalVideoTrack))||void 0===s?void 0:s.id);const d=this.createMuteMessage(o);await yT(this,hv.RequestMuteLocal,d);const l="video"===e.trackMediaType?Av.MUTE_LOCAL_VIDEO:Av.MUTE_LOCAL_AUDIO;await yT(this,hv.RequestP2PMuteLocal,{action:l,message:d,isMuteAll:c}),t();}catch(e){i(e);}finally{n();}}),sh(this,"handleUnmuteLocalTrack",async(e,t,i)=>{const n=await this.sendMutex.lock("Locking from P2PChannel2.handleUnmuteLocalTrack");try{if(!this.sendConnection||this.state!==uv.Connected)return void i(new Kg(Hg.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 s=this.createUnmuteMessage(r),o="video"===e.trackMediaType?Av.UNMUTE_LOCAL_VIDEO:Av.UNMUTE_LOCAL_AUDIO;await yT(this,hv.RequestP2PMuteLocal,{action:o,message:s}),t();}catch(e){i(e);}finally{n();}}),sh(this,"handleUpdateVideoEncoder",async(e,t,i)=>{const n=await this.sendMutex.lock("Locking from P2PChannel2.handleSetVideoEncoder");try{const i=this.localTrackMap.get(lv.LocalVideoTrack);if(!this.sendConnection||!i||i.track!==e||this.state!==uv.Connected)return void t();const{id:r,track:s}=i;r&&(await this.sendConnection.updateSendParameters(r,s),await this.sendConnection.updateEncoderConfig(r,s),this.emit(hv.UpdateVideoEncoder,s)),t();}catch(e){i(e);}finally{n();}}),sh(this,"handleSetOptimizationMode",async(e,t,i)=>{const n=await this.sendMutex.lock("Locking from P2PChannel2.handleSetOptimizationMode");try{const i=this.localTrackMap.get(lv.LocalVideoTrack);if(!this.sendConnection||!i||i.track!==e||this.state!==uv.Connected)return;const{id:r,track:s}=i;r&&(await this.sendConnection.updateSendParameters(r,s)),t();}catch(e){i(e);}finally{n();}}),sh(this,"handleReplaceTrack",async(e,t,i,n)=>{let r;jC.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 s;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!==uv.Connected)return void t();if(await(null===(s=this.sendConnection)||void 0===s?void 0:s.replaceTrack(e,i[1].id)),i[0]===lv.LocalVideoTrack&&IA().supportDualStreamEncoding){const t=this.localTrackMap.get(lv.LocalVideoLowTrack);if(t){const i=e._mediaStreamTrack.clone();t.track._originMediaStreamTrack.stop(),t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i,await new cg((e,i)=>{this.handleReplaceTrack(t.track,e,i,!0);});}}t();}catch(e){i(e);}finally{var o;null===(o=r)||void 0===o||o();}}),sh(this,"handleGetLocalVideoStats",e=>{e(this.statsCollector.getLocalVideoTrackStats());}),sh(this,"handleGetLocalAudioStats",e=>{e(this.statsCollector.getLocalAudioTrackStats());}),sh(this,"handleGetRemoteVideoStats",e=>this.statsCollector.getRemoteVideoTrackStats(e.uid)[e.uid]),sh(this,"handleGetRemoteAudioStats",e=>this.statsCollector.getRemoteAudioTrackStats(e.uid)[e.uid]),this.store=e,this.statsCollector=t,this.statsCollector.addP2PChannel(this),this.statsUploader=new rV(e),this.bindStatsUploaderEvents(),this.reconnectInterval=window.setInterval(()=>{[this.sendConnection,this.recvConnection].forEach(e=>{e&&("disconnected"!==e.iceConnectionState&&"failed"!==e.iceConnectionState||this.handleDisconnect(e.direction));});},RC("ICE_RESTART_INTERVAL"));}async startP2PConnection(e,t){throw new Kg(Hg.NOT_SUPPORTED,"p2p mode does not support startP2PConnection.");}async connect(e,t,i,n,r,s){throw new Kg(Hg.NOT_SUPPORTED,"p2p mode does not support connect.");}async startP2P(e,t){let i;try{if(t){this.recvConnection&&(jC.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 Bx(e,this.store,TI.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=uv.New,this.sendConnection&&(jC.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 Bx(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 Kg(Hg.UNEXPECTED_ERROR,"Cannot P2PChannel2.p2pConnect before P2PChannel2.startP2PConnection .");this.store.peerConnectionStart(),await this.sendConnection.connect(e),this.statsUploader.startUploadTransportStats(),this.statsUploader.startUploadExtensionUsageStats(),this.state=uv.Connected;}async addRemoteCandidate(e,t){if(t===TI.RECEIVE_ONLY){if(!this.sendConnection)throw new Kg(Hg.UNEXPECTED_ERROR,"Cannot P2PChannel2.connect before P2PChannel2.addRemoteCandidate .");await this.sendConnection.addRemoteCandidate(e);}else {if(!this.recvConnection)throw new Kg(Hg.UNEXPECTED_ERROR,"Cannot P2PChannel2.connect before P2PChannel2.addRemoteCandidate .");await this.recvConnection.addRemoteCandidate(e);}}publish(e,t,i){var n=this;return PU(function*(){const r=yield IU(n.sendMutex.lock("From P2PChannel.publish"));try{if(!n.sendConnection||n.state!==uv.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,RU.markPublishStart(n.store.clientId,n.store.pubId);const s=n.filterTobePublishedTracks(e,t,i);if(0===s.length)return void(yield IU(n.tryToUnmuteAudio(e)));s.forEach(e=>{let{track:t,type:i}=e;const r=Date.now();n.store.publish(t.getTrackId(),i===lv.LocalAudioTrack?"audio":"video",r);}),n.bindLocalTrackEvents(s);const o=yield IU(n.sendConnection.send(s.map(e=>{let{track:t}=e;return t;}),n.store.codec,n.store.audioCodec)),a=(yield IU(o.next())).value,c=n.createGatewayPublishMessage(s,a);try{yield c;}catch(e){throw o.throw(e),(null==e?void 0:e.code)===Hg.WS_ABORT&&s.forEach(e=>{let{track:t}=e;-1===n.pendingLocalTracks.indexOf(t)&&n.pendingLocalTracks.push(t);}),n.unbindLocalTrackEvents(s),e;}yield IU(o.next()),s.forEach(e=>{let{type:t}=e;n.statsCollector.addLocalStats(t);}),n.statsUploader.startUploadOutboundStats(),n.assignLocalTracks(s,a),s.forEach(e=>{let{track:t,type:i}=e;const r=Date.now();n.store.publish(t.getTrackId(),i===lv.LocalAudioTrack?"audio":"video",void 0,r);}),n.startUploadUplinkState();}finally{r();}})();}async unpublish(e){if(!this.sendConnection||this.state!==uv.Connected)return void(0===e.length?this.pendingLocalTracks.length=0:this.pendingLocalTracks=this.pendingLocalTracks.filter(t=>!bn(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===uv.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:s}]=i;const o={stream_type:aV(r,n),ssrcs:s};r._muted||!r._enabled?e.push(o):t.push(o);}),e.length>0&&e.forEach(e=>{yT(this,hv.RequestMuteLocal,[e]);}),t.length>0&&t.forEach(e=>{yT(this,hv.RequestUnmuteLocal,[e]);});};e(),this.uplinkStateUploadInterval=window.setInterval(()=>{e();},3e3);}stopUploadUplinkState(){this.uploadUnplinkStarted&&(this.uploadUnplinkStarted=!1,this.uplinkStateUploadInterval&&window.clearInterval(this.uplinkStateUploadInterval));}publishLowStream(e){return PU(function*(){throw new Kg(Hg.NOT_SUPPORTED,"p2p mode does not support publishLowStream.");})();}async republish(){this.pendingLocalTracks.length>0&&(jC.debug("[".concat(this.store.clientId,"] Emit P2PChannelEvents.RequestRePublish to republish tracks.")),await vT(this,hv.RequestRePublish,this.pendingLocalTracks),this.emit(hv.MediaReconnectEnd,this.store.uid),this.pendingLocalTracks=[]);}async unpublishLowStream(){throw new Kg(Hg.NOT_SUPPORTED,"p2p mode does not support unpublishLowStream.");}async subscribe(e,t,i,n){var r;if(!this.recvConnection)throw new Kg(Hg.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:s,mid:o,transceiver:a}=await this.recvConnection.receive(t,[{ssrcId:i}],String(e.uid),n);t===av.AUDIO?(e._audioTrack?e._audioTrack._updateOriginMediaStreamTrack(s):(e._audioTrack=new Nw(s,e.uid,e._uintid,this.store),jC.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(s):(e._videoTrack=new Ow(s,e.uid,e._uintid,this.store),jC.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,o):this.remoteUserMap.set(e,new Map([[t,o]])),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(hv.MediaReconnectEnd,e.uid));}async mockSubscribe(e,t,i,n){if(!this.recvConnection)throw new Kg(Hg.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===av.AUDIO)null===(n=e._audioTrack)||void 0===n||n._destroy(),e._audioTrack=void 0;else if(i===av.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,s;n===av.VIDEO&&t._videoSSRC&&(null===(r=this.recvConnection)||void 0===r||r.setStatsRemoteVideoIsReady(t._videoSSRC,!1));if(n===av.VIDEO)this.unbindRemoteTrackEvents(t._videoTrack),i||(null===(s=t._videoTrack)||void 0===s||s._destroy(),t._videoTrack=void 0);else if(n===av.AUDIO){var o;if(this.unbindRemoteTrackEvents(t._audioTrack),!i)null===(o=t._audioTrack)||void 0===o||o._destroy(),t._audioTrack=void 0;}}),r.forEach(e=>{let[,{kind:t}]=e;yT(this,hv.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;[av.VIDEO,av.AUDIO].forEach(e=>{t.has(e)?yT(this,hv.RequestP2PUnmuteRemote,e):yT(this,hv.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 Kg(Hg.NOT_SUPPORTED,"p2p mode does not support massSubscribe.");}async massSubscribeNoLock(e){throw new Kg(Hg.NOT_SUPPORTED,"p2p mode does not support massSubscribeNoLock.");}async massUnsubscribe(e){throw new Kg(Hg.NOT_SUPPORTED,"p2p mode does not support massUnsubscribe.");}async massUnsubscribeNoLock(e){throw new Kg(Hg.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 jC.warning("[".concat(this.store.clientId,"] P2PChannel2.muteRemote has no remote user ").concat(e.uid,"."));if(!i.get(t))return void jC.warning("[".concat(this.store.clientId,"] P2PChannel2.muteRemote has no remote user ").concat(e.uid," media type ").concat(t,"."));const n=t===av.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 jC.warning("[".concat(this.store.clientId,"] P2PChannel2.unmuteRemote has no remote user ").concat(e.uid,"."));i.get(t)||jC.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(lv.LocalAudioTrack);if((null==t?void 0:t.track)instanceof nw){const i=t.track;return Array.from(this.localTrackMap.entries()).filter(e=>{let[t]=e;return t!==lv.LocalAudioTrack;}).filter(t=>{let[i]=t;return !(e&&i===lv.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===lv.LocalVideoLowTrack);}).map(e=>{let[,{track:t}]=e;return t;});}reportPublishEvent(e,t,i,n,r){if(e){const i=this.localTrackMap.get(lv.LocalAudioTrack),s=n?this.localTrackMap.get(lv.LocalVideoLowTrack):this.localTrackMap.get(lv.LocalVideoTrack);eI.publish(this.store.sessionId,{eventElapse:RU.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:e,ec:t,audioName:null==i?void 0:i.track.getTrackLabel(),videoName:null==s?void 0:s.track.getTrackLabel(),screenshare:-1!==(null==s?void 0:s.track._hints.indexOf(jA.SCREEN_TRACK)),audio:!!i,video:!!s,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r});}else {var s;i||(i=[]);const o=i.find(e=>e instanceof ew),a=n?null===(s=this.localTrackMap.get(lv.LocalVideoTrack))||void 0===s?void 0:s.track:i.find(e=>e instanceof Rw);eI.publish(this.store.sessionId,{eventElapse:RU.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:e,ec:t,audioName:null==o?void 0:o.getTrackLabel(),videoName:null==a?void 0:a.getTrackLabel(),screenshare:-1!==(null==a?void 0:a._hints.indexOf(jA.SCREEN_TRACK)),audio:!!o,video:!!a,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r});}}reportSubscribeEvent(e,t,i,n){const r=n===av.VIDEO?i._videoSSRC:i._audioSSRC;r&&eI.subscribe(this.store.sessionId,{succ:e,ec:t,video:n===av.VIDEO,audio:n===av.AUDIO,peerid:i.uid,subscribeRequestid:n===av.VIDEO?i._videoSSRC:i._audioSSRC,p2pid:this.store.p2pId,eventElapse:RU.measureFromSubscribeStart(this.store.clientId,r)});}reset(){jC.debug("[".concat(this.store.clientId,"] P2PChannel2.reset")),this.sendMutex=new pS("P2PChannel2-send-mutex"),this.sendMutex=new pS("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(lv.LocalAudioTrack);if((null==e?void 0:e.track)instanceof nw){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=uv.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(lv.LocalAudioTrack);if(e)return e.track.getVolumeLevel();}getLocalVideoSize(){const e=this.localTrackMap.get(lv.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 Rw||t&&t.track instanceof ew?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(ph(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(lv.LocalAudioTrack);return t&&e.push({level:100*t.track._source.getAccurateVolumeLevel(),uid:this.store.uid}),e=ep(e).call(e,(e,t)=>e.level-t.level),e;}async disconnectForReconnect(){this.sendConnection&&this.recvConnection&&(jC.debug("[".concat(this.store.clientId,"] P2PChannel2.disconnectForReconnect closing P2PConnection")),this.state=uv.Reconnecting,RC("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 lv.LocalVideoTrack:bn(t=n._hints).call(t,jA.LOW_STREAM)?n.close():this.pendingLocalTracks.push(n);break;case lv.LocalAudioTrack:n instanceof nw?this.pendingLocalTracks=this.pendingLocalTracks.concat(n.trackList):this.pendingLocalTracks.push(n);case lv.LocalVideoLowTrack:}}),this.emit(hv.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(ph(i).call(i)).forEach(e=>{this.setPendingRemoteMedia(t,e);}),this.emit(hv.MediaReconnectStart,t.uid);}),this.unbindAllRemoteTrackEvents(),this.remoteUserMap.clear(),this.stopUploadUplinkState(),this.stopUploadDownlinkState(),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),jC.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 sV?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===TI.SEND_ONLY){if(!this.sendConnection)throw new Kg(Hg.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 Kg(Hg.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 vT(this,hv.RequestP2PRestartICE,{direction:TI.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(lv.LocalVideoTrack),i=this.localTrackMap.get(lv.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 s=AT(this,hv.NeedSignalRTT),o=n?n.rttMs:void 0,a=r?r.rttMs:void 0,c=o&&a?(o+a)/2:o||a,d=(c&&s?(c+s)/2:c||s)||0,l=100*e.sendPacketLossRate*.7/50+.3*d/1500,u=l<.17?1:l<.36?2:l<.59?3:l<.1?4:5,h=null==t?void 0:t.track;if(h&&h._encoderConfig&&-1===h._hints.indexOf(jA.SCREEN_TRACK)){const t=h._encoderConfig.bitrateMax,i=e.bitrate.actualEncoded;if(t&&i){const e=(1e3*t-i)/(1e3*t);return nI[e<.15?0:e<.3?1:e<.45?2:e<.6?3:4][u];}}return u;}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,s=n._videoSSRC,o=e.audioRecv.find(e=>e.ssrc===r),a=e.videoRecv.find(e=>e.ssrc===s);if(!o&&!a)return void(t+=1);const c=AT(this,hv.NeedSignalRTT),d=e.rtt,l=(d&&c?(d+c)/2:d||c)||0,u=o?o.jitterMs:void 0,h=e.recvPacketLossRate;let p=.7*h*100/50+.3*l/1500;u&&(p=.6*h*100/50+.2*l/1500+.2*u/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 cg((t,i)=>{this.handleMuteLocalTrack(e,t,i);});}filterTobePublishedTracks(e,t,i){const n=[],r=IA(),s=this.getAllTracks();e=HT(e=e.filter(e=>-1===s.indexOf(e)));let o=!1,a=!1;for(const s of e){if(s instanceof Rw&&(this.localTrackMap.has(lv.LocalVideoTrack)||o?new Kg(Hg.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS).throw():(n.push({track:s,type:lv.LocalVideoTrack}),o=!0),t)){const e=this.getLowVideoTrack(s,i);n.push({track:e,type:lv.LocalVideoLowTrack});}if(s instanceof ew){const e=this.localTrackMap.get(lv.LocalAudioTrack);if(e){if(!(e.track instanceof nw))throw new Kg(Hg.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser does not support audio mixing");if(s._bypassWebAudio)throw new Kg(Hg.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio");e.track.addAudioTrack(s),this.bindLocalAudioTrackEvents(s,!0);}else if(a){const e=n.find(e=>{let{type:t}=e;return t===lv.LocalAudioTrack;});if(!(e.track instanceof nw))throw new Kg(Hg.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser does not support audio mixing");if(s._bypassWebAudio)throw new Kg(Hg.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio");e.track.addAudioTrack(s);}else {if(!r.webAudioMediaStreamDest||s instanceof nw||s._bypassWebAudio)n.push({track:s,type:lv.LocalAudioTrack});else {const e=new nw();e.addAudioTrack(s),n.push({track:e,type:lv.LocalAudioTrack});}a=!0;}}}return n;}filterTobeUnpublishedTracks(e){const t=[],i=this.getAllTracks();e=HT(e=e.filter(e=>-1!==i.indexOf(e)));for(const i of e){if(i instanceof ew){const e=this.localTrackMap.get(lv.LocalAudioTrack);if(!e)continue;e.track instanceof nw?(e.track.removeAudioTrack(i),this.unbindLocalAudioTrackEvents(i),0===e.track.trackList.length&&(t.push([lv.LocalAudioTrack,e]),e.track.close())):t.push([lv.LocalAudioTrack,e]);}if(i instanceof Rw){const e=this.localTrackMap.get(lv.LocalVideoTrack);if(!e)continue;t.push([lv.LocalVideoTrack,e]);const i=this.localTrackMap.get(lv.LocalVideoLowTrack);i&&t.push([lv.LocalVideoLowTrack,i]);}}return t;}bindLocalTrackEvents(e){e.forEach(e=>{let{track:t,type:i}=e;switch(i){case lv.LocalVideoTrack:t.addListener(BA.GET_STATS,this.handleGetLocalVideoStats),t.addListener(BA.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.addListener(BA.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.addListener(BA.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.addListener(BA.SET_OPTIMIZATION_MODE,this.handleSetOptimizationMode),t.addListener(BA.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.addListener(BA.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.addListener(BA.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case lv.LocalAudioTrack:this.bindLocalAudioTrackEvents(t);case lv.LocalVideoLowTrack:}});}bindLocalAudioTrackEvents(e,t){e instanceof nw?e.trackList.forEach(e=>{e.addListener(BA.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(BA.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(BA.GET_STATS,this.handleGetLocalAudioStats),e.addListener(BA.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(BA.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);}):(e.addListener(BA.GET_STATS,this.handleGetLocalAudioStats),e.addListener(BA.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(BA.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(BA.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(BA.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack),t||e.addListener(BA.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 lv.LocalVideoTrack:t.off(BA.GET_STATS,this.handleGetLocalVideoStats),t.off(BA.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.off(BA.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.off(BA.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.off(BA.SET_OPTIMIZATION_MODE,this.handleSetOptimizationMode),t.off(BA.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.off(BA.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.off(BA.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case lv.LocalAudioTrack:this.unbindLocalAudioTrackEvents(t);case lv.LocalVideoLowTrack:}});}unbindLocalAudioTrackEvents(e){e instanceof nw?e.trackList.forEach(e=>{e.off(BA.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(BA.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(BA.GET_STATS,this.handleGetLocalAudioStats),e.off(BA.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(BA.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);}):(e.off(BA.GET_STATS,this.handleGetLocalAudioStats),e.off(BA.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(BA.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(BA.NEED_REPLACE_TRACK,this.handleReplaceTrack),e.off(BA.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(BA.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack));}bindRemoteTrackEvents(e,t){t instanceof Ow&&t.addListener(BA.GET_STATS,t=>{t(this.handleGetRemoteVideoStats(e));}),t instanceof Nw&&t.addListener(BA.GET_STATS,t=>{t(this.handleGetRemoteAudioStats(e));});}unbindRemoteTrackEvents(e){e&&e.removeAllListeners(BA.GET_STATS);}unbindAllRemoteTrackEvents(){Array.from(this.remoteUserMap.entries()).forEach(e=>{let[t,i]=e;i.has(av.AUDIO)&&this.unbindRemoteTrackEvents(t._audioTrack),i.has(av.VIDEO)&&this.unbindRemoteTrackEvents(t._videoTrack);});}createGatewayPublishMessage(e,t){return e.map((e,i)=>{var n;let r,{track:s,type:o}=e;switch(o){case lv.LocalAudioTrack:r=JI.Audio;break;case lv.LocalVideoTrack:r=bn(n=s._hints).call(n,jA.SCREEN_TRACK)?JI.Screen:JI.High;break;case lv.LocalVideoLowTrack:r=JI.Low;}return {kind:o===lv.LocalAudioTrack?av.AUDIO:av.VIDEO,stream_type:r,mid:t[i].id,ssrcs:t[i].localSSRC,isMuted:s.muted||!s.enabled};});}createGatewayUnpublishMessage(e){return e.map(e=>{var t;let i,[n,{track:r,ssrcs:s,id:o}]=e;switch(n){case lv.LocalVideoTrack:i=bn(t=r._hints).call(t,jA.SCREEN_TRACK)?JI.Screen:JI.High;break;case lv.LocalAudioTrack:i=JI.Audio;break;case lv.LocalVideoLowTrack:i=JI.Low;}return {stream_type:i,ssrcs:s,mid:o};});}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;jC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: ").concat(e.name,".onConnectionStateChange(").concat(t,")")),this.emit(hv.PeerConnectionStateChange,t),"connected"!==t||this.store.keyMetrics.peerConnectionEnd||this.store.peerConnectionEnd(),"connected"===t&&(e.isInRestartIce=!1),bn(i=this._restartStates).call(i,t)&&!e.isInRestartIce&&("disconnected"===t&&(await iS(800)),"disconnected"!==e.iceConnectionState&&"failed"!==e.iceConnectionState||this.handleDisconnect(e.direction));},e.onICEConnectionStateChange=e=>{"connected"!==e||this.store.keyMetrics.iceConnectionEnd||this.store.iceConnectionEnd(),jC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICEConnectionStateChange(").concat(e,")")),eI.reportApiInvoke(this.store.sessionId,{name:"ICEConnectionStateChange",options:e,tag:pT.TRACER}).onSuccess(),this.emit(hv.IceConnectionStateChange,e);},e.onICETransportStateChange=e=>{jC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICETransportStateChange(").concat(e,")"));},e.onDTLSTransportStateChange=e=>{jC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportStateChange(").concat(e,")"));},e.onDTLSTransportError=e=>{jC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportError(").concat(e,")"));},e.onFirstAudioDecoded=e=>{var t;const i=Array.from(ph(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(qA.FIRST_FRAME_DECODED),eI.firstRemoteFrame(this.store.sessionId,YC.FIRST_AUDIO_DECODE,qC.FIRST_AUDIO_DECODE,{peer:i._uintid,subscribeElapse:RU.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId}));},e.onFirstAudioReceived=e=>{var t;const i=Array.from(ph(t=this.remoteUserMap).call(t)).find(t=>t._audioSSRC===e);i&&eI.firstRemoteFrame(this.store.sessionId,YC.FIRST_AUDIO_RECEIVED,qC.FIRST_AUDIO_RECEIVED,{peer:i._uintid,subscribeElapse:RU.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(ph(t=this.remoteUserMap).call(t)).find(t=>t._videoSSRC===e);i&&eI.firstRemoteFrame(this.store.sessionId,YC.FIRST_VIDEO_RECEIVED,qC.FIRST_VIDEO_RECEIVED,{peer:i._uintid,subscribeElapse:RU.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(hv.ConnectionTypeChange,i),jC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedLocalCandidateChanged(").concat(JSON.stringify(Ay(t))," -> ").concat(JSON.stringify(Ay(e)),")"));},e.onSelectedRemoteCandidateChanged=(e,t)=>{jC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedRemoteCandidateChanged(").concat(JSON.stringify(Ay(t))," -> ").concat(JSON.stringify(Ay(e)),")"));},e.onFirstVideoDecodedTimeout=e=>{this.reportVideoFirstFrameDecoded(e,void 0,void 0,!0);},e.onLocalCandidate=t=>{this.emit(hv.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===TI.SEND_ONLY?this.sendConnection:this.recvConnection;t&&!t.isInRestartIce&&(t.isInRestartIce=!0,jC.debug("[".concat(this.store.clientId,"] [P2PChannel-").concat(t.name,"] start use restartICE")),e===TI.SEND_ONLY?this.restartICE(e):vT(this,hv.RequestP2PRestartICE,{direction:TI.SEND_ONLY}));}filterTobeMutedTracks(e){const t=[];if(-1===this.getAllTracks().indexOf(e))return t;const i=this.localTrackMap.get(lv.LocalAudioTrack);if(e instanceof ew&&(null==i?void 0:i.track)instanceof nw)return i.track.isActive||t.push([lv.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]===lv.LocalVideoTrack)){const e=this.localTrackMap.get(lv.LocalVideoLowTrack);e&&t.push([lv.LocalVideoLowTrack,e]);}return t;}filterTobeUnmutedTracks(e){const t=[],i=this.localTrackMap.get(lv.LocalAudioTrack);if(e instanceof ew&&(null==i?void 0:i.track)instanceof nw)return i.track.isActive&&t.push([lv.LocalAudioTrack,i]),t;const n=Array.from(this.localTrackMap.entries()).find(t=>{let[,{track:i}]=t;return e===i;});if(n)if(n[0]===lv.LocalVideoTrack){t.push(n);const e=this.localTrackMap.get(lv.LocalVideoLowTrack);e&&t.push([lv.LocalVideoLowTrack,e]);}else t.push(n);return t;}createMuteMessage(e){return e.map(e=>{var t;let i,[n,{track:r,ssrcs:s,id:o}]=e;switch(n){case lv.LocalAudioTrack:i=JI.Audio;break;case lv.LocalVideoTrack:i=bn(t=r._hints).call(t,jA.SCREEN_TRACK)?JI.Screen:JI.High;break;case lv.LocalVideoLowTrack:i=JI.Low;}return {stream_type:i,ssrcs:s,mid:o};});}createUnmuteMessage(e){return e.map(e=>{var t;let i,[n,{track:r,ssrcs:s,id:o}]=e;switch(n){case lv.LocalAudioTrack:i=JI.Audio;break;case lv.LocalVideoTrack:i=bn(t=r._hints).call(t,jA.SCREEN_TRACK)?JI.Screen:JI.High;break;case lv.LocalVideoLowTrack:i=JI.Low;}return {stream_type:i,ssrcs:s,mid:o};});}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 av.VIDEO:return void(i._videoSSRC&&t.push({stream_type:av.VIDEO,ssrcId:i._videoSSRC}));case av.AUDIO:return void(i._audioSSRC&&t.push({stream_type:av.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(lv.LocalVideoTrack),i=this.localTrackMap.get(lv.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(hv.RequestUpload,e,t),this.statsUploader.requestUploadStats=e=>this.emit(hv.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 iS(mS(this.dtlsFailedCount,ES)),this.emit(hv.RequestReconnect);}async reconnectP2P(){}canPublishLowStream(){return this.localTrackMap.has(lv.LocalVideoTrack)||this.pendingLocalTracks.some(e=>e instanceof Rw);}throwIfTrackTypeNotMatch(e){if(e.filter(e=>e instanceof Rw).length>1)throw new Kg(Hg.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(e.filter(e=>e instanceof ew).length>1&&(e.some(e=>e instanceof ew&&e._bypassWebAudio)||!IA().webAudioMediaStreamDest))throw new Kg(Hg.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 Rw&&this.pendingLocalTracks.some(e=>e instanceof Rw))throw new Kg(Hg.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(t instanceof ew&&this.pendingLocalTracks.some(e=>e instanceof ew)&&(!IA().webAudioMediaStreamDest||t._bypassWebAudio||this.pendingLocalTracks.some(e=>e instanceof ew&&e._bypassWebAudio)))throw new Kg(Hg.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=!RC("DISABLE_DUAL_STREAM_USE_ENCODING")&&IA().supportDualStreamEncoding,n=uV(uV({},{width:160,height:120,framerate:15,bitrate:50}),t);let r;r=i?e._mediaStreamTrack.clone():Gx(e,n);const s=nS(8,"track-low-"),o=new Rw(r,uV(uV({},i&&{scaleResolutionDownBy:yy(n,e)}),{},{frameRate:n.framerate,bitrateMax:n.bitrate,bitrateMin:n.bitrate}),void 0,void 0,s);return o.on(KA.TRANSCEIVER_UPDATED,t=>{e._updateRtpTransceiver(t,GA.LOW_STREAM);}),o._hints.push(jA.LOW_STREAM),e.addListener(BA.NEED_CLOSE,()=>{o.close();}),o;}async globalLock(){return this.recvMutex.lock("From P2PChannel2.globalLock");}reportVideoFirstFrameDecoded(e,t,i,n){var r;const s=Array.from(ph(r=this.remoteUserMap).call(r)).find(t=>t._videoSSRC===e);if(s){n||this.store.subscribe(s.uid,"video",void 0,void 0,void 0,void 0,Date.now());const r=this.store.keyMetrics,o=r.subscribe.find(e=>e.userId===s.uid&&"video"===e.type);eI.firstRemoteVideoDecode(this.store.sessionId,YC.FIRST_VIDEO_DECODE,qC.FIRST_VIDEO_DECODE,{peer:s._uintid,videowidth:t,videoheight:i,subscribeElapse:RU.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==o?void 0:o.subscribeEnd)||0,subscriberStart:(null==o?void 0:o.subscribeStart)||0,videoAddNotify:(null==o?void 0:o.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 s=await this.recvConnection.getRemoteSSRC(r);return void 0!==s&&s!==i;}resetConnection(e){jC.debug("[".concat(this.store.clientId,"] [P2PChannel2] reset connection to ").concat(e)),this.state===uv.Connected?(jC.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 Kg(Hg.NOT_SUPPORTED);}async unpublishDataChannel(e){throw new Kg(Hg.NOT_SUPPORTED);}async subscribeDataChannel(e,t){throw new Kg(Hg.NOT_SUPPORTED);}async unsubscribeDataChannel(e,t){throw new Kg(Hg.NOT_SUPPORTED);}hasPendingRemoteDataChannel(e,t){throw new Kg(Hg.NOT_SUPPORTED);}setPendingRemoteDataChannel(e,t){throw new Kg(Hg.NOT_SUPPORTED);}async preConnect(e,t,i,n,r,s){throw new Kg(Hg.NOT_SUPPORTED);}getEstablishParams(){throw new Kg(Hg.NOT_SUPPORTED);}async reSubscribe(e){throw new Kg(Hg.NOT_SUPPORTED);}async updateVideoStreamParameter(e,t){throw new Kg(Hg.NOT_SUPPORTED);}unbindRtpTransceiver(){0!==this.localTrackMap.size&&Array.from(this.localTrackMap.entries()).forEach(e=>{let[t,{track:i}]=e;t===lv.LocalVideoLowTrack?i._updateRtpTransceiver(void 0,GA.LOW_STREAM):i._updateRtpTransceiver(void 0);});}}function pV(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),s=0;s{this.p2pChannel&&(this.updateRemoteStats(this.p2pChannel),this.updateLocalStats(this.p2pChannel));}),this.store=e,this.updateStatsInterval=window.setInterval(this.updateStats,1e3),this.exceptionMonitor=new TU(),this.exceptionMonitor.on("exception",(e,t,i)=>{this.onStatsException&&this.onStatsException(e,t,i);});}reset(){this.localStats=new Map(),this.remoteStats=new Map(),this.trafficStats=void 0,this.trafficStatsPeerList=[],this.uplinkStats=void 0;}getLocalAudioTrackStats(){return this.localStats.get(lv.LocalAudioTrack)||EV({},XA);}getLocalVideoTrackStats(){return this.localStats.get(lv.LocalVideoTrack)||EV({},QA);}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(lv.LocalAudioTrack);r&&(e+=r.sendBytes,t+=r.sendBitrate);const s=this.localStats.get(lv.LocalVideoTrack);s&&(e+=s.sendBytes,t+=s.sendBitrate);const o=this.localStats.get(lv.LocalVideoLowTrack);o&&(e+=o.sendBytes,t+=o.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?RU.measureFromSubscribeStart(this.store.clientId,i.videoSSRC):0,r=null!=i&&i.audioSSRC?RU.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&&jC.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 lv.LocalVideoTrack:case lv.LocalVideoLowTrack:{const t=n,s=EV({},QA),o=e.getStats(),a=e.getLocalMedia(i);if(o){const i=o.videoSend.find(e=>e.ssrc===(null==a?void 0:a.ssrcs[0].ssrcId));if(i){const n=e.getLocalVideoSize(),r=e.getEncoderConfig(lv.LocalVideoTrack);"H264"!==i.codec&&"H265"!==i.codec&&"VP8"!==i.codec&&"VP9"!==i.codec&&"AV1X"!==i.codec&&"AV1"!==i.codec||(s.codecType=i.codec),s.sendBytes=i.bytes,s.sendBitrate=t?8*Math.max(0,s.sendBytes-t.sendBytes):0,i.inputFrame?(s.captureFrameRate=i.inputFrame.frameRate,s.captureResolutionHeight=i.inputFrame.height,s.captureResolutionWidth=i.inputFrame.width):n&&(s.captureResolutionWidth=n.width,s.captureResolutionHeight=n.height),i.sentFrame?(s.sendFrameRate=i.sentFrame.frameRate,s.sendResolutionHeight=i.sentFrame.height,s.sendResolutionWidth=i.sentFrame.width):n&&(s.sendResolutionWidth=n.width,s.sendResolutionHeight=n.height),i.avgEncodeMs&&(s.encodeDelay=i.avgEncodeMs),r&&r.bitrateMax&&(s.targetSendBitrate=1e3*r.bitrateMax),s.sendPackets=i.packets,s.sendPacketsLost=i.packetsLost,s.sendJitterMs=i.jitterMs,s.sendRttMs=i.rttMs,s.totalDuration=t?t.totalDuration+1:1,s.totalFreezeTime=t?t.totalFreezeTime:0,this.isLocalVideoFreeze(i)&&(s.totalFreezeTime+=1),i.scalabilityMode&&this.scalabilityMode!==i.scalabilityMode&&(jC.debug("[".concat(this.store.clientId,"]: The scalabilityMode of the video sending stream is ").concat(i.scalabilityMode)),this.scalabilityMode=i.scalabilityMode);}this.trafficStats&&(s.currentPacketLossRate=(this.trafficStats.B_pvlr4||0)/100);}var r;if(this.localStats.set(i,s),(null==t?void 0:t.sendResolutionWidth)!==s.sendResolutionWidth||(null==t?void 0:t.sendResolutionHeight)!==s.sendResolutionHeight)null===(r=this.onStatsChanged)||void 0===r||r.call(this,"resolution",{width:s.sendResolutionWidth,height:s.sendResolutionHeight});s&&a&&this.exceptionMonitor.setLocalVideoStats(this.store.uid,a.track,s);break;}case lv.LocalAudioTrack:{const t=n,r=EV({},XA),s=e.getStats(),o=e.getLocalMedia(i);if(s){const i=s.audioSend.find(e=>e.ssrc===(null==o?void 0:o.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(lv.LocalAudioTrack,r),r&&o&&this.exceptionMonitor.setLocalAudioStats(this.store.uid,o.track,r);break;}}});}updateRemoteStats(e){Array.from(this.remoteStats.entries()).forEach(t=>{var i,n;let[r,{videoStats:s,audioStats:o,videoPcStats:a}]=t;const c=o,d=s,l=a,u=EV({},ZA),h=EV({},eb),p=EV({},$A),{audioTrack:_,videoTrack:E,audioSSRC:m,videoSSRC:f}=e.getRemoteMedia(r);let g;g=e instanceof hV?e.getStats(!0):e.getStats();const T=null===(i=g)||void 0===i?void 0:i.audioRecv.find(e=>e.ssrc===m),S=null===(n=g)||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(T&&("opus"!==T.codec&&"aac"!==T.codec&&"PCMU"!==T.codec&&"PCMA"!==T.codec&&"G722"!==T.codec||(u.codecType=T.codec),T.outputLevel?u.receiveLevel=Math.round(32767*T.outputLevel):_&&(u.receiveLevel=Math.round(32767*_.getVolumeLevel())),u.receiveBytes=T.bytes,u.receivePackets=T.packets,u.receivePacketsLost=T.packetsLost,u.packetLossRate=u.receivePacketsLost/(u.receivePackets+u.receivePacketsLost),u.receiveBitrate=c?8*Math.max(0,u.receiveBytes-c.receiveBytes):0,u.totalDuration=c?c.totalDuration+1:1,u.totalFreezeTime=c?c.totalFreezeTime:0,u.freezeRate=u.totalFreezeTime/u.totalDuration,u.receiveDelay=T.jitterBufferMs,u.totalDuration>10&&mV.isRemoteAudioFreeze(_)&&(u.totalFreezeTime+=1)),S){"H264"!==S.codec&&"H265"!==S.codec&&"VP8"!==S.codec&&"VP9"!==S.codec&&"AV1X"!==S.codec&&"AV1"!==S.codec||(h.codecType=S.codec),h.receiveBytes=S.bytes,h.receiveBitrate=d?8*Math.max(0,h.receiveBytes-d.receiveBytes):0,h.decodeFrameRate=S.decodeFrameRate<0?0:S.decodeFrameRate,h.renderFrameRate=S.decodeFrameRate<0?0:S.decodeFrameRate,S.outputFrame&&(h.renderFrameRate=S.outputFrame.frameRate),S.receivedFrame?(h.receiveFrameRate=S.receivedFrame.frameRate,h.receiveResolutionHeight=S.receivedFrame.height,h.receiveResolutionWidth=S.receivedFrame.width):E&&(h.receiveResolutionHeight=E._videoHeight||0,h.receiveResolutionWidth=E._videoWidth||0),void 0!==S.framesRateFirefox&&(h.receiveFrameRate=Math.round(S.framesRateFirefox)),h.receivePackets=S.packets,h.receivePacketsLost=S.packetsLost,h.packetLossRate=h.receivePacketsLost/(h.receivePackets+h.receivePacketsLost),h.totalDuration=d?d.totalDuration+1:1,h.totalFreezeTime=d?d.totalFreezeTime:0,h.receiveDelay=S.jitterBufferMs||0;const t=!!f&&e.getRemoteVideoIsReady(f);E&&t&&mV.isRemoteVideoFreeze(E,S,l)&&(h.totalFreezeTime+=1),h.freezeRate=h.totalFreezeTime/h.totalDuration;}R&&(u.end2EndDelay=R.B_ad,h.end2EndDelay=R.B_vd,u.transportDelay=R.B_ed,h.transportDelay=R.B_ed,u.currentPacketLossRate=R.B_ealr4/100,h.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:u,videoStats:h,videoPcStats:S,networkStats:p}),_&&this.exceptionMonitor.setRemoteAudioStats(_,u),E&&this.exceptionMonitor.setRemoteVideoStats(E,h);});}}function fV(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 gV(e){for(var t=1;t{this.reconnectMode="retry",this.startPingPong();}),sh(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===RI.INJECT?this.emit(jI.INJECT_STREAM_STATUS,t):(eI.workerEvent(this.spec.sid,{actionType:"status",serverCode:t.code,workerType:this.serviceMode===RI.TRANSCODE?1:2}),this.emit(jI.PUBLISH_STREAM_STATUS,t));}),this.spec=t,this.token=e,this.serviceMode=n,this.websocket=new zv("live-streaming",i),this.websocket.on(SI.CONNECTED,this.handleWebSocketOpen),this.websocket.on(SI.ON_MESSAGE,this.handleWebSocketMessage),this.websocket.on(SI.REQUEST_NEW_URLS,(e,t)=>{vT(this,jI.REQUEST_NEW_ADDRESS).then(e).catch(t);}),this.websocket.on(SI.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,s=this.reqId;if(!s||!this.websocket)throw new LI(Hg.UNEXPECTED_ERROR);const o=gV({command:e,sdkVersion:"4.20.2"===EC?"0.0.1":EC,seq:s,requestId:s,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 LI(Hg.WS_DISCONNECT);const a=()=>new cg((e,t)=>{this.websocket.once(SI.CLOSED,()=>t(new LI(Hg.WS_ABORT))),this.websocket.once(SI.CONNECTED,e);});"connected"!==this.websocket.state&&(await a()),o.clientRequest&&(o.clientRequest.workerToken=this.token);const c=new cg((e,t)=>{const i=()=>{t(new LI(Hg.WS_ABORT));};this.websocket.once(SI.RECONNECTING,i),this.websocket.once(SI.CLOSED,i),this.once("@".concat(s,"-").concat(this.spec.sid),t=>{e(t);});});n&&eI.workerEvent(this.spec.sid,gV(gV({},n),{},{requestId:r,actionType:"request",payload:JSON.stringify(t.clientRequest),serverCode:0,code:0}));const d=Date.now();this.websocket.sendMessage(o);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&&eI.workerEvent(this.spec.sid,gV(gV({},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.20.2"===EC?"0.0.1":EC;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 WI.LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM:return void jC.warning("live stream response already exists stream");case WI.LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR:case WI.LIVE_STREAM_RESPONSE_BAD_STREAM:case WI.LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR:return new LI(Hg.LIVE_STREAMING_INVALID_ARGUMENT,"",{code:e.code}).throw();case WI.LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST:if("UnpublishStream"===e.serverResponse.command||"UninjectStream"===e.serverResponse.command)return;throw new LI(Hg.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream response wm worker not exist",{retry:!0});case WI.LIVE_STREAM_RESPONSE_NOT_AUTHORIZED:return new LI(Hg.LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED,"",{code:e.code}).throw();case WI.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE:{const t=new LI(Hg.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE);return this.emit(jI.WARNING,t,e.serverResponse.url);}case WI.LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN:{const t=new LI(Hg.LIVE_STREAMING_WARN_FREQUENT_REQUEST);return this.emit(jI.WARNING,t,e.serverResponse.url);}case WI.LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH:throw new LI(Hg.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream response wm worker not exist",{retry:!0});case WI.LIVE_STREAM_RESPONSE_NOT_SUPPORTED:return new LI(Hg.LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED,"",{code:e.code}).throw();case WI.LIVE_STREAM_RESPONSE_MAX_STREAM_NUM:{const t=new LI(Hg.LIVE_STREAMING_WARN_STREAM_NUM_REACH_LIMIT);return this.emit(jI.WARNING,t,e.serverResponse.url);}case WI.LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR:return new LI(Hg.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"",{code:e.code}).throw();case WI.LIVE_STREAM_RESPONSE_RESOURCE_LIMIT:throw new LI(Hg.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream resource limit",{retry:!0,changeAddress:!0});case WI.LIVE_STREAM_RESPONSE_WORKER_LOST:case WI.LIVE_STREAM_RESPONSE_WORKER_QUIT:if("UnpublishStream"===e.serverResponse.command||"UninjectStream"===e.serverResponse.command)return;throw new LI(Hg.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{retry:!0,changeAddress:!0});case WI.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 LI(Hg.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{code:e.code}).throw();throw new LI(Hg.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{retry:!0,changeAddress:!0});case WI.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN:case WI.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT:case WI.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE:case WI.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH:return new LI(Hg.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(sS);},6e3);}}function SV(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 RV(e){for(var t=1;t1&&void 0!==arguments[1]?arguments[1]:ES,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:ES;super(),sh(this,"onLiveStreamWarning",void 0),sh(this,"onLiveStreamError",void 0),sh(this,"onInjectStatusChange",void 0),sh(this,"spec",void 0),sh(this,"retryTimeout",1e4),sh(this,"connection",void 0),sh(this,"httpRetryConfig",void 0),sh(this,"wsRetryConfig",void 0),sh(this,"streamingTasks",new Map()),sh(this,"isStartingStreamingTask",!1),sh(this,"taskMutex",new pS("live-streaming")),sh(this,"cancelToken",sC.CancelToken.source()),sh(this,"transcodingConfig",void 0),sh(this,"injectConfig",RV({},BI)),sh(this,"injectLoopTimes",0),sh(this,"uapResponse",void 0),sh(this,"lastTaskId",1),sh(this,"statusError",new Map()),this.spec=e,this.httpRetryConfig=i,this.wsRetryConfig=t;}async setTranscodingConfig(e){const t=RV(RV({},FI),e);66!==t.videoCodecProfile&&77!==t.videoCodecProfile&&100!==t.videoCodecProfile&&(jC.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=>RV(RV(RV({},UI),e),{},{zOrder:e.zOrder?e.zOrder+1:1}))),function(e){Zg(e.width)||zg(e.width,"config.width",0,1e4),Zg(e.height)||zg(e.height,"config.height",0,1e4),Zg(e.videoBitrate)||zg(e.videoBitrate,"config.videoBitrate",1,1e6),Zg(e.videoFrameRate)||zg(e.videoFrameRate,"config.videoFrameRate"),Zg(e.lowLatency)||Yg(e.lowLatency,"config.lowLatency"),Zg(e.audioSampleRate)||qg(e.audioSampleRate,"config.audioSampleRate",[32e3,44100,48e3]),Zg(e.audioBitrate)||zg(e.audioBitrate,"config.audioBitrate",1,128),Zg(e.audioChannels)||qg(e.audioChannels,"config.audioChannels",[1,2,3,4,5]),Zg(e.videoGop)||zg(e.videoGop,"config.videoGop"),Zg(e.videoCodecProfile)||qg(e.videoCodecProfile,"config.videoCodecProfile",[66,77,100]),Zg(e.userCount)||zg(e.userCount,"config.userCount",0,17),Zg(e.backgroundColor)||zg(e.backgroundColor,"config.backgroundColor",0,16777215),Zg(e.userConfigExtraInfo)||Xg(e.userConfigExtraInfo,"config.userConfigExtraInfo",0,4096,!1),e.transcodingUsers&&!Zg(e.transcodingUsers)&&(Qg(e.transcodingUsers,"config.transcodingUsers"),e.transcodingUsers.forEach((e,t)=>{MI(e.uid),Zg(e.x)||zg(e.x,"transcodingUser[".concat(t,"].x"),0,1e4),Zg(e.y)||zg(e.y,"transcodingUser[".concat(t,"].y"),0,1e4),Zg(e.width)||zg(e.width,"transcodingUser[".concat(t,"].width"),0,1e4),Zg(e.height)||zg(e.height,"transcodingUser[".concat(t,"].height"),0,1e4),Zg(e.zOrder)||zg(e.zOrder-1,"transcodingUser[".concat(t,"].zOrder"),0,100),Zg(e.alpha)||zg(e.alpha,"transcodingUser[".concat(t,"].alpha"),0,1,!1);})),Zg(e.watermark)||VI(e.watermark,"watermark"),Zg(e.backgroundImage)||VI(e.backgroundImage,"backgroundImage"),e.images&&!Zg(e.images)&&(Qg(e.images,"config.images"),e.images.forEach((e,t)=>{VI(e,"images[".concat(t,"]"));}));}(t);const i=[];t.images&&i.push(...t.images.map(e=>RV(RV(RV({},xI),e),{},{zOrder:255}))),t.backgroundImage&&(i.push(RV(RV(RV({},xI),t.backgroundImage),{},{zOrder:0})),delete t.backgroundImage),t.watermark&&(i.push(RV(RV(RV({},xI),t.watermark),{},{zOrder:255})),delete t.watermark),t.images=i,t.transcodingUsers&&(t.userConfigs=t.transcodingUsers.map(e=>RV({},e)),t.userCount=t.transcodingUsers.length,delete t.transcodingUsers);const n=(t.userConfigs||[]).map(e=>"number"==typeof e.uid?cg.resolve(e.uid):pA(e.uid,this.spec,this.cancelToken.token,this.httpRetryConfig));if((await cg.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(NI(r=this.streamingTasks).call(r)).map(e=>e.taskId).join("#")});jC.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=>{jC.warning("[".concat(this.spec.clientId,"] live streaming receive error"),e.toString(),"try to republish",t.url),this.startLiveStreamingTask(t.url,t.mode,e).then(()=>{jC.debug("[".concat(this.spec.clientId,"] live streaming republish ").concat(t.url," success"));}).catch(e=>{jC.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;if(Array.from(NI(n=this.streamingTasks).call(n)).find(e=>e.mode===RI.INJECT)&&t===RI.INJECT)return new LI(Hg.LIVE_STREAMING_TASK_CONFLICT,"inject stream over limit").throw();if(!this.transcodingConfig&&t===RI.TRANSCODE)throw new LI(Hg.INVALID_OPERATION,"[LiveStreaming] no transcoding config found, can not start transcoding streaming task");let r={command:"PublishStream",ts:Date.now(),url:e,uid:this.spec.uid.toString(),autoDestroyTime:100,acceptImageTimeout:!0};jC.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 LI(Hg.LIVE_STREAMING_TASK_CONFLICT).throw();try{this.connection||(this.connection=await this.connect(t));}catch(e){throw s(),e;}switch(t){case RI.TRANSCODE:r.transcodingConfig=RV({},this.transcodingConfig);break;case RI.RAW:break;case RI.INJECT:r={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&&(r.vid=this.uapResponse.vid),this.isStartingStreamingTask=!0;const o=this.lastTaskId++;try{const n=new cg((t,n)=>{iS(this.retryTimeout).then(()=>{if(i)return n(i);const t=this.statusError.get(e);return t?(this.statusError.delete(e),n(t)):void 0;});}),a=await cg.race([this.connection.request("request",{clientRequest:r},!0,{url:e,command:"PublishStream",workerType:t===RI.TRANSCODE?1:2,requestByUser:!i,tid:o.toString()}),n]);this.isStartingStreamingTask=!1,jC.debug("[".concat(this.spec.clientId,"] live streaming started, code: ").concat(a.code)),this.streamingTasks.set(e,{clientRequest:r,mode:t,url:e,taskId:o}),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 cg((t,i)=>{const n=this.streamingTasks.get(e);if(!n||!this.connection)return new LI(Hg.UNEXPECTED_ERROR,"can not find streaming task to stop").throw();const r=n.mode;n.abortTask=()=>{jC.debug("[".concat(this.spec.clientId,"] stop live streaming success(worker exception)")),this.streamingTasks.delete(e),t();},this.connection.request("request",{clientRequest:{command:r===RI.INJECT?"UninjectStream":"UnpublishStream",url:n.url}},!1,{url:e,command:"UnPublishStream",workerType:r===RI.TRANSCODE?1:2,requestByUser:!0,tid:(this.lastTaskId++).toString()}).then(i=>{jC.debug("[".concat(this.spec.clientId,"] stop live streaming success, code: ").concat(i.code)),this.streamingTasks.delete(e),0===this.streamingTasks.size&&r!==RI.INJECT&&(this.connection&&this.connection.close(),this.connection=void 0),t(),r===RI.INJECT&&this.onInjectStatusChange&&this.onInjectStatusChange(CI.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!==RI.INJECT)throw new LI(Hg.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(NI(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=sC.CancelToken.source(),this.uapResponse=void 0,this.connection&&this.connection.close(),this.connection=void 0;}async connect(e){if(this.connection)throw new LI(Hg.UNEXPECTED_ERROR,"live streaming connection has already connected");const t=await vT(this,GI.REQUEST_WORKER_MANAGER_LIST,e);return this.uapResponse=t,this.connection=new TV(t.workerToken,this.spec,this.wsRetryConfig,e),this.connection.on(jI.WARNING,(e,t)=>this.onLiveStreamWarning&&this.onLiveStreamWarning(t,e)),this.connection.on(jI.PUBLISH_STREAM_STATUS,e=>this.handlePublishStreamServer(e)),this.connection.on(jI.INJECT_STREAM_STATUS,e=>this.handleInjectStreamServerStatus(e)),this.connection.on(jI.REQUEST_NEW_ADDRESS,(t,i)=>{if(!this.connection)return i(new LI(Hg.UNEXPECTED_ERROR,"can not get new live streaming address list"));vT(this,GI.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 WI.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN:case WI.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT:case WI.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE:case WI.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH:{const n=new LI(Hg.LIVE_STREAMING_CDN_ERROR,"",{code:e.code});if(i)return jC.error(n.toString()),this.onLiveStreamError&&this.onLiveStreamError(t,n);if(!this.isStartingStreamingTask)return;this.statusError.set(t,n);}case WI.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE:{const e=new LI(Hg.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE,n);return this.onLiveStreamWarning&&this.onLiveStreamWarning(t,e);}case WI.LIVE_STREAM_RESPONSE_WORKER_LOST:case WI.LIVE_STREAM_RESPONSE_WORKER_QUIT:{var r;if(!this.connection)return;this.connection.tryNextAddress();const t=Array.from(NI(r=this.streamingTasks).call(r));for(const i of t)i.abortTask?i.abortTask():(jC.warning("[".concat(this.spec.clientId,"] publish stream status code"),e.code,"try to republish",i.url),this.startLiveStreamingTask(i.url,i.mode,new LI(Hg.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"",{code:e.code})).then(()=>{jC.debug("[".concat(this.spec.clientId,"] republish live stream success"),i.url);}).catch(e=>{jC.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(CI.INJECT_STREAM_STATUS_START_SUCCESS,t,i));case 451:return this.onInjectStatusChange&&this.onInjectStatusChange(CI.INJECT_STREAM_STATUS_START_ALREADY_EXISTS,t,i),void this.streamingTasks.delete(i);case 453:return this.onInjectStatusChange&&this.onInjectStatusChange(CI.INJECT_STREAM_STATUS_START_UNAUTHORIZED,t,i),void this.streamingTasks.delete(i);case 470:return this.onInjectStatusChange&&this.onInjectStatusChange(CI.INJECT_STREAM_STATUS_BROKEN,t,i),void this.streamingTasks.delete(i);case 499:return this.onInjectStatusChange&&this.onInjectStatusChange(CI.INJECT_STREAM_STATUS_START_TIMEOUT,t,i),void this.streamingTasks.delete(i);default:return void jC.debug("inject stream server status",e);}}hasUrl(e){return this.streamingTasks.has(e);}}class IV{constructor(){sh(this,"destChannelMediaInfos",new Map()),sh(this,"srcChannelMediaInfo",void 0);}setSrcChannelInfo(e){tv(e),this.srcChannelMediaInfo=e;}addDestChannelInfo(e){tv(e),this.destChannelMediaInfos.set(e.channelName,e);}removeDestChannelInfo(e){kI(e),this.destChannelMediaInfos.delete(e);}getSrcChannelMediaInfo(){return this.srcChannelMediaInfo;}getDestChannelMediaInfo(){return this.destChannelMediaInfos;}}function vV(e){if(!(e instanceof IV)){return new LI(Hg.INVALID_PARAMS,"Config should be instance of [ChannelMediaRelayConfiguration]").throw();}const t=e.getSrcChannelMediaInfo(),i=e.getDestChannelMediaInfo();if(!t){return new LI(Hg.INVALID_PARAMS,"srcChannelMediaInfo should not be empty").throw();}if(0===i.size){return new LI(Hg.INVALID_PARAMS,"destChannelMediaInfo should not be empty").throw();}}class yV extends dT{constructor(e,t,i){super(),sh(this,"ws",void 0),sh(this,"requestId",1),sh(this,"heartBeatTimer",void 0),sh(this,"joinInfo",void 0),sh(this,"clientId",void 0),sh(this,"onOpen",()=>{this.emit("open"),this.startHeartBeatCheck();}),sh(this,"onClose",e=>{this.emit("close"),this.dispose();}),sh(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 zv("cross-channel-".concat(this.clientId),i),this.ws.on(SI.RECONNECTING,()=>{this.ws.reconnectMode="retry",this.emit("reconnecting");}),this.ws.on(SI.CONNECTED,this.onOpen),this.ws.on(SI.ON_MESSAGE,this.onMessage),this.ws.on(SI.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 cg((t,i)=>{const n=window.setTimeout(()=>{i(new LI(Hg.TIMEOUT,"wait status timeout, status: ".concat(e)));},5e3);this.once(e,r=>{window.clearTimeout(n),r.state&&0!==r.state?i(new LI(Hg.CROSS_CHANNEL_WAIT_STATUS_ERROR,"wait status error, status: ".concat(e))):t(void 0);}),this.once("dispose",()=>{window.clearTimeout(n),i(new LI(Hg.WS_ABORT));});});}async request(e){if("closed"===this.ws.state)throw new LI(Hg.WS_DISCONNECT);const t=()=>new cg((e,t)=>{this.ws.once(SI.CLOSED,()=>t(new LI(Hg.WS_ABORT))),this.ws.once(SI.CONNECTED,e);});"connected"!==this.ws.state&&(await t());const i=this.sendMessage(e),n=new cg((e,t)=>{const n=()=>{t(new LI(Hg.WS_ABORT));};this.ws.once(SI.RECONNECTING,n),this.ws.once(SI.CLOSED,n),this.once("req_".concat(i),e),iS(3e3).then(()=>{this.removeAllListeners("req_".concat(i)),this.ws.off(SI.RECONNECTING,n),this.ws.off(SI.CLOSED,n),t(new LI(Hg.TIMEOUT,"cross channel ws request timeout"));});}),r=await n;if(!r||200!==r.code)throw new LI(Hg.CROSS_CHANNEL_SERVER_ERROR_RESPONSE,"response: ".concat(JSON.stringify(r)));return r;}async connect(e){this.ws.removeAllListeners(SI.REQUEST_NEW_URLS),this.ws.on(SI.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 AV extends dT{set state(e){e!==this._state&&(e!==qI.RELAY_STATE_FAILURE&&(this.errorCode=zI.RELAY_OK),this.emit("state",e,this.errorCode),this._state=e);}get state(){return this._state;}constructor(e,t,i,n,r){super(),sh(this,"joinInfo",void 0),sh(this,"sid",void 0),sh(this,"clientId",void 0),sh(this,"cancelToken",sC.CancelToken.source()),sh(this,"workerToken",void 0),sh(this,"requestId",0),sh(this,"signal",void 0),sh(this,"prevChannelMediaConfig",void 0),sh(this,"httpRetryConfig",void 0),sh(this,"_resolution",void 0),sh(this,"_state",qI.RELAY_STATE_IDLE),sh(this,"errorCode",zI.RELAY_OK),sh(this,"onStatus",e=>{jC.debug("[".concat(this.clientId,"] ChannelMediaStatus: ").concat(JSON.stringify(e))),e&&e.command&&("onAudioPacketReceived"===e.command&&this.emit("event",YI.PACKET_RECEIVED_AUDIO_FROM_SRC),"onVideoPacketReceived"===e.command&&this.emit("event",YI.PACKET_RECEIVED_VIDEO_FROM_SRC),"onSrcTokenPrivilegeDidExpire"===e.command&&(this.errorCode=zI.SRC_TOKEN_EXPIRED,this.state=qI.RELAY_STATE_FAILURE),"onDestTokenPrivilegeDidExpire"===e.command&&(this.errorCode=zI.DEST_TOKEN_EXPIRED,this.state=qI.RELAY_STATE_FAILURE));}),sh(this,"onReconnect",async()=>{jC.debug("[".concat(this.clientId,"] ChannelMediaSocket disconnect, reconnecting")),this.emit("event",YI.NETWORK_DISCONNECTED),this.state=qI.RELAY_STATE_IDLE,this.prevChannelMediaConfig&&this.sendStartRelayMessage(this.prevChannelMediaConfig).catch(e=>{this.state!==qI.RELAY_STATE_IDLE&&(jC.error("auto restart channel media relay failed",e.toString()),this.errorCode=zI.SERVER_CONNECTION_LOST,this.state=qI.RELAY_STATE_FAILURE);});}),this.joinInfo=e,this.clientId=t,this.sid=rS(),this.signal=new yV(this.joinInfo,this.clientId,i),this.httpRetryConfig=n,this._resolution=r;}async startChannelMediaRelay(e){if(this.state!==qI.RELAY_STATE_IDLE)throw new LI(Hg.INVALID_OPERATION);this.state=qI.RELAY_STATE_CONNECTING,await this.connect(),jC.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 LI(Hg.CROSS_CHANNEL_FAILED_JOIN_SRC);if(e.data&&e.data.serverResponse&&"SetDestChannelStatus"===e.serverResponse.command)throw new LI(Hg.CROSS_CHANNEL_FAILED_JOIN_DEST);if(e.data&&e.data.serverResponse&&"StartPacketTransfer"===e.serverResponse.command)throw new LI(Hg.CROSS_CHANNEL_FAILED_PACKET_SENT_TO_DEST);throw e;}this.prevChannelMediaConfig=e;}async updateChannelMediaRelay(e){if(this.state!==qI.RELAY_STATE_RUNNING)throw new LI(Hg.INVALID_OPERATION);await this.sendUpdateMessage(e),this.prevChannelMediaConfig=e;}async setVideoProfile(e){if(this._resolution=e,this.state!==qI.RELAY_STATE_RUNNING)throw new LI(Hg.INVALID_OPERATION);const t=this.genMessage(KI.SetVideoProfile);await this.signal.request(t),jC.debug("[".concat(this.clientId,"] startChannelMediaRelay: setVideoProfile success"));}async stopChannelMediaRelay(){await this.sendStopRelayMessage(),jC.debug("[".concat(this.clientId,"] stopChannelMediaRelay: send stop message success")),this.state=qI.RELAY_STATE_IDLE,this.dispose();}dispose(){jC.debug("[".concat(this.clientId,"] disposeChannelMediaRelay")),this.cancelToken.cancel(),this.cancelToken=sC.CancelToken.source(),this.state=qI.RELAY_STATE_IDLE,this.emit("dispose"),this.signal.dispose(),this.prevChannelMediaConfig=void 0;}async connect(){const e=await fA(this.joinInfo,this.cancelToken.token,this.httpRetryConfig);this.workerToken=e.workerToken,await this.signal.connect(e.addressList),this.emit("event",YI.NETWORK_CONNECTED),this.signal.on("status",this.onStatus),this.signal.on("reconnecting",this.onReconnect);}async sendStartRelayMessage(e){const t=this.genMessage(KI.StopPacketTransfer);await this.signal.request(t),await this.signal.waitStatus("Normal Quit"),jC.debug("[".concat(this.clientId,"] startChannelMediaRelay: StopPacketTransfer success"));const i=this.genMessage(KI.SetSdkProfile,e);await this.signal.request(i),jC.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSdkProfile success"));const n=this.genMessage(KI.SetSourceChannel,e);await this.signal.request(n),await this.signal.waitStatus("SetSourceChannelStatus"),this.emit("event",YI.PACKET_JOINED_SRC_CHANNEL),jC.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSourceChannel success"));const r=this.genMessage(KI.SetSourceUserId,e);await this.signal.request(r),jC.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSourceUserId success"));const s=this.genMessage(KI.SetDestChannel,e);await this.signal.request(s),await this.signal.waitStatus("SetDestChannelStatus"),this.emit("event",YI.PACKET_JOINED_DEST_CHANNEL),jC.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetDestChannel success"));const o=this.genMessage(KI.StartPacketTransfer,e);await this.signal.request(o),this.emit("event",YI.PACKET_SENT_TO_DEST_CHANNEL),this.state=qI.RELAY_STATE_RUNNING,jC.debug("[".concat(this.clientId,"] startChannelMediaRelay: StartPacketTransfer success")),this.setVideoProfile(this._resolution);}async sendUpdateMessage(e){const t=this.genMessage(KI.UpdateDestChannel,e);await this.signal.request(t),this.emit("event",YI.PACKET_UPDATE_DEST_CHANNEL),jC.debug("[".concat(this.clientId,"] sendUpdateMessage: UpdateDestChannel success"));}async sendStopRelayMessage(){const e=this.genMessage(KI.StopPacketTransfer);await this.signal.request(e),jC.debug("[".concat(this.clientId,"] sendStopRelayMessage: StopPacketTransfer success"));}genMessage(e,t){const i=[],n=[],r=[];this.requestId+=1;const s={appId:this.joinInfo.appId,cname:this.joinInfo.cname,uid:this.joinInfo.uid.toString(),sdkVersion:EC,sid:this.sid,ts:Date.now(),requestId:this.requestId,seq:this.requestId,allocate:!0,clientRequest:{}};"4.20.2"===s.sdkVersion&&(s.sdkVersion="0.0.1");let o=null,a=null;switch(e){case KI.SetSdkProfile:return s.clientRequest={command:"SetSdkProfile",type:"multi_channel"},s;case KI.SetSourceChannel:if(a=t&&t.getSrcChannelMediaInfo(),!a)throw new LI(Hg.UNEXPECTED_ERROR,"can not find source config");return s.clientRequest={command:"SetSourceChannel",uid:"0",channelName:a.channelName,token:a.token||this.joinInfo.appId},s;case KI.SetSourceUserId:if(a=t&&t.getSrcChannelMediaInfo(),!a)throw new LI(Hg.UNEXPECTED_ERROR,"can not find source config");return s.clientRequest={command:"SetSourceUserId",uid:a.uid+""},s;case KI.SetDestChannel:if(o=t&&t.getDestChannelMediaInfo(),!o)throw new LI(Hg.UNEXPECTED_ERROR,"can not find dest config");return o.forEach(e=>{i.push(e.channelName),n.push(e.uid+""),r.push(e.token||this.joinInfo.appId);}),s.clientRequest={command:"SetDestChannel",channelName:i,uid:n,token:r},s;case KI.StartPacketTransfer:return s.clientRequest={command:"StartPacketTransfer"},s;case KI.Reconnect:return s.clientRequest={command:"Reconnect"},s;case KI.StopPacketTransfer:return s.clientRequest={command:"StopPacketTransfer"},s;case KI.UpdateDestChannel:if(o=t&&t.getDestChannelMediaInfo(),!o)throw new LI(Hg.UNEXPECTED_ERROR,"can not find dest config");return o.forEach(e=>{i.push(e.channelName),n.push(e.uid+""),r.push(e.token||this.joinInfo.appId);}),s.clientRequest={command:"UpdateDestChannel",channelName:i,uid:n,token:r},s;case KI.SetVideoProfile:s.clientRequest={command:"SetVideoProfile",width:this._resolution.width,height:this._resolution.height};}return s;}}function bV(e){var t={},i=!1;function n(t,n){return i=!0,{done:!1,value:new CU(n=new wU(function(i){i(e[t](n));}),1)};}return t[void 0!==xu&&th||"@@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 wV=i(OU);function OV(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 NV(e){for(var t=1;te.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").filter(e=>{var t;return bn(t=Object.keys(bC)).call(t,e);}))];}constructor(e,t){super(e,t),sh(this,"store",void 0),sh(this,"peerConnection",void 0),sh(this,"remoteSDP",void 0),sh(this,"initialOffer",void 0),sh(this,"statsFilter",void 0),sh(this,"useRTX",!1),sh(this,"localCapabilities",void 0),sh(this,"localCandidateCount",0),sh(this,"allCandidatesReceived",!1),sh(this,"establishPromise",void 0),sh(this,"mutex",new pS("P2PConnection-mutex")),this.store=t,this.peerConnection=new RTCPeerConnection(LV.resolvePCConfiguration(e),{optional:[{googDscp:!0}]}),this.statsFilter=Ex(this.peerConnection,RC("STATS_UPDATE_INTERVAL"),void 0,wg()?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=Tx(e.sdp),i=gx(e.sdp,{filterRTX:!this.useRTX,filterVideoFec:RC("FILTER_VIDEO_FEC"),filterAudioFec:RC("FILTER_AUDIO_FEC"),filterAudioCodec:["opus"]});return this.localCapabilities=i,this.initialOffer=e,PV(PV({},t),{},{rtpCapabilities:{send:{audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},recv:{audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},sendrecv:i},offerSDP:e.sdp});}catch(e){throw new Kg(Hg.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString());}}async connect(e,t,i,n,r,s){try{if(!this.initialOffer)throw new Error("Cannot establish P2PConnection without initial offer.");this.remoteSDP=new class{constructor(e){sh(this,"sessionDesc",void 0),sh(this,"localCapabilities",void 0),sh(this,"rtpCapabilities",void 0),sh(this,"candidates",void 0),sh(this,"iceParameters",void 0),sh(this,"dtlsParameters",void 0),sh(this,"setup",void 0),sh(this,"currentMidIndex",void 0),sh(this,"cname",void 0),e=YT(e);const{remoteIceParameters:t,remoteDtlsParameters:i,candidates:n,remoteRTPCapabilities:r,remoteSetup:s,localCapabilities:o,sdkCodec:a,cname:c}=e,d=JU.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=s,this.localCapabilities=o,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:bn(i=t.encodingName.toLowerCase()).call(i,a);});0===e.length&&(e=r.videoCodecs),o.attributes.payloads=e,o.attributes.extmaps=r.videoExtensions;}"audio"===o.media.mediaType&&(o.media.fmts=r.audioCodecs.map(e=>e.payloadType.toString(10)),o.attributes.payloads=r.audioCodecs,o.attributes.extmaps=r.audioExtensions),d.mediaDescriptions[e]=this.mungMediaDesc(o);}this.sessionDesc=d,this.currentMidIndex=d.mediaDescriptions.length-1;}toString(){return JU.print(this.sessionDesc);}send(e,t,i){const{ssrcs:n,ssrcGroups:r}=Cx(t,this.cname),s=this.sessionDesc.mediaDescriptions.find(t=>e===av.VIDEO?"video"===t.media.mediaType:"audio"===t.media.mediaType),o=n[0].attributes.label,a=n[0].attributes.mslabel;return s.attributes.ssrcs=s.attributes.ssrcs.concat(n),s.attributes.ssrcGroups=s.attributes.ssrcGroups.concat(r),{id:o,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=>{bn(e).call(e,t.attributes.label||"")?r.push(t):i.push(t);}),t.attributes.ssrcGroups.forEach(e=>{var t;bn(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===cv.TCP?this.candidates.forEach(e=>{-1===this.candidates.findIndex(t=>"tcp"===t.transport&&t.connectionAddress===e.connectionAddress&&t.port===e.port)&&this.candidates.push(NV(NV({},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=YT(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===av.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=YT(e);return vx(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:s});const o=this.remoteSDP.toString();await this.peerConnection.setLocalDescription(this.initialOffer),await this.peerConnection.setRemoteDescription({type:"answer",sdp:o});}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(e.toString()));}}async updateRemoteRTPCapabilities(e,t){throw new Kg(Hg.NOT_SUPPORTED,"Planb mode does not support createDataChannels.");}send(e,t){var i=this;return PU(function*(){const n=yield IU(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)),s=yield IU(i.peerConnection.createOffer()),o=JU.parse(s.sdp),a=e.map(e=>{const t=e._mediaStreamTrack,n=o.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=>{bg()&&e.replaceTrack(null),i.peerConnection.removeTrack(e);}),e;}const d=i.mungSendOfferSDP(s.sdp,e);i.remoteSDP.receive(e,t,c);const l=i.remoteSDP.toString();return yield IU(i.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield IU(i.applySendEncodings(r,e)),yield IU(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 Kg(Hg.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=>{bg()&&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 Kg(Hg.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),s=new cg((t,n)=>{const s=setTimeout(()=>{n(new Error("Cannot receive track, id: ".concat(i)));},1e4),o=n=>{const a=Sg();if(("Safari"===a.name&&11===Number(a.version)||Og())&&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",o),clearTimeout(s),void t(r);}if(n.track.id===i)return this.peerConnection.removeEventListener("track",o),clearTimeout(s),void t(n.track);};this.peerConnection.addEventListener("track",o);}),o=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:o});const a=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(a);return {track:await s,id:i};}catch(e){throw new Kg(Hg.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 Kg(Hg.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(bg()&&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 Kg(Hg.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(bg()&&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 Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteLocal failed; ".concat(e.toString()));}}restartICE(e){var t=this;return PU(function*(){const i=yield IU(t.mutex.lock("From P2PConnection.restartICE"));try{if(!t.remoteSDP)throw new Error("Cannot restartICE before remoteSDP created.");if(IA().supportPCSetConfiguration){const i=t.peerConnection.getConfiguration(),n=e===cv.RELAY?"relay":"all";i.iceTransportPolicy!==n&&(jC.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===cv.RELAY)return;e!==cv.RELAY&&t.remoteSDP.updateCandidates(e);const n=yield IU(t.peerConnection.createOffer({iceRestart:!0}));if(!n.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const r=Tx(n.sdp),{remoteIceParameters:s}=yield r.iceParameters;t.remoteSDP.restartICE(s);const o=t.remoteSDP.toString();yield IU(t.peerConnection.setLocalDescription(n)),yield IU(t.peerConnection.setRemoteDescription({type:"answer",sdp:o}));}catch(e){jC.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 Kg(Hg.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 Kg(Hg.NOT_SUPPORTED,"Planb mode does not support createDataChannels.");}stopDataChannels(e){throw new Kg(Hg.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,jC.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount));},setTimeout(()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,jC.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount));},RC("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(e){const t={iceServers:[],sdpSemantics:"plan-b"};return e.iceServers?t.iceServers=e.iceServers:e.turnServer&&"off"!==e.turnServer.mode&&(RT(e.turnServer.servers)?t.iceServers=e.turnServer.servers:(t.iceServers&&t.iceServers.push(...LV.turnServerConfigToIceServers(e.turnServer.servers)),RC("USE_TURN_SERVER_OF_GATEWAY")&&t.iceServers&&e.turnServer.serversFromGateway&&t.iceServers.push(...LV.turnServerConfigToIceServers(e.turnServer.serversFromGateway)),e.turnServer.servers.concat(e.turnServer.serversFromGateway||[]).forEach(e=>{e.forceturn&&(t.iceTransportPolicy="relay");}))),t;}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 jC.warn("[".concat(e.getTrackId(),"] no rtpSender found}"));if(!IA().supportSetRtpSenderParameters)return jC.warn("Browser not support set rtp-sender parameters");const n={},r={};if(e instanceof Rw)switch(e._optimizationMode){case"motion":n.degradationPreference="maintain-framerate";break;case"detail":n.degradationPreference="maintain-resolution";break;default:n.degradationPreference="balanced";}if(RC("DSCP_TYPE")&&jg()){var s;const e=RC("DSCP_TYPE");bn(s=["very-low","low","medium","high"]).call(s,e)&&(r.networkPriority=e);}const o=t.getParameters(),a=null===(i=o.encodings)||void 0===i?void 0:i[0];a&&Object.assign(a,r),Object.assign(o,n),jC.debug("[".concat(e.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(o.encodings))),await t.setParameters(o);}async applySendEncodings(e,t){try{if(!IA().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&&Ix(r,e);}),JU.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:s}=e[i];return new cg((e,t)=>{const i=setTimeout(()=>{t(new Error("Cannot receive track, id: ".concat(n)));},1e4),o=t=>{const a=Sg();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(s,n,t.track.id),this.peerConnection.removeEventListener("track",o),clearTimeout(i),void e({track:r,id:n});}if(t.track.id===n)return this.peerConnection.removeEventListener("track",o),clearTimeout(i),void e({track:t.track,id:n});};this.peerConnection.addEventListener("track",o);});}),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 cg.all(t);}catch(e){throw new Kg(Hg.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(e){if(IA().supportPCSetConfiguration){const t=LV.resolvePCConfiguration(e);this.peerConnection.setConfiguration(t);}}}function kV(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,s=new Array(r),o=0;oe.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").filter(e=>{var t;return bn(t=Object.keys(bC)).call(t,e);}))];}constructor(e,t){super(e,t),sh(this,"store",void 0),sh(this,"peerConnection",void 0),sh(this,"remoteSDP",void 0),sh(this,"initialOffer",void 0),sh(this,"transportEventReceiver",void 0),sh(this,"statsFilter",void 0),sh(this,"useXR",RC("USE_XR")),sh(this,"localCapabilities",void 0),sh(this,"remoteCodecs",void 0),sh(this,"localCandidateCount",0),sh(this,"allCandidatesReceived",!1),sh(this,"dataStreamChannelMap",new Map()),sh(this,"establishPromise",void 0),sh(this,"recoveredDataChannelIds",[]),sh(this,"currentDataChannelId",1),sh(this,"mutex",new pS("P2PConnection-mutex")),this.store=t,this.peerConnection=new RTCPeerConnection(jV.resolvePCConfiguration(e),{optional:[{googDscp:!0}]}),this.statsFilter=Ex(this.peerConnection,RC("STATS_UPDATE_INTERVAL"),void 0,wg()?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 jC.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 jC.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=Tx(e.sdp),i=await Ox({filterRTX:!RC("USE_PUB_RTX")&&!RC("USE_SUB_RTX"),filterVideoFec:RC("FILTER_VIDEO_FEC"),filterAudioFec:RC("FILTER_AUDIO_FEC"),filterVideoCodec:RC("FILTER_VIDEO_CODEC")},{useXR:this.useXR});return this.localCapabilities=Px(i),this.initialOffer=e,BV(BV({},t),{},{rtpCapabilities:i,offerSDP:e.sdp});}catch(e){throw new Kg(Hg.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString());}}async connect(e,t,i,n,r,s){try{if(!this.initialOffer)throw new Error("Cannot establish P2PConnection without initial offer.");this.remoteSDP=new class{get localCapabilities(){return YT(this._localCapabilities);}get rtpCapabilities(){return YT(this._rtpCapabilities);}get candidates(){return YT(this._candidates);}get iceParameters(){return YT(this._iceParameters);}get dtlsParameters(){return YT(this._dtlsParameters);}constructor(e){sh(this,"sessionDesc",void 0),sh(this,"_localCapabilities",void 0),sh(this,"_rtpCapabilities",void 0),sh(this,"_candidates",void 0),sh(this,"_iceParameters",void 0),sh(this,"_dtlsParameters",void 0),sh(this,"setup",void 0),sh(this,"currentMidIndex",void 0),sh(this,"cname",void 0),sh(this,"firefoxSsrcMidMap",new Map()),e=YT(e);const{remoteIceParameters:t,remoteDtlsParameters:i,candidates:n,remoteRTPCapabilities:r,remoteSetup:s,localCapabilities:o,cname:a}=e,c=JU.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=o,this.setup=s,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=s,"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,RC("PRELOAD_MEDIA_COUNT")>0)){const{ssrcs:t,ssrcGroups:i}=Cx([{ssrcId:VV,rtx:RC("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,Lx(e),RC("PRELOAD_MEDIA_COUNT")>0)){const{ssrcs:t,ssrcGroups:i}=Cx([{ssrcId:2e4}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i;}}this.sessionDesc=c,this.currentMidIndex=c.mediaDescriptions.length-1;}preloadRemoteMedia(){const e=RC("PRELOAD_MEDIA_COUNT");this.rtpCapabilities;const t=this.candidates,i=this.dtlsParameters,n=this.iceParameters,r=this.rtpCapabilities.send;for(let s=1;se.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*s)}}),this.sessionDesc.mediaDescriptions.push({media:{mediaType:"audio",port:xV,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*s+1)}}),this.currentMidIndex+=2;}this.updateBundleMids();}toString(){return JU.print(this.sessionDesc);}send(e,t,i,n){const{ssrcs:r,ssrcGroups:s}=Cx(t,this.cname,RC("SYNC_GROUP")?i:void 0),o=this.findPreloadMediaDesc(r);if(o){if(wg()&&this.firefoxSsrcMidMap.set(r[0].ssrcId,o.attributes.mid),n&&(n.twcc||n.remb)){const e=this.sessionDesc.mediaDescriptions.indexOf(o);return this.sessionDesc.mediaDescriptions[e]=this.mungSendMediaDesc(o,n),{mid:o.attributes.mid,needExchangeSDP:!0};}return {mid:o.attributes.mid,needExchangeSDP:!1};}{const t=this.findAvailableMediaIndex(e,r);let i;return -1===t||1===t&&(bg()||Lg())||0===t&&RC("USE_SUB_RTX")||kg()?(i=this.createOrRecycleSendMedia(e,r,s,"sendonly",n),this.updateBundleMids()):(i=YT(this.sessionDesc.mediaDescriptions[t]),i.attributes.direction="sendonly",i.attributes.ssrcs=r,i.attributes.ssrcGroups=s,this.sessionDesc.mediaDescriptions[t]=this.mungSendMediaDesc(i,n)),wg()&&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||wg()||kg()?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=>bn(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=>bn(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===cv.TCP){if(0===t.length)return;if(RC("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(UV(UV({},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(UV(UV({},t),{},{foundation:"tcpcandidate",priority:Number(t.priority)-1+"",transport:"tcp",port:Number(t.port)+90+""}));}),this._candidates=[...t,...e];}}else if(e===cv.RELAY){if(0!==t.length)return;{const e=this._candidates.filter(e=>"tcp"===e.transport);e.forEach(e=>{t.push(UV(UV({},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(UV(UV({},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=YT(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(wg()){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:xV,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,s){const o=e._mediaStreamTrack.kind,a=this.rtpCapabilities.recv,c=Mx(o,a,this.localCapabilities.send,o===av.VIDEO?n:r),d=o===av.VIDEO?a.videoExtensions:a.audioExtensions;this.currentMidIndex+=1;const l="".concat(this.currentMidIndex);let u={media:{mediaType:o,port:xV,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)}};u=this.mungRecvMediaDsec(u,e,s);const h=this.findFirstClosedMedia(o);if(h){const e=this.sessionDesc.mediaDescriptions.indexOf(h);this.sessionDesc.mediaDescriptions[e]=u;}else this.sessionDesc.mediaDescriptions.push(u);return u;}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 bn(t=Object.keys(bC)).call(t,e);}))],r=new Set(t);if(n.every(e=>r.has(e)))return jC.debug("codecs has not changed, no need to updateRemoteCodec, codecs: ".concat(t)),!1;const s=this._rtpCapabilities.recv.videoCodecs.filter(e=>t.some(t=>{var i;return bn(i=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").call(i,t);}));if(0===s.length)return jC.debug("updateRemoteCodec failed, because cannot find matched codec, remoteCapabilities codecs: ".concat(n," codecs: ").concat(t)),!1;const o=[...new Set(s.map(e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||""))];let a;if(jC.debug("updateRemoteCodec, from ".concat(n," to ").concat(o)),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&&bn(e).call(e,t.attributes.mid)&&"recvonly"===t.attributes.direction),a.length!==e.length)return jC.debug("updateRemoteCodec failed, because cannot find mids, mids: ".concat(e,", codecs: ").concat(t)),!1;this._rtpCapabilities.recv.videoCodecs=s;const c=this.localCapabilities.send,d=this.rtpCapabilities.recv,l=Mx(av.VIDEO,d,c,i);return a.forEach(e=>{const t=l.map(e=>e.payloadType.toString(10));jC.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 s=this.rtpCapabilities.send,o=e===av.VIDEO?s.videoCodecs:s.audioCodecs,a=e===av.VIDEO?s.videoExtensions:s.audioExtensions;this.currentMidIndex+=1;const c="".concat(this.currentMidIndex);let d={media:{mediaType:e,port:xV,protos:["UDP","TLS","RTP","SAVPF"],fmts:o.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:o,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=YT(e);return vx(n),Ix(n,t),yx(n,t),Ax(n),bx(n,i,this.localCapabilities.send),n;}mungSendMediaDesc(e,t){const i=YT(e);return bx(i,t,this.localCapabilities.recv),Lx(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=>wg()?"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:s}),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0&&this.remoteSDP.updateRemoteCodec([],this.remoteCodecs,this.store.codec);const o=this.remoteSDP.toString(),a=JU.parse(this.initialOffer.sdp),c=a.mediaDescriptions.find(e=>"audio"===e.media.mediaType);c&&Lx(c),this.useXR&&kx(a);const d=JU.print(a),l=this.logSDPExchange(d||"","offer","local","connect");this.store.descriptionStart(),await this.peerConnection.setLocalDescription({type:"offer",sdp:d}),null==l||l(o),await this.peerConnection.setRemoteDescription({type:"answer",sdp:o});const u=this.peerConnection.getTransceivers()[0];if(null!=u&&u.receiver&&this.tryBindTransportEvents(u.receiver),RC("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 Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(e.toString()));}}send(e,t,i){var n=this;return PU(function*(){const r=yield IU(n.mutex.lock("From P2PConnection.send"));try{if(!n.remoteSDP)throw new Error("Cannot call P2PConnection.send before remote SDP created");const s=[];e.forEach(e=>{const t=n.peerConnection.addTransceiver(e._mediaStreamTrack,{direction:"sendonly"});s.push(t),e._updateRtpTransceiver(t);}),wg()&&!0===RC("SIMULCAST")&&(yield IU(n.applySimulcastForFirefox(s,e)));const o=yield IU(n.peerConnection.createOffer()),a=n.remoteSDP.predictReceivingMids(e.length),c=n.mungSendOfferSDP(o.sdp,e,a),d=JU.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 Sx(t,RC("USE_PUB_RTX"));});let u;try{u=yield l;}catch(r){u=[],n.remoteSDP.receive(e,t,i,u);const s=n.remoteSDP.toString();throw yield IU(n.peerConnection.setLocalDescription({type:"offer",sdp:c})),yield IU(n.peerConnection.setRemoteDescription({type:"answer",sdp:s})),yield IU(n.stopSending(a,!0)),r;}n.remoteSDP.receive(e,t,i,u);const h=n.remoteSDP.toString(),p=n.logSDPExchange(c,"offer","local","send");return yield IU(n.peerConnection.setLocalDescription({type:"offer",sdp:c})),yield IU(n.applySimulcastEncodings(s,e)),yield IU(n.applySendEncodings(s,e)),null==p||p(h),yield IU(n.peerConnection.setRemoteDescription({type:"answer",sdp:h})),s.map((e,t)=>{const i=a[t];return {localSSRC:l[t],id:i,transceiver:e};});}catch(e){throw e instanceof Kg?e:new Kg(Hg.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)jC.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:RC("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),jC.debug("[P2PConnection] createDataChannels by exchanging SDP.");}else jC.debug("[P2PConnection] createDataChannels no need to exchange SDP.");return;}catch(e){throw e instanceof Kg?e:new Kg(Hg.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 Kg?e:new Kg(Hg.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;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 s=this.remoteSDP.toString();null==r||r(s),await this.peerConnection.setRemoteDescription({type:"answer",sdp:s});}catch(e){throw new Kg(Hg.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:s}=this.remoteSDP.send(e,t,i,n);if(s){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(),s=this.mungReceiveAnswerSDP(n.sdp,r,e);null==i||i(s||""),await this.peerConnection.setLocalDescription({type:"answer",sdp:s}),jC.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," by exchanging SDP."));}else jC.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," no need to exchange SDP."));const o=this.peerConnection.getTransceivers().find(e=>e.mid===r);if(!o)throw new Error("Cannot get transceiver after setLocalDescription.");return {track:o.receiver.track,id:r,transceiver:o};}catch(e){throw new Kg(Hg.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),jC.debug("[".concat(this.store.clientId,"] [P2PConnection] batchReceive by exchanging SDP."));}else jC.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 Kg(Hg.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 Kg(Hg.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 Kg(Hg.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 Kg(Hg.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 Kg(Hg.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 Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteLocal failed; ".concat(e.toString()));}}restartICE(e){var t=this;return PU(function*(){const i=yield IU(t.mutex.lock("From P2PConnection.restartICE"));try{if(!t.remoteSDP)throw new Error("Cannot restartICE before remoteSDP created.");if(IA().supportPCSetConfiguration){const i=t.peerConnection.getConfiguration(),n=e===cv.RELAY?"relay":"all";i.iceTransportPolicy!==n&&(jC.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===cv.RELAY)return;t.remoteSDP.updateCandidates(e);const n=yield IU(t.peerConnection.createOffer({iceRestart:!0}));if(!n.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const r=Tx(n.sdp),{remoteIceParameters:s}=yield r.iceParameters;t.remoteSDP.restartICE(s);const o=t.remoteSDP.toString(),a=t.logSDPExchange(n.sdp||"","offer","local","restartICE");t.store.descriptionStart(),yield IU(t.peerConnection.setLocalDescription(n)),null==a||a(o),yield IU(t.peerConnection.setRemoteDescription({type:"answer",sdp:o}));}catch(e){jC.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.tryUnbindTransportEvents(),this.unbindPCEvents(),this.unbindStatsEvents(),this.removeAllListeners(),this.transportEventReceiver=void 0,this.statsFilter.destroy(),this.dataStreamChannelMap.clear(),this.recoveredDataChannelIds=[],this.currentDataChannelId=1;}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(),s=this.logSDPExchange(n,"offer","local","updateEncoderConfig");await this.peerConnection.setLocalDescription({type:"offer",sdp:n}),null==s||s(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r});}catch(e){throw new Kg(Hg.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)?wg()||(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:BV(BV({},$U),{},{candidateType:i.type,protocol:i.protocol,address:i.address,port:i.port}),remote:BV(BV({},$U),{},{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,jC.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount));},setTimeout(()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,jC.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount));},RC("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(e){const t={iceServers:[]};return e.iceServers?t.iceServers=e.iceServers:e.turnServer&&"off"!==e.turnServer.mode&&(RT(e.turnServer.servers)?t.iceServers=e.turnServer.servers:(t.iceServers&&t.iceServers.push(...jV.turnServerConfigToIceServers(e.turnServer.servers)),RC("USE_TURN_SERVER_OF_GATEWAY")&&t.iceServers&&e.turnServer.serversFromGateway&&t.iceServers.push(...jV.turnServerConfigToIceServers(e.turnServer.serversFromGateway)),RC("FORCE_TURN_TCP")?t.iceTransportPolicy="relay":e.turnServer.servers.concat(e.turnServer.serversFromGateway||[]).forEach(e=>{e.forceturn&&(t.iceTransportPolicy="relay");}))),RC("ENABLE_ENCODED_TRANSFORM")&&IA().supportWebRTCEncodedTransform&&(t.encodedInsertableStreams=!0),t;}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(gy(e.turnServerURL),":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&!RC("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();jC.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;if(!t){t=this.peerConnection.getSenders().find(t=>t.track===e._mediaStreamTrack);}if(!t)return jC.warn("[".concat(e.getTrackId(),"] no rtpSender found}"));if(this.isVP8Simulcast(e))return jC.warn("[updateRtpSenderEncodings] Track is VP8 simulcast, please apply simulcast encodings");if(!IA().supportSetRtpSenderParameters)return jC.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 s;const{bitrateMax:t,frameRate:i,scaleResolutionDownBy:n}=e._encoderConfig;t&&(r.maxBitrate=1e3*t),(bn(s=e._hints).call(s,jA.LOW_STREAM)||e.isUseScaleResolutionDownBy)&&(i&&(r.maxFramerate=Sy(i)),n&&n>=1&&(r.scaleResolutionDownBy=n));}if(RC("DSCP_TYPE")&&jg()){var o;const e=RC("DSCP_TYPE");bn(o=["very-low","low","medium","high"]).call(o,e)&&(r.networkPriority=e);}const a=t.getParameters(),c=null===(i=a.encodings)||void 0===i?void 0:i[0];wg()&&!c&&(n.encodings=[r]),c&&Object.assign(c,r),Object.assign(a,n),jC.debug("[".concat(e.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(a.encodings))),await t.setParameters(a);}async applySendEncodings(e,t){try{if(!IA().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let i=0;i{const r=i[t],s=n.mediaDescriptions.find(e=>e.attributes.mid===r);s&&(Ix(s,e),wx(s,e,this.store.codec));}),JU.print(n);}mungReceiveAnswerSDP(e,t,i){const n=JU.parse(e),r=n.mediaDescriptions.find(e=>e.attributes.mid===t);return r&&(i===av.AUDIO&&"audio"===r.media.mediaType&&Lx(r),this.useXR&&kx(n)),JU.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!==(s=d._scalabilityMode)&&void 0!==s&&s.numSpatialLayers&&(null===(o=d._scalabilityMode)||void 0===o?void 0:o.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(!wg()&&e.length===t.length)for(let i=0;i200&&null!==(r=e._scalabilityMode)&&void 0!==r&&r.numSpatialLayers&&(null===(s=e._scalabilityMode)||void 0===s?void 0:s.numSpatialLayers)>1);}logSDPExchange(e,t,i,n){if(RC("SDP_LOGGING"))return jC.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(e){if(IA().supportPCSetConfiguration){const t=jV.resolvePCConfiguration(e);this.peerConnection.setConfiguration(t);}}}function GV(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,s=new Array(r),o=0;oe.payloadType.toString(10)),e.attributes.payloads=d.videoCodecs,e.attributes.extmaps=d.videoExtensions,RC("PRELOAD_MEDIA_COUNT")>0)){const{ssrcs:t,ssrcGroups:i}=Cx([{ssrcId:zV,rtx:RC("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,Lx(e),RC("PRELOAD_MEDIA_COUNT")>0)){const{ssrcs:t,ssrcGroups:i}=Cx([{ssrcId:qV}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i;}}this.sessionDesc=c,this.currentMidIndex=c.mediaDescriptions.length-1;}updateRemoteRTPCapabilities(e){const t=JU.parse(KV);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,RC("PRELOAD_MEDIA_COUNT")>0)){const{ssrcs:t,ssrcGroups:i}=Cx([{ssrcId:zV,rtx:RC("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,RC("PRELOAD_MEDIA_COUNT")>0)){const{ssrcs:t,ssrcGroups:i}=Cx([{ssrcId:qV}],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 s=1;se.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*s-1)}}),this.sessionDesc.mediaDescriptions.push({media:{mediaType:"audio",port:YV,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*s)}}),this.currentMidIndex+=2;}this.updateBundleMids();}toString(){return JU.print(this.sessionDesc);}send(e,t,i,n){const{ssrcs:r,ssrcGroups:s}=Cx(t,this.cname,RC("SYNC_GROUP")?i:void 0),o=this.findPreloadMediaDesc(r);if(o){if(wg()&&this.firefoxSsrcMidMap.set(r[0].ssrcId,o.attributes.mid),n&&(n.twcc||n.remb)){const e=this.sessionDesc.mediaDescriptions.indexOf(o);return this.sessionDesc.mediaDescriptions[e]=this.mungSendMediaDesc(o,n),{mid:o.attributes.mid,needExchangeSDP:!0};}return {mid:o.attributes.mid,needExchangeSDP:!1};}{const t=this.findAvailableMediaIndex(e,r);let i;return -1===t||bg()||Og()||Lg()||0===t&&RC("USE_SUB_RTX")?(i=this.createOrRecycleSendMedia(e,r,s,"sendonly",n),this.updateBundleMids()):(i=YT(this.sessionDesc.mediaDescriptions[t]),i.attributes.direction="sendonly",i.attributes.ssrcs=r,i.attributes.ssrcGroups=s,this.sessionDesc.mediaDescriptions[t]=this.mungSendMediaDesc(i,n)),wg()&&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||wg()||bg()||Og()?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=>bn(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=>bn(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===cv.TCP?this._candidates.forEach(e=>{-1===this._candidates.findIndex(t=>"tcp"===t.transport&&t.connectionAddress===e.connectionAddress&&t.port===e.port)&&this._candidates.push(HV(HV({},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=YT(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(wg()){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,s){const o=e._mediaStreamTrack.kind,a=this.rtpCapabilities.recv,c=Mx(o,a,this.localCapabilities.send,o===av.VIDEO?n:r),d=o===av.VIDEO?a.videoExtensions:a.audioExtensions;this.currentMidIndex+=1;const l="".concat(this.currentMidIndex);let u={media:{mediaType:o,port:YV,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)}};u=this.mungRecvMediaDsec(u,e,s);const h=this.findFirstClosedMedia(o);if(h){const e=this.sessionDesc.mediaDescriptions.indexOf(h);this.sessionDesc.mediaDescriptions[e]=u;}else this.sessionDesc.mediaDescriptions.push(u);return u;}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 bn(t=Object.keys(bC)).call(t,e);}))],r=new Set(t);if(n.every(e=>r.has(e)))return jC.debug("codecs has not changed, no need to updateRemoteCodec, codecs: ".concat(t)),!1;const s=this._rtpCapabilities.recv.videoCodecs.filter(e=>t.some(t=>{var i;return bn(i=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").call(i,t);}));if(0===s.length)return jC.debug("updateRemoteCodec failed, because cannot find matched codec, remoteCapabilities codecs: ".concat(n," codecs: ").concat(t)),!1;const o=[...new Set(s.map(e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||""))];let a;if(jC.debug("updateRemoteCodec, from ".concat(n," to ").concat(o)),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&&bn(e).call(e,t.attributes.mid)&&"recvonly"===t.attributes.direction),a.length!==e.length)return jC.debug("updateRemoteCodec failed, because cannot find mids, mids: ".concat(e,", codecs: ").concat(t)),!1;this._rtpCapabilities.recv.videoCodecs=s;const c=this.localCapabilities.send,d=this.rtpCapabilities.recv,l=Mx(av.VIDEO,d,c,i);return a.forEach(e=>{const t=l.map(e=>e.payloadType.toString(10));jC.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 s=this.rtpCapabilities.send,o=e===av.VIDEO?s.videoCodecs:s.audioCodecs,a=e===av.VIDEO?s.videoExtensions:s.audioExtensions;this.currentMidIndex+=1;const c="".concat(this.currentMidIndex);let d={media:{mediaType:e,port:YV,protos:["UDP","TLS","RTP","SAVPF"],fmts:o.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:o,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=YT(e);return vx(n),Ix(n,t),yx(n,t),Ax(n),bx(n,i,this.localCapabilities.send),n;}mungSendMediaDesc(e,t){const i=YT(e);return bx(i,t,this.localCapabilities.recv),Lx(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=>wg()?"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;}}function XV(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 QV(e){for(var t=1;te.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").filter(e=>{var t;return bn(t=Object.keys(bC)).call(t,e);}))];}constructor(e,t,i){super(e,t),sh(this,"store",void 0),sh(this,"peerConnection",void 0),sh(this,"remoteSDP",void 0),sh(this,"initialOffer",void 0),sh(this,"transportEventReceiver",void 0),sh(this,"statsFilter",void 0),sh(this,"useXR",RC("USE_XR")),sh(this,"localCapabilities",void 0),sh(this,"localCandidateCount",0),sh(this,"allCandidatesReceived",!1),sh(this,"remoteCodecs",void 0),sh(this,"dataStreamChannelMap",new Map()),sh(this,"establishPromise",void 0),sh(this,"mutex",new pS("NVExtentionsConnection-mutex")),sh(this,"rtcMedia",void 0),this.store=t,this.peerConnection=i,this.statsFilter=Ex(this.peerConnection,RC("STATS_UPDATE_INTERVAL"),void 0,wg()?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=Tx(e.sdp),i=await Ox({filterRTX:!RC("USE_PUB_RTX")&&!RC("USE_SUB_RTX"),filterVideoFec:RC("FILTER_VIDEO_FEC"),filterAudioFec:RC("FILTER_AUDIO_FEC"),filterVideoCodec:RC("FILTER_VIDEO_CODEC")},{useXR:this.useXR});return this.localCapabilities=i,this.initialOffer=e,QV(QV({},t),{},{rtpCapabilities:i,offerSDP:e.sdp});}catch(e){throw new LI(Hg.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString());}}async connect(e,t,i,n,r,s){try{if(!this.initialOffer)throw new Error("Cannot establish NVConnection without initial offer.");this.remoteSDP=new JV({remoteIceParameters:e,remoteDtlsParameters:t,candidates:i,remoteRTPCapabilities:n,remoteSetup:r,localCapabilities:Px(this.localCapabilities),cname:s});const o=this.remoteSDP.toString(),a=JU.parse(this.initialOffer.sdp),c=a.mediaDescriptions.find(e=>"audio"===e.media.mediaType);c&&Lx(c),this.useXR&&kx(a);const d=JU.print(a),l=this.logSDPExchange(d||"","offer","local","connect");await this.peerConnection.setLocalDescription({type:"offer",sdp:d}),null==l||l(o),await this.peerConnection.setRemoteDescription({type:"answer",sdp:o});}catch(e){throw new LI(Hg.EXCHANGE_SDP_FAILED,"NV.connect failed; ".concat(e.toString()));}}async updateRemoteRTPCapabilities(e,t){if(this.remoteCodecs=t,!this.remoteSDP)return void jC.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 jC.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 s=null===(n=this.remoteSDP)||void 0===n?void 0:n.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:s});const o=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(o),jC.debug("[NVExtentionsConnection] updateRemoteRTPCapabilities by exchanging SDP.");}send(e,t,i){var n=this;return PU(function*(){const r=yield IU(n.mutex.lock("From NVExtentionsConnection.send"));try{if(!n.remoteSDP)throw new Error("Cannot call NVExtentionsConnection.send before remote SDP created");const s=[];e.forEach(e=>{const t=n.peerConnection.addTransceiver(e._mediaStreamTrack,{direction:"sendonly"});s.push(t);}),wg()&&!0===RC("SIMULCAST")&&(yield IU(n.applySimulcastForFirefox(s,e)));const o=yield IU(n.peerConnection.createOffer()),a=n.remoteSDP.predictReceivingMids(e.length),c=n.mungSendOfferSDP(o.sdp,e,a),d=JU.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 Sx(t,RC("USE_PUB_RTX"));});let u;try{u=yield l;}catch(r){u=[],n.remoteSDP.receive(e,t,i,u);const s=n.remoteSDP.toString();throw yield IU(n.peerConnection.setLocalDescription({type:"offer",sdp:c})),yield IU(n.peerConnection.setRemoteDescription({type:"answer",sdp:s})),yield IU(n.stopSending(a,!0)),r;}n.remoteSDP.receive(e,t,i,u);const h=n.remoteSDP.toString(),p=n.logSDPExchange(c,"offer","local","send");return yield IU(n.peerConnection.setLocalDescription({type:"offer",sdp:c})),yield IU(n.applySimulcastEncodings(s,e)),yield IU(n.applySendEncodings(s,e)),null==p||p(h),yield IU(n.peerConnection.setRemoteDescription({type:"answer",sdp:h})),s.map((e,t)=>{const i=a[t];return {localSSRC:l[t],id:i,transceiver:e};});}catch(e){throw e instanceof LI?e:new LI(Hg.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 s=this.remoteSDP.toString();null==r||r(s),await this.peerConnection.setRemoteDescription({type:"answer",sdp:s});}catch(e){throw new LI(Hg.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?jC.debug("[P2PConnection] Channels are already available and can be reused directly."):(i=this.peerConnection.createDataChannel("datastream-channel",{ordered:!1,maxRetransmits:RC("DATASTREAM_MAX_RETRANSMITS")}),i.binaryType="arraybuffer",this.dataStreamChannelMap.set(e,i)),void t.forEach(e=>{e._updateOriginDataChannel(i);});}catch(e){throw e instanceof LI?e:new LI(Hg.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 LI?e:new LI(Hg.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:s}=this.remoteSDP.send(e,t,i,n);if(s){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(),s=this.mungReceiveAnswerSDP(n.sdp,r,e);null==i||i(s||""),await this.peerConnection.setLocalDescription({type:"answer",sdp:s}),jC.debug("[NVExtentionsConnection] receive ".concat(e," by exchanging SDP."));}else jC.debug("[NVExtentionsConnection] receive ".concat(e," no need to exchange SDP."));const o=this.peerConnection.getTransceivers().find(e=>e.mid===r);if(!o)throw new Error("Cannot get transceiver after setLocalDescription.");return {track:o.receiver.track,id:r};}catch(e){throw new LI(Hg.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),jC.debug("[NVExtentionsConnection] batchReceive by exchanging SDP.");}else jC.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 LI(Hg.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 LI(Hg.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 LI(Hg.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 LI(Hg.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 LI(Hg.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 LI(Hg.EXCHANGE_SDP_FAILED,"NVExtentionsConnection.unmuteLocal failed; ".concat(e.toString()));}}restartICE(e){var t=this;return PU(function*(){const i=yield IU(t.mutex.lock("From NVExtentionsConnection.restartICE"));try{if(!t.remoteSDP)throw new Error("Cannot restartICE before remoteSDP created.");if(IA().supportPCSetConfiguration){const i=t.peerConnection.getConfiguration(),n=e===cv.RELAY?"relay":"all";i.iceTransportPolicy!==n&&(jC.debug("restartICE change iceTransportPolicy from [".concat(i.iceTransportPolicy,"] to [").concat(n,"]")),i.iceTransportPolicy=n,t.peerConnection.setConfiguration(i));}else if(e===cv.RELAY)return;e!==cv.RELAY&&t.remoteSDP.updateCandidates(e);const n=yield IU(t.peerConnection.createOffer({iceRestart:!0}));if(!n.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const r=Tx(n.sdp),{remoteIceParameters:s}=yield r.iceParameters;t.remoteSDP.restartICE(s);const o=t.remoteSDP.toString(),a=t.logSDPExchange(n.sdp||"","offer","local","restartICE");yield IU(t.peerConnection.setLocalDescription(n)),null==a||a(o),yield IU(t.peerConnection.setRemoteDescription({type:"answer",sdp:o}));}catch(e){jC.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(),s=this.logSDPExchange(n,"offer","local","updateEncoderConfig");await this.peerConnection.setLocalDescription({type:"offer",sdp:n}),null==s||s(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r});}catch(e){throw new LI(Hg.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)?wg()||(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 QV(QV({},Tx(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,jC.debug("[pc-".concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount));},setTimeout(()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,jC.debug("[pc-".concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount));},RC("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(e){const t={iceServers:[]};return e.iceServers?t.iceServers=e.iceServers:e.turnServer&&"off"!==e.turnServer.mode&&(RT(e.turnServer.servers)?t.iceServers=e.turnServer.servers:(t.iceServers&&t.iceServers.push(...ZV.turnServerConfigToIceServers(e.turnServer.servers)),RC("USE_TURN_SERVER_OF_GATEWAY")&&t.iceServers&&e.turnServer.serversFromGateway&&t.iceServers.push(...ZV.turnServerConfigToIceServers(e.turnServer.serversFromGateway)),RC("FORCE_TURN_TCP")?t.iceTransportPolicy="relay":e.turnServer.servers.concat(e.turnServer.serversFromGateway||[]).forEach(e=>{e.forceturn&&(t.iceTransportPolicy="relay");}))),t;}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(gy(e.turnServerURL),":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&!RC("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(!IA().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let l=0;l1&&(t.scaleResolutionDownBy=h._encoderConfig.scaleResolutionDownBy);if(RC("DSCP_TYPE")&&jg()){var d;const e=RC("DSCP_TYPE");bn(d=["very-low","low","medium","high"]).call(d,e)&&(t.networkPriority=e);}const l=u.sender.getParameters(),p=null===(r=l.encodings)||void 0===r?void 0:r[0];wg()&&!p&&(e.encodings=[t]),p&&Object.assign(p,t),Object.assign(l,e),await u.sender.setParameters(l);}}}catch(e){jC.debug("Apply RTPSendEncodings failed.");}}mungSendOfferSDP(e,t,i){const n=JU.parse(e);return t.forEach((e,t)=>{const r=i[t],s=n.mediaDescriptions.find(e=>e.attributes.mid===r);s&&(Ix(s,e),wx(s,e,this.store.codec));}),JU.print(n);}mungReceiveAnswerSDP(e,t,i){const n=JU.parse(e),r=n.mediaDescriptions.find(e=>e.attributes.mid===t);return r&&i===av.AUDIO&&"audio"===r.media.mediaType&&Lx(r),this.useXR&&kx(n),JU.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!==(s=d._scalabilityMode)&&void 0!==s&&s.numSpatialLayers&&(null===(o=d._scalabilityMode)||void 0===o?void 0:o.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(!wg()&&e.length===t.length)for(let i=0;i200&&null!==(r=e._scalabilityMode)&&void 0!==r&&r.numSpatialLayers&&(null===(s=e._scalabilityMode)||void 0===s?void 0:s.numSpatialLayers)>1);}logSDPExchange(e,t,i,n){if(RC("SDP_LOGGING"))return jC.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(e){if(IA().supportPCSetConfiguration){const t=ZV.resolvePCConfiguration(e);this.peerConnection.setConfiguration(t);}}}function $V(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,s=new Array(r),o=0;o{const n=setTimeout(()=>{this.closeSignal(),t(new LI(Hg.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 PU(function*(){const r=yield IU(n.mutex.lock("From DataChannelConnection.send"));try{return yield*bV(eF(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?(jC.debug("[DataChannelConnection] receive ".concat(e," by DataChannel.")),await this._nvMedia.reveiveByRTCMedia(e,t,this.cname)):(jC.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 PU(function*(){return yield*bV(eF(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(RC("SDP_LOGGING"))return jC.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(e){const t={iceServers:[]};return e.iceServers?t.iceServers=e.iceServers:e.turnServer&&"off"!==e.turnServer.mode&&(RT(e.turnServer.servers)?t.iceServers=e.turnServer.servers:(t.iceServers&&t.iceServers.push(...iF.turnServerConfigToIceServers(e.turnServer.servers)),RC("USE_TURN_SERVER_OF_GATEWAY")&&t.iceServers&&e.turnServer.serversFromGateway&&t.iceServers.push(...iF.turnServerConfigToIceServers(e.turnServer.serversFromGateway)),RC("FORCE_TURN_TCP")?t.iceTransportPolicy="relay":e.turnServer.servers.concat(e.turnServer.serversFromGateway||[]).forEach(e=>{e.forceturn&&(t.iceTransportPolicy="relay");}))),t;}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(gy(e.turnServerURL),":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&!RC("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);}}function nF(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,s=new Array(r),o=0;o{const n=await this.mutex.lock("Locking from P2PChannel.handleMuteLocalTrack");try{if(!this.connection||this.state!==uv.Connected)return void i(new Kg(Hg.INVALID_OPERATION,"Cannot call P2PChannel.handleMuteLocalTrack before connection established."));const r=this.filterTobeMutedTracks(e);if(0===r.length)return void t();const s=r.find(e=>"videoLowTrack"===e[0]);if(s){s[1].track._originMediaStreamTrack.stop();}await this.connection.muteLocal(r.map(e=>{let[,{id:t}]=e;return t;}));const o=this.createMuteMessage(r);await yT(this,hv.RequestMuteLocal,o),t();}catch(e){i(e);}finally{n();}}),sh(this,"handleUnmuteLocalTrack",async(e,t,i)=>{const n=await this.mutex.lock("Locking from P2PChannel.handleUnmuteLocalTrack");try{if(!this.connection||this.state!==uv.Connected)return void i(new Kg(Hg.INVALID_OPERATION,"Cannot call P2PChannel.handleUnmuteLocalTrack before connection established."));const r=this.filterTobeUnmutedTracks(e);if(0===r.length)return void t();const s=r.find(e=>"videoLowTrack"===e[0]);if(s){const t=s[1];if(t.track._originMediaStreamTrack.stop(),!RC("DISABLE_DUAL_STREAM_USE_ENCODING")&&IA().supportDualStreamEncoding){const i=e._mediaStreamTrack.clone();t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i;}else {const i=Gx(e,bT(this,hv.RequestLowStreamParameter));t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i;}await new cg((e,i)=>{this.handleReplaceTrack(t.track,e,i,!0);});}await this.connection.unmuteLocal(r.map(e=>{let[,{id:t}]=e;return t;}));const o=this.createUnmuteMessage(r);await yT(this,hv.RequestUnmuteLocal,o),t();}catch(e){i(e);}finally{n();}}),sh(this,"handleUpdateVideoEncoder",async(e,t,i)=>{const n=await this.mutex.lock("Locking from P2PChannel.handleSetVideoEncoder");try{const i=this.localTrackMap.get(lv.LocalVideoTrack);if(!this.connection||!i||i.track!==e||this.state!==uv.Connected)return void t();const{id:r,track:s}=i;await this.connection.updateSendParameters(r,s),await this.connection.updateEncoderConfig(r,s),this.emit(hv.UpdateVideoEncoder,s),t();}catch(e){i(e);}finally{n();}}),sh(this,"handleSetOptimizationMode",async(e,t,i)=>{const n=await this.mutex.lock("Locking from P2PChannel.handleSetOptimizationMode");try{const i=this.localTrackMap.get(lv.LocalVideoTrack);if(!this.connection||!i||i.track!==e||this.state!==uv.Connected)return;const{id:r,track:s}=i;await this.connection.updateSendParameters(r,s),t();}catch(e){i(e);}finally{n();}}),sh(this,"handleReplaceMixingTrack",async(e,t,i,n)=>{if(!this.connection||this.state!==uv.Connected)return void t();const r=dV([e]);let s;jC.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection will replace audioTrack [").concat(r.getTrackId(),"]")),"boolean"==typeof n&&n||(s=await this.mutex.lock("From P2PChannel.handleReplaceMixingTrack"));try{await this.replaceTrack(e,r),t();}catch(e){i(e);}finally{var o;null===(o=s)||void 0===o||o();}}),sh(this,"handleReplaceTrack",async(e,t,i,n)=>{let r;jC.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 s;const i=Array.from(this.localTrackMap.entries()).find(t=>{let[,{track:i}]=t;return e===i;});if(!this.connection||!i||this.state!==uv.Connected)return void t();if(await(null===(s=this.connection)||void 0===s?void 0:s.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]===lv.LocalVideoTrack&&!RC("DISABLE_DUAL_STREAM_USE_ENCODING")&&IA().supportDualStreamEncoding){const t=this.localTrackMap.get(lv.LocalVideoLowTrack);if(t){const i=e._mediaStreamTrack.clone();t.track._originMediaStreamTrack.stop(),t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i,await new cg((e,i)=>{this.handleReplaceTrack(t.track,e,i,!0);});}}t();}catch(e){i(e);}finally{var o;null===(o=r)||void 0===o||o();}}),sh(this,"handleGetRTCStats",e=>{e(this.statsCollector.getRTCStats());}),sh(this,"handleGetLocalVideoStats",e=>{e(this.statsCollector.getLocalVideoTrackStats());}),sh(this,"handleGetLocalAudioStats",e=>{e(this.statsCollector.getLocalAudioTrackStats());}),sh(this,"handleGetRemoteVideoStats",e=>this.statsCollector.getRemoteVideoTrackStats(e.uid)[e.uid]),sh(this,"handleGetRemoteAudioStats",e=>this.statsCollector.getRemoteAudioTrackStats(e.uid)[e.uid]),this.store=e,this.statsCollector=t,this.statsCollector.addP2PChannel(this),this.statsUploader=new rV(this.store),this.bindStatsUploaderEvents(),this.isPlanB=!IA().supportUnifiedPlan||RC("CHROME_FORCE_PLAN_B")&&jg(),this.shouldForwardP2PCreation=RC("FORWARD_P2P_CREATION")&&IA().supportPCSetConfiguration&&function(){const e=Rg();return e===_g.ANDROID||e===_g.IOS||e===_g.HARMONY_OS;}(),this.shouldForwardP2PCreation&&(this.connection=this.store.useDataChannel?new iF({},this.store):this.isPlanB?new LV({},this.store):new jV({},this.store),this.bindConnectionEvents(this.connection));}async startP2PConnection(e,t){var i;this.state=uv.New;const n=this.shouldForwardP2PCreation&&"closed"===(null===(i=this.connection)||void 0===i?void 0:i.peerConnectionState);if(this.shouldForwardP2PCreation&&!n||(n&&this.connection&&(jC.warning("[".concat(this.store.clientId,"] P2PChannel.startP2PConnection ForwardP2P closed.")),this.connection.close(),this.unbindConnectionEvents(this.connection)),this.connection=this.store.useDataChannel?new iF(e,this.store):this.isPlanB?new LV(e,this.store):new jV(e,this.store),this.bindConnectionEvents(this.connection)),!this.connection)throw new Kg(Hg.UNEXPECTED_ERROR,"Cannot P2PChannel.startConnection before P2PConnection initialization .");return this._pcStatsUploadType=RC("NEW_ICE_RESTART")?dv.FIRST_CONNECTION:dv.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,s){if(!this.connection)throw new Kg(Hg.UNEXPECTED_ERROR,"Cannot P2PChannel.connect before P2PChannel.startP2PConnection .");this.connection instanceof iF?this.connection.updateRemoteConnect(n):(this.store.peerConnectionStart(),await this.connection.connect(e,t,i,n,r,s),this.statsUploader.startUploadTransportStats(),this.statsUploader.startUploadExtensionUsageStats(),this.state=uv.Connected);}updateRemoteRTPCapabilities(e){const t=Array.from(this.localTrackMap.entries()).filter(e=>{var t;let[i]=e;return bn(t=[lv.LocalVideoLowTrack,lv.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 jV){if(eI.updateRemoteRTPCapabilities(this.store.sessionId,{trackTypes:JSON.stringify(n),localCodecs:JSON.stringify(this.connection.localCodecs),remoteCodecs:JSON.stringify(e)}),!bn(e).call(e,this.store.codec)){const t=["vp8","h264"].find(t=>bn(e).call(e,t));t&&(this.store.codec=t,jC.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,s){if(!this.connection)throw new Kg(Hg.UNEXPECTED_ERROR,"Cannot P2PChannel.connect before P2PChannel.startP2PConnection .");this.store.peerConnectionStart();const o=await this.connection.connect(e,t,i,n,r,s);return this.statsUploader.startUploadTransportStats(),this.statsUploader.startUploadExtensionUsageStats(),this.state=uv.Connected,o;}getEstablishParams(){if(this.connection instanceof iF)return this.connection.getP2PConnectionParams();throw new Error("Only DataChannelConnection needs to obtain establishParams");}async publishDataChannel(e){if(!this.connection||this.state!==uv.Connected){if(this.state===uv.Disconnected)throw new Kg(Hg.UNEXPECTED_ERROR,"PeerConnection already disconnected.");return void e.forEach(e=>{var t;bn(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 PU(function*(){const r=yield IU(n.mutex.lock("From P2PChannel.publish"));try{if(!n.connection||n.state!==uv.Connected){if(n.state===uv.Disconnected)throw new Kg(Hg.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,RU.markPublishStart(n.store.clientId,n.store.pubId);const s=n.filterTobePublishedTracks(e,t,i);if(0===s.length)return void(yield IU(n.tryToUnmuteAudio(e)));yield*bV(oF(n.doPublish(n.connection,s)));}finally{r();}})();}doPublish(e,t){var i=this;return PU(function*(){t.forEach(e=>{let{track:t,type:n}=e;const r=Date.now();i.store.publish(t.getTrackId(),n===lv.LocalAudioTrack?"audio":"video",r);}),i.bindLocalTrackEvents(t);const n=t.map(e=>{let{track:t}=e;return t;}),r=yield IU(e.send(t.map(e=>{let{track:t}=e;return t;}),i.store.codec,i.store.audioCodec)),s=(yield IU(r.next())).value,o=i.createGatewayPublishMessage(t,s);let a;try{a=yield o;}catch(e){throw r.throw(e),(null==e?void 0:e.code)===Hg.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(o,a),d=(yield IU(r.next(c))).value,l=RC("ENABLE_VIDEO_SEI");n.forEach(async e=>{const t=e.getRTCRtpTransceiver();t&&l&&(e.trackMediaType===av.VIDEO?await async function(e,t){if(!IA().supportWebRTCEncodedTransform)return void jC.warning("browser not support video encoded transform");if(mU.has(e))return;if(!e.track)return;const i={track:e.track};if(Ag()){if(!e.createEncodedStreams)return void jC.warning("browser not support createEncodedStreams() API");let r=null;try{r=e.createEncodedStreams();}catch(e){return void jC.error("create video-encoded-streams error",e&&e.message);}let s=[];t.on("sei-to-send",e=>{s.push(e);});const o=new TransformStream({transform(t,r){i.controller||(i.controller=r),e.track&&e.track.id!==i.track.id&&(jC.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=s.shift();o&&(t.data=EU(t.data,o)),r.enqueue(t);}});r.readable.pipeThrough(o).pipeTo(r.writable);}else {if(!bg())return;{if("undefined"==typeof RTCRtpScriptTransform)return void jC.warning("browser not support RTCRtpScriptTransform");const r=lU(),s=new MessageChannel();await new cg(e=>r.onmessage=t=>{"registered"===t.data&&e(void 0);});const o=new RTCRtpScriptTransform(r,{name:"tx",port:s.port2},[s.port2]);e.transform=o,await new cg(e=>r.onmessage=t=>{"started"===t.data&&e(void 0);}),t.on("sei-to-send",e=>{s.port1.postMessage({sei:e});}),s.port1.onmessage=t=>{var r;t.data.transformed&&e.track&&(null===(r=e.track)||void 0===r?void 0:r.id)!==i.track.id&&(jC.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=mU.get(e);if(t){mU.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){jC.warning(e&&e.message);}}}mU.set(e,i),e.track.addEventListener("ended",n);}(t.sender,e):e.trackMediaType===av.AUDIO&&(await async function(e){if(!IA().supportWebRTCEncodedTransform)return void jC.warning("browser not support audio encoded transform");if(uU.has(e))return;if(!e.track)return;const t={track:e.track};if(Ag()){if(!e.createEncodedStreams)return void jC.warning("browser not support createEncodedStreams() API");let n=null;try{n=e.createEncodedStreams();}catch(e){return void jC.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&&(jC.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(bg()){if("undefined"==typeof RTCRtpScriptTransform)return void jC.warning("browser not support RTCRtpScriptTransform");const n=lU(),r=new MessageChannel();await new cg(e=>n.onmessage=t=>{"registered"===t.data&&e(void 0);});const s=new RTCRtpScriptTransform(n,{name:"tx",port:r.port2},[r.port2]);e.transform=s,await new cg(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&&(jC.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=uU.get(e);if(t){uU.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){jC.warning(e&&e.message);}}}uU.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===lv.LocalAudioTrack?"audio":"video",void 0,r);});})();}async updateVideoStreamParameter(e,t){const i=this.localTrackMap.get(t);if(!i)return;if(!(i.track instanceof Rw))return jC.warn("[updateVideoStreamParameter]: track is not an instance of LocalVideoTrack");if(!(this.connection instanceof jV||this.connection instanceof LV))return jC.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=yy(e,t)),i.maxFramerate=e.framerate?Sy(e.framerate):void 0,i.maxBitrate=e.bitrate?1e3*e.bitrate:void 0,i;}(e,n);if(n._encoderConfig||(n._encoderConfig={}),t!==lv.LocalVideoLowTrack||!RC("DISABLE_DUAL_STREAM_USE_ENCODING")&&IA().supportDualStreamEncoding)null!=r.scaleResolutionDownBy&&(n._encoderConfig.scaleResolutionDownBy=r.scaleResolutionDownBy);else {const t=n._originMediaStreamTrack;if(!t.canvas)return jC.warn("[".concat(n.getTrackId(),"] no canvas on track"));!function(e,t){const i=e.canvas;t.width&&(i.width=Sy(t.width)),t.height&&(i.height=Sy(t.height)),t.framerate&&(i.stopCapture&&i.stopCapture(),i.stopCapture=Tb(()=>{!i.startCapture&&i.stopCapture&&i.stopCapture(),i.startCapture&&i.startCapture();},Sy(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}),jC.debug("[".concat(n.getTrackId(),"] LowStreamEncoderConfig: , ").concat(JSON.stringify(n._encoderConfig))),await this.connection.updateRtpSenderEncodings(n);}publishLowStream(e){var t=this;return PU(function*(){if(!t.connection||t.state!==uv.Connected)return;const i=yield IU(t.mutex.lock("Locking from P2PChannel.publishLowStream"));try{const r=t.localTrackMap.get(lv.LocalVideoTrack);if(!r)throw new Kg(Hg.UNEXPECTED_ERROR,"Could not find high stream");if(t.localTrackMap.has(lv.LocalVideoLowTrack))throw new Kg(Hg.UNEXPECTED_ERROR,"[".concat(t.store.clientId,"] Can't publish low stream when stream already publish"));const s=[{track:t.getLowVideoTrack(r.track,e),type:lv.LocalVideoLowTrack}];if(yield*bV(oF(t.doPublish(t.connection,s))),r.track.muted||!r.track.enabled){var n;const e=null===(n=t.localTrackMap.get(lv.LocalVideoLowTrack))||void 0===n?void 0:n.id;void 0!==e&&(yield IU(t.connection.muteLocal([e])));}}finally{i();}})();}async republish(){this.pendingLocalTracks.length>0&&(jC.debug("[".concat(this.store.clientId,"] Emit P2PChannelEvents.RequestRePublish to republish tracks.")),await vT(this,hv.RequestRePublish,this.pendingLocalTracks),this.emit(hv.MediaReconnectEnd,this.store.uid),this.pendingLocalTracks=[]),this.pendingLocalDataChannels.length>0&&(jC.debug("Emit P2PChannelEvents.RequestRePublishDataChannel to republish datachannels."),await vT(this,hv.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!==av.AUDIO||t._audio_added_&&t._audioSSRC)&&(i!==av.VIDEO||t._video_added_&&t._videoSSRC)||this.pendingRemoteTracks.splice(e,1);}if(e)await vT(this,hv.RequestReSubscribe,this.pendingRemoteTracks);else for(const{user:e,kind:t}of this.pendingRemoteTracks)await this.subscribe(e,t,t===av.VIDEO?e._videoSSRC:e._audioSSRC);this.pendingRemoteTracks.forEach(e=>{let{user:t}=e;this.emit(hv.MediaReconnectEnd,t.uid);}),this.pendingRemoteTracks=[];}async unpublish(e){if(!this.connection||this.state!==uv.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!==uv.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!==uv.Connected)return;const e=this.localTrackMap.get(lv.LocalVideoLowTrack);if(!e)return;e.track.close();const t=[[lv.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!==uv.Connected)throw new Kg(Hg.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 s;if(!this.connection||this.state!==uv.Connected)throw new Kg(Hg.INVALID_OPERATION,"Cannot subscribe remote user when peerConnection disconnected.");if(null!==(s=this.remoteUserMap.get(e))&&void 0!==s&&s.has(t))return;let o,a,c;if(r){const i=r.find(e=>{let{stream_type:i}=e;return i===t;});if(!i)throw new Kg(Hg.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 jV&&(c=n.transceiver),o=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 jV&&(c=r.transceiver),o=r.track,a=r.id;}t===av.AUDIO?(e._audioTrack?e._audioTrack._updateOriginMediaStreamTrack(o):(e._audioTrack=new Nw(o,e.uid,e._uintid,this.store),jC.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(o):(e._videoTrack=new Ow(o,e.uid,e._uintid,this.store),jC.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)),RC("ENABLE_VIDEO_SEI")&&c&&(t==av.VIDEO?await gU(c.receiver,{onSei:t=>{var i;null===(i=e._videoTrack)||void 0===i||i._onSei(t);}}):t==av.AUDIO&&(await pU(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(hv.MediaReconnectEnd,e.uid));}async massSubscribe(e){return this.massSubscribeNoLock(e);}async massSubscribeNoLock(e){if(!this.connection||this.state!==uv.Connected)throw new Kg(Hg.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:s,id:o,transceiver:a}=t[i];r===av.AUDIO?(n._audioTrack?n._audioTrack._updateOriginMediaStreamTrack(s):(n._audioTrack=new Nw(s,n.uid,n._uintid,this.store),jC.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(s):(n._videoTrack=new Ow(s,n.uid,n._uintid,this.store),jC.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,o):this.remoteUserMap.set(n,new Map([[r,o]])),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(hv.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===uv.Connected||i||n.forEach(t=>{let{kind:i}=t;var n;if(i===av.AUDIO)null===(n=e._audioTrack)||void 0===n||n._destroy(),e._audioTrack=void 0;else if(i===av.VIDEO){var r;null===(r=e._videoTrack)||void 0===r||r._destroy(),e._videoTrack=void 0;}}),!this.connection||this.state!==uv.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 s=this.createUnsubscribeMessage(r);return this.withdrawRemoteTracks(r),0===this.remoteUserMap.size&&this.statsUploader.stopUploadInboundStats(),r.forEach(e=>{let[t,{kind:n}]=e;var r,s;n===av.VIDEO&&t._videoSSRC&&(null===(r=this.connection)||void 0===r||r.setStatsRemoteVideoIsReady(t._videoSSRC,!1));if(n===av.VIDEO)this.unbindRemoteTrackEvents(t._videoTrack),i||(null===(s=t._videoTrack)||void 0===s||s._destroy(),t._videoTrack=void 0);else if(n===av.AUDIO){var o;if(this.unbindRemoteTrackEvents(t._audioTrack),!i)null===(o=t._audioTrack)||void 0===o||o._destroy(),t._audioTrack=void 0;}}),s;}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!==uv.Connected)return void t.forEach(e=>{let{user:t,kind:i}=e;var n;if(i===av.AUDIO)null===(n=t._audioTrack)||void 0===n||n._destroy(),t._audioTrack=void 0;else if(i===av.VIDEO){var r;null===(r=t._videoTrack)||void 0===r||r._destroy(),t._videoTrack=void 0;}});const i=BT(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===av.VIDEO&&t._videoSSRC&&(null===(n=this.connection)||void 0===n||n.setStatsRemoteVideoIsReady(t._videoSSRC,!1));if(i===av.VIDEO)this.unbindRemoteTrackEvents(t._videoTrack),null===(r=t._videoTrack)||void 0===r||r._destroy(),t._videoTrack=void 0;else if(i===av.AUDIO){var s;this.unbindRemoteTrackEvents(t._audioTrack),null===(s=t._audioTrack)||void 0===s||s._destroy(),t._audioTrack=void 0;}}),n;}async muteRemote(e,t){if(!this.connection)return;const i=this.remoteUserMap.get(e);if(!i)return void jC.warning("[".concat(this.store.clientId,"] P2PChannel.muteRemote has no remote user ").concat(e.uid,"."));if(!i.get(t))return void jC.warning("[".concat(this.store.clientId,"] P2PChannel.muteRemote has no remote user ").concat(e.uid," media type ").concat(t,"."));const n=t===av.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 jC.warning("[".concat(this.store.clientId,"] P2PChannel.unmuteRemote has no remote user ").concat(e.uid,"."));i.get(t)||jC.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(lv.LocalAudioTrack);if((null==t?void 0:t.track)instanceof nw){const i=t.track;return Array.from(this.localTrackMap.entries()).filter(e=>{let[t]=e;return t!==lv.LocalAudioTrack;}).filter(t=>{let[i]=t;return !(e&&i===lv.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===lv.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(lv.LocalAudioTrack),s=n?this.localTrackMap.get(lv.LocalVideoLowTrack):this.localTrackMap.get(lv.LocalVideoTrack);eI.publish(this.store.sessionId,{eventElapse:RU.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:e,ec:t,audioName:null==i?void 0:i.track.getTrackLabel(),videoName:null==s?void 0:s.track.getTrackLabel(),screenshare:-1!==(null==s?void 0:s.track._hints.indexOf(jA.SCREEN_TRACK)),audio:!!i,video:!!s,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r});}else {var s;i||(i=[]);const o=i.find(e=>e instanceof ew),a=n?null===(s=this.localTrackMap.get(lv.LocalVideoTrack))||void 0===s?void 0:s.track:i.find(e=>e instanceof Rw);eI.publish(this.store.sessionId,{eventElapse:RU.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:e,ec:t,audioName:null==o?void 0:o.getTrackLabel(),videoName:null==a?void 0:a.getTrackLabel(),screenshare:-1!==(null==a?void 0:a._hints.indexOf(jA.SCREEN_TRACK)),audio:!!o,video:!!a,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r});}}reportSubscribeEvent(e,t,i,n){const r=n===av.VIDEO?i._videoSSRC:i._audioSSRC;r&&eI.subscribe(this.store.sessionId,{succ:e,ec:t,video:n===av.VIDEO,audio:n===av.AUDIO,peerid:i.uid,subscribeRequestid:n===av.VIDEO?i._videoSSRC:i._audioSSRC,p2pid:this.store.p2pId,eventElapse:RU.measureFromSubscribeStart(this.store.clientId,r)});}reset(){jC.debug("[".concat(this.store.clientId,"] P2PChannel.reset")),this.mutex=new pS("P2PChannel-mutex"),this.connection&&(this.connection.close(),this.unbindConnectionEvents(this.connection),this.connection=void 0),this.shouldForwardP2PCreation&&(this.connection=this.store.useDataChannel?new iF({},this.store):this.isPlanB?new LV({},this.store):new jV({},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(lv.LocalAudioTrack);if((null==e?void 0:e.track)instanceof nw){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=uv.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(lv.LocalAudioTrack);if(e)return e.track.getVolumeLevel();}getLocalVideoSize(){const e=this.localTrackMap.get(lv.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 Rw||t&&t.track instanceof ew?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(ph(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(lv.LocalAudioTrack);return t&&e.push({level:100*t.track._source.getAccurateVolumeLevel(),uid:this.store.uid}),e=ep(e).call(e,(e,t)=>e.level-t.level),e;}async disconnectForReconnect(){this.connection&&(jC.debug("[".concat(this.store.clientId,"] P2PChannel.disconnectForReconnect closing P2PConnection")),this.state=uv.Reconnecting,RC("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 iF({},this.store):this.isPlanB?new LV({},this.store):new jV({},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 lv.LocalVideoTrack:bn(t=n._hints).call(t,jA.LOW_STREAM)?n.close():this.pendingLocalTracks.push(n);break;case lv.LocalAudioTrack:n instanceof nw?this.pendingLocalTracks=this.pendingLocalTracks.concat(n.trackList):this.pendingLocalTracks.push(n);case lv.LocalVideoLowTrack:}}),this.emit(hv.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(ph(i).call(i)).forEach(e=>{this.setPendingRemoteMedia(t,e);}),this.emit(hv.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(ph(i).call(i)).forEach(e=>{this.setPendingRemoteDataChannel(t,e);});}),this.remoteDataChannelMap.clear()),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),jC.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 sV?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 sV?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 PU(function*(){if(!t.connection||t.state!==uv.Connected||t.connection instanceof iF)return;const i=yield IU(t.mutex.lock("From P2PChannel.restartICE"));let n;try{n=yield IU(t.connection.restartICE(e));const r=yield IU(n.next());if(r.done)return;const s=r.value,o=yield s;switch(t.reportPCDisconnectedOrFailed(e),e){case cv.TCP:t._pcStatsUploadType=dv.TCP_RESTART;break;case cv.RELAY:t._pcStatsUploadType=dv.RELAY_RESTART;break;default:t._pcStatsUploadType=dv.OLD_RESTART;}t._isInRestartIce=!0,n.next(o);}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(lv.LocalVideoTrack),i=this.localTrackMap.get(lv.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 s=AT(this,hv.NeedSignalRTT),o=n?n.rttMs:void 0,a=r?r.rttMs:void 0,c=o&&a?(o+a)/2:o||a,d=(c&&s?(c+s)/2:c||s)||0,l=100*e.sendPacketLossRate*.7/50+.3*d/1500,u=l<.17?1:l<.36?2:l<.59?3:l<.1?4:5,h=null==t?void 0:t.track;if(h&&h._encoderConfig&&-1===h._hints.indexOf(jA.SCREEN_TRACK)){const t=h._encoderConfig.bitrateMax,i=e.bitrate.actualEncoded;if(t&&i){const e=(1e3*t-i)/(1e3*t);return nI[e<.15?0:e<.3?1:e<.45?2:e<.6?3:4][u];}}return u;}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,s=n._videoSSRC,o=e.audioRecv.find(e=>e.ssrc===r),a=e.videoRecv.find(e=>e.ssrc===s);if(!o&&!a)return void(t+=1);const c=AT(this,hv.NeedSignalRTT),d=e.rtt,l=(d&&c?(d+c)/2:d||c)||0,u=o?o.jitterMs:void 0,h=e.recvPacketLossRate;let p=.7*h*100/50+.3*l/1500;u&&(p=.6*h*100/50+.2*l/1500+.2*u/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 cg((t,i)=>{this.handleMuteLocalTrack(e,t,i);});}async replaceTrack(e,t){var i;if(jC.debug("[".concat(this.store.clientId,"] P2PChannel replaceTrack from [").concat(e.getTrackId(),"] to [").concat(t.getTrackId(),"]")),!this.connection||this.state!==uv.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===lv.LocalVideoTrack&&!RC("DISABLE_DUAL_STREAM_USE_ENCODING")&&IA().supportDualStreamEncoding){const t=this.localTrackMap.get(lv.LocalVideoLowTrack);if(t){const i=e._mediaStreamTrack.clone();t.track._originMediaStreamTrack.stop(),t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i,await new cg((e,i)=>{this.handleReplaceTrack(t.track,e,i,!0);});}}}filterTobePublishedTracks(e,t,i){const n=[],r=this.getAllTracks();e=HT(e=e.filter(e=>-1===r.indexOf(e)));let s,o=!1;const a=this.localTrackMap.get(lv.LocalAudioTrack);for(const r of e){if(r instanceof Rw&&(this.localTrackMap.has(lv.LocalVideoTrack)||o?new Kg(Hg.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS).throw():(n.push({track:r,type:lv.LocalVideoTrack}),o=!0),t)){const e=this.getLowVideoTrack(r,i);n.push({track:e,type:lv.LocalVideoLowTrack});}if(r instanceof ew)if(a){const e=a.track;if(e instanceof nw)cV([r]),e.addAudioTrack(r),this.bindLocalAudioTrackEvents(r,!0);else {const t=dV([e,r]);jC.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection will replace audioTrack [").concat(t.getTrackId(),"]")),this.replaceTrack(e,t);}}else if(s instanceof nw)cV([r]),s.addAudioTrack(r);else if(s||!r._useAudioElement&&IA().webAudioMediaStreamDest&&!r._bypassWebAudio){s=dV(s?[r,s]:[r]);}else s=r;}return s&&(jC.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection will send audioTrack [").concat(s.getTrackId(),"]")),n.push({track:s,type:lv.LocalAudioTrack})),n;}filterTobeUnpublishedTracks(e){const t=[],i=this.getAllTracks();e=HT(e=e.filter(e=>-1!==i.indexOf(e)));for(const i of e){if(i instanceof ew){const e=this.localTrackMap.get(lv.LocalAudioTrack);if(!e)continue;e.track instanceof nw?(e.track.removeAudioTrack(i),this.unbindLocalAudioTrackEvents(i),0===e.track.trackList.length&&(t.push([lv.LocalAudioTrack,e]),e.track.close())):t.push([lv.LocalAudioTrack,e]);}if(i instanceof Rw){const e=this.localTrackMap.get(lv.LocalVideoTrack);if(!e)continue;t.push([lv.LocalVideoTrack,e]);const i=this.localTrackMap.get(lv.LocalVideoLowTrack);i&&t.push([lv.LocalVideoLowTrack,i]);}}return t;}filterTobePublishedDataChannels(e){return e=(e=HT(e)).filter(e=>-1===this.localDataChannels.findIndex(t=>t.id===e.id));}filterTobeUnpublishedDataChannels(e){return e=(e=(e=HT(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 lv.LocalVideoTrack:t.addListener(BA.GET_STATS,this.handleGetLocalVideoStats),t.addListener(BA.GET_RTC_STATS,this.handleGetRTCStats),t.addListener(BA.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.addListener(BA.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.addListener(BA.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.addListener(BA.SET_OPTIMIZATION_MODE,this.handleSetOptimizationMode),t.addListener(BA.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.addListener(BA.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.addListener(BA.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case lv.LocalAudioTrack:this.bindLocalAudioTrackEvents(t);case lv.LocalVideoLowTrack:}});}bindLocalAudioTrackEvents(e,t){e instanceof nw?e.trackList.forEach(e=>{e.addListener(BA.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(BA.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(BA.GET_STATS,this.handleGetLocalAudioStats),e.addListener(BA.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(BA.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);}):(e.addListener(BA.GET_STATS,this.handleGetLocalAudioStats),e.addListener(BA.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(BA.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(BA.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(BA.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack),t||(e.addListener(BA.NEED_REPLACE_TRACK,this.handleReplaceTrack),e.addListener(BA.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 lv.LocalVideoTrack:t.off(BA.GET_STATS,this.handleGetLocalVideoStats),t.off(BA.GET_RTC_STATS,this.handleGetRTCStats),t.off(BA.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.off(BA.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.off(BA.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.off(BA.SET_OPTIMIZATION_MODE,this.handleSetOptimizationMode),t.off(BA.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.off(BA.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.off(BA.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case lv.LocalAudioTrack:this.unbindLocalAudioTrackEvents(t);case lv.LocalVideoLowTrack:}});}unbindLocalAudioTrackEvents(e){e instanceof nw?e.trackList.forEach(e=>{e.off(BA.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(BA.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(BA.GET_STATS,this.handleGetLocalAudioStats),e.off(BA.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(BA.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);}):(e.off(BA.GET_STATS,this.handleGetLocalAudioStats),e.off(BA.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(BA.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(BA.NEED_REPLACE_TRACK,this.handleReplaceTrack),e.off(BA.NEED_REPLACE_MIXING_TRACK,this.handleReplaceMixingTrack),e.off(BA.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(BA.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack));}bindRemoteTrackEvents(e,t){t instanceof Ow&&t.addListener(BA.GET_STATS,t=>{t(this.handleGetRemoteVideoStats(e));}),t instanceof Nw&&t.addListener(BA.GET_STATS,t=>{t(this.handleGetRemoteAudioStats(e));});}unbindRemoteTrackEvents(e){e&&e.removeAllListeners(BA.GET_STATS);}unbindAllRemoteTrackEvents(){Array.from(this.remoteUserMap.entries()).forEach(e=>{let[t,i]=e;i.has(av.AUDIO)&&this.unbindRemoteTrackEvents(t._audioTrack),i.has(av.VIDEO)&&this.unbindRemoteTrackEvents(t._videoTrack);});}createGatewayPublishMessage(e,t){return e.map((e,i)=>{var n;let r,s,{track:o,type:a}=e;switch(a){case lv.LocalAudioTrack:r=JI.Audio,s={dtx:o instanceof tw&&o._config.DTX,hq:!1,lq:!1,stereo:!1,speech:!1};break;case lv.LocalVideoTrack:r=bn(n=o._hints).call(n,jA.SCREEN_TRACK)?JI.Screen:JI.High,s=sF(sF({},Ry(o)),{},{codec:this.store.codec});break;case lv.LocalVideoLowTrack:r=JI.Low,s=sF(sF({},Ry(o)),{},{codec:this.store.codec});}return {stream_type:r,attributes:s,ssrcs:t[i]};});}createGatewayUnpublishMessage(e){return e.map(e=>{var t;let i,[n,{track:r,ssrcs:s,id:o}]=e;switch(n){case lv.LocalVideoTrack:i=bn(t=r._hints).call(t,jA.SCREEN_TRACK)?JI.Screen:JI.High;break;case lv.LocalAudioTrack:i=JI.Audio;break;case lv.LocalVideoLowTrack:i=JI.Low;}return {stream_type:i,ssrcs:s,mid:o};});}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(jC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onConnectionStateChange(").concat(t,")")),this.emit(hv.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),RC("NEW_ICE_RESTART")){var i;if(bn(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){jC.debug("[".concat(this.store.clientId,"] [P2PChannel] start use restartICE, type is ").concat(t));"CONNECTED"===AT(this,hv.QueryClientConnectionState)&&this.emit(hv.RequestRestartICE,t);}},i=()=>{"disconnected"!==e.iceConnectionState&&"checking"!==e.iceConnectionState&&"failed"!==e.iceConnectionState||(this.reportPCStats(Date.now(),!1,this._pcStatsUploadType),jC.debug("[".concat(this.store.clientId,"] P2PConnection disconnected timeout, force reconnect")),setTimeout(()=>this.emit(hv.P2PLost),0),this.iceFailedCount+=1,this.requestReconnect());},n=RC("ICE_RESTART_INTERVAL");return void(this._restartTimer=window.setTimeout(()=>{if(RC("JOIN_WITH_FALLBACK_MEDIA_PROXY_FORCE")&&IA().supportPCSetConfiguration)t(cv.RELAY),this._restartTimer=window.setTimeout(i,n);else if(wg())t(cv.UDP),this._restartTimer=window.setTimeout(i,4e3);else {if(t(cv.TCP),IA().supportPCSetConfiguration)return void(this._restartTimer=window.setTimeout(()=>{t(cv.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&&RC("ICE_RESTART")){"CONNECTED"===AT(this,hv.QueryClientConnectionState)&&this.emit(hv.RequestRestartICE);}},800),void setTimeout(()=>{"disconnected"===e.peerConnectionState&&(jC.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(hv.P2PLost),0),this.iceFailedCount+=1,this.requestReconnect());},4e3);"failed"===t&&(jC.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection state failed, force reconnect")),this.reportPCDisconnectedOrFailed(),setTimeout(()=>this.emit(hv.P2PLost),0),this.iceFailedCount+=1,await this.requestReconnect());}},e.onICEConnectionStateChange=e=>{"connected"!==e||this.store.keyMetrics.iceConnectionEnd||this.store.iceConnectionEnd(),jC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICEConnectionStateChange(").concat(e,")")),eI.reportApiInvoke(this.store.sessionId,{name:"ICEConnectionStateChange",options:e,tag:pT.TRACER}).onSuccess(),this.emit(hv.IceConnectionStateChange,e);},e.onICETransportStateChange=e=>{jC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICETransportStateChange(").concat(e,")"));},e.onDTLSTransportStateChange=e=>{jC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportStateChange(").concat(e,")"));},e.onDTLSTransportError=e=>{jC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportError(").concat(e,")"));},e.onFirstAudioDecoded=e=>{var t;const i=Array.from(ph(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(qA.FIRST_FRAME_DECODED),eI.firstRemoteFrame(this.store.sessionId,YC.FIRST_AUDIO_DECODE,qC.FIRST_AUDIO_DECODE,{peer:i._uintid,subscribeElapse:RU.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId}));},e.onFirstAudioReceived=e=>{var t;const i=Array.from(ph(t=this.remoteUserMap).call(t)).find(t=>t._audioSSRC===e);i&&eI.firstRemoteFrame(this.store.sessionId,YC.FIRST_AUDIO_RECEIVED,qC.FIRST_AUDIO_RECEIVED,{peer:i._uintid,subscribeElapse:RU.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(ph(t=this.remoteUserMap).call(t)).find(t=>t._videoSSRC===e);i&&eI.firstRemoteFrame(this.store.sessionId,YC.FIRST_VIDEO_RECEIVED,qC.FIRST_VIDEO_RECEIVED,{peer:i._uintid,subscribeElapse:RU.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(hv.ConnectionTypeChange,i),jC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedLocalCandidateChanged(").concat(JSON.stringify(Ay(t))," -> ").concat(JSON.stringify(Ay(e)),")"));},e.onSelectedRemoteCandidateChanged=(e,t)=>{jC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedRemoteCandidateChanged(").concat(JSON.stringify(Ay(t))," -> ").concat(JSON.stringify(Ay(e)),")"));},e.onFirstVideoDecodedTimeout=e=>{this.reportVideoFirstFrameDecoded(e,void 0,void 0,!0);};}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;}filterTobeMutedTracks(e){const t=[];if(-1===this.getAllTracks().indexOf(e))return t;const i=this.localTrackMap.get(lv.LocalAudioTrack);if(e instanceof ew&&(null==i?void 0:i.track)instanceof nw)return i.track.isActive||t.push([lv.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]===lv.LocalVideoTrack)){const e=this.localTrackMap.get(lv.LocalVideoLowTrack);e&&t.push([lv.LocalVideoLowTrack,e]);}return t;}filterTobeUnmutedTracks(e){const t=[],i=this.localTrackMap.get(lv.LocalAudioTrack);if(e instanceof ew&&(null==i?void 0:i.track)instanceof nw)return i.track.isActive&&t.push([lv.LocalAudioTrack,i]),t;const n=Array.from(this.localTrackMap.entries()).find(t=>{let[,{track:i}]=t;return e===i;});if(n)if(n[0]===lv.LocalVideoTrack){t.push(n);const e=this.localTrackMap.get(lv.LocalVideoLowTrack);e&&t.push([lv.LocalVideoLowTrack,e]);}else t.push(n);return t;}createMuteMessage(e){return e.map(e=>{var t;let i,[n,{track:r,ssrcs:s,id:o}]=e;switch(n){case lv.LocalAudioTrack:i=JI.Audio;break;case lv.LocalVideoTrack:i=bn(t=r._hints).call(t,jA.SCREEN_TRACK)?JI.Screen:JI.High;break;case lv.LocalVideoLowTrack:i=JI.Low;}return {stream_type:i,ssrcs:s,mid:o};});}createUnmuteMessage(e){return e.map(e=>{var t;let i,[n,{track:r,ssrcs:s,id:o}]=e;switch(n){case lv.LocalAudioTrack:i=JI.Audio;break;case lv.LocalVideoTrack:i=bn(t=r._hints).call(t,jA.SCREEN_TRACK)?JI.Screen:JI.High;break;case lv.LocalVideoLowTrack:i=JI.Low;}return {stream_type:i,ssrcs:s,mid:o};});}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 av.VIDEO:return void(i._videoSSRC&&t.push({stream_type:av.VIDEO,ssrcId:i._videoSSRC}));case av.AUDIO:return void(i._audioSSRC&&t.push({stream_type:av.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===av.VIDEO?e|=ZI.Video:e|=ZI.Audio,t.set(i,e);}else n===av.VIDEO?t.set(i,ZI.Video):t.set(i,ZI.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(lv.LocalVideoTrack),i=this.localTrackMap.get(lv.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 yT(this,hv.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(hv.RequestUpload,e,t),this.statsUploader.requestUploadStats=e=>this.emit(hv.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 iS(mS(this.dtlsFailedCount,ES)),this.emit(hv.RequestReconnect);}async reconnectP2P(){const e=Array.from(this.localTrackMap.entries()),t=this.createGatewayUnpublishMessage(e);Array.from(this.remoteUserMap.entries()),t.length>0&&(await vT(this,hv.RequestUnpublishForReconnectPC,t)),this.disconnectForReconnect(),this.emit(hv.RequestReconnectPC);}canPublishLowStream(){return this.localTrackMap.has(lv.LocalVideoTrack)||this.pendingLocalTracks.some(e=>e instanceof Rw);}throwIfTrackTypeNotMatch(e){if(e.filter(e=>e instanceof Rw).length>1)throw new Kg(Hg.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(e.filter(e=>e instanceof ew).length>1&&(e.some(e=>e instanceof ew&&e._bypassWebAudio)||!IA().webAudioMediaStreamDest))throw new Kg(Hg.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 Rw&&this.pendingLocalTracks.some(e=>e instanceof Rw))throw new Kg(Hg.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(t instanceof ew&&this.pendingLocalTracks.some(e=>e instanceof ew)&&(!IA().webAudioMediaStreamDest||t._bypassWebAudio||this.pendingLocalTracks.some(e=>e instanceof ew&&e._bypassWebAudio)))throw new Kg(Hg.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=!RC("DISABLE_DUAL_STREAM_USE_ENCODING")&&IA().supportDualStreamEncoding,n=sF(sF({},{width:160,height:120,framerate:15,bitrate:50}),t);let r;r=i?e._mediaStreamTrack.clone():Gx(e,n);const s=nS(8,"track-low-"),o=new Rw(r,sF(sF({},i&&{scaleResolutionDownBy:yy(n,e)}),{},{frameRate:n.framerate,bitrateMax:n.bitrate,bitrateMin:n.bitrate}),void 0,void 0,s);return o.on(KA.TRANSCEIVER_UPDATED,t=>{e._updateRtpTransceiver(t,GA.LOW_STREAM);}),o._hints.push(jA.LOW_STREAM),e.on("sei-to-send",e=>{o.emit("sei-to-send",e);}),e.addListener(BA.NEED_CLOSE,()=>{o.close();}),o;}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 jV){var r,s,o,a;const c=this.store.keyMetrics.descriptionStart||0,{iceConnectionState:d,dtlsTransportState:l,peerConnectionState:u}=this.connection,{local:h,remote:p}=await this.connection.getSelectedCandidatePair();eI.pcStats(this.store.sessionId,{startTime:c,eventElapse:e-c||0,iceconnectionsate:d,dtlsstate:l,connectionstate:u,intSucc:t?1:2,error:n,selectedLocalCandidateProtocol:null!==(r=null==h?void 0:h.protocol)&&void 0!==r?r:"",selectedLocalCandidateType:null!==(s=h.candidateType)&&void 0!==s?s:"",selectedLocalCandidateAddress:"".concat(h.address,":").concat(h.port),selectedRemoteCandidateProtocol:null!==(o=p.protocol)&&void 0!==o?o:"",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 s=Array.from(ph(r=this.remoteUserMap).call(r)).find(t=>t._videoSSRC===e);if(s){n||this.store.subscribe(s.uid,"video",void 0,void 0,void 0,void 0,Date.now());const r=this.store.keyMetrics,o=r.subscribe.find(e=>e.userId===s.uid&&"video"===e.type);eI.firstRemoteVideoDecode(this.store.sessionId,YC.FIRST_VIDEO_DECODE,qC.FIRST_VIDEO_DECODE,{peer:s._uintid,videowidth:t,videoheight:i,subscribeElapse:RU.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==o?void 0:o.subscribeEnd)||0,subscriberStart:(null==o?void 0:o.subscribeStart)||0,videoAddNotify:(null==o?void 0:o.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 s=await this.connection.getRemoteSSRC(r);return void 0!==s&&s!==i;}resetConnection(e){jC.debug("[".concat(this.store.clientId,"] [P2PChannel] reset connection to ").concat(e)),this.state===uv.Connected?(jC.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===$I.datachannel?new iF({},this.store):this.isPlanB?new LV({},this.store):new jV({},this.store),this.bindConnectionEvents(this.connection)));}unbindRtpTransceiver(){0!==this.localTrackMap.size&&Array.from(this.localTrackMap.entries()).forEach(e=>{let[t,{track:i}]=e;t===lv.LocalVideoLowTrack?i._updateRtpTransceiver(void 0,GA.LOW_STREAM):i._updateRtpTransceiver(void 0);});}reportPCDisconnectedOrFailed(e){this.connection&&this.connection instanceof jV&&("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===dv.TCP_RESTART&&e===cv.RELAY?this.reportPCStats(Date.now(),!1,this._pcStatsUploadType):this.reportPCStats(Date.now(),!1,dv.DISCONNECTED_OR_FAILED)));}}function dF(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,s=new Array(r),o=0;o>>3){case 0:break e;case 1:t.code=kF(e);break;case 2:t.msg=bF(e,kF(e));break;case 3:{let i=_F(e);t.data=hF(e),e.limit=i;break;}default:EF(e,7&i);}}return t;}({bytes:t=e,offset:0,limit:t.length});var t;}function hF(e){let t={};e:for(;!vF(e);){let i=kF(e);switch(i>>>3){case 0:break e;case 1:t.requestId=bF(e,kF(e));break;case 2:t.requestType=kF(e)>>>0;break;case 3:t.scorePorn=PF(e);break;case 4:t.scoreSexy=PF(e);break;case 5:t.scoreNeutral=PF(e);break;case 6:t.requestScene=kF(e)>>>0;break;case 7:t.scene=kF(e)>>>0;break;default:EF(e,7&i);}}return t;}function pF(e,t){let i=e.service;void 0!==i&&(MF(t,8),MF(t,i));let n=e.vendor;void 0!==n&&(MF(t,16),MF(t,n));let r=e.token;void 0!==r&&(MF(t,26),wF(t,r));let s=e.callbackUrl;void 0!==s&&(MF(t,34),wF(t,s));}function _F(e){let t=kF(e),i=e.limit;return e.limit=e.offset+t,i;}function EF(e,t){switch(t){case 0:for(;128&NF(e););break;case 2:IF(e,kF(e));break;case 5:IF(e,4);break;case 1:IF(e,8);break;default:throw new Error("Unimplemented type: "+t);}}DI([dF,PI("design:type",Function),PI("design:paramtypes",[Object,Boolean]),PI("design:returntype",cg)],cF.prototype,"startP2PConnection",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[Object,Object,Array,Object,String,String]),PI("design:returntype",cg)],cF.prototype,"connect",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[Array]),PI("design:returntype",void 0)],cF.prototype,"updateRemoteRTPCapabilities",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[Object,Object,Array,Object,String,String]),PI("design:returntype",cg)],cF.prototype,"preConnect",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[Array]),PI("design:returntype",cg)],cF.prototype,"publishDataChannel",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[Array]),PI("design:returntype",cg)],cF.prototype,"unpublish",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[Array]),PI("design:returntype",cg)],cF.prototype,"unpublishDataChannel",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",cg)],cF.prototype,"unpublishLowStream",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[sV,Array]),PI("design:returntype",cg)],cF.prototype,"subscribeDataChannel",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[sV,String,Number,Number,Array]),PI("design:returntype",cg)],cF.prototype,"subscribe",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[Array]),PI("design:returntype",cg)],cF.prototype,"massSubscribe",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[sV,String,Boolean]),PI("design:returntype",cg)],cF.prototype,"unsubscribe",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[sV,Array]),PI("design:returntype",cg)],cF.prototype,"unsubscribeDataChannel",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[Array]),PI("design:returntype",cg)],cF.prototype,"massUnsubscribe",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[sV,String]),PI("design:returntype",cg)],cF.prototype,"muteRemote",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[sV,String]),PI("design:returntype",cg)],cF.prototype,"unmuteRemote",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[sV,String]),PI("design:returntype",cg)],cF.prototype,"hasRemoteMediaWithLock",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",cg)],cF.prototype,"disconnectForReconnect",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[Object]),PI("design:returntype",cg)],cF.prototype,"updateBitrateLimit",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[sV,String,Number]),PI("design:returntype",cg)],cF.prototype,"remoteMediaSsrcChanged",null);let mF=new Float32Array(1);new Uint8Array(mF.buffer);let fF=new Float64Array(1),gF=new Uint8Array(fF.buffer);function TF(e){return {low:e|=0,high:e>>31,unsigned:e>=0};}let SF=[];function RF(){const e=SF.pop();return e?(e.offset=e.limit=0,e):{bytes:new Uint8Array(64),offset:0,limit:0};}function CF(e){SF.push(e);}function IF(e,t){if(e.offset+t>e.limit)throw new Error("Skip past limit");e.offset+=t;}function vF(e){return e.offset>=e.limit;}function yF(e,t){let i=e.bytes,n=e.offset,r=e.limit,s=n+t;if(s>i.length){let t=new Uint8Array(2*s);t.set(i),e.bytes=t;}return e.offset=s,s>r&&(e.limit=s),n;}function AF(e,t){let i=e.offset;if(i+t>e.limit)throw new Error("Read past limit");return e.offset+=t,i;}function bF(e,t){let i=AF(e,t),n=String.fromCharCode,r=e.bytes,s="�",o="";for(let e=0;e=t?o+=s:(a=r[e+i+1],128!=(192&a)?o+=s:(l=(31&u)<<6|63&a,l<128?o+=s:(o+=n(l),e++))):224==(240&u)?e+2>=t?o+=s:(a=r[e+i+1],c=r[e+i+2],32896!=(49344&(a|c<<8))?o+=s:(l=(15&u)<<12|(63&a)<<6|63&c,l<2048||l>=55296&&l<=57343?o+=s:(o+=n(l),e+=2))):240==(248&u)?e+3>=t?o+=s:(a=r[e+i+1],c=r[e+i+2],d=r[e+i+3],8421504!=(12632256&(a|c<<8|d<<16))?o+=s:(l=(7&u)<<18|(63&a)<<12|(63&c)<<6|63&d,l<65536||l>1114111?o+=s:(l-=65536,o+=n(55296+(l>>10),56320+(1023&l)),e+=3))):o+=s;}return o;}function wF(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?s[r++]=n>>12&15|224:(s[r++]=n>>18&7|240,s[r++]=n>>12&63|128),s[r++]=n>>6&63|128),s[r++]=63&n|128);}}function OF(e,t){let i=yF(e,t.limit),n=e.bytes,r=t.bytes;for(let e=0,s=t.limit;e>>=0;t>=128;)DF(e,127&t|128),t>>>=7;DF(e,t);}function UF(e,t){let i=t.low>>>0,n=(t.low>>>28|t.high<<4)>>>0,r=t.high>>>24,s=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,o=yF(e,s),a=e.bytes;switch(s){case 10:a[o+9]=r>>>7&1;case 9:a[o+8]=9!==s?128|r:127&r;case 8:a[o+7]=8!==s?n>>>21|128:n>>>21&127;case 7:a[o+6]=7!==s?n>>>14|128:n>>>14&127;case 6:a[o+5]=6!==s?n>>>7|128:n>>>7&127;case 5:a[o+4]=5!==s?128|n:127&n;case 4:a[o+3]=4!==s?i>>>21|128:i>>>21&127;case 3:a[o+2]=3!==s?i>>>14|128:i>>>14&127;case 2:a[o+1]=2!==s?i>>>7|128:i>>>7&127;case 1:a[o]=1!==s?128|i:127&i;}}function xF(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 VF=new Map([["moderation",1],["supervise",2]]);class FF extends dT{get connectionState(){return this._connectionState;}set connectionState(e){if(this._connectionState===e)return;const t=this._connectionState;this._connectionState=e,this.emit(mv.CONNECTION_STATE_CHANGE,t,e);}get inspectType(){return this._inspectType;}set inspectType(e){var t;this._inspectMode=BT(t=e.map(e=>VF.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(),sh(this,"name","AgoraRTCVideoContentInspect"),sh(this,"_connectionState",_v.CONNECTING),sh(this,"_innerConnectionState",void 0),sh(this,"sequence",0),sh(this,"inspectStartTime",void 0),sh(this,"workerManagerConnection",void 0),sh(this,"workerConnection",void 0),sh(this,"workerMessageLengthLimit",void 0),sh(this,"inspectIntervalMinimum",void 0),sh(this,"qualityRatio",void 0),sh(this,"_connectInfo",void 0),sh(this,"_cancelTokenSource",sC.CancelToken.source()),sh(this,"_retryConfig",void 0),sh(this,"wmSequence",0),sh(this,"inspectInterval",void 0),sh(this,"inspectTimer",null),sh(this,"ossFilePrefix",void 0),sh(this,"extraInfo",void 0),sh(this,"_inspectType",void 0),sh(this,"_inspectMode",void 0),sh(this,"_quality",1),sh(this,"qualityTimer",null),sh(this,"_inspectId",void 0),sh(this,"_needWorkUrlOnly",!1),sh(this,"inspectImage",()=>{if(this.connectionState!==_v.CONNECTED)throw new LI(Hg.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===_v.CONNECTED?this.requestToInspectImage():jC.debug("[".concat(this._inspectId,"] Inspect State is not connected , "),this.connectionState);},this.inspectInterval{this._innerConnectionState=e,jC.debug("[".concat(this._inspectId,"] Inspect operation :").concat(Ev[e]," ").concat(t||""));}),this.handleWorkerManagerEvents(),this.workerConnection=new zv("worker-"+this._inspectId,ES),this.handleWorkerEvents();}async init(e,t){this.emit(mv.STATE_CHANGE,Ev.CONNECT_AP),this._connectInfo=e;const i=this._cancelTokenSource.token;return this._retryConfig=t,new cg((n,r)=>{this.on(mv.CONNECTION_STATE_CHANGE,(e,t)=>{t===_v.CONNECTED&&n();}),this.requestAP(e,i,t).then(e=>{this.connectWorkerManager(e);}).catch(e=>{r(e);});});}async requestAP(e,t,i){const n=RC("WEBCS_DOMAIN").map(e=>"https://".concat(e,"/api/v1")),r=await function(e,t,i,n){let{appId:r,areaCode:s,cname:o,sid:a,token:c,uid:d}=t;cA++;const l="image_moderation_api",u={service_name:l,json_body:JSON.stringify({appId:r,areaCode:s,cname:o,command:"allocateEdge",requestId:cA,seq:cA,sid:a,token:c,ts:Date.now(),uid:d+""})};let h,p,_=e[0];return fS(async()=>{h=Date.now();const e=await By(_,{data:u,cancelToken:i,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"},params:{action:"wrtc_gateway"}});if(p=Date.now()-h,0!==e.code){const t=new LI(Hg.UNEXPECTED_RESPONSE,"image inspect ap error, code"+e.code,{retry:!0,responseTime:p});throw jC.error(t.toString()),t;}const t=JSON.parse(e.json_body);if(200!==t.code){const e=new LI(Hg.UNEXPECTED_RESPONSE,"image inspect ap error, code: ".concat(t.code,", reason: ").concat(t.reason),{code:t.code,responseTime:p});throw jC.error(e.toString()),e;}if(!t.servers||!Array.isArray(t.servers)||0===t.servers.length){const e=new LI(Hg.UNEXPECTED_RESPONSE,"image inspect ap empty server",{code:t.code,responseTime:p});throw jC.error(e.toString()),e;}const n=RC("VIDEO_INSPECT_WORKER_MANAGER_HOST"),r=RC("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)=>(eI.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)=>(eI.apworkerEvent(a,{success:!1,sc:t.data&&t.data.code||200,serviceName:l,responseTime:p,serverIp:e[i%e.length]}),!!(t.code!==Hg.OPERATION_ABORTED&&t.code!==Hg.UNEXPECTED_RESPONSE||t.data&&t.data.retry)&&(_=e[(i+1)%e.length],!0)),n);}(n,e,t,i);this.emit(mv.STATE_CHANGE,Ev.AP_CONNECTED);const{addressList:s}=r;return this.wmSequence++,s;}async connectWorkerManager(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this._needWorkUrlOnly=t,this.emit(mv.STATE_CHANGE,Ev.CONNECT_WORKER_MANAGER),await this.workerManagerConnection.init(e,1e4);}async connectWorker(e){await this.workerConnection.init([e]);}handleWorkerManagerEvents(){this.workerManagerConnection.on(SI.CONNECTED,async()=>{this.emit(mv.STATE_CHANGE,Ev.WORKER_MANAGER_CONNECTED,this.workerManagerConnection.url),this.workerManagerConnection.sendMessage({appId:this._connectInfo.appId,cname:this._connectInfo.cname,uid:this._connectInfo.uid+"",sdkVersion:"4.20.2",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(SI.CLOSED,()=>{this._innerConnectionState{this._innerConnectionState{this._innerConnectionState{this.emit(mv.STATE_CHANGE,Ev.GET_WORKER_MANAGER_RESPONSE);const t=this.workerManagerConnection.url;this.workerManagerConnection.close();const i=JSON.parse(e.data);if(200!==i.code)throw jC.error("[".concat(this._inspectId,"] Unexpected code ").concat(i.code," from worker manager")),new LI(Hg.UNEXPECTED_RESPONSE,"response code of worker is unexpected",i);if(!(i.serverResponse&&i.serverResponse.portWss&&t))throw jC.error("[".concat(this._inspectId,"] Unexpected content from worker manager : ").concat(JSON.stringify(i))),new LI(Hg.UNEXPECTED_RESPONSE,"response content of worker is unexpected",i);{const e=RC("VIDEO_INSPECT_WORKER_PORT")||i.serverResponse.portWss,n=t.replace(/:\d+\/?$/,":".concat(e));this.emit(mv.STATE_CHANGE,Ev.CONNECT_WORKER,n),this._needWorkUrlOnly?this.emit(mv.REQUEST_NEW_WORKER_URL,n):await this.connectWorker(n);}}),this.workerManagerConnection.on(SI.WILL_RECONNECT,(e,t,i)=>{i(e);}),this.workerManagerConnection.on(SI.REQUEST_NEW_URLS,(e,t)=>{this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then(e).catch(t);});}handleWorkerEvents(){this.workerConnection.on(SI.CONNECTED,async()=>{this.emit(mv.STATE_CHANGE,Ev.WORKER_CONNECTED,this.workerConnection.url),this.connectionState=_v.CONNECTED;}),this.workerConnection.on(SI.ON_MESSAGE,async e=>{if(e.data instanceof ArrayBuffer){const i=uF(new Uint8Array(e.data));if(RC("SHOW_VIDEO_INSPECT_WORKER_MESSAGE")&&jC.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(mv.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=BT(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(mv.INSPECT_RESULT,r);}else this.emit(mv.INSPECT_RESULT,void 0,new LI(Hg.UNEXPECTED_RESPONSE,i.code+"","There is an unexpected data on message"));}else this.emit(mv.INSPECT_RESULT,void 0,new LI(Hg.UNEXPECTED_RESPONSE,i.code+"",i.msg));}else jC.error("[".concat(this._inspectId,"] Unexpected message type from worker")),this.emit(mv.INSPECT_RESULT,void 0,new LI(Hg.UNEXPECTED_RESPONSE,"invalid worker message type"));}),this.workerConnection.on(SI.CLOSED,()=>{this.connectionState=_v.CLOSED;}),this.workerConnection.on(SI.FAILED,()=>{this.connectionState=_v.CLOSED;}),this.workerConnection.on(SI.RECONNECTING,()=>{this.connectionState=this.connectionState===_v.CONNECTED?_v.RECONNECTING:_v.CONNECTING;}),this.workerConnection.on(SI.WILL_RECONNECT,(e,t,i)=>{"recover"===e&&i(e),i("tryNext");}),this.workerConnection.on(SI.REQUEST_NEW_URLS,(e,t)=>{this.workerManagerConnection.close(),this.once(mv.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=AT(this,mv.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(mv.INSPECT_RESULT,void 0,new LI(Hg.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(mv.INSPECT_RESULT,void 0,new LI(Hg.INVALID_OPERATION,"Only the track being published can be inspected"));}async generateRequestData(e,t){let{appId:i,cname:n,cid:r,vid:s,sid:o,uid:a}=t;const c=Date.now(),d=await e.getCurrentFrameImage("image/jpeg",this.quality),l=await gw(d,i,n),u=this.sequence+"-"+r+"-"+a+"-"+c+"-"+nS(12,""),h={appId:i,cid:r,cname:n,deviceId:"",elapse:FF.intToLong(Number(c-this.inspectStartTime)),fileSize:l.byteLength,jpgEncryption:2,height:d.height,width:d.width,jpg:l,networkType:6,osType:7,requestId:u,sdkVersion:"4.20.2",sequence:this.sequence,sid:o,timestamp:FF.intToLong(c),uid:a,vid:s,service:this._inspectMode,callbackData:this.extraInfo,ossFilePrefix:this.ossFilePrefix};void 0===this.extraInfo&&delete h.callbackData,void 0===this.ossFilePrefix&&delete h.ossFilePrefix;const p=lF(h);if(p.byteLength>>3){case 0:break e;case 1:t.code=eB(e);break;case 2:t.msg=XF(e,eB(e));break;case 3:t.requestId=XF(e,eB(e));break;case 4:t.timestamp=iB(e,!1);break;default:GF(e,7&i);}}return t;}({bytes:t=e,offset:0,limit:t.length});var t;}function GF(e,t){switch(t){case 0:for(;128&ZF(e););break;case 2:KF(e,eB(e));break;case 5:KF(e,4);break;case 1:KF(e,8);break;default:throw new Error("Unimplemented type: "+t);}}function WF(e){return {low:e|=0,high:e>>31,unsigned:e>=0};}let HF=[];function KF(e,t){if(e.offset+t>e.limit)throw new Error("Skip past limit");e.offset+=t;}function YF(e){return e.offset>=e.limit;}function qF(e,t){let i=e.bytes,n=e.offset,r=e.limit,s=n+t;if(s>i.length){let t=new Uint8Array(2*s);t.set(i),e.bytes=t;}return e.offset=s,s>r&&(e.limit=s),n;}function zF(e,t){let i=e.offset;if(i+t>e.limit)throw new Error("Read past limit");return e.offset+=t,i;}function JF(e,t){let i=qF(e,t.length);e.bytes.set(t,i);}function XF(e,t){let i=zF(e,t),n=String.fromCharCode,r=e.bytes,s="�",o="";for(let e=0;e=t?o+=s:(a=r[e+i+1],128!=(192&a)?o+=s:(l=(31&u)<<6|63&a,l<128?o+=s:(o+=n(l),e++))):224==(240&u)?e+2>=t?o+=s:(a=r[e+i+1],c=r[e+i+2],32896!=(49344&(a|c<<8))?o+=s:(l=(15&u)<<12|(63&a)<<6|63&c,l<2048||l>=55296&&l<=57343?o+=s:(o+=n(l),e+=2))):240==(248&u)?e+3>=t?o+=s:(a=r[e+i+1],c=r[e+i+2],d=r[e+i+3],8421504!=(12632256&(a|c<<8|d<<16))?o+=s:(l=(7&u)<<18|(63&a)<<12|(63&c)<<6|63&d,l<65536||l>1114111?o+=s:(l-=65536,o+=n(55296+(l>>10),56320+(1023&l)),e+=3))):o+=s;}return o;}function QF(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?s[r++]=n>>12&15|224:(s[r++]=n>>18&7|240,s[r++]=n>>12&63|128),s[r++]=n>>6&63|128),s[r++]=63&n|128);}}function ZF(e){return e.bytes[zF(e,1)];}function $F(e,t){let i=qF(e,1);e.bytes[i]=t;}function eB(e){let t,i=0,n=0;do{t=ZF(e),i<32&&(n|=(127&t)<>>=0;t>=128;)$F(e,127&t|128),t>>>=7;$F(e,t);}function iB(e,t){let i,n=0,r=0,s=0;return i=ZF(e),n=127&i,128&i&&(i=ZF(e),n|=(127&i)<<7,128&i&&(i=ZF(e),n|=(127&i)<<14,128&i&&(i=ZF(e),n|=(127&i)<<21,128&i&&(i=ZF(e),r=127&i,128&i&&(i=ZF(e),r|=(127&i)<<7,128&i&&(i=ZF(e),r|=(127&i)<<14,128&i&&(i=ZF(e),r|=(127&i)<<21,128&i&&(i=ZF(e),s=127&i,128&i&&(i=ZF(e),s|=(127&i)<<7))))))))),{low:n|r<<28,high:r>>>4|s<<24,unsigned:t};}function nB(e,t){let i=t.low>>>0,n=(t.low>>>28|t.high<<4)>>>0,r=t.high>>>24,s=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,o=qF(e,s),a=e.bytes;switch(s){case 10:a[o+9]=r>>>7&1;case 9:a[o+8]=9!==s?128|r:127&r;case 8:a[o+7]=8!==s?n>>>21|128:n>>>21&127;case 7:a[o+6]=7!==s?n>>>14|128:n>>>14&127;case 6:a[o+5]=6!==s?n>>>7|128:n>>>7&127;case 5:a[o+4]=5!==s?128|n:127&n;case 4:a[o+3]=4!==s?i>>>21|128:i>>>21&127;case 3:a[o+2]=3!==s?i>>>14|128:i>>>14&127;case 2:a[o+1]=2!==s?i>>>7|128:i>>>7&127;case 1:a[o]=1!==s?128|i:127&i;}}const rB={},sB={},oB=4294967296,aB=oB*oB,cB=aB/2,dB=_B(0,!0),lB=_B(0),uB=EB(0,-2147483648,!1),hB=EB(-1,2147483647,!1),pB=EB(-1,-1,!0);function _B(e,t){let i,n,r;return t?(r=0<=(e>>>=0)&&e<256)&&(n=sB[e],n)?n:(i=EB(e,0,!0),r&&(sB[e]=i),i):(r=-128<=(e|=0)&&e<128)&&(n=rB[e],n)?n:(i=EB(e,e<0?-1:0,!1),r&&(rB[e]=i),i);}function EB(e,t,i){return {low:0|e,high:0|t,unsigned:!!i};}function mB(e,t){if(isNaN(e))return t?dB:lB;if(t){if(e<0)return dB;if(e>=aB)return pB;}else {if(e<=-cB)return uB;if(e+1>=cB)return hB;}return e<0?t?dB:lB:EB(e%oB|0,e/oB|0,t);}function fB(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 gB extends dT{get connectionState(){return this._connectionState;}set connectionState(e){if(this._connectionState===e)return;const t=this._connectionState;this._connectionState=e,this.emit(Cv.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(),sh(this,"name","AgoraRTCImageModeration"),sh(this,"_connectionState",Rv.CONNECTING),sh(this,"_sequence",0),sh(this,"_moderationStartTime",void 0),sh(this,"_workerConnection",void 0),sh(this,"_workerMessageLengthLimit",void 0),sh(this,"_qualityRatio",void 0),sh(this,"_connectInfo",void 0),sh(this,"_cancelTokenSource",sC.CancelToken.source()),sh(this,"_retryConfig",void 0),sh(this,"_moderationInterval",void 0),sh(this,"_moderationTimer",null),sh(this,"_moderationMode",1),sh(this,"_quality",1),sh(this,"_qualityTimer",null),sh(this,"_ticket",void 0),sh(this,"_moderationIntervalMinimum",void 0),sh(this,"_uploadFailedNum",0),sh(this,"_uploadNum",0),sh(this,"_uploadTimer",null),sh(this,"_extraInfo",void 0),sh(this,"_vendor",""),sh(this,"_encoder",new TextEncoder()),sh(this,"_moderationId",void 0),sh(this,"inspectImage",()=>{if(this.connectionState!==Rv.CONNECTED)throw new LI(Hg.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===Rv.CONNECTED?this.requestToInspectImage():jC.debug("[".concat(this._moderationId,"] Moderation State is not connected , "),this.connectionState);},this._moderationInterval{jC.debug("[".concat(this._moderationId,"] Moderation operation :").concat(Iv[e]," ").concat(t||""));}),this.handleWorkerEvents();}async init(e,t){this.emit(Cv.STATE_CHANGE,Iv.CONNECT_AP),this._connectInfo=e;const i=this._cancelTokenSource.token;return this._retryConfig=t,new cg((n,r)=>{this.on(Cv.CONNECTION_STATE_CHANGE,(e,t)=>{e===Rv.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),jC.debug("[".concat(this._moderationId,"] updateConfig: ").concat(JSON.stringify(e))),this.connectionState===Rv.CONNECTED&&this.inspectImage();}async requestAP(e,t,i){const n=RC("WEBCS_DOMAIN").map(e=>"https://".concat(e,"/api/v1")),r=await function(e,t,i,n){let{appId:r,areaCode:s,cname:o,sid:a,token:c,uid:d}=t;cA++;const l="moderation_plugin",u={service_name:l,json_body:JSON.stringify({appId:r,areaCode:s,cname:o,command:"allocateEdge",requestId:cA,seq:cA,sid:a,appToken:c,ts:Date.now(),uid:d+""})};let h,p,_=e[0];return fS(async()=>{h=Date.now();const e=await By(_,{data:u,cancelToken:i,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"},params:{action:"wrtc_gateway"}});if(p=Date.now()-h,0!==e.code){const t=new LI(Hg.UNEXPECTED_RESPONSE,"moderation plugin ap error, code"+e.code,{retry:!0,responseTime:p});throw jC.error(t.toString()),t;}const t=JSON.parse(e.json_body);if(200!==t.code){const e=new LI(Hg.UNEXPECTED_RESPONSE,"moderation plugin ap error, code: ".concat(t.code,", reason: ").concat(t.reason),{code:t.code,responseTime:p});throw jC.error(e.toString()),e;}if(!t.servers||!Array.isArray(t.servers)||0===t.servers.length){const e=new LI(Hg.UNEXPECTED_RESPONSE,"moderation plugin ap empty server",{code:t.code,responseTime:p});throw jC.error(e.toString()),e;}if(!t.servers.some(e=>!!e.wss)){const e=new LI(Hg.UNEXPECTED_RESPONSE,"moderation plugin ap empty port",{code:t.code,responseTime:p});throw jC.error(e.toString()),e;}const n=RC("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)=>(eI.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)=>(eI.apworkerEvent(a,{success:!1,sc:t.data&&t.data.code||200,serviceName:l,responseTime:p,serverIp:e[i%e.length]}),!!(t.code!==Hg.OPERATION_ABORTED&&t.code!==Hg.UNEXPECTED_RESPONSE||t.data&&t.data.retry)&&(_=e[(i+1)%e.length],!0)),n);}(n,e,t,i);this.emit(Cv.STATE_CHANGE,Iv.AP_CONNECTED);const{addressList:s,ticket:o}=r;return this._ticket=o,s;}async connectWorker(e){this.emit(Cv.STATE_CHANGE,Iv.CONNECT_WORKER),await this._workerConnection.init(e,1e4);}handleWorkerEvents(){this._workerConnection.on(SI.CONNECTED,async()=>{this.emit(Cv.STATE_CHANGE,Iv.WORKER_CONNECTED,this._workerConnection.url),this.connectionState=Rv.CONNECTED;}),this._workerConnection.on(SI.CLOSED,()=>{this.connectionState=Rv.CLOSED;}),this._workerConnection.on(SI.FAILED,()=>{this.connectionState=Rv.CLOSED;}),this._workerConnection.on(SI.RECONNECTING,()=>{this.connectionState=this.connectionState===Rv.CONNECTED?Rv.RECONNECTING:Rv.CONNECTING;}),this._workerConnection.on(SI.ON_MESSAGE,async e=>{if(e.data instanceof ArrayBuffer){const t=jF(new Uint8Array(e.data));RC("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&jC.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++,jC.error("[".concat(this._moderationId,"] Error response from worke, code is ").concat(t.code,", msg is ").concat(t.msg)),this._uploadTimer||(this._uploadTimer=window.setTimeout(()=>{eI.reportApiInvoke(this._connectInfo.sid||null,{name:hT.IMAGE_MODERATION_UPLOAD,options:[this._uploadFailedNum,this._uploadNum,t.code],tag:pT.TRACER}).onError(new LI(Hg.IMAGE_MODERATION_UPLOAD_FAILED,t.msg)),this._uploadTimer=null;},RC("IMAGE_MODERATION_UPLOAD_REPORT_INTERVAL"))));}else jC.error("[".concat(this._moderationId,"] Unexpected message type from worker"));}),this._workerConnection.on(SI.WILL_RECONNECT,(e,t,i)=>{"recover"===e&&i(e),i("tryNext");}),this._workerConnection.on(SI.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=AT(this,Cv.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(RC("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&jC.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 RC("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&jC.debug("Only the track being published can be inspected");}async generateRequestData(e,t){let{appId:i,cname:n,cid:r,vid:s,sid:o,uid:a}=t;const c=Date.now(),d=await e.getCurrentFrameImage("image/jpeg",this.quality),l=await gw(d,i,n),u=this._sequence+"-"+r+"-"+a+"-"+c+"-"+nS(12,""),h={appId:i,cid:r,cname:n,deviceId:"",elapse:gB.intToLong(Number(c-this._moderationStartTime)),fileSize:d.buffer.byteLength,height:d.height,width:d.width,jpg:l,networkType:6,osType:7,requestId:u,sdkVersion:"4.20.2",sequence:this._sequence,sid:o,timestamp:mB(c),uid:a,vid:s,service:this._moderationMode,ticket:this._ticket,callbackData:this._extraInfo,vendorConfigs:this._vendor};void 0===this._extraInfo&&delete h.callbackData;const p=BF(h);if(p.byteLength0&&(n.firstRecvTs=Date.now()-s);let a=i.mediaDelay+o;a<=0?(t.pop(),AB(i.context,r),a=0):a=Math.min(a,CB),setTimeout(()=>t.length&&yB(e),a);}function AB(e,t){e.safeEmit(mT.STREAM_MESSAGE,t.uid,t.payload),e.onStreamMessage&&e.onStreamMessage(t);}function bB(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 AB(i,{uid:e.uid,payload:e.payload});const n="".concat(i.id,"-").concat(e.uid),r=IB.get(n)||[],s=r.findIndex(t=>e.sendTs>=t.sendTs),o=SB(SB({},e),{},{context:i,mediaDelay:t,recvTs:Date.now()});-1===s?r.push(o):r.splice(s,0,o),IB.set(n,r);let a=!1;var c;vB.has(n)?a=!(null===(c=vB.get(n))||void 0===c||!c.isSyncing):vB.set(n,{isSyncing:a,firstRecvTs:0,firstSendTs:0});a||yB(n);}const wB=Sg().name;function OB(){return !function(e,t,i){const n=Sg();if(n.os!==_g.IOS||!n.osVersion)return !1;const r=n.osVersion.split(".");return i?t&&Number(r[0])===e&&Number(r[1])