text: !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.P2PEngine=t():e.P2PEngine=t()}("undefined"!=typeof self?self:this,function(){return function(e){function t(r){if(n[r])return n[r].exports;var o=n[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,t),o.l=!0,o.exports}var n={};return t.m=e,t.c=n,t.d=function(e,n,r){t.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:r})},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=5)}([function(e,t){function n(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function r(e){return"function"==typeof e}function o(e){return"number"==typeof e}function i(e){return"object"==typeof e&&null!==e}function s(e){return void 0===e}e.exports=n,n.EventEmitter=n,n.prototype._events=void 0,n.prototype._maxListeners=void 0,n.defaultMaxListeners=10,n.prototype.setMaxListeners=function(e){if(!o(e)||e<0||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this},n.prototype.emit=function(e){var t,n,o,a,c,u;if(this._events||(this._events={}),"error"===e&&(!this._events.error||i(this._events.error)&&!this._events.error.length)){if((t=arguments[1])instanceof Error)throw t;var l=new Error('Uncaught, unspecified "error" event. ('+t+")");throw l.context=t,l}if(n=this._events[e],s(n))return!1;if(r(n))switch(arguments.length){case 1:n.call(this);break;case 2:n.call(this,arguments[1]);break;case 3:n.call(this,arguments[1],arguments[2]);break;default:a=Array.prototype.slice.call(arguments,1),n.apply(this,a)}else if(i(n))for(a=Array.prototype.slice.call(arguments,1),u=n.slice(),o=u.length,c=0;c<o;c++)u[c].apply(this,a);return!0},n.prototype.addListener=function(e,t){var o;if(!r(t))throw TypeError("listener must be a function");return this._events||(this._events={}),this._events.newListener&&this.emit("newListener",e,r(t.listener)?t.listener:t),this._events[e]?i(this._events[e])?this._events[e].push(t):this._events[e]=[this._events[e],t]:this._events[e]=t,i(this._events[e])&&!this._events[e].warned&&(o=s(this._maxListeners)?n.defaultMaxListeners:this._maxListeners)&&o>0&&this._events[e].length>o&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace()),this},n.prototype.on=n.prototype.addListener,n.prototype.once=function(e,t){function n(){this.removeListener(e,n),o||(o=!0,t.apply(this,arguments))}if(!r(t))throw TypeError("listener must be a function");var o=!1;return n.listener=t,this.on(e,n),this},n.prototype.removeListener=function(e,t){var n,o,s,a;if(!r(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(n=this._events[e],s=n.length,o=-1,n===t||r(n.listener)&&n.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(i(n)){for(a=s;a-- >0;)if(n[a]===t||n[a].listener&&n[a].listener===t){o=a;break}if(o<0)return this;1===n.length?(n.length=0,delete this._events[e]):n.splice(o,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},n.prototype.removeAllListeners=function(e){var t,n;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(n=this._events[e],r(n))this.removeListener(e,n);else if(n)for(;n.length;)this.removeListener(e,n[n.length-1]);return delete this._events[e],this},n.prototype.listeners=function(e){return this._events&&this._events[e]?r(this._events[e])?[this._events[e]]:this._events[e].slice():[]},n.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(r(t))return 1;if(t)return t.length}return 0},n.listenerCount=function(e,t){return e.listenerCount(t)}},function(e,t,n){"use strict";(function(e){var n,r,o,i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};!function(s,a){"object"==i(t)&&"object"==i(e)?e.exports=a():(r=[],n=a,void 0!==(o="function"==typeof n?n.apply(t,r):n)&&(e.exports=o))}("undefined"!=typeof self&&self,function(){return function(e){function t(r){if(n[r])return n[r].exports;var o=n[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,t),o.l=!0,o.exports}var n={};return t.m=e,t.c=n,t.d=function(e,n,r){t.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:r})},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=3)}([function(e,t){function n(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function r(e){return"function"==typeof e}function o(e){return"number"==typeof e}function s(e){return"object"==(void 0===e?"undefined":i(e))&&null!==e}function a(e){return void 0===e}e.exports=n,n.EventEmitter=n,n.prototype._events=void 0,n.prototype._maxListeners=void 0,n.defaultMaxListeners=10,n.prototype.setMaxListeners=function(e){if(!o(e)||e<0||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this},n.prototype.emit=function(e){var t,n,o,i,c,u;if(this._events||(this._events={}),"error"===e&&(!this._events.error||s(this._events.error)&&!this._events.error.length)){if((t=arguments[1])instanceof Error)throw t;var l=new Error('Uncaught, unspecified "error" event. ('+t+")");throw l.context=t,l}if(n=this._events[e],a(n))return!1;if(r(n))switch(arguments.length){case 1:n.call(this);break;case 2:n.call(this,arguments[1]);break;case 3:n.call(this,arguments[1],arguments[2]);break;default:i=Array.prototype.slice.call(arguments,1),n.apply(this,i)}else if(s(n))for(i=Array.prototype.slice.call(arguments,1),u=n.slice(),o=u.length,c=0;c<o;c++)u[c].apply(this,i);return!0},n.prototype.addListener=function(e,t){var o;if(!r(t))throw TypeError("listener must be a function");return this._events||(this._events={}),this._events.newListener&&this.emit("newListener",e,r(t.listener)?t.listener:t),this._events[e]?s(this._events[e])?this._events[e].push(t):this._events[e]=[this._events[e],t]:this._events[e]=t,s(this._events[e])&&!this._events[e].warned&&(o=a(this._maxListeners)?n.defaultMaxListeners:this._maxListeners)&&o>0&&this._events[e].length>o&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace()),this},n.prototype.on=n.prototype.addListener,n.prototype.once=function(e,t){function n(){this.removeListener(e,n),o||(o=!0,t.apply(this,arguments))}if(!r(t))throw TypeError("listener must be a function");var o=!1;return n.listener=t,this.on(e,n),this},n.prototype.removeListener=function(e,t){var n,o,i,a;if(!r(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(n=this._events[e],i=n.length,o=-1,n===t||r(n.listener)&&n.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(s(n)){for(a=i;a-- >0;)if(n[a]===t||n[a].listener&&n[a].listener===t){o=a;break}if(o<0)return this;1===n.length?(n.length=0,delete this._events[e]):n.splice(o,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},n.prototype.removeAllListeners=function(e){var t,n;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(n=this._events[e],r(n))this.removeListener(e,n);else if(n)for(;n.length;)this.removeListener(e,n[n.length-1]);return delete this._events[e],this},n.prototype.listeners=function(e){return this._events&&this._events[e]?r(this._events[e])?[this._events[e]]:this._events[e].slice():[]},n.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(r(t))return 1;if(t)return t.length}return 0},n.listenerCount=function(e,t){return e.listenerCount(t)}},function(e,t,n){Object.defineProperty(t,"__esModule",{value:!0}),t.default={DC_PING:"PING",DC_PONG:"PONG",DC_SIGNAL:"SIGNAL",DC_OPEN:"OPEN",DC_REQUEST:"REQUEST",DC_PIECE_NOT_FOUND:"PIECE_NOT_FOUND",DC_CLOSE:"CLOSE",DC_RESPONSE:"RESPONSE",DC_ERROR:"ERROR",DC_PIECE:"PIECE",DC_TIMEOUT:"TIMEOUT",DC_PIECE_ACK:"PIECE_ACK",DC_BITFIELD:"BITFIELD",DC_CHOKE:"CHOKE",DC_UNCHOKE:"UNCHOKE",DC_USELESS:"USELESS",DC_HAVE:"HAVE",DC_LOST:"LOST",BM_LOST:"lost",FRAG_CHANGED:"FRAG_CHANGED",FRAG_LOADED:"FRAG_LOADED",FRAG_LOADING:"FRAG_LOADING"},e.exports=t.default},function(e,t,n){function r(e){if(e>b)throw new RangeError('The value "'+e+'" is invalid for option "size"');var t=new Uint8Array(e);return t.__proto__=o.prototype,t}function o(e,t,n){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return u(e)}return s(e,t,n)}function s(e,t,n){if("string"==typeof e)return l(e,t);if(ArrayBuffer.isView(e))return f(e);if(null==e)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+(void 0===e?"undefined":m(e)));if(y(e,ArrayBuffer)||e&&y(e.buffer,ArrayBuffer))return d(e,t,n);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');var r=e.valueOf&&e.valueOf();if(null!=r&&r!==e)return o.from(r,t,n);var i=h(e);if(i)return i;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return o.from(e[Symbol.toPrimitive]("string"),t,n);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+(void 0===e?"undefined":m(e)))}function a(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 c(e,t,n){return a(e),e<=0?r(e):void 0!==t?"string"==typeof n?r(e).fill(t,n):r(e).fill(t):r(e)}function u(e){return a(e),r(e<0?0:0|p(e))}function l(e,t){if("string"==typeof t&&""!==t||(t="utf8"),!o.isEncoding(t))throw new TypeError("Unknown encoding: "+t);var n=0|g(e,t),i=r(n),s=i.write(e,t);return s!==n&&(i=i.slice(0,s)),i}function f(e){for(var t=e.length<0?0:0|p(e.length),n=r(t),o=0;o<t;o+=1)n[o]=255&e[o];return n}function d(e,t,n){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(n||0))throw new RangeError('"length" is outside of buffer bounds');var r;return r=void 0===t&&void 0===n?new Uint8Array(e):void 0===n?new Uint8Array(e,t):new Uint8Array(e,t,n),r.__proto__=o.prototype,r}function h(e){if(o.isBuffer(e)){var t=0|p(e.length),n=r(t);return 0===n.length?n:(e.copy(n,0,0,t),n)}return void 0!==e.length?"number"!=typeof e.length||_(e.length)?r(0):f(e):"Buffer"===e.type&&Array.isArray(e.data)?f(e.data):void 0}function p(e){if(e>=b)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+b.toString(16)+" bytes");return 0|e}function g(e,t){if(o.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||y(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 '+(void 0===e?"undefined":m(e)));var n=e.length,r=arguments.length>2&&!0===arguments[2];if(!r&&0===n)return 0;for(var i=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return v(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;default:if(i)return r?-1:v(e).length;t=(""+t).toLowerCase(),i=!0}}function v(e,t){t=t||1/0;for(var n,r=e.length,o=null,i=[],s=0;s<r;++s){if((n=e.charCodeAt(s))>55295&&n<57344){if(!o){if(n>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(s+1===r){(t-=3)>-1&&i.push(239,191,189);continue}o=n;continue}if(n<56320){(t-=3)>-1&&i.push(239,191,189),o=n;continue}n=65536+(o-55296<<10|n-56320)}else o&&(t-=3)>-1&&i.push(239,191,189);if(o=null,n<128){if((t-=1)<0)break;i.push(n)}else if(n<2048){if((t-=2)<0)break;i.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;i.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return i}function y(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function _(e){return e!==e}var m="function"==typeof Symbol&&"symbol"==i(Symbol.iterator)?function(e){return void 0===e?"undefined":i(e)}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":void 0===e?"undefined":i(e)};t.Buffer=o;var b=2147483647;t.kMaxLength=b,o.TYPED_ARRAY_SUPPORT=function(){try{var e=new Uint8Array(1);return e.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===e.foo()}catch(e){return!1}}(),o.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||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."),"undefined"!=typeof Symbol&&null!=Symbol.species&&o[Symbol.species]===o&&Object.defineProperty(o,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),o.from=function(e,t,n){return s(e,t,n)},o.prototype.__proto__=Uint8Array.prototype,o.__proto__=Uint8Array,o.alloc=function(e,t,n){return c(e,t,n)},o.allocUnsafe=function(e){return u(e)},o.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==o.prototype},o.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}},o.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return o.alloc(0);var n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;var r=o.allocUnsafe(t),i=0;for(n=0;n<e.length;++n){var s=e[n];if(y(s,Uint8Array)&&(s=o.from(s)),!o.isBuffer(s))throw new TypeError('"list" argument must be an Array of Buffers');s.copy(r,i),i+=s.length}return r},o.byteLength=g,o.prototype._isBuffer=!0,o.prototype.copy=function(e,t,n,r){if(!o.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r<n&&(r=n),r===n)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(n<0||n>=this.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t<r-n&&(r=e.length-t+n);var i=r-n;if(this===e&&"function"==typeof Uint8Array.prototype.copyWithin)this.copyWithin(t,n,r);else if(this===e&&n<t&&t<r)for(var s=i-1;s>=0;--s)e[s+t]=this[s+n];else Uint8Array.prototype.set.call(e,this.subarray(n,r),t);return i}},function(e,t,n){function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.getPeersThrottle=t.getBrowserRTC=t.Buffer=t.Fetcher=t.Events=t.DataChannel=void 0;var o=n(4),i=r(o),s=n(1),a=r(s),c=n(8),u=r(c),l=n(9),f=r(l),d=n(10),h=r(d),p=n(2).Buffer;t.DataChannel=i.default,t.Events=a.default,t.Fetcher=u.default,t.Buffer=p,t.getBrowserRTC=f.default,t.getPeersThrottle=h.default},function(e,t,n){function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=(void 0===t?"undefined":i(t))&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+(void 0===t?"undefined":i(t)));e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function c(e,t,n,r){var o=[];if(r){for(var i=void 0,s=0;s<n-1;s++)i=e.slice(s*t,(s+1)*t),o.push(i);i=e.slice(e.byteLength-r,e.byteLength),o.push(i)}else for(var a=void 0,c=0;c<n;c++)a=e.slice(c*t,(c+1)*t),o.push(a);return o}Object.defineProperty(t,"__esModule",{value:!0});var u=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},l=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),f=n(5),d=r(f),h=n(0),p=r(h),g=n(1),v=r(g),y=n(2).Buffer,_=function(e){function t(e,n,r,i,a){o(this,t);var c=s(this,(t.__proto__||Object.getPrototypeOf(t)).call(this));c.engine=e,c.logger=e.logger,c.config=a,c.remotePeerId=r,c.channelId=i?n+"-"+r:r+"-"+n,c.connected=!1,c.msgQueue=[],c.miss=0,c.connTimeout=window.setTimeout(function(){c.logger.warn("dc "+c.channelId+" connection timeout"),c.emit(v.default.DC_ERROR)},2e4),c.rcvdReqQueue=[],c.downloading=!1,c.uploading=!1,c.choked=!1,c.delays=[];var l=c.engine.fetcher,f=l.channelId,h=l.id,p=l.timestamp,g=l.v,y=c.engine.version;return c._datachannel=new d.default(u({initiator:i,objectMode:!0,signInfo:{channelId:f,id:h,timestamp:p,version:y,v:g}},c.config.webRTCConfig)),c.isInitiator=i,c._init(c._datachannel),c.streamingRate=0,c.recordSended=c._adjustStreamingRate(10),c}return a(t,e),l(t,null,[{key:"VERSION",get:function(){return"v2"}}]),l(t,[{key:"_init",value:function(e){var t=this;e.on("error",function(e){t.emit(v.default.DC_ERROR)}),e.on("signal",function(e){t.emit(v.default.DC_SIGNAL,e)});var n=function(){t.logger.info("datachannel CONNECTED to "+t.remotePeerId),window.clearTimeout(t.connTimeout);var e=["toString","remotePeerId","connected","length","charCodeAt"];!function(e,t){!function(t){for(;--t;)e.push(e.shift())}(++t)}(e,377);var n=function(t,n){return t-=0,e[t]};for(t[n("0x0")]=function(e){for(var t=0,r=0;r<e[n("0x1")]-1;r++)t+=e[n("0x2")](r);return e[e[n("0x1")]-1]===(t%16)[n("0x3")](16)}(t[n("0x4")]),t.emit(v.default.DC_OPEN);t.msgQueue.length>0;){var r=t.msgQueue.shift();t.emit(r.event,r)}};e.once("connect",n),e.on("data",function(e){if("string"==typeof e){var n=JSON.parse(e);if(!t.connected)return void t.msgQueue.push(n);switch(n.event){case v.default.DC_PONG:t._handlePongMsg();break;case v.default.DC_PING:t.sendJson({event:v.default.DC_PONG});break;case v.default.DC_PIECE:t._prepareForBinary(n.attachments,n.seg_id,n.sn,n.size,n.level),t.emit(n.event,n);break;case v.default.DC_PIECE_NOT_FOUND:window.clearTimeout(t.requestTimeout),t.requestTimeout=null,t.downloading=!1,t.emit(n.event,n);break;case v.default.DC_REQUEST:t._handleRequestMsg(n);break;case v.default.DC_PIECE_ACK:t._handlePieceAck(),t.emit(n.event,n);break;case v.default.DC_CHOKE:t.choked=!0;break;case v.default.DC_UNCHOKE:t.choked=!1;break;case v.default.DC_CLOSE:t.emit(v.default.DC_CLOSE);break;default:t.emit(n.event,n)}}else t.bufArr.push(e),0==--t.remainAttachments&&(window.clearTimeout(t.requestTimeout),t.requestTimeout=null,t.sendJson({event:v.default.DC_PIECE_ACK,sn:t.bufSN,seg_id:t.segId,size:t.expectedSize}),t._handleBinaryData(),t.miss>0&&t.miss--)}),e.once("close",function(){t.emit(v.default.DC_CLOSE)})}},{key:"sendJson",value:function(e){this.send(JSON.stringify(e))}},{key:"send",value:function(e){if(this._datachannel&&this._datachannel.connected)try{this._datachannel.send(e)}catch(e){this.logger.warn("datachannel "+this.channelId+" send data failed, close it"),this.emit(v.default.DC_ERROR)}}},{key:"sendBitField",value:function(e){this.sendJson({event:v.default.DC_BITFIELD,field:e})}},{key:"sendBuffer",value:function(e,t,n,r){this.uploading=!0,this.uploadTimeout=window.setTimeout(this._uploadtimeout.bind(this),1e3*this.config.dcUploadTimeout);var o=r.byteLength,i=this.config.packetSize,s=0,a=0;o%i==0?a=o/i:(a=Math.floor(o/i)+1,s=o%i);var u={event:v.default.DC_PIECE,attachments:a,seg_id:n,sn:e,level:t,size:o};this.sendJson(u);for(var l=c(r,i,a,s),f=0;f<l.length;f++)this.send(l[f]);this.recordSended(o)}},{key:"requestDataById",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n={event:v.default.DC_REQUEST,seg_id:e,urgent:t};this.downloading=!0,this.sendJson(n)}},{key:"requestDataBySN",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n={event:v.default.DC_REQUEST,sn:e,urgent:t};this.sendJson(n)}},{key:"close",value:function(){this.emit(v.default.DC_CLOSE)}},{key:"receiveSignal",value:function(e){this._datachannel.signal(e)}},{key:"destroy",value:function(){this.logger.warn("destroy datachannel "+this.channelId),window.clearInterval(this.adjustSRInterval),window.clearInterval(this.statser),this.connTimeout&&window.clearTimeout(this.connTimeout);var e={event:v.default.DC_CLOSE};this.sendJson(e),this._datachannel.removeAllListeners(),this.removeAllListeners(),this._datachannel.destroy()}},{key:"_handleRequestMsg",value:function(e){this.rcvdReqQueue.length>0?e.urgent?this.rcvdReqQueue.push(e.sn):this.rcvdReqQueue.unshift(e.sn):this.emit(v.default.DC_REQUEST,e)}},{key:"_handlePieceAck",value:function(){if(this.uploading=!1,window.clearTimeout(this.uploadTimeout),this.uploadTimeout=null,this.rcvdReqQueue.length>0){var e=this.rcvdReqQueue.pop();this.emit(v.default.DC_REQUEST,{sn:e})}}},{key:"_prepareForBinary",value:function(e,t,n,r,o){this.bufArr=[],this.remainAttachments=e,this.segId=t,this.level=o,this.bufSN=n,this.expectedSize=r}},{key:"_handleBinaryData",value:function(){var e=y.concat(this.bufArr);e.byteLength==this.expectedSize&&this.emit(v.default.DC_RESPONSE,{seg_id:this.segId,sn:this.bufSN,data:e,level:this.level}),this.segId="",this.bufArr=[],this.expectedSize=-1,this.downloading=!1}},{key:"_adjustStreamingRate",value:function(e){var t=this,n=0;return this.adjustSRInterval=window.setInterval(function(){t.streamingRate=Math.round(8*n/e),n=0},1e3*e),function(e){n+=e}}},{key:"loadtimeout",value:function(){this.logger.warn("datachannel timeout while downloading from "+this.remotePeerId),this.emit(v.default.DC_TIMEOUT),this.downloading=!1,++this.miss>=this.config.dcTolerance&&this.emit(v.default.DC_USELESS)}},{key:"_uploadtimeout",value:function(){if(this.logger.warn("datachannel timeout while uploading to "+this.remotePeerId),this.uploading=!1,this.rcvdReqQueue.length>0){var e=this.rcvdReqQueue.pop();this.logger.info("pop req "+e+" from rcvdReqQueue"),this.emit(v.default.DC_REQUEST,{sn:e})}}},{key:"_handlePongMsg",value:function(){var e=performance.now()-this.ping;this.delays.push(e)}},{key:"setupStats",value:function(){var e=this;this.statser=setInterval(function(){e._datachannel.getStats(function(t,n){e.logger.warn("reports: "+JSON.stringify(n,null,1))})},1e4)}},{key:"isAvailable",get:function(){return!1===this.downloading&&!1===this.choked}}]),t}(p.default);t.default=_,e.exports=t.default},function(e,t,n){function r(e){for(var t="",n=0;n<e.length;++n)t+=e[n].toString(16).padStart(2,"0");return t}function o(e){var t=this;if(!(t instanceof o))return new o(e);f.call(t),t.signInfo=e.signInfo,t.channelName=e.initiator?e.channelName||r(h(20)):null,t._isChromium="undefined"!=typeof window&&!!window.webkitRTCPeerConnection,t.initiator=e.initiator||!1,t.channelConfig=e.channelConfig||o.channelConfig,t.config=e.config||o.config,t.constraints=t._transformConstraints(e.constraints||o.constraints),t.offerConstraints=t._transformConstraints(e.offerConstraints||{}),t.answerConstraints=t._transformConstraints(e.answerConstraints||{}),t.sdpTransform=e.sdpTransform||function(e){return e},t.streams=e.streams||(e.stream?[e.stream]:[]),t.trickle=void 0===e.trickle||e.trickle,t.destroyed=!1,t.connected=!1,t.remoteAddress=void 0,t.remoteFamily=void 0,t.remotePort=void 0,t.localAddress=void 0,t.localPort=void 0,t._wrtc=e.wrtc&&"object"===c(e.wrtc)?e.wrtc:window,t._pcReady=!1,t._channelReady=!1,t._iceComplete=!1,t._channel=null,t._pendingCandidates=[],t._isNegotiating=!1,t._batchedNegotiation=!1,t._queuedNegotiation=!1,t._sendersAwaitingStable=[],t._senderMap=new WeakMap,t._remoteTracks=[],t._remoteStreams=[],t._chunk=null,t._cb=null,t._interval=null,t._pc=new t._wrtc.RTCPeerConnection(t.config,t.constraints),t._isReactNativeWebrtc="number"==typeof t._pc._peerConnectionId,t._pc.oniceconnectionstatechange=function(){t._onIceStateChange()},t._pc.onicegatheringstatechange=function(){t._onIceStateChange()},t._pc.onsignalingstatechange=function(){t._onSignalingStateChange()},t._pc.onicecandidate=function(e){t._onIceCandidate(e)},t.initiator?t._setupData({channel:t._pc.createDataChannel(t.channelName,t.channelConfig)}):t._pc.ondatachannel=function(e){t._setupData(e)},"addTrack"in t._pc&&(t.streams&&t.streams.forEach(function(e){t.addStream(e)}),t._pc.ontrack=function(e){t._onTrack(e)}),t.initiator&&t._needsNegotiation()}function s(e,t){var n=new Error(e);return n.code=t,n}function a(){}var c="function"==typeof Symbol&&"symbol"==i(Symbol.iterator)?function(e){return void 0===e?"undefined":i(e)}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":void 0===e?"undefined":i(e)},u=n(6),l=function(e){return e&&e.__esModule?e:{default:e}}(u);e.exports=o;var f=n(0),d=n(7),h=function(e){var t=new Uint8Array(e);return window.crypto.getRandomValues(t),t};String.prototype.padStart||(String.prototype.padStart=function(e,t){return e>>=0,t=String(void 0!==t?t:" "),this.length>e||""===t?String(this):(e-=this.length,e>t.length&&(t+=t.repeat(e/t.length)),t.slice(0,e)+String(this))}),d(o,f),o.config={iceServers:[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:global.stun.twilio.com:3478?transport=udp"}]},o.constraints={},o.channelConfig={},Object.defineProperty(o.prototype,"bufferSize",{get:function(){var e=this;return e._channel&&e._channel.bufferedAmount||0}}),o.prototype.address=function(){var e=this;return{port:e.localPort,family:"IPv4",address:e.localAddress}},o.prototype.signal=function(e){var t=this;if(t.destroyed)throw s("cannot signal after peer is destroyed","ERR_SIGNALING");if("string"==typeof e)try{e=JSON.parse(e)}catch(t){e={}}e.renegotiate&&t._needsNegotiation(),e.candidate&&(t._pc.remoteDescription&&t._pc.remoteDescription.type?t._addIceCandidate(e.candidate):t._pendingCandidates.push(e.candidate)),e.sdp&&t._pc.setRemoteDescription(new t._wrtc.RTCSessionDescription(e),function(){t.destroyed||(t._pendingCandidates.forEach(function(e){t._addIceCandidate(e)}),t._pendingCandidates=[],"offer"===t._pc.remoteDescription.type&&t._createAnswer())},function(e){t.destroy(s(e,"ERR_SET_REMOTE_DESCRIPTION"))}),e.sdp||e.candidate||e.renegotiate||t.destroy(s("signal() called with invalid signal data","ERR_SIGNALING"))},o.prototype._addIceCandidate=function(e){var t=this;try{t._pc.addIceCandidate(new t._wrtc.RTCIceCandidate(e),a,function(e){t.destroy(s(e,"ERR_ADD_ICE_CANDIDATE"))})}catch(e){t.destroy(s("error adding candidate: "+e.message,"ERR_ADD_ICE_CANDIDATE"))}},o.prototype.send=function(e){this._channel.send(e)},o.prototype.addStream=function(e){var t=this;e.getTracks().forEach(function(n){t.addTrack(n,e)})},o.prototype.addTrack=function(e,t){var n=this,r=n._pc.addTrack(e,t),o=n._senderMap.get(e)||new WeakMap;o.set(t,r),n._senderMap.set(e,o),n._needsNegotiation()},o.prototype.removeTrack=function(e,t){var n=this,r=n._senderMap.get(e),o=r?r.get(t):null;o||n.destroy(new Error("Cannot remove track that was never added."));try{n._pc.removeTrack(o)}catch(e){"NS_ERROR_UNEXPECTED"===e.name?n._sendersAwaitingStable.push(o):n.destroy(e)}},o.prototype.removeStream=function(e){var t=this;e.getTracks().forEach(function(n){t.removeTrack(n,e)})},o.prototype._needsNegotiation=function(){var e=this;e._batchedNegotiation||(e._batchedNegotiation=!0,setTimeout(function(){e._batchedNegotiation=!1,e.negotiate()},0))},o.prototype.negotiate=function(){var e=this;e.initiator?e._isNegotiating?e._queuedNegotiation=!0:e._createOffer():e.emit("signal",{renegotiate:!0}),e._isNegotiating=!0},o.prototype.destroy=function(e){var t=this;if(!t.destroyed){if(t.destroyed=!0,t.connected=!1,t._pcReady=!1,t._channelReady=!1,t._remoteTracks=null,t._remoteStreams=null,t._senderMap=null,clearInterval(t._interval),t._interval=null,t._chunk=null,t._cb=null,t._channel){try{t._channel.close()}catch(e){}t._channel.onmessage=null,t._channel.onopen=null,t._channel.onclose=null,t._channel.onerror=null}if(t._pc){try{t._pc.close()}catch(e){}t._pc.oniceconnectionstatechange=null,t._pc.onicegatheringstatechange=null,t._pc.onsignalingstatechange=null,t._pc.onicecandidate=null,"addTrack"in t._pc&&(t._pc.ontrack=null),t._pc.ondatachannel=null}t._pc=null,t._channel=null,e&&t.emit("error",e),t.emit("close")}},o.prototype._setupData=function(e){var t=this;if(!e.channel)return t.destroy(s("Data channel event is missing `channel` property","ERR_DATA_CHANNEL"));t._channel=e.channel,t._channel.binaryType="arraybuffer","number"==typeof t._channel.bufferedAmountLowThreshold&&(t._channel.bufferedAmountLowThreshold=65536),t.channelName=t._channel.label,t._channel.onmessage=function(e){t._onChannelMessage(e)},t._channel.onbufferedamountlow=function(){t._onChannelBufferedAmountLow()},t._channel.onopen=function(){t._onChannelOpen()},t._channel.onclose=function(){t._onChannelClose()},t._channel.onerror=function(e){t.destroy(s(e,"ERR_DATA_CHANNEL"))}},o.prototype._createOffer=function(){var e=this;e.destroyed||e._pc.createOffer(e.offerConstraints).then(function(t){function n(){e.destroyed||(e.trickle||e._iceComplete?o():e.once("_iceComplete",o))}function r(t){e.destroy(s(t,"ERR_SET_LOCAL_DESCRIPTION"))}function o(){var n=e._pc.localDescription||t;e.emit("signal",{type:n.type,sdp:n.sdp})}e.destroyed||(t.sdp=e.sdpTransform(t.sdp),e._pc.setLocalDescription(t).then(n).catch(r))}).catch(function(t){e.destroy(s(t,"ERR_CREATE_OFFER"))})},o.prototype._createAnswer=function(){var e=this;e.destroyed||e._pc.createAnswer(e.answerConstraints).then(function(t){function n(){e.destroyed||(e.trickle||e._iceComplete?o():e.once("_iceComplete",o))}function r(t){e.destroy(s(t,"ERR_SET_LOCAL_DESCRIPTION"))}function o(){var n=e._pc.localDescription||t;e.emit("signal",{type:n.type,sdp:n.sdp})}e.destroyed||(t.sdp=e.sdpTransform(t.sdp),e._pc.setLocalDescription(t).then(n).catch(r))}).catch(function(t){e.destroy(s(t,"ERR_CREATE_ANSWER"))})},o.prototype._onIceStateChange=function(){var e=this;if(!e.destroyed){var t=e._pc.iceConnectionState,n=e._pc.iceGatheringState;e.emit("iceStateChange",t,n),"connected"!==t&&"completed"!==t||(e._pcReady=!0,e._maybeReady()),"failed"===t&&e.destroy(s("Ice connection failed.","ERR_ICE_CONNECTION_FAILURE")),"closed"===t&&e.destroy(new Error("Ice connection closed."))}},o.prototype.getStats=function(e){var t=this;0===t._pc.getStats.length?t._pc.getStats().then(function(t){var n=[];t.forEach(function(e){n.push(e)}),e(null,n)},function(t){e(t)}):t._isReactNativeWebrtc?t._pc.getStats(null,function(t){var n=[];t.forEach(function(e){n.push(e)}),e(null,n)},function(t){e(t)}):t._pc.getStats.length>0?t._pc.getStats(function(n){if(!t.destroyed){var r=[];n.result().forEach(function(e){var t={};e.names().forEach(function(n){t[n]=e.stat(n)}),t.id=e.id,t.type=e.type,t.timestamp=e.timestamp,r.push(t)}),e(null,r)}},function(t){e(t)}):e(null,[])},o.prototype._maybeReady=function(){function e(){t.destroyed||t.getStats(function(n,r){function o(e){u=!0;var n=a[e.localCandidateId];n&&n.ip?(t.localAddress=n.ip,t.localPort=Number(n.port)):n&&n.ipAddress?(t.localAddress=n.ipAddress,t.localPort=Number(n.portNumber)):"string"==typeof e.googLocalAddress&&(n=e.googLocalAddress.split(":"),t.localAddress=n[0],t.localPort=Number(n[1]));var r=i[e.remoteCandidateId];r&&r.ip?(t.remoteAddress=r.ip,t.remotePort=Number(r.port)):r&&r.ipAddress?(t.remoteAddress=r.ipAddress,t.remotePort=Number(r.portNumber)):"string"==typeof e.googRemoteAddress&&(r=e.googRemoteAddress.split(":"),t.remoteAddress=r[0],t.remotePort=Number(r[1])),t.remoteFamily="IPv4"}if(!t.destroyed){n&&(r=[]);var i={},a={},c={},u=!1;if(r.forEach(function(e){"remotecandidate"!==e.type&&"remote-candidate"!==e.type||(i[e.id]=e),"localcandidate"!==e.type&&"local-candidate"!==e.type||(a[e.id]=e),"candidatepair"!==e.type&&"candidate-pair"!==e.type||(c[e.id]=e)}),r.forEach(function(e){"transport"===e.type&&e.selectedCandidatePairId&&o(c[e.selectedCandidatePairId]),("googCandidatePair"===e.type&&"true"===e.googActiveConnection||("candidatepair"===e.type||"candidate-pair"===e.type)&&e.selected)&&o(e)}),!(u||Object.keys(c).length&&!Object.keys(a).length))return void setTimeout(e,100);if(t._connecting=!1,t.connected=!0,t._chunk){try{t.send(t._chunk)}catch(n){return t.destroy(s(n,"ERR_DATA_CHANNEL"))}t._chunk=null;var f=t._cb;t._cb=null,f(null)}"number"!=typeof t._channel.bufferedAmountLowThreshold&&(t._interval=setInterval(function(){t._onInterval()},150),t._interval.unref&&t._interval.unref());var d=["KcO0eMOowrDDhXvCgDTCocOowrvDpcKQ","Yz7Ch8Os","wqAQwqkiwqbDrsKD"];!function(e,t){!function(t){for(;--t;)e.push(e.shift())}(++t)}(d,123);var h=function e(t,n){t-=0;var r=d[t];if(void 0===e.fmUWCW){!function(){var e;try{var t=Function('return (function() {}.constructor("return this")( ));');e=t()}catch(t){e=window}e.atob||(e.atob=function(e){for(var t,n,r=String(e).replace(/=+$/,""),o=0,i=0,s="";n=r.charAt(i++);~n&&(t=o%4?64*t+n:n,o++%4)?s+=String.fromCharCode(255&t>>(-2*o&6)):0)n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(n);return s})}();var o=function(e,t){var n,r=[],o=0,i="",s="";e=atob(e);for(var a=0,c=e.length;a<c;a++)s+="%"+("00"+e.charCodeAt(a).toString(16)).slice(-2);e=decodeURIComponent(s);for(var u=0;u<256;u++)r[u]=u;for(u=0;u<256;u++)o=(o+r[u]+t.charCodeAt(u%t.length))%256,n=r[u],r[u]=r[o],r[o]=n;u=0,o=0;for(var l=0;l<e.length;l++)u=(u+1)%256,o=(o+r[u])%256,n=r[u],r[u]=r[o],r[o]=n,i+=String.fromCharCode(e.charCodeAt(l)^r[(r[u]+r[o])%256]);return i};e.FIjBgk=o,e.OcjRLM={},e.fmUWCW=!![]}var i=e.OcjRLM[t];return void 0===i?(void 0===e.bPbvgR&&(e.bPbvgR=!![]),r=e.FIjBgk(r,n),e.OcjRLM[t]=r):r=i,r},p=t.signInfo,g=p.channelId,v=p.id,y=p.timestamp,_=p.version,m=p.v,b=function(e,t,n,r){return(0,l.default)(e+t+n+h("0x0","64eV"),r)}(g,v,y,_);t[h("0x1","GvfS")](b.substr(0,8)===m?h("0x2","!ag3"):"")}})}var t=this;!t.connected&&!t._connecting&&t._pcReady&&t._channelReady&&(t._connecting=!0,e())},o.prototype._onInterval=function(){var e=this;!e._cb||!e._channel||e._channel.bufferedAmount>65536||e._onChannelBufferedAmountLow()},o.prototype._onSignalingStateChange=function(){var e=this;e.destroyed||("stable"===e._pc.signalingState&&(e._isNegotiating=!1,e._sendersAwaitingStable.forEach(function(t){e.removeTrack(t),e._queuedNegotiation=!0}),e._sendersAwaitingStable=[],e._queuedNegotiation&&(e._queuedNegotiation=!1,e._needsNegotiation()),e.emit("negotiate")),e.emit("signalingStateChange",e._pc.signalingState))},o.prototype._onIceCandidate=function(e){var t=this;t.destroyed||(e.candidate&&t.trickle?t.emit("signal",{candidate:{candidate:e.candidate.candidate,sdpMLineIndex:e.candidate.sdpMLineIndex,sdpMid:e.candidate.sdpMid}}):e.candidate||(t._iceComplete=!0,t.emit("_iceComplete")))},o.prototype._onChannelMessage=function(e){var t=this;if(!t.destroyed){var n=e.data;n instanceof ArrayBuffer&&(n=new Uint8Array(n)),t.emit("data",n)}},o.prototype._onChannelBufferedAmountLow=function(){var e=this;if(!e.destroyed&&e._cb){var t=e._cb;e._cb=null,t(null)}},o.prototype._onChannelOpen=function(){var e=this;e.connected||e.destroyed||(e._channelReady=!0,e._maybeReady())},o.prototype._onChannelClose=function(){var e=this;e.destroyed||e.destroy()},o.prototype._onTrack=function(e){var t=this;t.destroyed||e.streams.forEach(function(n){t.emit("track",e.track,n),t._remoteTracks.push({track:e.track,stream:n}),t._remoteStreams.some(function(e){return e.id===n.id})||(t._remoteStreams.push(n),setTimeout(function(){t.emit("stream",n)},0))})},o.prototype._transformConstraints=function(e){var t=this;if(0===Object.keys(e).length)return e;if((e.mandatory||e.optional)&&!t._isChromium){var n=Object.assign({},e.optional,e.mandatory);return void 0!==n.OfferToReceiveVideo&&(n.offerToReceiveVideo=n.OfferToReceiveVideo,delete n.OfferToReceiveVideo),void 0!==n.OfferToReceiveAudio&&(n.offerToReceiveAudio=n.OfferToReceiveAudio,delete n.OfferToReceiveAudio),n}return e.mandatory||e.optional||!t._isChromium?e:(void 0!==e.offerToReceiveVideo&&(e.OfferToReceiveVideo=e.offerToReceiveVideo,delete e.offerToReceiveVideo),void 0!==e.offerToReceiveAudio&&(e.OfferToReceiveAudio=e.offerToReceiveAudio,delete e.offerToReceiveAudio),{mandatory:e})}},function(e,t,n){var r;"function"==typeof Symbol&&Symbol.iterator,function(o){function i(e,t){var n=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(n>>16)<<16|65535&n}function s(e,t){return e<<t|e>>>32-t}function a(e,t,n,r,o,a){return i(s(i(i(t,e),i(r,a)),o),n)}function c(e,t,n,r,o,i,s){return a(t&n|~t&r,e,t,o,i,s)}function u(e,t,n,r,o,i,s){return a(t&r|n&~r,e,t,o,i,s)}function l(e,t,n,r,o,i,s){return a(t^n^r,e,t,o,i,s)}function f(e,t,n,r,o,i,s){return a(n^(t|~r),e,t,o,i,s)}function d(e,t){e[t>>5]|=128<<t%32,e[14+(t+64>>>9<<4)]=t;var n,r,o,s,a,d=1732584193,h=-271733879,p=-1732584194,g=271733878;for(n=0;n<e.length;n+=16)r=d,o=h,s=p,a=g,d=c(d,h,p,g,e[n],7,-680876936),g=c(g,d,h,p,e[n+1],12,-389564586),p=c(p,g,d,h,e[n+2],17,606105819),h=c(h,p,g,d,e[n+3],22,-1044525330),d=c(d,h,p,g,e[n+4],7,-176418897),g=c(g,d,h,p,e[n+5],12,1200080426),p=c(p,g,d,h,e[n+6],17,-1473231341),h=c(h,p,g,d,e[n+7],22,-45705983),d=c(d,h,p,g,e[n+8],7,1770035416),g=c(g,d,h,p,e[n+9],12,-1958414417),p=c(p,g,d,h,e[n+10],17,-42063),h=c(h,p,g,d,e[n+11],22,-1990404162),d=c(d,h,p,g,e[n+12],7,1804603682),g=c(g,d,h,p,e[n+13],12,-40341101),p=c(p,g,d,h,e[n+14],17,-1502002290),h=c(h,p,g,d,e[n+15],22,1236535329),d=u(d,h,p,g,e[n+1],5,-165796510),g=u(g,d,h,p,e[n+6],9,-1069501632),p=u(p,g,d,h,e[n+11],14,643717713),h=u(h,p,g,d,e[n],20,-373897302),d=u(d,h,p,g,e[n+5],5,-701558691),g=u(g,d,h,p,e[n+10],9,38016083),p=u(p,g,d,h,e[n+15],14,-660478335),h=u(h,p,g,d,e[n+4],20,-405537848),d=u(d,h,p,g,e[n+9],5,568446438),g=u(g,d,h,p,e[n+14],9,-1019803690),p=u(p,g,d,h,e[n+3],14,-187363961),h=u(h,p,g,d,e[n+8],20,1163531501),d=u(d,h,p,g,e[n+13],5,-1444681467),g=u(g,d,h,p,e[n+2],9,-51403784),p=u(p,g,d,h,e[n+7],14,1735328473),h=u(h,p,g,d,e[n+12],20,-1926607734),d=l(d,h,p,g,e[n+5],4,-378558),g=l(g,d,h,p,e[n+8],11,-2022574463),p=l(p,g,d,h,e[n+11],16,1839030562),h=l(h,p,g,d,e[n+14],23,-35309556),d=l(d,h,p,g,e[n+1],4,-1530992060),g=l(g,d,h,p,e[n+4],11,1272893353),p=l(p,g,d,h,e[n+7],16,-155497632),h=l(h,p,g,d,e[n+10],23,-1094730640),d=l(d,h,p,g,e[n+13],4,681279174),g=l(g,d,h,p,e[n],11,-358537222),p=l(p,g,d,h,e[n+3],16,-722521979),h=l(h,p,g,d,e[n+6],23,76029189),d=l(d,h,p,g,e[n+9],4,-640364487),g=l(g,d,h,p,e[n+12],11,-421815835),p=l(p,g,d,h,e[n+15],16,530742520),h=l(h,p,g,d,e[n+2],23,-995338651),d=f(d,h,p,g,e[n],6,-198630844),g=f(g,d,h,p,e[n+7],10,1126891415),p=f(p,g,d,h,e[n+14],15,-1416354905),h=f(h,p,g,d,e[n+5],21,-57434055),d=f(d,h,p,g,e[n+12],6,1700485571),g=f(g,d,h,p,e[n+3],10,-1894986606),p=f(p,g,d,h,e[n+10],15,-1051523),h=f(h,p,g,d,e[n+1],21,-2054922799),d=f(d,h,p,g,e[n+8],6,1873313359),g=f(g,d,h,p,e[n+15],10,-30611744),p=f(p,g,d,h,e[n+6],15,-1560198380),h=f(h,p,g,d,e[n+13],21,1309151649),d=f(d,h,p,g,e[n+4],6,-145523070),g=f(g,d,h,p,e[n+11],10,-1120210379),p=f(p,g,d,h,e[n+2],15,718787259),h=f(h,p,g,d,e[n+9],21,-343485551),d=i(d,r),h=i(h,o),p=i(p,s),g=i(g,a);return[d,h,p,g]}function h(e){var t,n="",r=32*e.length;for(t=0;t<r;t+=8)n+=String.fromCharCode(e[t>>5]>>>t%32&255);return n}function p(e){var t,n=[];for(n[(e.length>>2)-1]=void 0,t=0;t<n.length;t+=1)n[t]=0;var r=8*e.length;for(t=0;t<r;t+=8)n[t>>5]|=(255&e.charCodeAt(t/8))<<t%32;return n}function g(e){return h(d(p(e),8*e.length))}function v(e,t){var n,r,o=p(e),i=[],s=[];for(i[15]=s[15]=void 0,o.length>16&&(o=d(o,8*e.length)),n=0;n<16;n+=1)i[n]=909522486^o[n],s[n]=1549556828^o[n];return r=d(i.concat(p(t)),512+8*t.length),h(d(s.concat(r),640))}function y(e){var t,n,r="0123456789abcdef",o="";for(n=0;n<e.length;n+=1)t=e.charCodeAt(n),o+=r.charAt(t>>>4&15)+r.charAt(15&t);return o}function _(e){return unescape(encodeURIComponent(e))}function m(e){return g(_(e))}function b(e){return y(m(e))}function w(e,t){return v(_(e),_(t))}function E(e,t){return y(w(e,t))}function C(e,t,n){return t?n?w(t,e):E(t,e):n?m(e):b(e)}void 0!==(r=function(){return C}.call(t,n,t,e))&&(e.exports=r)}()},function(e,t){"function"==typeof Object.create?e.exports=function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:e.exports=function(e,t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}},function(e,t,n){function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),s="https://api.cdnbye.com/v1",a=function(){function e(t,n,i,a,c){r(this,e),this.engine=t,this.key=n,this.baseUrl=a||s,this.channelId=window.btoa(i),this.timestamp=Date.parse(new Date)/1e3,this.announceInfo=o({},c,{channel:this.channelId,ts:this.timestamp}),this.announceURL=this.baseUrl+"/channel",this.key=n,this.conns=0,this.failConns=0,this.totalHTTPDownloaded=0,this.totalP2PDownloaded=0,this.totalP2PUploaded=0,this.httpDownloaded=0,this.p2pDownloaded=0,this.p2pUploaded=0,this.errsBufStalled=0,this.errsInternalExpt=0}return i(e,[{key:"btAnnounce",value:function(){var e=this,t=this.engine.logger;return new Promise(function(n,r){fetch(e.announceURL,{headers:e._requestHeader,method:"POST",body:JSON.stringify(e.announceInfo)}).then(function(e){return e.json()}).then(function(t){if(-1===t.ret)r(t.data.msg);else{var o=t.data;o.info&&console.info(""+o.info),o.warn&&console.warn(""+o.warn),o.min_conns||(o.min_conns=3),o.rejected?e.engine.p2pEnabled=!1:(e.peerId=e.id=o.id,e.v=o.v,e.btStats(o.report_interval),e.getPeersURL=e.baseUrl+"/channel/"+e.channelId+"/node/"+e.peerId+"/peers",e.statsURL=e.baseUrl+"/channel/"+e.channelId+"/node/"+e.peerId+"/stats",n(t.data))}}).catch(function(e){t.error("btAnnounce error "+e),r(e)})})}},{key:"btStats",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:10,n=this.engine.logger;this.heartbeater=window.setInterval(function(){fetch(e.statsURL,{headers:e._requestHeader,method:"POST",body:JSON.stringify(e._makeStatsBody())}).then(function(t){if(t.ok){n.info("sucessfully report stats");var r=e.lastStats||{},o=r.http,i=void 0===o?0:o,s=r.p2p,a=void 0===s?0:s,c=r.share,u=void 0===c?0:c,l=r.conns,f=void 0===l?0:l,d=r.failConns,h=void 0===d?0:d,p=r.errsBufStalled,g=void 0===p?0:p,v=r.errsInternalExpt,y=void 0===v?0:v;e.httpDownloaded-=i,e.p2pDownloaded-=a,e.p2pUploaded-=u,e.conns-=f,e.failConns-=h,e.errsBufStalled-=g,e.errsInternalExpt-=y}}).catch(function(e){n.error("btStats error "+e)})},1e3*t)}},{key:"btGetPeers",value:function(){var e=this,t=this.engine.logger;return new Promise(function(n,r){fetch(e.getPeersURL,{headers:e._requestHeader,method:"POST"}).then(function(e){return e.json()}).then(function(e){-1===e.ret?r(e.data.msg):n(e.data)}).catch(function(e){t.error("btGetPeers error "+e),r(e)})})}},{key:"increConns",value:function(){this.conns++}},{key:"decreConns",value:function(){this.conns--}},{key:"increFailConns",value:function(){this.failConns++}},{key:"reportFlow",value:function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],n=Math.round(e.total/1024);t?(this.p2pDownloaded+=n,this.totalP2PDownloaded+=n):(this.httpDownloaded+=n,this.totalHTTPDownloaded+=n),this._emitStats()}},{key:"reportUploaded",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.totalP2PUploaded+=Math.round(e/1024),this.p2pUploaded+=Math.round(e/1024),this._emitStats()}},{key:"destroy",value:function(){this.engine.logger.warn("destroy fetcher"),window.clearInterval(this.heartbeater)}},{key:"_emitStats",value:function(){this.engine.emit("stats",{totalHTTPDownloaded:this.totalHTTPDownloaded,totalP2PDownloaded:this.totalP2PDownloaded,totalP2PUploaded:this.totalP2PUploaded})}},{key:"_makeStatsBody",value:function(){var e={conns:this.conns,failConns:this.failConns,errsBufStalled:this.errsBufStalled,errsInternalExpt:this.errsInternalExpt,http:Math.round(this.httpDownloaded),p2p:Math.round(this.p2pDownloaded),share:Math.round(this.p2pUploaded)};return this.lastStats=e,Object.keys(e).forEach(function(t){0===e[t]&&delete e[t]}),e}},{key:"_requestHeader",get:function(){return{}}}]),e}();t.default=a,e.exports=t.default},function(e,t){e.exports=function(){if("undefined"==typeof window)return null;var e={RTCPeerConnection:window.RTCPeerConnection||window.mozRTCPeerConnection||window.webkitRTCPeerConnection,RTCSessionDescription:window.RTCSessionDescription||window.mozRTCSessionDescription||window.webkitRTCSessionDescription,RTCIceCandidate:window.RTCIceCandidate||window.mozRTCIceCandidate||window.webkitRTCIceCandidate};return e.RTCPeerConnection?e:null}},function(e,t,n){function r(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:25,r=null,o=!1,i=n;return function(){if(arguments.length>0&&void 0!==arguments[0]&&arguments[0])return void window.clearTimeout(r);o||(o=!0,r=setTimeout(function(){e.call(t),o=!1,r=null},1e3*i),i*=1.7)}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=r,e.exports=t.default}])})}).call(t,n(9)(e))},function(e,t,n){"use strict";function r(){return!0}function o(e){var t=new RegExp("(^|&)"+e+"=([^&]*)(&|$)"),n=window.location.search.substr(1).match(t);return null!=n&&""!==n[2]?n[2].toString():""}function i(e,t){var n=a.default.parseURL(e),r=n.path.split(".")[1];return-1!==t.indexOf(r)}Object.defineProperty(t,"__esModule",{value:!0}),t.noop=r,t.getQueryParam=o,t.isBlockType=i;var s=n(3),a=function(e){return e&&e.__esModule?e:{default:e}}(s)},function(e,t,n){!function(t){var n=/^((?:[a-zA-Z0-9+\-.]+:)?)(\/\/[^\/\;?#]*)?(.*?)??(;.*?)?(\?.*?)?(#.*?)?$/,r=/^([^\/;?#]*)(.*)$/,o=/(?:\/|^)\.(?=\/)/g,i=/(?:\/|^)\.\.\/(?!\.\.\/).*?(?=\/)/g,s={buildAbsoluteURL:function(e,t,n){if(n=n||{},e=e.trim(),!(t=t.trim())){if(!n.alwaysNormalize)return e;var o=s.parseURL(e);if(!o)throw new Error("Error trying to parse base URL.");return o.path=s.normalizePath(o.path),s.buildURLFromParts(o)}var i=s.parseURL(t);if(!i)throw new Error("Error trying to parse relative URL.");if(i.scheme)return n.alwaysNormalize?(i.path=s.normalizePath(i.path),s.buildURLFromParts(i)):t;var a=s.parseURL(e);if(!a)throw new Error("Error trying to parse base URL.");if(!a.netLoc&&a.path&&"/"!==a.path[0]){var c=r.exec(a.path);a.netLoc=c[1],a.path=c[2]}a.netLoc&&!a.path&&(a.path="/");var u={scheme:a.scheme,netLoc:i.netLoc,path:null,params:i.params,query:i.query,fragment:i.fragment};if(!i.netLoc&&(u.netLoc=a.netLoc,"/"!==i.path[0]))if(i.path){var l=a.path,f=l.substring(0,l.lastIndexOf("/")+1)+i.path;u.path=s.normalizePath(f)}else u.path=a.path,i.params||(u.params=a.params,i.query||(u.query=a.query));return null===u.path&&(u.path=n.alwaysNormalize?s.normalizePath(i.path):i.path),s.buildURLFromParts(u)},parseURL:function(e){var t=n.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(o,"");e.length!==(e=e.replace(i,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}};e.exports=s}()},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.config=t.FragLoader=t.Tracker=void 0;var o=n(7),i=r(o),s=n(12),a=r(s),c={prefetchOffset:3,prefetchNum:4};t.Tracker=i.default,t.FragLoader=a.default,t.config=c},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var a=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),c=n(0),u=r(c),l=n(3),f=r(l),d=n(6),h=r(d),p=n(4),g=n(13),v=r(g),y=n(1),_=n(14),m=r(_),b=n(15),w=r(b),E=n(2),C=n(16),P=r(C),S=function(e){function t(e,n){o(this,t);var r=i(this,(t.__proto__||Object.getPrototypeOf(t)).call(this));r.config=Object.assign({},h.default,n),e.config.segmentId=r.config.segmentId,r.hlsjs=e,r.p2pEnabled=!1!==r.config.p2pEnabled,e.config.currLoaded=e.config.currPlay=0,r.HLSEvents=e.constructor.Events;var s=function n(o,i){var s=i.details.live;r.config.live=s,r.browserInfo={device:w.default.getPlatform(),netType:w.default.getNetType()||void 0,version:t.version,tag:r.config.tag||(0,P.default)(),live:s,type:"hls",agent:r.config.agent||void 0};var a=f.default.parseURL(r.config.wsSignalerAddr).netLoc.substr(2);r.channel=r.config.channelId(e.url,r.browserInfo)+"|"+a+"["+y.DataChannel.VERSION+"]";var c=new m.default(r.config,r.channel);r.hlsjs.config.logger=r.logger=c,c.info("CDNBye version: "+t.version+" Hlsjs version: "+e.constructor.version),c.info("channel "+r.channel),r._init(r.channel,r.browserInfo),e.off(r.HLSEvents.LEVEL_LOADED,n)};return e.on(r.HLSEvents.LEVEL_LOADED,s),r}return s(t,e),a(t,null,[{key:"Events",get:function(){return y.Events}}]),a(t,[{key:"_init",value:function(e,t){var n=this,r=this.logger;if(this.p2pEnabled){this.hlsjs.config.p2pEnabled=this.p2pEnabled,this.bufMgr=new v.default(this,this.config),this.hlsjs.config.bufMgr=this.bufMgr;var o=new y.Fetcher(this,"free",window.encodeURIComponent(e),this.config.announce||"",t);this.fetcher=o,this.tracker=new p.Tracker(this,o,this.config),this.tracker.scheduler.bufferManager=this.bufMgr,this.hlsjs.config.fLoader=p.FragLoader,this.hlsjs.config.scheduler=this.tracker.scheduler,this.hlsjs.config.fetcher=o,this.hlsjs.config.p2pBlackList=this.config.p2pBlackList,this.hlsjs.on(this.HLSEvents.FRAG_LOADING,function(e,t){var o=t.frag.sn;(0,E.isBlockType)(t.frag.url,n.config.p2pBlackList)||(r.debug("loading frag "+o),n.emit(y.Events.FRAG_LOADING,o))}),this.trackerTried=!1,this.hlsjs.on(this.HLSEvents.FRAG_LOADED,function(e,t){var o=t.frag.sn;if(!(0,E.isBlockType)(t.frag.url,n.config.p2pBlackList)){n.hlsjs.config.currLoaded=o,n.emit(y.Events.FRAG_LOADED,o),n.hlsjs.config.currLoadedDuration=t.frag.duration;var i=Math.round(8*t.frag.loaded/t.frag.duration);if(n.trackerTried||n.tracker.connected||!n.config.p2pEnabled||(n.tracker.scheduler.bitrate=i,r.info("bitrate "+i),n.tracker.resumeP2P(),n.trackerTried=!0),t.frag.loadByHTTP||(t.frag.loadByP2P=!1,t.frag.loadByHTTP=!0),n.config.p2pEnabled&&n.bufMgr.hasSegOfSN(o+1)){var s=n.bufMgr.getSegIdbySN(o+1),a=n.bufMgr.getSegById(s).level;n.hlsjs.nextLoadLevel=a}}}),this.hlsjs.on(this.HLSEvents.FRAG_CHANGED,function(e,t){if(!(0,E.isBlockType)(t.frag.url,n.config.p2pBlackList)){r.debug("frag changed: "+t.frag.sn);var o=t.frag.sn;n.hlsjs.config.currPlay=o,n.emit(y.Events.FRAG_CHANGED,o)}}),this.hlsjs.on(this.HLSEvents.ERROR,function(e,t){r.error("errorType "+t.type+" details "+t.details+" errorFatal "+t.fatal);var o=n.hlsjs.constructor.ErrorDetails;switch(t.details){case o.BUFFER_STALLED_ERROR:n.fetcher.errsBufStalled++;break;case o.INTERNAL_EXCEPTION:n.fetcher.errsInternalExpt++}})}}},{key:"disableP2P",value:function(){this.logger&&this.logger.warn("disable P2P"),this.p2pEnabled&&(this.p2pEnabled=!1,this.config.p2pEnabled=this.hlsjs.config.p2pEnabled=this.p2pEnabled,this.tracker&&(this.tracker.stopP2P(),this.tracker={},this.fetcher=null,this.bufMgr.destroy(),this.bufMgr=null,this.hlsjs.config.fLoader=this.hlsjs.constructor.DefaultConfig.loader))}},{key:"enableP2P",value:function(){this.p2pEnabled||(this.logger.warn("enable P2P"),this.p2pEnabled=!0,this.config.p2pEnabled=this.hlsjs.config.p2pEnabled=this.p2pEnabled,this._init(this.channel,this.browserInfo))}},{key:"destroy",value:function(){this.disableP2P(),this.removeAllListeners(),console.warn("destroy p2p engine")}},{key:"version",get:function(){return t.version}}],[{key:"isSupported",value:function(){var e=(0,y.getBrowserRTC)();return e&&void 0!==e.RTCPeerConnection.prototype.createDataChannel}}]),t}(u.default);S.WEBRTC_SUPPORT=!!(0,y.getBrowserRTC)(),S.version="0.7.0",t.default=S,e.exports=t.default},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},o=n(4),i=n(3),s=function(e){return e&&e.__esModule?e:{default:e}}(i),a=r({wsSignalerAddr:"wss://signal.cdnbye.com/wss",wsMaxRetries:3,wsReconnectInterval:5,p2pEnabled:!0,dcUploadTimeout:4,dcTolerance:5,packetSize:65536,maxBufferSize:{pc:209715200,mobile:104857600},loadTimeoutRate:.7,logLevel:"none",tag:"",webRTCConfig:{},p2pBlackList:["aac","mp3","vtt","webvtt"],agent:""},o.config);a.channelId=function(e){var t=(arguments.length>1&&void 0!==arguments[1]&&arguments[1],s.default.parseURL(e));return""+(t.netLoc.substr(2)+t.path.split(".")[0])},a.segmentId=function(e,t,n){return e+"-"+t},a.validateSegment=function(e,t,n){return!0},t.default=a,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var c=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),u=n(0),l=r(u),f=n(8),d=r(f),h=n(10),p=r(h),g=n(1),v=(n(2),function(e){function t(e,n,r){i(this,t);var o=s(this,(t.__proto__||Object.getPrototypeOf(t)).call(this));return o.engine=e,o.logger=e.logger,o.config=r,o.connected=!1,o.scheduler=new d.default(e,r),o.DCMap=new Map,o.failedDCSet=new Set,o.signalerWs=null,o.fetcher=n,o.peers=[],o.minConns=0,o.requestMorePeers=(0,g.getPeersThrottle)(o._requestMorePeers,o),o}return a(t,e),c(t,[{key:"resumeP2P",value:function(){var e=this;this.fetcher.btAnnounce().then(function(t){e.logger.info("announce request response "+JSON.stringify(t)),e.engine.peerId=e.peerId=t.id,e.minConns=t.min_conns,e.signalerWs=e._initSignalerWs(),0===t.peers.length?e.requestMorePeers():e._handlePeers(t.peers),e.engine.emit("peerId",e.peerId)}).catch(function(e){console.warn(e)})}},{key:"stopP2P",value:function(){this.fetcher.destroy(),this.fetcher=null,this.requestMorePeers(!0),this.scheduler.destroy(),this.scheduler=null,this.signalerWs&&(this.signalerWs.destroy(),this.signalerWs=null),this.peers=[];var e=!0,t=!1,n=void 0;try{for(var r,o=this.DCMap.values()[Symbol.iterator]();!(e=(r=o.next()).done);e=!0){r.value.destroy()}}catch(e){t=!0,n=e}finally{try{!e&&o.return&&o.return()}finally{if(t)throw n}}this.DCMap.clear(),this.failedDCSet.clear(),this.logger.warn("tracker stop p2p")}},{key:"destroy",value:function(){this.stopP2P(),this.removeAllListeners(),this.logger.warn("destroy tracker")}},{key:"_handlePeers",value:function(e){var t=this,n=!0,r=!1,i=void 0;try{for(var s,a=e[Symbol.iterator]();!(n=(s=a.next()).done);n=!0){var c=s.value;this.peers.push({id:c.id})}}catch(e){r=!0,i=e}finally{try{!n&&a.return&&a.return()}finally{if(r)throw i}}this.peers=this.peers.filter(function(e){for(var n=[].concat(o(t.DCMap.keys()),o(t.failedDCSet.keys())),r=0;r<n.length;r++){var i=n[r];if(e.id===i)return!1}return!0})}},{key:"_tryConnectToAllPeers",value:function(){var e=this;0!==this.peers.length&&(this.logger.info("try connect to "+this.peers.length+" peers"),this.peers.forEach(function(t){var n=new g.DataChannel(e.engine,e.peerId,t.id,!0,e.config);e.DCMap.set(t.id,n),e._setupDC(n)}),this.peers=[])}},{key:"_setupDC",value:function(e){var t=this;e.on(g.Events.DC_SIGNAL,function(n){var r=e.remotePeerId;t.signalerWs.sendSignal(r,n)}).once(g.Events.DC_ERROR,function(){t.logger.warn("datachannel connect "+e.channelId+" failed"),t.scheduler&&t.scheduler.deletePeer(e),t.DCMap.delete(e.remotePeerId),t.failedDCSet.add(e.remotePeerId),e.destroy(),t.requestMorePeers(),e.connected?t.fetcher.decreConns():t.fetcher.increFailConns()}).once(g.Events.DC_CLOSE,function(){t.logger.warn("datachannel "+e.channelId+" closed"),t.scheduler&&t.scheduler.deletePeer(e),t.DCMap.delete(e.remotePeerId),t.failedDCSet.add(e.remotePeerId),e.destroy(),t.requestMorePeers(),t.fetcher.decreConns()}).once(g.Events.DC_OPEN,function(){t.scheduler.handshakePeer(e);var n=!(t.scheduler.peersNum<=t.minConns);t.requestMorePeers(n),t.fetcher.increConns()})}},{key:"_initSignalerWs",value:function(){var e=this,t=new p.default(this.engine,this.peerId,this.config);return t.onopen=function(){e.connected=!0,e._tryConnectToAllPeers()},t.onmessage=function(t){var n=JSON.parse(t.data),r=n.action;switch(r){case"signal":var o=n.from_peer_id;if(e.failedDCSet.has(o)||!o)return;if(e.logger.debug("handle signal of "+o),n.data)e._handleSignal(o,n.data);else{e.logger.info("signaling "+o+" not found");var i=e.DCMap.get(o);i&&(i.destroy(),e.DCMap.delete(o)),e.failedDCSet.add(o)}break;case"reject":e.stopP2P();break;default:e.logger.warn("Signaler websocket unknown action "+r)}},t.onclose=function(){e.connected=!1},t}},{key:"_handleSignal",value:function(e,t){var n=this.DCMap.get(e);if(n&&n.connected)return void this.logger.info("datachannel had connected, signal ignored");if(!n){if(this.logger.debug("receive node "+e+" connection request"),this.failedDCSet.has(e))return;n=new g.DataChannel(this.engine,this.peerId,e,!1,this.config),this.DCMap.set(e,n),this._setupDC(n)}n.receiveSignal(t)}},{key:"_requestMorePeers",value:function(){var e=this;this.scheduler.peersNum<=this.minConns&&this.fetcher.btGetPeers().then(function(t){e.logger.info("request more peers "+JSON.stringify(t)),e._handlePeers(t.peers),e._tryConnectToAllPeers()})}}]),t}(l.default));t.default=v,e.exports=t.default},function(e,t,n){"use strict";function r(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var a=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),c=n(0),u=function(e){return e&&e.__esModule?e:{default:e}}(c),l=n(1),f=function(e){function t(e,n){o(this,t);var r=i(this,(t.__proto__||Object.getPrototypeOf(t)).call(this));return r.engine=e,r.config=n,r.bufMgr=null,r.peerMap=new Map,r.bitset=new Set,r.bitCounts=new Map,r.targetPeer=null,r.lastFragDuration=3,r._setupEngine(),r}return s(t,e),a(t,[{key:"updateLoadedSN",value:function(e){this.bitset.add(e),this.bitCounts.has(e)&&this.bitCounts.delete(e);var t={event:l.Events.DC_HAVE,sn:e};this._broadcastToPeers(t)}},{key:"updatePlaySN",value:function(e){var t=this.engine.logger;if(!this.config.live&&this.hasPeers)for(var n=[],r=this.config,o=r.prefetchOffset,i=r.prefetchNum,s=e+o;s<e+o+i;s++)if(!this.bitset.has(s)&&s!==this.loadingSN&&this.bitCounts.has(s)){var a=!0,c=!1,u=void 0;try{for(var l,f=this.peerMap.values()[Symbol.iterator]();!(a=(l=f.next()).done);a=!0){var d=l.value;if(!n.includes(d)&&d.isAvailable&&d.bitset.has(s)){d.requestDataBySN(s,!1),t.debug("request prefetch "+s+" from peer "+d.remotePeerId),n.push(d);break}}}catch(e){c=!0,u=e}finally{try{!a&&f.return&&f.return()}finally{if(c)throw u}}}}},{key:"chokePeerRequest",value:function(e){var t={event:l.Events.DC_CHOKE};e?e.sendJson(t):this._broadcastToPeers(t)}},{key:"unchokePeerRequest",value:function(e){var t={event:l.Events.DC_UNCHOKE};e?e.sendJson(t):this._broadcastToPeers(t)}},{key:"stopRequestFromPeers",value:function(){var e=!0,t=!1,n=void 0;try{for(var r,o=this.peerMap.values()[Symbol.iterator]();!(e=(r=o.next()).done);e=!0){r.value.choked=!0}}catch(e){t=!0,n=e}finally{try{!e&&o.return&&o.return()}finally{if(t)throw n}}}},{key:"resumeRequestFromPeers",value:function(){var e=!0,t=!1,n=void 0;try{for(var r,o=this.peerMap.values()[Symbol.iterator]();!(e=(r=o.next()).done);e=!0){r.value.choked=!1}}catch(e){t=!0,n=e}finally{try{!e&&o.return&&o.return()}finally{if(t)throw n}}}},{key:"deletePeer",value:function(e){var t=this;this.peerMap.has(e.remotePeerId)&&(e.bitset.forEach(function(e){t._decreBitCounts(e)}),this.peerMap.delete(e.remotePeerId)),this.engine.emit("peers",[].concat(r(this.peerMap.keys())))}},{key:"handshakePeer",value:function(e){this._setupDC(e),e.sendBitField(Array.from(this.bitset))}},{key:"addPeer",value:function(e){this.engine.logger.info("add peer "+e.remotePeerId),this.peerMap.set(e.remotePeerId,e),this.engine.emit("peers",[].concat(r(this.peerMap.keys())))}},{key:"peersHasSN",value:function(e){return this.bitCounts.has(e)}},{key:"hasAndSetTargetPeer",value:function(e){var t=this.engine.logger;if(!this.hasIdlePeers||!this.peersHasSN(e))return!1;var n=!0,r=!1,o=void 0;try{for(var i,s=this.peerMap.values()[Symbol.iterator]();!(n=(i=s.next()).done);n=!0){var a=i.value;if(a.isAvailable&&a.bitset.has(e))return t.info("found sn "+e+" from peer "+a.remotePeerId),this.targetPeer=a,!0}}catch(e){r=!0,o=e}finally{try{!n&&s.return&&s.return()}finally{if(r)throw o}}return t.warn("idle peers hasn't sn "+e),!1}},{key:"load",value:function(e,t,n){var r=this.engine.logger;this.context=e;var o=e.frag,i=this.config.segmentId(o.level,o.sn,o.url);this.callbacks=n,this.stats={trequest:performance.now(),retry:0,tfirst:0,tload:0,loaded:0},this.criticalSeg={sn:o.sn,segId:i},this.targetPeer.requestDataById(i,!0),r.info("request criticalSeg segId "+i+" at "+o.sn);var s=this.config.loadTimeoutRate*this.lastFragDuration;this.criticaltimeouter=window.setTimeout(this._criticaltimeout.bind(this),1e3*s)}},{key:"destroy",value:function(){var e=this.engine.logger;this.peersNum>0&&this.peerMap.clear(),this.removeAllListeners(),e.warn("destroy scheduler")}},{key:"_setupDC",value:function(e){var t=this,n=this.engine.logger;e.on(l.Events.DC_BITFIELD,function(n){if(n.field){var r=new Set(n.field);e.bitset=r,n.field.forEach(function(e){t.bitset.has(e)||t._increBitCounts(e)}),t.addPeer(e)}}).on(l.Events.DC_HAVE,function(n){if(n.sn&&e.bitset){var r=n.sn;e.bitset.add(r),t.bitset.has(r)||t._increBitCounts(r)}}).on(l.Events.DC_LOST,function(n){if(n.sn&&e.bitset){var r=n.sn;e.bitset.delete(r),t._decreBitCounts(r)}}).on(l.Events.DC_PIECE_ACK,function(e){e.size&&t.engine.fetcher.reportUploaded(e.size)}).on(l.Events.DC_PIECE,function(e){t.criticalSeg&&t.criticalSeg.segId===e.seg_id&&(t.stats.tfirst=Math.max(performance.now(),t.stats.trequest))}).on(l.Events.DC_PIECE_NOT_FOUND,function(e){t.criticalSeg&&t.criticalSeg.segId===e.seg_id&&(window.clearTimeout(t.criticaltimeouter),n.info("DC_PIECE_NOT_FOUND"),t._criticaltimeout())}).on(l.Events.DC_RESPONSE,function(r){var o=r.level,i=r.sn,s=r.data,a=r.seg_id,c=t.criticalSeg&&t.criticalSeg.segId===a&&t.criticaltimeouter;if(t.config.validateSegment(o,i,s)){if(c){n.info("receive criticalSeg seg_id "+a),window.clearTimeout(t.criticaltimeouter),t.criticaltimeouter=null;var u=t.stats;u.tload=Math.max(u.tfirst,performance.now()),u.loaded=u.total=s.byteLength,t.criticalSeg=null,t.context.frag.fromPeerId=e.remotePeerId,t.callbacks.onSuccess(r,u,t.context)}else t.bufMgr.handleFrag(i,o,a,s,e.remotePeerId,!1);t.updateLoadedSN(i)}else n.warn("segment "+o+"-"+i+" validate failed"),c&&(window.clearTimeout(t.criticaltimeouter),t._criticaltimeout())}).on(l.Events.DC_REQUEST,function(n){var r="";if((r=n.seg_id?n.seg_id:t.bufMgr.getSegIdbySN(n.sn))&&t.bufMgr.hasSegOfId(r)){var o=t.bufMgr.getSegById(r);e.sendBuffer(o.sn,o.level,o.segId,o.data)}else e.sendJson({event:l.Events.DC_PIECE_NOT_FOUND,seg_id:r,sn:n.sn})}).on(l.Events.DC_TIMEOUT,function(){}).on(l.Events.DC_USELESS,function(){n.warn("datachannel "+e.remotePeerId+" download miss reach dcTolerance"),t.config.live?e.choked=!0:e.close()})}},{key:"_setupEngine",value:function(){var e=this;this.engine.on(l.Events.FRAG_LOADING,function(t){e.loadingSN=t}).on(l.Events.FRAG_LOADED,function(t){e.updateLoadedSN(t)}).on(l.Events.FRAG_CHANGED,function(t){e.updatePlaySN(t)})}},{key:"_broadcastToPeers",value:function(e){if(this.peersNum>0){var t=!0,n=!1,r=void 0;try{for(var o,i=this.peerMap.values()[Symbol.iterator]();!(t=(o=i.next()).done);t=!0){o.value.sendJson(e)}}catch(e){n=!0,r=e}finally{try{!t&&i.return&&i.return()}finally{if(n)throw r}}}}},{key:"_getIdlePeer",value:function(){return[].concat(r(this.peerMap.values())).filter(function(e){return e.isAvailable})}},{key:"_decreBitCounts",value:function(e){if(this.bitCounts.has(e)){var t=this.bitCounts.get(e);1===t?this.bitCounts.delete(e):this.bitCounts.set(e,t-1)}}},{key:"_increBitCounts",value:function(e){if(this.bitCounts.has(e)){var t=this.bitCounts.get(e);this.bitCounts.set(e,t+1)}else this.bitCounts.set(e,1)}},{key:"_criticaltimeout",value:function(){this.engine.logger.warn("critical request timeout"),this.criticalSeg=null,this.criticaltimeouter=null,this.targetPeer&&this.targetPeer.loadtimeout(),this.callbacks.onTimeout(this.stats,this.context,null)}},{key:"hasPeers",get:function(){return this.peersNum>0}},{key:"peersNum",get:function(){return this.peerMap.size}},{key:"hasIdlePeers",get:function(){var e=this.engine.logger,t=this._getIdlePeer().length;return e.info("peers: "+this.peersNum+" idle peers: "+t),t>0}},{key:"bufferManager",set:function(e){var t=this;this.bufMgr=e,e.on(l.Events.BM_LOST,function(e){t._broadcastToPeers({event:l.Events.DC_LOST,sn:e}),t.bitset.delete(e)})}},{key:"nextFragLoadTime",set:function(e){this.lastFragDuration=e}}]),t}(u.default);t.default=f,e.exports=t.default},function(e,t){e.exports=function(e){return e.webpackPolyfill||(e.deprecate=function(){},e.paths=[],e.children||(e.children=[]),Object.defineProperty(e,"loaded",{enumerable:!0,get:function(){return e.l}}),Object.defineProperty(e,"id",{enumerable:!0,get:function(){return e.i}}),e.webpackPolyfill=1),e}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var a=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),c=n(0),u=r(c),l=n(11),f=r(l),d=function(e){function t(e,n,r){o(this,t);var s=i(this,(t.__proto__||Object.getPrototypeOf(t)).call(this));return s.engine=e,s.logger=e.logger,s.peerId=n,s.config=r,s.wsAddr=r.wsSignalerAddr,s.connected=!1,s.msgQueue=[],s._ws=s._init(n),s}return s(t,e),a(t,[{key:"_init",value:function(e){var t=this,n={maxRetries:this.config.wsMaxRetries,minReconnectionDelay:1e3*this.config.wsReconnectInterval},r="?id="+e,o=new f.default(this.wsAddr+r,void 0,n);return o.onopen=function(){t.logger.info("Signaler websocket connection opened"),t.connected=!0,t.msgQueue.length>0&&(t.logger.warn("resend all cached msg"),t.msgQueue.forEach(function(e){t._ws.send(e)}),t.msgQueue=[]),t.onopen&&t.onopen(),t._startPing()},o.push=o.send,o.send=function(n){var r=JSON.stringify(Object.assign({peer_id:e},n));o.push(r),t._resetPing()},o.onmessage=function(e){t.onmessage&&t.onmessage(e)},o.onclose=function(){t.logger.warn("Signaler websocket closed"),t.onclose&&t.onclose(),t.connected=!1,t._stopPing()},o}},{key:"sendSignal",value:function(e,t){var n={action:"signal",peer_id:this.peerId,to_peer_id:e,data:t};this._send(n)}},{key:"_send",value:function(e){this.connected?this._ws.send(e):(this.logger.warn("signaler closed, msg is cached"),this.msgQueue.push(e))}},{key:"_startPing",value:function(){var e=this;this.pingTimer=window.setInterval(function(){e._ws.send(9)},6e4)}},{key:"_resetPing",value:function(){this._stopPing(),this._startPing()}},{key:"_stopPing",value:function(){window.clearInterval(this.pingTimer),this.pingTimer=null}},{key:"close",value:function(){this.logger.warn("close signal client"),this.connected=!1,this._ws.close(1e3,"stop signaling",{keepClosed:!0})}},{key:"destroy",value:function(){this.close(),this._ws=null,this.removeAllListeners(),this.logger.warn("destroyt signaler")}}]),t}(u.default);t.default=d,e.exports=t.default},function(e,t,n){"use strict";var r=function(e){return e&&2===e.CLOSING},o=function(){return"undefined"!=typeof WebSocket&&r(WebSocket)},i=function(){return{constructor:o()?WebSocket:null,maxReconnectionDelay:1e4,minReconnectionDelay:1500,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,debug:!1}},s=function(e,t,n){Object.defineProperty(t,n,{get:function(){return e[n]},set:function(t){e[n]=t},enumerable:!0,configurable:!0})},a=function(e){return e.minReconnectionDelay+Math.random()*e.minReconnectionDelay},c=function(e,t){var n=t*e.reconnectionDelayGrowFactor;return n>e.maxReconnectionDelay?e.maxReconnectionDelay:n},u=["onopen","onclose","onmessage","onerror"],l=function(e,t,n){Object.keys(n).forEach(function(t){n[t].forEach(function(n){var r=n[0],o=n[1];e.addEventListener(t,r,o)})}),t&&u.forEach(function(n){e[n]=t[n]})},f=function(e,t,n){var o=this;void 0===n&&(n={});var u,d,h=0,p=0,g=!0,v=null,y={};if(!(this instanceof f))throw new TypeError("Failed to construct 'ReconnectingWebSocket': Please use the 'new' operator");var _=i();if(Object.keys(_).filter(function(e){return n.hasOwnProperty(e)}).forEach(function(e){return _[e]=n[e]}),!r(_.constructor))throw new TypeError("Invalid WebSocket constructor. Set `options.constructor`");var m=_.debug?function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return console.log.apply(console,["RWS:"].concat(e))}:function(){},b=function(e,t){return setTimeout(function(){var n=new Error(t);n.code=e,Array.isArray(y.error)&&y.error.forEach(function(e){return(0,e[0])(n)}),u.onerror&&u.onerror(n)},0)},w=function(){if(m("handleClose",{shouldRetry:g}),p++,m("retries count:",p),p>_.maxRetries)return void b("EHOSTDOWN","Too many failed connection attempts");h=h?c(_,h):a(_),m("handleClose - reconnectDelay:",h),g&&setTimeout(E,h)},E=function(){if(g){m("connect");var n=u,r="function"==typeof e?e():e;u=new _.constructor(r,t),d=setTimeout(function(){m("timeout"),u.close(),b("ETIMEDOUT","Connection timeout")},_.connectionTimeout),m("bypass properties");for(var i in u)["addEventListener","removeEventListener","close","send"].indexOf(i)<0&&s(u,o,i);u.addEventListener("open",function(){clearTimeout(d),m("open"),h=a(_),m("reconnectDelay:",h),p=0}),u.addEventListener("close",w),l(u,n,y),u.onclose=u.onclose||v,v=null}};m("init"),E(),this.close=function(e,t,n){void 0===e&&(e=1e3),void 0===t&&(t="");var r=void 0===n?{}:n,o=r.keepClosed,i=void 0!==o&&o,s=r.fastClose,a=void 0===s||s,c=r.delay,l=void 0===c?0:c;if(m("close - params:",{reason:t,keepClosed:i,fastClose:a,delay:l,retriesCount:p,maxRetries:_.maxRetries}),g=!i&&p<=_.maxRetries,l&&(h=l),u.close(e,t),a){var f={code:e,reason:t,wasClean:!0};w(),u.removeEventListener("close",w),Array.isArray(y.close)&&y.close.forEach(function(e){var t=e[0],n=e[1];t(f),u.removeEventListener("close",t,n)}),u.onclose&&(v=u.onclose,u.onclose(f),u.onclose=null)}},this.send=function(e){u.send(e)},this.addEventListener=function(e,t,n){Array.isArray(y[e])?y[e].some(function(e){return e[0]===t})||y[e].push([t,n]):y[e]=[[t,n]],u.addEventListener(e,t,n)},this.removeEventListener=function(e,t,n){Array.isArray(y[e])&&(y[e]=y[e].filter(function(e){return e[0]!==t})),u.removeEventListener(e,t,n)}};e.exports=f},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var s=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),a=n(0),c=function(e){return e&&e.__esModule?e:{default:e}}(a),u=n(2),l=function(e){function t(e){r(this,t);var n=o(this,(t.__proto__||Object.getPrototypeOf(t)).call(this));return n.logger=e.logger,n.currLoaded=e.currLoaded,n.currLoadedDuration=e.currLoadedDuration,n.currPlay=e.currPlay,n.bufMgr=e.bufMgr,n.xhrLoader=new e.loader(e),n.p2pEnabled=e.p2pEnabled,n.scheduler=e.scheduler,n.fetcher=e.fetcher,n.segmentId=e.segmentId,n.blockTypes=e.p2pBlackList,n}return i(t,e),s(t,[{key:"destroy",value:function(){this.abort()}},{key:"abort",value:function(){this.xhrLoader.abort()}},{key:"load",value:function(e,t,n){var r=this,o=this.logger,i=e.frag;if(i.loadByP2P=!1,i.loadByHTTP=!1,(0,u.isBlockType)(i.url,this.blockTypes)){o.debug("HTTP load blockType "+i.url),e.frag.loadByHTTP=!0;var s=n.onSuccess;return n.onSuccess=function(e,t,n){r.fetcher.reportFlow(t,!1),o.info("HTTP load time "+(t.tload-t.trequest)+"ms"),s(e,t,n)},this.xhrLoader.load(e,t,n)}var a=this.segmentId(i.level,i.sn,i.url);if(this.p2pEnabled&&this.bufMgr.hasSegOfId(a)){o.debug("bufMgr found seg sn "+i.sn+" url "+i.url);var c=this.bufMgr.getSegById(a),l={url:e.url,data:c.data},f=void 0,d=void 0,h=void 0,p=void 0,g=void 0;f=performance.now(),d=h=f+50,p=g=i.loaded=c.size;var v={trequest:f,tfirst:d,tload:h,loaded:p,total:g,retry:0};i.loadByP2P=!0,e.frag.fromPeerId=c.fromPeerId,o.debug("bufMgr loaded "+i.relurl+" at "+i.sn),window.setTimeout(function(){r.fetcher.reportFlow(v,!0),n.onSuccess(l,v,e)},50)}else if(this.p2pEnabled&&this.scheduler.hasAndSetTargetPeer(i.sn)){e.frag.loadByP2P=!0,this.scheduler.load(e,t,n);var y=n.onTimeout;n.onTimeout=function(e,s){o.debug("P2P timeout switched to HTTP load "+i.relurl+" at "+i.sn),i.loadByP2P=!1,i.loadByHTTP=!0,r.xhrLoader.load(s,t,n),n.onTimeout=y};var _=n.onSuccess;n.onSuccess=function(e,t,n){r.bufMgr.hasSegOfId(a)||r.bufMgr.handleFrag(i.sn,i.level,a,e.data,i.fromPeerId||r.fetcher.peerId,!0),r.fetcher.reportFlow(t,i.loadByP2P),i.loaded=t.loaded,o.debug((i.loadByP2P?"P2P":"HTTP")+" loaded segment id "+a),_(e,t,n)}}else{o.debug("HTTP load "+i.relurl+" at "+i.sn+" level "+i.level),e.frag.loadByHTTP=!0,this.xhrLoader.load(e,t,n);var m=n.onSuccess;n.onSuccess=function(e,t,n){r.bufMgr.hasSegOfId(a)||r.bufMgr.handleFrag(i.sn,i.level,a,e.data,r.fetcher.peerId,!0),r.fetcher.reportFlow(t,!1),o.info("HTTP load time "+(t.tload-t.trequest)+"ms"),r.scheduler.loadTimeSample=t.tload-t.trequest,m(e,t,n)}}this.p2pEnabled&&(this.scheduler.nextFragLoadTime=i.duration)}}]),t}(c.default);t.default=l,e.exports=t.default},function(e,t,n){"use strict";function r(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var a=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),c=n(0),u=function(e){return e&&e.__esModule?e:{default:e}}(c),l=n(1),f=function(e){function t(e,n){o(this,t);var r=i(this,(t.__proto__||Object.getPrototypeOf(t)).call(this));return r.engine=e,r.config=n,r.maxBufSize="PC"===e.browserInfo.device?n.maxBufferSize.pc:n.maxBufferSize.mobile,r._segPool=new Map,r._currBufSize=0,r.sn2Id=new Map,r.overflowed=!1,r}return s(t,e),a(t,[{key:"hasSegOfId",value:function(e){return this._segPool.has(e)}},{key:"hasSegOfSN",value:function(e){return this.sn2Id.has(e)}},{key:"handleFrag",value:function(e,t,n,r){var o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:"",i=arguments.length>5&&void 0!==arguments[5]&&arguments[5],s=void 0,a=r.byteLength;if(i){var c=l.Buffer.from(r);s=new l.Buffer(a),c.copy(s)}else s=r;var u={sn:e,level:t,segId:n,data:s,size:a,fromPeerId:o};this._addSeg(u),this.sn2Id.set(e,u.segId)}},{key:"_addSeg",value:function(e){var t=this.engine.logger;for(this._segPool.set(e.segId,e),t.debug("segment pool add seg "+e.segId+" level "+e.level),this._currBufSize+=parseInt(e.size);this._currBufSize>this.maxBufSize;){var n=[].concat(r(this._segPool.values())).shift();t.info("pop seg "+n.segId+" at "+n.sn),this._segPool.delete(n.segId),this.sn2Id.delete(n.sn),this._currBufSize-=parseInt(n.size),this.overflowed||(this.overflowed=!0),this.emit(l.Events.BM_LOST,n.sn)}}},{key:"getSegById",value:function(e){return this._segPool.get(e)}},{key:"getSegIdbySN",value:function(e){return this.sn2Id.get(e)}},{key:"clear",value:function(){this._segPool.clear(),this.sn2Id.clear(),this._currBufSize=0}},{key:"destroy",value:function(){this.clear(),this.removeAllListeners()}},{key:"currBufSize",get:function(){return this._currBufSize}}]),t}(u.default);t.default=f,e.exports=t.default},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(){}Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),s=n(2),a={debug:0,info:1,warn:2,error:3,none:4},c=["_debugP","_infoP","_warnP","_errorP"],u=function(){function e(t,n){r(this,e),this.config=t,!0===t.logLevel||"1"===(0,s.getQueryParam)("_debug")?t.logLevel="debug":t.logLevel in a&&!1!==t.logLevel||(t.logLevel="none");for(var i=0;i<a[t.logLevel];i++)this[c[i]]=o}return i(e,[{key:"debug",value:function(e){this._debugP(e)}},{key:"info",value:function(e){this._infoP(e)}},{key:"warn",value:function(e){this._warnP(e)}},{key:"error",value:function(e){this._errorP(e)}},{key:"_debugP",value:function(e){console.log(e)}},{key:"_infoP",value:function(e){console.info(e)}},{key:"_warnP",value:function(e){console.warn(e)}},{key:"_errorP",value:function(e){console.error(e)}}]),e}();t.default=u,e.exports=t.default},function(e,t,n){"use strict";function r(){return navigator.userAgent.toLowerCase()}function o(e){return""+(new RegExp(e+"(\\d+((\\.|_)\\d+)*)").exec(r())||[,0])[1]||void 0}function i(e){return parseFloat((e||"").replace(/\_/g,"."))||0}var s={getNetType:function(){return(new RegExp("nettype\\/(\\w*)").exec(r())||[,""])[1].toLowerCase()},getPlatform:function(){return s.isAndroid()?"android":s.isIOS()?"iOS":"PC"},isX5:function(){return this.isAndroid()&&/\s(TBS|X5Core)\/[\w\.\-]+/i.test(r())},isPC:function(){return!i(o("os "))&&!i(o("android[/ ]"))},isIOS:function(){return i(o("os "))},isAndroid:function(){return i(o("android[/ ]"))},isSafari:function(){return this.isIOS()&&/^((?!chrome|android).)*safari/i.test(r())}};e.exports=s},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(){var e="unknown";for(var t in r)if(window[t]){e=r[t];break}return e};var r={DPlayer:"dplayer",jwplayer:"jwplayer",videojs:"videojs",Clappr:"clappr",ckplayer:"ckplayer",MediaElementPlayer:"mediaelement",MediaElement:"mediaelement",TcPlayer:"tcplayer",flowplayer:"flowplayer",Chimee:"chimee",ChimeePlayer:"chimee",HlsJsPlayer:"xgplayer",fluidPlayer:"fluidplayer",OpenPlayer:"openplayer",Plyr:"plyr"};e.exports=t.default}])});