>3,i-=N,p-=N<<3,h&=(1<{const c=a.bits;let d,l,u,h,p,g,m=0,f=0,T=0,R=0,A=0,N=0,O=0,w=0,L=0,M=0,j=null;const H=new Uint16Array(16),ht=new Uint16Array(16);let lt,rt,Kt,Ft=null;for(m=0;m<=_h;m++)H[m]=0;for(f=0;f=1&&H[R]===0;R--);if(A>R&&(A=R),R===0)return r[o++]=20971520,r[o++]=20971520,a.bits=1,0;for(T=1;T0&&(t===0||R!==1))return-1;for(ht[1]=0,m=1;m<_h;m++)ht[m+1]=ht[m]+H[m];for(f=0;f852||t===2&&L>592)return 1;for(;;){lt=m-O,s[f]+1=g?(rt=Ft[s[f]-g],Kt=j[s[f]-g]):(rt=96,Kt=0),d=1<>O)+l]=lt<<24|rt<<16|Kt|0;while(l!==0);for(d=1<>=1;if(d!==0?(M&=d-1,M+=d):M=0,f++,--H[m]==0){if(m===R)break;m=e[i+s[f]]}if(m>A&&(M&h)!==u){for(O===0&&(O=A),p+=T,N=m-O,w=1<852||t===2&&L>592)return 1;u=M&h,r[u]=A<<24|N<<16|p-o|0}}return M!==0&&(r[p+M]=m-O<<24|64<<16|0),a.bits=A,0};const{Z_FINISH:nN,Z_BLOCK:K5,Z_TREES:Eh,Z_OK:ms,Z_STREAM_END:Y5,Z_NEED_DICT:q5,Z_STREAM_ERROR:Fn,Z_DATA_ERROR:rN,Z_MEM_ERROR:oN,Z_BUF_ERROR:z5,Z_DEFLATED:sN}=Ua,mh=16180,fh=16190,zr=16191,Tf=16192,Rf=16194,gh=16199,Sh=16200,vf=16206,Le=16209,aN=t=>(t>>>24&255)+(t>>>8&65280)+((65280&t)<<8)+((255&t)<<24);function X5(){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 fs=t=>{if(!t)return 1;const e=t.state;return!e||e.strm!==t||e.mode16211?1:0},cN=t=>{if(fs(t))return Fn;const e=t.state;return t.total_in=t.total_out=e.total=0,t.msg="",e.wrap&&(t.adler=1&e.wrap),e.mode=mh,e.last=0,e.havedict=0,e.flags=-1,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new Int32Array(852),e.distcode=e.distdyn=new Int32Array(592),e.sane=1,e.back=-1,ms},dN=t=>{if(fs(t))return Fn;const e=t.state;return e.wsize=0,e.whave=0,e.wnext=0,cN(t)},lN=(t,e)=>{let i;if(fs(t))return Fn;const n=t.state;return e<0?(i=0,e=-e):(i=5+(e>>4),e<48&&(e&=15)),e&&(e<8||e>15)?Fn:(n.window!==null&&n.wbits!==e&&(n.window=null),n.wrap=i,n.wbits=e,dN(t))},uN=(t,e)=>{if(!t)return Fn;const i=new X5;t.state=i,i.strm=t,i.window=null,i.mode=mh;const n=lN(t,e);return n!==ms&&(t.state=null),n};let Cf,yf,hN=!0;const J5=t=>{if(hN){Cf=new Int32Array(512),yf=new Int32Array(32);let e=0;for(;e<144;)t.lens[e++]=8;for(;e<256;)t.lens[e++]=9;for(;e<280;)t.lens[e++]=7;for(;e<288;)t.lens[e++]=8;for(fd(1,t.lens,0,288,Cf,0,t.work,{bits:9}),e=0;e<32;)t.lens[e++]=5;fd(2,t.lens,0,32,yf,0,t.work,{bits:5}),hN=!1}t.lencode=Cf,t.lenbits=9,t.distcode=yf,t.distbits=5},pN=(t,e,i,n)=>{let r;const o=t.state;return o.window===null&&(o.wsize=1<=o.wsize?(o.window.set(e.subarray(i-o.wsize,i),0),o.wnext=0,o.whave=o.wsize):(r=o.wsize-o.wnext,r>n&&(r=n),o.window.set(e.subarray(i-n,i-n+r),o.wnext),(n-=r)?(o.window.set(e.subarray(i-n,i),0),o.wnext=n,o.whave=o.wsize):(o.wnext+=r,o.wnext===o.wsize&&(o.wnext=0),o.whave{let i,n,r,o,s,a,c,d,l,u,h,p,g,m,f,T,R,A,N,O,w,L,M=0;const j=new Uint8Array(4);let H,ht;const lt=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(fs(t)||!t.output||!t.input&&t.avail_in!==0)return Fn;i=t.state,i.mode===zr&&(i.mode=Tf),s=t.next_out,r=t.output,c=t.avail_out,o=t.next_in,n=t.input,a=t.avail_in,d=i.hold,l=i.bits,u=a,h=c,L=ms;t:for(;;)switch(i.mode){case mh:if(i.wrap===0){i.mode=Tf;break}for(;l<16;){if(a===0)break t;a--,d+=n[o++]<>>8&255,i.check=Ei(i.check,j,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){t.msg="incorrect header check",i.mode=Le;break}if((15&d)!==sN){t.msg="unknown compression method",i.mode=Le;break}if(d>>>=4,l-=4,w=8+(15&d),i.wbits===0&&(i.wbits=w),w>15||w>i.wbits){t.msg="invalid window size",i.mode=Le;break}i.dmax=1<>8&1),512&si(i)&&4&i.wrap&&(j[0]=255&d,j[1]=d>>>8&255,i.check=Ei(i.check,j,2,0)),d=0,l=0,i.mode=16182;case 16182:for(;l<32;){if(a===0)break t;a--,d+=n[o++]<>>8&255,j[2]=d>>>16&255,j[3]=d>>>24&255,i.check=Ei(i.check,j,4,0)),d=0,l=0,i.mode=16183;case 16183:for(;l<16;){if(a===0)break t;a--,d+=n[o++]<>8),512&si(i)&&4&i.wrap&&(j[0]=255&d,j[1]=d>>>8&255,i.check=Ei(i.check,j,2,0)),d=0,l=0,i.mode=16184;case 16184:if(1024&si(i)){for(;l<16;){if(a===0)break t;a--,d+=n[o++]<>>8&255,i.check=Ei(i.check,j,2,0)),d=0,l=0}else i.head&&(i.head.extra=null);i.mode=16185;case 16185:if(1024&si(i)&&(p=i.length,p>a&&(p=a),p&&(i.head&&(w=i.head.extra_len-i.length,i.head.extra||(i.head.extra=new Uint8Array(i.head.extra_len)),i.head.extra.set(n.subarray(o,o+p),w)),512&si(i)&&4&i.wrap&&(i.check=Ei(i.check,n,p,o)),a-=p,o+=p,i.length-=p),i.length))break t;i.length=0,i.mode=16186;case 16186:if(2048&si(i)){if(a===0)break t;p=0;do w=n[o+p++],i.head&&w&&i.length<65536&&(i.head.name+=String.fromCharCode(w));while(w&&p>9&1,i.head.done=!0),t.adler=i.check=0,i.mode=zr;break;case 16189:for(;l<32;){if(a===0)break t;a--,d+=n[o++]<>>=7&l,l-=7&l,i.mode=vf;break}for(;l<3;){if(a===0)break t;a--,d+=n[o++]<>>=1,l-=1,3&d){case 0:i.mode=16193;break;case 1:if(J5(i),i.mode=gh,e===Eh){d>>>=2,l-=2;break t}break;case 2:i.mode=16196;break;case 3:t.msg="invalid block type",i.mode=Le}d>>>=2,l-=2;break;case 16193:for(d>>>=7&l,l-=7&l;l<32;){if(a===0)break t;a--,d+=n[o++]<>>16^65535)){t.msg="invalid stored block lengths",i.mode=Le;break}if(i.length=65535&d,d=0,l=0,i.mode=Rf,e===Eh)break t;case Rf:i.mode=16195;case 16195:if(p=i.length,p){if(p>a&&(p=a),p>c&&(p=c),p===0)break t;r.set(n.subarray(o,o+p),s),a-=p,o+=p,c-=p,s+=p,i.length-=p;break}i.mode=zr;break;case 16196:for(;l<14;){if(a===0)break t;a--,d+=n[o++]<>>=5,l-=5,i.ndist=1+(31&d),d>>>=5,l-=5,i.ncode=4+(15&d),d>>>=4,l-=4,i.nlen>286||i.ndist>30){t.msg="too many length or distance symbols",i.mode=Le;break}i.have=0,i.mode=16197;case 16197:for(;i.have>>=3,l-=3}for(;i.have<19;)i.lens[lt[i.have++]]=0;if(i.lencode=i.lendyn,i.lenbits=7,H={bits:i.lenbits},L=fd(0,i.lens,0,19,i.lencode,0,i.work,H),i.lenbits=H.bits,L){t.msg="invalid code lengths set",i.mode=Le;break}i.have=0,i.mode=16198;case 16198:for(;i.have>>24,T=M>>>16&255,R=65535&M,!(f<=l);){if(a===0)break t;a--,d+=n[o++]<>>=f,l-=f,i.lens[i.have++]=R;else{if(R===16){for(ht=f+2;l>>=f,l-=f,i.have===0){t.msg="invalid bit length repeat",i.mode=Le;break}w=i.lens[i.have-1],p=3+(3&d),d>>>=2,l-=2}else if(R===17){for(ht=f+3;l>>=f,l-=f,w=0,p=3+(7&d),d>>>=3,l-=3}else{for(ht=f+7;l>>=f,l-=f,w=0,p=11+(127&d),d>>>=7,l-=7}if(i.have+p>i.nlen+i.ndist){t.msg="invalid bit length repeat",i.mode=Le;break}for(;p--;)i.lens[i.have++]=w}}if(i.mode===Le)break;if(i.lens[256]===0){t.msg="invalid code -- missing end-of-block",i.mode=Le;break}if(i.lenbits=9,H={bits:i.lenbits},L=fd(1,i.lens,0,i.nlen,i.lencode,0,i.work,H),i.lenbits=H.bits,L){t.msg="invalid literal/lengths set",i.mode=Le;break}if(i.distbits=6,i.distcode=i.distdyn,H={bits:i.distbits},L=fd(2,i.lens,i.nlen,i.ndist,i.distcode,0,i.work,H),i.distbits=H.bits,L){t.msg="invalid distances set",i.mode=Le;break}if(i.mode=gh,e===Eh)break t;case gh:i.mode=Sh;case Sh:if(a>=6&&c>=258){t.next_out=s,t.avail_out=c,t.next_in=o,t.avail_in=a,i.hold=d,i.bits=l,B5(t,h),s=t.next_out,r=t.output,c=t.avail_out,o=t.next_in,n=t.input,a=t.avail_in,d=i.hold,l=i.bits,i.mode===zr&&(i.back=-1);break}for(i.back=0;M=i.lencode[d&(1<>>24,T=M>>>16&255,R=65535&M,!(f<=l);){if(a===0)break t;a--,d+=n[o++]<>A)],f=M>>>24,T=M>>>16&255,R=65535&M,!(A+f<=l);){if(a===0)break t;a--,d+=n[o++]<>>=A,l-=A,i.back+=A}if(d>>>=f,l-=f,i.back+=f,i.length=R,T===0){i.mode=16205;break}if(32&T){i.back=-1,i.mode=zr;break}if(64&T){t.msg="invalid literal/length code",i.mode=Le;break}i.extra=15&T,i.mode=16201;case 16201:if(i.extra){for(ht=i.extra;l>>=i.extra,l-=i.extra,i.back+=i.extra}i.was=i.length,i.mode=16202;case 16202:for(;M=i.distcode[d&(1<>>24,T=M>>>16&255,R=65535&M,!(f<=l);){if(a===0)break t;a--,d+=n[o++]<>A)],f=M>>>24,T=M>>>16&255,R=65535&M,!(A+f<=l);){if(a===0)break t;a--,d+=n[o++]<>>=A,l-=A,i.back+=A}if(d>>>=f,l-=f,i.back+=f,64&T){t.msg="invalid distance code",i.mode=Le;break}i.offset=R,i.extra=15&T,i.mode=16203;case 16203:if(i.extra){for(ht=i.extra;l>>=i.extra,l-=i.extra,i.back+=i.extra}if(i.offset>i.dmax){t.msg="invalid distance too far back",i.mode=Le;break}i.mode=16204;case 16204:if(c===0)break t;if(p=h-c,i.offset>p){if(p=i.offset-p,p>i.whave&&i.sane){t.msg="invalid distance too far back",i.mode=Le;break}p>i.wnext?(p-=i.wnext,g=i.wsize-p):g=i.wnext-p,p>i.length&&(p=i.length),m=i.window}else m=r,g=s-i.offset,p=i.length;p>c&&(p=c),c-=p,i.length-=p;do r[s++]=m[g++];while(--p);i.length===0&&(i.mode=Sh);break;case 16205:if(c===0)break t;r[s++]=i.length,c--,i.mode=Sh;break;case vf:if(i.wrap){for(;l<32;){if(a===0)break t;a--,d|=n[o++]<uN(t,15),inflateInit2:uN,inflate:Q5,inflateEnd:t=>{if(fs(t))return Fn;let e=t.state;return e.window&&(e.window=null),t.state=null,ms},inflateGetHeader:(t,e)=>{if(fs(t))return Fn;const i=t.state;return 2&i.wrap?(i.head=e,e.done=!1,ms):Fn},inflateSetDictionary:(t,e)=>{const i=e.length;let n,r,o;return fs(t)?Fn:(n=t.state,n.wrap!==0&&n.mode!==fh?Fn:n.mode===fh&&(r=1,r=cd(r,e,i,0),r!==n.check)?rN:(o=pN(t,e,i,i),o?(n.mode=16210,oN):(n.havedict=1,ms)))},inflateInfo:"pako inflate (from Nodeca project)"},Z5=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 _N=Object.prototype.toString,{Z_NO_FLUSH:$5,Z_FINISH:t4,Z_OK:gd,Z_STREAM_END:If,Z_NEED_DICT:Af,Z_STREAM_ERROR:e4,Z_DATA_ERROR:EN,Z_MEM_ERROR:i4}=Ua;function Sd(t){this.options=uh.assign({chunkSize:65536,windowBits:15,to:""},t||{});const e=this.options;e.raw&&e.windowBits>=0&&e.windowBits<16&&(e.windowBits=-e.windowBits,e.windowBits===0&&(e.windowBits=-15)),!(e.windowBits>=0&&e.windowBits<16)||t&&t.windowBits||(e.windowBits+=32),e.windowBits>15&&e.windowBits<48&&!(15&e.windowBits)&&(e.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new eN,this.strm.avail_out=0;let i=Xr.inflateInit2(this.strm,e.windowBits);if(i!==gd)throw new Error(hs[i]);if(this.header=new Z5,Xr.inflateGetHeader(this.strm,this.header),e.dictionary&&(typeof e.dictionary=="string"?e.dictionary=Ed.string2buf(e.dictionary):_N.call(e.dictionary)==="[object ArrayBuffer]"&&(e.dictionary=new Uint8Array(e.dictionary)),e.raw&&(i=Xr.inflateSetDictionary(this.strm,e.dictionary),i!==gd)))throw new Error(hs[i])}function bf(t,e){const i=new Sd(e);if(i.push(t),i.err)throw i.msg||hs[i.err];return i.result}Sd.prototype.push=function(t,e){const i=this.strm,n=this.options.chunkSize,r=this.options.dictionary;let o,s,a;if(this.ended)return!1;for(s=e===~~e?e:e===!0?t4:$5,_N.call(t)==="[object ArrayBuffer]"?i.input=new Uint8Array(t):i.input=t,i.next_in=0,i.avail_in=i.input.length;;){for(i.avail_out===0&&(i.output=new Uint8Array(n),i.next_out=0,i.avail_out=n),o=Xr.inflate(i,s),o===Af&&r&&(o=Xr.inflateSetDictionary(i,r),o===gd?o=Xr.inflate(i,s):o===EN&&(o=Af));i.avail_in>0&&o===If&&i.state.wrap>0&&t[i.next_in]!==0;)Xr.inflateReset(i),o=Xr.inflate(i,s);switch(o){case e4:case EN:case Af:case i4:return this.onEnd(o),this.ended=!0,!1}if(a=i.avail_out,i.next_out&&(i.avail_out===0||o===If))if(this.options.to==="string"){let c=Ed.utf8border(i.output,i.next_out),d=i.next_out-c,l=Ed.buf2string(i.output,c);i.next_out=d,i.avail_out=n-d,d&&i.output.set(i.output.subarray(c,c+d),0),this.onData(l)}else this.onData(i.output.length===i.next_out?i.output:i.output.subarray(0,i.next_out));if(o!==gd||a!==0){if(o===If)return o=Xr.inflateEnd(this.strm),this.onEnd(o),this.ended=!0,!0;if(i.avail_in===0)break}}return!0},Sd.prototype.onData=function(t){this.chunks.push(t)},Sd.prototype.onEnd=function(t){t===gd&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=uh.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};var n4={Inflate:Sd,inflate:bf,inflateRaw:function(t,e){return(e=e||{}).raw=!0,bf(t,e)},ungzip:bf,constants:Ua};const{Deflate:SH,deflate:r4,deflateRaw:TH,gzip:RH}=F5,{Inflate:vH,inflate:o4,inflateRaw:CH,ungzip:yH}=n4;var s4=r4,a4=o4,mN=function(t){return t[t.ONE_BYTE=0]="ONE_BYTE",t[t.TWO_BYTE=1]="TWO_BYTE",t}(mN||{});class c4{constructor(){S(this,"_sequence",0),S(this,"_startTime",Date.now()),S(this,"isUseOneByte",!0)}get startTime(){const e=Date.now()-this._startTime;return e128){const a=new Uint8Array(4);a.set([1,0,0,0]);const c={id:0,length:4,data:a.buffer},d={profile:this.isUseOneByte?0:1,length:this.isUseOneByte?5:6,datas:[c]};i.commonPacketHeader.extension=1,i.extension=d,i.payload=this.compress(e),i.commonPacketHeader.length=8+(i.extension.length+2)+i.payload.byteLength}else i.commonPacketHeader.length=8+i.payload.byteLength;y("SHOW_DATASTREAM2_LOG")&&_.debug("send data header: ".concat(JSON.stringify(i.commonPacketHeader)));const n=new ArrayBuffer(i.commonPacketHeader.length),r=new Uint8Array(n),o=new DataView(n);let s=0;if(o.setUint16(s,i.commonPacketHeader.extension<<15|i.commonPacketHeader.reserved<<14|i.commonPacketHeader.length,!0),s+=2,o.setUint32(s,i.commonPacketHeader.sequence,!0),s+=4,o.setUint16(s,i.commonStreamHeader,!0),s+=2,i.extension){const a=this.serializeExtension(i.extension);r.set(new Uint8Array(a),s),s+=a.byteLength}if(r.set(new Uint8Array(i.payload),s),s+=i.payload.byteLength,s!==i.commonPacketHeader.length)throw Error("serialize error!");return n}deserialize(e){if(e.byteLength<4)return new ArrayBuffer(0);const i=new DataView(e);let n=0;const r=i.getUint16(n,!0);n+=2;const o={length:16383&r,reserved:(16384&r)>>14,extension:(32768&r)>>15,sequence:i.getUint16(n+2,!0)<<16|i.getUint16(n,!0)};let s,a;if(n+=4,y("SHOW_DATASTREAM2_LOG")&&_.debug("receive data header: ".concat(JSON.stringify(o))),i.getUint16(n,!0),n+=2,o.extension){a=this.deserializeExtension(e.slice(n)),n+=2+a.length,s=e.slice(n);let c=!1;if(a.datas.length>0){const d=a.datas.find(l=>l.id===0);d&&(c=(1&new DataView(d.data).getUint32(0,!0))==1)}s=c?this.decompress(s):s}else s=e.slice(8);return s}serializeExtension(e){const{profile:i,length:n,datas:r}=e,o=new ArrayBuffer(n+2),s=new Uint8Array(o),a=new DataView(o);let c=0;if(a.setUint8(c++,i),a.setUint8(c++,n),r.forEach(d=>{i?(a.setUint8(c++,d.id),a.setUint8(c++,d.length),s.set(new Uint8Array(d.data),c),c+=d.data.byteLength):(a.setUint8(c++,d.id|d.length<<4),s.set(new Uint8Array(d.data),c),c+=d.data.byteLength)}),c!==n+2)throw Error("serialize extension error, is ".concat(c,"!==").concat(n+2));return o}deserializeExtension(e){const i=new DataView(e);let n=0;const r=i.getUint8(n);n++;const o=i.getUint8(n);n++;const s=r===mN.TWO_BYTE,a=[],c=new DataView(e,2);let d=0;for(;d>4,d++),u>0&&(h=c.buffer.slice(d+2,d+2+u),d+=h.byteLength),a.push({id:l,length:u,data:h})}if(d!==o)throw Error("parse error");return{profile:r,length:o,datas:a}}decompress(e){return a4(new Uint8Array(e))}compress(e){return s4(new Uint8Array(e))}}const d4={name:"DataStream",create:(t,e)=>{const i=e?new g3(t):new S3(t);return i.useDataStream(new c4),i}};class l4 extends $t{constructor(e,i,n){super(),S(this,"ws",void 0),S(this,"requestId",1),S(this,"heartBeatTimer",void 0),S(this,"joinInfo",void 0),S(this,"clientId",void 0),S(this,"onOpen",()=>{this.emit("open"),this.startHeartBeatCheck()}),S(this,"onClose",r=>{this.emit("close"),this.dispose()}),S(this,"onMessage",r=>{const o=JSON.parse(r.data);if(!o||o.command!=="serverResponse"||!o.requestId)return o&&o.command==="serverStatus"&&o.serverStatus&&o.serverStatus.command?(this.emit("status",o.serverStatus),void this.emit(o.serverStatus.command,o.serverStatus)):void 0;this.emit("req_".concat(o.requestId),o)}),this.joinInfo=e,this.clientId=i,this.ws=new Gc("cross-channel-".concat(this.clientId),n),this.ws.on(dt.RECONNECTING,()=>{this.ws.reconnectMode="retry",this.emit("reconnecting")}),this.ws.on(dt.CONNECTED,this.onOpen),this.ws.on(dt.ON_MESSAGE,this.onMessage),this.ws.on(dt.CLOSED,this.onClose)}isConnect(){return this.ws.state==="connected"}sendMessage(e){const i=this.requestId++;return e.requestId=i,e.seq=i,this.ws.sendMessage(e),i}waitStatus(e){return new K((i,n)=>{const r=window.setTimeout(()=>{n(new P(v.TIMEOUT,"wait status timeout, status: ".concat(e)))},5e3);this.once(e,o=>{window.clearTimeout(r),o.state&&o.state!==0?n(new P(v.CROSS_CHANNEL_WAIT_STATUS_ERROR,"wait status error, status: ".concat(e))):i(void 0)}),this.once("dispose",()=>{window.clearTimeout(r),n(new P(v.WS_ABORT))})})}request(e){return C(this,null,function*(){if(this.ws.state==="closed")throw new P(v.WS_DISCONNECT);const i=()=>new K((s,a)=>{this.ws.once(dt.CLOSED,()=>a(new P(v.WS_ABORT))),this.ws.once(dt.CONNECTED,s)});this.ws.state!=="connected"&&(yield i());const n=this.sendMessage(e),r=new K((s,a)=>{const c=()=>{a(new P(v.WS_ABORT))};this.ws.once(dt.RECONNECTING,c),this.ws.once(dt.CLOSED,c),this.once("req_".concat(n),s),Ue(3e3).then(()=>{this.removeAllListeners("req_".concat(n)),this.ws.off(dt.RECONNECTING,c),this.ws.off(dt.CLOSED,c),a(new P(v.TIMEOUT,"cross channel ws request timeout"))})}),o=yield r;if(!o||o.code!==200)throw new P(v.CROSS_CHANNEL_SERVER_ERROR_RESPONSE,"response: ".concat(JSON.stringify(o)));return o})}connect(e){return C(this,null,function*(){this.ws.removeAllListeners(dt.REQUEST_NEW_URLS),this.ws.on(dt.REQUEST_NEW_URLS,i=>{i(e)}),yield this.ws.init(e)})}dispose(){this.clearHeartBeatCheck(),this.emit("dispose"),this.removeAllListeners(),this.ws.close()}sendPing(e){const i=this.requestId++;return e.requestId=i,this.ws.sendMessage(e),i}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 u4 extends $t{set state(e){e!==this._state&&(e!==Di.RELAY_STATE_FAILURE&&(this.errorCode=va.RELAY_OK),this.emit("state",e,this.errorCode),this._state=e)}get state(){return this._state}constructor(e,i,n,r,o){super(),S(this,"joinInfo",void 0),S(this,"sid",void 0),S(this,"clientId",void 0),S(this,"cancelToken",Ti.CancelToken.source()),S(this,"workerToken",void 0),S(this,"requestId",0),S(this,"signal",void 0),S(this,"prevChannelMediaConfig",void 0),S(this,"httpRetryConfig",void 0),S(this,"_resolution",void 0),S(this,"_state",Di.RELAY_STATE_IDLE),S(this,"errorCode",va.RELAY_OK),S(this,"onStatus",s=>{_.debug("[".concat(this.clientId,"] ChannelMediaStatus: ").concat(JSON.stringify(s))),s&&s.command&&(s.command==="onAudioPacketReceived"&&this.emit("event",Wr.PACKET_RECEIVED_AUDIO_FROM_SRC),s.command==="onVideoPacketReceived"&&this.emit("event",Wr.PACKET_RECEIVED_VIDEO_FROM_SRC),s.command==="onSrcTokenPrivilegeDidExpire"&&(this.errorCode=va.SRC_TOKEN_EXPIRED,this.state=Di.RELAY_STATE_FAILURE),s.command==="onDestTokenPrivilegeDidExpire"&&(this.errorCode=va.DEST_TOKEN_EXPIRED,this.state=Di.RELAY_STATE_FAILURE))}),S(this,"onReconnect",()=>C(this,null,function*(){_.debug("[".concat(this.clientId,"] ChannelMediaSocket disconnect, reconnecting")),this.emit("event",Wr.NETWORK_DISCONNECTED),this.state=Di.RELAY_STATE_IDLE,this.prevChannelMediaConfig&&this.sendStartRelayMessage(this.prevChannelMediaConfig).catch(s=>{this.state!==Di.RELAY_STATE_IDLE&&(_.error("auto restart channel media relay failed",s.toString()),this.errorCode=va.SERVER_CONNECTION_LOST,this.state=Di.RELAY_STATE_FAILURE)})})),this.joinInfo=e,this.clientId=i,this.sid=Zo(),this.signal=new l4(this.joinInfo,this.clientId,n),this.httpRetryConfig=r,this._resolution=o}startChannelMediaRelay(e){return C(this,null,function*(){if(this.state!==Di.RELAY_STATE_IDLE)throw new P(v.INVALID_OPERATION);this.state=Di.RELAY_STATE_CONNECTING,yield this.connect(),_.debug("[".concat(this.clientId,"] startChannelMediaRelay: connect success"));try{yield this.sendStartRelayMessage(e)}catch(i){throw i.data&&i.data.serverResponse&&i.data.serverResponse.command==="SetSourceChannel"?new P(v.CROSS_CHANNEL_FAILED_JOIN_SRC):i.data&&i.data.serverResponse&&i.serverResponse.command==="SetDestChannelStatus"?new P(v.CROSS_CHANNEL_FAILED_JOIN_DEST):i.data&&i.data.serverResponse&&i.serverResponse.command==="StartPacketTransfer"?new P(v.CROSS_CHANNEL_FAILED_PACKET_SENT_TO_DEST):i}this.prevChannelMediaConfig=e})}updateChannelMediaRelay(e){return C(this,null,function*(){if(this.state!==Di.RELAY_STATE_RUNNING)throw new P(v.INVALID_OPERATION);yield this.sendUpdateMessage(e),this.prevChannelMediaConfig=e})}setVideoProfile(e){return C(this,null,function*(){if(this._resolution=e,this.state!==Di.RELAY_STATE_RUNNING)throw new P(v.INVALID_OPERATION);const i=this.genMessage(_i.SetVideoProfile);yield this.signal.request(i),_.debug("[".concat(this.clientId,"] startChannelMediaRelay: setVideoProfile success"))})}stopChannelMediaRelay(){return C(this,null,function*(){yield this.sendStopRelayMessage(),_.debug("[".concat(this.clientId,"] stopChannelMediaRelay: send stop message success")),this.state=Di.RELAY_STATE_IDLE,this.dispose()})}dispose(){_.debug("[".concat(this.clientId,"] disposeChannelMediaRelay")),this.cancelToken.cancel(),this.cancelToken=Ti.CancelToken.source(),this.state=Di.RELAY_STATE_IDLE,this.emit("dispose"),this.signal.dispose(),this.prevChannelMediaConfig=void 0}connect(){return C(this,null,function*(){const e=yield yW(this.joinInfo,this.cancelToken.token,this.httpRetryConfig);this.workerToken=e.workerToken,yield this.signal.connect(e.addressList),this.emit("event",Wr.NETWORK_CONNECTED),this.signal.on("status",this.onStatus),this.signal.on("reconnecting",this.onReconnect)})}sendStartRelayMessage(e){return C(this,null,function*(){const i=this.genMessage(_i.StopPacketTransfer);yield this.signal.request(i),yield this.signal.waitStatus("Normal Quit"),_.debug("[".concat(this.clientId,"] startChannelMediaRelay: StopPacketTransfer success"));const n=this.genMessage(_i.SetSdkProfile,e);yield this.signal.request(n),_.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSdkProfile success"));const r=this.genMessage(_i.SetSourceChannel,e);yield this.signal.request(r),yield this.signal.waitStatus("SetSourceChannelStatus"),this.emit("event",Wr.PACKET_JOINED_SRC_CHANNEL),_.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSourceChannel success"));const o=this.genMessage(_i.SetSourceUserId,e);yield this.signal.request(o),_.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSourceUserId success"));const s=this.genMessage(_i.SetDestChannel,e);yield this.signal.request(s),yield this.signal.waitStatus("SetDestChannelStatus"),this.emit("event",Wr.PACKET_JOINED_DEST_CHANNEL),_.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetDestChannel success"));const a=this.genMessage(_i.StartPacketTransfer,e);yield this.signal.request(a),this.emit("event",Wr.PACKET_SENT_TO_DEST_CHANNEL),this.state=Di.RELAY_STATE_RUNNING,_.debug("[".concat(this.clientId,"] startChannelMediaRelay: StartPacketTransfer success")),this.setVideoProfile(this._resolution)})}sendUpdateMessage(e){return C(this,null,function*(){const i=this.genMessage(_i.UpdateDestChannel,e);yield this.signal.request(i),this.emit("event",Wr.PACKET_UPDATE_DEST_CHANNEL),_.debug("[".concat(this.clientId,"] sendUpdateMessage: UpdateDestChannel success"))})}sendStopRelayMessage(){return C(this,null,function*(){const e=this.genMessage(_i.StopPacketTransfer);yield this.signal.request(e),_.debug("[".concat(this.clientId,"] sendStopRelayMessage: StopPacketTransfer success"))})}genMessage(e,i){const n=[],r=[],o=[];this.requestId+=1;const s={appId:this.joinInfo.appId,cname:this.joinInfo.cname,uid:this.joinInfo.uid.toString(),sdkVersion:dn,sid:this.sid,ts:Date.now(),requestId:this.requestId,seq:this.requestId,allocate:!0,clientRequest:{}};s.sdkVersion==="4.23.4"&&(s.sdkVersion="0.0.1");let a=null,c=null;switch(e){case _i.SetSdkProfile:return s.clientRequest={command:"SetSdkProfile",type:"multi_channel"},s;case _i.SetSourceChannel:if(c=i&&i.getSrcChannelMediaInfo(),!c)throw new P(v.UNEXPECTED_ERROR,"can not find source config");return s.clientRequest={command:"SetSourceChannel",uid:"0",channelName:c.channelName,token:c.token||this.joinInfo.appId},s;case _i.SetSourceUserId:if(c=i&&i.getSrcChannelMediaInfo(),!c)throw new P(v.UNEXPECTED_ERROR,"can not find source config");return s.clientRequest={command:"SetSourceUserId",uid:c.uid+""},s;case _i.SetDestChannel:if(a=i&&i.getDestChannelMediaInfo(),!a)throw new P(v.UNEXPECTED_ERROR,"can not find dest config");return a.forEach(d=>{n.push(d.channelName),r.push(d.uid+""),o.push(d.token||this.joinInfo.appId)}),s.clientRequest={command:"SetDestChannel",channelName:n,uid:r,token:o},s;case _i.StartPacketTransfer:return s.clientRequest={command:"StartPacketTransfer"},s;case _i.Reconnect:return s.clientRequest={command:"Reconnect"},s;case _i.StopPacketTransfer:return s.clientRequest={command:"StopPacketTransfer"},s;case _i.UpdateDestChannel:if(a=i&&i.getDestChannelMediaInfo(),!a)throw new P(v.UNEXPECTED_ERROR,"can not find dest config");return a.forEach(d=>{n.push(d.channelName),r.push(d.uid+""),o.push(d.token||this.joinInfo.appId)}),s.clientRequest={command:"UpdateDestChannel",channelName:n,uid:r,token:o},s;case _i.SetVideoProfile:s.clientRequest={command:"SetVideoProfile",width:this._resolution.width,height:this._resolution.height}}return s}}const h4={name:"ChannelMediaRelay",create:function(t){return new u4(t.joinInfo,t.clientId,t.websocketRetryConfig||ge,t.httpRetryConfig||ge,t.resolution)}};function fN(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable})),i.push.apply(i,n)}return i}function Td(t){for(var e=1;e{this.reconnectMode="retry",this.startPingPong()}),S(this,"handleWebSocketMessage",o=>{if(!o.data)return;const s=JSON.parse(o.data);s.requestId?this.emit("@".concat(s.requestId,"-").concat(s.sid),s):(Z.workerEvent(this.spec.sid,{actionType:"status",serverCode:s.code,workerType:this.serviceMode===Gr.TRANSCODE?1:2}),this.emit(fo.PUBLISH_STREAM_STATUS,s))}),this.spec=i,this.token=e,this.serviceMode=r,this.websocket=new Gc("live-streaming",n),this.websocket.on(dt.CONNECTED,this.handleWebSocketOpen),this.websocket.on(dt.ON_MESSAGE,this.handleWebSocketMessage),this.websocket.on(dt.REQUEST_NEW_URLS,(o,s)=>{We(this,fo.REQUEST_NEW_ADDRESS).then(o).catch(s)}),this.websocket.on(dt.RECONNECTING,()=>{this.websocket.reconnectMode=this.reconnectMode})}init(e){return this.websocket.init(e)}request(e,i,n,r){return C(this,null,function*(){this.reqId+=1,e==="request"&&(this.commandReqId+=1);const o=this.commandReqId,s=this.reqId;if(!s||!this.websocket)throw new P(v.UNEXPECTED_ERROR);const a=Td({command:e,sdkVersion:dn==="4.23.4"?"0.0.1":dn,seq:s,requestId:s,allocate:n,cname:this.spec.cname,appId:this.spec.appId,sid:this.spec.sid,uid:this.spec.uid.toString(),ts:Math.floor(Date.now()/1e3)},i);if(this.websocket.state==="closed")throw new P(v.WS_DISCONNECT);const c=()=>new K((h,p)=>{this.websocket.once(dt.CLOSED,()=>p(new P(v.WS_ABORT))),this.websocket.once(dt.CONNECTED,h)});this.websocket.state!=="connected"&&(yield c()),a.clientRequest&&(a.clientRequest.workerToken=this.token);const d=new K((h,p)=>{const g=()=>{p(new P(v.WS_ABORT))};this.websocket.once(dt.RECONNECTING,g),this.websocket.once(dt.CLOSED,g),this.once("@".concat(s,"-").concat(this.spec.sid),m=>{h(m)})});r&&Z.workerEvent(this.spec.sid,Td(Td({},r),{},{requestId:o,actionType:"request",payload:JSON.stringify(i.clientRequest),serverCode:0,code:0}));const l=Date.now();this.websocket.sendMessage(a);let u=null;try{u=yield d}catch(h){if(this.websocket.state==="closed")throw h;return yield c(),yield this.request(e,i,n)}return r&&Z.workerEvent(this.spec.sid,Td(Td({},r),{},{requestId:o,actionType:"response",payload:JSON.stringify(u.serverResponse),serverCode:u.code,success:u.code===200,responseTime:Date.now()-l})),u.code!==200&&this.handleResponseError(u),u})}tryNextAddress(){this.reconnectMode="tryNext",this.websocket.reconnect("tryNext")}close(){const e=dn==="4.23.4"?"0.0.1":dn;this.reqId+=1,this.websocket.state==="connected"?(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 Ce.LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM:return void _.warning("live stream response already exists stream");case Ce.LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR:case Ce.LIVE_STREAM_RESPONSE_BAD_STREAM:case Ce.LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR:return new P(v.LIVE_STREAMING_INVALID_ARGUMENT,"",{code:e.code}).throw();case Ce.LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST:if(e.serverResponse.command==="UnpublishStream")return;throw new P(v.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream response wm worker not exist",{retry:!0});case Ce.LIVE_STREAM_RESPONSE_NOT_AUTHORIZED:return new P(v.LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED,"",{code:e.code}).throw();case Ce.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE:{const i=new P(v.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE);return this.emit(fo.WARNING,i,e.serverResponse.url)}case Ce.LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN:{const i=new P(v.LIVE_STREAMING_WARN_FREQUENT_REQUEST);return this.emit(fo.WARNING,i,e.serverResponse.url)}case Ce.LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH:throw new P(v.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream response wm worker not exist",{retry:!0});case Ce.LIVE_STREAM_RESPONSE_NOT_SUPPORTED:return new P(v.LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED,"",{code:e.code}).throw();case Ce.LIVE_STREAM_RESPONSE_MAX_STREAM_NUM:{const i=new P(v.LIVE_STREAMING_WARN_STREAM_NUM_REACH_LIMIT);return this.emit(fo.WARNING,i,e.serverResponse.url)}case Ce.LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR:return new P(v.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"",{code:e.code}).throw();case Ce.LIVE_STREAM_RESPONSE_RESOURCE_LIMIT:throw new P(v.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream resource limit",{retry:!0,changeAddress:!0});case Ce.LIVE_STREAM_RESPONSE_WORKER_LOST:case Ce.LIVE_STREAM_RESPONSE_WORKER_QUIT:if(e.serverResponse.command==="UnpublishStream")return;throw new P(v.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{retry:!0,changeAddress:!0});case Ce.ERROR_FAIL_SEND_MESSAGE:if(e.serverResponse.command==="UnpublishStream")return;if(e.serverResponse.command==="UpdateTranscoding"||e.serverResponse.command==="ControlStream")return new P(v.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{code:e.code}).throw();throw new P(v.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{retry:!0,changeAddress:!0});case Ce.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN:case Ce.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT:case Ce.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE:case Ce.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH:return new P(v.LIVE_STREAMING_CDN_ERROR,"",{code:e.code}).throw()}}startPingPong(){this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(()=>{this.websocket.state==="connected"&&this.request("ping",{}).catch(lu)},6e3)}}function gN(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable})),i.push.apply(i,n)}return i}function Pi(t){for(var e=1;e1&&arguments[1]!==void 0?arguments[1]:ge,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:ge;super(),S(this,"onLiveStreamWarning",void 0),S(this,"onLiveStreamError",void 0),S(this,"spec",void 0),S(this,"retryTimeout",1e4),S(this,"connection",void 0),S(this,"httpRetryConfig",void 0),S(this,"wsRetryConfig",void 0),S(this,"streamingTasks",new Map),S(this,"isStartingStreamingTask",!1),S(this,"taskMutex",new qe("live-streaming")),S(this,"cancelToken",Ti.CancelToken.source()),S(this,"transcodingConfig",void 0),S(this,"uapResponse",void 0),S(this,"lastTaskId",1),S(this,"statusError",new Map),this.spec=e,this.httpRetryConfig=n,this.wsRetryConfig=i}setTranscodingConfig(e){return C(this,null,function*(){const i=Pi(Pi({},nW),e);i.videoCodecProfile!==66&&i.videoCodecProfile!==77&&i.videoCodecProfile!==100&&(_.debug("[".concat(this.spec.clientId,"] set transcoding config, fix video codec profile: ").concat(i.videoCodecProfile," -> 100")),i.videoCodecProfile=100),i.transcodingUsers||(i.transcodingUsers=i.userConfigs),i.transcodingUsers&&(i.transcodingUsers=i.transcodingUsers.map(s=>Pi(Pi(Pi({},iW),s),{},{zOrder:s.zOrder?s.zOrder+1:1}))),function(s){re(s.width)||xt(s.width,"config.width",0,1e4),re(s.height)||xt(s.height,"config.height",0,1e4),re(s.videoBitrate)||xt(s.videoBitrate,"config.videoBitrate",1,1e6),re(s.videoFrameRate)||xt(s.videoFrameRate,"config.videoFrameRate"),re(s.lowLatency)||Fr(s.lowLatency,"config.lowLatency"),re(s.audioSampleRate)||Ae(s.audioSampleRate,"config.audioSampleRate",[32e3,44100,48e3]),re(s.audioBitrate)||xt(s.audioBitrate,"config.audioBitrate",1,128),re(s.audioChannels)||Ae(s.audioChannels,"config.audioChannels",[1,2,3,4,5]),re(s.videoGop)||xt(s.videoGop,"config.videoGop"),re(s.videoCodecProfile)||Ae(s.videoCodecProfile,"config.videoCodecProfile",[66,77,100]),re(s.userCount)||xt(s.userCount,"config.userCount",0,17),re(s.backgroundColor)||xt(s.backgroundColor,"config.backgroundColor",0,16777215),re(s.userConfigExtraInfo)||Me(s.userConfigExtraInfo,"config.userConfigExtraInfo",0,4096,!1),s.transcodingUsers&&!re(s.transcodingUsers)&&(Br(s.transcodingUsers,"config.transcodingUsers"),s.transcodingUsers.forEach((a,c)=>{ku(a.uid),re(a.x)||xt(a.x,"transcodingUser[".concat(c,"].x"),0,1e4),re(a.y)||xt(a.y,"transcodingUser[".concat(c,"].y"),0,1e4),re(a.width)||xt(a.width,"transcodingUser[".concat(c,"].width"),0,1e4),re(a.height)||xt(a.height,"transcodingUser[".concat(c,"].height"),0,1e4),re(a.zOrder)||xt(a.zOrder-1,"transcodingUser[".concat(c,"].zOrder"),0,100),re(a.alpha)||xt(a.alpha,"transcodingUser[".concat(c,"].alpha"),0,1,!1)})),re(s.watermark)||Im(s.watermark,"watermark"),re(s.backgroundImage)||Im(s.backgroundImage,"backgroundImage"),s.images&&!re(s.images)&&(Br(s.images,"config.images"),s.images.forEach((a,c)=>{Im(a,"images[".concat(c,"]"))}))}(i);const n=[];i.images&&n.push(...i.images.map(s=>Pi(Pi(Pi({},ym),s),{},{zOrder:255}))),i.backgroundImage&&(n.push(Pi(Pi(Pi({},ym),i.backgroundImage),{},{zOrder:0})),delete i.backgroundImage),i.watermark&&(n.push(Pi(Pi(Pi({},ym),i.watermark),{},{zOrder:255})),delete i.watermark),i.images=n,i.transcodingUsers&&(i.userConfigs=i.transcodingUsers.map(s=>Pi({},s)),i.userCount=i.transcodingUsers.length,delete i.transcodingUsers);const r=(i.userConfigs||[]).map(s=>typeof s.uid=="number"?K.resolve(s.uid):jw(s.uid,this.spec,this.cancelToken.token,this.httpRetryConfig));if((yield K.all(r)).forEach((s,a)=>{i.userConfigs&&i.userConfigs[a]&&(i.userConfigs[a].uid=s)}),this.transcodingConfig=i,this.connection)try{var o;const s=yield this.connection.request("request",{clientRequest:{command:"UpdateTranscoding",transcodingConfig:this.transcodingConfig}},!1,{command:"UpdateTranscoding",workerType:1,requestByUser:!0,tid:Array.from(Ui(o=this.streamingTasks).call(o)).map(a=>a.taskId).join("#")});_.debug("[".concat(this.spec.clientId,"] update live transcoding config success, code: ").concat(s.code,", config:"),JSON.stringify(this.transcodingConfig))}catch(s){if(!s.data||!s.data.retry)throw s;s.data.changeAddress&&this.connection.tryNextAddress(),this.streamingTasks.forEach(a=>{_.warning("[".concat(this.spec.clientId,"] live streaming receive error"),s.toString(),"try to republish",a.url),this.startLiveStreamingTask(a.url,a.mode,s).then(()=>{_.debug("[".concat(this.spec.clientId,"] live streaming republish ").concat(a.url," success"))}).catch(c=>{_.error("[".concat(this.spec.clientId,"] live streaming republish failed"),a.url,c.toString()),this.onLiveStreamError&&this.onLiveStreamError(a.url,c)})})}})}startLiveStreamingTask(e,i,n){return C(this,null,function*(){if(!this.transcodingConfig&&i===Gr.TRANSCODE)throw new P(v.INVALID_OPERATION,"[LiveStreaming] no transcoding config found, can not start transcoding streaming task");const r={command:"PublishStream",ts:Date.now(),url:e,uid:this.spec.uid.toString(),autoDestroyTime:100,acceptImageTimeout:!0};_.debug("[".concat(this.spec.clientId,"] start live streaming ").concat(e,", mode: ").concat(i));const o=yield this.taskMutex.lock();if(!this.connection&&n)return void o();if(this.streamingTasks.get(e)&&!n)return o(),new P(v.LIVE_STREAMING_TASK_CONFLICT).throw();try{this.connection||(this.connection=yield this.connect(i))}catch(a){throw o(),a}switch(i){case Gr.TRANSCODE:r.transcodingConfig=Pi({},this.transcodingConfig)}this.uapResponse&&this.uapResponse.vid&&(r.vid=this.uapResponse.vid),this.isStartingStreamingTask=!0;const s=this.lastTaskId++;try{const a=new K((d,l)=>{Ue(this.retryTimeout).then(()=>{if(n)return l(n);const u=this.statusError.get(e);return u?(this.statusError.delete(e),l(u)):void 0})}),c=yield K.race([this.connection.request("request",{clientRequest:r},!0,{url:e,command:"PublishStream",workerType:i===Gr.TRANSCODE?1:2,requestByUser:!n,tid:s.toString()}),a]);this.isStartingStreamingTask=!1,_.debug("[".concat(this.spec.clientId,"] live streaming started, code: ").concat(c.code)),this.streamingTasks.set(e,{clientRequest:r,mode:i,url:e,taskId:s}),o()}catch(a){if(o(),this.isStartingStreamingTask=!1,!a.data||!a.data.retry||n)throw a;return a.data.changeAddress?(this.connection.tryNextAddress(),yield this.startLiveStreamingTask(e,i,a)):yield this.startLiveStreamingTask(e,i,a)}})}stopLiveStreamingTask(e){return new K((i,n)=>{const r=this.streamingTasks.get(e);if(!r||!this.connection)return new P(v.UNEXPECTED_ERROR,"can not find streaming task to stop").throw();const o=r.mode;r.abortTask=()=>{_.debug("[".concat(this.spec.clientId,"] stop live streaming success(worker exception)")),this.streamingTasks.delete(e),i()},this.connection.request("request",{clientRequest:{command:"UnpublishStream",url:r.url}},!1,{url:e,command:"UnPublishStream",workerType:o===Gr.TRANSCODE?1:2,requestByUser:!0,tid:(this.lastTaskId++).toString()}).then(s=>{_.debug("[".concat(this.spec.clientId,"] stop live streaming success, code: ").concat(s.code)),this.streamingTasks.delete(e),this.streamingTasks.size===0&&(this.connection&&this.connection.close(),this.connection=void 0),i()}).catch(n)})}resetAllTask(){var e;const i=Array.from(Ui(e=this.streamingTasks).call(e));this.terminate();for(const n of i)this.startLiveStreamingTask(n.url,n.mode).catch(r=>{this.onLiveStreamError&&this.onLiveStreamError(n.url,r)})}terminate(){this.cancelToken&&this.cancelToken.cancel(),this.streamingTasks=new Map,this.isStartingStreamingTask=!1,this.statusError=new Map,this.cancelToken=Ti.CancelToken.source(),this.uapResponse=void 0,this.connection&&this.connection.close(),this.connection=void 0}connect(e){return C(this,null,function*(){if(this.connection)throw new P(v.UNEXPECTED_ERROR,"live streaming connection has already connected");const i=yield We(this,Am.REQUEST_WORKER_MANAGER_LIST,e);return this.uapResponse=i,this.connection=new p4(i.workerToken,this.spec,this.wsRetryConfig,e),this.connection.on(fo.WARNING,(n,r)=>this.onLiveStreamWarning&&this.onLiveStreamWarning(r,n)),this.connection.on(fo.PUBLISH_STREAM_STATUS,n=>this.handlePublishStreamServer(n)),this.connection.on(fo.REQUEST_NEW_ADDRESS,(n,r)=>{if(!this.connection)return r(new P(v.UNEXPECTED_ERROR,"can not get new live streaming address list"));We(this,Am.REQUEST_WORKER_MANAGER_LIST,e).then(o=>{this.uapResponse=o,n(o.addressList)}).catch(r)}),yield this.connection.init(i.addressList),this.connection})}handlePublishStreamServer(e){const i=e.serverStatus&&e.serverStatus.url||"empty_url",n=this.streamingTasks.get(i),r=e.reason;switch(e.code){case Ce.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN:case Ce.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT:case Ce.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE:case Ce.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH:{const s=new P(v.LIVE_STREAMING_CDN_ERROR,"",{code:e.code});if(n)return _.error(s.toString()),this.onLiveStreamError&&this.onLiveStreamError(i,s);if(!this.isStartingStreamingTask)return;this.statusError.set(i,s)}case Ce.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE:{const s=new P(v.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE,r);return this.onLiveStreamWarning&&this.onLiveStreamWarning(i,s)}case Ce.LIVE_STREAM_RESPONSE_WORKER_LOST:case Ce.LIVE_STREAM_RESPONSE_WORKER_QUIT:{var o;if(!this.connection)return;this.connection.tryNextAddress();const s=Array.from(Ui(o=this.streamingTasks).call(o));for(const a of s)a.abortTask?a.abortTask():(_.warning("[".concat(this.spec.clientId,"] publish stream status code"),e.code,"try to republish",a.url),this.startLiveStreamingTask(a.url,a.mode,new P(v.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"",{code:e.code})).then(()=>{_.debug("[".concat(this.spec.clientId,"] republish live stream success"),a.url)}).catch(c=>{_.error(c.toString()),this.onLiveStreamError&&this.onLiveStreamError(a.url,c)}));return}}}hasUrl(e){return this.streamingTasks.has(e)}}const E4={name:"LiveStreaming",create:function(t){return new _4(t.joinInfo,t.websocketRetryConfig||ge,t.httpRetryConfig||ge)}};function m4(t){let e=RN();return function(i,n){let r=i.appId;r!==void 0&&(Dt(n,10),Or(n,r));let o=i.cid;o!==void 0&&(Dt(n,16),Dt(n,o));let s=i.cname;s!==void 0&&(Dt(n,26),Or(n,s));let a=i.deviceId;a!==void 0&&(Dt(n,34),Or(n,a));let c=i.elapse;c!==void 0&&(Dt(n,40),Do(n,c));let d=i.fileSize;d!==void 0&&(Dt(n,48),Do(n,Ba(d)));let l=i.height;l!==void 0&&(Dt(n,56),Do(n,Ba(l)));let u=i.jpg;u!==void 0&&(Dt(n,66),Dt(n,u.length),function(Ii,U){let B=ja(Ii,U.length);Ii.bytes.set(U,B)}(n,u));let h=i.networkType;h!==void 0&&(Dt(n,72),Do(n,Ba(h)));let p=i.osType;p!==void 0&&(Dt(n,80),Do(n,Ba(p)));let g=i.requestId;g!==void 0&&(Dt(n,90),Or(n,g));let m=i.sdkVersion;m!==void 0&&(Dt(n,98),Or(n,m));let f=i.sequence;f!==void 0&&(Dt(n,104),Do(n,Ba(f)));let T=i.sid;T!==void 0&&(Dt(n,114),Or(n,T));let R=i.timestamp;R!==void 0&&(Dt(n,120),Do(n,R));let A=i.uid;A!==void 0&&(Dt(n,128),Dt(n,A));let N=i.vid;N!==void 0&&(Dt(n,136),Dt(n,N));let O=i.width;O!==void 0&&(Dt(n,144),Do(n,Ba(O)));let w=i.service;w!==void 0&&(Dt(n,152),Dt(n,w));let L=i.callbackData;L!==void 0&&(Dt(n,162),Or(n,L));let M=i.jpgEncryption;M!==void 0&&(Dt(n,168),Dt(n,M));let j=i.requestType;j!==void 0&&(Dt(n,176),Dt(n,j));let H=i.scorePorn;H!==void 0&&(Dt(n,185),Pf(n,H));let ht=i.scoreSexy;ht!==void 0&&(Dt(n,193),Pf(n,ht));let lt=i.scoreNeutral;lt!==void 0&&(Dt(n,201),Pf(n,lt));let rt=i.scene;rt!==void 0&&(Dt(n,208),Dt(n,rt));let Kt=i.ossFilePrefix;Kt!==void 0&&(Dt(n,218),Or(n,Kt));let Ft=i.serviceVendor;if(Ft!==void 0)for(let Ii of Ft){Dt(n,226);let U=RN();S4(Ii,U),Dt(n,U.limit),C4(n,U),v4(U)}}(t,e),function(i){let n=i.bytes,r=i.limit;return n.length===r?n:n.subarray(0,r)}(e)}function f4(t){return function(i){let n={};t:for(;!vN(i);){let r=Nr(i);switch(r>>>3){case 0:break t;case 1:n.code=Nr(i);break;case 2:n.msg=CN(i,Nr(i));break;case 3:{let o=T4(i);n.data=g4(i),i.limit=o;break}default:SN(i,7&r)}}return n}({bytes:e=t,offset:0,limit:e.length});var e}function g4(t){let e={};t:for(;!vN(t);){let i=Nr(t);switch(i>>>3){case 0:break t;case 1:e.requestId=CN(t,Nr(t));break;case 2:e.requestType=Nr(t)>>>0;break;case 3:e.scorePorn=Df(t);break;case 4:e.scoreSexy=Df(t);break;case 5:e.scoreNeutral=Df(t);break;case 6:e.requestScene=Nr(t)>>>0;break;case 7:e.scene=Nr(t)>>>0;break;default:SN(t,7&i)}}return e}function S4(t,e){let i=t.service;i!==void 0&&(Dt(e,8),Dt(e,i));let n=t.vendor;n!==void 0&&(Dt(e,16),Dt(e,n));let r=t.token;r!==void 0&&(Dt(e,26),Or(e,r));let o=t.callbackUrl;o!==void 0&&(Dt(e,34),Or(e,o))}function T4(t){let e=Nr(t),i=t.limit;return t.limit=t.offset+e,i}function SN(t,e){switch(e){case 0:for(;128&yN(t););break;case 2:Of(t,Nr(t));break;case 5:Of(t,4);break;case 1:Of(t,8);break;default:throw new Error("Unimplemented type: "+e)}}let R4=new Float32Array(1);new Uint8Array(R4.buffer);let wf=new Float64Array(1),Li=new Uint8Array(wf.buffer);function Ba(t){return{low:t|=0,high:t>>31,unsigned:t>=0}}let TN=[];function RN(){const t=TN.pop();return t?(t.offset=t.limit=0,t):{bytes:new Uint8Array(64),offset:0,limit:0}}function v4(t){TN.push(t)}function Of(t,e){if(t.offset+e>t.limit)throw new Error("Skip past limit");t.offset+=e}function vN(t){return t.offset>=t.limit}function ja(t,e){let i=t.bytes,n=t.offset,r=t.limit,o=n+e;if(o>i.length){let s=new Uint8Array(2*o);s.set(i),t.bytes=s}return t.offset=o,o>r&&(t.limit=o),n}function Nf(t,e){let i=t.offset;if(i+e>t.limit)throw new Error("Read past limit");return t.offset+=e,i}function CN(t,e){let i=Nf(t,e),n=String.fromCharCode,r=t.bytes,o="�",s="";for(let a=0;a=e?s+=o:(c=r[a+i+1],(192&c)!=128?s+=o:(u=(31&h)<<6|63&c,u<128?s+=o:(s+=n(u),a++))):(240&h)==224?a+2>=e?s+=o:(c=r[a+i+1],d=r[a+i+2],(49344&(c|d<<8))!=32896?s+=o:(u=(15&h)<<12|(63&c)<<6|63&d,u<2048||u>=55296&&u<=57343?s+=o:(s+=n(u),a+=2))):(248&h)==240?a+3>=e?s+=o:(c=r[a+i+1],d=r[a+i+2],l=r[a+i+3],(12632256&(c|d<<8|l<<16))!=8421504?s+=o:(u=(7&h)<<18|(63&c)<<12|(63&d)<<6|63&l,u<65536||u>1114111?s+=o:(u-=65536,s+=n(55296+(u>>10),56320+(1023&u)),a+=3))):s+=o:s+=n(h)}return s}function Or(t,e){let i=e.length,n=0;for(let s=0;s=55296&&a<=56319&&s+1=55296&&a<=56319&&s+1>6&31|192:(a<65536?o[r++]=a>>12&15|224:(o[r++]=a>>18&7|240,o[r++]=a>>12&63|128),o[r++]=a>>6&63|128),o[r++]=63&a|128)}}function C4(t,e){let i=ja(t,e.limit),n=t.bytes,r=e.bytes;for(let o=0,s=e.limit;o>>=0;e>=128;)IN(t,127&e|128),e>>>=7;IN(t,e)}function Do(t,e){let i=e.low>>>0,n=(e.low>>>28|e.high<<4)>>>0,r=e.high>>>24,o=r===0?n===0?i<16384?i<128?1:2:i<1<<21?3:4:n<16384?n<128?5:6:n<1<<21?7:8:r<128?9:10,s=ja(t,o),a=t.bytes;switch(o){case 10:a[s+9]=r>>>7&1;case 9:a[s+8]=o!==9?128|r:127&r;case 8:a[s+7]=o!==8?n>>>21|128:n>>>21&127;case 7:a[s+6]=o!==7?n>>>14|128:n>>>14&127;case 6:a[s+5]=o!==6?n>>>7|128:n>>>7&127;case 5:a[s+4]=o!==5?128|n:127&n;case 4:a[s+3]=o!==4?i>>>21|128:i>>>21&127;case 3:a[s+2]=o!==3?i>>>14|128:i>>>14&127;case 2:a[s+1]=o!==2?i>>>7|128:i>>>7&127;case 1:a[s]=o!==1?128|i:127&i}}function AN(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable})),i.push.apply(i,n)}return i}const y4=new Map([["moderation",1],["supervise",2]]);class I4 extends $t{get connectionState(){return this._connectionState}set connectionState(e){if(this._connectionState===e)return;const i=this._connectionState;this._connectionState=e,this.emit(Pe.CONNECTION_STATE_CHANGE,i,e)}get inspectType(){return this._inspectType}set inspectType(e){var i;this._inspectMode=Tn(i=e.map(n=>y4.get(n)||0)).call(i,(n,r)=>n+r),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(),S(this,"name","AgoraRTCVideoContentInspect"),S(this,"_connectionState",Pn.CONNECTING),S(this,"_innerConnectionState",void 0),S(this,"sequence",0),S(this,"inspectStartTime",void 0),S(this,"workerManagerConnection",void 0),S(this,"workerConnection",void 0),S(this,"workerMessageLengthLimit",void 0),S(this,"inspectIntervalMinimum",void 0),S(this,"qualityRatio",void 0),S(this,"_connectInfo",void 0),S(this,"_cancelTokenSource",Ti.CancelToken.source()),S(this,"_retryConfig",void 0),S(this,"wmSequence",0),S(this,"inspectInterval",void 0),S(this,"inspectTimer",null),S(this,"ossFilePrefix",void 0),S(this,"extraInfo",void 0),S(this,"_inspectType",void 0),S(this,"_inspectMode",void 0),S(this,"_quality",1),S(this,"qualityTimer",null),S(this,"_inspectId",void 0),S(this,"_needWorkUrlOnly",!1),S(this,"inspectImage",()=>{if(this.connectionState!==Pn.CONNECTED)throw new P(v.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===Pn.CONNECTED?this.requestToInspectImage():_.debug("[".concat(this._inspectId,"] Inspect State is not connected , "),this.connectionState)},this.inspectInterval{this._innerConnectionState=i,_.debug("[".concat(this._inspectId,"] Inspect operation :").concat(Ln[i]," ").concat(n||""))}),this.handleWorkerManagerEvents(),this.workerConnection=new Gc("worker-"+this._inspectId,ge),this.handleWorkerEvents()}init(e,i){return C(this,null,function*(){this.emit(Pe.STATE_CHANGE,Ln.CONNECT_AP),this._connectInfo=e;const n=this._cancelTokenSource.token;return this._retryConfig=i,new K((r,o)=>{this.on(Pe.CONNECTION_STATE_CHANGE,(s,a)=>{a===Pn.CONNECTED&&r()}),this.requestAP(e,n,i).then(s=>{this.connectWorkerManager(s)}).catch(s=>{o(s)})})})}requestAP(e,i,n){return C(this,null,function*(){const r=y("WEBCS_DOMAIN").map(a=>"https://".concat(a,"/api/v1")),o=yield function(a,c,d,l){let{appId:u,areaCode:h,cname:p,sid:g,token:m,uid:f}=c;Oa++;const T="image_moderation_api",R={service_name:T,json_body:JSON.stringify({appId:u,areaCode:h,cname:p,command:"allocateEdge",requestId:Oa,seq:Oa,sid:g,token:m,ts:Date.now(),uid:f+""})};let A,N,O=a[0];return Jn(()=>C(this,null,function*(){A=Date.now();const w=yield er(O,{data:R,cancelToken:d,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"},params:{action:"wrtc_gateway"}});if(N=Date.now()-A,w.code!==0){const H=new P(v.UNEXPECTED_RESPONSE,"image inspect ap error, code"+w.code,{retry:!0,responseTime:N});throw _.error(H.toString()),H}const L=JSON.parse(w.json_body);if(L.code!==200){const H=new P(v.UNEXPECTED_RESPONSE,"image inspect ap error, code: ".concat(L.code,", reason: ").concat(L.reason),{code:L.code,responseTime:N});throw _.error(H.toString()),H}if(!L.servers||!Array.isArray(L.servers)||L.servers.length===0){const H=new P(v.UNEXPECTED_RESPONSE,"image inspect ap empty server",{code:L.code,responseTime:N});throw _.error(H.toString()),H}const M=y("VIDEO_INSPECT_WORKER_MANAGER_HOST"),j=y("VIDEO_INSPECT_WORKER_MANAGER_PORT");return{addressList:L.servers.map(H=>{let{address:ht,wss:lt}=H;if(ht&<)return"wss://".concat(ht.replace(/\./g,"-"),".").concat(M,":").concat(j||lt)}).filter(H=>!!H),workerToken:L.workerToken,vid:L.vid,responseTime:N}}),(w,L)=>(Z.apworkerEvent(g,{success:!0,sc:200,serviceName:T,responseDetail:JSON.stringify(w.addressList),firstSuccess:L===0,responseTime:N,serverIp:a[L%a.length]}),!1),(w,L)=>(Z.apworkerEvent(g,{success:!1,sc:w.data&&w.data.code||200,serviceName:T,responseTime:N,serverIp:a[L%a.length]}),!!(w.code!==v.OPERATION_ABORTED&&w.code!==v.UNEXPECTED_RESPONSE||w.data&&w.data.retry)&&(O=a[(L+1)%a.length],!0)),l)}(r,e,i,n);this.emit(Pe.STATE_CHANGE,Ln.AP_CONNECTED);const{addressList:s}=o;return this.wmSequence++,s})}connectWorkerManager(i){return C(this,arguments,function*(e){let n=arguments.length>1&&arguments[1]!==void 0&&arguments[1];this._needWorkUrlOnly=n,this.emit(Pe.STATE_CHANGE,Ln.CONNECT_WORKER_MANAGER),yield this.workerManagerConnection.init(e,1e4)})}connectWorker(e){return C(this,null,function*(){yield this.workerConnection.init([e])})}handleWorkerManagerEvents(){this.workerManagerConnection.on(dt.CONNECTED,()=>C(this,null,function*(){this.emit(Pe.STATE_CHANGE,Ln.WORKER_MANAGER_CONNECTED,this.workerManagerConnection.url),this.workerManagerConnection.sendMessage({appId:this._connectInfo.appId,cname:this._connectInfo.cname,uid:this._connectInfo.uid+"",sdkVersion:"4.23.4",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(dt.CLOSED,()=>{this._innerConnectionState{this._innerConnectionState{this._innerConnectionStateC(this,null,function*(){this.emit(Pe.STATE_CHANGE,Ln.GET_WORKER_MANAGER_RESPONSE);const i=this.workerManagerConnection.url;this.workerManagerConnection.close();const n=JSON.parse(e.data);if(n.code!==200)throw _.error("[".concat(this._inspectId,"] Unexpected code ").concat(n.code," from worker manager")),new P(v.UNEXPECTED_RESPONSE,"response code of worker is unexpected",n);if(!(n.serverResponse&&n.serverResponse.portWss&&i))throw _.error("[".concat(this._inspectId,"] Unexpected content from worker manager : ").concat(JSON.stringify(n))),new P(v.UNEXPECTED_RESPONSE,"response content of worker is unexpected",n);{const r=y("VIDEO_INSPECT_WORKER_PORT")||n.serverResponse.portWss,o=i.replace(/:\d+\/?$/,":".concat(r));this.emit(Pe.STATE_CHANGE,Ln.CONNECT_WORKER,o),this._needWorkUrlOnly?this.emit(Pe.REQUEST_NEW_WORKER_URL,o):yield this.connectWorker(o)}})),this.workerManagerConnection.on(dt.WILL_RECONNECT,(e,i,n)=>{n(e)}),this.workerManagerConnection.on(dt.REQUEST_NEW_URLS,(e,i)=>{this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then(e).catch(i)})}handleWorkerEvents(){this.workerConnection.on(dt.CONNECTED,()=>C(this,null,function*(){this.emit(Pe.STATE_CHANGE,Ln.WORKER_CONNECTED,this.workerConnection.url),this.connectionState=Pn.CONNECTED})),this.workerConnection.on(dt.ON_MESSAGE,e=>C(this,null,function*(){if(e.data instanceof ArrayBuffer){const n=f4(new Uint8Array(e.data));if(y("SHOW_VIDEO_INSPECT_WORKER_MESSAGE")&&_.debug("[".concat(this._inspectId,"] Response message for worker of inspect content "),JSON.stringify(n)),n.code===200){if(Array.isArray(this.inspectType)&&this.inspectType.length===1&&this.inspectType[0]==="supervise")return void this.emit(Pe.INSPECT_RESULT,void 0,void 0);if(n.data&&n.data.scorePorn&&n.data.scoreSexy&&n.data.scoreNeutral){var i;const r={porn:n.data.scorePorn,sexy:n.data.scoreSexy,neutral:n.data.scoreNeutral},o=Tn(i=Object.keys(r)).call(i,(a,c)=>r[a]>r[c]?a:c,"porn"),s=Object.keys(r).find(a=>a===o);this.emit(Pe.INSPECT_RESULT,s)}else this.emit(Pe.INSPECT_RESULT,void 0,new P(v.UNEXPECTED_RESPONSE,n.code+"","There is an unexpected data on message"))}else this.emit(Pe.INSPECT_RESULT,void 0,new P(v.UNEXPECTED_RESPONSE,n.code+"",n.msg))}else _.error("[".concat(this._inspectId,"] Unexpected message type from worker")),this.emit(Pe.INSPECT_RESULT,void 0,new P(v.UNEXPECTED_RESPONSE,"invalid worker message type"))})),this.workerConnection.on(dt.CLOSED,()=>{this.connectionState=Pn.CLOSED}),this.workerConnection.on(dt.FAILED,()=>{this.connectionState=Pn.CLOSED}),this.workerConnection.on(dt.RECONNECTING,()=>{this.connectionState=this.connectionState===Pn.CONNECTED?Pn.RECONNECTING:Pn.CONNECTING}),this.workerConnection.on(dt.WILL_RECONNECT,(e,i,n)=>{e==="recover"&&n(e),n("tryNext")}),this.workerConnection.on(dt.REQUEST_NEW_URLS,(e,i)=>{this.workerManagerConnection.close(),this.once(Pe.REQUEST_NEW_WORKER_URL,n=>{e([n])}),this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then(n=>{this.connectWorkerManager(n,!0)}).catch(n=>{i(n)})})}requestToInspectImage(){return C(this,null,function*(){this.sequence++;const e=zi(this,Pe.CLIENT_LOCAL_VIDEO_TRACK),i={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(Pe.INSPECT_RESULT,void 0,new P(v.INVALID_OPERATION,"Only the track being played can be inspected"));const n=yield this.generateRequestData(e,i);this.workerConnection.sendMessage(n,!0,!0)}else this.emit(Pe.INSPECT_RESULT,void 0,new P(v.INVALID_OPERATION,"Only the track being published can be inspected"))})}generateRequestData(e,i){return C(this,null,function*(){let{appId:n,cname:r,cid:o,vid:s,sid:a,uid:c}=i;const d=Date.now(),l=yield e.getCurrentFrameImage("image/jpeg",this.quality),u=yield cA(l,n,r),h=this.sequence+"-"+o+"-"+c+"-"+d+"-"+Gt(12,""),p={appId:n,cid:o,cname:r,deviceId:"",elapse:(g=Number(d-this.inspectStartTime),{low:g|=0,high:g>>31,unsigned:g>=0}),fileSize:u.byteLength,jpgEncryption:2,height:l.height,width:l.width,jpg:u,networkType:6,osType:7,requestId:h,sdkVersion:"4.23.4",sequence:this.sequence,sid:a,timestamp:k0(d),uid:c,vid:s,service:this._inspectMode,callbackData:this.extraInfo,ossFilePrefix:this.ossFilePrefix};var g;this.extraInfo===void 0&&delete p.callbackData,this.ossFilePrefix===void 0&&delete p.ossFilePrefix;const m=m4(p);if(m.byteLength{var o;if(!G(o=["supervise","moderation"]).call(o,r))throw new P(v.INVALID_PARAMS,"".concat(r," is not a valid inspect type."))}),i.inspectType=n}if(i&&i.extraInfo&&i.extraInfo.length>1024)throw new P(v.INVALID_PARAMS,"inspectConfig.extraInfo length cannot exceed 1024 bytes")}(e),new I4(e)}};var bN=Pt(sn.Object.getOwnPropertySymbols),b4=Nt,w4=Hh.indexOf,O4=kd,Lf=Ka([].indexOf),wN=!!Lf&&1/Lf([1],1,-0)<0;b4({target:"Array",proto:!0,forced:wN||!O4("indexOf")},{indexOf:function(t){var e=arguments.length>1?arguments[1]:void 0;return wN?Lf(this,t,e)||0:w4(this,t,e)}});var N4=Sn("Array","indexOf"),D4=$e,P4=N4,kf=Array.prototype,L4=function(t){var e=t.indexOf;return t===kf||D4(kf,t)&&e===kf.indexOf?P4:e},ON=Pt(L4);function k4(t,e){if(t==null)return{};var i,n,r=function(s,a){if(s==null)return{};var c={};for(var d in s)if({}.hasOwnProperty.call(s,d)){if(ON(a).call(a,d)!==-1)continue;c[d]=s[d]}return c}(t,e);if(bN){var o=bN(t);for(n=0;nf.payloadType.toString(10)),m.attributes.payloads=p,m.attributes.extmaps=u.videoExtensions),m.media.mediaType==="audio"&&(m.media.fmts=g.map(f=>f.payloadType.toString(10)),m.attributes.payloads=g,m.attributes.extmaps=u.audioExtensions,wa(m));this.sessionDesc=l,this.currentMidIndex=l.mediaDescriptions.length-1}toString(){return mo(this.sessionDesc)}hasMid(t){return Array.isArray(t)?t.every(e=>this.hasMid(e)):this.sessionDesc.mediaDescriptions.some(e=>e.attributes.mid===t)}send(t,e,i,n,r){i=i.replace(/ /g,"-");const{ssrcs:o,ssrcGroups:s}=as(e,this.cname,y("SYNC_GROUP")?i:void 0),a=this.findPreloadMediaDesc(o);if(a){if(ne()&&this.firefoxSsrcMidMap.set(o[0].ssrcId,a.attributes.mid),r&&(r.twcc||r.remb)){const c=this.sessionDesc.mediaDescriptions.indexOf(a);return this.sessionDesc.mediaDescriptions[c]=this.mungSendMediaDesc(a,r),{mid:a.attributes.mid,needExchangeSDP:!0}}return{mid:a.attributes.mid,needExchangeSDP:!1}}{const c=this.findAvailableMediaIndex(t,o,n);let d;return c===-1?(d=this.createOrRecycleSendMedia(t,o,s,"sendonly",n,r),this.updateBundleMids()):(d=te(this.sessionDesc.mediaDescriptions[c]),d.attributes.direction="sendonly",d.attributes.ssrcs=o,d.attributes.ssrcGroups=s,this.sessionDesc.mediaDescriptions[c]=this.mungSendMediaDesc(d,r)),ne()&&this.firefoxSsrcMidMap.set(o[0].ssrcId,d.attributes.mid),{needExchangeSDP:!0,mid:d.attributes.mid}}}stopSending(t){const e=this.sessionDesc.mediaDescriptions.filter(i=>i.attributes.mid&&t.indexOf(i.attributes.mid)!==-1);if(e.length!==t.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.stopSending.");e.forEach(i=>{i.attributes.ssrcs=[]}),this.updateBundleMids()}receive(t,e,i){const n=[];return t.forEach(r=>{const o=r._mediaStreamTrack.kind,s=this.findAvailableRecvMediaIndex(o);let a,c=!1;s===-1?(c=!0,a=this.createOrRecycleRecvMedia(r,[],"recvonly",e,i),this.updateBundleMids()):(a=te(this.sessionDesc.mediaDescriptions[s]),a.attributes.direction="recvonly"),n.push({mid:a.attributes.mid,needCreateTransceiver:c})}),n}stopReceiving(t){const e=this.sessionDesc.mediaDescriptions.filter(i=>t.indexOf(i.attributes.mid)!==-1);if(e.length!==t.length)throw new Error("MediaDescriptions' length doesn't match mids's length when calling RemoteSDP.receive.");e.forEach(i=>{i.media.port="0",i.attributes.direction="inactive"}),this.updateBundleMids()}addRemoteCandidate(t){const{foundation:e,protocol:i,address:n,port:r,type:o,relatedAddress:s,relatedPort:a,priority:c}=new RTCIceCandidate(t),d={foundation:e!=null?e:"",componentId:"1",transport:i!=null?i:"",priority:c?c+"":"",connectionAddress:n!=null?n:"",port:r?r+"":"",type:o?o+"":"",relAddr:s!=null?s:"",relPort:a?a+"":"",extension:{}};this.candidates.some(l=>l.priority===d.priority&&l.connectionAddress===d.connectionAddress&&l.port===d.port)||(this._candidates.push(d),this.sessionDesc.mediaDescriptions.forEach(l=>{l.attributes.candidates=this.candidates}))}clearRemoteCandidate(){this._candidates=[],this.sessionDesc.mediaDescriptions[0].attributes.candidates=this._candidates}createOrRecycleRecvMedia(t,e,i,n,r){const o=t._mediaStreamTrack.kind,s=this.rtpCapabilities.recv,a=Kc(o,s,this.localCapabilities.send,o===q.AUDIO?r:n),c=o===q.VIDEO?s.videoExtensions:s.audioExtensions,d="".concat(++this.currentMidIndex);let l={media:{mediaType:o,port:"9",protos:["UDP","TLS","RTP","SAVPF"],fmts:a.map(h=>h.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:e,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,t);const u=this.findFirstClosedMedia(o);if(u){const h=this.sessionDesc.mediaDescriptions.indexOf(u);this.sessionDesc.mediaDescriptions[h]=l}else this.sessionDesc.mediaDescriptions.push(l);return l}muteRemote(t){const e=this.sessionDesc.mediaDescriptions.filter(i=>G(t).call(t,i.attributes.mid||""));if(e.length!==t.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");e.forEach(i=>{i.attributes.direction="inactive"})}unmuteRemote(t){const e=this.sessionDesc.mediaDescriptions.filter(i=>G(t).call(t,i.attributes.mid||""));if(e.length!==t.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");e.forEach(i=>{i.attributes.direction="recvonly"})}findAvailableMediaIndex(t,e,i){return this.sessionDesc.mediaDescriptions.findIndex(n=>{const r=n.media.mediaType===t&&n.media.port!=="0"&&(n.attributes.direction==="sendonly"||n.attributes.direction==="sendrecv")&&n.attributes.ssrcs.length===0;if(ne()){if(r){const o=this.firefoxSsrcMidMap.get(e[0].ssrcId);return!(o||n.attributes.mid!=="0"&&n.attributes.mid!=="1")||!(!o||o!==n.attributes.mid)}return!1}return r&&n.attributes.mid===i})}findAvailableRecvMediaIndex(t){return this.sessionDesc.mediaDescriptions.findIndex(e=>{const i=e.media.mediaType===t&&e.media.port!=="0"&&(e.attributes.direction==="recvonly"||e.attributes.direction==="sendrecv");return e.attributes.mid!=="0"&&e.attributes.mid!=="1"&&i})}predictReceivingMids(t){const e=[];for(let i=0;i{e.attributes.iceUfrag=t.iceUfrag,e.attributes.icePwd=t.icePwd})}createOrRecycleSendMedia(t,e,i,n,r,o){const s=this.rtpCapabilities.send,a=t===q.VIDEO?s.videoCodecs:s.audioCodecs,c=t===q.VIDEO?s.videoExtensions:s.audioExtensions;ne()&&(r="".concat(++this.currentMidIndex));let d={media:{mediaType:t,port:"9",protos:["UDP","TLS","RTP","SAVPF"],fmts:a.map(u=>u.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:e,ssrcGroups:i,rtcpFeedbackWildcards:[],payloads:a,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:n,rtcpMux:!0,rtcpRsize:!0,mid:r}};d=this.mungSendMediaDesc(d,o);const l=this.findFirstClosedMedia(t);if(l){const u=this.sessionDesc.mediaDescriptions.indexOf(l);this.sessionDesc.mediaDescriptions[u]=d}else this.sessionDesc.mediaDescriptions.push(d);return d}mungRecvMediaDsec(t,e,i){const n=te(t);return Pm(n),ba(n,e),Lm(n,e),Rw(n),ju(n,i,this.localCapabilities.send),n}mungSendMediaDesc(t,e){const i=te(t);return ju(i,e,this.localCapabilities.recv),wa(i),i}updateRecvMedia(t,e){const i=this.sessionDesc.mediaDescriptions.findIndex(n=>n.attributes.mid===t);if(i!==-1){const n=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[i],e);this.sessionDesc.mediaDescriptions[i]=n}}updateBundleMids(){this.sessionDesc.attributes.groups[0].identificationTag=this.sessionDesc.mediaDescriptions.filter(t=>t.media.port!=="0").map(t=>t.attributes.mid)}findPreloadMediaDesc(t){return this.sessionDesc.mediaDescriptions.find(e=>{var i;return((i=e.attributes)===null||i===void 0||(i=i.ssrcs[0])===null||i===void 0?void 0:i.ssrcId)===t[0].ssrcId})}findFirstClosedMedia(t){return this.sessionDesc.mediaDescriptions.find(e=>ne()?e.media.port==="0"&&e.media.mediaType===t:e.media.port==="0")}};const M4=["sdp"];var qt;function DN(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable})),i.push.apply(i,n)}return i}function Po(t){for(var e=1;e2?arguments[2]:void 0,arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},"sendonly"),h={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},p={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},g={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]};if(kn(u,l,"videoExtensions",h,p,g),kn(u,l,"videoCodecs",h,p,g),kn(u,l,"audioExtensions",h,p,g),kn(u,l,"audioCodecs",h,p,g),y("RAISE_H264_BASELINE_PRIORITY")){const m=g.videoCodecs.findIndex(f=>f.rtpMap&&f.rtpMap.encodingName.toLocaleLowerCase()==="h264"&&f.fmtp&&f.fmtp.parameters["profile-level-id"]==="42001f");if(m!==-1){const f=g.videoCodecs.findIndex(T=>T.rtpMap&&T.rtpMap.encodingName.toLocaleLowerCase()==="h264");if(f!(T.rtpMap&&T.rtpMap.encodingName.toLocaleLowerCase()==="h264"&&T.fmtp&&T.fmtp.parameters["profile-level-id"]!=="42001f")))}}return{send:h,recv:p,sendrecv:g}}({},{},n);this.remoteSDP=new NN({remoteIceParameters:r.iceParameters,remoteDtlsParameters:r.dtlsParameters,candidates:[],remoteRTPCapabilities:o,localCapabilities:this.localCapabilities,direction:this.direction,setup:"actpass",videoCodec:this.store.codec,audioCodec:this.store.audioCodec}),yield this.setRemoteDescription({type:"offer",sdp:this.remoteSDP.toString()}),this.isReady=!0;const s=yield this.peerConnection.createAnswer();if(!s.sdp)throw new Error("Cannot get answer sdp when trying to establish PeerConnection.");const a=Ro(s.sdp);yield this.peerConnection.setLocalDescription(s);const c=yield yw({},{},s.sdp);this.localCapabilities=Gu(c);const d=this.peerConnection.getTransceivers()[0];return d!=null&&d.receiver&&d.receiver.transport&&this.tryBindTransportEvents(d.receiver.transport),Po(Po({},a),{},{sdp:s.sdp})}{this.peerConnection.addTransceiver("video",{direction:"sendonly"}),this.peerConnection.addTransceiver("audio",{direction:"sendonly"});const n=yield this.peerConnection.createOffer();if(!n.sdp)throw new Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");const r=Ro(n.sdp);return this.initialOffer=n,Po(Po({},r),{},{sdp:n.sdp})}}catch(i){throw new k(v.GET_LOCAL_CONNECTION_PARAMS_FAILED,i.toString())}})}connect(e){return C(this,null,function*(){try{if(!this.initialOffer)throw new Error("Cannot establish P2PConnection without initial offer.");yield this.peerConnection.setLocalDescription(this.initialOffer);const{sdp:i,iceParameters:n,dtlsParameters:r}=e,o=yield yw({},{},i);this.remoteSDP=new NN({remoteIceParameters:n,remoteDtlsParameters:r,candidates:[],remoteRTPCapabilities:o,localCapabilities:this.localCapabilities,direction:this.direction,setup:"active",videoCodec:this.store.codec,audioCodec:this.store.audioCodec}),yield this.setRemoteDescription({type:"answer",sdp:this.remoteSDP.toString()});const s=this.peerConnection.getTransceivers()[0];s!=null&&s.sender&&s.sender.transport&&this.tryBindTransportEvents(s.sender.transport)}catch(i){throw new k(v.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(i.toString()))}})}addRemoteCandidate(e){return C(this,null,function*(){try{e&&this.pendingCandidates.push(e),this.peerConnection.remoteDescription&&this.isReady&&(this.pendingCandidates.forEach(i=>{this.peerConnection.addIceCandidate(i)}),this.pendingCandidates=[])}catch(i){throw new k(v.ADD_CANDIDATE_FAILED,"P2PConnection.addRemoteCandidate failed; ".concat(i.toString()))}})}send(e,i,n){var r=this;return cn(function*(){const o=yield Rt(r.mutex.lock("From P2PConnection.send"));try{if(!r.remoteSDP)throw new Error("Cannot call P2PConnection.send before remote SDP created");const s=[],a=r.remoteSDP.receive(e,i,n);e.forEach((f,T)=>{if(a[T].needCreateTransceiver){const R=r.peerConnection.addTransceiver(f._mediaStreamTrack,{direction:"sendonly"});s.push(R),f._updateRtpTransceiver(R)}else{const R=r.peerConnection.getTransceivers().find(A=>A.mid===a[T].mid);if(!R)throw new Error("cannot find transceiver when sendPeerconnection send, mid is ".concat(a[T].mid));s.push(R),f._updateRtpTransceiver(R)}}),ne()&&y("SIMULCAST")===!0&&(yield Rt(r.applySimulcastForFirefox(s,e)));const c=a.map(f=>f.mid),d=yield Rt(r.peerConnection.createOffer()),l=r.mungSendOfferSDP(d.sdp,e,c),u=Ni(l),h=c.map(f=>{const T=u.mediaDescriptions.find(R=>R.attributes.mid===f);if(!T)throw new Error("Cannot extract ssrc from mediaDescription.");return gw(T,y("USE_PUB_RTX"))}),p=s.map((f,T)=>{const R=c[T];return{localSSRC:h[T],id:R}});yield Rt(r.peerConnection.setLocalDescription({type:"offer",sdp:l}));try{yield p}catch(f){const T=r.remoteSDP.toString();throw yield Rt(r.peerConnection.setLocalDescription({type:"offer",sdp:l})),yield Rt(r.peerConnection.setRemoteDescription({type:"answer",sdp:T})),yield Rt(r.stopSending(c,!0)),f}yield Rt(r.applySimulcastEncodings(s,e)),yield Rt(r.applySendEncodings(s,e));const g=r.remoteSDP.toString(),m=r.logSDPExchange(l,"offer","local","send");return m==null||m(g),yield Rt(r.setRemoteDescription({type:"answer",sdp:g})),s.map((f,T)=>{const R=c[T];return{localSSRC:h[T],id:R}})}catch(s){throw s instanceof k?s:new k(v.EXCHANGE_SDP_FAILED,"P2PConnection.send failed; ".concat(s.toString()))}finally{o()}})()}stopSending(e,i){return C(this,null,function*(){const n=i?void 0:yield this.mutex.lock("From P2PConnection.stopSending");try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopSending before remote SDP created");const r=this.peerConnection.getTransceivers().filter(c=>e.indexOf(c.mid)!==-1);if(r.length!==e.length)throw new Error("Transceivers' length (".concat(r.length,") doesn't match mids' length (").concat(e.length,") when trying to call P2PConnection.stopSending."));r.map(c=>{var d;c.direction="inactive",(d=c.stop)===null||d===void 0||d.call(c)});const o=yield this.peerConnection.createOffer(),s=this.logSDPExchange(o.sdp||"","offer","local","stopSending");yield this.peerConnection.setLocalDescription(o),this.remoteSDP.stopReceiving(e);const a=this.remoteSDP.toString();s==null||s(a),yield this.setRemoteDescription({type:"answer",sdp:a})}catch(r){throw new k(v.EXCHANGE_SDP_FAILED,"P2PConnection.stopSending failed; ".concat(r.toString()))}finally{n&&n()}})}receive(e,i,n,r){return C(this,null,function*(){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.receive ".concat(e," before remoteSDP created."));const{mid:o,needExchangeSDP:s}=this.remoteSDP.send(e,i,n,r);if(s){const c=this.remoteSDP.toString(),d=this.logSDPExchange(c,"offer","remote","receive");yield this.setRemoteDescription({type:"offer",sdp:c});const l=yield this.peerConnection.createAnswer(),u=this.mungReceiveAnswerSDP(l.sdp,o,e);d==null||d(u||""),yield this.peerConnection.setLocalDescription({type:"answer",sdp:u}),_.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," by exchanging SDP."))}else _.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," no need to exchange SDP."));const a=this.peerConnection.getTransceivers().find(c=>c.mid===o);if(!a||a.mid===null)throw new Error("Cannot get transceiver after setLocalDescription.");return{track:a.receiver.track,mid:a.mid,transceiver:a}}catch(o){throw new k(v.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(o.toString()))}})}mockReceive(e,i,n,r){return C(this,null,function*(){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.receive ".concat(e," before remoteSDP created."));const{mid:o,needExchangeSDP:s}=this.remoteSDP.send(e,i,n,r);if(s){const a=this.remoteSDP.toString(),c=this.logSDPExchange(a,"offer","remote","receive");yield this.setRemoteDescription({type:"offer",sdp:a});const d=yield this.peerConnection.createAnswer(),l=this.mungReceiveAnswerSDP(d.sdp,o,e);c==null||c(l||""),yield this.peerConnection.setLocalDescription({type:"answer",sdp:l}),_.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," by exchanging SDP."))}else _.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," no need to exchange SDP."))}catch(o){throw new k(v.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(o.toString()))}})}stopReceiving(e){return C(this,null,function*(){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopReceiving before remote SDP created.");this.remoteSDP.stopSending(e);const i=this.remoteSDP.toString(),n=this.logSDPExchange(i,"offer","remote","stopReceiving");yield this.setRemoteDescription({type:"offer",sdp:i});const r=yield this.peerConnection.createAnswer();n==null||n(r.sdp||""),yield this.peerConnection.setLocalDescription(r)}catch(i){throw new k(v.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(i.toString()))}})}restartICE(e){return C(this,null,function*(){try{if(this.store.p2pTransport===$o.Auto&&(this.store.p2pTransport=$o.SdRtn,Ct().supportPCSetConfiguration&&this.peerConnection.setConfiguration(Wa.resolvePCConfiguration(this.spec,this.store.p2pTransport))),this.restartCnt>3&&(this.restartCnt=0,Ct().supportPCSetConfiguration&&this.peerConnection.setConfiguration(Wa.resolvePCConfiguration(this.spec,this.store.p2pTransport,++this.curTurnServerIndex))),!e){this.restartCnt++,this.isReady=!1;const i=yield this.peerConnection.createOffer({iceRestart:!0});if(!i.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const{iceParameters:n}=Ro(i.sdp);return this.store.descriptionStart(),this.direction===pi.SEND_ONLY&&(yield this.peerConnection.setLocalDescription(i)),n}if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopReceiving before remote SDP created.");if(this.remoteSDP.restartICE(e),this.store.descriptionStart(),this.direction===pi.RECEIVE_ONLY){this.restartCnt++,yield this.setRemoteDescription({type:"offer",sdp:this.remoteSDP.toString()});const i=yield this.peerConnection.createAnswer();if(!i.sdp)throw new Error("Cannot get answer sdp when trying to iceRestart.");const{iceParameters:n}=Ro(i.sdp);return yield this.peerConnection.setLocalDescription(i),n}yield this.setRemoteDescription({type:"answer",sdp:this.remoteSDP.toString()}),this.isReady=!0}catch(i){throw new k(v.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(i.toString()))}})}close(){var e;this.peerConnection.close(),this.peerConnection.onicecandidate=null,(e=this.onConnectionStateChange)===null||e===void 0||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)}updateEncoderConfig(e,i){return C(this,null,function*(){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.updateEncoderConfig before remote SDP created.");const n=yield this.peerConnection.createOffer(),r=this.mungSendOfferSDP(n.sdp,[i],[e]);this.remoteSDP.updateRecvMedia(e,i);const o=this.remoteSDP.toString(),s=this.logSDPExchange(r,"offer","local","updateEncoderConfig");yield this.peerConnection.setLocalDescription({type:"offer",sdp:r}),s==null||s(o),yield this.peerConnection.setRemoteDescription({type:"answer",sdp:o})}catch(n){throw new k(v.EXCHANGE_SDP_FAILED,n.toString())}})}updateSendParameters(e,i){return C(this,null,function*(){const n=this.peerConnection.getTransceivers().filter(r=>r.mid===e);n.length===1&&(this.isVP8Simulcast(i)?ne()||(yield this.applySimulcastEncodings(n,[i])):yield this.applySendEncodings(n,[i]))})}setStatsRemoteVideoIsReady(e,i){this.statsFilter.setVideoIsReady2(e,i)}replaceTrack(e,i){return C(this,null,function*(){const n=this.peerConnection.getTransceivers().find(r=>r.mid===i);n&&(yield n.sender.replaceTrack(e._mediaStreamTrack))})}getSelectedCandidatePair(){return C(this,null,function*(){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 i=e[0].transport.iceTransport,{local:n,remote:r}=i.getSelectedCandidatePair();return{local:Po(Po({},mr),{},{candidateType:n.type,protocol:n.protocol,address:n.address,port:n.port}),remote:Po(Po({},mr),{},{candidateType:r.type,protocol:r.protocol,address:r.address,port:r.port})}}return this.statsFilter.getSelectedCandidatePair()})}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var e,i;G(e=["connected","completed"]).call(e,this.peerConnection.iceConnectionState)&&(this.isReady=!1),(i=this.onICEConnectionStateChange)===null||i===void 0||i.call(this,this.peerConnection.iceConnectionState)},this.peerConnection.onconnectionstatechange=()=>{var e;this.peerConnection.connectionState==="connected"&&(this.restartCnt=0),(e=this.onConnectionStateChange)===null||e===void 0||e.call(this,this.peerConnection.connectionState)},this.startICECandidate()}startICECandidate(){this.peerConnection.onicecandidate||(this.localCandidateCount=0,this.peerConnection.onicecandidate=e=>{if(e.candidate){var i;e.candidate.candidate&&((i=this.onLocalCandidate)===null||i===void 0||i.call(this,e.candidate.toJSON())),this.localCandidateCount+=1}else _.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(e,i){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0;const r={iceServers:[]};var o;return e.iceServers?r.iceServers=e.iceServers:e.turnServer&&e.turnServer.mode!=="off"&&(Nc(e.turnServer.servers)?r.iceServers=e.turnServer.servers:(r.iceServers&&r.iceServers.push(...Wa.turnServerConfigToIceServers(e.turnServer.servers,i,n)),y("USE_TURN_SERVER_OF_GATEWAY")&&r.iceServers&&e.turnServer.serversFromGateway&&r.iceServers.push(...Wa.turnServerConfigToIceServers(e.turnServer.serversFromGateway,i,n)),G(o=[$o.Relay,$o.SdRtn]).call(o,i)&&(r.iceTransportPolicy="relay"),y("FORCE_TURN_TCP")?r.iceTransportPolicy="relay":e.turnServer.servers.concat(e.turnServer.serversFromGateway||[]).forEach(s=>{s.forceturn&&(r.iceTransportPolicy="relay")}))),y("ENABLE_ENCODED_TRANSFORM")&&Ct().supportWebRTCEncodedTransform&&(r.encodedInsertableStreams=!0),_.debug("P2PConnection p2pTransport is ".concat(i)),r}static turnServerConfigToIceServers(e,i){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0;const r=[],o=e.filter(a=>a.tcpport);_.debug("P2PConnection turnServers is ".concat(o,", current index is ").concat(n));const s=o.length>n?o[n]:o[0];switch(i){case $o.SdRtn:const a=e.filter(d=>{var l;return G(l=d.username).call(l,"glb:")&&d.turnServerURL==d.turnServerURL}),c=a.length>n?a[n]:a[0];c&&(r.push({username:c.username,credential:c.password,credentialType:"password",urls:"turn:".concat(So(c.turnServerURL),":").concat(c.tcpport,"?transport=udp")}),r.push({username:c.username,credential:c.password,credentialType:"password",urls:"turns:".concat(So(c.turnServerURL),":").concat(c.tcpport,"?transport=tcp")}));break;case $o.Relay:s&&(r.push({username:s.username,credential:s.password,credentialType:"password",urls:"turn:".concat(s.turnServerURL,":").concat(s.tcpport,"?transport=udp")}),r.push({username:s.username,credential:s.password,credentialType:"password",urls:"turns:".concat(So(s.turnServerURL),":").concat(s.tcpport,"?transport=tcp")}));break;default:s&&(r.push({username:s.username,credential:s.password,credentialType:"password",urls:"turn:".concat(s.turnServerURL,":").concat(s.tcpport,"?transport=udp")}),r.push({username:s.username,credential:s.password,credentialType:"password",urls:"turns:".concat(So(s.turnServerURL),":").concat(s.tcpport,"?transport=tcp")}),r.push({username:s.username,credential:s.password,credentialType:"password",urls:"stun:".concat(s.turnServerURL,":").concat(s.tcpport)}))}return r}tryBindTransportEvents(e){if(e){this.transport=e,e.onstatechange=()=>{var n;e!=null&&e.state&&((n=this.onDTLSTransportStateChange)===null||n===void 0||n.call(this,e.state))},e.onerror=n=>{var r;(r=this.onDTLSTransportError)===null||r===void 0||r.call(this,"error"in n?n.error:n)};const i=e.iceTransport;i&&(i.onstatechange=()=>{const n=e==null?void 0:e.iceTransport.state;var r;n&&((r=this.onICETransportStateChange)===null||r===void 0||r.call(this,n))},i.getSelectedCandidatePair&&(i.onselectedcandidatepairchange=()=>{if(i.getSelectedCandidatePair()){const{local:n,remote:r}=i.getSelectedCandidatePair();_.info("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] selectedcandidatepairchange: local ").concat(JSON.stringify({candidateType:n.type,protocol:n.protocol}),", remote ").concat(JSON.stringify({candidateType:r.type,protocol:r.protocol,address:r.address,port:r.port})," )"))}}))}}tryUnbindTransportEvents(){this.transport&&(this.transport.onstatechange=null,this.transport.onerror=null,this.transport.iceTransport&&(this.transport.iceTransport.onstatechange=null))}updateRtpSenderEncodings(e,i){return C(this,null,function*(){var n;if(i||(i=this.peerConnection.getSenders().find(l=>l.track===e._mediaStreamTrack)),!i)return _.warn("[".concat(e.getTrackId(),"] no rtpSender found}"));if(this.isVP8Simulcast(e))return _.warn("[updateRtpSenderEncodings] Track is VP8 simulcast, please apply simulcast encodings");if(!Ct().supportSetRtpSenderParameters)return _.warn("[updateRtpSenderEncodings] Browser not support set rtp-sender parameters");const r={},o={};switch(e._optimizationMode){case"motion":r.degradationPreference="maintain-framerate";break;case"detail":r.degradationPreference="maintain-resolution";break;default:r.degradationPreference="balanced"}if(e._encoderConfig){var s;const{bitrateMax:l,frameRate:u,scaleResolutionDownBy:h}=e._encoderConfig;l&&(o.maxBitrate=1e3*l),G(s=e._hints).call(s,Vt.LOW_STREAM)&&(u&&(o.maxFramerate=Bi(u)),h&&h>=1&&(o.scaleResolutionDownBy=h))}if(y("DSCP_TYPE")&&Vr()){var a;const l=y("DSCP_TYPE");G(a=["very-low","low","medium","high"]).call(a,l)&&(o.networkPriority=l)}const c=i.getParameters(),d=(n=c.encodings)===null||n===void 0?void 0:n[0];ne()&&!d&&(r.encodings=[o]),d&&Object.assign(d,o),Object.assign(c,r),_.debug("[".concat(e.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(c.encodings))),yield i.setParameters(c)})}applySendEncodings(e,i){return C(this,null,function*(){try{if(!Ct().supportSetRtpSenderParameters||e.length!==i.length)return;for(let n=0;n{const a=n[s],c=r.mediaDescriptions.find(d=>d.attributes.mid===a);c&&(ba(c,o),vw(c,o,this.store.codec))}),mo(r)}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=e=>{var i;(i=this.onFirstAudioReceived)===null||i===void 0||i.call(this,e)},this.statsFilter.onFirstVideoReceived=e=>{var i;(i=this.onFirstVideoReceived)===null||i===void 0||i.call(this,e)},this.statsFilter.onFirstAudioDecoded=e=>{var i;(i=this.onFirstAudioDecoded)===null||i===void 0||i.call(this,e)},this.statsFilter.onFirstVideoDecoded=(e,i,n)=>{var r;(r=this.onFirstVideoDecoded)===null||r===void 0||r.call(this,e,i,n)},this.statsFilter.onSelectedLocalCandidateChanged=(e,i)=>{var n;(n=this.onSelectedLocalCandidateChanged)===null||n===void 0||n.call(this,e,i)},this.statsFilter.onSelectedRemoteCandidateChanged=(e,i)=>{var n;(n=this.onSelectedRemoteCandidateChanged)===null||n===void 0||n.call(this,e,i)},this.statsFilter.onFirstVideoDecodedTimeout=e=>{var i;(i=this.onFirstVideoDecodedTimeout)===null||i===void 0||i.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}applySimulcastForFirefox(e,i){return C(this,null,function*(){if(e.length===i.length)for(let c=0;c