UNPKG

@swarmcloud/theoplayer

Version:

Let your viewers become your unlimitedly scalable CDN.

1 lines 183 kB
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.P2pEngineTheo=t():e.P2pEngineTheo=t()}(this,(()=>(()=>{var e={415:e=>{"use strict";var t,s="object"==typeof Reflect?Reflect:null,i=s&&"function"==typeof s.apply?s.apply:function(e,t,s){return Function.prototype.apply.call(e,t,s)};t=s&&"function"==typeof s.ownKeys?s.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var r=Number.isNaN||function(e){return e!=e};function n(){n.init.call(this)}e.exports=n,e.exports.once=function(e,t){return new Promise((function(s,i){function r(s){e.removeListener(t,n),i(s)}function n(){"function"==typeof e.removeListener&&e.removeListener("error",r),s([].slice.call(arguments))}p(e,t,n,{once:!0}),"error"!==t&&function(e,t,s){"function"==typeof e.on&&p(e,"error",t,s)}(e,r,{once:!0})}))},n.EventEmitter=n,n.prototype._events=void 0,n.prototype._eventsCount=0,n.prototype._maxListeners=void 0;var o=10;function a(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function h(e){return void 0===e._maxListeners?n.defaultMaxListeners:e._maxListeners}function l(e,t,s,i){var r,n,o,l;if(a(s),void 0===(n=e._events)?(n=e._events=Object.create(null),e._eventsCount=0):(void 0!==n.newListener&&(e.emit("newListener",t,s.listener?s.listener:s),n=e._events),o=n[t]),void 0===o)o=n[t]=s,++e._eventsCount;else if("function"==typeof o?o=n[t]=i?[s,o]:[o,s]:i?o.unshift(s):o.push(s),(r=h(e))>0&&o.length>r&&!o.warned){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=o.length,l=c,console&&console.warn&&console.warn(l)}return e}function c(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function d(e,t,s){var i={fired:!1,wrapFn:void 0,target:e,type:t,listener:s},r=c.bind(i);return r.listener=s,i.wrapFn=r,r}function u(e,t,s){var i=e._events;if(void 0===i)return[];var r=i[t];return void 0===r?[]:"function"==typeof r?s?[r.listener||r]:[r]:s?function(e){for(var t=new Array(e.length),s=0;s<t.length;++s)t[s]=e[s].listener||e[s];return t}(r):f(r,r.length)}function g(e){var t=this._events;if(void 0!==t){var s=t[e];if("function"==typeof s)return 1;if(void 0!==s)return s.length}return 0}function f(e,t){for(var s=new Array(t),i=0;i<t;++i)s[i]=e[i];return s}function p(e,t,s,i){if("function"==typeof e.on)i.once?e.once(t,s):e.on(t,s);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,(function r(n){i.once&&e.removeEventListener(t,r),s(n)}))}}Object.defineProperty(n,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(e){if("number"!=typeof e||e<0||r(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");o=e}}),n.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},n.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||r(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},n.prototype.getMaxListeners=function(){return h(this)},n.prototype.emit=function(e){for(var t=[],s=1;s<arguments.length;s++)t.push(arguments[s]);var r="error"===e,n=this._events;if(void 0!==n)r=r&&void 0===n.error;else if(!r)return!1;if(r){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var h=n[e];if(void 0===h)return!1;if("function"==typeof h)i(h,this,t);else{var l=h.length,c=f(h,l);for(s=0;s<l;++s)i(c[s],this,t)}return!0},n.prototype.addListener=function(e,t){return l(this,e,t,!1)},n.prototype.on=n.prototype.addListener,n.prototype.prependListener=function(e,t){return l(this,e,t,!0)},n.prototype.once=function(e,t){return a(t),this.on(e,d(this,e,t)),this},n.prototype.prependOnceListener=function(e,t){return a(t),this.prependListener(e,d(this,e,t)),this},n.prototype.removeListener=function(e,t){var s,i,r,n,o;if(a(t),void 0===(i=this._events))return this;if(void 0===(s=i[e]))return this;if(s===t||s.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,s.listener||t));else if("function"!=typeof s){for(r=-1,n=s.length-1;n>=0;n--)if(s[n]===t||s[n].listener===t){o=s[n].listener,r=n;break}if(r<0)return this;0===r?s.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(s,r),1===s.length&&(i[e]=s[0]),void 0!==i.removeListener&&this.emit("removeListener",e,o||t)}return this},n.prototype.off=n.prototype.removeListener,n.prototype.removeAllListeners=function(e){var t,s,i;if(void 0===(s=this._events))return this;if(void 0===s.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==s[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete s[e]),this;if(0===arguments.length){var r,n=Object.keys(s);for(i=0;i<n.length;++i)"removeListener"!==(r=n[i])&&this.removeAllListeners(r);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=s[e]))this.removeListener(e,t);else if(void 0!==t)for(i=t.length-1;i>=0;i--)this.removeListener(e,t[i]);return this},n.prototype.listeners=function(e){return u(this,e,!0)},n.prototype.rawListeners=function(e){return u(this,e,!1)},n.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):g.call(e,t)},n.prototype.listenerCount=g,n.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]}},558:function(e){!function(t){var s=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,r=/(?:\/|^)\.(?=\/)/g,n=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(e,t,s){if(s=s||{},e=e.trim(),!(t=t.trim())){if(!s.alwaysNormalize)return e;var r=o.parseURL(e);if(!r)throw new Error("Error trying to parse base URL.");return r.path=o.normalizePath(r.path),o.buildURLFromParts(r)}var n=o.parseURL(t);if(!n)throw new Error("Error trying to parse relative URL.");if(n.scheme)return s.alwaysNormalize?(n.path=o.normalizePath(n.path),o.buildURLFromParts(n)):t;var a=o.parseURL(e);if(!a)throw new Error("Error trying to parse base URL.");if(!a.netLoc&&a.path&&"/"!==a.path[0]){var h=i.exec(a.path);a.netLoc=h[1],a.path=h[2]}a.netLoc&&!a.path&&(a.path="/");var l={scheme:a.scheme,netLoc:n.netLoc,path:null,params:n.params,query:n.query,fragment:n.fragment};if(!n.netLoc&&(l.netLoc=a.netLoc,"/"!==n.path[0]))if(n.path){var c=a.path,d=c.substring(0,c.lastIndexOf("/")+1)+n.path;l.path=o.normalizePath(d)}else l.path=a.path,n.params||(l.params=a.params,n.query||(l.query=a.query));return null===l.path&&(l.path=s.alwaysNormalize?o.normalizePath(n.path):n.path),o.buildURLFromParts(l)},parseURL:function(e){var t=s.exec(e);return t?{scheme:t[1]||"",netLoc:t[2]||"",path:t[3]||"",params:t[4]||"",query:t[5]||"",fragment:t[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(r,"");e.length!==(e=e.replace(n,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}};e.exports=o}()},424:(e,t)=>{"use strict";t.h=r;var s=2147483647;function i(e){if(e>s)throw new RangeError('The value "'+e+'" is invalid for option "size"');var t=new Uint8Array(e);return t.__proto__=r.prototype,t}function r(e,t,s){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return a(e)}return n(e,t,s)}function n(e,t,s){if("string"==typeof e)return function(e,t){"string"==typeof t&&""!==t||(t="utf8");if(!r.isEncoding(t))throw new TypeError("Unknown encoding: "+t);var s=0|c(e,t),n=i(s),o=n.write(e,t);o!==s&&(n=n.slice(0,o));return n}(e,t);if(ArrayBuffer.isView(e))return h(e);if(null==e)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(_(e,ArrayBuffer)||e&&_(e.buffer,ArrayBuffer))return function(e,t,s){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(s||0))throw new RangeError('"length" is outside of buffer bounds');var i;i=void 0===t&&void 0===s?new Uint8Array(e):void 0===s?new Uint8Array(e,t):new Uint8Array(e,t,s);return i.__proto__=r.prototype,i}(e,t,s);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');var n=e.valueOf&&e.valueOf();if(null!=n&&n!==e)return r.from(n,t,s);var o=function(e){if(r.isBuffer(e)){var t=0|l(e.length),s=i(t);return 0===s.length||e.copy(s,0,0,t),s}if(void 0!==e.length)return"number"!=typeof e.length||y(e.length)?i(0):h(e);if("Buffer"===e.type&&Array.isArray(e.data))return h(e.data)}(e);if(o)return o;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return r.from(e[Symbol.toPrimitive]("string"),t,s);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function o(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function a(e){return o(e),i(e<0?0:0|l(e))}function h(e){for(var t=e.length<0?0:0|l(e.length),s=i(t),r=0;r<t;r+=1)s[r]=255&e[r];return s}function l(e){if(e>=s)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s.toString(16)+" bytes");return 0|e}function c(e,t){if(r.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||_(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);var s=e.length,i=arguments.length>2&&!0===arguments[2];if(!i&&0===s)return 0;for(var n=!1;;)switch(t){case"ascii":case"latin1":case"binary":return s;case"utf8":case"utf-8":return m(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*s;case"hex":return s>>>1;default:if(n)return i?-1:m(e).length;t=(""+t).toLowerCase(),n=!0}}function d(e,t,s,i){s=Number(s)||0;const r=e.length-s;i?(i=Number(i))>r&&(i=r):i=r;const n=t.length;let o;for(i>n/2&&(i=n/2),o=0;o<i;++o){const i=parseInt(t.substr(2*o,2),16);if(y(i))return o;e[s+o]=i}return o}function u(e,t,s,i){return p(m(t,e.length-s),e,s,i)}function g(e,t,s,i){return p(function(e){const t=[];for(let s=0;s<e.length;++s)t.push(255&e.charCodeAt(s));return t}(t),e,s,i)}function f(e,t,s,i){return p(function(e,t){let s,i,r;const n=[];for(let o=0;o<e.length&&!((t-=2)<0);++o)s=e.charCodeAt(o),i=s>>8,r=s%256,n.push(r),n.push(i);return n}(t,e.length-s),e,s,i)}function p(e,t,s,i){let r;for(r=0;r<i&&!(r+s>=t.length||r>=e.length);++r)t[r+s]=e[r];return r}function m(e,t){var s;t=t||1/0;for(var i=e.length,r=null,n=[],o=0;o<i;++o){if((s=e.charCodeAt(o))>55295&&s<57344){if(!r){if(s>56319){(t-=3)>-1&&n.push(239,191,189);continue}if(o+1===i){(t-=3)>-1&&n.push(239,191,189);continue}r=s;continue}if(s<56320){(t-=3)>-1&&n.push(239,191,189),r=s;continue}s=65536+(r-55296<<10|s-56320)}else r&&(t-=3)>-1&&n.push(239,191,189);if(r=null,s<128){if((t-=1)<0)break;n.push(s)}else if(s<2048){if((t-=2)<0)break;n.push(s>>6|192,63&s|128)}else if(s<65536){if((t-=3)<0)break;n.push(s>>12|224,s>>6&63|128,63&s|128)}else{if(!(s<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;n.push(s>>18|240,s>>12&63|128,s>>6&63|128,63&s|128)}}return n}function _(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function y(e){return e!=e}"undefined"!=typeof Symbol&&null!=Symbol.species&&r[Symbol.species]===r&&Object.defineProperty(r,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),r.from=function(e,t,s){return n(e,t,s)},r.prototype.__proto__=Uint8Array.prototype,r.__proto__=Uint8Array,r.alloc=function(e,t,s){return function(e,t,s){return o(e),e<=0?i(e):void 0!==t?"string"==typeof s?i(e).fill(t,s):i(e).fill(t):i(e)}(e,t,s)},r.allocUnsafe=function(e){return a(e)},r.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==r.prototype},r.isEncoding=function(e){switch(String(e).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}},r.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return r.alloc(0);var s;if(void 0===t)for(t=0,s=0;s<e.length;++s)t+=e[s].length;var i=r.allocUnsafe(t),n=0;for(s=0;s<e.length;++s){var o=e[s];if(_(o,Uint8Array)&&(o=r.from(o)),!r.isBuffer(o))throw new TypeError('"list" argument must be an Array of Buffers');o.copy(i,n),n+=o.length}return i},r.byteLength=c,r.prototype._isBuffer=!0,r.prototype.copy=function(e,t,s,i){if(!r.isBuffer(e))throw new TypeError("argument should be a Buffer");if(s||(s=0),i||0===i||(i=this.length),t>=e.length&&(t=e.length),t||(t=0),i>0&&i<s&&(i=s),i===s)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(s<0||s>=this.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),e.length-t<i-s&&(i=e.length-t+s);var n=i-s;if(this===e&&"function"==typeof Uint8Array.prototype.copyWithin)this.copyWithin(t,s,i);else if(this===e&&s<t&&t<i)for(var o=n-1;o>=0;--o)e[o+t]=this[o+s];else Uint8Array.prototype.set.call(e,this.subarray(s,i),t);return n},r.prototype.write=function(e,t,s,i){if(void 0===t)i="utf8",s=this.length,t=0;else if(void 0===s&&"string"==typeof t)i=t,s=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(s)?(s>>>=0,void 0===i&&(i="utf8")):(i=s,s=void 0)}const r=this.length-t;if((void 0===s||s>r)&&(s=r),e.length>0&&(s<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");let n=!1;for(;;)switch(i){case"hex":return d(this,e,t,s);case"utf8":case"utf-8":return u(this,e,t,s);case"ascii":case"latin1":case"binary":return g(this,e,t,s);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return f(this,e,t,s);default:if(n)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),n=!0}}},832:function(e,t,s){var i;!function(r){"use strict";function n(e,t){var s=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(s>>16)<<16|65535&s}function o(e,t,s,i,r,o){return n((a=n(n(t,e),n(i,o)))<<(h=r)|a>>>32-h,s);var a,h}function a(e,t,s,i,r,n,a){return o(t&s|~t&i,e,t,r,n,a)}function h(e,t,s,i,r,n,a){return o(t&i|s&~i,e,t,r,n,a)}function l(e,t,s,i,r,n,a){return o(t^s^i,e,t,r,n,a)}function c(e,t,s,i,r,n,a){return o(s^(t|~i),e,t,r,n,a)}function d(e,t){var s,i,r,o,d;e[t>>5]|=128<<t%32,e[14+(t+64>>>9<<4)]=t;var u=1732584193,g=-271733879,f=-1732584194,p=271733878;for(s=0;s<e.length;s+=16)i=u,r=g,o=f,d=p,u=a(u,g,f,p,e[s],7,-680876936),p=a(p,u,g,f,e[s+1],12,-389564586),f=a(f,p,u,g,e[s+2],17,606105819),g=a(g,f,p,u,e[s+3],22,-1044525330),u=a(u,g,f,p,e[s+4],7,-176418897),p=a(p,u,g,f,e[s+5],12,1200080426),f=a(f,p,u,g,e[s+6],17,-1473231341),g=a(g,f,p,u,e[s+7],22,-45705983),u=a(u,g,f,p,e[s+8],7,1770035416),p=a(p,u,g,f,e[s+9],12,-1958414417),f=a(f,p,u,g,e[s+10],17,-42063),g=a(g,f,p,u,e[s+11],22,-1990404162),u=a(u,g,f,p,e[s+12],7,1804603682),p=a(p,u,g,f,e[s+13],12,-40341101),f=a(f,p,u,g,e[s+14],17,-1502002290),u=h(u,g=a(g,f,p,u,e[s+15],22,1236535329),f,p,e[s+1],5,-165796510),p=h(p,u,g,f,e[s+6],9,-1069501632),f=h(f,p,u,g,e[s+11],14,643717713),g=h(g,f,p,u,e[s],20,-373897302),u=h(u,g,f,p,e[s+5],5,-701558691),p=h(p,u,g,f,e[s+10],9,38016083),f=h(f,p,u,g,e[s+15],14,-660478335),g=h(g,f,p,u,e[s+4],20,-405537848),u=h(u,g,f,p,e[s+9],5,568446438),p=h(p,u,g,f,e[s+14],9,-1019803690),f=h(f,p,u,g,e[s+3],14,-187363961),g=h(g,f,p,u,e[s+8],20,1163531501),u=h(u,g,f,p,e[s+13],5,-1444681467),p=h(p,u,g,f,e[s+2],9,-51403784),f=h(f,p,u,g,e[s+7],14,1735328473),u=l(u,g=h(g,f,p,u,e[s+12],20,-1926607734),f,p,e[s+5],4,-378558),p=l(p,u,g,f,e[s+8],11,-2022574463),f=l(f,p,u,g,e[s+11],16,1839030562),g=l(g,f,p,u,e[s+14],23,-35309556),u=l(u,g,f,p,e[s+1],4,-1530992060),p=l(p,u,g,f,e[s+4],11,1272893353),f=l(f,p,u,g,e[s+7],16,-155497632),g=l(g,f,p,u,e[s+10],23,-1094730640),u=l(u,g,f,p,e[s+13],4,681279174),p=l(p,u,g,f,e[s],11,-358537222),f=l(f,p,u,g,e[s+3],16,-722521979),g=l(g,f,p,u,e[s+6],23,76029189),u=l(u,g,f,p,e[s+9],4,-640364487),p=l(p,u,g,f,e[s+12],11,-421815835),f=l(f,p,u,g,e[s+15],16,530742520),u=c(u,g=l(g,f,p,u,e[s+2],23,-995338651),f,p,e[s],6,-198630844),p=c(p,u,g,f,e[s+7],10,1126891415),f=c(f,p,u,g,e[s+14],15,-1416354905),g=c(g,f,p,u,e[s+5],21,-57434055),u=c(u,g,f,p,e[s+12],6,1700485571),p=c(p,u,g,f,e[s+3],10,-1894986606),f=c(f,p,u,g,e[s+10],15,-1051523),g=c(g,f,p,u,e[s+1],21,-2054922799),u=c(u,g,f,p,e[s+8],6,1873313359),p=c(p,u,g,f,e[s+15],10,-30611744),f=c(f,p,u,g,e[s+6],15,-1560198380),g=c(g,f,p,u,e[s+13],21,1309151649),u=c(u,g,f,p,e[s+4],6,-145523070),p=c(p,u,g,f,e[s+11],10,-1120210379),f=c(f,p,u,g,e[s+2],15,718787259),g=c(g,f,p,u,e[s+9],21,-343485551),u=n(u,i),g=n(g,r),f=n(f,o),p=n(p,d);return[u,g,f,p]}function u(e){var t,s="",i=32*e.length;for(t=0;t<i;t+=8)s+=String.fromCharCode(e[t>>5]>>>t%32&255);return s}function g(e){var t,s=[];for(s[(e.length>>2)-1]=void 0,t=0;t<s.length;t+=1)s[t]=0;var i=8*e.length;for(t=0;t<i;t+=8)s[t>>5]|=(255&e.charCodeAt(t/8))<<t%32;return s}function f(e){var t,s,i="0123456789abcdef",r="";for(s=0;s<e.length;s+=1)t=e.charCodeAt(s),r+=i.charAt(t>>>4&15)+i.charAt(15&t);return r}function p(e){return unescape(encodeURIComponent(e))}function m(e){return function(e){return u(d(g(e),8*e.length))}(p(e))}function _(e,t){return function(e,t){var s,i,r=g(e),n=[],o=[];for(n[15]=o[15]=void 0,r.length>16&&(r=d(r,8*e.length)),s=0;s<16;s+=1)n[s]=909522486^r[s],o[s]=1549556828^r[s];return i=d(n.concat(g(t)),512+8*t.length),u(d(o.concat(i),640))}(p(e),p(t))}function y(e,t,s){return t?s?_(t,e):f(_(t,e)):s?m(e):f(m(e))}void 0===(i=function(){return y}.call(t,s,t,e))||(e.exports=i)}()},365:e=>{const t={ANDROID_WEB:"android-web",IOS_WEB:"iOS-web",PC_NATIVE:"PC-web",PC_WEB:"PC-web"};var s={getNetType:function(){let e=(new RegExp("nettype\\/(\\w*)").exec(i())||[,""])[1].toLowerCase();if(!e&&navigator.connection){switch(navigator.connection.type){case"ethernet":e="ethernet";break;case"cellular":e="cellular";break;default:e="wifi"}}return e},getPlatform:function(){return s.isAndroid()||s.isAndroidWebView()?t.ANDROID_WEB:s.isIOS()||s.isIpad()||s.isIOSWebView()?t.IOS_WEB:s.isElectron()?t.PC_NATIVE:t.PC_WEB},isX5:function(){return this.isAndroid()&&/\s(TBS|X5Core)\/[\w\.\-]+/i.test(i())},isPC:function(){return!n(r("os "))&&!n(r("android[/ ]"))},isIOS:function(){return n(r("os "))},isIpad:function(){return i().match(/(ipad)/)||"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1},isAndroid:function(){return n(r("android[/ ]"))},isIOSSafari:function(){return this.isIOS()&&this.isSafari()},isIpadSafari:function(){return this.isIpad()&&this.isSafari()},isElectron:function(){return/electron/i.test(i())},isMobile:function(){return s.isAndroid()||s.isIOS()},isSafari:function(){return/^((?!chrome|android).)*safari/i.test(i())},isFirefox:function(){return/firefox/i.test(i())},isChrome:function(){return/chrome/i.test(i())},isLocalHost:function(){return"localhost"===location.hostname},isAndroidWebView:function(){const e=i();return e.indexOf("wv")>-1&&e.indexOf("android")>-1},isIOSWebView:function(){const e=i();return/\b(ipad|iphone|macintosh).*applewebKit(?!.*safari)/i.test(e)},isWebView:function(){return s.isAndroidWebView()||s.isIOSWebView()},device:t,getBrowser:function(){return s.isX5()?"X5":s.isAndroidWebView()?"Android-WebView":s.isIOSWebView()?"iOS-WebView":s.isChrome()?"Chrome":s.isFirefox()?"Firefox":s.isIpadSafari()?"iPad-Safari":s.isIOSSafari()?"iPhone-Safari":s.isSafari()?"Mac-Safari":"Unknown"}};function i(){return navigator.userAgent.toLowerCase()}function r(e){return""+(new RegExp(e+"(\\d+((\\.|_)\\d+)*)").exec(i())||[,0])[1]||void 0}function n(e){return parseFloat((e||"").replace(/\_/g,"."))||0}e.exports=s}},t={};function s(i){var r=t[i];if(void 0!==r)return r.exports;var n=t[i]={exports:{}};return e[i].call(n.exports,n,n.exports,s),n.exports}s.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return s.d(t,{a:t}),t},s.d=(e,t)=>{for(var i in t)s.o(t,i)&&!s.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},s.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var i={};return(()=>{"use strict";s.d(i,{default:()=>Ts});var e=s(424),t=s(558),r=s.n(t);const n="__PROXY_IDENTIFIER__";const o=64e3;function a(){return!0}function h(e,t,s){const i=new URL(e);return i.searchParams.append(t,s),i.href}function l(){return Date.parse(new Date)/1e3}function c(e,t){return parseInt(Math.random()*(t-e+1)+e,10)}function d(e){return new Promise((t=>setTimeout(t,e)))}function u(){if("object"!=typeof self)return null;var e={RTCPeerConnection:self.RTCPeerConnection||self.mozRTCPeerConnection||self.webkitRTCPeerConnection,RTCSessionDescription:self.RTCSessionDescription||self.mozRTCSessionDescription||self.webkitRTCSessionDescription,RTCIceCandidate:self.RTCIceCandidate||self.mozRTCIceCandidate||self.webkitRTCIceCandidate};return e.RTCPeerConnection&&e.RTCPeerConnection.prototype?e:null}function g(t){const s=e.h.from(t),i=new e.h(t.byteLength);return s.copy(i),i}function f(e,t,s){if(e.size<=t)return;const i=[...e.keys()];do{const t=i.shift();s&&s(e.get(t)),e.delete(t)}while(e.size>t)}function p(e,t){if(e.size<=t)return;const s=[...e.values()];do{e.delete(s.shift())}while(e.size>t)}function m(e){return e instanceof ArrayBuffer&&0!==e.byteLength}function _(e){if(!e)return{};const t=(e=e.substring(6)).split("-");if(2!==t.length)return{};const s=Number(t[0]),i=t[1]?Number(t[1]):-1;return{rangeStart:s,rangeEnd:i>=0?i+1:void 0}}function y(){let e=new Date,t=e.getHours(),s=e.getMinutes(),i=e.getSeconds(),r=e.getMilliseconds();return`${t.toString().padStart(2,"0")}:${s.toString().padStart(2,"0")}:${i.toString().padStart(2,"0")}.${r}`}class S{}function v(e){return e&&"function"==typeof e}function P(e,t,s,i,r,n){e.sendPartialBuffer(s,i,{from:r,incompletes:n})&&(i.length<s.attachments?function(e,t,s){e.addStreamListener(s,t.remotePeerId,((e,s,i,r,n)=>{i?t.sendMsgPieceAbort(r,s,!0):t.uploading&&t.send(r),n&&(t.uploading=!1)}))}(t,e,!!s.reverse):e.uploading=!1)}const b=e=>0===c(0,1)?[null,e]:[e,null];function E(e,t,s){return 1===e.length?t.length>=1&&s.length>=1?t[0].weight>s[0].weight?[t[0],e[0]]:[e[0],s[0]]:t.length>=1?[t[0],e[0]]:s.length>=1?[e[0],s[0]]:b(e[0]):[t.length>=1?t[0]:null,s.length>=1?s[0]:null]}function w(){const e=performance.now();return{trequest:e,tfirst:0,tload:0,aborted:!1,loaded:0,retry:0,total:0,chunkCount:0,bwEstimate:0,loading:{start:e,first:0,end:0},parsing:{start:0,end:0},buffering:{start:0,first:0,end:0}}}var C=s(415),T=s.n(C);let I;const R="function"==typeof queueMicrotask?queueMicrotask.bind(globalThis):e=>(I||(I=Promise.resolve())).then(e).catch((e=>setTimeout((()=>{throw e}),0))),L=65536;function A(e){return e.replace(/a=ice-options:trickle\s\n/g,"")}class D extends(T()){constructor(e){super(),this.channelName=e.initiator?e.channelName:null,this.initiator=e.initiator||!1,this.channelConfig=e.channelConfig||D.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},D.config,e.config),this.offerOptions=e.offerOptions||{},this.answerOptions=e.answerOptions||{},this.sdpTransform=e.sdpTransform||(e=>e),this.trickle=void 0===e.trickle||e.trickle,this.allowHalfTrickle=void 0!==e.allowHalfTrickle&&e.allowHalfTrickle,this.iceCompleteTimeout=e.iceCompleteTimeout||5e3,this.destroyed=!1,this.destroying=!1,this._connected=!1,this.remoteAddress=void 0,this.remoteFamily=void 0,this.remotePort=void 0,this.localAddress=void 0,this.localFamily=void 0,this.localPort=void 0,this._wrtc=u(),this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._pendingData=[],this._isNegotiating=!1,this._firstNegotiation=!0,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._senderMap=new Map,this._closingInterval=null,this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new this._wrtc.RTCPeerConnection(this.config)}catch(e){return void R((()=>this.destroy(e)))}this._pc.oniceconnectionstatechange=()=>{this._onIceStateChange()},this._pc.onicegatheringstatechange=()=>{this._onIceStateChange()},this._pc.onconnectionstatechange=()=>{this._onConnectionStateChange()},this._pc.onsignalingstatechange=()=>{this._onSignalingStateChange()},this._pc.onicecandidate=e=>{this._onIceCandidate(e)},this.initiator||this.channelNegotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=e=>{this._setupData(e)},this._needsNegotiation()}get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&"open"===this._channel.readyState}signal(e){if(!this.destroyed&&this._pc){if("string"==typeof e)try{e=JSON.parse(e)}catch(t){e={}}if(e.renegotiate&&this.initiator&&this._needsNegotiation(),e.candidate)if(this._pc.remoteDescription&&this._pc.remoteDescription.type)try{this._addIceCandidate(e.candidate)}catch(e){}else this._pendingCandidates.push(e.candidate);e.sdp&&this._pc.setRemoteDescription(new this._wrtc.RTCSessionDescription(e)).then((()=>{this.destroyed||(this._pendingCandidates.forEach((e=>{try{this._addIceCandidate(e)}catch(e){}})),this._pendingCandidates=[],"offer"===this._pc.remoteDescription.type&&this._createAnswer())})).catch((e=>{e.debug=!0,this.destroy(e)})),e.sdp||e.candidate||e.renegotiate||e.transceiverRequest||this.destroy(new Error("signal() called with invalid signal data"))}}_addIceCandidate(e){const t=new this._wrtc.RTCIceCandidate(e);this._pc.addIceCandidate(t).catch((e=>{var s;!t.address||t.address.endsWith(".local")?(s="Ignoring unsupported ICE candidate.",console.warn(s)):(e.debug=!0,this.destroy(e))}))}send(e){if("string"==typeof e){RTCDataChannel.prototype.send.toString().includes("[native code]")&&this._channel.send(e)}else this._channel.send(e)}_needsNegotiation(){this._batchedNegotiation||(this._batchedNegotiation=!0,R((()=>{this._batchedNegotiation=!1,!this.initiator&&this._firstNegotiation||this.negotiate(),this._firstNegotiation=!1})))}negotiate(){this.initiator?this._isNegotiating?this._queuedNegotiation=!0:setTimeout((()=>{this._createOffer()}),0):this._isNegotiating?this._queuedNegotiation=!0:this.emit("signal",{type:"renegotiate",renegotiate:!0}),this._isNegotiating=!0}destroy(e){this._destroy(e)}_destroy(e){this.destroyed||this.destroying||(this.destroying=!0,R((()=>{if(this.destroyed=!0,this.destroying=!1,this._connected=!1,this._pcReady=!1,this._channelReady=!1,this._senderMap=null,clearInterval(this._closingInterval),this._closingInterval=null,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._channel){try{this._channel.close()}catch(e){}this._channel.onmessage=null,this._channel.onopen=null,this._channel.onclose=null,this._channel.onerror=null}if(this._pc){try{this._pc.close()}catch(e){}this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null}this._pc=null,this._channel=null,e&&this.emit("error",e),this.emit("close")})))}_setupData(e){if(!e.channel)return this.destroy(new Error("Data channel event is missing `channel` property"));this._channel=e.channel,this._channel.binaryType="arraybuffer","number"==typeof this._channel.bufferedAmountLowThreshold&&(this._channel.bufferedAmountLowThreshold=L),this.channelName=this._channel.label,this._channel.onmessage=e=>{this._onChannelMessage(e)},this._channel.onbufferedamountlow=()=>{this._onChannelBufferedAmountLow()},this._channel.onopen=()=>{this._onChannelOpen()},this._channel.onclose=()=>{this._onChannelClose()},this._channel.onerror=e=>{e.debug=!0,this.destroy(e)};let t=!1;this._closingInterval=setInterval((()=>{this._channel&&"closing"===this._channel.readyState?(t&&this._onChannelClose(),t=!0):t=!1}),5e3)}get isBufferedAmountHigh(){return this._channel.bufferedAmount>L}write(e,t){if(this.destroyed)return t(new Error("cannot write after peer is destroyed"));if(this._connected){try{this.send(e)}catch(e){return this.destroy(e)}this.isBufferedAmountHigh?this._cb=t:t(null)}else this._chunk=e,this._cb=t}_startIceCompleteTimeout(){this.destroyed||this._iceCompleteTimer||(this._iceCompleteTimer=setTimeout((()=>{this._iceComplete||(this._iceComplete=!0,this.emit("iceTimeout"),this.emit("_iceComplete"))}),this.iceCompleteTimeout))}_createOffer(){this.destroyed||this._pc.createOffer(this.offerOptions).then((e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=A(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(this.destroyed)return;const t=this._pc.localDescription||e;this.emit("signal",{type:t.type,sdp:t.sdp})};this._pc.setLocalDescription(e).then((()=>{this.destroyed||(this.trickle||this._iceComplete?t():this.once("_iceComplete",t))})).catch((e=>{this.destroy(e)}))})).catch((e=>{this.destroy(e)}))}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then((e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=A(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(this.destroyed)return;const t=this._pc.localDescription||e;this.emit("signal",{type:t.type,sdp:t.sdp})};this._pc.setLocalDescription(e).then((()=>{this.destroyed||(this.trickle||this._iceComplete?t():this.once("_iceComplete",t))})).catch((e=>{this.destroy(e)}))})).catch((e=>{this.destroy(e)}))}_onConnectionStateChange(){this.destroyed||"failed"===this._pc.connectionState&&this.destroy(new Error("Connection failed."))}_onIceStateChange(){if(this.destroyed)return;const e=this._pc.iceConnectionState,t=this._pc.iceGatheringState;this.emit("iceStateChange",e,t),"connected"!==e&&"completed"!==e||(this._pcReady=!0,this._maybeReady()),"failed"===e&&this.destroy(new Error("Ice connection failed.")),"closed"===e&&this.destroy(new Error("Ice connection closed."))}getStats(e){const t=e=>("[object Array]"===Object.prototype.toString.call(e.values)&&e.values.forEach((t=>{Object.assign(e,t)})),e);0===this._pc.getStats.length?this._pc.getStats().then((s=>{const i=[];s.forEach((e=>{i.push(t(e))})),e(null,i)}),(t=>e(t))):this._pc.getStats.length>0?this._pc.getStats((s=>{if(this.destroyed)return;const i=[];s.result().forEach((e=>{const s={};e.names().forEach((t=>{s[t]=e.stat(t)})),s.id=e.id,s.type=e.type,s.timestamp=e.timestamp,i.push(t(s))})),e(null,i)}),(t=>e(t))):e(null,[])}_maybeReady(){if(this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const e=()=>{this.destroyed||this.getStats(((t,s)=>{if(this.destroyed)return;t&&(s=[]);const i={},r={},n={};let o=!1;s.forEach((e=>{"remotecandidate"!==e.type&&"remote-candidate"!==e.type||(i[e.id]=e),"localcandidate"!==e.type&&"local-candidate"!==e.type||(r[e.id]=e),"candidatepair"!==e.type&&"candidate-pair"!==e.type||(n[e.id]=e)}));const a=e=>{o=!0;let t=r[e.localCandidateId];t&&(t.ip||t.address)?(this.localAddress=t.ip||t.address,this.localPort=Number(t.port)):t&&t.ipAddress?(this.localAddress=t.ipAddress,this.localPort=Number(t.portNumber)):"string"==typeof e.googLocalAddress&&(t=e.googLocalAddress.split(":"),this.localAddress=t[0],this.localPort=Number(t[1])),this.localAddress&&(this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4");let s=i[e.remoteCandidateId];s&&(s.ip||s.address)?(this.remoteAddress=s.ip||s.address,this.remotePort=Number(s.port)):s&&s.ipAddress?(this.remoteAddress=s.ipAddress,this.remotePort=Number(s.portNumber)):"string"==typeof e.googRemoteAddress&&(s=e.googRemoteAddress.split(":"),this.remoteAddress=s[0],this.remotePort=Number(s[1])),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4")};if(s.forEach((e=>{"transport"===e.type&&e.selectedCandidatePairId&&a(n[e.selectedCandidatePairId]),("googCandidatePair"===e.type&&"true"===e.googActiveConnection||("candidatepair"===e.type||"candidate-pair"===e.type)&&e.selected)&&a(e)})),o||Object.keys(n).length&&!Object.keys(r).length){if(this._connecting=!1,this._connected=!0,this._chunk){try{this.send(this._chunk)}catch(t){return this.destroy(t)}this._chunk=null;const e=this._cb;this._cb=null,e(null)}"number"!=typeof this._channel.bufferedAmountLowThreshold&&(this._interval=setInterval((()=>this._onInterval()),150),this._interval.unref&&this._interval.unref()),this.emit("connect");for(let e of this._pendingData)this.emit("data",e);this._pendingData=[]}else setTimeout(e,100)}))};e()}_onInterval(){!this._cb||!this._channel||this._channel.bufferedAmount>L||this._onChannelBufferedAmountLow()}_onSignalingStateChange(){this.destroyed||("stable"===this._pc.signalingState&&(this._isNegotiating=!1,this._queuedNegotiation?(this._queuedNegotiation=!1,this._needsNegotiation()):this.emit("negotiated")),this.emit("signalingStateChange",this._pc.signalingState))}_onIceCandidate(e){this.destroyed||(e.candidate&&this.trickle?this.emit("signal",{type:"candidate",candidate:{candidate:e.candidate.candidate,sdpMLineIndex:e.candidate.sdpMLineIndex,sdpMid:e.candidate.sdpMid}}):e.candidate||this._iceComplete||(this._iceComplete=!0,this.emit("_iceComplete")),e.candidate&&this._startIceCompleteTimeout())}_onChannelMessage(t){if(this.destroyed)return;let s=t.data;s instanceof ArrayBuffer&&(s=e.h.from(s)),this._connected?this.emit("data",s):this._pendingData.length<10&&this._pendingData.push(s)}_onChannelBufferedAmountLow(){if(this.destroyed||!this._cb)return;const e=this._cb;this._cb=null,e(null)}_onChannelOpen(){this._connected||this.destroyed||(this._channelReady=!0,this._maybeReady())}_onChannelClose(){this.destroyed||this.destroy()}}D.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},D.channelConfig={};const M=D,N={DC_SIGNAL:"SIGNAL",DC_SIGNAL_BATCH:"SIGNAL_BATCH",DC_OPEN:"OPEN",DC_REQUEST:"REQUEST",DC_PIECE_NOT_FOUND:"PIECE_NOT_FOUND",DC_PIECE_ABORT:"PIECE_ABORT",DC_PIECE_CANCEL:"PIECE_CANCEL",DC_CLOSE:"CLOSE",DC_DISCONNECT:"DISCONNECT",DC_RESPONSE:"RESPONSE",DC_ERROR:"ERROR",DC_PIECE:"PIECE",DC_PIECE_DATA:"PIECE_DATA",DC_TIMEOUT:"TIMEOUT",DC_PIECE_ACK:"PIECE_ACK",DC_METADATA:"METADATA",DC_PLAT_ANDROID:"ANDROID",DC_PLAT_IOS:"IOS",DC_PLAT_WEB:"WEB",DC_CHOKE:"CHOKE",DC_UNCHOKE:"UNCHOKE",DC_HAVE:"HAVE",DC_HAVE_REVERSE:"HAVE_REVERSE",DC_LOST:"LOST",DC_GET_PEERS:"GET_PEERS",DC_PEERS:"PEERS",DC_STATS:"STATS",DC_PEER_SIGNAL:"PEER_SIGNAL",DC_PLAYLIST:"PLAYLIST",BM_LOST:"lost",BM_ADDED_SEG_:"BM_ADDED_SEG_",BM_ADDED_SN_:"BM_ADDED_SN_",BM_SEG_ADDED:"BM_SEG_ADDED",BM_FATAL_ERROR:"BM_FATAL_ERROR",FRAG_CHANGED:"FRAG_CHANGED",FRAG_LOADED:"FRAG_LOADED",FRAG_LOADING:"FRAG_LOADING",RESTART_P2P:"RESTART_P2P",EXCEPTION:"exception",SYN_OUTPUT:"SYN_OUTPUT",SYN_ERROR:"SYN_ERROR",SYN_PROGRESS:"SYN_PROGRESS",MEDIA_REBUFFER:"MEDIA_REBUFFER"};class k{constructor(e,t,s,i,r=0,n=void 0){this.sn=e,this.segId=t,this.data=s,this.fromPeerId=i,this.level=r||0,this.ext=n}static fromSegment(e){const t=new k(e.sn,e.segId,e.data,e.fromPeerId,e.level,e.ext);return t.from=e.from,t}get size(){return this.data.byteLength}get isSequential(){return this.sn>=0}}var O=s(365),$=s.n(O);class B extends(T()){static get defaultPacketSize(){return o}static get VERSION(){return"8"}constructor(e,t,s,i,r,n={}){super(),this.channel=e.fetcher.channelId,this.logger=e.logger,this.config=r,this.isInitiator=i,this.options=n,this.intermediator=n.intermediator||null,this.signalMsgs=[],this.assignPeerId(t,s),this.platform="unknown",this.super=!1,this.mobile=!1,this.mobileWeb=!1,this.mobileNet=!1,this.connected=!1,this.msgQueue=[],this.miss=0,this.notifySet=new Set,this.bufArr=[],this.packetSize=o,this.sendReqQueue=[],this.downloading=!1,this.uploading=!1,this.choked=!1,this.streamListeners=[],this.pieceMsg={},this.datasToSend=[],this.bytesUploaded=0,this.dataWriting=!1,this.timeSendRequest=0,this.timeReceivePiece=0,this.timeSendPiece=0,this.weight=0,this.peersConnected=1,this.uploadSpeed=0,this.currentLevel=0,this.currentPos=0,this.useBackupSignal=!1,this.gotPeersTS=0,this.gotAnswer=!1,this.gotOffer=!1,this.gotSignal=!1,this.sentSignal=!1,this.incomingSignal=[],this.webRTCConfig={};const{stuns:a}=this.options;if(a&&a.length>0){const e=[];a.forEach((t=>{this.logger.info(`use stun ${t}`),e.push({urls:t})})),this.webRTCConfig.iceServers=e}this.config.webRTCConfig&&(this.webRTCConfig={...this.config.webRTCConfig,...this.webRTCConfig}),this.playlistMap=new Map,this._initPeerChannel(),this.notFatalClosed=!1,this.startSN=Number.MAX_SAFE_INTEGER,this.endSN=-1,this._loadedBytes=0}assignPeerId(e,t){this.remotePeerId=t,this.channelId=this.isInitiator?`${e}-${t}`:`${t}-${e}`,t&&this._startTimer(),setTimeout((()=>{this.signalMsgs.length>0&&this.emit(N.DC_SIGNAL_BATCH,this.signalMsgs)}),0)}_startTimer(){this.timeJoin=l(),this.dataExchangeTs=this.timeJoin,this.gotStatsTs=this.timeJoin,this.connTimeout=setTimeout((()=>{const{gotSignal:e,sentSignal:t,signalName:s}=this;this.logger.warn(`dc ${this.channelId} connection timeout, gotSignal ${e} sentSignal ${t} signalName ${s}`),this.emit(N.DC_TIMEOUT,{gotSignal:e,sentSignal:t,data:this.signalMsgs})}),this.isInitiator?15e3:12e3)}get isAvailable(){return this.downloadNum<2&&!this.choked}get isAvailableUrgently(){return!this.downloading&&!this.choked}cancelDownload(e,t,s){return!!this.downloading&&(!(this.bufSN>e)&&(!(this.streamListeners.length>0)&&(this.logger.info(`cancel download ${s} to ${this.remotePeerId} remain packets ${this.remainAttachments}`),this.timeReceivePiece=0,this.sendJson({event:N.DC_PIECE_CANCEL,sn:e,level:t,seg_id:s}))))}addStreamListener(e,t,s){this.streamListeners.push({handler:s,peerId:t})}removeStreamListener(e){this.streamListeners=this.streamListeners.filter((t=>t.peerId!==e||(t.handler(void 0,void 0,!0,"aborted by cancel"),!1)))}_initPeerChannel(){const e=new M({initiator:this.isInitiator,trickle:this.options.trickle||!1,config:this.webRTCConfig});this._datachannel=e,e.on("error",(e=>{let t=!0;(this.connected||this.notFatalClosed)&&(t=!1);let s=e.message;e.debug&&(s=`${s} raw: ${JSON.stringify(this.incomingSignal)}`),this.emit(N.DC_ERROR,t,s)})),e.on("signal",(e=>{e.candidate&&!e.candidate.candidate||(!this.useBackupSignal&&this.signalMsgs.length<10&&this.signalMsgs.push(e),this.sentSignal=!0,this.emit(N.DC_SIGNAL,e))}));e.on("connect",(()=>{for(this.logger.info(`datachannel CONNECTED from ${this.intermediator?"peer":"server "+this.signalName} to ${this.remotePeerId}`),this.connected=!0,this.incomingSignal=[],clearTimeout(this.connTimeout),this.signalMsgs=[],this.emit(N.DC_OPEN);this.msgQueue.length>0;){let e=this.msgQueue.shift();this.emit(e.event,e)}})),e.on("data",(e=>{const{logger:t}=this;if("string"==typeof e){let s=JSON.parse(e);if(!s)return void t.error("dc received string is null");if(!this.connected)return void this.msgQueue.push(s);let i,r=s.event;switch(i=r!==N.DC_PLAYLIST&&r!==N.DC_PEER_SIGNAL?`string: ${e}`:`event: ${r}`,t.debug(`datachannel receive ${i} from ${this.remotePeerId}`),r){case N.DC_HAVE:if(this.emit(s.event,s),!s.sn)return;this.config.live||(s.sn<this.startSN&&(this.startSN=s.sn),s.sn>this.endSN&&(this.endSN=s.sn));break;case N.DC_PIECE:this.downloading=!0,this.dataExchangeTs=l(),this.timeReceivePiece=performance.now(),this.pieceMsg=s,this._prepareForBinary(s.attachments,s.seg_id,s.sn,s.size),this.emit(s.event,s);break;case N.DC_PIECE_CANCEL:t.info(`send queue ${this.datasToSend.length}, uploading ${this.uploading}`),this.emit(s.event,s),this.sendMsgPieceAbort("transfer canceled",s.seg_id);break;case N.DC_PIECE_NOT_FOUND:this._sendNextReq()||(this.downloading=!1),this.emit(s.event,s);break;case N.DC_REQUEST:this._handleRequestMsg(s);break;case N.DC_PIECE_ACK:this._handlePieceAck(s.seg_id,s.size,s.miss);break;case N.DC_STATS:this._handleStats(s);break;case N.DC_PLAYLIST:this.config.sharePlaylist&&this._handlePlaylist(s);break;case N.DC_METADATA:this._handleMetadata(s);break;case N.DC_PIECE_ABORT:this.downloading&&(this._notifyDownloadListenersAbort("aborted by upstream peer"),this.emit(N.DC_PIECE_ABORT,s)),this.downloading=!1,this.segId=void 0;break;case N.DC_CHOKE:t.info(`choke peer ${this.remotePeerId}`),this.choked=!0;break;case N.DC_UNCHOKE:t.info(`unchoke peer ${this.remotePeerId}`),this.choked=!1;break;case N.DC_CLOSE:this.emit(s.event,s.fatal||!1);break;default:this.emit(s.event,s)}}else{if(!e)return void t.error("datachannel on data is undefined!");if(!this.downloading){const s=`peer ${this.remotePeerId} not downloading, data size ${e.byteLength} pieceMsg ${JSON.stringify(this.pieceMsg)}`;return t.warn(s),void this.emit(N.DC_ERROR,!1,s)}this._handleBinaryMsg(e)}})),e.once("close",(()=>{this.emit(N.DC_CLOSE,!1)})),e.on("iceStateChange",((e,t)=>{this.connected&&"disconnected"===e&&(this.logger.warn(`${this.remotePeerId} disconnected`),this.emit(N.DC_DISCONNECT))}))}sendJson(e){if(!this.remotePeerId)return!1;e.event!==N.DC_PLAYLIST&&e.event!==N.DC_PEER_SIGNAL?this.logger.debug(`dc bufferSize ${this._datachannel.bufferSize} send ${JSON.stringify(e)} to ${this.remotePeerId}`):this.logger.debug(`dc send event ${e.event} to ${this.remotePeerId}`);const t=JSON.stringify(e);return t.length>o?(this.logger.error("string to send is too large"),!1):this.send(t,!1)}send(e,t=!0){return t?(this.datasToSend.push(e),this.dataWriting||this._sendDataSync(),!0):this.sendImmediately(e)}_sendDataSync(){if(!this._datachannel.connected||0===this.datasToSend.length)return void(this.dataWriting=!1);this.dataWriting=!0;const e=this.datasToSend.shift();e?("string"!=typeof e&&(this.bytesUploaded+=e.byteLength),this._datachannel.write(e,(e=>{if(e)return this.dataWriting=!1,void this.emit(N.DC_ERROR,!1,e.message);this._sendDataSync()}))):this.logger.error("sendDataSync data is undefined!")}sendImmediately(e){if(this._datachannel.connected)try{return this._datachannel.send(e),!0}catch(e){const t=`datachannel ${this.channelId} send data failed, close it`;this.emit(N.DC_ERROR,!1,t)}return!1}sendMsgHave(e,t,s={}){const i=s.reverse||void 0;delete s.reverse,this.sendJson({event:i?N.DC_HAVE_REVERSE:N.DC_HAVE,sn:e,seg_id:t,...s})}sendPieceNotFound(e,t,s={}){this.uploading=!1,this.sendJson({event:N.DC_PIECE_NOT_FOUND,seg_id:t||void 0,sn:e,...s})}sendPeers(e){this.sendJson({event:N.DC_PEERS,peers:e})}sendPeersRequest(){this.sendJson({event:N.DC_GET_PEERS})}sendMsgStats(e,t={}){const s={event:N.DC_STATS,total_conns:e,...t};this.sendJson(s)}sendMsgPlaylist(e,t,s){const i=this.playlistMap.get(e);if(i&&i.seq>=s)return;const r={event:N.DC_PLAYLIST,url:e,data:t,seq:s};this.playlistMap.set(e,{data:t,seq:s}),this.sendJson(r)}sendMsgSignal(e,t,s){return this.sendJson({event:N.DC_PEER_SIGNAL,action:"signal",to_peer_id:e,from_peer_id:t,data:s})}sendMsgSignalReject(e,t,s,i=!1){return this.sendJson({event:N.DC_PEER_SIGNAL,action:"reject",to_peer_id:e,from_peer_id:t,reason:s,fatal:i})}sendMetaData(e,t,s,i,r=!1){this.isInitiator&&(this.timeSendRequest=performance.now()),this.sendJson({event:N.DC_METADATA,field:e,platform:N.DC_PLAT_WEB,mobile:!!$().isMobile(),mobile_net:r,channel:this.channel,version:"0.3.1",sequential:t,peers:s,region:i})}sendPartialBuffer(e,t,s={}){if(!this.sendMsgPiece(e,s))return!1;for(let e=0;e<t.length;e++)this.send(t[e]);return!0}sendMsgPiece(e,t={}){if(!this.uploading)return this.logger.info("not uploading, cancel send buffer"),!1;this.datasToSend=[],this.bytesUploaded=0,e.ext||(e.ext={}),e.ext.from&&t.from&&t.from.length<2500&&(t.from=`${e.ext.from}-${t.from}`),t.incompletes&&e.ext.incompletes&&(t.incompletes+=e.ext.incompletes),t=Object.assign({},e.ext,t);const s={...e,ext:t};return this.sendJson(s)}sendBuffer(e,t,s,i={}){const r=i.reverse||void 0;if(delete i.reverse,!s)return void this.logger.error("sendBuffer payload is undefined!");let n=s.byteLength,o=0,a=0;n%this.packetSize==0?a=n/this.packetSize:(a=Math.floor(n/this.packetSize)+1,o=n%this.packetSize);let h={event:N.DC_PIECE,attachments:a,seg_id:t,sn:e,level:i.level,size:n,reverse:r};if(delete i.level,!this.sendMsgPiece(h,i))return;const l=function(e,t,s,i){let r=[];if(i){let n;for(let i=0;i<s-1;i++)n=e.slice(i*t,(i+1)*t),r.push(n);n=e.slice(e.byteLength-i,e.byteLength),r.push(n)}else{let i;for(let n=0;n<s;n++)i=e.slice(n*t,(n+1)*t),r.push(i)}return r}(s,this.packetSize,a,o);this._sendBufferArray(l,r),this.uploading=!1,this.timeSendPiece=performance.now()}get downloadNum(){return this.downloading?this.sendReqQueue.length+1:0}requestDataById(e,t,s=!1,i={}){const r={event:N.DC_REQUEST,seg_id:e,sn:t,...i,urgent:s};this.downloading?(this.logger.info(`${this.remotePeerId} add req ${e} in queue`),s?this.sendReqQueue.unshift(r):this.sendReqQueue.push(r)):this._realRequestData(r)}requestDataBySN(e,t=!1,s={}){const i={event:N.DC_REQUEST,sn:e,...s,urgent:t};this.downloading?(this.logger.info(`add req ${e} in queue`),t?this.sendReqQueue.unshift(i):this.sendReqQueue.push(i)):this._realRequestData(i)}_sendBufferArray(e,t=!1){const s=t?e.reverse():e;for(let e=0;e<s.length;e++)this.send(s[e])}_realRequestData(e){this.sendJson(e),this.timeSendRequest=performance.now(),this.downloading=!0,this._loadedBytes=0}shouldWaitForRemain(e){return 0!==this.bufArrSize&&(0!==this.timeReceivePiece&&this.currentLoadSpeed()>=this.minRequiredSpeed(e))}close(e){e||(this.notFatalClosed=!0),this.emit(N.DC_CLOSE,e)}receiveSignal(e,t){if("answer"===e.type){if(this.gotAnswer||this.gotOffer)return;this.gotAnswer=!0}else if("offer"===e.type){if(this.gotOffer||this.gotAnswer)return;this.gotOffer=!0}this.gotSignal=!0,t&&this.incomingSignal.push(t),e&&this._datachannel.signal(e)}_notifyDownloadListenersAbort(e){for(let t of this.streamListeners){const{handler:s}=t;s(void 0,void 0,!0,e)}this.streamListeners=[]}destroy(e=!0){this.logger.info(`destroy datachannel ${this.channelId}`),clearTimeout(this.chokeTimer),clearTimeout(this.connTimeout),this._notifyDownloadListenersAbort("upstream peer is closed");let t={event:N.DC_CLOSE,fatal:e};this.sendJson(t),this._datachannel.removeAllListeners(),this.removeAllListeners(),this._datachannel.destroy()}_handleBinaryMsg(e){const{attachments:t,reverse:s}=this.pieceMsg;this.listenerCount(N.DC_RESPONSE)>0&&this.bufArr.push(e),this._loadedBytes+=e.byteLength,this.remainAttachments--;let i=s?this.remainAttachments+1:t-this.remainAttachments;const r=0===this.remainAttachments;if(this.emit(N.DC_PIECE_DATA,this.bufSN,this.segId,e,i,r,this.pieceMsg),this.streamListeners.length>0)for(let t of this.streamListeners){const{handler:s}=t;s(this.bufSN,this.segId,!1,e,r)}if(r){if(this.streamListeners=[],this.timeSendRequest>0)if(this.super)this.weight=1;else{const e=this.expectedSize/(performance.now()-this.timeSendRequest);this.weight=this.weight>0?.6*this.weight+.4*e:e}this.sendJson({event:N.DC_PIECE_ACK,seg_id:this.segId,size:this.expectedSize,miss:this.miss||void 0}),this.timeSendRequest=0,this.timeReceivePiece=0,this._sendNextReq()||(this.downloading=!1),this._handleBinaryData(s)}}_sendNextReq(){if(this.sendReqQueue.length>0){const e=this.sendReqQueue.shift();return this.logger.info(`get msg from sendReqQueue ${JSON.stringify(e)}`),this._realRequestData(e),!0}return!1}_handlePlaylist(e){const{url:t,data:s,seq:i}=e;this.playlistMap.set(t,{data:s,seq:i})}getLatestPlaylist(e,t){if(!this.playlistMap.has(e))return null;const s=this.playlistMap.get(e);return s.seq<=t||s.seq>t+2?null:s}_handleMetadata(e){const{logger:t}=this;if(this.isInitiator){const e=performance.now()-this.timeSendRequest;e>0&&(this.weight=1e5/e,t.info(`handle Metadata from ${this.remotePeerId} initial weight ${this.weight}`)),this.timeSendRequest=0}const s=e.channel;if(this.channel!==s){const e=`peer channel ${s} not matched!`;return t.error(e),void this.emit(N.DC_ERROR,!0,e)}if(e.super){t.info(`got super peer ${this.remotePeerId}`),this.super=!0;const{token:s}=this.config;if(s&&e.token!==s)return void this.emit(N.DC_ERROR,!0,`super peer token ${e.token} not matched!`)}e.region&&(this.region=e.region);switch(e.platform){case N.DC_PLAT_ANDROID:this.platform=N.DC_PLAT_ANDROID;break;case N.DC_PLAT_IOS:this.platform=N.DC_PLAT_IOS;break;case N.DC_PLAT_WEB:this.platform=N.DC_PLAT_WEB}if(this.mobile=e.mobile||!1,this.mobileNet=e.mobile_net||!1,this.mobileWeb=this.mobile&&this.platform===N.DC_PLAT_WEB||!1,this.sequential=e.sequential,t.info(`${this.remotePeerId} platform ${this.platform} sequential ${this.sequential}`),e.peers&&(this.peersConnected+=e.peers,t.info(`${this.remotePeerId} now has ${this.peersConnected} peers`)),this.emit(N.DC_METADATA,e),e.field&&!this.config.live&&e.sequential){const{field:t}=e;if(Array.isArray(t))this._handleField(t);else for(let e in t)this._handleField(t[e])}}_handleField(e){e.forEach((e=>{e>=0&&(e<this.startSN&&(this.startSN=e),e>this.endSN&&(this.endSN=e))}))}_handleStats(e){this.gotStatsTs=l();const t=e.total_conns;t>0&&this.peersConnected!==t&&(this.peersConnected=t,this.logger.info(`${this.remotePeerId} now has ${this.peersConnected} peers`)),e.level&&(this.currentLevel=e.level),e.pos&&(this.currentPo