quickvo-sdk-js 1.4.3 → 1.4.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +19407 -19595
- package/dist/index.umd.cjs +1 -1
- package/package.json +1 -1
package/dist/index.umd.cjs
CHANGED
|
@@ -6,4 +6,4 @@ between two successive fields at the output of the decoding process (see the not
|
|
|
6
6
|
*
|
|
7
7
|
* @author Feross Aboukhadijeh <https://feross.org>
|
|
8
8
|
* @license MIT
|
|
9
|
-
*/var hasRequiredBuffer;function requireBuffer(){return hasRequiredBuffer||(hasRequiredBuffer=1,function(A){const B=requireBase64Js(),D=requireIeee754(),M=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;A.Buffer=u,A.SlowBuffer=le,A.INSPECT_MAX_BYTES=50;const O=2147483647;A.kMaxLength=O,u.TYPED_ARRAY_SUPPORT=C(),!u.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function C(){try{const Q=new Uint8Array(1),z={foo:function(){return 42}};return Object.setPrototypeOf(z,Uint8Array.prototype),Object.setPrototypeOf(Q,z),Q.foo()===42}catch{return!1}}Object.defineProperty(u.prototype,"parent",{enumerable:!0,get:function(){if(u.isBuffer(this))return this.buffer}}),Object.defineProperty(u.prototype,"offset",{enumerable:!0,get:function(){if(u.isBuffer(this))return this.byteOffset}});function i(Q){if(Q>O)throw new RangeError('The value "'+Q+'" is invalid for option "size"');const z=new Uint8Array(Q);return Object.setPrototypeOf(z,u.prototype),z}function u(Q,z,Z){if(typeof Q=="number"){if(typeof z=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return j(Q)}return $(Q,z,Z)}u.poolSize=8192;function $(Q,z,Z){if(typeof Q=="string")return J(Q,z);if(ArrayBuffer.isView(Q))return Y(Q);if(Q==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof Q);if(ze(Q,ArrayBuffer)||Q&&ze(Q.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(ze(Q,SharedArrayBuffer)||Q&&ze(Q.buffer,SharedArrayBuffer)))return re(Q,z,Z);if(typeof Q=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');const X=Q.valueOf&&Q.valueOf();if(X!=null&&X!==Q)return u.from(X,z,Z);const ae=oe(Q);if(ae)return ae;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof Q[Symbol.toPrimitive]=="function")return u.from(Q[Symbol.toPrimitive]("string"),z,Z);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof Q)}u.from=function(Q,z,Z){return $(Q,z,Z)},Object.setPrototypeOf(u.prototype,Uint8Array.prototype),Object.setPrototypeOf(u,Uint8Array);function N(Q){if(typeof Q!="number")throw new TypeError('"size" argument must be of type number');if(Q<0)throw new RangeError('The value "'+Q+'" is invalid for option "size"')}function F(Q,z,Z){return N(Q),Q<=0?i(Q):z!==void 0?typeof Z=="string"?i(Q).fill(z,Z):i(Q).fill(z):i(Q)}u.alloc=function(Q,z,Z){return F(Q,z,Z)};function j(Q){return N(Q),i(Q<0?0:te(Q)|0)}u.allocUnsafe=function(Q){return j(Q)},u.allocUnsafeSlow=function(Q){return j(Q)};function J(Q,z){if((typeof z!="string"||z==="")&&(z="utf8"),!u.isEncoding(z))throw new TypeError("Unknown encoding: "+z);const Z=pe(Q,z)|0;let X=i(Z);const ae=X.write(Q,z);return ae!==Z&&(X=X.slice(0,ae)),X}function K(Q){const z=Q.length<0?0:te(Q.length)|0,Z=i(z);for(let X=0;X<z;X+=1)Z[X]=Q[X]&255;return Z}function Y(Q){if(ze(Q,Uint8Array)){const z=new Uint8Array(Q);return re(z.buffer,z.byteOffset,z.byteLength)}return K(Q)}function re(Q,z,Z){if(z<0||Q.byteLength<z)throw new RangeError('"offset" is outside of buffer bounds');if(Q.byteLength<z+(Z||0))throw new RangeError('"length" is outside of buffer bounds');let X;return z===void 0&&Z===void 0?X=new Uint8Array(Q):Z===void 0?X=new Uint8Array(Q,z):X=new Uint8Array(Q,z,Z),Object.setPrototypeOf(X,u.prototype),X}function oe(Q){if(u.isBuffer(Q)){const z=te(Q.length)|0,Z=i(z);return Z.length===0||Q.copy(Z,0,0,z),Z}if(Q.length!==void 0)return typeof Q.length!="number"||Xe(Q.length)?i(0):K(Q);if(Q.type==="Buffer"&&Array.isArray(Q.data))return K(Q.data)}function te(Q){if(Q>=O)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+O.toString(16)+" bytes");return Q|0}function le(Q){return+Q!=Q&&(Q=0),u.alloc(+Q)}u.isBuffer=function(z){return z!=null&&z._isBuffer===!0&&z!==u.prototype},u.compare=function(z,Z){if(ze(z,Uint8Array)&&(z=u.from(z,z.offset,z.byteLength)),ze(Z,Uint8Array)&&(Z=u.from(Z,Z.offset,Z.byteLength)),!u.isBuffer(z)||!u.isBuffer(Z))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(z===Z)return 0;let X=z.length,ae=Z.length;for(let de=0,me=Math.min(X,ae);de<me;++de)if(z[de]!==Z[de]){X=z[de],ae=Z[de];break}return X<ae?-1:ae<X?1:0},u.isEncoding=function(z){switch(String(z).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},u.concat=function(z,Z){if(!Array.isArray(z))throw new TypeError('"list" argument must be an Array of Buffers');if(z.length===0)return u.alloc(0);let X;if(Z===void 0)for(Z=0,X=0;X<z.length;++X)Z+=z[X].length;const ae=u.allocUnsafe(Z);let de=0;for(X=0;X<z.length;++X){let me=z[X];if(ze(me,Uint8Array))de+me.length>ae.length?(u.isBuffer(me)||(me=u.from(me)),me.copy(ae,de)):Uint8Array.prototype.set.call(ae,me,de);else if(u.isBuffer(me))me.copy(ae,de);else throw new TypeError('"list" argument must be an Array of Buffers');de+=me.length}return ae};function pe(Q,z){if(u.isBuffer(Q))return Q.length;if(ArrayBuffer.isView(Q)||ze(Q,ArrayBuffer))return Q.byteLength;if(typeof Q!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof Q);const Z=Q.length,X=arguments.length>2&&arguments[2]===!0;if(!X&&Z===0)return 0;let ae=!1;for(;;)switch(z){case"ascii":case"latin1":case"binary":return Z;case"utf8":case"utf-8":return Je(Q).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Z*2;case"hex":return Z>>>1;case"base64":return Ke(Q).length;default:if(ae)return X?-1:Je(Q).length;z=(""+z).toLowerCase(),ae=!0}}u.byteLength=pe;function ee(Q,z,Z){let X=!1;if((z===void 0||z<0)&&(z=0),z>this.length||((Z===void 0||Z>this.length)&&(Z=this.length),Z<=0)||(Z>>>=0,z>>>=0,Z<=z))return"";for(Q||(Q="utf8");;)switch(Q){case"hex":return Le(this,z,Z);case"utf8":case"utf-8":return be(this,z,Z);case"ascii":return De(this,z,Z);case"latin1":case"binary":return Be(this,z,Z);case"base64":return ve(this,z,Z);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Ve(this,z,Z);default:if(X)throw new TypeError("Unknown encoding: "+Q);Q=(Q+"").toLowerCase(),X=!0}}u.prototype._isBuffer=!0;function ne(Q,z,Z){const X=Q[z];Q[z]=Q[Z],Q[Z]=X}u.prototype.swap16=function(){const z=this.length;if(z%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let Z=0;Z<z;Z+=2)ne(this,Z,Z+1);return this},u.prototype.swap32=function(){const z=this.length;if(z%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let Z=0;Z<z;Z+=4)ne(this,Z,Z+3),ne(this,Z+1,Z+2);return this},u.prototype.swap64=function(){const z=this.length;if(z%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let Z=0;Z<z;Z+=8)ne(this,Z,Z+7),ne(this,Z+1,Z+6),ne(this,Z+2,Z+5),ne(this,Z+3,Z+4);return this},u.prototype.toString=function(){const z=this.length;return z===0?"":arguments.length===0?be(this,0,z):ee.apply(this,arguments)},u.prototype.toLocaleString=u.prototype.toString,u.prototype.equals=function(z){if(!u.isBuffer(z))throw new TypeError("Argument must be a Buffer");return this===z?!0:u.compare(this,z)===0},u.prototype.inspect=function(){let z="";const Z=A.INSPECT_MAX_BYTES;return z=this.toString("hex",0,Z).replace(/(.{2})/g,"$1 ").trim(),this.length>Z&&(z+=" ... "),"<Buffer "+z+">"},M&&(u.prototype[M]=u.prototype.inspect),u.prototype.compare=function(z,Z,X,ae,de){if(ze(z,Uint8Array)&&(z=u.from(z,z.offset,z.byteLength)),!u.isBuffer(z))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof z);if(Z===void 0&&(Z=0),X===void 0&&(X=z?z.length:0),ae===void 0&&(ae=0),de===void 0&&(de=this.length),Z<0||X>z.length||ae<0||de>this.length)throw new RangeError("out of range index");if(ae>=de&&Z>=X)return 0;if(ae>=de)return-1;if(Z>=X)return 1;if(Z>>>=0,X>>>=0,ae>>>=0,de>>>=0,this===z)return 0;let me=de-ae,Oe=X-Z;const Ce=Math.min(me,Oe),Re=this.slice(ae,de),Pe=z.slice(Z,X);for(let xe=0;xe<Ce;++xe)if(Re[xe]!==Pe[xe]){me=Re[xe],Oe=Pe[xe];break}return me<Oe?-1:Oe<me?1:0};function ue(Q,z,Z,X,ae){if(Q.length===0)return-1;if(typeof Z=="string"?(X=Z,Z=0):Z>2147483647?Z=2147483647:Z<-2147483648&&(Z=-2147483648),Z=+Z,Xe(Z)&&(Z=ae?0:Q.length-1),Z<0&&(Z=Q.length+Z),Z>=Q.length){if(ae)return-1;Z=Q.length-1}else if(Z<0)if(ae)Z=0;else return-1;if(typeof z=="string"&&(z=u.from(z,X)),u.isBuffer(z))return z.length===0?-1:se(Q,z,Z,X,ae);if(typeof z=="number")return z=z&255,typeof Uint8Array.prototype.indexOf=="function"?ae?Uint8Array.prototype.indexOf.call(Q,z,Z):Uint8Array.prototype.lastIndexOf.call(Q,z,Z):se(Q,[z],Z,X,ae);throw new TypeError("val must be string, number or Buffer")}function se(Q,z,Z,X,ae){let de=1,me=Q.length,Oe=z.length;if(X!==void 0&&(X=String(X).toLowerCase(),X==="ucs2"||X==="ucs-2"||X==="utf16le"||X==="utf-16le")){if(Q.length<2||z.length<2)return-1;de=2,me/=2,Oe/=2,Z/=2}function Ce(Pe,xe){return de===1?Pe[xe]:Pe.readUInt16BE(xe*de)}let Re;if(ae){let Pe=-1;for(Re=Z;Re<me;Re++)if(Ce(Q,Re)===Ce(z,Pe===-1?0:Re-Pe)){if(Pe===-1&&(Pe=Re),Re-Pe+1===Oe)return Pe*de}else Pe!==-1&&(Re-=Re-Pe),Pe=-1}else for(Z+Oe>me&&(Z=me-Oe),Re=Z;Re>=0;Re--){let Pe=!0;for(let xe=0;xe<Oe;xe++)if(Ce(Q,Re+xe)!==Ce(z,xe)){Pe=!1;break}if(Pe)return Re}return-1}u.prototype.includes=function(z,Z,X){return this.indexOf(z,Z,X)!==-1},u.prototype.indexOf=function(z,Z,X){return ue(this,z,Z,X,!0)},u.prototype.lastIndexOf=function(z,Z,X){return ue(this,z,Z,X,!1)};function ce(Q,z,Z,X){Z=Number(Z)||0;const ae=Q.length-Z;X?(X=Number(X),X>ae&&(X=ae)):X=ae;const de=z.length;X>de/2&&(X=de/2);let me;for(me=0;me<X;++me){const Oe=parseInt(z.substr(me*2,2),16);if(Xe(Oe))return me;Q[Z+me]=Oe}return me}function he(Q,z,Z,X){return Qe(Je(z,Q.length-Z),Q,Z,X)}function ie(Q,z,Z,X){return Qe(Ge(z),Q,Z,X)}function fe(Q,z,Z,X){return Qe(Ke(z),Q,Z,X)}function ye(Q,z,Z,X){return Qe(Ye(z,Q.length-Z),Q,Z,X)}u.prototype.write=function(z,Z,X,ae){if(Z===void 0)ae="utf8",X=this.length,Z=0;else if(X===void 0&&typeof Z=="string")ae=Z,X=this.length,Z=0;else if(isFinite(Z))Z=Z>>>0,isFinite(X)?(X=X>>>0,ae===void 0&&(ae="utf8")):(ae=X,X=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");const de=this.length-Z;if((X===void 0||X>de)&&(X=de),z.length>0&&(X<0||Z<0)||Z>this.length)throw new RangeError("Attempt to write outside buffer bounds");ae||(ae="utf8");let me=!1;for(;;)switch(ae){case"hex":return ce(this,z,Z,X);case"utf8":case"utf-8":return he(this,z,Z,X);case"ascii":case"latin1":case"binary":return ie(this,z,Z,X);case"base64":return fe(this,z,Z,X);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ye(this,z,Z,X);default:if(me)throw new TypeError("Unknown encoding: "+ae);ae=(""+ae).toLowerCase(),me=!0}},u.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function ve(Q,z,Z){return z===0&&Z===Q.length?B.fromByteArray(Q):B.fromByteArray(Q.slice(z,Z))}function be(Q,z,Z){Z=Math.min(Q.length,Z);const X=[];let ae=z;for(;ae<Z;){const de=Q[ae];let me=null,Oe=de>239?4:de>223?3:de>191?2:1;if(ae+Oe<=Z){let Ce,Re,Pe,xe;switch(Oe){case 1:de<128&&(me=de);break;case 2:Ce=Q[ae+1],(Ce&192)===128&&(xe=(de&31)<<6|Ce&63,xe>127&&(me=xe));break;case 3:Ce=Q[ae+1],Re=Q[ae+2],(Ce&192)===128&&(Re&192)===128&&(xe=(de&15)<<12|(Ce&63)<<6|Re&63,xe>2047&&(xe<55296||xe>57343)&&(me=xe));break;case 4:Ce=Q[ae+1],Re=Q[ae+2],Pe=Q[ae+3],(Ce&192)===128&&(Re&192)===128&&(Pe&192)===128&&(xe=(de&15)<<18|(Ce&63)<<12|(Re&63)<<6|Pe&63,xe>65535&&xe<1114112&&(me=xe))}}me===null?(me=65533,Oe=1):me>65535&&(me-=65536,X.push(me>>>10&1023|55296),me=56320|me&1023),X.push(me),ae+=Oe}return Ee(X)}const ge=4096;function Ee(Q){const z=Q.length;if(z<=ge)return String.fromCharCode.apply(String,Q);let Z="",X=0;for(;X<z;)Z+=String.fromCharCode.apply(String,Q.slice(X,X+=ge));return Z}function De(Q,z,Z){let X="";Z=Math.min(Q.length,Z);for(let ae=z;ae<Z;++ae)X+=String.fromCharCode(Q[ae]&127);return X}function Be(Q,z,Z){let X="";Z=Math.min(Q.length,Z);for(let ae=z;ae<Z;++ae)X+=String.fromCharCode(Q[ae]);return X}function Le(Q,z,Z){const X=Q.length;(!z||z<0)&&(z=0),(!Z||Z<0||Z>X)&&(Z=X);let ae="";for(let de=z;de<Z;++de)ae+=et[Q[de]];return ae}function Ve(Q,z,Z){const X=Q.slice(z,Z);let ae="";for(let de=0;de<X.length-1;de+=2)ae+=String.fromCharCode(X[de]+X[de+1]*256);return ae}u.prototype.slice=function(z,Z){const X=this.length;z=~~z,Z=Z===void 0?X:~~Z,z<0?(z+=X,z<0&&(z=0)):z>X&&(z=X),Z<0?(Z+=X,Z<0&&(Z=0)):Z>X&&(Z=X),Z<z&&(Z=z);const ae=this.subarray(z,Z);return Object.setPrototypeOf(ae,u.prototype),ae};function Te(Q,z,Z){if(Q%1!==0||Q<0)throw new RangeError("offset is not uint");if(Q+z>Z)throw new RangeError("Trying to access beyond buffer length")}u.prototype.readUintLE=u.prototype.readUIntLE=function(z,Z,X){z=z>>>0,Z=Z>>>0,X||Te(z,Z,this.length);let ae=this[z],de=1,me=0;for(;++me<Z&&(de*=256);)ae+=this[z+me]*de;return ae},u.prototype.readUintBE=u.prototype.readUIntBE=function(z,Z,X){z=z>>>0,Z=Z>>>0,X||Te(z,Z,this.length);let ae=this[z+--Z],de=1;for(;Z>0&&(de*=256);)ae+=this[z+--Z]*de;return ae},u.prototype.readUint8=u.prototype.readUInt8=function(z,Z){return z=z>>>0,Z||Te(z,1,this.length),this[z]},u.prototype.readUint16LE=u.prototype.readUInt16LE=function(z,Z){return z=z>>>0,Z||Te(z,2,this.length),this[z]|this[z+1]<<8},u.prototype.readUint16BE=u.prototype.readUInt16BE=function(z,Z){return z=z>>>0,Z||Te(z,2,this.length),this[z]<<8|this[z+1]},u.prototype.readUint32LE=u.prototype.readUInt32LE=function(z,Z){return z=z>>>0,Z||Te(z,4,this.length),(this[z]|this[z+1]<<8|this[z+2]<<16)+this[z+3]*16777216},u.prototype.readUint32BE=u.prototype.readUInt32BE=function(z,Z){return z=z>>>0,Z||Te(z,4,this.length),this[z]*16777216+(this[z+1]<<16|this[z+2]<<8|this[z+3])},u.prototype.readBigUInt64LE=We(function(z){z=z>>>0,$e(z,"offset");const Z=this[z],X=this[z+7];(Z===void 0||X===void 0)&&qe(z,this.length-8);const ae=Z+this[++z]*2**8+this[++z]*2**16+this[++z]*2**24,de=this[++z]+this[++z]*2**8+this[++z]*2**16+X*2**24;return BigInt(ae)+(BigInt(de)<<BigInt(32))}),u.prototype.readBigUInt64BE=We(function(z){z=z>>>0,$e(z,"offset");const Z=this[z],X=this[z+7];(Z===void 0||X===void 0)&&qe(z,this.length-8);const ae=Z*2**24+this[++z]*2**16+this[++z]*2**8+this[++z],de=this[++z]*2**24+this[++z]*2**16+this[++z]*2**8+X;return(BigInt(ae)<<BigInt(32))+BigInt(de)}),u.prototype.readIntLE=function(z,Z,X){z=z>>>0,Z=Z>>>0,X||Te(z,Z,this.length);let ae=this[z],de=1,me=0;for(;++me<Z&&(de*=256);)ae+=this[z+me]*de;return de*=128,ae>=de&&(ae-=Math.pow(2,8*Z)),ae},u.prototype.readIntBE=function(z,Z,X){z=z>>>0,Z=Z>>>0,X||Te(z,Z,this.length);let ae=Z,de=1,me=this[z+--ae];for(;ae>0&&(de*=256);)me+=this[z+--ae]*de;return de*=128,me>=de&&(me-=Math.pow(2,8*Z)),me},u.prototype.readInt8=function(z,Z){return z=z>>>0,Z||Te(z,1,this.length),this[z]&128?(255-this[z]+1)*-1:this[z]},u.prototype.readInt16LE=function(z,Z){z=z>>>0,Z||Te(z,2,this.length);const X=this[z]|this[z+1]<<8;return X&32768?X|4294901760:X},u.prototype.readInt16BE=function(z,Z){z=z>>>0,Z||Te(z,2,this.length);const X=this[z+1]|this[z]<<8;return X&32768?X|4294901760:X},u.prototype.readInt32LE=function(z,Z){return z=z>>>0,Z||Te(z,4,this.length),this[z]|this[z+1]<<8|this[z+2]<<16|this[z+3]<<24},u.prototype.readInt32BE=function(z,Z){return z=z>>>0,Z||Te(z,4,this.length),this[z]<<24|this[z+1]<<16|this[z+2]<<8|this[z+3]},u.prototype.readBigInt64LE=We(function(z){z=z>>>0,$e(z,"offset");const Z=this[z],X=this[z+7];(Z===void 0||X===void 0)&&qe(z,this.length-8);const ae=this[z+4]+this[z+5]*2**8+this[z+6]*2**16+(X<<24);return(BigInt(ae)<<BigInt(32))+BigInt(Z+this[++z]*2**8+this[++z]*2**16+this[++z]*2**24)}),u.prototype.readBigInt64BE=We(function(z){z=z>>>0,$e(z,"offset");const Z=this[z],X=this[z+7];(Z===void 0||X===void 0)&&qe(z,this.length-8);const ae=(Z<<24)+this[++z]*2**16+this[++z]*2**8+this[++z];return(BigInt(ae)<<BigInt(32))+BigInt(this[++z]*2**24+this[++z]*2**16+this[++z]*2**8+X)}),u.prototype.readFloatLE=function(z,Z){return z=z>>>0,Z||Te(z,4,this.length),D.read(this,z,!0,23,4)},u.prototype.readFloatBE=function(z,Z){return z=z>>>0,Z||Te(z,4,this.length),D.read(this,z,!1,23,4)},u.prototype.readDoubleLE=function(z,Z){return z=z>>>0,Z||Te(z,8,this.length),D.read(this,z,!0,52,8)},u.prototype.readDoubleBE=function(z,Z){return z=z>>>0,Z||Te(z,8,this.length),D.read(this,z,!1,52,8)};function Ie(Q,z,Z,X,ae,de){if(!u.isBuffer(Q))throw new TypeError('"buffer" argument must be a Buffer instance');if(z>ae||z<de)throw new RangeError('"value" argument is out of bounds');if(Z+X>Q.length)throw new RangeError("Index out of range")}u.prototype.writeUintLE=u.prototype.writeUIntLE=function(z,Z,X,ae){if(z=+z,Z=Z>>>0,X=X>>>0,!ae){const Oe=Math.pow(2,8*X)-1;Ie(this,z,Z,X,Oe,0)}let de=1,me=0;for(this[Z]=z&255;++me<X&&(de*=256);)this[Z+me]=z/de&255;return Z+X},u.prototype.writeUintBE=u.prototype.writeUIntBE=function(z,Z,X,ae){if(z=+z,Z=Z>>>0,X=X>>>0,!ae){const Oe=Math.pow(2,8*X)-1;Ie(this,z,Z,X,Oe,0)}let de=X-1,me=1;for(this[Z+de]=z&255;--de>=0&&(me*=256);)this[Z+de]=z/me&255;return Z+X},u.prototype.writeUint8=u.prototype.writeUInt8=function(z,Z,X){return z=+z,Z=Z>>>0,X||Ie(this,z,Z,1,255,0),this[Z]=z&255,Z+1},u.prototype.writeUint16LE=u.prototype.writeUInt16LE=function(z,Z,X){return z=+z,Z=Z>>>0,X||Ie(this,z,Z,2,65535,0),this[Z]=z&255,this[Z+1]=z>>>8,Z+2},u.prototype.writeUint16BE=u.prototype.writeUInt16BE=function(z,Z,X){return z=+z,Z=Z>>>0,X||Ie(this,z,Z,2,65535,0),this[Z]=z>>>8,this[Z+1]=z&255,Z+2},u.prototype.writeUint32LE=u.prototype.writeUInt32LE=function(z,Z,X){return z=+z,Z=Z>>>0,X||Ie(this,z,Z,4,4294967295,0),this[Z+3]=z>>>24,this[Z+2]=z>>>16,this[Z+1]=z>>>8,this[Z]=z&255,Z+4},u.prototype.writeUint32BE=u.prototype.writeUInt32BE=function(z,Z,X){return z=+z,Z=Z>>>0,X||Ie(this,z,Z,4,4294967295,0),this[Z]=z>>>24,this[Z+1]=z>>>16,this[Z+2]=z>>>8,this[Z+3]=z&255,Z+4};function He(Q,z,Z,X,ae){Se(z,X,ae,Q,Z,7);let de=Number(z&BigInt(4294967295));Q[Z++]=de,de=de>>8,Q[Z++]=de,de=de>>8,Q[Z++]=de,de=de>>8,Q[Z++]=de;let me=Number(z>>BigInt(32)&BigInt(4294967295));return Q[Z++]=me,me=me>>8,Q[Z++]=me,me=me>>8,Q[Z++]=me,me=me>>8,Q[Z++]=me,Z}function Ae(Q,z,Z,X,ae){Se(z,X,ae,Q,Z,7);let de=Number(z&BigInt(4294967295));Q[Z+7]=de,de=de>>8,Q[Z+6]=de,de=de>>8,Q[Z+5]=de,de=de>>8,Q[Z+4]=de;let me=Number(z>>BigInt(32)&BigInt(4294967295));return Q[Z+3]=me,me=me>>8,Q[Z+2]=me,me=me>>8,Q[Z+1]=me,me=me>>8,Q[Z]=me,Z+8}u.prototype.writeBigUInt64LE=We(function(z,Z=0){return He(this,z,Z,BigInt(0),BigInt("0xffffffffffffffff"))}),u.prototype.writeBigUInt64BE=We(function(z,Z=0){return Ae(this,z,Z,BigInt(0),BigInt("0xffffffffffffffff"))}),u.prototype.writeIntLE=function(z,Z,X,ae){if(z=+z,Z=Z>>>0,!ae){const Ce=Math.pow(2,8*X-1);Ie(this,z,Z,X,Ce-1,-Ce)}let de=0,me=1,Oe=0;for(this[Z]=z&255;++de<X&&(me*=256);)z<0&&Oe===0&&this[Z+de-1]!==0&&(Oe=1),this[Z+de]=(z/me>>0)-Oe&255;return Z+X},u.prototype.writeIntBE=function(z,Z,X,ae){if(z=+z,Z=Z>>>0,!ae){const Ce=Math.pow(2,8*X-1);Ie(this,z,Z,X,Ce-1,-Ce)}let de=X-1,me=1,Oe=0;for(this[Z+de]=z&255;--de>=0&&(me*=256);)z<0&&Oe===0&&this[Z+de+1]!==0&&(Oe=1),this[Z+de]=(z/me>>0)-Oe&255;return Z+X},u.prototype.writeInt8=function(z,Z,X){return z=+z,Z=Z>>>0,X||Ie(this,z,Z,1,127,-128),z<0&&(z=255+z+1),this[Z]=z&255,Z+1},u.prototype.writeInt16LE=function(z,Z,X){return z=+z,Z=Z>>>0,X||Ie(this,z,Z,2,32767,-32768),this[Z]=z&255,this[Z+1]=z>>>8,Z+2},u.prototype.writeInt16BE=function(z,Z,X){return z=+z,Z=Z>>>0,X||Ie(this,z,Z,2,32767,-32768),this[Z]=z>>>8,this[Z+1]=z&255,Z+2},u.prototype.writeInt32LE=function(z,Z,X){return z=+z,Z=Z>>>0,X||Ie(this,z,Z,4,2147483647,-2147483648),this[Z]=z&255,this[Z+1]=z>>>8,this[Z+2]=z>>>16,this[Z+3]=z>>>24,Z+4},u.prototype.writeInt32BE=function(z,Z,X){return z=+z,Z=Z>>>0,X||Ie(this,z,Z,4,2147483647,-2147483648),z<0&&(z=4294967295+z+1),this[Z]=z>>>24,this[Z+1]=z>>>16,this[Z+2]=z>>>8,this[Z+3]=z&255,Z+4},u.prototype.writeBigInt64LE=We(function(z,Z=0){return He(this,z,Z,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),u.prototype.writeBigInt64BE=We(function(z,Z=0){return Ae(this,z,Z,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function Fe(Q,z,Z,X,ae,de){if(Z+X>Q.length)throw new RangeError("Index out of range");if(Z<0)throw new RangeError("Index out of range")}function Ze(Q,z,Z,X,ae){return z=+z,Z=Z>>>0,ae||Fe(Q,z,Z,4),D.write(Q,z,Z,X,23,4),Z+4}u.prototype.writeFloatLE=function(z,Z,X){return Ze(this,z,Z,!0,X)},u.prototype.writeFloatBE=function(z,Z,X){return Ze(this,z,Z,!1,X)};function je(Q,z,Z,X,ae){return z=+z,Z=Z>>>0,ae||Fe(Q,z,Z,8),D.write(Q,z,Z,X,52,8),Z+8}u.prototype.writeDoubleLE=function(z,Z,X){return je(this,z,Z,!0,X)},u.prototype.writeDoubleBE=function(z,Z,X){return je(this,z,Z,!1,X)},u.prototype.copy=function(z,Z,X,ae){if(!u.isBuffer(z))throw new TypeError("argument should be a Buffer");if(X||(X=0),!ae&&ae!==0&&(ae=this.length),Z>=z.length&&(Z=z.length),Z||(Z=0),ae>0&&ae<X&&(ae=X),ae===X||z.length===0||this.length===0)return 0;if(Z<0)throw new RangeError("targetStart out of bounds");if(X<0||X>=this.length)throw new RangeError("Index out of range");if(ae<0)throw new RangeError("sourceEnd out of bounds");ae>this.length&&(ae=this.length),z.length-Z<ae-X&&(ae=z.length-Z+X);const de=ae-X;return this===z&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(Z,X,ae):Uint8Array.prototype.set.call(z,this.subarray(X,ae),Z),de},u.prototype.fill=function(z,Z,X,ae){if(typeof z=="string"){if(typeof Z=="string"?(ae=Z,Z=0,X=this.length):typeof X=="string"&&(ae=X,X=this.length),ae!==void 0&&typeof ae!="string")throw new TypeError("encoding must be a string");if(typeof ae=="string"&&!u.isEncoding(ae))throw new TypeError("Unknown encoding: "+ae);if(z.length===1){const me=z.charCodeAt(0);(ae==="utf8"&&me<128||ae==="latin1")&&(z=me)}}else typeof z=="number"?z=z&255:typeof z=="boolean"&&(z=Number(z));if(Z<0||this.length<Z||this.length<X)throw new RangeError("Out of range index");if(X<=Z)return this;Z=Z>>>0,X=X===void 0?this.length:X>>>0,z||(z=0);let de;if(typeof z=="number")for(de=Z;de<X;++de)this[de]=z;else{const me=u.isBuffer(z)?z:u.from(z,ae),Oe=me.length;if(Oe===0)throw new TypeError('The value "'+z+'" is invalid for argument "value"');for(de=0;de<X-Z;++de)this[de+Z]=me[de%Oe]}return this};const Ne={};function _e(Q,z,Z){Ne[Q]=class extends Z{constructor(){super(),Object.defineProperty(this,"message",{value:z.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${Q}]`,this.stack,delete this.name}get code(){return Q}set code(ae){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:ae,writable:!0})}toString(){return`${this.name} [${Q}]: ${this.message}`}}}_e("ERR_BUFFER_OUT_OF_BOUNDS",function(Q){return Q?`${Q} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),_e("ERR_INVALID_ARG_TYPE",function(Q,z){return`The "${Q}" argument must be of type number. Received type ${typeof z}`},TypeError),_e("ERR_OUT_OF_RANGE",function(Q,z,Z){let X=`The value of "${Q}" is out of range.`,ae=Z;return Number.isInteger(Z)&&Math.abs(Z)>2**32?ae=ke(String(Z)):typeof Z=="bigint"&&(ae=String(Z),(Z>BigInt(2)**BigInt(32)||Z<-(BigInt(2)**BigInt(32)))&&(ae=ke(ae)),ae+="n"),X+=` It must be ${z}. Received ${ae}`,X},RangeError);function ke(Q){let z="",Z=Q.length;const X=Q[0]==="-"?1:0;for(;Z>=X+4;Z-=3)z=`_${Q.slice(Z-3,Z)}${z}`;return`${Q.slice(0,Z)}${z}`}function we(Q,z,Z){$e(z,"offset"),(Q[z]===void 0||Q[z+Z]===void 0)&&qe(z,Q.length-(Z+1))}function Se(Q,z,Z,X,ae,de){if(Q>Z||Q<z){const me=typeof z=="bigint"?"n":"";let Oe;throw z===0||z===BigInt(0)?Oe=`>= 0${me} and < 2${me} ** ${(de+1)*8}${me}`:Oe=`>= -(2${me} ** ${(de+1)*8-1}${me}) and < 2 ** ${(de+1)*8-1}${me}`,new Ne.ERR_OUT_OF_RANGE("value",Oe,Q)}we(X,ae,de)}function $e(Q,z){if(typeof Q!="number")throw new Ne.ERR_INVALID_ARG_TYPE(z,"number",Q)}function qe(Q,z,Z){throw Math.floor(Q)!==Q?($e(Q,Z),new Ne.ERR_OUT_OF_RANGE("offset","an integer",Q)):z<0?new Ne.ERR_BUFFER_OUT_OF_BOUNDS:new Ne.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${z}`,Q)}const Me=/[^+/0-9A-Za-z-_]/g;function Ue(Q){if(Q=Q.split("=")[0],Q=Q.trim().replace(Me,""),Q.length<2)return"";for(;Q.length%4!==0;)Q=Q+"=";return Q}function Je(Q,z){z=z||1/0;let Z;const X=Q.length;let ae=null;const de=[];for(let me=0;me<X;++me){if(Z=Q.charCodeAt(me),Z>55295&&Z<57344){if(!ae){if(Z>56319){(z-=3)>-1&&de.push(239,191,189);continue}else if(me+1===X){(z-=3)>-1&&de.push(239,191,189);continue}ae=Z;continue}if(Z<56320){(z-=3)>-1&&de.push(239,191,189),ae=Z;continue}Z=(ae-55296<<10|Z-56320)+65536}else ae&&(z-=3)>-1&&de.push(239,191,189);if(ae=null,Z<128){if((z-=1)<0)break;de.push(Z)}else if(Z<2048){if((z-=2)<0)break;de.push(Z>>6|192,Z&63|128)}else if(Z<65536){if((z-=3)<0)break;de.push(Z>>12|224,Z>>6&63|128,Z&63|128)}else if(Z<1114112){if((z-=4)<0)break;de.push(Z>>18|240,Z>>12&63|128,Z>>6&63|128,Z&63|128)}else throw new Error("Invalid code point")}return de}function Ge(Q){const z=[];for(let Z=0;Z<Q.length;++Z)z.push(Q.charCodeAt(Z)&255);return z}function Ye(Q,z){let Z,X,ae;const de=[];for(let me=0;me<Q.length&&!((z-=2)<0);++me)Z=Q.charCodeAt(me),X=Z>>8,ae=Z%256,de.push(ae),de.push(X);return de}function Ke(Q){return B.toByteArray(Ue(Q))}function Qe(Q,z,Z,X){let ae;for(ae=0;ae<X&&!(ae+Z>=z.length||ae>=Q.length);++ae)z[ae+Z]=Q[ae];return ae}function ze(Q,z){return Q instanceof z||Q!=null&&Q.constructor!=null&&Q.constructor.name!=null&&Q.constructor.name===z.name}function Xe(Q){return Q!==Q}const et=function(){const Q="0123456789abcdef",z=new Array(256);for(let Z=0;Z<16;++Z){const X=Z*16;for(let ae=0;ae<16;++ae)z[X+ae]=Q[Z]+Q[ae]}return z}();function We(Q){return typeof BigInt>"u"?tt:Q}function tt(){throw new Error("BigInt not supported")}}(buffer)),buffer}var toolsEbml={},hasRequiredToolsEbml;function requireToolsEbml(){if(hasRequiredToolsEbml)return toolsEbml;hasRequiredToolsEbml=1;var A=toolsEbml&&toolsEbml.__assign||function(){return A=Object.assign||function(O){for(var C,i=1,u=arguments.length;i<u;i++){C=arguments[i];for(var $ in C)Object.prototype.hasOwnProperty.call(C,$)&&(O[$]=C[$])}return O},A.apply(this,arguments)},B=toolsEbml&&toolsEbml.__spreadArray||function(O,C,i){if(i||arguments.length===2)for(var u=0,$=C.length,N;u<$;u++)(N||!(u in C))&&(N||(N=Array.prototype.slice.call(C,0,u)),N[u]=C[u]);return O.concat(N||Array.prototype.slice.call(C))};Object.defineProperty(toolsEbml,"__esModule",{value:!0});var D=requireTools(),M=function(){function O(){}return O.readVint=function(C,i){i===void 0&&(i=0);var u=8-Math.floor(Math.log2(C[i]));if(u>8){var $=O.readHexString(C,i,i+u);throw new Error("Unrepresentable length: ".concat(u," ").concat($))}if(i+u>C.length)return null;for(var N=C[i]&(1<<8-u)-1,F=1;F<u;F+=1){if(F===7&&N>=Math.pow(2,8)&&C[i+7]>0)return{length:u,value:-1};N*=Math.pow(2,8),N+=C[i+F]}return{length:u,value:N}},O.writeVint=function(C){if(C<0||C>Math.pow(2,53))throw new Error("Unrepresentable value: ".concat(C));var i=1;for(i=1;i<=8&&!(C<Math.pow(2,7*i)-1);i+=1);for(var u=D.Buffer.alloc(i),$=C,N=1;N<=i;N+=1){var F=$&255;u[i-N]=F,$-=F,$/=Math.pow(2,8)}return u[0]|=1<<8-i,u},O.concatenate=function(C,i){return!C&&!i?D.Buffer.from([]):!C||C.byteLength===0?i:!i||i.byteLength===0?C:D.Buffer.from(B(B([],C,!0),i,!0))},O.readHexString=function(C,i,u){return i===void 0&&(i=0),u===void 0&&(u=C.byteLength),Array.from(C.slice(i,u)).map(function($){return Number($).toString(16)}).reduce(function($,N){return"".concat($).concat(N.padStart(2,"0"))},"")},O.readUtf8=function(C){try{return D.Buffer.from(C).toString("utf8")}catch{return null}},O.readUnsigned=function(C){var i=new DataView(C.buffer,C.byteOffset,C.byteLength);switch(C.byteLength){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 4:return i.getUint32(0)}return C.byteLength<=6?C.reduce(function(u,$){return u*256+$},0):O.readHexString(C,0,C.byteLength)},O.readSigned=function(C){var i=new DataView(C.buffer,C.byteOffset,C.byteLength);switch(C.byteLength){case 1:return i.getInt8(0);case 2:return i.getInt16(0);case 4:return i.getInt32(0);default:return NaN}},O.readFloat=function(C){var i=new DataView(C.buffer,C.byteOffset,C.byteLength);switch(C.byteLength){case 4:return i.getFloat32(0);case 8:return i.getFloat64(0);default:return NaN}},O.readDate=function(C){var i=new DataView(C.buffer,C.byteOffset,C.byteLength);switch(C.byteLength){case 1:return new Date(i.getUint8(0));case 2:return new Date(i.getUint16(0));case 4:return new Date(i.getUint32(0));case 8:return new Date(Number.parseInt(O.readHexString(C),16));default:return new Date(0)}},O.readDataFromTag=function(C,i){var u=C.type,$=C.name,N=C.track,F=C.discardable||!1,j=C.keyframe||!1,J=null,K;switch(u){case"u":K=O.readUnsigned(i);break;case"f":K=O.readFloat(i);break;case"i":K=O.readSigned(i);break;case"s":K=String.fromCharCode.apply(String,i);break;case"8":K=O.readUtf8(i);break;case"d":K=O.readDate(i);break}if($==="SimpleBlock"||$==="Block"){var Y=0,re=O.readVint(i,Y),oe=re.length,te=re.value;Y+=oe,N=te,K=O.readSigned(i.subarray(Y,Y+2)),Y+=2,$==="SimpleBlock"&&(j=!!(i[oe+2]&128),F=!!(i[oe+2]&1)),Y+=1,J=i.subarray(Y)}return A(A({},C),{data:i,discardable:F,keyframe:j,payload:J,track:N,value:K})},O}();return toolsEbml.default=M,toolsEbml}var vint,hasRequiredVint;function requireVint(){return hasRequiredVint||(hasRequiredVint=1,vint=function(A,B,D){B=B||0;for(var M=1;M<=8&&!(A[B]>=Math.pow(2,8-M));M++);if(M>8)throw new Error("Unrepresentable length: "+M+" "+A.toString("hex",B,B+M));if(B+M>A.length)return null;var O,C=A[B]&(1<<8-M)-1;for(O=1;O<M;O++){if(O===7&&C>=Math.pow(2,45)&&A[B+7]>0)return{length:M,value:-1};C*=Math.pow(2,8),C+=A[B+O]}return D&&(C-=Math.pow(2,M*7-1)-1),{length:M,value:C}}),vint}var bufferReader,hasRequiredBufferReader;function requireBufferReader(){if(hasRequiredBufferReader)return bufferReader;hasRequiredBufferReader=1;var A=requireVint();function B(D){this.buffer=D,this.offset=0}return B.prototype.nextInt16BE=function(){var D=this.buffer.readInt16BE(this.offset);return this.offset+=2,D},B.prototype.nextUInt8=function(){var D=this.buffer.readUInt8(this.offset);return this.offset+=1,D},B.prototype.nextUIntV=function(){var D=A(this.buffer,this.offset);return this.offset+=D.length,D.value},B.prototype.nextIntV=function(){var D=A(this.buffer,this.offset,!0);return this.offset+=D.length,D.value},B.prototype.nextBuffer=function(D){var M=D?this.buffer.slice(this.offset,this.offset+D):this.buffer.slice(this.offset);return this.offset+=D||this.length,M},Object.defineProperty(B.prototype,"length",{get:function(){return this.buffer.length-this.offset}}),bufferReader=B,bufferReader}var ebmlBlock,hasRequiredEbmlBlock;function requireEbmlBlock(){if(hasRequiredEbmlBlock)return ebmlBlock;hasRequiredEbmlBlock=1;var A=requireBufferReader(),B=1,D=3,M=2;ebmlBlock=function(C){var i={},u=new A(C);i.trackNumber=u.nextUIntV(),i.timecode=u.nextInt16BE();var $=u.nextUInt8();i.invisible=!!($&8),i.keyframe=!!($&128),i.discardable=!!($&1);var N=($&6)>>1;return i.frames=O(u,N),i};function O(C,i){if(!i)return[C.nextBuffer()];var u,$,N=[],F=C.nextUInt8()+1;if(i===M){if(C.length%F!==0)throw new Error("Fixed-Size Lacing Error");for($=C.length/F,u=0;u<F;u++)N.push(C.nextBuffer($));return N}var j=[];if(i===B)for(u=0;u<F-1;u++){var J;$=0;do J=C.nextUInt8(),$+=J;while(J===255);j.push($)}else if(i===D)for($=C.nextUIntV(),j.push($),u=1;u<F-1;u++)$+=C.nextIntV(),j.push($);for(u=0;u<F-1;u++)N.push(C.nextBuffer(j[u]));return N.push(C.nextBuffer()),N}return ebmlBlock}var hasRequiredTools;function requireTools(){return hasRequiredTools||(hasRequiredTools=1,function(A){Object.defineProperty(A,"__esModule",{value:!0}),A.convertEBMLDateToJSDate=A.createFloatBuffer=A.createIntBuffer=A.createUIntBuffer=A.encodeValueToBuffer=A.concat=A.putRefinedMetaData=A.extractElement=A.removeElement=A.makeMetadataSeekable=A.createRIFFChunk=A.VP8BitStreamToRiffWebPBuffer=A.WebPBlockFilter=A.encodeTag=A.readBlock=A.ebmlBlock=A.writeVint=A.readVint=A.Buffer=void 0;var B=requireInt64Buffer(),D=requireEBMLEncoder(),M=requireBuffer(),O=requireToolsEbml(),C=requireEbmlBlock();A.Buffer=M.Buffer,A.readVint=O.default.readVint,A.writeVint=O.default.writeVint,A.ebmlBlock=C;function i(ie){return(0,A.ebmlBlock)(new A.Buffer(ie))}A.readBlock=i;function u(ie,fe,ye){return ye===void 0&&(ye=!1),ee([ie,ye?new A.Buffer("01ffffffffffffff","hex"):(0,A.writeVint)(fe.length),fe])}A.encodeTag=u;function $(ie){return ie.reduce(function(fe,ye){if(ye.type!=="b"||ye.name!=="SimpleBlock")return fe;var ve=(0,A.ebmlBlock)(ye.data),be=ve.frames.some(function(ge){var Ee=ge.slice(3,6).toString("hex");return Ee==="9d012a"});return be?fe.concat(ye):fe},[])}A.WebPBlockFilter=$;function N(ie){var fe=F("VP8 ",ie),ye=ee([new A.Buffer("WEBP","ascii"),fe]);return F("RIFF",ye)}A.VP8BitStreamToRiffWebPBuffer=N;function F(ie,fe){var ye=new A.Buffer(4);return ye.writeUInt32LE(fe.byteLength,0),ee([new A.Buffer(ie.substr(0,4),"ascii"),ye,fe,new A.Buffer(fe.byteLength%2===0?0:1)])}A.createRIFFChunk=F;function j(ie,fe,ye){var ve=K("EBML",ie),be=re(ve),ge=be+12,Ee=ie[ie.length-1].dataEnd-ge,De=K("Info",ie);J("Duration",De),De.splice(1,0,{name:"Duration",type:"f",data:ce(fe,8)});for(var Be=re(De),Le=K("Tracks",ie),Ve=re(Le),Te=47,Ie=[],He=5+ye.length*15,Ae=[],Fe=-1,Ze=10,je=function(Se){var $e=Te,qe=$e+Be,Me=qe+Ve,Ue=Me+He,Je=Ue-Ee;if(Ie=[],Ie.push({name:"SeekHead",type:"m",isEnd:!1}),Ie.push({name:"Seek",type:"m",isEnd:!1}),Ie.push({name:"SeekID",type:"b",data:new A.Buffer([21,73,169,102])}),Ie.push({name:"SeekPosition",type:"u",data:ue($e)}),Ie.push({name:"Seek",type:"m",isEnd:!0}),Ie.push({name:"Seek",type:"m",isEnd:!1}),Ie.push({name:"SeekID",type:"b",data:new A.Buffer([22,84,174,107])}),Ie.push({name:"SeekPosition",type:"u",data:ue(qe)}),Ie.push({name:"Seek",type:"m",isEnd:!0}),Ie.push({name:"Seek",type:"m",isEnd:!1}),Ie.push({name:"SeekID",type:"b",data:new A.Buffer([28,83,187,107])}),Ie.push({name:"SeekPosition",type:"u",data:ue(Me)}),Ie.push({name:"Seek",type:"m",isEnd:!0}),Ie.push({name:"SeekHead",type:"m",isEnd:!0}),Te=re(Ie),Ae=[],Ae.push({name:"Cues",type:"m",isEnd:!1}),ye.forEach(function(Ge){var Ye=Ge.CueTrack,Ke=Ge.CueClusterPosition,Qe=Ge.CueTime;Ae.push({name:"CuePoint",type:"m",isEnd:!1}),Ae.push({name:"CueTime",type:"u",data:ue(Qe)}),Ae.push({name:"CueTrackPositions",type:"m",isEnd:!1}),Ae.push({name:"CueTrack",type:"u",data:ue(Ye)}),Ke-=ge,Ke+=Je,Ae.push({name:"CueClusterPosition",type:"u",data:ue(Ke)}),Ae.push({name:"CueTrackPositions",type:"m",isEnd:!0}),Ae.push({name:"CuePoint",type:"m",isEnd:!0})}),Ae.push({name:"Cues",type:"m",isEnd:!0}),He=re(Ae),Fe!==Je){if(Fe=Je,Se===Ze-1)throw new Error("Failed to converge to a stable metadata size")}else return"break"},Ne=0;Ne<Ze;Ne++){var _e=je(Ne);if(_e==="break")break}var ke=[].concat.apply([],[ve,{name:"Segment",type:"m",isEnd:!1,unknownSize:!0},Ie,De,Le,Ae]),we=new D.default().encode(ke);return we}A.makeMetadataSeekable=j;function J(ie,fe){for(var ye=-1,ve=0;ve<fe.length;ve++){var be=fe[ve];if(be.name===ie)if(be.type==="m")if(!be.isEnd)ye=ve;else{if(ye==-1)throw new Error("Detected ".concat(ie," closing element before finding the start"));fe.splice(ye,ve-ye+1);return}else{fe.splice(ve,1);return}}}A.removeElement=J;function K(ie,fe){for(var ye=[],ve=-1,be=0;be<fe.length;be++){var ge=fe[be];if(ge.name===ie)if(ge.type==="m")if(!ge.isEnd)ve=be;else{if(ve==-1)throw new Error("Detected ".concat(ie," closing element before finding the start"));ye=fe.slice(ve,be+1);break}else{ye.push(fe[be]);break}}return ye}A.extractElement=K;function Y(ie,fe){Array.isArray(fe.cueInfos)&&!Array.isArray(fe.cues)&&(console.warn("putRefinedMetaData: info.cueInfos property is deprecated. please use info.cues"),fe.cues=fe.cueInfos);for(var ye=[],ve=[],be=0;be<ie.length;be++){var ge=ie[be];if(ge.type==="m"&&ge.name==="Segment"){if(ye=ie.slice(0,be),ve=ie.slice(be),ge.unknownSize){ve.shift();break}throw new Error("this metadata is not streaming webm file")}}if(!(ve[ve.length-1].dataEnd>0))throw new Error("metadata dataEnd has wrong number");var Ee=ve[ve.length-1].dataEnd,De=ye[ye.length-1].dataEnd,Be=new D.default().encode(ye).byteLength,Le=Be-De,Ve=Ee-ve[0].tagStart;ve[0].tagStart-De,ve[0].tagStart;var Te=new A.Buffer([24,83,128,103]),Ie=new A.Buffer("01ffffffffffffff","hex"),He=Te.byteLength+Ie.byteLength,Ae=Ve,Fe;for(Fe=1;Fe<20;Fe++){var Ze=De+He+Ae,je=Ze-Ee,Ne=Le+je,_e=oe(ve,Ne,fe),ke=new D.default().encode(_e).byteLength;if(ke===Ae)return new D.default().encode([].concat(ye,[{type:"m",name:"Segment",isEnd:!1,unknownSize:!0}],_e));Ae=ke}throw new Error("unable to refine metadata, stable size could not be found in "+Fe+" iterations!")}A.putRefinedMetaData=Y;function re(ie){var fe=new D.default;return ie.reduce(function(ye,ve){return ye.concat(fe.encode([ve]))},[]).reduce(function(ye,ve){return ye+ve.byteLength},0)}function oe(ie,fe,ye){var ve=ye.duration,be=ye.clusterPtrs,ge=ye.cues,Ee=ie.slice(0);if(typeof ve=="number"){var De=!1;Ee.forEach(function(Le){Le.type==="f"&&Le.name==="Duration"&&(De=!0,Le.data=ce(ve,8))}),De||pe(Ee,"Info",[{name:"Duration",type:"f",data:ce(ve,8)}])}Array.isArray(ge)&&pe(Ee,"Cues",le(ge,fe));var Be=[];return Array.isArray(be)&&(console.warn("append cluster pointers to seekhead is deprecated. please use cues"),Be=te(be,fe)),pe(Ee,"SeekHead",Be,!0),Ee}function te(ie,fe){var ye=[];return ie.forEach(function(ve){ye.push({name:"Seek",type:"m",isEnd:!1}),ye.push({name:"SeekID",type:"b",data:new A.Buffer([31,67,182,117])}),ye.push({name:"SeekPosition",type:"u",data:ue(ve+fe)}),ye.push({name:"Seek",type:"m",isEnd:!0})}),ye}function le(ie,fe){var ye=[];return ie.forEach(function(ve){var be=ve.CueTrack,ge=ve.CueClusterPosition,Ee=ve.CueTime;ye.push({name:"CuePoint",type:"m",isEnd:!1}),ye.push({name:"CueTime",type:"u",data:ue(Ee)}),ye.push({name:"CueTrackPositions",type:"m",isEnd:!1}),ye.push({name:"CueTrack",type:"u",data:ue(be)}),ye.push({name:"CueClusterPosition",type:"u",data:ue(ge+fe)}),ye.push({name:"CueTrackPositions",type:"m",isEnd:!0}),ye.push({name:"CuePoint",type:"m",isEnd:!0})}),ye}function pe(ie,fe,ye,ve){ve===void 0&&(ve=!1);for(var be=-1,ge=0;ge<ie.length;ge++){var Ee=ie[ge];if(Ee.type==="m"&&Ee.name===fe&&Ee.isEnd===!1){be=ge;break}}be>=0?Array.prototype.splice.apply(ie,[be+1,0].concat(ye)):ve?[].concat([{name:fe,type:"m",isEnd:!1}],ye,[{name:fe,type:"m",isEnd:!0}]).reverse().forEach(function(De){ie.unshift(De)}):(ie.push({name:fe,type:"m",isEnd:!1}),ye.forEach(function(De){ie.push(De)}),ie.push({name:fe,type:"m",isEnd:!0}))}function ee(ie){return A.Buffer.concat(ie)}A.concat=ee;function ne(ie){var fe=new A.Buffer(0);if(ie.type==="m")return ie;switch(ie.type){case"u":fe=ue(ie.value);break;case"i":fe=se(ie.value);break;case"f":fe=ce(ie.value);break;case"s":fe=new A.Buffer(ie.value,"ascii");break;case"8":fe=new A.Buffer(ie.value,"utf8");break;case"b":fe=ie.value;break;case"d":fe=new B.Int64BE(ie.value.getTime().toString()).toBuffer();break}return Object.assign({},ie,{data:fe})}A.encodeValueToBuffer=ne;function ue(ie){for(var fe=1;ie>=Math.pow(2,8*fe);fe++);if(fe>=7)return console.warn("7bit or more bigger uint not supported."),new B.Uint64BE(ie).toBuffer();var ye=new A.Buffer(fe);return ye.writeUIntBE(ie,0,fe),ye}A.createUIntBuffer=ue;function se(ie){for(var fe=1;ie>=Math.pow(2,8*fe);fe++);if(fe>=7)return console.warn("7bit or more bigger uint not supported."),new B.Int64BE(ie).toBuffer();var ye=new A.Buffer(fe);return ye.writeIntBE(ie,0,fe),ye}A.createIntBuffer=se;function ce(ie,fe){if(fe===void 0&&(fe=8),fe===8){var ye=new A.Buffer(8);return ye.writeDoubleBE(ie,0),ye}else if(fe===4){var ye=new A.Buffer(4);return ye.writeFloatBE(ie,0),ye}else throw new Error("float type bits must 4bytes or 8bytes")}A.createFloatBuffer=ce;function he(ie){return ie instanceof Date?ie:new Date(new Date("2001-01-01T00:00:00.000Z").getTime()+Number(ie)/1e3/1e3)}A.convertEBMLDateToJSDate=he}(tools)),tools}var hasRequiredEBMLDecoder;function requireEBMLDecoder(){if(hasRequiredEBMLDecoder)return EBMLDecoder;hasRequiredEBMLDecoder=1,Object.defineProperty(EBMLDecoder,"__esModule",{value:!0});var A=requireInt64Buffer(),B=requireTools(),D=requireTools(),M=requireEbmlID(),O;(function(i){i[i.STATE_TAG=1]="STATE_TAG",i[i.STATE_SIZE=2]="STATE_SIZE",i[i.STATE_CONTENT=3]="STATE_CONTENT"})(O||(O={}));var C=function(){function i(){this._buffer=new B.Buffer(0),this._tag_stack=[],this._state=O.STATE_TAG,this._cursor=0,this._total=0,this._schema=M.byEbmlID,this._result=[]}return i.prototype.decode=function(u){this.readChunk(u);var $=this._result;return this._result=[],$},i.prototype.readChunk=function(u){for(this._buffer=D.concat([this._buffer,new B.Buffer(u)]);this._cursor<this._buffer.length&&!(this._state===O.STATE_TAG&&!this.readTag()||this._state===O.STATE_SIZE&&!this.readSize()||this._state===O.STATE_CONTENT&&!this.readContent()););},i.prototype.getSchemaInfo=function(u){return this._schema[u]||{name:"unknown",level:-1,type:"unknown",description:"unknown"}},i.prototype.readTag=function(){if(this._cursor>=this._buffer.length)return!1;var u=(0,B.readVint)(this._buffer,this._cursor);if(u==null)return!1;var $=this._buffer.slice(this._cursor,this._cursor+u.length),N=$.reduce(function(J,K,Y,re){return J+K*Math.pow(16,2*(re.length-1-Y))},0),F=this.getSchemaInfo(N),j={EBML_ID:N.toString(16),schema:F,type:F.type,name:F.name,level:F.level,tagStart:this._total,tagEnd:this._total+u.length,sizeStart:this._total+u.length,sizeEnd:null,dataStart:null,dataEnd:null,dataSize:null,data:null};return this._tag_stack.push(j),this._cursor+=u.length,this._total+=u.length,this._state=O.STATE_SIZE,!0},i.prototype.readSize=function(){if(this._cursor>=this._buffer.length)return!1;var u=(0,B.readVint)(this._buffer,this._cursor);if(u==null)return!1;var $=this._tag_stack[this._tag_stack.length-1];return $.sizeEnd=$.sizeStart+u.length,$.dataStart=$.sizeEnd,$.dataSize=u.value,u.value===-1?($.dataEnd=-1,$.type==="m"&&($.unknownSize=!0)):$.dataEnd=$.sizeEnd+u.value,this._cursor+=u.length,this._total+=u.length,this._state=O.STATE_CONTENT,!0},i.prototype.readContent=function(){var u=this._tag_stack[this._tag_stack.length-1];if(u.type==="m"){if(u.isEnd=!1,this._result.push(u),this._state=O.STATE_TAG,u.dataSize===0){var $=Object.assign({},u,{isEnd:!0});this._result.push($),this._tag_stack.pop()}return!0}if(this._buffer.length<this._cursor+u.dataSize)return!1;var N=this._buffer.slice(this._cursor,this._cursor+u.dataSize);switch(this._buffer=this._buffer.slice(this._cursor+u.dataSize),u.data=N,u.type){case"u":u.value=N.readUIntBE(0,N.length);break;case"i":u.value=N.readIntBE(0,N.length);break;case"f":u.value=u.dataSize===4?N.readFloatBE(0):u.dataSize===8?N.readDoubleBE(0):(console.warn("cannot read ".concat(u.dataSize," octets float. failback to 0")),0);break;case"s":u.value=N.toString("ascii");break;case"8":u.value=N.toString("utf8");break;case"b":u.value=N;break;case"d":u.value=(0,B.convertEBMLDateToJSDate)(new A.Int64BE(N).toNumber());break}if(u.value===null)throw new Error("unknown tag type:"+u.type);for(this._result.push(u),this._total+=u.dataSize,this._state=O.STATE_TAG,this._cursor=0,this._tag_stack.pop();this._tag_stack.length>0;){var F=this._tag_stack[this._tag_stack.length-1];if(F.dataEnd<0)return this._tag_stack.pop(),!0;if(this._total<F.dataEnd)break;if(F.type!=="m")throw new Error("parent element is not master element");var $=Object.assign({},F,{isEnd:!0});this._result.push($),this._tag_stack.pop()}return!0},i}();return EBMLDecoder.default=C,EBMLDecoder}var EBMLReader={},events={exports:{}},hasRequiredEvents;function requireEvents(){if(hasRequiredEvents)return events.exports;hasRequiredEvents=1;var A=typeof Reflect=="object"?Reflect:null,B=A&&typeof A.apply=="function"?A.apply:function(ne,ue,se){return Function.prototype.apply.call(ne,ue,se)},D;A&&typeof A.ownKeys=="function"?D=A.ownKeys:Object.getOwnPropertySymbols?D=function(ne){return Object.getOwnPropertyNames(ne).concat(Object.getOwnPropertySymbols(ne))}:D=function(ne){return Object.getOwnPropertyNames(ne)};function M(ee){console&&console.warn&&console.warn(ee)}var O=Number.isNaN||function(ne){return ne!==ne};function C(){C.init.call(this)}events.exports=C,events.exports.once=te,C.EventEmitter=C,C.prototype._events=void 0,C.prototype._eventsCount=0,C.prototype._maxListeners=void 0;var i=10;function u(ee){if(typeof ee!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof ee)}Object.defineProperty(C,"defaultMaxListeners",{enumerable:!0,get:function(){return i},set:function(ee){if(typeof ee!="number"||ee<0||O(ee))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+ee+".");i=ee}}),C.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},C.prototype.setMaxListeners=function(ne){if(typeof ne!="number"||ne<0||O(ne))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+ne+".");return this._maxListeners=ne,this};function $(ee){return ee._maxListeners===void 0?C.defaultMaxListeners:ee._maxListeners}C.prototype.getMaxListeners=function(){return $(this)},C.prototype.emit=function(ne){for(var ue=[],se=1;se<arguments.length;se++)ue.push(arguments[se]);var ce=ne==="error",he=this._events;if(he!==void 0)ce=ce&&he.error===void 0;else if(!ce)return!1;if(ce){var ie;if(ue.length>0&&(ie=ue[0]),ie instanceof Error)throw ie;var fe=new Error("Unhandled error."+(ie?" ("+ie.message+")":""));throw fe.context=ie,fe}var ye=he[ne];if(ye===void 0)return!1;if(typeof ye=="function")B(ye,this,ue);else for(var ve=ye.length,be=Y(ye,ve),se=0;se<ve;++se)B(be[se],this,ue);return!0};function N(ee,ne,ue,se){var ce,he,ie;if(u(ue),he=ee._events,he===void 0?(he=ee._events=Object.create(null),ee._eventsCount=0):(he.newListener!==void 0&&(ee.emit("newListener",ne,ue.listener?ue.listener:ue),he=ee._events),ie=he[ne]),ie===void 0)ie=he[ne]=ue,++ee._eventsCount;else if(typeof ie=="function"?ie=he[ne]=se?[ue,ie]:[ie,ue]:se?ie.unshift(ue):ie.push(ue),ce=$(ee),ce>0&&ie.length>ce&&!ie.warned){ie.warned=!0;var fe=new Error("Possible EventEmitter memory leak detected. "+ie.length+" "+String(ne)+" listeners added. Use emitter.setMaxListeners() to increase limit");fe.name="MaxListenersExceededWarning",fe.emitter=ee,fe.type=ne,fe.count=ie.length,M(fe)}return ee}C.prototype.addListener=function(ne,ue){return N(this,ne,ue,!1)},C.prototype.on=C.prototype.addListener,C.prototype.prependListener=function(ne,ue){return N(this,ne,ue,!0)};function F(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function j(ee,ne,ue){var se={fired:!1,wrapFn:void 0,target:ee,type:ne,listener:ue},ce=F.bind(se);return ce.listener=ue,se.wrapFn=ce,ce}C.prototype.once=function(ne,ue){return u(ue),this.on(ne,j(this,ne,ue)),this},C.prototype.prependOnceListener=function(ne,ue){return u(ue),this.prependListener(ne,j(this,ne,ue)),this},C.prototype.removeListener=function(ne,ue){var se,ce,he,ie,fe;if(u(ue),ce=this._events,ce===void 0)return this;if(se=ce[ne],se===void 0)return this;if(se===ue||se.listener===ue)--this._eventsCount===0?this._events=Object.create(null):(delete ce[ne],ce.removeListener&&this.emit("removeListener",ne,se.listener||ue));else if(typeof se!="function"){for(he=-1,ie=se.length-1;ie>=0;ie--)if(se[ie]===ue||se[ie].listener===ue){fe=se[ie].listener,he=ie;break}if(he<0)return this;he===0?se.shift():re(se,he),se.length===1&&(ce[ne]=se[0]),ce.removeListener!==void 0&&this.emit("removeListener",ne,fe||ue)}return this},C.prototype.off=C.prototype.removeListener,C.prototype.removeAllListeners=function(ne){var ue,se,ce;if(se=this._events,se===void 0)return this;if(se.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):se[ne]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete se[ne]),this;if(arguments.length===0){var he=Object.keys(se),ie;for(ce=0;ce<he.length;++ce)ie=he[ce],ie!=="removeListener"&&this.removeAllListeners(ie);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(ue=se[ne],typeof ue=="function")this.removeListener(ne,ue);else if(ue!==void 0)for(ce=ue.length-1;ce>=0;ce--)this.removeListener(ne,ue[ce]);return this};function J(ee,ne,ue){var se=ee._events;if(se===void 0)return[];var ce=se[ne];return ce===void 0?[]:typeof ce=="function"?ue?[ce.listener||ce]:[ce]:ue?oe(ce):Y(ce,ce.length)}C.prototype.listeners=function(ne){return J(this,ne,!0)},C.prototype.rawListeners=function(ne){return J(this,ne,!1)},C.listenerCount=function(ee,ne){return typeof ee.listenerCount=="function"?ee.listenerCount(ne):K.call(ee,ne)},C.prototype.listenerCount=K;function K(ee){var ne=this._events;if(ne!==void 0){var ue=ne[ee];if(typeof ue=="function")return 1;if(ue!==void 0)return ue.length}return 0}C.prototype.eventNames=function(){return this._eventsCount>0?D(this._events):[]};function Y(ee,ne){for(var ue=new Array(ne),se=0;se<ne;++se)ue[se]=ee[se];return ue}function re(ee,ne){for(;ne+1<ee.length;ne++)ee[ne]=ee[ne+1];ee.pop()}function oe(ee){for(var ne=new Array(ee.length),ue=0;ue<ne.length;++ue)ne[ue]=ee[ue].listener||ee[ue];return ne}function te(ee,ne){return new Promise(function(ue,se){function ce(ie){ee.removeListener(ne,he),se(ie)}function he(){typeof ee.removeListener=="function"&&ee.removeListener("error",ce),ue([].slice.call(arguments))}pe(ee,ne,he,{once:!0}),ne!=="error"&&le(ee,ce,{once:!0})})}function le(ee,ne,ue){typeof ee.on=="function"&&pe(ee,"error",ne,ue)}function pe(ee,ne,ue,se){if(typeof ee.on=="function")se.once?ee.once(ne,ue):ee.on(ne,ue);else if(typeof ee.addEventListener=="function")ee.addEventListener(ne,function ce(he){se.once&&ee.removeEventListener(ne,ce),ue(he)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof ee)}return events.exports}var hasRequiredEBMLReader;function requireEBMLReader(){if(hasRequiredEBMLReader)return EBMLReader;hasRequiredEBMLReader=1;var A=EBMLReader&&EBMLReader.__extends||function(){var O=function(C,i){return O=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(u,$){u.__proto__=$}||function(u,$){for(var N in $)Object.prototype.hasOwnProperty.call($,N)&&(u[N]=$[N])},O(C,i)};return function(C,i){if(typeof i!="function"&&i!==null)throw new TypeError("Class extends value "+String(i)+" is not a constructor or null");O(C,i);function u(){this.constructor=C}C.prototype=i===null?Object.create(i):(u.prototype=i.prototype,new u)}}();Object.defineProperty(EBMLReader,"__esModule",{value:!0});var B=requireEvents(),D=requireTools(),M=function(O){A(C,O);function C(){var i=O.call(this)||this;return i.logGroup="",i.hasLoggingStarted=!1,i.metadataloaded=!1,i.chunks=[],i.stack=[],i.segmentOffset=0,i.last2SimpleBlockVideoTrackTimecode=[0,0],i.last2SimpleBlockAudioTrackTimecode=[0,0],i.lastClusterTimecode=0,i.lastClusterPosition=0,i.timecodeScale=1e6,i.metadataSize=0,i.metadatas=[],i.cues=[],i.firstVideoBlockRead=!1,i.firstAudioBlockRead=!1,i.currentTrack={TrackNumber:-1,TrackType:-1,DefaultDuration:null,CodecDelay:null},i.trackTypes=[],i.trackDefaultDuration=[],i.trackCodecDelay=[],i.trackInfo={type:"nothing"},i.ended=!1,i.logging=!1,i.use_duration_every_simpleblock=!1,i.use_webp=!1,i.use_segment_info=!0,i.drop_default_duration=!0,i}return C.prototype.stop=function(){for(this.ended=!0,this.emit_segment_info();this.stack.length;)this.stack.pop(),this.logging&&console.groupEnd();this.logging&&this.hasLoggingStarted&&this.logGroup&&console.groupEnd()},C.prototype.emit_segment_info=function(){var i=this.chunks;if(this.chunks=[],this.metadataloaded){if(!this.use_segment_info)return;var N=this.lastClusterTimecode,F=this.duration,j=this.timecodeScale;this.emit("cluster",{timecode:N,data:i}),this.emit("duration",{timecodeScale:j,duration:F})}else{this.metadataloaded=!0,this.metadatas=i;var u=this.trackTypes.indexOf(1),$=this.trackTypes.indexOf(2);if(this.trackInfo=u>=0&&$>=0?{type:"both",trackNumber:u}:u>=0?{type:"video",trackNumber:u}:$>=0?{type:"audio",trackNumber:$}:{type:"nothing"},!this.use_segment_info)return;this.emit("metadata",{data:i,metadataSize:this.metadataSize})}},C.prototype.read=function(i){var u=this,$=!1;if(!this.ended){if(i.type==="m")if(i.isEnd)this.stack.pop();else{var N=this.stack[this.stack.length-1];if(N!=null&&N.level>=i.level){this.stack.pop(),this.logging&&console.groupEnd(),N.dataEnd=i.dataEnd,N.dataSize=i.dataEnd-N.dataStart,N.unknownSize=!1;var F=Object.assign({},N,{name:N.name,type:N.type,isEnd:!0});this.chunks.push(F)}this.stack.push(i)}if(i.type==="m"&&i.name=="Segment")this.segmentOffset!=0&&console.warn("Multiple segments detected!"),this.segmentOffset=i.dataStart,this.emit("segment_offset",this.segmentOffset);else if(i.type==="b"&&i.name==="SimpleBlock"){var j=D.ebmlBlock(i.data),J=j.timecode,K=j.trackNumber,Y=j.frames;if(this.trackTypes[K]===1){if(!this.firstVideoBlockRead&&(this.firstVideoBlockRead=!0,this.trackInfo.type==="both"||this.trackInfo.type==="video")){var re=this.lastClusterTimecode+J;this.cues.push({CueTrack:K,CueClusterPosition:this.lastClusterPosition,CueTime:re}),this.emit("cue_info",{CueTrack:K,CueClusterPosition:this.lastClusterPosition,CueTime:this.lastClusterTimecode}),this.emit("cue",{CueTrack:K,CueClusterPosition:this.lastClusterPosition,CueTime:re})}this.last2SimpleBlockVideoTrackTimecode=[this.last2SimpleBlockVideoTrackTimecode[1],J]}else if(this.trackTypes[K]===2){if(!this.firstAudioBlockRead&&(this.firstAudioBlockRead=!0,this.trackInfo.type==="audio")){var re=this.lastClusterTimecode+J;this.cues.push({CueTrack:K,CueClusterPosition:this.lastClusterPosition,CueTime:re}),this.emit("cue_info",{CueTrack:K,CueClusterPosition:this.lastClusterPosition,CueTime:this.lastClusterTimecode}),this.emit("cue",{CueTrack:K,CueClusterPosition:this.lastClusterPosition,CueTime:re})}this.last2SimpleBlockAudioTrackTimecode=[this.last2SimpleBlockAudioTrackTimecode[1],J]}this.use_duration_every_simpleblock&&this.emit("duration",{timecodeScale:this.timecodeScale,duration:this.duration}),this.use_webp&&Y.forEach(function(oe){var te=oe.slice(3,6).toString("hex");if(te==="9d012a"){var le=D.VP8BitStreamToRiffWebPBuffer(oe),pe=new Blob([le],{type:"image/webp"}),ee=u.duration;u.emit("webp",{currentTime:ee,webp:pe})}})}else i.type==="m"&&i.name==="Cluster"&&i.isEnd===!1?(this.firstVideoBlockRead=!1,this.firstAudioBlockRead=!1,this.emit_segment_info(),this.emit("cluster_ptr",i.tagStart),this.lastClusterPosition=i.tagStart):i.type==="u"&&i.name==="Timecode"?this.lastClusterTimecode=i.value:i.type==="u"&&i.name==="TimecodeScale"?this.timecodeScale=i.value:i.type==="m"&&i.name==="TrackEntry"?i.isEnd?(this.trackTypes[this.currentTrack.TrackNumber]=this.currentTrack.TrackType,this.trackDefaultDuration[this.currentTrack.TrackNumber]=this.currentTrack.DefaultDuration,this.trackCodecDelay[this.currentTrack.TrackNumber]=this.currentTrack.CodecDelay):this.currentTrack={TrackNumber:-1,TrackType:-1,DefaultDuration:null,CodecDelay:null}:i.type==="u"&&i.name==="TrackType"?this.currentTrack.TrackType=i.value:i.type==="u"&&i.name==="TrackNumber"?this.currentTrack.TrackNumber=i.value:i.type==="u"&&i.name==="CodecDelay"?this.currentTrack.CodecDelay=i.value:i.type==="u"&&i.name==="DefaultDuration"?this.drop_default_duration?(console.warn("DefaultDuration detected!, remove it"),$=!0):this.currentTrack.DefaultDuration=i.value:i.name==="unknown"&&console.warn(i);!this.metadataloaded&&i.dataEnd>0&&(this.metadataSize=i.dataEnd),$||this.chunks.push(i),this.logging&&this.put(i)}},Object.defineProperty(C.prototype,"duration",{get:function(){if(this.trackInfo.type==="nothing")return console.warn("no video, no audio track"),0;var i=0,u=0,$=0,N=this.trackDefaultDuration[this.trackInfo.trackNumber];if(typeof N=="number")i=N;else if(this.trackInfo.type==="both")if(this.last2SimpleBlockAudioTrackTimecode[1]>this.last2SimpleBlockVideoTrackTimecode[1]){i=(this.last2SimpleBlockAudioTrackTimecode[1]-this.last2SimpleBlockAudioTrackTimecode[0])*this.timecodeScale;var F=this.trackCodecDelay[this.trackTypes.indexOf(2)];typeof F=="number"&&(u=F),$=this.last2SimpleBlockAudioTrackTimecode[1]}else{i=(this.last2SimpleBlockVideoTrackTimecode[1]-this.last2SimpleBlockVideoTrackTimecode[0])*this.timecodeScale;var F=this.trackCodecDelay[this.trackTypes.indexOf(1)];typeof F=="number"&&(u=F),$=this.last2SimpleBlockVideoTrackTimecode[1]}else if(this.trackInfo.type==="video"){i=(this.last2SimpleBlockVideoTrackTimecode[1]-this.last2SimpleBlockVideoTrackTimecode[0])*this.timecodeScale;var F=this.trackCodecDelay[this.trackInfo.trackNumber];typeof F=="number"&&(u=F),$=this.last2SimpleBlockVideoTrackTimecode[1]}else if(this.trackInfo.type==="audio"){i=(this.last2SimpleBlockAudioTrackTimecode[1]-this.last2SimpleBlockAudioTrackTimecode[0])*this.timecodeScale;var F=this.trackCodecDelay[this.trackInfo.trackNumber];typeof F=="number"&&(u=F),$=this.last2SimpleBlockAudioTrackTimecode[1]}var j=(this.lastClusterTimecode+$)*this.timecodeScale+i-u,J=j/this.timecodeScale;return Math.floor(J)},enumerable:!1,configurable:!0}),C.prototype.addListener=function(i,u){return O.prototype.addListener.call(this,i,u)},C.prototype.put=function(i){this.hasLoggingStarted||(this.hasLoggingStarted=!0,this.logging&&this.logGroup&&console.groupCollapsed(this.logGroup)),i.type==="m"?i.isEnd?console.groupEnd():console.group(i.name+":"+i.tagStart):i.type==="b"?console.log(i.name,i.type):console.log(i.name,i.tagStart,i.type,i.value)},C}(B.EventEmitter);return EBMLReader.default=M,EBMLReader}var hasRequiredEbml;function requireEbml(){return hasRequiredEbml||(hasRequiredEbml=1,function(A){var B=ebml&&ebml.__createBinding||(Object.create?function(u,$,N,F){F===void 0&&(F=N),Object.defineProperty(u,F,{enumerable:!0,get:function(){return $[N]}})}:function(u,$,N,F){F===void 0&&(F=N),u[F]=$[N]}),D=ebml&&ebml.__exportStar||function(u,$){for(var N in u)N!=="default"&&!Object.prototype.hasOwnProperty.call($,N)&&B($,u,N)};Object.defineProperty(A,"__esModule",{value:!0}),A.tools=A.Reader=A.Encoder=A.Decoder=void 0,D(requireEBML(),A);var M=requireEBMLDecoder();A.Decoder=M.default;var O=requireEBMLEncoder();A.Encoder=O.default;var C=requireEBMLReader();A.Reader=C.default;var i=requireTools();A.tools=i}(ebml)),ebml}var hasRequiredLib;function requireLib(){if(hasRequiredLib)return lib;hasRequiredLib=1;var A=lib&&lib.__awaiter||function(O,C,i,u){function $(N){return N instanceof i?N:new i(function(F){F(N)})}return new(i||(i=Promise))(function(N,F){function j(Y){try{K(u.next(Y))}catch(re){F(re)}}function J(Y){try{K(u.throw(Y))}catch(re){F(re)}}function K(Y){Y.done?N(Y.value):$(Y.value).then(j,J)}K((u=u.apply(O,C||[])).next())})},B=lib&&lib.__generator||function(O,C){var i={label:0,sent:function(){if(N[0]&1)throw N[1];return N[1]},trys:[],ops:[]},u,$,N,F;return F={next:j(0),throw:j(1),return:j(2)},typeof Symbol=="function"&&(F[Symbol.iterator]=function(){return this}),F;function j(K){return function(Y){return J([K,Y])}}function J(K){if(u)throw new TypeError("Generator is already executing.");for(;i;)try{if(u=1,$&&(N=K[0]&2?$.return:K[0]?$.throw||((N=$.return)&&N.call($),0):$.next)&&!(N=N.call($,K[1])).done)return N;switch($=0,N&&(K=[K[0]&2,N.value]),K[0]){case 0:case 1:N=K;break;case 4:return i.label++,{value:K[1],done:!1};case 5:i.label++,$=K[1],K=[0];continue;case 7:K=i.ops.pop(),i.trys.pop();continue;default:if(N=i.trys,!(N=N.length>0&&N[N.length-1])&&(K[0]===6||K[0]===2)){i=0;continue}if(K[0]===3&&(!N||K[1]>N[0]&&K[1]<N[3])){i.label=K[1];break}if(K[0]===6&&i.label<N[1]){i.label=N[1],N=K;break}if(N&&i.label<N[2]){i.label=N[2],i.ops.push(K);break}N[2]&&i.ops.pop(),i.trys.pop();continue}K=C.call(O,i)}catch(Y){K=[6,Y],$=0}finally{u=N=0}if(K[0]&5)throw K[1];return{value:K[0]?K[1]:void 0,done:!0}}};Object.defineProperty(lib,"__esModule",{value:!0});var D=requireEbml();function M(O){return A(this,void 0,void 0,function(){var C,i,u,$,N,F,j,J,K,Y,re,oe;return B(this,function(te){switch(te.label){case 0:if(!O)throw Error("call to fixWebmDuration requires a blob");C=new D.Decoder,i=new D.Reader,u=O.stream(),$=u.getReader(),te.label=1;case 1:return[4,$.read()];case 2:return N=te.sent(),F=N.done,j=N.value,F?(i.stop(),[3,3]):(J=C.decode(j),J=J?.filter(function(le){return le.type!=="unknown"}),J.forEach(function(le){i.read(le)}),j=null,[3,1]);case 3:return K=D.tools.makeMetadataSeekable(i.metadatas,i.duration,i.cues),Y=new Blob([K],{type:O.type}),re=O.slice(i.metadataSize),oe=new Blob([Y,re],{type:O.type}),[2,oe]}})})}return lib.default=M,lib}var libExports=requireLib();const fixWebmDuration=getDefaultExportFromCjs(libExports);class StreamRecorder{#e;#n=!1;#t=!1;#r=0;#o=0;#i=0;#a=0;#c=0;onchange=B=>{};onDurationChange=B=>{};constructor(){}start=async(B="")=>{B||(B=`video_Record_${E$1(Date.now())}`);let D=[];return navigator.mediaDevices.getDisplayMedia({audio:!0,video:!0}).then(M=>{const O=M.getTracks();for(const i of O)i.onended=()=>this.stop();this.#n=!0,this.#t=!1,this.#e=new MediaRecorder(M),this.#e.start();const C=new Date().getTime();this.#r=C,this.#i=C,this.#l(),this.#s(),this.#e.addEventListener("dataavailable",i=>{D.push(i.data)}),this.#e.addEventListener("stop",async()=>{this.#n=!1;const i=new Date().getTime();this.#o=i,this.#a+=i-this.#i,this.#l(),clearInterval(this.#c);const u=M.getTracks();for(const J of u)J.stop();if(this.#e===null)return;const $=new Blob(D,{type:this.#e.mimeType}),N=await fixWebmDuration($),F=URL.createObjectURL(N),j=document.createElement("a");j.href=F,j.download=`${B}.mp4`,j.click(),URL.revokeObjectURL(F),D=[],this.#e=null})})};pause=async()=>{await new Promise(D=>setTimeout(()=>D(!0),300)),this.#e?.pause(),this.#t=!0;const B=new Date().getTime();this.#a+=B-this.#i,this.#l(),clearInterval(this.#c)};resume=async()=>{this.#e?.resume(),this.#t=!1;const B=new Date().getTime();this.#i=B,this.#l(),this.#s()};stop=async()=>{this.#e?.stop()};getDuration=()=>{if(this.#i===0)return 0;let B=this.#a;const D=new Date().getTime();if(this.#n&&this.#t===!1){const M=D-this.#i;this.#i=D,B=B+M}return B};getInfo=()=>({active:this.#n,pause:this.#t,startTime:this.#r,endTime:this.#o,duration:this.#a});#l=()=>{const B=this.getInfo();this.onchange(B)};#s=()=>{clearInterval(this.#c),this.#c=window.setInterval(()=>{this.#a=this.getDuration(),this.onDurationChange(this.#a)},500)}}var l=Object.defineProperty,y=A=>{throw TypeError(A)},q=(A,B,D)=>B in A?l(A,B,{enumerable:!0,configurable:!0,writable:!0,value:D}):A[B]=D,s=(A,B,D)=>q(A,typeof B!="symbol"?B+"":B,D),P=(A,B,D)=>B.has(A)||y("Cannot "+D),n=(A,B,D)=>(P(A,B,"read from private field"),D?D.call(A):B.get(A)),a=(A,B,D)=>B.has(A)?y("Cannot add the same private member more than once"):B instanceof WeakSet?B.add(A):B.set(A,D),d,v,o;class p{constructor(B={}){s(this,"queue",[]),s(this,"timer",0),s(this,"activeIndex",0),s(this,"activePromise"),s(this,"options",{timeout:0}),s(this,"add",(D,M={})=>new Promise(async(O,C)=>{const i=M.timeout||this.options.timeout,u=M.key||n(this,d).call(this),$=M.describe||"";if(this.queue.findIndex(F=>F.key===u)!==-1)return C(`${u} is exist.`);const N={key:u,func:D,describe:$,timeout:i,resolve:O,reject:C};this.queue.unshift(N),this.activePromise||n(this,o).call(this)})),s(this,"clear",()=>{this.queue=[],this.activePromise=void 0,clearTimeout(this.timer)}),s(this,"retry",()=>{n(this,o).call(this)}),a(this,d,()=>(this.activeIndex=this.activeIndex+1,`${this.activeIndex}`)),a(this,v,D=>{const M=this.queue.findIndex(O=>O.key===D);this.queue.splice(M,1)}),a(this,o,async()=>{const D=this.queue.length;if(D===0)return;const M=D-1,O=this.queue[M];this.activePromise=O;const{key:C,func:i,resolve:u,reject:$,timeout:N}=this.activePromise;N&&(this.timer=window.setTimeout(()=>{$(`pr-async-queue: ${C} is timeout.`),n(this,o).call(this)},N)),await i().then(u).catch($).finally(()=>{clearTimeout(this.timer),this.activePromise=void 0,n(this,v).call(this,C),n(this,o).call(this)})}),this.options={timeout:0,...B}}}d=new WeakMap,v=new WeakMap,o=new WeakMap;const enum_iceState={connecting:"连接中",connected:"已连接",disconnected:"已断开",failed:"连接错误",closed:"已关闭"};ht(enum_iceState);class PrResolves{resolvesMap=new Map;index=0;constructor(){}add=(B,D=()=>!1,M=5e3)=>new Promise(O=>{if(D())return O(!0);this.resolvesMap.has(B)||this.resolvesMap.set(B,new Map),this.index++;const u=`${this.index}`;M=Math.max(1e3,M);const $=window.setTimeout(()=>{this.emit(B)},M);this.resolvesMap.get(B)?.set(u,{resolve:O,timer:$})});emit=async B=>{const D=this.resolvesMap.get(B);if(!D)return;const M=[...D.keys()];for(const O of M){const C=D.get(O);C&&(clearTimeout(C.timer),C.resolve(),D.delete(O))}}}class RoomBase{options={appid:"",sdkToken:"",roomId:"",userId:"",earlyId:wt(),callType:0,debug:!1,reportErr:!0,logUrl:"https://logs1.quickvo.org",newPublishAutoSubscribe:!0};sfuPush=0;sfuPull=0;p2pPush=0;p2pPull=0;historical_publish_mediaTypes=[];historical_subscribe_mediaTypes=[];prResolves=new PrResolves;sdk_service_version="1.0.8";sdk_session="";isEarly=!1;isInRoom=!1;asyncQueue;await_remote_publish_users=[];roomState="ready";iceState="closed";createAt=Date.now();cwsIns;peerIns;sfuOffsetAverageQuality=0;transceiverMap=new Map;transceiverTrackMap=new Map;sendChannel;receiveChannel;userMap=new Map;p2pMap=new Map;setLocalStreamActiveMap=new Map;phoneyStreams=new Map;recorder=new StreamRecorder;networkQualityTester=new NetworkQualityTester;mediaDevicesErrInfo={microphoneCamera_audio:"",microphoneCamera_video:"",screenSharing_video:"",screenSharing_audio:""};constructor(B){this.setOptions(B),this.cwsIns=new CallsWebSocket({...B}),this.asyncQueue=new p}hasAsyncTask=B=>{let D=!1;return this.asyncQueue.activePromise?.describe===B&&(D=!0),D===!1&&this.asyncQueue.queue.find(O=>O.describe===B)&&(D=!0),D};createUserUpdateStreams=(B=[])=>{const D={};for(const M of B)D[M]=wt();return D};reportLogs=(B,D="未知错误")=>{const M=this.getOptions(),{appid:O,userId:C,earlyId:i="",logUrl:u,reportErr:$}=M;if(!$)return;const N="web",F=j=>({ws_c_timeout:0,webrtc_c_timeout:1,join_room_error:2,publish_error:3,subscribe_error:4,close_track_error:5,heartbeat_e_timeout:6,heartbeat_i_timeout:7,quit_room_error:8})[j].toString();{const j=F(B),J={origin:N,type:j,app_id:O,user_id:C,ins_id:i,desc:D},K=btoa(encodeURI(JSON.stringify(J))),Y=`${u}/upload/log?log_key=${K}`;{const re=localStorage.getItem("#quickvo.logs")||JSON.stringify([]),te=new TextEncoder().encode(re),le=pako.deflate(te,{gzip:!0});this.options.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->quickvo: reportLogs",{obj:J,url:Y,size:it(le.byteLength)}),fetch(Y,{headers:{"Content-Type":"multipart/form-data"},method:"POST",body:le})}}};initPhoneyStreams=(B,D=[])=>{D.length===0&&(D=mediaType_keys);for(const M of D){const O=this.phoneyStreams.get(M);if(O){const C=O.getTracks();for(const i of C)i.stop()}switch(M){case"microphoneCamera_audio":this.phoneyStreams.set("microphoneCamera_audio",createMutedAudioStream(B));break;case"microphoneCamera_video":this.phoneyStreams.set("microphoneCamera_video",createFakeVideoStream());break;case"screenSharing_audio":this.phoneyStreams.set("screenSharing_audio",createMutedAudioStream(B));break;case"screenSharing_video":this.phoneyStreams.set("screenSharing_video",createFakeVideoStream());break}}};getPhoneyStreams=B=>this.phoneyStreams.get(B);getRoomInfo=()=>{const{options:B,roomState:D,createAt:M}=this;return{...B,roomState:D,createAt:M}};setRoomState=B=>{if(this.roomState===B)return;this.roomState=B;const D=enum_roomState[B],M={state:B,stateStr:D};this.cwsIns.emitNotify("onRoomState",{code:200,data:M,desc:"room state is change."})};setIceState=B=>{if(this.iceState===B)return;this.iceState=B;const D=enum_iceState[B],M={state:B,stateStr:D};this.cwsIns.emitNotify("onIceState",{code:200,data:M,desc:"ice state is change."})};setOptions=B=>(this.options={...this.options,...B},this.options);getOptions=()=>this.options;stopStream=async B=>{const D=B.getTracks();for(const M of D)M.stop()};getMediaDevicesErrInfo=async()=>{try{const B=await navigator.mediaDevices.enumerateDevices();B.find(M=>M.kind==="audioinput")||(this.mediaDevicesErrInfo.microphoneCamera_audio="audioinput is not available."),B.find(M=>M.kind==="videoinput")||(this.mediaDevicesErrInfo.microphoneCamera_video="videoinput is not available.")}catch(B){this.options.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->quickvo: getMediaDevicesErrInfo is error.",B)}return this.mediaDevicesErrInfo};getUserMediaKey=(B,D)=>`${B}-${D}`;getCallAction=async B=>{let D="";const M=C=>B.findIndex(({type:u,enabled:$=!0})=>u===C&&$)===-1?"0":"1";return D=`${M(0)}${D}`,D=`${M(1)}${D}`,D=`${M(2)}${D}`,D=`${M(3)}${D}`,parseInt(D,2)};getCallActionMap=(B=0)=>{const M=Number(B).toString(2).padStart(4,"0").split(""),[O,C,i,u]=M;return{microphoneCamera_audio:!!Number(u),microphoneCamera_video:!!Number(i),screenSharing_video:!!Number(C),screenSharing_audio:!!Number(O)}};getBanBehaviorMap=(B=0)=>{const M=Number(B).toString(2).padStart(4,"0").split(""),[O,C,i,u]=M;return{microphoneCamera_audio:!!Number(u),microphoneCamera_video:!!Number(i),screenSharing_video:!!Number(C),screenSharing_audio:!!Number(O)}};getAverageVolume=(B,D)=>{B.getByteFrequencyData(D);let M=0;for(let C=0;C<D.length;C++)M+=D[C];return Math.ceil(M/D.length)};getTrackNamesFormTracks=(B,D=[],M="trackName")=>{const O=[];for(const C of B){const{type:i}=C;if(D.length===0||D.includes(i)){const u=C[M];u&&O.push(`${u}`)}}return O};usersFilter=B=>dt(B,["id","isSelf","isOwner","joinTime","tracks","network","permissions","isPublished","callAction","callActionStr","callActionMap","banBehavior","banBehaviorStr","banBehaviorMap","useP2P"]).sort((O,C)=>O.id.localeCompare(C.id,"en"))}var m=Object.defineProperty,G=(A,B,D)=>B in A?m(A,B,{enumerable:!0,configurable:!0,writable:!0,value:D}):A[B]=D,e=(A,B,D)=>G(A,typeof B!="symbol"?B+"":B,D);let g$1=class{constructor(B,D){e(this,"inputStream",new MediaStream),e(this,"outputStream",new MediaStream),e(this,"inputGain",1),e(this,"enhanceGain",1),e(this,"bgsGain",1),e(this,"bgmGain",1),e(this,"outputGain",1),e(this,"mixAudioMap",new Map),e(this,"audioContext",new AudioContext),e(this,"sourceNode"),e(this,"inputGainNode"),e(this,"enhanceGainNode"),e(this,"bgsGainNode"),e(this,"bgmGainNode"),e(this,"analyserNode"),e(this,"analyserArrayData"),e(this,"outputGainNode"),e(this,"destinationNode"),e(this,"filterStream",M=>M),e(this,"stop",()=>{{const M=this.inputStream.getTracks();for(const O of M)O.stop(),this.inputStream.removeTrack(O)}}),e(this,"getStream",()=>this.filterStream(this.outputStream)),e(this,"setMute",(M=!0)=>{M?this.analyserNode.disconnect(this.outputGainNode):this.analyserNode.connect(this.outputGainNode)}),e(this,"setInputGain",M=>{this.inputGain=M,this.inputGainNode.gain.setValueAtTime(M,this.audioContext.currentTime)}),e(this,"setEnhanceGain",async M=>{this.enhanceGain=M+1,this.enhanceGainNode.gain.setValueAtTime(this.enhanceGain,this.audioContext.currentTime)}),e(this,"setBgsGain",M=>{this.bgsGain=M,this.bgsGainNode.gain.setValueAtTime(M,this.audioContext.currentTime)}),e(this,"setBgmGain",M=>{this.bgmGain=M,this.bgmGainNode.gain.setValueAtTime(M,this.audioContext.currentTime)}),e(this,"setOutputGain",M=>{this.outputGain=M,this.outputGainNode.gain.setValueAtTime(this.outputGain,this.audioContext.currentTime)}),e(this,"getVolume",()=>{const{analyserNode:M,analyserArrayData:O}=this;M.getByteFrequencyData(O);let C=0;for(let i=0;i<O.length;i++)C+=O[i];return Math.ceil(C/O.length)}),e(this,"mixAudio",(M,O="bgm")=>new Promise(async(C,i)=>{try{{const N=this.mixAudioMap.get(O);N&&N.stop()}const u=O==="bgs"?this.bgsGainNode:this.bgmGainNode,$=this.audioContext.createBufferSource();this.mixAudioMap.set(O,$),$.buffer=M,$.connect(u),$.onended=()=>{$.disconnect(u),this.mixAudioMap.delete(O),C(!0)},$.start(0)}catch(u){i(u)}})),e(this,"mixAudioStop",M=>{const O=this.mixAudioMap.get(M);O?.stop()}),e(this,"changeMix",(M,O)=>{const C=M==="bgs"?this.bgsGainNode:this.bgmGainNode;O?C.connect(this.destinationNode):C.disconnect(this.destinationNode)}),D&&(this.audioContext=D),this.inputStream=B,this.sourceNode=this.audioContext.createMediaStreamSource(this.inputStream),this.inputGainNode=this.audioContext.createGain(),this.inputGainNode.gain.setValueAtTime(this.inputGain,this.audioContext.currentTime),this.enhanceGainNode=this.audioContext.createGain(),this.enhanceGainNode.gain.setValueAtTime(this.enhanceGain,this.audioContext.currentTime),this.bgsGainNode=this.audioContext.createGain(),this.bgsGainNode.gain.setValueAtTime(this.bgsGain,this.audioContext.currentTime),this.bgmGainNode=this.audioContext.createGain(),this.bgmGainNode.gain.setValueAtTime(this.bgmGain,this.audioContext.currentTime),this.analyserNode=this.audioContext.createAnalyser(),this.analyserNode.fftSize=512,this.analyserArrayData=new Uint8Array(this.analyserNode.frequencyBinCount),this.outputGainNode=this.audioContext.createGain(),this.outputGainNode.gain.setValueAtTime(this.outputGain,this.audioContext.currentTime),this.destinationNode=this.audioContext.createMediaStreamDestination(),this.outputStream=this.destinationNode.stream;{const{sourceNode:M,inputGainNode:O,enhanceGainNode:C,bgsGainNode:i,bgmGainNode:u,analyserNode:$,outputGainNode:N,destinationNode:F}=this;M.connect(O),O.connect(C),C.connect($),i.connect($),u.connect($),C.connect(F),i.connect(F),u.connect(F),$.connect(N),N.connect(this.audioContext.destination)}this.setMute(!0),this.audioContext.resume()}};class RoomMedias extends RoomBase{#e=[];#n=new Map;#t=new Map;#r=new Map;#o=new Map;#i=new Map;localStreamsActionMap=new Map;#a=new Map;audioContext=new(window.AudioContext||window.webkitAudioContext);constructor(B){super(B),this.#u(),this.#l(),this.#c(),document.addEventListener("click",()=>{this.audioContext?.state==="suspended"&&this.audioContext.resume()})}initMediaPhoneyStreams=(B=[])=>this.initPhoneyStreams(this.audioContext,B);initLocalStreamsFilter=()=>{for(const B of mediaType_keys){const D=async M=>M;this.#a.set(B,D)}};setLocalFilterStream=(B,D)=>{this.#a.set(B,D)};#c=()=>{this.#t.set("microphoneCamera_audio",{autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0}),this.#t.set("microphoneCamera_video",{frameRate:{min:10,ideal:30}}),this.#t.set("screenSharing_video",{frameRate:{min:10,ideal:30}}),this.#t.set("screenSharing_audio",{autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0})};#l=()=>{this.#n.set("audioinput","default"),this.#n.set("videoinput","default"),this.#n.set("audiooutput","default")};emitNotifyUpdateUsersStreams=async B=>{this.cwsIns.emitNotify("onRoomUsersStreams",{code:200,data:B,desc:"users streams is change."})};initUserMediaStreamContext=async(B,D,M,O)=>{const[C]=M.getTracks();if(M.active===!1||!C)return;O&&this.removeUserMediaStreamContext(B,D);const i=this.getUserMediaKey(B,D),{kind:u}=C;switch(u){case"audio":{const $=new MediaStream;$.addTrack(C);const N=new g$1($,this.audioContext);this.#r.set(i,N)}break;case"video":{const $=new VideoMediaContext(C);this.#o.set(i,$)}break}};getUserMediaStreamContext=(B,D)=>{const M=this.getUserMediaKey(B,D);if(["microphoneCamera_audio","screenSharing_audio"].includes(D))return this.#r.get(M);if(["microphoneCamera_video","screenSharing_video"].includes(D))return this.#o.get(M)};getUserAudioMediaStreamContext=(B,D)=>{const M=this.getUserMediaKey(B,D);return this.#r.get(M)};removeUserMediaStreamContext=(B,D)=>{const M=this.getUserMediaKey(B,D);if(["microphoneCamera_audio","screenSharing_audio"].includes(D))return this.#r.get(M)?.stop(),this.#r.delete(M);if(["microphoneCamera_video","screenSharing_video"].includes(D))return this.#o.get(M)?.stop(),this.#o.get(M)};getUserStream=(B,D)=>this.getUserMediaStreamContext(B,D)?.getStream()||new MediaStream;getUserStreams=(B,D=[])=>{D.length===0&&(D=mediaType_keys);const M={};for(const O of D){const C=this.getUserStream(B,O);M[O]=C}return M};removeUserStreams=async(B,D=[])=>{D.length===0&&(D=mediaType_keys);for(const M of D)this.removeUserMediaStreamContext(B,M)};clearUserStreams=()=>{{const B=this.#r.values();for(const D of B)D.stop();this.#r=new Map}{const B=this.#o.values();for(const D of B)D.stop();this.#o=new Map}};setMediaTrackConstraints=async(B,D)=>{this.#t.set(B,D);const M=await this.getLocalStream(B);if(!M)return;const O=M.getTracks();if(O.length!==0)for(const C of O){const i=C.getConstraints(),$={...this.#t.get(B),...i,...D};await C.applyConstraints($)}};stopLocalStreams=async(B=[])=>{B.length===0&&(B=mediaType_keys);for(const D of B){const M=this.#i.get(D);M&&await this.stopStream(M),this.#i.delete(D)}};addLocalStream=(B,D)=>{const M=this.#i.get(B);M&&this.stopStream(M),this.#i.set(B,D)};initLocalStream=async B=>{switch(B){case"microphoneCamera_audio":{const D=this.#n.get("audioinput"),M=this.#t.get("microphoneCamera_audio"),O=await navigator.mediaDevices.getUserMedia({audio:{deviceId:D,...M},video:!1});this.addLocalStream("microphoneCamera_audio",O)}break;case"microphoneCamera_video":{const D=this.#n.get("videoinput"),M=this.#t.get("microphoneCamera_video"),O=await navigator.mediaDevices.getUserMedia({audio:!1,video:{deviceId:D,...M}});this.addLocalStream("microphoneCamera_video",O)}break;case"microphoneCamera":{const D=this.#n.get("audioinput"),M=this.#n.get("videoinput"),O=this.#t.get("microphoneCamera_audio"),C=this.#t.get("microphoneCamera_video"),u=(await navigator.mediaDevices.getUserMedia({audio:{deviceId:D,...O},video:{deviceId:M,...C}})).getTracks();for(const $ of u){const{kind:N}=$;if(N==="audio"){const F=new MediaStream;F.addTrack($),this.addLocalStream("microphoneCamera_audio",F)}if(N==="video"){const F=new MediaStream;F.addTrack($),this.addLocalStream("microphoneCamera_video",F)}}}break;case"screenSharing_audio":{const D=this.#t.get("screenSharing_audio"),O=(await navigator.mediaDevices.getDisplayMedia({audio:!0,video:!0,...D})).getTracks();for(const C of O){const{kind:i}=C;if(i==="audio"){const u=new MediaStream;u.addTrack(C),this.addLocalStream("screenSharing_audio",u)}}}break;case"screenSharing_video":{const D=this.#t.get(B),O=(await navigator.mediaDevices.getDisplayMedia({audio:!1,video:!0,...D})).getTracks();for(const C of O){const{kind:i}=C;if(i==="video"){const u=new MediaStream;u.addTrack(C),this.addLocalStream("screenSharing_video",u)}}}break;case"screenSharing":{const D=this.#t.get("screenSharing_audio"),M=this.#t.get("screenSharing_video"),C=(await navigator.mediaDevices.getDisplayMedia({audio:!0,video:!0,...D,...M})).getTracks();for(const i of C){const{kind:u}=i;if(u==="audio"){const $=new MediaStream;$.addTrack(i),this.addLocalStream("screenSharing_audio",$)}if(u==="video"){const $=new MediaStream;$.addTrack(i),this.addLocalStream("screenSharing_video",$)}}}break}};getLocalStream=async B=>{const D=this.#i.get(B),M=this.#a.get(B);let O=D;return D&&M&&(O=await M(D)),O};getLocalStreams=async(B=[])=>{B.length===0&&(B=mediaType_keys);const D={};for(const M of B)D[M]=await this.getLocalStream(M);return D};#s=async()=>!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices?(console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->quickvo: 不支持 enumerateDevices"),[]):(await navigator.mediaDevices.enumerateDevices().then(B=>{const D=B.filter(M=>!["communications"].includes(M.deviceId));this.#e=D.sort((M,O)=>M.label.localeCompare(O.label,"zh-Hans-CN",{sensitivity:"accent"}))}).catch(function(B){console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->quickvo: getEnumerateDevices is err",B)}),this.#e);#u=()=>{navigator.mediaDevices&&(navigator.mediaDevices.ondevicechange=async()=>{await this.#s(),this.cwsIns.emitNotify("onDevicechange",{code:200,data:{},desc:"device is change."})}),this.#s()};getMediaDeviceKind=B=>this.#n.get(B);changeAudiooutput=async()=>{try{const B=this.#n.get("audiooutput");await this.audioContext.setSinkId(B)}catch(B){console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->quickvo: setSinkId is error.",B)}};setDeviceKind=(B,D)=>{this.#n.set(B,D)};setAudioOutputDevice=B=>this.setDeviceKind("audiooutput",B);getEnumerateDevices=async B=>(await this.#s(),this.#e.filter(M=>M.kind===B));getEnumerateAudioinputDevices=()=>this.getEnumerateDevices("audioinput");getEnumerateAudioOutputDevices=()=>this.getEnumerateDevices("audiooutput");getEnumerateVideoinputDevices=()=>this.getEnumerateDevices("videoinput")}const getNetworkQuality=(A,B,D)=>{const M=Number(A),O=Number(B),C=Number(D);let i=0;return M<.03&&O<100&&C<.05?i=5:M<.06&&O<160&&C<.1?i=4:M<.1&&O<250&&C<.15?i=3:M<.15&&O<400&&C<.2?i=2:i=1,Number(i)};class PeerAnalyzeStats{pc;network={inboundBytes:0,outboundBytes:0,lostRate:"0.00",roundTripTime:"0",jitter:"0",quality:0,averageQuality:0};reports=[];averageQualitys=[];timer=0;constructor(){}onNetwork=B=>{};getNetwork=()=>this.network;getAverageQuality=()=>this.network.averageQuality;start=B=>{this.stop(),this.network={inboundBytes:0,outboundBytes:0,lostRate:"0.00",roundTripTime:"0",jitter:"0",quality:0,averageQuality:0},this.reports=[],this.averageQualitys=[],this.pc=B,clearInterval(this.timer);const D=async()=>{this.pc?.connectionState==="connected"&&this.analyzeStats()};this.timer=window.setInterval(D,1*1e3)};analyzeStats=async()=>{try{if(!this.pc)return;const B=await this.pc.getStats(),D=["inbound-rtp","remote-inbound-rtp","outbound-rtp","transport"],O=[...B.values()].filter(ne=>D.includes(ne.type));let C=0,i=0,u=0,$=0,N=0,F=0,j=[],J=[];for(const ne of this.reports){const{packetsSent:ue,packetsLost:se}=ne;ue&&(u+=ue),se&&($+=se)}this.reports=O;for(const ne of this.reports){const{bytesSent:ue,bytesReceived:se,packetsSent:ce,packetsLost:he,roundTripTime:ie,jitter:fe}=ne;ue&&(i=ue),se&&(C=se),ce&&(N+=ce),he&&(F+=he),ie&&j.push((ie*100).toFixed(2)),fe&&J.push(fe.toFixed(2))}J.sort().reverse(),j.sort().reverse();const K=N-u,Y=F-$,re=K===0?"0.00":Math.max(0,Y/K).toFixed(2),[oe="0"]=j,[te="0"]=J,le=getNetworkQuality(re,oe,te);this.averageQualitys.unshift(le),this.averageQualitys=this.averageQualitys.slice(0,10);const pe=this.averageQualitys.length===10?Math.round(this.averageQualitys.reduce((ne,ue)=>ne+ue)/this.averageQualitys.length):0,ee={outboundBytes:i,inboundBytes:C,lostRate:re,roundTripTime:oe,jitter:te,quality:le,averageQuality:pe};this.network=ee,this.onNetwork(this.network)}catch(B){console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->quickvo: analyzeStats is err.",B)}};getReports=async(B=[])=>B.length===0?this.reports:this.reports.filter(D=>B.includes(D.mid));stop=()=>{clearInterval(this.timer)}}class P2P{prResolves=new PrResolves;phoneyStreams=new Map;recv_peer_ins;recv_icecandidates=[];recv_candidate_collected=!1;recv_transceiverMap=new Map;recvPeerAnalyzeStatsIns=new PeerAnalyzeStats;send_peer_ins;send_icecandidates=[];send_candidate_collected=!1;send_transceiverMap=new Map;sendPeerAnalyzeStatsIns=new PeerAnalyzeStats;tracks=[];reports=[];getPeerStatsTimer=0;constructor(B){this.phoneyStreams=B}onSendPeerNetwork=B=>{};onRecvPeerNetwork=B=>{};getPhoneyStreams=B=>this.phoneyStreams.get(B);sendIceConnected=()=>{const B=()=>this.send_peer_ins.iceConnectionState==="connected";return this.prResolves.add("sendIceConnected",B)};recvIceConnected=()=>{const B=()=>this.recv_peer_ins.iceConnectionState==="connected";return this.prResolves.add("recvIceConnected",B)};sendCandidateCollected=()=>{const B=()=>this.send_candidate_collected;return this.prResolves.add("sendCandidateCollected",B)};recvCandidateCollected=()=>{const B=()=>this.recv_candidate_collected;return this.prResolves.add("recvCandidateCollected",B)};getSendIcecandidates=async()=>(await this.sendCandidateCollected(),this.send_icecandidates);getRecvIcecandidates=async()=>(await this.recvCandidateCollected(),this.recv_icecandidates);setOffered=()=>{const B=()=>this.send_peer_ins?.remoteDescription;return this.prResolves.add("setOffered",B)};initSenderPc=async()=>{await this.clearSenderPc(),this.send_peer_ins=new RTCPeerConnection({iceServers:[{urls:"stun:stun.cloudflare.com:3478"}]});const B=M=>{M.candidate?this.send_icecandidates.push(M.candidate):(this.send_candidate_collected=!0,this.prResolves.emit("sendCandidateCollected"))};this.send_peer_ins.addEventListener("icecandidate",B);const D=M=>{const O=M.target.connectionState;switch(O){case"connected":console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#00b60f;",`------->quickvo: send_peer_ins: ${O}`),this.prResolves.emit("sendIceConnected");break;case"failed":case"closed":console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#b60000;",`------->quickvo: send_peer_ins: ${O}`),this.send_peer_ins.removeEventListener("icecandidate",B),this.send_peer_ins.removeEventListener("connectionstatechange",D);break;default:console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#b64900;",`------->quickvo: send_peer_ins: ${O}`);break}};this.send_peer_ins.addEventListener("connectionstatechange",D),this.sendPeerAnalyzeStatsIns?.start(this.send_peer_ins)};clearSenderPc=async()=>{this.sendPeerAnalyzeStatsIns.stop(),this.send_icecandidates=[],this.send_candidate_collected=!1,this.send_transceiverMap=new Map,this.send_peer_ins&&this.send_peer_ins.close(),clearInterval(this.getPeerStatsTimer)};initRecvPc=async()=>{await this.clearRecvPc(),this.recv_peer_ins=new RTCPeerConnection({iceServers:[{urls:"stun:stun.cloudflare.com:3478"}]});const B=M=>{M.candidate?this.recv_icecandidates.push(M.candidate):(this.recv_candidate_collected=!0,this.prResolves.emit("recvCandidateCollected"))};this.recv_peer_ins.addEventListener("icecandidate",B);const D=M=>{const O=M.target.connectionState;switch(O){case"connected":console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#00b60f;",`------->quickvo: recv_peer_ins: ${O}`),this.prResolves.emit("recvIceConnected");break;case"failed":case"closed":console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#b60000;",`------->quickvo: recv_peer_ins: ${O}`),this.recv_peer_ins.removeEventListener("icecandidate",B),this.recv_peer_ins.removeEventListener("connectionstatechange",D);break;default:console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#b64900;",`------->quickvo: recv_peer_ins: ${O}`);break}};this.recv_peer_ins.addEventListener("connectionstatechange",D),this.recvPeerAnalyzeStatsIns?.start(this.recv_peer_ins)};clearRecvPc=async()=>{this.recvPeerAnalyzeStatsIns.stop(),this.recv_icecandidates=[],this.recv_candidate_collected=!1,this.recv_transceiverMap=new Map,this.recv_peer_ins&&this.recv_peer_ins.close()};initSenders=async(B=[])=>{const D=this.send_peer_ins.getTransceivers();for(const M of D){const{mid:O}=M,C=B.find($=>$.mid===O);if(!C)continue;const{type:i}=C;if(i===void 0)continue;const u=mediaType_keys[i];M.direction="sendonly",this.send_transceiverMap.set(u,M)}};addSenders=async(B=[])=>{const D=[];for(const M of B){if(this.send_transceiverMap.get(M))continue;const C=this.getPhoneyStreams(M),[i]=C.getTracks(),u=this.send_peer_ins.addTransceiver(i,{direction:"sendonly"});this.send_transceiverMap.set(M,u),D.push(M)}return D};addRecvs=async(B=[])=>{const D=[];for(const M of B)if(!this.recv_transceiverMap.get(M))switch(M){case"microphoneCamera_audio":case"screenSharing_audio":{const C=this.recv_peer_ins.addTransceiver("audio",{direction:"recvonly"});this.recv_transceiverMap.set(M,C),D.push(M)}break;case"microphoneCamera_video":case"screenSharing_video":{const C=this.recv_peer_ins.addTransceiver("video",{direction:"recvonly"});this.recv_transceiverMap.set(M,C),D.push(M)}break}return D};getSenderTracks=async(B=[])=>{const D=[];for(const M of B){const O=this.send_transceiverMap.get(M);if(!O)continue;const{mid:C,sender:i}=O,{track:u}=i;if(!u)continue;const{id:$,enabled:N}=u,F=mediaType_keys.findIndex(K=>K===M),j=wt(),J={type:F,enabled:N,trackName:`web-${F}-${$}`,location:"local",mid:C,key:j,origin:"p2p",mediaType:M};D.push(J)}return D};getRecvTracks=async(B=[])=>{const D=[];for(const M of B){const O=this.recv_transceiverMap.get(M);if(!O)continue;const{mid:C,receiver:i}=O,{track:u}=i;if(!u)continue;const{id:$,enabled:N}=u,F=mediaType_keys.findIndex(K=>K===M),j=wt(),J={type:F,enabled:N,trackName:`web-${F}-${$}`,location:"local",mid:C,key:j};D.push(J)}return D};createOffer=()=>new Promise(async(B,D)=>{try{const M=await this.recv_peer_ins.createOffer();await this.recv_peer_ins.setLocalDescription(M),B(M)}catch(M){D(M)}});setOffer=async B=>{await this.send_peer_ins.setRemoteDescription(B),await this.prResolves.emit("setOffered")};createAnswer=()=>new Promise(async B=>{const D=await this.send_peer_ins.createAnswer();await this.send_peer_ins.setLocalDescription(D),B(D)});addCandidates=async B=>{await this.setOffered();for(const D of B)await this.send_peer_ins.addIceCandidate(D)};setAnswer=async(B,D)=>{await this.recv_peer_ins.setRemoteDescription(B);for(const M of D)await this.recv_peer_ins.addIceCandidate(M)};getTrack=B=>this.recv_transceiverMap.get(B)?.receiver?.track;getSendPeerNetwork=()=>this.sendPeerAnalyzeStatsIns.getNetwork();getRecvPeerNetwork=()=>this.recvPeerAnalyzeStatsIns.getNetwork()}class RoomUsers extends RoomMedias{constructor(B){super(B)}getP2PIns=async B=>this.p2pMap.get(B);getMaxVolumeUser=()=>{const B=Array.from(this.userMap.values(),({id:M})=>M);if(B.length===0)return;let D=[];for(const M of B){const O=this.getUserAudioMediaStreamContext(M,"microphoneCamera_audio");if(!O)continue;const C=O.getVolume();D.push({id:M,volume:C})}return D=D.sort((M,O)=>M.volume-O.volume>0?-1:1),D[0]};setVolume=(B,D,M)=>{this.getUserAudioMediaStreamContext(B,D)?.setInputGain(M)};setEnhanceGain=async(B,D,M)=>{this.getUserAudioMediaStreamContext(B,D)?.setEnhanceGain(M)};setSpeaker=(B,D,M)=>{const O=this.getUserAudioMediaStreamContext(B,D);O?.setOutputGain(M);const C=M===0;try{O?.setMute(C)}catch{}};playBgs=(B,D,M)=>this.getUserAudioMediaStreamContext(B,D)?.mixAudio(M,"bgs");setBgsGain=(B,D,M)=>{this.getUserAudioMediaStreamContext(B,D)?.setBgsGain(M)};stopBgs=(B,D)=>{this.getUserAudioMediaStreamContext(B,D)?.mixAudioStop("bgs")};playBgm=(B,D,M)=>this.getUserAudioMediaStreamContext(B,D)?.mixAudio(M,"bgm");setBgmGain=(B,D,M)=>{this.getUserAudioMediaStreamContext(B,D)?.setBgmGain(M)};stopBgm=(B,D)=>{this.getUserAudioMediaStreamContext(B,D)?.mixAudioStop("bgm")};changBgsMix=(B,D,M)=>{this.getUserAudioMediaStreamContext(B,D)?.changeMix("bgs",M)};changBgmMix=(B,D,M)=>{this.getUserAudioMediaStreamContext(B,D)?.changeMix("bgm",M)};getVolume=(B,D)=>this.getUserAudioMediaStreamContext(B,D)?.getVolume();clearUsers=()=>{this.userMap=new Map,this.p2pMap=new Map};removeUsers=async B=>{for(const D of B)this.userMap.delete(D),this.p2pMap.delete(D),await this.removeUserStreams(D)};createUser=async B=>{const D=Date.now(),M=this.getOptions(),O={id:B,permissions:0,callAction:0,callActionStr:"",callActionMap:{microphoneCamera_audio:!1,microphoneCamera_video:!1,screenSharing_video:!1,screenSharing_audio:!1},banBehavior:0,banBehaviorStr:"",banBehaviorMap:{microphoneCamera_audio:!1,microphoneCamera_video:!1,screenSharing_video:!1,screenSharing_audio:!1},callState:0,isOwner:this.userMap.size===0,isSelf:B===M.userId,isPublished:!1,useP2P:!1,joinTime:D,updateAt:D,network:{egress:0,ingress:0},tracks:[],updateStreams:{microphoneCamera_audio:!1,microphoneCamera_video:!1,screenSharing_video:!1,screenSharing_audio:!1}};this.userMap.set(B,O);{const C=new P2P(this.phoneyStreams);this.p2pMap.set(B,C)}};getUser=async B=>(this.userMap.has(B)||await this.createUser(B),this.userMap.get(B));getUsers=async(B=[])=>{B.length===0&&(B=[...this.userMap.keys()]);const D=[];for(const M of B){const O=await this.getUser(M);D.push(O)}return D};getAllUserTrackMids=async()=>{const B=await this.getUsers(),D=[];for(const M of B){const{tracks:O=[]}=M;for(const C of O)D.push(C.mid)}return D};getUserTrackByTrackName=async B=>{const D=await this.getUsers(),M=[];for(const O of D){const{tracks:C=[]}=O;for(const i of C){const{trackName:u}=i;B.includes(u)&&M.push(i)}}return M};getUserTrackByMid=async B=>{const D=await this.getUsers();let M;for(const O of D){const{tracks:C=[]}=O;for(const i of C)if(i.mid===B){M=i;break}}return M};getUsersMediaTypeBytrackNames=async B=>{if(B.length===0)return[];const D=[],M=await this.getUsers();for(const O of M){const{id:C,tracks:i=[]}=O,u=[];for(const N of i){const{trackName:F,mediaType:j}=N;!B.includes(F)||!j||u.push(j)}if(u.length===0)continue;const $={userId:C,mediaTypes:u};D.push($)}return D};getUserTrackByUserMediaTypes=async(B=[],D)=>{const M=[],O=await this.getUsers();for(const C of O){const{id:i,tracks:u=[]}=C;let $=[];const N=B.find(F=>F.userId===i);if(N&&($=u.filter(F=>N.mediaTypes.includes(F.mediaType)),$.length!==0)){if(D!==void 0)for(const F of $)F.lastRetry=D;M.push({id:i,tracks:$})}}return M};getAllUserMediaTypes=async()=>{const B=[],D=await this.getUsers();for(const M of D){const{id:O,tracks:C=[],isSelf:i}=M;if(i)continue;const u=Array.from(C,$=>$.mediaType);B.push({userId:O,mediaTypes:u})}return B};checkUserInRoom=B=>this.userMap.has(B);getUsersId=async()=>[...this.userMap.keys()];getSelfInfo=async()=>await this.getUser(this.options.userId);updateIsPublished=async(B,D=!1)=>{const M=await this.getUser(B);M.isPublished=D};setUserUpdateStreams=async(B,D,M=!0)=>{const O=await this.getUser(B),C={microphoneCamera_audio:!1,microphoneCamera_video:!1,screenSharing_video:!1,screenSharing_audio:!1};C[D]=M,O.updateStreams=C};updateUsertracks=async(B,D=[],M)=>{const O=await this.getUser(B);M&&(D=[...O.tracks,...D]),D=D.filter(({mid:u=""})=>u!==""),D=pt(D,["type"]),D=D.sort((u,$)=>u.type-$.type<0?-1:1);for(const u of D)u.userId=B,u.mediaType=mediaType_keys[u.type],u.enabled===void 0&&(u.enabled=!0),u.origin===void 0&&(u.origin="sfu");O.updateStreams={microphoneCamera_audio:!1,microphoneCamera_video:!1,screenSharing_video:!1,screenSharing_audio:!1};const C=dt(O.tracks,["mediaType","enabled","mid","msid","trackName","key"]),i=dt(D,["mediaType","enabled","mid","msid","trackName","key"]);for(const u of mediaType_keys){const $=i.find(j=>j.mediaType===u),N=C.find(j=>j.mediaType===u),F=JSON.stringify($)!==JSON.stringify(N);O.updateStreams[u]=F}O.tracks=D};updateUserCallAction=async(B,D=0)=>{const M=await this.getUser(B);M.callAction=D,M.callActionStr=D.toString(2).padStart(4,"0"),M.callActionMap=this.getCallActionMap(D)};updateUserBehaviors=async(B,D=0)=>{const M=await this.getUser(B);M.banBehavior=D,M.banBehaviorStr=D.toString(2).padStart(4,"0"),M.banBehaviorMap=this.getBanBehaviorMap(D)};updateUserNetwork=async(B,D={egress:5,ingress:5})=>{const M=await this.getUser(B);M.network=D};updateUserPermissions=async(B,D)=>{if(D){const M=await this.getUser(B);M.permissions=D}};updateUserUseP2P=async(B,D)=>{const M=await this.getUser(B);M.useP2P=D};updateUserBase=async B=>{const D=this.getOptions(),M=await this.getUser(B);M.isSelf=B===D.userId,M.updateAt=Date.now()};updateUsers=async B=>{for(const D of B){const{id:M,tracks:O,callAction:C,permissions:i,isPublished:u,useP2P:$}=D;await this.updateUserBase(M),await this.updateIsPublished(M,u),await this.updateUserPermissions(M,i),await this.updateUsertracks(M,O,!0),await this.updateUserCallAction(M,C),await this.updateUserNetwork(M),await this.updateUserUseP2P(M,$)}};emitNotifyUpdateUser=async B=>{const D=await this.getUsers([B]),[M]=this.usersFilter(D);this.cwsIns.emitNotify("onRoomUser",{code:200,data:M,desc:"user info is change."})};emitNotifyUpdateUsers=async()=>{const B=await this.getUsers(),D=this.usersFilter(B);this.cwsIns.emitNotify("onRoomUsers",{code:200,data:D,desc:"all users info is change."})}}class RoomPeer extends RoomUsers{#e=0;peerAnalyzeStatsIns=new PeerAnalyzeStats;offset_inboundBytes=0;offset_outboundBytes=0;constructor(B){super(B),this.initPeer(),this.peerAnalyzeStatsIns.onNetwork=this.#r}saveBoundBytes=B=>{const D=this.peerAnalyzeStatsIns?.getNetwork();D&&(B==="superfluous"&&(this.offset_inboundBytes=-D.inboundBytes,this.offset_outboundBytes=-D.outboundBytes),B==="missing"&&(this.offset_inboundBytes=this.offset_inboundBytes+D.inboundBytes,this.offset_outboundBytes=this.offset_outboundBytes+D.outboundBytes))};getTrafficUse=()=>{const{sfuPush:B,sfuPull:D,p2pPush:M,p2pPull:O}=this;return{sfuPush:B,sfuPull:D,p2pPush:M,p2pPull:O}};initPeer=()=>{clearTimeout(this.#e),this.saveBoundBytes("missing"),this.transceiverMap=new Map,this.peerIns?.close(),this.peerIns=void 0,this.peerIns=new RTCPeerConnection({iceServers:[{urls:"stun:stun.cloudflare.com:3478"}],bundlePolicy:"max-bundle"}),this.#n(),this.initMediaPhoneyStreams(),this.startGetPeerStats()};replaceSenderStream=async(B=[],D)=>{const M=this.getOptions(),{userId:O}=M;B.length===0&&(B=mediaType_keys);for(const C of B){const i=this.transceiverMap.get(C);let u;if(i){const{sender:$}=i;D?u=this.getUserStream(O,C):u=this.getPhoneyStreams(C);const[N]=u.getTracks();await $.replaceTrack(N)}}};getSenderTracks=async(B=[])=>{const D=[];for(const M of B){const O=this.transceiverTrackMap.get(M);O&&D.push(O)}return D};addSenders=async(B=[])=>{B.length===0&&(this.peerIns.addTransceiver("audio",{direction:"sendonly"}),this.peerIns.addTransceiver("video",{direction:"sendonly"}));const D=[];for(const M of B){if(this.transceiverMap.get(M))continue;const C=this.getPhoneyStreams(M),[i]=C.getTracks(),u=this.peerIns.addTransceiver(i,{direction:"sendonly"});this.transceiverMap.set(M,u),D.push(M)}if(B.length===0||D.length!==0){const M=await this.peerIns.createOffer();if(this.options.debug){const O=libExports$1.parse(M.sdp),C=dt(O.media,["mid","msid","type"]);console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#ffffff;","------->quickvo: setLocalDescription",{msidArr:C,sdpJson:O,description:M})}await this.peerIns.setLocalDescription(M);for(const O of B){const C=this.transceiverMap.get(O);if(!C)continue;const{mid:i,sender:u}=C,{track:$}=u;if(!$)continue;const{enabled:N}=$,F=mediaType_keys.findIndex(K=>K===O),j=`WEB-${F}-${wt()}`,J={type:F,mediaType:O,enabled:N,trackName:j,location:"local",mid:i,key:"",origin:"sfu"};this.transceiverTrackMap.set(O,J)}}return D};removeSenders=async(B=[])=>{B.length===0&&(B=mediaType_keys);for(const D of B)this.transceiverMap.has(D)&&(this.transceiverMap.delete(D),this.transceiverTrackMap.delete(D))};stopSenders=(B=[])=>{B.length===0&&(B=mediaType_keys);for(const D of B){if(!this.transceiverMap.has(D))continue;const M=this.transceiverMap.get(D);M?.sender.track?.stop(),M?.stop()}};#n=()=>{const B=()=>{clearTimeout(this.#e),this.setIceState("failed")};this.peerIns.onconnectionstatechange=async D=>{const M=D.target.connectionState;switch(M){case"connected":this.options.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#00b60f;",`------->quickvo: connectionState:${M}`),clearTimeout(this.#e),this.setIceState("connected"),this.prResolves.emit("iceConnected");break;case"disconnected":this.options.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#b64900;",`------->quickvo: connectionState:${M}`),this.setIceState("disconnected"),this.#e=window.setTimeout(B,15*1e3);break;case"failed":{if(this.options.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#b60000;",`------->quickvo: connectionState:${M}`),this.iceState==="closed")return;this.setIceState("failed")}break;case"closed":this.options.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#b60000;",`------->quickvo: connectionState:${M}`),clearTimeout(this.#e),this.setIceState("closed");break;default:this.options.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#b64900;",`------->quickvo: connectionState:${M}`);break}}};iceConnected=()=>{const B=()=>this.peerIns.connectionState==="connected";return this.prResolves.add("iceConnected",B)};stopTransceivers=async B=>{const D=this.peerIns.getTransceivers();for(const M of D){const{mid:O}=M;O&&B.includes(O)&&(M.stop(),this.options.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;",`------->quickvo: transceiver: ${O} is stop.`,M))}};createOffer=async()=>{const B=await this.peerIns.createOffer();if(this.options.debug){const D=libExports$1.parse(B.sdp),M=dt(D.media,["mid","msid","type"]);console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#ffffff;","------->quickvo: createOffer",{msidArr:M,sdpJson:D,description:B})}await this.peerIns.setLocalDescription(B)};createAnswer=async()=>{const B=await this.peerIns.createAnswer();if(this.options.debug){const D=libExports$1.parse(B.sdp),M=dt(D.media,["mid","msid","type"]);console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#ffffff;","------->quickvo: createAnswer",{msidArr:M,sdpJson:D,description:B})}await this.peerIns.setLocalDescription(B)};getSdp=()=>this.peerIns.localDescription?.sdp;setRemoteDescription=async B=>{if(this.options.debug){const D=libExports$1.parse(B.sdp),M=dt(D.media,["mid","msid","type"]);console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#ffffff;","------->quickvo: setRemoteDescription",{msidArr:M,sdpJson:D,description:B})}return await this.peerIns.setRemoteDescription(B),B};setCallStrategy=async(B,D=[])=>{D.length===0&&(D=mediaType_keys);let M="balanced";switch(B){case"qualityPriority":M="maintain-resolution";break;case"fluencyPriority":M="maintain-framerate";break;case"balancedDowngrade":M="balanced";break}const O=await this.getSelfInfo(),C=Array.from(O.tracks,({trackName:u})=>u),i=this.peerIns.getSenders();for(const u of i){const{track:$}=u;if(!$||!C.includes($.id))continue;const N=u.getParameters();u.setParameters({...N,degradationPreference:M})}};setRTCRtpSenderParameters=B=>{try{const D=this.peerIns.getSenders();for(const M of D){const O=M.getParameters();M.setParameters({...O,...B})}}catch(D){console.error("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->quickvo: setRTCRtpSenderParameters is error.",D)}};getPeerNetwork=()=>{const B=this.peerAnalyzeStatsIns?.getNetwork();return JSON.parse(JSON.stringify(B))};getRoomNetwork=()=>{const B=this.peerAnalyzeStatsIns?.getNetwork(),D=JSON.parse(JSON.stringify(B));return D.inboundBytes=Math.max(0,D.inboundBytes+this.offset_inboundBytes),D.outboundBytes=Math.max(0,D.outboundBytes+this.offset_outboundBytes),D};#t=()=>{const B=this.getRoomNetwork();{const{outboundBytes:D,inboundBytes:M}=B;this.sfuPush=Math.ceil(D/1024),this.sfuPull=Math.ceil(M/1024)}this.cwsIns.emitNotify("onRoomNetwork",{code:200,data:B,desc:"room network is change."})};#r=async B=>{try{const{quality:D}=B;D>=2&&this.prResolves.emit("senderActived"),this.#t();const M=await this.getSelfInfo(),{network:O}=M,C={egress:D,ingress:D};Ct("updateUserNetwork",async()=>{if(await this.updateUserNetwork(this.options.userId,C),JSON.stringify(O)!==JSON.stringify(C)){this.emitNotifyUpdateUsers();const $=this.getOptions(),{userId:N,roomId:F}=$,j={...C,userId:N,roomId:F};this.cwsIns.sendMessage({event:"networkQualityChange",data:j},!1)}},3*1e3)}catch(D){console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->quickvo: setNetQuality is err.",D)}};getReportsByMid=async(B=[])=>this.peerAnalyzeStatsIns?.getReports(B);startGetPeerStats=()=>{this.peerAnalyzeStatsIns.start(this.peerIns);const B=[...this.p2pMap.values()];for(const D of B)D.sendPeerAnalyzeStatsIns.start(D.send_peer_ins),D.recvPeerAnalyzeStatsIns.start(D.recv_peer_ins)};stopGetPeerStats=()=>{this.peerAnalyzeStatsIns.stop();const B=[...this.p2pMap.values()];for(const D of B)D.sendPeerAnalyzeStatsIns.stop(),D.recvPeerAnalyzeStatsIns.stop()}}const g=(A,B)=>{if(!(A!=null&&A.ip)||!(A!=null&&A.port)||!(A!=null&&A.serve_ip)||!(A!=null&&A.serve_port)||!(B!=null&&B.ip)||!(B!=null&&B.port)||!(B!=null&&B.serve_ip)||!(B!=null&&B.serve_port))return"Unknown";const[D,M]=[A.ip,A.port],[O,C]=[A.serve_ip,A.serve_port],[i,u]=[B.ip,B.port],[$,N]=[B.serve_ip,B.serve_port];return D===i&&M===u?"Full Cone":D===O&&(i!==O||u!==M)||i===$&&(D!==$||M!==u)?"Restricted Cone":D===O&&M===C&&(i!==O||u!==C)||i===$&&u===N&&(D!==$||M!==N)?"Port Restricted Cone":"Symmetric"},h=async()=>{const A="stun.cloudflare.com:3478",B="stun.l.google.com:19302",D=async M=>new Promise(O=>{const C=new RTCPeerConnection({iceServers:[{urls:`stun:${M}`}]});C.createDataChannel("ice-channel");let i=null;C.onicecandidate=u=>{var $,N;if((($=u.candidate)==null?void 0:$.type)==="srflx"){const[F,j]=M.split(":").map(J=>J.trim());i={ip:u.candidate.address||"",port:(N=u.candidate.port)==null?void 0:N.toString(),serve_ip:F,serve_port:j},C.close(),O(i)}},setTimeout(()=>{C.close(),O(null)},5e3),C.createOffer().then(u=>C.setLocalDescription(u)).catch(()=>O(null))});try{const M=await D(A),O=await D(B);if(!M||!O)return{address:"",natType:"Unknown"};const C=g(M,O);return{address:M.ip||"",natType:C}}catch(M){return console.error("获取NAT类型失败:",M),{address:"",natType:"Unknown"}}};class RoomCalls extends RoomPeer{#e=0;#n;constructor(B){super(B),this.#d()}setLocalStream=(B,D)=>new Promise(async(M,O)=>{try{const C=[];typeof B=="string"?C.push(B):C.push(...B);for(const u of C)this.localStreamsActionMap.set(u,D);if(D){if(B.includes("microphoneCamera_audio")&&B.includes("microphoneCamera_video")?await this.initLocalStream("microphoneCamera"):B.includes("microphoneCamera_audio")?await this.initLocalStream("microphoneCamera_audio"):B.includes("microphoneCamera_video")?await this.initLocalStream("microphoneCamera_video"):B.includes("screenSharing_audio")&&B.includes("screenSharing_video")?await this.initLocalStream("screenSharing"):B.includes("screenSharing_audio")&&!B.includes("screenSharing_video")?await this.initLocalStream("screenSharing_audio"):B.includes("screenSharing_video")&&!B.includes("screenSharing_audio")&&await this.initLocalStream("screenSharing_video"),B.includes("screenSharing_audio")){const u=await this.getLocalStream("screenSharing_audio");if(u){const $=u.getTracks();for(const N of $)N.onended=()=>this.stopPublish(["screenSharing_audio","screenSharing_video"])}}if(B.includes("screenSharing_video")){const u=await this.getLocalStream("screenSharing_video");if(u){const $=u.getTracks();for(const N of $)N.onended=()=>this.stopPublish(["screenSharing_audio","screenSharing_video"])}}}else await this.stopLocalStreams(C);const i=await this.getLocalStreams(C);if(await this.cwsIns.emitNotify("onLocalStream",{code:200,data:i,desc:"local stream is change."}),this.isInRoom){const u=()=>new Promise(async $=>{const N=this.getOptions(),{userId:F}=N,j={};for(const J of C){const K=await this.getLocalStream(J);K&&(j[J]=wt(),await this.initUserMediaStreamContext(F,J,K,!1))}await this.replaceSenderStream(C,D),await this.emitNotifyUpdateUsersStreams([{userId:F,updateStreams:j}]),$(!0)});this.asyncQueue.add(u,{describe:"setLocalStream"})}M(i)}catch(C){console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->Breathe: error",C),O(C)}});setMediaDeviceKind=(B,D)=>{const M=()=>new Promise(async(O,C)=>{this.setDeviceKind(B,D);const i=await this.getSelfInfo(),{id:u,tracks:$=[],callActionMap:N}=i,F=[],j=async J=>{const K=this.localStreamsActionMap.get(J),Y=$.find(oe=>oe.mediaType===J),re=N[J];if(K){F.push(J),await this.stopLocalStreams([J]);try{await this.initLocalStream(J)}catch(oe){this.options.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->quickvo: initLocalStream is error.",oe),await this.inactiveTracks([J],!1),C(oe)}}if(Y){const oe=await this.getLocalStream(J);if(oe&&(await this.initUserMediaStreamContext(u,J,oe,!0),re)){await this.replaceSenderStream([J],!0);const te=await this.getUsersId();await this.p2p.replaceSenderStreams(te,F,!0)}}{if(F.length!==0){const oe=await this.getLocalStreams(F);await this.cwsIns.emitNotify("onLocalStream",{code:200,data:oe,desc:"local stream is change."});const te=this.createUserUpdateStreams(F);await this.emitNotifyUpdateUsersStreams([{userId:this.options.userId,updateStreams:te}]),await this.emitNotifyUpdateUsers()}O(!0)}};B==="audioinput"&&await j("microphoneCamera_audio"),B==="videoinput"&&await j("microphoneCamera_video"),B==="audiooutput"&&(await this.changeAudiooutput(),O(!0))});return this.asyncQueue.add(M,{describe:"publish"})};changeScreenSharing=async B=>{const D=await this.getSelfInfo(),{tracks:M=[],callActionMap:O}=D;try{await this.setLocalStream(B,!0);for(const C of B)M.find(u=>u.mediaType===C&&O[C])&&await this.replaceSenderStream([C],!0)}catch(C){this.options.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->quickvo: changeScreenSharing is error.",C)}};earlyConnect=(B=[])=>new Promise(async(D,M)=>{try{this.isEarly=!0,await this.#a(),await this.#c(),B.length===0&&(B=["microphoneCamera_audio","microphoneCamera_video"]),await this.#l(B),D(!0)}catch(O){console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->Breathe: error",O),M(O)}});joinRoom=async B=>(this.isInRoom=!0,this.setOptions(B),await this.#a(),await this.cwsConnected(),new Promise(async(D,M)=>{this.#n=async()=>{try{const{userId:O,callType:C,sdkToken:i,roomId:u}=this.getOptions();this.clearUsers(),await this.cwsIns.sendMessage({event:this.isEarly?"joinRoomEx":"joinRoom",data:{callType:C,roomId:u,user:{id:O,tracks:[],callAction:0},token:i},version:2}).then(async $=>{const{code:N=0,desc:F="服务器繁忙",data:j}=$;if(N!==200)throw new Error(F);const{roomId:J="",roomUsers:K=[]}=j;if(J!==u)return M("加入的房间不匹配");this.sfuPush=0,this.sfuPull=0,this.p2pPush=0,this.p2pPull=0,this.saveBoundBytes("superfluous"),this.initHeartbeat(),this.startGetPeerStats(),this.isEarly===!1&&await this.#c(),await this.updateUsers(K);for(const re of K){const{id:oe}=re;await this.updateUserBehaviors(oe,re.behavior)}await this.emitNotifyUpdateUsers();const Y=await this.getUsers();D(Y)})}catch(O){M(O)}},this.#n()}));quitRoom=()=>new Promise(async B=>{const D=this.getOptions(),{roomId:M,userId:O}=D;try{if(this.isInRoom===!1)return B(!0);const C=async u=>{clearTimeout(u),this.isInRoom=!1,this.stopHeartbeat(),this.transceiverMap=new Map,this.peerAnalyzeStatsIns?.stop();const $=()=>this.stopSubscribe(),N=()=>this.cwsIns.sendMessage({event:"quitRoom",data:{roomId:M,user:{id:O}}});Promise.all([$(),N()]).finally(()=>()=>this.cwsIns.clearEvents()),this.asyncQueue.clear(),this.clearUserStreams(),this.clearUsers(),this.setRoomState("ready")},i=window.setTimeout(()=>C(i),2*1e3);try{await this.stopPublish(),C(i)}catch{}B(!0)}catch(C){this.reportLogs("quit_room_error",C.message||C)}});quitRoomEx=()=>new Promise(async B=>{const D=this.getOptions(),{roomId:M,userId:O}=D;try{if(this.isInRoom===!1)return B(!0);const C=async u=>{clearTimeout(u),this.isInRoom=!1,this.initHeartbeat(),this.peerAnalyzeStatsIns?.stop();const $=()=>this.stopSubscribe(),N=()=>this.cwsIns.sendMessage({event:"quitRoomEx",data:{roomId:M,user:{id:O}}});Promise.all([$(),N()]).finally(()=>()=>this.cwsIns.clearEvents()),this.asyncQueue.clear(),this.clearUserStreams(),this.clearUsers()},i=window.setTimeout(()=>C(i),2*1e3);try{await this.stopLocalStreams(),C(i)}catch{this.restoreICE()}B(!0)}catch(C){this.reportLogs("quit_room_error",C.message||C)}});syncRoomInfo=()=>new Promise(async(B,D)=>{try{const M=this.getOptions(),{userId:O}=M,C=await this.getUser(O),{id:i=O,callAction:u=0}=C;await this.cwsIns.sendMessage({event:"syncRoomInfo",data:{user:{id:i,callAction:u}}}).then(async $=>{const{code:N=0,desc:F,data:j={}}=$;if(N!==200)throw new Error(F);const{isActive:J=!1,users:K=[]}=j;if(J===!1)throw new Error("Do not stay in this room.");if(K.find(re=>re.id===O)===!1)throw new Error("Need to rejoin the room.");this.clearUsers(),await this.updateUsers(K),await this.updateUsertracks(C.id,C.tracks,!1);{const re=await this.getUsers();B(re)}})}catch(M){D(M)}});checkInRoom=()=>new Promise(async B=>{const D=this.getOptions(),{userId:M}=D,O=await this.getUser(M),{id:C=M,callAction:i=0}=O;await this.cwsIns.sendMessage({event:"syncRoomInfo",data:{user:{id:C,callAction:i}}}).then(async u=>{const{code:$=0,desc:N}=u;if($!==200)throw new Error(N);const F=u.data.users;return u.data?.isActive||F.find(J=>J.id===M)?B(!0):B(!1)}).catch(()=>B(!1))});senderActived=async B=>{const D=()=>{const{quality:M}=this.peerAnalyzeStatsIns?.getNetwork();return M>=2};await this.prResolves.add("senderActived",D,B)};publish=B=>new Promise(async(D,M)=>{try{{const $=await this.getSelfInfo(),{banBehaviorMap:N}=$;let F=!0;for(const j of B)if(N[j]){F=!1;break}if(F===!1)return M("publish is error: prohibited by administrator.")}const O=await this.getSelfInfo();for(const $ of B){const N=this.getPhoneyStreams($);await this.initUserMediaStreamContext(O.id,$,N,!0)}await this.replaceSenderStream(B,!1),await this.#l(B);const C=setTimeout(async()=>{await this.replaceSenderStream(B,!0),await this.inactiveTracks(B,!1)},5*1e3);this.setLocalStream(B,!0).then(()=>clearTimeout(C));const i=await this.getSenderTracks(B);await this.updateUsertracks(O.id,i,!0);const u=await this.getCallAction(O.tracks);await this.#i(u),await this.senderActived(3e3),this.#r(B);{await this.emitNotifyUpdateUsers();const $=this.createUserUpdateStreams(B);await this.emitNotifyUpdateUsersStreams([{userId:O.id,updateStreams:$}]),D(!0)}}catch(O){this.reportLogs("publish_error",O.message||O),M(O)}});stopPublish=(B=[])=>new Promise(async(D,M)=>{try{const O=await this.getSelfInfo();B.length===0&&(B=mediaType_keys),await this.replaceSenderStream(B,!0),await this.removeSenders(B),await this.#s([{userId:O.id,mediaTypes:B}],!0);const C=await this.getCallAction(O.tracks);await this.#i(C),await this.setLocalStream(B,!1),await this.emitNotifyUpdateUsers(),D(!0)}catch(O){this.reportLogs("close_track_error",O.message||O),M(O)}});inactiveTracks=async(B,D)=>new Promise(async M=>{const O=await this.getSelfInfo();if(!O||!O.id)return M(!0);const{tracks:C=[]}=O,i=[...C];for(let $ of i){const{mediaType:N}=$;if(N&&B.includes(N)){$.enabled=D;const F=await this.getLocalStream(N);if(!F)continue;const j=F.getTracks();for(const J of j)J.enabled=D}}await this.replaceSenderStream(B,D);const u=await this.getCallAction(i);await this.#i(u),await this.emitNotifyUpdateUsers(),M(!0)});subscribe=(B=[])=>{const D=()=>new Promise(async(M,O)=>{try{B.length===0&&(B=await this.getAllUserMediaTypes()),await this.iceConnected();const C=($,N=!1)=>new Promise(async F=>{const j=async K=>{const Y=[],re=[],oe=[];let te=0,le=0;for(const pe of K){const{id:ee,tracks:ne=[]}=pe;if(te=te+ne.length,!this.checkUserInRoom(ee))continue;const se=await this.getUser(ee),ce=[],he=[],ie=[];for(const fe of ne){const{code:ye=0,mid:ve,type:be}=fe,ge=se.tracks.find(Ee=>Ee.type===be);if(ge)switch(ye){case 200:ce.push({...ge,mid:ve});break;case 2026:ie.push({...ge,mid:ve});break;default:he.push({...ge});break}}ce.length!==0&&(Y.push({id:ee,tracks:ce}),le=le+ce.length),he.length!==0&&re.push({id:ee,tracks:he}),ie.length!==0&&oe.push({id:ee,tracks:ie})}return{expectation_num:te,success_num:le,success_users:Y,fail_users:re,retry_users:oe}},J=async(K,Y="成功",re=[])=>{const{expectation_num:oe,success_num:te,success_users:le,fail_users:pe,retry_users:ee}=await j(re);F({code:K,msg:Y,expectation_num:oe,success_num:te,success_users:le,fail_users:pe,retry_users:ee})};try{const K=await this.getUserTrackByUserMediaTypes($,N);if(K.length===0)return J(200,"成功",[]);const Y=await this.cwsIns.sendMessage({event:"subscribe",data:{session:this.sdk_session,users:K}}),{code:re=0,desc:oe,sn:te="",data:le={}}=Y;if(this.#o(te),re===2017&&oe.includes("renegotiation is expected before pulling or pushing tracks")&&await this.#t(),re===2026){const ne=[];for(const ue of K)ne.push({...ue,code:2026});return await J(re,oe,ne)}if(re!==200)return await J(re,oe);const{remoteSdp:pe,users:ee=[]}=le;if(pe){const ne=new RTCSessionDescription({type:"offer",sdp:pe});await this.setRemoteDescription(ne),await this.#t()}await J(200,"成功",ee)}catch(K){console.error("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->quickvo: error",K),await J(0,K.message||K)}}),i=($=[])=>new Promise(N=>{this.await_remote_publish_users=$;let F=0;for(const oe of $)F=F+oe.tracks.length;const j=[],J=wt(),K=async()=>{this.cwsIns.removeNotify([J]);const oe=await C(j);this.await_remote_publish_users=[],N(oe)},Y=setTimeout(()=>K(),30*1e3),re=async oe=>{const{user:te}=oe.data,{id:le,tracks:pe=[],callAction:ee=0}=te;await this.updateUserCallAction(le,ee),await this.updateUserPermissions(le,3),await this.updateUsertracks(le,pe,!0);const ne=[],ue=$.find(he=>he.id===le);if(!ue)return;for(const he of ue.tracks)for(const ie of pe)ie.type===he.type&&ne.push(he.mediaType);const se=[...new Set(ne)];se.length!==0&&j.push({userId:le,mediaTypes:se});let ce=0;for(const he of j)ce=ce+he.mediaTypes.length;ce===F&&(clearTimeout(Y),K())};this.cwsIns.addNotify({sn:J,event:"onPublish",callback:re},!0)}),u=async($=[])=>{let N=0;const F=new Map,j=this.peerIns.getTransceivers(),J=[],K=[];for(const re of $){const{id:oe,tracks:te=[]}=re;if(this.checkUserInRoom(oe)){await this.updateUsertracks(oe,te,!0);for(const pe of te){const{mid:ee,mediaType:ne}=pe,ue=j.find(ce=>ce.mid===ee);if(!ue)continue;const{receiver:se}=ue;if(se.track){{pe.msid=se.track.id;const ce=new MediaStream;ce.addTrack(se.track),await new Promise(fe=>setTimeout(()=>fe(!0),1e3));const{current_origin:he,suggest_origin:ie}=await this.#f(oe,ne);if(await this.#u(oe,[ne],ie),["microphoneCamera_audio","screenSharing_audio"].includes(ne)){const fe=new Audio;fe.srcObject=ce,(ne==="microphoneCamera_audio"||ne==="screenSharing_audio")&&this.getUserAudioMediaStreamContext(oe,ne)?.setMute(!1)}ie==="p2p"&&K.push({userId:oe,mediaTypes:[ne]}),he==="p2p"&&ie==="sfu"&&(J.push(oe),this.p2p.reportP2PConnect(this.options.userId,oe,"poor_network","poor network quality."));{F.has(oe)||F.set(oe,{userId:oe,tracks:[],updateStreams:{}});const ye=F.get(oe);ye.tracks.push(pe),ye.updateStreams[ne]=wt()}}N=N+1}}}}const Y=[...F.values()];return await this.emitNotifyUpdateUsersStreams(Y),J.length!==0&&this.p2p.closeRecv(J),K.length!==0&&this.#s(K,!1),await this.emitNotifyUpdateUsers(),N};{let $=await C(B,!1),{expectation_num:N,success_num:F,success_users:j=[],fail_users:J=[]}=$;if(j.length!==0){const K=await u(j);this.options.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#00b60f;",`------->quickvo: subscription results is: ${K}/${F}/${N}`,{actual_num:K,success_num:F,expectation_num:N})}if(J.length!==0){this.options.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->quickvo: ","The first subscription attempt failed completely. It will attempt to subscribe again in 4 seconds."),await new Promise(pe=>setTimeout(()=>pe(!0),4e3));const K=[];for(const pe of J){const ee=Array.from(pe.tracks,ne=>ne.mediaType);K.push({userId:pe.id,mediaTypes:ee})}const Y=await C(K,!0);let{expectation_num:re,success_num:oe,success_users:te=[],retry_users:le=[]}=Y;if(te.length!==0){const pe=await u(te);this.options.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#00b60f;",`------->quickvo: subscription results is: ${pe}/${oe}/${re}`,{actual_num:pe,success_num:oe,expectation_num:re})}if(le.length!==0){this.options.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#b64900;","------->quickvo: waiting for the other party to republish before subscribing.");const ee=await yt(()=>i(le),{message:"Wait for a timeout before publishing. No re-published track received from the other party within 40 seconds.",timeout:40*1e3});let{expectation_num:ne,success_num:ue,success_users:se=[]}=ee;if(se.length!==0){const ce=await u(se);this.options.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#00b60f;",`------->quickvo: subscription results is: ${ce}/${ue}/${ne}`,{actual_num:ce,success_num:ue,expectation_num:ne})}}}M(!0)}}catch(C){this.reportLogs("subscribe_error",C.message||C),O(C)}});return this.asyncQueue.add(D,{describe:"subscribe"})};#t=()=>new Promise(async(B,D)=>{try{await this.createAnswer(),await this.cwsIns.sendMessage({event:"renegotiate",data:{sdp:this.getSdp()}}).then(async M=>{const{code:O=0,desc:C,sn:i=""}=M;if(await this.#o(i),O!==200)throw new Error(C);B(M)})}catch(M){D(M)}});stopSubscribe=(B=[])=>new Promise(async(D,M)=>{try{B.length===0&&(B=await this.getAllUserMediaTypes());const O=await this.getUserTrackByUserMediaTypes(B);if(O.length===0)return D(!0);const C=[],i=[];for(const u of O){const{id:$,tracks:N=[]}=u;for(const F of N){const{type:j,mid:J,mediaType:K,msid:Y,origin:re="sfu",userId:oe}=F;if(K){if(re==="sfu"){if(!Y||!J)continue;const te={type:j,mid:J,trackName:Y,userId:oe};C.push(te),i.push(J)}re==="p2p"&&(await this.p2p.closeRecv([$],[K]),F.origin="sfu",this.p2p.reportP2PConnect(this.options.userId,$,"disconnect","p2p is close."))}}}if(C.length===0)return D(!0);await this.stopTransceivers(i),await this.#s(B,!1);for(const u of B){const{userId:$,mediaTypes:N=[]}=u;if(!this.checkUserInRoom($))continue;const j=await this.getUser($);for(const J of j.tracks)N.includes(J.mediaType)&&(J.msid="")}await this.emitNotifyUpdateUsers(),D(!0)}catch(O){this.reportLogs("close_track_error",O.message||O),M(O)}});setBanBehaviors=B=>new Promise(async(D,M)=>{try{const O=this.getOptions(),{roomId:C}=O,i=[];for(const u of B){const{id:$,banBehaviors:N}=u,F=Object.keys(N);if(F.length===0)continue;const j=[];for(const K of F){const Y=mediaType_keys.findIndex(te=>te===K),re=N[K],oe={type:Y,behavior:re};j.push(oe)}const J={id:$,behaviors:j};i.push(J)}await this.cwsIns.sendMessage({event:"preventUsersBehavior",data:{roomId:C,users:i}}).then(async u=>{const{code:$=0,desc:N}=u;if($!==200)return M(N);D(u)})}catch(O){M(O)}});debugger=()=>this.cwsIns.sendMessage({event:"debugger"},!1);shutdown=()=>this.cwsIns.sendMessage({event:"shutdown"},!1);restoreRoom=async()=>{if(this.isInRoom===!1)return;await this.checkInRoom()===!1&&this.#n&&await this.#n(),this.cwsIns.afreshSends()};restoreICE=async()=>{this.options.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->quickvo: restore ice."),await this.cwsConnected(),this.initPeer(),this.isEarly?this.earlyConnect():await this.#c();const B=await this.getUsers();for(const D of B){const{id:M,isSelf:O,callActionMap:C,tracks:i=[]}=D;if(O){for(const $ of mediaType_keys)C[$]&&this.historical_publish_mediaTypes.push($);continue}const u=[];for(const $ of i)($.msid||$.origin==="p2p")&&u.push($.mediaType);u.length!==0&&this.historical_subscribe_mediaTypes.push({userId:M,mediaTypes:u})}await this.syncRoomInfo(),await this.publish(this.historical_publish_mediaTypes).then(()=>{this.historical_publish_mediaTypes=[]}),this.historical_subscribe_mediaTypes.length!==0&&await this.subscribe(this.historical_subscribe_mediaTypes).then(()=>{this.historical_subscribe_mediaTypes=[]})};initHeartbeat=()=>{this.stopHeartbeat();const B=async()=>{if(this.isInRoom){const M=this.getTrafficUse();this.cwsIns.sendMessage({event:"heartbeat",data:M},!1)}else this.cwsIns.sendMessage({event:"heartbeatEx",data:{}},!1)},D=this.isInRoom?10*1e3:30*1e3;this.#e=window.setInterval(B,D),B()};stopHeartbeat=()=>{clearInterval(this.#e)};#r=async B=>new Promise(async(D,M)=>{try{const O=this.getOptions(),{roomId:C}=O;if(!C)return;const{id:i,tracks:u=[]}=await this.getSelfInfo(),$=u.filter(F=>F.mediaType&&B.includes(F.mediaType));if($.length===0)return;const N=dt($,["type","trackName","mid"]);await this.cwsIns.sendMessage({event:"pubNotify",data:{session:this.sdk_session,roomId:C,user:{id:i,tracks:N}}}),D(!0)}catch(O){M(O)}});#o=B=>new Promise(D=>{this.cwsIns.sendMessage({event:"ackMsg",data:{msgId:B}},!1),D(!0)});#i=async B=>new Promise(async(D,M)=>{const O=this.getOptions(),{roomId:C,userId:i}=O,u={roomId:C,user:{id:i,callAction:B}};await this.cwsIns.sendMessage({event:"updateCall",data:u}).then(async $=>{const{code:N=0}=$;if(N!==200)return M($);await this.updateUserCallAction(i,B),D(B)}).catch($=>M($))});setSession=()=>{const B=this.getOptions(),{appid:D,roomId:M,userId:O,earlyId:C}=B;if(!D)throw new Error("quickvo: createWs is error. You must first use QuickVO.setOptions to set the appid.");const i={c:D,r:M,p:"web",h:location.hostname,v:this.sdk_service_version};this.isEarly?i.i=C:i.b=O;const u=btoa(encodeURI(JSON.stringify(i)));this.options.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->quickvo: session",i);const $=`${this.options.url}?s=${u}&t=${Date.now()}`;this.cwsIns.prws.setOptions({url:$})};#a=()=>new Promise(async(B,D)=>{try{if(["connecting","connected"].includes(this.roomState))return B(!0);this.setRoomState("connecting"),this.cwsIns.clearEvents(),this.setSession(),await this.cwsIns.connect(),this.initHeartbeat(),this.setRoomState("connected"),await this.prResolves.emit("cwsConnected"),B(this.cwsIns)}catch(M){console.error("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->quickvo: createWs is error.",M),this.reportLogs("ws_c_timeout",M.message||M),D(M)}});cwsConnected=()=>{const B=()=>this.roomState==="connected";return this.prResolves.add("cwsConnected",B)};#c=async()=>new Promise(async B=>{try{await this.cwsConnected(),await this.addSenders();const D=await this.cwsIns.sendMessage({event:"connectCF",data:{sdp:this.getSdp()}}),{code:M=0,desc:O,data:C}=D;if(M!==200)throw new Error(O);const{remoteSdp:i,session:u=""}=C;if(this.sdk_session=u,this.options.debug){const $=libExports$1.parse(i),N=dt($.media,["mid","msid","type"]);console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#ffffff;","------->quickvo: setLocalDescription",{msidArr:N,sdpJson:$})}await this.setRemoteDescription({type:"answer",sdp:i}),await yt(this.iceConnected,{message:"ice connect is timeout.",timeout:10*1e3}),B(!0),this.p2p.reportNetwork()}catch(D){this.options.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->quickvo: ice connect is error. recreate in 5 seconds.",D),await new Promise(M=>setTimeout(()=>M(!0),5*1e3)),this.#c()}});#l=async B=>{const D=()=>new Promise(async(M,O)=>{try{await this.iceConnected();const C=await this.addSenders(B),i=await this.getSenderTracks(C);if(i.length===0)return M(!0);const u=await this.cwsIns.sendMessage({event:"publish",data:{session:this.sdk_session,sdp:this.getSdp(),tracks:i,callAction:0}}),{code:$=0,desc:N,sn:F="",data:j={}}=u;if(await this.#o(F),$!==200)throw new Error(N);const{remoteSdp:J}=j;await this.setRemoteDescription({type:"answer",sdp:J}),M(!0)}catch(C){this.reportLogs("publish_error",C.message||C),await this.removeSenders(B),O(C)}});return this.asyncQueue.add(D,{describe:"createTrack"})};#s=(B=[],D)=>{const M=()=>new Promise(async(O,C)=>{try{B.length===0&&(B=await this.getAllUserMediaTypes());const i=await this.getUserTrackByUserMediaTypes(B);if(i.length===0)return O(!0);const u=[];for(const $ of i){const{id:N,tracks:F=[]}=$,j=Array.from(F,K=>K.trackName);for(const K of F){const{type:Y,mid:re,mediaType:oe,msid:te,userId:le,trackName:pe}=K;if(!oe||re===null)continue;const ee={type:Y,mid:re,trackName:te||pe,userId:le};u.push(ee)}if(this.checkUserInRoom(N)){const K=await this.getUser(N);for(const Y of K.tracks)j.includes(Y.trackName)&&(Y.msid="");if(D){const Y=K.tracks.filter(re=>!j.includes(re.trackName));await this.updateUsertracks(K.id,Y,!1)}}}if(u.length===0)return O(!0);await this.createOffer(),await this.cwsIns.sendMessage({event:"closeTrack",data:{roomId:this.options.roomId,sdp:this.getSdp(),tracks:u}}).then(async $=>{const{code:N=0,desc:F,data:j={}}=$;if(N!==200)throw new Error(F);const{remoteSdp:J}=j;await this.setRemoteDescription({type:"answer",sdp:J})}),O(!0)}catch(i){this.reportLogs("close_track_error",i.message||i),C(i)}});return this.asyncQueue.add(M,{describe:"closeTrack"})};#u=async(B,D,M)=>{for(const O of D){let C;if(!this.checkUserInRoom(B))continue;const u=await this.getUser(B),{tracks:$=[]}=u,N=$.find(j=>j.mediaType===O);if(!N)continue;if(M==="sfu"){const{mid:j}=N;C=this.peerIns.getTransceivers().find(Y=>Y.mid===j)?.receiver.track,N.origin="sfu"}if(M==="p2p"&&(C=(await this.getP2PIns(B))?.getTrack(O),N.origin="p2p"),!C)continue;const F=new MediaStream;F.addTrack(C),await this.initUserMediaStreamContext(B,O,F,!1),this.options.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#00b60f;","------->quickvo: switching to",M,{userId:B,mediaType:O,origin:M,stream:F})}};#f=async(B,D)=>{let M="sfu",O="sfu";const C=await this.getP2PIns(B);if(C&&C?.recv_peer_ins?.connectionState==="connected"){const $=C?.recvPeerAnalyzeStatsIns.getAverageQuality();if($!==0){const{averageQuality:N}=this.getPeerNetwork();$-N>=this.sfuOffsetAverageQuality&&(M="p2p")}}return this.checkUserInRoom(B)&&(O=(await this.getUser(B)).tracks.find($=>$.mediaType===D)?.origin),{current_origin:O,suggest_origin:M}};#d=()=>{{const B=async D=>{let M="";const O=await this.getSelfInfo(),{code:C,data:i}=D;if(C!==200)return;const{sdp:u,sender:$={},tracks:N=[]}=i,{id:F}=$;M=F;{const J=await this.getUsersId();let K=0;for(const Y of J){const re=await this.getP2PIns(Y);re?.send_peer_ins&&re.send_peer_ins.iceConnectionState==="connected"&&(K+=1)}if(K>=3)return this.p2p.reportP2PConnect(M,O.id,"ignore","P2P connections have reached the maximum limit.")}const j=await this.getP2PIns(M);if(j){await j.initSenderPc(),j.sendPeerAnalyzeStatsIns.onNetwork=J=>{this.p2pPush+=Math.ceil(J.outboundBytes/1024)};try{const J=[];for(const ee of N){const{type:ne}=ee;ne!==void 0&&J.push(mediaType_keys[ee.type])}const K=new RTCSessionDescription({type:"offer",sdp:u});await j.setOffer(K),await j.initSenders(N),await this.p2p.replaceSenderStreams([M],J,!0);const Y=await j.createAnswer();if(this.options.debug){const ee=libExports$1.parse(Y.sdp),ne=dt(ee.media,["mid","msid","type"]);console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#ffffff;","------->quickvo: createAnswer",{msidArr:ne,sdpJson:ee})}const re=await j.getSenderTracks(J),oe=this.getOptions(),{roomId:te}=oe,le=()=>new Promise(async(ee,ne)=>{try{const ue=await this.cwsIns.sendMessage({event:"answer",data:{roomId:te,tracks:re,sender:{id:O.id,callAction:O.callAction,tracks:[]},receiverId:M,sdp:Y.sdp}}),{code:se=0,desc:ce}=ue;if(se!==200)throw new Error(ce);ee(!0)}catch(ue){ne(ue)}}),pe=()=>new Promise(async(ee,ne)=>{try{const ue=await yt(j.getSendIcecandidates,{message:"await get send candidates is timeout.",timeout:1e4}),se=Array.from(ue,({sdpMid:fe,sdpMLineIndex:ye,candidate:ve})=>({sdpMid:fe,sdpMLineIndex:ye,sdp:ve})),ce=await this.cwsIns.sendMessage({event:"candidate",data:{roomId:te,senderId:O.id,receiverId:M,candidates:se,isSubscribeReceiver:!1}}),{code:he=0,desc:ie}=ce;if(he!==200)throw new Error(ie);ee(!0)}catch(ue){ne(ue)}});await le(),await pe(),await yt(j.sendIceConnected,{message:"await send ice connect is timeout.",timeout:1e4})}catch{}}};this.cwsIns.addNotify({event:"onOffer",callback:B},!0)}{const B=async D=>{const{code:M,data:O}=D;if(M!==200)return;const{senderId:C,candidates:i=[],receiverId:u,isSubscribeReceiver:$=!1}=O,N=this.getOptions(),{userId:F}=N;if($===!1||u!==F)return;const j=await this.getP2PIns(C);if(!j)return;const J=Array.from(i,({sdpMid:K,sdpMLineIndex:Y,sdp:re})=>({sdpMid:K,sdpMLineIndex:Y,candidate:re}));await j.addCandidates(J)};this.cwsIns.addNotify({event:"onCandidate",callback:B},!0)}};p2p={open:(B,D=["microphoneCamera_video"])=>new Promise(async(M,O)=>{const C=this.getOptions(),{roomId:i,userId:u}=C,$=await this.getSelfInfo(),N=wt(),F=new Date().getTime();let j=!1;try{const J=await this.getP2PIns(B);if(!J)return O("illegal user object.");{if(!this.checkUserInRoom(B))return O("P2P connections without a subscription relationship are not allowed.");const le=await this.getUser(B),{tracks:pe=[]}=le;let ee=!0;for(const ne of D)pe.find(se=>se.mediaType===ne&&se.msid||se.origin==="p2p")||(ee=!1);if(ee===!1)return this.p2p.reportP2PConnect(u,B,"ignore","P2P connections without a subscription relationship are not allowed."),O("P2P connections without a subscription relationship are not allowed.")}const K=()=>new Promise(async(te,le)=>{try{await J.initRecvPc();const pe=()=>{const he=J.recv_peer_ins.connectionState;he==="disconnected"&&this.subscribe([{userId:B,mediaTypes:D}]),he==="failed"&&this.p2p.reportP2PConnect(this.options.userId,B,"disconnect","p2p is failed.")};J.recv_peer_ins.addEventListener("connectionstatechange",pe),await J.addRecvs(D);const ee=await J.createOffer();if(this.options.debug){const he=libExports$1.parse(ee.sdp),ie=dt(he.media,["mid","msid","type"]);console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#ffffff;","------->quickvo: createOffer",{msidArr:ie,sdpJson:he})}const ne=await J.getRecvTracks(D),ue=await this.cwsIns.sendMessage({event:"offer",data:{roomId:i,tracks:ne,sender:{id:$.id,callAction:$.callAction,tracks:[]},receiverId:B,sdp:ee.sdp}}),{code:se=0,desc:ce}=ue;if(se!==200)throw new Error(ce);te(!0)}catch(pe){le(pe)}}),Y=()=>yt(()=>new Promise(le=>{const pe=async ee=>{const{code:ne,data:ue}=ee;if(ne!==200)return;const{sender:se,sdp:ce,tracks:he=[]}=ue,{id:ie}=se;B===ie&&le({answer:{type:"answer",sdp:ce},tracks:he})};this.cwsIns.addNotify({event:"onAnswer",callback:pe,sn:`onAnswer: ${N}`},!0)}),{message:"await_answer is timeout.",timeout:20*1e3}),re=()=>new Promise(async(te,le)=>{try{const pe=await yt(J.getRecvIcecandidates,{message:"await get recv candidates is timeout.",timeout:1e4}),ee=Array.from(pe,({sdpMid:ce,sdpMLineIndex:he,candidate:ie})=>({sdpMid:ce,sdpMLineIndex:he,sdp:ie})),ne=await this.cwsIns.sendMessage({event:"candidate",data:{roomId:i,senderId:$.id,receiverId:B,candidates:ee,isSubscribeReceiver:!0}}),{code:ue=0,desc:se}=ne;if(ue!==200)throw new Error(se);te(!0)}catch(pe){le(pe)}}),oe=()=>yt(()=>new Promise(le=>{const pe=async ee=>{const{code:ne,data:ue}=ee;if(ne!==200)return;const{candidates:se=[],isSubscribeReceiver:ce=!1}=ue;if(ce===!1){const he=Array.from(se,({sdpMid:ie,sdpMLineIndex:fe,sdp:ye})=>({sdpMid:ie,sdpMLineIndex:fe,candidate:ye}));le(he)}};this.cwsIns.addNotify({event:"onCandidate",callback:pe,sn:`onCandidate: ${N}`},!0)}),{message:"await_answer_candidates is timeout.",timeout:20*1e3});Promise.all([Y(),oe()]).then(async te=>{const[{answer:le},pe]=te;if(this.options.debug){const ne=libExports$1.parse(le.sdp),ue=dt(ne.media,["mid","msid","type"]);console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#ffffff;","------->quickvo: setAnswer",{msidArr:ue,sdpJson:ne})}await J.setAnswer(le,pe),await yt(J.recvIceConnected,{message:"recv ice connect is timeout.",timeout:10*1e3});const ee=new Date().getTime()-F;this.p2p.reportP2PConnect(u,B,"success","连接成功",[],ee),this.options.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->quickvo: will compare the quality of P2P and SFU networks in 10 seconds."),J.recvPeerAnalyzeStatsIns.onNetwork=async ne=>{const{inboundBytes:ue,averageQuality:se}=ne;if(this.p2pPull+=Math.ceil(ue/1024),se===0)return;const{current_origin:ce,suggest_origin:he}=await this.#f(B,"microphoneCamera_video");if(j===!1){if(await this.#u(B,D,he),he==="sfu")return this.p2p.reportP2PConnect(u,B,"poor_network",`P2P quality is ${se}.`),await J.clearRecvPc(),M(!0);if(he==="p2p"){j=!0,await this.emitNotifyUpdateUsers();const ie=this.createUserUpdateStreams(D);await this.emitNotifyUpdateUsersStreams([{userId:B,updateStreams:ie}]),ce==="sfu"&&this.#s([{userId:B,mediaTypes:D}],!1)}return M(!0)}if(ce!==he)if(he==="p2p"){await this.#u(B,D,"p2p"),ce==="sfu"&&this.#s([{userId:B,mediaTypes:D}],!1),await this.emitNotifyUpdateUsers();const ie=this.createUserUpdateStreams(D);await this.emitNotifyUpdateUsersStreams([{userId:B,updateStreams:ie}])}else{if(this.hasAsyncTask("subscribe"))return;this.p2p.reportP2PConnect(u,B,"poor_network",`P2P quality is ${se}.`),this.subscribe([{userId:B,mediaTypes:D}])}}}).catch(te=>{O(te),this.p2p.reportP2PConnect(u,B,"fail",te.message||te)}).finally(()=>{this.cwsIns.removeNotify([`onAnswer: ${N}`,`onCandidate: ${N}`])}),await K(),await re()}catch(J){this.p2p.reportP2PConnect(u,B,"fail",J.message||J),O(J)}}),replaceSenderStreams:async(B,D=[],M)=>{const O=this.getOptions();for(const C of B){const{userId:i}=O,u=await this.getP2PIns(C);if(!(!u||!u.send_peer_ins))for(const $ of D){const N=u.send_transceiverMap.get($);let F;if(N){const{sender:j}=N;M?F=this.getUserStream(i,$):F=this.getPhoneyStreams($);const[J]=F.getTracks();J&&await j.replaceTrack(J)}}}},reportNetwork:()=>new Promise(async(B,D)=>{try{let M=0;switch((await h()).natType){case"Symmetric":M=0;break;case"Full Cone":M=1;break;case"Port Restricted Cone":M=2;break;case"Restricted Cone":M=3;break}let O=0;switch((navigator.connection||navigator.mozConnection||navigator.webkitConnection).effectiveType){case"wifi":O=0;break;case"4g":case"3g":case"2g":case"slow-2g":O=2;break;default:O=1;break}await this.cwsIns.sendMessage({event:"reportNetwork",data:{nat:M,type:O}}),B(!0)}catch(M){D(M)}}),reportP2PConnect:(B,D,M,O="",C=[],i=0)=>{let u;switch(M){case"success":u=0;break;case"fail":u=1;break;case"ignore":u=2;break;case"disconnect":u=3;break;case"poor_network":u=4;break}return this.cwsIns.sendMessage({event:"reportP2PConnect",data:{userId:B,origin:D,code:u,reason:O,pushUserIds:C,connectedTime:i}})},closeSend:async(B=[],D=[])=>{B.length===0&&(B=[...this.p2pMap.keys()]);for(const M of B){const O=await this.getP2PIns(M);if(!O||!O.recv_peer_ins)return;O.sendPeerAnalyzeStatsIns.stop(),await O.clearSenderPc(),this.options.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;",`------->quickvo: close closeSend: ${M}`,M,D)}},closeRecv:async(B=[],D=[])=>{B.length===0&&(B=[...this.p2pMap.keys()]);for(const M of B){const O=await this.getP2PIns(M);if(!O||!O.recv_peer_ins)return;O.recvPeerAnalyzeStatsIns.stop(),await O.clearRecvPc(),this.options.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;",`------->quickvo: close closeRecv: ${M}`,M,D)}}}}class Room extends RoomCalls{constructor(B){super(B)}}class QuickVO extends Room{#e=new Map;constructor(B){super(B),this.#t(),this.#n()}#n=()=>{{const B=async D=>{const{state:M}=D.data;if(M==="closed"){const{roomId:O,userId:C}=this.getOptions(),i={roomId:O,user:{id:C}};this.stopHeartbeat(),this.cwsIns.sendMessage({event:"quitRoom",data:i}),this.reportLogs("webrtc_c_timeout","webrtc state is closed.")}};this.cwsIns.addNotify({event:"onRoomState",callback:B},!0)}{const B=async D=>{const{state:M}=D.data;["closed","failed"].includes(M)&&this.restoreICE()};this.cwsIns.addNotify({event:"onIceState",callback:B},!0)}{const B=async D=>{const{qualities:M=[]}=D.data,[O]=M,{userId:C}=this.getOptions();if(!(O&&O.userId===C&&M.length===1)){for(const i of M){const{userId:u,egress:$,ingress:N}=i;this.checkUserInRoom(u)&&await this.updateUserNetwork(u,{egress:$,ingress:N})}await this.emitNotifyUpdateUsers()}};this.cwsIns.addNotify({event:"onNetQuality",callback:B},!0)}{const B=async D=>{const M=D.data.user;await this.removeUsers([M.id]),await this.updateUsers([M]),await this.updateUsertracks(M.id,M.track,!1),await this.updateUserBehaviors(M.id,M.behavior),await this.emitNotifyUpdateUsers()};this.cwsIns.addNotify({event:"onJoinRoom",callback:B},!0)}{const B=async D=>{await this.removeUsers([D.data.user.id]),await this.emitNotifyUpdateUsers()};this.cwsIns.addNotify({event:"onQuitRoom",callback:B},!0)}{const B=async D=>{const{user:M}=D.data,{id:O,tracks:C=[],callAction:i=0}=M;if(await this.updateUserCallAction(O,i),await this.updateUserPermissions(O,3),await this.updateUsertracks(O,C,!0),this.await_remote_publish_users.length!==0&&this.options.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->quickvo: ignore some user track releases.",this.await_remote_publish_users),this.options.newPublishAutoSubscribe){const u=[],$=(K,Y)=>{const re=this.await_remote_publish_users.find(te=>te.id===K);return!(!re||!re.tracks.find(te=>te.type===Y))},N=[];if(!this.checkUserInRoom(O))return;const j=await this.getUser(O);for(const K of j.tracks)for(const Y of C)K.type===Y.type&&$(O,Y.type)===!1&&N.push(Y.mediaType);const J=[...new Set(N)];u.push({userId:O,mediaTypes:J}),await this.subscribe(u)}else await this.emitNotifyUpdateUsers()};this.cwsIns.addNotify({event:"onPublish",callback:B},!0)}{const B=async D=>{const{id:M,tracks:O}=D.data.user,{userId:C}=this.getOptions();if(M===C||!this.checkUserInRoom(M))return;const u=Array.from(O,j=>j.trackName),$=await this.getUser(M),N=[];for(const j of $.tracks)u.includes(j.trackName)&&N.push(j.mediaType);await this.stopSubscribe([{userId:M,mediaTypes:N}]);const F=$.tracks.filter(j=>!u.includes(j.trackName));await this.updateUsertracks(M,F,!1),await this.emitNotifyUpdateUsers()};this.cwsIns.addNotify({event:"onCloseTrack",callback:B},!0)}{const B=async D=>{const{id:M,callAction:O}=D.data.user;this.checkUserInRoom(M)&&(await this.updateUserCallAction(M,O),this.emitNotifyUpdateUsers())};this.cwsIns.addNotify({event:"onUpdateCall",callback:B},!0)}{const B=async D=>{const{roomId:M,remoteUserId:O}=D.data,C=this.getOptions();this.checkUserInRoom(O)&&M===C.roomId&&this.p2p.closeSend([O])};this.cwsIns.addNotify({event:"onDisconnectP2P",callback:B},!0)}{const B=async D=>{const{user:M}=D.data,{id:O,permissions:C=1}=M;C===1?await this.removeUsers([O]):C===3&&await this.updateUsers([M]),await this.emitNotifyUpdateUsers()};this.cwsIns.addNotify({event:"onUpdatePermissions",callback:B},!0)}{const B=async D=>{const{users:M}=D.data;for(const O of M){const{id:C,behavior:i}=O;await this.updateUserBehaviors(C,i)}await this.emitNotifyUpdateUsers()};this.cwsIns.addNotify({event:"onUpdateBehavior",callback:B},!0)}{const B=async D=>{const{roomId:M,userId:O}=D.data;this.checkUserInRoom(O)&&this.options.roomId===M&&(await new Promise(C=>setTimeout(()=>C(!0),1e3)),this.p2p.open(O))};this.cwsIns.addNotify({event:"onAttemptP2PReq",callback:B},!0)}{const B=async D=>{const{session:M,sessionIsValid:O=!0,tracks:C=[]}=D.data;if(M!==this.sdk_session||O===!1)return this.restoreICE();const i=[],u=Array.from(C,N=>N.trackName),$=await this.getUserTrackByTrackName(u);for(const N of $)N&&N.mediaType&&i.push(N.mediaType);await this.stopPublish(i),await this.publish(i)};this.cwsIns.addNotify({event:"onTrackInactive",callback:B},!0)}this.cwsIns.addNotify({event:"onTokenExpired",callback:async B=>this.destroy()},!0),this.cwsIns.addNotify({event:"destroyRoom",callback:this.destroy},!0)};addNotify=B=>this.cwsIns.addNotify(B);#t=()=>{this.cwsIns.prws.checkReconnect=async B=>B.code===1e3?(this.setRoomState("closed"),!1):B.code===4001?(this.setRoomState("closed"),!1):B.code===4002?(this.setRoomState("closed"),!1):B.code===4003?(this.setRoomState("closed"),!1):(this.setSession(),B.code===4010?(this.setRoomState("connecting"),!0):(this.setRoomState("connecting"),!0)),this.cwsIns.prws.onReconnectSuccess=async B=>{this.setRoomState("connected"),await this.restoreRoom(),await this.prResolves.emit("cwsConnected")},this.cwsIns.prws.onReconnectStop=async B=>{this.setRoomState("closed")}};addRequestAnimationFrame=async(B,D)=>{{const O=this.#e.get(B);O&&cancelAnimationFrame(O)}const M=(O=Date.now())=>{D(O);const C=requestAnimationFrame(M);this.#e.set(B,C)};M()};clearRequestAnimationFrame=async(B=[])=>{B.length===0&&(B=[...this.#e.keys()]);const D=[];for(const M of B){const O=this.#e.get(M);O&&(cancelAnimationFrame(O),D.push(O))}return D};destroy=async()=>{this.stopLocalStreams(),this.stopGetPeerStats(),this.quitRoom(),this.clearUsers(),this.clearUserStreams(),this.stopHeartbeat(),await new Promise(B=>setTimeout(()=>B(!0),300)),this.cwsIns.emitNotify("onDestroy",{code:200,data:{},desc:"sdk is destroy."}),this.cwsIns.close(),this.options.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->quickvo: 销毁SDK")}}exports.QuickVO=QuickVO,Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"})});
|
|
9
|
+
*/var hasRequiredBuffer;function requireBuffer(){return hasRequiredBuffer||(hasRequiredBuffer=1,function(A){const B=requireBase64Js(),D=requireIeee754(),M=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;A.Buffer=u,A.SlowBuffer=le,A.INSPECT_MAX_BYTES=50;const O=2147483647;A.kMaxLength=O,u.TYPED_ARRAY_SUPPORT=C(),!u.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function C(){try{const Q=new Uint8Array(1),z={foo:function(){return 42}};return Object.setPrototypeOf(z,Uint8Array.prototype),Object.setPrototypeOf(Q,z),Q.foo()===42}catch{return!1}}Object.defineProperty(u.prototype,"parent",{enumerable:!0,get:function(){if(u.isBuffer(this))return this.buffer}}),Object.defineProperty(u.prototype,"offset",{enumerable:!0,get:function(){if(u.isBuffer(this))return this.byteOffset}});function i(Q){if(Q>O)throw new RangeError('The value "'+Q+'" is invalid for option "size"');const z=new Uint8Array(Q);return Object.setPrototypeOf(z,u.prototype),z}function u(Q,z,Z){if(typeof Q=="number"){if(typeof z=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return j(Q)}return $(Q,z,Z)}u.poolSize=8192;function $(Q,z,Z){if(typeof Q=="string")return J(Q,z);if(ArrayBuffer.isView(Q))return Y(Q);if(Q==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof Q);if(ze(Q,ArrayBuffer)||Q&&ze(Q.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(ze(Q,SharedArrayBuffer)||Q&&ze(Q.buffer,SharedArrayBuffer)))return re(Q,z,Z);if(typeof Q=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');const X=Q.valueOf&&Q.valueOf();if(X!=null&&X!==Q)return u.from(X,z,Z);const ae=oe(Q);if(ae)return ae;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof Q[Symbol.toPrimitive]=="function")return u.from(Q[Symbol.toPrimitive]("string"),z,Z);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof Q)}u.from=function(Q,z,Z){return $(Q,z,Z)},Object.setPrototypeOf(u.prototype,Uint8Array.prototype),Object.setPrototypeOf(u,Uint8Array);function N(Q){if(typeof Q!="number")throw new TypeError('"size" argument must be of type number');if(Q<0)throw new RangeError('The value "'+Q+'" is invalid for option "size"')}function F(Q,z,Z){return N(Q),Q<=0?i(Q):z!==void 0?typeof Z=="string"?i(Q).fill(z,Z):i(Q).fill(z):i(Q)}u.alloc=function(Q,z,Z){return F(Q,z,Z)};function j(Q){return N(Q),i(Q<0?0:te(Q)|0)}u.allocUnsafe=function(Q){return j(Q)},u.allocUnsafeSlow=function(Q){return j(Q)};function J(Q,z){if((typeof z!="string"||z==="")&&(z="utf8"),!u.isEncoding(z))throw new TypeError("Unknown encoding: "+z);const Z=pe(Q,z)|0;let X=i(Z);const ae=X.write(Q,z);return ae!==Z&&(X=X.slice(0,ae)),X}function K(Q){const z=Q.length<0?0:te(Q.length)|0,Z=i(z);for(let X=0;X<z;X+=1)Z[X]=Q[X]&255;return Z}function Y(Q){if(ze(Q,Uint8Array)){const z=new Uint8Array(Q);return re(z.buffer,z.byteOffset,z.byteLength)}return K(Q)}function re(Q,z,Z){if(z<0||Q.byteLength<z)throw new RangeError('"offset" is outside of buffer bounds');if(Q.byteLength<z+(Z||0))throw new RangeError('"length" is outside of buffer bounds');let X;return z===void 0&&Z===void 0?X=new Uint8Array(Q):Z===void 0?X=new Uint8Array(Q,z):X=new Uint8Array(Q,z,Z),Object.setPrototypeOf(X,u.prototype),X}function oe(Q){if(u.isBuffer(Q)){const z=te(Q.length)|0,Z=i(z);return Z.length===0||Q.copy(Z,0,0,z),Z}if(Q.length!==void 0)return typeof Q.length!="number"||Xe(Q.length)?i(0):K(Q);if(Q.type==="Buffer"&&Array.isArray(Q.data))return K(Q.data)}function te(Q){if(Q>=O)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+O.toString(16)+" bytes");return Q|0}function le(Q){return+Q!=Q&&(Q=0),u.alloc(+Q)}u.isBuffer=function(z){return z!=null&&z._isBuffer===!0&&z!==u.prototype},u.compare=function(z,Z){if(ze(z,Uint8Array)&&(z=u.from(z,z.offset,z.byteLength)),ze(Z,Uint8Array)&&(Z=u.from(Z,Z.offset,Z.byteLength)),!u.isBuffer(z)||!u.isBuffer(Z))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(z===Z)return 0;let X=z.length,ae=Z.length;for(let de=0,me=Math.min(X,ae);de<me;++de)if(z[de]!==Z[de]){X=z[de],ae=Z[de];break}return X<ae?-1:ae<X?1:0},u.isEncoding=function(z){switch(String(z).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},u.concat=function(z,Z){if(!Array.isArray(z))throw new TypeError('"list" argument must be an Array of Buffers');if(z.length===0)return u.alloc(0);let X;if(Z===void 0)for(Z=0,X=0;X<z.length;++X)Z+=z[X].length;const ae=u.allocUnsafe(Z);let de=0;for(X=0;X<z.length;++X){let me=z[X];if(ze(me,Uint8Array))de+me.length>ae.length?(u.isBuffer(me)||(me=u.from(me)),me.copy(ae,de)):Uint8Array.prototype.set.call(ae,me,de);else if(u.isBuffer(me))me.copy(ae,de);else throw new TypeError('"list" argument must be an Array of Buffers');de+=me.length}return ae};function pe(Q,z){if(u.isBuffer(Q))return Q.length;if(ArrayBuffer.isView(Q)||ze(Q,ArrayBuffer))return Q.byteLength;if(typeof Q!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof Q);const Z=Q.length,X=arguments.length>2&&arguments[2]===!0;if(!X&&Z===0)return 0;let ae=!1;for(;;)switch(z){case"ascii":case"latin1":case"binary":return Z;case"utf8":case"utf-8":return Je(Q).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Z*2;case"hex":return Z>>>1;case"base64":return Ke(Q).length;default:if(ae)return X?-1:Je(Q).length;z=(""+z).toLowerCase(),ae=!0}}u.byteLength=pe;function ee(Q,z,Z){let X=!1;if((z===void 0||z<0)&&(z=0),z>this.length||((Z===void 0||Z>this.length)&&(Z=this.length),Z<=0)||(Z>>>=0,z>>>=0,Z<=z))return"";for(Q||(Q="utf8");;)switch(Q){case"hex":return Le(this,z,Z);case"utf8":case"utf-8":return be(this,z,Z);case"ascii":return De(this,z,Z);case"latin1":case"binary":return Be(this,z,Z);case"base64":return ve(this,z,Z);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Ve(this,z,Z);default:if(X)throw new TypeError("Unknown encoding: "+Q);Q=(Q+"").toLowerCase(),X=!0}}u.prototype._isBuffer=!0;function ne(Q,z,Z){const X=Q[z];Q[z]=Q[Z],Q[Z]=X}u.prototype.swap16=function(){const z=this.length;if(z%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let Z=0;Z<z;Z+=2)ne(this,Z,Z+1);return this},u.prototype.swap32=function(){const z=this.length;if(z%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let Z=0;Z<z;Z+=4)ne(this,Z,Z+3),ne(this,Z+1,Z+2);return this},u.prototype.swap64=function(){const z=this.length;if(z%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let Z=0;Z<z;Z+=8)ne(this,Z,Z+7),ne(this,Z+1,Z+6),ne(this,Z+2,Z+5),ne(this,Z+3,Z+4);return this},u.prototype.toString=function(){const z=this.length;return z===0?"":arguments.length===0?be(this,0,z):ee.apply(this,arguments)},u.prototype.toLocaleString=u.prototype.toString,u.prototype.equals=function(z){if(!u.isBuffer(z))throw new TypeError("Argument must be a Buffer");return this===z?!0:u.compare(this,z)===0},u.prototype.inspect=function(){let z="";const Z=A.INSPECT_MAX_BYTES;return z=this.toString("hex",0,Z).replace(/(.{2})/g,"$1 ").trim(),this.length>Z&&(z+=" ... "),"<Buffer "+z+">"},M&&(u.prototype[M]=u.prototype.inspect),u.prototype.compare=function(z,Z,X,ae,de){if(ze(z,Uint8Array)&&(z=u.from(z,z.offset,z.byteLength)),!u.isBuffer(z))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof z);if(Z===void 0&&(Z=0),X===void 0&&(X=z?z.length:0),ae===void 0&&(ae=0),de===void 0&&(de=this.length),Z<0||X>z.length||ae<0||de>this.length)throw new RangeError("out of range index");if(ae>=de&&Z>=X)return 0;if(ae>=de)return-1;if(Z>=X)return 1;if(Z>>>=0,X>>>=0,ae>>>=0,de>>>=0,this===z)return 0;let me=de-ae,Oe=X-Z;const Ce=Math.min(me,Oe),Re=this.slice(ae,de),Pe=z.slice(Z,X);for(let xe=0;xe<Ce;++xe)if(Re[xe]!==Pe[xe]){me=Re[xe],Oe=Pe[xe];break}return me<Oe?-1:Oe<me?1:0};function ue(Q,z,Z,X,ae){if(Q.length===0)return-1;if(typeof Z=="string"?(X=Z,Z=0):Z>2147483647?Z=2147483647:Z<-2147483648&&(Z=-2147483648),Z=+Z,Xe(Z)&&(Z=ae?0:Q.length-1),Z<0&&(Z=Q.length+Z),Z>=Q.length){if(ae)return-1;Z=Q.length-1}else if(Z<0)if(ae)Z=0;else return-1;if(typeof z=="string"&&(z=u.from(z,X)),u.isBuffer(z))return z.length===0?-1:se(Q,z,Z,X,ae);if(typeof z=="number")return z=z&255,typeof Uint8Array.prototype.indexOf=="function"?ae?Uint8Array.prototype.indexOf.call(Q,z,Z):Uint8Array.prototype.lastIndexOf.call(Q,z,Z):se(Q,[z],Z,X,ae);throw new TypeError("val must be string, number or Buffer")}function se(Q,z,Z,X,ae){let de=1,me=Q.length,Oe=z.length;if(X!==void 0&&(X=String(X).toLowerCase(),X==="ucs2"||X==="ucs-2"||X==="utf16le"||X==="utf-16le")){if(Q.length<2||z.length<2)return-1;de=2,me/=2,Oe/=2,Z/=2}function Ce(Pe,xe){return de===1?Pe[xe]:Pe.readUInt16BE(xe*de)}let Re;if(ae){let Pe=-1;for(Re=Z;Re<me;Re++)if(Ce(Q,Re)===Ce(z,Pe===-1?0:Re-Pe)){if(Pe===-1&&(Pe=Re),Re-Pe+1===Oe)return Pe*de}else Pe!==-1&&(Re-=Re-Pe),Pe=-1}else for(Z+Oe>me&&(Z=me-Oe),Re=Z;Re>=0;Re--){let Pe=!0;for(let xe=0;xe<Oe;xe++)if(Ce(Q,Re+xe)!==Ce(z,xe)){Pe=!1;break}if(Pe)return Re}return-1}u.prototype.includes=function(z,Z,X){return this.indexOf(z,Z,X)!==-1},u.prototype.indexOf=function(z,Z,X){return ue(this,z,Z,X,!0)},u.prototype.lastIndexOf=function(z,Z,X){return ue(this,z,Z,X,!1)};function ce(Q,z,Z,X){Z=Number(Z)||0;const ae=Q.length-Z;X?(X=Number(X),X>ae&&(X=ae)):X=ae;const de=z.length;X>de/2&&(X=de/2);let me;for(me=0;me<X;++me){const Oe=parseInt(z.substr(me*2,2),16);if(Xe(Oe))return me;Q[Z+me]=Oe}return me}function he(Q,z,Z,X){return Qe(Je(z,Q.length-Z),Q,Z,X)}function ie(Q,z,Z,X){return Qe(Ge(z),Q,Z,X)}function fe(Q,z,Z,X){return Qe(Ke(z),Q,Z,X)}function ye(Q,z,Z,X){return Qe(Ye(z,Q.length-Z),Q,Z,X)}u.prototype.write=function(z,Z,X,ae){if(Z===void 0)ae="utf8",X=this.length,Z=0;else if(X===void 0&&typeof Z=="string")ae=Z,X=this.length,Z=0;else if(isFinite(Z))Z=Z>>>0,isFinite(X)?(X=X>>>0,ae===void 0&&(ae="utf8")):(ae=X,X=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");const de=this.length-Z;if((X===void 0||X>de)&&(X=de),z.length>0&&(X<0||Z<0)||Z>this.length)throw new RangeError("Attempt to write outside buffer bounds");ae||(ae="utf8");let me=!1;for(;;)switch(ae){case"hex":return ce(this,z,Z,X);case"utf8":case"utf-8":return he(this,z,Z,X);case"ascii":case"latin1":case"binary":return ie(this,z,Z,X);case"base64":return fe(this,z,Z,X);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ye(this,z,Z,X);default:if(me)throw new TypeError("Unknown encoding: "+ae);ae=(""+ae).toLowerCase(),me=!0}},u.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function ve(Q,z,Z){return z===0&&Z===Q.length?B.fromByteArray(Q):B.fromByteArray(Q.slice(z,Z))}function be(Q,z,Z){Z=Math.min(Q.length,Z);const X=[];let ae=z;for(;ae<Z;){const de=Q[ae];let me=null,Oe=de>239?4:de>223?3:de>191?2:1;if(ae+Oe<=Z){let Ce,Re,Pe,xe;switch(Oe){case 1:de<128&&(me=de);break;case 2:Ce=Q[ae+1],(Ce&192)===128&&(xe=(de&31)<<6|Ce&63,xe>127&&(me=xe));break;case 3:Ce=Q[ae+1],Re=Q[ae+2],(Ce&192)===128&&(Re&192)===128&&(xe=(de&15)<<12|(Ce&63)<<6|Re&63,xe>2047&&(xe<55296||xe>57343)&&(me=xe));break;case 4:Ce=Q[ae+1],Re=Q[ae+2],Pe=Q[ae+3],(Ce&192)===128&&(Re&192)===128&&(Pe&192)===128&&(xe=(de&15)<<18|(Ce&63)<<12|(Re&63)<<6|Pe&63,xe>65535&&xe<1114112&&(me=xe))}}me===null?(me=65533,Oe=1):me>65535&&(me-=65536,X.push(me>>>10&1023|55296),me=56320|me&1023),X.push(me),ae+=Oe}return Ee(X)}const ge=4096;function Ee(Q){const z=Q.length;if(z<=ge)return String.fromCharCode.apply(String,Q);let Z="",X=0;for(;X<z;)Z+=String.fromCharCode.apply(String,Q.slice(X,X+=ge));return Z}function De(Q,z,Z){let X="";Z=Math.min(Q.length,Z);for(let ae=z;ae<Z;++ae)X+=String.fromCharCode(Q[ae]&127);return X}function Be(Q,z,Z){let X="";Z=Math.min(Q.length,Z);for(let ae=z;ae<Z;++ae)X+=String.fromCharCode(Q[ae]);return X}function Le(Q,z,Z){const X=Q.length;(!z||z<0)&&(z=0),(!Z||Z<0||Z>X)&&(Z=X);let ae="";for(let de=z;de<Z;++de)ae+=et[Q[de]];return ae}function Ve(Q,z,Z){const X=Q.slice(z,Z);let ae="";for(let de=0;de<X.length-1;de+=2)ae+=String.fromCharCode(X[de]+X[de+1]*256);return ae}u.prototype.slice=function(z,Z){const X=this.length;z=~~z,Z=Z===void 0?X:~~Z,z<0?(z+=X,z<0&&(z=0)):z>X&&(z=X),Z<0?(Z+=X,Z<0&&(Z=0)):Z>X&&(Z=X),Z<z&&(Z=z);const ae=this.subarray(z,Z);return Object.setPrototypeOf(ae,u.prototype),ae};function Te(Q,z,Z){if(Q%1!==0||Q<0)throw new RangeError("offset is not uint");if(Q+z>Z)throw new RangeError("Trying to access beyond buffer length")}u.prototype.readUintLE=u.prototype.readUIntLE=function(z,Z,X){z=z>>>0,Z=Z>>>0,X||Te(z,Z,this.length);let ae=this[z],de=1,me=0;for(;++me<Z&&(de*=256);)ae+=this[z+me]*de;return ae},u.prototype.readUintBE=u.prototype.readUIntBE=function(z,Z,X){z=z>>>0,Z=Z>>>0,X||Te(z,Z,this.length);let ae=this[z+--Z],de=1;for(;Z>0&&(de*=256);)ae+=this[z+--Z]*de;return ae},u.prototype.readUint8=u.prototype.readUInt8=function(z,Z){return z=z>>>0,Z||Te(z,1,this.length),this[z]},u.prototype.readUint16LE=u.prototype.readUInt16LE=function(z,Z){return z=z>>>0,Z||Te(z,2,this.length),this[z]|this[z+1]<<8},u.prototype.readUint16BE=u.prototype.readUInt16BE=function(z,Z){return z=z>>>0,Z||Te(z,2,this.length),this[z]<<8|this[z+1]},u.prototype.readUint32LE=u.prototype.readUInt32LE=function(z,Z){return z=z>>>0,Z||Te(z,4,this.length),(this[z]|this[z+1]<<8|this[z+2]<<16)+this[z+3]*16777216},u.prototype.readUint32BE=u.prototype.readUInt32BE=function(z,Z){return z=z>>>0,Z||Te(z,4,this.length),this[z]*16777216+(this[z+1]<<16|this[z+2]<<8|this[z+3])},u.prototype.readBigUInt64LE=We(function(z){z=z>>>0,$e(z,"offset");const Z=this[z],X=this[z+7];(Z===void 0||X===void 0)&&qe(z,this.length-8);const ae=Z+this[++z]*2**8+this[++z]*2**16+this[++z]*2**24,de=this[++z]+this[++z]*2**8+this[++z]*2**16+X*2**24;return BigInt(ae)+(BigInt(de)<<BigInt(32))}),u.prototype.readBigUInt64BE=We(function(z){z=z>>>0,$e(z,"offset");const Z=this[z],X=this[z+7];(Z===void 0||X===void 0)&&qe(z,this.length-8);const ae=Z*2**24+this[++z]*2**16+this[++z]*2**8+this[++z],de=this[++z]*2**24+this[++z]*2**16+this[++z]*2**8+X;return(BigInt(ae)<<BigInt(32))+BigInt(de)}),u.prototype.readIntLE=function(z,Z,X){z=z>>>0,Z=Z>>>0,X||Te(z,Z,this.length);let ae=this[z],de=1,me=0;for(;++me<Z&&(de*=256);)ae+=this[z+me]*de;return de*=128,ae>=de&&(ae-=Math.pow(2,8*Z)),ae},u.prototype.readIntBE=function(z,Z,X){z=z>>>0,Z=Z>>>0,X||Te(z,Z,this.length);let ae=Z,de=1,me=this[z+--ae];for(;ae>0&&(de*=256);)me+=this[z+--ae]*de;return de*=128,me>=de&&(me-=Math.pow(2,8*Z)),me},u.prototype.readInt8=function(z,Z){return z=z>>>0,Z||Te(z,1,this.length),this[z]&128?(255-this[z]+1)*-1:this[z]},u.prototype.readInt16LE=function(z,Z){z=z>>>0,Z||Te(z,2,this.length);const X=this[z]|this[z+1]<<8;return X&32768?X|4294901760:X},u.prototype.readInt16BE=function(z,Z){z=z>>>0,Z||Te(z,2,this.length);const X=this[z+1]|this[z]<<8;return X&32768?X|4294901760:X},u.prototype.readInt32LE=function(z,Z){return z=z>>>0,Z||Te(z,4,this.length),this[z]|this[z+1]<<8|this[z+2]<<16|this[z+3]<<24},u.prototype.readInt32BE=function(z,Z){return z=z>>>0,Z||Te(z,4,this.length),this[z]<<24|this[z+1]<<16|this[z+2]<<8|this[z+3]},u.prototype.readBigInt64LE=We(function(z){z=z>>>0,$e(z,"offset");const Z=this[z],X=this[z+7];(Z===void 0||X===void 0)&&qe(z,this.length-8);const ae=this[z+4]+this[z+5]*2**8+this[z+6]*2**16+(X<<24);return(BigInt(ae)<<BigInt(32))+BigInt(Z+this[++z]*2**8+this[++z]*2**16+this[++z]*2**24)}),u.prototype.readBigInt64BE=We(function(z){z=z>>>0,$e(z,"offset");const Z=this[z],X=this[z+7];(Z===void 0||X===void 0)&&qe(z,this.length-8);const ae=(Z<<24)+this[++z]*2**16+this[++z]*2**8+this[++z];return(BigInt(ae)<<BigInt(32))+BigInt(this[++z]*2**24+this[++z]*2**16+this[++z]*2**8+X)}),u.prototype.readFloatLE=function(z,Z){return z=z>>>0,Z||Te(z,4,this.length),D.read(this,z,!0,23,4)},u.prototype.readFloatBE=function(z,Z){return z=z>>>0,Z||Te(z,4,this.length),D.read(this,z,!1,23,4)},u.prototype.readDoubleLE=function(z,Z){return z=z>>>0,Z||Te(z,8,this.length),D.read(this,z,!0,52,8)},u.prototype.readDoubleBE=function(z,Z){return z=z>>>0,Z||Te(z,8,this.length),D.read(this,z,!1,52,8)};function Ie(Q,z,Z,X,ae,de){if(!u.isBuffer(Q))throw new TypeError('"buffer" argument must be a Buffer instance');if(z>ae||z<de)throw new RangeError('"value" argument is out of bounds');if(Z+X>Q.length)throw new RangeError("Index out of range")}u.prototype.writeUintLE=u.prototype.writeUIntLE=function(z,Z,X,ae){if(z=+z,Z=Z>>>0,X=X>>>0,!ae){const Oe=Math.pow(2,8*X)-1;Ie(this,z,Z,X,Oe,0)}let de=1,me=0;for(this[Z]=z&255;++me<X&&(de*=256);)this[Z+me]=z/de&255;return Z+X},u.prototype.writeUintBE=u.prototype.writeUIntBE=function(z,Z,X,ae){if(z=+z,Z=Z>>>0,X=X>>>0,!ae){const Oe=Math.pow(2,8*X)-1;Ie(this,z,Z,X,Oe,0)}let de=X-1,me=1;for(this[Z+de]=z&255;--de>=0&&(me*=256);)this[Z+de]=z/me&255;return Z+X},u.prototype.writeUint8=u.prototype.writeUInt8=function(z,Z,X){return z=+z,Z=Z>>>0,X||Ie(this,z,Z,1,255,0),this[Z]=z&255,Z+1},u.prototype.writeUint16LE=u.prototype.writeUInt16LE=function(z,Z,X){return z=+z,Z=Z>>>0,X||Ie(this,z,Z,2,65535,0),this[Z]=z&255,this[Z+1]=z>>>8,Z+2},u.prototype.writeUint16BE=u.prototype.writeUInt16BE=function(z,Z,X){return z=+z,Z=Z>>>0,X||Ie(this,z,Z,2,65535,0),this[Z]=z>>>8,this[Z+1]=z&255,Z+2},u.prototype.writeUint32LE=u.prototype.writeUInt32LE=function(z,Z,X){return z=+z,Z=Z>>>0,X||Ie(this,z,Z,4,4294967295,0),this[Z+3]=z>>>24,this[Z+2]=z>>>16,this[Z+1]=z>>>8,this[Z]=z&255,Z+4},u.prototype.writeUint32BE=u.prototype.writeUInt32BE=function(z,Z,X){return z=+z,Z=Z>>>0,X||Ie(this,z,Z,4,4294967295,0),this[Z]=z>>>24,this[Z+1]=z>>>16,this[Z+2]=z>>>8,this[Z+3]=z&255,Z+4};function He(Q,z,Z,X,ae){Se(z,X,ae,Q,Z,7);let de=Number(z&BigInt(4294967295));Q[Z++]=de,de=de>>8,Q[Z++]=de,de=de>>8,Q[Z++]=de,de=de>>8,Q[Z++]=de;let me=Number(z>>BigInt(32)&BigInt(4294967295));return Q[Z++]=me,me=me>>8,Q[Z++]=me,me=me>>8,Q[Z++]=me,me=me>>8,Q[Z++]=me,Z}function Ae(Q,z,Z,X,ae){Se(z,X,ae,Q,Z,7);let de=Number(z&BigInt(4294967295));Q[Z+7]=de,de=de>>8,Q[Z+6]=de,de=de>>8,Q[Z+5]=de,de=de>>8,Q[Z+4]=de;let me=Number(z>>BigInt(32)&BigInt(4294967295));return Q[Z+3]=me,me=me>>8,Q[Z+2]=me,me=me>>8,Q[Z+1]=me,me=me>>8,Q[Z]=me,Z+8}u.prototype.writeBigUInt64LE=We(function(z,Z=0){return He(this,z,Z,BigInt(0),BigInt("0xffffffffffffffff"))}),u.prototype.writeBigUInt64BE=We(function(z,Z=0){return Ae(this,z,Z,BigInt(0),BigInt("0xffffffffffffffff"))}),u.prototype.writeIntLE=function(z,Z,X,ae){if(z=+z,Z=Z>>>0,!ae){const Ce=Math.pow(2,8*X-1);Ie(this,z,Z,X,Ce-1,-Ce)}let de=0,me=1,Oe=0;for(this[Z]=z&255;++de<X&&(me*=256);)z<0&&Oe===0&&this[Z+de-1]!==0&&(Oe=1),this[Z+de]=(z/me>>0)-Oe&255;return Z+X},u.prototype.writeIntBE=function(z,Z,X,ae){if(z=+z,Z=Z>>>0,!ae){const Ce=Math.pow(2,8*X-1);Ie(this,z,Z,X,Ce-1,-Ce)}let de=X-1,me=1,Oe=0;for(this[Z+de]=z&255;--de>=0&&(me*=256);)z<0&&Oe===0&&this[Z+de+1]!==0&&(Oe=1),this[Z+de]=(z/me>>0)-Oe&255;return Z+X},u.prototype.writeInt8=function(z,Z,X){return z=+z,Z=Z>>>0,X||Ie(this,z,Z,1,127,-128),z<0&&(z=255+z+1),this[Z]=z&255,Z+1},u.prototype.writeInt16LE=function(z,Z,X){return z=+z,Z=Z>>>0,X||Ie(this,z,Z,2,32767,-32768),this[Z]=z&255,this[Z+1]=z>>>8,Z+2},u.prototype.writeInt16BE=function(z,Z,X){return z=+z,Z=Z>>>0,X||Ie(this,z,Z,2,32767,-32768),this[Z]=z>>>8,this[Z+1]=z&255,Z+2},u.prototype.writeInt32LE=function(z,Z,X){return z=+z,Z=Z>>>0,X||Ie(this,z,Z,4,2147483647,-2147483648),this[Z]=z&255,this[Z+1]=z>>>8,this[Z+2]=z>>>16,this[Z+3]=z>>>24,Z+4},u.prototype.writeInt32BE=function(z,Z,X){return z=+z,Z=Z>>>0,X||Ie(this,z,Z,4,2147483647,-2147483648),z<0&&(z=4294967295+z+1),this[Z]=z>>>24,this[Z+1]=z>>>16,this[Z+2]=z>>>8,this[Z+3]=z&255,Z+4},u.prototype.writeBigInt64LE=We(function(z,Z=0){return He(this,z,Z,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),u.prototype.writeBigInt64BE=We(function(z,Z=0){return Ae(this,z,Z,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function Fe(Q,z,Z,X,ae,de){if(Z+X>Q.length)throw new RangeError("Index out of range");if(Z<0)throw new RangeError("Index out of range")}function Ze(Q,z,Z,X,ae){return z=+z,Z=Z>>>0,ae||Fe(Q,z,Z,4),D.write(Q,z,Z,X,23,4),Z+4}u.prototype.writeFloatLE=function(z,Z,X){return Ze(this,z,Z,!0,X)},u.prototype.writeFloatBE=function(z,Z,X){return Ze(this,z,Z,!1,X)};function je(Q,z,Z,X,ae){return z=+z,Z=Z>>>0,ae||Fe(Q,z,Z,8),D.write(Q,z,Z,X,52,8),Z+8}u.prototype.writeDoubleLE=function(z,Z,X){return je(this,z,Z,!0,X)},u.prototype.writeDoubleBE=function(z,Z,X){return je(this,z,Z,!1,X)},u.prototype.copy=function(z,Z,X,ae){if(!u.isBuffer(z))throw new TypeError("argument should be a Buffer");if(X||(X=0),!ae&&ae!==0&&(ae=this.length),Z>=z.length&&(Z=z.length),Z||(Z=0),ae>0&&ae<X&&(ae=X),ae===X||z.length===0||this.length===0)return 0;if(Z<0)throw new RangeError("targetStart out of bounds");if(X<0||X>=this.length)throw new RangeError("Index out of range");if(ae<0)throw new RangeError("sourceEnd out of bounds");ae>this.length&&(ae=this.length),z.length-Z<ae-X&&(ae=z.length-Z+X);const de=ae-X;return this===z&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(Z,X,ae):Uint8Array.prototype.set.call(z,this.subarray(X,ae),Z),de},u.prototype.fill=function(z,Z,X,ae){if(typeof z=="string"){if(typeof Z=="string"?(ae=Z,Z=0,X=this.length):typeof X=="string"&&(ae=X,X=this.length),ae!==void 0&&typeof ae!="string")throw new TypeError("encoding must be a string");if(typeof ae=="string"&&!u.isEncoding(ae))throw new TypeError("Unknown encoding: "+ae);if(z.length===1){const me=z.charCodeAt(0);(ae==="utf8"&&me<128||ae==="latin1")&&(z=me)}}else typeof z=="number"?z=z&255:typeof z=="boolean"&&(z=Number(z));if(Z<0||this.length<Z||this.length<X)throw new RangeError("Out of range index");if(X<=Z)return this;Z=Z>>>0,X=X===void 0?this.length:X>>>0,z||(z=0);let de;if(typeof z=="number")for(de=Z;de<X;++de)this[de]=z;else{const me=u.isBuffer(z)?z:u.from(z,ae),Oe=me.length;if(Oe===0)throw new TypeError('The value "'+z+'" is invalid for argument "value"');for(de=0;de<X-Z;++de)this[de+Z]=me[de%Oe]}return this};const Ne={};function _e(Q,z,Z){Ne[Q]=class extends Z{constructor(){super(),Object.defineProperty(this,"message",{value:z.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${Q}]`,this.stack,delete this.name}get code(){return Q}set code(ae){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:ae,writable:!0})}toString(){return`${this.name} [${Q}]: ${this.message}`}}}_e("ERR_BUFFER_OUT_OF_BOUNDS",function(Q){return Q?`${Q} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),_e("ERR_INVALID_ARG_TYPE",function(Q,z){return`The "${Q}" argument must be of type number. Received type ${typeof z}`},TypeError),_e("ERR_OUT_OF_RANGE",function(Q,z,Z){let X=`The value of "${Q}" is out of range.`,ae=Z;return Number.isInteger(Z)&&Math.abs(Z)>2**32?ae=ke(String(Z)):typeof Z=="bigint"&&(ae=String(Z),(Z>BigInt(2)**BigInt(32)||Z<-(BigInt(2)**BigInt(32)))&&(ae=ke(ae)),ae+="n"),X+=` It must be ${z}. Received ${ae}`,X},RangeError);function ke(Q){let z="",Z=Q.length;const X=Q[0]==="-"?1:0;for(;Z>=X+4;Z-=3)z=`_${Q.slice(Z-3,Z)}${z}`;return`${Q.slice(0,Z)}${z}`}function we(Q,z,Z){$e(z,"offset"),(Q[z]===void 0||Q[z+Z]===void 0)&&qe(z,Q.length-(Z+1))}function Se(Q,z,Z,X,ae,de){if(Q>Z||Q<z){const me=typeof z=="bigint"?"n":"";let Oe;throw z===0||z===BigInt(0)?Oe=`>= 0${me} and < 2${me} ** ${(de+1)*8}${me}`:Oe=`>= -(2${me} ** ${(de+1)*8-1}${me}) and < 2 ** ${(de+1)*8-1}${me}`,new Ne.ERR_OUT_OF_RANGE("value",Oe,Q)}we(X,ae,de)}function $e(Q,z){if(typeof Q!="number")throw new Ne.ERR_INVALID_ARG_TYPE(z,"number",Q)}function qe(Q,z,Z){throw Math.floor(Q)!==Q?($e(Q,Z),new Ne.ERR_OUT_OF_RANGE("offset","an integer",Q)):z<0?new Ne.ERR_BUFFER_OUT_OF_BOUNDS:new Ne.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${z}`,Q)}const Me=/[^+/0-9A-Za-z-_]/g;function Ue(Q){if(Q=Q.split("=")[0],Q=Q.trim().replace(Me,""),Q.length<2)return"";for(;Q.length%4!==0;)Q=Q+"=";return Q}function Je(Q,z){z=z||1/0;let Z;const X=Q.length;let ae=null;const de=[];for(let me=0;me<X;++me){if(Z=Q.charCodeAt(me),Z>55295&&Z<57344){if(!ae){if(Z>56319){(z-=3)>-1&&de.push(239,191,189);continue}else if(me+1===X){(z-=3)>-1&&de.push(239,191,189);continue}ae=Z;continue}if(Z<56320){(z-=3)>-1&&de.push(239,191,189),ae=Z;continue}Z=(ae-55296<<10|Z-56320)+65536}else ae&&(z-=3)>-1&&de.push(239,191,189);if(ae=null,Z<128){if((z-=1)<0)break;de.push(Z)}else if(Z<2048){if((z-=2)<0)break;de.push(Z>>6|192,Z&63|128)}else if(Z<65536){if((z-=3)<0)break;de.push(Z>>12|224,Z>>6&63|128,Z&63|128)}else if(Z<1114112){if((z-=4)<0)break;de.push(Z>>18|240,Z>>12&63|128,Z>>6&63|128,Z&63|128)}else throw new Error("Invalid code point")}return de}function Ge(Q){const z=[];for(let Z=0;Z<Q.length;++Z)z.push(Q.charCodeAt(Z)&255);return z}function Ye(Q,z){let Z,X,ae;const de=[];for(let me=0;me<Q.length&&!((z-=2)<0);++me)Z=Q.charCodeAt(me),X=Z>>8,ae=Z%256,de.push(ae),de.push(X);return de}function Ke(Q){return B.toByteArray(Ue(Q))}function Qe(Q,z,Z,X){let ae;for(ae=0;ae<X&&!(ae+Z>=z.length||ae>=Q.length);++ae)z[ae+Z]=Q[ae];return ae}function ze(Q,z){return Q instanceof z||Q!=null&&Q.constructor!=null&&Q.constructor.name!=null&&Q.constructor.name===z.name}function Xe(Q){return Q!==Q}const et=function(){const Q="0123456789abcdef",z=new Array(256);for(let Z=0;Z<16;++Z){const X=Z*16;for(let ae=0;ae<16;++ae)z[X+ae]=Q[Z]+Q[ae]}return z}();function We(Q){return typeof BigInt>"u"?tt:Q}function tt(){throw new Error("BigInt not supported")}}(buffer)),buffer}var toolsEbml={},hasRequiredToolsEbml;function requireToolsEbml(){if(hasRequiredToolsEbml)return toolsEbml;hasRequiredToolsEbml=1;var A=toolsEbml&&toolsEbml.__assign||function(){return A=Object.assign||function(O){for(var C,i=1,u=arguments.length;i<u;i++){C=arguments[i];for(var $ in C)Object.prototype.hasOwnProperty.call(C,$)&&(O[$]=C[$])}return O},A.apply(this,arguments)},B=toolsEbml&&toolsEbml.__spreadArray||function(O,C,i){if(i||arguments.length===2)for(var u=0,$=C.length,N;u<$;u++)(N||!(u in C))&&(N||(N=Array.prototype.slice.call(C,0,u)),N[u]=C[u]);return O.concat(N||Array.prototype.slice.call(C))};Object.defineProperty(toolsEbml,"__esModule",{value:!0});var D=requireTools(),M=function(){function O(){}return O.readVint=function(C,i){i===void 0&&(i=0);var u=8-Math.floor(Math.log2(C[i]));if(u>8){var $=O.readHexString(C,i,i+u);throw new Error("Unrepresentable length: ".concat(u," ").concat($))}if(i+u>C.length)return null;for(var N=C[i]&(1<<8-u)-1,F=1;F<u;F+=1){if(F===7&&N>=Math.pow(2,8)&&C[i+7]>0)return{length:u,value:-1};N*=Math.pow(2,8),N+=C[i+F]}return{length:u,value:N}},O.writeVint=function(C){if(C<0||C>Math.pow(2,53))throw new Error("Unrepresentable value: ".concat(C));var i=1;for(i=1;i<=8&&!(C<Math.pow(2,7*i)-1);i+=1);for(var u=D.Buffer.alloc(i),$=C,N=1;N<=i;N+=1){var F=$&255;u[i-N]=F,$-=F,$/=Math.pow(2,8)}return u[0]|=1<<8-i,u},O.concatenate=function(C,i){return!C&&!i?D.Buffer.from([]):!C||C.byteLength===0?i:!i||i.byteLength===0?C:D.Buffer.from(B(B([],C,!0),i,!0))},O.readHexString=function(C,i,u){return i===void 0&&(i=0),u===void 0&&(u=C.byteLength),Array.from(C.slice(i,u)).map(function($){return Number($).toString(16)}).reduce(function($,N){return"".concat($).concat(N.padStart(2,"0"))},"")},O.readUtf8=function(C){try{return D.Buffer.from(C).toString("utf8")}catch{return null}},O.readUnsigned=function(C){var i=new DataView(C.buffer,C.byteOffset,C.byteLength);switch(C.byteLength){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 4:return i.getUint32(0)}return C.byteLength<=6?C.reduce(function(u,$){return u*256+$},0):O.readHexString(C,0,C.byteLength)},O.readSigned=function(C){var i=new DataView(C.buffer,C.byteOffset,C.byteLength);switch(C.byteLength){case 1:return i.getInt8(0);case 2:return i.getInt16(0);case 4:return i.getInt32(0);default:return NaN}},O.readFloat=function(C){var i=new DataView(C.buffer,C.byteOffset,C.byteLength);switch(C.byteLength){case 4:return i.getFloat32(0);case 8:return i.getFloat64(0);default:return NaN}},O.readDate=function(C){var i=new DataView(C.buffer,C.byteOffset,C.byteLength);switch(C.byteLength){case 1:return new Date(i.getUint8(0));case 2:return new Date(i.getUint16(0));case 4:return new Date(i.getUint32(0));case 8:return new Date(Number.parseInt(O.readHexString(C),16));default:return new Date(0)}},O.readDataFromTag=function(C,i){var u=C.type,$=C.name,N=C.track,F=C.discardable||!1,j=C.keyframe||!1,J=null,K;switch(u){case"u":K=O.readUnsigned(i);break;case"f":K=O.readFloat(i);break;case"i":K=O.readSigned(i);break;case"s":K=String.fromCharCode.apply(String,i);break;case"8":K=O.readUtf8(i);break;case"d":K=O.readDate(i);break}if($==="SimpleBlock"||$==="Block"){var Y=0,re=O.readVint(i,Y),oe=re.length,te=re.value;Y+=oe,N=te,K=O.readSigned(i.subarray(Y,Y+2)),Y+=2,$==="SimpleBlock"&&(j=!!(i[oe+2]&128),F=!!(i[oe+2]&1)),Y+=1,J=i.subarray(Y)}return A(A({},C),{data:i,discardable:F,keyframe:j,payload:J,track:N,value:K})},O}();return toolsEbml.default=M,toolsEbml}var vint,hasRequiredVint;function requireVint(){return hasRequiredVint||(hasRequiredVint=1,vint=function(A,B,D){B=B||0;for(var M=1;M<=8&&!(A[B]>=Math.pow(2,8-M));M++);if(M>8)throw new Error("Unrepresentable length: "+M+" "+A.toString("hex",B,B+M));if(B+M>A.length)return null;var O,C=A[B]&(1<<8-M)-1;for(O=1;O<M;O++){if(O===7&&C>=Math.pow(2,45)&&A[B+7]>0)return{length:M,value:-1};C*=Math.pow(2,8),C+=A[B+O]}return D&&(C-=Math.pow(2,M*7-1)-1),{length:M,value:C}}),vint}var bufferReader,hasRequiredBufferReader;function requireBufferReader(){if(hasRequiredBufferReader)return bufferReader;hasRequiredBufferReader=1;var A=requireVint();function B(D){this.buffer=D,this.offset=0}return B.prototype.nextInt16BE=function(){var D=this.buffer.readInt16BE(this.offset);return this.offset+=2,D},B.prototype.nextUInt8=function(){var D=this.buffer.readUInt8(this.offset);return this.offset+=1,D},B.prototype.nextUIntV=function(){var D=A(this.buffer,this.offset);return this.offset+=D.length,D.value},B.prototype.nextIntV=function(){var D=A(this.buffer,this.offset,!0);return this.offset+=D.length,D.value},B.prototype.nextBuffer=function(D){var M=D?this.buffer.slice(this.offset,this.offset+D):this.buffer.slice(this.offset);return this.offset+=D||this.length,M},Object.defineProperty(B.prototype,"length",{get:function(){return this.buffer.length-this.offset}}),bufferReader=B,bufferReader}var ebmlBlock,hasRequiredEbmlBlock;function requireEbmlBlock(){if(hasRequiredEbmlBlock)return ebmlBlock;hasRequiredEbmlBlock=1;var A=requireBufferReader(),B=1,D=3,M=2;ebmlBlock=function(C){var i={},u=new A(C);i.trackNumber=u.nextUIntV(),i.timecode=u.nextInt16BE();var $=u.nextUInt8();i.invisible=!!($&8),i.keyframe=!!($&128),i.discardable=!!($&1);var N=($&6)>>1;return i.frames=O(u,N),i};function O(C,i){if(!i)return[C.nextBuffer()];var u,$,N=[],F=C.nextUInt8()+1;if(i===M){if(C.length%F!==0)throw new Error("Fixed-Size Lacing Error");for($=C.length/F,u=0;u<F;u++)N.push(C.nextBuffer($));return N}var j=[];if(i===B)for(u=0;u<F-1;u++){var J;$=0;do J=C.nextUInt8(),$+=J;while(J===255);j.push($)}else if(i===D)for($=C.nextUIntV(),j.push($),u=1;u<F-1;u++)$+=C.nextIntV(),j.push($);for(u=0;u<F-1;u++)N.push(C.nextBuffer(j[u]));return N.push(C.nextBuffer()),N}return ebmlBlock}var hasRequiredTools;function requireTools(){return hasRequiredTools||(hasRequiredTools=1,function(A){Object.defineProperty(A,"__esModule",{value:!0}),A.convertEBMLDateToJSDate=A.createFloatBuffer=A.createIntBuffer=A.createUIntBuffer=A.encodeValueToBuffer=A.concat=A.putRefinedMetaData=A.extractElement=A.removeElement=A.makeMetadataSeekable=A.createRIFFChunk=A.VP8BitStreamToRiffWebPBuffer=A.WebPBlockFilter=A.encodeTag=A.readBlock=A.ebmlBlock=A.writeVint=A.readVint=A.Buffer=void 0;var B=requireInt64Buffer(),D=requireEBMLEncoder(),M=requireBuffer(),O=requireToolsEbml(),C=requireEbmlBlock();A.Buffer=M.Buffer,A.readVint=O.default.readVint,A.writeVint=O.default.writeVint,A.ebmlBlock=C;function i(ie){return(0,A.ebmlBlock)(new A.Buffer(ie))}A.readBlock=i;function u(ie,fe,ye){return ye===void 0&&(ye=!1),ee([ie,ye?new A.Buffer("01ffffffffffffff","hex"):(0,A.writeVint)(fe.length),fe])}A.encodeTag=u;function $(ie){return ie.reduce(function(fe,ye){if(ye.type!=="b"||ye.name!=="SimpleBlock")return fe;var ve=(0,A.ebmlBlock)(ye.data),be=ve.frames.some(function(ge){var Ee=ge.slice(3,6).toString("hex");return Ee==="9d012a"});return be?fe.concat(ye):fe},[])}A.WebPBlockFilter=$;function N(ie){var fe=F("VP8 ",ie),ye=ee([new A.Buffer("WEBP","ascii"),fe]);return F("RIFF",ye)}A.VP8BitStreamToRiffWebPBuffer=N;function F(ie,fe){var ye=new A.Buffer(4);return ye.writeUInt32LE(fe.byteLength,0),ee([new A.Buffer(ie.substr(0,4),"ascii"),ye,fe,new A.Buffer(fe.byteLength%2===0?0:1)])}A.createRIFFChunk=F;function j(ie,fe,ye){var ve=K("EBML",ie),be=re(ve),ge=be+12,Ee=ie[ie.length-1].dataEnd-ge,De=K("Info",ie);J("Duration",De),De.splice(1,0,{name:"Duration",type:"f",data:ce(fe,8)});for(var Be=re(De),Le=K("Tracks",ie),Ve=re(Le),Te=47,Ie=[],He=5+ye.length*15,Ae=[],Fe=-1,Ze=10,je=function(Se){var $e=Te,qe=$e+Be,Me=qe+Ve,Ue=Me+He,Je=Ue-Ee;if(Ie=[],Ie.push({name:"SeekHead",type:"m",isEnd:!1}),Ie.push({name:"Seek",type:"m",isEnd:!1}),Ie.push({name:"SeekID",type:"b",data:new A.Buffer([21,73,169,102])}),Ie.push({name:"SeekPosition",type:"u",data:ue($e)}),Ie.push({name:"Seek",type:"m",isEnd:!0}),Ie.push({name:"Seek",type:"m",isEnd:!1}),Ie.push({name:"SeekID",type:"b",data:new A.Buffer([22,84,174,107])}),Ie.push({name:"SeekPosition",type:"u",data:ue(qe)}),Ie.push({name:"Seek",type:"m",isEnd:!0}),Ie.push({name:"Seek",type:"m",isEnd:!1}),Ie.push({name:"SeekID",type:"b",data:new A.Buffer([28,83,187,107])}),Ie.push({name:"SeekPosition",type:"u",data:ue(Me)}),Ie.push({name:"Seek",type:"m",isEnd:!0}),Ie.push({name:"SeekHead",type:"m",isEnd:!0}),Te=re(Ie),Ae=[],Ae.push({name:"Cues",type:"m",isEnd:!1}),ye.forEach(function(Ge){var Ye=Ge.CueTrack,Ke=Ge.CueClusterPosition,Qe=Ge.CueTime;Ae.push({name:"CuePoint",type:"m",isEnd:!1}),Ae.push({name:"CueTime",type:"u",data:ue(Qe)}),Ae.push({name:"CueTrackPositions",type:"m",isEnd:!1}),Ae.push({name:"CueTrack",type:"u",data:ue(Ye)}),Ke-=ge,Ke+=Je,Ae.push({name:"CueClusterPosition",type:"u",data:ue(Ke)}),Ae.push({name:"CueTrackPositions",type:"m",isEnd:!0}),Ae.push({name:"CuePoint",type:"m",isEnd:!0})}),Ae.push({name:"Cues",type:"m",isEnd:!0}),He=re(Ae),Fe!==Je){if(Fe=Je,Se===Ze-1)throw new Error("Failed to converge to a stable metadata size")}else return"break"},Ne=0;Ne<Ze;Ne++){var _e=je(Ne);if(_e==="break")break}var ke=[].concat.apply([],[ve,{name:"Segment",type:"m",isEnd:!1,unknownSize:!0},Ie,De,Le,Ae]),we=new D.default().encode(ke);return we}A.makeMetadataSeekable=j;function J(ie,fe){for(var ye=-1,ve=0;ve<fe.length;ve++){var be=fe[ve];if(be.name===ie)if(be.type==="m")if(!be.isEnd)ye=ve;else{if(ye==-1)throw new Error("Detected ".concat(ie," closing element before finding the start"));fe.splice(ye,ve-ye+1);return}else{fe.splice(ve,1);return}}}A.removeElement=J;function K(ie,fe){for(var ye=[],ve=-1,be=0;be<fe.length;be++){var ge=fe[be];if(ge.name===ie)if(ge.type==="m")if(!ge.isEnd)ve=be;else{if(ve==-1)throw new Error("Detected ".concat(ie," closing element before finding the start"));ye=fe.slice(ve,be+1);break}else{ye.push(fe[be]);break}}return ye}A.extractElement=K;function Y(ie,fe){Array.isArray(fe.cueInfos)&&!Array.isArray(fe.cues)&&(console.warn("putRefinedMetaData: info.cueInfos property is deprecated. please use info.cues"),fe.cues=fe.cueInfos);for(var ye=[],ve=[],be=0;be<ie.length;be++){var ge=ie[be];if(ge.type==="m"&&ge.name==="Segment"){if(ye=ie.slice(0,be),ve=ie.slice(be),ge.unknownSize){ve.shift();break}throw new Error("this metadata is not streaming webm file")}}if(!(ve[ve.length-1].dataEnd>0))throw new Error("metadata dataEnd has wrong number");var Ee=ve[ve.length-1].dataEnd,De=ye[ye.length-1].dataEnd,Be=new D.default().encode(ye).byteLength,Le=Be-De,Ve=Ee-ve[0].tagStart;ve[0].tagStart-De,ve[0].tagStart;var Te=new A.Buffer([24,83,128,103]),Ie=new A.Buffer("01ffffffffffffff","hex"),He=Te.byteLength+Ie.byteLength,Ae=Ve,Fe;for(Fe=1;Fe<20;Fe++){var Ze=De+He+Ae,je=Ze-Ee,Ne=Le+je,_e=oe(ve,Ne,fe),ke=new D.default().encode(_e).byteLength;if(ke===Ae)return new D.default().encode([].concat(ye,[{type:"m",name:"Segment",isEnd:!1,unknownSize:!0}],_e));Ae=ke}throw new Error("unable to refine metadata, stable size could not be found in "+Fe+" iterations!")}A.putRefinedMetaData=Y;function re(ie){var fe=new D.default;return ie.reduce(function(ye,ve){return ye.concat(fe.encode([ve]))},[]).reduce(function(ye,ve){return ye+ve.byteLength},0)}function oe(ie,fe,ye){var ve=ye.duration,be=ye.clusterPtrs,ge=ye.cues,Ee=ie.slice(0);if(typeof ve=="number"){var De=!1;Ee.forEach(function(Le){Le.type==="f"&&Le.name==="Duration"&&(De=!0,Le.data=ce(ve,8))}),De||pe(Ee,"Info",[{name:"Duration",type:"f",data:ce(ve,8)}])}Array.isArray(ge)&&pe(Ee,"Cues",le(ge,fe));var Be=[];return Array.isArray(be)&&(console.warn("append cluster pointers to seekhead is deprecated. please use cues"),Be=te(be,fe)),pe(Ee,"SeekHead",Be,!0),Ee}function te(ie,fe){var ye=[];return ie.forEach(function(ve){ye.push({name:"Seek",type:"m",isEnd:!1}),ye.push({name:"SeekID",type:"b",data:new A.Buffer([31,67,182,117])}),ye.push({name:"SeekPosition",type:"u",data:ue(ve+fe)}),ye.push({name:"Seek",type:"m",isEnd:!0})}),ye}function le(ie,fe){var ye=[];return ie.forEach(function(ve){var be=ve.CueTrack,ge=ve.CueClusterPosition,Ee=ve.CueTime;ye.push({name:"CuePoint",type:"m",isEnd:!1}),ye.push({name:"CueTime",type:"u",data:ue(Ee)}),ye.push({name:"CueTrackPositions",type:"m",isEnd:!1}),ye.push({name:"CueTrack",type:"u",data:ue(be)}),ye.push({name:"CueClusterPosition",type:"u",data:ue(ge+fe)}),ye.push({name:"CueTrackPositions",type:"m",isEnd:!0}),ye.push({name:"CuePoint",type:"m",isEnd:!0})}),ye}function pe(ie,fe,ye,ve){ve===void 0&&(ve=!1);for(var be=-1,ge=0;ge<ie.length;ge++){var Ee=ie[ge];if(Ee.type==="m"&&Ee.name===fe&&Ee.isEnd===!1){be=ge;break}}be>=0?Array.prototype.splice.apply(ie,[be+1,0].concat(ye)):ve?[].concat([{name:fe,type:"m",isEnd:!1}],ye,[{name:fe,type:"m",isEnd:!0}]).reverse().forEach(function(De){ie.unshift(De)}):(ie.push({name:fe,type:"m",isEnd:!1}),ye.forEach(function(De){ie.push(De)}),ie.push({name:fe,type:"m",isEnd:!0}))}function ee(ie){return A.Buffer.concat(ie)}A.concat=ee;function ne(ie){var fe=new A.Buffer(0);if(ie.type==="m")return ie;switch(ie.type){case"u":fe=ue(ie.value);break;case"i":fe=se(ie.value);break;case"f":fe=ce(ie.value);break;case"s":fe=new A.Buffer(ie.value,"ascii");break;case"8":fe=new A.Buffer(ie.value,"utf8");break;case"b":fe=ie.value;break;case"d":fe=new B.Int64BE(ie.value.getTime().toString()).toBuffer();break}return Object.assign({},ie,{data:fe})}A.encodeValueToBuffer=ne;function ue(ie){for(var fe=1;ie>=Math.pow(2,8*fe);fe++);if(fe>=7)return console.warn("7bit or more bigger uint not supported."),new B.Uint64BE(ie).toBuffer();var ye=new A.Buffer(fe);return ye.writeUIntBE(ie,0,fe),ye}A.createUIntBuffer=ue;function se(ie){for(var fe=1;ie>=Math.pow(2,8*fe);fe++);if(fe>=7)return console.warn("7bit or more bigger uint not supported."),new B.Int64BE(ie).toBuffer();var ye=new A.Buffer(fe);return ye.writeIntBE(ie,0,fe),ye}A.createIntBuffer=se;function ce(ie,fe){if(fe===void 0&&(fe=8),fe===8){var ye=new A.Buffer(8);return ye.writeDoubleBE(ie,0),ye}else if(fe===4){var ye=new A.Buffer(4);return ye.writeFloatBE(ie,0),ye}else throw new Error("float type bits must 4bytes or 8bytes")}A.createFloatBuffer=ce;function he(ie){return ie instanceof Date?ie:new Date(new Date("2001-01-01T00:00:00.000Z").getTime()+Number(ie)/1e3/1e3)}A.convertEBMLDateToJSDate=he}(tools)),tools}var hasRequiredEBMLDecoder;function requireEBMLDecoder(){if(hasRequiredEBMLDecoder)return EBMLDecoder;hasRequiredEBMLDecoder=1,Object.defineProperty(EBMLDecoder,"__esModule",{value:!0});var A=requireInt64Buffer(),B=requireTools(),D=requireTools(),M=requireEbmlID(),O;(function(i){i[i.STATE_TAG=1]="STATE_TAG",i[i.STATE_SIZE=2]="STATE_SIZE",i[i.STATE_CONTENT=3]="STATE_CONTENT"})(O||(O={}));var C=function(){function i(){this._buffer=new B.Buffer(0),this._tag_stack=[],this._state=O.STATE_TAG,this._cursor=0,this._total=0,this._schema=M.byEbmlID,this._result=[]}return i.prototype.decode=function(u){this.readChunk(u);var $=this._result;return this._result=[],$},i.prototype.readChunk=function(u){for(this._buffer=D.concat([this._buffer,new B.Buffer(u)]);this._cursor<this._buffer.length&&!(this._state===O.STATE_TAG&&!this.readTag()||this._state===O.STATE_SIZE&&!this.readSize()||this._state===O.STATE_CONTENT&&!this.readContent()););},i.prototype.getSchemaInfo=function(u){return this._schema[u]||{name:"unknown",level:-1,type:"unknown",description:"unknown"}},i.prototype.readTag=function(){if(this._cursor>=this._buffer.length)return!1;var u=(0,B.readVint)(this._buffer,this._cursor);if(u==null)return!1;var $=this._buffer.slice(this._cursor,this._cursor+u.length),N=$.reduce(function(J,K,Y,re){return J+K*Math.pow(16,2*(re.length-1-Y))},0),F=this.getSchemaInfo(N),j={EBML_ID:N.toString(16),schema:F,type:F.type,name:F.name,level:F.level,tagStart:this._total,tagEnd:this._total+u.length,sizeStart:this._total+u.length,sizeEnd:null,dataStart:null,dataEnd:null,dataSize:null,data:null};return this._tag_stack.push(j),this._cursor+=u.length,this._total+=u.length,this._state=O.STATE_SIZE,!0},i.prototype.readSize=function(){if(this._cursor>=this._buffer.length)return!1;var u=(0,B.readVint)(this._buffer,this._cursor);if(u==null)return!1;var $=this._tag_stack[this._tag_stack.length-1];return $.sizeEnd=$.sizeStart+u.length,$.dataStart=$.sizeEnd,$.dataSize=u.value,u.value===-1?($.dataEnd=-1,$.type==="m"&&($.unknownSize=!0)):$.dataEnd=$.sizeEnd+u.value,this._cursor+=u.length,this._total+=u.length,this._state=O.STATE_CONTENT,!0},i.prototype.readContent=function(){var u=this._tag_stack[this._tag_stack.length-1];if(u.type==="m"){if(u.isEnd=!1,this._result.push(u),this._state=O.STATE_TAG,u.dataSize===0){var $=Object.assign({},u,{isEnd:!0});this._result.push($),this._tag_stack.pop()}return!0}if(this._buffer.length<this._cursor+u.dataSize)return!1;var N=this._buffer.slice(this._cursor,this._cursor+u.dataSize);switch(this._buffer=this._buffer.slice(this._cursor+u.dataSize),u.data=N,u.type){case"u":u.value=N.readUIntBE(0,N.length);break;case"i":u.value=N.readIntBE(0,N.length);break;case"f":u.value=u.dataSize===4?N.readFloatBE(0):u.dataSize===8?N.readDoubleBE(0):(console.warn("cannot read ".concat(u.dataSize," octets float. failback to 0")),0);break;case"s":u.value=N.toString("ascii");break;case"8":u.value=N.toString("utf8");break;case"b":u.value=N;break;case"d":u.value=(0,B.convertEBMLDateToJSDate)(new A.Int64BE(N).toNumber());break}if(u.value===null)throw new Error("unknown tag type:"+u.type);for(this._result.push(u),this._total+=u.dataSize,this._state=O.STATE_TAG,this._cursor=0,this._tag_stack.pop();this._tag_stack.length>0;){var F=this._tag_stack[this._tag_stack.length-1];if(F.dataEnd<0)return this._tag_stack.pop(),!0;if(this._total<F.dataEnd)break;if(F.type!=="m")throw new Error("parent element is not master element");var $=Object.assign({},F,{isEnd:!0});this._result.push($),this._tag_stack.pop()}return!0},i}();return EBMLDecoder.default=C,EBMLDecoder}var EBMLReader={},events={exports:{}},hasRequiredEvents;function requireEvents(){if(hasRequiredEvents)return events.exports;hasRequiredEvents=1;var A=typeof Reflect=="object"?Reflect:null,B=A&&typeof A.apply=="function"?A.apply:function(ne,ue,se){return Function.prototype.apply.call(ne,ue,se)},D;A&&typeof A.ownKeys=="function"?D=A.ownKeys:Object.getOwnPropertySymbols?D=function(ne){return Object.getOwnPropertyNames(ne).concat(Object.getOwnPropertySymbols(ne))}:D=function(ne){return Object.getOwnPropertyNames(ne)};function M(ee){console&&console.warn&&console.warn(ee)}var O=Number.isNaN||function(ne){return ne!==ne};function C(){C.init.call(this)}events.exports=C,events.exports.once=te,C.EventEmitter=C,C.prototype._events=void 0,C.prototype._eventsCount=0,C.prototype._maxListeners=void 0;var i=10;function u(ee){if(typeof ee!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof ee)}Object.defineProperty(C,"defaultMaxListeners",{enumerable:!0,get:function(){return i},set:function(ee){if(typeof ee!="number"||ee<0||O(ee))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+ee+".");i=ee}}),C.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},C.prototype.setMaxListeners=function(ne){if(typeof ne!="number"||ne<0||O(ne))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+ne+".");return this._maxListeners=ne,this};function $(ee){return ee._maxListeners===void 0?C.defaultMaxListeners:ee._maxListeners}C.prototype.getMaxListeners=function(){return $(this)},C.prototype.emit=function(ne){for(var ue=[],se=1;se<arguments.length;se++)ue.push(arguments[se]);var ce=ne==="error",he=this._events;if(he!==void 0)ce=ce&&he.error===void 0;else if(!ce)return!1;if(ce){var ie;if(ue.length>0&&(ie=ue[0]),ie instanceof Error)throw ie;var fe=new Error("Unhandled error."+(ie?" ("+ie.message+")":""));throw fe.context=ie,fe}var ye=he[ne];if(ye===void 0)return!1;if(typeof ye=="function")B(ye,this,ue);else for(var ve=ye.length,be=Y(ye,ve),se=0;se<ve;++se)B(be[se],this,ue);return!0};function N(ee,ne,ue,se){var ce,he,ie;if(u(ue),he=ee._events,he===void 0?(he=ee._events=Object.create(null),ee._eventsCount=0):(he.newListener!==void 0&&(ee.emit("newListener",ne,ue.listener?ue.listener:ue),he=ee._events),ie=he[ne]),ie===void 0)ie=he[ne]=ue,++ee._eventsCount;else if(typeof ie=="function"?ie=he[ne]=se?[ue,ie]:[ie,ue]:se?ie.unshift(ue):ie.push(ue),ce=$(ee),ce>0&&ie.length>ce&&!ie.warned){ie.warned=!0;var fe=new Error("Possible EventEmitter memory leak detected. "+ie.length+" "+String(ne)+" listeners added. Use emitter.setMaxListeners() to increase limit");fe.name="MaxListenersExceededWarning",fe.emitter=ee,fe.type=ne,fe.count=ie.length,M(fe)}return ee}C.prototype.addListener=function(ne,ue){return N(this,ne,ue,!1)},C.prototype.on=C.prototype.addListener,C.prototype.prependListener=function(ne,ue){return N(this,ne,ue,!0)};function F(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function j(ee,ne,ue){var se={fired:!1,wrapFn:void 0,target:ee,type:ne,listener:ue},ce=F.bind(se);return ce.listener=ue,se.wrapFn=ce,ce}C.prototype.once=function(ne,ue){return u(ue),this.on(ne,j(this,ne,ue)),this},C.prototype.prependOnceListener=function(ne,ue){return u(ue),this.prependListener(ne,j(this,ne,ue)),this},C.prototype.removeListener=function(ne,ue){var se,ce,he,ie,fe;if(u(ue),ce=this._events,ce===void 0)return this;if(se=ce[ne],se===void 0)return this;if(se===ue||se.listener===ue)--this._eventsCount===0?this._events=Object.create(null):(delete ce[ne],ce.removeListener&&this.emit("removeListener",ne,se.listener||ue));else if(typeof se!="function"){for(he=-1,ie=se.length-1;ie>=0;ie--)if(se[ie]===ue||se[ie].listener===ue){fe=se[ie].listener,he=ie;break}if(he<0)return this;he===0?se.shift():re(se,he),se.length===1&&(ce[ne]=se[0]),ce.removeListener!==void 0&&this.emit("removeListener",ne,fe||ue)}return this},C.prototype.off=C.prototype.removeListener,C.prototype.removeAllListeners=function(ne){var ue,se,ce;if(se=this._events,se===void 0)return this;if(se.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):se[ne]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete se[ne]),this;if(arguments.length===0){var he=Object.keys(se),ie;for(ce=0;ce<he.length;++ce)ie=he[ce],ie!=="removeListener"&&this.removeAllListeners(ie);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(ue=se[ne],typeof ue=="function")this.removeListener(ne,ue);else if(ue!==void 0)for(ce=ue.length-1;ce>=0;ce--)this.removeListener(ne,ue[ce]);return this};function J(ee,ne,ue){var se=ee._events;if(se===void 0)return[];var ce=se[ne];return ce===void 0?[]:typeof ce=="function"?ue?[ce.listener||ce]:[ce]:ue?oe(ce):Y(ce,ce.length)}C.prototype.listeners=function(ne){return J(this,ne,!0)},C.prototype.rawListeners=function(ne){return J(this,ne,!1)},C.listenerCount=function(ee,ne){return typeof ee.listenerCount=="function"?ee.listenerCount(ne):K.call(ee,ne)},C.prototype.listenerCount=K;function K(ee){var ne=this._events;if(ne!==void 0){var ue=ne[ee];if(typeof ue=="function")return 1;if(ue!==void 0)return ue.length}return 0}C.prototype.eventNames=function(){return this._eventsCount>0?D(this._events):[]};function Y(ee,ne){for(var ue=new Array(ne),se=0;se<ne;++se)ue[se]=ee[se];return ue}function re(ee,ne){for(;ne+1<ee.length;ne++)ee[ne]=ee[ne+1];ee.pop()}function oe(ee){for(var ne=new Array(ee.length),ue=0;ue<ne.length;++ue)ne[ue]=ee[ue].listener||ee[ue];return ne}function te(ee,ne){return new Promise(function(ue,se){function ce(ie){ee.removeListener(ne,he),se(ie)}function he(){typeof ee.removeListener=="function"&&ee.removeListener("error",ce),ue([].slice.call(arguments))}pe(ee,ne,he,{once:!0}),ne!=="error"&&le(ee,ce,{once:!0})})}function le(ee,ne,ue){typeof ee.on=="function"&&pe(ee,"error",ne,ue)}function pe(ee,ne,ue,se){if(typeof ee.on=="function")se.once?ee.once(ne,ue):ee.on(ne,ue);else if(typeof ee.addEventListener=="function")ee.addEventListener(ne,function ce(he){se.once&&ee.removeEventListener(ne,ce),ue(he)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof ee)}return events.exports}var hasRequiredEBMLReader;function requireEBMLReader(){if(hasRequiredEBMLReader)return EBMLReader;hasRequiredEBMLReader=1;var A=EBMLReader&&EBMLReader.__extends||function(){var O=function(C,i){return O=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(u,$){u.__proto__=$}||function(u,$){for(var N in $)Object.prototype.hasOwnProperty.call($,N)&&(u[N]=$[N])},O(C,i)};return function(C,i){if(typeof i!="function"&&i!==null)throw new TypeError("Class extends value "+String(i)+" is not a constructor or null");O(C,i);function u(){this.constructor=C}C.prototype=i===null?Object.create(i):(u.prototype=i.prototype,new u)}}();Object.defineProperty(EBMLReader,"__esModule",{value:!0});var B=requireEvents(),D=requireTools(),M=function(O){A(C,O);function C(){var i=O.call(this)||this;return i.logGroup="",i.hasLoggingStarted=!1,i.metadataloaded=!1,i.chunks=[],i.stack=[],i.segmentOffset=0,i.last2SimpleBlockVideoTrackTimecode=[0,0],i.last2SimpleBlockAudioTrackTimecode=[0,0],i.lastClusterTimecode=0,i.lastClusterPosition=0,i.timecodeScale=1e6,i.metadataSize=0,i.metadatas=[],i.cues=[],i.firstVideoBlockRead=!1,i.firstAudioBlockRead=!1,i.currentTrack={TrackNumber:-1,TrackType:-1,DefaultDuration:null,CodecDelay:null},i.trackTypes=[],i.trackDefaultDuration=[],i.trackCodecDelay=[],i.trackInfo={type:"nothing"},i.ended=!1,i.logging=!1,i.use_duration_every_simpleblock=!1,i.use_webp=!1,i.use_segment_info=!0,i.drop_default_duration=!0,i}return C.prototype.stop=function(){for(this.ended=!0,this.emit_segment_info();this.stack.length;)this.stack.pop(),this.logging&&console.groupEnd();this.logging&&this.hasLoggingStarted&&this.logGroup&&console.groupEnd()},C.prototype.emit_segment_info=function(){var i=this.chunks;if(this.chunks=[],this.metadataloaded){if(!this.use_segment_info)return;var N=this.lastClusterTimecode,F=this.duration,j=this.timecodeScale;this.emit("cluster",{timecode:N,data:i}),this.emit("duration",{timecodeScale:j,duration:F})}else{this.metadataloaded=!0,this.metadatas=i;var u=this.trackTypes.indexOf(1),$=this.trackTypes.indexOf(2);if(this.trackInfo=u>=0&&$>=0?{type:"both",trackNumber:u}:u>=0?{type:"video",trackNumber:u}:$>=0?{type:"audio",trackNumber:$}:{type:"nothing"},!this.use_segment_info)return;this.emit("metadata",{data:i,metadataSize:this.metadataSize})}},C.prototype.read=function(i){var u=this,$=!1;if(!this.ended){if(i.type==="m")if(i.isEnd)this.stack.pop();else{var N=this.stack[this.stack.length-1];if(N!=null&&N.level>=i.level){this.stack.pop(),this.logging&&console.groupEnd(),N.dataEnd=i.dataEnd,N.dataSize=i.dataEnd-N.dataStart,N.unknownSize=!1;var F=Object.assign({},N,{name:N.name,type:N.type,isEnd:!0});this.chunks.push(F)}this.stack.push(i)}if(i.type==="m"&&i.name=="Segment")this.segmentOffset!=0&&console.warn("Multiple segments detected!"),this.segmentOffset=i.dataStart,this.emit("segment_offset",this.segmentOffset);else if(i.type==="b"&&i.name==="SimpleBlock"){var j=D.ebmlBlock(i.data),J=j.timecode,K=j.trackNumber,Y=j.frames;if(this.trackTypes[K]===1){if(!this.firstVideoBlockRead&&(this.firstVideoBlockRead=!0,this.trackInfo.type==="both"||this.trackInfo.type==="video")){var re=this.lastClusterTimecode+J;this.cues.push({CueTrack:K,CueClusterPosition:this.lastClusterPosition,CueTime:re}),this.emit("cue_info",{CueTrack:K,CueClusterPosition:this.lastClusterPosition,CueTime:this.lastClusterTimecode}),this.emit("cue",{CueTrack:K,CueClusterPosition:this.lastClusterPosition,CueTime:re})}this.last2SimpleBlockVideoTrackTimecode=[this.last2SimpleBlockVideoTrackTimecode[1],J]}else if(this.trackTypes[K]===2){if(!this.firstAudioBlockRead&&(this.firstAudioBlockRead=!0,this.trackInfo.type==="audio")){var re=this.lastClusterTimecode+J;this.cues.push({CueTrack:K,CueClusterPosition:this.lastClusterPosition,CueTime:re}),this.emit("cue_info",{CueTrack:K,CueClusterPosition:this.lastClusterPosition,CueTime:this.lastClusterTimecode}),this.emit("cue",{CueTrack:K,CueClusterPosition:this.lastClusterPosition,CueTime:re})}this.last2SimpleBlockAudioTrackTimecode=[this.last2SimpleBlockAudioTrackTimecode[1],J]}this.use_duration_every_simpleblock&&this.emit("duration",{timecodeScale:this.timecodeScale,duration:this.duration}),this.use_webp&&Y.forEach(function(oe){var te=oe.slice(3,6).toString("hex");if(te==="9d012a"){var le=D.VP8BitStreamToRiffWebPBuffer(oe),pe=new Blob([le],{type:"image/webp"}),ee=u.duration;u.emit("webp",{currentTime:ee,webp:pe})}})}else i.type==="m"&&i.name==="Cluster"&&i.isEnd===!1?(this.firstVideoBlockRead=!1,this.firstAudioBlockRead=!1,this.emit_segment_info(),this.emit("cluster_ptr",i.tagStart),this.lastClusterPosition=i.tagStart):i.type==="u"&&i.name==="Timecode"?this.lastClusterTimecode=i.value:i.type==="u"&&i.name==="TimecodeScale"?this.timecodeScale=i.value:i.type==="m"&&i.name==="TrackEntry"?i.isEnd?(this.trackTypes[this.currentTrack.TrackNumber]=this.currentTrack.TrackType,this.trackDefaultDuration[this.currentTrack.TrackNumber]=this.currentTrack.DefaultDuration,this.trackCodecDelay[this.currentTrack.TrackNumber]=this.currentTrack.CodecDelay):this.currentTrack={TrackNumber:-1,TrackType:-1,DefaultDuration:null,CodecDelay:null}:i.type==="u"&&i.name==="TrackType"?this.currentTrack.TrackType=i.value:i.type==="u"&&i.name==="TrackNumber"?this.currentTrack.TrackNumber=i.value:i.type==="u"&&i.name==="CodecDelay"?this.currentTrack.CodecDelay=i.value:i.type==="u"&&i.name==="DefaultDuration"?this.drop_default_duration?(console.warn("DefaultDuration detected!, remove it"),$=!0):this.currentTrack.DefaultDuration=i.value:i.name==="unknown"&&console.warn(i);!this.metadataloaded&&i.dataEnd>0&&(this.metadataSize=i.dataEnd),$||this.chunks.push(i),this.logging&&this.put(i)}},Object.defineProperty(C.prototype,"duration",{get:function(){if(this.trackInfo.type==="nothing")return console.warn("no video, no audio track"),0;var i=0,u=0,$=0,N=this.trackDefaultDuration[this.trackInfo.trackNumber];if(typeof N=="number")i=N;else if(this.trackInfo.type==="both")if(this.last2SimpleBlockAudioTrackTimecode[1]>this.last2SimpleBlockVideoTrackTimecode[1]){i=(this.last2SimpleBlockAudioTrackTimecode[1]-this.last2SimpleBlockAudioTrackTimecode[0])*this.timecodeScale;var F=this.trackCodecDelay[this.trackTypes.indexOf(2)];typeof F=="number"&&(u=F),$=this.last2SimpleBlockAudioTrackTimecode[1]}else{i=(this.last2SimpleBlockVideoTrackTimecode[1]-this.last2SimpleBlockVideoTrackTimecode[0])*this.timecodeScale;var F=this.trackCodecDelay[this.trackTypes.indexOf(1)];typeof F=="number"&&(u=F),$=this.last2SimpleBlockVideoTrackTimecode[1]}else if(this.trackInfo.type==="video"){i=(this.last2SimpleBlockVideoTrackTimecode[1]-this.last2SimpleBlockVideoTrackTimecode[0])*this.timecodeScale;var F=this.trackCodecDelay[this.trackInfo.trackNumber];typeof F=="number"&&(u=F),$=this.last2SimpleBlockVideoTrackTimecode[1]}else if(this.trackInfo.type==="audio"){i=(this.last2SimpleBlockAudioTrackTimecode[1]-this.last2SimpleBlockAudioTrackTimecode[0])*this.timecodeScale;var F=this.trackCodecDelay[this.trackInfo.trackNumber];typeof F=="number"&&(u=F),$=this.last2SimpleBlockAudioTrackTimecode[1]}var j=(this.lastClusterTimecode+$)*this.timecodeScale+i-u,J=j/this.timecodeScale;return Math.floor(J)},enumerable:!1,configurable:!0}),C.prototype.addListener=function(i,u){return O.prototype.addListener.call(this,i,u)},C.prototype.put=function(i){this.hasLoggingStarted||(this.hasLoggingStarted=!0,this.logging&&this.logGroup&&console.groupCollapsed(this.logGroup)),i.type==="m"?i.isEnd?console.groupEnd():console.group(i.name+":"+i.tagStart):i.type==="b"?console.log(i.name,i.type):console.log(i.name,i.tagStart,i.type,i.value)},C}(B.EventEmitter);return EBMLReader.default=M,EBMLReader}var hasRequiredEbml;function requireEbml(){return hasRequiredEbml||(hasRequiredEbml=1,function(A){var B=ebml&&ebml.__createBinding||(Object.create?function(u,$,N,F){F===void 0&&(F=N),Object.defineProperty(u,F,{enumerable:!0,get:function(){return $[N]}})}:function(u,$,N,F){F===void 0&&(F=N),u[F]=$[N]}),D=ebml&&ebml.__exportStar||function(u,$){for(var N in u)N!=="default"&&!Object.prototype.hasOwnProperty.call($,N)&&B($,u,N)};Object.defineProperty(A,"__esModule",{value:!0}),A.tools=A.Reader=A.Encoder=A.Decoder=void 0,D(requireEBML(),A);var M=requireEBMLDecoder();A.Decoder=M.default;var O=requireEBMLEncoder();A.Encoder=O.default;var C=requireEBMLReader();A.Reader=C.default;var i=requireTools();A.tools=i}(ebml)),ebml}var hasRequiredLib;function requireLib(){if(hasRequiredLib)return lib;hasRequiredLib=1;var A=lib&&lib.__awaiter||function(O,C,i,u){function $(N){return N instanceof i?N:new i(function(F){F(N)})}return new(i||(i=Promise))(function(N,F){function j(Y){try{K(u.next(Y))}catch(re){F(re)}}function J(Y){try{K(u.throw(Y))}catch(re){F(re)}}function K(Y){Y.done?N(Y.value):$(Y.value).then(j,J)}K((u=u.apply(O,C||[])).next())})},B=lib&&lib.__generator||function(O,C){var i={label:0,sent:function(){if(N[0]&1)throw N[1];return N[1]},trys:[],ops:[]},u,$,N,F;return F={next:j(0),throw:j(1),return:j(2)},typeof Symbol=="function"&&(F[Symbol.iterator]=function(){return this}),F;function j(K){return function(Y){return J([K,Y])}}function J(K){if(u)throw new TypeError("Generator is already executing.");for(;i;)try{if(u=1,$&&(N=K[0]&2?$.return:K[0]?$.throw||((N=$.return)&&N.call($),0):$.next)&&!(N=N.call($,K[1])).done)return N;switch($=0,N&&(K=[K[0]&2,N.value]),K[0]){case 0:case 1:N=K;break;case 4:return i.label++,{value:K[1],done:!1};case 5:i.label++,$=K[1],K=[0];continue;case 7:K=i.ops.pop(),i.trys.pop();continue;default:if(N=i.trys,!(N=N.length>0&&N[N.length-1])&&(K[0]===6||K[0]===2)){i=0;continue}if(K[0]===3&&(!N||K[1]>N[0]&&K[1]<N[3])){i.label=K[1];break}if(K[0]===6&&i.label<N[1]){i.label=N[1],N=K;break}if(N&&i.label<N[2]){i.label=N[2],i.ops.push(K);break}N[2]&&i.ops.pop(),i.trys.pop();continue}K=C.call(O,i)}catch(Y){K=[6,Y],$=0}finally{u=N=0}if(K[0]&5)throw K[1];return{value:K[0]?K[1]:void 0,done:!0}}};Object.defineProperty(lib,"__esModule",{value:!0});var D=requireEbml();function M(O){return A(this,void 0,void 0,function(){var C,i,u,$,N,F,j,J,K,Y,re,oe;return B(this,function(te){switch(te.label){case 0:if(!O)throw Error("call to fixWebmDuration requires a blob");C=new D.Decoder,i=new D.Reader,u=O.stream(),$=u.getReader(),te.label=1;case 1:return[4,$.read()];case 2:return N=te.sent(),F=N.done,j=N.value,F?(i.stop(),[3,3]):(J=C.decode(j),J=J?.filter(function(le){return le.type!=="unknown"}),J.forEach(function(le){i.read(le)}),j=null,[3,1]);case 3:return K=D.tools.makeMetadataSeekable(i.metadatas,i.duration,i.cues),Y=new Blob([K],{type:O.type}),re=O.slice(i.metadataSize),oe=new Blob([Y,re],{type:O.type}),[2,oe]}})})}return lib.default=M,lib}var libExports=requireLib();const fixWebmDuration=getDefaultExportFromCjs(libExports);class StreamRecorder{#e;#n=!1;#t=!1;#r=0;#o=0;#i=0;#a=0;#c=0;onchange=B=>{};onDurationChange=B=>{};constructor(){}start=async(B="")=>{B||(B=`video_Record_${E$1(Date.now())}`);let D=[];return navigator.mediaDevices.getDisplayMedia({audio:!0,video:!0}).then(M=>{const O=M.getTracks();for(const i of O)i.onended=()=>this.stop();this.#n=!0,this.#t=!1,this.#e=new MediaRecorder(M),this.#e.start();const C=new Date().getTime();this.#r=C,this.#i=C,this.#l(),this.#s(),this.#e.addEventListener("dataavailable",i=>{D.push(i.data)}),this.#e.addEventListener("stop",async()=>{this.#n=!1;const i=new Date().getTime();this.#o=i,this.#a+=i-this.#i,this.#l(),clearInterval(this.#c);const u=M.getTracks();for(const J of u)J.stop();if(this.#e===null)return;const $=new Blob(D,{type:this.#e.mimeType}),N=await fixWebmDuration($),F=URL.createObjectURL(N),j=document.createElement("a");j.href=F,j.download=`${B}.mp4`,j.click(),URL.revokeObjectURL(F),D=[],this.#e=null})})};pause=async()=>{await new Promise(D=>setTimeout(()=>D(!0),300)),this.#e?.pause(),this.#t=!0;const B=new Date().getTime();this.#a+=B-this.#i,this.#l(),clearInterval(this.#c)};resume=async()=>{this.#e?.resume(),this.#t=!1;const B=new Date().getTime();this.#i=B,this.#l(),this.#s()};stop=async()=>{this.#e?.stop()};getDuration=()=>{if(this.#i===0)return 0;let B=this.#a;const D=new Date().getTime();if(this.#n&&this.#t===!1){const M=D-this.#i;this.#i=D,B=B+M}return B};getInfo=()=>({active:this.#n,pause:this.#t,startTime:this.#r,endTime:this.#o,duration:this.#a});#l=()=>{const B=this.getInfo();this.onchange(B)};#s=()=>{clearInterval(this.#c),this.#c=window.setInterval(()=>{this.#a=this.getDuration(),this.onDurationChange(this.#a)},500)}}var l=Object.defineProperty,y=A=>{throw TypeError(A)},q=(A,B,D)=>B in A?l(A,B,{enumerable:!0,configurable:!0,writable:!0,value:D}):A[B]=D,s=(A,B,D)=>q(A,typeof B!="symbol"?B+"":B,D),P=(A,B,D)=>B.has(A)||y("Cannot "+D),n=(A,B,D)=>(P(A,B,"read from private field"),D?D.call(A):B.get(A)),a=(A,B,D)=>B.has(A)?y("Cannot add the same private member more than once"):B instanceof WeakSet?B.add(A):B.set(A,D),d,v,o;class p{constructor(B={}){s(this,"queue",[]),s(this,"timer",0),s(this,"activeIndex",0),s(this,"activePromise"),s(this,"options",{timeout:0}),s(this,"add",(D,M={})=>new Promise(async(O,C)=>{const i=M.timeout||this.options.timeout,u=M.key||n(this,d).call(this),$=M.describe||"";if(this.queue.findIndex(F=>F.key===u)!==-1)return C(`${u} is exist.`);const N={key:u,func:D,describe:$,timeout:i,resolve:O,reject:C};this.queue.unshift(N),this.activePromise||n(this,o).call(this)})),s(this,"clear",()=>{this.queue=[],this.activePromise=void 0,clearTimeout(this.timer)}),s(this,"retry",()=>{n(this,o).call(this)}),a(this,d,()=>(this.activeIndex=this.activeIndex+1,`${this.activeIndex}`)),a(this,v,D=>{const M=this.queue.findIndex(O=>O.key===D);this.queue.splice(M,1)}),a(this,o,async()=>{const D=this.queue.length;if(D===0)return;const M=D-1,O=this.queue[M];this.activePromise=O;const{key:C,func:i,resolve:u,reject:$,timeout:N}=this.activePromise;N&&(this.timer=window.setTimeout(()=>{$(`pr-async-queue: ${C} is timeout.`),n(this,o).call(this)},N)),await i().then(u).catch($).finally(()=>{clearTimeout(this.timer),this.activePromise=void 0,n(this,v).call(this,C),n(this,o).call(this)})}),this.options={timeout:0,...B}}}d=new WeakMap,v=new WeakMap,o=new WeakMap;const enum_iceState={connecting:"连接中",connected:"已连接",disconnected:"已断开",failed:"连接错误",closed:"已关闭"};ht(enum_iceState);class PrResolves{resolvesMap=new Map;index=0;constructor(){}add=(B,D=()=>!1,M=0)=>new Promise(O=>{if(D())return O(!0);this.resolvesMap.has(B)||this.resolvesMap.set(B,new Map),this.index++;const u=`${this.index}`;if(M=Math.max(0,M),M===0){this.resolvesMap.get(B)?.set(u,{resolve:O,timer:0});return}const $=window.setTimeout(()=>{this.emit(B)},M);this.resolvesMap.get(B)?.set(u,{resolve:O,timer:$})});emit=async B=>{const D=this.resolvesMap.get(B);if(!D)return;const M=[...D.keys()];for(const O of M){const C=D.get(O);C&&(clearTimeout(C.timer),C.resolve(),D.delete(O))}}}class RoomBase{options={appid:"",sdkToken:"",roomId:"",userId:"",earlyId:wt(),callType:0,debug:!1,reportErr:!0,logUrl:"https://logs1.quickvo.org",newPublishAutoSubscribe:!0};sfuPush=0;sfuPull=0;p2pPush=0;p2pPull=0;historical_publish_mediaTypes=[];historical_subscribe_mediaTypes=[];prResolves=new PrResolves;sdk_service_version="1.0.8";sdk_session="";isEarly=!1;isInRoom=!1;asyncQueue;await_remote_publish_users=[];roomState="ready";iceState="closed";createAt=Date.now();cwsIns;peerIns;sfuOffsetAverageQuality=0;transceiverMap=new Map;transceiverTrackMap=new Map;sendChannel;receiveChannel;userMap=new Map;p2pMap=new Map;setLocalStreamActiveMap=new Map;phoneyStreams=new Map;recorder=new StreamRecorder;networkQualityTester=new NetworkQualityTester;mediaDevicesErrInfo={microphoneCamera_audio:"",microphoneCamera_video:"",screenSharing_video:"",screenSharing_audio:""};constructor(B){this.setOptions(B),this.cwsIns=new CallsWebSocket({...B}),this.asyncQueue=new p}hasAsyncTask=B=>{let D=!1;return this.asyncQueue.activePromise?.describe===B&&(D=!0),D===!1&&this.asyncQueue.queue.find(O=>O.describe===B)&&(D=!0),D};createUserUpdateStreams=(B=[])=>{const D={};for(const M of B)D[M]=wt();return D};reportLogs=(B,D="未知错误")=>{const M=this.getOptions(),{appid:O,userId:C,earlyId:i="",logUrl:u,reportErr:$}=M;if(!$)return;const N="web",F=j=>({ws_c_timeout:0,webrtc_c_timeout:1,join_room_error:2,publish_error:3,subscribe_error:4,close_track_error:5,heartbeat_e_timeout:6,heartbeat_i_timeout:7,quit_room_error:8})[j].toString();{const j=F(B),J={origin:N,type:j,app_id:O,user_id:C,ins_id:i,desc:D},K=btoa(encodeURI(JSON.stringify(J))),Y=`${u}/upload/log?log_key=${K}`;{const re=localStorage.getItem("#quickvo.logs")||JSON.stringify([]),te=new TextEncoder().encode(re),le=pako.deflate(te,{gzip:!0});this.options.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->quickvo: reportLogs",{obj:J,url:Y,size:it(le.byteLength)}),fetch(Y,{headers:{"Content-Type":"multipart/form-data"},method:"POST",body:le})}}};initPhoneyStreams=(B,D=[])=>{D.length===0&&(D=mediaType_keys);for(const M of D){const O=this.phoneyStreams.get(M);if(O){const C=O.getTracks();for(const i of C)i.stop()}switch(M){case"microphoneCamera_audio":this.phoneyStreams.set("microphoneCamera_audio",createMutedAudioStream(B));break;case"microphoneCamera_video":this.phoneyStreams.set("microphoneCamera_video",createFakeVideoStream());break;case"screenSharing_audio":this.phoneyStreams.set("screenSharing_audio",createMutedAudioStream(B));break;case"screenSharing_video":this.phoneyStreams.set("screenSharing_video",createFakeVideoStream());break}}};getPhoneyStreams=B=>this.phoneyStreams.get(B);getRoomInfo=()=>{const{options:B,roomState:D,createAt:M}=this;return{...B,roomState:D,createAt:M}};setRoomState=B=>{if(this.roomState===B)return;this.roomState=B;const D=enum_roomState[B],M={state:B,stateStr:D};this.cwsIns.emitNotify("onRoomState",{code:200,data:M,desc:"room state is change."})};setIceState=B=>{if(this.iceState===B)return;this.iceState=B;const D=enum_iceState[B],M={state:B,stateStr:D};this.cwsIns.emitNotify("onIceState",{code:200,data:M,desc:"ice state is change."})};setOptions=B=>(this.options={...this.options,...B},this.options);getOptions=()=>this.options;stopStream=async B=>{const D=B.getTracks();for(const M of D)M.stop()};getMediaDevicesErrInfo=async()=>{try{const B=await navigator.mediaDevices.enumerateDevices();B.find(M=>M.kind==="audioinput")||(this.mediaDevicesErrInfo.microphoneCamera_audio="audioinput is not available."),B.find(M=>M.kind==="videoinput")||(this.mediaDevicesErrInfo.microphoneCamera_video="videoinput is not available.")}catch(B){this.options.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->quickvo: getMediaDevicesErrInfo is error.",B)}return this.mediaDevicesErrInfo};getUserMediaKey=(B,D)=>`${B}-${D}`;getCallAction=async B=>{let D="";const M=C=>B.findIndex(({type:u,enabled:$=!0})=>u===C&&$)===-1?"0":"1";return D=`${M(0)}${D}`,D=`${M(1)}${D}`,D=`${M(2)}${D}`,D=`${M(3)}${D}`,parseInt(D,2)};getCallActionMap=(B=0)=>{const M=Number(B).toString(2).padStart(4,"0").split(""),[O,C,i,u]=M;return{microphoneCamera_audio:!!Number(u),microphoneCamera_video:!!Number(i),screenSharing_video:!!Number(C),screenSharing_audio:!!Number(O)}};getBanBehaviorMap=(B=0)=>{const M=Number(B).toString(2).padStart(4,"0").split(""),[O,C,i,u]=M;return{microphoneCamera_audio:!!Number(u),microphoneCamera_video:!!Number(i),screenSharing_video:!!Number(C),screenSharing_audio:!!Number(O)}};getAverageVolume=(B,D)=>{B.getByteFrequencyData(D);let M=0;for(let C=0;C<D.length;C++)M+=D[C];return Math.ceil(M/D.length)};getTrackNamesFormTracks=(B,D=[],M="trackName")=>{const O=[];for(const C of B){const{type:i}=C;if(D.length===0||D.includes(i)){const u=C[M];u&&O.push(`${u}`)}}return O};usersFilter=B=>dt(B,["id","isSelf","isOwner","joinTime","tracks","network","permissions","isPublished","callAction","callActionStr","callActionMap","banBehavior","banBehaviorStr","banBehaviorMap","useP2P"]).sort((O,C)=>O.id.localeCompare(C.id,"en"))}var m=Object.defineProperty,G=(A,B,D)=>B in A?m(A,B,{enumerable:!0,configurable:!0,writable:!0,value:D}):A[B]=D,e=(A,B,D)=>G(A,typeof B!="symbol"?B+"":B,D);let g$1=class{constructor(B,D){e(this,"inputStream",new MediaStream),e(this,"outputStream",new MediaStream),e(this,"inputGain",1),e(this,"enhanceGain",1),e(this,"bgsGain",1),e(this,"bgmGain",1),e(this,"outputGain",1),e(this,"mixAudioMap",new Map),e(this,"audioContext",new AudioContext),e(this,"sourceNode"),e(this,"inputGainNode"),e(this,"enhanceGainNode"),e(this,"bgsGainNode"),e(this,"bgmGainNode"),e(this,"analyserNode"),e(this,"analyserArrayData"),e(this,"outputGainNode"),e(this,"destinationNode"),e(this,"filterStream",M=>M),e(this,"stop",()=>{{const M=this.inputStream.getTracks();for(const O of M)O.stop(),this.inputStream.removeTrack(O)}}),e(this,"getStream",()=>this.filterStream(this.outputStream)),e(this,"setMute",(M=!0)=>{M?this.analyserNode.disconnect(this.outputGainNode):this.analyserNode.connect(this.outputGainNode)}),e(this,"setInputGain",M=>{this.inputGain=M,this.inputGainNode.gain.setValueAtTime(M,this.audioContext.currentTime)}),e(this,"setEnhanceGain",async M=>{this.enhanceGain=M+1,this.enhanceGainNode.gain.setValueAtTime(this.enhanceGain,this.audioContext.currentTime)}),e(this,"setBgsGain",M=>{this.bgsGain=M,this.bgsGainNode.gain.setValueAtTime(M,this.audioContext.currentTime)}),e(this,"setBgmGain",M=>{this.bgmGain=M,this.bgmGainNode.gain.setValueAtTime(M,this.audioContext.currentTime)}),e(this,"setOutputGain",M=>{this.outputGain=M,this.outputGainNode.gain.setValueAtTime(this.outputGain,this.audioContext.currentTime)}),e(this,"getVolume",()=>{const{analyserNode:M,analyserArrayData:O}=this;M.getByteFrequencyData(O);let C=0;for(let i=0;i<O.length;i++)C+=O[i];return Math.ceil(C/O.length)}),e(this,"mixAudio",(M,O="bgm")=>new Promise(async(C,i)=>{try{{const N=this.mixAudioMap.get(O);N&&N.stop()}const u=O==="bgs"?this.bgsGainNode:this.bgmGainNode,$=this.audioContext.createBufferSource();this.mixAudioMap.set(O,$),$.buffer=M,$.connect(u),$.onended=()=>{$.disconnect(u),this.mixAudioMap.delete(O),C(!0)},$.start(0)}catch(u){i(u)}})),e(this,"mixAudioStop",M=>{const O=this.mixAudioMap.get(M);O?.stop()}),e(this,"changeMix",(M,O)=>{const C=M==="bgs"?this.bgsGainNode:this.bgmGainNode;O?C.connect(this.destinationNode):C.disconnect(this.destinationNode)}),D&&(this.audioContext=D),this.inputStream=B,this.sourceNode=this.audioContext.createMediaStreamSource(this.inputStream),this.inputGainNode=this.audioContext.createGain(),this.inputGainNode.gain.setValueAtTime(this.inputGain,this.audioContext.currentTime),this.enhanceGainNode=this.audioContext.createGain(),this.enhanceGainNode.gain.setValueAtTime(this.enhanceGain,this.audioContext.currentTime),this.bgsGainNode=this.audioContext.createGain(),this.bgsGainNode.gain.setValueAtTime(this.bgsGain,this.audioContext.currentTime),this.bgmGainNode=this.audioContext.createGain(),this.bgmGainNode.gain.setValueAtTime(this.bgmGain,this.audioContext.currentTime),this.analyserNode=this.audioContext.createAnalyser(),this.analyserNode.fftSize=512,this.analyserArrayData=new Uint8Array(this.analyserNode.frequencyBinCount),this.outputGainNode=this.audioContext.createGain(),this.outputGainNode.gain.setValueAtTime(this.outputGain,this.audioContext.currentTime),this.destinationNode=this.audioContext.createMediaStreamDestination(),this.outputStream=this.destinationNode.stream;{const{sourceNode:M,inputGainNode:O,enhanceGainNode:C,bgsGainNode:i,bgmGainNode:u,analyserNode:$,outputGainNode:N,destinationNode:F}=this;M.connect(O),O.connect(C),C.connect($),i.connect($),u.connect($),C.connect(F),i.connect(F),u.connect(F),$.connect(N),N.connect(this.audioContext.destination)}this.setMute(!0),this.audioContext.resume()}};class RoomMedias extends RoomBase{#e=[];#n=new Map;#t=new Map;#r=new Map;#o=new Map;#i=new Map;localStreamsActionMap=new Map;#a=new Map;audioContext=new(window.AudioContext||window.webkitAudioContext);constructor(B){super(B),this.#u(),this.#l(),this.#c(),document.addEventListener("click",()=>{this.audioContext?.state==="suspended"&&this.audioContext.resume()})}initMediaPhoneyStreams=(B=[])=>this.initPhoneyStreams(this.audioContext,B);initLocalStreamsFilter=()=>{for(const B of mediaType_keys){const D=async M=>M;this.#a.set(B,D)}};setLocalFilterStream=(B,D)=>{this.#a.set(B,D)};#c=()=>{this.#t.set("microphoneCamera_audio",{autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0}),this.#t.set("microphoneCamera_video",{frameRate:{min:10,ideal:30}}),this.#t.set("screenSharing_video",{frameRate:{min:10,ideal:30}}),this.#t.set("screenSharing_audio",{autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0})};#l=()=>{this.#n.set("audioinput","default"),this.#n.set("videoinput","default"),this.#n.set("audiooutput","default")};emitNotifyUpdateUsersStreams=async B=>{this.cwsIns.emitNotify("onRoomUsersStreams",{code:200,data:B,desc:"users streams is change."})};initUserMediaStreamContext=async(B,D,M,O)=>{const[C]=M.getTracks();if(M.active===!1||!C)return;O&&this.removeUserMediaStreamContext(B,D);const i=this.getUserMediaKey(B,D),{kind:u}=C;switch(u){case"audio":{const $=new MediaStream;$.addTrack(C);const N=new g$1($,this.audioContext);this.#r.set(i,N)}break;case"video":{const $=new VideoMediaContext(C);this.#o.set(i,$)}break}};getUserMediaStreamContext=(B,D)=>{const M=this.getUserMediaKey(B,D);if(["microphoneCamera_audio","screenSharing_audio"].includes(D))return this.#r.get(M);if(["microphoneCamera_video","screenSharing_video"].includes(D))return this.#o.get(M)};getUserAudioMediaStreamContext=(B,D)=>{const M=this.getUserMediaKey(B,D);return this.#r.get(M)};removeUserMediaStreamContext=(B,D)=>{const M=this.getUserMediaKey(B,D);if(["microphoneCamera_audio","screenSharing_audio"].includes(D))return this.#r.get(M)?.stop(),this.#r.delete(M);if(["microphoneCamera_video","screenSharing_video"].includes(D))return this.#o.get(M)?.stop(),this.#o.get(M)};getUserStream=(B,D)=>this.getUserMediaStreamContext(B,D)?.getStream()||new MediaStream;getUserStreams=(B,D=[])=>{D.length===0&&(D=mediaType_keys);const M={};for(const O of D){const C=this.getUserStream(B,O);M[O]=C}return M};removeUserStreams=async(B,D=[])=>{D.length===0&&(D=mediaType_keys);for(const M of D)this.removeUserMediaStreamContext(B,M)};clearUserStreams=()=>{{const B=this.#r.values();for(const D of B)D.stop();this.#r=new Map}{const B=this.#o.values();for(const D of B)D.stop();this.#o=new Map}};setMediaTrackConstraints=async(B,D)=>{this.#t.set(B,D);const M=await this.getLocalStream(B);if(!M)return;const O=M.getTracks();if(O.length!==0)for(const C of O){const i=C.getConstraints(),$={...this.#t.get(B),...i,...D};await C.applyConstraints($)}};stopLocalStreams=async(B=[])=>{B.length===0&&(B=mediaType_keys);for(const D of B){const M=this.#i.get(D);M&&await this.stopStream(M),this.#i.delete(D)}};addLocalStream=(B,D)=>{const M=this.#i.get(B);M&&this.stopStream(M),this.#i.set(B,D)};initLocalStream=async B=>{switch(B){case"microphoneCamera_audio":{const D=this.#n.get("audioinput"),M=this.#t.get("microphoneCamera_audio"),O=await navigator.mediaDevices.getUserMedia({audio:{deviceId:D,...M},video:!1});this.addLocalStream("microphoneCamera_audio",O)}break;case"microphoneCamera_video":{const D=this.#n.get("videoinput"),M=this.#t.get("microphoneCamera_video"),O=await navigator.mediaDevices.getUserMedia({audio:!1,video:{deviceId:D,...M}});this.addLocalStream("microphoneCamera_video",O)}break;case"microphoneCamera":{const D=this.#n.get("audioinput"),M=this.#n.get("videoinput"),O=this.#t.get("microphoneCamera_audio"),C=this.#t.get("microphoneCamera_video"),u=(await navigator.mediaDevices.getUserMedia({audio:{deviceId:D,...O},video:{deviceId:M,...C}})).getTracks();for(const $ of u){const{kind:N}=$;if(N==="audio"){const F=new MediaStream;F.addTrack($),this.addLocalStream("microphoneCamera_audio",F)}if(N==="video"){const F=new MediaStream;F.addTrack($),this.addLocalStream("microphoneCamera_video",F)}}}break;case"screenSharing_audio":{const D=this.#t.get("screenSharing_audio"),O=(await navigator.mediaDevices.getDisplayMedia({audio:!0,video:!0,...D})).getTracks();for(const C of O){const{kind:i}=C;if(i==="audio"){const u=new MediaStream;u.addTrack(C),this.addLocalStream("screenSharing_audio",u)}}}break;case"screenSharing_video":{const D=this.#t.get(B),O=(await navigator.mediaDevices.getDisplayMedia({audio:!1,video:!0,...D})).getTracks();for(const C of O){const{kind:i}=C;if(i==="video"){const u=new MediaStream;u.addTrack(C),this.addLocalStream("screenSharing_video",u)}}}break;case"screenSharing":{const D=this.#t.get("screenSharing_audio"),M=this.#t.get("screenSharing_video"),C=(await navigator.mediaDevices.getDisplayMedia({audio:!0,video:!0,...D,...M})).getTracks();for(const i of C){const{kind:u}=i;if(u==="audio"){const $=new MediaStream;$.addTrack(i),this.addLocalStream("screenSharing_audio",$)}if(u==="video"){const $=new MediaStream;$.addTrack(i),this.addLocalStream("screenSharing_video",$)}}}break}};getLocalStream=async B=>{const D=this.#i.get(B),M=this.#a.get(B);let O=D;return D&&M&&(O=await M(D)),O};getLocalStreams=async(B=[])=>{B.length===0&&(B=mediaType_keys);const D={};for(const M of B)D[M]=await this.getLocalStream(M);return D};#s=async()=>!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices?(console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->quickvo: 不支持 enumerateDevices"),[]):(await navigator.mediaDevices.enumerateDevices().then(B=>{const D=B.filter(M=>!["communications"].includes(M.deviceId));this.#e=D.sort((M,O)=>M.label.localeCompare(O.label,"zh-Hans-CN",{sensitivity:"accent"}))}).catch(function(B){console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->quickvo: getEnumerateDevices is err",B)}),this.#e);#u=()=>{navigator.mediaDevices&&(navigator.mediaDevices.ondevicechange=async()=>{await this.#s(),this.cwsIns.emitNotify("onDevicechange",{code:200,data:{},desc:"device is change."})}),this.#s()};getMediaDeviceKind=B=>this.#n.get(B);changeAudiooutput=async()=>{try{const B=this.#n.get("audiooutput");await this.audioContext.setSinkId(B)}catch(B){console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->quickvo: setSinkId is error.",B)}};setDeviceKind=(B,D)=>{this.#n.set(B,D)};setAudioOutputDevice=B=>this.setDeviceKind("audiooutput",B);getEnumerateDevices=async B=>(await this.#s(),this.#e.filter(M=>M.kind===B));getEnumerateAudioinputDevices=()=>this.getEnumerateDevices("audioinput");getEnumerateAudioOutputDevices=()=>this.getEnumerateDevices("audiooutput");getEnumerateVideoinputDevices=()=>this.getEnumerateDevices("videoinput")}const getNetworkQuality=(A,B,D)=>{const M=Number(A),O=Number(B),C=Number(D);let i=0;return M<.03&&O<100&&C<.05?i=5:M<.06&&O<160&&C<.1?i=4:M<.1&&O<250&&C<.15?i=3:M<.15&&O<400&&C<.2?i=2:i=1,Number(i)};class PeerAnalyzeStats{pc;network={inboundBytes:0,outboundBytes:0,lostRate:"0.00",roundTripTime:"0",jitter:"0",quality:0,averageQuality:0};reports=[];averageQualitys=[];timer=0;constructor(){}onNetwork=B=>{};getNetwork=()=>this.network;getAverageQuality=()=>this.network.averageQuality;start=B=>{this.stop(),this.network={inboundBytes:0,outboundBytes:0,lostRate:"0.00",roundTripTime:"0",jitter:"0",quality:0,averageQuality:0},this.reports=[],this.averageQualitys=[],this.pc=B,clearInterval(this.timer);const D=async()=>{this.pc?.connectionState==="connected"&&this.analyzeStats()};this.timer=window.setInterval(D,1*1e3)};analyzeStats=async()=>{try{if(!this.pc)return;const B=await this.pc.getStats(),D=["inbound-rtp","remote-inbound-rtp","outbound-rtp","transport"],O=[...B.values()].filter(ne=>D.includes(ne.type));let C=0,i=0,u=0,$=0,N=0,F=0,j=[],J=[];for(const ne of this.reports){const{packetsSent:ue,packetsLost:se}=ne;ue&&(u+=ue),se&&($+=se)}this.reports=O;for(const ne of this.reports){const{bytesSent:ue,bytesReceived:se,packetsSent:ce,packetsLost:he,roundTripTime:ie,jitter:fe}=ne;ue&&(i=ue),se&&(C=se),ce&&(N+=ce),he&&(F+=he),ie&&j.push((ie*100).toFixed(2)),fe&&J.push(fe.toFixed(2))}J.sort().reverse(),j.sort().reverse();const K=N-u,Y=F-$,re=K===0?"0.00":Math.max(0,Y/K).toFixed(2),[oe="0"]=j,[te="0"]=J,le=getNetworkQuality(re,oe,te);this.averageQualitys.unshift(le),this.averageQualitys=this.averageQualitys.slice(0,10);const pe=this.averageQualitys.length===10?Math.round(this.averageQualitys.reduce((ne,ue)=>ne+ue)/this.averageQualitys.length):0,ee={outboundBytes:i,inboundBytes:C,lostRate:re,roundTripTime:oe,jitter:te,quality:le,averageQuality:pe};this.network=ee,this.onNetwork(this.network)}catch(B){console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->quickvo: analyzeStats is err.",B)}};getReports=async(B=[])=>B.length===0?this.reports:this.reports.filter(D=>B.includes(D.mid));stop=()=>{clearInterval(this.timer)}}class P2P{prResolves=new PrResolves;phoneyStreams=new Map;recv_peer_ins;recv_icecandidates=[];recv_candidate_collected=!1;recv_transceiverMap=new Map;recvPeerAnalyzeStatsIns=new PeerAnalyzeStats;send_peer_ins;send_icecandidates=[];send_candidate_collected=!1;send_transceiverMap=new Map;sendPeerAnalyzeStatsIns=new PeerAnalyzeStats;tracks=[];reports=[];getPeerStatsTimer=0;constructor(B){this.phoneyStreams=B}onSendPeerNetwork=B=>{};onRecvPeerNetwork=B=>{};getPhoneyStreams=B=>this.phoneyStreams.get(B);sendIceConnected=()=>{const B=()=>this.send_peer_ins.iceConnectionState==="connected";return this.prResolves.add("sendIceConnected",B)};recvIceConnected=()=>{const B=()=>this.recv_peer_ins.iceConnectionState==="connected";return this.prResolves.add("recvIceConnected",B)};sendCandidateCollected=()=>{const B=()=>this.send_candidate_collected;return this.prResolves.add("sendCandidateCollected",B)};recvCandidateCollected=()=>{const B=()=>this.recv_candidate_collected;return this.prResolves.add("recvCandidateCollected",B)};getSendIcecandidates=async()=>(await this.sendCandidateCollected(),this.send_icecandidates);getRecvIcecandidates=async()=>(await this.recvCandidateCollected(),this.recv_icecandidates);setOffered=()=>{const B=()=>this.send_peer_ins?.remoteDescription;return this.prResolves.add("setOffered",B)};initSenderPc=async()=>{await this.clearSenderPc(),this.send_peer_ins=new RTCPeerConnection({iceServers:[{urls:"stun:stun.cloudflare.com:3478"}]});const B=M=>{M.candidate?this.send_icecandidates.push(M.candidate):(this.send_candidate_collected=!0,this.prResolves.emit("sendCandidateCollected"))};this.send_peer_ins.addEventListener("icecandidate",B);const D=M=>{const O=M.target.connectionState;switch(O){case"connected":console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#00b60f;",`------->quickvo: send_peer_ins: ${O}`),this.prResolves.emit("sendIceConnected");break;case"failed":case"closed":console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#b60000;",`------->quickvo: send_peer_ins: ${O}`),this.send_peer_ins.removeEventListener("icecandidate",B),this.send_peer_ins.removeEventListener("connectionstatechange",D);break;default:console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#b64900;",`------->quickvo: send_peer_ins: ${O}`);break}};this.send_peer_ins.addEventListener("connectionstatechange",D),this.sendPeerAnalyzeStatsIns?.start(this.send_peer_ins)};clearSenderPc=async()=>{this.sendPeerAnalyzeStatsIns.stop(),this.send_icecandidates=[],this.send_candidate_collected=!1,this.send_transceiverMap=new Map,this.send_peer_ins&&this.send_peer_ins.close(),clearInterval(this.getPeerStatsTimer)};initRecvPc=async()=>{await this.clearRecvPc(),this.recv_peer_ins=new RTCPeerConnection({iceServers:[{urls:"stun:stun.cloudflare.com:3478"}]});const B=M=>{M.candidate?this.recv_icecandidates.push(M.candidate):(this.recv_candidate_collected=!0,this.prResolves.emit("recvCandidateCollected"))};this.recv_peer_ins.addEventListener("icecandidate",B);const D=M=>{const O=M.target.connectionState;switch(O){case"connected":console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#00b60f;",`------->quickvo: recv_peer_ins: ${O}`),this.prResolves.emit("recvIceConnected");break;case"failed":case"closed":console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#b60000;",`------->quickvo: recv_peer_ins: ${O}`),this.recv_peer_ins.removeEventListener("icecandidate",B),this.recv_peer_ins.removeEventListener("connectionstatechange",D);break;default:console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#b64900;",`------->quickvo: recv_peer_ins: ${O}`);break}};this.recv_peer_ins.addEventListener("connectionstatechange",D),this.recvPeerAnalyzeStatsIns?.start(this.recv_peer_ins)};clearRecvPc=async()=>{this.recvPeerAnalyzeStatsIns.stop(),this.recv_icecandidates=[],this.recv_candidate_collected=!1,this.recv_transceiverMap=new Map,this.recv_peer_ins&&this.recv_peer_ins.close()};initSenders=async(B=[])=>{const D=this.send_peer_ins.getTransceivers();for(const M of D){const{mid:O}=M,C=B.find($=>$.mid===O);if(!C)continue;const{type:i}=C;if(i===void 0)continue;const u=mediaType_keys[i];M.direction="sendonly",this.send_transceiverMap.set(u,M)}};addSenders=async(B=[])=>{const D=[];for(const M of B){if(this.send_transceiverMap.get(M))continue;const C=this.getPhoneyStreams(M),[i]=C.getTracks(),u=this.send_peer_ins.addTransceiver(i,{direction:"sendonly"});this.send_transceiverMap.set(M,u),D.push(M)}return D};addRecvs=async(B=[])=>{const D=[];for(const M of B)if(!this.recv_transceiverMap.get(M))switch(M){case"microphoneCamera_audio":case"screenSharing_audio":{const C=this.recv_peer_ins.addTransceiver("audio",{direction:"recvonly"});this.recv_transceiverMap.set(M,C),D.push(M)}break;case"microphoneCamera_video":case"screenSharing_video":{const C=this.recv_peer_ins.addTransceiver("video",{direction:"recvonly"});this.recv_transceiverMap.set(M,C),D.push(M)}break}return D};getSenderTracks=async(B=[])=>{const D=[];for(const M of B){const O=this.send_transceiverMap.get(M);if(!O)continue;const{mid:C,sender:i}=O,{track:u}=i;if(!u)continue;const{id:$,enabled:N}=u,F=mediaType_keys.findIndex(K=>K===M),j=wt(),J={type:F,enabled:N,trackName:`web-${F}-${$}`,location:"local",mid:C,key:j,origin:"p2p",mediaType:M};D.push(J)}return D};getRecvTracks=async(B=[])=>{const D=[];for(const M of B){const O=this.recv_transceiverMap.get(M);if(!O)continue;const{mid:C,receiver:i}=O,{track:u}=i;if(!u)continue;const{id:$,enabled:N}=u,F=mediaType_keys.findIndex(K=>K===M),j=wt(),J={type:F,enabled:N,trackName:`web-${F}-${$}`,location:"local",mid:C,key:j};D.push(J)}return D};createOffer=()=>new Promise(async(B,D)=>{try{const M=await this.recv_peer_ins.createOffer();await this.recv_peer_ins.setLocalDescription(M),B(M)}catch(M){D(M)}});setOffer=async B=>{await this.send_peer_ins.setRemoteDescription(B),await this.prResolves.emit("setOffered")};createAnswer=()=>new Promise(async B=>{const D=await this.send_peer_ins.createAnswer();await this.send_peer_ins.setLocalDescription(D),B(D)});addCandidates=async B=>{await this.setOffered();for(const D of B)await this.send_peer_ins.addIceCandidate(D)};setAnswer=async(B,D)=>{await this.recv_peer_ins.setRemoteDescription(B);for(const M of D)await this.recv_peer_ins.addIceCandidate(M)};getTrack=B=>this.recv_transceiverMap.get(B)?.receiver?.track;getSendPeerNetwork=()=>this.sendPeerAnalyzeStatsIns.getNetwork();getRecvPeerNetwork=()=>this.recvPeerAnalyzeStatsIns.getNetwork()}class RoomUsers extends RoomMedias{constructor(B){super(B)}getP2PIns=async B=>this.p2pMap.get(B);getMaxVolumeUser=()=>{const B=Array.from(this.userMap.values(),({id:M})=>M);if(B.length===0)return;let D=[];for(const M of B){const O=this.getUserAudioMediaStreamContext(M,"microphoneCamera_audio");if(!O)continue;const C=O.getVolume();D.push({id:M,volume:C})}return D=D.sort((M,O)=>M.volume-O.volume>0?-1:1),D[0]};setVolume=(B,D,M)=>{this.getUserAudioMediaStreamContext(B,D)?.setInputGain(M)};setEnhanceGain=async(B,D,M)=>{this.getUserAudioMediaStreamContext(B,D)?.setEnhanceGain(M)};setSpeaker=(B,D,M)=>{const O=this.getUserAudioMediaStreamContext(B,D);O?.setOutputGain(M);const C=M===0;try{O?.setMute(C)}catch{}};playBgs=(B,D,M)=>this.getUserAudioMediaStreamContext(B,D)?.mixAudio(M,"bgs");setBgsGain=(B,D,M)=>{this.getUserAudioMediaStreamContext(B,D)?.setBgsGain(M)};stopBgs=(B,D)=>{this.getUserAudioMediaStreamContext(B,D)?.mixAudioStop("bgs")};playBgm=(B,D,M)=>this.getUserAudioMediaStreamContext(B,D)?.mixAudio(M,"bgm");setBgmGain=(B,D,M)=>{this.getUserAudioMediaStreamContext(B,D)?.setBgmGain(M)};stopBgm=(B,D)=>{this.getUserAudioMediaStreamContext(B,D)?.mixAudioStop("bgm")};changBgsMix=(B,D,M)=>{this.getUserAudioMediaStreamContext(B,D)?.changeMix("bgs",M)};changBgmMix=(B,D,M)=>{this.getUserAudioMediaStreamContext(B,D)?.changeMix("bgm",M)};getVolume=(B,D)=>this.getUserAudioMediaStreamContext(B,D)?.getVolume();clearUsers=()=>{this.userMap=new Map,this.p2pMap=new Map};removeUsers=async B=>{for(const D of B)this.userMap.delete(D),this.p2pMap.delete(D),await this.removeUserStreams(D)};createUser=async B=>{const D=Date.now(),M=this.getOptions(),O={id:B,permissions:0,callAction:0,callActionStr:"",callActionMap:{microphoneCamera_audio:!1,microphoneCamera_video:!1,screenSharing_video:!1,screenSharing_audio:!1},banBehavior:0,banBehaviorStr:"",banBehaviorMap:{microphoneCamera_audio:!1,microphoneCamera_video:!1,screenSharing_video:!1,screenSharing_audio:!1},callState:0,isOwner:this.userMap.size===0,isSelf:B===M.userId,isPublished:!1,useP2P:!1,joinTime:D,updateAt:D,network:{egress:0,ingress:0},tracks:[],updateStreams:{microphoneCamera_audio:!1,microphoneCamera_video:!1,screenSharing_video:!1,screenSharing_audio:!1}};this.userMap.set(B,O);{const C=new P2P(this.phoneyStreams);this.p2pMap.set(B,C)}};getUser=async B=>(this.userMap.has(B)||await this.createUser(B),this.userMap.get(B));getUsers=async(B=[])=>{B.length===0&&(B=[...this.userMap.keys()]);const D=[];for(const M of B){const O=await this.getUser(M);D.push(O)}return D};getAllUserTrackMids=async()=>{const B=await this.getUsers(),D=[];for(const M of B){const{tracks:O=[]}=M;for(const C of O)D.push(C.mid)}return D};getUserTrackByTrackName=async B=>{const D=await this.getUsers(),M=[];for(const O of D){const{tracks:C=[]}=O;for(const i of C){const{trackName:u}=i;B.includes(u)&&M.push(i)}}return M};getUserTrackByMid=async B=>{const D=await this.getUsers();let M;for(const O of D){const{tracks:C=[]}=O;for(const i of C)if(i.mid===B){M=i;break}}return M};getUsersMediaTypeBytrackNames=async B=>{if(B.length===0)return[];const D=[],M=await this.getUsers();for(const O of M){const{id:C,tracks:i=[]}=O,u=[];for(const N of i){const{trackName:F,mediaType:j}=N;!B.includes(F)||!j||u.push(j)}if(u.length===0)continue;const $={userId:C,mediaTypes:u};D.push($)}return D};getUserTrackByUserMediaTypes=async(B=[],D)=>{const M=[],O=await this.getUsers();for(const C of O){const{id:i,tracks:u=[]}=C;let $=[];const N=B.find(F=>F.userId===i);if(N&&($=u.filter(F=>N.mediaTypes.includes(F.mediaType)),$.length!==0)){if(D!==void 0)for(const F of $)F.lastRetry=D;M.push({id:i,tracks:$})}}return M};getAllUserMediaTypes=async()=>{const B=[],D=await this.getUsers();for(const M of D){const{id:O,tracks:C=[],isSelf:i}=M;if(i)continue;const u=Array.from(C,$=>$.mediaType);B.push({userId:O,mediaTypes:u})}return B};checkUserInRoom=B=>this.userMap.has(B);getUsersId=async()=>[...this.userMap.keys()];getSelfInfo=async()=>await this.getUser(this.options.userId);updateIsPublished=async(B,D=!1)=>{const M=await this.getUser(B);M.isPublished=D};setUserUpdateStreams=async(B,D,M=!0)=>{const O=await this.getUser(B),C={microphoneCamera_audio:!1,microphoneCamera_video:!1,screenSharing_video:!1,screenSharing_audio:!1};C[D]=M,O.updateStreams=C};updateUsertracks=async(B,D=[],M)=>{const O=await this.getUser(B);M&&(D=[...O.tracks,...D]),D=D.filter(({mid:u=""})=>u!==""),D=pt(D,["type"]),D=D.sort((u,$)=>u.type-$.type<0?-1:1);for(const u of D)u.userId=B,u.mediaType=mediaType_keys[u.type],u.enabled===void 0&&(u.enabled=!0),u.origin===void 0&&(u.origin="sfu");O.updateStreams={microphoneCamera_audio:!1,microphoneCamera_video:!1,screenSharing_video:!1,screenSharing_audio:!1};const C=dt(O.tracks,["mediaType","enabled","mid","msid","trackName","key"]),i=dt(D,["mediaType","enabled","mid","msid","trackName","key"]);for(const u of mediaType_keys){const $=i.find(j=>j.mediaType===u),N=C.find(j=>j.mediaType===u),F=JSON.stringify($)!==JSON.stringify(N);O.updateStreams[u]=F}O.tracks=D};updateUserCallAction=async(B,D=0)=>{const M=await this.getUser(B);M.callAction=D,M.callActionStr=D.toString(2).padStart(4,"0"),M.callActionMap=this.getCallActionMap(D)};updateUserBehaviors=async(B,D=0)=>{const M=await this.getUser(B);M.banBehavior=D,M.banBehaviorStr=D.toString(2).padStart(4,"0"),M.banBehaviorMap=this.getBanBehaviorMap(D)};updateUserNetwork=async(B,D={egress:5,ingress:5})=>{const M=await this.getUser(B);M.network=D};updateUserPermissions=async(B,D)=>{if(D){const M=await this.getUser(B);M.permissions=D}};updateUserUseP2P=async(B,D)=>{const M=await this.getUser(B);M.useP2P=D};updateUserBase=async B=>{const D=this.getOptions(),M=await this.getUser(B);M.isSelf=B===D.userId,M.updateAt=Date.now()};updateUsers=async B=>{for(const D of B){const{id:M,tracks:O,callAction:C,permissions:i,isPublished:u,useP2P:$}=D;await this.updateUserBase(M),await this.updateIsPublished(M,u),await this.updateUserPermissions(M,i),await this.updateUsertracks(M,O,!0),await this.updateUserCallAction(M,C),await this.updateUserNetwork(M),await this.updateUserUseP2P(M,$)}};emitNotifyUpdateUser=async B=>{const D=await this.getUsers([B]),[M]=this.usersFilter(D);this.cwsIns.emitNotify("onRoomUser",{code:200,data:M,desc:"user info is change."})};emitNotifyUpdateUsers=async()=>{const B=await this.getUsers(),D=this.usersFilter(B);this.cwsIns.emitNotify("onRoomUsers",{code:200,data:D,desc:"all users info is change."})}}class RoomPeer extends RoomUsers{#e=0;peerAnalyzeStatsIns=new PeerAnalyzeStats;offset_inboundBytes=0;offset_outboundBytes=0;constructor(B){super(B),this.initPeer(),this.peerAnalyzeStatsIns.onNetwork=this.#r}saveBoundBytes=B=>{const D=this.peerAnalyzeStatsIns?.getNetwork();D&&(B==="superfluous"&&(this.offset_inboundBytes=-D.inboundBytes,this.offset_outboundBytes=-D.outboundBytes),B==="missing"&&(this.offset_inboundBytes=this.offset_inboundBytes+D.inboundBytes,this.offset_outboundBytes=this.offset_outboundBytes+D.outboundBytes))};getTrafficUse=()=>{const{sfuPush:B,sfuPull:D,p2pPush:M,p2pPull:O}=this;return{sfuPush:B,sfuPull:D,p2pPush:M,p2pPull:O}};initPeer=()=>{clearTimeout(this.#e),this.saveBoundBytes("missing"),this.transceiverMap=new Map,this.peerIns?.close(),this.peerIns=void 0,this.peerIns=new RTCPeerConnection({iceServers:[{urls:"stun:stun.cloudflare.com:3478"}],bundlePolicy:"max-bundle"}),this.#n(),this.initMediaPhoneyStreams(),this.startGetPeerStats()};replaceSenderStream=async(B=[],D)=>{const M=this.getOptions(),{userId:O}=M;B.length===0&&(B=mediaType_keys);for(const C of B){const i=this.transceiverMap.get(C);let u;if(i){const{sender:$}=i;D?u=this.getUserStream(O,C):u=this.getPhoneyStreams(C);const[N]=u.getTracks();await $.replaceTrack(N)}}};getSenderTracks=async(B=[])=>{const D=[];for(const M of B){const O=this.transceiverTrackMap.get(M);O&&D.push(O)}return D};addSenders=async(B=[])=>{B.length===0&&(this.peerIns.addTransceiver("audio",{direction:"sendonly"}),this.peerIns.addTransceiver("video",{direction:"sendonly"}));const D=[];for(const M of B){if(this.transceiverMap.get(M))continue;const C=this.getPhoneyStreams(M),[i]=C.getTracks(),u=this.peerIns.addTransceiver(i,{direction:"sendonly"});this.transceiverMap.set(M,u),D.push(M)}if(B.length===0||D.length!==0){const M=await this.peerIns.createOffer();if(this.options.debug){const O=libExports$1.parse(M.sdp),C=dt(O.media,["mid","msid","type"]);console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#ffffff;","------->quickvo: setLocalDescription",{msidArr:C,sdpJson:O,description:M})}await this.peerIns.setLocalDescription(M);for(const O of B){const C=this.transceiverMap.get(O);if(!C)continue;const{mid:i,sender:u}=C,{track:$}=u;if(!$)continue;const{enabled:N}=$,F=mediaType_keys.findIndex(K=>K===O),j=`WEB-${F}-${wt()}`,J={type:F,mediaType:O,enabled:N,trackName:j,location:"local",mid:i,key:"",origin:"sfu"};this.transceiverTrackMap.set(O,J)}}return D};removeSenders=async(B=[])=>{B.length===0&&(B=mediaType_keys);for(const D of B)this.transceiverMap.has(D)&&(this.transceiverMap.delete(D),this.transceiverTrackMap.delete(D))};stopSenders=(B=[])=>{B.length===0&&(B=mediaType_keys);for(const D of B){if(!this.transceiverMap.has(D))continue;const M=this.transceiverMap.get(D);M?.sender.track?.stop(),M?.stop()}};#n=()=>{const B=()=>{clearTimeout(this.#e),this.setIceState("failed")};this.peerIns.onconnectionstatechange=async D=>{const M=D.target.connectionState;switch(M){case"connected":this.options.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#00b60f;",`------->quickvo: connectionState:${M}`),clearTimeout(this.#e),this.setIceState("connected"),this.prResolves.emit("iceConnected");break;case"disconnected":this.options.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#b64900;",`------->quickvo: connectionState:${M}`),this.setIceState("disconnected"),this.#e=window.setTimeout(B,15*1e3);break;case"failed":{if(this.options.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#b60000;",`------->quickvo: connectionState:${M}`),this.iceState==="closed")return;this.setIceState("failed")}break;case"closed":this.options.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#b60000;",`------->quickvo: connectionState:${M}`),clearTimeout(this.#e),this.setIceState("closed");break;default:this.options.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#b64900;",`------->quickvo: connectionState:${M}`);break}}};iceConnected=()=>{const B=()=>this.peerIns.connectionState==="connected";return this.prResolves.add("iceConnected",B)};stopTransceivers=async B=>{const D=this.peerIns.getTransceivers();for(const M of D){const{mid:O}=M;O&&B.includes(O)&&(M.stop(),this.options.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;",`------->quickvo: transceiver: ${O} is stop.`,M))}};createOffer=async()=>{const B=await this.peerIns.createOffer();if(this.options.debug){const D=libExports$1.parse(B.sdp),M=dt(D.media,["mid","msid","type"]);console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#ffffff;","------->quickvo: createOffer",{msidArr:M,sdpJson:D,description:B})}await this.peerIns.setLocalDescription(B)};createAnswer=async()=>{const B=await this.peerIns.createAnswer();if(this.options.debug){const D=libExports$1.parse(B.sdp),M=dt(D.media,["mid","msid","type"]);console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#ffffff;","------->quickvo: createAnswer",{msidArr:M,sdpJson:D,description:B})}await this.peerIns.setLocalDescription(B)};getSdp=()=>this.peerIns.localDescription?.sdp;setRemoteDescription=async B=>{if(this.options.debug){const D=libExports$1.parse(B.sdp),M=dt(D.media,["mid","msid","type"]);console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#ffffff;","------->quickvo: setRemoteDescription",{msidArr:M,sdpJson:D,description:B})}return await this.peerIns.setRemoteDescription(B),B};setCallStrategy=async(B,D=[])=>{D.length===0&&(D=mediaType_keys);let M="balanced";switch(B){case"qualityPriority":M="maintain-resolution";break;case"fluencyPriority":M="maintain-framerate";break;case"balancedDowngrade":M="balanced";break}const O=await this.getSelfInfo(),C=Array.from(O.tracks,({trackName:u})=>u),i=this.peerIns.getSenders();for(const u of i){const{track:$}=u;if(!$||!C.includes($.id))continue;const N=u.getParameters();u.setParameters({...N,degradationPreference:M})}};setRTCRtpSenderParameters=B=>{try{const D=this.peerIns.getSenders();for(const M of D){const O=M.getParameters();M.setParameters({...O,...B})}}catch(D){console.error("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->quickvo: setRTCRtpSenderParameters is error.",D)}};getPeerNetwork=()=>{const B=this.peerAnalyzeStatsIns?.getNetwork();return JSON.parse(JSON.stringify(B))};getRoomNetwork=()=>{const B=this.peerAnalyzeStatsIns?.getNetwork(),D=JSON.parse(JSON.stringify(B));return D.inboundBytes=Math.max(0,D.inboundBytes+this.offset_inboundBytes),D.outboundBytes=Math.max(0,D.outboundBytes+this.offset_outboundBytes),D};#t=()=>{const B=this.getRoomNetwork();{const{outboundBytes:D,inboundBytes:M}=B;this.sfuPush=Math.ceil(D/1024),this.sfuPull=Math.ceil(M/1024)}this.cwsIns.emitNotify("onRoomNetwork",{code:200,data:B,desc:"room network is change."})};#r=async B=>{try{const{quality:D}=B;D>=2&&this.prResolves.emit("senderActived"),this.#t();const M=await this.getSelfInfo(),{network:O}=M,C={egress:D,ingress:D};Ct("updateUserNetwork",async()=>{if(await this.updateUserNetwork(this.options.userId,C),JSON.stringify(O)!==JSON.stringify(C)){this.emitNotifyUpdateUsers();const $=this.getOptions(),{userId:N,roomId:F}=$,j={...C,userId:N,roomId:F};this.cwsIns.sendMessage({event:"networkQualityChange",data:j},!1)}},3*1e3)}catch(D){console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->quickvo: setNetQuality is err.",D)}};getReportsByMid=async(B=[])=>this.peerAnalyzeStatsIns?.getReports(B);startGetPeerStats=()=>{this.peerAnalyzeStatsIns.start(this.peerIns);const B=[...this.p2pMap.values()];for(const D of B)D.sendPeerAnalyzeStatsIns.start(D.send_peer_ins),D.recvPeerAnalyzeStatsIns.start(D.recv_peer_ins)};stopGetPeerStats=()=>{this.peerAnalyzeStatsIns.stop();const B=[...this.p2pMap.values()];for(const D of B)D.sendPeerAnalyzeStatsIns.stop(),D.recvPeerAnalyzeStatsIns.stop()}}const g=(A,B)=>{if(!(A!=null&&A.ip)||!(A!=null&&A.port)||!(A!=null&&A.serve_ip)||!(A!=null&&A.serve_port)||!(B!=null&&B.ip)||!(B!=null&&B.port)||!(B!=null&&B.serve_ip)||!(B!=null&&B.serve_port))return"Unknown";const[D,M]=[A.ip,A.port],[O,C]=[A.serve_ip,A.serve_port],[i,u]=[B.ip,B.port],[$,N]=[B.serve_ip,B.serve_port];return D===i&&M===u?"Full Cone":D===O&&(i!==O||u!==M)||i===$&&(D!==$||M!==u)?"Restricted Cone":D===O&&M===C&&(i!==O||u!==C)||i===$&&u===N&&(D!==$||M!==N)?"Port Restricted Cone":"Symmetric"},h=async()=>{const A="stun.cloudflare.com:3478",B="stun.l.google.com:19302",D=async M=>new Promise(O=>{const C=new RTCPeerConnection({iceServers:[{urls:`stun:${M}`}]});C.createDataChannel("ice-channel");let i=null;C.onicecandidate=u=>{var $,N;if((($=u.candidate)==null?void 0:$.type)==="srflx"){const[F,j]=M.split(":").map(J=>J.trim());i={ip:u.candidate.address||"",port:(N=u.candidate.port)==null?void 0:N.toString(),serve_ip:F,serve_port:j},C.close(),O(i)}},setTimeout(()=>{C.close(),O(null)},5e3),C.createOffer().then(u=>C.setLocalDescription(u)).catch(()=>O(null))});try{const M=await D(A),O=await D(B);if(!M||!O)return{address:"",natType:"Unknown"};const C=g(M,O);return{address:M.ip||"",natType:C}}catch(M){return console.error("获取NAT类型失败:",M),{address:"",natType:"Unknown"}}};class RoomCalls extends RoomPeer{#e=0;#n;constructor(B){super(B),this.#d()}setLocalStream=(B,D)=>new Promise(async(M,O)=>{try{const C=[];typeof B=="string"?C.push(B):C.push(...B);for(const u of C)this.localStreamsActionMap.set(u,D);if(D){if(B.includes("microphoneCamera_audio")&&B.includes("microphoneCamera_video")?await this.initLocalStream("microphoneCamera"):B.includes("microphoneCamera_audio")?await this.initLocalStream("microphoneCamera_audio"):B.includes("microphoneCamera_video")?await this.initLocalStream("microphoneCamera_video"):B.includes("screenSharing_audio")&&B.includes("screenSharing_video")?await this.initLocalStream("screenSharing"):B.includes("screenSharing_audio")&&!B.includes("screenSharing_video")?await this.initLocalStream("screenSharing_audio"):B.includes("screenSharing_video")&&!B.includes("screenSharing_audio")&&await this.initLocalStream("screenSharing_video"),B.includes("screenSharing_audio")){const u=await this.getLocalStream("screenSharing_audio");if(u){const $=u.getTracks();for(const N of $)N.onended=()=>this.stopPublish(["screenSharing_audio","screenSharing_video"])}}if(B.includes("screenSharing_video")){const u=await this.getLocalStream("screenSharing_video");if(u){const $=u.getTracks();for(const N of $)N.onended=()=>this.stopPublish(["screenSharing_audio","screenSharing_video"])}}}else await this.stopLocalStreams(C);const i=await this.getLocalStreams(C);if(await this.cwsIns.emitNotify("onLocalStream",{code:200,data:i,desc:"local stream is change."}),this.isInRoom){const u=()=>new Promise(async $=>{const N=this.getOptions(),{userId:F}=N,j={};for(const J of C){const K=await this.getLocalStream(J);K&&(j[J]=wt(),await this.initUserMediaStreamContext(F,J,K,!1))}await this.replaceSenderStream(C,D),await this.emitNotifyUpdateUsersStreams([{userId:F,updateStreams:j}]),$(!0)});this.asyncQueue.add(u,{describe:"setLocalStream"})}M(i)}catch(C){console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->Breathe: error",C),O(C)}});setMediaDeviceKind=(B,D)=>{const M=()=>new Promise(async(O,C)=>{this.setDeviceKind(B,D);const i=await this.getSelfInfo(),{id:u,tracks:$=[],callActionMap:N}=i,F=[],j=async J=>{const K=this.localStreamsActionMap.get(J),Y=$.find(oe=>oe.mediaType===J),re=N[J];if(K){F.push(J),await this.stopLocalStreams([J]);try{await this.initLocalStream(J)}catch(oe){this.options.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->quickvo: initLocalStream is error.",oe),await this.inactiveTracks([J],!1),C(oe)}}if(Y){const oe=await this.getLocalStream(J);if(oe&&(await this.initUserMediaStreamContext(u,J,oe,!0),re)){await this.replaceSenderStream([J],!0);const te=await this.getUsersId();await this.p2p.replaceSenderStreams(te,F,!0)}}{if(F.length!==0){const oe=await this.getLocalStreams(F);await this.cwsIns.emitNotify("onLocalStream",{code:200,data:oe,desc:"local stream is change."});const te=this.createUserUpdateStreams(F);await this.emitNotifyUpdateUsersStreams([{userId:this.options.userId,updateStreams:te}]),await this.emitNotifyUpdateUsers()}O(!0)}};B==="audioinput"&&await j("microphoneCamera_audio"),B==="videoinput"&&await j("microphoneCamera_video"),B==="audiooutput"&&(await this.changeAudiooutput(),O(!0))});return this.asyncQueue.add(M,{describe:"publish"})};changeScreenSharing=async B=>{const D=await this.getSelfInfo(),{tracks:M=[],callActionMap:O}=D;try{await this.setLocalStream(B,!0);for(const C of B)M.find(u=>u.mediaType===C&&O[C])&&await this.replaceSenderStream([C],!0)}catch(C){this.options.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->quickvo: changeScreenSharing is error.",C)}};earlyConnect=(B=[])=>new Promise(async(D,M)=>{try{this.isEarly=!0,await this.#a(),await this.#c(),B.length===0&&(B=["microphoneCamera_audio","microphoneCamera_video"]),await this.#l(B),D(!0)}catch(O){console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->Breathe: error",O),M(O)}});joinRoom=async B=>(this.isInRoom=!0,this.setOptions(B),await this.#a(),await this.cwsConnected(),new Promise(async(D,M)=>{this.#n=async()=>{try{const{userId:O,callType:C,sdkToken:i,roomId:u}=this.getOptions();this.clearUsers(),await this.cwsIns.sendMessage({event:this.isEarly?"joinRoomEx":"joinRoom",data:{callType:C,roomId:u,user:{id:O,tracks:[],callAction:0},token:i},version:2}).then(async $=>{const{code:N=0,desc:F="服务器繁忙",data:j}=$;if(N!==200)throw new Error(F);const{roomId:J="",roomUsers:K=[]}=j;if(J!==u)return M("加入的房间不匹配");this.sfuPush=0,this.sfuPull=0,this.p2pPush=0,this.p2pPull=0,this.saveBoundBytes("superfluous"),this.initHeartbeat(),this.startGetPeerStats(),this.isEarly===!1&&await this.#c(),await this.updateUsers(K);for(const re of K){const{id:oe}=re;await this.updateUserBehaviors(oe,re.behavior)}await this.emitNotifyUpdateUsers();const Y=await this.getUsers();D(Y)})}catch(O){M(O)}},this.#n()}));quitRoom=()=>new Promise(async B=>{const D=this.getOptions(),{roomId:M,userId:O}=D;try{if(this.isInRoom===!1)return B(!0);const C=async u=>{clearTimeout(u),this.isInRoom=!1,this.stopHeartbeat(),this.transceiverMap=new Map,this.peerAnalyzeStatsIns?.stop();const $=()=>this.stopSubscribe(),N=()=>this.cwsIns.sendMessage({event:"quitRoom",data:{roomId:M,user:{id:O}}});Promise.all([$(),N()]).finally(()=>()=>this.cwsIns.clearEvents()),this.asyncQueue.clear(),this.clearUserStreams(),this.clearUsers(),this.setRoomState("ready")},i=window.setTimeout(()=>C(i),2*1e3);try{await this.stopPublish(),C(i)}catch{}B(!0)}catch(C){this.reportLogs("quit_room_error",C.message||C)}});quitRoomEx=()=>new Promise(async B=>{const D=this.getOptions(),{roomId:M,userId:O}=D;try{if(this.isInRoom===!1)return B(!0);const C=async u=>{clearTimeout(u),this.isInRoom=!1,this.initHeartbeat(),this.peerAnalyzeStatsIns?.stop();const $=()=>this.stopSubscribe(),N=()=>this.cwsIns.sendMessage({event:"quitRoomEx",data:{roomId:M,user:{id:O}}});Promise.all([$(),N()]).finally(()=>()=>this.cwsIns.clearEvents()),this.asyncQueue.clear(),this.clearUserStreams(),this.clearUsers()},i=window.setTimeout(()=>C(i),2*1e3);try{await this.stopLocalStreams(),C(i)}catch{this.restoreICE()}B(!0)}catch(C){this.reportLogs("quit_room_error",C.message||C)}});syncRoomInfo=()=>new Promise(async(B,D)=>{try{const M=this.getOptions(),{userId:O}=M,C=await this.getUser(O),{id:i=O,callAction:u=0}=C;await this.cwsIns.sendMessage({event:"syncRoomInfo",data:{user:{id:i,callAction:u}}}).then(async $=>{const{code:N=0,desc:F,data:j={}}=$;if(N!==200)throw new Error(F);const{isActive:J=!1,users:K=[]}=j;if(J===!1)throw new Error("Do not stay in this room.");if(K.find(re=>re.id===O)===!1)throw new Error("Need to rejoin the room.");this.clearUsers(),await this.updateUsers(K),await this.updateUsertracks(C.id,C.tracks,!1);{const re=await this.getUsers();B(re)}})}catch(M){D(M)}});checkInRoom=()=>new Promise(async B=>{const D=this.getOptions(),{userId:M}=D,O=await this.getUser(M),{id:C=M,callAction:i=0}=O;await this.cwsIns.sendMessage({event:"syncRoomInfo",data:{user:{id:C,callAction:i}}}).then(async u=>{const{code:$=0,desc:N}=u;if($!==200)throw new Error(N);const F=u.data.users;return u.data?.isActive||F.find(J=>J.id===M)?B(!0):B(!1)}).catch(()=>B(!1))});senderActived=async B=>{const D=()=>{const{quality:M}=this.peerAnalyzeStatsIns?.getNetwork();return M>=2};await this.prResolves.add("senderActived",D,B)};publish=B=>new Promise(async(D,M)=>{try{{const $=await this.getSelfInfo(),{banBehaviorMap:N}=$;let F=!0;for(const j of B)if(N[j]){F=!1;break}if(F===!1)return M("publish is error: prohibited by administrator.")}const O=await this.getSelfInfo();for(const $ of B){const N=this.getPhoneyStreams($);await this.initUserMediaStreamContext(O.id,$,N,!0)}await this.replaceSenderStream(B,!1),await this.#l(B);const C=setTimeout(async()=>{await this.replaceSenderStream(B,!0),await this.inactiveTracks(B,!1)},5*1e3);this.setLocalStream(B,!0).then(()=>clearTimeout(C));const i=await this.getSenderTracks(B);await this.updateUsertracks(O.id,i,!0);const u=await this.getCallAction(O.tracks);await this.#i(u),await this.senderActived(3e3),this.#r(B);{await this.emitNotifyUpdateUsers();const $=this.createUserUpdateStreams(B);await this.emitNotifyUpdateUsersStreams([{userId:O.id,updateStreams:$}]),D(!0)}}catch(O){this.reportLogs("publish_error",O.message||O),M(O)}});stopPublish=(B=[])=>new Promise(async(D,M)=>{try{const O=await this.getSelfInfo();B.length===0&&(B=mediaType_keys),await this.replaceSenderStream(B,!0),await this.removeSenders(B),await this.#s([{userId:O.id,mediaTypes:B}],!0);const C=await this.getCallAction(O.tracks);await this.#i(C),await this.setLocalStream(B,!1),await this.emitNotifyUpdateUsers(),D(!0)}catch(O){this.reportLogs("close_track_error",O.message||O),M(O)}});inactiveTracks=async(B,D)=>new Promise(async M=>{const O=await this.getSelfInfo();if(!O||!O.id)return M(!0);const{tracks:C=[]}=O,i=[...C];for(let $ of i){const{mediaType:N}=$;if(N&&B.includes(N)){$.enabled=D;const F=await this.getLocalStream(N);if(!F)continue;const j=F.getTracks();for(const J of j)J.enabled=D}}await this.replaceSenderStream(B,D);const u=await this.getCallAction(i);await this.#i(u),await this.emitNotifyUpdateUsers(),M(!0)});subscribe=(B=[])=>{const D=()=>new Promise(async(M,O)=>{try{B.length===0&&(B=await this.getAllUserMediaTypes()),await this.iceConnected();const C=($,N=!1)=>new Promise(async F=>{const j=async K=>{const Y=[],re=[],oe=[];let te=0,le=0;for(const pe of K){const{id:ee,tracks:ne=[]}=pe;if(te=te+ne.length,!this.checkUserInRoom(ee))continue;const se=await this.getUser(ee),ce=[],he=[],ie=[];for(const fe of ne){const{code:ye=0,mid:ve,type:be}=fe,ge=se.tracks.find(Ee=>Ee.type===be);if(ge)switch(ye){case 200:ce.push({...ge,mid:ve});break;case 2026:ie.push({...ge,mid:ve});break;default:he.push({...ge});break}}ce.length!==0&&(Y.push({id:ee,tracks:ce}),le=le+ce.length),he.length!==0&&re.push({id:ee,tracks:he}),ie.length!==0&&oe.push({id:ee,tracks:ie})}return{expectation_num:te,success_num:le,success_users:Y,fail_users:re,retry_users:oe}},J=async(K,Y="成功",re=[])=>{const{expectation_num:oe,success_num:te,success_users:le,fail_users:pe,retry_users:ee}=await j(re);F({code:K,msg:Y,expectation_num:oe,success_num:te,success_users:le,fail_users:pe,retry_users:ee})};try{const K=await this.getUserTrackByUserMediaTypes($,N);if(K.length===0)return J(200,"成功",[]);const Y=await this.cwsIns.sendMessage({event:"subscribe",data:{session:this.sdk_session,users:K}}),{code:re=0,desc:oe,sn:te="",data:le={}}=Y;if(this.#o(te),re===2017&&oe.includes("renegotiation is expected before pulling or pushing tracks")&&await this.#t(),re===2026){const ne=[];for(const ue of K)ne.push({...ue,code:2026});return await J(re,oe,ne)}if(re!==200)return await J(re,oe);const{remoteSdp:pe,users:ee=[]}=le;if(pe){const ne=new RTCSessionDescription({type:"offer",sdp:pe});await this.setRemoteDescription(ne),await this.#t()}await J(200,"成功",ee)}catch(K){console.error("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->quickvo: error",K),await J(0,K.message||K)}}),i=($=[])=>new Promise(N=>{this.await_remote_publish_users=$;let F=0;for(const oe of $)F=F+oe.tracks.length;const j=[],J=wt(),K=async()=>{this.cwsIns.removeNotify([J]);const oe=await C(j);this.await_remote_publish_users=[],N(oe)},Y=setTimeout(()=>K(),30*1e3),re=async oe=>{const{user:te}=oe.data,{id:le,tracks:pe=[],callAction:ee=0}=te;await this.updateUserCallAction(le,ee),await this.updateUserPermissions(le,3),await this.updateUsertracks(le,pe,!0);const ne=[],ue=$.find(he=>he.id===le);if(!ue)return;for(const he of ue.tracks)for(const ie of pe)ie.type===he.type&&ne.push(he.mediaType);const se=[...new Set(ne)];se.length!==0&&j.push({userId:le,mediaTypes:se});let ce=0;for(const he of j)ce=ce+he.mediaTypes.length;ce===F&&(clearTimeout(Y),K())};this.cwsIns.addNotify({sn:J,event:"onPublish",callback:re},!0)}),u=async($=[])=>{let N=0;const F=new Map,j=this.peerIns.getTransceivers(),J=[],K=[];for(const re of $){const{id:oe,tracks:te=[]}=re;if(this.checkUserInRoom(oe)){await this.updateUsertracks(oe,te,!0);for(const pe of te){const{mid:ee,mediaType:ne}=pe,ue=j.find(ce=>ce.mid===ee);if(!ue)continue;const{receiver:se}=ue;if(se.track){{pe.msid=se.track.id;const ce=new MediaStream;ce.addTrack(se.track),await new Promise(fe=>setTimeout(()=>fe(!0),1e3));const{current_origin:he,suggest_origin:ie}=await this.#f(oe,ne);if(await this.#u(oe,[ne],ie),["microphoneCamera_audio","screenSharing_audio"].includes(ne)){const fe=new Audio;fe.srcObject=ce,(ne==="microphoneCamera_audio"||ne==="screenSharing_audio")&&this.getUserAudioMediaStreamContext(oe,ne)?.setMute(!1)}ie==="p2p"&&K.push({userId:oe,mediaTypes:[ne]}),he==="p2p"&&ie==="sfu"&&(J.push(oe),this.p2p.reportP2PConnect(this.options.userId,oe,"poor_network","poor network quality."));{F.has(oe)||F.set(oe,{userId:oe,tracks:[],updateStreams:{}});const ye=F.get(oe);ye.tracks.push(pe),ye.updateStreams[ne]=wt()}}N=N+1}}}}const Y=[...F.values()];return await this.emitNotifyUpdateUsersStreams(Y),J.length!==0&&this.p2p.closeRecv(J),K.length!==0&&this.#s(K,!1),await this.emitNotifyUpdateUsers(),N};{let $=await C(B,!1),{expectation_num:N,success_num:F,success_users:j=[],fail_users:J=[]}=$;if(j.length!==0){const K=await u(j);this.options.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#00b60f;",`------->quickvo: subscription results is: ${K}/${F}/${N}`,{actual_num:K,success_num:F,expectation_num:N})}if(J.length!==0){this.options.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->quickvo: ","The first subscription attempt failed completely. It will attempt to subscribe again in 4 seconds."),await new Promise(pe=>setTimeout(()=>pe(!0),4e3));const K=[];for(const pe of J){const ee=Array.from(pe.tracks,ne=>ne.mediaType);K.push({userId:pe.id,mediaTypes:ee})}const Y=await C(K,!0);let{expectation_num:re,success_num:oe,success_users:te=[],retry_users:le=[]}=Y;if(te.length!==0){const pe=await u(te);this.options.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#00b60f;",`------->quickvo: subscription results is: ${pe}/${oe}/${re}`,{actual_num:pe,success_num:oe,expectation_num:re})}if(le.length!==0){this.options.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#b64900;","------->quickvo: waiting for the other party to republish before subscribing.");const ee=await yt(()=>i(le),{message:"Wait for a timeout before publishing. No re-published track received from the other party within 40 seconds.",timeout:40*1e3});let{expectation_num:ne,success_num:ue,success_users:se=[]}=ee;if(se.length!==0){const ce=await u(se);this.options.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#00b60f;",`------->quickvo: subscription results is: ${ce}/${ue}/${ne}`,{actual_num:ce,success_num:ue,expectation_num:ne})}}}M(!0)}}catch(C){this.reportLogs("subscribe_error",C.message||C),O(C)}});return this.asyncQueue.add(D,{describe:"subscribe"})};#t=()=>new Promise(async(B,D)=>{try{await this.createAnswer(),await this.cwsIns.sendMessage({event:"renegotiate",data:{sdp:this.getSdp()}}).then(async M=>{const{code:O=0,desc:C,sn:i=""}=M;if(await this.#o(i),O!==200)throw new Error(C);B(M)})}catch(M){D(M)}});stopSubscribe=(B=[])=>new Promise(async(D,M)=>{try{B.length===0&&(B=await this.getAllUserMediaTypes());const O=await this.getUserTrackByUserMediaTypes(B);if(O.length===0)return D(!0);const C=[],i=[];for(const u of O){const{id:$,tracks:N=[]}=u;for(const F of N){const{type:j,mid:J,mediaType:K,msid:Y,origin:re="sfu",userId:oe}=F;if(K){if(re==="sfu"){if(!Y||!J)continue;const te={type:j,mid:J,trackName:Y,userId:oe};C.push(te),i.push(J)}re==="p2p"&&(await this.p2p.closeRecv([$],[K]),F.origin="sfu",this.p2p.reportP2PConnect(this.options.userId,$,"disconnect","p2p is close."))}}}if(C.length===0)return D(!0);await this.stopTransceivers(i),await this.#s(B,!1);for(const u of B){const{userId:$,mediaTypes:N=[]}=u;if(!this.checkUserInRoom($))continue;const j=await this.getUser($);for(const J of j.tracks)N.includes(J.mediaType)&&(J.msid="")}await this.emitNotifyUpdateUsers(),D(!0)}catch(O){this.reportLogs("close_track_error",O.message||O),M(O)}});setBanBehaviors=B=>new Promise(async(D,M)=>{try{const O=this.getOptions(),{roomId:C}=O,i=[];for(const u of B){const{id:$,banBehaviors:N}=u,F=Object.keys(N);if(F.length===0)continue;const j=[];for(const K of F){const Y=mediaType_keys.findIndex(te=>te===K),re=N[K],oe={type:Y,behavior:re};j.push(oe)}const J={id:$,behaviors:j};i.push(J)}await this.cwsIns.sendMessage({event:"preventUsersBehavior",data:{roomId:C,users:i}}).then(async u=>{const{code:$=0,desc:N}=u;if($!==200)return M(N);D(u)})}catch(O){M(O)}});debugger=()=>this.cwsIns.sendMessage({event:"debugger"},!1);shutdown=()=>this.cwsIns.sendMessage({event:"shutdown"},!1);restoreRoom=async()=>{if(this.isInRoom===!1)return;await this.checkInRoom()===!1&&this.#n&&await this.#n(),this.cwsIns.afreshSends()};restoreICE=async()=>{this.options.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->quickvo: restore ice."),await this.cwsConnected(),this.initPeer(),this.isEarly?this.earlyConnect():await this.#c();const B=await this.getUsers();for(const D of B){const{id:M,isSelf:O,callActionMap:C,tracks:i=[]}=D;if(O){for(const $ of mediaType_keys)C[$]&&this.historical_publish_mediaTypes.push($);continue}const u=[];for(const $ of i)($.msid||$.origin==="p2p")&&u.push($.mediaType);u.length!==0&&this.historical_subscribe_mediaTypes.push({userId:M,mediaTypes:u})}await this.syncRoomInfo(),await this.publish(this.historical_publish_mediaTypes).then(()=>{this.historical_publish_mediaTypes=[]}),this.historical_subscribe_mediaTypes.length!==0&&await this.subscribe(this.historical_subscribe_mediaTypes).then(()=>{this.historical_subscribe_mediaTypes=[]})};initHeartbeat=()=>{this.stopHeartbeat();const B=async()=>{if(this.isInRoom){const M=this.getTrafficUse();this.cwsIns.sendMessage({event:"heartbeat",data:M},!1)}else this.cwsIns.sendMessage({event:"heartbeatEx",data:{}},!1)},D=this.isInRoom?10*1e3:30*1e3;this.#e=window.setInterval(B,D),B()};stopHeartbeat=()=>{clearInterval(this.#e)};#r=async B=>new Promise(async(D,M)=>{try{const O=this.getOptions(),{roomId:C}=O;if(!C)return;const{id:i,tracks:u=[]}=await this.getSelfInfo(),$=u.filter(F=>F.mediaType&&B.includes(F.mediaType));if($.length===0)return;const N=dt($,["type","trackName","mid"]);await this.cwsIns.sendMessage({event:"pubNotify",data:{session:this.sdk_session,roomId:C,user:{id:i,tracks:N}}}),D(!0)}catch(O){M(O)}});#o=B=>new Promise(D=>{this.cwsIns.sendMessage({event:"ackMsg",data:{msgId:B}},!1),D(!0)});#i=async B=>new Promise(async(D,M)=>{const O=this.getOptions(),{roomId:C,userId:i}=O,u={roomId:C,user:{id:i,callAction:B}};await this.cwsIns.sendMessage({event:"updateCall",data:u}).then(async $=>{const{code:N=0}=$;if(N!==200)return M($);await this.updateUserCallAction(i,B),D(B)}).catch($=>M($))});setSession=()=>{const B=this.getOptions(),{appid:D,roomId:M,userId:O,earlyId:C}=B;if(!D)throw new Error("quickvo: createWs is error. You must first use QuickVO.setOptions to set the appid.");const i={c:D,r:M,p:"web",h:location.hostname,v:this.sdk_service_version};this.isEarly?i.i=C:i.b=O;const u=btoa(encodeURI(JSON.stringify(i)));this.options.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->quickvo: session",i);const $=`${this.options.url}?s=${u}&t=${Date.now()}`;this.cwsIns.prws.setOptions({url:$})};#a=()=>new Promise(async(B,D)=>{try{if(["connecting","connected"].includes(this.roomState))return B(!0);this.setRoomState("connecting"),this.cwsIns.clearEvents(),this.setSession(),await this.cwsIns.connect(),this.initHeartbeat(),this.setRoomState("connected"),await this.prResolves.emit("cwsConnected"),B(this.cwsIns)}catch(M){console.error("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->quickvo: createWs is error.",M),this.reportLogs("ws_c_timeout",M.message||M),D(M)}});cwsConnected=()=>{const B=()=>this.roomState==="connected";return this.prResolves.add("cwsConnected",B)};#c=async()=>new Promise(async B=>{try{await this.cwsConnected(),await this.addSenders();const D=await this.cwsIns.sendMessage({event:"connectCF",data:{sdp:this.getSdp()}}),{code:M=0,desc:O,data:C}=D;if(M!==200)throw new Error(O);const{remoteSdp:i,session:u=""}=C;if(this.sdk_session=u,this.options.debug){const $=libExports$1.parse(i),N=dt($.media,["mid","msid","type"]);console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#ffffff;","------->quickvo: setLocalDescription",{msidArr:N,sdpJson:$})}await this.setRemoteDescription({type:"answer",sdp:i}),await yt(this.iceConnected,{message:"ice connect is timeout.",timeout:10*1e3}),B(!0),this.p2p.reportNetwork()}catch(D){this.options.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->quickvo: ice connect is error. recreate in 5 seconds.",D),await new Promise(M=>setTimeout(()=>M(!0),5*1e3)),this.#c()}});#l=async B=>{const D=()=>new Promise(async(M,O)=>{try{await this.iceConnected();const C=await this.addSenders(B),i=await this.getSenderTracks(C);if(i.length===0)return M(!0);const u=await this.cwsIns.sendMessage({event:"publish",data:{session:this.sdk_session,sdp:this.getSdp(),tracks:i,callAction:0}}),{code:$=0,desc:N,sn:F="",data:j={}}=u;if(await this.#o(F),$!==200)throw new Error(N);const{remoteSdp:J}=j;await this.setRemoteDescription({type:"answer",sdp:J}),M(!0)}catch(C){this.reportLogs("publish_error",C.message||C),await this.removeSenders(B),O(C)}});return this.asyncQueue.add(D,{describe:"createTrack"})};#s=(B=[],D)=>{const M=()=>new Promise(async(O,C)=>{try{B.length===0&&(B=await this.getAllUserMediaTypes());const i=await this.getUserTrackByUserMediaTypes(B);if(i.length===0)return O(!0);const u=[];for(const $ of i){const{id:N,tracks:F=[]}=$,j=Array.from(F,K=>K.trackName);for(const K of F){const{type:Y,mid:re,mediaType:oe,msid:te,userId:le,trackName:pe}=K;if(!oe||re===null)continue;const ee={type:Y,mid:re,trackName:te||pe,userId:le};u.push(ee)}if(this.checkUserInRoom(N)){const K=await this.getUser(N);for(const Y of K.tracks)j.includes(Y.trackName)&&(Y.msid="");if(D){const Y=K.tracks.filter(re=>!j.includes(re.trackName));await this.updateUsertracks(K.id,Y,!1)}}}if(u.length===0)return O(!0);await this.createOffer(),await this.cwsIns.sendMessage({event:"closeTrack",data:{roomId:this.options.roomId,sdp:this.getSdp(),tracks:u}}).then(async $=>{const{code:N=0,desc:F,data:j={}}=$;if(N!==200)throw new Error(F);const{remoteSdp:J}=j;await this.setRemoteDescription({type:"answer",sdp:J})}),O(!0)}catch(i){this.reportLogs("close_track_error",i.message||i),C(i)}});return this.asyncQueue.add(M,{describe:"closeTrack"})};#u=async(B,D,M)=>{for(const O of D){let C;if(!this.checkUserInRoom(B))continue;const u=await this.getUser(B),{tracks:$=[]}=u,N=$.find(j=>j.mediaType===O);if(!N)continue;if(M==="sfu"){const{mid:j}=N;C=this.peerIns.getTransceivers().find(Y=>Y.mid===j)?.receiver.track,N.origin="sfu"}if(M==="p2p"&&(C=(await this.getP2PIns(B))?.getTrack(O),N.origin="p2p"),!C)continue;const F=new MediaStream;F.addTrack(C),await this.initUserMediaStreamContext(B,O,F,!1),this.options.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#00b60f;","------->quickvo: switching to",M,{userId:B,mediaType:O,origin:M,stream:F})}};#f=async(B,D)=>{let M="sfu",O="sfu";const C=await this.getP2PIns(B);if(C&&C?.recv_peer_ins?.connectionState==="connected"){const $=C?.recvPeerAnalyzeStatsIns.getAverageQuality();if($!==0){const{averageQuality:N}=this.getPeerNetwork();$-N>=this.sfuOffsetAverageQuality&&(M="p2p")}}return this.checkUserInRoom(B)&&(O=(await this.getUser(B)).tracks.find($=>$.mediaType===D)?.origin),{current_origin:O,suggest_origin:M}};#d=()=>{{const B=async D=>{let M="";const O=await this.getSelfInfo(),{code:C,data:i}=D;if(C!==200)return;const{sdp:u,sender:$={},tracks:N=[]}=i,{id:F}=$;M=F;{const J=await this.getUsersId();let K=0;for(const Y of J){const re=await this.getP2PIns(Y);re?.send_peer_ins&&re.send_peer_ins.iceConnectionState==="connected"&&(K+=1)}if(K>=3)return this.p2p.reportP2PConnect(M,O.id,"ignore","P2P connections have reached the maximum limit.")}const j=await this.getP2PIns(M);if(j){await j.initSenderPc(),j.sendPeerAnalyzeStatsIns.onNetwork=J=>{this.p2pPush+=Math.ceil(J.outboundBytes/1024)};try{const J=[];for(const ee of N){const{type:ne}=ee;ne!==void 0&&J.push(mediaType_keys[ee.type])}const K=new RTCSessionDescription({type:"offer",sdp:u});await j.setOffer(K),await j.initSenders(N),await this.p2p.replaceSenderStreams([M],J,!0);const Y=await j.createAnswer();if(this.options.debug){const ee=libExports$1.parse(Y.sdp),ne=dt(ee.media,["mid","msid","type"]);console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#ffffff;","------->quickvo: createAnswer",{msidArr:ne,sdpJson:ee})}const re=await j.getSenderTracks(J),oe=this.getOptions(),{roomId:te}=oe,le=()=>new Promise(async(ee,ne)=>{try{const ue=await this.cwsIns.sendMessage({event:"answer",data:{roomId:te,tracks:re,sender:{id:O.id,callAction:O.callAction,tracks:[]},receiverId:M,sdp:Y.sdp}}),{code:se=0,desc:ce}=ue;if(se!==200)throw new Error(ce);ee(!0)}catch(ue){ne(ue)}}),pe=()=>new Promise(async(ee,ne)=>{try{const ue=await yt(j.getSendIcecandidates,{message:"await get send candidates is timeout.",timeout:1e4}),se=Array.from(ue,({sdpMid:fe,sdpMLineIndex:ye,candidate:ve})=>({sdpMid:fe,sdpMLineIndex:ye,sdp:ve})),ce=await this.cwsIns.sendMessage({event:"candidate",data:{roomId:te,senderId:O.id,receiverId:M,candidates:se,isSubscribeReceiver:!1}}),{code:he=0,desc:ie}=ce;if(he!==200)throw new Error(ie);ee(!0)}catch(ue){ne(ue)}});await le(),await pe(),await yt(j.sendIceConnected,{message:"await send ice connect is timeout.",timeout:1e4})}catch{}}};this.cwsIns.addNotify({event:"onOffer",callback:B},!0)}{const B=async D=>{const{code:M,data:O}=D;if(M!==200)return;const{senderId:C,candidates:i=[],receiverId:u,isSubscribeReceiver:$=!1}=O,N=this.getOptions(),{userId:F}=N;if($===!1||u!==F)return;const j=await this.getP2PIns(C);if(!j)return;const J=Array.from(i,({sdpMid:K,sdpMLineIndex:Y,sdp:re})=>({sdpMid:K,sdpMLineIndex:Y,candidate:re}));await j.addCandidates(J)};this.cwsIns.addNotify({event:"onCandidate",callback:B},!0)}};p2p={open:(B,D=["microphoneCamera_video"])=>new Promise(async(M,O)=>{const C=this.getOptions(),{roomId:i,userId:u}=C,$=await this.getSelfInfo(),N=wt(),F=new Date().getTime();let j=!1;try{const J=await this.getP2PIns(B);if(!J)return O("illegal user object.");{if(!this.checkUserInRoom(B))return O("P2P connections without a subscription relationship are not allowed.");const le=await this.getUser(B),{tracks:pe=[]}=le;let ee=!0;for(const ne of D)pe.find(se=>se.mediaType===ne&&se.msid||se.origin==="p2p")||(ee=!1);if(ee===!1)return this.p2p.reportP2PConnect(u,B,"ignore","P2P connections without a subscription relationship are not allowed."),O("P2P connections without a subscription relationship are not allowed.")}const K=()=>new Promise(async(te,le)=>{try{await J.initRecvPc();const pe=()=>{const he=J.recv_peer_ins.connectionState;he==="disconnected"&&this.subscribe([{userId:B,mediaTypes:D}]),he==="failed"&&this.p2p.reportP2PConnect(this.options.userId,B,"disconnect","p2p is failed.")};J.recv_peer_ins.addEventListener("connectionstatechange",pe),await J.addRecvs(D);const ee=await J.createOffer();if(this.options.debug){const he=libExports$1.parse(ee.sdp),ie=dt(he.media,["mid","msid","type"]);console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#ffffff;","------->quickvo: createOffer",{msidArr:ie,sdpJson:he})}const ne=await J.getRecvTracks(D),ue=await this.cwsIns.sendMessage({event:"offer",data:{roomId:i,tracks:ne,sender:{id:$.id,callAction:$.callAction,tracks:[]},receiverId:B,sdp:ee.sdp}}),{code:se=0,desc:ce}=ue;if(se!==200)throw new Error(ce);te(!0)}catch(pe){le(pe)}}),Y=()=>yt(()=>new Promise(le=>{const pe=async ee=>{const{code:ne,data:ue}=ee;if(ne!==200)return;const{sender:se,sdp:ce,tracks:he=[]}=ue,{id:ie}=se;B===ie&&le({answer:{type:"answer",sdp:ce},tracks:he})};this.cwsIns.addNotify({event:"onAnswer",callback:pe,sn:`onAnswer: ${N}`},!0)}),{message:"await_answer is timeout.",timeout:20*1e3}),re=()=>new Promise(async(te,le)=>{try{const pe=await yt(J.getRecvIcecandidates,{message:"await get recv candidates is timeout.",timeout:1e4}),ee=Array.from(pe,({sdpMid:ce,sdpMLineIndex:he,candidate:ie})=>({sdpMid:ce,sdpMLineIndex:he,sdp:ie})),ne=await this.cwsIns.sendMessage({event:"candidate",data:{roomId:i,senderId:$.id,receiverId:B,candidates:ee,isSubscribeReceiver:!0}}),{code:ue=0,desc:se}=ne;if(ue!==200)throw new Error(se);te(!0)}catch(pe){le(pe)}}),oe=()=>yt(()=>new Promise(le=>{const pe=async ee=>{const{code:ne,data:ue}=ee;if(ne!==200)return;const{candidates:se=[],isSubscribeReceiver:ce=!1}=ue;if(ce===!1){const he=Array.from(se,({sdpMid:ie,sdpMLineIndex:fe,sdp:ye})=>({sdpMid:ie,sdpMLineIndex:fe,candidate:ye}));le(he)}};this.cwsIns.addNotify({event:"onCandidate",callback:pe,sn:`onCandidate: ${N}`},!0)}),{message:"await_answer_candidates is timeout.",timeout:20*1e3});Promise.all([Y(),oe()]).then(async te=>{const[{answer:le},pe]=te;if(this.options.debug){const ne=libExports$1.parse(le.sdp),ue=dt(ne.media,["mid","msid","type"]);console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#ffffff;","------->quickvo: setAnswer",{msidArr:ue,sdpJson:ne})}await J.setAnswer(le,pe),await yt(J.recvIceConnected,{message:"recv ice connect is timeout.",timeout:10*1e3});const ee=new Date().getTime()-F;this.p2p.reportP2PConnect(u,B,"success","连接成功",[],ee),this.options.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->quickvo: will compare the quality of P2P and SFU networks in 10 seconds."),J.recvPeerAnalyzeStatsIns.onNetwork=async ne=>{const{inboundBytes:ue,averageQuality:se}=ne;if(this.p2pPull+=Math.ceil(ue/1024),se===0)return;const{current_origin:ce,suggest_origin:he}=await this.#f(B,"microphoneCamera_video");if(j===!1){if(await this.#u(B,D,he),he==="sfu")return this.p2p.reportP2PConnect(u,B,"poor_network",`P2P quality is ${se}.`),await J.clearRecvPc(),M(!0);if(he==="p2p"){j=!0,await this.emitNotifyUpdateUsers();const ie=this.createUserUpdateStreams(D);await this.emitNotifyUpdateUsersStreams([{userId:B,updateStreams:ie}]),ce==="sfu"&&this.#s([{userId:B,mediaTypes:D}],!1)}return M(!0)}if(ce!==he)if(he==="p2p"){await this.#u(B,D,"p2p"),ce==="sfu"&&this.#s([{userId:B,mediaTypes:D}],!1),await this.emitNotifyUpdateUsers();const ie=this.createUserUpdateStreams(D);await this.emitNotifyUpdateUsersStreams([{userId:B,updateStreams:ie}])}else{if(this.hasAsyncTask("subscribe"))return;this.p2p.reportP2PConnect(u,B,"poor_network",`P2P quality is ${se}.`),this.subscribe([{userId:B,mediaTypes:D}])}}}).catch(te=>{O(te),this.p2p.reportP2PConnect(u,B,"fail",te.message||te)}).finally(()=>{this.cwsIns.removeNotify([`onAnswer: ${N}`,`onCandidate: ${N}`])}),await K(),await re()}catch(J){this.p2p.reportP2PConnect(u,B,"fail",J.message||J),O(J)}}),replaceSenderStreams:async(B,D=[],M)=>{const O=this.getOptions();for(const C of B){const{userId:i}=O,u=await this.getP2PIns(C);if(!(!u||!u.send_peer_ins))for(const $ of D){const N=u.send_transceiverMap.get($);let F;if(N){const{sender:j}=N;M?F=this.getUserStream(i,$):F=this.getPhoneyStreams($);const[J]=F.getTracks();J&&await j.replaceTrack(J)}}}},reportNetwork:()=>new Promise(async(B,D)=>{try{let M=0;switch((await h()).natType){case"Symmetric":M=0;break;case"Full Cone":M=1;break;case"Port Restricted Cone":M=2;break;case"Restricted Cone":M=3;break}let O=0;switch((navigator.connection||navigator.mozConnection||navigator.webkitConnection).effectiveType){case"wifi":O=0;break;case"4g":case"3g":case"2g":case"slow-2g":O=2;break;default:O=1;break}await this.cwsIns.sendMessage({event:"reportNetwork",data:{nat:M,type:O}}),B(!0)}catch(M){D(M)}}),reportP2PConnect:(B,D,M,O="",C=[],i=0)=>{let u;switch(M){case"success":u=0;break;case"fail":u=1;break;case"ignore":u=2;break;case"disconnect":u=3;break;case"poor_network":u=4;break}return this.cwsIns.sendMessage({event:"reportP2PConnect",data:{userId:B,origin:D,code:u,reason:O,pushUserIds:C,connectedTime:i}})},closeSend:async(B=[],D=[])=>{B.length===0&&(B=[...this.p2pMap.keys()]);for(const M of B){const O=await this.getP2PIns(M);if(!O||!O.recv_peer_ins)return;O.sendPeerAnalyzeStatsIns.stop(),await O.clearSenderPc(),this.options.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;",`------->quickvo: close closeSend: ${M}`,M,D)}},closeRecv:async(B=[],D=[])=>{B.length===0&&(B=[...this.p2pMap.keys()]);for(const M of B){const O=await this.getP2PIns(M);if(!O||!O.recv_peer_ins)return;O.recvPeerAnalyzeStatsIns.stop(),await O.clearRecvPc(),this.options.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;",`------->quickvo: close closeRecv: ${M}`,M,D)}}}}class Room extends RoomCalls{constructor(B){super(B)}}class QuickVO extends Room{#e=new Map;constructor(B){super(B),this.#t(),this.#n()}#n=()=>{{const B=async D=>{const{state:M}=D.data;if(M==="closed"){const{roomId:O,userId:C}=this.getOptions(),i={roomId:O,user:{id:C}};this.stopHeartbeat(),this.cwsIns.sendMessage({event:"quitRoom",data:i}),this.reportLogs("webrtc_c_timeout","webrtc state is closed.")}};this.cwsIns.addNotify({event:"onRoomState",callback:B},!0)}{const B=async D=>{const{state:M}=D.data;["closed","failed"].includes(M)&&this.restoreICE()};this.cwsIns.addNotify({event:"onIceState",callback:B},!0)}{const B=async D=>{const{qualities:M=[]}=D.data,[O]=M,{userId:C}=this.getOptions();if(!(O&&O.userId===C&&M.length===1)){for(const i of M){const{userId:u,egress:$,ingress:N}=i;this.checkUserInRoom(u)&&await this.updateUserNetwork(u,{egress:$,ingress:N})}await this.emitNotifyUpdateUsers()}};this.cwsIns.addNotify({event:"onNetQuality",callback:B},!0)}{const B=async D=>{const M=D.data.user;await this.removeUsers([M.id]),await this.updateUsers([M]),await this.updateUsertracks(M.id,M.track,!1),await this.updateUserBehaviors(M.id,M.behavior),await this.emitNotifyUpdateUsers()};this.cwsIns.addNotify({event:"onJoinRoom",callback:B},!0)}{const B=async D=>{await this.removeUsers([D.data.user.id]),await this.emitNotifyUpdateUsers()};this.cwsIns.addNotify({event:"onQuitRoom",callback:B},!0)}{const B=async D=>{const{user:M}=D.data,{id:O,tracks:C=[],callAction:i=0}=M;if(await this.updateUserCallAction(O,i),await this.updateUserPermissions(O,3),await this.updateUsertracks(O,C,!0),this.await_remote_publish_users.length!==0&&this.options.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->quickvo: ignore some user track releases.",this.await_remote_publish_users),this.options.newPublishAutoSubscribe){const u=[],$=(K,Y)=>{const re=this.await_remote_publish_users.find(te=>te.id===K);return!(!re||!re.tracks.find(te=>te.type===Y))},N=[];if(!this.checkUserInRoom(O))return;const j=await this.getUser(O);for(const K of j.tracks)for(const Y of C)K.type===Y.type&&$(O,Y.type)===!1&&N.push(Y.mediaType);const J=[...new Set(N)];u.push({userId:O,mediaTypes:J}),await this.subscribe(u)}else await this.emitNotifyUpdateUsers()};this.cwsIns.addNotify({event:"onPublish",callback:B},!0)}{const B=async D=>{const{id:M,tracks:O}=D.data.user,{userId:C}=this.getOptions();if(M===C||!this.checkUserInRoom(M))return;const u=Array.from(O,j=>j.trackName),$=await this.getUser(M),N=[];for(const j of $.tracks)u.includes(j.trackName)&&N.push(j.mediaType);await this.stopSubscribe([{userId:M,mediaTypes:N}]);const F=$.tracks.filter(j=>!u.includes(j.trackName));await this.updateUsertracks(M,F,!1),await this.emitNotifyUpdateUsers()};this.cwsIns.addNotify({event:"onCloseTrack",callback:B},!0)}{const B=async D=>{const{id:M,callAction:O}=D.data.user;this.checkUserInRoom(M)&&(await this.updateUserCallAction(M,O),this.emitNotifyUpdateUsers())};this.cwsIns.addNotify({event:"onUpdateCall",callback:B},!0)}{const B=async D=>{const{roomId:M,remoteUserId:O}=D.data,C=this.getOptions();this.checkUserInRoom(O)&&M===C.roomId&&this.p2p.closeSend([O])};this.cwsIns.addNotify({event:"onDisconnectP2P",callback:B},!0)}{const B=async D=>{const{user:M}=D.data,{id:O,permissions:C=1}=M;C===1?await this.removeUsers([O]):C===3&&await this.updateUsers([M]),await this.emitNotifyUpdateUsers()};this.cwsIns.addNotify({event:"onUpdatePermissions",callback:B},!0)}{const B=async D=>{const{users:M}=D.data;for(const O of M){const{id:C,behavior:i}=O;await this.updateUserBehaviors(C,i)}await this.emitNotifyUpdateUsers()};this.cwsIns.addNotify({event:"onUpdateBehavior",callback:B},!0)}{const B=async D=>{const{roomId:M,userId:O}=D.data;this.checkUserInRoom(O)&&this.options.roomId===M&&(await new Promise(C=>setTimeout(()=>C(!0),1e3)),this.p2p.open(O))};this.cwsIns.addNotify({event:"onAttemptP2PReq",callback:B},!0)}{const B=async D=>{const{session:M,sessionIsValid:O=!0,tracks:C=[]}=D.data;if(M!==this.sdk_session||O===!1)return this.restoreICE();const i=[],u=Array.from(C,N=>N.trackName),$=await this.getUserTrackByTrackName(u);for(const N of $)N&&N.mediaType&&i.push(N.mediaType);await this.stopPublish(i),await this.publish(i)};this.cwsIns.addNotify({event:"onTrackInactive",callback:B},!0)}this.cwsIns.addNotify({event:"onTokenExpired",callback:async B=>this.destroy()},!0),this.cwsIns.addNotify({event:"destroyRoom",callback:this.destroy},!0)};addNotify=B=>this.cwsIns.addNotify(B);#t=()=>{this.cwsIns.prws.checkReconnect=async B=>B.code===1e3?(this.setRoomState("closed"),!1):B.code===4001?(this.setRoomState("closed"),!1):B.code===4002?(this.setRoomState("closed"),!1):B.code===4003?(this.setRoomState("closed"),!1):(this.setSession(),B.code===4010?(this.setRoomState("connecting"),!0):(this.setRoomState("connecting"),!0)),this.cwsIns.prws.onReconnectSuccess=async B=>{this.setRoomState("connected"),await this.restoreRoom(),await this.prResolves.emit("cwsConnected")},this.cwsIns.prws.onReconnectStop=async B=>{this.setRoomState("closed")}};addRequestAnimationFrame=async(B,D)=>{{const O=this.#e.get(B);O&&cancelAnimationFrame(O)}const M=(O=Date.now())=>{D(O);const C=requestAnimationFrame(M);this.#e.set(B,C)};M()};clearRequestAnimationFrame=async(B=[])=>{B.length===0&&(B=[...this.#e.keys()]);const D=[];for(const M of B){const O=this.#e.get(M);O&&(cancelAnimationFrame(O),D.push(O))}return D};destroy=async()=>{this.stopLocalStreams(),this.stopGetPeerStats(),this.quitRoom(),this.clearUsers(),this.clearUserStreams(),this.stopHeartbeat(),await new Promise(B=>setTimeout(()=>B(!0),300)),this.cwsIns.emitNotify("onDestroy",{code:200,data:{},desc:"sdk is destroy."}),this.cwsIns.close(),this.options.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->quickvo: 销毁SDK")}}exports.QuickVO=QuickVO,Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"})});
|