!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(n){if(r[n])return r[n].exports;var i=r[n]={i:n,l:!1,exports:{}};return e[n].call(i.exports,i,i.exports,t),i.l=!0,i.exports}var r={};return t.m=e,t.c=r,t.d=function(e,r,n){t.o(e,r)||Object.defineProperty(e,r,{configurable:!1,enumerable:!0,get:n})},t.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(r,"a",r),r},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=6)}([function(e,t){function r(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function n(e){return"function"==typeof e}function i(e){return"number"==typeof e}function a(e){return"object"==typeof e&&null!==e}function o(e){return void 0===e}e.exports=r,r.EventEmitter=r,r.prototype._events=void 0,r.prototype._maxListeners=void 0,r.defaultMaxListeners=10,r.prototype.setMaxListeners=function(e){if(!i(e)||e<0||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this},r.prototype.emit=function(e){var t,r,i,s,u,l;if(this._events||(this._events={}),"error"===e&&(!this._events.error||a(this._events.error)&&!this._events.error.length)){if((t=arguments[1])instanceof Error)throw t;var c=new Error('Uncaught, unspecified "error" event. ('+t+")");throw c.context=t,c}if(r=this._events[e],o(r))return!1;if(n(r))switch(arguments.length){case 1:r.call(this);break;case 2:r.call(this,arguments[1]);break;case 3:r.call(this,arguments[1],arguments[2]);break;default:s=Array.prototype.slice.call(arguments,1),r.apply(this,s)}else if(a(r))for(s=Array.prototype.slice.call(arguments,1),l=r.slice(),i=l.length,u=0;u0&&this._events[e].length>i&&(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},r.prototype.on=r.prototype.addListener,r.prototype.once=function(e,t){function r(){this.removeListener(e,r),i||(i=!0,t.apply(this,arguments))}if(!n(t))throw TypeError("listener must be a function");var i=!1;return r.listener=t,this.on(e,r),this},r.prototype.removeListener=function(e,t){var r,i,o,s;if(!n(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(r=this._events[e],o=r.length,i=-1,r===t||n(r.listener)&&r.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(a(r)){for(s=o;s-- >0;)if(r[s]===t||r[s].listener&&r[s].listener===t){i=s;break}if(i<0)return this;1===r.length?(r.length=0,delete this._events[e]):r.splice(i,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},r.prototype.removeAllListeners=function(e){var t,r;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(r=this._events[e],n(r))this.removeListener(e,r);else if(r)for(;r.length;)this.removeListener(e,r[r.length-1]);return delete this._events[e],this},r.prototype.listeners=function(e){return this._events&&this._events[e]?n(this._events[e])?[this._events[e]]:this._events[e].slice():[]},r.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(n(t))return 1;if(t)return t.length}return 0},r.listenerCount=function(e,t){return e.listenerCount(t)}},function(e,t,r){"use strict";(function(e){var r,n,i,a="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(o,s){"object"==a(t)&&"object"==a(e)?e.exports=s():(n=[],r=s,void 0!==(i="function"==typeof r?r.apply(t,n):r)&&(e.exports=i))}("undefined"!=typeof self&&self,function(){return function(e){function t(n){if(r[n])return r[n].exports;var i=r[n]={i:n,l:!1,exports:{}};return e[n].call(i.exports,i,i.exports,t),i.l=!0,i.exports}var r={};return t.m=e,t.c=r,t.d=function(e,r,n){t.o(e,r)||Object.defineProperty(e,r,{configurable:!1,enumerable:!0,get:n})},t.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(r,"a",r),r},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=18)}([function(e,t){var r;r=function(){return this}();try{r=r||Function("return this")()||(0,eval)("this")}catch(e){"object"==("undefined"==typeof window?"undefined":a(window))&&(r=window)}e.exports=r},function(e,t){function r(){throw new Error("setTimeout has not been defined")}function n(){throw new Error("clearTimeout has not been defined")}function i(e){if(c===setTimeout)return setTimeout(e,0);if((c===r||!c)&&setTimeout)return c=setTimeout,setTimeout(e,0);try{return c(e,0)}catch(t){try{return c.call(null,e,0)}catch(t){return c.call(this,e,0)}}}function a(e){if(d===clearTimeout)return clearTimeout(e);if((d===n||!d)&&clearTimeout)return d=clearTimeout,clearTimeout(e);try{return d(e)}catch(t){try{return d.call(null,e)}catch(t){return d.call(this,e)}}}function o(){g&&h&&(g=!1,h.length?p=h.concat(p):v=-1,p.length&&s())}function s(){if(!g){var e=i(o);g=!0;for(var t=p.length;t;){for(h=p,p=[];++v1)for(var r=1;r=n())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+n().toString(16)+" bytes");return 0|e}function g(e){return+e!=e&&(e=0),a.alloc(+e)}function v(e,t){if(a.isBuffer(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var r=e.length;if(0===r)return 0;for(var n=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return W(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return V(e).length;default:if(n)return W(e).length;t=(""+t).toLowerCase(),n=!0}}function y(e,t,r){var n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if(r>>>=0,t>>>=0,r<=t)return"";for(e||(e="utf8");;)switch(e){case"hex":return P(this,t,r);case"utf8":case"utf-8":return C(this,t,r);case"ascii":return D(this,t,r);case"latin1":case"binary":return I(this,t,r);case"base64":return L(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return O(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function m(e,t,r){var n=e[t];e[t]=e[r],e[r]=n}function b(e,t,r,n,i){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=i?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(i)return-1;r=e.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof t&&(t=a.from(t,n)),a.isBuffer(t))return 0===t.length?-1:_(e,t,r,n,i);if("number"==typeof t)return t&=255,a.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):_(e,[t],r,n,i);throw new TypeError("val must be string, number or Buffer")}function _(e,t,r,n,i){function a(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}var o=1,s=e.length,u=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;o=2,s/=2,u/=2,r/=2}var l;if(i){var c=-1;for(l=r;ls&&(r=s-u),l=r;l>=0;l--){for(var d=!0,f=0;fi&&(n=i):n=i;var a=t.length;if(a%2!=0)throw new TypeError("Invalid hex string");n>a/2&&(n=a/2);for(var o=0;o239?4:a>223?3:a>191?2:1;if(i+s<=r){var u,l,c,d;switch(s){case 1:a<128&&(o=a);break;case 2:128==(192&(u=e[i+1]))&&(d=(31&a)<<6|63&u)>127&&(o=d);break;case 3:u=e[i+1],l=e[i+2],128==(192&u)&&128==(192&l)&&(d=(15&a)<<12|(63&u)<<6|63&l)>2047&&(d<55296||d>57343)&&(o=d);break;case 4:u=e[i+1],l=e[i+2],c=e[i+3],128==(192&u)&&128==(192&l)&&128==(192&c)&&(d=(15&a)<<18|(63&u)<<12|(63&l)<<6|63&c)>65535&&d<1114112&&(o=d)}}null===o?(o=65533,s=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|1023&o),n.push(o),i+=s}return k(n)}function k(e){var t=e.length;if(t<=Z)return String.fromCharCode.apply(String,e);for(var r="",n=0;nn)&&(r=n);for(var i="",a=t;ar)throw new RangeError("Trying to access beyond buffer length")}function M(e,t,r,n,i,o){if(!a.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||te.length)throw new RangeError("Index out of range")}function F(e,t,r,n){t<0&&(t=65535+t+1);for(var i=0,a=Math.min(e.length-r,2);i>>8*(n?i:1-i)}function N(e,t,r,n){t<0&&(t=4294967295+t+1);for(var i=0,a=Math.min(e.length-r,4);i>>8*(n?i:3-i)&255}function U(e,t,r,n,i,a){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function B(e,t,r,n,i){return i||U(e,t,r,4,3.4028234663852886e38,-3.4028234663852886e38),J.write(e,t,r,n,23,4),r+4}function G(e,t,r,n,i){return i||U(e,t,r,8,1.7976931348623157e308,-1.7976931348623157e308),J.write(e,t,r,n,52,8),r+8}function j(e){if(e=K(e).replace(ee,""),e.length<2)return"";for(;e.length%4!=0;)e+="=";return e}function K(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}function H(e){return e<16?"0"+e.toString(16):e.toString(16)}function W(e,t){t=t||1/0;for(var r,n=e.length,i=null,a=[],o=0;o55295&&r<57344){if(!i){if(r>56319){(t-=3)>-1&&a.push(239,191,189);continue}if(o+1===n){(t-=3)>-1&&a.push(239,191,189);continue}i=r;continue}if(r<56320){(t-=3)>-1&&a.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(t-=3)>-1&&a.push(239,191,189);if(i=null,r<128){if((t-=1)<0)break;a.push(r)}else if(r<2048){if((t-=2)<0)break;a.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;a.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;a.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return a}function Y(e){for(var t=[],r=0;r>8,i=r%256,a.push(i),a.push(n);return a}function V(e){return Q.toByteArray(j(e))}function z(e,t,r,n){for(var i=0;i=t.length||i>=e.length);++i)t[i+r]=e[i];return i}function X(e){return e!==e}var Q=r(21),J=r(22),$=r(9);t.Buffer=a,t.SlowBuffer=g,t.INSPECT_MAX_BYTES=50,a.TYPED_ARRAY_SUPPORT=void 0!==e.TYPED_ARRAY_SUPPORT?e.TYPED_ARRAY_SUPPORT:function(){try{var e=new Uint8Array(1);return e.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===e.foo()&&"function"==typeof e.subarray&&0===e.subarray(1,1).byteLength}catch(e){return!1}}(),t.kMaxLength=n(),a.poolSize=8192,a._augment=function(e){return e.__proto__=a.prototype,e},a.from=function(e,t,r){return o(null,e,t,r)},a.TYPED_ARRAY_SUPPORT&&(a.prototype.__proto__=Uint8Array.prototype,a.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&a[Symbol.species]===a&&Object.defineProperty(a,Symbol.species,{value:null,configurable:!0})),a.alloc=function(e,t,r){return u(null,e,t,r)},a.allocUnsafe=function(e){return l(null,e)},a.allocUnsafeSlow=function(e){return l(null,e)},a.isBuffer=function(e){return!(null==e||!e._isBuffer)},a.compare=function(e,t){if(!a.isBuffer(e)||!a.isBuffer(t))throw new TypeError("Arguments must be Buffers");if(e===t)return 0;for(var r=e.length,n=t.length,i=0,o=Math.min(r,n);i0&&(e=this.toString("hex",0,r).match(/.{2}/g).join(" "),this.length>r&&(e+=" ... ")),""},a.prototype.compare=function(e,t,r,n,i){if(!a.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),t<0||r>e.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&t>=r)return 0;if(n>=i)return-1;if(t>=r)return 1;if(t>>>=0,r>>>=0,n>>>=0,i>>>=0,this===e)return 0;for(var o=i-n,s=r-t,u=Math.min(o,s),l=this.slice(n,i),c=e.slice(t,r),d=0;di)&&(r=i),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var a=!1;;)switch(n){case"hex":return E(this,e,t,r);case"utf8":case"utf-8":return w(this,e,t,r);case"ascii":return T(this,e,t,r);case"latin1":case"binary":return S(this,e,t,r);case"base64":return R(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A(this,e,t,r);default:if(a)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),a=!0}},a.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var Z=4096;a.prototype.slice=function(e,t){var r=this.length;e=~~e,t=void 0===t?r:~~t,e<0?(e+=r)<0&&(e=0):e>r&&(e=r),t<0?(t+=r)<0&&(t=0):t>r&&(t=r),t0&&(i*=256);)n+=this[e+--t]*i;return n},a.prototype.readUInt8=function(e,t){return t||x(e,1,this.length),this[e]},a.prototype.readUInt16LE=function(e,t){return t||x(e,2,this.length),this[e]|this[e+1]<<8},a.prototype.readUInt16BE=function(e,t){return t||x(e,2,this.length),this[e]<<8|this[e+1]},a.prototype.readUInt32LE=function(e,t){return t||x(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},a.prototype.readUInt32BE=function(e,t){return t||x(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},a.prototype.readIntLE=function(e,t,r){e|=0,t|=0,r||x(e,t,this.length);for(var n=this[e],i=1,a=0;++a=i&&(n-=Math.pow(2,8*t)),n},a.prototype.readIntBE=function(e,t,r){e|=0,t|=0,r||x(e,t,this.length);for(var n=t,i=1,a=this[e+--n];n>0&&(i*=256);)a+=this[e+--n]*i;return i*=128,a>=i&&(a-=Math.pow(2,8*t)),a},a.prototype.readInt8=function(e,t){return t||x(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},a.prototype.readInt16LE=function(e,t){t||x(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},a.prototype.readInt16BE=function(e,t){t||x(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},a.prototype.readInt32LE=function(e,t){return t||x(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},a.prototype.readInt32BE=function(e,t){return t||x(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},a.prototype.readFloatLE=function(e,t){return t||x(e,4,this.length),J.read(this,e,!0,23,4)},a.prototype.readFloatBE=function(e,t){return t||x(e,4,this.length),J.read(this,e,!1,23,4)},a.prototype.readDoubleLE=function(e,t){return t||x(e,8,this.length),J.read(this,e,!0,52,8)},a.prototype.readDoubleBE=function(e,t){return t||x(e,8,this.length),J.read(this,e,!1,52,8)},a.prototype.writeUIntLE=function(e,t,r,n){e=+e,t|=0,r|=0,n||M(this,e,t,r,Math.pow(2,8*r)-1,0);var i=1,a=0;for(this[t]=255&e;++a=0&&(a*=256);)this[t+i]=e/a&255;return t+r},a.prototype.writeUInt8=function(e,t,r){return e=+e,t|=0,r||M(this,e,t,1,255,0),a.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},a.prototype.writeUInt16LE=function(e,t,r){return e=+e,t|=0,r||M(this,e,t,2,65535,0),a.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):F(this,e,t,!0),t+2},a.prototype.writeUInt16BE=function(e,t,r){return e=+e,t|=0,r||M(this,e,t,2,65535,0),a.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):F(this,e,t,!1),t+2},a.prototype.writeUInt32LE=function(e,t,r){return e=+e,t|=0,r||M(this,e,t,4,4294967295,0),a.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):N(this,e,t,!0),t+4},a.prototype.writeUInt32BE=function(e,t,r){return e=+e,t|=0,r||M(this,e,t,4,4294967295,0),a.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):N(this,e,t,!1),t+4},a.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t|=0,!n){var i=Math.pow(2,8*r-1);M(this,e,t,r,i-1,-i)}var a=0,o=1,s=0;for(this[t]=255&e;++a>0)-s&255;return t+r},a.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t|=0,!n){var i=Math.pow(2,8*r-1);M(this,e,t,r,i-1,-i)}var a=r-1,o=1,s=0;for(this[t+a]=255&e;--a>=0&&(o*=256);)e<0&&0===s&&0!==this[t+a+1]&&(s=1),this[t+a]=(e/o>>0)-s&255;return t+r},a.prototype.writeInt8=function(e,t,r){return e=+e,t|=0,r||M(this,e,t,1,127,-128),a.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},a.prototype.writeInt16LE=function(e,t,r){return e=+e,t|=0,r||M(this,e,t,2,32767,-32768),a.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):F(this,e,t,!0),t+2},a.prototype.writeInt16BE=function(e,t,r){return e=+e,t|=0,r||M(this,e,t,2,32767,-32768),a.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):F(this,e,t,!1),t+2},a.prototype.writeInt32LE=function(e,t,r){return e=+e,t|=0,r||M(this,e,t,4,2147483647,-2147483648),a.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):N(this,e,t,!0),t+4},a.prototype.writeInt32BE=function(e,t,r){return e=+e,t|=0,r||M(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),a.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):N(this,e,t,!1),t+4},a.prototype.writeFloatLE=function(e,t,r){return B(this,e,t,!0,r)},a.prototype.writeFloatBE=function(e,t,r){return B(this,e,t,!1,r)},a.prototype.writeDoubleLE=function(e,t,r){return G(this,e,t,!0,r)},a.prototype.writeDoubleBE=function(e,t,r){return G(this,e,t,!1,r)},a.prototype.copy=function(e,t,r,n){if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t=0;--i)e[i+t]=this[i+r];else if(o<1e3||!a.TYPED_ARRAY_SUPPORT)for(i=0;i>>=0,r=void 0===r?this.length:r>>>0,e||(e=0);var o;if("number"==typeof e)for(o=t;o0&&this._events[e].length>i&&(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},r.prototype.on=r.prototype.addListener,r.prototype.once=function(e,t){function r(){this.removeListener(e,r),i||(i=!0,t.apply(this,arguments))}if(!n(t))throw TypeError("listener must be a function");var i=!1;return r.listener=t,this.on(e,r),this},r.prototype.removeListener=function(e,t){var r,i,a,s;if(!n(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(r=this._events[e],a=r.length,i=-1,r===t||n(r.listener)&&r.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(o(r)){for(s=a;s-- >0;)if(r[s]===t||r[s].listener&&r[s].listener===t){i=s;break}if(i<0)return this;1===r.length?(r.length=0,delete this._events[e]):r.splice(i,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},r.prototype.removeAllListeners=function(e){var t,r;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(r=this._events[e],n(r))this.removeListener(e,r);else if(r)for(;r.length;)this.removeListener(e,r[r.length-1]);return delete this._events[e],this},r.prototype.listeners=function(e){return this._events&&this._events[e]?n(this._events[e])?[this._events[e]]:this._events[e].slice():[]},r.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(n(t))return 1;if(t)return t.length}return 0},r.listenerCount=function(e,t){return e.listenerCount(t)}},function(e,t){var r={}.toString;e.exports=Array.isArray||function(e){return"[object Array]"==r.call(e)}},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,r){(function(t,n){function i(e){return N.from(e)}function a(e){return N.isBuffer(e)||e instanceof U}function o(e,t,r){if("function"==typeof e.prependListener)return e.prependListener(t,r);e._events&&e._events[t]?x(e._events[t])?e._events[t].unshift(r):e._events[t]=[r,e._events[t]]:e.on(t,r)}function s(e,t){O=O||r(3),e=e||{};var n=t instanceof O;this.objectMode=!!e.objectMode,n&&(this.objectMode=this.objectMode||!!e.readableObjectMode);var i=e.highWaterMark,a=e.readableHighWaterMark,o=this.objectMode?16:16384;this.highWaterMark=i||0===i?i:n&&(a||0===a)?a:o,this.highWaterMark=Math.floor(this.highWaterMark),this.buffer=new H,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.destroyed=!1,this.defaultEncoding=e.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,e.encoding&&(K||(K=r(15).StringDecoder),this.decoder=new K(e.encoding),this.encoding=e.encoding)}function u(e){if(O=O||r(3),!(this instanceof u))return new u(e);this._readableState=new s(e,this),this.readable=!0,e&&("function"==typeof e.read&&(this._read=e.read),"function"==typeof e.destroy&&(this._destroy=e.destroy)),F.call(this)}function l(e,t,r,n,a){var o=e._readableState;if(null===t)o.reading=!1,g(e,o);else{var s;a||(s=d(o,t)),s?e.emit("error",s):o.objectMode||t&&t.length>0?("string"==typeof t||o.objectMode||Object.getPrototypeOf(t)===N.prototype||(t=i(t)),n?o.endEmitted?e.emit("error",new Error("stream.unshift() after end event")):c(e,o,t,!0):o.ended?e.emit("error",new Error("stream.push() after EOF")):(o.reading=!1,o.decoder&&!r?(t=o.decoder.write(t),o.objectMode||0!==t.length?c(e,o,t,!1):m(e,o)):c(e,o,t,!1))):n||(o.reading=!1)}return f(o)}function c(e,t,r,n){t.flowing&&0===t.length&&!t.sync?(e.emit("data",r),e.read(0)):(t.length+=t.objectMode?1:r.length,n?t.buffer.unshift(r):t.buffer.push(r),t.needReadable&&v(e)),m(e,t)}function d(e,t){var r;return a(t)||"string"==typeof t||void 0===t||e.objectMode||(r=new TypeError("Invalid non-string/buffer chunk")),r}function f(e){return!e.ended&&(e.needReadable||e.length=q?e=q:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function p(e,t){return e<=0||0===t.length&&t.ended?0:t.objectMode?1:e!==e?t.flowing&&t.length?t.buffer.head.data.length:t.length:(e>t.highWaterMark&&(t.highWaterMark=h(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function g(e,t){if(!t.ended){if(t.decoder){var r=t.decoder.end();r&&r.length&&(t.buffer.push(r),t.length+=t.objectMode?1:r.length)}t.ended=!0,v(e)}}function v(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(j("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?P.nextTick(y,e):y(e))}function y(e){j("emit readable"),e.emit("readable"),S(e)}function m(e,t){t.readingMore||(t.readingMore=!0,P.nextTick(b,e,t))}function b(e,t){for(var r=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length=t.length?(r=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.head.data:t.buffer.concat(t.length),t.buffer.clear()):r=A(e,t.buffer,t.decoder),r}function A(e,t,r){var n;return ea.length?a.length:e;if(o===a.length?i+=a:i+=a.slice(0,e),0==(e-=o)){o===a.length?(++n,r.next?t.head=r.next:t.head=t.tail=null):(t.head=r,r.data=a.slice(o));break}++n}return t.length-=n,i}function C(e,t){var r=N.allocUnsafe(e),n=t.head,i=1;for(n.data.copy(r),e-=n.data.length;n=n.next;){var a=n.data,o=e>a.length?a.length:e;if(a.copy(r,r.length-e,0,o),0==(e-=o)){o===a.length?(++i,n.next?t.head=n.next:t.head=t.tail=null):(t.head=n,n.data=a.slice(o));break}++i}return t.length-=i,r}function k(e){var t=e._readableState;if(t.length>0)throw new Error('"endReadable()" called on non-empty stream');t.endEmitted||(t.ended=!0,P.nextTick(D,t,e))}function D(e,t){e.endEmitted||0!==e.length||(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function I(e,t){for(var r=0,n=e.length;r=t.highWaterMark||t.ended))return j("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?k(this):v(this),null;if(0===(e=p(e,t))&&t.ended)return 0===t.length&&k(this),null;var n=t.needReadable;j("need readable",n),(0===t.length||t.length-e0?R(e,t):null,null===i?(t.needReadable=!0,e=0):t.length-=e,0===t.length&&(t.ended||(t.needReadable=!0),r!==e&&t.ended&&k(this)),null!==i&&this.emit("data",i),i},u.prototype._read=function(e){this.emit("error",new Error("_read() is not implemented"))},u.prototype.pipe=function(e,t){function r(e,t){j("onunpipe"),e===f&&t&&!1===t.hasUnpiped&&(t.hasUnpiped=!0,a())}function i(){j("onend"),e.end()}function a(){j("cleanup"),e.removeListener("close",l),e.removeListener("finish",c),e.removeListener("drain",v),e.removeListener("error",u),e.removeListener("unpipe",r),f.removeListener("end",i),f.removeListener("end",d),f.removeListener("data",s),y=!0,!h.awaitDrain||e._writableState&&!e._writableState.needDrain||v()}function s(t){j("ondata"),m=!1,!1!==e.write(t)||m||((1===h.pipesCount&&h.pipes===e||h.pipesCount>1&&-1!==I(h.pipes,e))&&!y&&(j("false write response, pause",f._readableState.awaitDrain),f._readableState.awaitDrain++,m=!0),f.pause())}function u(t){j("onerror",t),d(),e.removeListener("error",u),0===M(e,"error")&&e.emit("error",t)}function l(){e.removeListener("finish",c),d()}function c(){j("onfinish"),e.removeListener("close",l),d()}function d(){j("unpipe"),f.unpipe(e)}var f=this,h=this._readableState;switch(h.pipesCount){case 0:h.pipes=e;break;case 1:h.pipes=[h.pipes,e];break;default:h.pipes.push(e)}h.pipesCount+=1,j("pipe count=%d opts=%j",h.pipesCount,t);var p=(!t||!1!==t.end)&&e!==n.stdout&&e!==n.stderr,g=p?i:d;h.endEmitted?P.nextTick(g):f.once("end",g),e.on("unpipe",r);var v=_(f);e.on("drain",v);var y=!1,m=!1;return f.on("data",s),o(e,"error",u),e.once("close",l),e.once("finish",c),e.emit("pipe",f),h.flowing||(j("pipe resume"),f.resume()),e},u.prototype.unpipe=function(e){var t=this._readableState,r={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,r),this);if(!e){var n=t.pipes,i=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var a=0;a-1?n:C.nextTick;c.WritableState=l;var I=r(6);I.inherits=r(2);var P={deprecate:r(33)},O=r(12),x=r(5).Buffer,M=i.Uint8Array||function(){},F=r(13);I.inherits(c,O),l.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(l.prototype,"buffer",{get:P.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(e){}}();var N;"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(N=Function.prototype[Symbol.hasInstance],Object.defineProperty(c,Symbol.hasInstance,{value:function(e){return!!N.call(this,e)||this===c&&e&&e._writableState instanceof l}})):N=function(e){return e instanceof this},c.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},c.prototype.write=function(e,t,r){var n=this._writableState,i=!1,a=!n.objectMode&&s(e);return a&&!x.isBuffer(e)&&(e=o(e)),"function"==typeof t&&(r=t,t=null),a?t="buffer":t||(t=n.defaultEncoding),"function"!=typeof r&&(r=u),n.ended?d(this,r):(a||f(this,n,e,r))&&(n.pendingcb++,i=p(this,n,a,e,t,r)),i},c.prototype.cork=function(){this._writableState.corked++},c.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,e.writing||e.corked||e.finished||e.bufferProcessing||!e.bufferedRequest||E(this,e))},c.prototype.setDefaultEncoding=function(e){if("string"==typeof e&&(e=e.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(c.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),c.prototype._write=function(e,t,r){r(new Error("_write() is not implemented"))},c.prototype._writev=null,c.prototype.end=function(e,t,r){var n=this._writableState;"function"==typeof e?(r=e,e=null,t=null):"function"==typeof t&&(r=t,t=null),null!==e&&void 0!==e&&this.write(e,t),n.corked&&(n.corked=1,this.uncork()),n.ending||n.finished||A(this,n,r)},Object.defineProperty(c.prototype,"destroyed",{get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),c.prototype.destroy=F.destroy,c.prototype._undestroy=F.undestroy,c.prototype._destroy=function(e,t){this.end(),t(e)}}).call(t,r(1),r(31).setImmediate,r(0))},function(e,t,r){function n(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}function i(e){var t=n(e);if("string"!=typeof t&&(m.isEncoding===b||!b(e)))throw new Error("Unknown encoding: "+e);return t||e}function a(e){this.encoding=i(e);var t;switch(this.encoding){case"utf16le":this.text=f,this.end=h,t=4;break;case"utf8":this.fillLast=l,t=4;break;case"base64":this.text=p,this.end=g,t=3;break;default:return this.write=v,void(this.end=y)}this.lastNeed=0,this.lastTotal=0,this.lastChar=m.allocUnsafe(t)}function o(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function s(e,t,r){var n=t.length-1;if(n=0?(i>0&&(e.lastNeed=i-1),i):--n=0?(i>0&&(e.lastNeed=i-2),i):--n=0?(i>0&&(2===i?i=0:e.lastNeed=i-3),i):0)}function u(e,t,r){if(128!=(192&t[0]))return e.lastNeed=0,"�";if(e.lastNeed>1&&t.length>1){if(128!=(192&t[1]))return e.lastNeed=1,"�";if(e.lastNeed>2&&t.length>2&&128!=(192&t[2]))return e.lastNeed=2,"�"}}function l(e){var t=this.lastTotal-this.lastNeed,r=u(this,e,t);return void 0!==r?r:this.lastNeed<=e.length?(e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,t,0,e.length),void(this.lastNeed-=e.length))}function c(e,t){var r=s(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=r;var n=e.length-(r-this.lastNeed);return e.copy(this.lastChar,0,n),e.toString("utf8",t,n)}function d(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+"�":t}function f(e,t){if((e.length-t)%2==0){var r=e.toString("utf16le",t);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function h(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,r)}return t}function p(e,t){var r=(e.length-t)%3;return 0===r?e.toString("base64",t):(this.lastNeed=3-r,this.lastTotal=3,1===r?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-r))}function g(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function v(e){return e.toString(this.encoding)}function y(e){return e&&e.length?this.write(e):""}var m=r(5).Buffer,b=m.isEncoding||function(e){switch((e=""+e)&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};t.StringDecoder=a,a.prototype.write=function(e){if(0===e.length)return"";var t,r;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r0;){var e=t.msgQueue.shift();t.emit(e.event,e)}};e.once("connect",n),e.on("data",function(e){if("string"==typeof e){var r=JSON.parse(e);if(!t.connected)return void t.msgQueue.push(r);switch(r.event){case g.default.DC_PONG:t._handlePongMsg();break;case g.default.DC_PING:t.sendJson({event:g.default.DC_PONG});break;case g.default.DC_PIECE:t._prepareForBinary(r.attachments,r.url,r.sn,r.size),t.emit(r.event,r);break;case g.default.DC_PIECE_NOT_FOUND:window.clearTimeout(t.requestTimeout),t.requestTimeout=null,t.emit(r.event,r);break;case g.default.DC_REQUEST:t._handleRequestMsg(r);break;case g.default.DC_PIECE_ACK:t._handlePieceAck(),t.emit(r.event,r);break;default:t.emit(r.event,r)}}else t.bufArr.push(e),0==--t.remainAttachments&&(window.clearTimeout(t.requestTimeout),t.requestTimeout=null,t.sendJson({event:g.default.DC_PIECE_ACK,sn:t.bufSN,url:t.bufUrl,size:t.expectedSize}),t._handleBinaryData())}),e.once("close",function(){t.emit(g.default.DC_CLOSE)})}},{key:"sendJson",value:function(e){this.send(JSON.stringify(e))}},{key:"send",value:function(e){this._datachannel&&this._datachannel.connected&&this._datachannel.send(e)}},{key:"sendBitField",value:function(e){this.sendJson({event:g.default.DC_BITFIELD,field:e})}},{key:"sendBuffer",value:function(e,t,r){this.uploading=!0,this.uploadTimeout=window.setTimeout(this._uploadtimeout.bind(this),1e3*this.config.dcUploadTimeout);var n=r.byteLength,i=this.config.packetSize,a=0,o=0;n%i==0?o=n/i:(o=Math.floor(n/i)+1,a=n%i);var s={event:g.default.DC_PIECE,attachments:o,url:t,sn:e,size:n};this.sendJson(s);for(var l=u(r,i,o,a),c=0;c1&&void 0!==arguments[1]&&arguments[1],r={event:g.default.DC_REQUEST,url:e,urgent:t};this.downloading=!0,this.sendJson(r),t&&(this.requestTimeout=window.setTimeout(this._loadtimeout.bind(this),1e3*this.config.dcRequestTimeout))}},{key:"requestDataBySN",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r={event:g.default.DC_REQUEST,sn:e,urgent:t};this.downloading=!0,this.sendJson(r),t&&(this.requestTimeout=window.setTimeout(this._loadtimeout.bind(this),1e3*this.config.dcRequestTimeout))}},{key:"close",value:function(){this.destroy()}},{key:"receiveSignal",value:function(e){this._datachannel.signal(e)}},{key:"destroy",value:function(){window.clearInterval(this.adjustSRInterval),window.clearInterval(this.pinger),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(g.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(g.default.DC_REQUEST,{sn:e})}}},{key:"_prepareForBinary",value:function(e,t,r,n){this.bufArr=[],this.remainAttachments=e,this.bufUrl=t,this.bufSN=r,this.expectedSize=n}},{key:"_handleBinaryData",value:function(){var e=v.concat(this.bufArr);e.byteLength==this.expectedSize&&this.emit(g.default.DC_RESPONSE,{url:this.bufUrl,sn:this.bufSN,data:e}),this.bufUrl="",this.bufArr=[],this.expectedSize=-1,this.downloading=!1}},{key:"_adjustStreamingRate",value:function(e){var t=this,r=0;return this.adjustSRInterval=window.setInterval(function(){t.streamingRate=Math.round(8*r/e),r=0},1e3*e),function(e){r+=e}}},{key:"_loadtimeout",value:function(){var e=this.engine.logger;if(e.warn("datachannel timeout while downloading from "+this.remotePeerId),this.emit(g.default.DC_TIMEOUT),this.requestTimeout=null,this.downloading=!1,++this.miss>=this.config.dcTolerance){var t={event:g.default.DC_CLOSE};this.sendJson(t),e.warn("datachannel download miss reach dcTolerance, close "+this.remotePeerId),this.emit(g.default.DC_ERROR)}}},{key:"_uploadtimeout",value:function(){this.engine.logger.warn("datachannel timeout while uploading to "+this.remotePeerId),this.uploading=!1,this.rcvdReqQueue=[]}},{key:"_sendPing",value:function(){var e=this;this.ping=performance.now();for(var t=0;t0){var t=0,r=!0,n=!1,i=void 0;try{for(var a,o=e.delays[Symbol.iterator]();!(r=(a=o.next()).done);r=!0)t+=a.value}catch(e){n=!0,i=e}finally{try{!r&&o.return&&o.return()}finally{if(n)throw i}}e.delay=t/e.delays.length,e.delays=[]}},100)}},{key:"_handlePongMsg",value:function(){var e=performance.now()-this.ping;this.delays.push(e)}},{key:"setupStats",value:function(){var e=this,t=this.engine.logger;setInterval(function(){e._datachannel.getStats(function(e,r){t.warn("reports: "+JSON.stringify(r,null,1))})},1e4)}},{key:"isAvailable",get:function(){this.engine.logger;return!1===this.downloading&&!1===this.choked}}]),t}(h.default);t.default=y,e.exports=t.default},function(e,t,r){(function(t){function n(e){var t=this;if(!(t instanceof n))return new n(e);if(t._id=c(4).toString("hex").slice(0,7),t._debug("new peer %o",e),e=Object.assign({allowHalfOpen:!1},e),d.Duplex.call(t,e),t.channelName=e.initiator?e.channelName||c(20).toString("hex"):null,t._isChromium="undefined"!=typeof window&&!!window.webkitRTCPeerConnection,t.initiator=e.initiator||!1,t.channelConfig=e.channelConfig||n.channelConfig,t.config=e.config||n.config,t.constraints=t._transformConstraints(e.constraints||n.constraints),t.offerConstraints=t._transformConstraints(e.offerConstraints||{}),t.answerConstraints=t._transformConstraints(e.answerConstraints||{}),t.reconnectTimer=e.reconnectTimer||!1,t.sdpTransform=e.sdpTransform||function(e){return e},t.stream=e.stream||!1,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"===o(e.wrtc)?e.wrtc:u(),!t._wrtc)throw"undefined"==typeof window?new Error("No WebRTC support: Specify `opts.wrtc` option in this environment"):new Error("No WebRTC support: Not a supported browser");if(t._pcReady=!1,t._channelReady=!1,t._iceComplete=!1,t._channel=null,t._pendingCandidates=[],t._previousStreams=[],t._chunk=null,t._cb=null,t._interval=null,t._reconnectTimeout=null,t._pc=new t._wrtc.RTCPeerConnection(t.config,t.constraints),t._isWrtc=Array.isArray(t._pc.RTCIceConnectionStates),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){var r=!1;t._pc.onnegotiationneeded=function(){r||t._createOffer(),r=!0},t._setupData({channel:t._pc.createDataChannel(t.channelName,t.channelConfig)})}else t._pc.ondatachannel=function(e){t._setupData(e)};"addTrack"in t._pc?(t.stream&&t.stream.getTracks().forEach(function(e){t._pc.addTrack(e,t.stream)}),t._pc.ontrack=function(e){t._onTrack(e)}):(t.stream&&t._pc.addStream(t.stream),t._pc.onaddstream=function(e){t._onAddStream(e)}),t.initiator&&t._isWrtc&&t._pc.onnegotiationneeded(),t._onFinishBound=function(){t._onFinish()},t.once("finish",t._onFinishBound)}function i(){}var o="function"==typeof Symbol&&"symbol"==a(Symbol.iterator)?function(e){return void 0===e?"undefined":a(e)}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":void 0===e?"undefined":a(e)};e.exports=n;var s=r(23)("simple-channel"),u=r(10),l=r(2),c=r(26),d=r(27);l(n,d.Duplex),n.WEBRTC_SUPPORT=!!u(),n.config={iceServers:[{urls:"stun:stun.l.google.com:19302"}]},n.constraints={},n.channelConfig={},Object.defineProperty(n.prototype,"bufferSize",{get:function(){var e=this;return e._channel&&e._channel.bufferedAmount||0}}),n.prototype.address=function(){var e=this;return{port:e.localPort,family:"IPv4",address:e.localAddress}},n.prototype.signal=function(e){var t=this;if(t.destroyed)throw new Error("cannot signal after peer is destroyed");if("string"==typeof e)try{e=JSON.parse(e)}catch(t){e={}}t._debug("signal()"),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(e)}),e.sdp||e.candidate||t.destroy(new Error("signal() called with invalid signal data"))},n.prototype._addIceCandidate=function(e){var t=this;try{t._pc.addIceCandidate(new t._wrtc.RTCIceCandidate(e),i,function(e){t.destroy(e)})}catch(e){t.destroy(new Error("error adding candidate: "+e.message))}},n.prototype.send=function(e){this._channel.send(e)},n.prototype.destroy=function(e){this._destroy(e,function(){})},n.prototype._destroy=function(e,t){var r=this;if(!r.destroyed){if(r._debug("destroy (error: %s)",e&&(e.message||e)),r.readable=r.writable=!1,r._readableState.ended||r.push(null),r._writableState.finished||r.end(),r.destroyed=!0,r.connected=!1,r._pcReady=!1,r._channelReady=!1,r._previousStreams=null,clearInterval(r._interval),clearTimeout(r._reconnectTimeout),r._interval=null,r._reconnectTimeout=null,r._chunk=null,r._cb=null,r._onFinishBound&&r.removeListener("finish",r._onFinishBound),r._onFinishBound=null,r._pc){try{r._pc.close()}catch(e){}r._pc.oniceconnectionstatechange=null,r._pc.onicegatheringstatechange=null,r._pc.onsignalingstatechange=null,r._pc.onicecandidate=null,"addTrack"in r._pc?r._pc.ontrack=null:r._pc.onaddstream=null,r._pc.onnegotiationneeded=null,r._pc.ondatachannel=null}if(r._channel){try{r._channel.close()}catch(e){}r._channel.onmessage=null,r._channel.onopen=null,r._channel.onclose=null,r._channel.onerror=null}r._pc=null,r._channel=null,e&&r.emit("error",e),r.emit("close"),t()}},n.prototype._setupData=function(e){var t=this;if(!e.channel)return t.destroy(new Error("Data channel event is missing `channel` property"));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(e)}},n.prototype._read=function(){},n.prototype._write=function(e,t,r){var n=this;if(n.destroyed)return r(new Error("cannot write after peer is destroyed"));if(n.connected){try{n.send(e)}catch(e){return n.destroy(e)}n._channel.bufferedAmount>65536?(n._debug("start backpressure: bufferedAmount %d",n._channel.bufferedAmount),n._cb=r):r(null)}else n._debug("write before connect"),n._chunk=e,n._cb=r},n.prototype._onFinish=function(){function e(){setTimeout(function(){t.destroy()},1e3)}var t=this;t.destroyed||(t.connected?e():t.once("connect",e))},n.prototype._createOffer=function(){var e=this;e.destroyed||e._pc.createOffer(function(t){function r(){e.destroyed||(e.trickle||e._iceComplete?i():e.once("_iceComplete",i))}function n(t){e.destroy(t)}function i(){var r=e._pc.localDescription||t;e._debug("signal"),e.emit("signal",{type:r.type,sdp:r.sdp})}e.destroyed||(t.sdp=e.sdpTransform(t.sdp),e._pc.setLocalDescription(t,r,n))},function(t){e.destroy(t)},e.offerConstraints)},n.prototype._createAnswer=function(){var e=this;e.destroyed||e._pc.createAnswer(function(t){function r(){e.destroyed||(e.trickle||e._iceComplete?i():e.once("_iceComplete",i))}function n(t){e.destroy(t)}function i(){var r=e._pc.localDescription||t;e._debug("signal"),e.emit("signal",{type:r.type,sdp:r.sdp})}e.destroyed||(t.sdp=e.sdpTransform(t.sdp),e._pc.setLocalDescription(t,r,n))},function(t){e.destroy(t)},e.answerConstraints)},n.prototype._onIceStateChange=function(){var e=this;if(!e.destroyed){var t=e._pc.iceConnectionState,r=e._pc.iceGatheringState;e._debug("iceStateChange (connection: %s) (gathering: %s)",t,r),e.emit("iceStateChange",t,r),"connected"!==t&&"completed"!==t||(clearTimeout(e._reconnectTimeout),e._pcReady=!0,e._maybeReady()),"disconnected"===t&&(e.reconnectTimer?(clearTimeout(e._reconnectTimeout),e._reconnectTimeout=setTimeout(function(){e.destroy()},e.reconnectTimer)):e.destroy()),"failed"===t&&e.destroy(new Error("Ice connection failed.")),"closed"===t&&e.destroy()}},n.prototype.getStats=function(e){var t=this;0===t._pc.getStats.length?t._pc.getStats().then(function(t){var r=[];t.forEach(function(e){r.push(e)}),e(null,r)},function(t){e(t)}):t._isReactNativeWebrtc?t._pc.getStats(null,function(t){var r=[];t.forEach(function(e){r.push(e)}),e(null,r)},function(t){e(t)}):t._pc.getStats.length>0?t._pc.getStats(function(r){if(!t.destroyed){var n=[];r.result().forEach(function(e){var t={};e.names().forEach(function(r){t[r]=e.stat(r)}),t.id=e.id,t.type=e.type,t.timestamp=e.timestamp,n.push(t)}),e(null,n)}},function(t){e(t)}):e(null,[])},n.prototype._maybeReady=function(){function e(){t.destroyed||t.getStats(function(r,n){function i(e){u=!0;var r=o[e.localCandidateId];r&&r.ip?(t.localAddress=r.ip,t.localPort=Number(r.port)):r&&r.ipAddress?(t.localAddress=r.ipAddress,t.localPort=Number(r.portNumber)):"string"==typeof e.googLocalAddress&&(r=e.googLocalAddress.split(":"),t.localAddress=r[0],t.localPort=Number(r[1]));var n=a[e.remoteCandidateId];n&&n.ip?(t.remoteAddress=n.ip,t.remotePort=Number(n.port)):n&&n.ipAddress?(t.remoteAddress=n.ipAddress,t.remotePort=Number(n.portNumber)):"string"==typeof e.googRemoteAddress&&(n=e.googRemoteAddress.split(":"),t.remoteAddress=n[0],t.remotePort=Number(n[1])),t.remoteFamily="IPv4",t._debug("connect local: %s:%s remote: %s:%s",t.localAddress,t.localPort,t.remoteAddress,t.remotePort)}if(!t.destroyed){r&&(n=[]);var a={},o={},s={},u=!1;if(n.forEach(function(e){"remotecandidate"!==e.type&&"remote-candidate"!==e.type||(a[e.id]=e),"localcandidate"!==e.type&&"local-candidate"!==e.type||(o[e.id]=e),"candidatepair"!==e.type&&"candidate-pair"!==e.type||(s[e.id]=e)}),n.forEach(function(e){"transport"===e.type&&i(s[e.selectedCandidatePairId]),("googCandidatePair"===e.type&&"true"===e.googActiveConnection||("candidatepair"===e.type||"candidate-pair"===e.type)&&e.selected)&&i(e)}),!(u||Object.keys(s).length&&!Object.keys(o).length))return void setTimeout(e,100);if(t._connecting=!1,t.connected=!0,t._chunk){try{t.send(t._chunk)}catch(r){return t.destroy(r)}t._chunk=null,t._debug('sent chunk from "write before connect"');var l=t._cb;t._cb=null,l(null)}"number"!=typeof t._channel.bufferedAmountLowThreshold&&(t._interval=setInterval(function(){t._onInterval()},150),t._interval.unref&&t._interval.unref()),t._debug("connect"),t.emit("connect")}})}var t=this;t._debug("maybeReady pc %s channel %s",t._pcReady,t._channelReady),!t.connected&&!t._connecting&&t._pcReady&&t._channelReady&&(t._connecting=!0,e())},n.prototype._onInterval=function(){var e=this;!e._cb||!e._channel||e._channel.bufferedAmount>65536||e._onChannelBufferedAmountLow()},n.prototype._onSignalingStateChange=function(){var e=this;e.destroyed||(e._debug("signalingStateChange %s",e._pc.signalingState),e.emit("signalingStateChange",e._pc.signalingState))},n.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")))},n.prototype._onChannelMessage=function(e){var r=this;if(!r.destroyed){var n=e.data;n instanceof ArrayBuffer&&(n=t.from(n)),r.push(n)}},n.prototype._onChannelBufferedAmountLow=function(){var e=this;if(!e.destroyed&&e._cb){e._debug("ending backpressure: bufferedAmount %d",e._channel.bufferedAmount);var t=e._cb;e._cb=null,t(null)}},n.prototype._onChannelOpen=function(){var e=this;e.connected||e.destroyed||(e._debug("on channel open"),e._channelReady=!0,e._maybeReady())},n.prototype._onChannelClose=function(){var e=this;e.destroyed||(e._debug("on channel close"),e.destroy())},n.prototype._onAddStream=function(e){var t=this;t.destroyed||(t._debug("on add stream"),t.emit("stream",e.stream))},n.prototype._onTrack=function(e){var t=this;if(!t.destroyed){t._debug("on track");var r=e.streams[0].id;-1===t._previousStreams.indexOf(r)&&(t._previousStreams.push(r),t.emit("stream",e.streams[0]))}},n.prototype._debug=function(){var e=this,t=[].slice.call(arguments);t[0]="["+e._id+"] "+t[0],s.apply(null,t)},n.prototype._transformConstraints=function(e){var t=this;if(0===Object.keys(e).length)return e;if((e.mandatory||e.optional)&&!t._isChromium){var r=Object.assign({},e.optional,e.mandatory);return void 0!==r.OfferToReceiveVideo&&(r.offerToReceiveVideo=r.OfferToReceiveVideo,delete r.OfferToReceiveVideo),void 0!==r.OfferToReceiveAudio&&(r.offerToReceiveAudio=r.OfferToReceiveAudio,delete r.OfferToReceiveAudio),r}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})}}).call(t,r(4).Buffer)},function(e,t,r){function n(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function i(e){var t=n(e),r=t[0],i=t[1];return 3*(r+i)/4-i}function a(e,t,r){return 3*(t+r)/4-r}function o(e){for(var t,r=n(e),i=r[0],o=r[1],s=new f(a(e,i,o)),u=0,l=o>0?i-4:i,c=0;c>16&255,s[u++]=t>>8&255,s[u++]=255&t;return 2===o&&(t=d[e.charCodeAt(c)]<<2|d[e.charCodeAt(c+1)]>>4,s[u++]=255&t),1===o&&(t=d[e.charCodeAt(c)]<<10|d[e.charCodeAt(c+1)]<<4|d[e.charCodeAt(c+2)]>>2,s[u++]=t>>8&255,s[u++]=255&t),s}function s(e){return c[e>>18&63]+c[e>>12&63]+c[e>>6&63]+c[63&e]}function u(e,t,r){for(var n,i=[],a=t;ao?o:a+16383));return 1===n?(t=e[r-1],i.push(c[t>>2]+c[t<<4&63]+"==")):2===n&&(t=(e[r-2]<<8)+e[r-1],i.push(c[t>>10]+c[t>>4&63]+c[t<<2&63]+"=")),i.join("")}t.byteLength=i,t.toByteArray=o,t.fromByteArray=l;for(var c=[],d=[],f="undefined"!=typeof Uint8Array?Uint8Array:Array,h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",p=0,g=h.length;p>1,c=-7,d=r?i-1:0,f=r?-1:1,h=e[t+d];for(d+=f,a=h&(1<<-c)-1,h>>=-c,c+=s;c>0;a=256*a+e[t+d],d+=f,c-=8);for(o=a&(1<<-c)-1,a>>=-c,c+=n;c>0;o=256*o+e[t+d],d+=f,c-=8);if(0===a)a=1-l;else{if(a===u)return o?NaN:1/0*(h?-1:1);o+=Math.pow(2,n),a-=l}return(h?-1:1)*o*Math.pow(2,a-n)},t.write=function(e,t,r,n,i,a){var o,s,u,l=8*a-i-1,c=(1<>1,f=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,h=n?0:a-1,p=n?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,o=c):(o=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-o))<1&&(o--,u*=2),t+=o+d>=1?f/u:f*Math.pow(2,1-d),t*u>=2&&(o++,u/=2),o+d>=c?(s=0,o=c):o+d>=1?(s=(t*u-1)*Math.pow(2,i),o+=d):(s=t*Math.pow(2,d-1)*Math.pow(2,i),o=0));i>=8;e[r+h]=255&s,h+=p,s/=256,i-=8);for(o=o<0;e[r+h]=255&o,h+=p,o/=256,l-=8);e[r+h-p]|=128*g}},function(e,t,r){(function(n){function i(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type)||("undefined"==typeof navigator||!navigator.userAgent||!navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))}function o(e){var r=this.useColors;if(e[0]=(r?"%c":"")+this.namespace+(r?" %c":" ")+e[0]+(r?"%c ":" ")+"+"+t.humanize(this.diff),r){var n="color: "+this.color;e.splice(1,0,n,"color: inherit");var i=0,a=0;e[0].replace(/%[a-zA-Z%]/g,function(e){"%%"!==e&&(i++,"%c"===e&&(a=i))}),e.splice(a,0,n)}}function s(){return"object"==("undefined"==typeof console?"undefined":a(console))&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}function u(e){try{null==e?t.storage.removeItem("debug"):t.storage.debug=e}catch(e){}}function l(){var e;try{e=t.storage.debug}catch(e){}return!e&&void 0!==n&&"env"in n&&(e=n.env.DEBUG),e}t=e.exports=r(24),t.log=s,t.formatArgs=o,t.save=u,t.load=l,t.useColors=i,t.storage="undefined"!=typeof chrome&&void 0!==chrome.storage?chrome.storage.local:function(){try{return window.localStorage}catch(e){}}(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.formatters.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}},t.enable(l())}).call(t,r(1))},function(e,t,r){function n(e){var r,n=0;for(r in e)n=(n<<5)-n+e.charCodeAt(r),n|=0;return t.colors[Math.abs(n)%t.colors.length]}function i(e){function r(){if(r.enabled){var e=r,n=+new Date,a=n-(i||n);e.diff=a,e.prev=i,e.curr=n,i=n;for(var o=new Array(arguments.length),s=0;s100)){var t=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(e);if(t){var r=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return r*d;case"days":case"day":case"d":return r*c;case"hours":case"hour":case"hrs":case"hr":case"h":return r*l;case"minutes":case"minute":case"mins":case"min":case"m":return r*u;case"seconds":case"second":case"secs":case"sec":case"s":return r*s;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}function n(e){return e>=c?Math.round(e/c)+"d":e>=l?Math.round(e/l)+"h":e>=u?Math.round(e/u)+"m":e>=s?Math.round(e/s)+"s":e+"ms"}function i(e){return o(e,c,"day")||o(e,l,"hour")||o(e,u,"minute")||o(e,s,"second")||e+" ms"}function o(e,t,r){if(!(e0)return r(e);if("number"===o&&!1===isNaN(e))return t.long?i(e):n(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},function(e,t,r){(function(t,n){function i(){throw new Error("Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11")}function a(e,r){if(e>65536)throw new Error("requested too many random bytes");var i=new t.Uint8Array(e);e>0&&s.getRandomValues(i);var a=o.from(i.buffer);return"function"==typeof r?n.nextTick(function(){r(null,a)}):a}var o=r(5).Buffer,s=t.crypto||t.msCrypto;s&&s.getRandomValues?e.exports=a:e.exports=i}).call(t,r(0),r(1))},function(e,t,r){t=e.exports=r(11),t.Stream=t,t.Readable=t,t.Writable=r(14),t.Duplex=r(3),t.Transform=r(16),t.PassThrough=r(34)},function(e,t){},function(e,t,r){function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t,r){e.copy(t,r)}var a=r(5).Buffer,o=r(30);e.exports=function(){function e(){n(this,e),this.head=null,this.tail=null,this.length=0}return e.prototype.push=function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length},e.prototype.unshift=function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length},e.prototype.shift=function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}},e.prototype.clear=function(){this.head=this.tail=null,this.length=0},e.prototype.join=function(e){if(0===this.length)return"";for(var t=this.head,r=""+t.data;t=t.next;)r+=e+t.data;return r},e.prototype.concat=function(e){if(0===this.length)return a.alloc(0);if(1===this.length)return this.head.data;for(var t=a.allocUnsafe(e>>>0),r=this.head,n=0;r;)i(r.data,t,n),n+=r.data.length,r=r.next;return t},e}(),o&&o.inspect&&o.inspect.custom&&(e.exports.prototype[o.inspect.custom]=function(){var e=o.inspect({length:this.length});return this.constructor.name+" "+e})},function(e,t){},function(e,t,r){(function(e){function n(e,t){this._id=e,this._clearFn=t}var i=void 0!==e&&e||"undefined"!=typeof self&&self||window,a=Function.prototype.apply;t.setTimeout=function(){return new n(a.call(setTimeout,i,arguments),clearTimeout)},t.setInterval=function(){return new n(a.call(setInterval,i,arguments),clearInterval)},t.clearTimeout=t.clearInterval=function(e){e&&e.close()},n.prototype.unref=n.prototype.ref=function(){},n.prototype.close=function(){this._clearFn.call(i,this._id)},t.enroll=function(e,t){clearTimeout(e._idleTimeoutId),e._idleTimeout=t},t.unenroll=function(e){clearTimeout(e._idleTimeoutId),e._idleTimeout=-1},t._unrefActive=t.active=function(e){clearTimeout(e._idleTimeoutId);var t=e._idleTimeout;t>=0&&(e._idleTimeoutId=setTimeout(function(){e._onTimeout&&e._onTimeout()},t))},r(32),t.setImmediate="undefined"!=typeof self&&self.setImmediate||void 0!==e&&e.setImmediate||this&&this.setImmediate,t.clearImmediate="undefined"!=typeof self&&self.clearImmediate||void 0!==e&&e.clearImmediate||this&&this.clearImmediate}).call(t,r(0))},function(e,t,r){(function(e,t){!function(e,r){function n(e){"function"!=typeof e&&(e=new Function(""+e));for(var t=new Array(arguments.length-1),r=0;r0&&void 0!==arguments[0]?arguments[0]:10,r=this.engine.logger;this.heartbeater=window.setInterval(function(){fetch(e.statsURL,{headers:e._requestHeader,method:"POST",body:JSON.stringify(e._makeStatsBody())}).then(function(t){t.ok&&(r.info("sucessfully report stats"),e.httpDownloaded=0,e.p2pDownloaded=0,e.conns=0,e.failConns=0,e.errsFragLoad=0,e.errsBufStalled=0,e.errsInternalExpt=0)}).catch(function(e){r.error("btStats error "+e)})},1e3*t)}},{key:"btGetPeers",value:function(){var e=this,t=this.engine.logger;return new Promise(function(r,n){fetch(e.getPeersURL,{headers:e._requestHeader,method:"POST"}).then(function(e){return e.json()}).then(function(e){-1===e.ret?n(e.data.msg):r(e.data)}).catch(function(e){t.error("btGetPeers error "+e),n(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],r=Math.round(e.total/1024);t?(this.p2pDownloaded+=r,this.totalP2PDownloaded+=r):(this.httpDownloaded+=r,this.totalHTTPDownloaded+=r),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._emitStats()}},{key:"destroy",value:function(){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,errsFragLoad:this.errsFragLoad,errsBufStalled:this.errsBufStalled,errsInternalExpt:this.errsInternalExpt,http:Math.round(this.httpDownloaded),p2p:Math.round(this.p2pDownloaded)};return Object.keys(e).forEach(function(t){0===e[t]&&delete e[t]}),e}},{key:"_requestHeader",get:function(){return{}}}]),e}();t.default=u,e.exports=t.default},function(e,t,r){var n;"function"==typeof Symbol&&Symbol.iterator,function(i){function a(e,t){var r=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(r>>16)<<16|65535&r}function o(e,t){return e<>>32-t}function s(e,t,r,n,i,s){return a(o(a(a(t,e),a(n,s)),i),r)}function u(e,t,r,n,i,a,o){return s(t&r|~t&n,e,t,i,a,o)}function l(e,t,r,n,i,a,o){return s(t&n|r&~n,e,t,i,a,o)}function c(e,t,r,n,i,a,o){return s(t^r^n,e,t,i,a,o)}function d(e,t,r,n,i,a,o){return s(r^(t|~n),e,t,i,a,o)}function f(e,t){e[t>>5]|=128<>>9<<4)]=t;var r,n,i,o,s,f=1732584193,h=-271733879,p=-1732584194,g=271733878;for(r=0;r>5]>>>t%32&255);return r}function p(e){var t,r=[];for(r[(e.length>>2)-1]=void 0,t=0;t>5]|=(255&e.charCodeAt(t/8))<16&&(i=f(i,8*e.length)),r=0;r<16;r+=1)a[r]=909522486^i[r],o[r]=1549556828^i[r];return n=f(a.concat(p(t)),512+8*t.length),h(f(o.concat(n),640))}function y(e){var t,r,n="0123456789abcdef",i="";for(r=0;r>>4&15)+n.charAt(15&t);return i}function m(e){return unescape(encodeURIComponent(e))}function b(e){return g(m(e))}function _(e){return y(b(e))}function E(e,t){return v(m(e),m(t))}function w(e,t){return y(E(e,t))}function T(e,t,r){return t?r?E(t,e):w(t,e):r?b(e):_(e)}void 0!==(n=function(){return T}.call(t,r,t,e))&&(e.exports=n)}()},function(e,t,r){function n(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:20,n=null,i=!1;return function(){if(arguments.length>0&&void 0!==arguments[0]&&arguments[0])return void window.clearTimeout(n);i||(i=!0,n=setTimeout(function(){e.call(t),i=!1,n=null},1e3*r))}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=n,e.exports=t.default}])})}).call(t,r(10)(e))},function(e,t,r){"use strict";function n(e){return arguments.length>1&&void 0!==arguments[1]&&arguments[1]?e:e.split("?")[0]}function i(e){arguments.length>1&&void 0!==arguments[1]&&arguments[1];return""+u.default.parseURL(e).path.split(".")[0]}function a(){var e=-1,t="";return function(r,n){n=n.split("?")[0];var i=!0;return e!==r&&t===n&&(i=!1),e=r,t=n,i}}function o(){return!0}Object.defineProperty(t,"__esModule",{value:!0}),t.handleTSUrl=n,t.defaultChannelId=i,t.tsPathChecker=a,t.noop=o;var s=r(4),u=function(e){return e&&e.__esModule?e:{default:e}}(s)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.config=t.FragLoader=t.Tracker=void 0;var i=r(8),a=n(i),o=r(12),s=n(o),u={announce:"https://api.cdnbye.com/v1",urgentOffset:3};t.Tracker=a.default,t.FragLoader=s.default,t.config=u},function(e,t,r){!function(t){var r=/^((?:[a-zA-Z0-9+\-.]+:)?)(\/\/[^\/\;?#]*)?(.*?)??(;.*?)?(\?.*?)?(#.*?)?$/,n=/^([^\/;?#]*)(.*)$/,i=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/).*?(?=\/)/g,o={buildAbsoluteURL:function(e,t,r){if(r=r||{},e=e.trim(),!(t=t.trim())){if(!r.alwaysNormalize)return e;var i=o.parseURL(e);if(!i)throw new Error("Error trying to parse base URL.");return i.path=o.normalizePath(i.path),o.buildURLFromParts(i)}var a=o.parseURL(t);if(!a)throw new Error("Error trying to parse relative URL.");if(a.scheme)return r.alwaysNormalize?(a.path=o.normalizePath(a.path),o.buildURLFromParts(a)):t;var s=o.parseURL(e);if(!s)throw new Error("Error trying to parse base URL.");if(!s.netLoc&&s.path&&"/"!==s.path[0]){var u=n.exec(s.path);s.netLoc=u[1],s.path=u[2]}s.netLoc&&!s.path&&(s.path="/");var l={scheme:s.scheme,netLoc:a.netLoc,path:null,params:a.params,query:a.query,fragment:a.fragment};if(!a.netLoc&&(l.netLoc=s.netLoc,"/"!==a.path[0]))if(a.path){var c=s.path,d=c.substring(0,c.lastIndexOf("/")+1)+a.path;l.path=o.normalizePath(d)}else l.path=s.path,a.params||(l.params=s.params,a.query||(l.query=s.query));return null===l.path&&(l.path=r.alwaysNormalize?o.normalizePath(a.path):a.path),o.buildURLFromParts(l)},parseURL:function(e){var t=r.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(i,"");e.length!==(e=e.replace(a,"")).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}()},function(e,t,r){"use strict";var n=function(e){return e&&2===e.CLOSING},i=function(){return"undefined"!=typeof WebSocket&&n(WebSocket)},a=function(){return{constructor:i()?WebSocket:null,maxReconnectionDelay:1e4,minReconnectionDelay:1500,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,debug:!1}},o=function(e,t,r){Object.defineProperty(t,r,{get:function(){return e[r]},set:function(t){e[r]=t},enumerable:!0,configurable:!0})},s=function(e){return e.minReconnectionDelay+Math.random()*e.minReconnectionDelay},u=function(e,t){var r=t*e.reconnectionDelayGrowFactor;return r>e.maxReconnectionDelay?e.maxReconnectionDelay:r},l=["onopen","onclose","onmessage","onerror"],c=function(e,t,r){Object.keys(r).forEach(function(t){r[t].forEach(function(r){var n=r[0],i=r[1];e.addEventListener(t,n,i)})}),t&&l.forEach(function(r){e[r]=t[r]})},d=function(e,t,r){var i=this;void 0===r&&(r={});var l,f,h=0,p=0,g=!0,v=null,y={};if(!(this instanceof d))throw new TypeError("Failed to construct 'ReconnectingWebSocket': Please use the 'new' operator");var m=a();if(Object.keys(m).filter(function(e){return r.hasOwnProperty(e)}).forEach(function(e){return m[e]=r[e]}),!n(m.constructor))throw new TypeError("Invalid WebSocket constructor. Set `options.constructor`");var b=m.debug?function(){for(var e=[],t=0;tm.maxRetries)return void _("EHOSTDOWN","Too many failed connection attempts");h=h?u(m,h):s(m),b("handleClose - reconnectDelay:",h),g&&setTimeout(w,h)},w=function(){if(g){b("connect");var r=l,n="function"==typeof e?e():e;l=new m.constructor(n,t),f=setTimeout(function(){b("timeout"),l.close(),_("ETIMEDOUT","Connection timeout")},m.connectionTimeout),b("bypass properties");for(var a in l)["addEventListener","removeEventListener","close","send"].indexOf(a)<0&&o(l,i,a);l.addEventListener("open",function(){clearTimeout(f),b("open"),h=s(m),b("reconnectDelay:",h),p=0}),l.addEventListener("close",E),c(l,r,y),l.onclose=l.onclose||v,v=null}};b("init"),w(),this.close=function(e,t,r){void 0===e&&(e=1e3),void 0===t&&(t="");var n=void 0===r?{}:r,i=n.keepClosed,a=void 0!==i&&i,o=n.fastClose,s=void 0===o||o,u=n.delay,c=void 0===u?0:u;if(b("close - params:",{reason:t,keepClosed:a,fastClose:s,delay:c,retriesCount:p,maxRetries:m.maxRetries}),g=!a&&p<=m.maxRetries,c&&(h=c),l.close(e,t),s){var d={code:e,reason:t,wasClean:!0};E(),l.removeEventListener("close",E),Array.isArray(y.close)&&y.close.forEach(function(e){var t=e[0],r=e[1];t(d),l.removeEventListener("close",t,r)}),l.onclose&&(v=l.onclose,l.onclose(d),l.onclose=null)}},this.send=function(e){l.send(e)},this.addEventListener=function(e,t,r){Array.isArray(y[e])?y[e].some(function(e){return e[0]===t})||y[e].push([t,r]):y[e]=[[t,r]],l.addEventListener(e,t,r)},this.removeEventListener=function(e,t,r){Array.isArray(y[e])&&(y[e]=y[e].filter(function(e){return e[0]!==t})),l.removeEventListener(e,t,r)}};e.exports=d},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(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 o(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"==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},u=Object.assign||function(e){for(var t=1;t0){var t={event:c.Events.DC_HAVE,sn:e};this._broadcastToPeers(t)}}},{key:"updateLoadingSN",value:function(e){this.loadingSN=e}},{key:"updatePlaySN",value:function(e){var t=this.engine.logger;if(!this.config.live&&this.hasPeers)for(var r=[],n=e+1;n<=e+this.config.urgentOffset+1;n++)if(!this.bitset.has(n)&&n!==this.loadingSN&&this.bitCounts.has(n)){var i=!0,a=!1,o=void 0;try{for(var s,u=this.peerMap.values()[Symbol.iterator]();!(i=(s=u.next()).done);i=!0){var l=s.value;if(l.isAvailable&&l.bitset.has(n)){l.requestDataBySN(n,!0),t.debug("request urgent "+n+" from peer "+l.remotePeerId),r.push(n);break}}}catch(e){a=!0,o=e}finally{try{!i&&u.return&&u.return()}finally{if(a)throw o}}}}},{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(n(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(n(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 r=!0,n=!1,i=void 0;try{for(var a,o=this.peerMap.values()[Symbol.iterator]();!(r=(a=o.next()).done);r=!0){var s=a.value;if(s.isAvailable&&s.bitset.has(e))return t.info("found sn "+e+" from peer "+s.remotePeerId),this.targetPeer=s,!0}}catch(e){n=!0,i=e}finally{try{!r&&o.return&&o.return()}finally{if(n)throw i}}return t.warn("idle peers hasn't sn "+e),!1}},{key:"load",value:function(e,t,r){var n=this.engine.logger;this.context=e;var i=e.frag,a=(0,d.handleTSUrl)(i.relurl,this.config.tsStrictMatched);this.callbacks=r,this.stats={trequest:performance.now(),retry:0,tfirst:0,tload:0,loaded:0},this.criticalSeg={sn:i.sn,relurl:a},this.targetPeer.requestDataByURL(a,!0),n.info("request criticalSeg url "+i.relurl+" at "+i.sn),this.criticaltimeouter=window.setTimeout(this._criticaltimeout.bind(this),1e3*this.config.loadTimeout)}},{key:"_setupDC",value:function(e){var t=this,r=this.engine.logger;e.on(c.Events.DC_BITFIELD,function(r){if(r.field){var n=new Set(r.field);e.bitset=n,r.field.forEach(function(e){t.bitset.has(e)||t._increBitCounts(e)}),t.addPeer(e)}}).on(c.Events.DC_HAVE,function(r){if(r.sn&&e.bitset){var n=r.sn;e.bitset.add(n),t.bitset.has(n)||t._increBitCounts(n)}}).on(c.Events.DC_LOST,function(r){if(r.sn&&e.bitset){var n=r.sn;e.bitset.delete(n),t._decreBitCounts(n)}}).on(c.Events.DC_PIECE_ACK,function(e){e.size&&t.engine.fetcher.reportUploaded(e.size)}).on(c.Events.DC_PIECE,function(e){t.criticalSeg&&t.criticalSeg.relurl===e.url&&(t.stats.tfirst=Math.max(performance.now(),t.stats.trequest))}).on(c.Events.DC_PIECE_NOT_FOUND,function(e){t.criticalSeg&&t.criticalSeg.relurl===e.url&&(window.clearTimeout(t.criticaltimeouter),r.info("DC_PIECE_NOT_FOUND"),t._criticaltimeout())}).on(c.Events.DC_RESPONSE,function(n){if(t.criticalSeg&&t.criticalSeg.relurl===n.url&&t.criticaltimeouter){r.info("receive criticalSeg url "+n.url),window.clearTimeout(t.criticaltimeouter),t.criticaltimeouter=null;var i=t.stats;i.tload=Math.max(i.tfirst,performance.now()),i.loaded=i.total=n.data.byteLength,t.criticalSeg=null,t.context.frag.fromPeerId=e.remotePeerId,t.callbacks.onSuccess(n,i,t.context)}else t.bufMgr.addBuffer(n.sn,n.url,n.data,e.remotePeerId);t.updateLoadedSN(n.sn)}).on(c.Events.DC_REQUEST,function(r){var n="";if((n=r.url?r.url:t.bufMgr.getURLbySN(r.sn))&&t.bufMgr.hasSegOfURL(n)){var i=t.bufMgr.getSegByURL(n);e.sendBuffer(r.sn,i.relurl,i.data)}else e.sendJson({event:c.Events.DC_PIECE_NOT_FOUND,url:n,sn:r.sn})}).on(c.Events.DC_TIMEOUT,function(){r.warn("DC_TIMEOUT"),t.criticaltimeouter&&(window.clearTimeout(t.criticaltimeouter),t._criticaltimeout())})}},{key:"_broadcastToPeers",value:function(e){var t=!0,r=!1,n=void 0;try{for(var i,a=this.peerMap.values()[Symbol.iterator]();!(t=(i=a.next()).done);t=!0){i.value.sendJson(e)}}catch(e){r=!0,n=e}finally{try{!t&&a.return&&a.return()}finally{if(r)throw n}}}},{key:"_getIdlePeer",value:function(){return[].concat(n(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.callbacks.onTimeout(this.stats,this.context,null)}},{key:"hasPeers",get:function(){return this.peerMap.size>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.peerMap.size+" idle peers: "+t),t>0}},{key:"bufferManager",set:function(e){var t=this;this.bufMgr=e,e.on(c.Events.BM_LOST,function(e){t._broadcastToPeers({event:c.Events.DC_LOST,sn:e}),t.bitset.delete(e)})}}]),t}(l.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,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(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 o(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 r=0;r0&&(r.warn("resend all cached msg"),t.msgQueue.forEach(function(e){t._ws.send(e)}),t.msgQueue=[]),t.onopen&&t.onopen()},a.push=a.send,a.send=function(t){var r=JSON.stringify(Object.assign({peer_id:e},t));a.push(r)},a.onmessage=function(e){t.onmessage&&t.onmessage(e)},a.onclose=function(){r.warn("Signaler websocket closed"),t.onclose&&t.onclose(),t.connected=!1},a}},{key:"sendSignal",value:function(e,t){var r={action:"signal",peer_id:this.peerId,to_peer_id:e,data:t};this._send(r)}},{key:"_send",value:function(e){var t=this.engine.logger;this.connected?this._ws.send(e):(t.warn("signaler closed, msg is cached"),this.msgQueue.push(e))}},{key:"close",value:function(){this._ws.close(),this._ws=null}}]),t}(l.default);t.default=f,e.exports=t.default},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(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 o(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 r=0;r3&&void 0!==arguments[3]?arguments[3]:"",i=(0,d.handleTSUrl)(t,this.config.tsStrictMatched),a=c.Buffer.from(e),o=a.byteLength,s=new c.Buffer(o);a.copy(s);var u={sn:r,relurl:i,data:s,size:o,fromPeerId:n};this.addSeg(u),this.sn2Url.set(r,i)}},{key:"addBuffer",value:function(e,t,r){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"",i=(0,d.handleTSUrl)(t,this.config.tsStrictMatched),a={sn:e,relurl:i,data:r,size:r.byteLength,fromPeerId:n};this.addSeg(a),this.sn2Url.set(e,i)}},{key:"addSeg",value:function(e){var t=this.engine.logger;for(t.info("push seg "+e.sn+" "+e.size),this._segPool.set(e.relurl,e),this._currBufSize+=parseInt(e.size),t.debug("seg.size "+e.size+" _currBufSize "+this._currBufSize+" maxBufSize "+this.config.maxBufSize);this._currBufSize>this.config.maxBufSize;){var r=[].concat(n(this._segPool.values())).shift();t.info("pop seg "+r.relurl+" at "+r.sn),this._segPool.delete(r.relurl),this.sn2Url.delete(r.sn),this._currBufSize-=parseInt(r.size),this.overflowed||(this.overflowed=!0),this.emit(c.Events.BM_LOST,r.sn)}}},{key:"getSegByURL",value:function(e){return this._segPool.get(e)}},{key:"getURLbySN",value:function(e){return this.sn2Url.get(e)}},{key:"clear",value:function(){this._segPool.clear(),this.sn2Url.clear(),this._currBufSize=0}},{key:"currBufSize",get:function(){return this._currBufSize}}]),t}(l.default);t.default=f,e.exports=t.default},function(e,t,r){"use strict";function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(){}Object.defineProperty(t,"__esModule",{value:!0});var a=function(){function e(e,t){for(var r=0;r "+e,this._uploadLog(e)}},{key:"_infoU",value:function(e){e="["+this.identifier+" info] > "+e,this._uploadLog(e)}},{key:"_warnU",value:function(e){e="["+this.identifier+" warn] > "+e,this._uploadLog(e)}},{key:"_errorU",value:function(e){e="["+this.identifier+" error] > "+e,this._uploadLog(e)}},{key:"_uploadLog",value:function(e){this.connected&&this._ws.send(e)}},{key:"_initWs",value:function(e){var t=this,r={maxRetries:this.config.wsMaxRetries,minReconnectionDelay:1e3*this.config.wsReconnectInterval},n=new s.default(this.config.logUploadAddr+"?info_hash="+window.encodeURIComponent(e),void 0,r);return n.onopen=function(){t.debug("Log websocket connection opened"),t.connected=!0},n.onclose=function(){t.warn("Log websocket closed"),t.connected=!1},n}}]),e}();t.default=d,e.exports=t.default},function(e,t,r){"use strict";function n(){return navigator.userAgent.toLowerCase()}function i(e){return""+(new RegExp(e+"(\\d+((\\.|_)\\d+)*)").exec(n())||[,0])[1]||void 0}function a(e){return parseFloat((e||"").replace(/\_/g,"."))||0}var o={getNetType:function(){return(new RegExp("nettype\\/(\\w*)").exec(n())||[,""])[1].toLowerCase()},getPlatform:function(){return o.isAndroid()?"android":o.isIOS()?"iOS":"PC"},isX5:function(){return this.isAndroid()&&/\s(TBS|X5Core)\/[\w\.\-]+/i.test(n())},isPC:function(){return!a(i("os "))&&!a(i("android[/ ]"))},isIOS:function(){return a(i("os "))},isAndroid:function(){return a(i("android[/ ]"))},isSafari:function(){return this.isIOS()&&/^((?!chrome|android).)*safari/i.test(n())}};e.exports=o},function(e,t,r){!function(t,r){e.exports=r()}(0,function(){return function(e){function t(n){if(r[n])return r[n].exports;var i=r[n]={i:n,l:!1,exports:{}};return e[n].call(i.exports,i,i.exports,t),i.l=!0,i.exports}var r={};return t.m=e,t.c=r,t.d=function(e,r,n){t.o(e,r)||Object.defineProperty(e,r,{configurable:!1,enumerable:!0,get:n})},t.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(r,"a",r),r},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="/dist/",t(t.s=10)}([function(e,t,r){"use strict";function n(){}function i(e,t){return t="["+e+"] > "+t}function a(e){var t=d.console[e];return t?function(){for(var r=arguments.length,n=Array(r),a=0;a1?t-1:0),n=1;n0)return t.subarray(n,n+i)},e._readSize=function(e,t){var r=0;return r=(127&e[t])<<21,r|=(127&e[t+1])<<14,r|=(127&e[t+2])<<7,r|=127&e[t+3]},e.getTimeStamp=function(t){for(var r=e.getID3Frames(t),n=0;n1&&void 0!==arguments[1]&&arguments[1],r=e.length,n=void 0,i=void 0,a=void 0,o="",s=0;s>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:o+=String.fromCharCode(n);break;case 12:case 13:i=e[s++],o+=String.fromCharCode((31&n)<<6|63&i);break;case 14:i=e[s++],a=e[s++],o+=String.fromCharCode((15&n)<<12|(63&i)<<6|(63&a)<<0)}}return o},e}(),a=i._utf8ArrayToStr;t.a=i},function(e,t){function r(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function n(e){return"function"==typeof e}function i(e){return"number"==typeof e}function a(e){return"object"==typeof e&&null!==e}function o(e){return void 0===e}e.exports=r,r.EventEmitter=r,r.prototype._events=void 0,r.prototype._maxListeners=void 0,r.defaultMaxListeners=10,r.prototype.setMaxListeners=function(e){if(!i(e)||e<0||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this},r.prototype.emit=function(e){var t,r,i,s,u,l;if(this._events||(this._events={}),"error"===e&&(!this._events.error||a(this._events.error)&&!this._events.error.length)){if((t=arguments[1])instanceof Error)throw t;var c=new Error('Uncaught, unspecified "error" event. ('+t+")");throw c.context=t,c}if(r=this._events[e],o(r))return!1;if(n(r))switch(arguments.length){case 1:r.call(this);break;case 2:r.call(this,arguments[1]);break;case 3:r.call(this,arguments[1],arguments[2]);break;default:s=Array.prototype.slice.call(arguments,1),r.apply(this,s)}else if(a(r))for(s=Array.prototype.slice.call(arguments,1),l=r.slice(),i=l.length,u=0;u0&&this._events[e].length>i&&(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},r.prototype.on=r.prototype.addListener,r.prototype.once=function(e,t){function r(){this.removeListener(e,r),i||(i=!0,t.apply(this,arguments))}if(!n(t))throw TypeError("listener must be a function");var i=!1;return r.listener=t,this.on(e,r),this},r.prototype.removeListener=function(e,t){var r,i,o,s;if(!n(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(r=this._events[e],o=r.length,i=-1,r===t||n(r.listener)&&r.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(a(r)){for(s=o;s-- >0;)if(r[s]===t||r[s].listener&&r[s].listener===t){i=s;break}if(i<0)return this;1===r.length?(r.length=0,delete this._events[e]):r.splice(i,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},r.prototype.removeAllListeners=function(e){var t,r;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(r=this._events[e],n(r))this.removeListener(e,r);else if(r)for(;r.length;)this.removeListener(e,r[r.length-1]);return delete this._events[e],this},r.prototype.listeners=function(e){return this._events&&this._events[e]?n(this._events[e])?[this._events[e]]:this._events[e].slice():[]},r.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(n(t))return 1;if(t)return t.length}return 0},r.listenerCount=function(e,t){return e.listenerCount(t)}},function(e,t,r){"use strict";function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e){var t=e.byteLength,r=t&&new DataView(e).getUint8(t-1);return r?e.slice(0,t-r):e}function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var u=function(){function e(t,r){n(this,e),this.subtle=t,this.aesIV=r}return e.prototype.decrypt=function(e,t){return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e)},e}(),l=u,c=function(){function e(t,r){i(this,e),this.subtle=t,this.key=r}return e.prototype.expandKey=function(){return this.subtle.importKey("raw",this.key,{name:"AES-CBC"},!1,["encrypt","decrypt"])},e}(),d=c,f=function(){function e(){a(this,e),this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.initTable()}return e.prototype.uint8ArrayToUint32Array_=function(e){for(var t=new DataView(e),r=new Uint32Array(4),n=0;n<4;n++)r[n]=t.getUint32(4*n);return r},e.prototype.initTable=function(){var e=this.sBox,t=this.invSBox,r=this.subMix,n=r[0],i=r[1],a=r[2],o=r[3],s=this.invSubMix,u=s[0],l=s[1],c=s[2],d=s[3],f=new Uint32Array(256),h=0,p=0,g=0;for(g=0;g<256;g++)f[g]=g<128?g<<1:g<<1^283;for(g=0;g<256;g++){var v=p^p<<1^p<<2^p<<3^p<<4;v=v>>>8^255&v^99,e[h]=v,t[v]=h;var y=f[h],m=f[y],b=f[m],_=257*f[v]^16843008*v;n[h]=_<<24|_>>>8,i[h]=_<<16|_>>>16,a[h]=_<<8|_>>>24,o[h]=_,_=16843009*b^65537*m^257*y^16843008*h,u[v]=_<<24|_>>>8,l[v]=_<<16|_>>>16,c[v]=_<<8|_>>>24,d[v]=_,h?(h=y^f[f[f[b^y]]],p^=f[f[p]]):h=p=1}},e.prototype.expandKey=function(e){for(var t=this.uint8ArrayToUint32Array_(e),r=!0,n=0;n0},e.bin2str=function(e){return String.fromCharCode.apply(null,e)},e.readUint16=function(e,t){e.data&&(t+=e.start,e=e.data);var r=e[t]<<8|e[t+1];return r<0?65536+r:r},e.readUint32=function(e,t){e.data&&(t+=e.start,e=e.data);var r=e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3];return r<0?4294967296+r:r},e.writeUint32=function(e,t,r){e.data&&(t+=e.start,e=e.data),e[t]=r>>24,e[t+1]=r>>16&255,e[t+2]=r>>8&255,e[t+3]=255&r},e.findBox=function(t,r){var n=[],i=void 0,a=void 0,o=void 0,s=void 0,u=void 0,l=void 0,c=void 0;if(t.data?(l=t.start,s=t.end,t=t.data):(l=0,s=t.byteLength),!r.length)return null;for(i=l;i1?i+a:s,o===r[0]&&(1===r.length?n.push({data:t,start:i+8,end:c}):(u=e.findBox({data:t,start:i+8,end:c},r.slice(1)),u.length&&(n=n.concat(u)))),i=c;return n},e.parseSegmentIndex=function(t){var r=e.findBox(t,["moov"])[0],n=r?r.end:null,i=0,a=e.findBox(t,["sidx"]),o=void 0;if(!a||!a[0])return null;o=[],a=a[0];var s=a.data[0];i=0===s?8:16;var u=e.readUint32(a,i);i+=4;i+=0===s?8:16,i+=2;var l=a.end+0,c=e.readUint16(a,i);i+=2;for(var d=0;d>>31)return void console.warn("SIDX has hierarchical references (not supported)");var g=e.readUint32(a,f);f+=4,o.push({referenceSize:p,subsegmentDuration:g,info:{duration:g/u,start:l,end:l+p-1}}),l+=p,f+=4,i=f}return{earliestPresentationTime:0,timescale:u,version:s,referencesCount:c,references:o,moovEndOffset:n}},e.parseInitSegment=function(t){var r=[];return e.findBox(t,["moov","trak"]).forEach(function(t){var n=e.findBox(t,["tkhd"])[0];if(n){var a=n.data[n.start],o=0===a?12:20,s=e.readUint32(n,o),u=e.findBox(t,["mdia","mdhd"])[0];if(u){a=u.data[u.start],o=0===a?12:20;var l=e.readUint32(u,o),c=e.findBox(t,["mdia","hdlr"])[0];if(c){var d=e.bin2str(c.data.subarray(c.start+8,c.start+12)),f={soun:"audio",vide:"video"}[d];if(f){var h=e.findBox(t,["mdia","minf","stbl","stsd"]);if(h.length){h=h[0];var p=e.bin2str(h.data.subarray(h.start+12,h.start+16));i.b.log("MP4Demuxer:"+f+":"+p+" found")}r[s]={timescale:l,type:f},r[f]={timescale:l,id:s}}}}}}),r},e.getStartDTS=function(t,r){var n=void 0,i=void 0,a=void 0;return n=e.findBox(r,["moof","traf"]),i=[].concat.apply([],n.map(function(r){return e.findBox(r,["tfhd"]).map(function(n){var i=void 0,a=void 0;return i=e.readUint32(n,4),a=t[i].timescale||9e4,e.findBox(r,["tfdt"]).map(function(t){var r=void 0,n=void 0;return r=t.data[t.start],n=e.readUint32(t,4),1===r&&(n*=Math.pow(2,32),n+=e.readUint32(t,8)),n})[0]/a})})),a=Math.min.apply(null,i),isFinite(a)?a:0},e.offsetStartDTS=function(t,r,n){e.findBox(r,["moof","traf"]).map(function(r){return e.findBox(r,["tfhd"]).map(function(i){var a=e.readUint32(i,4),s=t[a].timescale||9e4;e.findBox(r,["tfdt"]).map(function(t){var r=t.data[t.start],i=e.readUint32(t,4);if(0===r)e.writeUint32(t,4,i-n*s);else{i*=Math.pow(2,32),i+=e.readUint32(t,8),i-=n*s,i=Math.max(i,0);var a=Math.floor(i/(o+1)),u=Math.floor(i%(o+1));e.writeUint32(t,4,a),e.writeUint32(t,8,u)}})})})},e.prototype.append=function(t,r,n,i){var o=this.initData;o||(this.resetInitSegment(t,this.audioCodec,this.videoCodec,!1),o=this.initData);var s=void 0,u=this.initPTS;if(void 0===u){var l=e.getStartDTS(o,t);this.initPTS=u=l-r,this.observer.trigger(a.a.INIT_PTS_FOUND,{initPTS:u})}e.offsetStartDTS(o,t,u),s=e.getStartDTS(o,t),this.remuxer.remux(o.audio,o.video,null,null,s,n,i,t)},e.prototype.destroy=function(){},e}();t.a=s},function(e,t,r){"use strict";function n(e,t,r,n){var i=void 0,a=void 0,o=void 0,s=void 0,u=void 0,l=navigator.userAgent.toLowerCase(),c=n,d=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];return i=1+((192&t[r+2])>>>6),(a=(60&t[r+2])>>>2)>d.length-1?void e.trigger(T.a.ERROR,{type:S.b.MEDIA_ERROR,details:S.a.FRAG_PARSING_ERROR,fatal:!0,reason:"invalid ADTS sampling index:"+a}):(s=(1&t[r+2])<<2,s|=(192&t[r+3])>>>6,A.b.log("manifest codec:"+n+",ADTS data:type:"+i+",sampleingIndex:"+a+"["+d[a]+"Hz],channelConfig:"+s),/firefox/i.test(l)?a>=6?(i=5,u=new Array(4),o=a-3):(i=2,u=new Array(2),o=a):-1!==l.indexOf("android")?(i=2,u=new Array(2),o=a):(i=5,u=new Array(4),n&&(-1!==n.indexOf("mp4a.40.29")||-1!==n.indexOf("mp4a.40.5"))||!n&&a>=6?o=a-3:((n&&-1!==n.indexOf("mp4a.40.2")&&(a>=6&&1===s||/vivaldi/i.test(l))||!n&&1===s)&&(i=2,u=new Array(2)),o=a)),u[0]=i<<3,u[0]|=(14&a)>>1,u[1]|=(1&a)<<7,u[1]|=s<<3,5===i&&(u[1]|=(14&o)>>1,u[2]=(1&o)<<7,u[2]|=8,u[3]=0),{config:u,samplerate:d[a],channelCount:s,codec:"mp4a.40."+i,manifestCodec:c})}function i(e,t){return 255===e[t]&&240==(246&e[t+1])}function a(e,t){return 1&e[t+1]?7:9}function o(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function s(e,t){return!!(t+10&&t+s+u<=c)return l=r+n*i,{headerLength:s,frameLength:u,stamp:l}}function f(e,t,r,n,i){var a=c(e.samplerate),o=d(t,r,n,i,a);if(o){var s=o.stamp,u=o.headerLength,l=o.frameLength,f={unit:t.subarray(r+u,r+u+l),pts:s,dts:s};return e.samples.push(f),e.len+=l,{sample:f,length:l+u}}}function h(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function p(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function g(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function v(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function y(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function m(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function b(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function E(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function w(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var T=r(1),S=r(2),R=r(7),A=r(0),L=r(3),C=r(5),k=function(){function e(t,r,n){h(this,e),this.observer=t,this.config=n,this.remuxer=r}return e.prototype.resetInitSegment=function(e,t,r,n){this._audioTrack={container:"audio/adts",type:"audio",id:0,sequenceNumber:0,isAAC:!0,samples:[],len:0,manifestCodec:t,duration:n,inputTimeScale:9e4}},e.prototype.resetTimeStamp=function(){},e.probe=function(e){if(!e)return!1;for(var t=C.a.getID3Data(e,0)||[],r=t.length,n=e.length;rt.length)){var a=this.parseHeader(t,r);if(a&&r+a.frameLength<=t.length){var o=9e4*a.samplesPerFrame/a.sampleRate,s=n+i*o,u={unit:t.subarray(r,r+a.frameLength),pts:s,dts:s};return e.config=[],e.channelCount=a.channelCount,e.samplerate=a.sampleRate,e.samples.push(u),e.len+=a.frameLength,{sample:u,length:a.frameLength}}}},parseHeader:function(e,t){var r=e[t+1]>>3&3,n=e[t+1]>>1&3,i=e[t+2]>>4&15,a=e[t+2]>>2&3,o=e[t+2]>>1&1;if(1!==r&&0!==i&&15!==i&&3!==a){var s=3===r?3-n:3===n?3:4,u=1e3*P.BitratesMap[14*s+i-1],l=3===r?0:2===r?1:2,c=P.SamplingRateMap[3*l+a],d=e[t+3]>>6==3?1:2,f=P.SamplesCoefficients[r][n],h=P.BytesInSlot[n],p=8*f*h;return{sampleRate:c,channelCount:d,frameLength:parseInt(f*u/c+o,10)*h,samplesPerFrame:p}}},isHeaderPattern:function(e,t){return 255===e[t]&&224==(224&e[t+1])&&0!=(6&e[t+1])},isHeader:function(e,t){return!!(t+1e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,t=e>>3,e-=t>>3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)},e.prototype.readBits=function(e){var t=Math.min(this.bitsAvailable,e),r=this.word>>>32-t;return e>32&&A.b.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0?this.word<<=t:this.bytesAvailable>0&&this.loadWord(),t=e-t,t>0&&this.bitsAvailable?r<>>e))return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()},e.prototype.skipUEG=function(){this.skipBits(1+this.skipLZ())},e.prototype.skipEG=function(){this.skipBits(1+this.skipLZ())},e.prototype.readUEG=function(){var e=this.skipLZ();return this.readBits(e+1)-1},e.prototype.readEG=function(){var e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)},e.prototype.readBoolean=function(){return 1===this.readBits(1)},e.prototype.readUByte=function(){return this.readBits(8)},e.prototype.readUShort=function(){return this.readBits(16)},e.prototype.readUInt=function(){return this.readBits(32)},e.prototype.skipScalingList=function(e){var t=8,r=8,n=void 0,i=void 0;for(n=0;n=e.length)return void r();if(!(e[t].unit.length<32)){var n=this.decrypter.isSync();if(this.decryptAacSample(e,t,r,n),!n)return}}},e.prototype.getAvcEncryptedData=function(e){for(var t=16*Math.floor((e.length-48)/160)+16,r=new Int8Array(t),n=0,i=32;i<=e.length-16;i+=160,n+=16)r.set(e.subarray(i,i+16),n);return r},e.prototype.getAvcDecryptedUnit=function(e,t){t=new Uint8Array(t);for(var r=0,n=32;n<=e.length-16;n+=160,r+=16)e.set(t.subarray(r,r+16),n);return e},e.prototype.decryptAvcSample=function(e,t,r,n,i,a){var o=this.discardEPB(i.data),s=this.getAvcEncryptedData(o),u=this;this.decryptBuffer(s.buffer,function(s){i.data=u.getAvcDecryptedUnit(o,s),a||u.decryptAvcSamples(e,t,r+1,n)})},e.prototype.decryptAvcSamples=function(e,t,r,n){for(;;t++,r=0){if(t>=e.length)return void n();for(var i=e[t].units;!(r>=i.length);r++){var a=i[r];if(!(a.length<=48||1!==a.type&&5!==a.type)){var o=this.decrypter.isSync();if(this.decryptAvcSample(e,t,r,n,a,o),!o)return}}}},e}(),N=F,U={video:1,audio:2,id3:3,text:4},B=function(){function e(t,r,n,i){v(this,e),this.observer=t,this.config=n,this.typeSupported=i,this.remuxer=r,this.sampleAes=null}return e.prototype.setDecryptData=function(e){null!=e&&null!=e.key&&"SAMPLE-AES"===e.method?this.sampleAes=new N(this.observer,this.config,e,this.discardEPB):this.sampleAes=null},e.probe=function(t){var r=e._syncOffset(t);return!(r<0)&&(r&&A.b.warn("MPEG2-TS detected but first sync word found @ offset "+r+", junk ahead ?"),!0)},e._syncOffset=function(e){for(var t=Math.min(1e3,e.length-564),r=0;r>4>1){if((l=a+5+t[a+4])===a+188)continue}else l=a+4;switch(u){case v:s&&(_&&(c=C(_))&&void 0!==c.pts&&k(c,!1),_={data:[],size:0}),_&&(_.data.push(t.subarray(l,a+188)),_.size+=a+188-l);break;case y:s&&(E&&(c=C(E))&&void 0!==c.pts&&(p.isAAC?D(c):I(c)),E={data:[],size:0}),E&&(E.data.push(t.subarray(l,a+188)),E.size+=a+188-l);break;case m:s&&(w&&(c=C(w))&&void 0!==c.pts&&P(c),w={data:[],size:0}),w&&(w.data.push(t.subarray(l,a+188)),w.size+=a+188-l);break;case 0:s&&(l+=t[l]+1),b=this._pmtId=R(t,l);break;case b:s&&(l+=t[l]+1);var x=L(t,l,!0===this.typeSupported.mpeg||!0===this.typeSupported.mp3,null!=this.sampleAes);v=x.avc,v>0&&(h.pid=v),y=x.audio,y>0&&(p.pid=y,p.isAAC=x.isAAC),m=x.id3,m>0&&(g.pid=m),d&&!f&&(A.b.log("reparse from beginning"),d=!1,a=O-188),f=this.pmtParsed=!0;break;case 17:case 8191:break;default:d=!0}}else this.observer.trigger(T.a.ERROR,{type:S.b.MEDIA_ERROR,details:S.a.FRAG_PARSING_ERROR,fatal:!1,reason:"TS packet did not start with 0x47"});_&&(c=C(_))&&void 0!==c.pts?(k(c,!0),h.pesData=null):h.pesData=_,E&&(c=C(E))&&void 0!==c.pts?(p.isAAC?D(c):I(c),p.pesData=null):(E&&E.size&&A.b.log("last AAC PES packet truncated,might overlap between fragments"),p.pesData=E),w&&(c=C(w))&&void 0!==c.pts?(P(c),g.pesData=null):g.pesData=w,null==this.sampleAes?this.remuxer.remux(p,h,g,this._txtTrack,r,n,i):this.decryptAndRemux(p,h,g,this._txtTrack,r,n,i)},e.prototype.decryptAndRemux=function(e,t,r,n,i,a,o){if(e.samples&&e.isAAC){var s=this;this.sampleAes.decryptAacSamples(e.samples,0,function(){s.decryptAndRemuxAvc(e,t,r,n,i,a,o)})}else this.decryptAndRemuxAvc(e,t,r,n,i,a,o)},e.prototype.decryptAndRemuxAvc=function(e,t,r,n,i,a,o){if(t.samples){var s=this;this.sampleAes.decryptAvcSamples(t.samples,0,0,function(){s.remuxer.remux(e,t,r,n,i,a,o)})}else this.remuxer.remux(e,t,r,n,i,a,o)},e.prototype.destroy=function(){this._initPTS=this._initDTS=void 0,this._duration=0},e.prototype._parsePAT=function(e,t){return(31&e[t+10])<<8|e[t+11]},e.prototype._parsePMT=function(e,t,r,n){var i=void 0,a=void 0,o=void 0,s=void 0,u={audio:-1,avc:-1,id3:-1,isAAC:!0};for(i=(15&e[t+1])<<8|e[t+2],a=t+3+i-4,o=(15&e[t+10])<<8|e[t+11],t+=12+o;t1;){var d=new Uint8Array(c[0].length+c[1].length);d.set(c[0]),d.set(c[1],c[0].length),c[0]=d,c.splice(1,1)}if(r=c[0],1===(r[0]<<16)+(r[1]<<8)+r[2]){if((i=(r[4]<<8)+r[5])&&i>e.size-6)return null;n=r[7],192&n&&(s=536870912*(14&r[9])+4194304*(255&r[10])+16384*(254&r[11])+128*(255&r[12])+(254&r[13])/2,s>4294967295&&(s-=8589934592),64&n?(u=536870912*(14&r[14])+4194304*(255&r[15])+16384*(254&r[16])+128*(255&r[17])+(254&r[18])/2,u>4294967295&&(u-=8589934592),s-u>54e5&&(A.b.warn(Math.round((s-u)/9e4)+"s delta between PTS and DTS, align them"),s=u)):u=s),a=r[8],l=a+9,e.size-=l,o=new Uint8Array(e.size);for(var f=0,h=c.length;fp){l-=p;continue}r=r.subarray(l),p-=l,l=0}o.set(r,t),t+=p}return i&&(i-=a+3),{data:o,pts:s,dts:u,len:i}}return null},e.prototype.pushAccesUnit=function(e,t){if(e.units.length&&e.frame){var r=t.samples,n=r.length;!this.config.forceKeyFrameOnDiscontinuity||!0===e.key||t.sps&&(n||this.contiguous)?(e.id=n,r.push(e)):t.dropped++}e.debug.length&&A.b.log(e.pts+"/"+e.dts+":"+e.debug)},e.prototype._parseAVCPES=function(e,t){var r=this,n=this._avcTrack,i=this._parseAVCNALu(e.data),a=void 0,o=this.avcSample,s=void 0,u=!1,l=void 0,c=this.pushAccesUnit.bind(this),d=function(e,t,r,n){return{key:e,pts:t,dts:r,units:[],debug:n}};e.data=null,o&&i.length&&!n.audFound&&(c(o,n),o=this.avcSample=d(!1,e.pts,e.dts,"")),i.forEach(function(t){switch(t.type){case 1:s=!0,o||(o=r.avcSample=d(!0,e.pts,e.dts,"")),o.frame=!0;var i=t.data;if(u&&i.length>4){var f=new M(i).readSliceType();2!==f&&4!==f&&7!==f&&9!==f||(o.key=!0)}break;case 5:s=!0,o||(o=r.avcSample=d(!0,e.pts,e.dts,"")),o.key=!0,o.frame=!0;break;case 6:s=!0,a=new M(r.discardEPB(t.data)),a.readUByte();for(var h=0,p=0,g=!1,v=0;!g&&a.bytesAvailable>1;){h=0;do{v=a.readUByte(),h+=v}while(255===v);p=0;do{v=a.readUByte(),p+=v}while(255===v);if(4===h&&0!==a.bytesAvailable){g=!0;if(181===a.readUByte()){if(49===a.readUShort()){if(1195456820===a.readUInt()){if(3===a.readUByte()){var y=a.readUByte(),m=a.readUByte(),b=31&y,_=[y,m];for(l=0;l0){if(t.pts>=e[r-1].pts)e.push(t);else for(var n=r-1;n>=0;n--)if(t.pts=0)l={data:e.subarray(d,t-o-1),type:f},u.push(l);else{var h=this._getLastNalUnit();if(h&&(s&&t<=4-s&&h.state&&(h.data=h.data.subarray(0,h.data.byteLength-s)),(i=t-o-1)>0)){var p=new Uint8Array(h.data.byteLength+i);p.set(h.data,0),p.set(e.subarray(0,i),h.data.byteLength),h.data=p}}t=0&&o>=0&&(l={data:e.subarray(d,r),type:f,state:o},u.push(l)),0===u.length){var g=this._getLastNalUnit();if(g){var v=new Uint8Array(g.data.byteLength+e.byteLength);v.set(g.data,0),v.set(e,g.data.byteLength),g.data=v}}return a.naluState=o,u},e.prototype.discardEPB=function(e){for(var t=e.byteLength,r=[],n=1,i=void 0,a=void 0;n1&&(A.b.log("AAC: align PTS for overlapping frames by "+Math.round((m-n)/90)),n=m)}for(;d>24&255,a[1]=r>>16&255,a[2]=r>>8&255,a[3]=255&r,a.set(e,4),n=0,r=8;n>24&255,t>>16&255,t>>8&255,255&t,n>>24,n>>16&255,n>>8&255,255&n,i>>24,i>>16&255,i>>8&255,255&i,85,196,0,0]))},e.mdia=function(t){return e.box(e.types.mdia,e.mdhd(t.timescale,t.duration),e.hdlr(t.type),e.minf(t))},e.mfhd=function(t){return e.box(e.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t]))},e.minf=function(t){return"audio"===t.type?e.box(e.types.minf,e.box(e.types.smhd,e.SMHD),e.DINF,e.stbl(t)):e.box(e.types.minf,e.box(e.types.vmhd,e.VMHD),e.DINF,e.stbl(t))},e.moof=function(t,r,n){return e.box(e.types.moof,e.mfhd(t),e.traf(n,r))},e.moov=function(t){for(var r=t.length,n=[];r--;)n[r]=e.trak(t[r]);return e.box.apply(null,[e.types.moov,e.mvhd(t[0].timescale,t[0].duration)].concat(n).concat(e.mvex(t)))},e.mvex=function(t){for(var r=t.length,n=[];r--;)n[r]=e.trex(t[r]);return e.box.apply(null,[e.types.mvex].concat(n))},e.mvhd=function(t,r){r*=t;var n=Math.floor(r/(Y+1)),i=Math.floor(r%(Y+1)),a=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,n>>24,n>>16&255,n>>8&255,255&n,i>>24,i>>16&255,i>>8&255,255&i,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return e.box(e.types.mvhd,a)},e.sdtp=function(t){var r=t.samples||[],n=new Uint8Array(4+r.length),i=void 0,a=void 0;for(a=0;a>>8&255),r.push(255&o),r=r.concat(Array.prototype.slice.call(a));for(i=0;i>>8&255),n.push(255&o),n=n.concat(Array.prototype.slice.call(a));var s=e.box(e.types.avcC,new Uint8Array([1,r[3],r[4],r[5],255,224|t.sps.length].concat(r).concat([t.pps.length]).concat(n))),u=t.width,l=t.height,c=t.pixelRatio[0],d=t.pixelRatio[1];return e.box(e.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,u>>8&255,255&u,l>>8&255,255&l,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),s,e.box(e.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(e.types.pasp,new Uint8Array([c>>24,c>>16&255,c>>8&255,255&c,d>>24,d>>16&255,d>>8&255,255&d])))},e.esds=function(e){var t=e.config.length;return new Uint8Array([0,0,0,0,3,23+t,0,1,0,4,15+t,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([t]).concat(e.config).concat([6,1,2]))},e.mp4a=function(t){var r=t.samplerate;return e.box(e.types.mp4a,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount,0,16,0,0,0,0,r>>8&255,255&r,0,0]),e.box(e.types.esds,e.esds(t)))},e.mp3=function(t){var r=t.samplerate;return e.box(e.types[".mp3"],new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount,0,16,0,0,0,0,r>>8&255,255&r,0,0]))},e.stsd=function(t){return"audio"===t.type?t.isAAC||"mp3"!==t.codec?e.box(e.types.stsd,e.STSD,e.mp4a(t)):e.box(e.types.stsd,e.STSD,e.mp3(t)):e.box(e.types.stsd,e.STSD,e.avc1(t))},e.tkhd=function(t){var r=t.id,n=t.duration*t.timescale,i=t.width,a=t.height,o=Math.floor(n/(Y+1)),s=Math.floor(n%(Y+1));return e.box(e.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,r>>24&255,r>>16&255,r>>8&255,255&r,0,0,0,0,o>>24,o>>16&255,o>>8&255,255&o,s>>24,s>>16&255,s>>8&255,255&s,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,i>>8&255,255&i,0,0,a>>8&255,255&a,0,0]))},e.traf=function(t,r){var n=e.sdtp(t),i=t.id,a=Math.floor(r/(Y+1)),o=Math.floor(r%(Y+1));return e.box(e.types.traf,e.box(e.types.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,255&i])),e.box(e.types.tfdt,new Uint8Array([1,0,0,0,a>>24,a>>16&255,a>>8&255,255&a,o>>24,o>>16&255,o>>8&255,255&o])),e.trun(t,n.length+16+20+8+16+8+8),n)},e.trak=function(t){return t.duration=t.duration||4294967295,e.box(e.types.trak,e.tkhd(t),e.mdia(t))},e.trex=function(t){var r=t.id;return e.box(e.types.trex,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))},e.trun=function(t,r){var n=t.samples||[],i=n.length,a=12+16*i,o=new Uint8Array(a),s=void 0,u=void 0,l=void 0,c=void 0,d=void 0,f=void 0;for(r+=8+a,o.set([0,0,15,1,i>>>24&255,i>>>16&255,i>>>8&255,255&i,r>>>24&255,r>>>16&255,r>>>8&255,255&r],0),s=0;s>>24&255,l>>>16&255,l>>>8&255,255&l,c>>>24&255,c>>>16&255,c>>>8&255,255&c,d.isLeading<<2|d.dependsOn,d.isDependedOn<<6|d.hasRedundancy<<4|d.paddingValue<<1|d.isNonSync,61440&d.degradPrio,15&d.degradPrio,f>>>24&255,f>>>16&255,f>>>8&255,255&f],12+16*s);return e.box(e.types.trun,o)},e.initSegment=function(t){e.types||e.init();var r=e.moov(t),n=void 0;return n=new Uint8Array(e.FTYP.byteLength+r.byteLength),n.set(e.FTYP),n.set(r,e.FTYP.byteLength),n},e}(),V=q,z=function(){function e(t,r,n,i){_(this,e),this.observer=t,this.config=r,this.typeSupported=n;var a=navigator.userAgent;this.isSafari=i&&i.indexOf("Apple")>-1&&a&&!a.match("CriOS"),this.ISGenerated=!1}return e.prototype.destroy=function(){},e.prototype.resetTimeStamp=function(e){this._initPTS=this._initDTS=e},e.prototype.resetInitSegment=function(){this.ISGenerated=!1},e.prototype.remux=function(e,t,r,n,i,a,o){if(this.ISGenerated||this.generateIS(e,t,i),this.ISGenerated){var s=e.samples.length,u=t.samples.length,l=i,c=i;if(s&&u){var d=(e.samples[0].dts-t.samples[0].dts)/t.inputTimeScale;l+=Math.max(0,d),c+=Math.max(0,-d)}if(s){e.timescale||(A.b.warn("regenerate InitSegment as audio detected"),this.generateIS(e,t,i));var f=this.remuxAudio(e,l,a,o);if(u){var h=void 0;f&&(h=f.endPTS-f.startPTS),t.timescale||(A.b.warn("regenerate InitSegment as video detected"),this.generateIS(e,t,i)),this.remuxVideo(t,c,a,h,o)}}else if(u){var p=this.remuxVideo(t,c,a,0,o);p&&e.codec&&this.remuxEmptyAudio(e,l,a,p)}}r.samples.length&&this.remuxID3(r,i),n.samples.length&&this.remuxText(n,i),this.observer.trigger(T.a.FRAG_PARSED)},e.prototype.generateIS=function(e,t,r){var n=this.observer,i=e.samples,a=t.samples,o=this.typeSupported,s="audio/mp4",u={},l={tracks:u},c=void 0===this._initPTS,d=void 0,f=void 0;if(c&&(d=f=1/0),e.config&&i.length&&(e.timescale=e.samplerate,A.b.log("audio sampling rate : "+e.samplerate),e.isAAC||(o.mpeg?(s="audio/mpeg",e.codec=""):o.mp3&&(e.codec="mp3")),u.audio={container:s,codec:e.codec,initSegment:!e.isAAC&&o.mpeg?new Uint8Array:V.initSegment([e]),metadata:{channelCount:e.channelCount}},c&&(d=f=i[0].pts-e.inputTimeScale*r)),t.sps&&t.pps&&a.length){var h=t.inputTimeScale;t.timescale=h,u.video={container:"video/mp4",codec:t.codec,initSegment:V.initSegment([t]),metadata:{width:t.width,height:t.height}},c&&(d=Math.min(d,a[0].pts-h*r),f=Math.min(f,a[0].dts-h*r),this.observer.trigger(T.a.INIT_PTS_FOUND,{initPTS:d}))}Object.keys(u).length?(n.trigger(T.a.FRAG_PARSING_INIT_SEGMENT,l),this.ISGenerated=!0,c&&(this._initPTS=d,this._initDTS=f)):n.trigger(T.a.ERROR,{type:S.b.MEDIA_ERROR,details:S.a.FRAG_PARSING_ERROR,fatal:!1,reason:"no audio/video samples found"})},e.prototype.remuxVideo=function(e,t,r,n,i){var a=8,o=e.timescale,s=void 0,u=void 0,l=void 0,c=void 0,d=void 0,f=void 0,h=void 0,p=e.samples,g=[],v=p.length,y=this._PTSNormalize,m=this._initDTS,b=this.nextAvcDts,_=this.isSafari;if(0!==v){_&&(r|=p.length&&b&&(i&&Math.abs(t-b/o)<.1||Math.abs(p[0].pts-b-m)1?A.b.log("AVC:"+L+" ms hole between fragments detected,filling it"):L<-1&&A.b.log("AVC:"+-L+" ms overlapping between fragments detected"),d=b,p[0].dts=d,c=Math.max(c-L,b),p[0].pts=c,A.b.log("Video/PTS/DTS adjusted: "+Math.round(c/90)+"/"+Math.round(d/90)+",delta:"+L+" ms")),d,R=p[p.length-1],h=Math.max(R.dts,0),f=Math.max(R.pts,0,h),_&&(s=Math.round((h-d)/(p.length-1)));for(var C=0,k=0,D=0;D0?U-1:U].dts;if(X.stretchShortVideoTrack){var J=X.maxBufferHole,$=Math.floor(J*o),Z=(n?c+n*o:this.nextAudioPts)-B.pts;Z>$?(s=Z-Q,s<0&&(s=Q),A.b.log("It is approximately "+Z/90+" ms to the next segment; using duration "+s/90+" ms for the last video frame.")):s=Q}else s=Q}K=Math.round(B.pts-B.dts)}g.push({size:j,duration:s,cts:K,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:B.key?2:1,isNonSync:B.key?0:1}})}this.nextAvcDts=h+s;var ee=e.dropped;if(e.len=0,e.nbNalu=0,e.dropped=0,g.length&&navigator.userAgent.toLowerCase().indexOf("chrome")>-1){var te=g[0].flags;te.dependsOn=2,te.isNonSync=0}e.samples=g,l=V.moof(e.sequenceNumber++,d,e),e.samples=[];var re={data1:l,data2:u,startPTS:c/o,endPTS:(f+s)/o,startDTS:d/o,endDTS:this.nextAvcDts/o,type:"video",hasAudio:!1,hasVideo:!0,nb:g.length,dropped:ee};return this.observer.trigger(T.a.FRAG_PARSING_DATA,re),re}},e.prototype.remuxAudio=function(e,t,r,n){var i=e.inputTimeScale,a=e.timescale,o=i/a,s=e.isAAC?1024:1152,u=s*o,l=this._PTSNormalize,c=this._initDTS,d=!e.isAAC&&this.typeSupported.mpeg,f=void 0,h=void 0,p=void 0,g=void 0,v=void 0,y=void 0,m=void 0,b=e.samples,_=[],E=this.nextAudioPts;if(r|=b.length&&E&&(n&&Math.abs(t-E/i)<.1||Math.abs(b[0].pts-E-c)<20*u),b.forEach(function(e){e.pts=e.dts=l(e.pts-c,t*i)}),b=b.filter(function(e){return e.pts>=0}),0!==b.length){if(r||(E=n?t*i:b[0].pts),e.isAAC)for(var w=this.config.maxAudioFramesDrift,R=0,L=E;R=w*u&&I<1e4&&L){var P=Math.round(C/u);A.b.warn("Injecting "+P+" audio frame @ "+(L/i).toFixed(3)+"s due to "+Math.round(1e3*C/i)+" ms gap.");for(var O=0;O0&&G<1e4)j=Math.round((B-E)/u),A.b.log(G+" ms hole between AAC samples detected,filling it"),j>0&&(p=W.getSilentFrame(e.manifestCodec||e.codec,e.channelCount),p||(p=U.subarray()),e.len+=j*p.length);else if(G<-12){A.b.log("drop overlapping AAC sample, expected/parsed/delta:"+(E/i).toFixed(3)+"s/"+(B/i).toFixed(3)+"s/"+-G+"ms"),e.len-=U.byteLength;continue}B=E}if(y=B,!(e.len>0))return;var K=d?e.len:e.len+8;f=d?0:8;try{g=new Uint8Array(K)}catch(e){return void this.observer.trigger(T.a.ERROR,{type:S.b.MUX_ERROR,details:S.a.REMUX_ALLOC_ERROR,fatal:!1,bytes:K,reason:"fail allocating audio mdat "+K})}if(!d){new DataView(g.buffer).setUint32(0,K),g.set(V.types.mdat,4)}for(var H=0;H=2&&(q=_[z-2].duration,h.duration=q),z){this.nextAudioPts=E=m+o*q,e.len=0,e.samples=_,v=d?new Uint8Array:V.moof(e.sequenceNumber++,y/o,e),e.samples=[];var X=y/i,Q=E/i,J={data1:v,data2:g,startPTS:X,endPTS:Q,startDTS:X,endDTS:Q,type:"audio",hasAudio:!0,hasVideo:!1,nb:z};return this.observer.trigger(T.a.FRAG_PARSING_DATA,J),J}return null}},e.prototype.remuxEmptyAudio=function(e,t,r,n){var i=e.inputTimeScale,a=e.samplerate?e.samplerate:i,o=i/a,s=this.nextAudioPts,u=(void 0!==s?s:n.startDTS*i)+this._initDTS,l=n.endDTS*i+this._initDTS,c=1024*o,d=Math.ceil((l-u)/c),f=W.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);if(A.b.warn("remux empty Audio"),!f)return void A.b.trace("Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec!");for(var h=[],p=0;p4294967296;)e+=r;return e},e}(),X=z,Q=function(){function e(t){E(this,e),this.observer=t}return e.prototype.destroy=function(){},e.prototype.resetTimeStamp=function(){},e.prototype.resetInitSegment=function(){},e.prototype.remux=function(e,t,r,n,i,a,o,s){var u=this.observer,l="";e&&(l+="audio"),t&&(l+="video"),u.trigger(T.a.FRAG_PARSING_DATA,{data1:s,startPTS:i,startDTS:i,type:l,hasAudio:!!e,hasVideo:!!t,nb:1,dropped:0}),u.trigger(T.a.FRAG_PARSED)},e}(),J=Q,$=Object(L.a)(),Z=$,ee=function(){function e(t,r,n,i){w(this,e),this.observer=t,this.typeSupported=r,this.config=n,this.vendor=i}return e.prototype.destroy=function(){var e=this.demuxer;e&&e.destroy()},e.prototype.push=function(e,t,r,n,i,a,o,s,u,l,c,d){if(e.byteLength>0&&null!=t&&null!=t.key&&"AES-128"===t.method){var f=this.decrypter;null==f&&(f=this.decrypter=new R.a(this.observer,this.config));var h=this,p=void 0;try{p=Z.now()}catch(e){p=Date.now()}f.decrypt(e,t.key.buffer,t.iv.buffer,function(e){var f=void 0;try{f=Z.now()}catch(e){f=Date.now()}h.observer.trigger(T.a.FRAG_DECRYPTED,{stats:{tstart:p,tdecrypt:f}}),h.pushDecrypted(new Uint8Array(e),t,new Uint8Array(r),n,i,a,o,s,u,l,c,d)})}else this.pushDecrypted(new Uint8Array(e),t,new Uint8Array(r),n,i,a,o,s,u,l,c,d)},e.prototype.pushDecrypted=function(e,t,r,n,i,a,o,s,u,l,c,d){var f=this.demuxer;if(!f||(o||s)&&!this.probe(e)){for(var h=this.observer,p=this.typeSupported,g=this.config,v=[{demux:G,remux:X},{demux:I.a,remux:J},{demux:D,remux:X},{demux:K,remux:X}],y=0,m=v.length;yt?n.start+n.duration:Math.max(n.start-i.duration,0):r>t?(n.duration=a-n.start,n.duration<0&&Je.b.warn("negative duration computed for frag "+n.sn+",level "+n.level+", there should be some duration drift between playlist and fragment!")):(i.duration=n.start-a,i.duration<0&&Je.b.warn("negative duration computed for frag "+i.sn+",level "+i.level+", there should be some duration drift between playlist and fragment!"))}function L(e,t,r,n,i,a){var o=r;if(!isNaN(t.startPTS)){var s=Math.abs(t.startPTS-r);isNaN(t.deltaPTS)?t.deltaPTS=s:t.deltaPTS=Math.max(s,t.deltaPTS),o=Math.max(r,t.startPTS),r=Math.min(r,t.startPTS),n=Math.max(n,t.endPTS),i=Math.min(i,t.startDTS),a=Math.max(a,t.endDTS)}var u=r-t.start;t.start=t.startPTS=r,t.maxStartPTS=o,t.endPTS=n,t.startDTS=i,t.endDTS=a,t.duration=n-r;var l=t.sn;if(!e||le.endSN)return 0;var c=void 0,d=void 0,f=void 0;for(c=l-e.startSN,d=e.fragments,d[c]=t,f=c;f>0;f--)A(d,f,f-1);for(f=c;f=0&&it?-1:0})}function I(e,t,r){var n=!1;return t&&t.details&&r&&(r.endCC>r.startCC||e&&e.cc0&&void 0!==arguments[0]?arguments[0]:0,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments[2],n=0;if(r.programDateTime){var i=Date.parse(r.programDateTime);isNaN(i)||(n=1e3*t+i-1e3*e)}return n}function B(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;if(!Array.isArray(e)||!e.length||null===t)return null;if(t=e[e.length-1].endPdt)return null;for(var r=0;r2&&void 0!==arguments[2]?arguments[2]:0,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0,a=void 0,o=e?t[e.sn-t[0].sn+1]:null;return rn-i&&(i=0),a=o&&!j(r,i,o)?o:Mt.search(t,j.bind(null,r,i))),a}function j(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments[2],n=Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return r.start+r.duration-n<=e?1:r.start-n>e&&r.start?-1:0}function K(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function H(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 W(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)}function Y(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function q(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 V(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)}function z(e,t){var r=null;try{r=new window.Event("addtrack")}catch(e){r=document.createEvent("Event"),r.initEvent("addtrack",!1,!1)}r.track=e,t.dispatchEvent(r)}function X(e){if(e&&e.cues)for(;e.cues.length>0;)e.removeCue(e.cues[0])}function Q(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function J(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 $(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)}function Z(){var e=T(),t=window.SourceBuffer||window.WebKitSourceBuffer,r=e&&"function"==typeof e.isTypeSupported&&e.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"'),n=!t||t.prototype&&"function"==typeof t.prototype.appendBuffer&&"function"==typeof t.prototype.remove;return!!r&&!!n}function ee(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function te(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function re(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function ne(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 ie(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)}function ae(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function oe(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 se(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)}function ue(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function le(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 ce(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)}function de(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function fe(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 he(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)}function pe(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function ge(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function ve(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 ye(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)}function me(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function be(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 _e(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)}function Ee(){this.window=window,this.state="INITIAL",this.buffer="",this.decoder=new Wr,this.regionList=[]}function we(e){function t(e,t,r,n){return 3600*(0|e)+60*(0|t)+(0|r)+(0|n)/1e3}var r=e.match(/^(\d+):(\d{2})(:\d{2})?\.(\d{3})/);return r?r[3]?t(r[1],r[2],r[3].replace(":",""),r[4]):r[1]>59?t(r[1],r[2],0,r[4]):t(0,r[1],r[2],r[4]):null}function Te(){this.values=Object.create(null)}function Se(e,t,r,n){var i=n?e.split(n):[e];for(var a in i)if("string"==typeof i[a]){var o=i[a].split(r);if(2===o.length){var s=o[0],u=o[1];t(s,u)}}}function Re(e,t,r){function n(){var t=we(e);if(null===t)throw new Error("Malformed timestamp: "+a);return e=e.replace(/^[^\sa-zA-Z-]+/,""),t}function i(){e=e.replace(/^\s+/,"")}var a=e;if(i(),t.startTime=n(),i(),"--\x3e"!==e.substr(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+a);e=e.substr(3),i(),t.endTime=n(),i(),function(e,t){var n=new Te;Se(e,function(e,t){switch(e){case"region":for(var i=r.length-1;i>=0;i--)if(r[i].id===t){n.set(e,r[i].region);break}break;case"vertical":n.alt(e,t,["rl","lr"]);break;case"line":var a=t.split(","),o=a[0];n.integer(e,o),n.percent(e,o)&&n.set("snapToLines",!1),n.alt(e,o,["auto"]),2===a.length&&n.alt("lineAlign",a[1],["start",qr,"end"]);break;case"position":a=t.split(","),n.percent(e,a[0]),2===a.length&&n.alt("positionAlign",a[1],["start",qr,"end","line-left","line-right","auto"]);break;case"size":n.percent(e,t);break;case"align":n.alt(e,t,["start",qr,"end","left","right"])}},/:/,/\s/),t.region=n.get("region",null),t.vertical=n.get("vertical","");var i=n.get("line","auto");"auto"===i&&-1===Yr.line&&(i=-1),t.line=i,t.lineAlign=n.get("lineAlign","start"),t.snapToLines=n.get("snapToLines",!0),t.size=n.get("size",100),t.align=n.get("align",qr);var a=n.get("position","auto");"auto"===a&&50===Yr.position&&(a="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=a}(e,t)}function Ae(e){return e.replace(//gi,"\n")}function Le(e,t,r,n){for(var i=void 0,a=void 0,o=void 0,s=void 0,u=void 0,l=window.VTTCue||window.TextTrackCue,c=0;c=16?s--:s++,navigator.userAgent.match(/Firefox\//)?a.line=c+1:a.line=c>7?c-2:c+1,a.align="left",a.position=Math.max(0,Math.min(100,s/32*100+(navigator.userAgent.match(/Firefox\//)?50:0))),e.addCue(a)}}function Ce(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function ke(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function De(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function Ie(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 Pe(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)}function Oe(e,t){return e&&e.label===t.name&&!(e.textTrack1||e.textTrack2)}function xe(e,t,r,n){return Math.min(t,n)-Math.max(e,r)}function Me(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function Fe(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 Ne(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)}function Ue(e){for(var t=[],r=0;r1?r-1:0),a=1;a>8*(15-r)&255;return t},e.prototype.fragmentDecryptdataFromLevelkey=function(e,t){var r=e;return e&&e.method&&e.uri&&!e.iv&&(r=new at,r.method=e.method,r.baseuri=e.baseuri,r.reluri=e.reluri,r.iv=this.createInitializationVector(t)),r},ot(e,[{key:"url",get:function(){return!this._url&&this.relurl&&(this._url=ze.a.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url},set:function(e){this._url=e}},{key:"programDateTime",get:function(){return!this._programDateTime&&this.rawProgramDateTime&&(this._programDateTime=new Date(Date.parse(this.rawProgramDateTime))),this._programDateTime}},{key:"byteRange",get:function(){if(!this._byteRange&&!this.rawByteRange)return[];if(this._byteRange)return this._byteRange;var e=[];if(this.rawByteRange){var t=this.rawByteRange.split("@",2);if(1===t.length){var r=this.lastByteRangeEndOffset;e[0]=r||0}else e[0]=parseInt(t[1]);e[1]=parseInt(t[0])+e[0],this._byteRange=e}return e}},{key:"byteRangeStartOffset",get:function(){return this.byteRange[0]}},{key:"byteRangeEndOffset",get:function(){return this.byteRange[1]}},{key:"decryptdata",get:function(){return this._decryptdata||(this._decryptdata=this.fragmentDecryptdataFromLevelkey(this.levelkey,this.sn)),this._decryptdata}},{key:"encrypted",get:function(){return!(!this.decryptdata||null===this.decryptdata.uri||null!==this.decryptdata.key)}}],[{key:"ElementaryStreamTypes",get:function(){return{AUDIO:"audio",VIDEO:"video"}}}]),e}(),ut=st,lt=/^(\d+)x(\d+)$/,ct=/\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g,dt=function(){function e(t){o(this,e),"string"==typeof t&&(t=e.parseAttrList(t));for(var r in t)t.hasOwnProperty(r)&&(this[r]=t[r])}return e.prototype.decimalInteger=function(e){var t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t},e.prototype.hexadecimalInteger=function(e){if(this[e]){var t=(this[e]||"0x").slice(2);t=(1&t.length?"0":"")+t;for(var r=new Uint8Array(t.length/2),n=0;nNumber.MAX_SAFE_INTEGER?1/0:t},e.prototype.decimalFloatingPoint=function(e){return parseFloat(this[e])},e.prototype.enumeratedString=function(e){return this[e]},e.prototype.decimalResolution=function(e){var t=lt.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}},e.parseAttrList=function(e){var t=void 0,r={};for(ct.lastIndex=0;null!==(t=ct.exec(e));){var n=t[2];0===n.indexOf('"')&&n.lastIndexOf('"')===n.length-1&&(n=n.slice(1,-1)),r[t[1]]=n}return r},e}(),ft=dt,ht={audio:{a3ds:!0,"ac-3":!0,"ac-4":!0,alac:!0,alaw:!0,dra1:!0,"dts+":!0,"dts-":!0,dtsc:!0,dtse:!0,dtsh:!0,"ec-3":!0,enca:!0,g719:!0,g726:!0,m4ae:!0,mha1:!0,mha2:!0,mhm1:!0,mhm2:!0,mlpa:!0,mp4a:!0,"raw ":!0,Opus:!0,samr:!0,sawb:!0,sawp:!0,sevc:!0,sqcp:!0,ssmv:!0,twos:!0,ulaw:!0},video:{avc1:!0,avc2:!0,avc3:!0,avc4:!0,avcp:!0,drac:!0,dvav:!0,dvhe:!0,encv:!0,hev1:!0,hvc1:!0,mjp2:!0,mp4v:!0,mvc1:!0,mvc2:!0,mvc3:!0,mvc4:!0,resv:!0,rv60:!0,s263:!0,svc1:!0,svc2:!0,"vc-1":!0,vp08:!0,vp09:!0}},pt=/#EXT-X-STREAM-INF:([^\n\r]*)[\r\n]+([^\r\n]+)/g,gt=/#EXT-X-MEDIA:(.*)/g,vt=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/|(?!#)(\S+)/.source,/|#EXT-X-BYTERANGE:*(.+)/.source,/|#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/|#.*/.source].join(""),"g"),yt=/(?:(?:#(EXTM3U))|(?:#EXT-X-(PLAYLIST-TYPE):(.+))|(?:#EXT-X-(MEDIA-SEQUENCE): *(\d+))|(?:#EXT-X-(TARGETDURATION): *(\d+))|(?:#EXT-X-(KEY):(.+))|(?:#EXT-X-(START):(.+))|(?:#EXT-X-(ENDLIST))|(?:#EXT-X-(DISCONTINUITY-SEQ)UENCE:(\d+))|(?:#EXT-X-(DIS)CONTINUITY))|(?:#EXT-X-(VERSION):(\d+))|(?:#EXT-X-(MAP):(.+))|(?:(#)(.*):(.*))|(?:(#)(.*))(?:.*)\r?\n?/,mt=/\.(mp4|m4s|m4v|m4a)$/i,bt=function(){function e(){l(this,e)}return e.findGroup=function(e,t){if(!e)return null;for(var r=null,n=0;n2?(t=r.shift()+".",t+=parseInt(r.shift()).toString(16),t+=("000"+parseInt(r.shift()).toString(16)).substr(-4)):t=e,t},e.resolve=function(e,t){return ze.a.buildAbsoluteURL(t,e,{alwaysNormalize:!0})},e.parseMasterPlaylist=function(t,r){var n=[],i=void 0;for(pt.lastIndex=0;null!=(i=pt.exec(t));){var a={},o=a.attrs=new ft(i[1]);a.url=e.resolve(i[2],r);var u=o.decimalResolution("RESOLUTION");u&&(a.width=u.width,a.height=u.height),a.bitrate=o.decimalInteger("AVERAGE-BANDWIDTH")||o.decimalInteger("BANDWIDTH"),a.name=o.NAME,function(e,t){["video","audio"].forEach(function(r){var n=e.filter(function(e){return s(e,r)});if(n.length){var i=n.filter(function(e){return 0===e.lastIndexOf("avc1",0)||0===e.lastIndexOf("mp4a",0)});t[r+"Codec"]=i.length>0?i[0]:n[0],e=e.filter(function(e){return-1===n.indexOf(e)})}}),t.unknownCodecs=e}([].concat((o.CODECS||"").split(/[ ,]+/)),a),a.videoCodec&&-1!==a.videoCodec.indexOf("avc1")&&(a.videoCodec=e.convertAVC1ToAVCOTI(a.videoCodec)),n.push(a)}return n},e.parseMasterPlaylistMedia=function(t,r,n){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:[],a=void 0,o=[],s=0;for(gt.lastIndex=0;null!==(a=gt.exec(t));){var u={},l=new ft(a[1]);if(l.TYPE===n){if(u.groupId=l["GROUP-ID"],u.name=l.NAME,u.type=n,u.default="YES"===l.DEFAULT,u.autoselect="YES"===l.AUTOSELECT,u.forced="YES"===l.FORCED,l.URI&&(u.url=e.resolve(l.URI,r)),u.lang=l.LANGUAGE,u.name||(u.name=u.lang),i.length){var c=e.findGroup(i,u.groupId);u.audioCodec=c?c.codec:i[0].codec}u.id=s++,o.push(u)}}return o},e.parseLevelPlaylist=function(e,t,r,n,i){var a=0,o=0,s={type:null,version:null,url:t,fragments:[],live:!0,startSN:0},u=new at,l=0,c=null,d=new ut,f=void 0,h=void 0;for(vt.lastIndex=0;null!==(f=vt.exec(e));){var p=f[1];if(p){d.duration=parseFloat(p);var g=(" "+f[2]).slice(1);d.title=g||null,d.tagList.push(g?["INF",p,g]:["INF",p])}else if(f[3]){if(!isNaN(d.duration)){var v=a++;d.type=n,d.start=o,d.levelkey=u,d.sn=v,d.level=r,d.cc=l,d.urlId=i,d.baseurl=t,d.relurl=(" "+f[3]).slice(1),s.programDateTime&&(c?d.rawProgramDateTime?d.pdt=Date.parse(d.rawProgramDateTime):d.pdt=c.pdt+1e3*c.duration:d.pdt=Date.parse(s.programDateTime),d.endPdt=d.pdt+1e3*d.duration),s.fragments.push(d),c=d,o+=d.duration,d=new ut}}else if(f[4]){if(d.rawByteRange=(" "+f[4]).slice(1),c){var y=c.byteRangeEndOffset;y&&(d.lastByteRangeEndOffset=y)}}else if(f[5])d.rawProgramDateTime=(" "+f[5]).slice(1),d.tagList.push(["PROGRAM-DATE-TIME",d.rawProgramDateTime]),void 0===s.programDateTime&&(s.programDateTime=new Date(new Date(Date.parse(f[5]))-1e3*o));else{for(f=f[0].match(yt),h=1;h=0&&(u.method=w,u.baseuri=t,u.reluri=T,u.key=null,u.iv=S));break;case"START":var R=m,A=new ft(R),L=A.decimalFloatingPoint("TIME-OFFSET");isNaN(L)||(s.startTimeOffset=L);break;case"MAP":var C=new ft(m);d.relurl=C.URI,d.rawByteRange=C.BYTERANGE,d.baseurl=t,d.level=r,d.type=n,d.sn="initSegment",s.initSegment=d,d=new ut;break;default:Je.b.warn("line parsed but not handled: "+f)}}}return d=c,d&&!d.relurl&&(s.fragments.pop(),o-=d.duration),s.totalduration=o,s.averagetargetduration=o/s.fragments.length,s.endSN=a-1,s.startCC=s.fragments[0]?s.fragments[0].cc:0,s.endCC=l,!s.initSegment&&s.fragments.length&&s.fragments.every(function(e){return mt.test(e.relurl)})&&(Je.b.warn("MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX"),d=new ut,d.relurl=s.fragments[0].relurl,d.baseurl=t,d.level=r,d.type=n,d.sn="initSegment",s.initSegment=d,s.needSidxRanges=!0),s},e}(),_t=bt,Et=function(){function e(e,t){for(var r=0;r3&&void 0!==arguments[3]?arguments[3]:null;if(r.isSidxRequest)return this._handleSidxRequest(e,r),void this._handlePlaylistLoaded(e,t,r,n);this.resetInternalLoader(r.type);var i=e.data;if(t.tload=Tt.now(),0!==i.indexOf("#EXTM3U"))return void this._handleManifestParsingError(e,r,"no EXTM3U delimiter",n);i.indexOf("#EXTINF:")>0||i.indexOf("#EXT-X-TARGETDURATION:")>0?this._handleTrackOrLevelPlaylist(e,t,r,n):this._handleMasterPlaylist(e,t,r,n)},t.prototype.loaderror=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;this._handleNetworkError(t,r)},t.prototype.loadtimeout=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;this._handleNetworkError(t,r,!0)},t.prototype._handleMasterPlaylist=function(e,r,n,i){var a=this.hls,o=e.data,s=t.getResponseUrl(e,n),u=_t.parseMasterPlaylist(o,s);if(!u.length)return void this._handleManifestParsingError(e,n,"no level found in manifest",i);var l=u.map(function(e){return{id:e.attrs.AUDIO,codec:e.audioCodec}}),c=_t.parseMasterPlaylistMedia(o,s,"AUDIO",l),d=_t.parseMasterPlaylistMedia(o,s,"SUBTITLES");if(c.length){var f=!1;c.forEach(function(e){e.url||(f=!0)}),!1===f&&u[0].audioCodec&&!u[0].attrs.AUDIO&&(Je.b.log("audio codec signaled in quality level, but no embedded audio track signaled, create one"),c.unshift({type:"main",name:"main"}))}a.trigger(Qe.a.MANIFEST_LOADED,{levels:u,audioTracks:c,subtitles:d,url:s,stats:r,networkDetails:i})},t.prototype._handleTrackOrLevelPlaylist=function(e,r,n,i){var a=this.hls,o=n.id,s=n.level,u=n.type,l=t.getResponseUrl(e,n),c=isNaN(o)?0:o,d=isNaN(s)?c:s,f=t.mapContextToLevelType(n),h=_t.parseLevelPlaylist(e.data,l,d,f,c);if(h.tload=r.tload,u===St.MANIFEST){var p={url:l,details:h};a.trigger(Qe.a.MANIFEST_LOADED,{levels:[p],audioTracks:[],url:l,stats:r,networkDetails:i})}if(r.tparsed=Tt.now(),h.needSidxRanges){var g=h.initSegment.url;return void this.load(g,{isSidxRequest:!0,type:u,level:s,levelDetails:h,id:o,rangeStart:0,rangeEnd:2048,responseType:"arraybuffer"})}n.levelDetails=h,this._handlePlaylistLoaded(e,r,n,i)},t.prototype._handleSidxRequest=function(e,t){var r=rt.a.parseSegmentIndex(new Uint8Array(e.data));r.references.forEach(function(e,r){var n=e.info,i=t.levelDetails.fragments[r];0===i.byteRange.length&&(i.rawByteRange=String(1+n.end-n.start)+"@"+String(n.start))}),t.levelDetails.initSegment.rawByteRange=String(r.moovEndOffset)+"@0"},t.prototype._handleManifestParsingError=function(e,t,r,n){this.hls.trigger(Qe.a.ERROR,{type:Xe.b.NETWORK_ERROR,details:Xe.a.MANIFEST_PARSING_ERROR,fatal:!0,url:e.url,reason:r,networkDetails:n})},t.prototype._handleNetworkError=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];Je.b.info("A network error occured while loading a "+e.type+"-type playlist");var n=void 0,i=void 0,a=this.getInternalLoader(e);switch(e.type){case St.MANIFEST:n=r?Xe.a.MANIFEST_LOAD_TIMEOUT:Xe.a.MANIFEST_LOAD_ERROR,i=!0;break;case St.LEVEL:n=r?Xe.a.LEVEL_LOAD_TIMEOUT:Xe.a.LEVEL_LOAD_ERROR,i=!1;break;case St.AUDIO_TRACK:n=r?Xe.a.AUDIO_TRACK_LOAD_TIMEOUT:Xe.a.AUDIO_TRACK_LOAD_ERROR,i=!1;break;default:i=!1}a&&(a.abort(),this.resetInternalLoader(e.type)),this.hls.trigger(Qe.a.ERROR,{type:Xe.b.NETWORK_ERROR,details:n,fatal:i,url:a.url,loader:a,context:e,networkDetails:t})},t.prototype._handlePlaylistLoaded=function(e,r,n,i){var a=n.type,o=n.level,s=n.id,u=n.levelDetails;if(!u.targetduration)return void this._handleManifestParsingError(e,n,"invalid target duration",i);if(t.canHaveQualityLevels(n.type))this.hls.trigger(Qe.a.LEVEL_LOADED,{details:u,level:o||0,id:s||0,stats:r,networkDetails:i});else switch(a){case St.AUDIO_TRACK:this.hls.trigger(Qe.a.AUDIO_TRACK_LOADED,{details:u,id:s,stats:r,networkDetails:i});break;case St.SUBTITLE_TRACK:this.hls.trigger(Qe.a.SUBTITLE_TRACK_LOADED,{details:u,id:s,stats:r,networkDetails:i})}},Et(t,null,[{key:"ContextType",get:function(){return St}},{key:"LevelType",get:function(){return Rt}}]),t}(tt),Lt=At,Ct=function(e){function t(r){h(this,t);var n=p(this,e.call(this,r,Qe.a.FRAG_LOADING));return n.loaders={},n}return g(t,e),t.prototype.destroy=function(){var t=this.loaders;for(var r in t){var n=t[r];n&&n.destroy()}this.loaders={},e.prototype.destroy.call(this)},t.prototype.onFragLoading=function(e){var t=e.frag,r=t.type,n=this.loaders,i=this.hls.config,a=i.fLoader,o=i.loader;t.loaded=0;var s=n[r];s&&(Je.b.warn("abort previous fragment loader for type: "+r),s.abort()),s=n[r]=t.loader=i.fLoader?new a(i):new o(i);var u=void 0,l=void 0,c=void 0;u={url:t.url,frag:t,responseType:"arraybuffer",progressData:!1};var d=t.byteRangeStartOffset,f=t.byteRangeEndOffset;isNaN(d)||isNaN(f)||(u.rangeStart=d,u.rangeEnd=f),l={timeout:i.fragLoadingTimeOut,maxRetry:0,retryDelay:0,maxRetryDelay:i.fragLoadingMaxRetryTimeout},c={onSuccess:this.loadsuccess.bind(this),onError:this.loaderror.bind(this),onTimeout:this.loadtimeout.bind(this),onProgress:this.loadprogress.bind(this)},s.load(u,l,c)},t.prototype.loadsuccess=function(e,t,r){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,i=e.data,a=r.frag;a.loader=void 0,this.loaders[a.type]=void 0,this.hls.trigger(Qe.a.FRAG_LOADED,{payload:i,frag:a,stats:t,networkDetails:n})},t.prototype.loaderror=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,n=t.loader;n&&n.abort(),this.loaders[t.type]=void 0,this.hls.trigger(Qe.a.ERROR,{type:Xe.b.NETWORK_ERROR,details:Xe.a.FRAG_LOAD_ERROR,fatal:!1,frag:t.frag,response:e,networkDetails:r})},t.prototype.loadtimeout=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,n=t.loader;n&&n.abort(),this.loaders[t.type]=void 0,this.hls.trigger(Qe.a.ERROR,{type:Xe.b.NETWORK_ERROR,details:Xe.a.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t.frag,networkDetails:r})},t.prototype.loadprogress=function(e,t,r){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,i=t.frag;i.loaded=e.loaded,this.hls.trigger(Qe.a.FRAG_LOAD_PROGRESS,{frag:i,stats:e,networkDetails:n})},t}(tt),kt=Ct,Dt=function(e){function t(r){v(this,t);var n=y(this,e.call(this,r,Qe.a.KEY_LOADING));return n.loaders={},n.decryptkey=null,n.decrypturl=null,n}return m(t,e),t.prototype.destroy=function(){for(var e in this.loaders){var t=this.loaders[e];t&&t.destroy()}this.loaders={},tt.prototype.destroy.call(this)},t.prototype.onKeyLoading=function(e){var t=e.frag,r=t.type,n=this.loaders[r],i=t.decryptdata,a=i.uri;if(a!==this.decrypturl||null===this.decryptkey){var o=this.hls.config;n&&(Je.b.warn("abort previous key loader for type:"+r),n.abort()),t.loader=this.loaders[r]=new o.loader(o),this.decrypturl=a,this.decryptkey=null;var s=void 0,u=void 0,l=void 0;s={url:a,frag:t,responseType:"arraybuffer"},u={timeout:o.fragLoadingTimeOut,maxRetry:o.fragLoadingMaxRetry,retryDelay:o.fragLoadingRetryDelay,maxRetryDelay:o.fragLoadingMaxRetryTimeout},l={onSuccess:this.loadsuccess.bind(this),onError:this.loaderror.bind(this),onTimeout:this.loadtimeout.bind(this)},t.loader.load(s,u,l)}else this.decryptkey&&(i.key=this.decryptkey,this.hls.trigger(Qe.a.KEY_LOADED,{frag:t}))},t.prototype.loadsuccess=function(e,t,r){var n=r.frag;this.decryptkey=n.decryptdata.key=new Uint8Array(e.data),n.loader=void 0,this.loaders[n.type]=void 0,this.hls.trigger(Qe.a.KEY_LOADED,{frag:n})},t.prototype.loaderror=function(e,t){var r=t.frag,n=r.loader;n&&n.abort(),this.loaders[t.type]=void 0,this.hls.trigger(Qe.a.ERROR,{type:Xe.b.NETWORK_ERROR,details:Xe.a.KEY_LOAD_ERROR,fatal:!1,frag:r,response:e})},t.prototype.loadtimeout=function(e,t){var r=t.frag,n=r.loader;n&&n.abort(),this.loaders[t.type]=void 0,this.hls.trigger(Qe.a.ERROR,{type:Xe.b.NETWORK_ERROR,details:Xe.a.KEY_LOAD_TIMEOUT,fatal:!1,frag:r})},t}(tt),It=Dt,Pt={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"},Ot=function(e){function t(r){b(this,t);var n=_(this,e.call(this,r,Qe.a.BUFFER_APPENDED,Qe.a.FRAG_BUFFERED,Qe.a.FRAG_LOADED));return n.bufferPadding=.2,n.fragments=Object.create(null),n.timeRanges=Object.create(null),n.config=r.config,n}return E(t,e),t.prototype.destroy=function(){this.fragments=null,this.timeRanges=null,this.config=null,tt.prototype.destroy.call(this),e.prototype.destroy.call(this)},t.prototype.getBufferedFrag=function(e,t){var r=this.fragments,n=Object.keys(r).filter(function(n){var i=r[n];if(i.body.type!==t)return!1;if(!i.buffered)return!1;var a=i.body;return a.startPTS<=e&&e<=a.endPTS});if(0===n.length)return null;var i=n.pop();return r[i].body},t.prototype.detectEvictedFragments=function(e,t){var r=this,n=void 0,i=void 0;Object.keys(this.fragments).forEach(function(a){var o=r.fragments[a];if(!0===o.buffered){var s=o.range[e];if(s){n=s.time;for(var u=0;u=i&&t<=a){n.push({startPTS:Math.max(e,r.start(s)),endPTS:Math.min(t,r.end(s))});break}if(ei)n.push({startPTS:Math.max(e,r.start(s)),endPTS:Math.min(t,r.end(s))}),o=!0;else if(t<=i)break}return{time:n,partial:o}},t.prototype.getFragmentKey=function(e){return e.type+"_"+e.level+"_"+e.urlId+"_"+e.sn},t.prototype.getPartialFragment=function(e){var t=this,r=void 0,n=void 0,i=void 0,a=null,o=0;return Object.keys(this.fragments).forEach(function(s){var u=t.fragments[s];t.isPartial(u)&&(n=u.body.startPTS-t.bufferPadding,i=u.body.endPTS+t.bufferPadding,e>=n&&e<=i&&(r=Math.min(e-n,i-e),o<=r&&(a=u.body,o=r)))}),a},t.prototype.getState=function(e){var t=this.getFragmentKey(e),r=this.fragments[t],n=Pt.NOT_LOADED;return void 0!==r&&(n=r.buffered?!0===this.isPartial(r)?Pt.PARTIAL:Pt.OK:Pt.APPENDING),n},t.prototype.isPartial=function(e){return!0===e.buffered&&(void 0!==e.range.video&&!0===e.range.video.partial||void 0!==e.range.audio&&!0===e.range.audio.partial)},t.prototype.isTimeBuffered=function(e,t,r){for(var n=void 0,i=void 0,a=0;a=n&&t<=i)return!0;if(t<=n)return!1}return!1},t.prototype.onFragLoaded=function(e){var t=e.frag;if(!isNaN(t.sn)&&!t.bitrateTest){var r=this.getFragmentKey(t),n={body:t,range:Object.create(null),buffered:!1};this.fragments[r]=n}},t.prototype.onBufferAppended=function(e){var t=this;this.timeRanges=e.timeRanges,Object.keys(this.timeRanges).forEach(function(e){var r=t.timeRanges[e];t.detectEvictedFragments(e,r)})},t.prototype.onFragBuffered=function(e){this.detectPartialFragments(e.frag)},t.prototype.hasFragment=function(e){var t=this.getFragmentKey(e);return void 0!==this.fragments[t]},t.prototype.removeFragment=function(e){var t=this.getFragmentKey(e);delete this.fragments[t]},t.prototype.removeAllFragments=function(){this.fragments=Object.create(null)},t}(tt),xt={search:function(e,t){for(var r=0,n=e.length-1,i=null,a=null;r<=n;){i=(r+n)/2|0,a=e[i];var o=t(a);if(o>0)r=i+1;else{if(!(o<0))return a;n=i-1}}return null}},Mt=xt,Ft=function(){function e(){w(this,e)}return e.isBuffered=function(e,t){try{if(e)for(var r=e.buffered,n=0;n=r.start(n)&&t<=r.end(n))return!0}catch(e){}return!1},e.bufferInfo=function(e,t,r){try{if(e){var n=e.buffered,i=[],a=void 0;for(a=0;ac&&(n[l-1].end=e[u].end):n.push(e[u])}else n.push(e[u])}for(u=0,i=0,a=o=t;u=d&&t1?t-1:0),i=1;i1?t-1:0),i=1;i1?n-1:0),a=1;a1&&(this.clearNextTick(),this._tickTimer=setTimeout(this._boundTick,0)),this._tickCallCount=0)},t.prototype.doTick=function(){},t}(tt),Qt=Xt,Jt=function(){function e(e,t){for(var r=0;r0&&-1===e&&(Je.b.log("override startPosition with lastCurrentTime @"+t.toFixed(3)),e=t),this.state=$t.IDLE,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}else this.forceStartLoad=!0,this.state=$t.STOPPED},t.prototype.stopLoad=function(){var e=this.fragCurrent;e&&(e.loader&&e.loader.abort(),this.fragmentTracker.removeFragment(e),this.fragCurrent=null),this.fragPrevious=null,this.demuxer&&(this.demuxer.destroy(),this.demuxer=null),this.clearInterval(),this.state=$t.STOPPED,this.forceStartLoad=!1},t.prototype.doTick=function(){switch(this.state){case $t.BUFFER_FLUSHING:this.fragLoadError=0;break;case $t.IDLE:this._doTickIdle();break;case $t.WAITING_LEVEL:var e=this.levels[this.level];e&&e.details&&(this.state=$t.IDLE);break;case $t.FRAG_LOADING_WAITING_RETRY:var t=window.performance.now(),r=this.retryDate;(!r||t>=r||this.media&&this.media.seeking)&&(Je.b.log("mediaController: retryDate reached, switch back to IDLE state"),this.state=$t.IDLE);break;case $t.ERROR:case $t.STOPPED:case $t.FRAG_LOADING:case $t.PARSING:case $t.PARSED:case $t.ENDED:}this._checkBuffer(),this._checkFragmentChanged()},t.prototype._doTickIdle=function(){var e=this.hls,t=e.config,r=this.media;if(void 0!==this.levelLastLoaded&&(r||!this.startFragRequested&&t.startFragPrefetch)){var n=void 0;n=this.loadedmetadata?r.currentTime:this.nextLoadPosition;var i=e.nextLoadLevel,a=this.levels[i];if(a){var o=a.bitrate,s=void 0;s=o?Math.max(8*t.maxBufferSize/o,t.maxBufferLength):t.maxBufferLength,s=Math.min(s,t.maxMaxBufferLength);var u=Ft.bufferInfo(this.mediaBuffer?this.mediaBuffer:r,n,t.maxBufferHole),l=u.len;if(!(l>=s)){Je.b.trace("buffer length of "+l.toFixed(3)+" is below max of "+s.toFixed(3)+". checking for more payload ..."),this.level=e.nextLoadLevel=i;var c=a.details;if(!c||c.live&&this.levelLastLoaded!==i)return void(this.state=$t.WAITING_LEVEL);var d=this.fragPrevious;if(!c.live&&d&&!d.backtracked&&d.sn===c.endSN&&!u.nextStart){if(Math.min(r.duration,d.start+d.duration)-Math.max(u.end,d.start)<=Math.max(.2,d.duration)){var f={};return this.altAudio&&(f.type="video"),this.hls.trigger(Qe.a.BUFFER_EOS,f),void(this.state=$t.ENDED)}}this._fetchPayloadOrEos(n,u,c)}}}},t.prototype._fetchPayloadOrEos=function(e,t,r){var n=this.fragPrevious,i=this.level,a=r.fragments,o=a.length;if(0!==o){var s=a[0].start,u=a[o-1].start+a[o-1].duration,l=t.end,c=void 0;if(r.initSegment&&!r.initSegment.data)c=r.initSegment;else if(r.live){var d=this.config.initialLiveManifestSize;if(od&&(u.currentTime=d),this.nextLoadPosition=d}if(e.PTSKnown&&t>n&&u&&u.readyState)return null;if(this.startFragRequested&&!e.PTSKnown){if(i)if(e.programDateTime)l=B(a,i.endPdt+1);else{var f=i.sn+1;if(f>=e.startSN&&f<=e.endSN){var h=a[f-e.startSN];i.cc===h.cc&&(l=h,Je.b.log("live playlist, switching playlist, load frag with next SN: "+l.sn))}l||(l=Mt.search(a,function(e){return i.cc-e.cc}))&&Je.b.log("live playlist, switching playlist, load frag with same CC: "+l.sn)}l||(l=a[Math.min(o-1,Math.round(o/2))],Je.b.log("live playlist, switching playlist, unknown, load middle frag : "+l.sn))}return l},t.prototype._findFragment=function(e,t,r,n,i,a,o){var s=this.hls.config,u=void 0,l=void 0;if(is.maxBufferHole&&t.dropped&&c?(u=f,Je.b.warn("SN just loaded, with large PTS gap between audio and video, maybe frag is not starting with a keyframe ? load previous one to try to overcome this")):(u=h,Je.b.log("SN just loaded, load next one: "+u.sn))}else u=null;else u.backtracked&&(h&&h.backtracked?(Je.b.warn("Already backtracked from fragment "+h.sn+", will not backtrack to fragment "+u.sn+". Loading fragment "+h.sn),u=h):(Je.b.warn("Loaded fragment with dropped frames, backtracking 1 segment to find a keyframe"),u.dropped=0,f?(u=f,u.backtracked=!0):c&&(u=null)))}return u},t.prototype._loadKey=function(e){this.state=$t.KEY_LOADING,this.hls.trigger(Qe.a.KEY_LOADING,{frag:e})},t.prototype._loadFragment=function(e){var t=this.fragmentTracker.getState(e);this.fragCurrent=e,this.startFragRequested=!0,isNaN(e.sn)||e.bitrateTest||(this.nextLoadPosition=e.start+e.duration),e.backtracked||t===Pt.NOT_LOADED||t===Pt.PARTIAL?(e.autoLevel=this.hls.autoLevelEnabled,e.bitrateTest=this.bitrateTest,this.hls.trigger(Qe.a.FRAG_LOADING,{frag:e}),this.demuxer||(this.demuxer=new qt(this.hls,"main")),this.state=$t.FRAG_LOADING):t===Pt.APPENDING&&this._reduceMaxBufferLength(e.duration)&&this.fragmentTracker.removeFragment(e)},t.prototype.getBufferedFrag=function(e){return this.fragmentTracker.getBufferedFrag(e,Lt.LevelType.MAIN)},t.prototype.followingBufferedFrag=function(e){return e?this.getBufferedFrag(e.endPTS+.5):null},t.prototype._checkFragmentChanged=function(){var e=void 0,t=void 0,r=this.media;if(r&&r.readyState&&!1===r.seeking&&(t=r.currentTime,t>this.lastCurrentTime&&(this.lastCurrentTime=t),Ft.isBuffered(r,t)?e=this.getBufferedFrag(t):Ft.isBuffered(r,t+.1)&&(e=this.getBufferedFrag(t+.1)),e)){var n=e;if(n!==this.fragPlaying){this.hls.trigger(Qe.a.FRAG_CHANGED,{frag:n});var i=n.level;this.fragPlaying&&this.fragPlaying.level===i||this.hls.trigger(Qe.a.LEVEL_SWITCHED,{level:i}),this.fragPlaying=n}}},t.prototype.immediateLevelSwitch=function(){if(Je.b.log("immediateLevelSwitch"),!this.immediateSwitch){this.immediateSwitch=!0;var e=this.media,t=void 0;e?(t=e.paused,e.pause()):t=!0,this.previouslyPaused=t}var r=this.fragCurrent;r&&r.loader&&r.loader.abort(),this.fragCurrent=null,this.flushMainBuffer(0,Number.POSITIVE_INFINITY)},t.prototype.immediateLevelSwitchEnd=function(){var e=this.media;e&&e.buffered.length&&(this.immediateSwitch=!1,Ft.isBuffered(e,e.currentTime)&&(e.currentTime-=1e-4),this.previouslyPaused||e.play())},t.prototype.nextLevelSwitch=function(){var e=this.media;if(e&&e.readyState){var t=void 0,r=void 0,n=void 0;if(r=this.getBufferedFrag(e.currentTime),r&&r.startPTS>1&&this.flushMainBuffer(0,r.startPTS-1),e.paused)t=0;else{var i=this.hls.nextLoadLevel,a=this.levels[i],o=this.fragLastKbps;t=o&&this.fragCurrent?this.fragCurrent.duration*a.bitrate/(1e3*o)+1:0}if((n=this.getBufferedFrag(e.currentTime+t))&&(n=this.followingBufferedFrag(n))){var s=this.fragCurrent;s&&s.loader&&s.loader.abort(),this.fragCurrent=null,this.flushMainBuffer(n.maxStartPTS,Number.POSITIVE_INFINITY)}}},t.prototype.flushMainBuffer=function(e,t){this.state=$t.BUFFER_FLUSHING;var r={startOffset:e,endOffset:t};this.altAudio&&(r.type="video"),this.hls.trigger(Qe.a.BUFFER_FLUSHING,r)},t.prototype.onMediaAttached=function(e){var t=this.media=this.mediaBuffer=e.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),this.onvended=this.onMediaEnded.bind(this),t.addEventListener("seeking",this.onvseeking),t.addEventListener("seeked",this.onvseeked),t.addEventListener("ended",this.onvended);var r=this.config;this.levels&&r.autoStartLoad&&this.hls.startLoad(r.startPosition)},t.prototype.onMediaDetaching=function(){var e=this.media;e&&e.ended&&(Je.b.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0);var t=this.levels;t&&t.forEach(function(e){e.details&&e.details.fragments.forEach(function(e){e.backtracked=void 0})}),e&&(e.removeEventListener("seeking",this.onvseeking),e.removeEventListener("seeked",this.onvseeked),e.removeEventListener("ended",this.onvended),this.onvseeking=this.onvseeked=this.onvended=null),this.media=this.mediaBuffer=null,this.loadedmetadata=!1,this.stopLoad()},t.prototype.onMediaSeeking=function(){var e=this.media,t=e?e.currentTime:void 0,r=this.config;isNaN(t)||Je.b.log("media seeking to "+t.toFixed(3));var n=this.mediaBuffer?this.mediaBuffer:e,i=Ft.bufferInfo(n,t,this.config.maxBufferHole);if(this.state===$t.FRAG_LOADING){var a=this.fragCurrent;if(0===i.len&&a){var o=r.maxFragLookUpTolerance,s=a.start-o,u=a.start+a.duration+o;tu?(a.loader&&(Je.b.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),a.loader.abort()),this.fragCurrent=null,this.fragPrevious=null,this.state=$t.IDLE):Je.b.log("seeking outside of buffer but within currently loaded fragment range")}}else this.state===$t.ENDED&&(0===i.len&&(this.fragPrevious=0),this.state=$t.IDLE);e&&(this.lastCurrentTime=t),this.loadedmetadata||(this.nextLoadPosition=this.startPosition=t),this.tick()},t.prototype.onMediaSeeked=function(){var e=this.media,t=e?e.currentTime:void 0;isNaN(t)||Je.b.log("media seeked to "+t.toFixed(3)),this.tick()},t.prototype.onMediaEnded=function(){Je.b.log("media ended"),this.startPosition=this.lastCurrentTime=0},t.prototype.onManifestLoading=function(){Je.b.log("trigger BUFFER_RESET"),this.hls.trigger(Qe.a.BUFFER_RESET),this.fragmentTracker.removeAllFragments(),this.stalled=!1,this.startPosition=this.lastCurrentTime=0},t.prototype.onManifestParsed=function(e){var t=!1,r=!1,n=void 0;e.levels.forEach(function(e){(n=e.audioCodec)&&(-1!==n.indexOf("mp4a.40.2")&&(t=!0),-1!==n.indexOf("mp4a.40.5")&&(r=!0))}),this.audioCodecSwitch=t&&r,this.audioCodecSwitch&&Je.b.log("both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=e.levels,this.startFragRequested=!1;var i=this.config;(i.autoStartLoad||this.forceStartLoad)&&this.hls.startLoad(i.startPosition)},t.prototype.onLevelLoaded=function(e){var t=e.details,r=e.level,n=this.levels[this.levelLastLoaded],i=this.levels[r],a=t.totalduration,o=0;if(Je.b.log("level "+r+" loaded ["+t.startSN+","+t.endSN+"],duration:"+a),t.live){var s=i.details;s&&t.fragments.length>0?(C(s,t),o=t.fragments[0].start,this.liveSyncPosition=this.computeLivePosition(o,s),t.PTSKnown&&!isNaN(o)?Je.b.log("live playlist sliding:"+o.toFixed(3)):(Je.b.log("live playlist - outdated PTS, unknown sliding"),x(this.fragPrevious,n,t))):(Je.b.log("live playlist - first load, unknown sliding"),t.PTSKnown=!1,x(this.fragPrevious,n,t))}else t.PTSKnown=!1;if(i.details=t,this.levelLastLoaded=r,this.hls.trigger(Qe.a.LEVEL_UPDATED,{details:t,level:r}),!1===this.startFragRequested){if(-1===this.startPosition||-1===this.lastCurrentTime){var u=t.startTimeOffset;isNaN(u)?t.live?(this.startPosition=this.computeLivePosition(o,t),Je.b.log("configure startPosition to "+this.startPosition)):this.startPosition=0:(u<0&&(Je.b.log("negative start time offset "+u+", count from end of last fragment"),u=o+a+u),Je.b.log("start time offset found in playlist, adjust startPosition to "+u),this.startPosition=u),this.lastCurrentTime=this.startPosition}this.nextLoadPosition=this.startPosition}this.state===$t.WAITING_LEVEL&&(this.state=$t.IDLE),this.tick()},t.prototype.onKeyLoaded=function(){this.state===$t.KEY_LOADING&&(this.state=$t.IDLE,this.tick())},t.prototype.onFragLoaded=function(e){var t=this.fragCurrent,r=e.frag;if(this.state===$t.FRAG_LOADING&&t&&"main"===r.type&&r.level===t.level&&r.sn===t.sn){var n=e.stats,i=this.levels[t.level],a=i.details;if(Je.b.log("Loaded "+t.sn+" of ["+a.startSN+" ,"+a.endSN+"],level "+t.level),this.bitrateTest=!1,this.stats=n,!0===r.bitrateTest&&this.hls.nextLoadLevel)this.state=$t.IDLE,this.startFragRequested=!1,n.tparsed=n.tbuffered=window.performance.now(),this.hls.trigger(Qe.a.FRAG_BUFFERED,{stats:n,frag:t,id:"main"}),this.tick();else if("initSegment"===r.sn)this.state=$t.IDLE,n.tparsed=n.tbuffered=window.performance.now(),a.initSegment.data=e.payload,this.hls.trigger(Qe.a.FRAG_BUFFERED,{stats:n,frag:t,id:"main"}),this.tick();else{this.state=$t.PARSING;var o=a.totalduration,s=t.level,u=t.sn,l=this.config.defaultAudioCodec||i.audioCodec;this.audioCodecSwap&&(Je.b.log("swapping playlist audio codec"),void 0===l&&(l=this.lastAudioCodec),l&&(l=-1!==l.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5")),this.pendingBuffering=!0,this.appended=!1,Je.b.log("Parsing "+u+" of ["+a.startSN+" ,"+a.endSN+"],level "+s+", cc "+t.cc);var c=this.demuxer;c||(c=this.demuxer=new qt(this.hls,"main"));var d=this.media,f=d&&d.seeking,h=!f&&(a.PTSKnown||!a.live),p=a.initSegment?a.initSegment.data:[];c.push(e.payload,p,l,i.videoCodec,t,o,h,void 0)}}this.fragLoadError=0},t.prototype.onFragParsingInitSegment=function(e){var t=this.fragCurrent,r=e.frag;if(t&&"main"===e.id&&r.sn===t.sn&&r.level===t.level&&this.state===$t.PARSING){var n=e.tracks,i=void 0,a=void 0;if(n.audio&&this.altAudio&&delete n.audio,a=n.audio){var o=this.levels[this.level].audioCodec,s=navigator.userAgent.toLowerCase();o&&this.audioCodecSwap&&(Je.b.log("swapping playlist audio codec"),o=-1!==o.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),this.audioCodecSwitch&&1!==a.metadata.channelCount&&-1===s.indexOf("firefox")&&(o="mp4a.40.5"),-1!==s.indexOf("android")&&"audio/mpeg"!==a.container&&(o="mp4a.40.2",Je.b.log("Android: force audio codec to "+o)),a.levelCodec=o,a.id=e.id}a=n.video,a&&(a.levelCodec=this.levels[this.level].videoCodec,a.id=e.id),this.hls.trigger(Qe.a.BUFFER_CODECS,n);for(i in n){a=n[i],Je.b.log("main track:"+i+",container:"+a.container+",codecs[level/parsed]=["+a.levelCodec+"/"+a.codec+"]");var u=a.initSegment;u&&(this.appended=!0,this.pendingBuffering=!0,this.hls.trigger(Qe.a.BUFFER_APPENDING,{type:i,data:u,parent:"main",content:"initSegment"}))}this.tick()}},t.prototype.onFragParsingData=function(e){var t=this,r=this.fragCurrent,n=e.frag;if(r&&"main"===e.id&&n.sn===r.sn&&n.level===r.level&&("audio"!==e.type||!this.altAudio)&&this.state===$t.PARSING){var i=this.levels[this.level],a=r;if(isNaN(e.endPTS)&&(e.endPTS=e.startPTS+r.duration,e.endDTS=e.startDTS+r.duration),!0===e.hasAudio&&a.addElementaryStream(ut.ElementaryStreamTypes.AUDIO),!0===e.hasVideo&&a.addElementaryStream(ut.ElementaryStreamTypes.VIDEO),Je.b.log("Parsed "+e.type+",PTS:["+e.startPTS.toFixed(3)+","+e.endPTS.toFixed(3)+"],DTS:["+e.startDTS.toFixed(3)+"/"+e.endDTS.toFixed(3)+"],nb:"+e.nb+",dropped:"+(e.dropped||0)),"video"===e.type)if(a.dropped=e.dropped,a.dropped)if(a.backtracked)Je.b.warn("Already backtracked on this fragment, appending with the gap",a.sn);else{var o=i.details;if(!o||a.sn!==o.startSN)return Je.b.warn("missing video frame(s), backtracking fragment",a.sn),this.fragmentTracker.removeFragment(a),a.backtracked=!0,this.nextLoadPosition=e.startPTS,this.state=$t.IDLE,this.fragPrevious=a,void this.tick();Je.b.warn("missing video frame(s) on first frag, appending with gap",a.sn)}else a.backtracked=!1;var s=L(i.details,a,e.startPTS,e.endPTS,e.startDTS,e.endDTS),u=this.hls;u.trigger(Qe.a.LEVEL_PTS_UPDATED,{details:i.details,level:this.level,drift:s,type:e.type,start:e.startPTS,end:e.endPTS}),[e.data1,e.data2].forEach(function(r){r&&r.length&&t.state===$t.PARSING&&(t.appended=!0,t.pendingBuffering=!0,u.trigger(Qe.a.BUFFER_APPENDING,{type:e.type,data:r,parent:"main",content:"data"}))}),this.tick()}},t.prototype.onFragParsed=function(e){var t=this.fragCurrent,r=e.frag;t&&"main"===e.id&&r.sn===t.sn&&r.level===t.level&&this.state===$t.PARSING&&(this.stats.tparsed=window.performance.now(),this.state=$t.PARSED,this._checkAppendedParsed())},t.prototype.onAudioTrackSwitching=function(e){var t=!!e.url,r=e.id;if(!t){if(this.mediaBuffer!==this.media){Je.b.log("switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;var n=this.fragCurrent;n.loader&&(Je.b.log("switching to main audio track, cancel main fragment load"),n.loader.abort()),this.fragCurrent=null,this.fragPrevious=null,this.demuxer&&(this.demuxer.destroy(),this.demuxer=null),this.state=$t.IDLE}var i=this.hls;i.trigger(Qe.a.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:"audio"}),i.trigger(Qe.a.AUDIO_TRACK_SWITCHED,{id:r}),this.altAudio=!1}},t.prototype.onAudioTrackSwitched=function(e){var t=e.id,r=!!this.hls.audioTracks[t].url;if(r){var n=this.videoBuffer;n&&this.mediaBuffer!==n&&(Je.b.log("switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=n)}this.altAudio=r,this.tick()},t.prototype.onBufferCreated=function(e){var t=e.tracks,r=void 0,n=void 0,i=!1;for(var a in t){var o=t[a];"main"===o.id?(n=a,r=o,"video"===a&&(this.videoBuffer=t[a].buffer)):i=!0}i&&r?(Je.b.log("alternate track found, use "+n+".buffered to schedule main fragment loading"),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media},t.prototype.onBufferAppended=function(e){if("main"===e.parent){var t=this.state;t!==$t.PARSING&&t!==$t.PARSED||(this.pendingBuffering=e.pending>0,this._checkAppendedParsed())}},t.prototype._checkAppendedParsed=function(){if(!(this.state!==$t.PARSED||this.appended&&this.pendingBuffering)){var e=this.fragCurrent;if(e){var t=this.mediaBuffer?this.mediaBuffer:this.media;Je.b.log("main buffered : "+zt.toString(t.buffered)),this.fragPrevious=e;var r=this.stats;r.tbuffered=window.performance.now(),this.fragLastKbps=Math.round(8*r.total/(r.tbuffered-r.tfirst)),this.hls.trigger(Qe.a.FRAG_BUFFERED,{stats:r,frag:e,id:"main"}),this.state=$t.IDLE}this.tick()}},t.prototype.onError=function(e){var t=e.frag||this.fragCurrent;if(!t||"main"===t.type){var r=!!this.media&&Ft.isBuffered(this.media,this.media.currentTime)&&Ft.isBuffered(this.media,this.media.currentTime+.5);switch(e.details){case Xe.a.FRAG_LOAD_ERROR:case Xe.a.FRAG_LOAD_TIMEOUT:case Xe.a.KEY_LOAD_ERROR:case Xe.a.KEY_LOAD_TIMEOUT:if(!e.fatal)if(this.fragLoadError+1<=this.config.fragLoadingMaxRetry){var n=Math.min(Math.pow(2,this.fragLoadError)*this.config.fragLoadingRetryDelay,this.config.fragLoadingMaxRetryTimeout);Je.b.warn("mediaController: frag loading failed, retry in "+n+" ms"),this.retryDate=window.performance.now()+n,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.fragLoadError++,this.state=$t.FRAG_LOADING_WAITING_RETRY}else Je.b.error("mediaController: "+e.details+" reaches max retry, redispatch as fatal ..."),e.fatal=!0,this.state=$t.ERROR;break;case Xe.a.LEVEL_LOAD_ERROR:case Xe.a.LEVEL_LOAD_TIMEOUT:this.state!==$t.ERROR&&(e.fatal?(this.state=$t.ERROR,Je.b.warn("streamController: "+e.details+",switch to "+this.state+" state ...")):e.levelRetry||this.state!==$t.WAITING_LEVEL||(this.state=$t.IDLE));break;case Xe.a.BUFFER_FULL_ERROR:"main"!==e.parent||this.state!==$t.PARSING&&this.state!==$t.PARSED||(r?(this._reduceMaxBufferLength(this.config.maxBufferLength),this.state=$t.IDLE):(Je.b.warn("buffer full error also media.currentTime is not buffered, flush everything"),this.fragCurrent=null,this.flushMainBuffer(0,Number.POSITIVE_INFINITY)))}}},t.prototype._reduceMaxBufferLength=function(e){var t=this.config;return t.maxMaxBufferLength>=e&&(t.maxMaxBufferLength/=2,Je.b.warn("main:reduce max buffer length to "+t.maxMaxBufferLength+"s"),!0)},t.prototype._checkBuffer=function(){var e=this.config,t=this.media;if(t&&0!==t.readyState){var r=t.currentTime,n=this.mediaBuffer?this.mediaBuffer:t,i=n.buffered;if(!this.loadedmetadata&&i.length)this.loadedmetadata=!0,this._seekToStartPos();else if(this.immediateSwitch)this.immediateLevelSwitchEnd();else{var a=!(t.paused&&t.readyState>1||t.ended||0===t.buffered.length),o=window.performance.now();if(r!==this.lastCurrentTime)this.stallReported&&(Je.b.warn("playback not stuck anymore @"+r+", after "+Math.round(o-this.stalled)+"ms"),this.stallReported=!1),this.stalled=null,this.nudgeRetry=0;else if(a){var s=o-this.stalled,u=Ft.bufferInfo(t,r,e.maxBufferHole);if(!this.stalled)return void(this.stalled=o);s>=1e3&&this._reportStall(u.len),this._tryFixBufferStall(u,s)}}}},t.prototype.onFragLoadEmergencyAborted=function(){this.state=$t.IDLE,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tick()},t.prototype.onBufferFlushed=function(){var e=this.mediaBuffer?this.mediaBuffer:this.media;e&&this.fragmentTracker.detectEvictedFragments(ut.ElementaryStreamTypes.VIDEO,e.buffered),this.state=$t.IDLE,this.fragPrevious=null},t.prototype.swapAudioCodec=function(){this.audioCodecSwap=!this.audioCodecSwap},t.prototype.computeLivePosition=function(e,t){var r=void 0!==this.config.liveSyncDuration?this.config.liveSyncDuration:this.config.liveSyncDurationCount*t.targetduration;return e+Math.max(0,t.totalduration-r)},t.prototype._tryFixBufferStall=function(e,t){var r=this.config,n=this.media,i=n.currentTime,a=this.fragmentTracker.getPartialFragment(i);a&&this._trySkipBufferHole(a),e.len>.5&&t>1e3*r.highBufferWatchdogPeriod&&(this.stalled=null,this._tryNudgeBuffer())},t.prototype._reportStall=function(e){var t=this.hls,r=this.media;this.stallReported||(this.stallReported=!0,Je.b.warn("Playback stalling at @"+r.currentTime+" due to low buffer"),t.trigger(Qe.a.ERROR,{type:Xe.b.MEDIA_ERROR,details:Xe.a.BUFFER_STALLED_ERROR,fatal:!1,buffer:e}))},t.prototype._trySkipBufferHole=function(e){for(var t=this.hls,r=this.media,n=r.currentTime,i=0,a=0;a=i&&n"+e),this.hls.trigger(Qe.a.STREAM_STATE_TRANSITION,{previousState:t,nextState:e})}},get:function(){return this._state}},{key:"currentLevel",get:function(){var e=this.media;if(e){var t=this.getBufferedFrag(e.currentTime);if(t)return t.level}return-1}},{key:"nextBufferedFrag",get:function(){var e=this.media;return e?this.followingBufferedFrag(this.getBufferedFrag(e.currentTime)):null}},{key:"nextLevel",get:function(){var e=this.nextBufferedFrag;return e?e.level:-1}},{key:"liveSyncPosition",get:function(){return this._liveSyncPosition},set:function(e){this._liveSyncPosition=e}}]),t}(Qt),er=Zt,tr="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},rr=function(){function e(e,t){for(var r=0;r0){r=t[0].bitrate,t.sort(function(e,t){return e.bitrate-t.bitrate}),this._levels=t;for(var c=0;c0&&a})}else this.hls.trigger(Qe.a.ERROR,{type:Xe.b.MEDIA_ERROR,details:Xe.a.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:this.hls.url,reason:"no level with compatible codecs found in manifest"})},t.prototype.setLevelInternal=function(e){var t=this._levels,r=this.hls;if(e>=0&&e1&&s.loadError0){var t=this.currentLevelIndex,r=e.urlId,n=e.url[r];Je.b.log("Attempt loading level index "+t+" with URL-id "+r),this.hls.trigger(Qe.a.LEVEL_LOADING,{url:n,level:t,id:r})}}},rr(t,[{key:"levels",get:function(){return this._levels}},{key:"level",get:function(){return this.currentLevelIndex},set:function(e){var t=this._levels;t&&(e=Math.min(e,t.length-1),this.currentLevelIndex===e&&t[e].details||this.setLevelInternal(e))}},{key:"manualLevel",get:function(){return this.manualLevelIndex},set:function(e){this.manualLevelIndex=e,void 0===this._startLevel&&(this._startLevel=e),-1!==e&&(this.level=e)}},{key:"firstLevel",get:function(){return this._firstLevel},set:function(e){this._firstLevel=e}},{key:"startLevel",get:function(){if(void 0===this._startLevel){var e=this.hls.config.startLevel;return void 0!==e?e:this._firstLevel}return this._startLevel},set:function(e){this._startLevel=e}},{key:"nextLoadLevel",get:function(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel},set:function(e){this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}}]),t}(tt),or=ar,sr=r(5),ur=function(e){function t(r){Q(this,t);var n=J(this,e.call(this,r,Qe.a.MEDIA_ATTACHED,Qe.a.MEDIA_DETACHING,Qe.a.FRAG_PARSING_METADATA));return n.id3Track=void 0,n.media=void 0,n}return $(t,e),t.prototype.destroy=function(){tt.prototype.destroy.call(this)},t.prototype.onMediaAttached=function(e){this.media=e.media,this.media},t.prototype.onMediaDetaching=function(){X(this.id3Track),this.id3Track=void 0,this.media=void 0},t.prototype.getID3Track=function(e){for(var t=0;t=this.minWeight_},e.prototype.getEstimate=function(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_},e.prototype.destroy=function(){},e}(),hr=fr,pr=function(){function e(e,t){for(var r=0;r500*r.duration/s){var u=e.levels,l=Math.max(1,a.bw?a.bw/8:1e3*a.loaded/o),c=u[r.level],d=c.realBitrate?Math.max(c.realBitrate,c.bitrate):c.bitrate,f=a.total?a.total:Math.max(a.loaded,Math.round(r.duration*d/8)),h=t.currentTime,p=(f-a.loaded)/l,g=(Ft.bufferInfo(t,h,e.config.maxBufferHole).end-h)/s;if(g<2*r.duration/s&&p>g){var v=void 0,y=void 0;for(y=r.level-1;y>i;y--){var m=u[y].realBitrate?Math.max(u[y].realBitrate,u[y].bitrate):u[y].bitrate;if((v=r.duration*m/(6.4*l))=n;l--){var c=u[l],d=c.details,f=d?d.totalduration/d.fragments.length:t,h=!!d&&d.live,p=void 0;p=l<=e?o*r:s*r;var g=u[l].realBitrate?Math.max(u[l].realBitrate,u[l].bitrate):u[l].bitrate,v=g*f/p;if(Je.b.trace("level/adjustedbw/bitrate/avgDuration/maxFetchDuration/fetchDuration: "+l+"/"+Math.round(p)+"/"+g+"/"+f+"/"+a+"/"+v),p>g&&(!v||h&&!this.bitrateTestDelay||v=0)return f;Je.b.trace("rebuffering expected to happen, lets try to find a quality level minimizing the rebuffering");var h=s?Math.min(s,n.maxStarvationDelay):n.maxStarvationDelay,p=n.abrBandWidthFactor,g=n.abrBandWidthUpFactor;if(0===d){var v=this.bitrateTestDelay;if(v){h=(s?Math.min(s,n.maxLoadingDelay):n.maxLoadingDelay)-v,Je.b.trace("bitrate test took "+Math.round(1e3*v)+"ms, set first fragment max fetchDuration to "+Math.round(1e3*h)+" ms"),p=g=1}}return f=this._findBestLevel(o,s,c,i,t,d+h,p,g,r),Math.max(f,0)}}]),t}(tt),mr=yr,br=T(),_r=function(e){function t(r){ae(this,t);var n=oe(this,e.call(this,r,Qe.a.MEDIA_ATTACHING,Qe.a.MEDIA_DETACHING,Qe.a.MANIFEST_PARSED,Qe.a.BUFFER_RESET,Qe.a.BUFFER_APPENDING,Qe.a.BUFFER_CODECS,Qe.a.BUFFER_EOS,Qe.a.BUFFER_FLUSHING,Qe.a.LEVEL_PTS_UPDATED,Qe.a.LEVEL_UPDATED));return n._msDuration=null,n._levelDuration=null,n._live=null,n._objectUrl=null,n.onsbue=n.onSBUpdateEnd.bind(n),n.onsbe=n.onSBUpdateError.bind(n),n.pendingTracks={},n.tracks={},n}return se(t,e),t.prototype.destroy=function(){tt.prototype.destroy.call(this)},t.prototype.onLevelPtsUpdated=function(e){var t=e.type,r=this.tracks.audio;if("audio"===t&&r&&"audio/mpeg"===r.container){var n=this.sourceBuffer.audio;if(Math.abs(n.timestampOffset-e.start)>.1){var i=n.updating;try{n.abort()}catch(e){i=!0,Je.b.warn("can not abort audio buffer: "+e)}i?this.audioTimestampOffset=e.start:(Je.b.warn("change mpeg audio timestamp offset from "+n.timestampOffset+" to "+e.start),n.timestampOffset=e.start)}}},t.prototype.onManifestParsed=function(e){var t=e.audio,r=e.video||e.levels.length&&e.altAudio,n=0;e.altAudio&&(t||r)&&(n=(t?1:0)+(r?1:0),Je.b.log(n+" sourceBuffer(s) expected")),this.sourceBufferNb=n},t.prototype.onMediaAttaching=function(e){var t=this.media=e.media;if(t){var r=this.mediaSource=new br;this.onmso=this.onMediaSourceOpen.bind(this),this.onmse=this.onMediaSourceEnded.bind(this),this.onmsc=this.onMediaSourceClose.bind(this),r.addEventListener("sourceopen",this.onmso),r.addEventListener("sourceended",this.onmse),r.addEventListener("sourceclose",this.onmsc),t.src=window.URL.createObjectURL(r),this._objectUrl=t.src}},t.prototype.onMediaDetaching=function(){Je.b.log("media source detaching");var e=this.mediaSource;if(e){if("open"===e.readyState)try{e.endOfStream()}catch(e){Je.b.warn("onMediaDetaching:"+e.message+" while calling endOfStream")}e.removeEventListener("sourceopen",this.onmso),e.removeEventListener("sourceended",this.onmse),e.removeEventListener("sourceclose",this.onmsc),this.media&&(window.URL.revokeObjectURL(this._objectUrl),this.media.src===this._objectUrl?(this.media.removeAttribute("src"),this.media.load()):Je.b.warn("media.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.pendingTracks={},this.tracks={},this.sourceBuffer={},this.flushRange=[],this.segments=[],this.appended=0}this.onmso=this.onmse=this.onmsc=null,this.hls.trigger(Qe.a.MEDIA_DETACHED)},t.prototype.onMediaSourceOpen=function(){Je.b.log("media source opened"),this.hls.trigger(Qe.a.MEDIA_ATTACHED,{media:this.media});var e=this.mediaSource;e&&e.removeEventListener("sourceopen",this.onmso),this.checkPendingTracks()},t.prototype.checkPendingTracks=function(){var e=this.pendingTracks,t=Object.keys(e).length;t&&(this.sourceBufferNb<=t||0===this.sourceBufferNb)&&(this.createSourceBuffers(e),this.pendingTracks={},this.doAppending())},t.prototype.onMediaSourceClose=function(){Je.b.log("media source closed")},t.prototype.onMediaSourceEnded=function(){Je.b.log("media source ended")},t.prototype.onSBUpdateEnd=function(){if(this.audioTimestampOffset){var e=this.sourceBuffer.audio;Je.b.warn("change mpeg audio timestamp offset from "+e.timestampOffset+" to "+this.audioTimestampOffset),e.timestampOffset=this.audioTimestampOffset,delete this.audioTimestampOffset}this._needsFlush&&this.doFlush(),this._needsEos&&this.checkEos(),this.appending=!1;var t=this.parent,r=this.segments.reduce(function(e,r){return r.parent===t?e+1:e},0),n={},i=this.sourceBuffer;for(var a in i)n[a]=i[a].buffered;this.hls.trigger(Qe.a.BUFFER_APPENDED,{parent:t,pending:r,timeRanges:n}),this._needsFlush||this.doAppending(),this.updateMediaElementDuration()},t.prototype.onSBUpdateError=function(e){Je.b.error("sourceBuffer error:",e),this.hls.trigger(Qe.a.ERROR,{type:Xe.b.MEDIA_ERROR,details:Xe.a.BUFFER_APPENDING_ERROR,fatal:!1})},t.prototype.onBufferReset=function(){var e=this.sourceBuffer;for(var t in e){var r=e[t];try{this.mediaSource.removeSourceBuffer(r),r.removeEventListener("updateend",this.onsbue),r.removeEventListener("error",this.onsbe)}catch(e){}}this.sourceBuffer={},this.flushRange=[],this.segments=[],this.appended=0},t.prototype.onBufferCodecs=function(e){if(0===Object.keys(this.sourceBuffer).length){for(var t in e)this.pendingTracks[t]=e[t];var r=this.mediaSource;r&&"open"===r.readyState&&this.checkPendingTracks()}},t.prototype.createSourceBuffers=function(e){var t=this.sourceBuffer,r=this.mediaSource;for(var n in e)if(!t[n]){var i=e[n],a=i.levelCodec||i.codec,o=i.container+";codecs="+a;Je.b.log("creating sourceBuffer("+o+")");try{var s=t[n]=r.addSourceBuffer(o);s.addEventListener("updateend",this.onsbue),s.addEventListener("error",this.onsbe),this.tracks[n]={codec:a,container:i.container},i.buffer=s}catch(e){Je.b.error("error while trying to add sourceBuffer:"+e.message),this.hls.trigger(Qe.a.ERROR,{type:Xe.b.MEDIA_ERROR,details:Xe.a.BUFFER_ADD_CODEC_ERROR,fatal:!1,err:e,mimeType:o})}}this.hls.trigger(Qe.a.BUFFER_CREATED,{tracks:e})},t.prototype.onBufferAppending=function(e){this._needsFlush||(this.segments?this.segments.push(e):this.segments=[e],this.doAppending())},t.prototype.onBufferAppendFail=function(e){Je.b.error("sourceBuffer error:",e.event),this.hls.trigger(Qe.a.ERROR,{type:Xe.b.MEDIA_ERROR,details:Xe.a.BUFFER_APPENDING_ERROR,fatal:!1})},t.prototype.onBufferEos=function(e){var t=this.sourceBuffer,r=e.type;for(var n in t)r&&n!==r||t[n].ended||(t[n].ended=!0,Je.b.log(n+" sourceBuffer now EOS"));this.checkEos()},t.prototype.checkEos=function(){var e=this.sourceBuffer,t=this.mediaSource;if(!t||"open"!==t.readyState)return void(this._needsEos=!1);for(var r in e){var n=e[r];if(!n.ended)return;if(n.updating)return void(this._needsEos=!0)}Je.b.log("all media data available, signal endOfStream() to MediaSource and stop loading fragment");try{t.endOfStream()}catch(e){Je.b.warn("exception while calling mediaSource.endOfStream()")}this._needsEos=!1},t.prototype.onBufferFlushing=function(e){this.flushRange.push({start:e.startOffset,end:e.endOffset,type:e.type}),this.flushBufferCounter=0,this.doFlush()},t.prototype.onLevelUpdated=function(e){var t=e.details;t.fragments.length>0&&(this._levelDuration=t.totalduration+t.fragments[0].start,this._live=t.live,this.updateMediaElementDuration())},t.prototype.updateMediaElementDuration=function(){var e=this.hls.config,t=void 0;if(null!==this._levelDuration&&this.media&&this.mediaSource&&this.sourceBuffer&&0!==this.media.readyState&&"open"===this.mediaSource.readyState){for(var r in this.sourceBuffer)if(!0===this.sourceBuffer[r].updating)return;t=this.media.duration,null===this._msDuration&&(this._msDuration=this.mediaSource.duration),!0===this._live&&!0===e.liveDurationInfinity?(Je.b.log("Media Source duration is set to Infinity"),this._msDuration=this.mediaSource.duration=1/0):(this._levelDuration>this._msDuration&&this._levelDuration>t||t===1/0||isNaN(t))&&(Je.b.log("Updating Media Source duration to "+this._levelDuration.toFixed(3)),this._msDuration=this.mediaSource.duration=this._levelDuration)}},t.prototype.doFlush=function(){for(;this.flushRange.length;){var e=this.flushRange[0];if(!this.flushBuffer(e.start,e.end,e.type))return void(this._needsFlush=!0);this.flushRange.shift(),this.flushBufferCounter=0}if(0===this.flushRange.length){this._needsFlush=!1;var t=0,r=this.sourceBuffer;try{for(var n in r)t+=r[n].buffered.length}catch(e){Je.b.error("error while accessing sourceBuffer.buffered")}this.appended=t,this.hls.trigger(Qe.a.BUFFER_FLUSHED)}},t.prototype.doAppending=function(){var e=this.hls,t=this.sourceBuffer,r=this.segments;if(Object.keys(t).length){if(this.media.error)return this.segments=[],void Je.b.error("trying to append although a media error occured, flush segment and abort");if(this.appending)return;if(r&&r.length){var n=r.shift();try{var i=n.type,a=t[i];a?a.updating?r.unshift(n):(a.ended=!1,this.parent=n.parent,a.appendBuffer(n.data),this.appendError=0,this.appended++,this.appending=!0):this.onSBUpdateEnd()}catch(t){Je.b.error("error while trying to append buffer:"+t.message),r.unshift(n);var o={type:Xe.b.MEDIA_ERROR,parent:n.parent};22!==t.code?(this.appendError?this.appendError++:this.appendError=1,o.details=Xe.a.BUFFER_APPEND_ERROR,this.appendError>e.config.appendErrorMaxRetry?(Je.b.log("fail "+e.config.appendErrorMaxRetry+" times to append segment in sourceBuffer"),r=[],o.fatal=!0,e.trigger(Qe.a.ERROR,o)):(o.fatal=!1,e.trigger(Qe.a.ERROR,o))):(this.segments=[],o.details=Xe.a.BUFFER_FULL_ERROR,o.fatal=!1,e.trigger(Qe.a.ERROR,o))}}}},t.prototype.flushBuffer=function(e,t,r){var n=void 0,i=void 0,a=void 0,o=void 0,s=void 0,u=void 0,l=this.sourceBuffer;if(Object.keys(l).length){if(Je.b.log("flushBuffer,pos/start/end: "+this.media.currentTime.toFixed(3)+"/"+e+"/"+t),this.flushBufferCounter.5)return this.flushBufferCounter++,Je.b.log("flush "+c+" ["+s+","+u+"], of ["+a+","+o+"], pos:"+this.media.currentTime),n.remove(s,u),!1}catch(e){Je.b.warn("exception while accessing sourcebuffer, it might have been removed from MediaSource")}}}else Je.b.warn("abort flushing too many retries");Je.b.log("buffer flushed")}return!0},t}(tt),Er=_r,wr=function(){function e(e,t){for(var r=0;rthis.autoLevelCapping&&t.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}},t.prototype.getMaxLevel=function(e){var r=this;if(!this.levels)return-1;var n=this.levels.filter(function(n,i){return t.isLevelAllowed(i,r.restrictedLevels)&&i<=e});return t.getMaxLevelByMediaSize(n,this.mediaWidth,this.mediaHeight)},t.prototype._startCapping=function(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,this.hls.firstLevel=this.getMaxLevel(this.firstLevel),clearInterval(this.timer),this.timer=setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())},t.prototype._stopCapping=function(){this.restrictedLevels=[],this.firstLevel=null,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(this.timer=clearInterval(this.timer),this.timer=null)},t.isLevelAllowed=function(e){return-1===(arguments.length>1&&void 0!==arguments[1]?arguments[1]:[]).indexOf(e)},t.getMaxLevelByMediaSize=function(e,t,r){if(!e||e&&!e.length)return-1;for(var n=e.length-1,i=0;i=t||a.height>=r)&&function(e,t){return!t||(e.width!==t.width||e.height!==t.height)}(a,e[i+1])){n=i;break}}return n},wr(t,[{key:"mediaWidth",get:function(){var e=void 0,r=this.media;return r&&(e=r.width||r.clientWidth||r.offsetWidth,e*=t.contentScaleFactor),e}},{key:"mediaHeight",get:function(){var e=void 0,r=this.media;return r&&(e=r.height||r.clientHeight||r.offsetHeight,e*=t.contentScaleFactor),e}}],[{key:"contentScaleFactor",get:function(){var e=1;try{e=window.devicePixelRatio}catch(e){}return e}}]),t}(tt),Sr=Tr,Rr=window,Ar=Rr.performance,Lr=function(e){function t(r){return de(this,t),fe(this,e.call(this,r,Qe.a.MEDIA_ATTACHING))}return he(t,e),t.prototype.destroy=function(){this.timer&&clearInterval(this.timer),this.isVideoPlaybackQualityAvailable=!1},t.prototype.onMediaAttaching=function(e){var t=this.hls.config;if(t.capLevelOnFPSDrop){"function"==typeof(this.video=e.media instanceof window.HTMLVideoElement?e.media:null).getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),clearInterval(this.timer),this.timer=setInterval(this.checkFPSInterval.bind(this),t.fpsDroppedMonitoringPeriod)}},t.prototype.checkFPS=function(e,t,r){var n=Ar.now();if(t){if(this.lastTime){var i=n-this.lastTime,a=r-this.lastDroppedFrames,o=t-this.lastDecodedFrames,s=1e3*a/i,u=this.hls;if(u.trigger(Qe.a.FPS_DROP,{currentDropped:a,currentDecoded:o,totalDroppedFrames:r}),s>0&&a>u.config.fpsDroppedMonitoringThreshold*o){var l=u.currentLevel;Je.b.warn("drop FPS ratio greater than max allowed value for currentLevel: "+l),l>0&&(-1===u.autoLevelCapping||u.autoLevelCapping>=l)&&(l-=1,u.trigger(Qe.a.FPS_DROP_LEVEL_CAPPING,{level:l,droppedLevel:u.currentLevel}),u.autoLevelCapping=l,u.streamController.nextLevelSwitch())}}this.lastTime=n,this.lastDroppedFrames=r,this.lastDecodedFrames=t}},t.prototype.checkFPSInterval=function(){var e=this.video;if(e)if(this.isVideoPlaybackQualityAvailable){var t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)},t}(tt),Cr=Lr,kr=window,Dr=kr.performance,Ir=kr.XMLHttpRequest,Pr=function(){function e(t){pe(this,e),t&&t.xhrSetup&&(this.xhrSetup=t.xhrSetup)}return e.prototype.destroy=function(){this.abort(),this.loader=null},e.prototype.abort=function(){var e=this.loader;e&&4!==e.readyState&&(this.stats.aborted=!0,e.abort()),window.clearTimeout(this.requestTimeout),this.requestTimeout=null,window.clearTimeout(this.retryTimeout),this.retryTimeout=null},e.prototype.load=function(e,t,r){this.context=e,this.config=t,this.callbacks=r,this.stats={trequest:Dr.now(),retry:0},this.retryDelay=t.retryDelay,this.loadInternal()},e.prototype.loadInternal=function(){var e=void 0,t=this.context;e=this.loader=new Ir;var r=this.stats;r.tfirst=0,r.loaded=0;var n=this.xhrSetup;try{if(n)try{n(e,t.url)}catch(r){e.open("GET",t.url,!0),n(e,t.url)}e.readyState||e.open("GET",t.url,!0)}catch(r){return void this.callbacks.onError({code:e.status,text:r.message},t,e)}t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,this.requestTimeout=window.setTimeout(this.loadtimeout.bind(this),this.config.timeout),e.send()},e.prototype.readystatechange=function(e){var t=e.currentTarget,r=t.readyState,n=this.stats,i=this.context,a=this.config;if(!n.aborted&&r>=2)if(window.clearTimeout(this.requestTimeout),0===n.tfirst&&(n.tfirst=Math.max(Dr.now(),n.trequest)),4===r){var o=t.status;if(o>=200&&o<300){n.tload=Math.max(n.tfirst,Dr.now());var s=void 0,u=void 0;"arraybuffer"===i.responseType?(s=t.response,u=s.byteLength):(s=t.responseText,u=s.length),n.loaded=n.total=u;var l={url:t.responseURL,data:s};this.callbacks.onSuccess(l,n,i,t)}else n.retry>=a.maxRetry||o>=400&&o<499?(Je.b.error(o+" while loading "+i.url),this.callbacks.onError({code:o,text:t.statusText},i,t)):(Je.b.warn(o+" while loading "+i.url+", retrying in "+this.retryDelay+"..."),this.destroy(),this.retryTimeout=window.setTimeout(this.loadInternal.bind(this),this.retryDelay),this.retryDelay=Math.min(2*this.retryDelay,a.maxRetryDelay),n.retry++)}else this.requestTimeout=window.setTimeout(this.loadtimeout.bind(this),a.timeout)},e.prototype.loadtimeout=function(){Je.b.warn("timeout while loading "+this.context.url),this.callbacks.onTimeout(this.stats,this.context,null)},e.prototype.loadprogress=function(e){var t=e.currentTarget,r=this.stats;r.loaded=e.loaded,e.lengthComputable&&(r.total=e.total);var n=this.callbacks.onProgress;n&&n(r,this.context,null,t)},e}(),Or=Pr,xr=function(){function e(e,t){for(var r=0;r=this.tracks.length)return void Je.b.warn("Invalid audio track id:",e.id);if(Je.b.log("audioTrack "+e.id+" loaded"),this.tracks[e.id].details=e.details,e.details.live&&!this.hasInterval()){var t=1e3*e.details.targetduration;this.setInterval(t)}!e.details.live&&this.hasInterval()&&this.clearInterval()},t.prototype.onAudioTrackSwitched=function(e){var t=this.tracks[e.id].groupId;t&&this.audioGroupId!==t&&(this.audioGroupId=t)},t.prototype.onLevelLoaded=function(e){var t=this.hls.levels[e.level];if(t.audioGroupIds){var r=t.audioGroupIds[t.urlId];this.audioGroupId!==r&&(this.audioGroupId=r,this._selectInitialAudioTrack())}},t.prototype.onError=function(e){e.type===Xe.b.NETWORK_ERROR&&(e.fatal&&this.clearInterval(),e.details===Xe.a.AUDIO_TRACK_LOAD_ERROR&&(Je.b.warn("Network failure on audio-track id:",e.context.id),this._handleLoadError()))},t.prototype.doTick=function(){this._updateTrack(this.trackId)},t.prototype._selectInitialAudioTrack=function(){var e=this,t=this.tracks;if(t.length){var r=this.tracks[this.trackId],n=null;r&&(n=r.name);var i=t.filter(function(e){return e.default});i.length?t=i:Je.b.warn("No default audio tracks defined");var a=!1,o=function(){t.forEach(function(t){a||e.audioGroupId&&t.groupId!==e.audioGroupId||n&&n!==t.name||(e.audioTrack=t.id,a=!0)})};o(),a||(n=null,o()),a||(Je.b.error("No track found for running audio group-ID: "+this.audioGroupId),this.hls.trigger(Qe.a.ERROR,{type:Xe.b.MEDIA_ERROR,details:Xe.a.AUDIO_TRACK_LOAD_ERROR,fatal:!0}))}},t.prototype._needsTrackLoading=function(e){var t=e.details;return!t||(!!t.live||void 0)},t.prototype._loadTrackDetailsIfNeeded=function(e){if(this._needsTrackLoading(e)){var t=e.url,r=e.id;Je.b.log("loading audio-track playlist for id: "+r),this.hls.trigger(Qe.a.AUDIO_TRACK_LOADING,{url:t,id:r})}},t.prototype._updateTrack=function(e){if(!(e<0||e>=this.tracks.length)){this.clearInterval(),this.trackId=e,Je.b.log("trying to update audio-track "+e);var t=this.tracks[e];this._loadTrackDetailsIfNeeded(t)}},t.prototype._handleLoadError=function(){this.trackIdBlacklist[this.trackId]=!0;var e=this.trackId,t=this.tracks[e],r=t.name,n=t.language,i=t.groupId;Je.b.warn("Loading failed on audio track id: "+e+", group-id: "+i+', name/language: "'+r+'" / "'+n+'"');for(var a=e,o=0;o no-op");if(e<0||e>=this.tracks.length)return void Je.b.warn("Invalid id passed to audio-track controller");var t=this.tracks[e];Je.b.log("Now switching to audio-track index "+e),this.clearInterval(),this.trackId=e;var r=t.url,n=t.type,i=t.id;this.hls.trigger(Qe.a.AUDIO_TRACK_SWITCHING,{id:i,type:n,url:r}),this._loadTrackDetailsIfNeeded(t)}}]),t}(Qt),Fr=Mr,Nr=function(){function e(e,t){for(var r=0;r0&&-1===e?(Je.b.log("audio:override startPosition with lastCurrentTime @"+t.toFixed(3)),this.state=Gr.IDLE):(this.lastCurrentTime=this.startPosition?this.startPosition:e,this.state=Gr.STARTING),this.nextLoadPosition=this.startPosition=this.lastCurrentTime,this.tick()}else this.startPosition=e,this.state=Gr.STOPPED},t.prototype.stopLoad=function(){var e=this.fragCurrent;e&&(e.loader&&e.loader.abort(),this.fragmentTracker.removeFragment(e),this.fragCurrent=null),this.fragPrevious=null,this.demuxer&&(this.demuxer.destroy(),this.demuxer=null),this.state=Gr.STOPPED},t.prototype.doTick=function(){var e=void 0,t=void 0,r=void 0,n=this.hls,i=n.config;switch(this.state){case Gr.ERROR:case Gr.PAUSED:case Gr.BUFFER_FLUSHING:break;case Gr.STARTING:this.state=Gr.WAITING_TRACK,this.loadedmetadata=!1;break;case Gr.IDLE:var a=this.tracks;if(!a)break;if(!this.media&&(this.startFragRequested||!i.startFragPrefetch))break;if(this.loadedmetadata)e=this.media.currentTime;else if(void 0===(e=this.nextLoadPosition))break;var o=this.mediaBuffer?this.mediaBuffer:this.media,s=this.videoBuffer?this.videoBuffer:this.media,u=Ft.bufferInfo(o,e,i.maxBufferHole),l=Ft.bufferInfo(s,e,i.maxBufferHole),c=u.len,d=u.end,f=this.fragPrevious,h=Math.min(i.maxBufferLength,i.maxMaxBufferLength),p=Math.max(h,l.len),g=this.audioSwitch,v=this.trackId;if((cb||u.nextStart))return;Je.b.log("alt audio track ahead of main track, seek to start of alt audio track"),this.media.currentTime=b+.05}if(r.initSegment&&!r.initSegment.data)E=r.initSegment;else if(d<=b){if(E=y[0],null!==this.videoTrackCC&&E.cc!==this.videoTrackCC&&(E=D(y,this.videoTrackCC)),r.live&&E.loadIdx&&E.loadIdx===this.fragLoadIdx){var w=u.nextStart?u.nextStart:b;return Je.b.log("no alt audio available @currentTime:"+this.media.currentTime+", seeking @"+(w+.05)),void(this.media.currentTime=w+.05)}}else{var T=void 0,S=i.maxFragLookUpTolerance,R=f?y[f.sn-y[0].sn+1]:void 0,A=function(e){var t=Math.min(S,e.duration);return e.start+e.duration-t<=d?1:e.start-t>d&&e.start?-1:0};d<_?(d>_-S&&(S=0),T=R&&!A(R)?R:Mt.search(y,A)):T=y[m-1],T&&(E=T,b=T.start,f&&E.level===f.level&&E.sn===f.sn&&(E.sn=C||k)&&(Je.b.log("audioStreamController: retryDate reached, switch back to IDLE state"),this.state=Gr.IDLE);break;case Gr.WAITING_INIT_PTS:var I=this.videoTrackCC;if(void 0===this.initPTS[I])break;var P=this.waitingFragment;if(P){var O=P.frag.cc;I!==O?(t=this.tracks[this.trackId],t.details&&t.details.live&&(Je.b.warn("Waiting fragment CC ("+O+") does not match video track CC ("+I+")"),this.waitingFragment=null,this.state=Gr.IDLE)):(this.state=Gr.FRAG_LOADING,this.onFragLoaded(this.waitingFragment),this.waitingFragment=null)}else this.state=Gr.IDLE;break;case Gr.STOPPED:case Gr.FRAG_LOADING:case Gr.PARSING:case Gr.PARSED:case Gr.ENDED:}},t.prototype.onMediaAttached=function(e){var t=this.media=this.mediaBuffer=e.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvended=this.onMediaEnded.bind(this),t.addEventListener("seeking",this.onvseeking),t.addEventListener("ended",this.onvended);var r=this.config;this.tracks&&r.autoStartLoad&&this.startLoad(r.startPosition)},t.prototype.onMediaDetaching=function(){var e=this.media;e&&e.ended&&(Je.b.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),e&&(e.removeEventListener("seeking",this.onvseeking),e.removeEventListener("ended",this.onvended),this.onvseeking=this.onvseeked=this.onvended=null),this.media=this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1,this.stopLoad()},t.prototype.onMediaSeeking=function(){this.state===Gr.ENDED&&(this.state=Gr.IDLE),this.media&&(this.lastCurrentTime=this.media.currentTime),this.tick()},t.prototype.onMediaEnded=function(){this.startPosition=this.lastCurrentTime=0},t.prototype.onAudioTracksUpdated=function(e){Je.b.log("audio tracks updated"),this.tracks=e.audioTracks},t.prototype.onAudioTrackSwitching=function(e){var t=!!e.url;this.trackId=e.id,this.fragCurrent=null,this.state=Gr.PAUSED,this.waitingFragment=null,t?this.setInterval(100):this.demuxer&&(this.demuxer.destroy(),this.demuxer=null),t&&(this.audioSwitch=!0,this.state=Gr.IDLE),this.tick()},t.prototype.onAudioTrackLoaded=function(e){var t=e.details,r=e.id,n=this.tracks[r],i=t.totalduration,a=0;if(Je.b.log("track "+r+" loaded ["+t.startSN+","+t.endSN+"],duration:"+i),t.live){var o=n.details;o&&t.fragments.length>0?(C(o,t),a=t.fragments[0].start,t.PTSKnown?Je.b.log("live audio playlist sliding:"+a.toFixed(3)):Je.b.log("live audio playlist - outdated PTS, unknown sliding")):(t.PTSKnown=!1,Je.b.log("live audio playlist - first load, unknown sliding"))}else t.PTSKnown=!1;if(n.details=t,!this.startFragRequested){if(-1===this.startPosition){var s=t.startTimeOffset;isNaN(s)?this.startPosition=0:(Je.b.log("start time offset found in playlist, adjust startPosition to "+s),this.startPosition=s)}this.nextLoadPosition=this.startPosition}this.state===Gr.WAITING_TRACK&&(this.state=Gr.IDLE),this.tick()},t.prototype.onKeyLoaded=function(){this.state===Gr.KEY_LOADING&&(this.state=Gr.IDLE,this.tick())},t.prototype.onFragLoaded=function(e){var t=this.fragCurrent,r=e.frag;if(this.state===Gr.FRAG_LOADING&&t&&"audio"===r.type&&r.level===t.level&&r.sn===t.sn){var n=this.tracks[this.trackId],i=n.details,a=i.totalduration,o=t.level,s=t.sn,u=t.cc,l=this.config.defaultAudioCodec||n.audioCodec||"mp4a.40.2",c=this.stats=e.stats;if("initSegment"===s)this.state=Gr.IDLE,c.tparsed=c.tbuffered=Br.now(),i.initSegment.data=e.payload,this.hls.trigger(Qe.a.FRAG_BUFFERED,{stats:c,frag:t,id:"audio"}),this.tick();else{this.state=Gr.PARSING,this.appended=!1,this.demuxer||(this.demuxer=new qt(this.hls,"audio"));var d=this.initPTS[u],f=i.initSegment?i.initSegment.data:[];if(i.initSegment||void 0!==d){this.pendingBuffering=!0,Je.b.log("Demuxing "+s+" of ["+i.startSN+" ,"+i.endSN+"],track "+o);this.demuxer.push(e.payload,f,l,null,t,a,!1,d)}else Je.b.log("unknown video PTS for continuity counter "+u+", waiting for video PTS before demuxing audio frag "+s+" of ["+i.startSN+" ,"+i.endSN+"],track "+o),this.waitingFragment=e,this.state=Gr.WAITING_INIT_PTS}}this.fragLoadError=0},t.prototype.onFragParsingInitSegment=function(e){var t=this.fragCurrent,r=e.frag;if(t&&"audio"===e.id&&r.sn===t.sn&&r.level===t.level&&this.state===Gr.PARSING){var n=e.tracks,i=void 0;if(n.video&&delete n.video,i=n.audio){i.levelCodec=i.codec,i.id=e.id,this.hls.trigger(Qe.a.BUFFER_CODECS,n),Je.b.log("audio track:audio,container:"+i.container+",codecs[level/parsed]=["+i.levelCodec+"/"+i.codec+"]");var a=i.initSegment;if(a){var o={type:"audio",data:a,parent:"audio",content:"initSegment"};this.audioSwitch?this.pendingData=[o]:(this.appended=!0,this.pendingBuffering=!0,this.hls.trigger(Qe.a.BUFFER_APPENDING,o))}this.tick()}}},t.prototype.onFragParsingData=function(e){var t=this,r=this.fragCurrent,n=e.frag;if(r&&"audio"===e.id&&"audio"===e.type&&n.sn===r.sn&&n.level===r.level&&this.state===Gr.PARSING){var i=this.trackId,a=this.tracks[i],o=this.hls;isNaN(e.endPTS)&&(e.endPTS=e.startPTS+r.duration,e.endDTS=e.startDTS+r.duration),r.addElementaryStream(ut.ElementaryStreamTypes.AUDIO),Je.b.log("parsed "+e.type+",PTS:["+e.startPTS.toFixed(3)+","+e.endPTS.toFixed(3)+"],DTS:["+e.startDTS.toFixed(3)+"/"+e.endDTS.toFixed(3)+"],nb:"+e.nb),L(a.details,r,e.startPTS,e.endPTS);var s=this.audioSwitch,u=this.media,l=!1;if(s&&u)if(u.readyState){var c=u.currentTime;Je.b.log("switching audio track : currentTime:"+c),c>=e.startPTS&&(Je.b.log("switching audio track : flushing all audio"),this.state=Gr.BUFFER_FLUSHING,o.trigger(Qe.a.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:"audio"}),l=!0,this.audioSwitch=!1,o.trigger(Qe.a.AUDIO_TRACK_SWITCHED,{id:i}))}else this.audioSwitch=!1,o.trigger(Qe.a.AUDIO_TRACK_SWITCHED,{id:i});var d=this.pendingData;if(!d)return Je.b.warn("Apparently attempt to enqueue media payload without codec initialization data upfront"),void o.trigger(Qe.a.ERROR,{type:Xe.b.MEDIA_ERROR,details:null,fatal:!0});this.audioSwitch||([e.data1,e.data2].forEach(function(t){t&&t.length&&d.push({type:e.type,data:t,parent:"audio",content:"data"})}),!l&&d.length&&(d.forEach(function(e){t.state===Gr.PARSING&&(t.pendingBuffering=!0,t.hls.trigger(Qe.a.BUFFER_APPENDING,e))}),this.pendingData=[],this.appended=!0)),this.tick()}},t.prototype.onFragParsed=function(e){var t=this.fragCurrent,r=e.frag;t&&"audio"===e.id&&r.sn===t.sn&&r.level===t.level&&this.state===Gr.PARSING&&(this.stats.tparsed=Br.now(),this.state=Gr.PARSED,this._checkAppendedParsed())},t.prototype.onBufferReset=function(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1},t.prototype.onBufferCreated=function(e){var t=e.tracks.audio;t&&(this.mediaBuffer=t.buffer,this.loadedmetadata=!0),e.tracks.video&&(this.videoBuffer=e.tracks.video.buffer)},t.prototype.onBufferAppended=function(e){if("audio"===e.parent){var t=this.state;t!==Gr.PARSING&&t!==Gr.PARSED||(this.pendingBuffering=e.pending>0,this._checkAppendedParsed())}},t.prototype._checkAppendedParsed=function(){if(!(this.state!==Gr.PARSED||this.appended&&this.pendingBuffering)){var e=this.fragCurrent,t=this.stats,r=this.hls;if(e){this.fragPrevious=e,t.tbuffered=Br.now(),r.trigger(Qe.a.FRAG_BUFFERED,{stats:t,frag:e,id:"audio"});var n=this.mediaBuffer?this.mediaBuffer:this.media;Je.b.log("audio buffered : "+zt.toString(n.buffered)),this.audioSwitch&&this.appended&&(this.audioSwitch=!1,r.trigger(Qe.a.AUDIO_TRACK_SWITCHED,{id:this.trackId})),this.state=Gr.IDLE}this.tick()}},t.prototype.onError=function(e){var t=e.frag;if(!t||"audio"===t.type)switch(e.details){case Xe.a.FRAG_LOAD_ERROR:case Xe.a.FRAG_LOAD_TIMEOUT:var r=e.frag;if(r&&"audio"!==r.type)break;if(!e.fatal){var n=this.fragLoadError;n?n++:n=1;var i=this.config;if(n<=i.fragLoadingMaxRetry){this.fragLoadError=n;var a=Math.min(Math.pow(2,n-1)*i.fragLoadingRetryDelay,i.fragLoadingMaxRetryTimeout);Je.b.warn("AudioStreamController: frag loading failed, retry in "+a+" ms"),this.retryDate=Br.now()+a,this.state=Gr.FRAG_LOADING_WAITING_RETRY}else Je.b.error("AudioStreamController: "+e.details+" reaches max retry, redispatch as fatal ..."),e.fatal=!0,this.state=Gr.ERROR}break;case Xe.a.AUDIO_TRACK_LOAD_ERROR:case Xe.a.AUDIO_TRACK_LOAD_TIMEOUT:case Xe.a.KEY_LOAD_ERROR:case Xe.a.KEY_LOAD_TIMEOUT:this.state!==Gr.ERROR&&(this.state=e.fatal?Gr.ERROR:Gr.IDLE,Je.b.warn("AudioStreamController: "+e.details+" while loading frag, now switching to "+this.state+" state ..."));break;case Xe.a.BUFFER_FULL_ERROR:if("audio"===e.parent&&(this.state===Gr.PARSING||this.state===Gr.PARSED)){var o=this.mediaBuffer,s=this.media.currentTime;if(o&&Ft.isBuffered(o,s)&&Ft.isBuffered(o,s+.5)){var u=this.config;u.maxMaxBufferLength>=u.maxBufferLength&&(u.maxMaxBufferLength/=2,Je.b.warn("AudioStreamController: reduce max buffer length to "+u.maxMaxBufferLength+"s")),this.state=Gr.IDLE}else Je.b.warn("AudioStreamController: buffer full error also media.currentTime is not buffered, flush audio buffer"),this.fragCurrent=null,this.state=Gr.BUFFER_FLUSHING,this.hls.trigger(Qe.a.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:"audio"})}}},t.prototype.onBufferFlushed=function(){var e=this,t=this.pendingData;t&&t.length?(Je.b.log("AudioStreamController: appending pending audio data after buffer flushed"),t.forEach(function(t){e.hls.trigger(Qe.a.BUFFER_APPENDING,t)}),this.appended=!0,this.pendingData=[],this.state=Gr.PARSED):(this.state=Gr.IDLE,this.fragPrevious=null,this.tick())},Nr(t,[{key:"state",set:function(e){if(this.state!==e){var t=this.state;this._state=e,Je.b.log("audio stream:"+t+"->"+e)}},get:function(){return this._state}}]),t}(Qt),Kr=jr,Hr=function(){function e(e){return"string"==typeof e&&(!!a[e.toLowerCase()]&&e.toLowerCase())}function t(e){return"string"==typeof e&&(!!o[e.toLowerCase()]&&e.toLowerCase())}function r(e){for(var t=1;t100)throw new Error("Position must be between 0 and 100.");_=e,this.hasBeenReset=!0}})),Object.defineProperty(s,"positionAlign",r({},l,{get:function(){return E},set:function(e){var r=t(e);if(!r)throw new SyntaxError("An invalid or illegal string was specified.");E=r,this.hasBeenReset=!0}})),Object.defineProperty(s,"size",r({},l,{get:function(){return w},set:function(e){if(e<0||e>100)throw new Error("Size must be between 0 and 100.");w=e,this.hasBeenReset=!0}})),Object.defineProperty(s,"align",r({},l,{get:function(){return T},set:function(e){var r=t(e);if(!r)throw new SyntaxError("An invalid or illegal string was specified.");T=r,this.hasBeenReset=!0}})),s.displayState=void 0,u)return s}if("undefined"!=typeof window&&window.VTTCue)return window.VTTCue;var i="auto",a={"":!0,lr:!0,rl:!0},o={start:!0,middle:!0,end:!0,left:!0,right:!0};return n.prototype.getCueAsHTML=function(){return window.WebVTT.convertCueToDOMTree(window,this.text)},n}(),Wr=function(){return{decode:function(e){if(!e)return"";if("string"!=typeof e)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}};Te.prototype={set:function(e,t){this.get(e)||""===t||(this.values[e]=t)},get:function(e,t,r){return r?this.has(e)?this.values[e]:t[r]:this.has(e)?this.values[e]:t},has:function(e){return e in this.values},alt:function(e,t,r){for(var n=0;n=0&&t<=100)&&(this.set(e,t),!0)}};var Yr=new Hr(0,0,0),qr="middle"===Yr.align?"middle":"center";Ee.prototype={parse:function(e){function t(){var e=r.buffer,t=0;for(e=Ae(e);tJr&&(nn.log("ERROR","Too large cursor position "+this.pos),this.pos=Jr)},e.prototype.moveCursor=function(e){var t=this.pos+e;if(e>1)for(var r=this.pos+1;r=144&&this.backSpace();var t=Xr(e);if(this.pos>=Jr)return void nn.log("ERROR","Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!");this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1)},e.prototype.clearFromPos=function(e){var t=void 0;for(t=e;t0&&(r=e?"["+t.join(" | ")+"]":t.join("\n")),r},e.prototype.getTextAndFormat=function(){return this.rows},e}(),cn=function(){function e(t,r){Ce(this,e),this.chNr=t,this.outputFilter=r,this.mode=null,this.verbose=0,this.displayedMemory=new ln,this.nonDisplayedMemory=new ln,this.lastOutputScreen=new ln,this.currRollUpRow=this.displayedMemory.rows[Qr-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}return e.prototype.reset=function(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.currRollUpRow=this.displayedMemory.rows[Qr-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.lastCueEndTime=null},e.prototype.getHandler=function(){return this.outputFilter},e.prototype.setHandler=function(e){this.outputFilter=e},e.prototype.setPAC=function(e){this.writeScreen.setPAC(e)},e.prototype.setBkgData=function(e){this.writeScreen.setBkgData(e)},e.prototype.setMode=function(e){e!==this.mode&&(this.mode=e,nn.log("INFO","MODE="+e),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)},e.prototype.insertChars=function(e){for(var t=0;t=46,t.italics)t.foreground="white";else{var r=Math.floor(e/2)-16,n=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=n[r]}nn.log("INFO","MIDROW: "+JSON.stringify(t)),this.writeScreen.setPen(t)},e.prototype.outputDataUpdate=function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=nn.time;null!==t&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue&&(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),!0===e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue()),this.cueStartTime=this.displayedMemory.isEmpty()?null:t):this.cueStartTime=t,this.lastOutputScreen.copy(this.displayedMemory))},e.prototype.cueSplitAtTime=function(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))},e}(),dn=function(){function e(t,r,n){Ce(this,e),this.field=t||1,this.outputs=[r,n],this.channels=[new cn(1,r),new cn(2,n)],this.currChNr=-1,this.lastCmdA=null,this.lastCmdB=null,this.bufferedData=[],this.startTime=null,this.lastTime=null,this.dataCounters={padding:0,char:0,cmd:0,other:0}}return e.prototype.getHandler=function(e){return this.channels[e].getHandler()},e.prototype.setHandler=function(e,t){this.channels[e].setHandler(t)},e.prototype.addData=function(e,t){var r=void 0,n=void 0,i=void 0,a=!1;this.lastTime=e,nn.setTime(e);for(var o=0;o ("+an([n,i])+")"),r=this.parseCmd(n,i),r||(r=this.parseMidrow(n,i)),r||(r=this.parsePAC(n,i)),r||(r=this.parseBackgroundAttributes(n,i)),!r&&(a=this.parseChars(n,i)))if(this.currChNr&&this.currChNr>=0){var s=this.channels[this.currChNr-1];s.insertChars(a)}else nn.log("WARNING","No channel found yet. TEXT-MODE?");r?this.dataCounters.cmd+=2:a?this.dataCounters.char+=2:(this.dataCounters.other+=2,nn.log("WARNING","Couldn't parse cleaned data "+an([n,i])+" orig: "+an([t[o],t[o+1]])))}else this.dataCounters.padding+=2},e.prototype.parseCmd=function(e,t){var r=null,n=(20===e||28===e)&&t>=32&&t<=47,i=(23===e||31===e)&&t>=33&&t<=35;if(!n&&!i)return!1;if(e===this.lastCmdA&&t===this.lastCmdB)return this.lastCmdA=null,this.lastCmdB=null,nn.log("DEBUG","Repeated command ("+an([e,t])+") is dropped"),!0;r=20===e||23===e?1:2;var a=this.channels[r-1];return 20===e||28===e?32===t?a.ccRCL():33===t?a.ccBS():34===t?a.ccAOF():35===t?a.ccAON():36===t?a.ccDER():37===t?a.ccRU(2):38===t?a.ccRU(3):39===t?a.ccRU(4):40===t?a.ccFON():41===t?a.ccRDC():42===t?a.ccTR():43===t?a.ccRTD():44===t?a.ccEDM():45===t?a.ccCR():46===t?a.ccENM():47===t&&a.ccEOC():a.ccTO(t-32),this.lastCmdA=e,this.lastCmdB=t,this.currChNr=r,!0},e.prototype.parseMidrow=function(e,t){var r=null;if((17===e||25===e)&&t>=32&&t<=47){if((r=17===e?1:2)!==this.currChNr)return nn.log("ERROR","Mismatch channel in midrow parsing"),!1;return this.channels[r-1].ccMIDROW(t),nn.log("DEBUG","MIDROW ("+an([e,t])+")"),!0}return!1},e.prototype.parsePAC=function(e,t){var r=null,n=null,i=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,a=(16===e||24===e)&&t>=64&&t<=95;if(!i&&!a)return!1;if(e===this.lastCmdA&&t===this.lastCmdB)return this.lastCmdA=null,this.lastCmdB=null,!0;r=e<=23?1:2,n=t>=64&&t<=95?1===r?$r[e]:en[e]:1===r?Zr[e]:tn[e];var o=this.interpretPAC(n,t);return this.channels[r-1].setPAC(o),this.lastCmdA=e,this.lastCmdB=t,this.currChNr=r,!0},e.prototype.interpretPAC=function(e,t){var r=t,n={color:null,italics:!1,indent:null,underline:!1,row:e};return r=t>95?t-96:t-64,n.underline=1==(1&r),r<=13?n.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(r/2)]:r<=15?(n.italics=!0,n.color="white"):n.indent=4*Math.floor((r-16)/2),n},e.prototype.parseChars=function(e,t){var r=null,n=null,i=null;if(e>=25?(r=2,i=e-8):(r=1,i=e),i>=17&&i<=19){var a=t;a=17===i?t+80:18===i?t+112:t+144,nn.log("INFO","Special char '"+Xr(a)+"' in channel "+r),n=[a]}else e>=32&&e<=127&&(n=0===t?[e]:[e,t]);if(n){var o=an(n);nn.log("DEBUG","Char codes = "+o.join(",")),this.lastCmdA=null,this.lastCmdB=null}return n},e.prototype.parseBackgroundAttributes=function(e,t){var r=void 0,n=void 0,i=void 0,a=void 0,o=(16===e||24===e)&&t>=32&&t<=47,s=(23===e||31===e)&&t>=45&&t<=47;return!(!o&&!s)&&(r={},16===e||24===e?(n=Math.floor((t-32)/2),r.background=rn[n],t%2==1&&(r.background=r.background+"_semi")):45===t?r.background="transparent":(r.foreground="black",47===t&&(r.underline=!0)),i=e<24?1:2,a=this.channels[i-1],a.setBkgData(r),this.lastCmdA=null,this.lastCmdB=null,!0)},e.prototype.reset=function(){for(var e=0;ee)&&(this.startTime=e),this.endTime=t,this.screen=r,this.timelineController.createCaptionsTrack(this.trackName)},e}(),pn=hn,gn=function(e,t,r){return e.substr(r||0,t.length)===t},vn=function(e){var t=parseInt(e.substr(-3)),r=parseInt(e.substr(-6,2)),n=parseInt(e.substr(-9,2)),i=e.length>9?parseInt(e.substr(0,e.indexOf(":"))):0;return isNaN(t)||isNaN(r)||isNaN(n)||isNaN(i)?-1:(t+=1e3*r,t+=6e4*n,t+=36e5*i)},yn=function(e){for(var t=5381,r=e.length;r;)t=33*t^e.charCodeAt(--r);return(t>>>0).toString()},mn=function(e,t,r){var n=e[t],i=e[n.prevCC];if(!i||!i.new&&n.new)return e.ccOffset=e.presentationOffset=n.start,void(n.new=!1);for(;i&&i.new;)e.ccOffset+=n.start-i.start,n.new=!1,n=i,i=e[n.prevCC];e.presentationOffset=r},bn={parse:function(e,t,r,n,i,a){var o=/\r\n|\n\r|\n|\r/g,s=Object(sr.b)(new Uint8Array(e)).trim().replace(o,"\n").split("\n"),u="00:00.000",l=0,c=0,d=0,f=[],h=void 0,p=!0,g=new Vr;g.oncue=function(e){var t=r[n],i=r.ccOffset;t&&t.new&&(void 0!==c?i=r.ccOffset=t.start:mn(r,n,d)),d&&(i=d+r.ccOffset-r.presentationOffset),e.startTime+=i-c,e.endTime+=i-c,e.id=yn(e.startTime.toString())+yn(e.endTime.toString())+yn(e.text),e.text=decodeURIComponent(encodeURIComponent(e.text)),e.endTime>0&&f.push(e)},g.onparsingerror=function(e){h=e},g.onflush=function(){if(h&&a)return void a(h);i(f)},s.forEach(function(e){if(p){if(gn(e,"X-TIMESTAMP-MAP=")){p=!1,e.substr(16).split(",").forEach(function(e){gn(e,"LOCAL:")?u=e.substr(6):gn(e,"MPEGTS:")&&(l=parseInt(e.substr(7)))});try{t=t<0?t+8589934592:t,l-=t,c=vn(u)/1e3,d=l/9e4,-1===c&&(h=new Error("Malformed X-TIMESTAMP-MAP: "+e))}catch(t){h=new Error("Malformed X-TIMESTAMP-MAP: "+e)}return}""===e&&(p=!1)}g.parse(e+"\n")}),g.flush()}},_n=bn,En=function(e){function t(r){De(this,t);var n=Ie(this,e.call(this,r,Qe.a.MEDIA_ATTACHING,Qe.a.MEDIA_DETACHING,Qe.a.FRAG_PARSING_USERDATA,Qe.a.FRAG_DECRYPTED,Qe.a.MANIFEST_LOADING,Qe.a.MANIFEST_LOADED,Qe.a.FRAG_LOADED,Qe.a.LEVEL_SWITCHING,Qe.a.INIT_PTS_FOUND));if(n.hls=r,n.config=r.config,n.enabled=!0,n.Cues=r.config.cueHandler,n.textTracks=[],n.tracks=[],n.unparsedVttFrags=[],n.initPTS=void 0,n.cueRanges=[],n.captionsTracks={},n.captionsProperties={textTrack1:{label:n.config.captionsTextTrack1Label,languageCode:n.config.captionsTextTrack1LanguageCode},textTrack2:{label:n.config.captionsTextTrack2Label,languageCode:n.config.captionsTextTrack2LanguageCode}},n.config.enableCEA708Captions){var i=new pn(n,"textTrack1"),a=new pn(n,"textTrack2");n.cea608Parser=new fn(0,i,a)}return n}return Pe(t,e),t.prototype.addCues=function(e,t,r,n){for(var i=this.cueRanges,a=!1,o=i.length;o--;){var s=i[o],u=xe(s[0],s[1],t,r);if(u>=0&&(s[0]=Math.min(s[0],t),s[1]=Math.max(s[1],r),a=!0,u/(r-t)>.5))return}a||i.push([t,r]),this.Cues.newCue(this.captionsTracks[e],t,r,n)},t.prototype.onInitPtsFound=function(e){var t=this;void 0===this.initPTS&&(this.initPTS=e.initPTS),this.unparsedVttFrags.length&&(this.unparsedVttFrags.forEach(function(e){t.onFragLoaded(e)}),this.unparsedVttFrags=[])},t.prototype.getExistingTrack=function(e){var t=this.media;if(t)for(var r=0;r=r.length)&&(this._stopTimer(),this.trackId=e,Je.b.log("switching to subtitle track "+e),t.trigger(Qe.a.SUBTITLE_TRACK_SWITCH,{id:e}),-1!==e)){var n=r[e],i=n.details;i&&!i.live||(Je.b.log("(re)loading playlist for subtitle track "+e),t.trigger(Qe.a.SUBTITLE_TRACK_LOADING,{url:n.url,id:e}))}},t.prototype._stopTimer=function(){this.timer&&(clearInterval(this.timer),this.timer=null)},t.prototype._toggleTrackModes=function(e){var t=this.media,r=this.subtitleDisplay,n=this.trackId;if(t){var i=Ue(t.textTracks);if(-1===e)[].slice.call(i).forEach(function(e){e.mode="disabled"});else{var a=i[n];a&&(a.mode="disabled")}var o=i[e];o&&(o.mode=r?"showing":"hidden")}},Tn(t,[{key:"subtitleTracks",get:function(){return this.tracks}},{key:"subtitleTrack",get:function(){return this.trackId},set:function(e){this.trackId!==e&&(this._toggleTrackModes(e),this.setSubtitleTrackInternal(e))}}]),t}(tt),Rn=Sn,An=r(7),Ln=window,Cn=Ln.performance,kn={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING"},Dn=function(e){function t(r){Be(this,t);var n=Ge(this,e.call(this,r,Qe.a.MEDIA_ATTACHED,Qe.a.ERROR,Qe.a.KEY_LOADED,Qe.a.FRAG_LOADED,Qe.a.SUBTITLE_TRACKS_UPDATED,Qe.a.SUBTITLE_TRACK_SWITCH,Qe.a.SUBTITLE_TRACK_LOADED,Qe.a.SUBTITLE_FRAG_PROCESSED));return n.config=r.config,n.vttFragSNsProcessed={},n.vttFragQueues=void 0,n.currentlyProcessing=null,n.state=kn.STOPPED,n.currentTrackId=-1,n.decrypter=new An.a(r.observer,r.config),n}return je(t,e),t.prototype.onHandlerDestroyed=function(){this.state=kn.STOPPED},t.prototype.clearVttFragQueues=function(){var e=this;this.vttFragQueues={},this.tracks.forEach(function(t){e.vttFragQueues[t.id]=[]})},t.prototype.nextFrag=function(){if(null===this.currentlyProcessing&&this.currentTrackId>-1&&this.vttFragQueues[this.currentTrackId].length){var e=this.currentlyProcessing=this.vttFragQueues[this.currentTrackId].shift();this.fragCurrent=e,this.hls.trigger(Qe.a.FRAG_LOADING,{frag:e}),this.state=kn.FRAG_LOADING}},t.prototype.onSubtitleFragProcessed=function(e){e.success&&this.vttFragSNsProcessed[e.frag.trackId].push(e.frag.sn),this.currentlyProcessing=null,this.state=kn.IDLE,this.nextFrag()},t.prototype.onMediaAttached=function(){this.state=kn.IDLE},t.prototype.onError=function(e){var t=e.frag;t&&"subtitle"!==t.type||this.currentlyProcessing&&(this.currentlyProcessing=null,this.nextFrag())},t.prototype.doTick=function(){var e=this;switch(this.state){case kn.IDLE:var t=this.tracks,r=this.currentTrackId,n=this.vttFragSNsProcessed[r],i=this.vttFragQueues[r],a=this.currentlyProcessing?this.currentlyProcessing.sn:-1,o=function(e){return n.indexOf(e.sn)>-1},s=function(e){return i.some(function(t){return t.sn===e.sn})};if(!t)break;var u;if(r0&&null!=r&&null!=r.key&&"AES-128"===r.method){var a=void 0;try{a=Cn.now()}catch(e){a=Date.now()}this.decrypter.decrypt(e.payload,r.key.buffer,r.iv.buffer,function(e){var t=void 0;try{t=Cn.now()}catch(e){t=Date.now()}i.trigger(Qe.a.FRAG_DECRYPTED,{frag:n,payload:e,stats:{tstart:a,tdecrypt:t}})})}},t}(Qt),In=Dn,Pn=function(){function e(e,t){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:{};Ye(this,e);var n=e.DefaultConfig;if((r.liveSyncDurationCount||r.liveMaxLatencyDurationCount)&&(r.liveSyncDuration||r.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");for(var i in n)i in r||(r[i]=n[i]);if(void 0!==r.liveMaxLatencyDurationCount&&r.liveMaxLatencyDurationCount<=r.liveSyncDurationCount)throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be gt "liveSyncDurationCount"');if(void 0!==r.liveMaxLatencyDuration&&(r.liveMaxLatencyDuration<=r.liveSyncDuration||void 0===r.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be gt "liveSyncDuration"');Object(Je.a)(r.debug),this.config=r,this._autoLevelCapping=-1;var a=this.observer=new Ut.a;a.trigger=function(e){for(var t=arguments.length,r=Array(t>1?t-1:0),n=1;n1?t-1:0),n=1;n0&&void 0!==arguments[0]?arguments[0]:-1;Je.b.log("startLoad("+e+")"),this.networkControllers.forEach(function(t){t.startLoad(e)})},e.prototype.stopLoad=function(){Je.b.log("stopLoad"),this.networkControllers.forEach(function(e){e.stopLoad()})},e.prototype.swapAudioCodec=function(){Je.b.log("swapAudioCodec"),this.streamController.swapAudioCodec()},e.prototype.recoverMediaError=function(){Je.b.log("recoverMediaError");var e=this.media;this.detachMedia(),this.attachMedia(e)},Kn(e,[{key:"levels",get:function(){return this.levelController.levels}},{key:"currentLevel",get:function(){return this.streamController.currentLevel},set:function(e){Je.b.log("set currentLevel:"+e),this.loadLevel=e,this.streamController.immediateLevelSwitch()}},{key:"nextLevel",get:function(){return this.streamController.nextLevel},set:function(e){Je.b.log("set nextLevel:"+e),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}},{key:"loadLevel",get:function(){return this.levelController.level},set:function(e){Je.b.log("set loadLevel:"+e),this.levelController.manualLevel=e}},{key:"nextLoadLevel",get:function(){return this.levelController.nextLoadLevel},set:function(e){this.levelController.nextLoadLevel=e}},{key:"firstLevel",get:function(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)},set:function(e){Je.b.log("set firstLevel:"+e),this.levelController.firstLevel=e}},{key:"startLevel",get:function(){return this.levelController.startLevel},set:function(e){Je.b.log("set startLevel:"+e);var t=this;-1!==e&&(e=Math.max(e,t.minAutoLevel)),t.levelController.startLevel=e}},{key:"autoLevelCapping",get:function(){return this._autoLevelCapping},set:function(e){Je.b.log("set autoLevelCapping:"+e),this._autoLevelCapping=e}},{key:"autoLevelEnabled",get:function(){return-1===this.levelController.manualLevel}},{key:"manualLevel",get:function(){return this.levelController.manualLevel}},{key:"minAutoLevel",get:function(){for(var e=this,t=e.levels,r=e.config.minAutoBitrate,n=t?t.length:0,i=0;ir)return i}return 0}},{key:"maxAutoLevel",get:function(){var e=this,t=e.levels,r=e.autoLevelCapping;return-1===r&&t&&t.length?t.length-1:r}},{key:"nextAutoLevel",get:function(){var e=this;return Math.min(Math.max(e.abrController.nextAutoLevel,e.minAutoLevel),e.maxAutoLevel)},set:function(e){var t=this;t.abrController.nextAutoLevel=Math.max(t.minAutoLevel,e)}},{key:"audioTracks",get:function(){var e=this.audioTrackController;return e?e.audioTracks:[]}},{key:"audioTrack",get:function(){var e=this.audioTrackController;return e?e.audioTrack:-1},set:function(e){var t=this.audioTrackController;t&&(t.audioTrack=e)}},{key:"liveSyncPosition",get:function(){return this.streamController.liveSyncPosition}},{key:"subtitleTracks",get:function(){var e=this.subtitleTrackController;return e?e.subtitleTracks:[]}},{key:"subtitleTrack",get:function(){var e=this.subtitleTrackController;return e?e.subtitleTrack:-1},set:function(e){var t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}},{key:"subtitleDisplay",get:function(){var e=this.subtitleTrackController;return!!e&&e.subtitleDisplay},set:function(e){var t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}}]),e}();t.default=Hn},function(e,t,r){function n(e){function t(n){if(r[n])return r[n].exports;var i=r[n]={i:n,l:!1,exports:{}};return e[n].call(i.exports,i,i.exports,t),i.l=!0,i.exports}var r={};t.m=e,t.c=r,t.i=function(e){return e},t.d=function(e,r,n){t.o(e,r)||Object.defineProperty(e,r,{configurable:!1,enumerable:!0,get:n})},t.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(r,"a",r),r},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="/",t.oe=function(e){throw console.error(e),e};var n=t(t.s=ENTRY_MODULE);return n.default||n}function i(e){return(e+"").replace(/[.?*+^$[\]\\(){}|-]/g,"\\$&")}function a(e,t,n){var a={};a[n]=[];var o=t.toString(),s=o.match(/^function\s?\(\w+,\s*\w+,\s*(\w+)\)/);if(!s)return a;for(var c,d=s[1],f=new RegExp("(\\\\n|\\W)"+i(d)+l,"g");c=f.exec(o);)"dll-reference"!==c[3]&&a[n].push(c[3]);for(f=new RegExp("\\("+i(d)+'\\("(dll-reference\\s('+u+'))"\\)\\)'+l,"g");c=f.exec(o);)e[c[2]]||(a[n].push(c[1]),e[c[2]]=r(c[1]).m),a[c[2]]=a[c[2]]||[],a[c[2]].push(c[4]);return a}function o(e){return Object.keys(e).reduce(function(t,r){return t||e[r].length>0},!1)}function s(e,t){for(var r={main:[t]},n={main:[]},i={main:{}};o(r);)for(var s=Object.keys(r),u=0;u1?r-1:0),i=1;i1?r-1:0),i=1;i1){var s=arguments[1];void 0!==s&&(o=s?Number(s):0)!=o&&(o=0)}var u=Math.min(Math.max(o,0),n),l=u-a;if(l<0)return!1;for(var c=-1;++c